diff --git a/.github/workflows/designimport.yml b/.github/workflows/designimport.yml new file mode 100644 index 00000000000..13b14818af3 --- /dev/null +++ b/.github/workflows/designimport.yml @@ -0,0 +1,140 @@ +name: Design Import + +# Design Import: the engine and its command line are the reactor module maven/design-import, +# which cn1:import-design and the Gradle importDesign task resolve and fork; the desktop +# workbench app is scripts/designimport. The tests import the GUI Builder demo forms and the +# developer guide's Sketch files through the core design readers, so a change to any of those +# is what can break it. +# Per the nightly policy it runs on a pull request only when its own inputs change. + +on: + workflow_dispatch: + schedule: + - cron: '11 0 * * *' + pull_request: + branches: + - master + paths: + - 'scripts/ci/retry.sh' + - '.github/workflows/designimport.yml' + - 'scripts/designimport/**' + - 'maven/design-import/**' + - 'maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/ImportDesignMojo.java' + - 'maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/tasks/ImportDesignTask.java' + - 'maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java' + - 'CodenameOne/src/com/codename1/components/CoachMarks.java' + - '!scripts/designimport/**/*.md' + - 'scripts/guibuilder/demo-project/**' + - 'docs/developer-guide/sketch/**' + - 'CodenameOne/src/com/codename1/art/**' + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + golden-plan: + uses: ./.github/workflows/golden-plan.yml + permissions: + contents: read + + designimport: + needs: golden-plan + if: needs.golden-plan.outputs.run == 'true' + runs-on: ubuntu-24.04 + timeout-minutes: 60 + container: ghcr.io/codenameone/codenameone/pr-ci-container:latest + defaults: + run: + shell: bash + + steps: + - uses: actions/checkout@v6 + + - name: Cache Maven dependencies + uses: actions/cache@v5 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-m2 + + - name: Use Google's copy of Maven Central first + uses: ./.github/actions/maven-central-mirror + + - name: Prepare Codename One binaries + # The JavaSE port needs jfxrt.jar from cn1-binaries; without it the + # build fails with a large, misleading set of missing javafx.* errors. + run: | + set -euo pipefail + rm -rf maven/target/cn1-binaries + mkdir -p maven/target + cp -r /opt/cn1-binaries maven/target/cn1-binaries + + - name: Install Codename One artifacts (JDK 8) + # JAVA_HOME_8 / JAVA_HOME_17 are container image environment variables, + # so they are expanded by the shell rather than the env context. + run: | + set -euo pipefail + export JAVA_HOME="${JAVA_HOME_8}" + export PATH="${JAVA_HOME}/bin:${PATH}" + cd maven + # Retried: Central has been answering 403 on this runner pool, and Maven treats a + # failed build-extension resolution as permanent -- the job dies in setup having + # proved nothing. Same rationale as setup-workspace.sh's mvn_retry. + bash ../scripts/ci/retry.sh mvn -B install -Plocal-dev-javase -DskipTests \ + -Darchetype.test.skip=true -Dmaven.javadoc.skip=true \ + -Dcn1.binaries="${GITHUB_WORKSPACE}/maven/target/cn1-binaries" + + - name: Run Design Import tests (JDK 8) + # Headless: the workbench test paints the window into an image, nothing needs a display. + run: | + set -euo pipefail + export JAVA_HOME="${JAVA_HOME_8}" + export PATH="${JAVA_HOME}/bin:${PATH}" + (cd maven && mvn -B test -pl design-import \ + -Ddesignimport.argLine="-Ddesignimport.examples=${GITHUB_WORKSPACE}/scripts/designimport/target/examples") + cd scripts/designimport + # No clean: the gallery the tests above wrote lives in this target and is uploaded below. + mvn -B install -Dcodename1.platform=javase -DargLine="-Djava.awt.headless=true" + + - name: cn1:import-design in a new application + # The goal resolves the tool at the plugin's version and forks it; the form it writes + # has to build with the application, stylesheet and generated test included. + run: | + set -euo pipefail + export JAVA_HOME="${JAVA_HOME_8}" + export PATH="${JAVA_HOME}/bin:${PATH}" + APPS="${RUNNER_TEMP}/designimport-app" + rm -rf "$APPS" && mkdir -p "$APPS" && cd "$APPS" + VERSION=$(cd "${GITHUB_WORKSPACE}/maven" && mvn -B -q help:evaluate -Dexpression=project.version -DforceStdout) + mvn -B -q archetype:generate -DarchetypeGroupId=com.codenameone -DarchetypeArtifactId=cn1app-archetype \ + -DarchetypeVersion="$VERSION" -DgroupId=com.acme -DartifactId=shop -Dversion=1.0 -DmainName=Shop \ + -Dpackage=com.acme.shop -DinteractiveMode=false + cd shop + mvn -B cn1:import-design -Dcn1.design="${GITHUB_WORKSPACE}/docs/developer-guide/sketch/new-gui-builder-property-sheet.sketch" \ + -Dcn1.design.class=SheetForm | tee import.log + grep -q '\[design-import\] emit:' import.log + test -f common/src/main/java/com/acme/shop/SheetFormBase.java + mvn -B test-compile + + - name: MCP smoke session + run: | + set -euo pipefail + export JAVA_HOME="${JAVA_HOME_8}" + export PATH="${JAVA_HOME}/bin:${PATH}" + # Maven's own answer: in this container HOME is /github/home, while Maven writes to /root/.m2. + REPO=$(cd maven && mvn -B -q help:evaluate -Dexpression=settings.localRepository -DforceStdout) + MAVEN_REPO_LOCAL="$REPO" DESIGNIMPORT_MVN_OFFLINE= DESIGNIMPORT_SKIP_BUILD=1 \ + scripts/designimport/design-import.sh --mcp-smoke + + - name: Upload reports and the regenerated gallery + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v7 + with: + name: designimport-reports + path: | + scripts/designimport/javase/target/surefire-reports + scripts/designimport/target/examples + if-no-files-found: warn + retention-days: 14 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index f294a470333..a02953944a5 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -269,7 +269,7 @@ jobs: -Dcn1.binaries="${CN1_BINARIES}" \ -Pcompile-android \ -DbackendAnalysis \ - -pl android,ios,project-model,build-engine,codenameone-maven-plugin,codenameone-gradle-plugin,backend,backend-test,backend-parparvm,javac,code-model,android-res-compiler,android-compat,swing-compat,javafx-compat,compose-compat,rive-runtime,fxml-compiler,desktop-compat-runtime,cn1-app-kit/backend,cn1-app-kit/common,python-transpiler -am verify + -pl android,ios,project-model,build-engine,codenameone-maven-plugin,codenameone-gradle-plugin,backend,backend-test,backend-parparvm,javac,code-model,android-res-compiler,android-compat,swing-compat,javafx-compat,compose-compat,rive-runtime,fxml-compiler,design-import,desktop-compat-runtime,cn1-app-kit/backend,cn1-app-kit/common,python-transpiler -am verify # The step above skips tests, so the Android port's pure-Java unit tests # (maven/android/src/test) run here, against the classes it just built. - name: Run Android port unit tests @@ -516,7 +516,7 @@ jobs: - name: Generate static analysis HTML summaries if: ${{ !cancelled() && matrix.java-version == 8 }} env: - QUALITY_REPORT_TARGET_DIRS: maven/core-unittests/target:maven/android/target:maven/ios/target:vm/ByteCodeTranslator/target:maven/codenameone-maven-plugin/target:maven/build-engine/target:maven/project-model/target:maven/codenameone-gradle-plugin/target:maven/build-hint-catalog/target:maven/build-hint-tools/target:maven/backend/target:maven/backend-test/target:maven/backend-parparvm/target:maven/javac/target:maven/code-model/target:maven/android-res-compiler/target:maven/android-compat/target:maven/swing-compat/target:maven/javafx-compat/target:maven/compose-compat/target:maven/fxml-compiler/target:maven/desktop-compat-runtime/target:maven/python-transpiler/target:maven/python-runtime/target:maven/rive-runtime/target + QUALITY_REPORT_TARGET_DIRS: maven/core-unittests/target:maven/android/target:maven/ios/target:vm/ByteCodeTranslator/target:maven/codenameone-maven-plugin/target:maven/build-engine/target:maven/project-model/target:maven/codenameone-gradle-plugin/target:maven/build-hint-catalog/target:maven/build-hint-tools/target:maven/backend/target:maven/backend-test/target:maven/backend-parparvm/target:maven/javac/target:maven/code-model/target:maven/android-res-compiler/target:maven/android-compat/target:maven/swing-compat/target:maven/javafx-compat/target:maven/compose-compat/target:maven/fxml-compiler/target:maven/design-import/target:maven/desktop-compat-runtime/target:maven/python-transpiler/target:maven/python-runtime/target:maven/rive-runtime/target QUALITY_REPORT_SERVER_URL: ${{ github.server_url }} QUALITY_REPORT_REPOSITORY: ${{ github.repository }} QUALITY_REPORT_REF: ${{ github.event.pull_request.head.sha || github.sha }} @@ -543,6 +543,7 @@ jobs: "compose-compat:maven/compose-compat/target" \ "rive-runtime:maven/rive-runtime/target" \ "fxml-compiler:maven/fxml-compiler/target" \ + "design-import:maven/design-import/target" \ "desktop-compat-runtime:maven/desktop-compat-runtime/target" \ "project-model:maven/project-model/target" \ "gradle-plugin:maven/codenameone-gradle-plugin/target" \ @@ -675,11 +676,11 @@ jobs: - name: Generate quality report summary if: ${{ !cancelled() && matrix.java-version == 8 }} env: - QUALITY_REPORT_TARGET_DIRS: maven/core-unittests/target:maven/android/target:maven/ios/target:vm/ByteCodeTranslator/target:maven/codenameone-maven-plugin/target:maven/build-engine/target:maven/project-model/target:maven/codenameone-gradle-plugin/target:maven/build-hint-catalog/target:maven/build-hint-tools/target:maven/backend/target:maven/backend-test/target:maven/backend-parparvm/target:maven/javac/target:maven/code-model/target:maven/android-res-compiler/target:maven/android-compat/target:maven/swing-compat/target:maven/javafx-compat/target:maven/compose-compat/target:maven/fxml-compiler/target:maven/desktop-compat-runtime/target:maven/python-transpiler/target:maven/python-runtime/target:maven/rive-runtime/target + QUALITY_REPORT_TARGET_DIRS: maven/core-unittests/target:maven/android/target:maven/ios/target:vm/ByteCodeTranslator/target:maven/codenameone-maven-plugin/target:maven/build-engine/target:maven/project-model/target:maven/codenameone-gradle-plugin/target:maven/build-hint-catalog/target:maven/build-hint-tools/target:maven/backend/target:maven/backend-test/target:maven/backend-parparvm/target:maven/javac/target:maven/code-model/target:maven/android-res-compiler/target:maven/android-compat/target:maven/swing-compat/target:maven/javafx-compat/target:maven/compose-compat/target:maven/fxml-compiler/target:maven/design-import/target:maven/desktop-compat-runtime/target:maven/python-transpiler/target:maven/python-runtime/target:maven/rive-runtime/target # Every project listed here must produce a SpotBugs report and that # report must be empty. A missing report fails the gate too, so a # SpotBugs run that silently stops running is not mistaken for clean. - QUALITY_REPORT_REQUIRED_SPOTBUGS: core-unittests:android:ios:ByteCodeTranslator:codenameone-maven-plugin:build-engine:project-model:codenameone-gradle-plugin:build-hint-catalog:build-hint-tools:backend:backend-test:javac:code-model:android-res-compiler:android-compat:swing-compat:javafx-compat:compose-compat:fxml-compiler:desktop-compat-runtime:python-transpiler:python-runtime:rive-runtime + QUALITY_REPORT_REQUIRED_SPOTBUGS: core-unittests:android:ios:ByteCodeTranslator:codenameone-maven-plugin:build-engine:project-model:codenameone-gradle-plugin:build-hint-catalog:build-hint-tools:backend:backend-test:javac:code-model:android-res-compiler:android-compat:swing-compat:javafx-compat:compose-compat:fxml-compiler:design-import:desktop-compat-runtime:python-transpiler:python-runtime:rive-runtime # PMD and Checkstyle run on the core, the backend runtime and the Python # transpiler and runtime, and each must produce its report: without one, # the PMD gate below it has nothing to read and passes. diff --git a/CLAUDE.md b/CLAUDE.md index f0acc7fb374..c3ac7d2261c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -112,6 +112,7 @@ PR CI (`.github/workflows/pr.yml`, Java 8 leg) runs SpotBugs over `core-unittests`, `android`, `ios`, `ByteCodeTranslator`, `codenameone-maven-plugin`, `build-engine` (the Maven-free build logic both build plugins share), `project-model` (the project-layout API), +`design-import` (the Design Import engine), `android-res-compiler` and `android-compat` (the Android compatibility runtime), `codenameone-gradle-plugin`, `javac` (the in-tree Java compiler, `vm/JavaCompiler`), `code-model` (the code visualizer's analyzer) and `python-transpiler`, plus `python-runtime` in a step of @@ -131,7 +132,7 @@ it runs only when the Unity tree itself changes, so a change to the core's - **Record intentional exceptions in the project's `spotbugs-exclude.xml`** (`maven/core-unittests/`, `Ports/Android/`, `Ports/iOSPort/`, `vm/ByteCodeTranslator/`, `maven/codenameone-maven-plugin/`, - `maven/build-engine/`, `maven/project-model/`, + `maven/build-engine/`, `maven/project-model/`, `maven/design-import/`, `maven/android-res-compiler/`, `maven/android-compat/`, `maven/codenameone-gradle-plugin/`, `maven/javac/`, `maven/code-model/`, `maven/python-transpiler/`, `maven/python-runtime/`, diff --git a/CodenameOne/src/com/codename1/art/ArtNode.java b/CodenameOne/src/com/codename1/art/ArtNode.java index bef69cdce5a..dc5ea1e96cb 100644 --- a/CodenameOne/src/com/codename1/art/ArtNode.java +++ b/CodenameOne/src/com/codename1/art/ArtNode.java @@ -26,7 +26,10 @@ import com.codename1.ui.geom.GeneralPath; import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /// One element of an artwork: a group, shape, text, image or adjustment layer. /// @@ -45,6 +48,49 @@ public abstract class ArtNode { private boolean luminanceMask; private boolean knockout; private final List effects = new ArrayList(); + private Map attributes; + + /// A source attribute the reader kept, or null. + /// + /// Readers keep facts the rendering model has no field for, so that tools reading + /// the document as a design can still see them: Figma's auto-layout + /// (`layoutMode`, `itemSpacing`, `paddingLeft`...), resizing constraints + /// (`constraints.horizontal`), component instances (`componentId`), and the + /// source's own node type (`sourceType`). Rendering never reads them. + /// + /// #### Parameters + /// + /// - `key`: the attribute name + public String getAttribute(String key) { + return attributes == null ? null : attributes.get(key); + } + + /// Sets a source attribute; null removes it. + /// + /// #### Parameters + /// + /// - `key`: the attribute name + /// - `value`: the value, or null + public void setAttribute(String key, String value) { + if (value == null) { + if (attributes != null) { + attributes.remove(key); + } + return; + } + if (attributes == null) { + attributes = new LinkedHashMap(); + } + attributes.put(key, value); + } + + /// Every source attribute, in the order they were set; read only. + public Map getAttributes() { + if (attributes == null) { + return Collections.emptyMap(); + } + return Collections.unmodifiableMap(attributes); + } /// The node's id, unique within a document when set. public String getId() { @@ -226,6 +272,9 @@ protected ArtNode copyBase(ArtNode n) { n.mask = mask == null ? null : mask.copy(); n.luminanceMask = luminanceMask; n.knockout = knockout; + if (attributes != null) { + n.attributes = new LinkedHashMap(attributes); + } for (int i = 0; i < effects.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation n.effects.add(effects.get(i).copy()); } diff --git a/CodenameOne/src/com/codename1/art/FigmaClient.java b/CodenameOne/src/com/codename1/art/FigmaClient.java index 9869142ee15..f79a4a712e9 100644 --- a/CodenameOne/src/com/codename1/art/FigmaClient.java +++ b/CodenameOne/src/com/codename1/art/FigmaClient.java @@ -87,10 +87,25 @@ public FigmaClient setOAuth(boolean oauth) { /// /// - `fileKey`: the key in the file's URL, `figma.com/design/KEY/...` public ArtDocument fetch(String fileKey) throws IOException { + Map images = new HashMap(); + byte[] json = fetchJson(fileKey, images); + return FigmaReader.read(json, images); + } + + /// Downloads a file without reading it: its JSON is returned and the pictures its fills + /// name are put in `images`, keyed by image ref. `FigmaReader.read(json, images)` turns the + /// pair into the same document `fetch` returns, so a caller can keep a copy of a file and + /// read it again without asking Figma, whose quota on whole-file reads is small. + /// + /// #### Parameters + /// + /// - `fileKey`: the key in the file's URL, `figma.com/design/KEY/...` + /// + /// - `images`: receives the pictures the file uses + public byte[] fetchJson(String fileKey, Map images) throws IOException { checkKey(fileKey); byte[] json = get(API + "files/" + fileKey + "?geometry=paths"); Map parsed = JSONParser.parseJSON(json); - Map images = new HashMap(); List refs = FigmaReader.imageRefs(parsed); if (!refs.isEmpty()) { Map fills = JSONParser.parseJSON(get(API + "files/" + fileKey + "/images")); @@ -108,7 +123,7 @@ public ArtDocument fetch(String fileKey) throws IOException { } } } - return FigmaReader.read(json, images); + return json; } /// The raw JSON of any API path, such as `files/KEY/nodes?ids=1:2&geometry=paths`. @@ -167,7 +182,7 @@ private byte[] request(String url, boolean auth) throws IOException { throw new IOException("Figma file not found (404)"); } if (code == 429) { - throw new IOException("Figma rate limit reached (429); try again later"); + throw new IOException("Figma rate limit reached (429); " + retryAfter(r.retryAfter)); } if (code < 200 || code >= 300 || data == null) { throw new IOException("Figma request failed with HTTP " + code); @@ -175,8 +190,40 @@ private byte[] request(String url, boolean auth) throws IOException { return data; } + /// How long Figma asks a refused caller to wait, from its `Retry-After` seconds. On the + /// Starter plan that is days, not seconds, and "try again later" hides it. + static String retryAfter(String seconds) { + long s = -1; + if (seconds != null) { + try { + s = Long.parseLong(seconds.trim()); + } catch (NumberFormatException e) { + s = -1; + } + } + if (s < 0) { + return "try again later"; + } + if (s < 120) { + return "Figma asks to wait " + s + " seconds"; + } + if (s < 2 * 3600) { + return "Figma asks to wait " + (s / 60) + " minutes"; + } + if (s < 2 * 86400) { + return "Figma asks to wait " + (s / 3600) + " hours"; + } + return "Figma asks to wait " + (s / 86400) + " days"; + } + private static final class Request extends ConnectionRequest { private Exception failure; + private String retryAfter; + + @Override + protected void readHeaders(Object connection) throws IOException { + retryAfter = getHeader(connection, "Retry-After"); + } @Override protected void handleException(Exception err) { diff --git a/CodenameOne/src/com/codename1/art/FigmaReader.java b/CodenameOne/src/com/codename1/art/FigmaReader.java index c110f4c5ba8..a9354fab7e1 100644 --- a/CodenameOne/src/com/codename1/art/FigmaReader.java +++ b/CodenameOne/src/com/codename1/art/FigmaReader.java @@ -211,6 +211,42 @@ private void children(Map parent, GroupNode into, double[] paren } } + private static final String[] LAYOUT_KEYS = { + "type", "layoutMode", "layoutWrap", "itemSpacing", "counterAxisSpacing", + "paddingLeft", "paddingRight", "paddingTop", "paddingBottom", + "primaryAxisAlignItems", "counterAxisAlignItems", "primaryAxisSizingMode", + "counterAxisSizingMode", "layoutAlign", "layoutGrow", "layoutPositioning", + "layoutSizingHorizontal", "layoutSizingVertical", "componentId", "cornerRadius", + "minWidth", "maxWidth" + }; + + /// Keeps the auto-layout, constraint and component facts the render model has no + /// field for, so a design tool reading the document can still use them. + private static void layoutAttributes(Map n, ArtNode out) { + for (String k : LAYOUT_KEYS) { + Object v = n.get(k); + if (v instanceof String || v instanceof Number || v instanceof Boolean) { + String key = "type".equals(k) ? "sourceType" : k; + out.setAttribute(key, number(v)); + } + } + Map c = Json.obj(n, "constraints"); + if (c != null) { + out.setAttribute("constraints.horizontal", Json.str(c, "horizontal")); + out.setAttribute("constraints.vertical", Json.str(c, "vertical")); + } + } + + private static String number(Object v) { + if (v instanceof Number) { + double d = ((Number) v).doubleValue(); + if (d == Math.floor(d) && Math.abs(d) < 1e15) { + return String.valueOf((long) d); + } + } + return String.valueOf(v); + } + private static double[] box(Map n) { Map b = Json.obj(n, "absoluteBoundingBox"); if (b == null) { @@ -245,6 +281,49 @@ private static Matrix transform(Map n, double[] abs, double[] pa return Matrix.translate(abs[0] - px, abs[1] - py); } + /// Whether a group's children carry relativeTransforms in the group's parent's space rather + /// than the group's. Files differ: the REST API has been seen to send both, so the absolute + /// boxes decide. An unrotated child's offset says which space it is in: its box minus the + /// group's box, or minus the parent's. With nothing to compare, the group's space is taken, + /// which is what current files send. + private static boolean childrenInParentSpace(Map n, double[] abs, double[] parentBox) { + if (abs == null || parentBox == null) { + return false; + } + List kids = Json.list(n, "children"); + if (kids == null) { + return false; + } + for (int i = 0; i < kids.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation + if (!(kids.get(i) instanceof Map)) { + continue; + } + @SuppressWarnings("unchecked") + Map k = (Map) kids.get(i); + double[] kb = box(k); + List rt = Json.list(k, "relativeTransform"); + if (kb == null || rt == null || rt.size() != 2 || !(rt.get(0) instanceof List) + || !(rt.get(1) instanceof List)) { + continue; + } + List r0 = (List) rt.get(0); + List r1 = (List) rt.get(1); + if (r0.size() != 3 || r1.size() != 3 || Math.abs(d(r0.get(0)) - 1) > 0.001 + || Math.abs(d(r1.get(1)) - 1) > 0.001 || Math.abs(d(r0.get(1))) > 0.001) { + continue; + } + double tx = d(r0.get(2)); + double ty = d(r1.get(2)); + double inGroup = Math.abs(kb[0] - abs[0] - tx) + Math.abs(kb[1] - abs[1] - ty); + double inParent = Math.abs(kb[0] - parentBox[0] - tx) + Math.abs(kb[1] - parentBox[1] - ty); + // A child at the group's own corner fits both readings and decides nothing. + if (inGroup >= 0.5 || inParent >= 0.5) { + return inParent < inGroup; + } + } + return false; + } + private static double d(Object o) { return o instanceof Number ? ((Number) o).doubleValue() : 0; } @@ -299,8 +378,10 @@ private ArtNode node(Map n, double[] parentBox, int depth) throw // A group in the REST API is positioned in its parent's space but its children are // positioned relative to it, so groups need their own offset like any other node. out.setTransform(transform(n, abs, parentBox)); - if ("GROUP".equals(type) && Json.list(n, "relativeTransform") != null) { - // With relativeTransform, children of a group are relative to the group's parent. + if ("GROUP".equals(type) && Json.list(n, "relativeTransform") != null + && childrenInParentSpace(n, abs, parentBox)) { + // Here the group's children are positioned in the group's parent's space, not the + // group's: take the group's own offset back out of them. Matrix t = out.getTransform(); Matrix inv = t.invert(); if (inv != null) { @@ -312,6 +393,7 @@ private ArtNode node(Map n, double[] parentBox, int depth) throw } out.setName(name); out.setId(Json.str(n, "id")); + layoutAttributes(n, out); out.setVisible(Json.bool(n, "visible", true)); out.setLocked(Json.bool(n, "locked", false)); out.setOpacity((float) Json.num(n, "opacity", 1)); diff --git a/CodenameOne/src/com/codename1/art/NativeFormat.java b/CodenameOne/src/com/codename1/art/NativeFormat.java index d2eda226a7e..eb42e198744 100644 --- a/CodenameOne/src/com/codename1/art/NativeFormat.java +++ b/CodenameOne/src/com/codename1/art/NativeFormat.java @@ -180,6 +180,9 @@ private Map node(ArtNode n) { if (n.isKnockout()) { m.put("knockout", Boolean.TRUE); } + if (!n.getAttributes().isEmpty()) { + m.put("attributes", new LinkedHashMap(n.getAttributes())); + } if (!n.getEffects().isEmpty()) { List fx = new ArrayList(); for (int i = 0; i < n.getEffects().size(); i++) { @@ -545,6 +548,14 @@ private ArtNode readNode(Map m) throws IOException { if (Json.bool(m, "knockout", false)) { n.setKnockout(true); } + Map attrs = Json.obj(m, "attributes"); + if (attrs != null) { + for (Map.Entry e : attrs.entrySet()) { + if (e.getValue() != null) { + n.setAttribute(e.getKey(), String.valueOf(e.getValue())); + } + } + } List fx = Json.list(m, "effects"); if (fx != null) { for (int i = 0; i < fx.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation diff --git a/CodenameOne/src/com/codename1/art/SketchReader.java b/CodenameOne/src/com/codename1/art/SketchReader.java index 410880ac4dd..2f00918d6fa 100644 --- a/CodenameOne/src/com/codename1/art/SketchReader.java +++ b/CodenameOne/src/com/codename1/art/SketchReader.java @@ -206,6 +206,11 @@ private void childLayers(List ls, GroupNode into) throws IOException { m.setBlendMode(BlendMode.NORMAL); m.getEffects().clear(); m.setVisible(true); + if (Json.num(l, "clippingMaskMode", 0) == 0) { + // An outline mask clips to the layer's shape whatever its style: Sketch files + // routinely carry one with no fill at all, which as an alpha mask hid everything. + outline(m); + } clipGroup.setMask(m, false); into.add(clipGroup); continue; @@ -218,6 +223,23 @@ private void childLayers(List ls, GroupNode into) throws IOException { } } + /// Makes a mask layer opaque wherever its shapes are, ignoring their paints. + private static void outline(ArtNode n) { + if (n instanceof ShapeNode) { + ShapeNode s = (ShapeNode) n; + s.getFills().clear(); + s.getFills().add(new SolidPaint(0xff000000)); + s.getStrokes().clear(); + } else if (n instanceof GroupNode) { + List ch = ((GroupNode) n).getChildren(); + for (int i = 0; i < ch.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation + ArtNode c = ch.get(i); + c.setOpacity(1); + outline(c); + } + } + } + private static double[] frame(Map l) { Map f = Json.obj(l, "frame"); return new double[]{Json.num(f, "x", 0), Json.num(f, "y", 0), Json.num(f, "width", 0), @@ -299,6 +321,17 @@ private ArtNode layer(Map l) throws IOException { } n.setName(name); n.setId(Json.str(l, "do_objectID")); + n.setAttribute("sourceType", cls); + if (l.get("resizingConstraint") instanceof Number) { + n.setAttribute("resizingConstraint", String.valueOf((int) Json.num(l, "resizingConstraint", 63))); + } + n.setAttribute("symbolID", Json.str(l, "symbolID")); + Map gl = Json.obj(l, "groupLayout"); + if (gl != null && gl.get("axis") instanceof Number) { + // MSImmutableInferredGroupLayout: axis 0 is horizontal, 1 vertical. + n.setAttribute("groupLayout.axis", String.valueOf((int) Json.num(gl, "axis", 0))); + n.setAttribute("groupLayout.anchor", String.valueOf((int) Json.num(gl, "layoutAnchor", 0))); + } n.setVisible(Json.bool(l, "isVisible", true)); n.setLocked(Json.bool(l, "isLocked", false)); n.setTransform(placement(l, f)); @@ -791,6 +824,9 @@ private ArtNode text(Map l, double[] f) { if (t.getRuns().isEmpty()) { t.getRuns().add(new TextRun(s, null, 12, new SolidPaint(0xff000000))); } + if (Json.bool(l, CENTRED, false)) { + align = TextNode.ALIGN_CENTER; + } t.setAlign(align); if (lineHeight > 0) { t.setLineHeight(lineHeight); @@ -816,6 +852,11 @@ private static String family(String ps) { return dash > 0 ? ps.substring(0, dash) : ps; } + /// A symbol instance is its master laid out again at the instance's size. Sketch never + /// scales a master into an instance: the overrides go in first (a longer text, another + /// nested symbol), and then every layer moves or stretches by its own resizing constraint. + /// That is done here on a copy of the master's JSON, so the layers are then read exactly + /// like any others, at their real sizes. private ArtNode instance(Map l, double[] f) throws IOException { String id = Json.str(l, "symbolID"); Map master = id == null ? null : symbols.get(id); @@ -828,25 +869,29 @@ private ArtNode instance(Map l, double[] f) throws IOException { } depth++; try { - GroupNode g = new GroupNode(); double[] mf = frame(master); - if (Json.bool(master, "hasBackgroundColor", false) && Json.bool(master, "includeBackgroundColorInInstance", false)) { - ShapeNode bg = ShapeNode.rect(0, 0, mf[2], mf[3], 0); - bg.fill(new SolidPaint(color(Json.obj(master, "backgroundColor")))); - g.add(bg); - } - children(master, g); - g.setFrame(0, 0, mf[2], mf[3], false); + Map copy = Json.asObj(copyJson(master)); List ov = Json.list(l, "overrideValues"); if (ov != null) { for (int i = 0; i < ov.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation - override(g, Json.str(ov.get(i), "overrideName"), ov.get(i)); + Object v = ov.get(i); + override(copy, Json.str(v, "overrideName"), v instanceof Map ? Json.asObj(v).get("value") : null); } } - GroupNode holder = new GroupNode(); - if (mf[2] > 0 && mf[3] > 0 && (mf[2] != f[2] || mf[3] != f[3])) { - g.setTransform(Matrix.scale(f[2] / mf[2], f[3] / mf[3])); + List ls = Json.list(copy, "layers"); + if (ls != null && mf[2] > 0 && mf[3] > 0 && (mf[2] != f[2] || mf[3] != f[3]) + && Json.bool(master, "resizesContent", true)) { + relayout(ls, mf[2], mf[3], f[2], f[3]); } + GroupNode g = new GroupNode(); + if (Json.bool(master, "hasBackgroundColor", false) && Json.bool(master, "includeBackgroundColorInInstance", false)) { + ShapeNode bg = ShapeNode.rect(0, 0, f[2], f[3], 0); + bg.fill(new SolidPaint(color(Json.obj(master, "backgroundColor")))); + g.add(bg); + } + children(copy, g); + g.setFrame(0, 0, f[2], f[3], false); + GroupNode holder = new GroupNode(); holder.add(g); holder.setSymbolId(id); return holder; @@ -855,65 +900,169 @@ private ArtNode instance(Map l, double[] f) throws IOException { } } - private void override(GroupNode g, String name, Object ov) throws IOException { + /// Marks a text layer whose string an override replaced, in the copy only. + private static final String OVERRIDDEN = "cn1.overridden"; + + /// A deep copy of parsed JSON: maps and lists are new, everything else is shared. + static Object copyJson(Object o) { + if (o instanceof Map) { + Map m = (Map) o; + Map c = new HashMap(); + for (Map.Entry e : m.entrySet()) { + c.put(String.valueOf(e.getKey()), copyJson(e.getValue())); + } + return c; + } + if (o instanceof List) { + List l = (List) o; + List c = new ArrayList(l.size()); + for (int i = 0; i < l.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation + c.add(copyJson(l.get(i))); + } + return c; + } + return o; + } + + /// Applies one override to a copied master. Its name is a path of layer ids and a property, + /// `id/id_stringValue`: the first id is a layer of this master, and the rest of the path is + /// handed down to that layer when it is itself a symbol instance. + private void override(Map master, String name, Object v) { if (name == null) { return; } int us = name.lastIndexOf('_'); - if (us < 0) { + if (us <= 0) { return; } String path = name.substring(0, us); String prop = name.substring(us + 1); - String target = path.lastIndexOf('/') >= 0 ? path.substring(path.lastIndexOf('/') + 1) : path; - ArtNode n = find(g, target); - if (n == null) { + int slash = path.indexOf('/'); + String head = slash < 0 ? path : path.substring(0, slash); + Map target = findLayer(Json.list(master, "layers"), head); + if (target == null) { + if (slash < 0 && "stringValue".equals(prop) && v instanceof String) { + // A symbol detached from its library keeps overrides naming the library's layer + // ids. With one text in the master there is no doubt which one was meant. + List> texts = new ArrayList>(); + texts(Json.list(master, "layers"), texts); + if (texts.size() == 1) { + setText(texts.get(0), (String) v); + keepCentred(master, texts.get(0)); + } + } + return; + } + if (slash >= 0) { + if ("symbolInstance".equals(Json.str(target, "_class"))) { + List nested = Json.list(target, "overrideValues"); + List all = nested == null ? new ArrayList() : nested; + Map o = new HashMap(); + o.put("overrideName", path.substring(slash + 1) + "_" + prop); + o.put("value", v); + // After the instance's own overrides, so the outer one wins. + all.add(o); + target.put("overrideValues", all); + } return; } - Object v = ov instanceof Map ? Json.asObj(ov).get("value") : null; - if ("stringValue".equals(prop) && n instanceof TextNode && v instanceof String) { - TextNode t = (TextNode) n; - TextRun first = t.getRuns().isEmpty() ? new TextRun("", null, 12, new SolidPaint(0xff000000)) - : t.getRuns().get(0).copy(); - first.setText((String) v); - t.getRuns().clear(); - t.getRuns().add(first); + if ("stringValue".equals(prop) && v instanceof String && "text".equals(Json.str(target, "_class"))) { + setText(target, (String) v); + keepCentred(master, target); } else if ("symbolID".equals(prop) && v instanceof String) { - GroupNode parent = parentOf(g, n); - Map m = symbols.get((String) v); - if (parent != null && m != null) { - GroupNode repl = new GroupNode(); - children(m, repl); - repl.setTransform(n.getTransform()); - repl.setName(n.getName()); - repl.setSymbolId((String) v); - int idx = parent.getChildren().indexOf(n); - parent.getChildren().set(idx, repl); - } else if (parent != null && "".equals(v)) { - n.setVisible(false); - } - } else if ("image".equals(prop)) { - Raster img = image(Json.asObj(v)); - if (img != null && n instanceof GroupNode && !((GroupNode) n).getChildren().isEmpty() - && ((GroupNode) n).getChildren().get(0) instanceof RasterNode) { - RasterNode r = (RasterNode) ((GroupNode) n).getChildren().get(0); - double[] b = r.getBounds(); - r.setImage(img); - if (b != null) { - r.setTransform(Matrix.scale(b[2] / Math.max(1, img.getWidth()), b[3] / Math.max(1, img.getHeight()))); - } + if (((String) v).length() == 0) { + target.put("isVisible", Boolean.FALSE); + } else { + // The swapped symbol takes the slot's frame; instance() lays it out to fit. + target.put("symbolID", v); + target.remove("overrideValues"); + } + } else if ("image".equals(prop) && v instanceof Map && "bitmap".equals(Json.str(target, "_class"))) { + target.put("image", v); + } + } + + private static final String CENTRED = "cn1.centred"; + + /// A text that fits its content and sits centred in its master is a label the designer + /// centred: a button's. Its string is replaced by the override, and the new string stays + /// centred, where growing it from the master's left edge put "Raise your account to the + /// top" off the side of its button. The layer takes the master's width and is centred in it. + private static void keepCentred(Map master, Map text) { + if ((int) Json.num(text, "textBehaviour", 0) != 0) { + return; + } + List top = Json.list(master, "layers"); + if (top == null || !top.contains(text)) { + return; + } + Map mf = Json.obj(master, "frame"); + Map fr = Json.obj(text, "frame"); + if (mf == null || fr == null) { + return; + } + double w = Json.num(mf, "width", 0); + double x = Json.num(fr, "x", 0); + double tw = Json.num(fr, "width", 0); + if (w <= tw || Math.abs(x + tw / 2 - w / 2) > 1) { + return; + } + fr.put("x", Double.valueOf(0)); + fr.put("width", Double.valueOf(w)); + text.put(CENTRED, Boolean.TRUE); + } + + private static void setText(Map text, String v) { + Map as = Json.obj(text, "attributedString"); + if (as == null) { + return; + } + List attrs = Json.list(as, "attributes"); + List one = new ArrayList(); + if (attrs != null && !attrs.isEmpty() && attrs.get(0) instanceof Map) { + Map first = Json.asObj(attrs.get(0)); + first.put("location", Double.valueOf(0)); + first.put("length", Double.valueOf(v.length())); + one.add(first); + } + as.put("string", v); + as.put("attributes", one); + text.put(OVERRIDDEN, Boolean.TRUE); + } + + private static void texts(List ls, List> out) { + if (ls == null) { + return; + } + for (int i = 0; i < ls.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation + Map l = Json.asObj(ls.get(i)); + if (l == null) { + continue; + } + if ("text".equals(Json.str(l, "_class"))) { + out.add(l); + } else if (!"symbolInstance".equals(Json.str(l, "_class"))) { + texts(Json.list(l, "layers"), out); } } } - private static ArtNode find(GroupNode g, String id) { - List ch = g.getChildren(); - for (ArtNode c : ch) { - if (id.equals(c.getId())) { - return c; + /// The layer with this id among these layers and their groups, not inside nested symbols: + /// those carry their own overrides. + private static Map findLayer(List ls, String id) { + if (ls == null) { + return null; + } + for (int i = 0; i < ls.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation + Map l = Json.asObj(ls.get(i)); + if (l == null) { + continue; + } + if (id.equals(Json.str(l, "do_objectID"))) { + return l; } - if (c instanceof GroupNode) { - ArtNode f = find((GroupNode) c, id); + if (!"symbolInstance".equals(Json.str(l, "_class"))) { + Map f = findLayer(Json.list(l, "layers"), id); if (f != null) { return f; } @@ -922,19 +1071,100 @@ private static ArtNode find(GroupNode g, String id) { return null; } - private static GroupNode parentOf(GroupNode g, ArtNode n) { - List ch = g.getChildren(); - for (ArtNode c : ch) { - if (c == n) { // NOPMD CompareObjectsWithEquals - node identity - return g; + /// Moves and sizes layers for a parent that went from ow x oh to nw x nh, the way Sketch + /// does. A text that fits its content and got a different string pushes whatever sits to + /// its right along with it: that is how a chat bubble keeps its time after the message, and + /// how the designer sized the instance in the first place. Everything else follows its + /// resizing constraint. + static void relayout(List ls, double ow, double oh, double nw, double nh) { + double dw = nw - ow; + Map grow = null; + for (int i = 0; i < ls.size() && dw != 0; i++) { + Map l = Json.asObj(ls.get(i)); + if (l != null && holdsGrownText(l)) { + grow = l; + break; } - if (c instanceof GroupNode) { - GroupNode p = parentOf((GroupNode) c, n); - if (p != null) { - return p; + } + double[] gf = grow == null ? null : frame(grow); + for (int i = 0; i < ls.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator allocation + Map l = Json.asObj(ls.get(i)); + if (l == null || Json.obj(l, "frame") == null) { + continue; + } + double[] f = frame(l); + double[] n; + if (l == grow) { // NOPMD CompareObjectsWithEquals - the same layer + n = new double[]{f[0], f[1], f[2] + dw, f[3]}; + double[] v = axis(f[1], f[3], oh, nh, constraint(l), 32, 16, 8); + n[1] = v[0]; + n[3] = v[1]; + } else if (gf != null && f[0] >= gf[0] + gf[2] - 0.5 && f[1] < gf[1] + gf[3] && f[1] + f[3] > gf[1]) { + n = new double[]{f[0] + dw, f[1], f[2], f[3]}; + double[] v = axis(f[1], f[3], oh, nh, constraint(l), 32, 16, 8); + n[1] = v[0]; + n[3] = v[1]; + } else { + int rc = constraint(l); + double[] h = axis(f[0], f[2], ow, nw, rc, 4, 2, 1); + double[] v = axis(f[1], f[3], oh, nh, rc, 32, 16, 8); + n = new double[]{h[0], v[0], h[1], v[1]}; + } + Map fr = Json.obj(l, "frame"); + fr.put("x", Double.valueOf(n[0])); + fr.put("y", Double.valueOf(n[1])); + fr.put("width", Double.valueOf(n[2])); + fr.put("height", Double.valueOf(n[3])); + String cls = Json.str(l, "_class"); + List kids = Json.list(l, "layers"); + if (kids != null && ("group".equals(cls) || "shapeGroup".equals(cls)) && (n[2] != f[2] || n[3] != f[3])) { + relayout(kids, f[2], f[3], n[2], n[3]); + } + } + } + + private static int constraint(Map l) { + return (int) Json.num(l, "resizingConstraint", 63); + } + + private static boolean holdsGrownText(Map l) { + String cls = Json.str(l, "_class"); + if ("text".equals(cls)) { + return Json.bool(l, OVERRIDDEN, false) && (int) Json.num(l, "textBehaviour", 0) == 0; + } + if ("group".equals(cls)) { + List kids = Json.list(l, "layers"); + for (int i = 0; kids != null && i < kids.size(); i++) { + Map k = Json.asObj(kids.get(i)); + if (k != null && holdsGrownText(k)) { + return true; } } } - return null; + return false; + } + + /// One axis of a Sketch resizing constraint. The constraint is a mask of six bits in which a + /// CLEARED bit pins: near edge, size, far edge (`low`, `size`, `high`). 63 pins nothing, and + /// such a layer scales with its parent. + static double[] axis(double pos, double len, double old, double now, int rc, int low, int size, int high) { + boolean pinLow = (rc & low) == 0; + boolean fixed = (rc & size) == 0; + boolean pinHigh = (rc & high) == 0; + double k = old == 0 ? 1 : now / old; + if (pinLow && pinHigh) { + return new double[]{pos, Math.max(0, len + now - old)}; + } + if (pinLow) { + return new double[]{pos, fixed ? len : len * k}; + } + if (pinHigh) { + double nl = fixed ? len : len * k; + return new double[]{now - (old - pos - len) - nl, nl}; + } + if (fixed) { + return new double[]{(pos + len / 2) * k - len / 2, len}; + } + return new double[]{pos * k, len * k}; } } diff --git a/CodenameOne/src/com/codename1/art/SvgReader.java b/CodenameOne/src/com/codename1/art/SvgReader.java index d3d7ace7d0f..fdc7fab170a 100644 --- a/CodenameOne/src/com/codename1/art/SvgReader.java +++ b/CodenameOne/src/com/codename1/art/SvgReader.java @@ -494,6 +494,10 @@ private void applyCommon(SvgElement e, ArtNode node, Map st) { if (label == null) { label = e.attr("label"); } + if (label == null) { + // Illustrator, and SvgWriter, keep a layer name that is not a valid id here. + label = e.attr("data-name"); + } node.setName(label != null ? label : (e.attr("id") != null ? e.attr("id") : e.name)); Matrix t = transform(e.attr("transform")); if ("use".equals(e.name)) { diff --git a/CodenameOne/src/com/codename1/components/CoachMarks.java b/CodenameOne/src/com/codename1/components/CoachMarks.java index 3e935e5edd7..4f1077370f3 100644 --- a/CodenameOne/src/com/codename1/components/CoachMarks.java +++ b/CodenameOne/src/com/codename1/components/CoachMarks.java @@ -94,6 +94,8 @@ public class CoachMarks { private int current = -1; private Overlay overlay; private ActionListener pressListener; + private ActionListener dragListener; + private boolean sawPress; private ActionListener releaseListener; /// A tour over a form. Add steps with `#add(Component, String, String)`. @@ -242,16 +244,30 @@ public void show() { return; } overlay = new Overlay(); - pressListener = new ConsumeListener(); + dragListener = new ConsumeListener(); + sawPress = false; + pressListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent evt) { + evt.consume(); + sawPress = true; + } + }; releaseListener = new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { evt.consume(); - released(evt.getX(), evt.getY()); + // Only a release whose press the tour saw: a tour started by a button's action + // gets that very release next, and would take it as a tap on the dim and skip + // its first step. + if (sawPress) { + sawPress = false; + released(evt.getX(), evt.getY()); + } } }; form.addPointerPressedListener(pressListener); - form.addPointerDraggedListener(pressListener); + form.addPointerDraggedListener(dragListener); form.addPointerReleasedListener(releaseListener); // The layer starts with a flow layout that is never laid out again, // which left the overlay 0x0 when the tour began before the form was @@ -292,7 +308,7 @@ public void dismiss() { return; } form.removePointerPressedListener(pressListener); - form.removePointerDraggedListener(pressListener); + form.removePointerDraggedListener(dragListener); form.removePointerReleasedListener(releaseListener); Overlay o = overlay; overlay = null; @@ -591,9 +607,14 @@ public void layoutContainer(Container parent) { int margin = CN.convertToPixels(4f); int gap = CN.convertToPixels(2.5f); int w = Math.min(parent.getWidth() - margin * 2, CN.convertToPixels(80f)); + // Wrapped text is as tall as the width it wraps at, and it learns that width from a + // layout: lay the bubble out at its width first, then measure, or a long text is + // measured as one line and the bubble cuts it and its buttons off. bubble.setWidth(w); + bubble.setHeight(parent.getHeight()); + bubble.layoutContainer(); bubble.setShouldCalcPreferredSize(true); - int h = bubble.getPreferredH(); + int h = Math.min(bubble.getPreferredH(), parent.getHeight() - margin * 2); int[] hole = o.hole(); o.laidOutHole = hole; int x; diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java index ca43fb64531..0cbdfd0b4a4 100644 --- a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java +++ b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java @@ -5086,12 +5086,17 @@ private BufferedImage updateBufferSize(BufferedImage buffer) { if (getScreenCoordinates() == null) { java.awt.Dimension d = getSize(); double cs = canvasScale(); - if (buffer == null || buffer.getWidth() != (int)(d.width * cs) || buffer.getHeight() != (int)(d.height * cs)) { + // Compare against the size createBufferedImage really makes: it never goes below + // 20x20. Comparing against the raw size made a canvas that was never shown (0x0: + // headless runs, tests, command line tools) replace its buffer on every call, and + // getGraphics2D then slept 10ms -- once per stringWidth and font height. + if (buffer == null || buffer.getWidth() != Math.max(20, (int)(d.width * cs)) + || buffer.getHeight() != Math.max(20, (int)(d.height * cs))) { buffer = createBufferedImage(); } } else { - if (buffer == null || buffer.getWidth() != (int) (getScreenCoordinates().width * zoomLevel) - || buffer.getHeight() != (int) (getScreenCoordinates().height * zoomLevel)) { + if (buffer == null || buffer.getWidth() != Math.max(20, (int) (getScreenCoordinates().width * zoomLevel)) + || buffer.getHeight() != Math.max(20, (int) (getScreenCoordinates().height * zoomLevel))) { buffer = createBufferedImage(); } } diff --git a/docs/demos/common/src/main/snippets/developer-guide/design-import.sh b/docs/demos/common/src/main/snippets/developer-guide/design-import.sh new file mode 100644 index 00000000000..6d1f901535f --- /dev/null +++ b/docs/demos/common/src/main/snippets/developer-guide/design-import.sh @@ -0,0 +1,24 @@ +// Generated from docs/developer-guide source blocks. Edit the guide snippets here, not inline. + +// tag::design-import-bash-001[] +mvn cn1:import-design # Maven +./gradlew importDesign # Gradle +// end::design-import-bash-001[] + +// tag::design-import-bash-002[] +mvn cn1:import-design -Dcn1.design=designs/login.fig -Dcn1.design.class=LoginForm +./gradlew importDesign -Pcn1.design=designs/login.fig -Pcn1.design.class=LoginForm +// end::design-import-bash-002[] + +// tag::design-import-bash-003[] +export FIGMA_TOKEN=figd_... +mvn cn1:import-design -Dcn1.design="https://www.figma.com/design/KEY/Shop?node-id=0-1" +// end::design-import-bash-003[] + +// tag::design-import-bash-004[] +cd scripts/designimport +./design-import.sh # the desktop window +./design-import.sh login.sketch out LoginForm # headless: writes the form, CSS and test +./design-import.sh --script ops.json # headless: plays a list of operations +./design-import.sh --mcp-stdio # an MCP server on standard input and output +// end::design-import-bash-004[] diff --git a/docs/developer-guide/Design-Import.asciidoc b/docs/developer-guide/Design-Import.asciidoc new file mode 100644 index 00000000000..1f807a91adb --- /dev/null +++ b/docs/developer-guide/Design-Import.asciidoc @@ -0,0 +1,275 @@ +[[design-import]] +== Design Import + +Design Import turns a design into a Codename One form. Point it at a Figma file, by its link or +as a `.fig` file, or at a Sketch (`.sketch`), Photoshop (`.psd`) or SVG file, and it writes three +things: + +* a `Form` subclass that builds the screen, split into a generated base class and a subclass + that's yours to edit; +* a stylesheet with one UIID for each distinct style in the design; +* a unit test that checks every component is there with its UIID and text, that wide ones + stretch and that the vertical order matches the design. + +The tool doesn't pretend the result is finished. Every guess it makes and every effect +that CSS can't express is recorded as an issue, with the layer it applies to and how to fix it. + +image::img/design-import/workbench.png[The review step: layers on the left, the design and the live form side by side, the selected text field outlined in both, the issue guide and the inspector on the right,role="text-center"] + +=== Importing a design into your project + +Run the import from the root of a Codename One application: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/design-import.sh[tag=design-import-bash-001,indent=0] +---- + +This opens the import wizard. It takes four steps: + +. *Design*: choose the file, or paste a Figma link (see <>). +. *Screens*: when the file holds several screens, choose the ones to import. Every screen is + chosen to begin with, and each becomes a form of its own. A phone frame and a tablet frame + of the same screen, such as `Login / Phone` and `Login / Tablet`, are one screen and become + one form that adapts between them. +. *Review*: the workbench described below, one screen at a time. +. *Write*: confirm the package, and the forms go into the project, each named after its + screen. + +image::img/design-import/wizard.png[The wizard's screens step: a card for each screen of the design with its thumbnail, all of them chosen,role="text-center"] + +The screens shown here and below come from the Laza E-commerce UI Kit, a Figma Community file +published under CC BY 4.0. + +The *A-* and *A+* buttons in the title bar make the text of the tool smaller or larger, and the +tool remembers the size. + +Every step has a short tour: coach marks that point at each part of the page in turn and say +what it's for. Press *?* in the title bar to play the tour of the step you're on, *Next* to move +through it and *Skip* to close it. The review step's tour plays by itself the first time you +reach it. + +image::img/design-import/tour.png[The review step's tour: the design pane is outlined and a bubble explains it, with Skip and Next buttons and a step count,role="text-center"] + +Name the design to skip the window and import it as it comes: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/design-import.sh[tag=design-import-bash-002,indent=0] +---- + +`-Dcn1.design.gui=true` (`-Pcn1.design.gui=true` with Gradle) opens the wizard on a named +design, starting at its screens step, or at the review step when the design holds one screen. + +The form goes into the package of your application, unless `cn1.design.package` names +another. `cn1.design.frame` picks the frame when the file holds several: give a layer id, a +name path such as `Page 1/Login`, or an index path such as `#0/2`. Without it the tool picks +the most screen-like frame, and pairs it with a tablet frame of the same name when the file +has one. + +The import writes `LoginFormBase.java`, `LoginForm.java`, `LoginForm.css` (imported from +`theme.css`), the images and `LoginFormTest.java`. It prints each step as it runs, then the +files it wrote, how well the form matches the design and the open issues. Renders of the +design and of the form go to `target/design-import`, or `build/design-import` with Gradle, so you can +compare the two. Importing again rewrites the base class, the stylesheet and the test, and +leaves the subclass alone. + +The tool isn't part of the build plugin. The first import downloads it, as +`com.codenameone:codenameone-design-import` at the plugin's version, and later imports read it from the +local repository. An import takes a second or two. + +[[design-import-figma]] +=== Importing from a Figma link + +You don't need to export anything from Figma. Open the file in Figma, choose *Share* and then +*Copy link*, and paste the link into the wizard's first step. Links to a design, a file or a +prototype all work, and so does a Figma Community file once you have duplicated it into your +own account. + +image::img/design-import/wizard-design.png[The wizard's first step with a Figma link pasted and the access token field filled in,role="text-center"] + +Figma reads the file only for someone it knows, so the tool also needs a personal access token: + +. In Figma, open the account menu (your name, top left) and choose *Settings*, then *Security*. +. Under *Personal access tokens*, choose *Generate new token*. +. Give it read access to *File content* and create it. +. Copy the token. Figma shows it only once. + +Paste the token into the field under the link, or set the `FIGMA_TOKEN` environment variable +before you start the import, and the field fills itself in. The token goes only to Figma's +API, to read the file, and is never saved or written to a log. + +A link works without the wizard too. The token then has to come from `FIGMA_TOKEN`: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/design-import.sh[tag=design-import-bash-003,indent=0] +---- + +Reading a large file takes Figma half a minute or so, and the wizard says so while it waits. + +Figma limits how often a token can read a whole file, and on the Starter plan a handful of reads +in a short time can lock the token out for days. The tool therefore keeps a copy of each file +it reads, the design and its images but never the token, under +`design-import/figma/` in its home directory. When Figma refuses a read, the import +opens that copy, and a note at the bottom of the window says so and how long Figma asked to +wait. With no copy, the error says how long the wait is. To read a file again after changing +it in Figma, wait until the limit lifts. + +=== Importing a React or HTML prototype + +Tools that generate prototypes as code, such as Claude Design, v0 and Lovable, usually produce one +`.html` file that loads React and Babel from a CDN, sometimes with `.jsx` files beside an `index.html`. +Open the `.html` file, the folder holding `index.html`, or one of the `.jsx` files beside it, the same +way you open a design file. + +The tool doesn't parse the code. It runs the prototype in headless Chrome and reads what the page +rendered, so it works however the prototype is packaged. That has two requirements: + +* Google Chrome, Chromium or Microsoft Edge must be installed. If the tool can't find it, set the + `designimport.chrome` system property or the `CHROME_PATH` environment variable to the browser's + executable. +* The machine needs a network connection when the prototype loads its scripts from a CDN. When a + script can't be reached the page renders nothing, and the import stops with an error naming the + script, rather than importing an empty screen. + +The page renders twice, at a phone width of 390 and a desktop width of 1440, and each render becomes +one frame as tall as the page, named `Phone` and `Desktop`. A tall page becomes a scrolling form. Flex +and grid containers keep their direction, gap and padding, and elements with fixed or sticky positioning +are marked as such, so the layout follows the prototype's own CSS rather than a guess from positions. +Images the page loads from the web aren't fetched; local images and inline SVG are imported. + +=== The workbench + +The workbench shows the design and the form it became side by side, each scaled to fit its +pane. Click an element in either one, or a layer in the tree on the left, and it's outlined +in both, so you can see what each part of the design turned into. + +The guide on the right walks the open issues one at a time, warnings first. Each one outlines +the element it concerns. Accept it with *Fine as is*, change the element in the inspector below +the guide, or take the element out of the form with *Leave it out*. Under *Or try*, the guide +offers other readings of the element that answer the issue, such as a different kind of +component, a picture of it, or its exact positions; one click applies it and moves on. *Accept all notes* clears the +notes about faithful compromises, such as a shadow drawn as an elevation, in one step. The full +list of issues is under the guide. Hover over one to read it whole, and click it to show it in the guide. + +The form pane is a live form, not a picture of one. Pick a device from the size menu, a phone, a +tablet, a laptop or a desktop window, or type a width and height, and the form is built again at +that size. Drag the handles at the right and bottom edges to resize it continuously and watch +components stretch, wrap and move. The rotate button swaps width and height. Three modes decide +what a click does: + +Inspect:: Selects the element under the pointer, in the form and in the design. +Interact:: Hands the click to the form, so you can type in fields, flip switches, scroll a long +screen and dismiss a popup. +Fit:: Scales the whole form into the pane instead of showing it at its real size. + +When a document has a phone, a tablet and a desktop frame of one screen, the form uses each +from its own width up, and the size menu shows which one is in use. + +Two cards under the inspector explain the selected element. *Code* shows the Java lines that +build it and the CSS rule of its style, cut from the files the import writes; *Form Java* and +*Stylesheet* open the whole files. *Resizing* holds the choices that decide how the form adapts: +whether components stretch to the width, whether the content scrolls, the widest the content +column gets, and the widths at which the tablet and desktop layouts take over. Changing one +rebuilds the form at once. + +Several screens imported together are shown as a strip of chips above the panes; click one to +review it. + +The workbench is the wizard's review step, and it also runs on its own from a checkout of +Codename One: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/design-import.sh[tag=design-import-bash-004,indent=0] +---- + +The headless form also writes `design.png` and `preview.png` next to the sources and prints +how well the form matches the design. + +=== The stages + +Each import runs the same stages in order, and each one can be inspected: + +Scope:: Picks the frame to import. A document with several frames gets the most screen-like +one. A phone frame and a tablet frame with the same name, such as `Login / Phone` and +`Login / Tablet`, become two variants of one form. A screen pasted into a device mockup is +found inside the bezel and imported without it. +Detect and classify:: Decides what each layer is: a button, a text field, a check box, a +label, an image, a title bar. Layer names help when they mean something, but the shapes +decide: a filled box with one centred line of text is a button whether it's called +`Button` or `Rectangle 9`, and a tall box with one grey line at its top left is a text field +that takes several lines. +Structure and layout:: Groups layers into rows and columns and picks a layout for each +container. Figma auto layout carries over unchanged. +Popups and long screens:: A layer that dims the whole screen and holds a smaller panel is a +popup. It becomes a layer over the form that a tap outside the panel closes, and a panel at the +bottom edge becomes a bottom sheet. A screen drawn taller than a device is a scrolling form: the +title bar stays at the top, the tab bar at the bottom, and the rest scrolls. A row that runs past +the right edge, such as a strip of chips, scrolls sideways. +Responsive:: With one frame, the form adapts by default: wide components stretch, content is +capped at a maximum width and centred on large screens, and the content scrolls. With two +variants, the form switches between their layouts at a width breakpoint. +Style:: Writes the stylesheet. Colors, fonts, corner radii, borders and gradients map to CSS. +Effects that have no CSS form, such as blend modes and inner shadows, are rendered to an +image or replaced, and each such compromise is an issue. +Emit:: Writes the sources. A second import rewrites the base class and the stylesheet and +never touches your subclass. The stylesheet is added to `theme.css` with `@import`, because a +project build compiles only `theme.css`. + +=== Issues + +An issue has a severity (`INFO`, `WARNING` or `TODO`), the stage that raised it, the layer it +applies to and a suggested fix. In the window, the checklist groups them by stage. Clicking +one selects its layer, and *Accept* marks it as handled. + +One warning deserves mention. A design that comes back as pictures, such as a flattened PSD +or a screenshot, raises a `flattened` warning. The form would be an image of a UI, and it +would match the design while being useless, so the tool says so instead of reporting +a good score. + +=== Driving it from an LLM + +The same operations the window uses are MCP tools. An LLM client can open a design, read the +tree and the issues, override a role or a layout, render the preview at a width, score it +against the design and emit the sources: + +[cols="1,3"] +|=== +|Tool |What it does + +|`designimport_open` |Opens a design from a path or from base64 data. +|`designimport_frames` |Lists the frames that look like screens. +|`designimport_options` |Reads or sets the import options: the class and package names, the frames to import and the responsive settings. +|`designimport_run` |Runs the stages, all of them or up to a named one (`scope`, `detect`, `structure`, `classify`, `layout`, `responsive`, `style`, `emit`). +|`designimport_tree` |Returns the classified layer tree. +|`designimport_issues` |Returns the open issues. +|`designimport_set` |Overrides a layer's role, layout, alignment or UIID. +|`designimport_resolve` |Marks an issue as handled. +|`designimport_preview` |Renders the form, and the design, at a given width. +|`designimport_score` |Measures how well the form matches the design. +|`designimport_emit` |Writes the sources into a project, or returns them. +|=== + +Run `./design-import.sh --mcp-stdio` to serve them to a client that launches its servers as +processes. The desktop window serves them on a socket when it starts with +`-Ddesignimport.mcp.port=PORT`. + +=== How well it works + +The examples in `scripts/designimport/examples` show the input and the output side by side +for every case below, with the generated sources and the issues each import raised. + +The tool's tests rebuild the twelve GUI Builder demo forms, export each to SVG with every layer +renamed the way design tools name layers nobody named, and import them again. Because the +answer is known, the result can be scored: 71 of 74 components come back as the right kind of +component. The five Sketch files that illustrate the GUI Builder chapter of this guide are imported too, +and are never used to tune the rules. + +image::img/design-import/grid-before.png[A grid of buttons as designed,role="text-center"] + +image::img/design-import/grid-after.png[The same grid as a running Codename One form,role="text-center"] + +Treat the output as a starting point. The layout is usually right; spacing is close; multi-line +text and unusual controls often need a role override or a hand edit in your subclass. diff --git a/docs/developer-guide/developer-guide.asciidoc b/docs/developer-guide/developer-guide.asciidoc index e48cd5dfde4..5bc5918306f 100644 --- a/docs/developer-guide/developer-guide.asciidoc +++ b/docs/developer-guide/developer-guide.asciidoc @@ -380,6 +380,8 @@ include::Working-With-CodenameOne-Sources.asciidoc[] include::Skin-Designer.asciidoc[] +include::Design-Import.asciidoc[] + = Appendices include::Promises.asciidoc[] diff --git a/docs/developer-guide/img/design-import/grid-after.png b/docs/developer-guide/img/design-import/grid-after.png new file mode 100644 index 00000000000..7ca2a5f0eb4 Binary files /dev/null and b/docs/developer-guide/img/design-import/grid-after.png differ diff --git a/docs/developer-guide/img/design-import/grid-before.png b/docs/developer-guide/img/design-import/grid-before.png new file mode 100644 index 00000000000..db8ab1f4314 Binary files /dev/null and b/docs/developer-guide/img/design-import/grid-before.png differ diff --git a/docs/developer-guide/img/design-import/tour.png b/docs/developer-guide/img/design-import/tour.png new file mode 100644 index 00000000000..bd9a129a26d Binary files /dev/null and b/docs/developer-guide/img/design-import/tour.png differ diff --git a/docs/developer-guide/img/design-import/wizard-design.png b/docs/developer-guide/img/design-import/wizard-design.png new file mode 100644 index 00000000000..c54aab4dca0 Binary files /dev/null and b/docs/developer-guide/img/design-import/wizard-design.png differ diff --git a/docs/developer-guide/img/design-import/wizard.png b/docs/developer-guide/img/design-import/wizard.png new file mode 100644 index 00000000000..77790425972 Binary files /dev/null and b/docs/developer-guide/img/design-import/wizard.png differ diff --git a/docs/developer-guide/img/design-import/workbench.png b/docs/developer-guide/img/design-import/workbench.png new file mode 100644 index 00000000000..e2bf60a313f Binary files /dev/null and b/docs/developer-guide/img/design-import/workbench.png differ diff --git a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java index b5af9ad1cf4..781756357df 100644 --- a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java +++ b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/AppSupport.java @@ -286,6 +286,22 @@ static void apply(final Project project, final ProjectLayout layout, final Coden main.getResources().exclude(new NestedDesktopResources( new File(layout.buildDir(), "generated/resources/cn1-desktop").getAbsoluteFile())); + // Resolved only when importDesign runs, so a project that never imports a design + // never downloads the tool. + final Configuration designImport = resolvable(project, "cn1DesignImport", "The Codename One Design Import tool"); + addFramework(project, designImport.getName(), version, "codenameone-design-import"); + project.getTasks().register("importDesign", com.codename1.gradle.tasks.ImportDesignTask.class, t -> { + common(t, project, layout, ext, userProperties); + t.setDescription("Imports a Figma, Sketch, PSD or SVG design as a form (the wizard, or -Pcn1.design=FILE)"); + t.getToolClasspath().from(designImport); + t.getDesign().set(project.getProviders().gradleProperty("cn1.design")); + t.getClassName().set(project.getProviders().gradleProperty("cn1.design.class")); + t.getFrame().set(project.getProviders().gradleProperty("cn1.design.frame")); + t.getPackageName().set(project.getProviders().gradleProperty("cn1.design.package")); + t.getGui().set(project.getProviders().gradleProperty("cn1.design.gui")); + t.getOutputs().upToDateWhen(x -> false); + }); + TaskProvider css = project.getTasks().register("cn1Css", Cn1CssTask.class, t -> { common(t, project, layout, ext, userProperties); t.setDescription("Compiles src/main/css into theme.res"); diff --git a/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/tasks/ImportDesignTask.java b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/tasks/ImportDesignTask.java new file mode 100644 index 00000000000..0c5d462ddd5 --- /dev/null +++ b/maven/codenameone-gradle-plugin/src/main/java/com/codename1/gradle/tasks/ImportDesignTask.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.gradle.tasks; + +import org.gradle.api.GradleException; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Classpath; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.Optional; +import org.gradle.api.tasks.TaskAction; +import org.gradle.process.ExecOperations; + +import javax.inject.Inject; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/// `gradle importDesign [-Pcn1.design=designs/login.fig] [-Pcn1.design.class=LoginForm] +/// [-Pcn1.design.frame="Page 1/Login"] [-Pcn1.design.package=com.acme] [-Pcn1.design.gui=true]`: +/// the Gradle twin of `cn1:import-design`. With no design, or with `cn1.design.gui`, it opens +/// the import wizard in a window. Forks `codenameone-design-import`, which the `cn1DesignImport` +/// configuration resolves at the plugin's version the first time this task runs; its steps +/// are printed as they happen. +public abstract class ImportDesignTask extends Cn1Task { + /// The tool and its runtime dependencies. + @Classpath + public abstract ConfigurableFileCollection getToolClasspath(); + + /// The design file, relative to the project directory unless absolute. + @Input + @Optional + public abstract Property getDesign(); + + @Input + @Optional + public abstract Property getClassName(); + + @Input + @Optional + public abstract Property getFrame(); + + @Input + @Optional + public abstract Property getPackageName(); + + /// `true` opens the wizard even though a design is named. + @Input + @Optional + public abstract Property getGui(); + + @Inject + protected abstract ExecOperations getExecOperations(); + + @TaskAction + public void importDesign() { + File dir = getProjectDirectory().get().getAsFile(); + boolean named = getDesign().isPresent() && getDesign().get().length() > 0; + final boolean window = !named || "true".equals(getGui().getOrNull()); + String design = null; + if (named) { + String d = getDesign().get().trim(); + if (d.startsWith("https://") && d.contains("figma.com/") || d.startsWith("figma.com/") + || d.startsWith("www.figma.com/")) { + // A Figma link, passed on as written; the token comes from FIGMA_TOKEN. + design = d; + } else { + File f = new File(d); + if (!f.isAbsolute()) { + f = new File(dir, d); + } + if (!f.isFile()) { + throw new GradleException("No design at " + f); + } + design = f.getAbsolutePath(); + } + } + String pkg = getPackageName().getOrNull(); + if (pkg == null) { + pkg = effectiveSettings().getProperty("codename1.packageName"); + } + final List args = new ArrayList(); + if (window) { + args.add("--gui"); + getLogger().lifecycle("[design-import] opening the import wizard; close its window to stop"); + } + args.add("--project"); + args.add(dir.getAbsolutePath()); + if (design != null) { + args.add("--design"); + args.add(design); + } + add(args, "--class", getClassName().getOrNull()); + add(args, "--package", pkg); + add(args, "--frame", getFrame().getOrNull()); + if (!window) { + args.add("--preview"); + args.add(new File(getBuildDirectory().get().getAsFile(), "design-import").getAbsolutePath()); + } + int status = getExecOperations().javaexec(spec -> { + spec.classpath(getToolClasspath()); + spec.getMainClass().set("com.codename1.designimport.DesignImportCli"); + if (!window) { + spec.jvmArgs("-Djava.awt.headless=true"); + } + spec.args(args); + spec.setWorkingDir(dir); + spec.setIgnoreExitValue(true); + }).getExitValue(); + // 4 is DesignImportWindow.CLOSED_WITHOUT_IMPORT: the tool is forked, not linked. + if (window && status == 4) { + getLogger().lifecycle("The wizard was closed before it wrote anything; nothing was imported."); + } else if (status != 0) { + throw new GradleException("Design Import failed (exit status " + status + "); see above."); + } + } + + private static void add(List args, String flag, String value) { + if (value != null && value.length() > 0) { + args.add(flag); + args.add(value); + } + } +} diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/AbstractCN1Mojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/AbstractCN1Mojo.java index db0aa06c6c0..b4522b65822 100644 --- a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/AbstractCN1Mojo.java +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/AbstractCN1Mojo.java @@ -988,7 +988,7 @@ protected File resolveExact(String groupId, String artifactId, String version, S /// The version this plugin was built at, which is the version its ports were /// published at. Not `cn1.plugin.version`: that is a property a project sets by /// convention, and a project that names the plugin's version directly has none. - private String ownVersion() { + protected String ownVersion() { if (pluginVersion != null && pluginVersion.length() > 0) { return pluginVersion; } diff --git a/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/ImportDesignMojo.java b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/ImportDesignMojo.java new file mode 100644 index 00000000000..4d2401988a7 --- /dev/null +++ b/maven/codenameone-maven-plugin/src/main/java/com/codename1/maven/ImportDesignMojo.java @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.maven; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; +import org.apache.maven.artifact.resolver.ArtifactResolutionResult; +import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/// Imports a Figma, Sketch, PSD or SVG design as a form: +/// +/// ``` +/// mvn cn1:import-design # the wizard, in a window +/// mvn cn1:import-design -Dcn1.design=designs/login.fig [-Dcn1.design.class=LoginForm] +/// [-Dcn1.design.frame="Page 1/Login"] [-Dcn1.design.gui=true] +/// ``` +/// +/// With no design named, or with `cn1.design.gui`, it opens the import wizard: choose the +/// design and the screen in it, review and correct what the import decided, and write the +/// form. Otherwise it imports without a window and prints the issues. +/// +/// Writes a generated base class and a subclass that is yours to edit into the common +/// module's package, the form's stylesheet (imported from `theme.css`), its images and a unit +/// test, and prints the issues the import raised. Importing again rewrites the base class and +/// the stylesheet and leaves your subclass alone. +/// +/// The tool is `com.codenameone:codenameone-design-import`, resolved at this plugin's own +/// version the first time it is needed and forked: the plugin does not depend on it, so a +/// project that never imports a design never downloads it. +@Mojo(name = "import-design", requiresProject = true, aggregator = true) +public class ImportDesignMojo extends AbstractCN1Mojo { + static final String TOOL_ARTIFACT = "codenameone-design-import"; + static final String TOOL_MAIN = "com.codename1.designimport.DesignImportCli"; + /// DesignImportWindow.CLOSED_WITHOUT_IMPORT: the tool is forked, not linked. + static final int CLOSED_WITHOUT_IMPORT = 4; + + /// The design file, or a Figma link (the token comes from `FIGMA_TOKEN`). + @Parameter(property = "cn1.design") + private String design; + + /// The form's class name; defaults to one made from the frame's name. + @Parameter(property = "cn1.design.class") + private String className; + + /// The frame to import: a layer id, an index path (`#0/2`) or a name path + /// (`Page 1/Login`). Defaults to the most screen-like frame, paired with a tablet + /// frame of the same name when there is one. + @Parameter(property = "cn1.design.frame") + private String frame; + + /// The package; defaults to the application's `codename1.packageName`. + @Parameter(property = "cn1.design.package") + private String packageName; + + /// Opens the wizard even though a design is named. + @Parameter(property = "cn1.design.gui", defaultValue = "false") + private boolean gui; + + @Override + protected void executeImpl() throws MojoExecutionException, MojoFailureException { + boolean window = gui || design == null; + String file = null; + if (design != null && design.length() > 0) { + if (isFigmaLink(design)) { + // Passed on as written: the tool reads it from Figma's API. + file = design; + } else { + File f = new File(design); + f = f.isAbsolute() ? f : new File(project.getBasedir(), design); + if (!f.isFile()) { + throw new MojoFailureException("No design at " + f); + } + file = f.getAbsolutePath(); + } + } else { + window = true; + } + File common = getCN1ProjectDir(); + if (common == null) { + throw new MojoExecutionException("Run this from a Codename One application project"); + } + String pkg = packageName; + if (pkg == null && properties != null) { + pkg = properties.getProperty("codename1.packageName"); + } + String version = ownVersion(); + if (version == null) { + throw new MojoExecutionException("Cannot tell which version of " + TOOL_ARTIFACT + " to use"); + } + getLog().info("[design-import] resolving " + TOOL_ARTIFACT + " " + version + + " (downloaded once, then read from the local repository)"); + List cp = resolveTool(version); + List cmd = new ArrayList(); + cmd.add(new File(new File(System.getProperty("java.home"), "bin"), "java").getPath()); + if (!window) { + cmd.add("-Djava.awt.headless=true"); + } else { + getLog().info("[design-import] opening the import wizard; close its window to stop"); + } + cmd.add("-cp"); + StringBuilder sb = new StringBuilder(); + for (File f : cp) { + if (sb.length() > 0) { + sb.append(File.pathSeparatorChar); + } + sb.append(f.getAbsolutePath()); + } + cmd.add(sb.toString()); + cmd.add(TOOL_MAIN); + cmd.addAll(toolArguments(window, common, file, className, pkg, frame, + new File(common, "target/design-import"))); + int status; + try { + Process p = new ProcessBuilder(cmd).directory(common).start(); + p.getOutputStream().close(); + Thread err = relay(p.getErrorStream(), true); + relay(p.getInputStream(), false).join(); + err.join(); + status = p.waitFor(); + } catch (IOException ex) { + throw new MojoExecutionException("Could not start the Design Import tool", ex); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new MojoExecutionException("Interrupted", ex); + } + if (window && status == CLOSED_WITHOUT_IMPORT) { + getLog().info("The wizard was closed before it wrote anything; nothing was imported."); + return; + } + if (status != 0) { + throw new MojoFailureException("Design Import failed (exit status " + status + "); see above."); + } + } + + /// The command line DesignImportCli takes: its project mode, or its wizard (`--gui`), + /// which may start without a design and writes no renders. + static List toolArguments(boolean gui, File project, String design, String className, String pkg, + String frame, File previewDir) { + List a = new ArrayList(); + if (gui) { + a.add("--gui"); + } + a.add("--project"); + a.add(project.getAbsolutePath()); + if (design != null) { + a.add("--design"); + a.add(design); + } + if (className != null && className.length() > 0) { + a.add("--class"); + a.add(className); + } + if (pkg != null && pkg.length() > 0) { + a.add("--package"); + a.add(pkg); + } + if (frame != null && frame.length() > 0) { + a.add("--frame"); + a.add(frame); + } + if (!gui) { + a.add("--preview"); + a.add(previewDir.getAbsolutePath()); + } + return a; + } + + /// A Figma link (`figma.com/design/...`, `/file/`, `/proto/`), which is not a file path. + static boolean isFigmaLink(String s) { + String t = s.trim(); + return t.startsWith("https://") && t.contains("figma.com/") || t.startsWith("figma.com/") + || t.startsWith("www.figma.com/"); + } + + /// Passes the tool's output on line by line, as it comes: its standard error carries + /// the steps (`[design-import] ...`) and the port's own chatter, which is dropped. + private Thread relay(final InputStream in, final boolean steps) { + Thread t = new Thread(new Runnable() { + @Override + public void run() { + try { + BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); + String line; + while ((line = r.readLine()) != null) { + if (!steps) { + getLog().info(line); + } else if (line.startsWith("[design-import]")) { + getLog().info(line); + } else if (line.contains("Exception") || line.startsWith("\tat ")) { + getLog().warn(line); + } else { + getLog().debug(line); + } + } + } catch (IOException ex) { + getLog().debug(ex); + } + } + }, "design-import-" + (steps ? "err" : "out")); + t.setDaemon(true); + t.start(); + return t; + } + + private static final ScopeArtifactFilter RUNTIME_SCOPE = new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME); + + /// The tool jar first, then its runtime dependencies (the core and the JavaSE port). + private List resolveTool(String version) throws MojoFailureException { + Artifact artifact = repositorySystem.createArtifact(GROUP_ID, TOOL_ARTIFACT, version, "jar"); + List repositories = + new ArrayList(); + if (remoteRepositories != null) { + repositories.addAll(remoteRepositories); + } + if (project != null && project.getPluginArtifactRepositories() != null) { + for (org.apache.maven.artifact.repository.ArtifactRepository r : project.getPluginArtifactRepositories()) { + if (!repositories.contains(r)) { + repositories.add(r); + } + } + } + ArtifactResolutionResult result = repositorySystem.resolve(new ArtifactResolutionRequest() + .setLocalRepository(localRepository) + .setRemoteRepositories(repositories) + .setResolveTransitively(true) + .setCollectionFilter(RUNTIME_SCOPE) + .setResolutionFilter(RUNTIME_SCOPE) + .setOffline(offline) + .setArtifact(artifact)); + String incomplete = resolutionFailure(result); + if (incomplete != null || artifact.getFile() == null || !artifact.getFile().isFile()) { + throw new MojoFailureException("Importing a design needs " + GROUP_ID + ":" + TOOL_ARTIFACT + ":" + version + + ", which could not be resolved" + (incomplete == null ? "" : ": " + incomplete) + + ".\nRun again with -U, or without -o if the build is offline."); + } + List files = new ArrayList(); + files.add(artifact.getFile()); + if (result.getArtifacts() != null) { + for (Artifact a : result.getArtifacts()) { + File f = a.getFile(); + if (f != null && f.isFile() && !files.contains(f)) { + files.add(f); + } + } + } + return files; + } +} diff --git a/maven/codenameone-maven-plugin/src/test/java/com/codename1/maven/ImportDesignMojoTest.java b/maven/codenameone-maven-plugin/src/test/java/com/codename1/maven/ImportDesignMojoTest.java new file mode 100644 index 00000000000..5cdbaec070f --- /dev/null +++ b/maven/codenameone-maven-plugin/src/test/java/com/codename1/maven/ImportDesignMojoTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.maven; + + +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ImportDesignMojoTest { + @Test + void passesOnlyWhatWasGiven() { + File p = new File("/p").getAbsoluteFile(); + String d = new File("/d.fig").getAbsolutePath(); + File out = new File("/p/target/design-import").getAbsoluteFile(); + List a = ImportDesignMojo.toolArguments(false, p, d, null, "com.acme", "", out); + assertEquals(Arrays.asList("--project", p.getPath(), "--design", d, "--package", "com.acme", + "--preview", out.getPath()), a); + List b = ImportDesignMojo.toolArguments(false, p, d, "LoginForm", null, "Page 1/Login", out); + assertEquals(Arrays.asList("--project", p.getPath(), "--design", d, "--class", "LoginForm", + "--frame", "Page 1/Login", "--preview", out.getPath()), b); + // The wizard can start with nothing chosen, and renders nothing. + assertEquals(Arrays.asList("--gui", "--project", p.getPath()), + ImportDesignMojo.toolArguments(true, p, null, null, null, null, out)); + } + + @Test + void aFigmaLinkIsNotAFile() { + assertTrue(ImportDesignMojo.isFigmaLink("https://www.figma.com/design/AbC123/Shop?node-id=0-1")); + assertTrue(ImportDesignMojo.isFigmaLink("figma.com/file/AbC123/Shop")); + assertFalse(ImportDesignMojo.isFigmaLink("designs/figma.com/login.fig")); + assertFalse(ImportDesignMojo.isFigmaLink("/d.fig")); + } +} diff --git a/maven/core-unittests/src/test/java/com/codename1/art/ArtFormatsTest.java b/maven/core-unittests/src/test/java/com/codename1/art/ArtFormatsTest.java index 919e7fa4a26..00894ff0d94 100644 --- a/maven/core-unittests/src/test/java/com/codename1/art/ArtFormatsTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/art/ArtFormatsTest.java @@ -28,12 +28,17 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertSame; @@ -288,6 +293,34 @@ void figmaReadsFramesGeometryAndPaints() throws IOException { assertNotNull(find(d.getRoot(), "Rect")); } + private static String figmaGroupDoc(int childX, int childY) { + // A frame at (0,0) holding a group at (20,30) holding a 10x10 green square whose + // absolute box is (20,30). childX/childY is the square's relativeTransform offset. + return "{\"name\":\"F\",\"document\":{\"type\":\"DOCUMENT\",\"children\":[{\"type\":\"CANVAS\"," + + "\"name\":\"Page\",\"children\":[{\"type\":\"FRAME\",\"name\":\"Frame\",\"absoluteBoundingBox\":" + + "{\"x\":0,\"y\":0,\"width\":60,\"height\":60},\"size\":{\"x\":60,\"y\":60}," + + "\"relativeTransform\":[[1,0,0],[0,1,0]],\"children\":[{\"type\":\"GROUP\",\"name\":\"G\"," + + "\"absoluteBoundingBox\":{\"x\":20,\"y\":30,\"width\":10,\"height\":10}," + + "\"relativeTransform\":[[1,0,20],[0,1,30]],\"children\":[{\"type\":\"RECTANGLE\",\"name\":\"Sq\"," + + "\"absoluteBoundingBox\":{\"x\":20,\"y\":30,\"width\":10,\"height\":10}," + + "\"size\":{\"x\":10,\"y\":10},\"relativeTransform\":[[1,0," + childX + "],[0,1," + childY + "]]," + + "\"fills\":[{\"type\":\"SOLID\",\"color\":{\"r\":0,\"g\":1,\"b\":0,\"a\":1}}]," + + "\"fillGeometry\":[{\"path\":\"M0 0L10 0L10 10L0 10Z\",\"windingRule\":\"NONZERO\"}]}]}]}]}]}}"; + } + + @Test + void figmaGroupChildrenLandWhereTheirBoxesSay() throws IOException { + // Files place a group's children in the group's space (0,0) or in its parent's (20,30); + // either way the square is drawn at its absolute box. + int[][] offsets = {{0, 0}, {20, 30}}; + for (int[] o : offsets) { + ArtDocument d = FigmaReader.read(utf8(figmaGroupDoc(o[0], o[1])), new HashMap()); + Raster r = ArtRenderer.render(d, 1); + assertEquals(0x00ff00, rgb(r, 25, 35), "offset " + o[0] + "," + o[1]); + assertNotEquals(0x00ff00, rgb(r, 5, 5), "offset " + o[0] + "," + o[1]); + } + } + @Test void detectionRejectsUnknownAndOldSketch() { assertThrows(IOException.class, () -> ArtFormats.read(utf8("SQLite format 3\u0000...."))); @@ -404,6 +437,152 @@ void psdPatternLibraryIsDecoded() throws IOException { near(0x008000, rgb(r, 3, 0)); } + private static String sketchBox(String id, String name, int x, int y, int w, int h, int rc, String rgb) { + return sketchRect(x, y, w, h, -1).replace("{\"_class\":\"rectangle\",", "{\"_class\":\"rectangle\"," + + "\"do_objectID\":\"" + id + "\",\"name\":\"" + name + "\",\"resizingConstraint\":" + rc + ",") + .replace("]}", "],\"style\":{\"fills\":[{\"isEnabled\":true,\"fillType\":0,\"color\":" + rgb + "}]}}"); + } + + private static String sketchText(String id, int x, int y, int w, String s) { + return "{\"_class\":\"text\",\"do_objectID\":\"" + id + "\",\"name\":\"Text\",\"isVisible\":true," + + "\"resizingConstraint\":9,\"textBehaviour\":0,\"frame\":{\"x\":" + x + ",\"y\":" + y + + ",\"width\":" + w + ",\"height\":19},\"attributedString\":{\"string\":\"" + s + "\",\"attributes\":" + + "[{\"location\":0,\"length\":" + s.length() + ",\"attributes\":{\"MSAttributedStringFontAttribute\":" + + "{\"attributes\":{\"name\":\"Helvetica\",\"size\":16}}}}]}}"; + } + + private static String sketchMaster(String symbolId, int w, int h, String layers) { + return "{\"_class\":\"symbolMaster\",\"symbolID\":\"" + symbolId + "\",\"name\":\"M" + symbolId + "\"," + + "\"resizesContent\":true,\"frame\":{\"x\":0,\"y\":1000,\"width\":" + w + ",\"height\":" + h + "}," + + "\"layers\":[" + layers + "]}"; + } + + private static String sketchInstance(String name, String symbolId, int x, int y, int w, int h, String overrides) { + return "{\"_class\":\"symbolInstance\",\"name\":\"" + name + "\",\"symbolID\":\"" + symbolId + "\"," + + "\"isVisible\":true,\"frame\":{\"x\":" + x + ",\"y\":" + y + ",\"width\":" + w + ",\"height\":" + h + + "},\"overrideValues\":[" + overrides + "]}"; + } + + private static String sketchOverride(String name, String value) { + return "{\"_class\":\"overrideValue\",\"overrideName\":\"" + name + "\",\"value\":\"" + value + "\"}"; + } + + private static ArtDocument sketchDoc(int w, int h, String layers) throws IOException { + String page = "{\"_class\":\"page\",\"name\":\"P\",\"frame\":{\"x\":0,\"y\":0,\"width\":" + w + ",\"height\":" + h + + "},\"layers\":[" + layers + "]}"; + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ZipOutputStream z = new ZipOutputStream(bo); + z.putNextEntry(new ZipEntry("document.json")); + z.write(utf8("{\"_class\":\"document\",\"pages\":[{\"_ref\":\"pages/P1\"}]}")); + z.putNextEntry(new ZipEntry("pages/P1.json")); + z.write(utf8(page)); + z.putNextEntry(new ZipEntry("meta.json")); + z.write(utf8("{\"version\":136}")); + z.close(); + return ArtFormats.read(bo.toByteArray()); + } + + private static List pathTo(ArtNode n, String id) { + if (id.equals(n.getId())) { + List l = new ArrayList(); + l.add(n); + return l; + } + if (n instanceof GroupNode) { + for (ArtNode c : ((GroupNode) n).getChildren()) { + List l = pathTo(c, id); + if (l != null) { + l.add(0, n); + return l; + } + } + } + return null; + } + + private static void texts(ArtNode n, List out) { + if (n instanceof TextNode) { + out.add(((TextNode) n).getRuns().get(0).getText()); + } else if (n instanceof GroupNode) { + for (ArtNode c : ((GroupNode) n).getChildren()) { + texts(c, out); + } + } + } + + private static final String RED = "{\"red\":1,\"green\":0,\"blue\":0,\"alpha\":1}"; + private static final String BLUE = "{\"red\":0,\"green\":0,\"blue\":1,\"alpha\":1}"; + private static final String GREEN = "{\"red\":0,\"green\":1,\"blue\":0,\"alpha\":1}"; + + @Test + void sketchCentredLabelStaysCentredWithALongerOverride() throws IOException { + // A button master with its label centred; an instance of the same size says more. The + // label grows both ways from the middle, not out of the button's right side. + String button = sketchMaster("BTN", 300, 50, sketchBox("BG", "Background", 0, 0, 300, 50, 63, RED) + "," + + sketchText("LBL", 100, 16, 100, "Button Text")); + ArtDocument d = sketchDoc(300, 50, button + "," + sketchInstance("Raise", "BTN", 0, 0, 300, 50, + sketchOverride("LBL_stringValue", "Raise your account to the top"))); + List path = pathTo(find(d.getRoot(), "Raise"), "LBL"); + assertNotNull(path); + TextNode t = (TextNode) path.get(path.size() - 1); + assertEquals(TextNode.ALIGN_CENTER, t.getAlign()); + assertEquals(300, t.getBoxWidth(), 0.001); + } + + @Test + void sketchInstanceIsLaidOutByConstraintsNotScaled() throws IOException { + // A chat bubble: a 136 wide master whose background stretches (63), a text that fits its + // string (pinned top left, 9) and a time beside it. The instance is 270 wide because the + // message is longer: the background stretches, the text keeps its 16px, the time moves. + String bubble = sketchMaster("BUBBLE", 136, 33, sketchBox("BG", "Background", 0, 0, 136, 33, 63, RED) + "," + + sketchText("TXT", 10, 7, 94, "Message Text") + "," + sketchBox("TIME", "Time", 111, 14, 20, 12, 9, BLUE)); + ArtDocument d = sketchDoc(300, 40, bubble + "," + sketchInstance("Message", "BUBBLE", 0, 0, 270, 33, + sketchOverride("TXT_stringValue", "Everything is great, how are you?"))); + Raster r = ArtRenderer.render(d, 1); + assertEquals(0x0000ff, rgb(r, 263, 25), "the time follows the longer message"); + assertEquals(0xff0000, rgb(r, 262, 4), "the background stretches to the instance"); + List path = pathTo(find(d.getRoot(), "Message"), "TXT"); + assertNotNull(path); + TextNode t = (TextNode) path.get(path.size() - 1); + assertEquals("Everything is great, how are you?", t.getRuns().get(0).getText()); + assertEquals(16, t.getRuns().get(0).getSize(), 0.001); + double sx = 1; + for (ArtNode n : path) { + sx *= n.getTransform().getA(); + } + assertEquals(1, sx, 0.001, "the text is not stretched"); + } + + @Test + void sketchSwappedSymbolFillsTheSlotItWasSwappedInto() throws IOException { + // An emoji master is 160x160; the bubble's slot for it is 16x16. + String emoji = sketchMaster("EMOJI", 160, 160, sketchBox("FACE", "Face", 0, 0, 160, 160, 63, GREEN)); + String dot = sketchMaster("DOT", 16, 16, sketchBox("D", "Dot", 0, 0, 16, 16, 63, BLUE)); + String holder = sketchMaster("HOLDER", 40, 40, sketchInstance("Slot", "DOT", 10, 10, 16, 16, "").replace( + "\"_class\":\"symbolInstance\",", "\"_class\":\"symbolInstance\",\"do_objectID\":\"SLOT\",")); + ArtDocument d = sketchDoc(100, 100, emoji + "," + dot + "," + holder + "," + + sketchInstance("H", "HOLDER", 0, 0, 40, 40, sketchOverride("SLOT_symbolID", "EMOJI"))); + Raster r = ArtRenderer.render(d, 1); + assertEquals(0x00ff00, rgb(r, 18, 18), "the swapped symbol is drawn in the slot"); + assertTrue((rgb(r, 32, 32) & 0x00ff00) != 0x00ff00, "and only in the slot"); + } + + @Test + void sketchNestedOverridesReachEachInstanceOfOneMaster() throws IOException { + // Two keys of one master inside a keyboard: each key's own override names its letter. + String key = sketchMaster("KEY", 30, 30, sketchText("LETTER", 5, 5, 20, "A")); + String board = sketchMaster("BOARD", 60, 30, + sketchInstance("Q", "KEY", 0, 0, 30, 30, "").replace("\"_class\":\"symbolInstance\",", + "\"_class\":\"symbolInstance\",\"do_objectID\":\"KQ\",") + + "," + sketchInstance("W", "KEY", 30, 0, 30, 30, "").replace("\"_class\":\"symbolInstance\",", + "\"_class\":\"symbolInstance\",\"do_objectID\":\"KW\",")); + ArtDocument d = sketchDoc(100, 100, key + "," + board + "," + sketchInstance("Board", "BOARD", 0, 50, 60, 30, + sketchOverride("KQ/LETTER_stringValue", "Q") + "," + sketchOverride("KW/LETTER_stringValue", "W"))); + List letters = new ArrayList(); + texts(find(d.getRoot(), "Board"), letters); + assertEquals(Arrays.asList("Q", "W"), letters); + } + private static String sketchShapeGroup(int op) { return "{\"_class\":\"shapeGroup\",\"name\":\"SG\",\"isVisible\":true," + "\"frame\":{\"x\":0,\"y\":0,\"width\":40,\"height\":20}," @@ -423,8 +602,12 @@ private static String sketchRect(int x, int y, int w, int h, int op) { } private static Raster sketchBoolean(int op) throws IOException { + return sketchPage(sketchShapeGroup(op)); + } + + private static Raster sketchPage(String layers) throws IOException { String page = "{\"_class\":\"page\",\"name\":\"P\",\"frame\":{\"x\":0,\"y\":0,\"width\":40,\"height\":20}," - + "\"layers\":[" + sketchShapeGroup(op) + "]}"; + + "\"layers\":[" + layers + "]}"; ByteArrayOutputStream bo = new ByteArrayOutputStream(); ZipOutputStream z = new ZipOutputStream(bo); z.putNextEntry(new ZipEntry("document.json")); @@ -437,6 +620,36 @@ private static Raster sketchBoolean(int op) throws IOException { return ArtRenderer.render(ArtFormats.read(bo.toByteArray()), 1); } + @Test + void sketchOutlineMaskWithNoFillStillClips() throws IOException { + // An outline mask (clippingMaskMode 0) with no fills, over the left half: Sketch clips to + // its shape whatever its style. Read as an alpha mask it hid the red layer entirely. + String mask = sketchRect(0, 0, 20, 20, -1).replace("{\"_class\":\"rectangle\",", + "{\"_class\":\"rectangle\",\"hasClippingMask\":true,\"clippingMaskMode\":0,\"style\":{\"fills\":[]},"); + String red = sketchShapeGroup(-1); + Raster r = sketchPage(mask + "," + red); + assertEquals(0xffff0000, r.get(5, 10)); + assertEquals(0, r.get(30, 10) >>> 24); + } + + @Test + void layoutAttributesSurviveCopyAndNativeFormat() throws IOException { + GroupNode g = new GroupNode(); + g.setAttribute("layoutMode", "VERTICAL"); + g.setAttribute("itemSpacing", "8"); + assertEquals("VERTICAL", g.copy().getAttribute("layoutMode")); + g.setAttribute("itemSpacing", null); + assertNull(g.getAttribute("itemSpacing")); + ArtDocument d = new ArtDocument(10, 10); + d.getRoot().getChildren().add(g); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + NativeFormat.write(d, out); + ArtDocument back = ArtFormats.read(out.toByteArray()); + ArtNode first = back.getRoot().getChildren().get(0); + assertEquals("VERTICAL", first.getAttribute("layoutMode")); + assertEquals(1, first.getAttributes().size()); + } + @Test void sketchBooleanOperationsKeepTheirRegion() throws IOException { // Rectangles 0..30 and 10..40: probe the left only, the overlap and the right only. diff --git a/maven/core-unittests/src/test/java/com/codename1/art/FigmaClientRetryTest.java b/maven/core-unittests/src/test/java/com/codename1/art/FigmaClientRetryTest.java new file mode 100644 index 00000000000..e12d9f7b037 --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/art/FigmaClientRetryTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.art; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class FigmaClientRetryTest { + + @Test + void aRefusalSaysHowLongFigmaAsksToWait() { + // 398598 seconds is what a Starter-plan token was told after a few whole-file reads. + assertEquals("Figma asks to wait 4 days", FigmaClient.retryAfter("398598")); + assertEquals("Figma asks to wait 30 seconds", FigmaClient.retryAfter("30")); + assertEquals("Figma asks to wait 10 minutes", FigmaClient.retryAfter("600")); + assertEquals("Figma asks to wait 5 hours", FigmaClient.retryAfter("18000")); + assertEquals("try again later", FigmaClient.retryAfter(null)); + assertEquals("try again later", FigmaClient.retryAfter("Wed, 21 Oct 2015 07:28:00 GMT")); + } +} diff --git a/maven/core-unittests/src/test/java/com/codename1/components/CoachMarksTest.java b/maven/core-unittests/src/test/java/com/codename1/components/CoachMarksTest.java index 830900cd081..74fb514ac11 100644 --- a/maven/core-unittests/src/test/java/com/codename1/components/CoachMarksTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/components/CoachMarksTest.java @@ -66,6 +66,73 @@ void stepsAdvanceAndFinish() { assertEquals(1, clicked[0], "the form gets touches back once the tour ends"); } + @FormTest + void aTourStartedByAButtonStartsAtItsFirstStep() { + Form f = new Form(BoxLayout.y()); + Button help = new Button("Help"); + Button b = new Button("B"); + f.add(help).add(b); + f.show(); + final CoachMarks tour = new CoachMarks(f).add(help, "A", "First").add(b, null, "Second"); + help.addActionListener(e -> tour.show()); + int x = help.getAbsoluteX() + help.getWidth() / 2; + int y = help.getAbsoluteY() + help.getHeight() / 2; + f.pointerPressed(x, y); + f.pointerReleased(x, y); + assertTrue(tour.isShowing()); + assertEquals(0, tour.getCurrentStep(), "the release that started the tour is not a tap on it"); + f.pointerPressed(5, f.getHeight() - 5); + f.pointerReleased(5, f.getHeight() - 5); + assertEquals(1, tour.getCurrentStep()); + } + + @FormTest + void aLongTextOnAWideFormKeepsItsButtons() { + Form f = new Form(BoxLayout.y()); + f.setWidth(1400); + f.setHeight(900); + Button a = new Button("A"); + f.add(a); + f.show(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 1; i++) { + sb.append("A sentence that has to wrap inside the bubble. "); + } + CoachMarks tour = new CoachMarks(f).add(a, "Title", sb.toString()).add(a, null, "Second"); + tour.show(); + f.revalidate(); + com.codename1.ui.Container pane = f.getFormLayeredPane(CoachMarks.class, false); + com.codename1.ui.Container overlay = (com.codename1.ui.Container) pane.getComponentAt(0); + overlay.layoutContainer(); + Button next = find(overlay, "Next"); + assertNotNull(next); + assertTrue(next.getHeight() > 0, "the Next button is cut off"); + com.codename1.ui.Container bubble = next.getParent(); + while (bubble.getParent() != overlay) { + bubble = bubble.getParent(); + } + assertTrue(next.getAbsoluteY() + next.getHeight() <= bubble.getAbsoluteY() + bubble.getHeight(), + "the Next button lies inside the bubble: next " + next.getAbsoluteY() + "+" + next.getHeight() + + " bubble " + bubble.getAbsoluteY() + "+" + bubble.getHeight() + " w " + bubble.getWidth() + + " pref " + bubble.getPreferredH() + " overlay " + overlay.getHeight()); + } + + private static Button find(com.codename1.ui.Container c, String text) { + for (int i = 0; i < c.getComponentCount(); i++) { + com.codename1.ui.Component k = c.getComponentAt(i); + if (k instanceof Button && text.equals(((Button) k).getText())) { + return (Button) k; + } + if (k instanceof com.codename1.ui.Container) { + Button b = find((com.codename1.ui.Container) k, text); + if (b != null) { + return b; + } + } + } + return null; + } + @FormTest void anAreaStepLightsOnlyThatPartOfTheTarget() { Form f = new Form(BoxLayout.y()); diff --git a/maven/design-import/pom.xml b/maven/design-import/pom.xml new file mode 100644 index 00000000000..c8c834ea064 --- /dev/null +++ b/maven/design-import/pom.xml @@ -0,0 +1,87 @@ + + + + + com.codenameone + codenameone + 8.0-SNAPSHOT + + 4.0.0 + com.codenameone + codenameone-design-import + 8.0-SNAPSHOT + jar + codenameone-design-import + + + UTF-8 + 1.8 + 1.8 + + + + + + + com.codenameone + codenameone-core + + + com.codenameone + codenameone-javase + ${project.version} + + + org.junit.jupiter + junit-jupiter + test + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.7.3.4 + + Max + Low + false + true + ${project.build.directory} + ${project.basedir}/spotbugs-exclude.xml + + + + spotbugs + verify + + spotbugs + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + -Djava.awt.headless=true ${designimport.argLine} + + + + + diff --git a/maven/design-import/spotbugs-exclude.xml b/maven/design-import/spotbugs-exclude.xml new file mode 100644 index 00000000000..2f81b5a3c83 --- /dev/null +++ b/maven/design-import/spotbugs-exclude.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/maven/design-import/src/main/java/com/codename1/designimport/Assets.java b/maven/design-import/src/main/java/com/codename1/designimport/Assets.java new file mode 100644 index 00000000000..76e2c83745d --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/Assets.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtDocument; +import com.codename1.art.ArtNode; +import com.codename1.art.ArtRenderer; +import com.codename1.art.GroupNode; +import com.codename1.art.Matrix; +import com.codename1.art.Raster; +import com.codename1.ui.Image; +import java.util.LinkedHashMap; +import java.util.Map; + +/// Renders the layers the form shows as pictures -- photos, icons, shapes that are not +/// rectangles -- each on its own, without whatever lies under it in the design. +final class Assets { + /// Assets are rendered at this many pixels per dp, crisp on a 3x screen. + static final double PIXELS_PER_DP = 3; + private final ImportSession session; + final Map images = new LinkedHashMap(); + private int counter; + + Assets(ImportSession session) { + this.session = session; + } + + void run(ImportSession.Variant v, String stem) { + visit(v.root, v, stem); + } + + private void visit(DNode n, ImportSession.Variant v, String stem) { + boolean picture = n.rasterize || n.imageBackground || n.role == DNode.Role.ICON || n.role == DNode.Role.IMAGE; + if (picture && n.source != null && n.parentToDoc != null) { + Image img = render(n, v); + if (img != null) { + String base = Text.lower(stem) + "_" + (n.fieldName != null ? Text.lower(n.fieldName) : "image" + counter); + counter++; + String name = base + ".png"; + int k = 2; + while (images.containsKey(name)) { + name = base + "_" + k++ + ".png"; + } + n.imageName = name; + images.put(name, img); + } + } + if (!n.rasterize) { + for (int i = 0; i < n.children.size(); i++) { + visit(n.children.get(i), v, stem); + } + } + } + + /// The layer alone, cropped to its box, at [#PIXELS_PER_DP]. + private Image render(DNode n, ImportSession.Variant v) { + double s = PIXELS_PER_DP / session.getEffectiveScale(); + int w = (int) Math.max(1, Math.ceil(n.w * s)); + int h = (int) Math.max(1, Math.ceil(n.h * s)); + if ((long) w * h > 16L * 1024 * 1024) { + return null; + } + ArtNode copy = n.source.copy(); + Matrix place = Matrix.scale(s, s).multiply(Matrix.translate(-(n.x + v.originX), -(n.y + v.originY))) + .multiply(n.parentToDoc).multiply(n.source.getTransform()); + copy.setTransform(place); + ArtDocument doc = new ArtDocument(w, h); + GroupNode root = new GroupNode(); + root.add(copy); + doc.setRoot(root); + try { + Raster r = new ArtRenderer().render(doc, Matrix.IDENTITY, new int[]{0, 0, w, h}); + return Image.createImage(r.getPixels(), r.getWidth(), r.getHeight()); + } catch (RuntimeException ex) { + session.issue("style", Issue.Severity.WARNING, n, "render-failed", + "\"" + n.name + "\" could not be rendered: " + ex.getMessage(), null); + return null; + } + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/ClassifyStage.java b/maven/design-import/src/main/java/com/codename1/designimport/ClassifyStage.java new file mode 100644 index 00000000000..a423de60953 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/ClassifyStage.java @@ -0,0 +1,529 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import java.util.List; + +/// Stage 2: gives every node a role -- button, text field, label, icon, card, list, toolbar -- +/// with a confidence and a reason. +/// +/// Names win when the designer gave them ("Sign in button", a Figma component called +/// "Input/Default"); otherwise the role is read from shape: a filled rounded box holding one +/// centred line of text is a button; a stroked box holding one grey left-aligned line is a +/// text field; three or more siblings with the same structure are a list. A role below the +/// session's confidence threshold becomes a TODO, so a person or an LLM confirms it. +final class ClassifyStage { + static final String STAGE = "classify"; + private final ImportSession session; + + ClassifyStage(ImportSession session) { + this.session = session; + } + + void run(DNode root) { + visit(root, root, 0); + bars(root); + } + + private void visit(DNode n, DNode root, int depth) { + for (int i = 0; i < n.children.size(); i++) { + visit(n.children.get(i), root, depth + 1); + } + if (n != root) { // NOPMD CompareObjectsWithEquals - identity + classify(n); + } + lists(n); + ImportSession.Override o = session.overrides.get(n.id); + if (o != null && o.role != null) { + n.role = o.role; + n.confidence = 1; + n.reason = "set by override"; + n.roleLocked = true; + } + if (o != null && o.rasterize != null) { + n.rasterize = o.rasterize.booleanValue(); + } + if (!n.roleLocked && n != root && n.confidence < session.confidenceThreshold) { // NOPMD CompareObjectsWithEquals + session.issue(STAGE, Issue.Severity.TODO, n, "low-confidence-role", + "\"" + n.name + "\" was classified as " + Text.lower(n.role.name()) + " with " + + Math.round(n.confidence * 100) + "% confidence (" + n.reason + ").", + "Confirm or change it with designimport_set (role)."); + } + } + + static boolean namedForItsText(DNode n) { + if (n.text == null || n.name == null) { + return false; + } + String name = Text.lower(n.name.trim()); + return name.length() > 0 && Text.lower(n.text.trim()).startsWith(name); + } + + private static final String[] BUTTON = {"button", "btn", "cta", "action"}; + private static final String[] FIELD = {"input", "field", "textfield", "text field", "search", "textbox", "edit"}; + private static final String[] ICON = {"icon", "ic_", "ic-", "glyph", "chevron", "arrow", "close"}; + private static final String[] IMAGE = {"image", "img", "photo", "picture", "avatar", "thumbnail", "hero", "cover", "logo"}; + private static final String[] DIVIDER = {"divider", "separator", "rule", "hairline"}; + private static final String[] SWITCH = {"switch", "toggle"}; + private static final String[] RADIO = {"radio", "radiobutton", "radio button"}; + private static final String[] CHECK = {"checkbox", "check box", "tickbox", "radio", "radiobutton", "radio button"}; + private static final String[] TOOLBAR = {"toolbar", "app bar", "appbar", "navbar", "nav bar", "navigation bar", "header", "title bar"}; + private static final String[] TABS = {"tab bar", "tabbar", "bottom nav", "bottomnav", "tabs", "bottom bar"}; + private static final String[] CARD = {"card", "tile", "panel", "sheet"}; + private static final String[] LIST = {"list", "feed", "table"}; + + void classify(DNode n) { + if (n.roleLocked) { + return; + } + String name = Text.lower(n.name); + // Sketch and Figma name a text layer after what it says: "Inner box button" is a label + // that reads so, not a layer someone named a button. + boolean generic = Text.isGenericName(n.name) || namedForItsText(n); + int texts = 0; + DNode onlyText = null; + int icons = 0; + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if (c.role == DNode.Role.LABEL) { + texts++; + onlyText = c; + } else if (c.role == DNode.Role.ICON || c.role == DNode.Role.IMAGE) { + icons++; + } + } + // Names first. + if (!generic) { + // Before buttons: "RadioButton" is a radio button, not a button. + if (Text.hasWord(name, SWITCH)) { + set(n, DNode.Role.SWITCH, 0.9, "named \"" + n.name + "\""); + return; + } + if (Text.hasWord(name, CHECK)) { + set(n, DNode.Role.CHECKBOX, 0.9, "named \"" + n.name + "\""); + n.radio = Text.hasWord(name, RADIO); + return; + } + if (n.text == null && Text.hasWord(name, FIELD) && n.h <= 72 && !holdsControl(n) + && !holds(n, DNode.Role.TEXT_FIELD)) { + set(n, DNode.Role.TEXT_FIELD, 0.9, "named \"" + n.name + "\""); + return; + } + // "Buttons" holding a button and a link under it is a group of controls, not one. + if (Text.hasWord(name, BUTTON) && n.h <= 96 && textsIn(n) <= 1) { + set(n, DNode.Role.BUTTON, 0.9, "named \"" + n.name + "\""); + return; + } + if (Text.hasWord(name, DIVIDER) && Math.min(n.w, n.h) <= 3) { + set(n, DNode.Role.DIVIDER, 0.95, "named \"" + n.name + "\""); + return; + } + // "Label + Icon" holds its caption: a picture of it would print the text twice. + if (n.text == null && textsIn(n) == 0 && Text.hasWord(name, ICON) && n.w <= 64 && n.h <= 64) { + set(n, DNode.Role.ICON, 0.9, "named \"" + n.name + "\""); + n.rasterize = true; + return; + } + if (n.text == null && n.children.isEmpty() && Text.hasWord(name, IMAGE)) { + set(n, DNode.Role.IMAGE, 0.9, "named \"" + n.name + "\""); + n.rasterize = true; + return; + } + if (Text.hasWord(name, TABS) && !n.children.isEmpty()) { + set(n, DNode.Role.TABS, 0.85, "named \"" + n.name + "\""); + return; + } + if (Text.hasWord(name, TOOLBAR) && !n.children.isEmpty()) { + set(n, DNode.Role.TOOLBAR, 0.85, "named \"" + n.name + "\""); + return; + } + if (Text.hasWord(name, CARD) && !n.children.isEmpty()) { + set(n, DNode.Role.CARD, 0.85, "named \"" + n.name + "\""); + return; + } + } + // Then geometry. + if (n.text != null) { + set(n, DNode.Role.LABEL, 0.95, "a text layer"); + return; + } + if (n.children.isEmpty()) { + double thin = Math.min(n.w, n.h); + double longSide = Math.max(n.w, n.h); + if (thin <= 2.5 && longSide >= 24) { + set(n, DNode.Role.DIVIDER, 0.9, "a hairline " + Text.num(longSide) + "px long"); + return; + } + // A heart or a ring is outlined too; only a rectangle is a check box's box. + if (!n.rasterize && outlinedSquare(n)) { + set(n, DNode.Role.CHECKBOX, 0.6, "a small outlined square"); + n.rasterize = false; + return; + } + if (n.rasterize && n.w <= 48 && n.h <= 48 && ratio(n) <= 1.5) { + set(n, DNode.Role.ICON, 0.75, "a small square picture"); + return; + } + if (n.rasterize) { + set(n, DNode.Role.IMAGE, 0.85, "a picture"); + return; + } + if (n.w <= 40 && n.h <= 40 && ratio(n) <= 1.5) { + n.rasterize = true; + set(n, DNode.Role.ICON, 0.6, "a small square shape"); + return; + } + if (n.borderColor != null && n.w >= 140 && n.h >= 24 && n.h <= 60 + && (n.background == null || isLight(n.background.intValue()))) { + set(n, DNode.Role.TEXT_FIELD, 0.5, "an empty outlined box the height of an input"); + return; + } + if (n.background == null && n.borderColor == null) { + set(n, DNode.Role.SPACER, 0.7, "an empty layer"); + return; + } + // A plain decorative shape. + set(n, DNode.Role.CONTAINER, 0.5, "a plain shape with nothing in it"); + return; + } + double r = n.w / Math.max(1, n.h); + // An outlined square beside one line: a check box with its label. + if (n.children.size() == 2 && texts == 1 && outlinedSquare(n.children.get(0)) + && n.children.get(1).text != null && n.children.get(1).x >= n.children.get(0).right() - 1) { + set(n, DNode.Role.CHECKBOX, 0.8, "an outlined square beside a line"); + return; + } + // A pill holding a knob: a switch. + if (n.children.size() == 1 && texts == 0 && r >= 1.5 && r <= 2.4 && n.h <= 40 && n.radius >= n.h * 0.35) { + set(n, DNode.Role.SWITCH, 0.7, "a pill with a knob"); + return; + } + if (texts == 0 && n.children.size() <= 1 && n.w <= 30 && n.h <= 30 && ratio(n) <= 1.2 && n.borderColor != null) { + set(n, DNode.Role.CHECKBOX, 0.6, "a small outlined square"); + return; + } + if (texts == 1 && n.children.size() <= 3 && icons == n.children.size() - 1 && n.h >= 24 && n.h <= 72 + && (n.background != null || n.borderColor != null)) { + boolean centred = Math.abs((onlyText.x + onlyText.w / 2) - (n.x + n.w / 2)) <= Math.max(3, n.w * 0.06) + || onlyText.textAlign == 0; + boolean placeholderGrey = onlyText.foreground != null && isGrey(onlyText.foreground.intValue()); + boolean strongFill = n.background != null && saturation(n.background.intValue()) > 0.25 && n.backgroundAlpha > 0.5; + boolean wide = n.w >= 140; + if (!centred && wide && (n.borderColor != null || placeholderGrey) && !strongFill) { + set(n, DNode.Role.TEXT_FIELD, placeholderGrey ? 0.75 : 0.6, + "a box holding one left-aligned " + (placeholderGrey ? "grey " : "") + "line"); + return; + } + if (centred || strongFill) { + set(n, DNode.Role.BUTTON, strongFill && centred ? 0.85 : 0.65, + (strongFill ? "a filled box" : "a box") + " holding one " + (centred ? "centred " : "") + "line"); + return; + } + } + // A tall box with one grey line at its top left: a multi-line field ("Describe your + // experience?"), which keeps the height the design gives it. + if (texts == 1 && n.children.size() == 1 && onlyText != null && n.h > 72 && n.w >= 140 + && (n.background != null || n.borderColor != null) && onlyText.foreground != null + && isGrey(onlyText.foreground.intValue()) && onlyText.y - n.y <= 32 && onlyText.x - n.x <= 32 + && !(n.background != null && saturation(n.background.intValue()) > 0.25 && n.backgroundAlpha > 0.5)) { + set(n, DNode.Role.TEXT_FIELD, 0.7, "a tall box holding one grey line at its top left"); + n.multiline = true; + return; + } + if (texts == 1 && n.children.size() == 1 && n.h > 72 && n.background != null && n.backgroundAlpha > 0.5 + && saturation(n.background.intValue()) > 0.25 && onlyText != null + && Math.abs((onlyText.x + onlyText.w / 2) - (n.x + n.w / 2)) <= Math.max(3, n.w * 0.06) + && Math.abs((onlyText.y + onlyText.h / 2) - (n.y + n.h / 2)) <= Math.max(3, n.h * 0.06)) { + // A layout stretched it, but a coloured box with one line dead in its centre is + // still a button. + set(n, DNode.Role.BUTTON, 0.6, "a filled box holding one centred line, stretched"); + return; + } + if (isIllustration(n, texts)) { + // Pieces drawn over each other with no text among them: one picture, which a + // layout of components would only take apart. + n.rasterize = true; + boolean small = n.w <= 48 && n.h <= 48 && ratio(n) <= 1.5; + set(n, small ? DNode.Role.ICON : DNode.Role.IMAGE, 0.7, + "overlapping shapes with no text: " + (small ? "an icon" : "an illustration")); + return; + } + if ((n.background != null || n.borderColor != null || n.shadow) && n.children.size() >= 2 && !n.imageBackground) { + set(n, DNode.Role.CARD, n.shadow || n.radius > 0 ? 0.75 : 0.6, "a styled box holding several items"); + return; + } + set(n, DNode.Role.CONTAINER, 0.8, "a group of " + n.children.size() + " items"); + } + + /// True for a group with no text whose every leaf is a picture or a bare shape. + static boolean onlyDrawing(DNode n) { + if (n.text != null || n.roleLocked && n.role != DNode.Role.ICON && n.role != DNode.Role.IMAGE) { + return false; + } + if (n.children.isEmpty()) { + return n.rasterize || n.role == DNode.Role.ICON || n.role == DNode.Role.IMAGE + || n.role == DNode.Role.CONTAINER || n.role == DNode.Role.SPACER; + } + if (n.role == DNode.Role.SWITCH || n.role == DNode.Role.CHECKBOX || n.role == DNode.Role.BUTTON + || n.role == DNode.Role.TEXT_FIELD) { + return false; + } + for (int i = 0; i < n.children.size(); i++) { + if (!onlyDrawing(n.children.get(i))) { + return false; + } + } + return true; + } + + /// Every child a picture or a bare shape, at least two of them overlapping, and no text + /// anywhere inside. A row of separate icons does not overlap and stays a row. + static boolean isIllustration(DNode n, int texts) { + if (texts > 0 || n.children.isEmpty() || n.allText().length() > 0) { + return false; + } + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + boolean picture = c.role == DNode.Role.ICON || c.role == DNode.Role.IMAGE || c.rasterize; + boolean bare = c.children.isEmpty() && (c.role == DNode.Role.CONTAINER || c.role == DNode.Role.SPACER + || c.role == DNode.Role.DIVIDER || c.role == DNode.Role.CHECKBOX); + // A group that is itself only drawing (an eye inside a speech bubble) is a piece + // of the same picture; taking it apart drew the pieces out of place. + if (!picture && !bare && !onlyDrawing(c)) { + return false; + } + } + if (n.imageBackground) { + // Drawn over its own picture. + return true; + } + if (n.children.size() == 1) { + // A wrapper that paints under or around its one picture (a tinted backdrop, a + // frame) is one picture with it. A bare group around a picture is left alone: + // flattening it gains nothing and loses the picture's own bounds. + DNode only = n.children.get(0); + boolean paints = n.background != null && n.backgroundAlpha > 0 || n.borderColor != null + || n.gradientTo != null || n.shadow; + // ... and only when it shows: a picture filling its wrapper hides what it paints. + paints = paints && (only.w < n.w * 0.95 || only.h < n.h * 0.95); + return paints && (only.rasterize || only.role == DNode.Role.ICON || only.role == DNode.Role.IMAGE); + } + for (int i = 0; i < n.children.size(); i++) { + DNode a = n.children.get(i); + for (int j = i + 1; j < n.children.size(); j++) { + DNode b = n.children.get(j); + double ix = Math.min(a.right(), b.right()) - Math.max(a.x, b.x); + double iy = Math.min(a.bottom(), b.bottom()) - Math.max(a.y, b.y); + if (ix > 1 && iy > 1) { + return true; + } + } + } + return false; + } + + private static boolean isLight(int rgb) { + int r = (rgb >> 16) & 0xff; + int g = (rgb >> 8) & 0xff; + int b = rgb & 0xff; + return r + g + b >= 600; + } + + /// A small square with an outline and no fill: a check box's box. + static boolean outlinedSquare(DNode n) { + return n.children.isEmpty() && n.text == null && n.borderColor != null + && (n.background == null || n.backgroundAlpha < 0.1) && n.w <= 30 && n.h <= 30 && n.w >= 8 && ratio(n) <= 1.2 + // A ring is a radio button's or an icon's, never a check box's square. + && n.radius < Math.min(n.w, n.h) / 3; + } + + /// Three or more consecutive siblings with the same shape are the items of a list. + private void lists(DNode n) { + List ch = n.children; + if (ch.size() < 3 || n.layout == DNode.Layout.GRID || n.layout == DNode.Layout.BOX_X) { + return; + } + String sig = signature(ch.get(0)); + int same = 0; + for (int i = 0; i < ch.size(); i++) { + if (signature(ch.get(i)).equals(sig) && !ch.get(i).children.isEmpty() + && Math.abs(ch.get(i).h - ch.get(0).h) <= Math.max(4, ch.get(0).h * 0.3)) { + same++; + } + } + if (same >= 3 && same >= ch.size() - 1) { + if (!n.roleLocked && (n.role == DNode.Role.CONTAINER || n.role == DNode.Role.SCREEN || n.role == DNode.Role.CARD)) { + if (n.role != DNode.Role.SCREEN) { + set(n, DNode.Role.LIST, 0.75, same + " items with the same structure"); + } + } + for (int i = 0; i < ch.size(); i++) { + DNode c = ch.get(i); + if (!c.roleLocked && signature(c).equals(sig) + && (c.role == DNode.Role.CONTAINER || c.role == DNode.Role.CARD)) { + c.role = DNode.Role.LIST_ITEM; + c.confidence = 0.8; + c.reason = "one of " + same + " repeated items"; + } + } + } + } + + /// The roles of a node's children in order: two list rows share it. + static String signature(DNode d) { + StringBuilder sb = new StringBuilder(); + sb.append(d.children.size()).append(':'); + for (int i = 0; i < d.children.size(); i++) { + sb.append(d.children.get(i).role.ordinal()).append(','); + } + return sb.toString(); + } + + /// A full-width strip at the top holding a title is a toolbar; one at the bottom + /// holding three to five evenly spaced items is a tab bar. + private void bars(DNode scope) { + // A screen background drawn as one box holding everything: its children are the screen's. + DNode root = scope; + while (root.children.size() == 1 && root.children.get(0).w >= root.w * 0.98 + && root.children.get(0).h >= root.h * 0.98 && !root.children.get(0).children.isEmpty()) { + root = root.children.get(0); + } + List ch = root.children; + if (ch.isEmpty()) { + return; + } + DNode top = ch.get(0); + if (!top.roleLocked && top.role != DNode.Role.TOOLBAR && top.w >= root.w * 0.9 && top.y <= root.h * 0.12 + && top.h >= 40 && top.h <= Math.max(120, root.h * 0.13) && !top.children.isEmpty() + && top.allText().length() > 0 && ch.size() > 1 && top.role != DNode.Role.LIST) { + set(top, DNode.Role.TOOLBAR, 0.65, "a full-width strip at the top with a title"); + } + DNode bottom = ch.get(ch.size() - 1); + int items = bottom.children.size() == 1 ? bottom.children.get(0).children.size() : bottom.children.size(); + if (!bottom.roleLocked && bottom.role != DNode.Role.TABS && ch.size() > 1 && bottom.w >= root.w * 0.9 + && bottom.bottom() >= root.h * 0.95 && bottom.h >= 44 && bottom.h <= 120 && items >= 3 && items <= 5) { + set(bottom, DNode.Role.TABS, 0.7, items + " items in a full-width strip at the bottom"); + } + } + + private static void set(DNode n, DNode.Role role, double confidence, String reason) { + n.role = role; + n.confidence = confidence; + n.reason = reason; + if (role == DNode.Role.TABS || role == DNode.Role.TOOLBAR || role == DNode.Role.BUTTON + || role == DNode.Role.TEXT_FIELD) { + // A button whose fill is on a group inside it would otherwise lose the fill when it + // becomes one component. + absorbWrapper(n); + } + } + + private static int textsIn(DNode n) { + int k = n.text != null && n.text.trim().length() > 0 ? 1 : 0; + for (int i = 0; i < n.children.size(); i++) { + k += textsIn(n.children.get(i)); + } + return k; + } + + /// Whether a check box, a radio button or a switch is inside: a kit's "Input" symbol + /// reused for a payment choice is a row with a radio button, not a field to type in. + /// Whether a descendant has the role: a field symbol holding a caption and a field of its + /// own is a labelled field, a group, and the field inside is the field. + static boolean holds(DNode n, DNode.Role role) { + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if (c.role == role || holds(c, role)) { + return true; + } + } + return false; + } + + static boolean holdsControl(DNode n) { + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if (c.role == DNode.Role.CHECKBOX || c.role == DNode.Role.SWITCH || holdsControl(c)) { + return true; + } + } + return false; + } + + /// Kits draw a bar as a group holding one background group that holds the items. The + /// items are the bar's tabs and actions, so the bar takes the wrapper's look and its + /// children; left alone, the whole wrapper became one tab. + static void absorbWrapper(DNode n) { + while (n.children.size() == 1) { + DNode c = n.children.get(0); + if (c.children.isEmpty() || c.rasterize || c.imageBackground || c.text != null + || c.w < n.w * 0.95 || c.h < n.h * 0.9) { + return; + } + if (n.background == null && n.gradientTo == null) { + n.background = c.background; + n.backgroundAlpha = c.backgroundAlpha; + n.gradientTo = c.gradientTo; + } + if (n.borderColor == null) { + n.borderColor = c.borderColor; + n.borderWidth = c.borderWidth; + } + n.radius = Math.max(n.radius, c.radius); + n.shadow = n.shadow || c.shadow; + // The items were arranged inside the wrapper, so its arrangement is theirs. + n.layout = c.layout; + n.gap = c.gap; + n.columns = c.columns; + n.centerCross = c.centerCross; + for (int i = 0; i < 4; i++) { + n.padding[i] = c.padding[i] + (i == 0 ? c.y - n.y : i == 3 ? c.x - n.x : 0); + } + n.children.clear(); + n.children.addAll(c.children); + } + } + + private static double ratio(DNode n) { + return Math.max(n.w, n.h) / Math.max(1, Math.min(n.w, n.h)); + } + + static boolean isGrey(int rgb) { + int r = (rgb >> 16) & 0xff; + int g = (rgb >> 8) & 0xff; + int b = rgb & 0xff; + int max = Math.max(r, Math.max(g, b)); + int min = Math.min(r, Math.min(g, b)); + return max - min < 24 && max > 100 && max < 210; + } + + static double saturation(int rgb) { + int r = (rgb >> 16) & 0xff; + int g = (rgb >> 8) & 0xff; + int b = rgb & 0xff; + int max = Math.max(r, Math.max(g, b)); + int min = Math.min(r, Math.min(g, b)); + return max == 0 ? 0 : (max - min) / (double) max; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/CodeCard.java b/maven/design-import/src/main/java/com/codename1/designimport/CodeCard.java new file mode 100644 index 00000000000..05c52a3a153 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/CodeCard.java @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.Dialog; +import com.codename1.ui.FontImage; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.editor.LanguageDef; +import com.codename1.ui.editor.SyntaxHighlightResult; +import com.codename1.ui.editor.SyntaxToken; +import com.codename1.ui.editor.Tokenizer; +import com.codename1.ui.layouts.FlowLayout; + +/// What the selected element becomes in source: the Java lines that build it and the CSS +/// rule of its UIID, cut from the very files the import writes. The whole base class and +/// stylesheet are one click further, so nobody has to emit to see what a choice did. +final class CodeCard { + private CodeCard() { + } + + /// Fills `card` for node `n` (null for no selection) from the generated code. + static void fill(Container card, GeneratedCode code, DNode n) { + card.removeAll(); + card.add(new Label("Code", "WorkbenchCardTitle")); + if (code == null || code.baseSource == null) { + card.add(new Label("Run the import to see the code.", "WorkbenchHint")); + return; + } + if (n != null) { + String java = javaFor(code.baseSource, n); + String css = cssFor(code.css, n.uiid); + if (java.length() > 0) { + card.add(new Label("Java", "WorkbenchFieldLabel")); + card.add(block(java, "java")); + } + if (css.length() > 0) { + card.add(new Label("CSS", "WorkbenchFieldLabel")); + card.add(block(css, "css")); + } + if (java.length() == 0 && css.length() == 0) { + card.add(new Label("No code of its own: it is part of its parent.", "WorkbenchHint")); + } + } + Button javaAll = new Button("Form Java", "WorkbenchButton"); + FontImage.setMaterialIcon(javaAll, FontImage.MATERIAL_CODE); + javaAll.addActionListener(e -> showWhole(code.className + "Base.java", code.baseSource)); + Button cssAll = new Button("Stylesheet", "WorkbenchButton"); + FontImage.setMaterialIcon(cssAll, FontImage.MATERIAL_PALETTE); + cssAll.addActionListener(e -> showWhole(code.className + ".css", code.css == null ? "" : code.css)); + card.add(FlowLayout.encloseIn(javaAll, cssAll)); + } + + /// The statements of the base class that build the node: those naming its field, and those + /// naming the local variable a container is built in (found through its `setName`). A + /// form with several variants builds the same element more than once; each line shows once. + static String javaFor(String source, DNode n) { + if (n.fieldName == null || source == null) { + return ""; + } + String[] lines = source.split("\n"); + java.util.List ids = new java.util.ArrayList(); + ids.add(n.fieldName); + String named = ".setName(\"" + n.fieldName + "\")"; + for (int i = 0; i < lines.length; i++) { + int at = lines[i].indexOf(named); + if (at > 0) { + String v = lines[i].substring(0, at).trim(); + if (v.length() > 0 && !ids.contains(v)) { + ids.add(v); + } + } + } + java.util.Set seen = new java.util.LinkedHashSet(); + for (int i = 0; i < lines.length; i++) { + for (int k = 0; k < ids.size(); k++) { + if (hasIdentifier(lines[i], ids.get(k))) { + seen.add(lines[i].trim()); + break; + } + } + } + StringBuilder out = new StringBuilder(); + for (String l : seen) { + out.append(l).append('\n'); + } + return out.toString().trim(); + } + + /// Every rule of the stylesheet whose selector is the UIID, with its states. + static String cssFor(String css, String uiid) { + if (css == null || uiid == null || uiid.length() == 0) { + return ""; + } + StringBuilder out = new StringBuilder(); + int i = 0; + while (i < css.length()) { + int open = css.indexOf('{', i); + if (open < 0) { + break; + } + int close = css.indexOf('}', open); + if (close < 0) { + break; + } + String selector = css.substring(i, open).trim(); + int comment = selector.lastIndexOf("*/"); + if (comment >= 0) { + selector = selector.substring(comment + 2).trim(); + } + if (selectorNames(selector, uiid)) { + out.append(selector).append(" {\n"); + String[] decls = css.substring(open + 1, close).split(";"); + for (int k = 0; k < decls.length; k++) { + String d = decls[k].trim(); + if (d.length() > 0) { + out.append(" ").append(d).append(";\n"); + } + } + out.append("}\n"); + } + i = close + 1; + } + return out.toString().trim(); + } + + private static boolean selectorNames(String selector, String uiid) { + String[] parts = selector.split(","); + for (int i = 0; i < parts.length; i++) { + String p = parts[i].trim(); + int dot = p.indexOf('.'); + String base = dot < 0 ? p : p.substring(0, dot); + if (base.equals(uiid)) { + return true; + } + } + return false; + } + + static boolean hasIdentifier(String line, String id) { + int at = line.indexOf(id); + while (at >= 0) { + boolean before = at == 0 || !Character.isJavaIdentifierPart(line.charAt(at - 1)); + int end = at + id.length(); + boolean after = end >= line.length() || !Character.isJavaIdentifierPart(line.charAt(end)); + if (before && after) { + return true; + } + at = line.indexOf(id, at + 1); + } + return false; + } + + /// Source as a block of lines, coloured by the code editor's own highlighter: one row of + /// labels per line, a label per token, monospaced, scrolling sideways for a long line. + /// Labels measure themselves exactly, which a read-only text area did not. + static Container block(String text, String language) { + Container lines = new Container(BoxLayout.y()); + lines.setUIID("Container"); + Tokenizer tokens = new Tokenizer(LanguageDef.forName(language)); + int state = Tokenizer.STATE_NORMAL; + String[] l = text.split("\n", -1); + for (int i = 0; i < l.length; i++) { + String line = l[i].replace("\t", " "); + Container row = new Container(BoxLayout.x()); + row.setUIID("Container"); + if (line.length() == 0) { + row.add(piece(" ", "WorkbenchCodeLine")); + } else { + SyntaxHighlightResult r = tokens.tokenize(line, state); + state = r.endState; + int at = 0; + for (int k = 0; k < r.tokens.size(); k++) { + SyntaxToken t = r.tokens.get(k); + int start = Math.max(at, Math.min(t.start, line.length())); + int end = Math.min(line.length(), t.start + t.length); + if (start > at) { + row.add(piece(line.substring(at, start), "WorkbenchCodeLine")); + } + if (end > start) { + row.add(piece(line.substring(start, end), kindUiid(t.kind))); + at = end; + } + } + if (at < line.length()) { + row.add(piece(line.substring(at), "WorkbenchCodeLine")); + } + } + lines.add(row); + } + Container box = new Container(new BorderLayout(), "WorkbenchCode"); + box.setScrollableX(true); + box.add(BorderLayout.CENTER, lines); + return box; + } + + private static Label piece(String text, String uiid) { + Label lb = new Label(text, uiid); + lb.setEndsWith3Points(false); + return lb; + } + + private static String kindUiid(int kind) { + switch (kind) { + case SyntaxToken.KEYWORD: + return "WorkbenchCodeKeyword"; + case SyntaxToken.STRING: + return "WorkbenchCodeString"; + case SyntaxToken.COMMENT: + return "WorkbenchCodeComment"; + case SyntaxToken.NUMBER: + return "WorkbenchCodeNumber"; + case SyntaxToken.TYPE: + return "WorkbenchCodeType"; + case SyntaxToken.PROPERTY: + return "WorkbenchCodeProperty"; + default: + return "WorkbenchCodeLine"; + } + } + + /// The whole file in a dialog, scrolling, selectable. + static void showWhole(String title, String text) { + Dialog d = new Dialog(title, new BorderLayout()); + d.setDialogUIID("WorkbenchDialog"); + d.getTitleComponent().setUIID("WorkbenchCardTitle"); + Container scroll = new Container(BoxLayout.y()); + scroll.setScrollableY(true); + scroll.add(block(text, title.endsWith(".css") ? "css" : "java")); + Button close = new Button("Close", "WorkbenchPrimary"); + close.addActionListener(e -> d.dispose()); + d.add(BorderLayout.CENTER, scroll); + d.add(BorderLayout.SOUTH, FlowLayout.encloseRight(close)); + d.setDisposeWhenPointerOutOfBounds(true); + d.show(dialogMargin(), dialogMargin(), dialogMargin(), dialogMargin()); + } + + private static int dialogMargin() { + return com.codename1.ui.CN.convertToPixels(12f); + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/DNode.java b/maven/design-import/src/main/java/com/codename1/designimport/DNode.java new file mode 100644 index 00000000000..22401f8b6b0 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/DNode.java @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtNode; +import com.codename1.art.Matrix; +import java.util.ArrayList; +import java.util.List; + +/// One element of the design as the importer understands it: what it is (its role), where it +/// is in the scope's space, how its children are laid out and how it is styled. +/// +/// The tree starts as a mirror of the design's layers and is reshaped by the stages: the +/// structure stage nests siblings inside the shape that contains them and splits rows, the +/// classify stage gives every node a role, the layout stage picks a Codename One layout and +/// the style stage assigns UIIDs. Coordinates are design pixels relative to the scope root. +public final class DNode { + /// What a node becomes in the generated form. + public enum Role { + SCREEN, CONTAINER, CARD, TOOLBAR, TABS, LIST, LIST_ITEM, BUTTON, TEXT_FIELD, LABEL, + IMAGE, ICON, DIVIDER, SWITCH, CHECKBOX, SPACER + } + + /// The Codename One layout a container is given. + public enum Layout { + NONE, BOX_Y, BOX_X, BORDER, GRID, LAYERED, FLOW + } + + /// Horizontal placement of a child inside a vertical box. + public enum Align { + FILL, LEFT, CENTER, RIGHT + } + + public String id; + public String name; + /// The design layer this node came from; null for a node the structure stage made. + public ArtNode source; + /// The transform from the source layer's parent to document space. + public Matrix parentToDoc; + public double x; + public double y; + public double w; + public double h; + public final List children = new ArrayList(); + + public Role role = Role.CONTAINER; + public double confidence; + /// Why the classifier picked the role, in words the checklist shows. + public String reason; + /// True once a person or an LLM fixed the role, so a rerun keeps it. + public boolean roleLocked; + + public Layout layout = Layout.NONE; + public boolean layoutLocked; + public double gap; + /// top, right, bottom, left. + public double[] padding = new double[4]; + public int columns; + public Align align = Align.LEFT; + /// Left offset inside the parent's padding, for a LEFT aligned child. + public double indent; + /// For a child of a horizontal box: true when it takes the remaining width. + public boolean grow; + /// The space before this child along its parent's axis, in design pixels. + public double before; + /// For a child of a BorderLayout parent: NORTH, SOUTH, EAST, WEST or CENTER. + public String slot; + /// For a horizontal box: children centred vertically. + public boolean centerCross; + /// For a BorderLayout: the CENTER child is centred on the whole container, as a title bar + /// centres its title whatever sits beside it. + public boolean centerAbsolute; + + public String text; + public Integer background; + public double backgroundAlpha = 1; + public Integer gradientTo; + public Integer foreground; + public double radius; + public Integer borderColor; + public double borderWidth; + public String fontFamily; + public double fontSize; + public boolean bold; + public boolean italic; + public boolean underline; + /// -1 left, 0 center, 1 right. + public int textAlign = -1; + public boolean multiline; + public boolean shadow; + + /// Rendered as an image rather than built from components. + public boolean rasterize; + /// The image asset name when the node is, or contains, an image. + public String imageName; + /// A picture that other layers sit on: the container's background image. + public boolean imageBackground; + + public String uiid; + /// The Java field the generated form holds this node in, or null for an unnamed node. + public String fieldName; + /// The order the design paints it in, across the whole tree: a later node is drawn over an + /// earlier one. Reading order rearranges children; overlapping ones go back to this. + public int z; + /// True for a row that runs past the screen's edge: the design shows its start and the + /// form scrolls it sideways, as a strip of chips or photos does on a device. + public boolean scrollX; + /// True for a dimming layer drawn over the whole screen with a popup on it: the screen + /// shows a sheet or dialog over another form. + public boolean overlay; + /// True for a check box the design names a radio button: one of a set, only one chosen. + public boolean radio; + /// True when the node is design chrome (status bar, bezel) left out of the form. + public boolean excluded; + + DNode() { + } + + DNode(String id, String name, double x, double y, double w, double h) { + this.id = id; + this.name = name; + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } + + /// True for a node that has children in the generated form. + public boolean isContainer() { + return !children.isEmpty() && !rasterize; + } + + public double right() { + return x + w; + } + + public double bottom() { + return y + h; + } + + /// True when `o` lies inside this node, allowing `slack` pixels. + public boolean contains(DNode o, double slack) { + return o.x >= x - slack && o.y >= y - slack && o.right() <= right() + slack + && o.bottom() <= bottom() + slack; + } + + /// Finds a node by id below and including this one. + public DNode find(String nodeId) { + if (nodeId == null) { + return null; + } + if (nodeId.equals(id)) { + return this; + } + for (int i = 0; i < children.size(); i++) { + DNode f = children.get(i).find(nodeId); + if (f != null) { + return f; + } + } + return null; + } + + /// Every text below this node, joined with spaces. + public String allText() { + StringBuilder sb = new StringBuilder(); + collectText(this, sb); + return sb.toString().trim(); + } + + private static void collectText(DNode n, StringBuilder sb) { + if (n.text != null) { + sb.append(n.text).append(' '); + } + for (int i = 0; i < n.children.size(); i++) { + collectText(n.children.get(i), sb); + } + } + + /// The number of nodes below and including this one. + public int count() { + int c = 1; + for (int i = 0; i < children.size(); i++) { + c += children.get(i).count(); + } + return c; + } + + @Override + public String toString() { + return role + "(" + name + ")"; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/DesignImportApp.java b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportApp.java new file mode 100644 index 00000000000..303b791d251 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportApp.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import com.codename1.io.Log; +import com.codename1.ui.Form; +import com.codename1.ui.plaf.UIManager; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +/// The Design Import desktop app: the import wizard when it was started for a project, the +/// bare workbench otherwise. It also serves MCP on a loopback port when +/// `designimport.mcp.port` is set, so an LLM can watch and drive the same session. +public class DesignImportApp { + private Form current; + private final DesignImportService service = new DesignImportService(); + + /// What the wizard starts from; null for the bare workbench. + static ImportWizard.Config wizard; + + /// Opens the file picker; the window installs one, a test has none. + static ImportWizard.Chooser chooser; + + public void init(Object context) { + installTheme(); + DesignImportMcpTools tools = new DesignImportMcpTools(service); + tools.register(); + String port = System.getProperty("designimport.mcp.port"); + if (port != null && port.trim().length() > 0 && !com.codename1.mcp.MCP.isRunning()) { + try { + com.codename1.mcp.MCP.startSocketServer(Integer.parseInt(port.trim())); + } catch (NumberFormatException ex) { + Log.p("designimport.mcp.port is not a number: " + port); + } + } + } + + /// Compiles the tool's own stylesheet and installs it. It ships as CSS inside the jar + /// rather than as a compiled theme, so there is one file to edit and no build step for it. + public static void installTheme() { + installTheme(textScale()); + } + + /// The Preferences key of the text size factor. + static final String TEXT_SCALE = "designimport.textScale"; + + /// The text size factor the person chose, 1 by default. + static double textScale() { + return Math.max(0.6, Math.min(2.5, com.codename1.io.Preferences.get(TEXT_SCALE, 1.0))); + } + + /// Makes every text in the tool bigger (a factor above 1) or smaller, remembers it, and + /// repaints the current form with it. Answers the new factor. + public static double zoomText(double factor) { + double next = Math.max(0.6, Math.min(2.5, Math.round(textScale() * factor * 20) / 20.0)); + com.codename1.io.Preferences.set(TEXT_SCALE, next); + installTheme(next); + com.codename1.ui.Form f = com.codename1.ui.CN.getCurrentForm(); + if (f != null) { + f.refreshTheme(); + f.revalidate(); + } + return next; + } + + /// Every `font-size: Nmm` multiplied by `scale`. The stylesheet sizes all text in mm, so + /// this is the whole of the text size control. + static String scaleFonts(String css, double scale) { + if (Math.abs(scale - 1) < 0.001) { + return css; + } + java.util.regex.Matcher m = java.util.regex.Pattern.compile("font-size:\\s*([0-9.]+)mm").matcher(css); + StringBuffer sb = new StringBuffer(); + while (m.find()) { + double v = Double.parseDouble(m.group(1)) * scale; + m.appendReplacement(sb, "font-size: " + (Math.round(v * 100) / 100.0) + "mm"); + } + m.appendTail(sb); + return sb.toString(); + } + + static void installTheme(double scale) { + InputStream in = DesignImportApp.class.getResourceAsStream("workbench.css"); + if (in == null) { + Log.p("Design Import: workbench.css is missing from the class path"); + return; + } + try { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + byte[] b = new byte[8192]; + int n; + while ((n = in.read(b)) > 0) { + bo.write(b, 0, n); + } + com.codename1.ui.util.MutableResource res = new com.codename1.ui.util.MutableResource(); + new com.codename1.ui.css.CSSThemeCompiler().compile(scaleFonts(new String(bo.toByteArray(), "UTF-8"), scale), + res, "Theme"); + UIManager.getInstance().setThemeProps(res.getTheme("Theme")); + } catch (IOException ex) { + Log.e(ex); + } finally { + try { + in.close(); + } catch (IOException ignored) { + // nothing was written + } + } + } + + public void start() { + if (current != null) { + current.show(); + return; + } + if (wizard != null) { + ImportWizard w = new ImportWizard(service, wizard, chooser); + current = w.getForm(); + w.start(); + return; + } + Workbench w = new Workbench(service); + current = w.getForm(); + current.show(); + String file = System.getProperty("designimport.open"); + if (file != null && file.length() > 0) { + w.open(file); + } + } + + public void stop() { + } + + public void destroy() { + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/DesignImportCli.java b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportCli.java new file mode 100644 index 00000000000..63a10137b83 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportCli.java @@ -0,0 +1,329 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.io.JSONParser; +import com.codename1.mcp.MCP; +import com.codename1.ui.Display; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.swing.JPanel; + +/// The tool without a window. +/// +/// - `--mcp-stdio`: serves the `designimport_*` tools over MCP on standard input and output, +/// which is how an LLM client launches it. +/// - `--script ops.json`: plays a JSON array of `{"op": ..., "args": {...}}` and prints the +/// results as a JSON array; stops at the first failure and exits 1. +/// - `DESIGN OUT_DIR [ClassName]`: open, run, emit into `OUT_DIR`, write the preview and +/// the design render beside it, and print the score. +/// - `--gui [--project DIR] [--design FILE] [--class NAME] [--package PKG] [--frame SCOPE]`: the +/// import wizard in a window ([ImportWizard]); exits 0 once it wrote the form and +/// [DesignImportWindow#CLOSED_WITHOUT_IMPORT] when the window was closed first. +/// - `--project DIR --design FILE [--class NAME] [--package PKG] [--frame SCOPE] [--preview DIR]`: +/// what `cn1:import-design` and the Gradle `importDesign` task fork. Imports into the +/// Codename One project at `DIR` (the module with `src/main/css/theme.css`), reports each +/// step on standard error as it happens and a summary on standard output, and exits 1 when +/// the import failed. +public final class DesignImportCli { + private DesignImportCli() { + } + + public static void main(String[] args) throws Exception { + if (args.length > 0 && "--gui".equals(args[0])) { + // The wizard: a window, so none of the headless set-up below. + ImportWizard.Config c = new ImportWizard.Config(); + for (int i = 1; i + 1 < args.length; i += 2) { + String v = args[i + 1]; + if ("--project".equals(args[i])) { + c.project = new File(v).getAbsolutePath(); + } else if ("--design".equals(args[i])) { + c.design = designPath(v); + } else if ("--class".equals(args[i])) { + c.className = v; + } else if ("--package".equals(args[i])) { + c.packageName = v; + } else if ("--frame".equals(args[i])) { + c.frame = v; + } + } + DesignImportWindow.wizard(c); + return; + } + System.setProperty("java.awt.headless", "true"); + // Standard output carries the answer (or the MCP stream) and nothing else; the port's + // own chatter goes to standard error. + java.io.PrintStream answer = System.out; + boolean mcp = args.length == 1 && "--mcp-stdio".equals(args[0]); + System.setOut(System.err); + if (!Display.isInitialized()) { + Display.init(new JPanel()); + } + DesignImportService service = new DesignImportService(); + if (mcp) { + // The transport takes standard output when it starts, and keeps it for the protocol. + System.setOut(answer); + new DesignImportMcpTools(service).register(); + MCP.startStdioServer(); + // Serves until the transport stops (the client closed standard input). + while (MCP.isRunning()) { + Thread.sleep(200); + } + System.exit(0); + return; + } + List results = new ArrayList(); + boolean ok; + if (args.length == 2 && "--script".equals(args[0])) { + ok = script(service, new File(args[1]), results); + } else if (args.length >= 2 && args[0].startsWith("--")) { + int code = project(service, args, answer); + System.exit(code); + return; + } else if (args.length >= 2) { + ok = oneShot(service, args, results); + } else { + System.err.println("usage: DesignImportCli --mcp-stdio | --script ops.json | DESIGN OUT_DIR [ClassName]"); + System.exit(2); + return; + } + answer.println(JSONParser.toJson(results)); + answer.flush(); + System.exit(ok ? 0 : 1); + } + + /// The build tools' mode. Returns the exit status. + /// A design file as an absolute path; a Figma link is not a path and stays as written. + static String designPath(String v) { + return DesignImportService.figmaKey(v) != null ? v : new File(v).getAbsolutePath(); + } + + private static int project(DesignImportService s, String[] args, java.io.PrintStream out) { + Map o = new LinkedHashMap(); + for (int i = 0; i + 1 < args.length; i += 2) { + if (!args[i].startsWith("--")) { + System.err.println("unexpected argument " + args[i]); + return 2; + } + o.put(args[i].substring(2), args[i + 1]); + } + String design = o.get("design"); + String dir = o.get("project"); + if (design == null || dir == null) { + System.err.println("usage: DesignImportCli --project DIR --design FILE [--class NAME] [--package PKG]" + + " [--frame SCOPE] [--preview DIR]"); + return 2; + } + long start = System.currentTimeMillis(); + boolean link = DesignImportService.figmaKey(design) != null; + progress(link ? "reading the design from Figma" : "reading " + new File(design).getName()); + Map a = new LinkedHashMap(); + a.put("path", designPath(design)); + Map opts = new LinkedHashMap(); + if (o.get("class") != null) { + opts.put("className", o.get("class")); + } + if (o.get("package") != null) { + opts.put("packageName", o.get("package")); + } + a.put("options", opts); + if (!project(s, "open", a, out)) { + return 1; + } + if (o.get("frame") != null) { + // A frame id, an index path (#0/2) or a name path (Page 1/Login), imported as the + // kind of screen the scope stage takes it for. + String frame = o.get("frame"); + String kind = "phone"; + Object fs = new DesignImportMcpTools(s).invokeOnEdt("frames", new LinkedHashMap()).get("frames"); + if (fs instanceof List) { + for (Object f : (List) fs) { + if (f instanceof Map && (frame.equals(((Map) f).get("path")) + || frame.equals(((Map) f).get("id")))) { + kind = String.valueOf(((Map) f).get("kind")); + } + } + } + Map v = new LinkedHashMap(); + v.put("scope", frame); + v.put("kind", kind); + List vs = new ArrayList(); + vs.add(v); + Map set = new LinkedHashMap(); + set.put("variants", vs); + Map oa = new LinkedHashMap(); + oa.put("set", set); + if (!project(s, "options", oa, out)) { + return 1; + } + } + s.getSession().progress = new ImportSession.Progress() { + @Override + public void step(String line) { + progress(line); + } + }; + if (!project(s, "run", new LinkedHashMap(), out)) { + return 1; + } + progress("writing sources into " + dir); + Map e = new LinkedHashMap(); + e.put("dir", new File(dir).getAbsolutePath()); + Map written = new DesignImportMcpTools(s).invokeOnEdt("emit", e); + if (!Boolean.TRUE.equals(written.get("success"))) { + out.println("Design Import failed: " + written.get("error")); + return 1; + } + Map score = null; + if (o.get("preview") != null) { + progress("rendering the design and the form to compare them"); + File pd = new File(o.get("preview")); + if (!pd.isDirectory() && !pd.mkdirs()) { + out.println("Design Import failed: cannot create " + pd); + return 1; + } + Map p = new LinkedHashMap(); + p.put("path", new File(pd, "preview.png").getPath()); + p.put("designPath", new File(pd, "design.png").getPath()); + new DesignImportMcpTools(s).invokeOnEdt("preview", p); + score = new DesignImportMcpTools(s).invokeOnEdt("score", new LinkedHashMap()); + } + ImportSession session = s.getSession(); + out.println("Imported " + new File(design).getName() + " as " + session.getCode().packageName + "." + + session.getCode().className + " in " + (System.currentTimeMillis() - start) + " ms"); + if (written.get("written") instanceof List) { + for (Object f : (List) written.get("written")) { + out.println(" wrote " + f); + } + } + if (score != null && score.get("fidelity") instanceof Map) { + Map f = (Map) score.get("fidelity"); + out.println(" matches the design: layout overlap " + f.get("layoutOverlap") + ", pixel similarity " + f.get("pixelSimilarity") + + " (renders in " + o.get("preview") + ")"); + } + // Several layers can raise the same line (five copies of one screenshot, each masked); + // the build log shows it once, with a count. The tree and the window keep them apart. + Map lines = new LinkedHashMap(); + int open = 0; + for (Issue i : session.getIssues()) { + if (i.resolved) { + continue; + } + open++; + String line = i.severity + " [" + i.stage + "] " + i.message + (i.fix == null ? "" : " -- " + i.fix); + Integer n = lines.get(line); + lines.put(line, Integer.valueOf(n == null ? 1 : n.intValue() + 1)); + } + for (Map.Entry l : lines.entrySet()) { + out.println(" " + l.getKey() + (l.getValue().intValue() > 1 ? " (" + l.getValue() + " layers)" : "")); + } + out.println(open == 0 ? " no open issues" : " " + open + " open issue(s); see above"); + return 0; + } + + private static boolean project(DesignImportService s, String op, Map a, java.io.PrintStream out) { + Map r = new DesignImportMcpTools(s).invokeOnEdt(op, a); + if (!Boolean.TRUE.equals(r.get("success"))) { + out.println("Design Import failed: " + r.get("error")); + return false; + } + return true; + } + + /// One line on standard error per step: the build tools pass it on as it happens. + static void progress(String line) { + System.err.println("[design-import] " + line); + System.err.flush(); + } + + private static boolean step(DesignImportService s, String op, Map args, List results) { + Map r = new DesignImportMcpTools(s).invokeOnEdt(op, args); + Map entry = new LinkedHashMap(); + entry.put("op", op); + entry.put("result", r); + results.add(entry); + return Boolean.TRUE.equals(r.get("success")); + } + + private static boolean script(DesignImportService s, File f, List results) throws Exception { + Reader r = new InputStreamReader(new FileInputStream(f), "UTF-8"); + Map root; + try { + root = new JSONParser().parseJSON(r); + } finally { + r.close(); + } + Object ops = root.get("root") instanceof List ? root.get("root") : root.get("ops"); + if (!(ops instanceof List)) { + System.err.println("expected a JSON array of {op, args}"); + return false; + } + for (Object o : (List) ops) { + if (!(o instanceof Map)) { + continue; + } + Map m = (Map) o; + Map a = new LinkedHashMap(); + if (m.get("args") instanceof Map) { + for (Map.Entry e : ((Map) m.get("args")).entrySet()) { + a.put(String.valueOf(e.getKey()), e.getValue()); + } + } + if (!step(s, String.valueOf(m.get("op")), a, results)) { + return false; + } + } + return true; + } + + private static boolean oneShot(DesignImportService s, String[] args, List results) { + String design = new File(args[0]).getAbsolutePath(); + File out = new File(args[1]).getAbsoluteFile(); + Map a = new LinkedHashMap(); + a.put("path", design); + if (args.length > 2) { + Map o = new LinkedHashMap(); + o.put("className", args[2]); + a.put("options", o); + } + if (!step(s, "open", a, results) || !step(s, "run", new LinkedHashMap(), results)) { + return false; + } + Map e = new LinkedHashMap(); + e.put("dir", out.getPath()); + Map p = new LinkedHashMap(); + p.put("path", new File(out, "preview.png").getPath()); + p.put("designPath", new File(out, "design.png").getPath()); + Map issues = new LinkedHashMap(); + issues.put("openOnly", Boolean.TRUE); + return step(s, "emit", e, results) && step(s, "preview", p, results) + && step(s, "score", new LinkedHashMap(), results) && step(s, "issues", issues, results); + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/DesignImportMcpTools.java b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportMcpTools.java new file mode 100644 index 00000000000..7871e60021f --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportMcpTools.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.ai.Tool; +import com.codename1.ai.ToolHandler; +import com.codename1.io.JSONParser; +import com.codename1.mcp.MCP; +import com.codename1.ui.Display; +import java.io.ByteArrayInputStream; +import java.io.InputStreamReader; +import java.util.LinkedHashMap; +import java.util.Map; + +/// The tool's operations as MCP tools, `designimport_`, so an LLM can run an +/// import end to end without a window: open, inspect the tree and the issues, override what +/// it disagrees with, render the preview, read the score, and emit. +public final class DesignImportMcpTools { + private final DesignImportService service; + private Runnable onChange; + + public DesignImportMcpTools(DesignImportService service) { + this.service = service; + } + + /// Called on the EDT after an operation that may have changed the session. + public void setOnChange(Runnable r) { + onChange = r; + } + + /// The JSON schema of one operation's arguments. + static String schema(String op) { + String obj = "{\"type\":\"object\",\"properties\":{"; + String variant = "\"variant\":{\"type\":\"string\",\"enum\":[\"phone\",\"tablet\",\"desktop\"]}"; + if ("open".equals(op)) { + return obj + "\"path\":{\"type\":\"string\",\"description\":\"Absolute path of a .psd, .sketch, .fig, .svg or .cn1art file, or of a React/HTML prototype (.html, a folder with index.html, or a .jsx beside one; needs Chrome)\"}," + + "\"base64\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"options\":{\"type\":\"object\"}}}"; + } + if ("options".equals(op)) { + return obj + "\"set\":{\"type\":\"object\",\"description\":\"Keys of the options map to change, e.g. " + + "variants:[{scope,kind}], className, maxContentWidthDp, scrollable, tabletBreakpointDp\"}}}"; + } + if ("run".equals(op)) { + return obj + "\"stage\":{\"type\":\"string\",\"description\":\"Stop after this stage: " + + "scope, detect, structure, classify, layout, responsive, style or emit\"}}}"; + } + if ("tree".equals(op)) { + return obj + "\"node\":{\"type\":\"string\"},\"depth\":{\"type\":\"integer\"}," + variant + "}}"; + } + if ("issues".equals(op)) { + return obj + "\"openOnly\":{\"type\":\"boolean\"},\"stage\":{\"type\":\"string\"}}}"; + } + if ("set".equals(op)) { + return obj + "\"node\":{\"type\":\"string\"},\"role\":{\"type\":\"string\"},\"layout\":{\"type\":\"string\"}," + + "\"align\":{\"type\":\"string\"},\"uiid\":{\"type\":\"string\"},\"field\":{\"type\":\"string\"}," + + "\"excluded\":{\"type\":\"boolean\"},\"rasterize\":{\"type\":\"boolean\"},\"flag\":{\"description\":\"a person marked it as converted wrong: their note; false clears it\"}," + + "\"columns\":{\"type\":\"integer\"},\"gap\":{\"type\":\"number\"}},\"required\":[\"node\"]}"; + } + if ("resolve".equals(op)) { + return obj + "\"issue\":{\"type\":\"string\"}},\"required\":[\"issue\"]}"; + } + if ("preview".equals(op)) { + return obj + "\"widthDp\":{\"type\":\"number\"},\"heightPx\":{\"type\":\"integer\"}," + + "\"path\":{\"type\":\"string\",\"description\":\"Write the PNG here instead of returning it\"}," + + "\"designPath\":{\"type\":\"string\",\"description\":\"Also write the design's render here\"}," + + variant + "}}"; + } + if ("score".equals(op)) { + return obj + "\"widthDp\":{\"type\":\"number\"}," + variant + "}}"; + } + if ("emit".equals(op)) { + return obj + "\"dir\":{\"type\":\"string\",\"description\":\"A project's common module; omit to get " + + "the files inline\"}}}"; + } + return obj + "}}"; + } + + static String describe(String op) { + if ("open".equals(op)) { + return "Opens a design file and lists the frames that look like screens."; + } else if ("frames".equals(op)) { + return "Lists candidate frames: id, name, bounds, guessed form factor."; + } else if ("options".equals(op)) { + return "Reads or changes the import options: scope variants, class name, responsive levers."; + } else if ("run".equals(op)) { + return "Runs the pipeline (optionally up to one stage) and returns the stage log and issue counts."; + } else if ("tree".equals(op)) { + return "Returns the imported tree: each node's role, confidence, reason, layout and bounds."; + } else if ("issues".equals(op)) { + return "Returns warnings, TODOs and the CSS compromises made, with a fix hint for each."; + } else if ("set".equals(op)) { + return "Overrides the importer's decision for one node (role, layout, uiid, field name, exclusion) " + + "and re-runs."; + } else if ("resolve".equals(op)) { + return "Marks an issue accepted."; + } else if ("preview".equals(op)) { + return "Renders the generated form at a width, as a PNG (base64 or written to a path)."; + } else if ("score".equals(op)) { + return "Compares the generated form with the design: pixel similarity and component-box overlap."; + } + return "Writes the Form, its Base class, theme.css, images and a unit test."; + } + + /// Registers every operation with the MCP server. + public void register() { + MCP.getServer().setServerInfo("codename-one-design-import", "8.0-SNAPSHOT"); + for (int i = 0; i < DesignImportService.OPERATIONS.size(); i++) { + final String op = DesignImportService.OPERATIONS.get(i); + MCP.addTool(new Tool("designimport_" + op, describe(op), schema(op), new ToolHandler() { + @Override + public String invoke(String argumentsJson) throws Exception { + return JSONParser.toJson(invokeOnEdt(op, parse(argumentsJson))); + } + })); + } + } + + /// Runs one operation on the EDT, which the preview's components need. + public Map invokeOnEdt(final String op, final Map args) { + final Object[] out = new Object[1]; + Runnable r = new Runnable() { + @Override + public void run() { + out[0] = service.call(op, args); + if (onChange != null && !"tree".equals(op) && !"issues".equals(op) && !"frames".equals(op)) { + onChange.run(); + } + } + }; + if (Display.getInstance().isEdt()) { + r.run(); + } else { + Display.getInstance().callSeriallyAndWait(r); + } + @SuppressWarnings("unchecked") + Map m = (Map) out[0]; // NOPMD - call() always answers a map + return m; + } + + static Map parse(String json) throws java.io.IOException { + if (json == null || json.trim().length() == 0) { + return new LinkedHashMap(); + } + JSONParser p = new JSONParser(); + return p.parseJSON(new InputStreamReader(new ByteArrayInputStream(json.getBytes("UTF-8")), "UTF-8")); + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/DesignImportService.java b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportService.java new file mode 100644 index 00000000000..8e49577151c --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportService.java @@ -0,0 +1,693 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtDocument; +import com.codename1.art.ArtFormats; +import com.codename1.io.FileSystemStorage; +import com.codename1.io.Util; +import com.codename1.ui.Image; +import com.codename1.ui.util.ImageIO; +import com.codename1.util.Base64; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.HashMap; +import java.util.Map; + +/// Everything the tool can do, as named operations over JSON-ready maps. +/// +/// The MCP tools, the command line and the tests all go through [#call(String, Map)], so an +/// LLM driving the tool headlessly and a person clicking through it reach the same code. +/// Each operation answers a map with `success` and, on failure, `error`. +public final class DesignImportService { + /// The operations, in the order an import usually uses them. + public static final java.util.List OPERATIONS = java.util.Collections.unmodifiableList(java.util.Arrays.asList("open", "frames", "options", "run", "tree", "issues", "set", "resolve", + "preview", "score", "emit")); + + private ImportSession session; + + /// The session being worked on, or null before `open`. + public ImportSession getSession() { + return session; + } + + /// Starts working on an already-read document. + public void setSession(ImportSession s) { + session = s; + } + + /// Runs one operation; never throws. + public Map call(String op, Map args) { + Map a = args == null ? new LinkedHashMap() : args; + try { + if ("open".equals(op)) { + return open(a); + } + if (session == null) { + return error("No design is open; call open first."); + } + if ("frames".equals(op)) { + return frames(); + } else if ("options".equals(op)) { + return options(a); + } else if ("run".equals(op)) { + return run(a); + } else if ("tree".equals(op)) { + return tree(a); + } else if ("issues".equals(op)) { + return issues(a); + } else if ("set".equals(op)) { + return set(a); + } else if ("resolve".equals(op)) { + return resolve(a); + } else if ("preview".equals(op)) { + return preview(a); + } else if ("score".equals(op)) { + return score(a); + } else if ("emit".equals(op)) { + return emit(a); + } + return error("Unknown operation " + op); + } catch (IOException ex) { + return error(ex.getMessage() == null ? ex.toString() : ex.getMessage()); + } catch (IllegalArgumentException ex) { + // A refused value: the message is meant for the user as it is. + return error(ex.getMessage() == null ? ex.toString() : ex.getMessage()); + } catch (RuntimeException ex) { + return error(ex.toString()); + } + } + + private Map open(Map a) throws IOException { + String path = str(a, "path"); + String data = str(a, "base64"); + byte[] bytes = null; + String name; + ArtDocument doc = null; + String figmaKey = data == null ? figmaKey(path) : null; + if (figmaKey != null) { + // A Figma link: the file is fetched from Figma's API with the user's token. The + // token comes with the call or from FIGMA_TOKEN, and is never stored or logged. + String token = str(a, "figmaToken"); + if (token == null || token.length() == 0) { + token = System.getenv("FIGMA_TOKEN"); + } + if (token == null || token.length() == 0) { + return error("A Figma link needs a personal access token: Figma > Settings > Security >" + + " Personal access tokens, with file content read access."); + } + doc = fetchFigma(token, figmaKey); + name = figmaName(path, figmaKey); + } else if (data == null && path != null && HtmlPrototypeReader.handles(path)) { + // A prototype is a program, not a file format: it is run in Chrome, not parsed. + // Chrome runs for up to a minute per viewport; on the EDT that waits in + // invokeAndBlock so the wizard keeps painting its status. + if (com.codename1.ui.CN.isEdt()) { + Object[] out = new Object[1]; + com.codename1.ui.CN.invokeAndBlock(new HtmlRead(path, out)); + if (out[0] instanceof IOException) { + throw (IOException) out[0]; + } + if (out[0] instanceof RuntimeException) { + throw (RuntimeException) out[0]; + } + if (out[0] instanceof Exception) { + throw new IOException(((Exception) out[0]).getMessage(), (Exception) out[0]); + } + doc = out[0] instanceof ArtDocument ? (ArtDocument) out[0] : null; + } else { + doc = HtmlPrototypeReader.read(path); + } + int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + name = path.substring(slash + 1); + } else if (data != null) { + bytes = Base64.decode(data.getBytes("UTF-8")); + name = str(a, "name") == null ? "design" : str(a, "name"); + } else if (path != null) { + bytes = read(path); + int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + name = path.substring(slash + 1); + } else { + return error("open needs path or base64."); + } + if (doc == null) { + doc = ArtFormats.read(bytes); + } + ImportSession opened = new ImportSession(doc, name); + if (a.get("options") instanceof Map) { + // Before the session is kept, so a refused option leaves the last one open. + opened.applyOptions(cast(a.get("options"))); + } + session = opened; + Map r = ok(); + if (figmaNote != null) { + r.put("note", figmaNote); + figmaNote = null; + } + r.put("source", name); + r.put("size", list(Double.valueOf(doc.getWidth()), Double.valueOf(doc.getHeight()))); + r.put("frames", frameList()); + return r; + } + + /// Set by `fetchFigma` when the design came from the local copy, for `open` to report. + private String figmaNote; + + /// Reads a Figma file, keeping a copy of what Figma sent. Figma's quota on whole-file + /// reads is small (on the Starter plan a few reads can lock a token out for days), so when + /// Figma refuses, the copy from the last successful read is opened instead and the reply + /// says so. The copy holds the design only, never the token. + private ArtDocument fetchFigma(String token, String key) throws IOException { + String dir = figmaCacheDir(key); + Map images = new HashMap(); + byte[] json; + try { + json = new com.codename1.art.FigmaClient(token).fetchJson(key, images); + } catch (IOException e) { + // Only a refusal to serve (the rate limit) or no connection opens the copy. A + // token Figma rejects (403) or a file it no longer has (404) must not quietly + // import an old design; FigmaClient names those statuses in its message. + String m = String.valueOf(e.getMessage()); + if (m.contains("(403)") || m.contains("(404)")) { + throw e; + } + if (dir == null || !exists(join(dir, "file.json"))) { + throw new IOException(e.getMessage() + (dir == null ? "" : "; no copy of this file is kept at " + dir), e); + } + json = read(join(dir, "file.json")); + images.clear(); + String[] names = FileSystemStorage.getInstance().listFiles(fsPath(join(dir, "images"))); + for (int i = 0; names != null && i < names.length; i++) { + String n = names[i].endsWith("/") ? null : names[i]; + if (n != null) { + images.put(n, read(join(join(dir, "images"), n))); + } + } + figmaNote = e.getMessage() + ". Opened the copy kept from the last time this file was read."; + return com.codename1.art.FigmaReader.read(json, images); + } + if (dir != null) { + try { + write(join(dir, "file.json"), json); + for (Map.Entry en : images.entrySet()) { + if (safeName(en.getKey())) { + write(join(join(dir, "images"), en.getKey()), en.getValue()); + } + } + } catch (IOException e) { + // The copy is a convenience; the design was read either way. + com.codename1.io.Log.e(e); + } + } + return com.codename1.art.FigmaReader.read(json, images); + } + + /// Where the copy of a Figma file is kept, under the app's home directory, or null when + /// there is none. + private static String figmaCacheDir(String key) { + String home = FileSystemStorage.getInstance().getAppHomePath(); + if (home == null || !safeName(key)) { + return null; + } + // A port may answer a virtual root ("file://home/"), kept as it is, or a file URL of a + // real path ("file:/Users/me/.cn1/"), which the helpers here take as a plain path. + if (home.startsWith("file:/") && !home.startsWith("file://")) { + home = home.substring("file:".length()); + } + return join(join(home, "design-import/figma"), key); + } + + private static boolean safeName(String s) { + if (s == null || s.length() == 0) { + return false; + } + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_')) { + return false; + } + } + return true; + } + + /// The file key of a Figma link (`figma.com/design/KEY/Name`, also `file/` and `proto/`), + /// or null when `path` is not one. + static String figmaKey(String path) { + if (path == null) { + return null; + } + String p = path.trim(); + int at = p.indexOf("figma.com/"); + if (at < 0 || !(p.startsWith("https://") || p.startsWith("http://") || at == 0 + || p.startsWith("www.figma.com/"))) { + return null; + } + String rest = p.substring(at + "figma.com/".length()); + String[] kinds = {"design/", "file/", "proto/"}; + for (int i = 0; i < kinds.length; i++) { + if (rest.startsWith(kinds[i])) { + String k = rest.substring(kinds[i].length()); + int end = 0; + // ASCII only, the same test FigmaClient and the cache apply to a key. + while (end < k.length() && (k.charAt(end) >= 'a' && k.charAt(end) <= 'z' + || k.charAt(end) >= 'A' && k.charAt(end) <= 'Z' || k.charAt(end) >= '0' && k.charAt(end) <= '9' + || k.charAt(end) == '-' || k.charAt(end) == '_')) { + end++; + } + return end == 0 ? null : k.substring(0, end); + } + } + return null; + } + + /// The file's name as its link spells it, `Mobile-Kit` in `.../design/KEY/Mobile-Kit?...`. + static String figmaName(String path, String key) { + int at = path.indexOf(key) + key.length(); + if (at < path.length() && path.charAt(at) == '/') { + String n = path.substring(at + 1); + int q = n.indexOf('?'); + if (q >= 0) { + n = n.substring(0, q); + } + int slash = n.indexOf('/'); + if (slash >= 0) { + n = n.substring(0, slash); + } + if (n.length() > 0) { + return n.replace('-', ' '); + } + } + return "Figma " + key; + } + + private Map frames() { + Map r = ok(); + r.put("frames", frameList()); + return r; + } + + private List frameList() { + List l = new ArrayList(); + List fs = ScopeStage.candidates(session.getDocument()); + for (int i = 0; i < fs.size(); i++) { + l.add(fs.get(i).toMap()); + } + return l; + } + + private Map options(Map a) { + if (a.get("set") instanceof Map) { + session.applyOptions(cast(a.get("set"))); + } + Map r = ok(); + r.put("options", session.optionsToMap()); + return r; + } + + private Map run(Map a) { + String last = str(a, "stage"); + Pipeline.run(session, last); + return summary(); + } + + private Map summary() { + Map r = ok(); + r.put("log", new ArrayList(session.getStageLog())); + r.put("issues", Integer.valueOf(session.getIssues().size())); + r.put("openIssues", Integer.valueOf(session.openIssueCount())); + r.put("variants", Integer.valueOf(session.variants.size())); + if (session.getCode() != null) { + r.put("className", session.getCode().className); + } + return r; + } + + private Map tree(Map a) { + ImportSession.Variant v = variant(a); + if (v == null || v.root == null) { + return error("Nothing imported yet; call run first."); + } + DNode n = v.root; + if (str(a, "node") != null) { + n = v.root.find(str(a, "node")); + if (n == null) { + return error("No node " + str(a, "node")); + } + } + int depth = (int) ImportSession.dbl(a.get("depth"), 64); + Map r = ok(); + r.put("tree", node(n, depth)); + return r; + } + + private ImportSession.Variant variant(Map a) { + if (session.variants.isEmpty()) { + return null; + } + String k = str(a, "variant"); + if (k != null) { + ImportSession.Variant v = session.variant(ImportSession.kind(k)); + if (v != null) { + return v; + } + } + return session.primary(); + } + + static Map node(DNode n, int depth) { + Map m = new LinkedHashMap(); + m.put("id", n.id); + m.put("name", n.name); + m.put("role", Text.lower(n.role.name())); + m.put("confidence", Double.valueOf(Math.round(n.confidence * 100) / 100.0)); + if (n.reason != null) { + m.put("reason", n.reason); + } + m.put("layout", Text.lower(n.layout.name())); + m.put("bounds", list(Double.valueOf(Math.round(n.x)), Double.valueOf(Math.round(n.y)), + Double.valueOf(Math.round(n.w)), Double.valueOf(Math.round(n.h)))); + if (n.text != null) { + m.put("text", n.text); + } + if (n.uiid != null) { + m.put("uiid", n.uiid); + } + if (n.rasterize) { + m.put("rasterize", Boolean.TRUE); + } + if (!n.children.isEmpty()) { + if (depth <= 0) { + m.put("childCount", Integer.valueOf(n.children.size())); + } else { + List c = new ArrayList(); + for (int i = 0; i < n.children.size(); i++) { + c.add(node(n.children.get(i), depth - 1)); + } + m.put("children", c); + } + } + return m; + } + + private Map issues(Map a) { + boolean open = ImportSession.bool(a.get("openOnly"), false); + String stage = str(a, "stage"); + List l = new ArrayList(); + List is = session.getIssues(); + for (int i = 0; i < is.size(); i++) { + Issue x = is.get(i); + if ((open && x.resolved) || (stage != null && !stage.equals(x.stage))) { + continue; + } + l.add(x.toMap()); + } + Map r = ok(); + r.put("issues", l); + return r; + } + + private Map set(Map a) { + String node = str(a, "node"); + if (node == null) { + return error("set needs node."); + } + String err = session.applyOverride(node, a); + if (err != null) { + return error(err); + } + Pipeline.run(session); + return summary(); + } + + private Map resolve(Map a) { + String id = str(a, "issue"); + if (id == null) { + return error("resolve needs issue."); + } + if (!session.resolvedIssues.contains(id)) { + session.resolvedIssues.add(id); + } + List is = session.getIssues(); + for (int i = 0; i < is.size(); i++) { + if (id.equals(is.get(i).id)) { + is.get(i).resolved = true; + } + } + Map r = ok(); + r.put("openIssues", Integer.valueOf(session.openIssueCount())); + return r; + } + + private Preview build(Map a) { + if (session.getCode() == null) { + Pipeline.run(session); + } + ImportSession.Variant v = variant(a); + double width = ImportSession.dbl(a.get("widthDp"), v.width / session.getEffectiveScale()); + return Preview.build(session, width); + } + + private Map preview(Map a) throws IOException { + Preview p = build(a); + ImportSession.Variant v = variant(a); + int[] size = Fidelity.size(session, v); + double widthDp = ImportSession.dbl(a.get("widthDp"), v.width / session.getEffectiveScale()); + int w = (int) Math.round(size[0] * widthDp / (v.width / session.getEffectiveScale())); + int h = (int) ImportSession.dbl(a.get("heightPx"), size[1]); + Image built = p.snapshot(w, h); + Map r = ok(); + r.put("size", list(Integer.valueOf(w), Integer.valueOf(h))); + if (p.cssError != null) { + r.put("cssError", p.cssError); + } + String path = str(a, "path"); + byte[] png = png(built); + if (path != null) { + write(path, png); + r.put("path", path); + if (str(a, "designPath") != null) { + write(str(a, "designPath"), png(Preview.designImage(session, v, size[0], size[1]))); + r.put("designPath", str(a, "designPath")); + } + } else { + r.put("png", Base64.encodeNoNewline(png)); + } + return r; + } + + private Map score(Map a) { + Preview p = build(a); + Map r = ok(); + r.put("fidelity", Fidelity.measure(session, p).toMap()); + if (p.cssError != null) { + r.put("cssError", p.cssError); + } + return r; + } + + private Map emit(Map a) throws IOException { + if (session.getCode() == null) { + Pipeline.run(session); + } + GeneratedCode code = session.getCode(); + String dir = str(a, "dir"); + Map r = ok(); + List written = new ArrayList(); + Map inline = new LinkedHashMap(); + for (Map.Entry e : code.textFiles().entrySet()) { + if (dir == null) { + inline.put(e.getKey(), e.getValue()); + } else { + String p = join(dir, e.getKey()); + if (e.getKey().endsWith("/" + code.className + ".java") && exists(p)) { + // The user's own subclass is written once and then belongs to them. + continue; + } + write(p, e.getValue().getBytes("UTF-8")); + written.add(e.getKey()); + } + } + if (dir != null) { + String css = null; + for (String k : code.textFiles().keySet()) { + if (k.startsWith("src/main/css/") && k.endsWith(".css")) { + css = k.substring("src/main/css/".length()); + } + } + if (css != null && importInTheme(join(dir, "src/main/css/theme.css"), css)) { + written.add("src/main/css/theme.css"); + } + } + for (Map.Entry e : code.images.entrySet()) { + if (dir != null) { + String p = join(dir, "src/main/resources/" + e.getKey()); + write(p, png(e.getValue())); + written.add("src/main/resources/" + e.getKey()); + } + } + if (dir == null) { + r.put("files", inline); + } else { + r.put("written", written); + } + r.put("className", code.className); + return r; + } + + /// Only `theme.css` is compiled by a project build; the form's own stylesheet reaches the + /// theme through an `@import`, which the build-time compiler inlines. Answers whether the + /// theme file was changed. + static boolean importInTheme(String themePath, String cssFile) throws IOException { + String line = "@import \"" + cssFile + "\";"; + String theme = exists(themePath) ? new String(read(themePath), "UTF-8") : ""; + if (theme.indexOf(line) >= 0) { + return false; + } + // An @import must precede every rule, so it goes first; only a leading @charset, + // which must stay the very first thing in the file, comes before it. + String out; + if (theme.startsWith("@charset")) { + int nl = theme.indexOf('\n'); + out = nl < 0 ? theme + "\n" + line + "\n" : theme.substring(0, nl + 1) + line + "\n" + theme.substring(nl + 1); + } else { + out = line + "\n" + theme; + } + write(themePath, out.getBytes("UTF-8")); + return true; + } + + // ---- small helpers ---- + + private static byte[] png(Image img) throws IOException { + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + ImageIO.getImageIO().save(img, out, ImageIO.FORMAT_PNG, 1); + return out.toByteArray(); + } + + static String fsPath(String p) { + if (p.startsWith("file:")) { + return p; + } + return p.startsWith("/") ? "file://" + p : p; + } + + private static byte[] read(String path) throws IOException { + InputStream in = FileSystemStorage.getInstance().openInputStream(fsPath(path)); + try { + return Util.readInputStream(in); + } finally { + Util.cleanup(in); + } + } + + private static boolean exists(String path) { + return FileSystemStorage.getInstance().exists(fsPath(path)); + } + + private static void write(String path, byte[] data) throws IOException { + FileSystemStorage fs = FileSystemStorage.getInstance(); + String p = fsPath(path); + int slash = p.lastIndexOf('/'); + if (slash > "file://".length()) { + mkdirs(p.substring(0, slash)); + } + OutputStream out = fs.openOutputStream(p); + try { + out.write(data); + } finally { + Util.cleanup(out); + } + } + + private static void mkdirs(String dir) { + FileSystemStorage fs = FileSystemStorage.getInstance(); + if (fs.exists(dir)) { + return; + } + int slash = dir.lastIndexOf('/'); + if (slash > "file://".length()) { + mkdirs(dir.substring(0, slash)); + } + fs.mkdir(dir); + } + + private static String join(String dir, String rel) { + return dir.endsWith("/") ? dir + rel : dir + "/" + rel; + } + + @SuppressWarnings("unchecked") + private static Map cast(Object o) { + return (Map) o; // NOPMD - checked with instanceof Map by every caller + } + + private static String str(Map a, String k) { + Object v = a.get(k); + return v instanceof String && ((String) v).length() > 0 ? (String) v : null; + } + + private static List list(Object... v) { + List l = new ArrayList(); + for (int i = 0; i < v.length; i++) { + l.add(v[i]); + } + return l; + } + + private static Map ok() { + Map m = new LinkedHashMap(); + m.put("success", Boolean.TRUE); + return m; + } + + static Map error(String message) { + Map m = new LinkedHashMap(); + m.put("success", Boolean.FALSE); + m.put("error", message); + return m; + } + + /// Runs Chrome off the EDT; the document, or what it threw, lands in `out[0]`. + private static final class HtmlRead implements Runnable { + private final String path; + private final Object[] out; + + HtmlRead(String path, Object[] out) { + this.path = path; + this.out = out; + } + + @Override + public void run() { + try { + out[0] = HtmlPrototypeReader.read(path); + } catch (Exception ex) { + out[0] = ex; + } + } + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/DesignImportWindow.java b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportWindow.java new file mode 100644 index 00000000000..d45d6e55c3d --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/DesignImportWindow.java @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import com.codename1.impl.javase.JavaSEPort; +import com.codename1.ui.Display; + +import java.awt.FileDialog; +import java.awt.GraphicsEnvironment; +import java.awt.Toolkit; +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.atomic.AtomicReference; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; + +/// The desktop window the app runs in, on the JavaSE port. +public final class DesignImportWindow implements Runnable { + static final String APP_DISPLAY_NAME = "Codename One Design Import"; + + /// The exit status when the window was closed before anything was written. + public static final int CLOSED_WITHOUT_IMPORT = 4; + + private static JFrame frame; + + private DesignImportWindow() { + } + + /// The import wizard as `scripts/designimport` starts it, for the Codename One project it + /// was started in (`-Ddesignimport.project`, the working folder by default). + /// `-Ddesignimport.workbench=true` opens the bare workbench instead. + public static void main(String[] args) { + if (Boolean.getBoolean("designimport.workbench")) { + open(null); + return; + } + ImportWizard.Config c = new ImportWizard.Config(); + // The tool always works inside a Codename One project: the folder it was started from, + // or the nearest one above it that holds the project's settings. + File project = findProject(new File(System.getProperty("designimport.project", System.getProperty("user.dir")))); + if (project == null) { + System.err.println("Design Import runs inside a Codename One project; start it from the project's" + + " folder (mvn cn1:import-design) or set DESIGNIMPORT_PROJECT."); + System.exit(2); + return; + } + c.project = project.getAbsolutePath(); + c.packageName = ImportWizard.appPackage(project, new File(project, "common")); + String file = System.getProperty("designimport.open"); + if (file != null && file.length() > 0) { + c.design = file; + } + open(c); + } + + /// The nearest folder at or above `from` that is a Codename One project: one holding + /// codenameone_settings.properties itself or in its `common` module. Null when none is. + static File findProject(File from) { + for (File d = from.getAbsoluteFile(); d != null; d = d.getParentFile()) { + if (new File(d, "codenameone_settings.properties").isFile() + || new File(d, "common/codenameone_settings.properties").isFile()) { + return d; + } + } + return null; + } + + /// Opens the import wizard for a project. The process exits when the wizard finishes + /// (status 0) or the window closes first ([#CLOSED_WITHOUT_IMPORT]). + public static void wizard(ImportWizard.Config config) { + open(config); + } + + private static void open(ImportWizard.Config config) { + if (GraphicsEnvironment.isHeadless()) { + System.err.println("[design-import] there is no display to open the window on; name the design" + + " (-Dcn1.design=...) to import it without one"); + System.exit(2); + return; + } + System.setProperty("apple.awt.application.name", APP_DISPLAY_NAME); + System.setProperty("sun.awt.application.name", APP_DISPLAY_NAME); + if (DesignImportWindow.class.getResource("/NativeTheme.res") != null) { + JavaSEPort.setNativeTheme("/NativeTheme.res"); + } + JavaSEPort.blockMonitors(); + JavaSEPort.setAppHomeDir(".CodenameOneDesignImport"); + JavaSEPort.setExposeFilesystem(true); + JavaSEPort.setTablet(true); + JavaSEPort.setUseNativeInput(true); + JavaSEPort.setShowEDTViolationStacks(false); + JavaSEPort.setShowEDTWarnings(false); + JavaSEPort.setDesktopTitleBarMode("native"); + JavaSEPort.setDesktopInteractiveScrollbars(true); + JavaSEPort.setFontFaces(File.separatorChar == '\\' ? "ArialUnicodeMS" : "Arial", "SansSerif", "Monospaced"); + frame = new JFrame(APP_DISPLAY_NAME); + JavaSEPort.setDefaultPixelMilliRatio(Toolkit.getDefaultToolkit().getScreenResolution() / 25.4 + * JavaSEPort.getRetinaScale()); + Display.init(frame.getContentPane()); + Display.getInstance().setProperty("AppName", APP_DISPLAY_NAME); + if (config != null) { + config.onFinish = new Runnable() { + @Override + public void run() { + System.exit(0); + } + }; + DesignImportApp.wizard = config; + } + DesignImportApp.chooser = new ImportWizard.Chooser() { + @Override + public String choose(String current) { + return pick(current); + } + }; + SwingUtilities.invokeLater(new DesignImportWindow()); + } + + /// The platform's own file dialog, shown on the Swing thread while the EDT waits. + static String pick(final String current) { + final AtomicReference chosen = new AtomicReference(); + Display.getInstance().invokeAndBlock(new Runnable() { + @Override + public void run() { + try { + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + FileDialog d = new FileDialog(frame, "Choose a design", FileDialog.LOAD); + if (current != null && current.length() > 0) { + File f = new File(current); + d.setDirectory(f.isDirectory() ? f.getPath() : f.getParent()); + } + d.setFilenameFilter((dir, name) -> ImportWizard.isDesign(name)); + d.setVisible(true); + if (d.getFile() != null) { + chosen.set(new File(d.getDirectory(), d.getFile()).getAbsolutePath()); + } + } + }); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } catch (InvocationTargetException ex) { + com.codename1.io.Log.e(ex); + } + } + }); + return chosen.get(); + } + + private static final class Closing extends java.awt.event.WindowAdapter { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(DesignImportApp.wizard == null ? 0 : CLOSED_WITHOUT_IMPORT); + } + } + + private static void startApp() { + DesignImportApp app = new DesignImportApp(); + app.init(null); + app.start(); + } + + @Override + public void run() { + // Closing the window before the wizard wrote anything is not a failure, but it is + // not an import either: the build tool says so instead of reporting success. + frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + frame.addWindowListener(new Closing()); + frame.getContentPane().setPreferredSize(new java.awt.Dimension(1480, 920)); + frame.pack(); + frame.setLocationByPlatform(true); + frame.setVisible(true); + Display.getInstance().callSerially(DesignImportWindow::startApp); + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/Fidelity.java b/maven/design-import/src/main/java/com/codename1/designimport/Fidelity.java new file mode 100644 index 00000000000..bb5383d288f --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/Fidelity.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.ui.Component; +import com.codename1.ui.Image; +import java.util.LinkedHashMap; +import java.util.Map; + +/// How close the built form is to the design, measured two ways. +/// +/// - **Pixels**: a structural similarity (SSIM) of the two renders' luminance, over 8x8 +/// windows, the same measure the Initializr skill's `CompareToMockup` uses. 1 is identical. +/// - **Layout**: for every component, the overlap (intersection over union) of its box with +/// its node's box in the design, averaged. Pixels forgive a box in the wrong place if it is +/// the same colour as what is there; this does not. +public final class Fidelity { + public double pixels; + public double layout; + public int compared; + /// The node whose component is furthest from its design box, and that overlap. + public String worstNode; + public double worstOverlap = 1; + + private Fidelity() { + } + + /// Measures a preview built at the variant's own width. + public static Fidelity measure(ImportSession s, Preview p) { + Fidelity f = new Fidelity(); + ImportSession.Variant v = p.variant; + if (v == null || v.root == null) { + return f; + } + int[] size = size(s, v); + int w = size[0]; + int h = size[1]; + Image built = p.snapshot(w, h); + Image design = Preview.designImage(s, v, w, h); + f.pixels = ssim(design.getRGB(), built.getRGB(), w, h); + double sx = w / v.width; + double sy = h / v.height; + double total = 0; + for (Map.Entry e : p.components.entrySet()) { + DNode n = v.root.find(e.getKey()); + Component c = e.getValue(); + if (n == null || n.role == DNode.Role.SCREEN || c.getWidth() == 0) { + continue; + } + int ax = c.getAbsoluteX() - p.root.getAbsoluteX(); + int ay = c.getAbsoluteY() - p.root.getAbsoluteY(); + double iou = iou(ax, ay, c.getWidth(), c.getHeight(), n.x * sx, n.y * sy, n.w * sx, n.h * sy); + total += iou; + f.compared++; + if (iou < f.worstOverlap) { + f.worstOverlap = iou; + f.worstNode = n.id; + } + } + f.layout = f.compared == 0 ? 0 : total / f.compared; + return f; + } + + /// The variant's size in device pixels: its design size in dp at this display's density. + public static int[] size(ImportSession s, ImportSession.Variant v) { + int w = (int) Math.round(v.width / s.getEffectiveScale() * dpPixels()); + int h = (int) Math.round(v.height / s.getEffectiveScale() * dpPixels()); + return new int[]{Math.max(1, Math.min(w, 2400)), Math.max(1, Math.min(h, 4800))}; + } + + static double dpPixels() { + // Measured over 100 dp so the integer rounding of convertToPixels stays small. + return Math.max(0.05, com.codename1.ui.CN.convertToPixels((float) StyleStage.MM_PER_DP * 100) / 100.0); + } + + static double iou(double ax, double ay, double aw, double ah, double bx, double by, double bw, double bh) { + double ix = Math.max(0, Math.min(ax + aw, bx + bw) - Math.max(ax, bx)); + double iy = Math.max(0, Math.min(ay + ah, by + bh) - Math.max(ay, by)); + double inter = ix * iy; + double union = aw * ah + bw * bh - inter; + return union <= 0 ? 0 : inter / union; + } + + /// Mean SSIM over 8x8 windows of the luminance. + static double ssim(int[] a, int[] b, int w, int h) { + final double c1 = (0.01 * 255) * (0.01 * 255); + final double c2 = (0.03 * 255) * (0.03 * 255); + double sum = 0; + int windows = 0; + for (int y = 0; y + 8 <= h; y += 8) { + for (int x = 0; x + 8 <= w; x += 8) { + double ma = 0; + double mb = 0; + for (int j = 0; j < 8; j++) { + for (int i = 0; i < 8; i++) { + int k = (y + j) * w + x + i; + ma += lum(a[k]); + mb += lum(b[k]); + } + } + ma /= 64; + mb /= 64; + double va = 0; + double vb = 0; + double cov = 0; + for (int j = 0; j < 8; j++) { + for (int i = 0; i < 8; i++) { + int k = (y + j) * w + x + i; + double da = lum(a[k]) - ma; + double db = lum(b[k]) - mb; + va += da * da; + vb += db * db; + cov += da * db; + } + } + va /= 63; + vb /= 63; + cov /= 63; + sum += ((2 * ma * mb + c1) * (2 * cov + c2)) / ((ma * ma + mb * mb + c1) * (va + vb + c2)); + windows++; + } + } + return windows == 0 ? 0 : sum / windows; + } + + private static double lum(int p) { + return 0.299 * ((p >> 16) & 0xff) + 0.587 * ((p >> 8) & 0xff) + 0.114 * (p & 0xff); + } + + /// The scores as JSON-ready values. + public Map toMap() { + Map m = new LinkedHashMap(); + m.put("pixelSimilarity", Double.valueOf(round(pixels))); + m.put("layoutOverlap", Double.valueOf(round(layout))); + m.put("componentsCompared", Integer.valueOf(compared)); + if (worstNode != null) { + m.put("worstNode", worstNode); + m.put("worstOverlap", Double.valueOf(round(worstOverlap))); + } + return m; + } + + private static double round(double d) { + return Math.round(d * 1000) / 1000.0; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/FitView.java b/maven/design-import/src/main/java/com/codename1/designimport/FitView.java new file mode 100644 index 00000000000..0f55b0260e6 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/FitView.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; +import com.codename1.ui.geom.Dimension; + +/// A picture scaled to fit its pane, whatever the pane's size, with one rectangle outlined +/// on it. The design and the form in the review step are each one of these, outlining the +/// same element, and a click on either reports where it landed in the picture's own pixels. +final class FitView extends Component { + /// Told where a click landed, in the picture's pixels. + interface Picker { + void picked(double x, double y); + } + + private Image image; + private double[] mark; + private Picker picker; + + FitView() { + setUIID("WorkbenchCanvas"); + setFocusable(false); + } + + void setImage(Image img) { + image = img; + repaint(); + } + + Image getImage() { + return image; + } + + /// Outlines x, y, width, height (picture pixels); null clears it. + /// Outlines `r` (x, y, w, h); an empty array or null clears the outline. + void setMark(double[] r) { + mark = r == null || r.length < 4 ? null : r; + repaint(); + } + + double[] getMark() { + return mark; + } + + void setPicker(Picker p) { + picker = p; + } + + /// The scale and the offset the picture is drawn at: {scale, x, y}. + double[] fit() { + if (image == null) { + return new double[]{1, 0, 0}; + } + int pad = CN.convertToPixels(2); + double aw = Math.max(1, getWidth() - pad * 2); + double ah = Math.max(1, getHeight() - pad * 2); + double s = Math.min(aw / image.getWidth(), ah / image.getHeight()); + double x = getX() + (getWidth() - image.getWidth() * s) / 2; + double y = getY() + (getHeight() - image.getHeight() * s) / 2; + return new double[]{s, x, y}; + } + + @Override + public void paint(Graphics g) { + if (image == null) { + return; + } + double[] f = fit(); + int w = (int) Math.round(image.getWidth() * f[0]); + int h = (int) Math.round(image.getHeight() * f[0]); + g.drawImage(image, (int) f[1], (int) f[2], w, h); + if (mark != null) { + spotlight(g, f, mark, (int) f[1], (int) f[2], w, h); + } + } + + /// Shows the selection as it is and dims what is around it, so the eye lands on it + /// without a tint hiding its detail. A selection as large as the picture is outlined only: + /// there is nothing around it to dim. + static void spotlight(Graphics g, double[] f, double[] r, int ix, int iy, int iw, int ih) { + int x = (int) Math.round(f[1] + r[0] * f[0]); + int y = (int) Math.round(f[2] + r[1] * f[0]); + int w = Math.max(2, (int) Math.round(r[2] * f[0])); + int h = Math.max(2, (int) Math.round(r[3] * f[0])); + int a = g.getAlpha(); + int x1 = Math.max(ix, x); + int y1 = Math.max(iy, y); + int x2 = Math.min(ix + iw, x + w); + int y2 = Math.min(iy + ih, y + h); + g.setColor(0x000000); + g.setAlpha(120); + if (y1 > iy) { + g.fillRect(ix, iy, iw, y1 - iy); + } + if (y2 < iy + ih) { + g.fillRect(ix, y2, iw, iy + ih - y2); + } + if (y2 > y1) { + if (x1 > ix) { + g.fillRect(ix, y1, x1 - ix, y2 - y1); + } + if (x2 < ix + iw) { + g.fillRect(x2, y1, ix + iw - x2, y2 - y1); + } + } + g.setAlpha(255); + g.setColor(0x5b8cff); + int t = Math.max(1, CN.convertToPixels(0.25f)); + for (int i = 0; i < t; i++) { + g.drawRect(x - i - 1, y - i - 1, w + i * 2 + 1, h + i * 2 + 1); + } + g.setAlpha(a); + } + + @Override + public void pointerReleased(int x, int y) { + super.pointerReleased(x, y); + if (picker == null || image == null) { + return; + } + double[] f = fit(); + double px = (x - getAbsoluteX() + getX() - f[1]) / f[0]; + double py = (y - getAbsoluteY() + getY() - f[2]) / f[0]; + if (px >= 0 && py >= 0 && px <= image.getWidth() && py <= image.getHeight()) { + picker.picked(px, py); + } + } + + @Override + protected Dimension calcPreferredSize() { + return new Dimension(CN.convertToPixels(40), CN.convertToPixels(60)); + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/FormExporter.java b/maven/design-import/src/main/java/com/codename1/designimport/FormExporter.java new file mode 100644 index 00000000000..5ba74433df4 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/FormExporter.java @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtDocument; +import com.codename1.art.GroupNode; +import com.codename1.art.Raster; +import com.codename1.art.RasterNode; +import com.codename1.art.ShapeNode; +import com.codename1.art.SolidPaint; +import com.codename1.art.StrokeStyle; +import com.codename1.art.TextNode; +import com.codename1.art.TextRun; +import com.codename1.components.SpanLabel; +import com.codename1.ui.CN; +import com.codename1.ui.CheckBox; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Font; +import com.codename1.ui.Image; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; +import com.codename1.ui.geom.GeneralPath; +import com.codename1.ui.plaf.Border; +import com.codename1.ui.plaf.RoundRectBorder; +import com.codename1.ui.plaf.Style; + +/// Turns a laid-out component tree into a design document: groups for containers, +/// rectangles for backgrounds and borders, text layers for text, pictures for icons. +/// +/// It is the other half of the round trip that proves the importer: a form whose structure +/// is known is exported, imported back, and the result is compared with the original. +/// [#setStripNames] removes every hint a name would give, so what is measured is how much +/// the heuristics recover from geometry and style alone -- the situation of a design file +/// drawn by hand. +public final class FormExporter { + private boolean stripNames; + private int counter; + + /// When true, layers get the generic names a design tool gives ("Rectangle 3", "Group 2") + /// instead of the components' names. + public void setStripNames(boolean stripNames) { + this.stripNames = stripNames; + } + + /// Exports `root`, which must be laid out, at one design pixel per device pixel. + public ArtDocument export(Component root) { + ArtDocument doc = new ArtDocument(root.getWidth(), root.getHeight()); + doc.setTitle(root.getName() == null ? "Design" : root.getName()); + GroupNode frame = group(root, root); + frame.setAttribute("sourceType", "artboard"); + doc.getRoot().getChildren().add(frame); + return doc; + } + + private String name(Component c, String generic) { + if (!stripNames && c.getName() != null) { + return c.getName(); + } + counter++; + return generic + " " + counter; + } + + private GroupNode group(Component c, Component root) { + int x = c.getAbsoluteX() - root.getAbsoluteX(); + int y = c.getAbsoluteY() - root.getAbsoluteY(); + GroupNode g = new GroupNode(); + g.setName(c == root ? (c.getName() == null ? "Screen" : c.getName()) : name(c, "Group")); // NOPMD CompareObjectsWithEquals + g.setFrame(x, y, c.getWidth(), c.getHeight(), c == root); // NOPMD CompareObjectsWithEquals + background(c, g, x, y); + if (c instanceof Container && !(c instanceof SpanLabel)) { + Container k = (Container) c; + for (int i = 0; i < k.getComponentCount(); i++) { + Component ch = k.getComponentAt(i); + if (ch.isVisible() && ch.getWidth() > 0 && ch.getHeight() > 0) { + g.getChildren().add(group(ch, root)); + } + } + } else { + content(c, g, x, y); + } + return g; + } + + private void background(Component c, GroupNode g, int x, int y) { + Style s = c.getStyle(); + Border b = s.getBorder(); + int alpha = s.getBgTransparency() & 0xff; + float radius = 0; + int strokeColor = 0; + float stroke = 0; + if (b instanceof RoundRectBorder) { + RoundRectBorder r = (RoundRectBorder) b; + radius = CN.convertToPixels(r.getCornerRadius()); + if (r.getStrokeOpacity() > 0 && r.getStrokeThickness() > 0) { + strokeColor = (r.getStrokeOpacity() << 24) | (r.getStrokeColor() & 0xffffff); + stroke = Math.max(1, r.isStrokeMM() ? CN.convertToPixels(r.getStrokeThickness()) : r.getStrokeThickness()); + } + } + if (alpha == 0 && stroke == 0) { + return; + } + GeneralPath p = new GeneralPath(); + if (radius > 0) { + roundRect(p, x, y, c.getWidth(), c.getHeight(), radius); + } else { + p.moveTo(x, y); + p.lineTo(x + c.getWidth(), y); + p.lineTo(x + c.getWidth(), y + c.getHeight()); + p.lineTo(x, y + c.getHeight()); + p.closePath(); + } + ShapeNode shape = new ShapeNode(p); + shape.setName(stripNames ? "Rectangle " + (++counter) : "Background"); + if (alpha > 0) { + shape.getFills().add(new SolidPaint((alpha << 24) | (s.getBgColor() & 0xffffff))); + } + if (stroke > 0) { + shape.getStrokes().add(new StrokeStyle(new SolidPaint(strokeColor), stroke)); + } + g.getChildren().add(shape); + } + + /// A rounded rectangle; quadratic corners are close enough for a design file. + static void roundRect(GeneralPath p, double x, double y, double w, double h, double r) { + r = Math.min(r, Math.min(w, h) / 2); + p.moveTo(x + r, y); + p.lineTo(x + w - r, y); + p.quadTo(x + w, y, x + w, y + r); + p.lineTo(x + w, y + h - r); + p.quadTo(x + w, y + h, x + w - r, y + h); + p.lineTo(x + r, y + h); + p.quadTo(x, y + h, x, y + h - r); + p.lineTo(x, y + r); + p.quadTo(x, y, x + r, y); + p.closePath(); + } + + private void content(Component c, GroupNode g, int x, int y) { + Style s = c.getStyle(); + int left = x + s.getPaddingLeftNoRTL(); + int innerW = c.getWidth() - s.getHorizontalPadding(); + if (c instanceof SpanLabel) { + SpanLabel sl = (SpanLabel) c; + text(g, sl.getText(), sl.getTextAllStyles().getFont(), sl.getTextUnselectedStyle().getFgColor(), left, + y + s.getPaddingTop(), innerW, true, TextNode.ALIGN_LEFT, c.getHeight()); + return; + } + if (c instanceof Label) { + Label l = (Label) c; + Image icon = l.getIcon(); + int textX = left; + if (c instanceof CheckBox) { + int box = Math.max(8, s.getFont().getHeight() * 3 / 4); + int by = y + (c.getHeight() - box) / 2; + GeneralPath p = new GeneralPath(); + roundRect(p, left, by, box, box, box / 6f); + ShapeNode sq = new ShapeNode(p); + sq.setName(stripNames ? "Rectangle " + (++counter) : "Check"); + sq.getStrokes().add(new StrokeStyle(new SolidPaint(0xff000000 | (s.getFgColor() & 0xffffff)), + Math.max(1, box / 8f))); + g.getChildren().add(sq); + textX += box + s.getFont().getHeight() / 3; + } else if (icon != null) { + int[] px = icon.getRGB(); + RasterNode r = new RasterNode(new Raster(left, y + (c.getHeight() - icon.getHeight()) / 2, + icon.getWidth(), icon.getHeight(), px)); + r.setName(stripNames ? "Bitmap " + (++counter) : "Icon"); + g.getChildren().add(r); + textX += icon.getWidth() + l.getGap(); + } + String t = l.getText(); + if (t != null && t.length() > 0) { + int align = TextNode.ALIGN_LEFT; + int a = s.getAlignment(); + if (a == Component.CENTER) { + align = TextNode.ALIGN_CENTER; + } else if (a == Component.RIGHT) { + align = TextNode.ALIGN_RIGHT; + } + text(g, t, s.getFont(), s.getFgColor(), textX, y, x + c.getWidth() - s.getPaddingRightNoRTL() - textX, + false, align, c.getHeight()); + } + return; + } + if (c instanceof TextArea) { + TextArea ta = (TextArea) c; + String t = ta.getText(); + int color = s.getFgColor(); + if ((t == null || t.length() == 0) && ta.getHint() != null) { + t = ta.getHint(); + color = ta.getHintLabel() != null ? ta.getHintLabel().getStyle().getFgColor() : 0x888888; + } + if (t != null && t.length() > 0) { + text(g, t, s.getFont(), color, left, y, innerW, false, TextNode.ALIGN_LEFT, c.getHeight()); + } + } + } + + private void text(GroupNode g, String t, Font f, int color, int x, int y, int width, boolean wrap, int align, + int height) { + TextNode tn = new TextNode(); + float size = f.getHeight() * 0.8f; + TextRun run = new TextRun(t, f.getFace() == Font.FACE_MONOSPACE ? "Monospace" : null, size, + new SolidPaint(0xff000000 | (color & 0xffffff))); + run.setBold((f.getStyle() & Font.STYLE_BOLD) != 0); + run.setItalic((f.getStyle() & Font.STYLE_ITALIC) != 0); + tn.getRuns().add(run); + double baseline = wrap ? y + f.getAscent() : y + (height - f.getHeight()) / 2.0 + f.getAscent(); + double tx = x; + if (!wrap && align == TextNode.ALIGN_CENTER) { + tx = x + width / 2.0; + } else if (!wrap && align == TextNode.ALIGN_RIGHT) { + tx = x + width; + } + tn.setPosition(tx, baseline); + tn.setAlign(align); + if (wrap) { + tn.setBoxWidth(width); + } + tn.setName(stripNames ? (t.length() > 20 ? t.substring(0, 20) : t) : "Text"); + g.getChildren().add(tn); + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/FormWalker.java b/maven/design-import/src/main/java/com/codename1/designimport/FormWalker.java new file mode 100644 index 00000000000..a3ff55ab6d2 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/FormWalker.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +/// Walks a variant's tree and tells a [Sink] what to build: which nodes are components, +/// which are containers, and how every child is attached. All the layout decisions of the +/// generated form are made here, once. +final class FormWalker { + private final ImportSession session; + private final Sink sink; + /// The width the form is built for, in design pixels; decides adaptive grid columns. + private final double width; + private final double designWidth; + + FormWalker(ImportSession session, Sink sink, double width, double designWidth) { + this.session = session; + this.sink = sink; + this.width = width; + this.designWidth = designWidth; + } + + Object walk(DNode root) { + return node(root, null); + } + + /// True when a node becomes one component rather than a container of its children. + static boolean isLeaf(DNode n, DNode parent) { + if (n.rasterize || n.children.isEmpty()) { + return true; + } + if (parent != null && parent.role == DNode.Role.TABS) { + return true; + } + return n.role == DNode.Role.BUTTON || n.role == DNode.Role.TEXT_FIELD || n.role == DNode.Role.SWITCH + || n.role == DNode.Role.CHECKBOX || n.role == DNode.Role.ICON || n.role == DNode.Role.IMAGE; + } + + private Object node(DNode n, DNode parent) { + if (n.excluded || n.role == DNode.Role.SPACER) { + return null; + } + if (isLeaf(n, parent) && parent != null) { + return sink.leaf(n, parent); + } + int columns = n.columns; + if (n.layout == DNode.Layout.GRID && session.adaptiveGrid && designWidth > 0) { + // Keep the design's cell width: a three-column grid on a phone is five on a tablet. + double cell = (n.w - n.padding[1] - n.padding[3]) / Math.max(1, n.columns); + double avail = n.w * (width / designWidth); + if (n.align == DNode.Align.FILL || n.w >= designWidth * 0.8) { + columns = (int) Math.max(1, Math.min(n.children.size(), Math.floor((avail + n.gap) / (cell + n.gap) + 0.15))); + } + } + Object c = sink.container(n, Math.max(1, columns)); + if (n.overlay) { + sink.overlay(c, n); + } + for (int i = 0; i < n.children.size(); i++) { + DNode ch = n.children.get(i); + Object cc = node(ch, n); + if (cc == null) { + continue; + } + attach(c, n, cc, ch, i); + } + return c; + } + + private void attach(Object c, DNode n, Object cc, DNode ch, int index) { + double[] m = new double[4]; + switch (n.layout) { + case LAYERED: { + double[] in = new double[4]; + in[0] = ch.y - n.y; + in[3] = ch.x - n.x; + // A layer as wide as its parent, or most of it with margins either side (a photo, + // a sheet's button), is pinned to both sides so it narrows and widens with the + // screen; one as tall, top and bottom. Small layers keep their size. + in[1] = ch.w >= n.w - 1 || ch.w >= n.w * 0.6 && n.right() - ch.right() >= 0 ? n.right() - ch.right() : -1; + in[2] = ch.h >= n.h - 1 ? n.bottom() - ch.bottom() : -1; + sink.add(c, n, cc, ch, null, nonNegative(m), 0); + sink.layered(c, cc, in); + return; + } + case BORDER: { + String slot = ch.slot == null ? "CENTER" : ch.slot; + if ("EAST".equals(slot)) { + // The centre stretches, so a wide gap before the east item is the centre's + // own room; only a tight one is a real spacing to keep. + m[3] = ch.before > n.w * 0.15 ? 0 : ch.before; + } else if ("CENTER".equals(slot) && index > 0 && n.layout == DNode.Layout.BORDER + && !"NORTH".equals(n.children.get(index - 1).slot)) { + m[3] = ch.before; + } + // A fixed-size item in the middle of a bar (a segmented control, a logo) keeps its + // size, centred, rather than stretching across the gap. + int wrap = 0; + if ("CENTER".equals(slot) && !fillsNaturally(ch) && n.role == DNode.Role.TOOLBAR) { + wrap = 2; + m[3] = 0; + } + sink.add(c, n, cc, ch, slot, nonNegative(m), wrap); + return; + } + case BOX_X: + case FLOW: + m[3] = index == 0 ? 0 : ch.before; + sink.add(c, n, cc, ch, null, nonNegative(m), 0); + return; + case GRID: { + double half = n.gap / 2; + m[0] = half; + m[1] = half; + m[2] = half; + m[3] = half; + sink.add(c, n, cc, ch, null, nonNegative(m), 0); + return; + } + default: { + m[0] = index == 0 ? 0 : ch.before; + int wrap = 0; + double inner = n.w - n.padding[1] - n.padding[3]; + switch (ch.align) { + case FILL: + if (!session.fillWidth || ch.w < inner - 2) { + m[3] = ch.indent; + m[1] = Math.max(0, inner - ch.indent - ch.w); + } + break; + case CENTER: + wrap = 2; + break; + case RIGHT: + wrap = 3; + break; + default: + if (fillsNaturally(ch)) { + m[3] = ch.indent; + } else { + wrap = 1; + m[3] = ch.indent; + } + break; + } + sink.add(c, n, cc, ch, null, nonNegative(m), wrap); + } + } + } + + /// Labels and containers read fine stretched across a column; buttons, fields and images + /// keep their design width. + private static boolean fillsNaturally(DNode ch) { + return ch.role == DNode.Role.LABEL || ch.role == DNode.Role.DIVIDER + || (!ch.children.isEmpty() && ch.role != DNode.Role.BUTTON && ch.role != DNode.Role.TEXT_FIELD + && !ch.rasterize && ch.background == null && ch.borderColor == null); + } + + /// Overlapping siblings would ask for negative margins, which a style refuses; overlap is + /// LayeredLayout's job, and the structure stage reports it. + static double[] nonNegative(double[] m) { + for (int i = 0; i < m.length; i++) { + if (m[i] < 0) { + m[i] = 0; + } + } + return m; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/GeneratedCode.java b/maven/design-import/src/main/java/com/codename1/designimport/GeneratedCode.java new file mode 100644 index 00000000000..941b9da64d5 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/GeneratedCode.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.ui.Image; +import java.util.LinkedHashMap; +import java.util.Map; + +/// What an import writes: the form's two classes, its CSS, its test and its images. +public final class GeneratedCode { + public String packageName; + public String className; + public String baseSource; + public String userSource; + public String css; + public String testSource; + /// Image file name to image. + public final Map images = new LinkedHashMap(); + /// The field each component is kept in, to its Java type. + public final Map fields = new LinkedHashMap(); + + /// The files to write, relative to a Maven project's `common` module: path to text. + public Map textFiles() { + Map m = new LinkedHashMap(); + String dir = packageName.replace('.', '/'); + m.put("src/main/java/" + dir + "/" + className + "Base.java", baseSource); + m.put("src/main/java/" + dir + "/" + className + ".java", userSource); + m.put("src/main/css/" + className + ".css", css); + m.put("src/test/java/" + dir + "/" + className + "Test.java", testSource); + return m; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/HtmlPrototypeReader.java b/maven/design-import/src/main/java/com/codename1/designimport/HtmlPrototypeReader.java new file mode 100644 index 00000000000..aa44aeb890f --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/HtmlPrototypeReader.java @@ -0,0 +1,1105 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtDocument; +import com.codename1.art.ArtFormats; +import com.codename1.art.ArtImages; +import com.codename1.art.ArtNode; +import com.codename1.art.ArtPaint; +import com.codename1.art.GradientPaint; +import com.codename1.art.GroupNode; +import com.codename1.art.Matrix; +import com.codename1.art.Raster; +import com.codename1.art.RasterNode; +import com.codename1.art.ShapeNode; +import com.codename1.art.SolidPaint; +import com.codename1.art.StrokeStyle; +import com.codename1.art.TextNode; +import com.codename1.art.TextRun; +import com.codename1.io.JSONParser; +import com.codename1.util.Base64; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.net.URLDecoder; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/// Reads a React or HTML prototype (one `.html` that loads React and Babel from a CDN, or an +/// `index.html` with `.jsx` files beside it) by running it in headless Chrome and turning the +/// rendered DOM into an [ArtDocument]. Executing the page is what makes this work for any +/// packaging: whatever the prototype does to build its DOM, Chrome has done it. +/// +/// The page is rendered twice, at a phone and a desktop viewport, and each becomes one +/// artboard as tall as the page, so the two are offered as variants of one screen. +public final class HtmlPrototypeReader { + /// The viewports rendered, as name, width, height. + static final Object[][] VIEWPORTS = {{"Phone", Integer.valueOf(390), Integer.valueOf(844)}, + {"Desktop", Integer.valueOf(1440), Integer.valueOf(900)}}; + + private static final long TIMEOUT_SECONDS = 60; + private static final long MAX_COPY_BYTES = 200L * 1024 * 1024; + private static final double ARTBOARD_GAP = 200; + + private HtmlPrototypeReader() { + } + + /// True for a path this reader opens: an `.html`/`.htm`, a directory with an `index.html`, + /// or a script file with an `index.html` beside it. + public static boolean handles(String path) { + return path != null && entry(new File(stripFileUrl(path))) != null; + } + + static String stripFileUrl(String p) { + if (p.startsWith("file://")) { + return p.substring(7); + } + if (p.startsWith("file:")) { + return p.substring(5); + } + return p; + } + + /// The html file to load for a path, or null when the path is not a prototype. + static File entry(File f) { + if (f.isDirectory()) { + File i = new File(f, "index.html"); + return i.isFile() ? i : null; + } + String n = Text.lower(f.getName()); + if (n.endsWith(".html") || n.endsWith(".htm")) { + return f; + } + if (n.endsWith(".jsx") || n.endsWith(".tsx") || n.endsWith(".js") || n.endsWith(".ts")) { + File dir = f.getAbsoluteFile().getParentFile(); + File i = dir == null ? null : new File(dir, "index.html"); + return i != null && i.isFile() ? i : null; + } + return null; + } + + /// Renders the prototype at `path` and converts it. + public static ArtDocument read(String path) throws IOException { + File html = entry(new File(stripFileUrl(path))); + if (html == null) { + throw new IOException(path + " is not an HTML prototype (an .html file, or a folder with index.html)."); + } + String chrome = findChrome(); + if (chrome == null) { + throw new IOException("Importing an HTML or React prototype needs Google Chrome, Chromium or Microsoft Edge. " + + "Install one, or point the system property designimport.chrome or the CHROME_PATH environment " + + "variable at its executable."); + } + File work = Files.createTempDirectory("cn1-html-import").toFile(); + try { + File srcDir = html.getAbsoluteFile().getParentFile(); + long[] budget = {MAX_COPY_BYTES}; + copyTree(srcDir, work, budget, 0); + File page = new File(work, html.getName()); + String source = new String(Files.readAllBytes(page.toPath()), "UTF-8"); + Files.write(page.toPath(), inject(source, script()).getBytes("UTF-8")); + List> dumps = new ArrayList>(); + for (int i = 0; i < VIEWPORTS.length; i++) { + int w = ((Integer) VIEWPORTS[i][1]).intValue(); + int h = ((Integer) VIEWPORTS[i][2]).intValue(); + Map d = parseDump(render(chrome, frame(page, w, h), w, h, new File(work, ".cn1-profile-" + i))); + checkRendered(d); + dumps.add(d); + } + ArtDocument doc = build(dumps, work); + doc.setTitle(html.getName()); + return doc; + } finally { + delete(work); + } + } + + /// Fails loudly on a page that rendered nothing: an empty screen is never what was meant. + static void checkRendered(Map d) throws IOException { + Map root = obj(d.get("root")); + boolean empty = root == null || (list(root.get("ch")).isEmpty() && root.get("runs") == null); + if (!empty && num(d.get("textLength"), 0) > 0) { + return; + } + if (!empty && hasVisual(root)) { + return; + } + List failed = list(d.get("failed")); + List scripts = list(d.get("scripts")); + if (!failed.isEmpty()) { + throw new IOException("The prototype loads scripts from " + failed.get(0) + ", which could not be reached. " + + "Importing it needs a network connection."); + } + List errors = list(d.get("errors")); + String first = scripts.isEmpty() ? null : String.valueOf(scripts.get(0)); + if (!errors.isEmpty()) { + throw new IOException("The prototype rendered nothing; a script failed: " + errors.get(0) + + (first == null ? "" : " (it loads scripts from " + first + ")")); + } + throw new IOException("The prototype rendered nothing" + + (first == null ? "." : "; it loads scripts from " + first + ", which may not have been reachable.")); + } + + private static boolean hasVisual(Map e) { + String t = str(e, "t"); + if ("img".equals(t) || "svg".equals(t) || "canvas".equals(t) || "input".equals(t)) { + return true; + } + List ch = list(e.get("ch")); + for (int i = 0; i < ch.size(); i++) { + Map c = obj(ch.get(i)); + if (c != null && hasVisual(c)) { + return true; + } + } + return false; + } + + static String script() throws IOException { + InputStream in = HtmlPrototypeReader.class.getResourceAsStream("html-dump.js"); + if (in == null) { + throw new IOException("html-dump.js is missing from the design import jar."); + } + try { + return new String(readAll(in), "UTF-8"); + } finally { + in.close(); + } + } + + /// Puts the script first in the document so it sees every script error, including a CDN + /// script that fails to load. + static String inject(String html, String js) { + String tag = ""; + String low = Text.lower(html); + int head = low.indexOf("= 0) { + int end = low.indexOf('>', head); + if (end > 0) { + return html.substring(0, end + 1) + tag + html.substring(end + 1); + } + } + int h = low.indexOf("= 0) { + int end = low.indexOf('>', h); + if (end > 0) { + return html.substring(0, end + 1) + "" + tag + "" + html.substring(end + 1); + } + } + return tag + html; + } + + /// Headless Chrome will not make a window narrower than about 500 pixels, so a phone + /// width is rendered in an iframe of exactly that size; its media queries then see 390. + static File frame(File page, int w, int h) throws IOException { + File f = new File(page.getParentFile(), ".cn1-frame-" + w + ".html"); + String html = "" + + "" + + "" + + ""; + Files.write(f.toPath(), html.getBytes("UTF-8")); + return f; + } + + static String findChrome() { + String p = System.getProperty("designimport.chrome"); + if (p != null && new File(p).canExecute()) { + return p; + } + p = System.getenv("CHROME_PATH"); + if (p != null && new File(p).canExecute()) { + return p; + } + String[] fixed = {"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", + "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", + "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"}; + for (int i = 0; i < fixed.length; i++) { + if (new File(fixed[i]).canExecute()) { + return fixed[i]; + } + } + String path = System.getenv("PATH"); + if (path != null) { + String[] names = {"google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"}; + String[] dirs = path.split(File.pathSeparator); + for (int n = 0; n < names.length; n++) { + for (int d = 0; d < dirs.length; d++) { + File f = new File(dirs[d], names[n]); + if (f.canExecute()) { + return f.getPath(); + } + } + } + } + return null; + } + + private static String render(String chrome, File page, int w, int h, File profile) throws IOException { + List cmd = new ArrayList(); + cmd.add(chrome); + cmd.add("--headless=new"); + cmd.add("--disable-gpu"); + cmd.add("--hide-scrollbars"); + cmd.add("--no-first-run"); + cmd.add("--no-default-browser-check"); + // file:// pages may load their own .jsx with fetch (Babel standalone does). + cmd.add("--allow-file-access-from-files"); + cmd.add("--user-data-dir=" + profile.getAbsolutePath()); + cmd.add("--window-size=" + Math.max(w, 600) + "," + (h + 40)); + cmd.add("--virtual-time-budget=15000"); + cmd.add("--dump-dom"); + cmd.add(page.toURI().toString()); + ProcessBuilder pb = new ProcessBuilder(cmd); + pb.redirectErrorStream(false); + pb.redirectError(ProcessBuilder.Redirect.to(new File(page.getParentFile(), ".cn1-chrome-" + w + ".log"))); + final Process proc = pb.start(); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final InputStream in = proc.getInputStream(); + Thread reader = new Thread(new Runnable() { + @Override + public void run() { + byte[] buf = new byte[65536]; + try { + int n; + while ((n = in.read(buf)) > 0) { + synchronized (out) { + out.write(buf, 0, n); + } + } + } catch (IOException ex) { + // The process was killed; what was read is all there is. + } + } + }, "cn1-chrome-reader"); + reader.setDaemon(true); + reader.start(); + boolean done; + try { + done = proc.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (done) { + reader.join(5000); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + done = false; + } + if (!done) { + proc.destroyForcibly(); + throw new IOException("Chrome did not finish rendering the prototype within " + TIMEOUT_SECONDS + " seconds."); + } + synchronized (out) { + return new String(out.toByteArray(), "UTF-8"); + } + } + + /// Pulls the JSON the injected script wrote out of Chrome's DOM dump. + static Map parseDump(String dom) throws IOException { + int at = dom.indexOf("id=\"cn1-dump\""); + int start = at < 0 ? -1 : dom.indexOf('>', at); + int end = start < 0 ? -1 : dom.indexOf("", start); + if (end < 0) { + throw new IOException("The prototype did not finish loading in Chrome (it never fired its load event " + + "within the time budget)."); + } + return parseJson(dom.substring(start + 1, end)); + } + + static Map parseJson(String json) throws IOException { + JSONParser p = new JSONParser(); + return p.parseJSON(new StringReader(json)); + } + + /// Converts rendered dumps (one per viewport, in [#VIEWPORTS] order) into a document. + /// `base` resolves relative and `file:` image sources; it may be null. + static ArtDocument build(List> dumps, File base) { + GroupNode page = new GroupNode(); + page.setName("Prototype"); + page.setAttribute("sourceType", "page"); + double x = 0; + double maxH = 0; + for (int i = 0; i < dumps.size(); i++) { + Map d = dumps.get(i); + String name = i < VIEWPORTS.length ? (String) VIEWPORTS[i][0] : "Viewport " + (i + 1); + double w = num(d.get("w"), 390); + double h = num(d.get("h"), 844); + GroupNode board = new GroupNode(); + board.setName(name); + board.setAttribute("sourceType", "FRAME"); + board.setFrame(0, 0, w, h, true); + board.setTransform(Matrix.translate(x, 0)); + int bg = color(d.get("bg")); + ShapeNode back = ShapeNode.rect(0, 0, w, h, 0); + back.fill(new SolidPaint((bg >>> 24) == 0 ? 0xffffffff : bg)); + back.setName("Background"); + board.add(back); + Map root = obj(d.get("root")); + if (root != null) { + List ch = list(root.get("ch")); + for (int c = 0; c < ch.size(); c++) { + ArtNode n = node(obj(ch.get(c)), base, root); + if (n != null) { + board.add(n); + } + } + if (root.get("runs") != null) { + ArtNode t = text(root); + if (t != null) { + board.add(t); + } + } + } + page.add(board); + x += w + ARTBOARD_GAP; + maxH = Math.max(maxH, h); + } + ArtDocument doc = new ArtDocument(Math.max(1, x - ARTBOARD_GAP), Math.max(1, maxH)); + doc.getRoot().add(page); + return doc; + } + + private static ArtNode node(Map e, File base, Map parent) { + if (e == null || Boolean.TRUE.equals(bool(e.get("hidden")))) { + return null; + } + Map s = obj(e.get("s")); + if (s == null) { + return null; + } + String tag = str(e, "t"); + double x = num(e.get("x"), 0); + double y = num(e.get("y"), 0); + double w = num(e.get("w"), 0); + double h = num(e.get("h"), 0); + GroupNode g = new GroupNode(); + if (e.get("id") instanceof String) { + g.setId("html-" + e.get("id")); + } + g.setAttribute("html.tag", tag); + String pos = str(s, "pos"); + if ("fixed".equals(pos) || "sticky".equals(pos)) { + g.setAttribute("fixed", "true"); + g.setAttribute("css.position", pos); + } + if ("absolute".equals(pos) || "fixed".equals(pos)) { + g.setAttribute("layoutPositioning", "ABSOLUTE"); + } + if (num(s.get("fg"), 0) > 0) { + g.setAttribute("layoutGrow", "1"); + } + float op = (float) num(s.get("op"), 1); + if (op < 1) { + g.setOpacity(op); + } + layout(g, s); + String oy = str(s, "oy"); + if ("auto".equals(oy) || "scroll".equals(oy)) { + g.setAttribute("scrollY", "true"); + } + String ox = str(s, "ox"); + if ("auto".equals(ox) || "scroll".equals(ox)) { + g.setAttribute("scrollX", "true"); + } + if (w > 0 && h > 0) { + ShapeNode box = box(s, x, y, w, h); + if (box != null) { + g.add(box); + } + } + String label = label(e); + if ("img".equals(tag) || "canvas".equals(tag)) { + ArtNode img = image(str(e, "src"), base, x, y, w, h); + if (img != null) { + g.add(img); + } + g.setName((w <= 48 && h <= 48 ? "Icon " : "Image ") + label); + return g.getChildren().isEmpty() ? null : g; + } + if ("svg".equals(tag)) { + ArtNode v = svg(str(e, "svg"), x, y, w, h); + if (v != null) { + g.add(v); + } + g.setName((w <= 48 && h <= 48 ? "Icon " : "Image ") + label); + return g.getChildren().isEmpty() ? null : g; + } + if (e.get("itype") instanceof String) { + return field(e, g, s, x, y, w, h); + } + if (e.get("runs") != null) { + ArtNode t = text(e); + if (t != null) { + g.add(t); + } + } + List ch = list(e.get("ch")); + for (int i = 0; i < ch.size(); i++) { + ArtNode c = node(obj(ch.get(i)), base, e); + if (c != null) { + g.add(c); + } + } + if (g.getChildren().isEmpty()) { + return null; + } + g.setName(name(e, tag, label, ch, parent)); + if (g.getChildren().size() > 1 || g.getChildren().get(0) instanceof GroupNode + || g.getAttribute("layoutMode") != null || g.getAttribute("fixed") != null) { + g.setFrame(x, y, w, h, false); + } + return g; + } + + /// Flex and grid are the author's own layout, so they are recorded the way Figma's auto + /// layout is and the layout stage uses them instead of guessing from positions. + private static void layout(GroupNode g, Map s) { + String display = str(s, "display"); + if (display == null) { + return; + } + g.setAttribute("css.display", display); + boolean flex = display.indexOf("flex") >= 0; + boolean grid = display.indexOf("grid") >= 0; + if (!flex && !grid) { + return; + } + String fd = str(s, "fd"); + boolean row; + if (flex) { + row = fd == null || fd.startsWith("row"); + if ("wrap".equals(str(s, "fw")) || "wrap-reverse".equals(str(s, "fw"))) { + g.setAttribute("layoutWrap", "WRAP"); + } + } else { + int cols = gridColumns(str(s, "gtc")); + g.setAttribute("gridColumns", String.valueOf(cols)); + row = cols > 1; + if (row) { + g.setAttribute("layoutWrap", "WRAP"); + } + } + g.setAttribute("layoutMode", row ? "HORIZONTAL" : "VERTICAL"); + g.setAttribute("itemSpacing", Text.num(num(s.get(row ? "cg" : "rg"), 0))); + g.setAttribute("paddingTop", Text.num(num(s.get("pt"), 0))); + g.setAttribute("paddingRight", Text.num(num(s.get("pr"), 0))); + g.setAttribute("paddingBottom", Text.num(num(s.get("pb"), 0))); + g.setAttribute("paddingLeft", Text.num(num(s.get("pl"), 0))); + String ai = str(s, "ai"); + if ("center".equals(ai)) { + g.setAttribute("counterAxisAlignItems", "CENTER"); + } + String jc = str(s, "jc"); + if (jc != null) { + g.setAttribute("css.justifyContent", jc); + } + } + + static int gridColumns(String gtc) { + if (gtc == null || "none".equals(gtc) || gtc.trim().length() == 0) { + return 1; + } + // Computed style resolves repeat() to one length per track. + int n = 0; + int depth = 0; + boolean inToken = false; + for (int i = 0; i < gtc.length(); i++) { + char c = gtc.charAt(i); + if (c == '(' || c == '[') { + depth++; + } else if (c == ')' || c == ']') { + depth--; + } + boolean space = c == ' ' && depth == 0; + if (!space && !inToken && depth <= 1 && c != ']') { + if (c != '[') { + n++; + } + inToken = c != '['; + } else if (space) { + inToken = false; + } + } + return Math.max(1, n); + } + + private static ShapeNode box(Map s, double x, double y, double w, double h) { + int bg = color(s.get("bg")); + ArtPaint fill = null; + Map grad = obj(s.get("grad")); + if (grad != null) { + fill = gradient(grad, x, y, w, h); + } + if (fill == null && (bg >>> 24) != 0) { + fill = new SolidPaint(bg); + } + double bw = Math.max(Math.max(num(s.get("bt"), 0), num(s.get("bb"), 0)), Math.max(num(s.get("bl"), 0), num(s.get("br"), 0))); + int bc = color(s.get("bc")); + if ((bc >>> 24) == 0) { + bc = color(s.get("bbc")); + } + boolean stroke = bw > 0 && (bc >>> 24) != 0; + boolean shadow = s.get("shadow") instanceof String; + if (fill == null && !stroke && !shadow) { + return null; + } + List rad = list(s.get("rad")); + double r = 0; + for (int i = 0; i < rad.size(); i++) { + r = Math.max(r, num(rad.get(i), 0)); + } + r = Math.min(r, Math.min(w, h) / 2); + ShapeNode sh = ShapeNode.rect(x, y, w, h, r); + sh.setName("Background"); + if (fill != null) { + sh.fill(fill); + } + if (stroke) { + StrokeStyle st = new StrokeStyle(new SolidPaint(bc), (float) bw); + st.setAlignment(StrokeStyle.ALIGN_INSIDE); + sh.stroke(st); + } + if (r > 0) { + sh.setAttribute("cornerRadius", Text.num(r)); + } + if (shadow) { + sh.setAttribute("css.boxShadow", (String) s.get("shadow")); + } + if (stroke && fill == null && num(s.get("bt"), 0) == 0 && num(s.get("bl"), 0) == 0) { + // Only a bottom border: the classic divider under a row. + sh.setAttribute("css.borderBottomOnly", "true"); + } + return sh; + } + + private static ArtPaint gradient(Map g, double x, double y, double w, double h) { + List stops = list(g.get("stops")); + if (stops.size() < 2) { + return null; + } + int[] colors = new int[stops.size()]; + float[] pos = new float[stops.size()]; + for (int i = 0; i < colors.length; i++) { + colors[i] = color(stops.get(i)); + pos[i] = (float) i / (colors.length - 1); + } + // CSS angles: 0deg points up, 90deg right. + double a = Math.toRadians(num(g.get("angle"), 180)); + double dx = Math.sin(a); + double dy = -Math.cos(a); + double half = (Math.abs(w * dx) + Math.abs(h * dy)) / 2; + double cx = x + w / 2; + double cy = y + h / 2; + return GradientPaint.linear(cx - dx * half, cy - dy * half, cx + dx * half, cy + dy * half, pos, colors); + } + + private static ArtNode field(Map e, GroupNode g, Map s, double x, double y, double w, double h) { + String type = str(e, "itype"); + String ph = str(e, "ph"); + String val = str(e, "val"); + if ("checkbox".equals(type) || "radio".equals(type)) { + if (g.getChildren().isEmpty()) { + ShapeNode b = "radio".equals(type) ? ShapeNode.ellipse(x + w / 2, y + h / 2, w / 2, h / 2) + : ShapeNode.rect(x, y, w, h, Math.min(w, h) / 5); + b.stroke(new StrokeStyle(new SolidPaint(0xff767676), 1)); + g.add(b); + } + g.setName(("radio".equals(type) ? "Radio " : "Checkbox ") + label(e)); + g.setAttribute("checked", String.valueOf(Boolean.TRUE.equals(bool(e.get("checked"))))); + return g; + } + if ("range".equals(type)) { + g.setName("Slider " + label(e)); + if (g.getChildren().isEmpty()) { + g.add(ShapeNode.rect(x, y + h / 2 - 2, w, 4, 2).fill(new SolidPaint(0xffcccccc))); + } + return g; + } + boolean button = "button".equals(type) || "submit".equals(type) || "reset".equals(type); + String shown = val != null && val.length() > 0 ? val : ph; + if (g.getChildren().isEmpty()) { + g.add(ShapeNode.rect(x, y, w, h, 0).stroke(new StrokeStyle(new SolidPaint(0xff767676), 1))); + } + if (shown != null && shown.length() > 0) { + Map f = obj(e.get("f")); + float size = (float) num(f == null ? null : f.get("fs"), 14); + int c = color(f == null ? null : f.get("c")); + if (!button && (val == null || val.length() == 0)) { + // A placeholder is drawn at a lighter shade. + c = (c & 0x00ffffff) | 0x80000000; + } + TextNode t = new TextNode(shown, size, (c >>> 24) == 0 ? 0xff000000 : c); + TextRun run = t.getRuns().get(0); + run.setFontFamily(family(f == null ? null : str(f, "ff"))); + double padL = num(s.get("pl"), 0); + t.setPosition(x + padL, baseline(y + (h - size * 1.2) / 2, size * 1.2, size)); + if (button) { + t.setAlign(TextNode.ALIGN_CENTER); + t.setPosition(x, t.getY()); + t.setBoxWidth(w); + } + g.add(t); + if (!button && (val == null || val.length() == 0)) { + g.setAttribute("placeholder", ph); + } + } + String what = button ? "Button " : "textarea".equals(type) ? "Input multiline " : "select".equals(type) ? "Input dropdown " + : "search".equals(type) ? "Search input " : "password".equals(type) ? "Input password " : "Input "; + g.setName(what + (shown == null ? label(e) : shown)); + g.setAttribute("inputType", type); + g.setFrame(x, y, w, h, false); + return g; + } + + private static ArtNode text(Map e) { + List rs = list(e.get("runs")); + Map tb = obj(e.get("tb")); + if (rs.isEmpty() || tb == null) { + return null; + } + TextNode t = new TextNode(); + float first = 0; + StringBuilder all = new StringBuilder(); + for (int i = 0; i < rs.size(); i++) { + Map r = obj(rs.get(i)); + if (r == null) { + continue; + } + String s = str(r, "text"); + if (s == null) { + continue; + } + if (all.length() == 0) { + s = ltrim(s); + } + if (i == rs.size() - 1) { + s = rtrim(s); + } + if (s.length() == 0) { + continue; + } + all.append(s); + float size = (float) num(r.get("fs"), 16); + int c = color(r.get("c")); + TextRun run = new TextRun(s, family(str(r, "ff")), size, new SolidPaint((c >>> 24) == 0 ? 0xff000000 : c)); + run.setBold(num(r.get("fw"), 400) >= 600); + run.setItalic(Boolean.TRUE.equals(bool(r.get("fi")))); + run.setUnderline(Boolean.TRUE.equals(bool(r.get("u")))); + float ls = (float) num(r.get("ls"), 0); + if (ls != 0) { + run.setLetterSpacing(ls); + } + if (first == 0) { + first = size; + } + t.getRuns().add(run); + } + if (t.getRuns().isEmpty()) { + return null; + } + Map s = obj(e.get("s")); + double tx = num(tb.get("x"), 0); + double ty = num(tb.get("y"), 0); + double tw = num(tb.get("w"), 0); + double th = num(tb.get("h"), 0); + int lines = (int) num(tb.get("lines"), 1); + String ta = s == null ? null : str(s, "ta"); + double lineH = lines > 0 ? th / lines : th; + if (s != null) { + double lh = parsePx(str(s, "lh")); + if (lh > 0 && first > 0) { + t.setLineHeight((float) (lh / first)); + lineH = lh; + } + } + int align = TextNode.ALIGN_LEFT; + if ("center".equals(ta)) { + align = TextNode.ALIGN_CENTER; + } else if ("right".equals(ta) || "end".equals(ta)) { + align = TextNode.ALIGN_RIGHT; + } + double boxX = tx; + double boxW = 0; + if (lines > 1 || align != TextNode.ALIGN_LEFT) { + // Wrapped or aligned text keeps the width of the element it sits in. + boxX = num(e.get("x"), tx) + (s == null ? 0 : num(s.get("pl"), 0)); + boxW = Math.max(tw, num(e.get("w"), tw) - (s == null ? 0 : num(s.get("pl"), 0) + num(s.get("pr"), 0))); + } + t.setAlign(align); + t.setBoxWidth(boxW); + t.setPosition(boxX, baseline(ty, lineH, first)); + t.setName(clip(all.toString(), 40)); + return t; + } + + /// The first baseline of a line box: half the leading, then the ascent (about 0.8 em). + private static double baseline(double top, double lineH, double size) { + return top + Math.max(0, (lineH - size) / 2) + size * 0.8; + } + + private static ArtNode image(String src, File base, double x, double y, double w, double h) { + if (src == null || w <= 0 || h <= 0) { + return null; + } + byte[] data = imageBytes(src, base); + if (data.length == 0) { + return null; + } + Raster r = ArtImages.decode(data); + if (r != null && r.getWidth() > 0 && r.getHeight() > 0) { + RasterNode n = new RasterNode(r); + n.setTransform(Matrix.translate(x, y).multiply(Matrix.scale(w / r.getWidth(), h / r.getHeight()))); + n.setName("Image"); + return n; + } + // An .svg used as an image. + String head = new String(data, 0, Math.min(data.length, 512), java.nio.charset.StandardCharsets.ISO_8859_1); + if (head.indexOf("= 0) { + return svgBytes(data, x, y, w, h); + } + return null; + } + + static byte[] imageBytes(String src, File base) { + try { + if (src.startsWith("data:")) { + int comma = src.indexOf(','); + if (comma < 0) { + return new byte[0]; + } + String meta = src.substring(5, comma); + String body = src.substring(comma + 1); + if (meta.endsWith(";base64")) { + return Base64.decode(body.getBytes("US-ASCII")); + } + return URLDecoder.decode(body, "UTF-8").getBytes("UTF-8"); + } + File f; + if (src.startsWith("file:")) { + f = new File(new java.net.URI(src)); + } else if (src.startsWith("http:") || src.startsWith("https:")) { + // Remote images are not fetched; the box imports without them. + return new byte[0]; + } else if (base != null) { + f = new File(base, src); + } else { + return new byte[0]; + } + return f.isFile() ? Files.readAllBytes(f.toPath()) : new byte[0]; + } catch (IOException ex) { + return new byte[0]; + } catch (java.net.URISyntaxException ex) { + return new byte[0]; + } catch (IllegalArgumentException ex) { + return new byte[0]; + } + } + + private static ArtNode svg(String markup, double x, double y, double w, double h) { + if (markup == null || w <= 0 || h <= 0) { + return null; + } + String m = markup; + if (m.indexOf("xmlns=") < 0) { + m = m.replaceFirst(" 0 ? d.getWidth() : w; + double dh = d.getHeight() > 0 ? d.getHeight() : h; + root.setTransform(Matrix.translate(x, y).multiply(Matrix.scale(w / dw, h / dh)).multiply(root.getTransform())); + root.setName("Vector"); + return root; + } catch (IOException ex) { + return null; + } catch (RuntimeException ex) { + // A malformed inline icon must not sink the whole import. + return null; + } + } + + /// A name the classifier understands, from the element's semantics. + private static String name(Map e, String tag, String label, List children, Map parent) { + String role = str(e, "role"); + Map s = obj(e.get("s")); + boolean fixed = s != null && ("fixed".equals(str(s, "pos")) || "sticky".equals(str(s, "pos"))); + if ("button".equals(tag) || "button".equals(role)) { + return "Button " + label; + } + if ("a".equals(tag)) { + return (s != null && box(s, 0, 0, 10, 10) != null ? "Button " : "Link ") + label; + } + if ("switch".equals(role)) { + return "Switch " + label; + } + if ("checkbox".equals(role)) { + return "Checkbox " + label; + } + if ("tablist".equals(role)) { + return "Tabs " + label; + } + if (tag.length() == 2 && tag.charAt(0) == 'h' && tag.charAt(1) >= '1' && tag.charAt(1) <= '6') { + return "Heading " + label; + } + if ("nav".equals(tag) || "navigation".equals(role)) { + double y = num(e.get("y"), 0); + double ph = parent == null ? 0 : num(parent.get("h"), 0); + boolean bottom = fixed && s != null && (ph <= 0 || y > ph / 2 || "0px".equals(str(s, "bottom"))); + if ((bottom || fixed && y > 200) && children.size() >= 3) { + return "Tab bar " + label; + } + return "Nav bar " + label; + } + if ("header".equals(tag) || "banner".equals(role)) { + return "Header " + label; + } + if ("footer".equals(tag)) { + return "Footer " + label; + } + if ("ul".equals(tag) || "ol".equals(tag) || "list".equals(role)) { + return "List " + label; + } + if ("hr".equals(tag)) { + return "Divider"; + } + if ("img".equals(role)) { + return "Image " + label; + } + return label.length() > 0 ? label : tag; + } + + /// What the element says it is: aria-label, then its text, then its id. + private static String label(Map e) { + String a = str(e, "aria"); + if (a != null && a.trim().length() > 0) { + return clip(a.trim(), 40); + } + String alt = str(e, "alt"); + if (alt != null && alt.trim().length() > 0) { + return clip(alt.trim(), 40); + } + StringBuilder sb = new StringBuilder(); + collectText(e, sb); + String t = sb.toString().trim(); + if (t.length() > 0) { + return clip(t, 40); + } + String id = str(e, "id"); + return id == null ? "" : id; + } + + private static void collectText(Map e, StringBuilder sb) { + if (sb.length() > 60 || e == null) { + return; + } + List rs = list(e.get("runs")); + for (int i = 0; i < rs.size(); i++) { + Map r = obj(rs.get(i)); + String s = r == null ? null : str(r, "text"); + if (s != null) { + sb.append(s); + } + } + List ch = list(e.get("ch")); + for (int i = 0; i < ch.size(); i++) { + if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') { + sb.append(' '); + } + collectText(obj(ch.get(i)), sb); + } + } + + /// The first family of a CSS font stack, unquoted. + static String family(String ff) { + if (ff == null) { + return "Roboto"; + } + int comma = ff.indexOf(','); + String f = (comma < 0 ? ff : ff.substring(0, comma)).trim(); + if (f.length() > 1 && (f.charAt(0) == '"' || f.charAt(0) == '\'')) { + f = f.substring(1, f.length() - 1); + } + return f.length() == 0 ? "Roboto" : f; + } + + private static double parsePx(String v) { + if (v == null || !v.endsWith("px")) { + return 0; + } + try { + return Double.parseDouble(v.substring(0, v.length() - 2)); + } catch (NumberFormatException ex) { + return 0; + } + } + + private static String clip(String s, int n) { + String t = s.replace('\n', ' '); + return t.length() <= n ? t : t.substring(0, n); + } + + private static String ltrim(String s) { + int i = 0; + while (i < s.length() && s.charAt(i) == ' ') { + i++; + } + return s.substring(i); + } + + private static String rtrim(String s) { + int i = s.length(); + while (i > 0 && s.charAt(i - 1) == ' ') { + i--; + } + return s.substring(0, i); + } + + static int color(Object o) { + if (o instanceof Number) { + return (int) ((Number) o).longValue(); + } + return 0; + } + + @SuppressWarnings("unchecked") + static Map obj(Object o) { + return o instanceof Map ? (Map) o : null; + } + + @SuppressWarnings("unchecked") + static List list(Object o) { + return o instanceof List ? (List) o : new ArrayList(); + } + + static String str(Map m, String k) { + Object o = m.get(k); + return o instanceof String ? (String) o : null; + } + + static double num(Object o, double def) { + if (o instanceof Number) { + return ((Number) o).doubleValue(); + } + if (o instanceof String) { + try { + return Double.parseDouble((String) o); + } catch (NumberFormatException ex) { + return def; + } + } + return def; + } + + /// The parser hands booleans back as Boolean or as the strings it read. + static Boolean bool(Object o) { + if (o instanceof Boolean) { + return (Boolean) o; + } + if (o instanceof String) { + return Boolean.valueOf("true".equals(o)); + } + return Boolean.FALSE; + } + + private static byte[] readAll(InputStream in) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] b = new byte[8192]; + int n; + while ((n = in.read(b)) > 0) { + out.write(b, 0, n); + } + return out.toByteArray(); + } + + private static void copyTree(File from, File to, long[] budget, int depth) throws IOException { + File[] fs = from.listFiles(); + if (fs == null || depth > 4) { + return; + } + for (int i = 0; i < fs.length; i++) { + File f = fs[i]; + String n = f.getName(); + if (n.equals("node_modules") || n.equals(".git") || n.equals("target") || n.equals("build")) { + continue; + } + File t = new File(to, n); + if (f.isDirectory()) { + if (!t.mkdirs() && !t.isDirectory()) { + throw new IOException("Could not create " + t); + } + copyTree(f, t, budget, depth + 1); + } else if (f.isFile() && web(n) && f.length() < 20L * 1024 * 1024) { + budget[0] -= f.length(); + if (budget[0] < 0) { + throw new IOException("The prototype's folder holds more than " + (MAX_COPY_BYTES >> 20) + + " MB; open the html file from a folder of its own."); + } + Files.copy(f.toPath(), t.toPath()); + } + } + } + + /// Only what a page loads is copied, so a prototype saved in Downloads does not copy all of it. + private static boolean web(String name) { + String n = Text.lower(name); + String[] ext = {".html", ".htm", ".js", ".mjs", ".jsx", ".ts", ".tsx", ".css", ".json", ".png", ".jpg", ".jpeg", + ".gif", ".webp", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".otf"}; + for (int i = 0; i < ext.length; i++) { + if (n.endsWith(ext[i])) { + return true; + } + } + return false; + } + + private static void delete(File f) { + File[] fs = f.listFiles(); + if (fs != null) { + for (int i = 0; i < fs.length; i++) { + delete(fs[i]); + } + } + if (!f.delete() && f.exists()) { + f.deleteOnExit(); + } + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/ImportSession.java b/maven/design-import/src/main/java/com/codename1/designimport/ImportSession.java new file mode 100644 index 00000000000..b1239534e7b --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/ImportSession.java @@ -0,0 +1,535 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtDocument; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// Everything one import knows: the design, the choices made about it (scope, variants, +/// responsive levers, per-node overrides) and what the stages produced from them. +/// +/// The choices are the session's state and serialize to JSON ([#optionsToMap()]); the stage +/// output is recomputed from them, so a session saved by the app and opened by an LLM over +/// MCP, or the reverse, reproduces the same result. +public final class ImportSession { + /// The form factor a scope was designed for. + public enum Kind { + PHONE, TABLET, DESKTOP + } + + /// One frame being imported and what it became. + public static final class Variant { + public String scopeId; + public Kind kind; + public DNode root; + public double width; + public double height; + /// Where the scope's top left corner is in document space. + public double originX; + public double originY; + + Variant(String scopeId, Kind kind) { + this.scopeId = scopeId; + this.kind = kind; + } + } + + /// A choice made about one node; null fields leave the importer's own decision. + public static final class Override { + public DNode.Role role; + public DNode.Layout layout; + public DNode.Align align; + public String uiid; + public String fieldName; + public Boolean excluded; + public Boolean rasterize; + public Integer columns; + public Double gap; + /// Set when a person marked the element as converted wrong: their note, possibly + /// empty. It is raised as an issue on every run until the flag is cleared, so an LLM + /// driving the import over MCP sees it as well. + public String flag; + } + + private final ArtDocument document; + private final String sourceName; + + // Choices. + public String packageName = "com.example.design"; + public String className; + /// Design pixels per density independent pixel; 0 detects it from the frame width. + public double designScale; + public final List variants = new ArrayList(); + public final Map overrides = new LinkedHashMap(); + /// Responsive levers. They apply to every import and become constants in the generated + /// form, so they stay tunable after generation. + public boolean fillWidth = true; + public int maxContentWidthDp = 640; + + /// The content cap actually applied: never narrower than the widest design frame, which + /// would squeeze the very layout being imported. + public double contentCapDp() { + if (maxContentWidthDp <= 0) { + return 0; + } + double widest = 0; + for (int i = 0; i < variants.size(); i++) { + widest = Math.max(widest, variants.get(i).width / getEffectiveScale()); + } + return Math.max(maxContentWidthDp, widest); + } + public boolean scrollable = true; + public boolean adaptiveGrid = true; + public int tabletBreakpointDp = 600; + /// At or above this width a desktop or web variant is used, when there is one. + public int desktopBreakpointDp = 1024; + public double snapTolerance = 3; + public double confidenceThreshold = 0.6; + /// Issue ids marked resolved; kept across reruns because ids are deterministic. + public final List resolvedIssues = new ArrayList(); + + // Results. + final List issues = new ArrayList(); + private final List stageLog = new ArrayList(); + double effectiveScale = 1; + GeneratedCode code; + + public ImportSession(ArtDocument document, String sourceName) { + this.document = document; + this.sourceName = sourceName == null ? "Design" : sourceName; + } + + public ArtDocument getDocument() { + return document; + } + + public String getSourceName() { + return sourceName; + } + + /// The design pixels per dp in use after the last run. + public double getEffectiveScale() { + return effectiveScale; + } + + public List getIssues() { + return issues; + } + + public List getStageLog() { + return stageLog; + } + + /// The output of the last emit, or null. + public GeneratedCode getCode() { + return code; + } + + /// The first variant, which is the one shown when only one is imported. + public Variant primary() { + return variants.isEmpty() ? null : variants.get(0); + } + + public Variant variant(Kind k) { + for (int i = 0; i < variants.size(); i++) { + if (variants.get(i).kind == k) { + return variants.get(i); + } + } + return null; + } + + /// The override for a node, created on first use. + public Override override(String nodeId) { + Override o = overrides.get(nodeId); + if (o == null) { + o = new Override(); + overrides.put(nodeId, o); + } + return o; + } + + /// The generated class name: the option when set, else one made from the scope's name. + public String effectiveClassName() { + if (className != null && className.length() > 0) { + return className; + } + Variant v = primary(); + String base = v == null || v.root == null ? sourceName : v.root.name; + String p = Text.pascal(base); + return p.endsWith("Form") ? p : p + "Form"; + } + + /// Receives each stage's summary line as the stage finishes; null for none. + public interface Progress { + /// Called on the importing thread with a line such as `detect: 35 nodes in "Login"`. + void step(String line); + } + + /// Where stage lines go as they happen, as well as into the stage log. + public Progress progress; + + void log(String line) { + stageLog.add(line); + if (progress != null) { + progress.step(line); + } + } + + void clearResults() { + issues.clear(); + stageLog.clear(); + code = null; + } + + /// Raises an issue. The id is derived from the stage, kind and node so the same problem + /// keeps its id across runs and a resolution survives a rerun. + Issue issue(String stage, Issue.Severity sev, DNode node, String kind, String message, String fix) { + String nodeId = node == null ? null : node.id; + String id = stage + ":" + kind + (nodeId == null ? "" : ":" + nodeId); + for (int i = 0; i < issues.size(); i++) { + if (issues.get(i).id.equals(id)) { + return issues.get(i); + } + } + Issue is = new Issue(id, stage, sev, nodeId, kind, message, fix); + is.resolved = resolvedIssues.contains(id); + if (node != null && node.w > 0 && node.h > 0) { + is.bounds = new double[]{node.x, node.y, node.w, node.h}; + } + issues.add(is); + return is; + } + + /// The count of issues not yet resolved. + public int openIssueCount() { + int c = 0; + for (int i = 0; i < issues.size(); i++) { + if (!issues.get(i).resolved) { + c++; + } + } + return c; + } + + /// The session's choices as JSON-ready values. + public Map optionsToMap() { + Map m = new LinkedHashMap(); + m.put("packageName", packageName); + if (className != null) { + m.put("className", className); + } + m.put("designScale", Double.valueOf(designScale)); + List vs = new ArrayList(); + for (int i = 0; i < variants.size(); i++) { + Map vm = new LinkedHashMap(); + vm.put("scope", variants.get(i).scopeId); + vm.put("kind", Text.lower(variants.get(i).kind.name())); + vs.add(vm); + } + m.put("variants", vs); + m.put("fillWidth", Boolean.valueOf(fillWidth)); + m.put("maxContentWidthDp", Integer.valueOf(maxContentWidthDp)); + m.put("scrollable", Boolean.valueOf(scrollable)); + m.put("adaptiveGrid", Boolean.valueOf(adaptiveGrid)); + m.put("tabletBreakpointDp", Integer.valueOf(tabletBreakpointDp)); + m.put("desktopBreakpointDp", Integer.valueOf(desktopBreakpointDp)); + m.put("snapTolerance", Double.valueOf(snapTolerance)); + m.put("confidenceThreshold", Double.valueOf(confidenceThreshold)); + Map om = new LinkedHashMap(); + for (Map.Entry e : overrides.entrySet()) { + Override o = e.getValue(); + Map x = new LinkedHashMap(); + putEnum(x, "role", o.role); + putEnum(x, "layout", o.layout); + putEnum(x, "align", o.align); + if (o.uiid != null) { + x.put("uiid", o.uiid); + } + if (o.fieldName != null) { + x.put("field", o.fieldName); + } + if (o.excluded != null) { + x.put("excluded", o.excluded); + } + if (o.rasterize != null) { + x.put("rasterize", o.rasterize); + } + if (o.columns != null) { + x.put("columns", o.columns); + } + if (o.gap != null) { + x.put("gap", o.gap); + } + if (o.flag != null) { + x.put("flag", o.flag); + } + om.put(e.getKey(), x); + } + m.put("overrides", om); + m.put("resolved", new ArrayList(resolvedIssues)); + return m; + } + + private static void putEnum(Map m, String k, Enum v) { + if (v != null) { + m.put(k, Text.lower(v.name())); + } + } + + private static final String[] KEYWORDS = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", + "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", + "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", + "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", + "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", + "while", "true", "false", "null", "var", "record", "yield"}; + + /// An ASCII Java identifier that is not a keyword, or with `dotted` a dot-separated list + /// of them (a package name). + static boolean javaName(String s, boolean dotted) { + int start = 0; + while (true) { + int dot = dotted ? s.indexOf('.', start) : -1; + String part = dot < 0 ? s.substring(start) : s.substring(start, dot); + if (part.length() == 0) { + return false; + } + for (int i = 0; i < part.length(); i++) { + char c = part.charAt(i); + boolean letter = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_' || c == '$'; + if (!letter && !(i > 0 && c >= '0' && c <= '9')) { + return false; + } + } + for (int i = 0; i < KEYWORDS.length; i++) { + if (KEYWORDS[i].equals(part)) { + return false; + } + } + if (dot < 0) { + return true; + } + start = dot + 1; + } + } + + /// Applies choices read back from [#optionsToMap()]; keys that are absent keep their value. + public void applyOptions(Map m) { + if (m == null) { + return; + } + if (m.get("packageName") instanceof String) { + String p = ((String) m.get("packageName")).trim(); + // Both end up in file paths and in Java source, so anything that is not a Java + // name is refused here rather than written outside the sources or left to the + // next build to reject. + // An empty package would emit "package ;", so it is refused like any other. + if (!javaName(p, true)) { + throw new IllegalArgumentException("Not a Java package name: \"" + p + "\""); + } + } + if (m.get("className") instanceof String) { + String c = ((String) m.get("className")).trim(); + if (c.length() > 0 && !javaName(c, false)) { + throw new IllegalArgumentException("Not a Java class name: " + c); + } + } + // Both checked before either is kept, so a refusal changes nothing. + if (m.get("packageName") instanceof String) { + packageName = ((String) m.get("packageName")).trim(); + } + if (m.get("className") instanceof String) { + className = ((String) m.get("className")).trim(); + } + designScale = dbl(m.get("designScale"), designScale); + if (m.get("variants") instanceof List) { + variants.clear(); + List vs = (List) m.get("variants"); + for (int i = 0; i < vs.size(); i++) { + if (!(vs.get(i) instanceof Map) || !(((Map) vs.get(i)).get("scope") instanceof String)) { + // A bare id here was once ignored, and the default screen was imported instead. + throw new IllegalArgumentException("variants[" + i + "] must be {\"scope\": ," + + " \"kind\": }, not " + vs.get(i)); + } + Map vm = (Map) vs.get(i); + Kind k = kind(String.valueOf(vm.get("kind"))); + variants.add(new Variant((String) vm.get("scope"), k)); + } + } + fillWidth = bool(m.get("fillWidth"), fillWidth); + maxContentWidthDp = (int) dbl(m.get("maxContentWidthDp"), maxContentWidthDp); + scrollable = bool(m.get("scrollable"), scrollable); + adaptiveGrid = bool(m.get("adaptiveGrid"), adaptiveGrid); + tabletBreakpointDp = (int) dbl(m.get("tabletBreakpointDp"), tabletBreakpointDp); + desktopBreakpointDp = (int) dbl(m.get("desktopBreakpointDp"), desktopBreakpointDp); + snapTolerance = dbl(m.get("snapTolerance"), snapTolerance); + confidenceThreshold = dbl(m.get("confidenceThreshold"), confidenceThreshold); + if (m.get("overrides") instanceof Map) { + Map om = (Map) m.get("overrides"); + for (Map.Entry e : om.entrySet()) { + if (e.getValue() instanceof Map) { + applyOverride(String.valueOf(e.getKey()), (Map) e.getValue()); + } + } + } + if (m.get("resolved") instanceof List) { + List r = (List) m.get("resolved"); + for (int i = 0; i < r.size(); i++) { + String id = String.valueOf(r.get(i)); + if (!resolvedIssues.contains(id)) { + resolvedIssues.add(id); + } + } + } + } + + /// Applies one override given as JSON-ready values; returns an error or null. + public String applyOverride(String nodeId, Map x) { + Override o = override(nodeId); + try { + if (x.get("role") != null) { + o.role = DNode.Role.valueOf(upper(String.valueOf(x.get("role")))); + } + if (x.get("layout") != null) { + o.layout = DNode.Layout.valueOf(upper(String.valueOf(x.get("layout")))); + } + if (x.get("align") != null) { + o.align = DNode.Align.valueOf(upper(String.valueOf(x.get("align")))); + } + } catch (IllegalArgumentException ex) { + return "Unknown value: " + ex.getMessage(); + } + if (x.get("uiid") instanceof String) { + o.uiid = (String) x.get("uiid"); + } + if (x.get("field") instanceof String) { + o.fieldName = (String) x.get("field"); + } + if (x.get("excluded") != null) { + o.excluded = Boolean.valueOf(bool(x.get("excluded"), false)); + } + if (x.containsKey("flag")) { + // false or null clears it; anything else is the note (true is a flag without one). + Object f = x.get("flag"); + o.flag = f == null || Boolean.FALSE.equals(f) ? null : Boolean.TRUE.equals(f) ? "" : String.valueOf(f); + } + if (x.get("rasterize") != null) { + o.rasterize = Boolean.valueOf(bool(x.get("rasterize"), false)); + } + if (x.get("columns") != null) { + o.columns = Integer.valueOf((int) dbl(x.get("columns"), 1)); + } + if (x.get("gap") != null) { + o.gap = Double.valueOf(dbl(x.get("gap"), 0)); + } + return null; + } + + /// The narrowest width, in dp, at which a variant of this kind is used. + public int minWidthDp(Kind k) { + return k == Kind.DESKTOP ? desktopBreakpointDp : k == Kind.TABLET ? tabletBreakpointDp : 0; + } + + /// The variants from the narrowest screen they serve to the widest. + public List byWidth() { + List out = new ArrayList(); + for (int i = 0; i < variants.size(); i++) { + Variant v = variants.get(i); + int at = 0; + while (at < out.size() && minWidthDp(out.get(at).kind) <= minWidthDp(v.kind)) { + at++; + } + out.add(at, v); + } + return out; + } + + /// The variant a screen `widthDp` wide shows: the widest whose breakpoint it reaches, or + /// the narrowest when it reaches none. + public Variant variantFor(double widthDp) { + List vs = byWidth(); + if (vs.isEmpty()) { + return null; + } + Variant best = vs.get(0); + for (int i = 1; i < vs.size(); i++) { + if (widthDp >= minWidthDp(vs.get(i).kind)) { + best = vs.get(i); + } + } + return best; + } + + static Kind kind(String s) { + String k = Text.lower(s); + if ("tablet".equals(k)) { + return Kind.TABLET; + } + if ("desktop".equals(k)) { + return Kind.DESKTOP; + } + return Kind.PHONE; + } + + static String upper(String s) { + StringBuilder sb = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c >= 'a' && c <= 'z') { + c = (char) (c - 32); + } else if (c == '-' || c == ' ') { + c = '_'; + } + sb.append(c); + } + return sb.toString(); + } + + static double dbl(Object o, double def) { + if (o instanceof Number) { + return ((Number) o).doubleValue(); + } + if (o instanceof String) { + try { + return Double.parseDouble((String) o); + } catch (NumberFormatException e) { + return def; + } + } + return def; + } + + static boolean bool(Object o, boolean def) { + if (o instanceof Boolean) { + return ((Boolean) o).booleanValue(); + } + if (o instanceof String) { + return "true".equals(o); + } + return def; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/ImportWizard.java b/maven/design-import/src/main/java/com/codename1/designimport/ImportWizard.java new file mode 100644 index 00000000000..33a2bfdec55 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/ImportWizard.java @@ -0,0 +1,1039 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import com.codename1.components.ClearableTextField; +import com.codename1.components.EmptyState; +import com.codename1.components.SpanLabel; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.ComboBox; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Image; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.GridLayout; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// Design to forms in four steps: choose the design, choose the screens in it (each becomes a +/// form of its own; a phone and a tablet frame of one screen become one adaptive form), review +/// what the import decided, screen by screen, and write the forms into the project. +/// +/// `cn1:import-design` and `importDesign` open it when no design is named, or with +/// `-Dcn1.design.gui=true`. Like the workbench it does everything through +/// [DesignImportService], so what it writes is what the headless import writes for the +/// same choices. +public final class ImportWizard { + /// Where the wizard starts and where it writes. Every field may be null. + public static final class Config { + /// The application module the forms are written into (it holds `src/main/css`); null + /// asks for a directory on the last step. + public String project; + /// A design to start from; the first step is then already filled in. + public String design; + /// The class name when one screen is imported; with several each is named after its + /// screen. + public String className; + public String packageName; + /// A frame to preselect alone: an id, a name path or an index path. + public String frame; + /// Run on the EDT once the forms were written and the summary dismissed. + public Runnable onFinish; + } + + /// Asks the person for a design file; answers the chosen path or null. + public interface Chooser { + String choose(String current); + } + + /// One screen of the design: its frames (a phone frame and its tablet twin when the + /// design has both), whether it is chosen, and the class it becomes. + static final class Screen { + final String name; + final List> frames = new ArrayList>(); + boolean chosen = true; + String className; + + Screen(String name) { + this.name = name; + } + + Map first() { + return frames.get(0); + } + } + + static final String[] STEPS = {"Design", "Screens", "Review", "Write"}; + + private final DesignImportService service; + private final Config config; + private final Chooser chooser; + private final TextField figmaToken = figmaTokenField(); + private final Form form = new Form("Design Import", new BorderLayout()); + private final Container steps = new Container(BoxLayout.x(), "WizardSteps"); + /// The step's own controls, in the bar at the top: the screen under review and the size + /// of the form on the review step, nothing on the others. + private final Container tools = new Container(LiveView.row(Component.LEFT), "Container"); + private final Container body = new Container(new BorderLayout(), "Workbench"); + private final Label status = new Label("", "WorkbenchStatus"); + private final Button back = new Button("Back", "WorkbenchButton"); + private final Button next = new Button("Next", "WorkbenchPrimary"); + private final TextField path = new TextField("", "A design file (.sketch, .psd, .svg, .html) or a Figma link", 50, TextField.ANY); + private final TextField className = new TextField("", "Class name", 24, TextField.ANY); + private final TextField packageName = new TextField("", "Package", 24, TextField.ANY); + /// Where the forms go: the module that holds src/main/java. The package names the folder + /// below it, so only the application is chosen, never a directory. + private String projectDir; + private final Label into = new Label("", "WorkbenchHint"); + private final TextField filter = new TextField("", "Filter screens by name", 30, TextField.ANY); + /// Made once: wrapping the field again on a second visit to the step would find it + /// still inside the first wrapper. + private final ClearableTextField filterBox; + /// The screen cards; the filter refills it without rebuilding the page around the field. + private final Container grid = new Container(GridLayout.autoFit(), "Container"); + private final Map thumbs = new HashMap(); + private Workbench workbench; + private final List screens = new ArrayList(); + /// The screen the session holds now. + private Screen active; + private String openedPath; + private int step = -1; + private boolean finished; + private boolean writing; + + public ImportWizard(DesignImportService service, Config config, Chooser chooser) { + this.service = service; + this.config = config; + this.chooser = chooser; + form.setUIID("Workbench"); + Button smaller = icon(FontImage.MATERIAL_TEXT_DECREASE, "Smaller text"); + smaller.addActionListener(e -> DesignImportApp.zoomText(1 / 1.15)); + Button bigger = icon(FontImage.MATERIAL_TEXT_INCREASE, "Bigger text"); + bigger.addActionListener(e -> DesignImportApp.zoomText(1.15)); + Button help = icon(FontImage.MATERIAL_HELP_OUTLINE, "Show me around this step"); + help.addActionListener(e -> tour()); + Container header = BorderLayout.centerEastWest(tools, FlowLayout.encloseRightMiddle(help, smaller, bigger), null); + header.setUIID("WizardHeader"); + form.add(BorderLayout.NORTH, header); + form.add(BorderLayout.CENTER, body); + // One line at the bottom: where the import is, what it says, and the way on. + // A box, not a FlowLayout: Next turns into "Write 132 forms" on the last step, and a flow + // measured at the width it had for "Next" wrapped the two buttons and doubled the bar. + Container nav = BorderLayout.centerEastWest(status, BoxLayout.encloseXNoGrow(back, next), steps); + nav.setUIID("WorkbenchBottom"); + form.add(BorderLayout.SOUTH, nav); + back.addActionListener(e -> go(step == 2 && screens.size() < 2 ? 0 : step - 1)); + next.addActionListener(e -> forward()); + path.setUIID("WorkbenchField"); + className.setUIID("WorkbenchField"); + packageName.setUIID("WorkbenchField"); + packageName.addDataChangedListener((t, i) -> updateInto()); + filter.setUIID("WorkbenchField"); + filterBox = ClearableTextField.wrap(filter); + filter.addDataChangedListener((t, i) -> { + if (step == 1) { + fillGrid(); + // A new filter starts at the top of its results: the old scroll position could + // leave the matches above the view and read as "nothing found". + Container sc = grid.getParent(); + if (sc != null) { + boolean smooth = sc.isSmoothScrolling(); + sc.setSmoothScrolling(false); + sc.scrollRectToVisible(0, 0, 1, 1, sc); + sc.setSmoothScrolling(smooth); + } + form.revalidateLater(); + } + }); + if (config.design != null) { + path.setText(config.design); + } + if (config.packageName != null) { + packageName.setText(config.packageName); + } + if (config.project != null) { + useProject(config.project); + } + } + + /// Walks the current step with coach marks: what each part of the page is for. + void tour() { + if (step == 2) { + com.codename1.components.CoachMarks.resetShowOnce(Workbench.TOUR); + if (workbench != null) { + workbench.tour(); + } + return; + } + com.codename1.components.CoachMarks t = new com.codename1.components.CoachMarks(form); + switch (step) { + case 0: + t.add(path, "The design", "A Sketch, Photoshop or SVG file, an HTML prototype, or a Figma link:" + + " in Figma, Share > Copy link."); + t.add(figmaToken, "Figma access", "A Figma link is read through Figma's API with your personal access" + + " token. It is used only to read the file and is never saved."); + t.add(steps, "Four steps", "Choose the design, pick its screens, review what each became, and write" + + " the forms into this project."); + break; + case 1: + t.add(filterBox, "Find a screen", "Filter the design's screens by name."); + t.add(grid, "Pick the screens", "Each chosen screen becomes a form. A phone and a tablet frame of" + + " the same screen become one form that adapts."); + break; + default: + t.add(packageName, "Where it goes", "The package of the generated forms, taken from the project."); + t.add(into, "Into the project", "The base classes and CSS are rewritten on every import; the" + + " subclasses are yours to edit."); + break; + } + t.add(next, "On to the next step", step == STEPS.length - 1 ? "Write the forms, their CSS, images and" + + " tests." : "Move on when this step is done."); + t.show(); + } + + private static Button icon(char material, String tip) { + Button b = new Button("", "WorkbenchIcon"); + FontImage.setMaterialIcon(b, material); + b.setTooltip(tip); + return b; + } + + public Form getForm() { + return form; + } + + /// Shows the form at its first step, or straight at the screen step when a design was + /// named and opens. + public void start() { + form.show(); + go(0); + if (config.design != null && open()) { + go(screens.size() < 2 ? 2 : 1); + } + } + + int step() { + return step; + } + + boolean finished() { + return finished; + } + + List screens() { + return screens; + } + + Workbench workbench() { + return workbench; + } + + static boolean isDesign(String name) { + String n = Text.lower(name); + return DesignImportService.figmaKey(name) != null || n.endsWith(".json") || n.endsWith(".sketch") || n.endsWith(".psd") || n.endsWith(".svg") + || HtmlPrototypeReader.handles(name); + } + + void forward() { + if (finished) { + if (config.onFinish != null) { + config.onFinish.run(); + } + return; + } + if (writing) { + return; + } + switch (step) { + case 0: + if (open()) { + go(screens.size() < 2 ? 2 : 1); + } + break; + case 1: + if (chosen().isEmpty()) { + status.setText("Choose at least one screen."); + form.revalidateLater(); + return; + } + go(2); + break; + case 2: + go(3); + break; + default: + write(); + break; + } + } + + void go(int s) { + step = Math.max(0, Math.min(STEPS.length - 1, s)); + steps.removeAll(); + for (int i = 0; i < STEPS.length; i++) { + if (i > 0) { + Label sep = new Label("", "WizardStep"); + FontImage.setMaterialIcon(sep, FontImage.MATERIAL_CHEVRON_RIGHT); + steps.add(sep); + } + Button l = new Button((i + 1) + " " + STEPS[i], i == step ? "WizardStepOn" + : i < step ? "WizardStepDone" : "WizardStep"); + if (i < step) { + // A step already passed is a way back to it. + FontImage.setMaterialIcon(l, FontImage.MATERIAL_CHECK_CIRCLE); + final int to = i; + l.addActionListener(e -> go(to)); + l.setTooltip("Back to " + STEPS[i]); + } else { + l.setEnabled(i == step); + l.setFocusable(false); + } + steps.add(l); + } + body.removeAll(); + tools.removeAll(); + back.setVisible(step > 0); + next.setText(step == STEPS.length - 1 ? writeLabel() : "Next"); + switch (step) { + case 0: + body.add(BorderLayout.CENTER, designPage()); + break; + case 1: + body.add(BorderLayout.CENTER, screenPage()); + break; + case 2: + if (workbench == null) { + workbench = new Workbench(service); + workbench.reportTo(status); + } + Container review = new Container(new BorderLayout(), "Workbench"); + if (chosen().size() > 1) { + tools.add(screenSwitcher()); + } + review.add(BorderLayout.CENTER, workbench.embed()); + tools.add(detached(workbench.liveView().controls())); + body.add(BorderLayout.CENTER, review); + List c = chosen(); + if (active == null || !c.contains(active)) { + scope(c.isEmpty() ? null : c.get(0)); + } + workbench.showSession(); + status.setText("Click any element to see what it became; the guide on the right walks the doubts."); + CN.callSerially(() -> { + if (step == 2 && workbench != null) { + workbench.tour(); + } + }); + break; + default: + body.add(BorderLayout.CENTER, writePage()); + break; + } + form.revalidateLater(); + } + + private String writeLabel() { + int n = chosen().size(); + return n > 1 ? "Write " + n + " forms" : "Write the form"; + } + + private Container page(String heading, String hint) { + Container c = new Container(BoxLayout.y(), "WizardPage"); + c.add(new Label(heading, "WizardHeading")); + c.add(new SpanLabel(hint, "WorkbenchHint")); + c.setScrollableY(true); + return c; + } + + private Component designPage() { + EmptyState empty = new EmptyState(FontImage.MATERIAL_UPLOAD_FILE, "Choose a design", + "A Figma link, a Sketch (.sketch), Photoshop (.psd) or SVG file, or a React/HTML prototype (.html)." + + " It is read here; nothing is uploaded anywhere."); + if (chooser != null) { + empty.setAction("Browse...", e -> { + String f = chooser.choose(path.getText()); + if (f != null) { + path.setText(f); + forward(); + } + }); + } + Container c = new Container(BoxLayout.y(), "WizardPage"); + c.add(empty); + // The field outlives the page: Back rebuilds the page around the same one. + path.remove(); + Container row = BorderLayout.center(path); + row.add(BorderLayout.NORTH, new Label("Or paste its path, or a Figma link", "WorkbenchFieldLabel")); + c.add(row); + // Figma's API needs the user's token. It lives in this field for the session and goes + // only to api.figma.com; FIGMA_TOKEN in the environment fills it in. + figmaToken.remove(); + Container tok = BorderLayout.center(figmaToken); + tok.add(BorderLayout.NORTH, new Label("Figma personal access token (for a Figma link)", "WorkbenchFieldLabel")); + tok.add(BorderLayout.SOUTH, new SpanLabel("To get a token: in Figma, open the account menu (your name," + + " top left) > Settings > Security. Under Personal access tokens choose Generate new token, give" + + " it read access to File content, and copy it here; Figma shows it only once. To get the link:" + + " open the file and choose Share > Copy link. The token is used only to read the file and is" + + " never saved.", "WorkbenchHint")); + c.add(tok); + status.setText(config.project == null ? "" : "The forms will be written into " + config.project); + return c; + } + + /// Opens the design in the path field and lists its screens. Answers false, having said + /// why, when it cannot. + private boolean open() { + String file = path.getText().trim(); + if (file.length() == 0) { + status.setText("Choose a design first."); + return false; + } + if (!isDesign(file)) { + status.setText("That is not a Figma link, or a .sketch, .psd, .svg or .html file."); + return false; + } + if (file.equals(openedPath) && service.getSession() != null) { + return true; + } + Map a = new LinkedHashMap(); + a.put("path", file); + if (figmaToken.getText().trim().length() > 0) { + a.put("figmaToken", figmaToken.getText().trim()); + } + a.put("options", new LinkedHashMap()); + // Figma is read over the network and a large file takes a while: say so, so the + // wizard does not look stuck. The read waits in invokeAndBlock, so this paints. + status.setText(DesignImportService.figmaKey(file) != null ? "Reading the design from Figma..." + : "Reading the design..."); + form.revalidate(); + Map opened = service.call("open", a); + if (!ok(opened)) { + return false; + } + if (opened.get("note") instanceof String) { + com.codename1.components.ToastBar.showInfoMessage((String) opened.get("note")); + } + openedPath = file; + thumbs.clear(); + active = null; + List> frames = new ArrayList>(); + Object fs = service.call("frames", null).get("frames"); + if (fs instanceof List) { + for (Object f : (List) fs) { + if (f instanceof Map) { + @SuppressWarnings("unchecked") + Map m = (Map) f; + frames.add(m); + } + } + } + screens.clear(); + screens.addAll(group(frames)); + name(screens); + if (config.frame != null) { + for (Screen s : screens) { + s.chosen = false; + for (Map f : s.frames) { + if (config.frame.equals(f.get("path")) || config.frame.equals(f.get("id"))) { + s.chosen = true; + } + } + } + } + if (screens.size() == 1 && config.className != null) { + screens.get(0).className = config.className; + } + if (screens.isEmpty()) { + // Nothing looks like a screen; the import takes the whole document. + return ok(service.call("run", null)); + } + return true; + } + + /// A phone frame and a tablet frame with the same name (less the form factor words) are + /// one screen; every other frame is a screen of its own. + static List group(List> frames) { + List out = new ArrayList(); + Map byStem = new HashMap(); + for (Map f : frames) { + String name = f.get("name") == null ? String.valueOf(f.get("path")) : String.valueOf(f.get("name")); + String stem = ScopeStage.stem(name); + Screen s = stem.length() == 0 ? null : byStem.get(stem); + if (s != null && !hasKind(s, String.valueOf(f.get("kind")))) { + // One frame per form factor: phone, tablet and desktop of one screen. + s.frames.add(f); + continue; + } + s = new Screen(name); + s.frames.add(f); + out.add(s); + if (stem.length() > 0 && !byStem.containsKey(stem)) { + byStem.put(stem, s); + } + } + return out; + } + + private static boolean hasKind(Screen s, String kind) { + for (Map f : s.frames) { + if (kind.equals(String.valueOf(f.get("kind")))) { + return true; + } + } + return false; + } + + /// A class per screen, named after it, never two alike. + static void name(List screens) { + Set used = new HashSet(); + for (Screen s : screens) { + String base = Text.pascal(ScopeStage.stem(s.name).length() > 0 ? s.name : "Screen"); + if (base.length() == 0 || !Character.isJavaIdentifierStart(base.charAt(0))) { + base = "Screen" + base; + } + if (base.endsWith("Form")) { + base = base.substring(0, base.length() - 4); + } + String n = base + "Form"; + for (int i = 2; used.contains(n); i++) { + n = base + i + "Form"; + } + used.add(n); + s.className = n; + } + } + + List chosen() { + List out = new ArrayList(); + for (Screen s : screens) { + if (s.chosen) { + out.add(s); + } + } + return out; + } + + /// Puts one screen in the session and runs the import on it. + boolean scope(Screen s) { + active = s; + List vs = new ArrayList(); + Map set = new LinkedHashMap(); + if (s != null) { + for (Map f : s.frames) { + Map v = new LinkedHashMap(); + v.put("scope", f.get("id") != null ? f.get("id") : f.get("path")); + v.put("kind", String.valueOf(f.get("kind"))); + vs.add(v); + } + set.put("className", s.className); + } + set.put("variants", vs); + if (packageName.getText().trim().length() > 0) { + set.put("packageName", packageName.getText().trim()); + } + Map a = new LinkedHashMap(); + a.put("set", set); + return ok(service.call("options", a)) && ok(service.call("run", null)); + } + + // ---- the screens step ---- + + private Component screenPage() { + Container c = new Container(new BorderLayout(), "WizardPage"); + Container head = new Container(BoxLayout.y(), "Container"); + head.add(new Label("Choose the screens", "WizardHeading")); + head.add(new SpanLabel("Each screen becomes a form of its own. A phone frame and a tablet frame of the same" + + " screen become one form that adapts between them.", "WorkbenchHint")); + Button all = new Button("Select all", "WorkbenchLink"); + all.addActionListener(e -> { + for (Screen s : visible()) { + s.chosen = true; + } + go(1); + }); + Button none = new Button("Select none", "WorkbenchLink"); + none.addActionListener(e -> { + for (Screen s : visible()) { + s.chosen = false; + } + go(1); + }); + filterBox.remove(); + Container tools = BorderLayout.centerEastWest(filterBox, + FlowLayout.encloseRightMiddle(new Label(" ", "WorkbenchHint"), all, new Label(" ", "WorkbenchHint"), none), null); + head.add(tools); + c.add(BorderLayout.NORTH, head); + // Cards keep their own height: the grid sits in a scrolling column rather than being + // stretched over the page. + grid.remove(); + Container scroll = BoxLayout.encloseY(grid); + scroll.setScrollableY(true); + c.add(BorderLayout.CENTER, scroll); + fillGrid(); + countStatus(); + return c; + } + + private void fillGrid() { + grid.removeAll(); + List shown = visible(); + for (int i = 0; i < shown.size(); i++) { + Screen s = shown.get(i); + if (i < 12 && !thumbs.containsKey(key(s))) { + Image img = thumbnail(s.first()); + if (img != null) { + thumbs.put(key(s), img); + } + } + grid.add(card(s)); + } + thumbnails(new ArrayList(shown), 0); + } + + private List visible() { + String q = Text.lower(filter.getText().trim()); + List out = new ArrayList(); + for (Screen s : screens) { + if (q.length() == 0 || Text.lower(s.name).indexOf(q) >= 0) { + out.add(s); + } + } + return out; + } + + private void countStatus() { + int n = chosen().size(); + status.setText(n + " of " + screens.size() + " screens chosen"); + next.setText(step == STEPS.length - 1 ? writeLabel() : "Next"); + } + + private Component card(final Screen s) { + final Container card = new Container(new BorderLayout(), s.chosen ? "WizardCardOn" : "WizardCard"); + final Label thumb = new Label("", "WizardThumb"); + thumb.getAllStyles().setAlignment(Component.CENTER); + int tw = CN.convertToPixels(24); + int th = CN.convertToPixels(40); + thumb.setPreferredW(tw + thumb.getStyle().getHorizontalPadding()); + thumb.setPreferredH(th); + Image cached = thumbs.get(key(s)); + if (cached != null) { + thumb.setIcon(cached); + } + thumb.setName("thumb:" + key(s)); + StringBuilder meta = new StringBuilder(); + for (int i = 0; i < s.frames.size(); i++) { + Map f = s.frames.get(i); + if (i > 0) { + meta.append(" + "); + } + meta.append(f.get("kind")); + Object b = f.get("bounds"); + if (b instanceof List && ((List) b).size() == 4) { + meta.append(' ').append(num(((List) b).get(2))).append('x').append(num(((List) b).get(3))); + } + } + Label name = new Label(s.name, "WizardCardName"); + Label check = new Label("", "WizardCardMeta"); + FontImage.setMaterialIcon(check, s.chosen ? FontImage.MATERIAL_CHECK_BOX : FontImage.MATERIAL_CHECK_BOX_OUTLINE_BLANK); + Container text = BoxLayout.encloseY(name, new Label(meta.toString(), "WizardCardMeta")); + card.add(BorderLayout.CENTER, FlowLayout.encloseCenter(thumb)); + card.add(BorderLayout.SOUTH, BorderLayout.centerEastWest(text, check, null)); + Button lead = new Button(); + lead.setUIID("Container"); + lead.addActionListener(e -> { + s.chosen = !s.chosen; + card.setUIID(s.chosen ? "WizardCardOn" : "WizardCard"); + FontImage.setMaterialIcon(check, s.chosen ? FontImage.MATERIAL_CHECK_BOX + : FontImage.MATERIAL_CHECK_BOX_OUTLINE_BLANK); + countStatus(); + form.revalidateLater(); + }); + card.add(BorderLayout.NORTH, lead); + card.setLeadComponent(lead); + return card; + } + + private static String key(Screen s) { + return String.valueOf(s.first().get("id")); + } + + /// Renders the thumbnails a few at a time, so a design with a hundred screens shows its + /// grid at once and fills it in rather than freezing while it draws them all. + private void thumbnails(final List todo, final int from) { + if (from >= todo.size() || step != 1) { + return; + } + int end = Math.min(todo.size(), from + 6); + for (int i = from; i < end; i++) { + Screen s = todo.get(i); + String k = key(s); + Image img = thumbs.get(k); + if (img == null) { + img = thumbnail(s.first()); + if (img != null) { + thumbs.put(k, img); + } + } + Label l = (Label) find(body, "thumb:" + k); + if (l != null && img != null && l.getIcon() == null) { + l.setIcon(img); + } + } + form.revalidateLater(); + CN.callSerially(() -> thumbnails(todo, end)); + } + + private Image thumbnail(Map frame) { + ImportSession s = service.getSession(); + Object b = frame.get("bounds"); + if (s == null || !(b instanceof List) || ((List) b).size() != 4) { + return null; + } + List bl = (List) b; + ImportSession.Variant v = new ImportSession.Variant(String.valueOf(frame.get("id")), ImportSession.Kind.PHONE); + v.originX = dbl(bl.get(0)); + v.originY = dbl(bl.get(1)); + v.width = Math.max(1, dbl(bl.get(2))); + v.height = Math.max(1, dbl(bl.get(3))); + int tw = CN.convertToPixels(24); + int th = CN.convertToPixels(40); + double f = Math.min(tw / v.width, th / v.height); + int w = Math.max(1, (int) (v.width * f)); + int h = Math.max(1, (int) (v.height * f)); + // Text drawn straight at a few pixels a line runs its glyphs together; drawn at three + // times the size and scaled down, it reads as a smooth, faithful miniature. + Image big = Preview.designImage(s, v, w * 3, h * 3); + return big == null ? null : big.scaled(w, h); + } + + private static double dbl(Object o) { + return o instanceof Number ? ((Number) o).doubleValue() : 0; + } + + private static Component find(Container c, String name) { + for (int i = 0; i < c.getComponentCount(); i++) { + Component k = c.getComponentAt(i); + if (name.equals(k.getName())) { + return k; + } + if (k instanceof Container) { + Component f = find((Container) k, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private static String num(Object o) { + return o instanceof Number ? String.valueOf(Math.round(((Number) o).doubleValue())) : String.valueOf(o); + } + + // ---- the review step ---- + + /// A compact drop-down of the chosen screens, numbered, beside previous and next: every + /// screen is two clicks away and the bar stays one line high however many there are. + private Component screenSwitcher() { + final List c = chosen(); + int at = Math.max(0, c.indexOf(active)); + final ComboBox pick = new ComboBox(); + pick.setUIID("WizardScreenPick"); + pick.setName("screens"); + for (int i = 0; i < c.size(); i++) { + Screen sc = c.get(i); + pick.addItem((i + 1) + ". " + sc.name + (sc.frames.size() > 1 ? " (" + sc.frames.size() + " sizes)" : "")); + } + pick.setSelectedIndex(at); + pick.addActionListener(e -> { + int i = pick.getSelectedIndex(); + if (i >= 0 && i < c.size()) { + show(c.get(i)); + } + }); + Button prev = icon(FontImage.MATERIAL_CHEVRON_LEFT, "Previous screen"); + prev.setEnabled(at > 0); + prev.addActionListener(e -> show(c.get(Math.max(0, c.indexOf(active) - 1)))); + Button nxt = icon(FontImage.MATERIAL_CHEVRON_RIGHT, "Next screen"); + nxt.setEnabled(at < c.size() - 1); + nxt.addActionListener(e -> show(c.get(Math.min(c.size() - 1, c.indexOf(active) + 1)))); + Container bar = new Container(LiveView.row(Component.LEFT)); + bar.addAll(new Label("Screen", "WorkbenchHint"), prev, pick, nxt, new Label("of " + c.size(), "WorkbenchHint")); + bar.setUIID("Container"); + return bar; + } + + /// Reviews another of the chosen screens. Changes made to the last one are kept: they + /// are overrides on its own layers, which the session holds for every screen. + void show(Screen s) { + if (s == active) { // NOPMD CompareObjectsWithEquals - identity + return; + } + scope(s); + go(2); + } + + // ---- the write step ---- + + private Component writePage() { + List c = chosen(); + Container p = page(c.size() > 1 ? "Write " + c.size() + " forms" : "Write the form", + "The base classes and the stylesheets are rewritten by every import; the subclasses are yours to" + + " edit and are written only the first time."); + ImportSession s = service.getSession(); + if (packageName.getText().length() == 0 && s != null && s.getCode() != null) { + packageName.setText(s.getCode().packageName); + } + if (c.size() <= 1) { + Screen one = c.isEmpty() ? null : c.get(0); + if (className.getText().length() == 0) { + className.setText(one != null ? one.className : s != null && s.getCode() != null ? s.getCode().className : ""); + } + p.add(new Label("Class", "WorkbenchFieldLabel")); + p.add(detached(className)); + } + p.add(new Label("Package", "WorkbenchFieldLabel")); + p.add(detached(packageName)); + p.add(new Label("Into", "WorkbenchFieldLabel")); + updateInto(); + p.add(detached(into)); + if (c.size() > 1) { + p.add(new Label("Forms", "WorkbenchFieldLabel")); + for (Screen sc : c) { + p.add(new Label(sc.className + " from \"" + sc.name + "\"", "WorkbenchHint")); + } + } + countStatus(); + return p; + } + + /// Takes an application's folder: the module that holds its sources (`common` in a Maven + /// project) and, when no package is set yet, the application's own package. + void useProject(String folder) { + File f = new File(folder); + File common = new File(f, "common"); + File module = new File(common, "src/main").isDirectory() ? common : f; + projectDir = module.getAbsolutePath(); + if (packageName.getText().trim().length() == 0) { + String pkg = appPackage(module, f); + if (pkg != null) { + packageName.setText(pkg); + } + } + updateInto(); + } + + /// The package in codenameone_settings.properties, or null. + static String appPackage(File... dirs) { + for (File d : dirs) { + File props = new File(d, "codenameone_settings.properties"); + if (props.isFile()) { + java.util.Properties p = new java.util.Properties(); + try (java.io.InputStream in = new java.io.FileInputStream(props)) { + p.load(in); + } catch (java.io.IOException e) { + continue; + } + String pkg = p.getProperty("codename1.packageName"); + if (pkg != null && pkg.trim().length() > 0) { + return pkg.trim(); + } + } + } + return null; + } + + private static TextField figmaTokenField() { + TextField t = new TextField("", "figd_...", 30, TextField.PASSWORD); + String env = System.getenv("FIGMA_TOKEN"); + if (env != null) { + t.setText(env); + } + return t; + } + + TextField filterField() { + return filter; + } + + Container screenGrid() { + return grid; + } + + String intoText() { + return into.getText(); + } + + void setPackage(String pkg) { + packageName.setText(pkg); + updateInto(); + } + + private void updateInto() { + if (projectDir == null) { + into.setText("No Codename One project: the tool is started from one, by cn1:import-design."); + return; + } + String pkg = packageName.getText().trim(); + into.setText(new File(projectDir, "src/main/java" + (pkg.length() == 0 ? "" : "/" + pkg.replace('.', '/'))) + .getPath()); + if (into.getParent() != null) { + into.getParent().revalidateLater(); + } + } + + /// The fields outlive the page: a second visit to it (Back, then Next again) builds a new + /// page while the old one still holds them, and adding them again threw. + private static Component detached(Component c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + private void write() { + final String dir = projectDir == null ? "" : projectDir; + if (dir.length() == 0) { + status.setText("There is no Codename One project to write into."); + form.revalidateLater(); + return; + } + final List c = chosen(); + if (c.size() <= 1 && className.getText().trim().length() > 0) { + if (c.isEmpty()) { + Map set = new LinkedHashMap(); + set.put("className", className.getText().trim()); + Map a = new LinkedHashMap(); + a.put("set", set); + if (!ok(service.call("options", a))) { + return; + } + } else { + c.get(0).className = className.getText().trim(); + } + } + writing = true; + next.setEnabled(false); + back.setEnabled(false); + writeFrom(c, 0, dir, new ArrayList()); + } + + /// Writes one screen and schedules the next, so the window says how far it got. + private void writeFrom(final List c, final int i, final String dir, final List done) { + if (i >= c.size() && !c.isEmpty()) { + done(dir, done); + return; + } + Screen s = c.isEmpty() ? null : c.get(i); + status.setText(c.size() > 1 ? "Writing " + (i + 1) + " of " + c.size() + ": " + s.className : "Writing..."); + status.getParent().revalidateLater(); + if (s != null && !scope(s)) { + fail(); + return; + } + if (s == null && !ok(service.call("run", null))) { + fail(); + return; + } + Map e = new LinkedHashMap(); + e.put("dir", new File(dir).getAbsolutePath()); + Map r = service.call("emit", e); + if (!ok(r)) { + fail(); + return; + } + report(s, r.get("written"), done); + if (c.isEmpty()) { + done(dir, done); + return; + } + CN.callSerially(() -> writeFrom(c, i + 1, dir, done)); + } + + private void fail() { + writing = false; + next.setEnabled(true); + back.setEnabled(true); + } + + private void report(Screen s, Object written, List done) { + ImportSession session = service.getSession(); + GeneratedCode code = session.getCode(); + String cls = code.packageName + "." + code.className; + System.out.println("Imported " + (s == null ? new File(openedPath).getName() : "\"" + s.name + "\"") + " as " + cls); + done.add(cls); + if (written instanceof List) { + for (Object f : (List) written) { + System.out.println(" wrote " + f); + } + } + for (Issue is : session.getIssues()) { + if (!is.resolved) { + System.out.println(" " + is.severity + " [" + is.stage + "] " + is.message); + } + } + System.out.flush(); + } + + private void done(String dir, List classes) { + writing = false; + Container c = page("Done", (classes.size() == 1 ? classes.get(0) + " was" : classes.size() + " forms were") + + " written into " + dir + "."); + for (String cls : classes) { + Label l = new Label(cls, "WorkbenchHint"); + FontImage.setMaterialIcon(l, FontImage.MATERIAL_CHECK_CIRCLE); + c.add(l); + } + body.removeAll(); + body.add(BorderLayout.CENTER, c); + back.setVisible(false); + next.setEnabled(true); + next.setText("Close"); + finished = true; + status.setText(""); + form.revalidateLater(); + } + + private boolean ok(Map r) { + if (r != null && r.get("error") != null) { + status.setText(String.valueOf(r.get("error"))); + form.revalidateLater(); + return false; + } + return true; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/Issue.java b/maven/design-import/src/main/java/com/codename1/designimport/Issue.java new file mode 100644 index 00000000000..cbbfc73d6f5 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/Issue.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// A warning or TODO raised while importing: something the importer guessed, could not +/// express, or changed. The checklist shows them grouped by stage, and an LLM reads them +/// through `designimport_issues` and resolves them one at a time. +public final class Issue { + /// How much a person should care. + public enum Severity { + INFO, WARNING, TODO + } + + public final String id; + public final String stage; + public final Severity severity; + public final String nodeId; + /// A stable machine readable kind, such as `low-confidence-role` or `css-blend-mode`. + public final String kind; + public final String message; + /// What resolving it means, in words; the fix action for kinds that have one. + public final String fix; + public boolean resolved; + /// Where the element it is about lies in its frame, in design pixels: x, y, width, + /// height. Kept apart from the node because the node may be gone by the time anyone + /// looks (chrome is left out, a masked group becomes one picture). Null when the issue is + /// about no element. + double[] bounds; + + Issue(String id, String stage, Severity severity, String nodeId, String kind, String message, String fix) { + this.id = id; + this.stage = stage; + this.severity = severity; + this.nodeId = nodeId; + this.kind = kind; + this.message = message; + this.fix = fix; + } + + /// The issue as JSON-ready values. + public Map toMap() { + Map m = new LinkedHashMap(); + m.put("id", id); + m.put("stage", stage); + m.put("severity", Text.lower(severity.name())); + if (nodeId != null) { + m.put("node", nodeId); + } + m.put("kind", kind); + m.put("message", message); + if (fix != null) { + m.put("fix", fix); + } + if (bounds != null) { + List b = new ArrayList(); + for (int i = 0; i < 4; i++) { + b.add(Double.valueOf(bounds[i])); + } + m.put("bounds", b); + } + m.put("resolved", Boolean.valueOf(resolved)); + return m; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/JavaEmitter.java b/maven/design-import/src/main/java/com/codename1/designimport/JavaEmitter.java new file mode 100644 index 00000000000..550232ce1b3 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/JavaEmitter.java @@ -0,0 +1,519 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// Stage 7: writes the form. +/// +/// The output is a pair: `Base`, regenerated on every import, and ``, written +/// once and never overwritten, where the developer's code lives. The base class keeps one +/// field per meaningful component, built once, and an arrangement method per variant that +/// lays those fields out; a size change re-runs the arrangement, so a phone turning into a +/// tablet (or a desktop window being resized) re-lays the same components, keeping what the +/// user typed. The responsive levers are constants at the top of the class. +final class JavaEmitter { + private final ImportSession session; + private final StringBuilder fields = new StringBuilder(); + private final StringBuilder create = new StringBuilder(); + private final List declared = new ArrayList(); + private final Map fieldTypes = new LinkedHashMap(); + private int locals; + private int unnamed; + private boolean usesSpan; + private boolean usesSwitch; + private boolean usesRadio; + private boolean radioSelected; + private boolean usesImages; + + JavaEmitter(ImportSession session) { + this.session = session; + } + + String mm(double px) { + double v = px / session.getEffectiveScale() * StyleStage.MM_PER_DP; + return Text.num(v) + "f"; + } + + /// The sink writing one arrangement method. + final class JavaSink implements Sink { + final StringBuilder body = new StringBuilder(); + String contentVar; + final DNode root; + final double designWidth; + + JavaSink(DNode root, double designWidth) { + this.root = root; + this.designWidth = designWidth; + } + + @Override + public Object leaf(DNode n, DNode parent) { + String f = n.fieldName; + if (f == null) { + f = "part" + (++unnamed); + n.fieldName = f; + } + if (!declared.contains(f)) { + declared.add(f); + declareLeaf(n, parent, f); + } + return "take(" + f + ")"; + } + + @Override + public Object container(DNode n, int columns) { + String v = n == root ? "root" : "c" + (++locals); // NOPMD CompareObjectsWithEquals - identity + String layout; + switch (n.layout) { + case BOX_X: + layout = n.centerCross ? "BoxLayout.xCenter()" : "new BoxLayout(BoxLayout.X_AXIS)"; + break; + case BORDER: + layout = n.centerAbsolute ? "BorderLayout.absolute()" : "new BorderLayout()"; + break; + case GRID: { + double cell = (n.w - n.padding[1] - n.padding[3]) / Math.max(1, n.columns); + boolean adaptive = n.align == DNode.Align.FILL || n.w >= designWidth * 0.8; + String cols = adaptive ? "columns(widthMm * " + Text.num(n.w / designWidth) + "f, " + mm(cell) + + ", " + mm(n.gap) + ", " + n.columns + ", " + n.children.size() + ")" : String.valueOf(n.columns); + body.append(" int ").append(v).append("Cols = ").append(cols).append(";\n"); + layout = "new GridLayout((" + n.children.size() + " + " + v + "Cols - 1) / " + v + "Cols, " + v + "Cols)"; + break; + } + case LAYERED: + layout = "new LayeredLayout()"; + break; + case FLOW: + layout = "new FlowLayout()"; + break; + default: + layout = "new BoxLayout(BoxLayout.Y_AXIS)"; + } + body.append(" Container ").append(v).append(" = new Container(").append(layout).append(", ") + .append(Text.javaString(n.uiid == null ? "Container" : n.uiid)).append(");\n"); + if (n.fieldName != null && n.role != DNode.Role.SCREEN) { + body.append(" ").append(v).append(".setName(").append(Text.javaString(n.fieldName)).append(");\n"); + } + if (n.imageBackground && n.imageName != null) { + usesImages = true; + body.append(" background(").append(v).append(", ").append(Text.javaString(n.imageName)).append(");\n"); + } + boolean content = n.role == DNode.Role.SCREEN || ("CENTER".equals(n.slot) && n.layout == DNode.Layout.BOX_Y); + if (content && n.layout == DNode.Layout.BOX_Y) { + body.append(" ").append(v).append(".setScrollableY(SCROLLABLE);\n"); + } + if (n.scrollX) { + body.append(" ").append(v).append(".setScrollableX(true);\n"); + } + if (content && (contentVar == null || n != root)) { // NOPMD CompareObjectsWithEquals - identity + contentVar = v; + } + return v; + } + + @Override + public void add(Object parent, DNode parentNode, Object child, DNode childNode, String constraint, + double[] margins, int wrap) { + String c = (String) child; + if (wrap != 0) { + c = (wrap == 2 ? "FlowLayout.encloseCenter(" : wrap == 3 ? "FlowLayout.encloseRight(" : "FlowLayout.encloseIn(") + + c + ")"; + } + // Always set, zeros included: the arrangements share their components, so a + // margin one of them sets must not stay behind in another (LiveSink does the same). + { + c = "margin(" + c + ", " + mm(margins[0]) + ", " + mm(margins[1]) + ", " + mm(margins[2]) + ", " + + mm(margins[3]) + ")"; + } + body.append(" ").append(parent).append(".add("); + if (constraint != null) { + body.append("BorderLayout.").append(constraint).append(", "); + } + body.append(c).append(");\n"); + } + + @Override + public void layered(Object parent, Object child, double[] insets) { + String c = (String) child; + if (c.startsWith("take(")) { + c = c.substring(5, c.length() - 1); + } + body.append(" ((LayeredLayout) ").append(parent).append(".getLayout()).setInsets(").append(c) + .append(", ").append(Text.javaString(inset(insets[0]) + " " + inset(insets[1]) + " " + + inset(insets[2]) + " " + inset(insets[3]))).append(");\n"); + } + + @Override + public void overlay(Object scrim, DNode n) { + String c = (String) scrim; + body.append(" // \"").append(plain(n.name == null ? n.id : n.name)) + .append("\" dims the form under a popup; a tap outside the popup closes it.\n"); + body.append(" ").append(c).append(".addPointerReleasedListener(e -> {\n"); + body.append(" if (").append(c).append(".getComponentAt(e.getX(), e.getY()) == ").append(c).append(") {\n"); + body.append(" ").append(c).append(".setVisible(false);\n"); + body.append(" ").append(c).append(".getParent().repaint();\n"); + body.append(" }\n"); + body.append(" });\n"); + } + + /// Letters, digits and spaces only, for a comment. + private String plain(String s) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + b.append(ch < 128 && (Character.isLetterOrDigit(ch) || ch == ' ') ? ch : ' '); + } + return b.toString().trim(); + } + + private String inset(double px) { + if (px < 0) { + return "auto"; + } + String m = mm(px); + return m.substring(0, m.length() - 1) + "mm"; + } + } + + private void declareLeaf(DNode n, DNode parent, String f) { + DNode t = StyleStage.textChild(n); + String text = t == null ? "" : t.text; + String type; + String init; + boolean tab = parent != null && parent.role == DNode.Role.TABS; + DNode icon = firstPicture(n); + DNode icon0 = icon; + if (n.role == DNode.Role.CHECKBOX && icon != null && LiveSink.boxLike(icon, t)) { + // The drawn square is the check box's own box, which the theme draws. + icon = null; + } + if (tab || n.role == DNode.Role.BUTTON) { + type = "Button"; + init = "new Button(" + Text.javaString(text) + ")"; + } else if (n.role == DNode.Role.TEXT_FIELD) { + type = "TextField"; + init = "new TextField(\"\", " + Text.javaString(text) + ", 20, TextField.ANY)"; + + } else if (n.role == DNode.Role.SWITCH) { + type = "Switch"; + init = "new Switch()"; + usesSwitch = true; + } else if (n.role == DNode.Role.CHECKBOX && n.radio) { + type = "RadioButton"; + init = "RadioButton.createToggle(" + Text.javaString(text) + ", radios)"; + radioSelected = icon != null && !LiveSink.boxLike(icon, t); + icon = null; + if (!usesRadio) { + // One set per form: a design with two sets of choices on one screen is rare, + // and splitting this group is a one-line edit in the subclass. + fields.append(" protected final ButtonGroup radios = new ButtonGroup();\n"); + } + usesRadio = true; + } else if (n.role == DNode.Role.CHECKBOX) { + type = "CheckBox"; + // A control the design draws itself keeps its drawing: a toggle shows the picture + // and no check box graphic of the theme's. + init = icon != null ? "CheckBox.createToggle(" + Text.javaString(text) + ")" + : "new CheckBox(" + Text.javaString(text) + ")"; + } else if (n.role == DNode.Role.LABEL && n.multiline) { + type = "SpanLabel"; + init = "new SpanLabel(" + Text.javaString(n.text) + ")"; + usesSpan = true; + } else if (n.role == DNode.Role.LABEL) { + type = "Label"; + init = "new Label(" + Text.javaString(n.text) + ")"; + } else if (n.role == DNode.Role.DIVIDER) { + type = "Container"; + init = "new Container()"; + } else { + type = "Label"; + init = "new Label()"; + } + fieldTypes.put(f, type); + fields.append(" protected ").append(type).append(' ').append(f).append(";\n"); + create.append(" ").append(f).append(" = ").append(init).append(";\n"); + if ("SpanLabel".equals(type)) { + create.append(" ").append(f).append(".setTextUIID(").append(Text.javaString(n.uiid)).append(");\n"); + } else if (n.uiid != null) { + create.append(" ").append(f).append(".setUIID(").append(Text.javaString(n.uiid)).append(");\n"); + } + create.append(" ").append(f).append(".setName(").append(Text.javaString(f)).append(");\n"); + if ("TextField".equals(type) && n.uiid != null && t != null) { + create.append(" ").append(f).append(".getHintLabel().setUIID(").append(Text.javaString(n.uiid + "Hint")) + .append(");\n"); + } + DNode picture = n.imageName != null ? n : icon; + if ("Switch".equals(type)) { + int[] ink = LiveSink.switchInk(n); + create.append(" switchInk(").append(f).append(", 0x").append(Integer.toHexString(ink[0])).append(", 0x") + .append(Integer.toHexString(ink[1])).append(");\n"); + } + if ("TextField".equals(type) && n.multiline) { + create.append(" ").append(f).append(".setSingleLineTextArea(false);\n"); + create.append(" ").append(f).append(".setRows(").append(LiveSink.rows(n)).append(");\n"); + create.append(" ").append(f).append(".setGrowByContent(false);\n"); + // The text, and with it the hint, starts at the top as the design draws it. + create.append(" ").append(f).append(".setVerticalAlignment(Component.TOP);\n"); + } + if ("RadioButton".equals(type)) { + picture = null; + int[] ink = LiveSink.radioInk(n); + create.append(" radioIcons(").append(f).append(", ").append(mm(icon0 == null ? n.h : icon0.h)) + .append(", 0x").append(Integer.toHexString(ink[0])).append(", 0x").append(Integer.toHexString(ink[1])) + .append(");\n"); + if (radioSelected) { + create.append(" ").append(f).append(".setSelected(true);\n"); + } + } + if (picture != null && picture.imageName != null && !"Container".equals(type) && !"Switch".equals(type) + && !"TextField".equals(type) && !"SpanLabel".equals(type)) { + usesImages = true; + create.append(" ").append(f).append(".setIcon(image(").append(Text.javaString(picture.imageName)) + .append(", ").append(mm(picture.w)).append(", ").append(mm(picture.h)).append("));\n"); + } + if (tab) { + create.append(" ").append(f).append(".setTextPosition(Component.BOTTOM);\n"); + } + } + + private static DNode firstPicture(DNode n) { + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if (c.imageName != null) { + return c; + } + DNode d = firstPicture(c); + if (d != null) { + return d; + } + } + return null; + } + + /// The base class source. + String base(String className) { + List vs = session.byWidth(); + List methods = new ArrayList(); + List built = new ArrayList(); + StringBuilder build = new StringBuilder(); + for (int i = 0; i < vs.size(); i++) { + ImportSession.Variant v = vs.get(i); + if (v.root == null) { + continue; + } + JavaSink sink = new JavaSink(v.root, v.width); + locals = 0; + new FormWalker(session, sink, v.width, v.width).walk(v.root); + String m = vs.size() == 1 ? "build" : "build" + Text.pascal(Text.lower(v.kind.name())); + methods.add(m); + built.add(v); + build.append(" /// The ").append(Text.lower(v.kind.name())).append(" arrangement, from \"") + .append(comment(v.root.name)).append("\" (").append(Text.num(v.width)).append(" x ") + .append(Text.num(v.height)).append(" design px).\n"); + build.append(" protected Container ").append(m).append("(float widthMm) {\n"); + build.append(sink.body); + build.append(" content = ").append(sink.contentVar == null ? "root" : sink.contentVar).append(";\n"); + build.append(" return root;\n }\n\n"); + } + StringBuilder sb = new StringBuilder(); + sb.append("package ").append(session.packageName).append(";\n\n"); + sb.append("import com.codename1.ui.*;\n"); + sb.append("import com.codename1.ui.events.ActionEvent;\n"); + sb.append("import com.codename1.ui.events.ActionListener;\n"); + sb.append("import com.codename1.ui.layouts.*;\n"); + sb.append("import com.codename1.ui.plaf.Border;\n"); + sb.append("import com.codename1.ui.plaf.Style;\n"); + if (usesSpan) { + sb.append("import com.codename1.components.SpanLabel;\n"); + } + if (usesSwitch) { + sb.append("import com.codename1.components.Switch;\n"); + } + if (usesImages) { + sb.append("import java.io.IOException;\nimport java.io.InputStream;\n"); + } + sb.append("\n/// Generated by Codename One Design Import from ").append(comment(session.getSourceName())) + .append(".\n///\n/// Regenerating the import overwrites this class. Put your own code in [") + .append(className).append("], which extends it.\n"); + sb.append("public class ").append(className).append("Base extends Form {\n"); + sb.append(" // Responsive levers. The importer writes them from its options; change them here or there.\n"); + sb.append(" /// Content is never wider than this, and is centred when the screen is; 0 turns it off.\n"); + sb.append(" protected static final float MAX_CONTENT_WIDTH_MM = ") + .append(Text.num(session.contentCapDp() * StyleStage.MM_PER_DP)).append("f;\n"); + sb.append(" /// The content column scrolls when it is taller than the screen.\n"); + sb.append(" protected static final boolean SCROLLABLE = ").append(session.scrollable).append(";\n"); + sb.append(" /// Grids keep their design cell width and gain or lose columns with the screen.\n"); + sb.append(" protected static final boolean ADAPTIVE_GRID = ").append(session.adaptiveGrid).append(";\n"); + for (int i = 1; i < built.size(); i++) { + String kind = built.get(i).kind.name(); + sb.append(" /// At or above this width the ").append(Text.lower(kind)).append(" arrangement is used.\n"); + sb.append(" protected static final float ").append(kind).append("_BREAKPOINT_MM = ") + .append(Text.num(session.minWidthDp(built.get(i).kind) * StyleStage.MM_PER_DP)).append("f;\n"); + } + sb.append('\n'); + sb.append(fields); + sb.append(" /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM.\n"); + sb.append(" protected Container content;\n"); + sb.append(" private float arrangedWidthMm = -1;\n\n"); + sb.append(" public ").append(className).append("Base() {\n"); + sb.append(" super(new BorderLayout());\n"); + sb.append(" setScrollable(false);\n"); + sb.append(" getTitleArea().setUIID(\"Container\");\n"); + sb.append(" getContentPane().setUIID(\"Container\");\n"); + sb.append(" createComponents();\n"); + sb.append(" arrange();\n"); + sb.append(" addSizeChangedListener(new ActionListener() {\n"); + sb.append(" public void actionPerformed(ActionEvent evt) {\n"); + sb.append(" arrange();\n"); + sb.append(" }\n"); + sb.append(" });\n"); + sb.append(" }\n\n"); + sb.append(" /// Creates every component once; the arrangements only lay them out.\n"); + sb.append(" protected void createComponents() {\n").append(create).append(" }\n\n"); + sb.append(" /// Lays the components out for the current width. Runs again whenever the size changes.\n"); + sb.append(" protected void arrange() {\n"); + // The form's own width once it has one: a form in a window or beside another pane is + // narrower than the display. The display's before the first layout. + sb.append(" int widthPx = getWidth() > 0 ? getWidth() : CN.getDisplayWidth();\n"); + sb.append(" float widthMm = widthPx / (float) CN.convertToPixels(1f);\n"); + sb.append(" if (Math.abs(widthMm - arrangedWidthMm) < 1) {\n return;\n }\n"); + sb.append(" arrangedWidthMm = widthMm;\n"); + sb.append(" removeAll();\n"); + if (methods.size() > 1) { + // The widest arrangement whose breakpoint the screen reaches. + sb.append(" Container root;\n"); + for (int i = methods.size() - 1; i > 0; i--) { + sb.append(i == methods.size() - 1 ? " if" : " else if").append(" (widthMm >= ") + .append(built.get(i).kind.name()).append("_BREAKPOINT_MM) {\n root = ") + .append(methods.get(i)).append("(widthMm);\n }"); + } + sb.append(" else {\n root = ").append(methods.get(0)).append("(widthMm);\n }\n"); + } else if (methods.size() == 1) { + sb.append(" Container root = ").append(methods.get(0)).append("(widthMm);\n"); + } else { + sb.append(" Container root = new Container();\n"); + } + sb.append(" if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) {\n"); + sb.append(" float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2;\n"); + sb.append(" Style s = content.getAllStyles();\n"); + sb.append(" s.setPaddingUnit(Style.UNIT_TYPE_DIPS);\n"); + sb.append(" s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side);\n"); + sb.append(" s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side);\n"); + sb.append(" }\n"); + sb.append(" add(BorderLayout.CENTER, root);\n"); + sb.append(" revalidate();\n"); + sb.append(" }\n\n"); + sb.append(build); + // Helpers. + sb.append(" /// Detaches a component from the previous arrangement so the next one can add it.\n"); + sb.append(" protected static T take(T c) {\n"); + sb.append(" if (c.getParent() != null) {\n c.remove();\n }\n return c;\n }\n\n"); + sb.append(" /// Sets margins in millimetres: top, right, bottom, left.\n"); + sb.append(" protected static Component margin(Component c, float top, float right, float bottom, float left) {\n"); + sb.append(" Style s = c.getAllStyles();\n"); + sb.append(" s.setMarginUnit(Style.UNIT_TYPE_DIPS);\n"); + sb.append(" s.setMargin(top, bottom, left, right);\n"); + sb.append(" return c;\n }\n\n"); + sb.append(" /// How many grid columns of the design's cell width fit, between 1 and max.\n"); + sb.append(" protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) {\n"); + sb.append(" if (!ADAPTIVE_GRID) {\n return designColumns;\n }\n"); + sb.append(" int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f);\n"); + sb.append(" return Math.max(1, Math.min(max, c));\n }\n"); + if (usesSwitch) { + sb.append("\n /// The track and thumb in the design's colours; on swaps them so the change shows.\n"); + sb.append(" protected static void switchInk(Switch sw, int track, int thumb) {\n"); + sb.append(" Style off = sw.getUnselectedStyle();\n off.setBgColor(track);\n off.setFgColor(thumb);\n"); + sb.append(" Style on = sw.getSelectedStyle();\n on.setBgColor(thumb);\n on.setFgColor(0xffffff);\n }\n"); + } + if (usesRadio) { + sb.append("\n /// A ring, and a ring with a dot when chosen, in the design's colours.\n"); + sb.append(" protected static void radioIcons(RadioButton rb, float sizeMm, int ring, int dot) {\n"); + sb.append(" Style s = new Style();\n s.setBgTransparency(0);\n s.setFgColor(ring);\n"); + sb.append(" rb.setIcon(FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_UNCHECKED, s, sizeMm));\n"); + sb.append(" Style on = new Style(s);\n on.setFgColor(dot);\n"); + sb.append(" rb.setPressedIcon(FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_CHECKED, on, sizeMm));\n }\n"); + } + if (usesImages) { + sb.append("\n /// Opens a generated image. Override it to load the pictures from somewhere else.\n"); + sb.append(" protected InputStream resource(String name) {\n"); + sb.append(" return CN.getResourceAsStream(\"/\" + name);\n }\n"); + sb.append("\n /// Loads a generated image from the resources, sized in millimetres.\n"); + sb.append(" protected Image image(String name, float widthMm, float heightMm) {\n"); + sb.append(" try {\n"); + sb.append(" InputStream in = resource(name);\n"); + sb.append(" if (in == null) {\n return null;\n }\n"); + sb.append(" Image img = Image.createImage(in);\n"); + sb.append(" in.close();\n"); + sb.append(" return img.scaled(Math.max(1, CN.convertToPixels(widthMm)), Math.max(1, CN.convertToPixels(heightMm)));\n"); + sb.append(" } catch (IOException e) {\n return null;\n }\n }\n\n"); + sb.append(" /// Fills a container's background with a generated image.\n"); + sb.append(" protected void background(Container c, String name) {\n"); + sb.append(" try {\n"); + sb.append(" InputStream in = resource(name);\n"); + sb.append(" if (in == null) {\n return;\n }\n"); + sb.append(" // The picture has the design's corners and outline; a border would paint over it.\n"); + sb.append(" c.getAllStyles().setBorder(Border.createEmpty());\n"); + sb.append(" c.getAllStyles().setBgImage(Image.createImage(in));\n"); + sb.append(" c.getAllStyles().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);\n"); + sb.append(" in.close();\n"); + sb.append(" } catch (IOException e) {\n // The image is missing from the resources: leave the background plain.\n }\n }\n"); + } + sb.append("}\n"); + return sb.toString(); + } + + /// A design or file name made safe for a `///` comment: printable ASCII without the + /// backslash, since javac reads a backslash-u escape even inside a comment, and the + /// generated sources must stay ASCII. + static String comment(String s) { + StringBuilder b = new StringBuilder(); + for (int i = 0; s != null && i < s.length(); i++) { + char ch = s.charAt(i); + b.append(ch >= 32 && ch < 127 && ch != '\\' ? ch : ' '); + } + return b.toString().trim(); + } + + /// The class the developer owns, written only when it does not exist yet. + String user(String className) { + return "package " + session.packageName + ";\n\n" + + "/// The form imported from " + comment(session.getSourceName()) + ".\n///\n" + + "/// Design Import writes this class once and never touches it again: add behaviour here.\n" + + "/// The components are the protected fields of [" + className + "Base].\n" + + "public class " + className + " extends " + className + "Base {\n" + + " public " + className + "() {\n" + + " // Wire listeners here, for example:\n" + + " // someButton.addActionListener(e -> ...);\n" + + " }\n" + + "}\n"; + } + + Map fieldTypes() { + return fieldTypes; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/LayoutStage.java b/maven/design-import/src/main/java/com/codename1/designimport/LayoutStage.java new file mode 100644 index 00000000000..b142a33e845 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/LayoutStage.java @@ -0,0 +1,506 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtNode; +import java.util.ArrayList; +import java.util.List; + +/// Stage 4: settles each container's Codename One layout. +/// +/// What the design says outright wins over what the structure stage inferred: a Figma frame +/// with auto layout is a box with its own spacing and padding, a Sketch group with an +/// inferred layout is a row or a column. Overrides win over both. The stage then shapes the +/// screen itself -- toolbar to the north, tab bar to the south, the rest in a scrolling +/// column -- and names the fields the generated form keeps. +final class LayoutStage { + /// Finds the screens that are a popup over another form: a layer on top of the others that + /// covers the screen with a see-through dark (or light) fill and holds the popup. Kits draw a + /// sheet or dialog this way, over a copy of the form it opens from. The layer stays in the + /// form, so the screen looks as designed, and a tap on it outside the popup dismisses it. + static void markOverlays(ImportSession s, DNode root) { + paintOrder(root); + markOverlays(s, root, root); + } + + private static void markOverlays(ImportSession s, DNode root, DNode n) { + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if (n.layout == DNode.Layout.LAYERED && i > 0 && isScrim(root, c)) { + c.overlay = true; + DNode popup = c.children.get(0); + if (c.children.size() == 1 && popup.bottom() >= c.bottom() - 2 && popup.w >= c.w * 0.9) { + // A sheet: it stays on the bottom edge whatever the screen's height. + c.layout = DNode.Layout.BORDER; + c.layoutLocked = true; + popup.slot = "SOUTH"; + } + s.issue(STAGE, Issue.Severity.INFO, c, "overlay", + "\"" + nm(popup) + "\" is a popup over the screen: \"" + nm(c) + + "\" dims the form under it. A tap outside the popup closes it.", + "Accept, or show the popup from the form it opens over with a Sheet or Dialog."); + continue; + } + markOverlays(s, root, c); + } + } + + /// Children of a LayeredLayout overlap, so they go in the order the design paints them; + /// the reading order the structure stage sorted them into would put a backdrop on top. + static void paintOrder(DNode n) { + if (n.layout == DNode.Layout.LAYERED) { + java.util.List l = n.children; + for (int i = 1; i < l.size(); i++) { + DNode k = l.get(i); + int j = i - 1; + while (j >= 0 && zOf(l.get(j)) > zOf(k)) { + l.set(j + 1, l.get(j)); + j--; + } + l.set(j + 1, k); + } + } + for (int i = 0; i < n.children.size(); i++) { + paintOrder(n.children.get(i)); + } + } + + /// A group the structure stage made up has no paint order of its own: it paints where its + /// first child does. + private static int zOf(DNode n) { + if (n.z > 0 || n.children.isEmpty()) { + return n.z; + } + int z = Integer.MAX_VALUE; + for (int i = 0; i < n.children.size(); i++) { + z = Math.min(z, zOf(n.children.get(i))); + } + return z; + } + + private static String nm(DNode n) { + return n.name == null ? n.id : n.name; + } + + static boolean isScrim(DNode root, DNode c) { + if (c.children.isEmpty() || c.background == null) { + return false; + } + boolean covers = c.w >= root.w * 0.95 && c.h >= root.h * 0.9; + boolean seeThrough = c.backgroundAlpha > 0.05 && c.backgroundAlpha < 0.9; + double area = 0; + for (int i = 0; i < c.children.size(); i++) { + area += c.children.get(i).w * c.children.get(i).h; + } + // The popup leaves most of the screen to the dimmed form. A designer's name for it says + // so too, when the backdrop is opaque or a blur that did not come through. + return covers && (seeThrough || namedPopup(c)) && area < c.w * c.h * 0.75; + } + + private static final String[] POPUP_WORDS = {"dialog", "popup", "pop-up", "pop up", "modal", "sheet", "alert", + "overlay", "scrim", "backdrop"}; + + /// Whether the layer or the one it holds is named like a popup. + static boolean namedPopup(DNode c) { + if (named(c.name)) { + return true; + } + for (int i = 0; i < c.children.size(); i++) { + if (named(c.children.get(i).name)) { + return true; + } + } + return false; + } + + private static boolean named(String name) { + if (name == null) { + return false; + } + String l = Text.lower(name); + for (String w : POPUP_WORDS) { + if (l.contains(w)) { + return true; + } + } + return false; + } + + static final String STAGE = "layout"; + private final ImportSession session; + private final List usedFields = new ArrayList(); + + LayoutStage(ImportSession session) { + this.session = session; + } + + void run(DNode root) { + hoistWrapper(root); + wrapLongText(root, root); + visit(root); + stretchRows(root); + fitToScreen(root, root); + screen(root); + name(root); + } + + private void visit(DNode n) { + for (int i = 0; i < n.children.size(); i++) { + visit(n.children.get(i)); + } + fromSource(n); + ImportSession.Override o = session.overrides.get(n.id); + if (o != null) { + if (o.layout != null) { + n.layout = o.layout; + n.layoutLocked = true; + if (n.layout == DNode.Layout.GRID && n.columns < 1) { + n.columns = Math.max(1, Math.min(4, n.children.size())); + } + } + if (o.columns != null) { + n.columns = o.columns.intValue(); + } + if (o.gap != null) { + n.gap = o.gap.doubleValue(); + for (int i = 1; i < n.children.size(); i++) { + n.children.get(i).before = n.gap; + } + } + if (o.align != null) { + n.align = o.align; + } + } + if (n.isContainer() && n.layout == DNode.Layout.NONE) { + n.layout = DNode.Layout.BOX_Y; + } + if (n.role == DNode.Role.BUTTON || n.role == DNode.Role.TEXT_FIELD) { + // A button's text and icon become one component, not a container of them. + n.layout = DNode.Layout.NONE; + } + } + + /// Figma auto layout and Sketch's inferred group layout are the designer's own answer. + private void fromSource(DNode n) { + ArtNode s = n.source; + if (s == null || n.layoutLocked || n.children.isEmpty()) { + return; + } + String mode = s.getAttribute("layoutMode"); + if ("HORIZONTAL".equals(mode) || "VERTICAL".equals(mode)) { + boolean wrap = "WRAP".equals(s.getAttribute("layoutWrap")); + n.layout = wrap ? DNode.Layout.FLOW : "HORIZONTAL".equals(mode) ? DNode.Layout.BOX_X : DNode.Layout.BOX_Y; + n.gap = ImportSession.dbl(s.getAttribute("itemSpacing"), n.gap); + n.padding[0] = ImportSession.dbl(s.getAttribute("paddingTop"), n.padding[0]); + n.padding[1] = ImportSession.dbl(s.getAttribute("paddingRight"), n.padding[1]); + n.padding[2] = ImportSession.dbl(s.getAttribute("paddingBottom"), n.padding[2]); + n.padding[3] = ImportSession.dbl(s.getAttribute("paddingLeft"), n.padding[3]); + n.centerCross = "CENTER".equals(s.getAttribute("counterAxisAlignItems")); + boolean anyAbsolute = false; + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + c.before = i == 0 ? 0 : n.gap; + ArtNode cs = c.source; + if (cs == null) { + continue; + } + if ("ABSOLUTE".equals(cs.getAttribute("layoutPositioning"))) { + anyAbsolute = true; + } + boolean fill = "STRETCH".equals(cs.getAttribute("layoutAlign")) + || "FILL".equals(cs.getAttribute(n.layout == DNode.Layout.BOX_X ? "layoutSizingVertical" : "layoutSizingHorizontal")); + if (fill && n.layout == DNode.Layout.BOX_Y) { + c.align = DNode.Align.FILL; + } + if ("1".equals(cs.getAttribute("layoutGrow")) + || "FILL".equals(cs.getAttribute(n.layout == DNode.Layout.BOX_X ? "layoutSizingHorizontal" : "layoutSizingVertical"))) { + c.grow = true; + } + } + if (anyAbsolute) { + n.layout = DNode.Layout.LAYERED; + } + if (n.layout == DNode.Layout.BOX_X) { + for (int i = 0; i < n.children.size(); i++) { + if (n.children.get(i).grow) { + n.layout = DNode.Layout.BORDER; + assignRowSlots(n, i); + break; + } + } + } + session.log("layout: " + n.name + " uses the design's auto layout (" + Text.lower(n.layout.name()) + ")"); + return; + } + String axis = s.getAttribute("groupLayout.axis"); + if (axis != null && (n.layout == DNode.Layout.BOX_X || n.layout == DNode.Layout.BOX_Y)) { + n.layout = "0".equals(axis) ? DNode.Layout.BOX_X : DNode.Layout.BOX_Y; + } + } + + /// A line of text drawn across most of the screen wraps on a narrower one instead of + /// running past its edge. + static void wrapLongText(DNode root, DNode n) { + if (n.role == DNode.Role.LABEL && n.text != null && n.w >= root.w * 0.6 && n.text.indexOf(' ') > 0) { + n.multiline = true; + } + for (int i = 0; i < n.children.size(); i++) { + wrapLongText(root, n.children.get(i)); + } + } + + /// A price and a wide button, a label and a field: when a row's button or field runs to the + /// row's far edge and takes most of it, it takes what the row has left on any screen, as + /// the design draws it, instead of shrinking to its text. + static void stretchRows(DNode n) { + if (n.layout == DNode.Layout.BOX_X && n.role != DNode.Role.TOOLBAR && n.role != DNode.Role.TABS + && !n.layoutLocked && n.children.size() >= 2 && n.children.size() <= 3) { + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + boolean control = c.role == DNode.Role.BUTTON || c.role == DNode.Role.TEXT_FIELD; + boolean last = i == n.children.size() - 1; + if (control && last && c.right() >= n.right() - 2 && c.w >= n.w * 0.4) { + n.layout = DNode.Layout.BORDER; + assignRowSlots(n, i); + if (n.layout == DNode.Layout.BORDER) { + // The row spans its column, or the control would have nothing to take. + n.align = DNode.Align.FILL; + } + break; + } + } + } + for (int i = 0; i < n.children.size(); i++) { + stretchRows(n.children.get(i)); + } + } + + /// A row whose child at `grow` stretches: what comes before it goes west, after it east. + private static void assignRowSlots(DNode n, int grow) { + List ch = n.children; + if (ch.size() > 3 || grow == 0 && ch.size() == 3) { + n.layout = DNode.Layout.BOX_X; + return; + } + for (int i = 0; i < ch.size(); i++) { + ch.get(i).slot = i < grow ? "WEST" : i == grow ? "CENTER" : "EAST"; + } + } + + /// Kits wrap a whole screen in one group. It paints nothing and holds everything, so its + /// children are the screen's: only then can a toolbar and a tab bar be the screen's own. + static void hoistWrapper(DNode root) { + while (root.children.size() == 1) { + DNode c = root.children.get(0); + boolean plain = c.background == null && c.gradientTo == null && c.borderColor == null && !c.shadow + && !c.imageBackground && !c.rasterize && c.text == null; + if (!plain || c.children.size() < 2 || c.w < root.w * 0.9 || c.h < root.h * 0.9 + || c.layout == DNode.Layout.LAYERED || hasOverlap(c)) { + return; + } + root.children.clear(); + root.children.addAll(c.children); + } + } + + private static boolean hasOverlap(DNode n) { + for (int i = 0; i < n.children.size(); i++) { + DNode a = n.children.get(i); + for (int j = i + 1; j < n.children.size(); j++) { + DNode b = n.children.get(j); + if (Math.min(a.right(), b.right()) - Math.max(a.x, b.x) > 1 + && Math.min(a.bottom(), b.bottom()) - Math.max(a.y, b.y) > 1) { + return true; + } + } + } + return false; + } + + /// Nothing is wider than the screen. A row that runs past its right edge is a strip that + /// scrolls sideways (the design shows its start); anything else that grew past it only + /// because of such a row is cut back to the screen. + static boolean fitToScreen(DNode root, DNode n) { + // Top down: a column is cut back before its children are looked at, and what is inside + // a strip that scrolls sideways is left as it is, since it scrolls. + boolean cut = false; + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + boolean row = c.layout == DNode.Layout.BOX_X || c.layout == DNode.Layout.FLOW + || c.layout == DNode.Layout.LAYERED && c.children.size() > 2; + // Only a strip is cut: a single layer hanging off the canvas is the designer's, + // drawn there on purpose, and is left as it is. + if (row && c.right() > root.right() + 1 && c.x < root.right()) { + c.scrollX = true; + // Kits keep the same margin on both sides of a column: a strip that starts 30 + // in ends 30 before the edge. + double left = c.x - root.x; + double edge = left < root.w / 3 ? root.right() - left : root.right(); + c.w = Math.max(1, edge - c.x); + cut = true; + } + if (!c.scrollX && fitToScreen(root, c)) { + cut = true; + } + } + // A plain group that only grew because of a strip shrinks back around what it holds, + // keeping its left inset on the right too, and its padding is measured again. + boolean plain = n.background == null && n.borderColor == null && n.gradientTo == null && !n.shadow; + if (cut && n != root && plain && !n.children.isEmpty()) { // NOPMD CompareObjectsWithEquals - the root itself + double minX = Double.MAX_VALUE; + double maxR = -Double.MAX_VALUE; + for (int i = 0; i < n.children.size(); i++) { + minX = Math.min(minX, n.children.get(i).x); + maxR = Math.max(maxR, n.children.get(i).right()); + } + n.w = Math.max(1, maxR + Math.max(0, minX - n.x) - n.x); + StructureStage.padding(n); + } + return cut; + } + + /// Toolbar north, tab bar south, the rest a scrolling column in the centre. + private void screen(DNode root) { + if (root.layoutLocked || root.layout == DNode.Layout.LAYERED) { + return; + } + List ch = root.children; + DNode north = !ch.isEmpty() && ch.get(0).role == DNode.Role.TOOLBAR ? ch.get(0) : null; + DNode south = ch.size() > 1 && ch.get(ch.size() - 1).role == DNode.Role.TABS ? ch.get(ch.size() - 1) : null; + if (north == null && south == null) { + return; + } + List middle = new ArrayList(); + for (int i = 0; i < ch.size(); i++) { + DNode c = ch.get(i); + if (c != north && c != south) { // NOPMD CompareObjectsWithEquals - identity + middle.add(c); + } + } + DNode content = StructureStage.union(middle.isEmpty() ? ch : middle, root.id + "-content"); + content.name = "Content"; + content.x = 0; + content.w = root.w; + content.children.addAll(middle); + content.role = DNode.Role.CONTAINER; + content.confidence = 1; + content.reason = "the screen between its bars"; + new StructureStage(session).column(content); + if (!middle.isEmpty()) { + middle.get(0).before = 0; + } + ch.clear(); + if (north != null) { + north.slot = "NORTH"; + ch.add(north); + } + content.slot = "CENTER"; + ch.add(content); + if (south != null) { + south.slot = "SOUTH"; + ch.add(south); + } + root.layout = DNode.Layout.BORDER; + session.log("layout: screen is a BorderLayout" + (north != null ? " with a toolbar" : "") + + (south != null ? " with a tab bar" : "")); + } + + /// Fields for the nodes a developer will want to reach: everything interactive, every + /// text, every container with a real name. Names come from the design where it has them. + private void name(DNode n) { + ImportSession.Override o = session.overrides.get(n.id); + String base = null; + if (o != null && o.fieldName != null) { + base = o.fieldName; + } else if (n.role == DNode.Role.SCREEN) { + base = null; + } else if (!Text.isGenericName(n.name)) { + base = Text.camel(n.name); + } else if (n.role == DNode.Role.BUTTON || n.role == DNode.Role.TEXT_FIELD || n.role == DNode.Role.LABEL + || n.role == DNode.Role.SWITCH || n.role == DNode.Role.CHECKBOX) { + String t = n.text != null ? n.text : n.allText(); + base = Text.camel((t.length() > 0 ? firstWords(t) + " " : "") + suffix(n.role)); + } else if (n.isContainer() || n.role == DNode.Role.IMAGE || n.role == DNode.Role.ICON) { + base = Text.camel(Text.lower(n.role.name()).replace('_', ' ')); + } + if (base != null) { + n.fieldName = unique(javaSafe(base)); + } + for (int i = 0; i < n.children.size(); i++) { + name(n.children.get(i)); + } + } + + private static String suffix(DNode.Role r) { + switch (r) { + case BUTTON: + return "button"; + case TEXT_FIELD: + return "field"; + case SWITCH: + return "switch"; + case CHECKBOX: + return "check"; + default: + return "label"; + } + } + + static String firstWords(String t) { + String s = t.trim(); + int words = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == ' ' && ++words == 3) { + return s.substring(0, i); + } + } + return s.length() > 24 ? s.substring(0, 24) : s; + } + + private static final String[] RESERVED = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", + "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", + "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", + "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", + "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", + "volatile", "while", "true", "false", "null", "title", "toolbar", "content", "layout", "style"}; + + private static String javaSafe(String s) { + for (int i = 0; i < RESERVED.length; i++) { + if (RESERVED[i].equals(s)) { + return s + "Item"; + } + } + return s; + } + + private String unique(String base) { + String n = base; + int k = 2; + while (usedFields.contains(n)) { + n = base + k++; + } + usedFields.add(n); + return n; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/LiveSink.java b/maven/design-import/src/main/java/com/codename1/designimport/LiveSink.java new file mode 100644 index 00000000000..f6298a00362 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/LiveSink.java @@ -0,0 +1,388 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.components.SpanLabel; +import com.codename1.components.Switch; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.ButtonGroup; +import com.codename1.ui.CheckBox; +import com.codename1.ui.FontImage; +import com.codename1.ui.RadioButton; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Image; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.layouts.LayeredLayout; +import com.codename1.ui.layouts.Layout; +import com.codename1.ui.plaf.Style; +import java.util.LinkedHashMap; +import java.util.Map; + +/// Builds the live components of the preview. Every component is named after its node id, +/// so a click in the preview selects the node, and the fidelity check finds each node's +/// component. +final class LiveSink implements Sink { + private final ImportSession session; + private final ButtonGroup radios = new ButtonGroup(); + private final Map images; + final Map byNode = new LinkedHashMap(); + + LiveSink(ImportSession session, Map images) { + this.session = session; + this.images = images; + } + + float mm(double px) { + return (float) (px / session.getEffectiveScale() * StyleStage.MM_PER_DP); + } + + private Image image(DNode n) { + Image img = n.imageName == null ? null : images.get(n.imageName); + if (img == null) { + return null; + } + int w = Math.max(1, CN.convertToPixels(mm(n.w))); + int h = Math.max(1, CN.convertToPixels(mm(n.h))); + return img.scaled(w, h); + } + + @Override + public Object leaf(DNode n, DNode parent) { + Component c; + DNode t = StyleStage.textChild(n); + String text = t == null ? "" : t.text; + if (parent != null && parent.role == DNode.Role.TABS) { + Button b = new Button(text); + DNode icon = firstPicture(n); + if (icon != null) { + b.setIcon(image(icon)); + } + b.setTextPosition(Component.BOTTOM); + c = b; + } else { + switch (n.role) { + case BUTTON: { + Button b = new Button(text); + DNode icon = firstPicture(n); + if (icon != null) { + b.setIcon(image(icon)); + } + c = b; + break; + } + case TEXT_FIELD: { + TextField f = new TextField("", text, 20, TextField.ANY); + if (n.multiline) { + f.setSingleLineTextArea(false); + f.setRows(rows(n)); + f.setGrowByContent(false); + f.setVerticalAlignment(com.codename1.ui.Component.TOP); + } + if (n.uiid != null && f.getHintLabel() != null) { + f.getHintLabel().setUIID(n.uiid + "Hint"); + } + c = f; + break; + } + case SWITCH: + c = new Switch(); + break; + case CHECKBOX: { + DNode icon = firstPicture(n); + // A drawn square or ring is the check box's own box, which the theme draws; + // only a picture of something else makes the control a picture toggle. + boolean picture = icon != null && !boxLike(icon, t); + if (n.radio) { + // The theme draws the ring; a drawn dot in it says which one is chosen. + RadioButton rb = RadioButton.createToggle(text, radios); + int[] ink = radioInk(n); + radioIcons(rb, mm(icon == null ? n.h : icon.h), ink[0], ink[1]); + rb.setSelected(picture); + c = rb; + break; + } + CheckBox cb = picture ? CheckBox.createToggle(text) : new CheckBox(text); + if (picture) { + cb.setIcon(image(icon)); + } + c = cb; + break; + } + case LABEL: + if (n.multiline) { + SpanLabel sl = new SpanLabel(n.text); + sl.setTextUIID(n.uiid); + sl.setUIID("Container"); + c = sl; + } else { + c = new Label(n.text); + } + break; + case DIVIDER: + c = new Container(); + break; + default: { + Image img = image(n); + c = img == null ? new Label() : new Label(img); + } + } + } + if (!(c instanceof SpanLabel) && n.uiid != null) { + c.setUIID(n.uiid); + } + if (c instanceof Switch) { + int[] ink = switchInk(n); + switchInk((Switch) c, ink[0], ink[1]); + } + c.setName(n.id); + byNode.put(n.id, c); + return c; + } + + /// Whether a check box's picture is just its box: an empty outlined square, about as tall + /// as its caption. A filled ring, a tick or a styled dot is the design's own look, kept. + /// A ring and a ring with a dot, the design's size, in the control's colour: the theme's + /// own radio is a square on some themes, and the design drew a ring. + /// The icons are made from a style of their own: the control's is the theme's toggle + /// style at this point, whose opaque background the icon would bake in. + static void radioIcons(RadioButton rb, float mm, int ring, int dot) { + com.codename1.ui.plaf.Style s = new com.codename1.ui.plaf.Style(); + s.setBgTransparency(0); + s.setFgColor(ring); + rb.setIcon(FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_UNCHECKED, s, mm)); + com.codename1.ui.plaf.Style on = new com.codename1.ui.plaf.Style(s); + on.setFgColor(dot); + rb.setPressedIcon(FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_CHECKED, on, mm)); + } + + /// The ring's colour and the chosen dot's, from the drawing: the first stroke and the + /// first fill inside the radio button. A light grey ring when nothing says otherwise. + /// A switch draws its track in the background colour and its thumb in the foreground, + /// unselected when off and selected when on. The design's UIID is the switch's box, whose + /// colours were both dark, so the switch drew black on black: the track and thumb come + /// from the design's own shapes instead, and "on" swaps them so the change shows. + static int[] switchInk(DNode n) { + Integer track = n.background; + Integer thumb = null; + for (int i = 0; i < n.children.size(); i++) { + DNode k = n.children.get(i); + if (k.w <= n.h * 1.3 && thumb == null) { + thumb = first(k, false); + } else if (track == null) { + track = k.background; + if (thumb == null) { + int[] inner = switchInk(k); + thumb = inner[1] == NO_THUMB ? null : Integer.valueOf(inner[1]); + } + } + } + return new int[] {track == null ? 0x3a3a3a : track.intValue(), thumb == null ? NO_THUMB : thumb.intValue()}; + } + + private static final int NO_THUMB = 0x9e9e9e; + + static void switchInk(Switch sw, int track, int thumb) { + Style off = sw.getUnselectedStyle(); + off.setBgColor(track); + off.setFgColor(thumb); + Style on = sw.getSelectedStyle(); + on.setBgColor(thumb); + on.setFgColor(0xffffff); + } + + static int[] radioInk(DNode n) { + Integer ring = first(n, true); + Integer dot = first(n, false); + int r = ring == null ? 0xcccccc : ring.intValue(); + return new int[] {r, dot == null ? r : dot.intValue()}; + } + + private static Integer first(DNode n, boolean stroke) { + Integer v = stroke ? (n.borderWidth > 0 ? n.borderColor : null) : n.background; + for (int i = 0; v == null && i < n.children.size(); i++) { + v = first(n.children.get(i), stroke); + } + return v; + } + + static boolean boxLike(DNode icon, DNode caption) { + double line = caption == null ? 24 : Math.max(caption.h, 8); + boolean square = Math.abs(icon.w - icon.h) <= Math.max(2, icon.w * 0.15) && icon.h <= line * 1.5; + boolean outline = icon.borderColor != null && (icon.background == null || icon.backgroundAlpha < 0.05) + && icon.children.isEmpty() && icon.radius < icon.w / 3; + return square && outline; + } + + private static DNode firstPicture(DNode n) { + // A tab that is only an icon is its own picture. + if (n.imageName != null && n.rasterize) { + return n; + } + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if (c.imageName != null) { + return c; + } + DNode d = firstPicture(c); + if (d != null) { + return d; + } + } + return null; + } + + /// The lines a multi-line field shows: as many of its text's lines as its box holds. + static int rows(DNode n) { + double size = 14; + for (int i = 0; i < n.children.size(); i++) { + if (n.children.get(i).fontSize > 0) { + size = n.children.get(i).fontSize; + } + } + double inner = n.h - n.padding[0] - n.padding[2]; + return Math.max(2, (int) Math.floor(inner / (size * 1.4))); + } + + static Layout layout(DNode n, int columns) { + switch (n.layout) { + case BOX_X: + return n.centerCross ? BoxLayout.xCenter() : new BoxLayout(BoxLayout.X_AXIS); + case BORDER: { + BorderLayout b = new BorderLayout(); + if (n.centerAbsolute) { + b.setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER_ABSOLUTE); + } + return b; + } + case GRID: + return new GridLayout((n.children.size() + columns - 1) / columns, columns); + case LAYERED: + return new LayeredLayout(); + case FLOW: + return new FlowLayout(); + default: + return new BoxLayout(BoxLayout.Y_AXIS); + } + } + + @Override + public Object container(DNode n, int columns) { + Container c = new Container(layout(n, columns)); + if (n.uiid != null) { + c.setUIID(n.uiid); + } + if (n.imageBackground && n.imageName != null) { + Image img = images.get(n.imageName); + if (img != null) { + // A CSS border paints its own background over the picture; the picture already + // has the design's corners and outline. + c.getAllStyles().setBorder(com.codename1.ui.plaf.Border.createEmpty()); + c.getAllStyles().setBgImage(img); + c.getAllStyles().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL); + } + } + if (n.role == DNode.Role.SCREEN || "CENTER".equals(n.slot) && n.layout == DNode.Layout.BOX_Y) { + c.setScrollableY(session.scrollable && n.layout == DNode.Layout.BOX_Y); + } + if (n.scrollX) { + c.setScrollableX(true); + } + c.setName(n.id); + byNode.put(n.id, c); + return c; + } + + @Override + public void add(Object parent, DNode parentNode, Object child, DNode childNode, String constraint, + double[] margins, int wrap) { + Container p = (Container) parent; + Component c = (Component) child; + Component added = c; + if (wrap != 0) { + Container w = new Container(new FlowLayout(wrap == 2 ? Component.CENTER : wrap == 3 ? Component.RIGHT + : Component.LEFT)); + w.setUIID("Container"); + w.add(c); + added = w; + } + Style s = added.getAllStyles(); + // UNIT_TYPE_DIPS is millimetres, despite the name. + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(mm(margins[0]), mm(margins[2]), mm(margins[3]), mm(margins[1])); + if (constraint != null) { + p.add(borderConstraint(constraint), added); + } else { + p.add(added); + } + } + + /// The engine names slots NORTH, CENTER...; BorderLayout's constants are "North", "Center". + static String borderConstraint(String slot) { + if ("NORTH".equals(slot)) { + return BorderLayout.NORTH; + } + if ("SOUTH".equals(slot)) { + return BorderLayout.SOUTH; + } + if ("EAST".equals(slot)) { + return BorderLayout.EAST; + } + if ("WEST".equals(slot)) { + return BorderLayout.WEST; + } + return BorderLayout.CENTER; + } + + @Override + public void layered(Object parent, Object child, double[] insets) { + Container p = (Container) parent; + Component c = (Component) child; + LayeredLayout ll = (LayeredLayout) p.getLayout(); + ll.setInsets(c, inset(insets[0]) + " " + inset(insets[1]) + " " + inset(insets[2]) + " " + inset(insets[3])); + } + + @Override + public void overlay(Object scrim, DNode n) { + final Container c = (Container) scrim; + c.addPointerReleasedListener(e -> { + int x = e.getX() - c.getAbsoluteX() + c.getX(); + int y = e.getY() - c.getAbsoluteY() + c.getY(); + if (c.getComponentAt(e.getX(), e.getY()) == c && c.contains(x, y)) { // NOPMD CompareObjectsWithEquals - the layer itself + c.setVisible(false); + c.getParent().repaint(); + } + }); + } + + private String inset(double px) { + return px < 0 ? "auto" : Text.num(mm(px)) + "mm"; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/LiveView.java b/maven/design-import/src/main/java/com/codename1/designimport/LiveView.java new file mode 100644 index 00000000000..4cf72a55ddd --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/LiveView.java @@ -0,0 +1,514 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import com.codename1.io.Preferences; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.ComboBox; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Graphics; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.LayeredLayout; + +import java.util.Map; + +/// The form as it runs: the real components, at the real size of a screen, scrolling and +/// answering clicks. The screen is any size: pick a device, type one, or drag the edges and +/// watch the form re-arrange as it would on a device that size, switching to the tablet or +/// desktop arrangement as it crosses a breakpoint. +/// +/// Two modes, because a click either uses the form or asks what an element became: +/// Interact passes clicks to the form, Inspect selects the element under the pointer. +/// Fit shows a picture of the whole form scaled into the pane, for a long page or a wide one. +final class LiveView extends Container { + /// A screen size to try: a name, and width by height in dp. + static final String[] DEVICES = {"Small phone", "Phone", "Large phone", "Tablet", "Tablet landscape", "Laptop", + "Desktop", "Wide desktop"}; + static final int[][] SIZES = {{360, 640}, {390, 844}, {430, 932}, {820, 1180}, {1180, 820}, {1280, 800}, + {1440, 900}, {1920, 1080}}; + static final String PREF_W = "designimport.viewW"; + static final String PREF_H = "designimport.viewH"; + static final int MIN_DP = 240; + static final int MAX_DP = 2560; + + /// Builds the live form for a width, and tells which component a node became. + interface Host { + Preview build(int widthDp); + + /// The arrangement a screen this wide shows, without building it. + ImportSession.Variant variantAt(int widthDp); + + void picked(String nodeId); + + void rebuilt(); + } + + private final Host host; + private final ComboBox device = new ComboBox(); + private Container controls; + private final TextField widthField = new TextField("", "W", 5, TextField.NUMERIC); + private final TextField heightField = new TextField("", "H", 5, TextField.NUMERIC); + private final Button inspect = new Button("Inspect", "WorkbenchSegmentOn"); + private final Button interact = new Button("Interact", "WorkbenchSegment"); + private final Button fit = new Button("Fit", "WorkbenchSegment"); + private final Viewport viewport = new Viewport(); + private final Cover cover = new Cover(); + /// Scrolls when the screen is bigger than the pane, but the form inside lays out at its + /// own screen size: inside a scrolling parent a container otherwise takes its preferred + /// size, so text ran past the screen's edge and a long form never scrolled itself. + private final Container stage = new Stage(); + + private static final class Stage extends Container { + Stage() { + super(new FlowLayout(Component.CENTER), "WorkbenchViewStage"); + } + + @Override + protected boolean constrainWidthWhenScrollable() { + return true; + } + + @Override + protected boolean constrainHeightWhenScrollable() { + return true; + } + } + private final FitView picture = new FitView(); + private final Container body = new Container(new BorderLayout()); + private int widthDp; + private int heightDp; + private boolean inspecting = true; + private boolean fitting; + private Preview shown; + private Component marked; + private boolean updating; + + LiveView(Host host) { + super(new BorderLayout(), "WorkbenchCanvas"); + this.host = host; + widthDp = clamp(Preferences.get(PREF_W, 390)); + heightDp = clamp(Preferences.get(PREF_H, 844)); + for (int i = 0; i < DEVICES.length; i++) { + device.addItem(DEVICES[i] + " " + SIZES[i][0] + " x " + SIZES[i][1]); + } + device.addItem("Custom"); + device.addActionListener(e -> { + if (updating) { + return; + } + int i = device.getSelectedIndex(); + if (i >= 0 && i < DEVICES.length) { + resize(SIZES[i][0], SIZES[i][1], true); + } + }); + widthField.setUIID("WorkbenchField"); + heightField.setUIID("WorkbenchField"); + widthField.setTooltip("Screen width in dp"); + heightField.setTooltip("Screen height in dp"); + widthField.setDoneListener(e -> typed()); + heightField.setDoneListener(e -> typed()); + Button swap = new Button("", "WorkbenchIcon"); + FontImage.setMaterialIcon(swap, FontImage.MATERIAL_SCREEN_ROTATION); + swap.setTooltip("Turn the screen"); + swap.addActionListener(e -> resize(heightDp, widthDp, true)); + inspect.setTooltip("A click selects the element under it"); + interact.setTooltip("Clicks, typing and scrolling go to the form"); + fit.setTooltip("A picture of the whole form, scaled to the pane"); + inspect.addActionListener(e -> mode(true, false)); + interact.addActionListener(e -> mode(false, false)); + fit.addActionListener(e -> mode(inspecting, !fitting)); + Label x = new Label("x", "WorkbenchFieldLabel"); + widthField.setColumns(4); + heightField.setColumns(4); + // One row the host puts above the design and the form together, so neither pane + // starts lower than the other and the two can be read side by side. + controls = new Container(row(Component.RIGHT)); + controls.addAll(device, swap, widthField, x, heightField, inspect, interact, fit); + controls.setUIID("WorkbenchViewBar"); + + viewport.setLayout(new LayeredLayout()); + Handle right = new Handle(true, false); + Handle bottom = new Handle(false, true); + Handle corner = new Handle(true, true); + Container column = new Container(new BorderLayout()); + column.add(BorderLayout.CENTER, viewport); + column.add(BorderLayout.EAST, right); + column.add(BorderLayout.SOUTH, BorderLayout.centerEastWest(bottom, corner, null)); + stage.add(column); + stage.setScrollableX(true); + stage.setScrollableY(true); + picture.setPicker((px, py) -> pickAt(px, py, false)); + body.add(BorderLayout.CENTER, stage); + add(BorderLayout.CENTER, body); + syncFields(); + } + + /// The device, size and click-mode controls, for the host's toolbar. + Container controls() { + return controls; + } + + int getWidthDp() { + return widthDp; + } + + int getHeightDp() { + return heightDp; + } + + Preview getShown() { + return shown; + } + + boolean isFitting() { + return fitting; + } + + Component getMarked() { + return marked; + } + + boolean isInspecting() { + return inspecting; + } + + /// Builds the form again, at the current size. + void refresh() { + Preview p = host.build(widthDp); + show(p); + } + + private void show(Preview p) { + shown = p; + viewport.removeAll(); + if (p != null && p.root != null) { + p.root.remove(); + viewport.add(p.root); + } + viewport.add(cover); + cover.setVisible(inspecting); + if (fitting) { + showPicture(); + } + host.rebuilt(); + } + + /// Sets the screen size in dp. `rebuild` builds the form anew (the content cap and the + /// arrangement are chosen for a width); without it the same components lay out again, + /// which is what a drag does until the pointer is let go. + void resize(int w, int h, boolean rebuild) { + w = clamp(w); + h = clamp(h); + if (w == widthDp && h == heightDp && !rebuild) { + return; + } + widthDp = w; + heightDp = h; + Preferences.set(PREF_W, w); + Preferences.set(PREF_H, h); + syncFields(); + ImportSession.Variant was = shown == null ? null : shown.variant; + Preview next = rebuild ? host.build(w) : null; + if (next == null && was != null && host.variantAt(w) != was) { // NOPMD CompareObjectsWithEquals - same variant + // Crossing a breakpoint mid-drag shows the other arrangement at once. + next = host.build(w); + } + if (next != null) { + show(next); + } + viewport.setShouldCalcPreferredSize(true); + if (fitting) { + showPicture(); + } + revalidateLater(); + } + + private void typed() { + int w = parse(widthField.getText(), widthDp); + int h = parse(heightField.getText(), heightDp); + resize(w, h, true); + } + + private static int parse(String s, int def) { + try { + return Integer.parseInt(s.trim()); + } catch (NumberFormatException ex) { + return def; + } + } + + private void syncFields() { + updating = true; + try { + widthField.setText(String.valueOf(widthDp)); + heightField.setText(String.valueOf(heightDp)); + int match = DEVICES.length; + for (int i = 0; i < DEVICES.length; i++) { + if (SIZES[i][0] == widthDp && SIZES[i][1] == heightDp) { + match = i; + } + } + device.setSelectedIndex(match); + } finally { + updating = false; + } + } + + static int clamp(int dp) { + return Math.max(MIN_DP, Math.min(MAX_DP, dp)); + } + + void mode(boolean inspectMode, boolean fitMode) { + inspecting = inspectMode; + fitting = fitMode; + inspect.setUIID(inspectMode ? "WorkbenchSegmentOn" : "WorkbenchSegment"); + interact.setUIID(inspectMode ? "WorkbenchSegment" : "WorkbenchSegmentOn"); + fit.setUIID(fitMode ? "WorkbenchSegmentOn" : "WorkbenchSegment"); + cover.setVisible(inspectMode); + body.removeAll(); + if (fitMode) { + showPicture(); + body.add(BorderLayout.CENTER, picture); + } else { + body.add(BorderLayout.CENTER, stage); + } + revalidateLater(); + } + + /// The whole form as a picture: the screen's width, and its full height when the form is + /// longer than the screen. + private void showPicture() { + if (shown == null || shown.root == null) { + picture.setImage(null); + return; + } + double px = Fidelity.dpPixels(); + int w = (int) Math.round(widthDp * px); + int h = (int) Math.round(heightDp * px); + int full = Math.max(h, shown.root.getPreferredH()); + Preview copy = host.build(widthDp); + picture.setImage(copy.snapshot(Math.max(1, w), Math.max(1, Math.min(full, 6000)))); + picture.setMark(marked == null ? null : rectIn(marked, copy, findId(marked))); + } + + private double[] rectIn(Component c, Preview p, String id) { + Component k = id == null || p == null ? null : p.components.get(id); + if (k == null || p.root == null) { + return new double[0]; + } + return new double[]{k.getAbsoluteX() - p.root.getAbsoluteX(), k.getAbsoluteY() - p.root.getAbsoluteY(), + k.getWidth(), k.getHeight()}; + } + + private String findId(Component c) { + if (shown == null || c == null) { + return null; + } + for (Map.Entry e : shown.components.entrySet()) { + if (e.getValue() == c) { // NOPMD CompareObjectsWithEquals - the same component + return e.getKey(); + } + } + return null; + } + + /// Outlines the component a node became; null clears the outline. + void mark(Component c) { + marked = c; + if (c != null && !fitting) { + // Scroll the form's own scrolling container so the element is in view. + Container p = c.getParent(); + while (p != null && p != viewport) { // NOPMD CompareObjectsWithEquals - walking up to the viewport + if (p.isScrollableY() || p.isScrollableX()) { + p.scrollComponentToVisible(c); + break; + } + p = p.getParent(); + } + stage.scrollComponentToVisible(viewport); + } + if (fitting) { + showPicture(); + } + viewport.repaint(); + } + + /// The smallest built component under a point, in viewport pixels (live) or picture + /// pixels (fit), reported to the host as its node id. + private void pickAt(double x, double y, boolean live) { + Preview p = shown; + if (p == null || p.root == null) { + return; + } + Preview in = live ? p : host.build(widthDp); + if (!live) { + double px = Fidelity.dpPixels(); + in.snapshot((int) Math.round(widthDp * px), Math.max((int) Math.round(heightDp * px), p.root.getPreferredH())); + } + String best = null; + double area = Double.MAX_VALUE; + for (Map.Entry e : in.components.entrySet()) { + Component c = e.getValue(); + if (!c.isVisible() || c.getWidth() <= 0) { + continue; + } + double cx = c.getAbsoluteX() - in.root.getAbsoluteX(); + double cy = c.getAbsoluteY() - in.root.getAbsoluteY(); + double a = (double) c.getWidth() * c.getHeight(); + if (x >= cx && y >= cy && x <= cx + c.getWidth() && y <= cy + c.getHeight() && a < area) { + area = a; + best = e.getKey(); + } + } + if (best != null) { + host.picked(best); + } + } + + /// A row whose items are centred on one line. FlowLayout's vertical alignment places the + /// whole row in its container; only valign-by-row centres a short button beside a taller + /// field, which is what a toolbar needs. + static FlowLayout row(int align) { + FlowLayout f = new FlowLayout(align, Component.CENTER); + f.setValignByRow(true); + return f; + } + + /// Holds the form at exactly the screen size, and outlines the selected element over it. + final class Viewport extends Container { + Viewport() { + setUIID("WorkbenchViewport"); + } + + @Override + protected Dimension calcPreferredSize() { + double px = Fidelity.dpPixels(); + return new Dimension((int) Math.round(widthDp * px), (int) Math.round(heightDp * px)); + } + + @Override + public void paint(Graphics g) { + super.paint(g); + Component c = marked; + if (c == null || !c.isVisible() || c.getWidth() <= 0) { + return; + } + int x = c.getAbsoluteX() - getAbsoluteX() + getX(); + int y = c.getAbsoluteY() - getAbsoluteY() + getY(); + int[] clip = g.getClip(); + g.clipRect(getX(), getY(), getWidth(), getHeight()); + FitView.spotlight(g, new double[]{1, 0, 0}, new double[]{x, y, c.getWidth(), c.getHeight()}, + getX(), getY(), getWidth(), getHeight()); + g.setClip(clip); + } + } + + /// Lies over the form in Inspect mode and turns a click into a selection. + final class Cover extends Component { + Cover() { + setUIID("Container"); + setFocusable(false); + } + + @Override + public void pointerReleased(int x, int y) { + super.pointerReleased(x, y); + pickAt(x - viewport.getAbsoluteX(), y - viewport.getAbsoluteY(), true); + } + + @Override + protected Dimension calcPreferredSize() { + return new Dimension(1, 1); + } + } + + /// An edge or the corner of the screen, dragged to resize it. + final class Handle extends Component { + private final boolean horizontal; + private final boolean vertical; + private int startX; + private int startY; + private int startW; + private int startH; + + Handle(boolean horizontal, boolean vertical) { + this.horizontal = horizontal; + this.vertical = vertical; + setUIID("WorkbenchHandle"); + setFocusable(false); + setTooltip(horizontal && vertical ? "Drag to resize the screen" : horizontal ? "Drag to change the width" + : "Drag to change the height"); + } + + @Override + public void pointerPressed(int x, int y) { + startX = x; + startY = y; + startW = widthDp; + startH = heightDp; + } + + @Override + public void pointerDragged(int x, int y) { + double px = Fidelity.dpPixels(); + int w = horizontal ? (int) Math.round(startW + (x - startX) / px) : widthDp; + int h = vertical ? (int) Math.round(startH + (y - startY) / px) : heightDp; + resize(w, h, false); + } + + @Override + public void pointerReleased(int x, int y) { + resize(widthDp, heightDp, true); + } + + @Override + protected Dimension calcPreferredSize() { + int s = CN.convertToPixels(2.5f); + return new Dimension(s, s); + } + + @Override + public void paint(Graphics g) { + super.paint(g); + g.setColor(0x8a919c); + int cx = getX() + getWidth() / 2; + int cy = getY() + getHeight() / 2; + int r = Math.max(2, CN.convertToPixels(0.6f)); + if (horizontal && !vertical) { + g.fillRect(cx - 1, cy - r * 3, 2, r * 6); + } else if (vertical && !horizontal) { + g.fillRect(cx - r * 3, cy - 1, r * 6, 2); + } else { + g.fillRect(cx - r, cy - r, r * 2, r * 2); + } + } + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/Pipeline.java b/maven/design-import/src/main/java/com/codename1/designimport/Pipeline.java new file mode 100644 index 00000000000..4a06b54aa29 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/Pipeline.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtNode; +import com.codename1.art.GroupNode; +import com.codename1.art.ImportNote; +import com.codename1.art.Matrix; +import java.util.ArrayList; +import java.util.List; + +/// Runs the import: scope, detect, structure, classify, layout, responsive, style, emit. +/// +/// Every run starts from the session's choices and recomputes everything else, so it is +/// deterministic: the same design and the same choices always give the same code. +public final class Pipeline { + /// The stages in order, as the app and the MCP tools name them. + public static final java.util.List STAGES = java.util.Collections.unmodifiableList(java.util.Arrays.asList("scope", "detect", "structure", "classify", "layout", "responsive", + "style", "emit")); + + private Pipeline() { + } + + /// Runs every stage. + /// A screen that comes back as one picture is a flattened PSD or a screenshot: the form + /// would be an image of a UI, which is no UI at all. Say so rather than score it well. + static void flattened(ImportSession s, DNode root) { + List leaves = new ArrayList(); + leaves(root, leaves); + int pictures = 0; + double pictureArea = 0; + for (int i = 0; i < leaves.size(); i++) { + DNode n = leaves.get(i); + if (n.rasterize) { + pictures++; + pictureArea += n.w * n.h; + } + } + if (!leaves.isEmpty() && pictures * 2 >= leaves.size() && pictureArea >= root.w * root.h * 0.6) { + s.issue("classify", Issue.Severity.WARNING, root, "flattened", + "The design is mostly pictures (" + pictures + " of " + leaves.size() + + " layers): it was probably flattened, so the form shows an image of a UI.", + "Export the design with its layers (shapes and live text), or import it from the source file."); + } + } + + private static void leaves(DNode n, List out) { + if (n.children.isEmpty() || n.rasterize) { + out.add(n); + return; + } + for (int i = 0; i < n.children.size(); i++) { + leaves(n.children.get(i), out); + } + } + + /// Raises the elements a person marked as converted wrong, with their note. + static void flagged(ImportSession s, DNode root) { + for (java.util.Map.Entry e : s.overrides.entrySet()) { + String note = e.getValue().flag; + DNode n = note == null ? null : root.find(e.getKey()); + if (n != null) { + s.issue("review", Issue.Severity.TODO, n, "flagged", + "\"" + (n.name == null ? n.id : n.name) + "\" is marked as converted wrong" + + (note.length() == 0 ? "." : ": " + note), + "Pick what it is (its kind, or a picture of it), or leave it out; clear the mark when it looks right."); + } + } + } + + public static void run(ImportSession s) { + run(s, "emit"); + } + + /// Runs the stages up to and including `last`. + public static void run(ImportSession s, String last) { + s.clearResults(); + int upTo = indexOf(last); + List notes = s.getDocument().getNotes(); + for (int i = 0; i < notes.size(); i++) { + ImportNote n = notes.get(i); + s.issue("scope", Issue.Severity.WARNING, null, "reader-note:" + i, + "The file reader skipped something at " + n.getWhere() + ": " + n.getMessage(), null); + } + ScopeStage.autoScope(s); + s.log("scope: " + s.variants.size() + " variant(s)"); + for (int i = 0; i < s.variants.size(); i++) { + ImportSession.Variant v = s.variants.get(i); + ArtNode art = ScopeStage.resolve(s.getDocument(), v.scopeId); + if (art == null) { + s.issue("scope", Issue.Severity.WARNING, null, "scope-missing:" + v.scopeId, + "No layer with the id or path \"" + v.scopeId + "\"; imported the whole document.", + "List the frames with designimport_frames and pick one."); + art = s.getDocument().getRoot(); + } + art = ScopeStage.skipSkin(s, art); + Matrix toDoc = s.getDocument().toDocument(art); + if (toDoc == null) { + toDoc = Matrix.IDENTITY; + } + if (i == 0) { + double[] box = art instanceof GroupNode ? ScopeStage.localBox((GroupNode) art) : art.getLocalBounds(); + ScopeStage.Frame f = new ScopeStage.Frame(); + f.w = box == null ? s.getDocument().getWidth() : box[2] * Math.abs(toDoc.getA()); + f.h = box == null ? s.getDocument().getHeight() : box[3] * Math.abs(toDoc.getD()); + ScopeStage.classify(f); + s.effectiveScale = s.designScale > 0 ? s.designScale : f.scale; + s.log("scope: " + Text.num(f.w) + "x" + Text.num(f.h) + " design px at " + + Text.num(s.effectiveScale) + " px/dp"); + } + TreeBuilder tb = new TreeBuilder(s); + v.root = tb.build(art, toDoc); + v.originX = tb.originX(); + v.originY = tb.originY(); + v.width = v.root.w; + v.height = v.root.h; + s.log("detect: " + v.root.count() + " nodes in \"" + v.root.name + "\""); + } + if (upTo < 2) { + return; + } + for (int i = 0; i < s.variants.size(); i++) { + new StructureStage(s).run(s.variants.get(i).root); + } + if (upTo < 3) { + return; + } + for (int i = 0; i < s.variants.size(); i++) { + new ClassifyStage(s).run(s.variants.get(i).root); + flattened(s, s.variants.get(i).root); + flagged(s, s.variants.get(i).root); + } + if (upTo < 4) { + return; + } + for (int i = 0; i < s.variants.size(); i++) { + new LayoutStage(s).run(s.variants.get(i).root); + LayoutStage.markOverlays(s, s.variants.get(i).root); + } + if (upTo < 5) { + return; + } + new ResponsiveStage(s).run(); + if (upTo < 6) { + return; + } + String cls = s.effectiveClassName(); + String stem = cls.endsWith("Form") ? cls.substring(0, cls.length() - 4) : cls; + StyleStage style = new StyleStage(s); + for (int i = 0; i < s.variants.size(); i++) { + style.run(s.variants.get(i).root, stem); + } + Assets assets = new Assets(s); + for (int i = 0; i < s.variants.size(); i++) { + assets.run(s.variants.get(i), stem); + } + GeneratedCode code = new GeneratedCode(); + code.packageName = s.packageName; + code.className = cls; + code.css = style.css(); + code.images.putAll(assets.images); + s.code = code; + s.log("style: " + style.rules().size() + " UIIDs, " + assets.images.size() + " images"); + if (upTo < 7) { + return; + } + JavaEmitter java = new JavaEmitter(s); + code.baseSource = java.base(cls); + code.userSource = java.user(cls); + code.fields.putAll(java.fieldTypes()); + code.testSource = new TestEmitter(s).emit(cls, java.fieldTypes()); + s.log("emit: " + cls + " with " + code.fields.size() + " components"); + } + + static int indexOf(String stage) { + for (int i = 0; i < STAGES.size(); i++) { + if (STAGES.get(i).equals(stage)) { + return i; + } + } + return STAGES.size() - 1; + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/Preview.java b/maven/design-import/src/main/java/com/codename1/designimport/Preview.java new file mode 100644 index 00000000000..c2b0c04b23f --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/Preview.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtRenderer; +import com.codename1.art.Matrix; +import com.codename1.art.Raster; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; +import com.codename1.ui.css.CSSThemeCompiler; +import com.codename1.ui.plaf.Style; +import com.codename1.ui.plaf.UIManager; +import com.codename1.ui.util.MutableResource; +import java.util.Hashtable; +import java.util.LinkedHashMap; +import java.util.Map; + +/// The live form: builds the components the generated code would build, styled by the +/// generated CSS, so the preview beside the design is the real thing and not a picture of it. +public final class Preview { + /// Components by node id, for selection and for the fidelity check. + public final Map components = new LinkedHashMap(); + public Container root; + public ImportSession.Variant variant; + /// An error the CSS compiler reported, or null. + public String cssError; + + private Preview() { + } + + /// Installs the generated CSS into the running theme. The UIIDs are the form's own, so + /// nothing else in the app changes. Returns the compiler's error, or null. + public static String applyCss(ImportSession s) { + if (s.getCode() == null || s.getCode().css == null) { + return null; + } + try { + MutableResource res = new MutableResource(); + new CSSThemeCompiler().compile(s.getCode().css, res, "Theme"); + Hashtable theme = res.getTheme("Theme"); + if (theme != null) { + UIManager.getInstance().addThemeProps(theme); + } + return null; + } catch (RuntimeException ex) { + return ex.getMessage(); + } + } + + /// Builds the form for a screen `widthDp` wide, choosing the variant the generated form + /// would choose at that width. + public static Preview build(ImportSession s, double widthDp) { + Preview p = new Preview(); + p.cssError = applyCss(s); + ImportSession.Variant v = s.variants.size() > 1 ? s.variantFor(widthDp) : s.primary(); + p.variant = v; + if (v == null || v.root == null) { + p.root = new Container(); + return p; + } + LiveSink sink = new LiveSink(s, s.getCode() == null ? new LinkedHashMap() : s.getCode().images); + double widthPx = widthDp * s.getEffectiveScale(); + p.root = (Container) new FormWalker(s, sink, widthPx, v.width).walk(v.root); + p.components.putAll(sink.byNode); + // The content cap, as arrange() applies it. + double widthMm = widthDp * StyleStage.MM_PER_DP; + double cap = s.contentCapDp() * StyleStage.MM_PER_DP; + if (cap > 0 && widthMm > cap) { + Component content = contentOf(p, v.root); + float side = (float) ((widthMm - cap) / 2); + Style st = content.getAllStyles(); + float px = CN.convertToPixels(1f); + st.setPaddingUnit(Style.UNIT_TYPE_DIPS); + st.setPadding(Component.LEFT, st.getPaddingLeftNoRTL() / px + side); + st.setPadding(Component.RIGHT, st.getPaddingRightNoRTL() / px + side); + } + return p; + } + + private static Component contentOf(Preview p, DNode root) { + for (int i = 0; i < root.children.size(); i++) { + DNode c = root.children.get(i); + if ("CENTER".equals(c.slot) && p.components.containsKey(c.id)) { + return p.components.get(c.id); + } + } + return p.root; + } + + /// Lays the preview out at a size in pixels and paints it into an image. + public Image snapshot(int w, int h) { + root.setX(0); + root.setY(0); + root.setWidth(w); + root.setHeight(h); + root.setShouldCalcPreferredSize(true); + root.layoutContainer(); + root.revalidate(); + layoutAll(root); + Image img = Image.createImage(w, h, 0xffffffff); + Graphics g = img.getGraphics(); + root.paintComponent(g, true); + return img; + } + + private static void layoutAll(Container c) { + c.layoutContainer(); + for (int i = 0; i < c.getComponentCount(); i++) { + Component k = c.getComponentAt(i); + if (k instanceof Container) { + layoutAll((Container) k); + } + } + } + + /// The design's own pixels for a variant, rendered at `w` by `h`. + public static Image designImage(ImportSession s, ImportSession.Variant v, int w, int h) { + double sx = w / Math.max(1, v.width); + double sy = h / Math.max(1, v.height); + Matrix view = Matrix.scale(sx, sy).multiply(Matrix.translate(-v.originX, -v.originY)); + Raster r = new ArtRenderer().render(s.getDocument(), view, new int[]{0, 0, w, h}); + int[] px = r.getPixels(); + // Composite over white: a transparent design reads as the white page it sits on. + for (int i = 0; i < px.length; i++) { + int a = (px[i] >>> 24) & 0xff; + if (a < 255) { + int rr = ((px[i] >> 16) & 0xff) * a / 255 + (255 - a); + int gg = ((px[i] >> 8) & 0xff) * a / 255 + (255 - a); + int bb = (px[i] & 0xff) * a / 255 + (255 - a); + px[i] = 0xff000000 | (rr << 16) | (gg << 8) | bb; + } + } + return Image.createImage(px, r.getWidth(), r.getHeight()); + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/ResponsiveStage.java b/maven/design-import/src/main/java/com/codename1/designimport/ResponsiveStage.java new file mode 100644 index 00000000000..53edc3f4e4c --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/ResponsiveStage.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import java.util.ArrayList; +import java.util.List; + +/// Stage 5: makes the form adapt. +/// +/// With a phone and a tablet frame, it matches their components -- by name, then by text, +/// then by role and position -- so both arrangements share one set of fields, and it reports +/// what exists in only one of them. With one frame it relies on the levers (fill width, a +/// capped and centred content column, scrolling, grids that gain columns) and says which it +/// applied, so they can be tuned rather than discovered. +final class ResponsiveStage { + static final String STAGE = "responsive"; + private final ImportSession session; + + ResponsiveStage(ImportSession session) { + this.session = session; + } + + void run() { + ImportSession.Variant first = session.primary(); + if (first == null || first.root == null) { + return; + } + if (session.variants.size() == 1) { + levers(first); + return; + } + for (int i = 1; i < session.variants.size(); i++) { + ImportSession.Variant v = session.variants.get(i); + if (v.root != null) { + match(first, v); + } + } + } + + private void levers(ImportSession.Variant v) { + List applied = new ArrayList(); + if (session.fillWidth) { + applied.add("wide components stretch to the screen width"); + } + if (session.maxContentWidthDp > 0) { + applied.add("content is capped at " + session.maxContentWidthDp + "dp and centred on wider screens"); + } + if (session.scrollable) { + applied.add("the content column scrolls"); + } + if (session.adaptiveGrid && hasGrid(v.root)) { + applied.add("grids keep their cell width and gain columns as the screen widens"); + } + session.issue(STAGE, Issue.Severity.INFO, null, "implicit-responsive", + "The design has one " + Text.lower(v.kind.name()) + " frame, so the form adapts by default: " + + join(applied) + ".", + "Tune the levers (fillWidth, maxContentWidthDp, scrollable, adaptiveGrid), or link a " + + (v.kind == ImportSession.Kind.PHONE ? "tablet or desktop" : "phone") + " frame as another variant."); + fixedWidths(v.root, v.width); + } + + /// Wide fixed-width items that will look stranded on a tablet. + private void fixedWidths(DNode n, double screenW) { + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if ((c.align == DNode.Align.CENTER || c.align == DNode.Align.LEFT) && c.w >= screenW * 0.6 && c.w < screenW * 0.8 + && (c.role == DNode.Role.BUTTON || c.role == DNode.Role.TEXT_FIELD || c.role == DNode.Role.CARD)) { + session.issue(STAGE, Issue.Severity.TODO, c, "fixed-width", + "\"" + c.name + "\" is " + Math.round(c.w / screenW * 100) + "% of the screen wide but keeps a fixed width.", + "Set align=fill to stretch it, or leave it fixed."); + } + fixedWidths(c, screenW); + } + } + + private static boolean hasGrid(DNode n) { + if (n.layout == DNode.Layout.GRID) { + return true; + } + for (int i = 0; i < n.children.size(); i++) { + if (hasGrid(n.children.get(i))) { + return true; + } + } + return false; + } + + private static String join(List l) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < l.size(); i++) { + if (i > 0) { + sb.append(i == l.size() - 1 ? " and " : ", "); + } + sb.append(l.get(i)); + } + return sb.length() == 0 ? "nothing" : sb.toString(); + } + + /// Gives every component of `other` the field of its counterpart in `base`. + private void match(ImportSession.Variant base, ImportSession.Variant other) { + List a = new ArrayList(); + List b = new ArrayList(); + leaves(base.root, a); + leaves(other.root, b); + List taken = new ArrayList(); + int matched = 0; + for (int i = 0; i < b.size(); i++) { + DNode o = b.get(i); + DNode best = null; + for (int pass = 0; pass < 3 && best == null; pass++) { + for (int j = 0; j < a.size(); j++) { + DNode p = a.get(j); + if (taken.contains(p) || p.role != o.role) { + continue; + } + if (pass == 0 && !Text.isGenericName(o.name) && o.name.equals(p.name) + || pass == 1 && o.allText().length() > 0 && o.allText().equals(p.allText()) + || pass == 2 && Math.abs(o.y / other.height - p.y / base.height) < 0.05 + && Math.abs(o.x / other.width - p.x / base.width) < 0.1) { + best = p; + break; + } + } + } + if (best != null) { + taken.add(best); + o.fieldName = best.fieldName; + matched++; + } else if (o.fieldName != null) { + o.fieldName = o.fieldName + Text.pascal(Text.lower(other.kind.name())); + session.issue(STAGE, Issue.Severity.INFO, o, "variant-only", + "\"" + o.name + "\" appears only in the " + Text.lower(other.kind.name()) + " frame.", null); + } + } + for (int j = 0; j < a.size(); j++) { + if (!taken.contains(a.get(j))) { + session.issue(STAGE, Issue.Severity.INFO, a.get(j), "variant-only", + "\"" + a.get(j).name + "\" appears only in the " + Text.lower(base.kind.name()) + " frame.", null); + } + } + double share = a.isEmpty() ? 0 : matched / (double) Math.max(a.size(), b.size()); + session.issue(STAGE, share < 0.4 ? Issue.Severity.WARNING : Issue.Severity.INFO, null, "variants-matched", + "Matched " + matched + " of " + Math.max(a.size(), b.size()) + " components between the " + + Text.lower(base.kind.name()) + " and " + Text.lower(other.kind.name()) + " frames; they share fields and " + + "the form switches arrangement at " + session.tabletBreakpointDp + "dp.", + share < 0.4 ? "So little matches that these may be different screens; check the scope." : null); + } + + private static void leaves(DNode n, List out) { + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if (FormWalker.isLeaf(c, n)) { + if (!c.excluded && c.role != DNode.Role.SPACER) { + out.add(c); + } + } else { + leaves(c, out); + } + } + } +} diff --git a/maven/design-import/src/main/java/com/codename1/designimport/ScopeStage.java b/maven/design-import/src/main/java/com/codename1/designimport/ScopeStage.java new file mode 100644 index 00000000000..c10b896eda2 --- /dev/null +++ b/maven/design-import/src/main/java/com/codename1/designimport/ScopeStage.java @@ -0,0 +1,522 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtDocument; +import com.codename1.art.ArtNode; +import com.codename1.art.GroupNode; +import com.codename1.art.Matrix; +import com.codename1.art.RasterNode; +import com.codename1.art.ShapeNode; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// Stage 1: decides which layer of the design is the screen. +/// +/// A design file is rarely one screen. It has pages of frames, a phone and a tablet version +/// side by side, or a screen pasted into a picture of a device. This stage lists the frames +/// that look like screens, guesses each one's form factor from its size, pairs a phone frame +/// with a tablet frame of the same name, and, inside a chosen frame, steps past a device skin +/// to the screen it frames. +public final class ScopeStage { + static final String STAGE = "scope"; + + /// A layer that may be a screen. + public static final class Frame { + public String id; + public String name; + public String path; + public double x; + public double y; + public double w; + public double h; + public ImportSession.Kind kind; + public double scale; + double score; + ArtNode node; + + /// The frame as JSON-ready values. + public Map toMap() { + Map m = new LinkedHashMap(); + m.put("id", id); + m.put("name", name); + m.put("path", path); + m.put("bounds", bounds()); + m.put("kind", Text.lower(kind.name())); + m.put("scale", Double.valueOf(scale)); + return m; + } + + private List bounds() { + List l = new ArrayList(); + l.add(Double.valueOf(x)); + l.add(Double.valueOf(y)); + l.add(Double.valueOf(w)); + l.add(Double.valueOf(h)); + return l; + } + } + + private ScopeStage() { + } + + /// Lists the layers that may be screens, the most screen-like first. + public static List candidates(ArtDocument doc) { + List out = new ArrayList(); + collect(doc.getRoot(), doc.getRoot().getTransform(), "", 0, out, doc); + if (out.isEmpty()) { + Frame f = frameFor(doc.getRoot(), doc.getRoot().getTransform(), ""); + if (f == null) { + f = new Frame(); + f.id = doc.getRoot().getId(); + f.name = doc.getTitle(); + f.path = ""; + f.w = doc.getWidth(); + f.h = doc.getHeight(); + classify(f); + } + out.add(f); + } + for (int i = 0; i < out.size(); i++) { + Frame f = out.get(i); + if (f.id == null && f.node != null) { + // SVG and hand-built documents carry no layer ids; a child-index path names the + // frame exactly, where a name path would not ("Login / Phone" has a slash). + f.id = indexPath(doc.getRoot(), f.node); + } + } + // Highest score first; a stable insertion sort keeps document order for ties. + for (int i = 1; i < out.size(); i++) { + Frame k = out.get(i); + int j = i - 1; + while (j >= 0 && out.get(j).score < k.score) { + out.set(j + 1, out.get(j)); + j--; + } + out.set(j + 1, k); + } + return out; + } + + private static void collect(GroupNode g, Matrix m, String path, int depth, List out, ArtDocument doc) { + if (depth > 3) { + return; + } + List ch = g.getChildren(); + for (int i = 0; i < ch.size(); i++) { + ArtNode n = ch.get(i); + if (!(n instanceof GroupNode) || !n.isVisible()) { + continue; + } + Matrix cm = m.multiply(n.getTransform()); + String p = path.length() == 0 ? safe(n.getName()) : path + "/" + safe(n.getName()); + Frame f = frameFor((GroupNode) n, cm, p); + if (f != null && f.w >= 160 && f.h >= 160 && !holdsFrames((GroupNode) n)) { + out.add(f); + } else { + // A page or a section: look inside for the frames. + collect((GroupNode) n, cm, p, depth + 1, out, doc); + } + } + } + + /// A page or canvas, or anything holding artboards or frames: the screens are inside it. + static boolean holdsFrames(GroupNode g) { + String st = g.getAttribute("sourceType"); + if ("page".equals(st) || "CANVAS".equals(st) || "DOCUMENT".equals(st)) { + return true; + } + if ("FRAME".equals(st) || "artboard".equals(st) || "COMPONENT".equals(st) || "symbolMaster".equals(st)) { + // A screen itself; frames nested in it are its cards and sections. + return false; + } + List ch = g.getChildren(); + for (int i = 0; i < ch.size(); i++) { + ArtNode c = ch.get(i); + if (c instanceof GroupNode && c.isVisible()) { + String cst = c.getAttribute("sourceType"); + if ("artboard".equals(cst) || "FRAME".equals(cst) || "symbolMaster".equals(cst)) { + return true; + } + } + } + return layoutOfScreens(g); + } + + /// A format with no artboards (SVG) still lays several screens out side by side, under one + /// wrapper group: the `` element itself, or a group a tool put everything in. Such a + /// wrapper draws nothing of its own, and every visible child is a screen-shaped group of + /// frame size that overlaps none of the others. A screen with two columns fails this: it + /// has a background, a header or text beside them. + static boolean layoutOfScreens(GroupNode g) { + List ch = g.getChildren(); + ListSign in
"; + File f = dir.resolve("index.html").toFile(); + Files.write(f.toPath(), html.getBytes("UTF-8")); + DesignImportService s = new DesignImportService(); + Map opened = s.call("open", args("path", f.getPath())); + assertEquals(Boolean.TRUE, opened.get("success"), String.valueOf(opened.get("error"))); + List frames = (List) opened.get("frames"); + System.out.println("html e2e frames: " + frames); + assertTrue(frames.size() >= 2, String.valueOf(frames)); + Map run = s.call("run", args()); + assertEquals(Boolean.TRUE, run.get("success"), String.valueOf(run.get("error"))); + Map tree = (Map) s.call("tree", args("depth", Integer.valueOf(20))).get("tree"); + StringBuilder roles = new StringBuilder(); + walk(tree, roles); + String all = roles.toString(); + System.out.println("html e2e tree: " + all); + assertTrue(all.contains("button:"), all); + assertTrue(all.contains("text_field:"), all); + assertTrue(all.contains("Sign in to continue"), all); + } + + private static void walk(Map n, StringBuilder sb) { + sb.append(n.get("role")).append(':').append(n.get("name")).append('/').append(n.get("text")).append("; "); + Object ch = n.get("children"); + if (ch instanceof List) { + for (Object c : (List) ch) { + if (c instanceof Map) { + walk((Map) c, sb); + } + } + } + } + + private static Map args(Object... kv) { + Map m = new LinkedHashMap(); + for (int i = 0; i < kv.length; i += 2) { + m.put((String) kv[i], kv[i + 1]); + } + return m; + } + + private static GroupNode find(GroupNode g, String prefix) { + for (ArtNode c : g.getChildren()) { + if (c instanceof GroupNode) { + if (c.getName() != null && c.getName().startsWith(prefix)) { + return (GroupNode) c; + } + GroupNode r = find((GroupNode) c, prefix); + if (r != null) { + return r; + } + } + } + return null; + } + + private static ArtNode findAttr(GroupNode g, String key) { + for (ArtNode c : g.getChildren()) { + if (c.getAttribute(key) != null) { + return c; + } + if (c instanceof GroupNode) { + ArtNode r = findAttr((GroupNode) c, key); + if (r != null) { + return r; + } + } + } + return null; + } + + private static String texts(GroupNode g) { + StringBuilder sb = new StringBuilder(); + for (ArtNode c : g.getChildren()) { + if (c instanceof TextNode) { + sb.append(((TextNode) c).getText()); + } else if (c instanceof GroupNode) { + sb.append(texts((GroupNode) c)); + } + } + return sb.toString(); + } +} diff --git a/maven/design-import/src/test/java/com/codename1/designimport/MockupHeuristicsTest.java b/maven/design-import/src/test/java/com/codename1/designimport/MockupHeuristicsTest.java new file mode 100644 index 00000000000..e95a30a4f27 --- /dev/null +++ b/maven/design-import/src/test/java/com/codename1/designimport/MockupHeuristicsTest.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// What a UI kit mockup draws that is not the app: the phone's home indicator, a picture +/// drawn as a pile of shapes, a tab bar wrapped in its own backdrop. Each shape here is the +/// geometry a real kit used, rebuilt by hand. +class MockupHeuristicsTest { + private static DNode node(String name, double x, double y, double w, double h) { + return new DNode(name, name, x, y, w, h); + } + + @Test + void namesMatchWordsNotLettersInsideWords() { + String[] field = {"input", "field", "edit"}; + assertFalse(Text.hasWord("credits", field), "Credits holds \"edit\" and is a chip"); + assertTrue(Text.hasWord("edit name", field)); + assertTrue(Text.hasWord("emailfield", field), "a lowered camel-case name ends with the word"); + assertTrue(Text.hasWord("input/email", field)); + } + + @Test + void homeIndicatorIsPhoneChrome() { + DNode screen = node("screen", 0, 0, 375, 812); + DNode bar = node("Rectangle", 120, 799, 134, 5); + assertTrue(StructureStage.isChrome(screen, bar, 1), "a thin centred bar at the bottom"); + DNode off = node("Rectangle", 10, 799, 134, 5); + assertFalse(StructureStage.isChrome(screen, off, 1), "not centred: a divider, not the indicator"); + DNode button = node("Button", 120, 760, 134, 44); + assertFalse(StructureStage.isChrome(screen, button, 1), "too tall to be the indicator"); + DNode named = node("Home Indicator", 0, 0, 10, 10); + assertTrue(StructureStage.isChrome(screen, named, 2), "named for it"); + DNode tabletScreen = node("screen", 0, 0, 1024, 768); + assertFalse(StructureStage.isChrome(tabletScreen, node("Rectangle", 412, 760, 200, 5), 1), + "landscape: no home indicator rule"); + } + + @Test + void overlappingShapesWithoutTextAreOnePicture() { + DNode art = node("Illustration", 0, 0, 200, 160); + DNode a = node("Oval", 0, 0, 120, 120); + DNode b = node("Path", 60, 40, 140, 120); + art.children.add(a); + art.children.add(b); + assertTrue(ClassifyStage.isIllustration(art, 0)); + assertFalse(ClassifyStage.isIllustration(art, 1), "text makes it UI"); + + DNode row = node("Row", 0, 0, 200, 40); + row.children.add(node("Oval", 0, 0, 40, 40)); + row.children.add(node("Oval", 60, 0, 40, 40)); + assertFalse(ClassifyStage.isIllustration(row, 0), "shapes side by side are separate items"); + } + + @Test + void bareWrapperAroundAPictureIsLeftAlone() { + DNode wrap = node("Screen Shot", 0, 0, 300, 200); + DNode pic = node("Image", 0, 0, 300, 200); + pic.role = DNode.Role.IMAGE; + wrap.children.add(pic); + assertFalse(ClassifyStage.isIllustration(wrap, 0), "a group around one picture adds nothing"); + DNode backdrop = node("Avatar", 0, 0, 80, 80); + backdrop.background = Integer.valueOf(0xffeeeeee); + backdrop.backgroundAlpha = 1; + DNode face = node("Image", 10, 10, 60, 60); + face.role = DNode.Role.IMAGE; + backdrop.children.add(face); + assertTrue(ClassifyStage.isIllustration(backdrop, 0), "a backdrop showing around the picture"); + } + + @Test + void tabBarAdoptsTheBackdropItIsWrappedIn() { + DNode bar = node("Tab Bar", 0, 730, 375, 82); + DNode backdrop = node("Background", 0, 730, 375, 82); + backdrop.background = Integer.valueOf(0xff101010); + backdrop.backgroundAlpha = 1; + for (int i = 0; i < 4; i++) { + backdrop.children.add(node("Tab " + i, 20 + i * 90, 745, 40, 40)); + } + bar.children.add(backdrop); + ClassifyStage.absorbWrapper(bar); + assertEquals(4, bar.children.size(), "the tabs are the bar's own children"); + assertEquals(Integer.valueOf(0xff101010), bar.background, "with the backdrop's colour"); + } +} diff --git a/maven/design-import/src/test/java/com/codename1/designimport/RoundTripTest.java b/maven/design-import/src/test/java/com/codename1/designimport/RoundTripTest.java new file mode 100644 index 00000000000..eaaaba906f0 --- /dev/null +++ b/maven/design-import/src/test/java/com/codename1/designimport/RoundTripTest.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtDocument; +import com.codename1.art.ArtFormats; +import com.codename1.art.SvgWriter; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import javax.swing.JPanel; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/// The proof that the importer works on forms whose answer is known. +/// +/// Each GUI Builder demo form is built, laid out on a phone screen, exported to SVG with +/// every layer renamed to what a design tool would call it, read back through the SVG reader +/// and imported. The import is then compared with the form it came from: did each component +/// come back as the right kind of component, in the right place, and does the result look +/// like the design? +class RoundTripTest { + static final Path DEMO = Paths.get("../../scripts/guibuilder/demo-project/src/main/guibuilder/com/example"); + + @BeforeAll + static void init() { + if (!com.codename1.ui.Display.isInitialized()) { + com.codename1.ui.Display.init(new JPanel()); + } + } + + static final class Result { + String name; + int originals; + int rolesRight; + int placed; + Fidelity fidelity; + ImportSession session; + List misses = new ArrayList(); + } + + static Result roundTrip(Path gui) throws Exception { + GuiForms forms = new GuiForms(); + Container screen = forms.build(gui); + double dp = Fidelity.dpPixels(); + int w = (int) Math.round(390 * dp); + int h = (int) Math.round(844 * dp); + GuiForms.layout(screen, w, h); + FormExporter ex = new FormExporter(); + ex.setStripNames(true); + ArtDocument design = ex.export(screen); + ByteArrayOutputStream svg = new ByteArrayOutputStream(); + SvgWriter.write(design, svg); + if (System.getProperty("designimport.svgdump") != null) { + Files.write(Paths.get(System.getProperty("designimport.svgdump")), svg.toByteArray()); + } + ArtDocument back = ArtFormats.read(svg.toByteArray()); + String name = gui.getFileName().toString().replace(".gui", ""); + ImportSession s = new ImportSession(back, name + ".svg"); + s.className = name; + s.designScale = dp; + Pipeline.run(s); + Result r = new Result(); + r.name = name; + r.session = s; + ImportSession.Variant v = s.primary(); + List leaves = new ArrayList(); + collect(v.root, leaves); + if (name.equals(System.getProperty("designimport.debug"))) { + for (Map.Entry e : forms.byName.entrySet()) { + Component c = e.getValue(); + System.out.println("ORIG " + e.getKey() + " " + c.getAbsoluteX() + "," + c.getAbsoluteY() + " " + c.getWidth() + + "x" + c.getHeight()); + } + System.out.println("origin " + v.originX + "," + v.originY + " size " + v.width + "x" + v.height); + debugTree(v.root, ""); + } + for (Map.Entry e : forms.byName.entrySet()) { + String type = forms.types.get(e.getKey()); + DNode.Role want = expected(type); + if (want == null) { + continue; + } + Component c = e.getValue(); + if (c.getWidth() <= 0 || c.getHeight() <= 0) { + // Laid out off screen (an overflowing row): nothing of it is in the design. + continue; + } + r.originals++; + DNode best = null; + double bestIou = 0; + for (int i = 0; i < leaves.size(); i++) { + DNode n = leaves.get(i); + int cx = c.getAbsoluteX() - screen.getAbsoluteX(); + int cy = c.getAbsoluteY() - screen.getAbsoluteY(); + double iou = Fidelity.iou(cx, cy, c.getWidth(), c.getHeight(), n.x, n.y, n.w, n.h); + if (want == DNode.Role.LABEL || want == DNode.Role.CHECKBOX) { + // A label component is as wide as its column; the design only has its text. + // Inside the component is the right place for it. + double ix = Math.max(0, Math.min(cx + c.getWidth(), n.right()) - Math.max(cx, n.x)); + double iy = Math.max(0, Math.min(cy + c.getHeight(), n.bottom()) - Math.max(cy, n.y)); + double inside = ix * iy / Math.max(1, n.w * n.h); + if (inside > 0.8 && n.h >= c.getHeight() * 0.25) { + iou = Math.max(iou, inside * 0.9); + } + } + if (iou > bestIou) { + bestIou = iou; + best = n; + } + } + if (best != null && bestIou >= 0.4) { + r.placed++; + if (best.role == want) { + r.rolesRight++; + } else { + r.misses.add(e.getKey() + ": " + type + " came back as " + best.role + " (" + best.reason + ")"); + } + } else { + r.misses.add(e.getKey() + ": " + type + " not found (best overlap " + Math.round(bestIou * 100) + "%)"); + } + } + Preview p = Preview.build(s, v.width / s.getEffectiveScale()); + r.fidelity = Fidelity.measure(s, p); + assertNull(p.cssError, name + ": generated CSS does not compile"); + GeneratedCompiles.check(name, s.code); + return r; + } + + static void debugTree(DNode n, String ind) { + System.out.println("NODE " + ind + n.role + " '" + n.name + "' " + Math.round(n.x) + "," + Math.round(n.y) + " " + + Math.round(n.w) + "x" + Math.round(n.h) + " " + n.layout + (n.rasterize ? " raster" : "") + + " (" + n.reason + ")"); + for (int i = 0; i < n.children.size(); i++) { + debugTree(n.children.get(i), ind + " "); + } + } + + private static void collect(DNode n, List out) { + for (int i = 0; i < n.children.size(); i++) { + DNode c = n.children.get(i); + if (c.role == DNode.Role.BUTTON || c.role == DNode.Role.TEXT_FIELD || c.role == DNode.Role.CHECKBOX + || c.role == DNode.Role.LABEL || c.role == DNode.Role.SWITCH || c.role == DNode.Role.LIST_ITEM) { + out.add(c); + if (c.role == DNode.Role.LABEL) { + continue; + } + } + collect(c, out); + } + } + + static DNode.Role expected(String type) { + if ("Button".equals(type)) { + return DNode.Role.BUTTON; + } + if ("TextField".equals(type)) { + return DNode.Role.TEXT_FIELD; + } + if ("CheckBox".equals(type)) { + return DNode.Role.CHECKBOX; + } + if ("Label".equals(type) || "SpanLabel".equals(type)) { + return DNode.Role.LABEL; + } + return null; + } + + static List demoForms() throws Exception { + List out = new ArrayList(); + DirectoryStream ds = Files.newDirectoryStream(DEMO, "*.gui"); + try { + for (Path p : ds) { + out.add(p); + } + } finally { + ds.close(); + } + java.util.Collections.sort(out); + return out; + } + + @Test + void everyDemoFormRoundTrips() throws Exception { + List forms = demoForms(); + assertTrue(forms.size() >= 12, "expected the GUI Builder demo forms at " + DEMO.toAbsolutePath()); + int originals = 0; + int right = 0; + int placed = 0; + double layout = 0; + double pixels = 0; + StringBuilder report = new StringBuilder(); + String only = System.getProperty("designimport.only"); + for (Path f : forms) { + if (only != null && !f.getFileName().toString().startsWith(only)) { + continue; + } + Result r = roundTrip(f); + originals += r.originals; + right += r.rolesRight; + placed += r.placed; + layout += r.fidelity.layout; + pixels += r.fidelity.pixels; + report.append(String.format("%-24s roles %2d/%2d placed %2d layout %.2f pixels %.2f issues %d%n", r.name, + r.rolesRight, r.originals, r.placed, r.fidelity.layout, r.fidelity.pixels, r.session.getIssues().size())); + for (String m : r.misses) { + report.append(" ").append(m).append('\n'); + } + } + System.out.println(report); + double roleRate = right / (double) originals; + double placedRate = placed / (double) originals; + System.out.println("roles " + right + "/" + originals + " placed " + placed + " layout " + + layout / forms.size() + " pixels " + pixels / forms.size()); + assertTrue(placedRate >= 0.9, "components placed: " + placedRate + "\n" + report); + assertTrue(roleRate >= 0.9, "roles recovered: " + roleRate + "\n" + report); + // Ratchets set just under what the importer measures today (roles 71/74, layout 0.61, + // pixels 0.80 over the twelve forms): raise them as it improves, never lower them. + assertTrue(layout / forms.size() >= 0.55, "layout overlap\n" + report); + assertTrue(pixels / forms.size() >= 0.75, "pixel similarity\n" + report); + } +} diff --git a/maven/design-import/src/test/java/com/codename1/designimport/ServiceTest.java b/maven/design-import/src/test/java/com/codename1/designimport/ServiceTest.java new file mode 100644 index 00000000000..d6dfa4a149b --- /dev/null +++ b/maven/design-import/src/test/java/com/codename1/designimport/ServiceTest.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import java.io.File; +import java.nio.file.Files; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.swing.JPanel; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/// Drives an import the way an LLM does over MCP: open, look, override, look again, emit. +class ServiceTest { + @BeforeAll + static void init() { + if (!com.codename1.ui.Display.isInitialized()) { + com.codename1.ui.Display.init(new JPanel()); + } + } + + private static Map args(Object... kv) { + Map m = new LinkedHashMap(); + for (int i = 0; i < kv.length; i += 2) { + m.put((String) kv[i], kv[i + 1]); + } + return m; + } + + private static Map ok(DesignImportService s, String op, Map a) { + Map r = new DesignImportMcpTools(s).invokeOnEdt(op, a); + assertEquals(Boolean.TRUE, r.get("success"), op + " failed: " + r.get("error")); + return r; + } + + @Test + void anImportDrivenThroughTheOperations() throws Exception { + DesignImportService s = new DesignImportService(); + assertEquals(Boolean.FALSE, s.call("tree", null).get("success"), "nothing is open yet"); + File design = new File("../../docs/developer-guide/sketch/new-gui-builder-left-toolbar.sketch").getAbsoluteFile(); + Map opened = ok(s, "open", args("path", design.getPath(), "options", + args("className", "LeftToolbarForm"))); + assertFalse(((List) opened.get("frames")).isEmpty(), "the artboard is a candidate frame"); + ok(s, "run", args()); + Map tree = (Map) ok(s, "tree", args("depth", Integer.valueOf(1))).get("tree"); + List kids = (List) tree.get("children"); + assertNotNull(kids); + Map first = (Map) kids.get(0); + String id = (String) first.get("id"); + + // Override that node, and the override survives the re-run and is in the options. + ok(s, "set", args("node", id, "role", "card", "uiid", "PaletteCard")); + Map again = (Map) ok(s, "tree", args("node", id, "depth", Integer.valueOf(0))).get("tree"); + assertEquals("card", again.get("role")); + Map opts = (Map) ok(s, "options", args()).get("options"); + assertTrue(((Map) opts.get("overrides")).containsKey(id)); + assertEquals(Boolean.FALSE, s.call("set", args("node", id, "role", "banana")).get("success")); + + List issues = (List) ok(s, "issues", args()).get("issues"); + if (!issues.isEmpty()) { + String issue = (String) ((Map) issues.get(0)).get("id"); + int before = s.getSession().openIssueCount(); + ok(s, "resolve", args("issue", issue)); + assertTrue(s.getSession().openIssueCount() <= before); + } + + Map fid = (Map) ok(s, "score", args()).get("fidelity"); + assertTrue(((Number) fid.get("layoutOverlap")).doubleValue() > 0.5, String.valueOf(fid)); + assertNotNull(ok(s, "preview", args("widthDp", Double.valueOf(360))).get("png")); + + File dir = Files.createTempDirectory("designimport-emit").toFile(); + List written = (List) ok(s, "emit", args("dir", dir.getPath())).get("written"); + assertTrue(written.contains("src/main/css/theme.css"), String.valueOf(written)); + String theme = new String(Files.readAllBytes(new File(dir, "src/main/css/theme.css").toPath()), "UTF-8"); + assertTrue(theme.startsWith("@import \"LeftToolbarForm.css\";"), theme); + assertTrue(containsSuffix(written, "LeftToolbarForm.java")); + // A second emit must leave the user's own subclass alone. + File user = find(dir, "LeftToolbarForm.java"); + assertNotNull(user); + Files.write(user.toPath(), "// mine".getBytes("UTF-8")); + ok(s, "emit", args("dir", dir.getPath())); + assertEquals(theme, new String(Files.readAllBytes(new File(dir, "src/main/css/theme.css").toPath()), "UTF-8"), + "the import is added once"); + assertEquals("// mine", new String(Files.readAllBytes(user.toPath()), "UTF-8")); + ok(s, "preview", args("path", new File(dir, "p.png").getPath(), "designPath", new File(dir, "d.png").getPath())); + assertTrue(new File(dir, "p.png").length() > 0 && new File(dir, "d.png").length() > 0); + } + + @Test + void everyOperationHasASchemaThatParses() throws Exception { + for (String op : DesignImportService.OPERATIONS) { + Map m = DesignImportMcpTools.parse(DesignImportMcpTools.schema(op)); + assertEquals("object", m.get("type"), op); + assertNotNull(DesignImportMcpTools.describe(op)); + } + } + + private static boolean containsSuffix(List l, String suffix) { + for (Object o : l) { + if (String.valueOf(o).endsWith(suffix)) { + return true; + } + } + return false; + } + + private static File find(File dir, String name) { + File[] fs = dir.listFiles(); + if (fs == null) { + return null; + } + for (File f : fs) { + if (f.isDirectory()) { + File r = find(f, name); + if (r != null) { + return r; + } + } else if (f.getName().equals(name)) { + return f; + } + } + return null; + } +} diff --git a/maven/design-import/src/test/java/com/codename1/designimport/SmokeTest.java b/maven/design-import/src/test/java/com/codename1/designimport/SmokeTest.java new file mode 100644 index 00000000000..7751289b6e1 --- /dev/null +++ b/maven/design-import/src/test/java/com/codename1/designimport/SmokeTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +import com.codename1.art.ArtDocument; +import com.codename1.art.ArtFormats; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import javax.swing.JPanel; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class SmokeTest { + static void dumpTree(com.codename1.art.ArtNode n, String ind) { + String extra = ""; + if (n instanceof com.codename1.art.GroupNode) { + com.codename1.art.GroupNode g = (com.codename1.art.GroupNode) n; + extra = " mask=" + (g.getMask() != null) + " clip=" + (g.getClipPath() != null) + " clipFrame=" + g.isClipToFrame(); + } + System.out.println("TREE " + ind + n.getClass().getSimpleName() + " '" + n.getName() + "' vis=" + n.isVisible() + + " op=" + n.getOpacity() + " b=" + java.util.Arrays.toString(n.getLocalBounds()) + extra); + if (n instanceof com.codename1.art.GroupNode) { + java.util.List ch = ((com.codename1.art.GroupNode) n).getChildren(); + for (int i = 0; i < ch.size(); i++) { + dumpTree(ch.get(i), ind + " "); + } + } + } + + static void dump(com.codename1.ui.Image img, File f) throws Exception { + int[] rgb = img.getRGB(); + java.awt.image.BufferedImage b = new java.awt.image.BufferedImage(img.getWidth(), img.getHeight(), + java.awt.image.BufferedImage.TYPE_INT_ARGB); + b.setRGB(0, 0, img.getWidth(), img.getHeight(), rgb, 0, img.getWidth()); + javax.imageio.ImageIO.write(b, "png", f); + } + + @BeforeAll + static void init() { + if (!com.codename1.ui.Display.isInitialized()) { + com.codename1.ui.Display.init(new JPanel()); + } + } + + @Test + void docsSketchFilesImport() throws Exception { + File dir = new File("../../docs/developer-guide/sketch"); + File[] files = dir.listFiles(); + assertNotNull(files, dir.getAbsolutePath()); + for (File f : files) { + if (!f.getName().endsWith(".sketch")) { + continue; + } + ArtDocument doc; + InputStream in = new FileInputStream(f); + try { + doc = ArtFormats.read(in); + } finally { + in.close(); + } + ImportSession s = new ImportSession(doc, f.getName()); + Pipeline.run(s); + System.out.println("== " + f.getName() + " " + s.getStageLog()); + System.out.println("issues=" + s.getIssues().size()); + for (int i = 0; i < Math.min(8, s.getIssues().size()); i++) { + System.out.println(" " + s.getIssues().get(i).toMap()); + } + assertNotNull(s.getCode()); + assertNotNull(s.getCode().baseSource); + Preview p = Preview.build(s, s.primary().width / s.getEffectiveScale()); + Fidelity fid = Fidelity.measure(s, p); + System.out.println("fidelity=" + fid.toMap() + " cssError=" + p.cssError); + assertNull(p.cssError, f.getName() + ": generated CSS does not compile"); + GeneratedCompiles.check(f.getName(), s); + // Held-out ratchet: these files are never tuned against. Measured today the worst + // is 0.56 layout and 0.65 pixels; raise the floors as the importer improves. + assertTrue(fid.layout >= 0.5, f.getName() + " layout overlap " + fid.layout); + assertTrue(fid.pixels >= 0.6, f.getName() + " pixel similarity " + fid.pixels); + String out = System.getProperty("designimport.dump"); + if (out != null) { + ImportSession.Variant v = s.primary(); + int w = Fidelity.size(s, v)[0]; + int h = Fidelity.size(s, v)[1]; + double k = w / v.width; + dump(Preview.designImage(s, v, w, h), new File(out, f.getName() + ".design.png")); + dump(p.snapshot(w, h), new File(out, f.getName() + ".built.png")); + com.codename1.art.Raster full = com.codename1.art.ArtRenderer.render(doc, 1); + dump(com.codename1.ui.Image.createImage(full.getPixels(), full.getWidth(), full.getHeight()), + new File(out, f.getName() + ".full.png")); + dumpTree(doc.getRoot(), ""); + for (java.util.Map.Entry e : p.components.entrySet()) { + DNode n = v.root.find(e.getKey()); + com.codename1.ui.Component c = e.getValue(); + System.out.println(" " + n.role + " " + n.name + " design=" + (int) (n.x * k) + "," + (int) (n.y * k) + " " + (int) (n.w * k) + + "x" + (int) (n.h * k) + " built=" + (c.getAbsoluteX() - p.root.getAbsoluteX()) + "," + + (c.getAbsoluteY() - p.root.getAbsoluteY()) + " " + c.getWidth() + "x" + c.getHeight()); + } + System.out.println(s.getCode().css); + } + } + } +} diff --git a/maven/design-import/src/test/java/com/codename1/designimport/WizardTest.java b/maven/design-import/src/test/java/com/codename1/designimport/WizardTest.java new file mode 100644 index 00000000000..4a5c15e3d1e --- /dev/null +++ b/maven/design-import/src/test/java/com/codename1/designimport/WizardTest.java @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import com.codename1.art.SvgWriter; +import com.codename1.ui.Display; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import javax.swing.JPanel; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// Walks the import wizard the way a person does, from a design with a phone and a tablet +/// frame to the form written into a project. +class WizardTest { + @BeforeAll + static void init() { + if (!Display.isInitialized()) { + Display.init(new JPanel()); + } + DesignImportApp.installTheme(); + } + + /// Paints the wizard as it stands; with `-Ddesignimport.examples=DIR` also saves it there + /// for the developer guide. + static void shot(ImportWizard w, String name) { + com.codename1.ui.Form f = w.getForm(); + f.setVisible(true); + f.setWidth(1600); + f.setHeight(1000); + f.setShouldCalcPreferredSize(true); + layoutAll(f); + com.codename1.ui.Image img = com.codename1.ui.Image.createImage(1600, 1000, 0xff000000); + f.paintComponent(img.getGraphics(), true); + String dir = System.getProperty("designimport.examples"); + if (dir == null) { + return; + } + File out = new File(dir); + // The gallery directory may not exist yet (the job builds the app after these + // tests); a throw here runs on the EDT and leaves callSeriallyAndWait waiting. + if (!out.isDirectory() && !out.mkdirs()) { + return; + } + try { + OutputStream o = new FileOutputStream(new File(out, name)); + try { + com.codename1.ui.util.ImageIO.getImageIO().save(img, o, com.codename1.ui.util.ImageIO.FORMAT_PNG, 1); + } finally { + o.close(); + } + } catch (java.io.IOException ex) { + throw new IllegalStateException(ex); + } + } + + @Test + void anAppFolderGivesTheModuleAndThePackage(@org.junit.jupiter.api.io.TempDir Path tmp) throws Exception { + if (!Display.isInitialized()) { + Display.init(new javax.swing.JPanel()); + } + File root = tmp.toFile(); + File common = new File(root, "common"); + assertTrue(new File(common, "src/main/java").mkdirs()); + Files.write(new File(common, "codenameone_settings.properties").toPath(), + "codename1.packageName=com.example.myapp\n".getBytes(StandardCharsets.UTF_8)); + ImportWizard w = new ImportWizard(new DesignImportService(), new ImportWizard.Config(), null); + onEdt(() -> { + w.useProject(root.getPath()); + assertTrue(w.intoText().replace('\\', '/').endsWith("common/src/main/java/com/example/myapp"), w.intoText()); + }); + } + + static void assertFitsWidth(com.codename1.ui.Container c, int width) { + for (int i = 0; i < c.getComponentCount(); i++) { + com.codename1.ui.Component k = c.getComponentAt(i); + int right = k.getAbsoluteX() - c.getAbsoluteX() + k.getWidth() + c.getAbsoluteX(); + int edge = c.getAbsoluteX() + (c.isScrollableX() ? Integer.MAX_VALUE / 2 : c.getWidth()); + assertTrue(right <= edge + 1, k.getUIID() + " ends at " + right + ", past its parent " + c.getUIID() + " at " + edge); + if (k instanceof com.codename1.ui.Container && !c.isScrollableX()) { + assertFitsWidth((com.codename1.ui.Container) k, width); + } + } + } + + static void layoutAll(com.codename1.ui.Container c) { + c.layoutContainer(); + for (int i = 0; i < c.getComponentCount(); i++) { + if (c.getComponentAt(i) instanceof com.codename1.ui.Container) { + layoutAll((com.codename1.ui.Container) c.getComponentAt(i)); + } + } + } + + /// Runs on the EDT and rethrows here what it threw there; callSeriallyAndWait alone never + /// returns when the runnable throws, and the test hangs instead of failing. + static void onEdt(Runnable r) throws Exception { + java.util.concurrent.atomic.AtomicReference err = new java.util.concurrent.atomic.AtomicReference<>(); + Display.getInstance().callSeriallyAndWait(() -> { + try { + r.run(); + } catch (Throwable t) { + err.set(t); + } + }); + if (err.get() instanceof Exception) { + throw (Exception) err.get(); + } + if (err.get() != null) { + throw new AssertionError(err.get()); + } + } + + /// Runs the EDT until the wizard finished writing. + static void waitFor(ImportWizard w) throws Exception { + for (int i = 0; i < 400 && !w.finished(); i++) { + onEdt(() -> { }); + } + assertTrue(w.finished(), "the wizard finished writing"); + } + + /// A design with three unrelated screens: all are chosen, a press on one card leaves it + /// out, and the two left are written as two forms into one project. + @Test + void severalScreensBecomeSeveralForms(@TempDir Path tmp) throws Exception { + double dp = Fidelity.dpPixels(); + com.codename1.art.ArtDocument three = new com.codename1.art.ArtDocument( + Math.round((ExamplesTest.PHONE_W + 100) * 3 * dp), Math.round(ExamplesTest.PHONE_H * dp)); + String[] names = {"Login", "Profile", "Settings"}; + for (int i = 0; i < 3; i++) { + com.codename1.art.ArtDocument one = ExamplesTest.export(ExamplesTest.form("LoginForm"), + ExamplesTest.PHONE_W, ExamplesTest.PHONE_H); + com.codename1.art.ArtNode f = one.getRoot().getChildren().get(0); + one.getRoot().getChildren().remove(f); + f.setName(names[i]); + f.setTransform(com.codename1.art.Matrix.translate((ExamplesTest.PHONE_W + 100) * i * dp, 0)); + three.getRoot().getChildren().add(f); + } + File design = tmp.resolve("three.svg").toFile(); + OutputStream o = new FileOutputStream(design); + try { + SvgWriter.write(three, o); + } finally { + o.close(); + } + File app = tmp.resolve("app").toFile(); + File css = new File(app, "src/main/css/theme.css"); + assertTrue(css.getParentFile().mkdirs()); + Files.write(css.toPath(), "/* app */\n".getBytes(StandardCharsets.UTF_8)); + final ImportWizard.Config c = new ImportWizard.Config(); + c.project = app.getAbsolutePath(); + c.design = design.getAbsolutePath(); + c.packageName = "com.acme.multi"; + final AtomicReference ref = new AtomicReference(); + final DesignImportService service = new DesignImportService(); + onEdt(() -> { + ImportWizard w = new ImportWizard(service, c, null); + ref.set(w); + w.start(); + }); + final ImportWizard w = ref.get(); + assertEquals(1, w.step(), "several screens: the wizard asks which"); + assertEquals(3, w.screens().size()); + assertEquals(3, w.chosen().size(), "every screen is chosen to begin with"); + Display.getInstance().callSeriallyAndWait(() -> shot(w, "wizard-screen.png")); + // Typing a filter while scrolled down starts the results at the top, where they are. + onEdt(() -> { + com.codename1.ui.Form f = w.getForm(); + f.setWidth(400); + f.setHeight(480); + f.revalidate(); + com.codename1.ui.Container sc = w.screenGrid().getParent(); + sc.setSmoothScrolling(false); + sc.scrollRectToVisible(0, sc.getScrollDimension().getHeight() - 1, 1, 1, sc); + sc.setSmoothScrolling(true); + assertTrue(sc.getScrollY() > 0, "the grid scrolls at this size"); + w.filterField().setText("o"); + assertEquals(0, w.screenGrid().getParent().getScrollY(), "a new filter shows its results from the top"); + w.filterField().setText(""); + }); + // A real press on the second card, the way a person leaves a screen out. + onEdt(() -> { + com.codename1.ui.Component card = cardOf(w.getForm(), "Profile"); + assertTrue(card != null, "the Profile card is shown"); + int x = card.getAbsoluteX() + card.getWidth() / 2; + int y = card.getAbsoluteY() + card.getHeight() / 2; + w.getForm().pointerPressed(x, y); + w.getForm().pointerReleased(x, y); + }); + assertEquals(2, w.chosen().size(), "the pressed card is left out, and stays out"); + // Back to the first step and forward again rebuilds the page around the same filter + // field; that once threw "already contained". Typing narrows the cards. + onEdt(() -> { + w.go(0); + w.go(1); + w.go(1); + }); + onEdt(() -> { + com.codename1.ui.TextField f = filterOf(w.getForm()); + f.setText("sett"); + assertTrue(cardOf(w.getForm(), "Settings") != null); + assertTrue(cardOf(w.getForm(), "Login") == null, "filtered out"); + f.setText(""); + }); + assertTrue(!w.screens().get(1).chosen); + // Every step rebuilt from every other: each rebuild re-adds components that live as + // long as the wizard, the class of bug that threw twice. + onEdt(() -> { + for (int from = 0; from < 3; from++) { + for (int to = 0; to < 3; to++) { + w.go(from); + w.go(to); + } + } + }); + // A step already passed is a button back to it, pressed as a person would. + onEdt(() -> { + w.go(2); + w.getForm().revalidate(); + }); + onEdt(() -> { + com.codename1.ui.Component chip = buttonText(w.getForm(), "2 Screens"); + assertTrue(chip != null && chip.isEnabled(), "the passed step is a button"); + int x = chip.getAbsoluteX() + chip.getWidth() / 2; + int y = chip.getAbsoluteY() + chip.getHeight() / 2; + w.getForm().pointerPressed(x, y); + w.getForm().pointerReleased(x, y); + }); + assertEquals(1, w.step(), "pressing a passed step goes back to it"); + assertTrue(com.codename1.ui.plaf.UIManager.getInstance().getLookAndFeel().isInteractiveScroll(), + "desktop scrollbars: a click on the track pages, the thumb drags"); + assertEquals(2, w.chosen().size(), "going back keeps the choice"); + Display.getInstance().callSeriallyAndWait(w::forward); + assertEquals(2, w.step()); + Display.getInstance().callSeriallyAndWait(w::forward); + Display.getInstance().callSeriallyAndWait(w::forward); + waitFor(w); + File pkg = new File(app, "src/main/java/com/acme/multi"); + String theme = new String(Files.readAllBytes(css.toPath()), StandardCharsets.UTF_8); + for (String n : new String[]{"LoginForm", "SettingsForm"}) { + assertTrue(new File(pkg, n + "Base.java").isFile(), n + " is written"); + assertTrue(theme.contains(n + ".css"), n + "'s stylesheet is imported once"); + assertEquals(theme.indexOf(n + ".css"), theme.lastIndexOf(n + ".css")); + } + assertTrue(!new File(pkg, "ProfileFormBase.java").exists(), "the screen left out is not written"); + } + + static com.codename1.ui.Component buttonText(com.codename1.ui.Container c, String text) { + for (int i = 0; i < c.getComponentCount(); i++) { + com.codename1.ui.Component k = c.getComponentAt(i); + if (k instanceof com.codename1.ui.Button && text.equals(((com.codename1.ui.Button) k).getText())) { + return k; + } + if (k instanceof com.codename1.ui.Container) { + com.codename1.ui.Component f = buttonText((com.codename1.ui.Container) k, text); + if (f != null) { + return f; + } + } + } + return null; + } + + static com.codename1.ui.TextField filterOf(com.codename1.ui.Container c) { + for (int i = 0; i < c.getComponentCount(); i++) { + com.codename1.ui.Component k = c.getComponentAt(i); + if (k instanceof com.codename1.ui.TextField && "Filter screens by name".equals(((com.codename1.ui.TextField) k).getHint())) { + return (com.codename1.ui.TextField) k; + } + if (k instanceof com.codename1.ui.Container) { + com.codename1.ui.TextField f = filterOf((com.codename1.ui.Container) k); + if (f != null) { + return f; + } + } + } + return null; + } + + static com.codename1.ui.Component cardOf(com.codename1.ui.Container c, String name) { + for (int i = 0; i < c.getComponentCount(); i++) { + com.codename1.ui.Component k = c.getComponentAt(i); + if (k instanceof com.codename1.ui.Label && name.equals(((com.codename1.ui.Label) k).getText()) + && "WizardCardName".equals(k.getUIID())) { + com.codename1.ui.Component p = k; + while (p != null && !"WizardCard".equals(p.getUIID()) && !"WizardCardOn".equals(p.getUIID())) { + p = p.getParent(); + } + return p; + } + if (k instanceof com.codename1.ui.Container) { + com.codename1.ui.Component f = cardOf((com.codename1.ui.Container) k, name); + if (f != null) { + return f; + } + } + } + return null; + } + + @Test + void fromDesignToWrittenForm(@TempDir Path tmp) throws Exception { + File design = tmp.resolve("login.svg").toFile(); + OutputStream o = new FileOutputStream(design); + try { + SvgWriter.write(ExamplesTest.adaptiveDocument(), o); + } finally { + o.close(); + } + File app = tmp.resolve("app").toFile(); + File css = new File(app, "src/main/css/theme.css"); + assertTrue(css.getParentFile().mkdirs()); + Files.write(css.toPath(), "/* app */\n".getBytes(StandardCharsets.UTF_8)); + + final ImportWizard.Config c = new ImportWizard.Config(); + c.project = app.getAbsolutePath(); + c.design = design.getAbsolutePath(); + c.packageName = "com.acme.shop"; + final AtomicBoolean finished = new AtomicBoolean(); + c.onFinish = () -> finished.set(true); + final AtomicReference ref = new AtomicReference(); + final DesignImportService service = new DesignImportService(); + onEdt(() -> { + ImportWizard w = new ImportWizard(service, c, null); + ref.set(w); + w.start(); + }); + final ImportWizard w = ref.get(); + // Two frames of one screen: paired, so the wizard goes straight to the review. + assertEquals(1, w.screens().size(), String.valueOf(service.call("frames", null))); + assertEquals(2, w.screens().get(0).frames.size(), "the phone and tablet frames are one screen"); + assertEquals(2, w.step()); + assertEquals(2, service.getSession().variants.size()); + Display.getInstance().callSeriallyAndWait(() -> shot(w, "wizard-review.png")); + // The form is laid out at its own screen width inside the scrolling stage: nothing runs + // past the right edge (a scrolling parent once made every container take its preferred + // width, so a long line pushed the whole form wider than the screen). + onEdt(() -> { + com.codename1.ui.Container root = w.workbench().liveView().getShown().root; + assertTrue(root.getWidth() > 0, "the form is laid out"); + assertFitsWidth(root, root.getWidth()); + }); + // Every issue about an element says where it is, and the guide outlines it on both sides. + for (Issue is : service.getSession().getIssues()) { + if (is.nodeId != null) { + assertTrue(is.bounds != null, "issue without bounds: " + is.message); + } + } + onEdt(() -> { + Workbench wb = w.workbench(); + Issue first = null; + for (Issue is : wb.walk()) { + if (is.nodeId != null && Workbench.find(service.getSession().primary().root, is.nodeId) != null) { + first = is; + break; + } + } + assertTrue(first != null, "an element issue to walk to"); + wb.guideTo(first.id); + assertEquals(first.nodeId, wb.selected()); + assertTrue(wb.designView().getMark() != null, "outlined on the design"); + assertTrue(wb.liveView().getMarked() != null, "outlined on the form"); + for (Issue is : wb.walk()) { + if (is.nodeId != null && !"classify".equals(is.stage) && wb.alternatives(is).isEmpty()) { + org.junit.jupiter.api.Assertions.fail("no alternative offered for " + is.kind + ": " + is.message); + } + } + int before = wb.walk().size(); + wb.acceptNotes(); + assertTrue(wb.walk().size() <= before); + }); + Display.getInstance().callSeriallyAndWait(w::forward); + assertEquals(3, w.step()); + Display.getInstance().callSeriallyAndWait(() -> shot(w, "wizard-write.png")); + // Where the forms go follows the package; there is no directory to type. + onEdt(() -> { + assertTrue(w.intoText().replace('\\', '/').endsWith("src/main/java/com/acme/shop"), w.intoText()); + w.setPackage("com.acme.store.ui"); + assertTrue(w.intoText().replace('\\', '/').endsWith("src/main/java/com/acme/store/ui"), w.intoText()); + w.setPackage("com.acme.shop"); + }); + // Back to the review and forward again builds the write page a second time: its fields + // are kept between the two and once threw "already contained in Container". + Display.getInstance().callSeriallyAndWait(() -> w.go(2)); + assertEquals(2, w.step()); + Display.getInstance().callSeriallyAndWait(w::forward); + assertEquals(3, w.step()); + Display.getInstance().callSeriallyAndWait(w::forward); + waitFor(w); + String cls = service.getSession().getCode().className; + File pkg = new File(app, "src/main/java/com/acme/shop"); + assertTrue(new File(pkg, cls + "Base.java").isFile(), "the base class is written"); + assertTrue(new File(pkg, cls + ".java").isFile(), "the subclass is written"); + assertTrue(new String(Files.readAllBytes(css.toPath()), StandardCharsets.UTF_8).contains(cls + ".css"), + "the form's stylesheet is imported from theme.css"); + // What was written compiles, passes its own test and paints the screen the review showed. + GeneratedCompiles.check("wizard", service.getSession()); + Display.getInstance().callSeriallyAndWait(w::forward); + assertTrue(finished.get(), "Close ends the wizard"); + } +} diff --git a/maven/integration-tests/gradle-app-test.sh b/maven/integration-tests/gradle-app-test.sh index d0a25b5c40e..8ba9225d576 100755 --- a/maven/integration-tests/gradle-app-test.sh +++ b/maven/integration-tests/gradle-app-test.sh @@ -64,6 +64,18 @@ public interface Greeter extends NativeInterface { String greet(String name); } EOF +# importDesign resolves codenameone-design-import on demand, forks it, and the form it +# writes must then compile with the app, stylesheet included. +DESIGN="$SCRIPTPATH/../../docs/developer-guide/sketch/new-gui-builder-property-sheet.sketch" +run_gradle "$APP" importDesign -Pcn1.design="$DESIGN" -Pcn1.design.class=SheetForm > "$WORKDIR/design.log" 2>&1 \ + || { cat "$WORKDIR/design.log"; fail "importDesign"; } +grep -q "\[design-import\] emit:" "$WORKDIR/design.log" || { cat "$WORKDIR/design.log"; fail "importDesign printed no progress"; } +[ -n "$(find "$APP/src/main/java" -name SheetFormBase.java)" ] || fail "importDesign wrote no form" +run_gradle "$APP" classes cn1Css > "$WORKDIR/design-build.log" 2>&1 \ + || { cat "$WORKDIR/design-build.log"; fail "the imported design does not build"; } +find "$APP/src" \( -name 'SheetForm*' -o -name 'sheet*' -o -name 'newguibuilderpropertysheet*' \) -exec rm -f {} + +sed -i.bak '/SheetForm.css/d' "$APP/src/main/css/theme.css" && rm -f "$APP/src/main/css/theme.css.bak" + run_gradle "$APP" generateNativeInterfaces > "$WORKDIR/ni.log" 2>&1 || { cat "$WORKDIR/ni.log"; fail "generateNativeInterfaces"; } ANDROID_IMPL="$APP/src/android/java/$PKG_PATH/GreeterImpl.java" IOS_IMPL="$APP/src/ios/objectivec/com_acme_gradleapp_GreeterImpl.m" diff --git a/maven/pom.xml b/maven/pom.xml index bc516fa4173..5d8d2addf2a 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -134,6 +134,7 @@ css-cli + design-import android ios mac diff --git a/scripts/check-copyright-headers.sh b/scripts/check-copyright-headers.sh index e5470969b69..be32b90b0bf 100755 --- a/scripts/check-copyright-headers.sh +++ b/scripts/check-copyright-headers.sh @@ -44,6 +44,12 @@ is_excluded() { case "$candidate" in scripts/wayline/*|scripts/savor/*|scripts/bazaar/*|scripts/skirmish/*|scripts/dash/*|scripts/parley/*|scripts/bastion/*|scripts/reel/*|scripts/pulse/*|scripts/slate/*|scripts/splat/*|scripts/papercut/*|scripts/fieldline/*|scripts/brickyard/*|maven/cn1app-archetype/src/main/resources/archetype-resources/*|scripts/initializr/common/src/main/resources/skill/*) return 0 ;; esac + # Design Import's gallery is the tool's own output, regenerated by ExamplesTest: a form, + # a stylesheet and a test written for whoever runs the tool, which carry no header by + # design. Adding one by hand would be overwritten on the next regeneration. + case "$candidate" in + scripts/designimport/examples/*) return 0 ;; + esac awk -F '\\|' -v candidate="$candidate" ' /^[[:space:]]*(#|$)/ { next } { diff --git a/scripts/designimport/.gitignore b/scripts/designimport/.gitignore new file mode 100644 index 00000000000..2f7896d1d13 --- /dev/null +++ b/scripts/designimport/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/scripts/designimport/common/codenameone_settings.properties b/scripts/designimport/common/codenameone_settings.properties new file mode 100644 index 00000000000..9437c7a508d --- /dev/null +++ b/scripts/designimport/common/codenameone_settings.properties @@ -0,0 +1,7 @@ +codename1.packageName=com.codename1.designimport +codename1.mainName=DesignImportTool +codename1.displayName=Codename One Design Import +codename1.version=1.0 +codename1.vendor=Codename One +codename1.cssTheme=true +codename1.arg.java.version=17 diff --git a/scripts/designimport/common/pom.xml b/scripts/designimport/common/pom.xml new file mode 100644 index 00000000000..b14116a0eb8 --- /dev/null +++ b/scripts/designimport/common/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + com.codenameone.designimportcn1-designimport8.0-SNAPSHOT + cn1-designimport-common + common + + org.codehaus.mojoproperties-maven-plugin1.0.0initializeread-project-properties${basedir}/codenameone_settings.properties + com.codenameonecodenameone-maven-plugin${cn1.plugin.version}true + cn1-process-classesprocess-classesbytecode-compliancecssprocess-annotations + attach-test-artifacttestattach-test-artifact + + org.apache.maven.pluginsmaven-surefire-plugintruefalse + + + com.codenameonecodenameone-core + + com.codenameonecodenameone-design-import${cn1.version} + org.junit.jupiterjunit-jupiter-api5.10.2test + org.junit.jupiterjunit-jupiter-engine5.10.2test + + diff --git a/scripts/designimport/common/src/main/css/theme.css b/scripts/designimport/common/src/main/css/theme.css new file mode 100644 index 00000000000..a9d5c61f5bb --- /dev/null +++ b/scripts/designimport/common/src/main/css/theme.css @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +/* The tool styles itself: DesignImportApp compiles workbench.css from the codenameone-design-import jar. */ diff --git a/scripts/designimport/common/src/main/java/com/codename1/designimport/DesignImportTool.java b/scripts/designimport/common/src/main/java/com/codename1/designimport/DesignImportTool.java new file mode 100644 index 00000000000..61933754d24 --- /dev/null +++ b/scripts/designimport/common/src/main/java/com/codename1/designimport/DesignImportTool.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +/// The Design Import desktop app as a Codename One application. Everything is in +/// [DesignImportApp], in the `codenameone-design-import` jar the build tools run. +public class DesignImportTool extends DesignImportApp { +} diff --git a/scripts/designimport/design-import.sh b/scripts/designimport/design-import.sh new file mode 100755 index 00000000000..7345c78557a --- /dev/null +++ b/scripts/designimport/design-import.sh @@ -0,0 +1,80 @@ +#!/bin/bash +# Builds the Design Import tool against this working tree and runs it. +# +# ./design-import.sh the desktop app, run from inside a Codename One +# project or with DESIGNIMPORT_PROJECT set (set DESIGNIMPORT_MCP_PORT to +# also serve MCP on a loopback port) +# ./design-import.sh DESIGN OUT_DIR [Class] headless: import, emit into OUT_DIR, write +# preview.png and design.png, print the score +# ./design-import.sh --script ops.json headless: play [{op, args}] and print results +# ./design-import.sh --mcp-stdio headless MCP server on stdin/stdout +# ./design-import.sh --mcp-smoke checks the MCP server answers a real session +# +# Builds against the checkout's own Maven repository, never ~/.m2 (see CLAUDE.md). +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$HERE/../.." && pwd)" +REPO="${MAVEN_REPO_LOCAL:-$ROOT/maven/.m2-repo}" +export MAVEN_OPTS="${MAVEN_OPTS:-} -Dmaven.repo.local=$REPO" +# shellcheck disable=SC1091 +# Only when no working JDK is set: env.sh names a workstation's own JDK paths, and on a CI +# runner it would replace a valid JAVA_HOME with one that does not exist there. +if [ -z "${JAVA_HOME:-}" ] || [ ! -x "${JAVA_HOME}/bin/java" ]; then + source "$ROOT/tools/env.sh" >/dev/null 2>&1 || true +fi + +# The project the forms go into: where the script was started, unless DESIGNIMPORT_PROJECT says. +PROJECT="${DESIGNIMPORT_PROJECT:-$PWD}" +cd "$HERE" +if [ "${DESIGNIMPORT_SKIP_BUILD:-}" != "1" ]; then + mvn -B -q ${DESIGNIMPORT_MVN_OFFLINE--o} install -DskipTests -Dmaven.repo.local="$REPO" >&2 +fi +CP_FILE="$HERE/javase/target/designimport.classpath" +(cd javase && mvn -B -q ${DESIGNIMPORT_MVN_OFFLINE--o} dependency:build-classpath -Dmdep.outputFile="$CP_FILE" -Dmaven.repo.local="$REPO" >&2) +CP="$HERE/javase/target/classes:$(cat "$CP_FILE")" + +if [ "${1:-}" = "--mcp-smoke" ]; then + DESIGN="$ROOT/docs/developer-guide/sketch/new-gui-builder-drag-button.sketch" + OUT="$(mktemp -d)" + trap 'rm -rf "$OUT"' EXIT + { + printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"smoke","version":"1"}}}' \ + '{"jsonrpc":"2.0","method":"notifications/initialized"}' \ + '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \ + "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"designimport_open\",\"arguments\":{\"path\":\"$DESIGN\"}}}" \ + '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"designimport_run","arguments":{}}}' \ + '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"designimport_score","arguments":{}}}' + sleep "${DESIGNIMPORT_SMOKE_WAIT:-30}" + } | java -Djava.awt.headless=true -cp "$CP" com.codename1.designimport.DesignImportCli --mcp-stdio >"$OUT/out" 2>"$OUT/err" & + PID=$! + # Bounded: a server that ignores the closed stream must not hang the check. + ( sleep $(( ${DESIGNIMPORT_SMOKE_WAIT:-30} + 30 )); pkill -f "DesignImportCli --mcp-stdio" 2>/dev/null ) & + KILLER=$! + wait "$PID" || true + kill "$KILLER" 2>/dev/null || true + wait "$KILLER" 2>/dev/null || true + python3 - "$OUT/out" <<'PY' +import json, sys +seen = {} +for line in open(sys.argv[1]): + line = line.strip() + if not line: + continue + msg = json.loads(line) # anything but JSON-RPC on stdout breaks a client + seen[msg.get("id")] = msg.get("result", {}) +names = {t["name"] for t in seen.get(2, {}).get("tools", [])} +missing = {"designimport_" + o for o in "open frames options run tree issues set resolve preview score emit".split()} - names +assert not missing, "tools missing: %s" % sorted(missing) +for i in (3, 4, 5): + body = json.loads(seen[i]["content"][0]["text"]) + assert body.get("success"), "call %d failed: %s" % (i, body) +score = json.loads(seen[5]["content"][0]["text"])["fidelity"] +print("mcp smoke ok: %d tools, layout %.2f, pixels %.2f" % (len(names), score["layoutOverlap"], score["pixelSimilarity"])) +PY + exit 0 +fi + +if [ $# -gt 0 ]; then + exec java -Djava.awt.headless=true -cp "$CP" com.codename1.designimport.DesignImportCli "$@" +fi +exec java ${DESIGNIMPORT_MCP_PORT:+-Ddesignimport.mcp.port=$DESIGNIMPORT_MCP_PORT} -Ddesignimport.project="$PROJECT" -cp "$CP" com.codename1.designimport.DesignImportLauncher diff --git a/scripts/designimport/examples/README.md b/scripts/designimport/examples/README.md new file mode 100644 index 00000000000..53c9e35bf43 --- /dev/null +++ b/scripts/designimport/examples/README.md @@ -0,0 +1,36 @@ +# Design Import examples + +Every example here was written by `ExamplesTest` and is rewritten the same way: + +```bash +cd maven +mvn -o test -pl design-import -Dtest=ExamplesTest -Dmaven.repo.local=$PWD/.m2-repo \ + -Ddesignimport.argLine="-Ddesignimport.examples=$PWD/../scripts/designimport/examples" +``` + +Each folder holds `before.png` (the design, rendered), `after.png` (the generated form, +running), the generated `*Base.java`, `*.css` and `*Test.java`, and `issues.md`: the warnings, +TODOs and CSS compromises the import raised. `scores.md` has the numbers. + +- **`svg/`** -- the twelve GUI Builder demo forms (`scripts/guibuilder/demo-project`), built + with a fixed theme, exported to SVG with every layer renamed the way a design tool names + layers nobody named ("Group 8", "Rectangle 9"), and imported again. The answer is known, so + `RoundTripTest` scores it: 71 of 74 components come back as the right kind of component. +- **`psd/`** -- the same forms written as PSD, which flattens shapes and text to pixels. The + result is an image of a UI, and the import says so with a `flattened` warning rather than + passing it off; its high scores are a picture matching itself. +- **`adaptive/`** -- one form laid out for a phone and a tablet, as two frames named + `Login / Phone` and `Login / Tablet`. They are linked as variants of one form, which + switches layout at a width breakpoint. +- **`skin/`** -- the phone screen pasted into a device mockup with a bezel and a status bar. + The import steps past the skin and imports the screen. + +| Example | Before | After | +|---|---|---| +| `svg/LoginForm` | ![](svg/LoginForm/before.png) | ![](svg/LoginForm/after.png) | +| `svg/GridLayoutForm` | ![](svg/GridLayoutForm/before.png) | ![](svg/GridLayoutForm/after.png) | +| `svg/TableLayoutForm` | ![](svg/TableLayoutForm/before.png) | ![](svg/TableLayoutForm/after.png) | +| `svg/NestedLayoutsForm` | ![](svg/NestedLayoutsForm/before.png) | ![](svg/NestedLayoutsForm/after.png) | +| `adaptive/Login` | ![](adaptive/Login/before.png) | ![](adaptive/Login/after.png) | +| `skin/Login` | ![](skin/Login/before.png) | ![](skin/Login/after.png) | +| `psd/BorderDropForm` | ![](psd/BorderDropForm/before.png) | ![](psd/BorderDropForm/after.png) | diff --git a/scripts/designimport/examples/adaptive/Login/LoginForm.css b/scripts/designimport/examples/adaptive/Login/LoginForm.css new file mode 100644 index 00000000000..359e4e94c70 --- /dev/null +++ b/scripts/designimport/examples/adaptive/Login/LoginForm.css @@ -0,0 +1,234 @@ +/* Generated by Codename One Design Import from login-adaptive.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --login-color-1: #ffffff; + --login-color-2: #1e3a8a; + --login-color-3: #111827; + --login-color-4: #4b5563; + --login-color-5: #94a3b8; + --login-color-6: #9298a2; + --login-color-7: #2563eb; +} + +LoginScreen { + background-color: #ffffff; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +LoginToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.31mm 23.76mm 4.1mm 23.76mm; + margin: 0; +} + +LoginSignIn { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +LoginContent { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +LoginContainer { + background-color: transparent; + border: none; + padding: 4.31mm 3.42mm 75.16mm 3.01mm; + margin: 0; +} + +LoginWelcomeBack { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginSignInToContinue { + background-color: transparent; + border: none; + color: #4b5563; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginTextField { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 32.49mm 2.83mm 2.51mm; + margin: 0; +} + +LoginTextFieldHint { + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 2.51mm 2.83mm 2.51mm; + background-color: transparent; + border: none; + margin: 0; +} + +LoginTextField2 { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 38.24mm 2.83mm 2.51mm; + margin: 0; +} + +LoginTextField2Hint { + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 2.51mm 2.83mm 2.51mm; + background-color: transparent; + border: none; + margin: 0; +} + +LoginCheckbox { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0.91mm 0 0.91mm 0; + margin: 0; +} + +LoginCheckbox2 { + background-color: transparent; + border: 0.23mm solid #111827; + border-radius: 1.19mm; + padding: 0 0 0 0; + margin: 0; +} + +LoginRememberMe { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 22.75mm 2.11mm 22.75mm; + margin: 0; +} + +LoginToolbar2 { + background-color: #1e3a8a; + border: none; + padding: 4.31mm 57.92mm 4.1mm 57.92mm; + margin: 0; +} + +LoginContainer2 { + background-color: transparent; + border: none; + padding: 4.31mm 3.42mm 128.41mm 3.01mm; + margin: 0; +} + +LoginTextField3 { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 100.82mm 2.83mm 2.51mm; + margin: 0; +} + +LoginTextField3Hint { + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 2.51mm 2.83mm 2.51mm; + background-color: transparent; + border: none; + margin: 0; +} + +LoginTextField4 { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 106.56mm 2.83mm 2.51mm; + margin: 0; +} + +LoginTextField4Hint { + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 2.51mm 2.83mm 2.51mm; + background-color: transparent; + border: none; + margin: 0; +} + +LoginButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 56.91mm 2.11mm 56.91mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/adaptive/Login/LoginFormBase.java b/scripts/designimport/examples/adaptive/Login/LoginFormBase.java new file mode 100644 index 00000000000..6e7120cd156 --- /dev/null +++ b/scripts/designimport/examples/adaptive/Login/LoginFormBase.java @@ -0,0 +1,184 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from login-adaptive.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [LoginForm], which extends it. +public class LoginFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 130.22f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + /// At or above this width the tablet arrangement is used. + protected static final float TABLET_BREAKPOINT_MM = 95.25f; + + protected Label signIn; + protected Label welcomeBack; + protected Label signInToContinue; + protected TextField emailAddressField; + protected TextField passwordField; + protected CheckBox rememberMeCheck; + protected Button signInButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public LoginFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + signIn = new Label("Sign in"); + signIn.setUIID("LoginSignIn"); + signIn.setName("signIn"); + welcomeBack = new Label("Welcome back"); + welcomeBack.setUIID("LoginWelcomeBack"); + welcomeBack.setName("welcomeBack"); + signInToContinue = new Label("Sign in to continue to your Codename One project."); + signInToContinue.setUIID("LoginSignInToContinue"); + signInToContinue.setName("signInToContinue"); + emailAddressField = new TextField("", "Email address", 20, TextField.ANY); + emailAddressField.setUIID("LoginTextField"); + emailAddressField.setName("emailAddressField"); + emailAddressField.getHintLabel().setUIID("LoginTextFieldHint"); + passwordField = new TextField("", "Password", 20, TextField.ANY); + passwordField.setUIID("LoginTextField2"); + passwordField.setName("passwordField"); + passwordField.getHintLabel().setUIID("LoginTextField2Hint"); + rememberMeCheck = new CheckBox("Remember me"); + rememberMeCheck.setUIID("LoginCheckbox"); + rememberMeCheck.setName("rememberMeCheck"); + signInButton = new Button("Sign in"); + signInButton.setUIID("LoginButton"); + signInButton.setName("signInButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root; + if (widthMm >= TABLET_BREAKPOINT_MM) { + root = buildTablet(widthMm); + } else { + root = buildPhone(widthMm); + } + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "Login / Phone" (308 x 667 design px). + protected Container buildPhone(float widthMm) { + Container root = new Container(new BorderLayout(), "LoginScreen"); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginToolbar"); + c1.setName("toolbarItem"); + c1.add(take(signIn)); + root.add(BorderLayout.NORTH, c1); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c2.setName("contentItem"); + c2.setScrollableY(SCROLLABLE); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContainer"); + c3.setName("container"); + c3.add(margin(take(welcomeBack), 0f, 0f, 0f, 1f)); + c3.add(margin(take(signInToContinue), 1.41f, 0f, 0f, 0f)); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c4.setName("container2"); + c4.add(take(emailAddressField)); + c3.add(margin(c4, 3.5f, 0.6f, 0f, 1f)); + Container c5 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c5.setName("container3"); + c5.add(take(passwordField)); + c3.add(margin(c5, 1.41f, 0.6f, 0f, 1f)); + c3.add(margin(take(rememberMeCheck), 1.41f, 0f, 0f, 0f)); + c3.add(margin(take(signInButton), 1.41f, 0.6f, 0f, 1f)); + c2.add(c3); + root.add(BorderLayout.CENTER, c2); + content = c2; + return root; + } + + /// The tablet arrangement, from "Login / Tablet" (648 x 932 design px). + protected Container buildTablet(float widthMm) { + Container root = new Container(new BorderLayout(), "LoginScreen"); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginToolbar2"); + c1.setName("toolbarItem"); + c1.add(take(signIn)); + root.add(BorderLayout.NORTH, c1); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c2.setName("contentItem"); + c2.setScrollableY(SCROLLABLE); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContainer2"); + c3.setName("container"); + c3.add(margin(take(welcomeBack), 0f, 0f, 0f, 1f)); + c3.add(margin(take(signInToContinue), 1.41f, 0f, 0f, 0f)); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c4.setName("container2"); + c4.add(take(emailAddressField)); + c3.add(margin(c4, 3.5f, 0.6f, 0f, 1f)); + Container c5 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c5.setName("container3"); + c5.add(take(passwordField)); + c3.add(margin(c5, 1.41f, 0.6f, 0f, 1f)); + c3.add(margin(take(rememberMeCheck), 1.41f, 0f, 0f, 0f)); + c3.add(margin(take(signInButton), 1.41f, 0.6f, 0f, 1f)); + c2.add(c3); + root.add(BorderLayout.CENTER, c2); + content = c2; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/adaptive/Login/LoginFormTest.java b/scripts/designimport/examples/adaptive/Login/LoginFormTest.java new file mode 100644 index 00000000000..3556fff801f --- /dev/null +++ b/scripts/designimport/examples/adaptive/Login/LoginFormTest.java @@ -0,0 +1,101 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [LoginForm] keeps the structure of the design it was imported from. +public class LoginFormTest extends AbstractTest { + private LoginForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new LoginForm(); + form.show(); + form.revalidate(); + uiid("signIn", "LoginSignIn"); + text("signIn", "Sign in"); + stretches("signIn"); + uiid("welcomeBack", "LoginWelcomeBack"); + text("welcomeBack", "Welcome back"); + uiid("signInToContinue", "LoginSignInToContinue"); + text("signInToContinue", "Sign in to continue to your Codename One project."); + above("welcomeBack", "signInToContinue"); + uiid("emailAddressField", "LoginTextField"); + text("emailAddressField", "Email address"); + stretches("emailAddressField"); + uiid("passwordField", "LoginTextField2"); + text("passwordField", "Password"); + stretches("passwordField"); + uiid("rememberMeCheck", "LoginCheckbox"); + text("rememberMeCheck", "Remember me"); + stretches("rememberMeCheck"); + above("signInToContinue", "rememberMeCheck"); + uiid("signInButton", "LoginButton"); + text("signInButton", "Sign in"); + stretches("signInButton"); + above("rememberMeCheck", "signInButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/adaptive/Login/after.png b/scripts/designimport/examples/adaptive/Login/after.png new file mode 100644 index 00000000000..47b0856528c Binary files /dev/null and b/scripts/designimport/examples/adaptive/Login/after.png differ diff --git a/scripts/designimport/examples/adaptive/Login/before.png b/scripts/designimport/examples/adaptive/Login/before.png new file mode 100644 index 00000000000..0c90eb5beea Binary files /dev/null and b/scripts/designimport/examples/adaptive/Login/before.png differ diff --git a/scripts/designimport/examples/adaptive/Login/issues.md b/scripts/designimport/examples/adaptive/Login/issues.md new file mode 100644 index 00000000000..7b1acb439a3 --- /dev/null +++ b/scripts/designimport/examples/adaptive/Login/issues.md @@ -0,0 +1,5 @@ +# adaptive/Login + +- **INFO** (scope) Linked "Login / Phone" (phone) with "Login / Tablet" (tablet) as variants of one form. +- **WARNING** (structure) 2 vertical gaps in "Group 5" differ from the 7px the others use by a pixel or two; evened out. +- **INFO** (responsive) Matched 7 of 7 components between the phone and tablet frames; they share fields and the form switches arrangement at 600dp. diff --git a/scripts/designimport/examples/psd/BorderDropForm/BorderDropForm.css b/scripts/designimport/examples/psd/BorderDropForm/BorderDropForm.css new file mode 100644 index 00000000000..f6ef5a63013 --- /dev/null +++ b/scripts/designimport/examples/psd/BorderDropForm/BorderDropForm.css @@ -0,0 +1,17 @@ +/* Generated by Codename One Design Import from BorderDropForm.psd. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +BorderDropScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +BorderDropScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + diff --git a/scripts/designimport/examples/psd/BorderDropForm/BorderDropFormBase.java b/scripts/designimport/examples/psd/BorderDropForm/BorderDropFormBase.java new file mode 100644 index 00000000000..606f15e7450 --- /dev/null +++ b/scripts/designimport/examples/psd/BorderDropForm/BorderDropFormBase.java @@ -0,0 +1,133 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; +import java.io.IOException; +import java.io.InputStream; + +/// Generated by Codename One Design Import from BorderDropForm.psd. +/// +/// Regenerating the import overwrites this class. Put your own code in [BorderDropForm], which extends it. +public class BorderDropFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label screen; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public BorderDropFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + screen = new Label(); + screen.setUIID("BorderDropScreen2"); + screen.setName("screen"); + screen.setIcon(image("borderdrop_screen.png", 61.89f, 134.03f)); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "Group" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BorderDropScreen"); + root.setScrollableY(SCROLLABLE); + root.add(take(screen)); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } + + /// Loads a generated image from the resources, sized in millimetres. + protected Image image(String name, float widthMm, float heightMm) { + try { + InputStream in = CN.getResourceAsStream("/" + name); + if (in == null) { + return null; + } + Image img = Image.createImage(in); + in.close(); + return img.scaled(Math.max(1, CN.convertToPixels(widthMm)), Math.max(1, CN.convertToPixels(heightMm))); + } catch (IOException e) { + return null; + } + } + + /// Fills a container's background with a generated image. + protected void background(Container c, String name) { + try { + InputStream in = CN.getResourceAsStream("/" + name); + if (in == null) { + return; + } + c.getAllStyles().setBgImage(Image.createImage(in)); + c.getAllStyles().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL); + in.close(); + } catch (IOException e) { + // The image is missing from the resources: leave the background plain. + } + } +} diff --git a/scripts/designimport/examples/psd/BorderDropForm/BorderDropFormTest.java b/scripts/designimport/examples/psd/BorderDropForm/BorderDropFormTest.java new file mode 100644 index 00000000000..05990c392d6 --- /dev/null +++ b/scripts/designimport/examples/psd/BorderDropForm/BorderDropFormTest.java @@ -0,0 +1,81 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [BorderDropForm] keeps the structure of the design it was imported from. +public class BorderDropFormTest extends AbstractTest { + private BorderDropForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new BorderDropForm(); + form.show(); + form.revalidate(); + uiid("screen", "BorderDropScreen2"); + stretches("screen"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/psd/BorderDropForm/after.png b/scripts/designimport/examples/psd/BorderDropForm/after.png new file mode 100644 index 00000000000..e7b99dcff00 Binary files /dev/null and b/scripts/designimport/examples/psd/BorderDropForm/after.png differ diff --git a/scripts/designimport/examples/psd/BorderDropForm/before.png b/scripts/designimport/examples/psd/BorderDropForm/before.png new file mode 100644 index 00000000000..a3ca982e61b Binary files /dev/null and b/scripts/designimport/examples/psd/BorderDropForm/before.png differ diff --git a/scripts/designimport/examples/psd/BorderDropForm/issues.md b/scripts/designimport/examples/psd/BorderDropForm/issues.md new file mode 100644 index 00000000000..a15c6844c64 --- /dev/null +++ b/scripts/designimport/examples/psd/BorderDropForm/issues.md @@ -0,0 +1,4 @@ +# psd/BorderDropForm + +- **WARNING** (classify) The design is mostly pictures (1 of 1 layers): it was probably flattened, so the form shows an image of a UI. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutForm.css b/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutForm.css new file mode 100644 index 00000000000..672079fd7e6 --- /dev/null +++ b/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutForm.css @@ -0,0 +1,17 @@ +/* Generated by Codename One Design Import from BoxXLayoutForm.psd. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +BoxXLayoutScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +BoxXLayoutScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + diff --git a/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutFormBase.java b/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutFormBase.java new file mode 100644 index 00000000000..2ed30b20676 --- /dev/null +++ b/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutFormBase.java @@ -0,0 +1,133 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; +import java.io.IOException; +import java.io.InputStream; + +/// Generated by Codename One Design Import from BoxXLayoutForm.psd. +/// +/// Regenerating the import overwrites this class. Put your own code in [BoxXLayoutForm], which extends it. +public class BoxXLayoutFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label screen; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public BoxXLayoutFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + screen = new Label(); + screen.setUIID("BoxXLayoutScreen2"); + screen.setName("screen"); + screen.setIcon(image("boxxlayout_screen.png", 61.89f, 134.03f)); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "Group" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BoxXLayoutScreen"); + root.setScrollableY(SCROLLABLE); + root.add(take(screen)); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } + + /// Loads a generated image from the resources, sized in millimetres. + protected Image image(String name, float widthMm, float heightMm) { + try { + InputStream in = CN.getResourceAsStream("/" + name); + if (in == null) { + return null; + } + Image img = Image.createImage(in); + in.close(); + return img.scaled(Math.max(1, CN.convertToPixels(widthMm)), Math.max(1, CN.convertToPixels(heightMm))); + } catch (IOException e) { + return null; + } + } + + /// Fills a container's background with a generated image. + protected void background(Container c, String name) { + try { + InputStream in = CN.getResourceAsStream("/" + name); + if (in == null) { + return; + } + c.getAllStyles().setBgImage(Image.createImage(in)); + c.getAllStyles().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL); + in.close(); + } catch (IOException e) { + // The image is missing from the resources: leave the background plain. + } + } +} diff --git a/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutFormTest.java b/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutFormTest.java new file mode 100644 index 00000000000..9f087170306 --- /dev/null +++ b/scripts/designimport/examples/psd/BoxXLayoutForm/BoxXLayoutFormTest.java @@ -0,0 +1,81 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [BoxXLayoutForm] keeps the structure of the design it was imported from. +public class BoxXLayoutFormTest extends AbstractTest { + private BoxXLayoutForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new BoxXLayoutForm(); + form.show(); + form.revalidate(); + uiid("screen", "BoxXLayoutScreen2"); + stretches("screen"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/psd/BoxXLayoutForm/after.png b/scripts/designimport/examples/psd/BoxXLayoutForm/after.png new file mode 100644 index 00000000000..ab243e4333a Binary files /dev/null and b/scripts/designimport/examples/psd/BoxXLayoutForm/after.png differ diff --git a/scripts/designimport/examples/psd/BoxXLayoutForm/before.png b/scripts/designimport/examples/psd/BoxXLayoutForm/before.png new file mode 100644 index 00000000000..45dade63829 Binary files /dev/null and b/scripts/designimport/examples/psd/BoxXLayoutForm/before.png differ diff --git a/scripts/designimport/examples/psd/BoxXLayoutForm/issues.md b/scripts/designimport/examples/psd/BoxXLayoutForm/issues.md new file mode 100644 index 00000000000..4e7bf15c9fb --- /dev/null +++ b/scripts/designimport/examples/psd/BoxXLayoutForm/issues.md @@ -0,0 +1,4 @@ +# psd/BoxXLayoutForm + +- **WARNING** (classify) The design is mostly pictures (1 of 1 layers): it was probably flattened, so the form shows an image of a UI. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingForm.css b/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingForm.css new file mode 100644 index 00000000000..f57bed63432 --- /dev/null +++ b/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingForm.css @@ -0,0 +1,17 @@ +/* Generated by Codename One Design Import from DeepNestingForm.psd. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +DeepNestingScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +DeepNestingScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + diff --git a/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingFormBase.java b/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingFormBase.java new file mode 100644 index 00000000000..924a9703b35 --- /dev/null +++ b/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingFormBase.java @@ -0,0 +1,133 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; +import java.io.IOException; +import java.io.InputStream; + +/// Generated by Codename One Design Import from DeepNestingForm.psd. +/// +/// Regenerating the import overwrites this class. Put your own code in [DeepNestingForm], which extends it. +public class DeepNestingFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label screen; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public DeepNestingFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + screen = new Label(); + screen.setUIID("DeepNestingScreen2"); + screen.setName("screen"); + screen.setIcon(image("deepnesting_screen.png", 61.89f, 134.03f)); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "Group" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DeepNestingScreen"); + root.setScrollableY(SCROLLABLE); + root.add(take(screen)); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } + + /// Loads a generated image from the resources, sized in millimetres. + protected Image image(String name, float widthMm, float heightMm) { + try { + InputStream in = CN.getResourceAsStream("/" + name); + if (in == null) { + return null; + } + Image img = Image.createImage(in); + in.close(); + return img.scaled(Math.max(1, CN.convertToPixels(widthMm)), Math.max(1, CN.convertToPixels(heightMm))); + } catch (IOException e) { + return null; + } + } + + /// Fills a container's background with a generated image. + protected void background(Container c, String name) { + try { + InputStream in = CN.getResourceAsStream("/" + name); + if (in == null) { + return; + } + c.getAllStyles().setBgImage(Image.createImage(in)); + c.getAllStyles().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL); + in.close(); + } catch (IOException e) { + // The image is missing from the resources: leave the background plain. + } + } +} diff --git a/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingFormTest.java b/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingFormTest.java new file mode 100644 index 00000000000..1fad5eb6f6e --- /dev/null +++ b/scripts/designimport/examples/psd/DeepNestingForm/DeepNestingFormTest.java @@ -0,0 +1,81 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [DeepNestingForm] keeps the structure of the design it was imported from. +public class DeepNestingFormTest extends AbstractTest { + private DeepNestingForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new DeepNestingForm(); + form.show(); + form.revalidate(); + uiid("screen", "DeepNestingScreen2"); + stretches("screen"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/psd/DeepNestingForm/after.png b/scripts/designimport/examples/psd/DeepNestingForm/after.png new file mode 100644 index 00000000000..1e4dabca562 Binary files /dev/null and b/scripts/designimport/examples/psd/DeepNestingForm/after.png differ diff --git a/scripts/designimport/examples/psd/DeepNestingForm/before.png b/scripts/designimport/examples/psd/DeepNestingForm/before.png new file mode 100644 index 00000000000..b83cac36ea6 Binary files /dev/null and b/scripts/designimport/examples/psd/DeepNestingForm/before.png differ diff --git a/scripts/designimport/examples/psd/DeepNestingForm/issues.md b/scripts/designimport/examples/psd/DeepNestingForm/issues.md new file mode 100644 index 00000000000..0d61a1b89a6 --- /dev/null +++ b/scripts/designimport/examples/psd/DeepNestingForm/issues.md @@ -0,0 +1,4 @@ +# psd/DeepNestingForm + +- **WARNING** (classify) The design is mostly pictures (1 of 1 layers): it was probably flattened, so the form shows an image of a UI. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/scores.md b/scripts/designimport/examples/scores.md new file mode 100644 index 00000000000..c083627b66a --- /dev/null +++ b/scripts/designimport/examples/scores.md @@ -0,0 +1,23 @@ +# Scores + +Generated by `ExamplesTest`; do not edit. + +| Example | Variants | Layout overlap | Pixel similarity | Issues | +|---|---|---|---|---| +| svg/BorderDropForm | 1 | 0.74 | 0.77 | 2 | +| svg/BoxXLayoutForm | 1 | 0.71 | 0.58 | 3 | +| svg/DeepNestingForm | 1 | 0.66 | 0.81 | 2 | +| svg/DrainAndRefillForm | 1 | 0.44 | 0.78 | 2 | +| svg/GridLayoutForm | 1 | 0.90 | 0.74 | 2 | +| svg/GuidedLayoutForm | 1 | 0.89 | 0.92 | 2 | +| svg/LoginForm | 1 | 0.59 | 0.76 | 4 | +| svg/MixedNestedLayoutsForm | 1 | 0.62 | 0.73 | 2 | +| svg/NestedGuidedForm | 1 | 0.63 | 0.86 | 2 | +| svg/NestedLayoutsForm | 1 | 0.79 | 0.78 | 2 | +| svg/NestedTableForm | 1 | 0.41 | 0.82 | 2 | +| svg/TableLayoutForm | 1 | 0.46 | 0.90 | 3 | +| psd/BorderDropForm | 1 | 0.97 | 0.88 | 2 | +| psd/BoxXLayoutForm | 1 | 0.97 | 0.89 | 2 | +| psd/DeepNestingForm | 1 | 0.97 | 0.90 | 2 | +| adaptive/Login | 2 | 0.53 | 0.74 | 3 | +| skin/Login | 1 | 0.53 | 0.74 | 3 | diff --git a/scripts/designimport/examples/skin/Login/LoginForm.css b/scripts/designimport/examples/skin/Login/LoginForm.css new file mode 100644 index 00000000000..29e1be0bc38 --- /dev/null +++ b/scripts/designimport/examples/skin/Login/LoginForm.css @@ -0,0 +1,159 @@ +/* Generated by Codename One Design Import from login-in-skin.cn1art. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --login-color-1: #ffffff; + --login-color-2: #111827; + --login-color-3: #94a3b8; + --login-color-4: #9298a2; +} + +LoginScreen { + background-color: #ffffff; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +LoginToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.31mm 23.76mm 4.1mm 23.76mm; + margin: 0; +} + +LoginSignIn { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +LoginContent { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +LoginContainer { + background-color: transparent; + border: none; + padding: 4.31mm 3.42mm 75.16mm 3.01mm; + margin: 0; +} + +LoginWelcomeBack { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginSignInToContinue { + background-color: transparent; + border: none; + color: #4b5563; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginTextField { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 32.49mm 2.83mm 2.51mm; + margin: 0; +} + +LoginTextFieldHint { + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 2.51mm 2.83mm 2.51mm; + background-color: transparent; + border: none; + margin: 0; +} + +LoginTextField2 { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 38.24mm 2.83mm 2.51mm; + margin: 0; +} + +LoginTextField2Hint { + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.83mm 2.51mm 2.83mm 2.51mm; + background-color: transparent; + border: none; + margin: 0; +} + +LoginCheckbox { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0.91mm 0 0.91mm 0; + margin: 0; +} + +LoginCheckbox2 { + background-color: transparent; + border: 0.23mm solid #111827; + border-radius: 1.19mm; + padding: 0 0 0 0; + margin: 0; +} + +LoginRememberMe { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 22.75mm 2.11mm 22.75mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/skin/Login/LoginFormBase.java b/scripts/designimport/examples/skin/Login/LoginFormBase.java new file mode 100644 index 00000000000..e9ac1d442ad --- /dev/null +++ b/scripts/designimport/examples/skin/Login/LoginFormBase.java @@ -0,0 +1,147 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from login-in-skin.cn1art. +/// +/// Regenerating the import overwrites this class. Put your own code in [LoginForm], which extends it. +public class LoginFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label signIn; + protected Label welcomeBack; + protected Label signInToContinue; + protected TextField emailAddressField; + protected TextField passwordField; + protected CheckBox rememberMeCheck; + protected Button signInButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public LoginFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + signIn = new Label("Sign in"); + signIn.setUIID("LoginSignIn"); + signIn.setName("signIn"); + welcomeBack = new Label("Welcome back"); + welcomeBack.setUIID("LoginWelcomeBack"); + welcomeBack.setName("welcomeBack"); + signInToContinue = new Label("Sign in to continue to your Codename One project."); + signInToContinue.setUIID("LoginSignInToContinue"); + signInToContinue.setName("signInToContinue"); + emailAddressField = new TextField("", "Email address", 20, TextField.ANY); + emailAddressField.setUIID("LoginTextField"); + emailAddressField.setName("emailAddressField"); + emailAddressField.getHintLabel().setUIID("LoginTextFieldHint"); + passwordField = new TextField("", "Password", 20, TextField.ANY); + passwordField.setUIID("LoginTextField2"); + passwordField.setName("passwordField"); + passwordField.getHintLabel().setUIID("LoginTextField2Hint"); + rememberMeCheck = new CheckBox("Remember me"); + rememberMeCheck.setUIID("LoginCheckbox"); + rememberMeCheck.setName("rememberMeCheck"); + signInButton = new Button("Sign in"); + signInButton.setUIID("LoginButton"); + signInButton.setName("signInButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "Screen" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BorderLayout(), "LoginScreen"); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginToolbar"); + c1.setName("toolbarItem"); + c1.add(take(signIn)); + root.add(BorderLayout.NORTH, c1); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c2.setName("contentItem"); + c2.setScrollableY(SCROLLABLE); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContainer"); + c3.setName("container"); + c3.add(margin(take(welcomeBack), 0f, 0f, 0f, 1f)); + c3.add(margin(take(signInToContinue), 1.41f, 0f, 0f, 0f)); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c4.setName("container2"); + c4.add(take(emailAddressField)); + c3.add(margin(c4, 3.5f, 0.6f, 0f, 1f)); + Container c5 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginContent"); + c5.setName("container3"); + c5.add(take(passwordField)); + c3.add(margin(c5, 1.41f, 0.6f, 0f, 1f)); + c3.add(margin(take(rememberMeCheck), 1.41f, 0f, 0f, 0f)); + c3.add(margin(take(signInButton), 1.41f, 0.6f, 0f, 1f)); + c2.add(c3); + root.add(BorderLayout.CENTER, c2); + content = c2; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/skin/Login/LoginFormTest.java b/scripts/designimport/examples/skin/Login/LoginFormTest.java new file mode 100644 index 00000000000..3556fff801f --- /dev/null +++ b/scripts/designimport/examples/skin/Login/LoginFormTest.java @@ -0,0 +1,101 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [LoginForm] keeps the structure of the design it was imported from. +public class LoginFormTest extends AbstractTest { + private LoginForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new LoginForm(); + form.show(); + form.revalidate(); + uiid("signIn", "LoginSignIn"); + text("signIn", "Sign in"); + stretches("signIn"); + uiid("welcomeBack", "LoginWelcomeBack"); + text("welcomeBack", "Welcome back"); + uiid("signInToContinue", "LoginSignInToContinue"); + text("signInToContinue", "Sign in to continue to your Codename One project."); + above("welcomeBack", "signInToContinue"); + uiid("emailAddressField", "LoginTextField"); + text("emailAddressField", "Email address"); + stretches("emailAddressField"); + uiid("passwordField", "LoginTextField2"); + text("passwordField", "Password"); + stretches("passwordField"); + uiid("rememberMeCheck", "LoginCheckbox"); + text("rememberMeCheck", "Remember me"); + stretches("rememberMeCheck"); + above("signInToContinue", "rememberMeCheck"); + uiid("signInButton", "LoginButton"); + text("signInButton", "Sign in"); + stretches("signInButton"); + above("rememberMeCheck", "signInButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/skin/Login/after.png b/scripts/designimport/examples/skin/Login/after.png new file mode 100644 index 00000000000..47b0856528c Binary files /dev/null and b/scripts/designimport/examples/skin/Login/after.png differ diff --git a/scripts/designimport/examples/skin/Login/before.png b/scripts/designimport/examples/skin/Login/before.png new file mode 100644 index 00000000000..0c90eb5beea Binary files /dev/null and b/scripts/designimport/examples/skin/Login/before.png differ diff --git a/scripts/designimport/examples/skin/Login/issues.md b/scripts/designimport/examples/skin/Login/issues.md new file mode 100644 index 00000000000..4e65c1b7136 --- /dev/null +++ b/scripts/designimport/examples/skin/Login/issues.md @@ -0,0 +1,5 @@ +# skin/Login + +- **INFO** (scope) "iPhone mockup" is a device skin; imported its screen "Screen". +- **WARNING** (structure) 2 vertical gaps in "Group 5" differ from the 7px the others use by a pixel or two; evened out. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/svg/BorderDropForm/BorderDropForm.css b/scripts/designimport/examples/svg/BorderDropForm/BorderDropForm.css new file mode 100644 index 00000000000..15c77d819cf --- /dev/null +++ b/scripts/designimport/examples/svg/BorderDropForm/BorderDropForm.css @@ -0,0 +1,98 @@ +/* Generated by Codename One Design Import from BorderDropForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --borderdrop-color-1: #ffffff; + --borderdrop-color-2: #2563eb; +} + +BorderDropScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +BorderDropScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +BorderDropContainer { + background-color: #ffffff; + border: none; + padding: 0 0 121.37mm 0; + margin: 0; +} + +BorderDropButton { + background-color: #1e3a8a; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 4.2mm 5.74mm 4.2mm 5.74mm; + margin: 0; +} + +BorderDropNORTHDropUsesAc { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +BorderDropButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 48.83mm 2.6mm 48.83mm 2.6mm; + margin: 0; +} + +BorderDropCENTERHasNoStored { + background-color: transparent; + border: none; + color: #4b5563; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +BorderDropButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 48.83mm 2.56mm 48.83mm 2.56mm; + margin: 0; +} + +BorderDropButton4 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 22.62mm 2.11mm 22.62mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/BorderDropForm/BorderDropFormBase.java b/scripts/designimport/examples/svg/BorderDropForm/BorderDropFormBase.java new file mode 100644 index 00000000000..d58f7936db3 --- /dev/null +++ b/scripts/designimport/examples/svg/BorderDropForm/BorderDropFormBase.java @@ -0,0 +1,143 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from BorderDropForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [BorderDropForm], which extends it. +public class BorderDropFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Button borderLayoutDropTestButton; + protected Label nORTHDropUsesAc; + protected Button wESTButton; + protected Label cENTERHasNoStored; + protected Button eASTButton; + protected Button sOUTHButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public BorderDropFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + borderLayoutDropTestButton = new Button("BorderLayout Drop Test"); + borderLayoutDropTestButton.setUIID("BorderDropButton"); + borderLayoutDropTestButton.setName("borderLayoutDropTestButton"); + nORTHDropUsesAc = new Label("NORTH \u2014 drop uses actual preferred height"); + nORTHDropUsesAc.setUIID("BorderDropNORTHDropUsesAc"); + nORTHDropUsesAc.setName("nORTHDropUsesAc"); + wESTButton = new Button("WEST"); + wESTButton.setUIID("BorderDropButton2"); + wESTButton.setName("wESTButton"); + cENTERHasNoStored = new Label("CENTER has no stored constraint. Drag another component here to swap regions."); + cENTERHasNoStored.setUIID("BorderDropCENTERHasNoStored"); + cENTERHasNoStored.setName("cENTERHasNoStored"); + eASTButton = new Button("EAST"); + eASTButton.setUIID("BorderDropButton3"); + eASTButton.setName("eASTButton"); + sOUTHButton = new Button("SOUTH"); + sOUTHButton.setUIID("BorderDropButton4"); + sOUTHButton.setName("sOUTHButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BorderDropScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BorderDropScreen2"); + c1.setName("screen"); + Container c2 = new Container(new LayeredLayout(), "BorderDropScreen2"); + c2.setName("container"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BorderDropContainer"); + c3.setName("container2"); + c3.add(take(borderLayoutDropTestButton)); + c2.add(c3); + ((LayeredLayout) c2.getLayout()).setInsets(c3, "0mm 0mm 0mm 0mm"); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BorderDropScreen2"); + c4.setName("container3"); + c4.add(take(nORTHDropUsesAc)); + Container c5 = new Container(BoxLayout.xCenter(), "BorderDropScreen2"); + c5.setName("row"); + c5.setScrollableX(true); + c5.add(take(wESTButton)); + c5.add(margin(take(cENTERHasNoStored), 0f, 0f, 0f, 1f)); + c5.add(take(eASTButton)); + c4.add(margin(c5, 1.21f, 0f, 0f, 0f)); + c4.add(margin(FlowLayout.encloseIn(take(sOUTHButton)), 2.01f, 0f, 0f, 0f)); + c2.add(c4); + ((LayeredLayout) c2.getLayout()).setInsets(c4, "16.81mm auto auto 4.02mm"); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/BorderDropForm/BorderDropFormTest.java b/scripts/designimport/examples/svg/BorderDropForm/BorderDropFormTest.java new file mode 100644 index 00000000000..83f28f127d3 --- /dev/null +++ b/scripts/designimport/examples/svg/BorderDropForm/BorderDropFormTest.java @@ -0,0 +1,95 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [BorderDropForm] keeps the structure of the design it was imported from. +public class BorderDropFormTest extends AbstractTest { + private BorderDropForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new BorderDropForm(); + form.show(); + form.revalidate(); + uiid("borderLayoutDropTestButton", "BorderDropButton"); + text("borderLayoutDropTestButton", "BorderLayout Drop Test"); + stretches("borderLayoutDropTestButton"); + uiid("nORTHDropUsesAc", "BorderDropNORTHDropUsesAc"); + text("nORTHDropUsesAc", "NORTH \u2014 drop uses actual preferred height"); + uiid("wESTButton", "BorderDropButton2"); + text("wESTButton", "WEST"); + uiid("cENTERHasNoStored", "BorderDropCENTERHasNoStored"); + text("cENTERHasNoStored", "CENTER has no stored constraint. Drag another component here to swap regions."); + leftOf("wESTButton", "cENTERHasNoStored"); + uiid("eASTButton", "BorderDropButton3"); + text("eASTButton", "EAST"); + leftOf("cENTERHasNoStored", "eASTButton"); + uiid("sOUTHButton", "BorderDropButton4"); + text("sOUTHButton", "SOUTH"); + above("nORTHDropUsesAc", "sOUTHButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/BorderDropForm/after.png b/scripts/designimport/examples/svg/BorderDropForm/after.png new file mode 100644 index 00000000000..0a99d808978 Binary files /dev/null and b/scripts/designimport/examples/svg/BorderDropForm/after.png differ diff --git a/scripts/designimport/examples/svg/BorderDropForm/before.png b/scripts/designimport/examples/svg/BorderDropForm/before.png new file mode 100644 index 00000000000..0049da89f40 Binary files /dev/null and b/scripts/designimport/examples/svg/BorderDropForm/before.png differ diff --git a/scripts/designimport/examples/svg/BorderDropForm/design.svg b/scripts/designimport/examples/svg/BorderDropForm/design.svg new file mode 100644 index 00000000000..2254ac17084 --- /dev/null +++ b/scripts/designimport/examples/svg/BorderDropForm/design.svg @@ -0,0 +1,38 @@ + + +screen + + + + + + + + + +BorderLayout Drop Test + + + + +NORTH — drop uses actual preferred height + + + +WEST + + +CENTER has no stored constraint. Drag another component here to swap regions. + + + +EAST + + + +SOUTH + + + + + diff --git a/scripts/designimport/examples/svg/BorderDropForm/issues.md b/scripts/designimport/examples/svg/BorderDropForm/issues.md new file mode 100644 index 00000000000..e08d98d146d --- /dev/null +++ b/scripts/designimport/examples/svg/BorderDropForm/issues.md @@ -0,0 +1,4 @@ +# svg/BorderDropForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutForm.css b/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutForm.css new file mode 100644 index 00000000000..175a3924246 --- /dev/null +++ b/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutForm.css @@ -0,0 +1,102 @@ +/* Generated by Codename One Design Import from BoxXLayoutForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --boxxlayout-color-1: #ffffff; + --boxxlayout-color-2: #2563eb; +} + +BoxXLayoutScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +BoxXLayoutScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +BoxXLayoutContainer { + background-color: #ffffff; + border: none; + padding: 16.68mm 4.42mm 4.02mm 4.02mm; + margin: 0; +} + +BoxXLayoutButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 55.47mm 2.48mm 55.47mm 2.48mm; + margin: 0; +} + +BoxXLayoutButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 55.47mm 2.29mm 55.47mm 2.29mm; + margin: 0; +} + +BoxXLayoutButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 55.47mm 2.26mm 55.47mm 2.26mm; + margin: 0; +} + +BoxXLayoutButton4 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 55.47mm 2.18mm 55.47mm 2.18mm; + margin: 0; +} + +BoxXLayoutToolbar { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +BoxXLayoutContainer2 { + background-color: #1e3a8a; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +BoxXLayoutBoxLayoutXScroll { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutFormBase.java b/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutFormBase.java new file mode 100644 index 00000000000..e8833394b6a --- /dev/null +++ b/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutFormBase.java @@ -0,0 +1,144 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from BoxXLayoutForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [BoxXLayoutForm], which extends it. +public class BoxXLayoutFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Button firstButton; + protected Button secondButton; + protected Button thirdButton; + protected Button fourthButton; + protected Label part1; + protected Label boxLayoutXScroll; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public BoxXLayoutFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + firstButton = new Button("First"); + firstButton.setUIID("BoxXLayoutButton"); + firstButton.setName("firstButton"); + secondButton = new Button("Second"); + secondButton.setUIID("BoxXLayoutButton2"); + secondButton.setName("secondButton"); + thirdButton = new Button("Third"); + thirdButton.setUIID("BoxXLayoutButton3"); + thirdButton.setName("thirdButton"); + fourthButton = new Button("Fourth"); + fourthButton.setUIID("BoxXLayoutButton4"); + fourthButton.setName("fourthButton"); + part1 = new Label(); + part1.setUIID("BoxXLayoutContainer2"); + part1.setName("part1"); + boxLayoutXScroll = new Label("BoxLayout X \u2014 scroll and reorder horizontally"); + boxLayoutXScroll.setUIID("BoxXLayoutBoxLayoutXScroll"); + boxLayoutXScroll.setName("boxLayoutXScroll"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BoxXLayoutScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BoxXLayoutScreen2"); + c1.setName("screen"); + Container c2 = new Container(new LayeredLayout(), "BoxXLayoutScreen2"); + c2.setName("container"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "BoxXLayoutContainer"); + c3.setName("container2"); + Container c4 = new Container(BoxLayout.xCenter(), "BoxXLayoutScreen2"); + c4.setName("container3"); + c4.add(take(firstButton)); + c4.add(margin(take(secondButton), 0f, 0f, 0f, 2.01f)); + c4.add(margin(take(thirdButton), 0f, 0f, 0f, 2.01f)); + c4.add(margin(take(fourthButton), 0f, 0f, 0f, 2.01f)); + c3.add(c4); + c2.add(c3); + ((LayeredLayout) c2.getLayout()).setInsets(c3, "0mm auto 0mm 5.83mm"); + Container c5 = new Container(new LayeredLayout(), "BoxXLayoutToolbar"); + c5.setName("toolbarItem"); + c5.add(take(part1)); + ((LayeredLayout) c5.getLayout()).setInsets(part1, "0mm auto 0mm 5.83mm"); + c5.add(take(boxLayoutXScroll)); + ((LayeredLayout) c5.getLayout()).setInsets(boxLayoutXScroll, "4.31mm 0mm auto 0mm"); + c2.add(c5); + ((LayeredLayout) c2.getLayout()).setInsets(c5, "0mm 0mm auto 0mm"); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutFormTest.java b/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutFormTest.java new file mode 100644 index 00000000000..6e852b9c900 --- /dev/null +++ b/scripts/designimport/examples/svg/BoxXLayoutForm/BoxXLayoutFormTest.java @@ -0,0 +1,93 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [BoxXLayoutForm] keeps the structure of the design it was imported from. +public class BoxXLayoutFormTest extends AbstractTest { + private BoxXLayoutForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new BoxXLayoutForm(); + form.show(); + form.revalidate(); + uiid("firstButton", "BoxXLayoutButton"); + text("firstButton", "First"); + uiid("secondButton", "BoxXLayoutButton2"); + text("secondButton", "Second"); + leftOf("firstButton", "secondButton"); + uiid("thirdButton", "BoxXLayoutButton3"); + text("thirdButton", "Third"); + leftOf("secondButton", "thirdButton"); + uiid("fourthButton", "BoxXLayoutButton4"); + text("fourthButton", "Fourth"); + leftOf("thirdButton", "fourthButton"); + uiid("part1", "BoxXLayoutContainer2"); + uiid("boxLayoutXScroll", "BoxXLayoutBoxLayoutXScroll"); + text("boxLayoutXScroll", "BoxLayout X \u2014 scroll and reorder horizontally"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/BoxXLayoutForm/after.png b/scripts/designimport/examples/svg/BoxXLayoutForm/after.png new file mode 100644 index 00000000000..29418bd92c4 Binary files /dev/null and b/scripts/designimport/examples/svg/BoxXLayoutForm/after.png differ diff --git a/scripts/designimport/examples/svg/BoxXLayoutForm/before.png b/scripts/designimport/examples/svg/BoxXLayoutForm/before.png new file mode 100644 index 00000000000..45dade63829 Binary files /dev/null and b/scripts/designimport/examples/svg/BoxXLayoutForm/before.png differ diff --git a/scripts/designimport/examples/svg/BoxXLayoutForm/design.svg b/scripts/designimport/examples/svg/BoxXLayoutForm/design.svg new file mode 100644 index 00000000000..ff7e66c0c06 --- /dev/null +++ b/scripts/designimport/examples/svg/BoxXLayoutForm/design.svg @@ -0,0 +1,36 @@ + + +screen + + + + + + + + + +BoxLayout X — scroll and reorder horizontally + + + + + +First + + + +Second + + + +Third + + + +Fourth + + + + + diff --git a/scripts/designimport/examples/svg/BoxXLayoutForm/issues.md b/scripts/designimport/examples/svg/BoxXLayoutForm/issues.md new file mode 100644 index 00000000000..487173473f4 --- /dev/null +++ b/scripts/designimport/examples/svg/BoxXLayoutForm/issues.md @@ -0,0 +1,5 @@ +# svg/BoxXLayoutForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **TODO** (classify) "Rectangle 3" was classified as container with 50% confidence (a plain shape with nothing in it). +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingForm.css b/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingForm.css new file mode 100644 index 00000000000..643070cb26b --- /dev/null +++ b/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingForm.css @@ -0,0 +1,95 @@ +/* Generated by Codename One Design Import from DeepNestingForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --deepnesting-color-1: #ffffff; + --deepnesting-color-2: #374151; + --deepnesting-color-3: #2563eb; +} + +DeepNestingScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +DeepNestingScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +DeepNestingCard { + background-color: #ffffff; + border: none; + padding: 0 0 4.02mm 0; + margin: 0; +} + +DeepNestingToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.2mm 10.25mm 4.2mm 10.25mm; + margin: 0; +} + +DeepNestingDeepNestingFour { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +DeepNestingDragDeepLeafOutTo { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +DeepNestingButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 3.41mm 2.11mm 3.41mm; + margin: 0; +} + +DeepNestingButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 2.31mm 2.11mm 2.31mm; + margin: 0; +} + +DeepNestingButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 14mm 2.11mm 14mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingFormBase.java b/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingFormBase.java new file mode 100644 index 00000000000..2938175f148 --- /dev/null +++ b/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingFormBase.java @@ -0,0 +1,159 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from DeepNestingForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [DeepNestingForm], which extends it. +public class DeepNestingFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label deepNestingFour; + protected Label dragDeepLeafOutTo; + protected Button fourLevelsDownButton; + protected Label sibling; + protected Button flow1Button; + protected Button flow2Button; + protected Label parkComponentsHere; + protected Button dragMeIntoButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public DeepNestingFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + deepNestingFour = new Label("Deep nesting - four levels"); + deepNestingFour.setUIID("DeepNestingDeepNestingFour"); + deepNestingFour.setName("deepNestingFour"); + dragDeepLeafOutTo = new Label("Drag deepLeaf out to the title area and back down"); + dragDeepLeafOutTo.setUIID("DeepNestingDragDeepLeafOutTo"); + dragDeepLeafOutTo.setName("dragDeepLeafOutTo"); + fourLevelsDownButton = new Button("Four levels down"); + fourLevelsDownButton.setUIID("DeepNestingButton"); + fourLevelsDownButton.setName("fourLevelsDownButton"); + sibling = new Label("Sibling"); + sibling.setUIID("DeepNestingDragDeepLeafOutTo"); + sibling.setName("sibling"); + flow1Button = new Button("Flow 1"); + flow1Button.setUIID("DeepNestingButton2"); + flow1Button.setName("flow1Button"); + flow2Button = new Button("Flow 2"); + flow2Button.setUIID("DeepNestingButton2"); + flow2Button.setName("flow2Button"); + parkComponentsHere = new Label("Park components here"); + parkComponentsHere.setUIID("DeepNestingDragDeepLeafOutTo"); + parkComponentsHere.setName("parkComponentsHere"); + dragMeIntoButton = new Button("Drag me into any level"); + dragMeIntoButton.setUIID("DeepNestingButton3"); + dragMeIntoButton.setName("dragMeIntoButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DeepNestingScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DeepNestingScreen2"); + c1.setName("screen"); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DeepNestingCard"); + c2.setName("card"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DeepNestingToolbar"); + c3.setName("toolbarItem"); + c3.add(take(deepNestingFour)); + c2.add(c3); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DeepNestingScreen2"); + c4.setName("container"); + c4.add(take(dragDeepLeafOutTo)); + Container c5 = new Container(BoxLayout.xCenter(), "DeepNestingScreen2"); + c5.setName("container2"); + Container c6 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DeepNestingScreen2"); + c6.setName("container3"); + Container c7 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DeepNestingScreen2"); + c7.setName("container4"); + c7.add(take(fourLevelsDownButton)); + c7.add(margin(take(sibling), 2.14f, 0f, 0f, 0f)); + c6.add(c7); + Container c8 = new Container(BoxLayout.xCenter(), "DeepNestingScreen2"); + c8.setName("container5"); + c8.add(take(flow1Button)); + c8.add(margin(take(flow2Button), 0f, 0f, 0f, 2.01f)); + c6.add(margin(c8, 39.87f, 0f, 0f, 0f)); + c5.add(c6); + c5.add(margin(take(parkComponentsHere), 0f, 0f, 0f, 2.01f)); + c4.add(margin(c5, 2.09f, 0f, 0f, 0f)); + c4.add(margin(take(dragMeIntoButton), 44.41f, 0f, 0f, 0f)); + c2.add(margin(c4, 4.15f, 4.02f, 0f, 4.02f)); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingFormTest.java b/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingFormTest.java new file mode 100644 index 00000000000..034d3f665e9 --- /dev/null +++ b/scripts/designimport/examples/svg/DeepNestingForm/DeepNestingFormTest.java @@ -0,0 +1,101 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [DeepNestingForm] keeps the structure of the design it was imported from. +public class DeepNestingFormTest extends AbstractTest { + private DeepNestingForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new DeepNestingForm(); + form.show(); + form.revalidate(); + uiid("deepNestingFour", "DeepNestingDeepNestingFour"); + text("deepNestingFour", "Deep nesting - four levels"); + stretches("deepNestingFour"); + uiid("dragDeepLeafOutTo", "DeepNestingDragDeepLeafOutTo"); + text("dragDeepLeafOutTo", "Drag deepLeaf out to the title area and back down"); + uiid("fourLevelsDownButton", "DeepNestingButton"); + text("fourLevelsDownButton", "Four levels down"); + stretches("fourLevelsDownButton"); + uiid("sibling", "DeepNestingDragDeepLeafOutTo"); + text("sibling", "Sibling"); + above("fourLevelsDownButton", "sibling"); + uiid("flow1Button", "DeepNestingButton2"); + text("flow1Button", "Flow 1"); + uiid("flow2Button", "DeepNestingButton2"); + text("flow2Button", "Flow 2"); + leftOf("flow1Button", "flow2Button"); + uiid("parkComponentsHere", "DeepNestingDragDeepLeafOutTo"); + text("parkComponentsHere", "Park components here"); + uiid("dragMeIntoButton", "DeepNestingButton3"); + text("dragMeIntoButton", "Drag me into any level"); + stretches("dragMeIntoButton"); + above("dragDeepLeafOutTo", "dragMeIntoButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/DeepNestingForm/after.png b/scripts/designimport/examples/svg/DeepNestingForm/after.png new file mode 100644 index 00000000000..5bc885aa310 Binary files /dev/null and b/scripts/designimport/examples/svg/DeepNestingForm/after.png differ diff --git a/scripts/designimport/examples/svg/DeepNestingForm/before.png b/scripts/designimport/examples/svg/DeepNestingForm/before.png new file mode 100644 index 00000000000..b83cac36ea6 Binary files /dev/null and b/scripts/designimport/examples/svg/DeepNestingForm/before.png differ diff --git a/scripts/designimport/examples/svg/DeepNestingForm/design.svg b/scripts/designimport/examples/svg/DeepNestingForm/design.svg new file mode 100644 index 00000000000..d5ec4567625 --- /dev/null +++ b/scripts/designimport/examples/svg/DeepNestingForm/design.svg @@ -0,0 +1,55 @@ + + +screen + + + + + + + + + +Deep nesting - four levels + + + + +Drag deepLeaf out to the title area and back down + + + + + + +Four levels down + + +Sibling + + + + + +Flow 1 + + + +Flow 2 + + + + + +Park components here + + + + + +Drag me into any level + + + + + diff --git a/scripts/designimport/examples/svg/DeepNestingForm/issues.md b/scripts/designimport/examples/svg/DeepNestingForm/issues.md new file mode 100644 index 00000000000..cf2a03c3727 --- /dev/null +++ b/scripts/designimport/examples/svg/DeepNestingForm/issues.md @@ -0,0 +1,4 @@ +# svg/DeepNestingForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillForm.css b/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillForm.css new file mode 100644 index 00000000000..685924ca20e --- /dev/null +++ b/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillForm.css @@ -0,0 +1,118 @@ +/* Generated by Codename One Design Import from DrainAndRefillForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --drainandrefill-color-1: #ffffff; + --drainandrefill-color-2: #2563eb; +} + +DrainAndRefillScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +DrainAndRefillScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +DrainAndRefillContainer { + background-color: #ffffff; + border: none; + padding: 0 0 121.37mm 0; + margin: 0; +} + +DrainAndRefillButton { + background-color: #1e3a8a; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 4.2mm 0 4.2mm 0; + margin: 0; +} + +DrainAndRefillEmptyTheLeftColum { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +DrainAndRefillList { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +DrainAndRefillButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 3.58mm 2.11mm 3.58mm; + margin: 0; +} + +DrainAndRefillButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 3.45mm 2.11mm 3.45mm; + margin: 0; +} + +DrainAndRefillButton4 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 2.53mm 2.11mm 2.53mm; + margin: 0; +} + +DrainAndRefillButton5 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 3.05mm 2.11mm 3.05mm; + margin: 0; +} + +DrainAndRefillButton6 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 25.42mm 1.83mm 25.42mm 1.83mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillFormBase.java b/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillFormBase.java new file mode 100644 index 00000000000..66dea42f7b5 --- /dev/null +++ b/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillFormBase.java @@ -0,0 +1,150 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from DrainAndRefillForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [DrainAndRefillForm], which extends it. +public class DrainAndRefillFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Button drainAContainerButton; + protected Label emptyTheLeftColum; + protected Button oneButton; + protected Button twoButton; + protected Button threeButton; + protected Button fourButton; + protected Button onlyChildButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public DrainAndRefillFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + drainAContainerButton = new Button("Drain a container, then refill it"); + drainAContainerButton.setUIID("DrainAndRefillButton"); + drainAContainerButton.setName("drainAContainerButton"); + emptyTheLeftColum = new Label("Empty the left column completely, then drag components back into it"); + emptyTheLeftColum.setUIID("DrainAndRefillEmptyTheLeftColum"); + emptyTheLeftColum.setName("emptyTheLeftColum"); + oneButton = new Button("One"); + oneButton.setUIID("DrainAndRefillButton2"); + oneButton.setName("oneButton"); + twoButton = new Button("Two"); + twoButton.setUIID("DrainAndRefillButton3"); + twoButton.setName("twoButton"); + threeButton = new Button("Three"); + threeButton.setUIID("DrainAndRefillButton4"); + threeButton.setName("threeButton"); + fourButton = new Button("Four"); + fourButton.setUIID("DrainAndRefillButton5"); + fourButton.setName("fourButton"); + onlyChildButton = new Button("Only child"); + onlyChildButton.setUIID("DrainAndRefillButton6"); + onlyChildButton.setName("onlyChildButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DrainAndRefillScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DrainAndRefillScreen2"); + c1.setName("screen"); + Container c2 = new Container(new LayeredLayout(), "DrainAndRefillScreen2"); + c2.setName("container"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DrainAndRefillContainer"); + c3.setName("container2"); + c3.add(take(drainAContainerButton)); + c2.add(c3); + ((LayeredLayout) c2.getLayout()).setInsets(c3, "0mm auto 0mm 0mm"); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DrainAndRefillScreen2"); + c4.setName("container3"); + c4.add(take(emptyTheLeftColum)); + Container c5 = new Container(BoxLayout.xCenter(), "DrainAndRefillScreen2"); + c5.setName("container4"); + Container c6 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "DrainAndRefillList"); + c6.setName("list"); + c6.add(take(oneButton)); + c6.add(margin(take(twoButton), 2.01f, 0f, 0f, 0f)); + c6.add(margin(take(threeButton), 2.01f, 0f, 0f, 0f)); + c6.add(margin(take(fourButton), 2.01f, 0f, 0f, 0f)); + c5.add(c6); + c5.add(margin(take(onlyChildButton), 0f, 0f, 0f, 2.01f)); + c4.add(margin(c5, 2.09f, 0f, 0f, 0f)); + c2.add(c4); + ((LayeredLayout) c2.getLayout()).setInsets(c4, "16.81mm auto auto 4.02mm"); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillFormTest.java b/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillFormTest.java new file mode 100644 index 00000000000..cc98d9128cd --- /dev/null +++ b/scripts/designimport/examples/svg/DrainAndRefillForm/DrainAndRefillFormTest.java @@ -0,0 +1,102 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [DrainAndRefillForm] keeps the structure of the design it was imported from. +public class DrainAndRefillFormTest extends AbstractTest { + private DrainAndRefillForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new DrainAndRefillForm(); + form.show(); + form.revalidate(); + uiid("drainAContainerButton", "DrainAndRefillButton"); + text("drainAContainerButton", "Drain a container, then refill it"); + stretches("drainAContainerButton"); + uiid("emptyTheLeftColum", "DrainAndRefillEmptyTheLeftColum"); + text("emptyTheLeftColum", "Empty the left column completely, then drag components back into it"); + stretches("emptyTheLeftColum"); + uiid("oneButton", "DrainAndRefillButton2"); + text("oneButton", "One"); + stretches("oneButton"); + uiid("twoButton", "DrainAndRefillButton3"); + text("twoButton", "Two"); + stretches("twoButton"); + above("oneButton", "twoButton"); + uiid("threeButton", "DrainAndRefillButton4"); + text("threeButton", "Three"); + stretches("threeButton"); + above("twoButton", "threeButton"); + uiid("fourButton", "DrainAndRefillButton5"); + text("fourButton", "Four"); + stretches("fourButton"); + above("threeButton", "fourButton"); + uiid("onlyChildButton", "DrainAndRefillButton6"); + text("onlyChildButton", "Only child"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/DrainAndRefillForm/after.png b/scripts/designimport/examples/svg/DrainAndRefillForm/after.png new file mode 100644 index 00000000000..fa5621c9ae9 Binary files /dev/null and b/scripts/designimport/examples/svg/DrainAndRefillForm/after.png differ diff --git a/scripts/designimport/examples/svg/DrainAndRefillForm/before.png b/scripts/designimport/examples/svg/DrainAndRefillForm/before.png new file mode 100644 index 00000000000..a230020b504 Binary files /dev/null and b/scripts/designimport/examples/svg/DrainAndRefillForm/before.png differ diff --git a/scripts/designimport/examples/svg/DrainAndRefillForm/design.svg b/scripts/designimport/examples/svg/DrainAndRefillForm/design.svg new file mode 100644 index 00000000000..261b94b3a00 --- /dev/null +++ b/scripts/designimport/examples/svg/DrainAndRefillForm/design.svg @@ -0,0 +1,49 @@ + + +screen + + + + + + + + + +Drain a container, then refill it + + + + +Empty the left column completely, then drag components back into it + + + + + +One + + + +Two + + + +Three + + + +Four + + + + + +Only child + + + + + + + diff --git a/scripts/designimport/examples/svg/DrainAndRefillForm/issues.md b/scripts/designimport/examples/svg/DrainAndRefillForm/issues.md new file mode 100644 index 00000000000..a26271f31f2 --- /dev/null +++ b/scripts/designimport/examples/svg/DrainAndRefillForm/issues.md @@ -0,0 +1,4 @@ +# svg/DrainAndRefillForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutForm.css b/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutForm.css new file mode 100644 index 00000000000..8ff482ead26 --- /dev/null +++ b/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutForm.css @@ -0,0 +1,71 @@ +/* Generated by Codename One Design Import from GridLayoutForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --gridlayout-color-1: #ffffff; + --gridlayout-color-2: #2563eb; +} + +GridLayoutScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +GridLayoutScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +GridLayoutCard { + background-color: #ffffff; + border: none; + padding: 0 0 4.02mm 0; + margin: 0; +} + +GridLayoutToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.2mm 9.44mm 4.2mm 9.44mm; + margin: 0; +} + +GridLayoutGridLayoutReorder { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +GridLayoutButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 26.63mm 9.43mm 26.63mm 9.43mm; + margin: 0; +} + +GridLayoutButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 26.63mm 9.57mm 26.63mm 9.57mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutFormBase.java b/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutFormBase.java new file mode 100644 index 00000000000..d72d2316506 --- /dev/null +++ b/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutFormBase.java @@ -0,0 +1,133 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from GridLayoutForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [GridLayoutForm], which extends it. +public class GridLayoutFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label gridLayoutReorder; + protected Button cellAButton; + protected Button cellBButton; + protected Button cellCButton; + protected Button cellDButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public GridLayoutFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + gridLayoutReorder = new Label("GridLayout \u2014 reorder cells"); + gridLayoutReorder.setUIID("GridLayoutGridLayoutReorder"); + gridLayoutReorder.setName("gridLayoutReorder"); + cellAButton = new Button("Cell A"); + cellAButton.setUIID("GridLayoutButton"); + cellAButton.setName("cellAButton"); + cellBButton = new Button("Cell B"); + cellBButton.setUIID("GridLayoutButton2"); + cellBButton.setName("cellBButton"); + cellCButton = new Button("Cell C"); + cellCButton.setUIID("GridLayoutButton"); + cellCButton.setName("cellCButton"); + cellDButton = new Button("Cell D"); + cellDButton.setUIID("GridLayoutButton"); + cellDButton.setName("cellDButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "GridLayoutScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "GridLayoutScreen2"); + c1.setName("screen"); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "GridLayoutCard"); + c2.setName("card"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "GridLayoutToolbar"); + c3.setName("toolbarItem"); + c3.add(take(gridLayoutReorder)); + c2.add(c3); + int c4Cols = columns(widthMm * 0.87f, 26.93f, 2.01f, 2, 4); + Container c4 = new Container(new GridLayout((4 + c4Cols - 1) / c4Cols, c4Cols), "GridLayoutScreen2"); + c4.setName("container"); + c4.add(margin(take(cellAButton), 1f, 1f, 1f, 1f)); + c4.add(margin(take(cellBButton), 1f, 1f, 1f, 1f)); + c4.add(margin(take(cellCButton), 1f, 1f, 1f, 1f)); + c4.add(margin(take(cellDButton), 1f, 1f, 1f, 1f)); + c2.add(margin(c4, 4.02f, 4.02f, 0f, 4.02f)); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutFormTest.java b/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutFormTest.java new file mode 100644 index 00000000000..9cbdccf04dd --- /dev/null +++ b/scripts/designimport/examples/svg/GridLayoutForm/GridLayoutFormTest.java @@ -0,0 +1,90 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [GridLayoutForm] keeps the structure of the design it was imported from. +public class GridLayoutFormTest extends AbstractTest { + private GridLayoutForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new GridLayoutForm(); + form.show(); + form.revalidate(); + uiid("gridLayoutReorder", "GridLayoutGridLayoutReorder"); + text("gridLayoutReorder", "GridLayout \u2014 reorder cells"); + stretches("gridLayoutReorder"); + uiid("cellAButton", "GridLayoutButton"); + text("cellAButton", "Cell A"); + uiid("cellBButton", "GridLayoutButton2"); + text("cellBButton", "Cell B"); + uiid("cellCButton", "GridLayoutButton"); + text("cellCButton", "Cell C"); + uiid("cellDButton", "GridLayoutButton"); + text("cellDButton", "Cell D"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/GridLayoutForm/after.png b/scripts/designimport/examples/svg/GridLayoutForm/after.png new file mode 100644 index 00000000000..f27c8b8586a Binary files /dev/null and b/scripts/designimport/examples/svg/GridLayoutForm/after.png differ diff --git a/scripts/designimport/examples/svg/GridLayoutForm/before.png b/scripts/designimport/examples/svg/GridLayoutForm/before.png new file mode 100644 index 00000000000..db8ab1f4314 Binary files /dev/null and b/scripts/designimport/examples/svg/GridLayoutForm/before.png differ diff --git a/scripts/designimport/examples/svg/GridLayoutForm/design.svg b/scripts/designimport/examples/svg/GridLayoutForm/design.svg new file mode 100644 index 00000000000..46f2b9e2192 --- /dev/null +++ b/scripts/designimport/examples/svg/GridLayoutForm/design.svg @@ -0,0 +1,36 @@ + + +screen + + + + + + + + + +GridLayout — reorder cells + + + + + +Cell A + + + +Cell B + + + +Cell C + + + +Cell D + + + + + diff --git a/scripts/designimport/examples/svg/GridLayoutForm/issues.md b/scripts/designimport/examples/svg/GridLayoutForm/issues.md new file mode 100644 index 00000000000..65100a4c5f1 --- /dev/null +++ b/scripts/designimport/examples/svg/GridLayoutForm/issues.md @@ -0,0 +1,4 @@ +# svg/GridLayoutForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens, the content column scrolls and grids keep their cell width and gain columns as the screen widens. diff --git a/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutForm.css b/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutForm.css new file mode 100644 index 00000000000..efa0f5eb192 --- /dev/null +++ b/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutForm.css @@ -0,0 +1,109 @@ +/* Generated by Codename One Design Import from GuidedLayoutForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --guidedlayout-color-1: #ffffff; + --guidedlayout-color-2: #2563eb; +} + +GuidedLayoutScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +GuidedLayoutScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +GuidedLayoutContainer { + background-color: #ffffff; + border: none; + padding: 0 0 121.37mm 0; + margin: 0; +} + +GuidedLayoutButton { + background-color: #1e3a8a; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 4.2mm 15.79mm 4.2mm 15.79mm; + margin: 0; +} + +GuidedLayoutGuidedLayout { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +GuidedLayoutDragComponentsByT { + background-color: transparent; + border: none; + color: #4b5563; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +GuidedLayoutButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 1.43mm 2.11mm 1.43mm; + margin: 0; +} + +GuidedLayoutButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 20.14mm 2.11mm 20.14mm; + margin: 0; +} + +GuidedLayoutBaselineAligned { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +GuidedLayoutButton4 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 2.11mm 2.11mm 2.11mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutFormBase.java b/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutFormBase.java new file mode 100644 index 00000000000..32d2d529f6b --- /dev/null +++ b/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutFormBase.java @@ -0,0 +1,151 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from GuidedLayoutForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [GuidedLayoutForm], which extends it. +public class GuidedLayoutFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Button guidedLayoutButton; + protected Label guidedLayout2; + protected Label dragComponentsByT; + protected Button primaryActionButton; + protected Button sameWidthButton; + protected Label baselineAligned; + protected Button actionButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public GuidedLayoutFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + guidedLayoutButton = new Button("Guided Layout"); + guidedLayoutButton.setUIID("GuidedLayoutButton"); + guidedLayoutButton.setName("guidedLayoutButton"); + guidedLayout2 = new Label("Guided Layout"); + guidedLayout2.setUIID("GuidedLayoutGuidedLayout"); + guidedLayout2.setName("guidedLayout2"); + dragComponentsByT = new Label("Drag components by their body. Drag the blue edge and corner handles to resize. Snap edges, centers, baselines, and matching sizes to build a responsive arbitrary UI."); + dragComponentsByT.setUIID("GuidedLayoutDragComponentsByT"); + dragComponentsByT.setName("dragComponentsByT"); + primaryActionButton = new Button("Primary action"); + primaryActionButton.setUIID("GuidedLayoutButton2"); + primaryActionButton.setName("primaryActionButton"); + sameWidthButton = new Button("Same width"); + sameWidthButton.setUIID("GuidedLayoutButton3"); + sameWidthButton.setName("sameWidthButton"); + baselineAligned = new Label("Baseline aligned"); + baselineAligned.setUIID("GuidedLayoutBaselineAligned"); + baselineAligned.setName("baselineAligned"); + actionButton = new Button("Action"); + actionButton.setUIID("GuidedLayoutButton4"); + actionButton.setName("actionButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The tablet arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "GuidedLayoutScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "GuidedLayoutScreen2"); + c1.setName("screen"); + Container c2 = new Container(new LayeredLayout(), "GuidedLayoutScreen2"); + c2.setName("container"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "GuidedLayoutContainer"); + c3.setName("container2"); + c3.add(take(guidedLayoutButton)); + c2.add(c3); + ((LayeredLayout) c2.getLayout()).setInsets(c3, "0mm 0mm 0mm 0mm"); + Container c4 = new Container(new LayeredLayout(), "GuidedLayoutScreen2"); + c4.setName("container3"); + c4.setScrollableX(true); + c4.add(take(guidedLayout2)); + ((LayeredLayout) c4.getLayout()).setInsets(guidedLayout2, "5.11mm auto auto 5.83mm"); + c4.add(take(dragComponentsByT)); + ((LayeredLayout) c4.getLayout()).setInsets(dragComponentsByT, "1.54mm auto auto 0mm"); + c4.add(take(primaryActionButton)); + ((LayeredLayout) c4.getLayout()).setInsets(primaryActionButton, "4.82mm auto auto 1mm"); + c4.add(take(sameWidthButton)); + ((LayeredLayout) c4.getLayout()).setInsets(sameWidthButton, "2.41mm auto auto 1mm"); + c4.add(take(baselineAligned)); + ((LayeredLayout) c4.getLayout()).setInsets(baselineAligned, "3.75mm auto auto 1mm"); + c4.add(take(actionButton)); + ((LayeredLayout) c4.getLayout()).setInsets(actionButton, "0mm auto auto 3.42mm"); + c2.add(c4); + ((LayeredLayout) c2.getLayout()).setInsets(c4, "16.68mm auto auto 3.01mm"); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutFormTest.java b/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutFormTest.java new file mode 100644 index 00000000000..4e1f3d3eb0e --- /dev/null +++ b/scripts/designimport/examples/svg/GuidedLayoutForm/GuidedLayoutFormTest.java @@ -0,0 +1,94 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [GuidedLayoutForm] keeps the structure of the design it was imported from. +public class GuidedLayoutFormTest extends AbstractTest { + private GuidedLayoutForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new GuidedLayoutForm(); + form.show(); + form.revalidate(); + uiid("guidedLayoutButton", "GuidedLayoutButton"); + text("guidedLayoutButton", "Guided Layout"); + stretches("guidedLayoutButton"); + uiid("guidedLayout2", "GuidedLayoutGuidedLayout"); + text("guidedLayout2", "Guided Layout"); + uiid("dragComponentsByT", "GuidedLayoutDragComponentsByT"); + text("dragComponentsByT", "Drag components by their body. Drag the blue edge and corner handles to resize. Snap edges, centers, baselines, and matching sizes to build a responsive arbitrary UI."); + uiid("primaryActionButton", "GuidedLayoutButton2"); + text("primaryActionButton", "Primary action"); + uiid("sameWidthButton", "GuidedLayoutButton3"); + text("sameWidthButton", "Same width"); + uiid("baselineAligned", "GuidedLayoutBaselineAligned"); + text("baselineAligned", "Baseline aligned"); + uiid("actionButton", "GuidedLayoutButton4"); + text("actionButton", "Action"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/GuidedLayoutForm/after.png b/scripts/designimport/examples/svg/GuidedLayoutForm/after.png new file mode 100644 index 00000000000..b1787843cd5 Binary files /dev/null and b/scripts/designimport/examples/svg/GuidedLayoutForm/after.png differ diff --git a/scripts/designimport/examples/svg/GuidedLayoutForm/before.png b/scripts/designimport/examples/svg/GuidedLayoutForm/before.png new file mode 100644 index 00000000000..7214f6d1ff4 Binary files /dev/null and b/scripts/designimport/examples/svg/GuidedLayoutForm/before.png differ diff --git a/scripts/designimport/examples/svg/GuidedLayoutForm/design.svg b/scripts/designimport/examples/svg/GuidedLayoutForm/design.svg new file mode 100644 index 00000000000..ec8ea17c362 --- /dev/null +++ b/scripts/designimport/examples/svg/GuidedLayoutForm/design.svg @@ -0,0 +1,41 @@ + + +screen + + + + + + + + + +Guided Layout + + + + +Guided Layout + + +Drag components by their body. Drag the blue edge and corner handles to resize. Snap edges, centers, baselines, and matching sizes to build a responsive arbitrary UI. + + + +Primary action + + + +Same width + + +Baseline aligned + + + +Action + + + + + diff --git a/scripts/designimport/examples/svg/GuidedLayoutForm/issues.md b/scripts/designimport/examples/svg/GuidedLayoutForm/issues.md new file mode 100644 index 00000000000..c3c05dc30e6 --- /dev/null +++ b/scripts/designimport/examples/svg/GuidedLayoutForm/issues.md @@ -0,0 +1,4 @@ +# svg/GuidedLayoutForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one tablet frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/svg/LoginForm/LoginForm.css b/scripts/designimport/examples/svg/LoginForm/LoginForm.css new file mode 100644 index 00000000000..e3485a4518c --- /dev/null +++ b/scripts/designimport/examples/svg/LoginForm/LoginForm.css @@ -0,0 +1,159 @@ +/* Generated by Codename One Design Import from LoginForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --login-color-1: #ffffff; + --login-color-2: #111827; + --login-color-3: #94a3b8; + --login-color-4: #9298a2; +} + +LoginScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +LoginScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +LoginCard { + background-color: #ffffff; + border: none; + padding: 0 0 75.16mm 0; + margin: 0; +} + +LoginToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.31mm 23.76mm 4.1mm 23.76mm; + margin: 0; +} + +LoginSignIn { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +LoginWelcomeBack { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginSignInToContinue { + background-color: transparent; + border: none; + color: #4b5563; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginTextField { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.33mm 31.99mm 2.33mm 2.01mm; + margin: 0; +} + +LoginTextFieldHint { + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.33mm 2.01mm 2.33mm 2.01mm; + background-color: transparent; + border: none; + margin: 0; +} + +LoginTextField2 { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.33mm 37.74mm 2.33mm 2.01mm; + margin: 0; +} + +LoginTextField2Hint { + color: #9298a2; + font-family: "native:MainRegular"; + font-size: 2.41mm; + text-align: left; + padding: 2.33mm 2.01mm 2.33mm 2.01mm; + background-color: transparent; + border: none; + margin: 0; +} + +LoginCheckbox { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0mm 0 0mm 0; + margin: 0; +} + +LoginCheckbox2 { + background-color: transparent; + border: 0.23mm solid #111827; + border-radius: 1.19mm; + padding: 0 0 0 0; + margin: 0; +} + +LoginRememberMe { + background-color: transparent; + border: none; + color: #111827; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +LoginButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 22.75mm 2.11mm 22.75mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/LoginForm/LoginFormBase.java b/scripts/designimport/examples/svg/LoginForm/LoginFormBase.java new file mode 100644 index 00000000000..84ec43391f6 --- /dev/null +++ b/scripts/designimport/examples/svg/LoginForm/LoginFormBase.java @@ -0,0 +1,150 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from LoginForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [LoginForm], which extends it. +public class LoginFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label signIn; + protected Label welcomeBack; + protected Label signInToContinue; + protected TextField emailAddressField; + protected TextField passwordField; + protected CheckBox rememberMeCheck; + protected Button signInButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public LoginFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + signIn = new Label("Sign in"); + signIn.setUIID("LoginSignIn"); + signIn.setName("signIn"); + welcomeBack = new Label("Welcome back"); + welcomeBack.setUIID("LoginWelcomeBack"); + welcomeBack.setName("welcomeBack"); + signInToContinue = new Label("Sign in to continue to your Codename One project."); + signInToContinue.setUIID("LoginSignInToContinue"); + signInToContinue.setName("signInToContinue"); + emailAddressField = new TextField("", "Email address", 20, TextField.ANY); + emailAddressField.setUIID("LoginTextField"); + emailAddressField.setName("emailAddressField"); + emailAddressField.getHintLabel().setUIID("LoginTextFieldHint"); + passwordField = new TextField("", "Password", 20, TextField.ANY); + passwordField.setUIID("LoginTextField2"); + passwordField.setName("passwordField"); + passwordField.getHintLabel().setUIID("LoginTextField2Hint"); + rememberMeCheck = new CheckBox("Remember me"); + rememberMeCheck.setUIID("LoginCheckbox"); + rememberMeCheck.setName("rememberMeCheck"); + signInButton = new Button("Sign in"); + signInButton.setUIID("LoginButton"); + signInButton.setName("signInButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginScreen2"); + c1.setName("screen"); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginCard"); + c2.setName("card"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginToolbar"); + c3.setName("toolbarItem"); + c3.add(take(signIn)); + c2.add(c3); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginScreen2"); + c4.setName("container"); + c4.add(margin(take(welcomeBack), 0f, 0f, 0f, 1f)); + c4.add(margin(take(signInToContinue), 1.21f, 0f, 0f, 0f)); + Container c5 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginScreen2"); + c5.setName("container2"); + c5.add(take(emailAddressField)); + c4.add(margin(c5, 3.5f, 0f, 0f, 1f)); + Container c6 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "LoginScreen2"); + c6.setName("container3"); + c6.add(take(passwordField)); + c4.add(margin(c6, 2.29f, 0f, 0f, 1f)); + c4.add(margin(take(rememberMeCheck), 2.33f, 0f, 0f, 1f)); + c4.add(margin(take(signInButton), 2.29f, 0f, 0f, 1f)); + c2.add(margin(c4, 4.31f, 4.02f, 0f, 3.01f)); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/LoginForm/LoginFormTest.java b/scripts/designimport/examples/svg/LoginForm/LoginFormTest.java new file mode 100644 index 00000000000..ffeffe38a0b --- /dev/null +++ b/scripts/designimport/examples/svg/LoginForm/LoginFormTest.java @@ -0,0 +1,100 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [LoginForm] keeps the structure of the design it was imported from. +public class LoginFormTest extends AbstractTest { + private LoginForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new LoginForm(); + form.show(); + form.revalidate(); + uiid("signIn", "LoginSignIn"); + text("signIn", "Sign in"); + stretches("signIn"); + uiid("welcomeBack", "LoginWelcomeBack"); + text("welcomeBack", "Welcome back"); + uiid("signInToContinue", "LoginSignInToContinue"); + text("signInToContinue", "Sign in to continue to your Codename One project."); + above("welcomeBack", "signInToContinue"); + uiid("emailAddressField", "LoginTextField"); + text("emailAddressField", "Email address"); + stretches("emailAddressField"); + uiid("passwordField", "LoginTextField2"); + text("passwordField", "Password"); + stretches("passwordField"); + uiid("rememberMeCheck", "LoginCheckbox"); + text("rememberMeCheck", "Remember me"); + above("signInToContinue", "rememberMeCheck"); + uiid("signInButton", "LoginButton"); + text("signInButton", "Sign in"); + stretches("signInButton"); + above("rememberMeCheck", "signInButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/LoginForm/after.png b/scripts/designimport/examples/svg/LoginForm/after.png new file mode 100644 index 00000000000..30396bc3263 Binary files /dev/null and b/scripts/designimport/examples/svg/LoginForm/after.png differ diff --git a/scripts/designimport/examples/svg/LoginForm/before.png b/scripts/designimport/examples/svg/LoginForm/before.png new file mode 100644 index 00000000000..0c90eb5beea Binary files /dev/null and b/scripts/designimport/examples/svg/LoginForm/before.png differ diff --git a/scripts/designimport/examples/svg/LoginForm/design.svg b/scripts/designimport/examples/svg/LoginForm/design.svg new file mode 100644 index 00000000000..b8782f6fb01 --- /dev/null +++ b/scripts/designimport/examples/svg/LoginForm/design.svg @@ -0,0 +1,50 @@ + + +screen + + + + + + + + + +Sign in + + + + +Welcome back + + +Sign in to continue to your Codename One project. + + + + + + +Email address + + + + + + +Password + + + + + +Remember me + + + +Sign in + + + + + diff --git a/scripts/designimport/examples/svg/LoginForm/issues.md b/scripts/designimport/examples/svg/LoginForm/issues.md new file mode 100644 index 00000000000..9e68c7c0b25 --- /dev/null +++ b/scripts/designimport/examples/svg/LoginForm/issues.md @@ -0,0 +1,6 @@ +# svg/LoginForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **WARNING** (structure) "Group 12" is 1.41px left of the edge its siblings share; snapped to it. +- **WARNING** (structure) 1 vertical gap in "Group 5" differ from the 11.4px the others use by a pixel or two; evened out. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsForm.css b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsForm.css new file mode 100644 index 00000000000..123b87bd659 --- /dev/null +++ b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsForm.css @@ -0,0 +1,119 @@ +/* Generated by Codename One Design Import from MixedNestedLayoutsForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --mixednestedlayouts-color-1: #ffffff; + --mixednestedlayouts-color-2: #374151; + --mixednestedlayouts-color-3: #2563eb; +} + +MixedNestedLayoutsScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +MixedNestedLayoutsScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +MixedNestedLayoutsCard { + background-color: #ffffff; + border: none; + padding: 0 0 4.02mm 0; + margin: 0; +} + +MixedNestedLayoutsToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.2mm 14.67mm 4.2mm 14.67mm; + margin: 0; +} + +MixedNestedLayoutsEveryLayoutNested { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +MixedNestedLayoutsMoveAComponentThr { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +MixedNestedLayoutsButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 1.52mm 2.11mm 1.52mm; + margin: 0; +} + +MixedNestedLayoutsButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 5.57mm 2.11mm 5.57mm; + margin: 0; +} + +MixedNestedLayoutsButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 23.31mm 2.37mm 23.31mm 2.37mm; + margin: 0; +} + +MixedNestedLayoutsButton4 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 1.82mm 2.11mm 1.82mm; + margin: 0; +} + +MixedNestedLayoutsButton5 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 1.8mm 2.11mm 1.8mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsFormBase.java b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsFormBase.java new file mode 100644 index 00000000000..85f46cbceb0 --- /dev/null +++ b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsFormBase.java @@ -0,0 +1,170 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from MixedNestedLayoutsForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [MixedNestedLayoutsForm], which extends it. +public class MixedNestedLayoutsFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label everyLayoutNested; + protected Label moveAComponentThr; + protected Label boxLayoutY; + protected Button dragMeAnywhereButton; + protected Button boxSecondButton; + protected Button grid1Button; + protected Button grid2Button; + protected Button grid3Button; + protected Button flowFirstButton; + protected Button flowSecondButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public MixedNestedLayoutsFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + everyLayoutNested = new Label("Every layout, nested"); + everyLayoutNested.setUIID("MixedNestedLayoutsEveryLayoutNested"); + everyLayoutNested.setName("everyLayoutNested"); + moveAComponentThr = new Label("Move a component through every layout in turn"); + moveAComponentThr.setUIID("MixedNestedLayoutsMoveAComponentThr"); + moveAComponentThr.setName("moveAComponentThr"); + boxLayoutY = new Label("BoxLayout Y"); + boxLayoutY.setUIID("MixedNestedLayoutsMoveAComponentThr"); + boxLayoutY.setName("boxLayoutY"); + dragMeAnywhereButton = new Button("Drag me anywhere"); + dragMeAnywhereButton.setUIID("MixedNestedLayoutsButton"); + dragMeAnywhereButton.setName("dragMeAnywhereButton"); + boxSecondButton = new Button("Box second"); + boxSecondButton.setUIID("MixedNestedLayoutsButton2"); + boxSecondButton.setName("boxSecondButton"); + grid1Button = new Button("Grid 1"); + grid1Button.setUIID("MixedNestedLayoutsButton3"); + grid1Button.setName("grid1Button"); + grid2Button = new Button("Grid 2"); + grid2Button.setUIID("MixedNestedLayoutsButton3"); + grid2Button.setName("grid2Button"); + grid3Button = new Button("Grid 3"); + grid3Button.setUIID("MixedNestedLayoutsButton3"); + grid3Button.setName("grid3Button"); + flowFirstButton = new Button("Flow first"); + flowFirstButton.setUIID("MixedNestedLayoutsButton4"); + flowFirstButton.setName("flowFirstButton"); + flowSecondButton = new Button("Flow second"); + flowSecondButton.setUIID("MixedNestedLayoutsButton5"); + flowSecondButton.setName("flowSecondButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "MixedNestedLayoutsScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "MixedNestedLayoutsScreen2"); + c1.setName("screen"); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "MixedNestedLayoutsCard"); + c2.setName("card"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "MixedNestedLayoutsToolbar"); + c3.setName("toolbarItem"); + c3.add(take(everyLayoutNested)); + c2.add(c3); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "MixedNestedLayoutsScreen2"); + c4.setName("container"); + c4.add(take(moveAComponentThr)); + Container c5 = new Container(BoxLayout.xCenter(), "MixedNestedLayoutsScreen2"); + c5.setName("container2"); + Container c6 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "MixedNestedLayoutsScreen2"); + c6.setName("container3"); + c6.add(take(boxLayoutY)); + c6.add(margin(take(dragMeAnywhereButton), 2.09f, 0f, 0f, 0f)); + c6.add(margin(take(boxSecondButton), 2.01f, 0f, 0f, 0f)); + c5.add(c6); + int c7Cols = 2; + Container c7 = new Container(new GridLayout((3 + c7Cols - 1) / c7Cols, c7Cols), "MixedNestedLayoutsScreen2"); + c7.setName("container4"); + c7.add(margin(take(grid1Button), 1f, 1f, 1f, 1f)); + c7.add(margin(take(grid2Button), 1f, 1f, 1f, 1f)); + c7.add(margin(take(grid3Button), 1f, 1f, 1f, 1f)); + c5.add(margin(c7, 0f, 0f, 0f, 2.01f)); + c4.add(margin(c5, 2.09f, 0f, 0f, 0f)); + Container c8 = new Container(BoxLayout.xCenter(), "MixedNestedLayoutsScreen2"); + c8.setName("container5"); + c8.add(take(flowFirstButton)); + c8.add(margin(take(flowSecondButton), 0f, 0f, 0f, 2.01f)); + c4.add(margin(c8, 2.01f, 0f, 0f, 0f)); + c2.add(margin(c4, 4.15f, 5.02f, 0f, 4.02f)); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsFormTest.java b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsFormTest.java new file mode 100644 index 00000000000..6d25192d832 --- /dev/null +++ b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/MixedNestedLayoutsFormTest.java @@ -0,0 +1,105 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [MixedNestedLayoutsForm] keeps the structure of the design it was imported from. +public class MixedNestedLayoutsFormTest extends AbstractTest { + private MixedNestedLayoutsForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new MixedNestedLayoutsForm(); + form.show(); + form.revalidate(); + uiid("everyLayoutNested", "MixedNestedLayoutsEveryLayoutNested"); + text("everyLayoutNested", "Every layout, nested"); + stretches("everyLayoutNested"); + uiid("moveAComponentThr", "MixedNestedLayoutsMoveAComponentThr"); + text("moveAComponentThr", "Move a component through every layout in turn"); + uiid("boxLayoutY", "MixedNestedLayoutsMoveAComponentThr"); + text("boxLayoutY", "BoxLayout Y"); + uiid("dragMeAnywhereButton", "MixedNestedLayoutsButton"); + text("dragMeAnywhereButton", "Drag me anywhere"); + stretches("dragMeAnywhereButton"); + above("boxLayoutY", "dragMeAnywhereButton"); + uiid("boxSecondButton", "MixedNestedLayoutsButton2"); + text("boxSecondButton", "Box second"); + stretches("boxSecondButton"); + above("dragMeAnywhereButton", "boxSecondButton"); + uiid("grid1Button", "MixedNestedLayoutsButton3"); + text("grid1Button", "Grid 1"); + uiid("grid2Button", "MixedNestedLayoutsButton3"); + text("grid2Button", "Grid 2"); + uiid("grid3Button", "MixedNestedLayoutsButton3"); + text("grid3Button", "Grid 3"); + uiid("flowFirstButton", "MixedNestedLayoutsButton4"); + text("flowFirstButton", "Flow first"); + uiid("flowSecondButton", "MixedNestedLayoutsButton5"); + text("flowSecondButton", "Flow second"); + leftOf("flowFirstButton", "flowSecondButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/MixedNestedLayoutsForm/after.png b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/after.png new file mode 100644 index 00000000000..baea16d7e9f Binary files /dev/null and b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/after.png differ diff --git a/scripts/designimport/examples/svg/MixedNestedLayoutsForm/before.png b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/before.png new file mode 100644 index 00000000000..600d0afe173 Binary files /dev/null and b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/before.png differ diff --git a/scripts/designimport/examples/svg/MixedNestedLayoutsForm/design.svg b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/design.svg new file mode 100644 index 00000000000..8b1cf835402 --- /dev/null +++ b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/design.svg @@ -0,0 +1,64 @@ + + +screen + + + + + + + + + +Every layout, nested + + + + +Move a component through every layout in turn + + + + +BoxLayout Y + + + +Drag me anywhere + + + +Box second + + + + + +Grid 1 + + + +Grid 2 + + + +Grid 3 + + + + + + + + +Flow first + + + +Flow second + + + + + + diff --git a/scripts/designimport/examples/svg/MixedNestedLayoutsForm/issues.md b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/issues.md new file mode 100644 index 00000000000..e35a9c9e62d --- /dev/null +++ b/scripts/designimport/examples/svg/MixedNestedLayoutsForm/issues.md @@ -0,0 +1,4 @@ +# svg/MixedNestedLayoutsForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens, the content column scrolls and grids keep their cell width and gain columns as the screen widens. diff --git a/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedForm.css b/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedForm.css new file mode 100644 index 00000000000..1d47e129823 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedForm.css @@ -0,0 +1,95 @@ +/* Generated by Codename One Design Import from NestedGuidedForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --nestedguided-color-1: #ffffff; + --nestedguided-color-2: #374151; + --nestedguided-color-3: #2563eb; +} + +NestedGuidedScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +NestedGuidedScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +NestedGuidedCard { + background-color: #ffffff; + border: none; + padding: 0 0 69.33mm 0; + margin: 0; +} + +NestedGuidedToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.2mm 0.4mm 4.2mm 0.4mm; + margin: 0; +} + +NestedGuidedGuidedLayoutNested { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +NestedGuidedALayeredLayoutCont { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +NestedGuidedButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 2.13mm 2.11mm 2.13mm; + margin: 0; +} + +NestedGuidedButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 1.69mm 2.11mm 1.69mm; + margin: 0; +} + +NestedGuidedButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 6.03mm 2.11mm 6.03mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedFormBase.java b/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedFormBase.java new file mode 100644 index 00000000000..f0318073ce5 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedFormBase.java @@ -0,0 +1,159 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from NestedGuidedForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [NestedGuidedForm], which extends it. +public class NestedGuidedFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label guidedLayoutNested; + protected Label aLayeredLayoutCont; + protected Label anchoredTitle; + protected Button primaryButton; + protected Label boxInsideGuided; + protected Button innerActionButton; + protected Label dragBetweenGuided; + protected Button ordinaryActionButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public NestedGuidedFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + guidedLayoutNested = new Label("Guided layout nested in ordinary ones"); + guidedLayoutNested.setUIID("NestedGuidedGuidedLayoutNested"); + guidedLayoutNested.setName("guidedLayoutNested"); + aLayeredLayoutCont = new Label("A LayeredLayout container inside a box, and boxes inside it"); + aLayeredLayoutCont.setUIID("NestedGuidedALayeredLayoutCont"); + aLayeredLayoutCont.setName("aLayeredLayoutCont"); + anchoredTitle = new Label("Anchored title"); + anchoredTitle.setUIID("NestedGuidedALayeredLayoutCont"); + anchoredTitle.setName("anchoredTitle"); + primaryButton = new Button("Primary"); + primaryButton.setUIID("NestedGuidedButton"); + primaryButton.setName("primaryButton"); + boxInsideGuided = new Label("Box inside guided"); + boxInsideGuided.setUIID("NestedGuidedALayeredLayoutCont"); + boxInsideGuided.setName("boxInsideGuided"); + innerActionButton = new Button("Inner action"); + innerActionButton.setUIID("NestedGuidedButton2"); + innerActionButton.setName("innerActionButton"); + dragBetweenGuided = new Label("Drag between guided and ordinary"); + dragBetweenGuided.setUIID("NestedGuidedALayeredLayoutCont"); + dragBetweenGuided.setName("dragBetweenGuided"); + ordinaryActionButton = new Button("Ordinary action"); + ordinaryActionButton.setUIID("NestedGuidedButton3"); + ordinaryActionButton.setName("ordinaryActionButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedGuidedScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedGuidedScreen2"); + c1.setName("screen"); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedGuidedCard"); + c2.setName("card"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedGuidedToolbar"); + c3.setName("toolbarItem"); + c3.add(take(guidedLayoutNested)); + c2.add(c3); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedGuidedScreen2"); + c4.setName("container"); + c4.add(take(aLayeredLayoutCont)); + Container c5 = new Container(BoxLayout.xCenter(), "NestedGuidedScreen2"); + c5.setName("container2"); + Container c6 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedGuidedScreen2"); + c6.setName("container3"); + c6.add(take(anchoredTitle)); + c6.add(margin(FlowLayout.encloseIn(take(primaryButton)), 11.53f, 0f, 0f, 0f)); + Container c7 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedGuidedScreen2"); + c7.setName("container4"); + c7.add(take(boxInsideGuided)); + c7.add(margin(take(innerActionButton), 2.09f, 0f, 0f, 0f)); + c6.add(margin(c7, 7.56f, 0f, 0f, 0f)); + c5.add(c6); + Container c8 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedGuidedScreen2"); + c8.setName("container5"); + c8.add(take(dragBetweenGuided)); + c8.add(margin(FlowLayout.encloseIn(take(ordinaryActionButton)), 2.09f, 0f, 0f, 0f)); + c5.add(margin(c8, 0f, 0f, 0f, 2.01f)); + c4.add(margin(FlowLayout.encloseRight(c5), 2.22f, 0f, 0f, 0f)); + c2.add(margin(c4, 4.15f, 3.22f, 0f, 4.02f)); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedFormTest.java b/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedFormTest.java new file mode 100644 index 00000000000..3160ff0c02d --- /dev/null +++ b/scripts/designimport/examples/svg/NestedGuidedForm/NestedGuidedFormTest.java @@ -0,0 +1,101 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [NestedGuidedForm] keeps the structure of the design it was imported from. +public class NestedGuidedFormTest extends AbstractTest { + private NestedGuidedForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new NestedGuidedForm(); + form.show(); + form.revalidate(); + uiid("guidedLayoutNested", "NestedGuidedGuidedLayoutNested"); + text("guidedLayoutNested", "Guided layout nested in ordinary ones"); + stretches("guidedLayoutNested"); + uiid("aLayeredLayoutCont", "NestedGuidedALayeredLayoutCont"); + text("aLayeredLayoutCont", "A LayeredLayout container inside a box, and boxes inside it"); + uiid("anchoredTitle", "NestedGuidedALayeredLayoutCont"); + text("anchoredTitle", "Anchored title"); + uiid("primaryButton", "NestedGuidedButton"); + text("primaryButton", "Primary"); + above("anchoredTitle", "primaryButton"); + uiid("boxInsideGuided", "NestedGuidedALayeredLayoutCont"); + text("boxInsideGuided", "Box inside guided"); + uiid("innerActionButton", "NestedGuidedButton2"); + text("innerActionButton", "Inner action"); + stretches("innerActionButton"); + above("boxInsideGuided", "innerActionButton"); + uiid("dragBetweenGuided", "NestedGuidedALayeredLayoutCont"); + text("dragBetweenGuided", "Drag between guided and ordinary"); + stretches("dragBetweenGuided"); + uiid("ordinaryActionButton", "NestedGuidedButton3"); + text("ordinaryActionButton", "Ordinary action"); + above("dragBetweenGuided", "ordinaryActionButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/NestedGuidedForm/after.png b/scripts/designimport/examples/svg/NestedGuidedForm/after.png new file mode 100644 index 00000000000..8a6f9180eae Binary files /dev/null and b/scripts/designimport/examples/svg/NestedGuidedForm/after.png differ diff --git a/scripts/designimport/examples/svg/NestedGuidedForm/before.png b/scripts/designimport/examples/svg/NestedGuidedForm/before.png new file mode 100644 index 00000000000..6c507698d2e Binary files /dev/null and b/scripts/designimport/examples/svg/NestedGuidedForm/before.png differ diff --git a/scripts/designimport/examples/svg/NestedGuidedForm/design.svg b/scripts/designimport/examples/svg/NestedGuidedForm/design.svg new file mode 100644 index 00000000000..cf8316fb4db --- /dev/null +++ b/scripts/designimport/examples/svg/NestedGuidedForm/design.svg @@ -0,0 +1,52 @@ + + +screen + + + + + + + + + +Guided layout nested in ordinary ones + + + + +A LayeredLayout container inside a box, and boxes inside it + + + + +Anchored title + + + +Primary + + + +Box inside guided + + + +Inner action + + + + + +Drag between guided and ordinary + + + +Ordinary action + + + + + + + diff --git a/scripts/designimport/examples/svg/NestedGuidedForm/issues.md b/scripts/designimport/examples/svg/NestedGuidedForm/issues.md new file mode 100644 index 00000000000..464f8053a89 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedGuidedForm/issues.md @@ -0,0 +1,4 @@ +# svg/NestedGuidedForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsForm.css b/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsForm.css new file mode 100644 index 00000000000..156c72645b3 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsForm.css @@ -0,0 +1,88 @@ +/* Generated by Codename One Design Import from NestedLayoutsForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --nestedlayouts-color-1: #ffffff; + --nestedlayouts-color-2: #374151; + --nestedlayouts-color-3: #2563eb; +} + +NestedLayoutsScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +NestedLayoutsScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +NestedLayoutsContainer { + background-color: #ffffff; + border: none; + padding: 0 0 121.37mm 0; + margin: 0; +} + +NestedLayoutsButton { + background-color: #1e3a8a; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 4.2mm 12.79mm 4.2mm 12.79mm; + margin: 0; +} + +NestedLayoutsNestedBorderBox { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +NestedLayoutsButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 25.42mm 2.9mm 25.42mm 2.9mm; + margin: 0; +} + +NestedLayoutsButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 25.42mm 3.03mm 25.42mm 3.03mm; + margin: 0; +} + +NestedLayoutsButton4 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 13.36mm 2.11mm 13.36mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsFormBase.java b/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsFormBase.java new file mode 100644 index 00000000000..1516c69d142 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsFormBase.java @@ -0,0 +1,160 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from NestedLayoutsForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [NestedLayoutsForm], which extends it. +public class NestedLayoutsFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Button nestedHierarchyButton; + protected Label nestedBorderBox; + protected Button aButton; + protected Button bButton; + protected Button cButton; + protected Button dButton; + protected Label dragComponentsBetw; + protected Button actionButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public NestedLayoutsFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + nestedHierarchyButton = new Button("Nested hierarchy"); + nestedHierarchyButton.setUIID("NestedLayoutsButton"); + nestedHierarchyButton.setName("nestedHierarchyButton"); + nestedBorderBox = new Label("Nested Border \u2192 Box X \u2192 Grid"); + nestedBorderBox.setUIID("NestedLayoutsNestedBorderBox"); + nestedBorderBox.setName("nestedBorderBox"); + aButton = new Button("A"); + aButton.setUIID("NestedLayoutsButton2"); + aButton.setName("aButton"); + bButton = new Button("B"); + bButton.setUIID("NestedLayoutsButton3"); + bButton.setName("bButton"); + cButton = new Button("C"); + cButton.setUIID("NestedLayoutsButton2"); + cButton.setName("cButton"); + dButton = new Button("D"); + dButton.setUIID("NestedLayoutsButton2"); + dButton.setName("dButton"); + dragComponentsBetw = new Label("Drag components between both nested containers."); + dragComponentsBetw.setUIID("NestedLayoutsNestedBorderBox"); + dragComponentsBetw.setName("dragComponentsBetw"); + actionButton = new Button("Action"); + actionButton.setUIID("NestedLayoutsButton4"); + actionButton.setName("actionButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedLayoutsScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedLayoutsScreen2"); + c1.setName("screen"); + Container c2 = new Container(new LayeredLayout(), "NestedLayoutsScreen2"); + c2.setName("container"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedLayoutsContainer"); + c3.setName("container2"); + c3.add(take(nestedHierarchyButton)); + c2.add(c3); + ((LayeredLayout) c2.getLayout()).setInsets(c3, "0mm 0mm 0mm 0mm"); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedLayoutsScreen2"); + c4.setName("container3"); + c4.add(take(nestedBorderBox)); + Container c5 = new Container(BoxLayout.xCenter(), "NestedLayoutsScreen2"); + c5.setName("container4"); + c5.setScrollableX(true); + int c6Cols = 2; + Container c6 = new Container(new GridLayout((4 + c6Cols - 1) / c6Cols, c6Cols), "NestedLayoutsScreen2"); + c6.setName("container5"); + c6.add(margin(take(aButton), 1f, 1f, 1f, 1f)); + c6.add(margin(take(bButton), 1f, 1f, 1f, 1f)); + c6.add(margin(take(cButton), 1f, 1f, 1f, 1f)); + c6.add(margin(take(dButton), 1f, 1f, 1f, 1f)); + c5.add(c6); + Container c7 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedLayoutsScreen2"); + c7.setName("container6"); + c7.add(take(dragComponentsBetw)); + c7.add(margin(FlowLayout.encloseIn(take(actionButton)), 2.09f, 0f, 0f, 0f)); + c5.add(margin(c7, 0f, 0f, 0f, 2.01f)); + c4.add(margin(c5, 2.09f, 0f, 0f, 0f)); + c2.add(c4); + ((LayeredLayout) c2.getLayout()).setInsets(c4, "16.81mm auto auto 4.02mm"); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsFormTest.java b/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsFormTest.java new file mode 100644 index 00000000000..f421a09ce76 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedLayoutsForm/NestedLayoutsFormTest.java @@ -0,0 +1,98 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [NestedLayoutsForm] keeps the structure of the design it was imported from. +public class NestedLayoutsFormTest extends AbstractTest { + private NestedLayoutsForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new NestedLayoutsForm(); + form.show(); + form.revalidate(); + uiid("nestedHierarchyButton", "NestedLayoutsButton"); + text("nestedHierarchyButton", "Nested hierarchy"); + stretches("nestedHierarchyButton"); + uiid("nestedBorderBox", "NestedLayoutsNestedBorderBox"); + text("nestedBorderBox", "Nested Border \u2192 Box X \u2192 Grid"); + uiid("aButton", "NestedLayoutsButton2"); + text("aButton", "A"); + uiid("bButton", "NestedLayoutsButton3"); + text("bButton", "B"); + uiid("cButton", "NestedLayoutsButton2"); + text("cButton", "C"); + uiid("dButton", "NestedLayoutsButton2"); + text("dButton", "D"); + uiid("dragComponentsBetw", "NestedLayoutsNestedBorderBox"); + text("dragComponentsBetw", "Drag components between both nested containers."); + stretches("dragComponentsBetw"); + uiid("actionButton", "NestedLayoutsButton4"); + text("actionButton", "Action"); + above("dragComponentsBetw", "actionButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/NestedLayoutsForm/after.png b/scripts/designimport/examples/svg/NestedLayoutsForm/after.png new file mode 100644 index 00000000000..9eee63e8096 Binary files /dev/null and b/scripts/designimport/examples/svg/NestedLayoutsForm/after.png differ diff --git a/scripts/designimport/examples/svg/NestedLayoutsForm/before.png b/scripts/designimport/examples/svg/NestedLayoutsForm/before.png new file mode 100644 index 00000000000..1fd7efa4307 Binary files /dev/null and b/scripts/designimport/examples/svg/NestedLayoutsForm/before.png differ diff --git a/scripts/designimport/examples/svg/NestedLayoutsForm/design.svg b/scripts/designimport/examples/svg/NestedLayoutsForm/design.svg new file mode 100644 index 00000000000..448e69057c3 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedLayoutsForm/design.svg @@ -0,0 +1,52 @@ + + +screen + + + + + + + + + +Nested hierarchy + + + + +Nested Border → Box X → Grid + + + + + +A + + + +B + + + +C + + + +D + + + + +Drag components between both nested containers. + + + +Action + + + + + + + diff --git a/scripts/designimport/examples/svg/NestedLayoutsForm/issues.md b/scripts/designimport/examples/svg/NestedLayoutsForm/issues.md new file mode 100644 index 00000000000..a19ddd49bef --- /dev/null +++ b/scripts/designimport/examples/svg/NestedLayoutsForm/issues.md @@ -0,0 +1,4 @@ +# svg/NestedLayoutsForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens, the content column scrolls and grids keep their cell width and gain columns as the screen widens. diff --git a/scripts/designimport/examples/svg/NestedTableForm/NestedTableForm.css b/scripts/designimport/examples/svg/NestedTableForm/NestedTableForm.css new file mode 100644 index 00000000000..e473a8bc768 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedTableForm/NestedTableForm.css @@ -0,0 +1,107 @@ +/* Generated by Codename One Design Import from NestedTableForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --nestedtable-color-1: #ffffff; + --nestedtable-color-2: #374151; + --nestedtable-color-3: #2563eb; +} + +NestedTableScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +NestedTableScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +NestedTableCard { + background-color: #ffffff; + border: none; + padding: 0 0 80.18mm 0; + margin: 0; +} + +NestedTableToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.2mm 14.67mm 4.2mm 14.67mm; + margin: 0; +} + +NestedTableTablesInsideTables { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +NestedTableOuter00 { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +NestedTableButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 1.61mm 2.11mm 1.61mm; + margin: 0; +} + +NestedTableButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 4.42mm 2.28mm 4.42mm 2.28mm; + margin: 0; +} + +NestedTableButton3 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 2.11mm 2.11mm 2.11mm; + margin: 0; +} + +NestedTableButton4 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 2.28mm 2.11mm 2.28mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/NestedTableForm/NestedTableFormBase.java b/scripts/designimport/examples/svg/NestedTableForm/NestedTableFormBase.java new file mode 100644 index 00000000000..43688a94c95 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedTableForm/NestedTableFormBase.java @@ -0,0 +1,165 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from NestedTableForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [NestedTableForm], which extends it. +public class NestedTableFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label tablesInsideTables; + protected Label outer00; + protected Button inner00Button; + protected Button inner01Button; + protected Button inner10Button; + protected Button outer10Button; + protected Label boxInACell; + protected Button actionButton; + protected Button outer22Button; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public NestedTableFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + tablesInsideTables = new Label("Tables inside tables"); + tablesInsideTables.setUIID("NestedTableTablesInsideTables"); + tablesInsideTables.setName("tablesInsideTables"); + outer00 = new Label("Outer 0,0"); + outer00.setUIID("NestedTableOuter00"); + outer00.setName("outer00"); + inner00Button = new Button("Inner 0,0"); + inner00Button.setUIID("NestedTableButton"); + inner00Button.setName("inner00Button"); + inner01Button = new Button("Inner 0,1"); + inner01Button.setUIID("NestedTableButton"); + inner01Button.setName("inner01Button"); + inner10Button = new Button("Inner 1,0"); + inner10Button.setUIID("NestedTableButton"); + inner10Button.setName("inner10Button"); + outer10Button = new Button("Outer 1,0"); + outer10Button.setUIID("NestedTableButton2"); + outer10Button.setName("outer10Button"); + boxInACell = new Label("Box in a cell"); + boxInACell.setUIID("NestedTableOuter00"); + boxInACell.setName("boxInACell"); + actionButton = new Button("Action"); + actionButton.setUIID("NestedTableButton3"); + actionButton.setName("actionButton"); + outer22Button = new Button("Outer 2,2"); + outer22Button.setUIID("NestedTableButton4"); + outer22Button.setName("outer22Button"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedTableScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedTableScreen2"); + c1.setName("screen"); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedTableCard"); + c2.setName("card"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedTableToolbar"); + c3.setName("toolbarItem"); + c3.add(take(tablesInsideTables)); + c2.add(c3); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedTableScreen2"); + c4.setName("container"); + Container c5 = new Container(BoxLayout.xCenter(), "NestedTableScreen2"); + c5.setName("row"); + c5.add(take(outer00)); + int c6Cols = 2; + Container c6 = new Container(new GridLayout((3 + c6Cols - 1) / c6Cols, c6Cols), "NestedTableScreen2"); + c6.setName("container2"); + c6.add(margin(take(inner00Button), 1f, 1f, 1f, 1f)); + c6.add(margin(take(inner01Button), 1f, 1f, 1f, 1f)); + c6.add(margin(take(inner10Button), 1f, 1f, 1f, 1f)); + c5.add(margin(c6, 0f, 0f, 0f, 9.04f)); + c4.add(c5); + Container c7 = new Container(BoxLayout.xCenter(), "NestedTableScreen2"); + c7.setName("row2"); + c7.add(take(outer10Button)); + Container c8 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "NestedTableScreen2"); + c8.setName("container3"); + c8.add(take(boxInACell)); + c8.add(margin(take(actionButton), 2.09f, 0f, 0f, 0f)); + c7.add(margin(c8, 0f, 0f, 0f, 2.01f)); + c4.add(margin(c7, 2.01f, 0f, 0f, 0f)); + c4.add(margin(FlowLayout.encloseRight(take(outer22Button)), 2.01f, 0f, 0f, 0f)); + c2.add(margin(c4, 4.02f, 0f, 0f, 4.02f)); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/NestedTableForm/NestedTableFormTest.java b/scripts/designimport/examples/svg/NestedTableForm/NestedTableFormTest.java new file mode 100644 index 00000000000..541e6f9362a --- /dev/null +++ b/scripts/designimport/examples/svg/NestedTableForm/NestedTableFormTest.java @@ -0,0 +1,100 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [NestedTableForm] keeps the structure of the design it was imported from. +public class NestedTableFormTest extends AbstractTest { + private NestedTableForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new NestedTableForm(); + form.show(); + form.revalidate(); + uiid("tablesInsideTables", "NestedTableTablesInsideTables"); + text("tablesInsideTables", "Tables inside tables"); + stretches("tablesInsideTables"); + uiid("outer00", "NestedTableOuter00"); + text("outer00", "Outer 0,0"); + uiid("inner00Button", "NestedTableButton"); + text("inner00Button", "Inner 0,0"); + uiid("inner01Button", "NestedTableButton"); + text("inner01Button", "Inner 0,1"); + uiid("inner10Button", "NestedTableButton"); + text("inner10Button", "Inner 1,0"); + uiid("outer10Button", "NestedTableButton2"); + text("outer10Button", "Outer 1,0"); + uiid("boxInACell", "NestedTableOuter00"); + text("boxInACell", "Box in a cell"); + uiid("actionButton", "NestedTableButton3"); + text("actionButton", "Action"); + stretches("actionButton"); + above("boxInACell", "actionButton"); + uiid("outer22Button", "NestedTableButton4"); + text("outer22Button", "Outer 2,2"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/NestedTableForm/after.png b/scripts/designimport/examples/svg/NestedTableForm/after.png new file mode 100644 index 00000000000..f4a6b09f297 Binary files /dev/null and b/scripts/designimport/examples/svg/NestedTableForm/after.png differ diff --git a/scripts/designimport/examples/svg/NestedTableForm/before.png b/scripts/designimport/examples/svg/NestedTableForm/before.png new file mode 100644 index 00000000000..dd4b1dc5005 Binary files /dev/null and b/scripts/designimport/examples/svg/NestedTableForm/before.png differ diff --git a/scripts/designimport/examples/svg/NestedTableForm/design.svg b/scripts/designimport/examples/svg/NestedTableForm/design.svg new file mode 100644 index 00000000000..eaa7c8995c4 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedTableForm/design.svg @@ -0,0 +1,54 @@ + + +screen + + + + + + + + + +Tables inside tables + + + + +Outer 0,0 + + + + +Inner 0,0 + + + +Inner 0,1 + + + +Inner 1,0 + + + + +Outer 1,0 + + + +Box in a cell + + + +Action + + + + +Outer 2,2 + + + + + diff --git a/scripts/designimport/examples/svg/NestedTableForm/issues.md b/scripts/designimport/examples/svg/NestedTableForm/issues.md new file mode 100644 index 00000000000..b9d443cea10 --- /dev/null +++ b/scripts/designimport/examples/svg/NestedTableForm/issues.md @@ -0,0 +1,4 @@ +# svg/NestedTableForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens, the content column scrolls and grids keep their cell width and gain columns as the screen widens. diff --git a/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutForm.css b/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutForm.css new file mode 100644 index 00000000000..55aefe0ab3d --- /dev/null +++ b/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutForm.css @@ -0,0 +1,91 @@ +/* Generated by Codename One Design Import from TableLayoutForm.svg. + Sizes are millimetres at 0.79 design px per dp. Edit freely; a regenerate overwrites this file. */ + +:root { + --tablelayout-color-1: #ffffff; + --tablelayout-color-2: #374151; + --tablelayout-color-3: #2563eb; +} + +TableLayoutScreen { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +TableLayoutScreen2 { + background-color: transparent; + border: none; + padding: 0 0 0 0; + margin: 0; +} + +TableLayoutCard { + background-color: #ffffff; + border: none; + padding: 0 0 101.28mm 0; + margin: 0; +} + +TableLayoutToolbar { + background-color: #1e3a8a; + border: none; + padding: 4.2mm 8.44mm 4.2mm 8.44mm; + margin: 0; +} + +TableLayoutTableLayoutExplic { + background-color: transparent; + border: none; + color: #ffffff; + font-family: "native:MainBold"; + font-size: 3.7mm; + text-align: center; + padding: 0 0 0 0; + margin: 0; +} + +TableLayoutName { + background-color: transparent; + border: none; + color: #374151; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: left; + padding: 0 0 0 0; + margin: 0; +} + +TableLayoutTextField { + background-color: #ffffff; + border: 0.4mm solid #94a3b8; + border-radius: 2.41mm; + padding: 0 0 0 0; + margin: 0; +} + +TableLayoutButton { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 2.08mm 2.11mm 2.08mm; + margin: 0; +} + +TableLayoutButton2 { + background-color: #2563eb; + border: none; + border-radius: 1mm; + color: #ffffff; + font-family: "native:MainRegular"; + font-size: 2.09mm; + text-align: center; + padding: 2.11mm 2.03mm 2.11mm 2.03mm; + margin: 0; +} + diff --git a/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutFormBase.java b/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutFormBase.java new file mode 100644 index 00000000000..4d8b0cb85dc --- /dev/null +++ b/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutFormBase.java @@ -0,0 +1,143 @@ +package com.example.design; + +import com.codename1.ui.*; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.*; +import com.codename1.ui.plaf.Style; + +/// Generated by Codename One Design Import from TableLayoutForm.svg. +/// +/// Regenerating the import overwrites this class. Put your own code in [TableLayoutForm], which extends it. +public class TableLayoutFormBase extends Form { + // Responsive levers. The importer writes them from its options; change them here or there. + /// Content is never wider than this, and is centred when the screen is; 0 turns it off. + protected static final float MAX_CONTENT_WIDTH_MM = 101.6f; + /// The content column scrolls when it is taller than the screen. + protected static final boolean SCROLLABLE = true; + /// Grids keep their design cell width and gain or lose columns with the screen. + protected static final boolean ADAPTIVE_GRID = true; + + protected Label tableLayoutExplic; + protected Label name; + protected TextField field; + protected Label role; + protected Button designerButton; + protected Button developerButton; + /// The container that scrolls and is held to MAX_CONTENT_WIDTH_MM. + protected Container content; + private float arrangedWidthMm = -1; + + public TableLayoutFormBase() { + super(new BorderLayout()); + setScrollable(false); + getTitleArea().setUIID("Container"); + getContentPane().setUIID("Container"); + createComponents(); + arrange(); + addSizeChangedListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + arrange(); + } + }); + } + + /// Creates every component once; the arrangements only lay them out. + protected void createComponents() { + tableLayoutExplic = new Label("TableLayout \u2014 explicit cells"); + tableLayoutExplic.setUIID("TableLayoutTableLayoutExplic"); + tableLayoutExplic.setName("tableLayoutExplic"); + name = new Label("Name"); + name.setUIID("TableLayoutName"); + name.setName("name"); + field = new TextField("", "", 20, TextField.ANY); + field.setUIID("TableLayoutTextField"); + field.setName("field"); + role = new Label("Role"); + role.setUIID("TableLayoutName"); + role.setName("role"); + designerButton = new Button("Designer"); + designerButton.setUIID("TableLayoutButton"); + designerButton.setName("designerButton"); + developerButton = new Button("Developer"); + developerButton.setUIID("TableLayoutButton2"); + developerButton.setName("developerButton"); + } + + /// Lays the components out for the current width. Runs again whenever the size changes. + protected void arrange() { + float widthMm = CN.getDisplayWidth() / (float) CN.convertToPixels(1f); + if (Math.abs(widthMm - arrangedWidthMm) < 1) { + return; + } + arrangedWidthMm = widthMm; + removeAll(); + Container root = build(widthMm); + if (MAX_CONTENT_WIDTH_MM > 0 && content != null && widthMm > MAX_CONTENT_WIDTH_MM) { + float side = (widthMm - MAX_CONTENT_WIDTH_MM) / 2; + Style s = content.getAllStyles(); + s.setPaddingUnit(Style.UNIT_TYPE_DIPS); + s.setPadding(Component.LEFT, s.getPaddingLeftNoRTL() / (float) CN.convertToPixels(1f) + side); + s.setPadding(Component.RIGHT, s.getPaddingRightNoRTL() / (float) CN.convertToPixels(1f) + side); + } + add(BorderLayout.CENTER, root); + revalidate(); + } + + /// The phone arrangement, from "svg" (308 x 667 design px). + protected Container build(float widthMm) { + Container root = new Container(new BoxLayout(BoxLayout.Y_AXIS), "TableLayoutScreen"); + root.setScrollableY(SCROLLABLE); + Container c1 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "TableLayoutScreen2"); + c1.setName("screen"); + Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "TableLayoutCard"); + c2.setName("card"); + Container c3 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "TableLayoutToolbar"); + c3.setName("toolbarItem"); + c3.add(take(tableLayoutExplic)); + c2.add(c3); + Container c4 = new Container(new BoxLayout(BoxLayout.Y_AXIS), "TableLayoutScreen2"); + c4.setName("container"); + Container c5 = new Container(BoxLayout.xCenter(), "TableLayoutScreen2"); + c5.setName("row"); + c5.add(take(name)); + c5.add(margin(take(field), 0f, 0f, 0f, 2.61f)); + c4.add(c5); + Container c6 = new Container(BoxLayout.xCenter(), "TableLayoutScreen2"); + c6.setName("row2"); + c6.add(take(role)); + c6.add(margin(take(designerButton), 0f, 0f, 0f, 3.82f)); + c6.add(margin(take(developerButton), 0f, 0f, 0f, 2.01f)); + c4.add(margin(c6, 2.01f, 0f, 0f, 0f)); + c2.add(margin(c4, 4.02f, 0f, 0f, 4.02f)); + c1.add(c2); + root.add(c1); + content = root; + return root; + } + + /// Detaches a component from the previous arrangement so the next one can add it. + protected static T take(T c) { + if (c.getParent() != null) { + c.remove(); + } + return c; + } + + /// Sets margins in millimetres: top, right, bottom, left. + protected static Component margin(Component c, float top, float right, float bottom, float left) { + Style s = c.getAllStyles(); + s.setMarginUnit(Style.UNIT_TYPE_DIPS); + s.setMargin(top, bottom, left, right); + return c; + } + + /// How many grid columns of the design's cell width fit, between 1 and max. + protected static int columns(float availMm, float cellMm, float gapMm, int designColumns, int max) { + if (!ADAPTIVE_GRID) { + return designColumns; + } + int c = (int) Math.floor((availMm + gapMm) / (cellMm + gapMm) + 0.15f); + return Math.max(1, Math.min(max, c)); + } +} diff --git a/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutFormTest.java b/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutFormTest.java new file mode 100644 index 00000000000..c520756405e --- /dev/null +++ b/scripts/designimport/examples/svg/TableLayoutForm/TableLayoutFormTest.java @@ -0,0 +1,94 @@ +package com.example.design; + +import com.codename1.components.SpanLabel; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Label; +import com.codename1.ui.TextArea; + +/// Generated by Codename One Design Import: checks that [TableLayoutForm] keeps the structure of the design it was imported from. +public class TableLayoutFormTest extends AbstractTest { + private TableLayoutForm form; + + @Override + public boolean shouldExecuteOnEDT() { + return true; + } + + @Override + public boolean runTest() throws Exception { + form = new TableLayoutForm(); + form.show(); + form.revalidate(); + uiid("tableLayoutExplic", "TableLayoutTableLayoutExplic"); + text("tableLayoutExplic", "TableLayout \u2014 explicit cells"); + stretches("tableLayoutExplic"); + uiid("name", "TableLayoutName"); + text("name", "Name"); + uiid("field", "TableLayoutTextField"); + leftOf("name", "field"); + uiid("role", "TableLayoutName"); + text("role", "Role"); + uiid("designerButton", "TableLayoutButton"); + text("designerButton", "Designer"); + leftOf("role", "designerButton"); + uiid("developerButton", "TableLayoutButton2"); + text("developerButton", "Developer"); + leftOf("designerButton", "developerButton"); + return true; + } + + private Component find(String name) { + Component c = find(form, name); + assertNotNull(c, "missing component " + name); + return c; + } + + private static Component find(Container root, String name) { + for (int i = 0; i < root.getComponentCount(); i++) { + Component c = root.getComponentAt(i); + if (name.equals(c.getName())) { + return c; + } + if (c instanceof Container) { + Component f = find((Container) c, name); + if (f != null) { + return f; + } + } + } + return null; + } + + private void uiid(String name, String uiid) { + Component c = find(name); + String actual = c instanceof SpanLabel ? ((SpanLabel) c).getTextUIID() : c.getUIID(); + assertEqual(uiid, actual, name + " UIID"); + } + + private void text(String name, String text) { + Component c = find(name); + String actual = c instanceof Label ? ((Label) c).getText() : c instanceof TextArea + ? ((TextArea) c).getHint() : c instanceof SpanLabel ? ((SpanLabel) c).getText() : null; + assertEqual(text, actual, name + " text"); + } + + private void above(String a, String b) { + assertTrue(find(a).getAbsoluteY() + find(a).getHeight() <= find(b).getAbsoluteY() + 1, + a + " should be above " + b); + } + + private void leftOf(String a, String b) { + assertTrue(find(a).getAbsoluteX() + find(a).getWidth() <= find(b).getAbsoluteX() + 1, + a + " should be left of " + b); + } + + private void stretches(String name) { + Component c = find(name); + Container p = c.getParent(); + int inner = p.getWidth() - p.getStyle().getHorizontalPadding(); + assertTrue(c.getWidth() + c.getStyle().getHorizontalMargins() >= inner * 0.9, + name + " should span its column"); + } +} diff --git a/scripts/designimport/examples/svg/TableLayoutForm/after.png b/scripts/designimport/examples/svg/TableLayoutForm/after.png new file mode 100644 index 00000000000..36d73b4ee26 Binary files /dev/null and b/scripts/designimport/examples/svg/TableLayoutForm/after.png differ diff --git a/scripts/designimport/examples/svg/TableLayoutForm/before.png b/scripts/designimport/examples/svg/TableLayoutForm/before.png new file mode 100644 index 00000000000..4fd45db2d24 Binary files /dev/null and b/scripts/designimport/examples/svg/TableLayoutForm/before.png differ diff --git a/scripts/designimport/examples/svg/TableLayoutForm/design.svg b/scripts/designimport/examples/svg/TableLayoutForm/design.svg new file mode 100644 index 00000000000..587980aaa88 --- /dev/null +++ b/scripts/designimport/examples/svg/TableLayoutForm/design.svg @@ -0,0 +1,40 @@ + + +screen + + + + + + + + + +TableLayout — explicit cells + + + + +Name + + + + + + + + +Role + + + +Designer + + + +Developer + + + + + diff --git a/scripts/designimport/examples/svg/TableLayoutForm/issues.md b/scripts/designimport/examples/svg/TableLayoutForm/issues.md new file mode 100644 index 00000000000..8feb65b8251 --- /dev/null +++ b/scripts/designimport/examples/svg/TableLayoutForm/issues.md @@ -0,0 +1,5 @@ +# svg/TableLayoutForm + +- **WARNING** (detect) "g" is clipped to a shape; a container clips only to its rectangle. +- **TODO** (classify) "path" was classified as text_field with 50% confidence (an empty outlined box the height of an input). +- **INFO** (responsive) The design has one phone frame, so the form adapts by default: wide components stretch to the screen width, content is capped at 640dp and centred on wider screens and the content column scrolls. diff --git a/scripts/designimport/examples/workbench.png b/scripts/designimport/examples/workbench.png new file mode 100644 index 00000000000..fab82ce93f0 Binary files /dev/null and b/scripts/designimport/examples/workbench.png differ diff --git a/scripts/designimport/javase/pom.xml b/scripts/designimport/javase/pom.xml new file mode 100644 index 00000000000..66f529abf8f --- /dev/null +++ b/scripts/designimport/javase/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + com.codenameone.designimportcn1-designimport8.0-SNAPSHOT + com.codenameone + codenameone-designimport + codenameone-designimport + Codename One Design Import desktop tool. + javasejavase + + ${project.basedir}/../common/src/test/java + ${project.basedir}/../../settings/javase/src/desktop/resourcesNativeTheme.res + + com.codenameonecodenameone-maven-plugin${cn1.plugin.version}add-se-sourcesgenerate-sourcesgenerate-javase-sources + org.codehaus.mojobuild-helper-maven-plugin3.4.0add-desktop-sourcesgenerate-sourcesadd-source${project.basedir}/src/desktop/javaadd-javase-test-sourcesgenerate-test-sourcesadd-test-source${project.basedir}/src/test/java + + + + com.codenameone.designimport${cn1app.name}-common${project.version} + com.codenameone.designimport${cn1app.name}-common${project.version}teststest + com.codenameonecodenameone-core + com.codenameonecodenameone-javase + org.junit.jupiterjunit-jupiter-api5.10.2test + org.junit.jupiterjunit-jupiter-engine5.10.2test + + executable-jarjavase + + org.codehaus.mojoproperties-maven-plugin1.0.0initializeread-project-properties${basedir}/../common/codenameone_settings.properties + com.codenameonecodenameone-maven-plugin${cn1.plugin.version}generate-desktop-app-wrappergenerate-sourcesgenerate-desktop-app-wrapper + org.apache.maven.pluginsmaven-dependency-plugincopy-dependenciesprepare-packagecopy-dependencies${project.build.directory}/libsruntime + org.apache.maven.pluginsmaven-jar-plugintruelibs/com.codename1.designimport.DesignImportLauncherCodename One Design ImportCodename One Design Import${project.version} + + + diff --git a/scripts/designimport/javase/src/desktop/java/com/codename1/designimport/DesignImportLauncher.java b/scripts/designimport/javase/src/desktop/java/com/codename1/designimport/DesignImportLauncher.java new file mode 100644 index 00000000000..2b7c730aff1 --- /dev/null +++ b/scripts/designimport/javase/src/desktop/java/com/codename1/designimport/DesignImportLauncher.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.designimport; + +/// Entry point of the desktop tool. +public final class DesignImportLauncher { + private DesignImportLauncher() { + } + + public static void main(String[] args) throws Exception { + DesignImportStub.main(args); + } +} diff --git a/scripts/designimport/javase/src/desktop/java/com/codename1/designimport/DesignImportStub.java b/scripts/designimport/javase/src/desktop/java/com/codename1/designimport/DesignImportStub.java new file mode 100644 index 00000000000..395e3d00fb7 --- /dev/null +++ b/scripts/designimport/javase/src/desktop/java/com/codename1/designimport/DesignImportStub.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +/// Starts the app in a desktop window; see [DesignImportWindow]. +public final class DesignImportStub { + private DesignImportStub() { + } + + public static void main(String[] args) { + DesignImportWindow.main(args); + } +} diff --git a/scripts/designimport/javase/src/test/java/com/codename1/designimport/WorkbenchTest.java b/scripts/designimport/javase/src/test/java/com/codename1/designimport/WorkbenchTest.java new file mode 100644 index 00000000000..7508dc22553 --- /dev/null +++ b/scripts/designimport/javase/src/test/java/com/codename1/designimport/WorkbenchTest.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.designimport; + +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.Image; +import java.io.File; +import javax.swing.JPanel; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/// Drives the desktop window without a display: opens a design, selects a layer, overrides +/// its role, accepts an issue and toggles the onion skin, then renders the window. With +/// `-Ddesignimport.examples=DIR` the render is written to `DIR/workbench.png`. +class WorkbenchTest { + @BeforeAll + static void init() { + if (!com.codename1.ui.Display.isInitialized()) { + com.codename1.ui.Display.init(new JPanel()); + } + } + + @Test + void window() throws Exception { + // The tool's own stylesheet, compiled the way the app compiles it when it starts. + DesignImportApp.installTheme(); + DesignImportService svc = new DesignImportService(); + Workbench w = new Workbench(svc); + Form f = w.getForm(); + f.setVisible(true); // shown, as far as painting is concerned, without a window + f.setWidth(1600); + f.setHeight(1000); + w.open(new File("../../../docs/developer-guide/sketch/new-gui-builder-left-toolbar.sketch").getAbsolutePath()); + w.showPath("new-gui-builder-left-toolbar.sketch"); + ImportSession s = svc.getSession(); + assertNotNull(s, "the design opened"); + DNode leaf = firstLeaf(s.primary().root); + w.select(leaf.id); + w.liveView().resize(820, 1180, true); + f.setShouldCalcPreferredSize(true); + layoutAll(f); + assertTrue(count(f, "WorkbenchLayer") + count(f, "WorkbenchLayerSelected") > 3, "the layer tree is filled"); + assertEquals(1, count(f, "WorkbenchLayerSelected"), "one layer is selected"); + assertTrue(count(f, "WorkbenchStage") > 0, "the checklist groups issues by stage"); + Image shot = Image.createImage(1600, 1000, 0xff000000); + f.paintComponent(shot.getGraphics(), true); + String dir = System.getProperty("designimport.examples"); + if (dir != null) { + java.io.OutputStream o = new java.io.FileOutputStream(new File(dir, "workbench.png")); + try { + com.codename1.ui.util.ImageIO.getImageIO().save(shot, o, com.codename1.ui.util.ImageIO.FORMAT_PNG, 1); + } finally { + o.close(); + } + } + } + + static void layoutAll(Container c) { + c.layoutContainer(); + for (int i = 0; i < c.getComponentCount(); i++) { + if (c.getComponentAt(i) instanceof Container) { + layoutAll((Container) c.getComponentAt(i)); + } + } + } + + static DNode firstLeaf(DNode n) { + return n.children.isEmpty() ? n : firstLeaf(n.children.get(n.children.size() / 2)); + } + + static int count(Component c, String uiid) { + int n = uiid.equals(c.getUIID()) ? 1 : 0; + if (c instanceof Container) { + for (int i = 0; i < ((Container) c).getComponentCount(); i++) { + n += count(((Container) c).getComponentAt(i), uiid); + } + } + return n; + } +} diff --git a/scripts/designimport/pom.xml b/scripts/designimport/pom.xml new file mode 100644 index 00000000000..ba6fef500b4 --- /dev/null +++ b/scripts/designimport/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + com.codenameone.designimport + cn1-designimport + 8.0-SNAPSHOT + pom + Codename One Design Import + Turns Figma, Sketch and Photoshop designs into Codename One forms, CSS and tests. + https://www.codenameone.com + GPL v2 With Classpath Exceptionhttps://openjdk.java.net/legal/gplv2+ce.htmlrepo + + shaiShai Almogshai.almog@codenameone.com+4 + chenChen Fishbeinchen.fishbein@codenameone.com+4 + shannahSteve Hannahsteve.hannah@codenameone.com-8 + + https://github.com/codenameone/CodenameOnescm:git:git@github.com:codenameone/CodenameOne.git + common + + 8.0-SNAPSHOT + 8.0-SNAPSHOT + UTF-8 + + 1.8 + 1.8 + 1.8 + 3.11.0 + cn1-designimport + + + com.codenameonecodenameone-core${cn1.version} + com.codenameonecodenameone-javase${cn1.version} + + + com.codenameonecodenameone-maven-plugin${cn1.plugin.version} + org.apache.maven.pluginsmaven-compiler-plugin${maven-compiler-plugin.version} + org.apache.maven.pluginsmaven-surefire-plugin3.2.2 + org.apache.maven.pluginsmaven-jar-plugin3.3.0 + org.apache.maven.pluginsmaven-dependency-plugin3.6.1 + + com.codenameonecodenameone-maven-plugin${cn1.plugin.version} + + + javasecodename1.platformjavasetruejavase + designimport-central + org.apache.maven.pluginsmaven-source-plugin3.3.0attach-sourcesjar-no-fork + org.apache.maven.pluginsmaven-javadoc-plugin3.6.3nonefalseattach-javadocsjar + org.apache.maven.pluginsmaven-gpg-plugin1.5sign-artifactsverifysign${gpg.passphrase}--pinentry-modeloopback + org.sonatype.centralcentral-publishing-maven-plugin0.8.0truecentraltrue + + + diff --git a/scripts/initializr/common/src/main/resources/skill/references/mockup-comparison.md b/scripts/initializr/common/src/main/resources/skill/references/mockup-comparison.md index 78697c2bdfb..1211a35b4cf 100644 --- a/scripts/initializr/common/src/main/resources/skill/references/mockup-comparison.md +++ b/scripts/initializr/common/src/main/resources/skill/references/mockup-comparison.md @@ -19,6 +19,12 @@ to a predictable path for the comparison tool to read. > **independent reference**, so comparing against it actually measures whether you built the right > thing. +> **Need a whole screen, not just a starting theme?** The Design Import tool +> (`scripts/designimport`, see the developer guide's "Design Import" chapter) turns a Figma, +> Sketch, PSD or SVG frame into a form, a stylesheet and a unit test, and serves the same steps +> as `designimport_*` MCP tools. Its `designimport_score` gives the similarity this loop +> measures. Use the tools below when you build the screen yourself. + ## The loop 1. **(Optional) Import the design** to seed your styling: