From 23d874679ecd54b1eae302a4fe66270c4a3a7af9 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 18:49:49 +0200 Subject: [PATCH 1/6] Fold-aware layouts: FoldLayout, FoldAvoidingLayout and Form fold semantics Layouts declare how a form responds to a fold or posture change (FOLD_IGNORE / FOLD_REVALIDATE / FOLD_ANIMATE) and read the hinge through FoldState. The current form listens for posture changes, calls onFoldChanged and revalidates or animates its content pane accordingly. Adds animation screenshot tests for book, table-top and flip folds. Co-Authored-By: Claude Opus 5.5 --- CodenameOne/src/com/codename1/ui/Display.java | 5 + .../src/com/codename1/ui/FoldState.java | 210 +++++++++++ CodenameOne/src/com/codename1/ui/Form.java | 70 ++++ .../ui/layouts/FoldAvoidingLayout.java | 215 +++++++++++ .../com/codename1/ui/layouts/FoldLayout.java | 351 ++++++++++++++++++ .../src/com/codename1/ui/layouts/Layout.java | 66 ++++ ...viceInputAndFormFactorsJava007Snippet.java | 96 +++++ ...viceInputAndFormFactorsJava008Snippet.java | 99 +++++ .../Device-Input-And-Form-Factors.asciidoc | 43 +++ .../codename1/ui/FormFoldBehaviorTest.java | 118 ++++++ .../codename1/ui/layouts/FoldLayoutTest.java | 208 +++++++++++ .../AbstractFoldAnimationScreenshotTest.java | 115 ++++++ .../tests/Cn1ssDeviceRunner.java | 4 + .../tests/FoldAvoidingGridScreenshotTest.java | 27 ++ .../tests/FoldBookOpenScreenshotTest.java | 33 ++ .../tests/FoldFlipGridScreenshotTest.java | 27 ++ .../tests/FoldTableTopScreenshotTest.java | 33 ++ 17 files changed, 1720 insertions(+) create mode 100644 CodenameOne/src/com/codename1/ui/FoldState.java create mode 100644 CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java create mode 100644 CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java create mode 100644 docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava007Snippet.java create mode 100644 docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava008Snippet.java create mode 100644 maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java create mode 100644 maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java create mode 100644 scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/AbstractFoldAnimationScreenshotTest.java create mode 100644 scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldAvoidingGridScreenshotTest.java create mode 100644 scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldBookOpenScreenshotTest.java create mode 100644 scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldFlipGridScreenshotTest.java create mode 100644 scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldTableTopScreenshotTest.java diff --git a/CodenameOne/src/com/codename1/ui/Display.java b/CodenameOne/src/com/codename1/ui/Display.java index 37c140b6690..3722c34bce7 100644 --- a/CodenameOne/src/com/codename1/ui/Display.java +++ b/CodenameOne/src/com/codename1/ui/Display.java @@ -6707,6 +6707,11 @@ public DevicePosture getDevicePosture() { /// delivered `com.codename1.ui.events.ActionEvent` has the type `PostureChange`; query the new /// posture from `com.codename1.ui.DevicePosture#getInstance()`. /// + /// The current form already responds to these changes by itself, laying out again or + /// animating as its layouts ask (see `com.codename1.ui.layouts.Layout#getFoldBehavior()` and + /// `com.codename1.ui.Form#onFoldChanged(FoldState)`), so a listener is only needed for + /// changes a layout cannot express. + /// /// #### Parameters /// /// - `l`: the listener to add diff --git a/CodenameOne/src/com/codename1/ui/FoldState.java b/CodenameOne/src/com/codename1/ui/FoldState.java new file mode 100644 index 00000000000..d296fcddf98 --- /dev/null +++ b/CodenameOne/src/com/codename1/ui/FoldState.java @@ -0,0 +1,210 @@ +/* + * 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.ui; + +import com.codename1.ui.geom.Rectangle; + +/// An immutable snapshot of a foldable device's fold, expressed relative to one container. +/// +/// Fold-aware layouts such as `com.codename1.ui.layouts.FoldLayout` read the hinge through this +/// class rather than through `DevicePosture` directly, so the same layout can be driven by the live +/// device (`#current(Component)`) or by an explicit state: a preview, a large tablet that wants a +/// "virtual hinge", or a test that runs on a device that does not fold at all. +/// +/// ```java +/// FoldState book = new FoldState(DevicePosture.POSTURE_HALF_OPENED, +/// DevicePosture.FOLD_ORIENTATION_VERTICAL, true, new Rectangle(500, 0, 20, 1200)); +/// if (book.isVerticalSeparation()) { +/// // two panes side by side, one on each side of the hinge +/// } +/// ``` +public final class FoldState { + /// The state of a device with no fold, or a fold that does not separate the screen. + public static final FoldState NONE = new FoldState(DevicePosture.POSTURE_UNKNOWN, + DevicePosture.FOLD_ORIENTATION_NONE, false, null); + + private final int posture; + private final int orientation; + private final boolean separating; + private final int foldX; + private final int foldY; + private final int foldWidth; + private final int foldHeight; + private final boolean hasBounds; + + /// Creates a fold state. + /// + /// #### Parameters + /// + /// - `posture`: one of the `DevicePosture` `POSTURE_*` constants + /// + /// - `orientation`: one of the `DevicePosture` `FOLD_ORIENTATION_*` constants + /// + /// - `separating`: true when the fold splits the screen into two logical areas + /// + /// - `foldBounds`: the hinge bounds relative to the container being laid out, or null. A + /// zero-width (or zero-height) rectangle is a seamless fold line with no occluded area. + public FoldState(int posture, int orientation, boolean separating, Rectangle foldBounds) { + this.posture = posture; + this.orientation = orientation; + this.separating = separating; + if (foldBounds != null) { + hasBounds = true; + foldX = foldBounds.getX(); + foldY = foldBounds.getY(); + foldWidth = foldBounds.getWidth(); + foldHeight = foldBounds.getHeight(); + } else { + hasBounds = false; + foldX = 0; + foldY = 0; + foldWidth = 0; + foldHeight = 0; + } + } + + /// The live fold state of this device, with the hinge translated into the coordinate space of + /// the given component. + /// + /// #### Parameters + /// + /// - `relativeTo`: the component whose coordinate space the hinge bounds use, or null for + /// display coordinates + /// + /// #### Returns + /// + /// the current fold state, `#NONE` on a device that does not fold + public static FoldState current(Component relativeTo) { + DevicePosture dp = DevicePosture.getInstance(); + if (!dp.isFoldable()) { + return NONE; + } + Rectangle r = dp.getFoldBounds(null); + if (r != null && relativeTo != null) { + r = new Rectangle(r.getX() - relativeTo.getAbsoluteX(), r.getY() - relativeTo.getAbsoluteY(), + r.getWidth(), r.getHeight()); + } + return new FoldState(dp.getPosture(), dp.getFoldOrientation(), dp.isSeparating(), r); + } + + /// The posture, one of the `DevicePosture` `POSTURE_*` constants. + /// + /// #### Returns + /// + /// the posture + public int getPosture() { + return posture; + } + + /// The fold orientation, one of the `DevicePosture` `FOLD_ORIENTATION_*` constants. + /// `FOLD_ORIENTATION_VERTICAL` is a book or dual-screen fold, `FOLD_ORIENTATION_HORIZONTAL` a + /// flip or table-top fold. + /// + /// #### Returns + /// + /// the orientation + public int getOrientation() { + return orientation; + } + + /// True when the fold splits the screen into two logical areas. + /// + /// #### Returns + /// + /// true for a separating fold + public boolean isSeparating() { + return separating; + } + + /// True for a separating fold with known bounds and a vertical hinge: content belongs on the + /// left and the right of it. + /// + /// #### Returns + /// + /// true for a vertical separating fold + public boolean isVerticalSeparation() { + return separating && hasBounds && orientation == DevicePosture.FOLD_ORIENTATION_VERTICAL; + } + + /// True for a separating fold with known bounds and a horizontal hinge: content belongs above + /// and below it. + /// + /// #### Returns + /// + /// true for a horizontal separating fold + public boolean isHorizontalSeparation() { + return separating && hasBounds && orientation == DevicePosture.FOLD_ORIENTATION_HORIZONTAL; + } + + /// The hinge bounds in the coordinate space this state was created for. + /// + /// #### Returns + /// + /// a new rectangle, or null when the bounds are unknown + public Rectangle getFoldBounds() { + if (!hasBounds) { + return null; + } + return new Rectangle(foldX, foldY, foldWidth, foldHeight); + } + + /// The left (or top, for a horizontal fold) edge of the hinge. + /// + /// #### Returns + /// + /// the leading coordinate of the hinge along the axis it divides + public int getFoldStart() { + return orientation == DevicePosture.FOLD_ORIENTATION_HORIZONTAL ? foldY : foldX; + } + + /// The right (or bottom, for a horizontal fold) edge of the hinge. + /// + /// #### Returns + /// + /// the trailing coordinate of the hinge along the axis it divides + public int getFoldEnd() { + return orientation == DevicePosture.FOLD_ORIENTATION_HORIZONTAL ? foldY + foldHeight : foldX + foldWidth; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof FoldState)) { + return false; + } + FoldState f = (FoldState) o; + return posture == f.posture && orientation == f.orientation && separating == f.separating + && hasBounds == f.hasBounds && foldX == f.foldX && foldY == f.foldY + && foldWidth == f.foldWidth && foldHeight == f.foldHeight; + } + + @Override + public int hashCode() { + int h = posture; + h = 31 * h + orientation; + h = 31 * h + (separating ? 1 : 0); + h = 31 * h + foldX; + h = 31 * h + foldY; + h = 31 * h + foldWidth; + return 31 * h + foldHeight; + } +} diff --git a/CodenameOne/src/com/codename1/ui/Form.java b/CodenameOne/src/com/codename1/ui/Form.java index 7830454f677..43e64440ff4 100644 --- a/CodenameOne/src/com/codename1/ui/Form.java +++ b/CodenameOne/src/com/codename1/ui/Form.java @@ -228,6 +228,7 @@ HoverTracker getHoverTracker() { private EventDispatcher orientationListener; private EventDispatcher pointerCancelledListener; private EventDispatcher sizeChangedListener; + private ActionListener postureListener; private EventDispatcher pasteListener; private UIManager uiManager; private Component stickyDrag; @@ -1125,6 +1126,64 @@ protected void showNotify() { protected void sizeChanged(int w, int h) { } + /// Invoked on the EDT when the device folds, unfolds or changes posture while this form is + /// showing, before the form lays itself out again. Override it to swap content for the new + /// posture; the relayout that follows is decided by the layouts in the form, see + /// `com.codename1.ui.layouts.Layout#getFoldBehavior()`. + /// + /// #### Parameters + /// + /// - `fold`: the new fold state, relative to this form + protected void onFoldChanged(FoldState fold) { + } + + /// Handles a fold or posture change: calls `#onFoldChanged(FoldState)`, then lays the form + /// out again the way its layouts ask -- animated when any layout in the form answers + /// `Layout#FOLD_ANIMATE` (and reduced motion is off), revalidated when any answers + /// `Layout#FOLD_REVALIDATE`, and left alone when every layout ignores folds. + void foldChangedInternal() { + onFoldChanged(FoldState.current(this)); + int[] behavior = new int[2]; + collectFoldBehavior(getContentPane(), behavior); + if (behavior[0] == Layout.FOLD_ANIMATE && !Display.getInstance().isReduceMotionEnabled()) { + getContentPane().animateLayout(behavior[1]); + } else if (behavior[0] != Layout.FOLD_IGNORE) { + revalidate(); + } + } + + /// Records in `out[0]` the strongest fold behaviour among the layouts under `c` and in + /// `out[1]` the longest animation duration among the layouts that animate. + private static void collectFoldBehavior(Container c, int[] out) { + Layout l = c.getLayout(); + if (l != null) { + int b = l.getFoldBehavior(); + if (b > out[0]) { + out[0] = b; + } + if (b == Layout.FOLD_ANIMATE && l.getFoldAnimationDuration() > out[1]) { + out[1] = l.getFoldAnimationDuration(); + } + } + int count = c.getComponentCount(); + for (int i = 0; i < count; i++) { + Component child = c.getComponentAt(i); + if (child instanceof Container) { + collectFoldBehavior((Container) child, out); + } + } + } + + /// Relays a posture change to the form it belongs to. + private final class PostureListener implements ActionListener { + @Override + public void actionPerformed(ActionEvent evt) { + if (isInitialized()) { + foldChangedInternal(); + } + } + } + /// Causes the display safe area to be recalculated the next time the form list laid out. /// /// #### See also @@ -2932,6 +2991,9 @@ void deinitializeImpl() { // the release goes to the new form, and on a platform whose own recognizer starts the // session the drag begins later still. It would then have carried the hidden form's // payload, and reported its outcome to a component that is no longer anywhere. + if (postureListener != null) { + Display.getInstance().removePostureListener(postureListener); + } NativeDragAndDrop.topLevelInputCancelled(this); super.deinitializeImpl(); animMananger.flush(); @@ -3414,6 +3476,14 @@ void applyDocumentModified(java.util.List commands) { void initComponentImpl() { super.initComponentImpl(); dragged = null; + if (getParent() == null) { + // Only a form that owns the surface follows the device fold; an embedded one is + // laid out by the form that hosts it. + if (postureListener == null) { + postureListener = new PostureListener(); + } + Display.getInstance().addPostureListener(postureListener); + } // Only a form that owns the surface publishes its commands to the platform. // An embedded one -- a Dialog hosted in a window's layered pane, a form inside // an EmbeddedContainer -- would otherwise overwrite the real surface's native diff --git a/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java b/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java new file mode 100644 index 00000000000..b23c22d96ea --- /dev/null +++ b/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java @@ -0,0 +1,215 @@ +/* + * 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.ui.layouts; + +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FoldState; +import com.codename1.ui.geom.Dimension; + +/// Wraps any layout so that its children stay off the hinge of a foldable device. +/// +/// The wrapped layout arranges the container as usual. When there is a separating fold, the +/// container's axis across the hinge is then divided at its middle and each half is mapped onto +/// the screen area on its own side of the hinge: a child wholly on one side is scaled into that +/// side, and a child straddling the middle goes to the side holding its center and stops at the +/// hinge. Content whose columns (or rows) divide evenly at the middle, such as a +/// `GridLayout` with an even number of columns, therefore splits cleanly into the two halves of a +/// book foldable or a half-opened flip phone, with nothing drawn under the crease. +/// +/// Its `#getFoldBehavior()` is `#FOLD_ANIMATE`, so the form animates the content into place when +/// the device folds or unfolds. +/// +/// ```java +/// Container gallery = new Container(new FoldAvoidingLayout(new GridLayout(3, 2))); +/// ``` +public class FoldAvoidingLayout extends Layout { + private final Layout delegate; + private int foldBehavior = FOLD_ANIMATE; + private int foldAnimationDuration = 300; + + /// Wraps a layout. + /// + /// #### Parameters + /// + /// - `delegate`: the layout that arranges the children + public FoldAvoidingLayout(Layout delegate) { + this.delegate = delegate; + } + + /// The wrapped layout. + /// + /// #### Returns + /// + /// the layout that arranges the children + public Layout getDelegate() { + return delegate; + } + + /// Sets how the form responds to a fold change, see `Layout#getFoldBehavior()`. + /// + /// #### Parameters + /// + /// - `foldBehavior`: `#FOLD_IGNORE`, `#FOLD_REVALIDATE` or `#FOLD_ANIMATE` + public void setFoldBehavior(int foldBehavior) { + this.foldBehavior = foldBehavior; + } + + @Override + public int getFoldBehavior() { + return foldBehavior; + } + + /// Sets the duration of the fold animation. + /// + /// #### Parameters + /// + /// - `foldAnimationDuration`: the duration in milliseconds + public void setFoldAnimationDuration(int foldAnimationDuration) { + this.foldAnimationDuration = foldAnimationDuration; + } + + @Override + public int getFoldAnimationDuration() { + return foldAnimationDuration; + } + + @Override + public void layoutContainer(Container parent) { + delegate.layoutContainer(parent); + FoldState fold = getFoldState(parent); + boolean vertical = fold.isVerticalSeparation(); + if (!vertical && !fold.isHorizontalSeparation()) { + return; + } + int size = vertical ? parent.getWidth() : parent.getHeight(); + int fs = Math.max(0, Math.min(size, fold.getFoldStart())); + int fe = Math.max(fs, Math.min(size, fold.getFoldEnd())); + int mid = size / 2; + if (mid <= 0 || mid >= size) { + return; + } + int count = parent.getComponentCount(); + for (int i = 0; i < count; i++) { + Component c = parent.getComponentAt(i); + int start = vertical ? c.getX() : c.getY(); + int end = start + (vertical ? c.getWidth() : c.getHeight()); + int newStart; + int newEnd; + if (start + end <= 2 * mid) { + newStart = mapLow(start, mid, fs); + newEnd = Math.min(mapLow(end, mid, fs), fs); + } else { + newStart = Math.max(mapHigh(start, mid, fe, size), fe); + newEnd = mapHigh(end, mid, fe, size); + } + int len = Math.max(0, newEnd - newStart); + if (vertical) { + c.setX(newStart); + c.setWidth(len); + } else { + c.setY(newStart); + c.setHeight(len); + } + } + } + + private static int mapLow(int v, int mid, int foldStart) { + if (v >= mid) { + return foldStart; + } + return (int) ((long) v * foldStart / mid); + } + + private static int mapHigh(int v, int mid, int foldEnd, int size) { + if (v <= mid) { + return foldEnd; + } + return foldEnd + (int) ((long) (v - mid) * (size - foldEnd) / (size - mid)); + } + + @Override + public Dimension getPreferredSize(Container parent) { + Dimension d = delegate.getPreferredSize(parent); + FoldState fold = getFoldState(parent); + int hinge = Math.max(0, fold.getFoldEnd() - fold.getFoldStart()); + if (fold.isVerticalSeparation()) { + return new Dimension(d.getWidth() + hinge, d.getHeight()); + } + if (fold.isHorizontalSeparation()) { + return new Dimension(d.getWidth(), d.getHeight() + hinge); + } + return d; + } + + @Override + public void addLayoutComponent(Object value, Component comp, Container c) { + delegate.addLayoutComponent(value, comp, c); + } + + @Override + public void removeLayoutComponent(Component comp) { + delegate.removeLayoutComponent(comp); + } + + @Override + public Object getComponentConstraint(Component comp) { + return delegate.getComponentConstraint(comp); + } + + @Override + public Object cloneConstraint(Object constraint) { + return delegate.cloneConstraint(constraint); + } + + @Override + public boolean isConstraintTracking() { + return delegate.isConstraintTracking(); + } + + @Override + public boolean isOverlapSupported() { + return delegate.isOverlapSupported(); + } + + @Override + public boolean obscuresPotential(Container parent) { + return delegate.obscuresPotential(parent); + } + + @Override + public boolean equals(Object o) { + return super.equals(o) && delegate.equals(((FoldAvoidingLayout) o).delegate) + && foldBehavior == ((FoldAvoidingLayout) o).foldBehavior; + } + + @Override + public int hashCode() { + return delegate.hashCode() * 31 + foldBehavior; + } + + @Override + public String toString() { + return "FoldAvoidingLayout(" + delegate + ")"; + } +} diff --git a/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java b/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java new file mode 100644 index 00000000000..fcbfd8ff471 --- /dev/null +++ b/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java @@ -0,0 +1,351 @@ +/* + * 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.ui.layouts; + +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FoldState; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.plaf.Style; + +/// A two-pane layout that follows the fold of a foldable device. +/// +/// Add one component with `#PRIMARY` and optionally one with `#SECONDARY`: +/// +/// - **Vertical separating fold** (a book-style foldable, or a dual-screen device): the panes sit +/// side by side, each exactly on its own side of the hinge, and the hinge itself stays empty. +/// The primary pane is on the leading side (the right in RTL). +/// - **Horizontal separating fold** (a flip phone half opened, or a book foldable in table-top +/// posture): the primary pane is above the hinge and the secondary below it. +/// - **No separating fold**: the fallback chosen with `#setFallback(int)` applies -- the primary +/// pane alone (`#FALLBACK_PRIMARY_ONLY`, the default, the secondary pane collapses to zero width +/// at the trailing edge), the two stacked (`#FALLBACK_STACK`), or split side by side +/// (`#FALLBACK_SPLIT`, as on a large unfolded screen). +/// +/// The layout's `#getFoldBehavior()` is `#FOLD_ANIMATE`, so the form animates the panes into place +/// whenever the device folds, unfolds or changes posture. +/// +/// ```java +/// Form f = new Form("Mail", new FoldLayout()); +/// f.add(FoldLayout.PRIMARY, inboxList); +/// f.add(FoldLayout.SECONDARY, messageView); +/// f.show(); +/// ``` +public class FoldLayout extends Layout { + /// Constraint of the primary pane, the one that is always visible. + public static final String PRIMARY = "Primary"; + + /// Constraint of the secondary pane, shown when there is room for it. + public static final String SECONDARY = "Secondary"; + + /// Without a separating fold, show only the primary pane. + public static final int FALLBACK_PRIMARY_ONLY = 0; + + /// Without a separating fold, stack the primary pane above the secondary. + public static final int FALLBACK_STACK = 1; + + /// Without a separating fold, place the panes side by side, split by `#setSplitRatio(float)`. + public static final int FALLBACK_SPLIT = 2; + + private Component primary; + private Component secondary; + private int fallback; + private float splitRatio = 0.5f; + private int foldBehavior = FOLD_ANIMATE; + private int foldAnimationDuration = 300; + + /// Creates a fold layout that shows only the primary pane when there is no separating fold. + public FoldLayout() { + this(FALLBACK_PRIMARY_ONLY); + } + + /// Creates a fold layout. + /// + /// #### Parameters + /// + /// - `fallback`: `#FALLBACK_PRIMARY_ONLY`, `#FALLBACK_STACK` or `#FALLBACK_SPLIT` + public FoldLayout(int fallback) { + this.fallback = fallback; + } + + /// The arrangement used when there is no separating fold. + /// + /// #### Returns + /// + /// `#FALLBACK_PRIMARY_ONLY`, `#FALLBACK_STACK` or `#FALLBACK_SPLIT` + public int getFallback() { + return fallback; + } + + /// Sets the arrangement used when there is no separating fold. + /// + /// #### Parameters + /// + /// - `fallback`: `#FALLBACK_PRIMARY_ONLY`, `#FALLBACK_STACK` or `#FALLBACK_SPLIT` + public void setFallback(int fallback) { + this.fallback = fallback; + } + + /// The share of the width the primary pane takes under `#FALLBACK_SPLIT`. + /// + /// #### Returns + /// + /// a value between 0 and 1, 0.5 by default + public float getSplitRatio() { + return splitRatio; + } + + /// Sets the share of the width the primary pane takes under `#FALLBACK_SPLIT`. + /// + /// #### Parameters + /// + /// - `splitRatio`: a value between 0 and 1 + public void setSplitRatio(float splitRatio) { + this.splitRatio = Math.max(0f, Math.min(1f, splitRatio)); + } + + /// Sets how the form responds to a fold change, see `Layout#getFoldBehavior()`. + /// + /// #### Parameters + /// + /// - `foldBehavior`: `#FOLD_IGNORE`, `#FOLD_REVALIDATE` or `#FOLD_ANIMATE` + public void setFoldBehavior(int foldBehavior) { + this.foldBehavior = foldBehavior; + } + + @Override + public int getFoldBehavior() { + return foldBehavior; + } + + /// Sets the duration of the fold animation. + /// + /// #### Parameters + /// + /// - `foldAnimationDuration`: the duration in milliseconds + public void setFoldAnimationDuration(int foldAnimationDuration) { + this.foldAnimationDuration = foldAnimationDuration; + } + + @Override + public int getFoldAnimationDuration() { + return foldAnimationDuration; + } + + @Override + public void addLayoutComponent(Object value, Component comp, Container c) { + if (SECONDARY.equals(value)) { + if (secondary != null && secondary != comp) { //NOPMD CompareObjectsWithEquals + c.removeComponent(secondary); + } + secondary = comp; + } else { + if (primary != null && primary != comp) { //NOPMD CompareObjectsWithEquals + c.removeComponent(primary); + } + primary = comp; + } + } + + @Override + public void removeLayoutComponent(Component comp) { + if (comp == primary) { //NOPMD CompareObjectsWithEquals + primary = null; + } else if (comp == secondary) { //NOPMD CompareObjectsWithEquals + secondary = null; + } + } + + @Override + public Object getComponentConstraint(Component comp) { + if (comp == primary) { //NOPMD CompareObjectsWithEquals + return PRIMARY; + } + if (comp == secondary) { //NOPMD CompareObjectsWithEquals + return SECONDARY; + } + return null; + } + + @Override + public boolean isConstraintTracking() { + return true; + } + + /// The primary pane. + /// + /// #### Returns + /// + /// the primary component or null + public Component getPrimary() { + return primary; + } + + /// The secondary pane. + /// + /// #### Returns + /// + /// the secondary component or null + public Component getSecondary() { + return secondary; + } + + @Override + public void layoutContainer(Container parent) { + Style s = parent.getStyle(); + boolean rtl = parent.isRTL(); + int top = s.getPaddingTop(); + int bottom = parent.getLayoutHeight() - parent.getBottomGap() - s.getPaddingBottom(); + int left = s.getPaddingLeft(rtl); + int right = parent.getLayoutWidth() - parent.getSideGap() - s.getPaddingRight(rtl); + FoldState fold = getFoldState(parent); + if (fold.isVerticalSeparation()) { + int fs = clamp(fold.getFoldStart(), left, right); + int fe = clamp(fold.getFoldEnd(), fs, right); + placeSideBySide(left, fs, fe, right, top, bottom, rtl); + } else if (fold.isHorizontalSeparation()) { + int fs = clamp(fold.getFoldStart(), top, bottom); + int fe = clamp(fold.getFoldEnd(), fs, bottom); + place(primary, left, top, right, fs); + place(secondary, left, fe, right, bottom); + } else if (secondary == null || fallback == FALLBACK_PRIMARY_ONLY) { + place(primary, left, top, right, bottom); + if (secondary != null) { + // Collapsed at the trailing edge, so an unfold animates it in from that side. + int edge = rtl ? left : right; + place(secondary, edge, top, edge, bottom); + } + } else if (fallback == FALLBACK_STACK) { + int ph = primary == null ? 0 : primary.getPreferredH() + + primary.getStyle().getVerticalMargins(); + int split = clamp(top + ph, top, bottom); + place(primary, left, top, right, split); + place(secondary, left, split, right, bottom); + } else { + int split = left + (int) ((right - left) * splitRatio); + placeSideBySide(left, split, split, right, top, bottom, rtl); + } + } + + private void placeSideBySide(int left, int foldStart, int foldEnd, int right, int top, int bottom, + boolean rtl) { + if (rtl) { + place(secondary, left, top, foldStart, bottom); + place(primary, foldEnd, top, right, bottom); + } else { + place(primary, left, top, foldStart, bottom); + place(secondary, foldEnd, top, right, bottom); + } + } + + private static int clamp(int v, int min, int max) { + if (v < min) { + return min; + } + return v > max ? max : v; + } + + private static void place(Component c, int x1, int y1, int x2, int y2) { + if (c == null) { + return; + } + Style st = c.getStyle(); + int ml = st.getMarginLeftNoRTL(); + int mr = st.getMarginRightNoRTL(); + int mt = st.getMarginTop(); + int mb = st.getMarginBottom(); + int w = x2 - x1; + int h = y2 - y1; + if (w <= ml + mr) { + c.setX(x1); + c.setWidth(0); + } else { + c.setX(x1 + ml); + c.setWidth(w - ml - mr); + } + if (h <= mt + mb) { + c.setY(y1); + c.setHeight(0); + } else { + c.setY(y1 + mt); + c.setHeight(h - mt - mb); + } + } + + @Override + public Dimension getPreferredSize(Container parent) { + int pw = 0; + int ph = 0; + int sw = 0; + int sh = 0; + if (primary != null) { + pw = primary.getPreferredW() + primary.getStyle().getHorizontalMargins(); + ph = primary.getPreferredH() + primary.getStyle().getVerticalMargins(); + } + if (secondary != null) { + sw = secondary.getPreferredW() + secondary.getStyle().getHorizontalMargins(); + sh = secondary.getPreferredH() + secondary.getStyle().getVerticalMargins(); + } + FoldState fold = getFoldState(parent); + int w; + int h; + if (fold.isVerticalSeparation()) { + w = pw + sw + Math.max(0, fold.getFoldEnd() - fold.getFoldStart()); + h = Math.max(ph, sh); + } else if (fold.isHorizontalSeparation()) { + w = Math.max(pw, sw); + h = ph + sh + Math.max(0, fold.getFoldEnd() - fold.getFoldStart()); + } else if (secondary == null || fallback == FALLBACK_PRIMARY_ONLY) { + w = pw; + h = ph; + } else if (fallback == FALLBACK_STACK) { + w = Math.max(pw, sw); + h = ph + sh; + } else { + w = pw + sw; + h = Math.max(ph, sh); + } + Style s = parent.getStyle(); + return new Dimension(w + s.getHorizontalPadding(), h + s.getVerticalPadding()); + } + + @Override + public boolean equals(Object o) { + if (!super.equals(o)) { + return false; + } + FoldLayout f = (FoldLayout) o; + return fallback == f.fallback && splitRatio == f.splitRatio + && foldBehavior == f.foldBehavior; + } + + @Override + public int hashCode() { + return (super.hashCode() * 31 + fallback) * 31 + foldBehavior; + } + + @Override + public String toString() { + return "FoldLayout"; + } +} diff --git a/CodenameOne/src/com/codename1/ui/layouts/Layout.java b/CodenameOne/src/com/codename1/ui/layouts/Layout.java index 9abbfff6572..d735845ffa2 100644 --- a/CodenameOne/src/com/codename1/ui/layouts/Layout.java +++ b/CodenameOne/src/com/codename1/ui/layouts/Layout.java @@ -25,6 +25,7 @@ import com.codename1.ui.Component; import com.codename1.ui.Container; +import com.codename1.ui.FoldState; import com.codename1.ui.geom.Dimension; @@ -32,6 +33,71 @@ /// a predefined algorithm. This class may be implemented externally and is similar /// in spirit to the AWT/Swing layout managers. public abstract class Layout { + /// `#getFoldBehavior()` value: a fold or posture change does not affect this layout. The + /// default for every layout that does not know about folds. + public static final int FOLD_IGNORE = 0; + + /// `#getFoldBehavior()` value: when the device folds, unfolds or changes posture the form + /// revalidates, laying this container out again in one step. + public static final int FOLD_REVALIDATE = 1; + + /// `#getFoldBehavior()` value: when the device folds, unfolds or changes posture the form + /// animates its components from their old positions to the new layout, over + /// `#getFoldAnimationDuration()` milliseconds. + public static final int FOLD_ANIMATE = 2; + + private FoldState foldState; + + /// How the current `com.codename1.ui.Form` responds to a fold or posture change when a + /// container uses this layout. A form honours the strongest behaviour among its containers: + /// one `#FOLD_ANIMATE` layout animates the whole form, otherwise one `#FOLD_REVALIDATE` + /// revalidates it, and a form made only of `#FOLD_IGNORE` layouts is left alone. + /// + /// #### Returns + /// + /// `#FOLD_IGNORE`, `#FOLD_REVALIDATE` or `#FOLD_ANIMATE`; `#FOLD_IGNORE` by default + public int getFoldBehavior() { + return FOLD_IGNORE; + } + + /// The duration of the relayout animation used when `#getFoldBehavior()` is `#FOLD_ANIMATE`. + /// + /// #### Returns + /// + /// the duration in milliseconds, 300 by default + public int getFoldAnimationDuration() { + return 300; + } + + /// Fixes the fold this layout lays out against, instead of the live device fold. Useful for a + /// preview, for a large screen that wants a "virtual hinge", and for tests on a device that + /// does not fold. + /// + /// #### Parameters + /// + /// - `foldState`: the fold to use, in the coordinate space of the container being laid out, or + /// null to follow the device + public void setFoldState(FoldState foldState) { + this.foldState = foldState; + } + + /// The fold this layout lays the given container out against: the state passed to + /// `#setFoldState(FoldState)` if there is one, otherwise the live device fold relative to the + /// container. + /// + /// #### Parameters + /// + /// - `parent`: the container being laid out + /// + /// #### Returns + /// + /// the fold state, never null + public FoldState getFoldState(Container parent) { + if (foldState != null) { + return foldState; + } + return FoldState.current(parent); + } /// Utility method /// diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava007Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava007Snippet.java new file mode 100644 index 00000000000..34c8701c54c --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava007Snippet.java @@ -0,0 +1,96 @@ +/* + * 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.codenameone.developerguide.snippets.generated; + +import com.codename1.gpu.*; +import com.codename1.ui.*; +import com.codename1.ui.animations.*; +import com.codename1.ui.events.*; +import com.codename1.ui.geom.*; +import com.codename1.ui.layouts.*; +import com.codename1.ui.list.*; +import com.codename1.ui.plaf.*; +import com.codename1.ui.util.*; +import com.codename1.components.*; +import com.codename1.charts.models.*; +import com.codename1.charts.renderers.*; +import com.codename1.charts.views.*; +import com.codename1.capture.*; +import com.codename1.io.*; +import com.codename1.l10n.*; +import com.codename1.location.*; +import com.codename1.maps.*; +import com.codename1.media.*; +import com.codename1.messaging.*; +import com.codename1.payment.*; +import com.codename1.processing.*; +import com.codename1.properties.*; +import com.codename1.push.*; +import com.codename1.security.*; +import com.codename1.social.*; +import com.codename1.ui.spinner.*; +import java.io.*; +import com.codename1.sensors.*; +import java.util.*; + + +class DeviceInputAndFormFactorsJava007Snippet { + + + Object context; + Object url; + Object value; + Object body; + Object event; + String apiKey = "test-key"; + String myHttpsURL = "https://example.com"; + java.util.List validKeysList = new java.util.ArrayList<>(); + Image myImage; + Graphics graphics; + Graphics g; + GraphicsDevice device; + Form form; + Form hi; + Container cnt; + Container myForm; + Component component; + Button button; + MultiButton myMultiButton; + Label label; + BrowserComponent browserComponent; + Resources theme; + + // tag::device-input-and-form-factors-java-007[] + void showMail(Container inbox, Container message) { + // List on its own when the device is closed; list | message across the hinge of a + // book foldable; list above, message below, in table-top posture. + Form mail = new Form("Mail", new FoldLayout(FoldLayout.FALLBACK_PRIMARY_ONLY)); + mail.add(FoldLayout.PRIMARY, inbox); + mail.add(FoldLayout.SECONDARY, message); + mail.show(); + } + // end::device-input-and-form-factors-java-007[] + + +} diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava008Snippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava008Snippet.java new file mode 100644 index 00000000000..7573f28dac9 --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava008Snippet.java @@ -0,0 +1,99 @@ +/* + * 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.codenameone.developerguide.snippets.generated; + +import com.codename1.gpu.*; +import com.codename1.ui.*; +import com.codename1.ui.animations.*; +import com.codename1.ui.events.*; +import com.codename1.ui.geom.*; +import com.codename1.ui.layouts.*; +import com.codename1.ui.list.*; +import com.codename1.ui.plaf.*; +import com.codename1.ui.util.*; +import com.codename1.components.*; +import com.codename1.charts.models.*; +import com.codename1.charts.renderers.*; +import com.codename1.charts.views.*; +import com.codename1.capture.*; +import com.codename1.io.*; +import com.codename1.l10n.*; +import com.codename1.location.*; +import com.codename1.maps.*; +import com.codename1.media.*; +import com.codename1.messaging.*; +import com.codename1.payment.*; +import com.codename1.processing.*; +import com.codename1.properties.*; +import com.codename1.push.*; +import com.codename1.security.*; +import com.codename1.social.*; +import com.codename1.ui.spinner.*; +import java.io.*; +import com.codename1.sensors.*; +import java.util.*; + + +class DeviceInputAndFormFactorsJava008Snippet { + + + Object context; + Object url; + Object value; + Object body; + Object event; + String apiKey = "test-key"; + String myHttpsURL = "https://example.com"; + java.util.List validKeysList = new java.util.ArrayList<>(); + Image myImage; + Graphics graphics; + Graphics g; + GraphicsDevice device; + Form form; + Form hi; + Container cnt; + Container myForm; + Component component; + Button button; + MultiButton myMultiButton; + Label label; + BrowserComponent browserComponent; + Resources theme; + + // tag::device-input-and-form-factors-java-008[] + class GalleryForm extends Form { + GalleryForm() { + super("Gallery", new FoldAvoidingLayout(new GridLayout(3, 2))); + } + + @Override + protected void onFoldChanged(FoldState fold) { + // Runs before the form animates into the new layout + setTitle(fold.isSeparating() ? "Gallery (unfolded)" : "Gallery"); + } + } + // end::device-input-and-form-factors-java-008[] + + +} diff --git a/docs/developer-guide/Device-Input-And-Form-Factors.asciidoc b/docs/developer-guide/Device-Input-And-Form-Factors.asciidoc index 7c951bb7c4c..0a87c0a2bb9 100644 --- a/docs/developer-guide/Device-Input-And-Form-Factors.asciidoc +++ b/docs/developer-guide/Device-Input-And-Form-Factors.asciidoc @@ -150,6 +150,49 @@ React to fold changes with a posture listener: include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava006Snippet.java[tag=device-input-and-form-factors-java-006,indent=0] ---- +==== Fold-aware layouts + +Most screens don't need a listener at all. A form follows the fold by itself: when the device +folds, unfolds or changes posture it asks the layouts it contains how to respond, through +`Layout.getFoldBehavior()`: + +* `FOLD_IGNORE` - the default for every existing layout; nothing happens, as before. +* `FOLD_REVALIDATE` - the form lays itself out again in one step. +* `FOLD_ANIMATE` - the form animates its components from where they were to the new layout. + With reduced motion turned on in the system settings the form revalidates instead. + +The strongest answer in the form wins, so one fold-aware container is enough to animate the screen. +Two layouts answer `FOLD_ANIMATE` out of the box. + +`FoldLayout` holds a `PRIMARY` and a `SECONDARY` pane. Across a vertical hinge (a book foldable or +a dual screen device) it puts one pane on each side, leaving the hinge empty. Across a horizontal +hinge (a flip phone half opened, or table-top posture) the primary pane goes above the hinge and the +secondary below. With no separating fold the fallback you choose applies: the primary pane alone +(`FALLBACK_PRIMARY_ONLY`, where the secondary collapses at the trailing edge and slides in when the +device opens), the panes stacked (`FALLBACK_STACK`), or side by side (`FALLBACK_SPLIT`): + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava007Snippet.java[tag=device-input-and-form-factors-java-007,indent=0] +---- + +`FoldAvoidingLayout` wraps any layout you already have. The wrapped layout arranges the container +as usual, then each half of the container is fitted to the screen area on its own side of the +hinge, so nothing is drawn under the crease. A grid with an even number of columns (or rows, for a +horizontal hinge) splits cleanly into the two halves. Override `Form.onFoldChanged(FoldState)` to +change content for the new posture; it runs before the form lays itself out again: + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/generated/DeviceInputAndFormFactorsJava008Snippet.java[tag=device-input-and-form-factors-java-008,indent=0] +---- + +A layout reads the hinge through `FoldState`, a snapshot of the fold relative to the container +being laid out. `Layout.setFoldState(FoldState)` fixes the fold a layout uses instead of the live +device: a preview of the unfolded screen, or a large tablet that should split its content as if it +had a hinge. Your own layout can do the same as these two: answer `FOLD_ANIMATE` from +`getFoldBehavior()` and read `getFoldState(parent)` in `layoutContainer`. + To exercise this in the desktop simulator, use the *Simulate -> Foldable* menu: enable foldable mode, then pick a posture (flat, half-opened or closed), the fold orientation (vertical or horizontal) and the hinge angle. The running app receives the same posture changes and listener diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java new file mode 100644 index 00000000000..a3a3eaa657f --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java @@ -0,0 +1,118 @@ +/* + * 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.ui; + +import com.codename1.junit.FormTest; +import com.codename1.junit.UITestBase; +import com.codename1.ui.geom.Rectangle; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.FoldLayout; +import com.codename1.ui.layouts.Layout; + +import static org.junit.jupiter.api.Assertions.*; + +class FormFoldBehaviorTest extends UITestBase { + private static final FoldState BOOK = new FoldState(DevicePosture.POSTURE_HALF_OPENED, + DevicePosture.FOLD_ORIENTATION_VERTICAL, true, new Rectangle(100, 0, 20, 2000)); + + private static final class CountingForm extends Form { + int foldCalls; + + CountingForm(Layout l) { + super("Fold", l); + } + + @Override + protected void onFoldChanged(FoldState fold) { + foldCalls++; + } + } + + private static CountingForm showFoldForm(FoldLayout fl, Label p, Label s) { + CountingForm f = new CountingForm(fl); + fl.setFoldState(FoldState.NONE); + f.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); + f.show(); + DisplayTest.flushEdt(); + return f; + } + + private static void firePosture() { + Display.getInstance().postureChanged(); + for (int i = 0; i < 5; i++) { + DisplayTest.flushEdt(); + } + } + + @FormTest + void revalidatingLayoutRelaysOutImmediately() { + FoldLayout fl = new FoldLayout(); + fl.setFoldBehavior(Layout.FOLD_REVALIDATE); + Label p = new Label("p"); + Label s = new Label("s"); + CountingForm f = showFoldForm(fl, p, s); + assertEquals(0, s.getWidth()); + fl.setFoldState(BOOK); + firePosture(); + assertEquals(1, f.foldCalls); + assertTrue(s.getWidth() > 0, "secondary pane should be laid out next to the hinge"); + assertTrue(s.getX() >= 120); + } + + @FormTest + void animatingLayoutStartsAnAnimation() { + FoldLayout fl = new FoldLayout(); + Label p = new Label("p"); + Label s = new Label("s"); + CountingForm f = showFoldForm(fl, p, s); + fl.setFoldState(BOOK); + f.foldChangedInternal(); + assertEquals(1, f.foldCalls); + assertTrue(f.getAnimationManager().isAnimating(), "a fold-aware layout animates into place"); + } + + @FormTest + void ignoringLayoutsLeaveTheFormAlone() { + CountingForm f = new CountingForm(new BorderLayout()); + Label l = new Label("x"); + f.add(BorderLayout.CENTER, l); + f.show(); + DisplayTest.flushEdt(); + int w = l.getWidth(); + f.foldChangedInternal(); + assertEquals(1, f.foldCalls); + assertFalse(f.getAnimationManager().isAnimating()); + assertEquals(w, l.getWidth()); + } + + @FormTest + void aFormThatIsNoLongerShowingStopsListening() { + FoldLayout fl = new FoldLayout(); + CountingForm first = showFoldForm(fl, new Label("p"), new Label("s")); + Form second = new Form("Other", new BorderLayout()); + second.show(); + DisplayTest.flushEdt(); + firePosture(); + assertEquals(0, first.foldCalls); + } +} diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java new file mode 100644 index 00000000000..f60e2502cb0 --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java @@ -0,0 +1,208 @@ +/* + * 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.ui.layouts; + +import com.codename1.junit.FormTest; +import com.codename1.junit.UITestBase; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.DevicePosture; +import com.codename1.ui.FoldState; +import com.codename1.ui.Label; +import com.codename1.ui.geom.Rectangle; + +import static org.junit.jupiter.api.Assertions.*; + +class FoldLayoutTest extends UITestBase { + static final FoldState BOOK = new FoldState(DevicePosture.POSTURE_HALF_OPENED, + DevicePosture.FOLD_ORIENTATION_VERTICAL, true, new Rectangle(190, 0, 20, 300)); + static final FoldState TABLE_TOP = new FoldState(DevicePosture.POSTURE_HALF_OPENED, + DevicePosture.FOLD_ORIENTATION_HORIZONTAL, true, new Rectangle(0, 140, 400, 20)); + + static Label pane(String name) { + Label l = new Label(name); + l.getAllStyles().setMargin(0, 0, 0, 0); + l.getAllStyles().setPadding(0, 0, 0, 0); + return l; + } + + static Container host(Layout layout) { + Container c = new Container(layout); + c.getAllStyles().setPadding(0, 0, 0, 0); + c.getAllStyles().setMargin(0, 0, 0, 0); + c.setWidth(400); + c.setHeight(300); + return c; + } + + private static void assertBounds(Component c, int x, int y, int w, int h) { + assertEquals(x, c.getX(), "x"); + assertEquals(y, c.getY(), "y"); + assertEquals(w, c.getWidth(), "width"); + assertEquals(h, c.getHeight(), "height"); + } + + @FormTest + void verticalFoldPutsOnePaneOnEachSideOfTheHinge() { + FoldLayout fl = new FoldLayout(); + fl.setFoldState(BOOK); + Container c = host(fl); + Label p = pane("p"); + Label s = pane("s"); + c.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); + c.layoutContainer(); + assertBounds(p, 0, 0, 190, 300); + assertBounds(s, 210, 0, 190, 300); + } + + @FormTest + void horizontalFoldPutsPrimaryAboveTheHinge() { + FoldLayout fl = new FoldLayout(); + fl.setFoldState(TABLE_TOP); + Container c = host(fl); + Label p = pane("p"); + Label s = pane("s"); + c.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); + c.layoutContainer(); + assertBounds(p, 0, 0, 400, 140); + assertBounds(s, 0, 160, 400, 140); + } + + @FormTest + void withoutAFoldThePrimaryPaneFillsAndTheSecondaryCollapses() { + FoldLayout fl = new FoldLayout(); + fl.setFoldState(FoldState.NONE); + Container c = host(fl); + Label p = pane("p"); + Label s = pane("s"); + c.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); + c.layoutContainer(); + assertBounds(p, 0, 0, 400, 300); + assertEquals(400, s.getX()); + assertEquals(0, s.getWidth()); + } + + @FormTest + void splitFallbackDividesByTheRatio() { + FoldLayout fl = new FoldLayout(FoldLayout.FALLBACK_SPLIT); + fl.setSplitRatio(0.25f); + fl.setFoldState(FoldState.NONE); + Container c = host(fl); + Label p = pane("p"); + Label s = pane("s"); + c.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); + c.layoutContainer(); + assertBounds(p, 0, 0, 100, 300); + assertBounds(s, 100, 0, 300, 300); + } + + @FormTest + void stackFallbackGivesPrimaryItsPreferredHeight() { + FoldLayout fl = new FoldLayout(FoldLayout.FALLBACK_STACK); + fl.setFoldState(FoldState.NONE); + Container c = host(fl); + Label p = pane("p"); + Label s = pane("s"); + c.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); + c.layoutContainer(); + int ph = p.getPreferredH(); + assertBounds(p, 0, 0, 400, ph); + assertBounds(s, 0, ph, 400, 300 - ph); + } + + @FormTest + void addingASecondPrimaryReplacesTheFirst() { + FoldLayout fl = new FoldLayout(); + Container c = host(fl); + Label first = pane("a"); + Label second = pane("b"); + c.add(FoldLayout.PRIMARY, first); + c.add(FoldLayout.PRIMARY, second); + assertSame(second, fl.getPrimary()); + assertNull(first.getParent()); + assertEquals(FoldLayout.PRIMARY, fl.getComponentConstraint(second)); + } + + @FormTest + void foldLayoutsAnimateByDefaultAndPlainLayoutsIgnoreFolds() { + assertEquals(Layout.FOLD_ANIMATE, new FoldLayout().getFoldBehavior()); + assertEquals(Layout.FOLD_ANIMATE, new FoldAvoidingLayout(new FlowLayout()).getFoldBehavior()); + assertEquals(Layout.FOLD_IGNORE, new BorderLayout().getFoldBehavior()); + assertEquals(Layout.FOLD_IGNORE, BoxLayout.y().getFoldBehavior()); + } + + @FormTest + void avoidingLayoutSplitsAnEvenGridAroundAVerticalHinge() { + FoldAvoidingLayout l = new FoldAvoidingLayout(new GridLayout(1, 2)); + l.setFoldState(BOOK); + Container c = host(l); + Label a = pane("a"); + Label b = pane("b"); + c.add(a).add(b); + c.layoutContainer(); + assertBounds(a, 0, 0, 190, 300); + assertBounds(b, 210, 0, 190, 300); + } + + @FormTest + void avoidingLayoutSplitsRowsAroundAHorizontalHinge() { + FoldAvoidingLayout l = new FoldAvoidingLayout(new GridLayout(2, 1)); + l.setFoldState(TABLE_TOP); + Container c = host(l); + Label a = pane("a"); + Label b = pane("b"); + c.add(a).add(b); + c.layoutContainer(); + assertBounds(a, 0, 0, 400, 140); + assertBounds(b, 0, 160, 400, 140); + } + + @FormTest + void avoidingLayoutNeverLeavesAChildUnderTheHinge() { + FoldAvoidingLayout l = new FoldAvoidingLayout(new GridLayout(2, 3)); + l.setFoldState(BOOK); + Container c = host(l); + for (int i = 0; i < 6; i++) { + c.add(pane("t" + i)); + } + c.layoutContainer(); + for (int i = 0; i < 6; i++) { + Component t = c.getComponentAt(i); + boolean clear = t.getX() + t.getWidth() <= 190 || t.getX() >= 210; + assertTrue(clear, "tile " + i + " at " + t.getX() + "+" + t.getWidth() + " overlaps the hinge"); + } + } + + @FormTest + void avoidingLayoutLeavesTheDelegateAloneWithoutAFold() { + FoldAvoidingLayout l = new FoldAvoidingLayout(new GridLayout(1, 2)); + l.setFoldState(FoldState.NONE); + Container c = host(l); + Label a = pane("a"); + Label b = pane("b"); + c.add(a).add(b); + c.layoutContainer(); + assertBounds(a, 0, 0, 200, 300); + assertBounds(b, 200, 0, 200, 300); + } +} diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/AbstractFoldAnimationScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/AbstractFoldAnimationScreenshotTest.java new file mode 100644 index 00000000000..918591d6969 --- /dev/null +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/AbstractFoldAnimationScreenshotTest.java @@ -0,0 +1,115 @@ +package com.codenameone.examples.hellocodenameone.tests; + +import com.codename1.ui.Container; +import com.codename1.ui.DevicePosture; +import com.codename1.ui.FoldState; +import com.codename1.ui.Graphics; +import com.codename1.ui.Label; +import com.codename1.ui.animations.ComponentAnimation; +import com.codename1.ui.geom.Rectangle; +import com.codename1.ui.layouts.Layout; +import com.codename1.ui.plaf.Style; + +/// Films a fold-aware layout adapting as a foldable device opens or folds. +/// +/// The container starts laid out with no separating fold; the layout is then handed the fold +/// (a vertical hinge for a book or dual-screen device, a horizontal one for a flip phone or table +/// top posture) and animated into place with `createAnimateLayout` -- exactly what a `Form` does +/// when `Display.postureChanged()` reports the fold, see `Form.onFoldChanged`. Driving the +/// layout with an explicit `FoldState` keeps the film identical on every port, none of which +/// runs on a foldable device in CI. +/// +/// The hinge is drawn over each frame as a dark band that fades in with the animation, so the +/// strip reads as the screen creasing while the content moves off the crease. +public abstract class AbstractFoldAnimationScreenshotTest extends AbstractContainerAnimationScreenshotTest { + protected static final int[] PALETTE = {0xef476f, 0xffd166, 0x06d6a0, 0x118ab2, 0x073b4c, 0x8338ec}; + + private Container foldContainer; + private Rectangle hinge; + + /// The fold-aware layout under test. + protected abstract Layout createFoldLayout(); + + /// Adds the content to the container that uses `createFoldLayout()`. + protected abstract void populate(Container c); + + /// True to fold along a vertical hinge (book / dual screen), false for a horizontal one + /// (flip phone / table top). + protected abstract boolean isVerticalHinge(); + + @Override + protected Container buildContainer(int frameWidth, int frameHeight) { + Layout l = createFoldLayout(); + l.setFoldState(FoldState.NONE); + Container c = new Container(l); + Style cs = c.getAllStyles(); + cs.setBgColor(0xfafafa); + cs.setBgTransparency(255); + cs.setPaddingUnit(Style.UNIT_TYPE_PIXELS); + cs.setPadding(0, 0, 0, 0); + cs.setMarginUnit(Style.UNIT_TYPE_PIXELS); + cs.setMargin(0, 0, 0, 0); + populate(c); + foldContainer = c; + return c; + } + + @Override + protected ComponentAnimation startAnimation(Container container, int duration) { + int w = container.getWidth(); + int h = container.getHeight(); + if (isVerticalHinge()) { + int hw = Math.max(4, w / 24); + hinge = new Rectangle(w / 2 - hw / 2, 0, hw, h); + } else { + int hh = Math.max(4, h / 24); + hinge = new Rectangle(0, h / 2 - hh / 2, w, hh); + } + container.getLayout().setFoldState(new FoldState(DevicePosture.POSTURE_HALF_OPENED, + isVerticalHinge() ? DevicePosture.FOLD_ORIENTATION_VERTICAL + : DevicePosture.FOLD_ORIENTATION_HORIZONTAL, + true, hinge)); + return container.createAnimateLayout(duration); + } + + @Override + protected void renderFrame(Graphics g, int width, int height, double progress, int frameIndex) { + super.renderFrame(g, width, height, progress, frameIndex); + if (hinge == null || foldContainer == null) { + return; + } + int alpha = g.getAlpha(); + g.setAlpha((int) (40 + 180 * progress)); + g.setColor(0x202020); + g.fillRect(foldContainer.getAbsoluteX() + hinge.getX(), foldContainer.getAbsoluteY() + hinge.getY(), + hinge.getWidth(), hinge.getHeight()); + g.setAlpha(alpha); + } + + @Override + protected void finishCapture() { + foldContainer = null; + hinge = null; + super.finishCapture(); + } + + @Override + protected String getHostTitle() { + return "Fold"; + } + + /// A solid, pixel-styled tile, so the scene renders the same on every port whatever unit the + /// theme declares its paddings in (see `AnimateLayoutScreenshotTest`). + protected static Label tile(String text, int color) { + Label tile = new Label(text); + Style ts = tile.getAllStyles(); + ts.setBgColor(color); + ts.setFgColor(0xffffff); + ts.setBgTransparency(255); + ts.setMarginUnit(Style.UNIT_TYPE_PIXELS); + ts.setPaddingUnit(Style.UNIT_TYPE_PIXELS); + ts.setMargin(4, 4, 4, 4); + ts.setPadding(12, 12, 12, 12); + return tile; + } +} diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/Cn1ssDeviceRunner.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/Cn1ssDeviceRunner.java index 6cbda8890ab..335d654d43e 100644 --- a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/Cn1ssDeviceRunner.java +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/Cn1ssDeviceRunner.java @@ -373,6 +373,10 @@ private static int testTimeoutMs(BaseTest testClass) { new AnimateLayoutScreenshotTest(), new AnimateHierarchyScreenshotTest(), new AnimateUnlayoutScreenshotTest(), + new FoldBookOpenScreenshotTest(), + new FoldTableTopScreenshotTest(), + new FoldAvoidingGridScreenshotTest(), + new FoldFlipGridScreenshotTest(), new SmoothScrollScreenshotTest(), new StickyHeaderScreenshotTest(), new StickyHeaderSlideTransitionScreenshotTest(), diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldAvoidingGridScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldAvoidingGridScreenshotTest.java new file mode 100644 index 00000000000..1eb6ee20573 --- /dev/null +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldAvoidingGridScreenshotTest.java @@ -0,0 +1,27 @@ +package com.codenameone.examples.hellocodenameone.tests; + +import com.codename1.ui.Container; +import com.codename1.ui.layouts.FoldAvoidingLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.layouts.Layout; + +/// An ordinary grid wrapped in `FoldAvoidingLayout` on a book foldable: as the vertical hinge +/// appears, the two columns move apart so no tile sits under the crease. +public class FoldAvoidingGridScreenshotTest extends AbstractFoldAnimationScreenshotTest { + @Override + protected Layout createFoldLayout() { + return new FoldAvoidingLayout(new GridLayout(3, 2)); + } + + @Override + protected void populate(Container c) { + for (int i = 0; i < PALETTE.length; i++) { + c.add(tile("Tile " + (i + 1), PALETTE[i])); + } + } + + @Override + protected boolean isVerticalHinge() { + return true; + } +} diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldBookOpenScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldBookOpenScreenshotTest.java new file mode 100644 index 00000000000..3d0154afea6 --- /dev/null +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldBookOpenScreenshotTest.java @@ -0,0 +1,33 @@ +package com.codenameone.examples.hellocodenameone.tests; + +import com.codename1.ui.Container; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FoldLayout; +import com.codename1.ui.layouts.Layout; + +/// A list/detail screen on a book-style foldable: closed, only the list shows; opened, the list +/// stays on the left of the vertical hinge and the detail pane slides in on the right. +public class FoldBookOpenScreenshotTest extends AbstractFoldAnimationScreenshotTest { + @Override + protected Layout createFoldLayout() { + return new FoldLayout(FoldLayout.FALLBACK_PRIMARY_ONLY); + } + + @Override + protected void populate(Container c) { + Container list = new Container(BoxLayout.y()); + for (int i = 0; i < 4; i++) { + list.add(tile("Item " + (i + 1), PALETTE[i])); + } + Container detail = new Container(BoxLayout.y()); + detail.add(tile("Detail", PALETTE[5])); + detail.add(tile("Body", PALETTE[4])); + c.add(FoldLayout.PRIMARY, list); + c.add(FoldLayout.SECONDARY, detail); + } + + @Override + protected boolean isVerticalHinge() { + return true; + } +} diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldFlipGridScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldFlipGridScreenshotTest.java new file mode 100644 index 00000000000..8dd163b0312 --- /dev/null +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldFlipGridScreenshotTest.java @@ -0,0 +1,27 @@ +package com.codenameone.examples.hellocodenameone.tests; + +import com.codename1.ui.Container; +import com.codename1.ui.layouts.FoldAvoidingLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.layouts.Layout; + +/// The same grid on a flip phone: as it half folds along a horizontal hinge, the rows move apart +/// so the top half and the bottom half each keep whole tiles. +public class FoldFlipGridScreenshotTest extends AbstractFoldAnimationScreenshotTest { + @Override + protected Layout createFoldLayout() { + return new FoldAvoidingLayout(new GridLayout(2, 3)); + } + + @Override + protected void populate(Container c) { + for (int i = 0; i < PALETTE.length; i++) { + c.add(tile("Tile " + (i + 1), PALETTE[i])); + } + } + + @Override + protected boolean isVerticalHinge() { + return false; + } +} diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldTableTopScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldTableTopScreenshotTest.java new file mode 100644 index 00000000000..47da8a1a7ee --- /dev/null +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldTableTopScreenshotTest.java @@ -0,0 +1,33 @@ +package com.codenameone.examples.hellocodenameone.tests; + +import com.codename1.ui.Container; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FoldLayout; +import com.codename1.ui.layouts.Layout; + +/// A media screen moving into table-top posture: flat, the player and its controls sit side by +/// side; half folded along a horizontal hinge, the player moves above the crease and the controls +/// below it, like a laptop. +public class FoldTableTopScreenshotTest extends AbstractFoldAnimationScreenshotTest { + @Override + protected Layout createFoldLayout() { + return new FoldLayout(FoldLayout.FALLBACK_SPLIT); + } + + @Override + protected void populate(Container c) { + Container player = new Container(new BorderLayout()); + player.add(BorderLayout.CENTER, tile("Player", PALETTE[3])); + Container controls = new Container(BoxLayout.y()); + controls.add(tile("Play", PALETTE[2])); + controls.add(tile("Seek", PALETTE[1])); + c.add(FoldLayout.PRIMARY, player); + c.add(FoldLayout.SECONDARY, controls); + } + + @Override + protected boolean isVerticalHinge() { + return false; + } +} From bf518fe5b2801912a6e22d35beda292f26c6e99f Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:13:01 +0200 Subject: [PATCH 2/6] Fold layouts: dedupe posture events, non-scrolling FoldLayout forms, gate fixes Co-Authored-By: Claude Opus 5.5 --- CodenameOne/src/com/codename1/ui/Form.java | 17 +++++- .../com/codename1/ui/layouts/FoldLayout.java | 6 +-- docs/website/data/port_status.json | 28 ++++++++++ .../TestCodenameOneImplementation.java | 48 +++++++++++++++++ .../codename1/ui/FormFoldBehaviorTest.java | 53 +++++++++++++++---- .../AbstractFoldAnimationScreenshotTest.java | 22 ++++++++ .../tests/FoldAvoidingGridScreenshotTest.java | 22 ++++++++ .../tests/FoldBookOpenScreenshotTest.java | 22 ++++++++ .../tests/FoldFlipGridScreenshotTest.java | 22 ++++++++ .../tests/FoldTableTopScreenshotTest.java | 22 ++++++++ 10 files changed, 246 insertions(+), 16 deletions(-) diff --git a/CodenameOne/src/com/codename1/ui/Form.java b/CodenameOne/src/com/codename1/ui/Form.java index 43e64440ff4..2c27d04cebf 100644 --- a/CodenameOne/src/com/codename1/ui/Form.java +++ b/CodenameOne/src/com/codename1/ui/Form.java @@ -36,6 +36,7 @@ import com.codename1.ui.geom.Rectangle; import com.codename1.ui.layouts.BorderLayout; import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.FoldLayout; import com.codename1.ui.layouts.LayeredLayout; import com.codename1.ui.layouts.Layout; import com.codename1.ui.list.ListCellRenderer; @@ -229,6 +230,7 @@ HoverTracker getHoverTracker() { private EventDispatcher pointerCancelledListener; private EventDispatcher sizeChangedListener; private ActionListener postureListener; + private FoldState lastFold; private EventDispatcher pasteListener; private UIManager uiManager; private Component stickyDrag; @@ -1142,7 +1144,15 @@ protected void onFoldChanged(FoldState fold) { /// `Layout#FOLD_ANIMATE` (and reduced motion is off), revalidated when any answers /// `Layout#FOLD_REVALIDATE`, and left alone when every layout ignores folds. void foldChangedInternal() { - onFoldChanged(FoldState.current(this)); + FoldState fold = FoldState.current(this); + // Ports report every step of a fold (the simulator's hinge slider fires per tick, and + // Android's window-layout stream repeats states); only a change of the fold itself -- + // posture, orientation, separation or hinge bounds -- moves anything. + if (fold.equals(lastFold)) { + return; + } + lastFold = fold; + onFoldChanged(fold); int[] behavior = new int[2]; collectFoldBehavior(getContentPane(), behavior); if (behavior[0] == Layout.FOLD_ANIMATE && !Display.getInstance().isReduceMotionEnabled()) { @@ -3482,6 +3492,7 @@ void initComponentImpl() { if (postureListener == null) { postureListener = new PostureListener(); } + lastFold = FoldState.current(this); Display.getInstance().addPostureListener(postureListener); } // Only a form that owns the surface publishes its commands to the platform. @@ -4160,7 +4171,9 @@ public Layout getLayout() { /// {@inheritDoc} @Override public void setLayout(Layout layout) { - if (layout instanceof BorderLayout) { + if (layout instanceof BorderLayout || layout instanceof FoldLayout) { + // A FoldLayout pane fills its side of the hinge and scrolls by itself; a scrolling + // content pane would size the panes to their preferred height instead. setScrollable(false); } contentPane.setLayout(layout); diff --git a/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java b/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java index fcbfd8ff471..3268b5e7957 100644 --- a/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java +++ b/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java @@ -47,8 +47,8 @@ /// /// ```java /// Form f = new Form("Mail", new FoldLayout()); -/// f.add(FoldLayout.PRIMARY, inboxList); -/// f.add(FoldLayout.SECONDARY, messageView); +/// f.add(FoldLayout.PRIMARY, new Label("Inbox")); +/// f.add(FoldLayout.SECONDARY, new Label("Message")); /// f.show(); /// ``` public class FoldLayout extends Layout { @@ -335,7 +335,7 @@ public boolean equals(Object o) { return false; } FoldLayout f = (FoldLayout) o; - return fallback == f.fallback && splitRatio == f.splitRatio + return fallback == f.fallback && Float.floatToIntBits(splitRatio) == Float.floatToIntBits(f.splitRatio) && foldBehavior == f.foldBehavior; } diff --git a/docs/website/data/port_status.json b/docs/website/data/port_status.json index c87a23c4a31..b61324df6a9 100644 --- a/docs/website/data/port_status.json +++ b/docs/website/data/port_status.json @@ -183,6 +183,18 @@ "MorphTransitionTest" ] }, + { + "id": "fold-layout", + "category": "Animation and navigation", + "name": "Fold-aware layouts", + "description": "Checks layouts adapting with animation as a book, table-top or flip foldable changes posture.", + "tests": [ + "FoldAvoidingGridScreenshotTest", + "FoldBookOpenScreenshotTest", + "FoldFlipGridScreenshotTest", + "FoldTableTopScreenshotTest" + ] + }, { "id": "layout-animation", "category": "Animation and navigation", @@ -1303,6 +1315,22 @@ "pattern": "AnimateUnlayoutScreenshotTest", "test": "AnimateUnlayoutScreenshotTest" }, + { + "pattern": "FoldAvoidingGridScreenshotTest", + "test": "FoldAvoidingGridScreenshotTest" + }, + { + "pattern": "FoldBookOpenScreenshotTest", + "test": "FoldBookOpenScreenshotTest" + }, + { + "pattern": "FoldFlipGridScreenshotTest", + "test": "FoldFlipGridScreenshotTest" + }, + { + "pattern": "FoldTableTopScreenshotTest", + "test": "FoldTableTopScreenshotTest" + }, { "pattern": "SmoothScrollScreenshotTest", "test": "SmoothScrollScreenshotTest" diff --git a/maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java b/maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java index edb4e26d25c..c3e51d609d4 100644 --- a/maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java +++ b/maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java @@ -1566,8 +1566,56 @@ public void repaint(com.codename1.ui.animations.Animation cmp) { super.repaint(cmp); } + private boolean foldable; + private int devicePosture = com.codename1.ui.DevicePosture.POSTURE_UNKNOWN; + private int foldOrientation = com.codename1.ui.DevicePosture.FOLD_ORIENTATION_NONE; + private Rectangle foldBounds; + + /// Makes this implementation report a fold. A null `bounds` clears it back to a device that + /// does not fold. + public void setFold(int posture, int orientation, Rectangle bounds) { + foldable = bounds != null; + devicePosture = posture; + foldOrientation = orientation; + foldBounds = bounds; + } + + @Override + public boolean isFoldable() { + return foldable; + } + + @Override + public int getDevicePosture() { + return devicePosture; + } + + @Override + public int getFoldOrientation() { + return foldOrientation; + } + + @Override + public boolean isPostureSeparating() { + return foldBounds != null; + } + + @Override + public Rectangle getFoldBounds(Rectangle rect) { + if (foldBounds == null) { + return null; + } + if (rect == null) { + rect = new Rectangle(); + } + rect.setBounds(foldBounds.getX(), foldBounds.getY(), foldBounds.getWidth(), foldBounds.getHeight()); + return rect; + } + public void reset() { dipScale = 1f; + setFold(com.codename1.ui.DevicePosture.POSTURE_UNKNOWN, + com.codename1.ui.DevicePosture.FOLD_ORIENTATION_NONE, null); shapeSupported = false; drawCalls = null; drawnStrings = null; diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java index a3a3eaa657f..13c85e19b14 100644 --- a/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java @@ -32,9 +32,6 @@ import static org.junit.jupiter.api.Assertions.*; class FormFoldBehaviorTest extends UITestBase { - private static final FoldState BOOK = new FoldState(DevicePosture.POSTURE_HALF_OPENED, - DevicePosture.FOLD_ORIENTATION_VERTICAL, true, new Rectangle(100, 0, 20, 2000)); - private static final class CountingForm extends Form { int foldCalls; @@ -50,13 +47,20 @@ protected void onFoldChanged(FoldState fold) { private static CountingForm showFoldForm(FoldLayout fl, Label p, Label s) { CountingForm f = new CountingForm(fl); - fl.setFoldState(FoldState.NONE); f.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); f.show(); DisplayTest.flushEdt(); return f; } + /// A vertical hinge 20 pixels wide down the middle of the display. + private void openBook() { + int w = Display.getInstance().getDisplayWidth(); + int h = Display.getInstance().getDisplayHeight(); + implementation.setFold(DevicePosture.POSTURE_HALF_OPENED, DevicePosture.FOLD_ORIENTATION_VERTICAL, + new Rectangle(w / 2 - 10, 0, 20, h)); + } + private static void firePosture() { Display.getInstance().postureChanged(); for (int i = 0; i < 5; i++) { @@ -65,32 +69,58 @@ private static void firePosture() { } @FormTest - void revalidatingLayoutRelaysOutImmediately() { + void revalidatingLayoutRelaysOutAcrossTheHinge() { FoldLayout fl = new FoldLayout(); fl.setFoldBehavior(Layout.FOLD_REVALIDATE); Label p = new Label("p"); Label s = new Label("s"); CountingForm f = showFoldForm(fl, p, s); assertEquals(0, s.getWidth()); - fl.setFoldState(BOOK); + openBook(); firePosture(); assertEquals(1, f.foldCalls); + int hingeRight = Display.getInstance().getDisplayWidth() / 2 + 10; assertTrue(s.getWidth() > 0, "secondary pane should be laid out next to the hinge"); - assertTrue(s.getX() >= 120); + assertTrue(s.getAbsoluteX() >= hingeRight, "secondary pane must start past the hinge"); + assertTrue(p.getAbsoluteX() + p.getWidth() <= hingeRight - 20, "primary pane must end before the hinge"); } @FormTest - void animatingLayoutStartsAnAnimation() { + void panesFillTheFormInsteadOfScrolling() { FoldLayout fl = new FoldLayout(); Label p = new Label("p"); Label s = new Label("s"); CountingForm f = showFoldForm(fl, p, s); - fl.setFoldState(BOOK); + assertFalse(f.getContentPane().isScrollableY()); + Container cp = f.getContentPane(); + int inner = cp.getHeight() - cp.getStyle().getVerticalPadding(); + assertEquals(inner, p.getHeight() + p.getStyle().getVerticalMargins()); + } + + @FormTest + void animatingLayoutStartsAnAnimation() { + FoldLayout fl = new FoldLayout(); + CountingForm f = showFoldForm(fl, new Label("p"), new Label("s")); + openBook(); f.foldChangedInternal(); assertEquals(1, f.foldCalls); assertTrue(f.getAnimationManager().isAnimating(), "a fold-aware layout animates into place"); } + @FormTest + void repeatedPostureEventsWithTheSameFoldAreIgnored() { + FoldLayout fl = new FoldLayout(); + fl.setFoldBehavior(Layout.FOLD_REVALIDATE); + CountingForm f = showFoldForm(fl, new Label("p"), new Label("s")); + f.foldChangedInternal(); + assertEquals(0, f.foldCalls, "nothing changed since the form was shown"); + openBook(); + f.foldChangedInternal(); + f.foldChangedInternal(); + f.foldChangedInternal(); + assertEquals(1, f.foldCalls); + } + @FormTest void ignoringLayoutsLeaveTheFormAlone() { CountingForm f = new CountingForm(new BorderLayout()); @@ -99,6 +129,7 @@ void ignoringLayoutsLeaveTheFormAlone() { f.show(); DisplayTest.flushEdt(); int w = l.getWidth(); + openBook(); f.foldChangedInternal(); assertEquals(1, f.foldCalls); assertFalse(f.getAnimationManager().isAnimating()); @@ -107,11 +138,11 @@ void ignoringLayoutsLeaveTheFormAlone() { @FormTest void aFormThatIsNoLongerShowingStopsListening() { - FoldLayout fl = new FoldLayout(); - CountingForm first = showFoldForm(fl, new Label("p"), new Label("s")); + CountingForm first = showFoldForm(new FoldLayout(), new Label("p"), new Label("s")); Form second = new Form("Other", new BorderLayout()); second.show(); DisplayTest.flushEdt(); + openBook(); firePosture(); assertEquals(0, first.foldCalls); } diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/AbstractFoldAnimationScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/AbstractFoldAnimationScreenshotTest.java index 918591d6969..d85063d65bf 100644 --- a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/AbstractFoldAnimationScreenshotTest.java +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/AbstractFoldAnimationScreenshotTest.java @@ -1,3 +1,25 @@ +/* + * 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.codenameone.examples.hellocodenameone.tests; import com.codename1.ui.Container; diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldAvoidingGridScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldAvoidingGridScreenshotTest.java index 1eb6ee20573..8435433f1f7 100644 --- a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldAvoidingGridScreenshotTest.java +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldAvoidingGridScreenshotTest.java @@ -1,3 +1,25 @@ +/* + * 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.codenameone.examples.hellocodenameone.tests; import com.codename1.ui.Container; diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldBookOpenScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldBookOpenScreenshotTest.java index 3d0154afea6..f726eb71f29 100644 --- a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldBookOpenScreenshotTest.java +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldBookOpenScreenshotTest.java @@ -1,3 +1,25 @@ +/* + * 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.codenameone.examples.hellocodenameone.tests; import com.codename1.ui.Container; diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldFlipGridScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldFlipGridScreenshotTest.java index 8dd163b0312..1a5261e1de2 100644 --- a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldFlipGridScreenshotTest.java +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldFlipGridScreenshotTest.java @@ -1,3 +1,25 @@ +/* + * 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.codenameone.examples.hellocodenameone.tests; import com.codename1.ui.Container; diff --git a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldTableTopScreenshotTest.java b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldTableTopScreenshotTest.java index 47da8a1a7ee..88b136119f0 100644 --- a/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldTableTopScreenshotTest.java +++ b/scripts/hellocodenameone/common/src/main/java/com/codenameone/examples/hellocodenameone/tests/FoldTableTopScreenshotTest.java @@ -1,3 +1,25 @@ +/* + * 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.codenameone.examples.hellocodenameone.tests; import com.codename1.ui.Container; From ed060322f66ad7df0e23845363971b967d85e54f Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:53:51 +0200 Subject: [PATCH 3/6] Fold layouts: red-team fixes (no removal during setLayout, scroll-safe hinge, padded split, hidden collapsed pane) Co-Authored-By: Claude Opus 5.5 --- .../src/com/codename1/ui/FoldState.java | 6 +- .../ui/layouts/FoldAvoidingLayout.java | 40 ++++++++----- .../com/codename1/ui/layouts/FoldLayout.java | 50 +++++++++++++--- .../src/com/codename1/ui/layouts/Layout.java | 2 +- .../codename1/ui/layouts/FoldLayoutTest.java | 57 ++++++++++++++++++- 5 files changed, 128 insertions(+), 27 deletions(-) diff --git a/CodenameOne/src/com/codename1/ui/FoldState.java b/CodenameOne/src/com/codename1/ui/FoldState.java index d296fcddf98..cce5cc83166 100644 --- a/CodenameOne/src/com/codename1/ui/FoldState.java +++ b/CodenameOne/src/com/codename1/ui/FoldState.java @@ -101,7 +101,11 @@ public static FoldState current(Component relativeTo) { } Rectangle r = dp.getFoldBounds(null); if (r != null && relativeTo != null) { - r = new Rectangle(r.getX() - relativeTo.getAbsoluteX(), r.getY() - relativeTo.getAbsoluteY(), + // getAbsoluteX/Y subtract the component's own scroll; a layout works in unscrolled + // child coordinates, so add it back or the hinge would move as the container scrolls. + int ax = relativeTo.getAbsoluteX() + relativeTo.getScrollX(); + int ay = relativeTo.getAbsoluteY() + relativeTo.getScrollY(); + r = new Rectangle(r.getX() - ax, r.getY() - ay, r.getWidth(), r.getHeight()); } return new FoldState(dp.getPosture(), dp.getFoldOrientation(), dp.isSeparating(), r); diff --git a/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java b/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java index b23c22d96ea..9bab06349d7 100644 --- a/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java +++ b/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java @@ -102,13 +102,18 @@ public void layoutContainer(Container parent) { if (!vertical && !fold.isHorizontalSeparation()) { return; } - int size = vertical ? parent.getWidth() : parent.getHeight(); - int fs = Math.max(0, Math.min(size, fold.getFoldStart())); - int fe = Math.max(fs, Math.min(size, fold.getFoldEnd())); - int mid = size / 2; - if (mid <= 0 || mid >= size) { + // Map over the padded inner range, so asymmetric padding does not move the split. + com.codename1.ui.plaf.Style st = parent.getStyle(); + boolean rtl = parent.isRTL(); + int lo = vertical ? st.getPaddingLeft(rtl) : st.getPaddingTop(); + int hi = vertical ? parent.getWidth() - st.getPaddingRight(rtl) + : parent.getHeight() - st.getPaddingBottom(); + if (hi - lo <= 1) { return; } + int fs = Math.max(lo, Math.min(hi, fold.getFoldStart())); + int fe = Math.max(fs, Math.min(hi, fold.getFoldEnd())); + int mid = lo + (hi - lo) / 2; int count = parent.getComponentCount(); for (int i = 0; i < count; i++) { Component c = parent.getComponentAt(i); @@ -117,11 +122,11 @@ public void layoutContainer(Container parent) { int newStart; int newEnd; if (start + end <= 2 * mid) { - newStart = mapLow(start, mid, fs); - newEnd = Math.min(mapLow(end, mid, fs), fs); + newStart = mapLow(start, lo, mid, fs); + newEnd = Math.min(mapLow(end, lo, mid, fs), fs); } else { - newStart = Math.max(mapHigh(start, mid, fe, size), fe); - newEnd = mapHigh(end, mid, fe, size); + newStart = Math.max(mapHigh(start, mid, fe, hi), fe); + newEnd = mapHigh(end, mid, fe, hi); } int len = Math.max(0, newEnd - newStart); if (vertical) { @@ -134,18 +139,24 @@ public void layoutContainer(Container parent) { } } - private static int mapLow(int v, int mid, int foldStart) { + private static int mapLow(int v, int lo, int mid, int foldStart) { if (v >= mid) { return foldStart; } - return (int) ((long) v * foldStart / mid); + if (v <= lo) { + return v; + } + return lo + (int) ((long) (v - lo) * (foldStart - lo) / (mid - lo)); } - private static int mapHigh(int v, int mid, int foldEnd, int size) { + private static int mapHigh(int v, int mid, int foldEnd, int hi) { if (v <= mid) { return foldEnd; } - return foldEnd + (int) ((long) (v - mid) * (size - foldEnd) / (size - mid)); + if (v >= hi) { + return v; + } + return foldEnd + (int) ((long) (v - mid) * (hi - foldEnd) / (hi - mid)); } @Override @@ -200,7 +211,8 @@ public boolean obscuresPotential(Container parent) { @Override public boolean equals(Object o) { return super.equals(o) && delegate.equals(((FoldAvoidingLayout) o).delegate) - && foldBehavior == ((FoldAvoidingLayout) o).foldBehavior; + && foldBehavior == ((FoldAvoidingLayout) o).foldBehavior + && foldAnimationDuration == ((FoldAvoidingLayout) o).foldAnimationDuration; } @Override diff --git a/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java b/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java index 3268b5e7957..e884541ae7d 100644 --- a/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java +++ b/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java @@ -73,6 +73,7 @@ public class FoldLayout extends Layout { private float splitRatio = 0.5f; private int foldBehavior = FOLD_ANIMATE; private int foldAnimationDuration = 300; + private Component collapsedByLayout; /// Creates a fold layout that shows only the primary pane when there is no separating fold. public FoldLayout() { @@ -154,21 +155,27 @@ public int getFoldAnimationDuration() { @Override public void addLayoutComponent(Object value, Component comp, Container c) { + // Never removes a component from here: Container.setLayout re-adds every child while it + // iterates them, and a removal inside that loop would skip the next child. A pane added + // over an existing one takes its place in the layout; the one it displaced stays a child + // and is laid out at zero size until removed. A constraint that is neither PRIMARY nor + // SECONDARY (another layout's, when a container switches to this one) fills the primary + // slot, then the secondary. if (SECONDARY.equals(value)) { - if (secondary != null && secondary != comp) { //NOPMD CompareObjectsWithEquals - c.removeComponent(secondary); - } secondary = comp; - } else { - if (primary != null && primary != comp) { //NOPMD CompareObjectsWithEquals - c.removeComponent(primary); - } + } else if (PRIMARY.equals(value) || primary == null) { primary = comp; + } else if (secondary == null) { + secondary = comp; } } @Override public void removeLayoutComponent(Component comp) { + if (comp == collapsedByLayout) { //NOPMD CompareObjectsWithEquals + comp.setVisible(true); + collapsedByLayout = null; + } if (comp == primary) { //NOPMD CompareObjectsWithEquals primary = null; } else if (comp == secondary) { //NOPMD CompareObjectsWithEquals @@ -212,6 +219,14 @@ public Component getSecondary() { @Override public void layoutContainer(Container parent) { + int count = parent.getComponentCount(); + for (int i = 0; i < count; i++) { + Component c = parent.getComponentAt(i); + if (c != primary && c != secondary) { //NOPMD CompareObjectsWithEquals + c.setWidth(0); + c.setHeight(0); + } + } Style s = parent.getStyle(); boolean rtl = parent.isRTL(); int top = s.getPaddingTop(); @@ -219,6 +234,7 @@ public void layoutContainer(Container parent) { int left = s.getPaddingLeft(rtl); int right = parent.getLayoutWidth() - parent.getSideGap() - s.getPaddingRight(rtl); FoldState fold = getFoldState(parent); + setCollapsed(secondary, false); if (fold.isVerticalSeparation()) { int fs = clamp(fold.getFoldStart(), left, right); int fe = clamp(fold.getFoldEnd(), fs, right); @@ -235,6 +251,8 @@ public void layoutContainer(Container parent) { int edge = rtl ? left : right; place(secondary, edge, top, edge, bottom); } + setCollapsed(secondary, true); + return; } else if (fallback == FALLBACK_STACK) { int ph = primary == null ? 0 : primary.getPreferredH() + primary.getStyle().getVerticalMargins(); @@ -247,6 +265,22 @@ public void layoutContainer(Container parent) { } } + /// A collapsed pane must not take focus or traversal: it is still a child, at zero width. + private void setCollapsed(Component c, boolean collapsed) { + if (c == null) { + return; + } + if (collapsed) { + if (c.isVisible()) { + c.setVisible(false); + collapsedByLayout = c; + } + } else if (c == collapsedByLayout) { //NOPMD CompareObjectsWithEquals + c.setVisible(true); + collapsedByLayout = null; + } + } + private void placeSideBySide(int left, int foldStart, int foldEnd, int right, int top, int bottom, boolean rtl) { if (rtl) { @@ -336,7 +370,7 @@ public boolean equals(Object o) { } FoldLayout f = (FoldLayout) o; return fallback == f.fallback && Float.floatToIntBits(splitRatio) == Float.floatToIntBits(f.splitRatio) - && foldBehavior == f.foldBehavior; + && foldBehavior == f.foldBehavior && foldAnimationDuration == f.foldAnimationDuration; } @Override diff --git a/CodenameOne/src/com/codename1/ui/layouts/Layout.java b/CodenameOne/src/com/codename1/ui/layouts/Layout.java index d735845ffa2..e866ce5b70a 100644 --- a/CodenameOne/src/com/codename1/ui/layouts/Layout.java +++ b/CodenameOne/src/com/codename1/ui/layouts/Layout.java @@ -69,7 +69,7 @@ public int getFoldAnimationDuration() { return 300; } - /// Fixes the fold this layout lays out against, instead of the live device fold. Useful for a + /// Fixes the fold this layout lays out against (`#equals(Object)` does not compare it), instead of the live device fold. Useful for a /// preview, for a large screen that wants a "virtual hinge", and for tests on a device that /// does not fold. /// diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java index f60e2502cb0..f8bf21fb28c 100644 --- a/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java @@ -131,16 +131,51 @@ void stackFallbackGivesPrimaryItsPreferredHeight() { } @FormTest - void addingASecondPrimaryReplacesTheFirst() { + void addingASecondPrimaryReplacesTheFirstWithoutRemovingIt() { FoldLayout fl = new FoldLayout(); + fl.setFoldState(FoldState.NONE); Container c = host(fl); Label first = pane("a"); Label second = pane("b"); c.add(FoldLayout.PRIMARY, first); c.add(FoldLayout.PRIMARY, second); assertSame(second, fl.getPrimary()); - assertNull(first.getParent()); - assertEquals(FoldLayout.PRIMARY, fl.getComponentConstraint(second)); + assertSame(c, first.getParent()); + c.layoutContainer(); + assertEquals(0, first.getWidth()); + assertEquals(400, second.getWidth()); + } + + @FormTest + void switchingABorderLayoutContainerKeepsEveryChild() { + Container c = host(new BorderLayout()); + Label north = pane("n"); + Label center = pane("c"); + Label south = pane("s"); + c.add(BorderLayout.NORTH, north).add(BorderLayout.CENTER, center).add(BorderLayout.SOUTH, south); + FoldLayout fl = new FoldLayout(); + fl.setFoldState(BOOK); + c.setLayout(fl); + assertEquals(3, c.getComponentCount()); + assertSame(north, fl.getPrimary()); + assertSame(center, fl.getSecondary()); + } + + @FormTest + void collapsedSecondaryIsHiddenAndComesBackWhenTheDeviceOpens() { + FoldLayout fl = new FoldLayout(); + fl.setFoldState(FoldState.NONE); + Container c = host(fl); + Label p = pane("p"); + Label s = pane("s"); + c.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); + c.layoutContainer(); + assertFalse(s.isVisible()); + fl.setFoldState(BOOK); + c.setShouldCalcPreferredSize(true); + c.layoutContainer(); + assertTrue(s.isVisible()); + assertEquals(190, s.getWidth()); } @FormTest @@ -193,6 +228,22 @@ void avoidingLayoutNeverLeavesAChildUnderTheHinge() { } } + @FormTest + void avoidingLayoutSplitsAtTheMiddleOfThePaddedArea() { + FoldAvoidingLayout l = new FoldAvoidingLayout(new GridLayout(1, 2)); + l.setFoldState(BOOK); + Container c = host(l); + c.getAllStyles().setPaddingUnit(com.codename1.ui.plaf.Style.UNIT_TYPE_PIXELS); + c.getAllStyles().setPadding(0, 0, 20, 0); + Label a = pane("a"); + Label b = pane("b"); + c.add(a).add(b); + c.layoutContainer(); + assertTrue(a.getX() + a.getWidth() <= 190); + assertTrue(b.getX() >= 210); + assertTrue(a.getX() >= 20, "left padding is kept"); + } + @FormTest void avoidingLayoutLeavesTheDelegateAloneWithoutAFold() { FoldAvoidingLayout l = new FoldAvoidingLayout(new GridLayout(1, 2)); From f3d0bc701ea52af2f2b121ca10f07874fe255571 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:56:02 +0200 Subject: [PATCH 4/6] Fold layouts: leave pane visibility to the app, align FoldAvoidingLayout bounds Co-Authored-By: Claude Opus 5.5 --- .../ui/layouts/FoldAvoidingLayout.java | 4 +-- .../com/codename1/ui/layouts/FoldLayout.java | 28 ++----------------- .../codename1/ui/layouts/FoldLayoutTest.java | 5 ++-- 3 files changed, 8 insertions(+), 29 deletions(-) diff --git a/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java b/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java index 9bab06349d7..2542bf0eb38 100644 --- a/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java +++ b/CodenameOne/src/com/codename1/ui/layouts/FoldAvoidingLayout.java @@ -106,8 +106,8 @@ public void layoutContainer(Container parent) { com.codename1.ui.plaf.Style st = parent.getStyle(); boolean rtl = parent.isRTL(); int lo = vertical ? st.getPaddingLeft(rtl) : st.getPaddingTop(); - int hi = vertical ? parent.getWidth() - st.getPaddingRight(rtl) - : parent.getHeight() - st.getPaddingBottom(); + int hi = vertical ? parent.getLayoutWidth() - parent.getSideGap() - st.getPaddingRight(rtl) + : parent.getLayoutHeight() - parent.getBottomGap() - st.getPaddingBottom(); if (hi - lo <= 1) { return; } diff --git a/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java b/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java index e884541ae7d..69cef987484 100644 --- a/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java +++ b/CodenameOne/src/com/codename1/ui/layouts/FoldLayout.java @@ -39,7 +39,9 @@ /// posture): the primary pane is above the hinge and the secondary below it. /// - **No separating fold**: the fallback chosen with `#setFallback(int)` applies -- the primary /// pane alone (`#FALLBACK_PRIMARY_ONLY`, the default, the secondary pane collapses to zero width -/// at the trailing edge), the two stacked (`#FALLBACK_STACK`), or split side by side +/// at the trailing edge, so it slides in and out with the fold animation; the layout never +/// changes its visibility, so hide it yourself in `Form#onFoldChanged` if it must not take +/// focus while collapsed), the two stacked (`#FALLBACK_STACK`), or split side by side /// (`#FALLBACK_SPLIT`, as on a large unfolded screen). /// /// The layout's `#getFoldBehavior()` is `#FOLD_ANIMATE`, so the form animates the panes into place @@ -73,7 +75,6 @@ public class FoldLayout extends Layout { private float splitRatio = 0.5f; private int foldBehavior = FOLD_ANIMATE; private int foldAnimationDuration = 300; - private Component collapsedByLayout; /// Creates a fold layout that shows only the primary pane when there is no separating fold. public FoldLayout() { @@ -172,10 +173,6 @@ public void addLayoutComponent(Object value, Component comp, Container c) { @Override public void removeLayoutComponent(Component comp) { - if (comp == collapsedByLayout) { //NOPMD CompareObjectsWithEquals - comp.setVisible(true); - collapsedByLayout = null; - } if (comp == primary) { //NOPMD CompareObjectsWithEquals primary = null; } else if (comp == secondary) { //NOPMD CompareObjectsWithEquals @@ -234,7 +231,6 @@ public void layoutContainer(Container parent) { int left = s.getPaddingLeft(rtl); int right = parent.getLayoutWidth() - parent.getSideGap() - s.getPaddingRight(rtl); FoldState fold = getFoldState(parent); - setCollapsed(secondary, false); if (fold.isVerticalSeparation()) { int fs = clamp(fold.getFoldStart(), left, right); int fe = clamp(fold.getFoldEnd(), fs, right); @@ -251,8 +247,6 @@ public void layoutContainer(Container parent) { int edge = rtl ? left : right; place(secondary, edge, top, edge, bottom); } - setCollapsed(secondary, true); - return; } else if (fallback == FALLBACK_STACK) { int ph = primary == null ? 0 : primary.getPreferredH() + primary.getStyle().getVerticalMargins(); @@ -265,22 +259,6 @@ public void layoutContainer(Container parent) { } } - /// A collapsed pane must not take focus or traversal: it is still a child, at zero width. - private void setCollapsed(Component c, boolean collapsed) { - if (c == null) { - return; - } - if (collapsed) { - if (c.isVisible()) { - c.setVisible(false); - collapsedByLayout = c; - } - } else if (c == collapsedByLayout) { //NOPMD CompareObjectsWithEquals - c.setVisible(true); - collapsedByLayout = null; - } - } - private void placeSideBySide(int left, int foldStart, int foldEnd, int right, int top, int bottom, boolean rtl) { if (rtl) { diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java index f8bf21fb28c..4a23f346fbf 100644 --- a/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/ui/layouts/FoldLayoutTest.java @@ -162,7 +162,7 @@ void switchingABorderLayoutContainerKeepsEveryChild() { } @FormTest - void collapsedSecondaryIsHiddenAndComesBackWhenTheDeviceOpens() { + void collapsedSecondaryKeepsItsVisibilityAndComesBackWhenTheDeviceOpens() { FoldLayout fl = new FoldLayout(); fl.setFoldState(FoldState.NONE); Container c = host(fl); @@ -170,7 +170,8 @@ void collapsedSecondaryIsHiddenAndComesBackWhenTheDeviceOpens() { Label s = pane("s"); c.add(FoldLayout.PRIMARY, p).add(FoldLayout.SECONDARY, s); c.layoutContainer(); - assertFalse(s.isVisible()); + assertTrue(s.isVisible()); + assertEquals(0, s.getWidth()); fl.setFoldState(BOOK); c.setShouldCalcPreferredSize(true); c.layoutContainer(); From a2221fe3db59b32fd386e780a2eabe438b05a0ff Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:58:17 +0200 Subject: [PATCH 5/6] Fold layouts: Form(FoldLayout) constructor builds a non-scrolling content pane Co-Authored-By: Claude Opus 5.5 --- CodenameOne/src/com/codename1/ui/Form.java | 3 ++- .../src/test/java/com/codename1/ui/FormFoldBehaviorTest.java | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CodenameOne/src/com/codename1/ui/Form.java b/CodenameOne/src/com/codename1/ui/Form.java index 2c27d04cebf..393e7b3c94f 100644 --- a/CodenameOne/src/com/codename1/ui/Form.java +++ b/CodenameOne/src/com/codename1/ui/Form.java @@ -286,7 +286,8 @@ public Form(Layout contentPaneLayout) { initAdPadding(d); contentPane.setUIID("ContentPane"); - contentPane.setScrollableY(true); + // A FoldLayout pane fills its side of the hinge and scrolls by itself, see setLayout. + contentPane.setScrollableY(!(contentPaneLayout instanceof FoldLayout)); if (title.getText() != null && title.shouldTickerStart()) { title.startTicker(getUIManager().getLookAndFeel().getTickerSpeed(), true); diff --git a/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java b/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java index 13c85e19b14..41c5e723139 100644 --- a/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/ui/FormFoldBehaviorTest.java @@ -89,9 +89,12 @@ void revalidatingLayoutRelaysOutAcrossTheHinge() { void panesFillTheFormInsteadOfScrolling() { FoldLayout fl = new FoldLayout(); Label p = new Label("p"); + // Far taller than the screen: a scrolling content pane would stretch it to this height. + p.setPreferredH(Display.getInstance().getDisplayHeight() * 3); Label s = new Label("s"); CountingForm f = showFoldForm(fl, p, s); - assertFalse(f.getContentPane().isScrollableY()); + assertFalse(f.getContentPane().scrollableYFlag()); + assertTrue(p.getHeight() <= f.getContentPane().getHeight()); Container cp = f.getContentPane(); int inner = cp.getHeight() - cp.getStyle().getVerticalPadding(); assertEquals(inner, p.getHeight() + p.getStyle().getVerticalMargins()); From c4ab01095137946bfe50bf48436db91a68637096 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:22:50 +0200 Subject: [PATCH 6/6] JavaScript port: test Form receivers with instanceOf, not a class-name prefix Form.postureListener's class, Form$PostureListener, starts with the Form prefix; the addComponent fallback took it for the form and rebuilt its content pane with a FlowLayout, blanking the Chart2 animation screenshots. Co-Authored-By: Claude Opus 5.5 --- Ports/JavaScriptPort/src/main/webapp/port.js | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Ports/JavaScriptPort/src/main/webapp/port.js b/Ports/JavaScriptPort/src/main/webapp/port.js index b4a6a35e266..37e6d493c88 100644 --- a/Ports/JavaScriptPort/src/main/webapp/port.js +++ b/Ports/JavaScriptPort/src/main/webapp/port.js @@ -4083,12 +4083,18 @@ function resolveCurrentTranslatedMethod(methodIds, ownerClassName, fallbackSymbo } return null; } +// A class-name prefix is not a type test: "com_codename1_ui_Form" also prefixes Form's own inner +// classes (Form$PostureListener), and treating one of those as the form sent Form.addComponent +// to a listener whose content pane the fallback then rebuilt with a FlowLayout. +function isFormInstance(value) { + return !!(value && value.__class && jvm.instanceOf(value, "com_codename1_ui_Form")); +} function isLikelyFormObject(value) { if (!value || typeof value !== "object") { return false; } const classId = value.__class ? String(value.__class) : ""; - if (classId.indexOf("com_codename1_ui_Form") === 0 || classId.indexOf("com_codename1_ui_Dialog") === 0) { + if (isFormInstance(value)) { return true; } const classDef = value.__classDef; @@ -4887,12 +4893,12 @@ bindCiFallbackWithMethodId("Form.addComponentNullContentPaneGuard", formAddCompo } let effectiveSelf = __cn1ThisObject; let receiverRemapField = null; - if (!(effectiveSelf && effectiveSelf.__class && effectiveSelf.__class.indexOf("com_codename1_ui_Form") === 0) && effectiveSelf && typeof effectiveSelf === "object") { + if (!(isFormInstance(effectiveSelf)) && effectiveSelf && typeof effectiveSelf === "object") { const keys = Object.keys(effectiveSelf); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = effectiveSelf[key]; - if (value && value.__class && value.__class.indexOf("com_codename1_ui_Form") === 0) { + if (isFormInstance(value)) { effectiveSelf = value; receiverRemapField = key; break; @@ -4902,7 +4908,7 @@ bindCiFallbackWithMethodId("Form.addComponentNullContentPaneGuard", formAddCompo if (receiverRemapField) { emitDiagLine("PARPAR:DIAG:FALLBACK:formAddComponent:receiverRemap=" + receiverRemapField); } - if (effectiveSelf && effectiveSelf.__class && effectiveSelf.__class.indexOf("com_codename1_ui_Form") === 0) { + if (isFormInstance(effectiveSelf)) { emitDiagLine( "PARPAR:DIAG:FALLBACK:formAddComponent:receiver=" + effectiveSelf.__class