Commit graph

479 commits

Author SHA1 Message Date
Kevin Boos
5ec03ff0ad
Add full app lifecycle event support, and Ctrl+C/signal catch (#1074)
* WIP: adding full app lifecycle event support, and Ctrl+C/signal catch

* Added fuller lifecycle event support, plus ability to catch sigquit

Tested working well on every platform except web/wasm, as I don't have
a working setup able to test that.
2026-05-01 22:30:24 +02:00
Kevin Boos
3fe61b3ed0
Add separate touch margin; use it on dock splitter and tab close (#1072)
* Fix portallist alignment handling so centering actually works

Now, alignment on PortalLists now only applies to the "cross-axis"
of each item, not the main axis.
So when you center a portallist itself, it won't add weird space
on the leading side of the list

* Fix text not drawing on top of a background, e.g., `<code>` tags

This worked in *most* but not all cases, e.g., if you had a ton of
inline code tags, some of them would rarely but deterministically
not show the actual text glyphs, but just an empty background.

* Avoid large margin on the left of `<code>` if it's on a new line

* Add a separate "touch" margin; use it on dock splitter and tab close

Without this, those dock UI elements are nearly impossible to grab
and press on a real touch screen device, even on my iPad.

Also, tweak cargo-makepad iOS and Android builds to use a polished
display name for the app (uppercase first character) by default.
2026-04-30 08:33:04 +02:00
Admin
9d3d0e4450 ai mgr update 2026-04-28 18:25:08 +02:00
Admin
61a3f53c5c ai manager otw 2026-04-28 12:24:40 +02:00
Admin
614e203f17 aimgr 2026-04-27 14:51:24 +02:00
Kevin Boos
cd6d2e78cd
Separate apply-reload and script-reapply into different concepts (#1069)
* Simplify tooltip logic, fix positioning to respect safe inset areas

And other misc positioning/formatting fixes, like wrapping
after a hard line break, as well as ensuring that the callout
arrow thing itself is centered (to the fullest extent possible)
w.r.t. the rest of the tooltip body.

Basically, now it looks good again.

* Fix CheckBox/Toggle `set_active` to animate like others

All other widgets allow you to pass an `animate` arg when setting
them as active, except CheckBox (and by proxy, its wrapper Toggle).
This is necessary for proper non-animated thigns like restoring the
state of a toggle from persistent storage, or other similar examples
where you don't really want the animation to occur (because that'll
look like the user did it accidentally or some kind of phantom movement).

* PortalList: pass "touch stop" (FingerUp) events to children, always

I had recently implemented a feature where PortalList would not pass
events down to its children if those events were being direclty handled
by the PortalList as part of its scroll-action. That was generally correct,
but it missed one rare case where a child widget was waiting on a
finger up (touch stop/release) for something like stopping a hover/down
animation.

So the child, like a button, could capture the initial FingerDown
but never the FingerUp, so they'd get stuck on the hover or down
animation. This fixes that issue by passing FingerUp-causing events
down to the child widgets.

Note that the children must use `was_tap()` on the FingerUp in order
to handle a regular click -- but they should have already been doing that.
So this doesn't break anything, it's just strictly a proper fix
for something that i should've covered previously.

* Separate apply-reload and script-reapply into different concepts

The goal here is to differentiate between "applies" that change the actual
Splash script "DSL" (i.e., the template) from a "re-apply" that doesn't
change the DSL template but does change runtime heap objects.

Mostly, we want to ensure that LiveEdit (the former) is different from
things that require heap updates (the latter), such as changing a theme
value or doing screen rotation that changes safe inset areas on mobile.

I don't know that I love this approach as a permanent solution,
but it's a good stepping stone until we can redesign LiveEdit/Apply
to funnel all of these various events through the same singular system.
We probably want to use different attributes on widget fields in order
to have more fine-grained control over what happens on an Apply action.

Generated list of brief details here:

* `Apply::ScriptReapply` variant + `is_script_reapply` /
  `is_live_edit_reload` predicates; `Event::ScriptReapply` now applies
  via `Apply::ScriptReapply`.
* `String` / `ArcStringMut` `script_apply` early-return on
  `ScriptReapply`.
* Codegen: `#[deref]` runs before `#[apply_default]`'s recursive call
  so animator state wins over template defaults.
* `Animator::script_apply_default` returns `state_object` on
  `ScriptReapply`; new `current_state_apply()` helper for
  `on_after_apply` hooks.

* `Cx::request_live_edit()` + `pending_live_edit_request` for primitive
  heap mutations (safe-area insets baked into `script_mod!`
  expressions).
* `handle_live_edit()` returns `LiveEditTrigger {None, FileChange,
  Manual}`; `run_live_edit_if_needed` skips shader-cache reset and
  same-tick `ScriptReapply` follow-up for `Manual` (fixes ~1s rotation
  lag).
* iOS/Android post-event hook now drains both flags via
  `run_live_edit_if_needed` (was firing `LiveEdit` indiscriminately).
* `Window` `WindowGeomChange` uses `request_live_edit()` for
  safe-area.

* `StackNavigationView` gains `runtime_title` field re-asserted in
  `on_after_apply`; new `StackNavigation::set_title` API.
* `app_main!` collapses 4 duplicate platform branches into a shared
  `_app_main_event_closure!` macro.
2026-04-26 22:11:31 +02:00
Kevin Boos
18669f5a58
Support runtime changes to script-level heap objects (#1063)
* Support runtime-reassigned module templates and app-wide events

- Dock/PortalList: add `refresh_widgets_mod_template()` so callers can
  re-capture a content template from `mod.widgets.*` after reassigning
  it at runtime via `script_eval!`. Dock's variant takes a separate
  template_key and mod_widgets_name since local DSL names (e.g.
  `room_screen`) don't always match the module entry (`RoomScreen`).
- PortalList: add `all_items_and_pool()` iterator so callers can walk
  every live and pooled item (e.g. to push a new property across the
  whole list on a preference change).
- StackNavigation: forward non-visibility events (`Event::Actions`) to
  all child stack views, not just visible ones. Inactive views need
  global state updates too; `View::handle_event` still gates on each
  child's own `visible` flag for events that require visibility.
- TextInput: add `submit_on_enter` so callers can opt into Cmd/Ctrl+
  Enter submit semantics, plus a `key_focus_lost` helper for commit-
  on-blur inputs.
- Image: honor `Size::Fit { max }` when `peek_walk_turtle` returns NaN
  so `Fit{max: Abs(..)}` caps image height without clipping.
- FlatList: derive `Default` on the shared `WidgetItem` struct.
- draw: re-export `Base` and `FitBound` from turtle.

* Add Event::ScriptReapply + preserve Dock state on reload

- `Event::ScriptReapply`: new event signalling a widget-tree Apply::Reload
  that does NOT re-run `script_mod!`. Fires from `run_live_edit_if_needed`
  when `Cx::pending_script_reapply` is set (previously the flag was never
  observed on desktop). The AppMain macro caches the app's script root as
  a rooted `ScriptObjectRef` and re-applies the tree with it — so runtime
  heap mutations (e.g. `script_eval!` overriding a user preference) stay
  intact. If a file-driven `LiveEdit` handler then sets the flag again, a
  bounded follow-up `ScriptReapply` pass runs in the same tick.

- Dock: on `Apply::Reload`, preserve existing runtime `dock_items` (open
  tabs, selected indices, splitter positions). Only insert DSL-defined
  items for IDs that don't already exist — so a source hot-reload no
  longer wipes the user's opened tabs.

* cleanup, remove unnecessary crap from prior approaches

the whole `refresh_widgets_mod_template` was a misguided approach,
and now that we have script reload/re-apply working and we have fixed
LiveEdit for most widgets, we just don't need it

* cleanup, remove more unused functions
2026-04-22 23:36:56 +02:00
Kevin Boos
85fbea9b0f
Switch to SLUG/DrawGlyph font drawing stack (#1042)
* Switch to SLUG/DrawGlyph font drawing stack (via Codex)

* Improve same-frame new glyph caching and SLUG packed instances

* avoid performance regression by batch updating slug atlas cache

* TextFlow: separate SLUG glyph batches to avoid interleaving HTML text drawing

* SLUG optimization: append instead of a full clone each generation

* trying out codex perf fix for linux wayland

* Disable SLUG glyps on Linux for now

* Fix Linux SLUG rendering, warmup, and promotion behavior

- re-enable Linux SLUG through a separate Linux-only DrawText helper
  instead of bloating the normal DrawText shader path
- preserve widget text styling on Linux SLUG by syncing common DrawText
  state into the helper, including base colors, gradients, and interactive
  states such as hover, focus, down, active, pressed, drag, empty, and
  disabled
- keep normal Linux UI text on the raster/MSDF path and only switch to
  SLUG above the Linux cutoff, while still falling back cleanly when SLUG
  data is unavailable
- fix Linux SLUG glyph placement so promoted text uses the correct glyph
  origin, layout position, and atlas packing
- add progressive SLUG warmup on Linux by budgeting glyph generation and
  uploads across redraws and falling back to raster/MSDF until SLUG data
  is actually ready
- lazily register and prewarm the shared Linux SLUG helper so app startup
  and first-use latency stay low
- opt only the Linux SLUG helper into async GL shader compilation and use
  parallel shader compile support when available, avoiding the large
  startup and first-tab stalls seen before
- fix Linux runtime shader issues caused by copied widget text shaders and
  custom get_color logic by using a shared helper shader with the expected
  text-state inputs
- stabilize Linux SLUG promotion by preventing stale retained areas,
  cleaning up raster/helper ownership correctly during draw, and
  shadow-promoting the first ready SLUG frame before making it visible
- eliminate the visible SLUG handoff flicker so Linux text now switches
  from raster/MSDF to SLUG without freezes or noticeable visual artifacts
- add a dedicated UIZoo SLUG tab with side-by-side below-cutoff and
  above-cutoff examples, plus diagnostic cases for plain labels,
  gradients, custom text shaders, and glyph/color probes
- keep the final diff focused by removing unrelated formatting-only churn
  from the worktree during cleanup

* Tighten Linux SLUG promotion and helper sync

- make Linux SLUG promotion state local to each DrawText instance
  instead of using a global per-redraw gate
- cache Linux SLUG helper shader field intersections so helper state
  syncing avoids repeated per-draw allocations and linear membership checks
- harden the shadow-promotion fallback path so failed helper batching
  only takes a single raster fallback path
- preserve DrawText memory alignment after adding Linux SLUG bookkeeping

* try to fix emoji on Android

* emoji fix take 2

* uizoo example: allow touch/drag scroll. Don't panic in FileTree demo

* Fix emoji on Android

* Windows: async HLSL shader compile + extend SLUG helper path to Windows

Fixes two major performance issues on Windows that made uizoo unusable on
first launch:

1. **60-75s startup stall** caused by synchronous `D3DCompile` of ~30+
   SLUG-bearing text shader variants on the UI thread before the window
   could present.
2. **3-4s hang when opening the SLUG tab** caused by synchronous compile
   of the fat DrawTextSlug helper shader the first time a SLUG glyph was
   needed.

Also fixes a latent HLSL-only `CreateInputLayout` E_INVALIDARG crash
triggered by shaders with >26 instance inputs (exposed by DrawTextSlug).

`DrawTextLinuxSlug` → `DrawTextSlug` and all `linux_slug_*` /
`LinuxSlug*` symbols dropped their `Linux` prefix. Cfg guards expanded
from `target_os = "linux"` to `any(target_os = "linux", target_os = "windows")`
so Windows now:

- uses the same lean base `DrawText` shader (SDF/MSDF only, no SLUG
  curve-solver HLSL inlined)
- uses a separate `DrawTextSlug` helper shader for the SLUG path
- has the same progressive glyph-build budget and DPI cutoff
  (`default_slug_new_glyphs_per_redraw`, `default_slug_min_dpxs_per_em`
  in `fonts.rs` now match `OsType::Windows` alongside the Linux variants)
- falls back to raster/MSDF while the SLUG helper shader or its glyph
  data isn't yet ready

macOS/iOS/Android/WASM paths are untouched — they still use the fat
all-in-one `DrawText` shader via `cfg(not(any(linux, windows)))`.

Added `AsyncHlslCompile` in `d3d11.rs` and an `async_hlsl_compile` field
on `CxOs`. Shaders flagged `async_compile: true` (the SLUG helper) now
dispatch to a background thread per shader via `std:🧵:Builder`
(named `hlsl-compile-<id>` for debugging). Workers call `D3DCompile`
off the UI thread, write the resulting DXBC to the on-disk cache, and
send only a status result (not the bytes themselves — SLUG is ~240 KB
and ferrying it through the channel is wasteful) back via an mpsc
channel guarded by a `Mutex`.

`hlsl_compile_shaders` drains completed results at the top of each
call, constructs `CxOsDrawShader` objects on the main thread (the
bytes come from the cache-hit path in `CxOsDrawShader::new`), and
triggers `redraw_all()` so widgets whose shaders just became ready
get re-rendered. The existing `sh.os_shader_id.is_none()` guard in
`render_view` handles skipping the draw call while a shader is
pending.

Added `Cx::is_draw_shader_window_ready()` on Windows for the SLUG
helper's readiness check; on Windows it's simply
`os_shader_id.is_some()` since HLSL compile is either synchronous
(cache hit) or tracked via the async path.

Cold-start still compiled 30+ shaders synchronously (parallelized via
`std:🧵:scope`) which took ~5-10s because FXC's per-call speed is
the bottleneck and parallelism helps less than expected. Now
`hlsl_compile_shaders` partitions queued shaders by cache state:

- cache hit → sync path: disk read + D3D11 object creation, a few ms
- cache miss OR `async_compile: true` → async path: worker thread

On a fully cold cache, every shader is a cache miss → the window
presents on the first frame with no compile work on the UI thread.
Widgets fill in over the next ~1-2s as their shaders become ready.
On a warm cache every shader is a hit → instant startup as before.

Added `shader_bytes_cached()` for cheap existence checking of the
cache entries.

`d3d_compile_hlsl` now passes `D3DCOMPILE_SKIP_OPTIMIZATION`. FXC's
optimizer is what makes individual compiles burn hundreds of ms to
seconds on text shaders with loops; UI shaders don't benefit enough
from it to justify the cold-cache cost. If a specific shader is later
shown to be a runtime hotspot, the fix is to recompile it optimized
on a background thread and hot-swap, not to pay the cost upfront for
every shader.

Bumped `CACHE_KEY_VERSION` to 2 so pre-existing `.dxbc` blobs compiled
with the old flags are invalidated cleanly on upgrade.

`d3d11.rs` used its own `index_to_char(i) = i + 'A'` which produced
invalid HLSL semantic names (`[`, `\`, `]`, …) past 26 inputs, while
the HLSL generator in `shader_hlsl.rs` already used a correct
multi-character scheme (`A..Z, AA..AZ, BA..`). `CreateInputLayout`
returned E_INVALIDARG because the names didn't match. Replaced with
`makepad_script::shader_hlsl::index_to_semantic` so both sides of
the binding agree.

This was a latent bug — no existing shader had >26 instance inputs
until `DrawTextSlug` (which inherits many interactive-state fields
from Label-derived shaders). Linux/GLSL is unaffected because GLSL
binds by identifier, not semantic name.

- Hoisted `d3d_compile_hlsl`, `hlsl_cache_key`, and
  `get_or_compile_shader_bytes` out of `CxOsDrawShader::new` to module
  scope so they can be shared with the async worker.
- Compute `hlsl_cache_key` once per shader during partition and reuse
  at dispatch instead of recomputing.
- Scoped borrows in the async drain loop eliminate mapping/bindings
  clones.

- `platform/src/os/windows/d3d11.rs` — compile pipeline, async infra,
  semantic-name fix
- `platform/src/os/windows/windows.rs` — `async_hlsl_compile` field on
  `CxOs`
- `draw/src/shader/draw_text.rs` — rename `LinuxSlug*` → `Slug*`,
  expand cfg gates
- `draw/src/text/fonts.rs` — extend SLUG cutoff/budget defaults to
  Windows

No changes to macOS, iOS, Android, or WASM paths.
2026-04-16 22:50:48 +02:00
Kevin Boos
293804f044
Fix iOS touch hit-test and window geometry source (#1047)
Two independent iOS touch-input correctness fixes.

1. Hit-test: stop inflating widget bounds by touch radius

   `Cx::hits_with_options_and_test` was inflating every widget's
   clickable rect outward by `touch.radius` on all four sides, where
   `radius` comes from `UITouch.majorRadius` on iOS (and the Android
   equivalent). On real fingers this is 5-15pt, but the iOS Simulator
   synthesizes mouse clicks as touches with `majorRadius` ~25-40pt, so
   every button in the simulator captured clicks ~30pt outside its
   visible bounds — a click well above or below the Upload Avatar
   button still activated it.

   Remove the inflation in both TouchState::Start and TouchState::Stop
   and hit-test against the touch centroid only. This matches UIKit/
   AppKit native behavior; Apple's HIG and Material Design already
   require touch targets large enough that hidden inflation isn't
   needed. Apps that want explicit hit padding can still pass it via
   `HitOptions::margin`. `touch.radius` is still populated and
   delivered to apps that want it for visual feedback.

   Affected platforms: iOS, Android, web touch. Desktop mouse paths
   (MouseDown/Up) never touched this code.

2. Window geometry: read from MTKView, not UIScreen

   `IosApp::check_window_geom` was reading `inner_size` from
   `UIScreen.mainScreen.bounds`, which describes the *physical screen*
   rather than the app's drawing surface. On iPad Split View, Slide
   Over, Stage Manager, and multi-scene apps the window is a fraction
   of the screen, so `inner_size` could disagree with the MTKView's
   actual bounds — introducing a constant offset between layout and
   the touch coordinate space (UITouch `locationInView:` is always
   view-local).

   Read `bounds`, `contentScaleFactor`, and `safeAreaInsets` from the
   MTKView itself, falling back to UIScreen only during the early-init
   window before the view exists.

   Also use the `size` parameter delivered to
   `mtkView:drawableSizeWillChange:` directly (converting pixels→points
   via `contentScaleFactor` from the same view) rather than re-querying.
   UIKit gives us the authoritative new size synchronously with the
   resize callback; re-reading any other source can race by one layout
   pass during rotation or multitasking transitions.

   Extract the common WindowGeom construction / first-draw / update_geom
   / callback-dispatch tail into `apply_new_window_geom`.
2026-04-16 20:51:13 +02:00
Kevin Boos
0136260f6a
Fully proper fix for black screen on Android start/resume (#1043)
* Another proper fix for black screen on Android start/resume

* Fix all Android surface artifacts on pause, resume, and cold start

* cleanup: remove java-level logging in MakepadActivity

* additional cleanup/improvements for android lifecycle stuff
2026-04-15 08:22:35 +02:00
Kevin Boos
3cf602a432
Windows: fix perf and flicker/stretch artifacts when resizing a window (#1036)
* WIP fixing performance issue on Windows OS when resizing app window

* Improved resize behavior (flickering/stretching) on Windows

* cleanup window-resize optimizations for Windows OS
2026-04-13 21:51:22 +02:00
Kevin Boos
113ab5c6ad
Fix Android platform errors, mostly no draw on start/resume (#1035)
* Android: fix nondeterminstic crashes when using a bad surface

Makepad apps on Android were randomly crashing within the `Cx::render_view`
callstack when the host Activity surface was recycled, e.g., on
background/foreground transitions, rotation, IME show/hide, etc.

Details of the change are generated below:
----

`SurfaceHolder.Callback.surfaceDestroyed` posted a fire-and-forget message
to the render thread and returned to Android immediately, leaving two
overlapping races:

1. The render thread could drain `SurfaceDestroyed` from the mpsc channel,
   call `destroy_surface()` (which does `eglMakeCurrent(NULL, NULL, NULL,
   NULL)` and nulls the EGL surface), then in the *same* `RenderLoop`
   iteration call `handle_drawing()` → `render_view()` and issue GL calls
   with no current EGL context.
2. Even when our Rust side was well-behaved, Android was free to recycle
   the underlying buffer queue the moment `surfaceDestroyed` returned to
   Java, while the render thread was still mid-frame against it.

**Layer 1 — Surface validity tracking.** Added `CxOs::surface_alive`,
flipped synchronously in `SurfaceCreated`/`SurfaceChanged`/`SurfaceDestroyed`
handlers, plus a `CxOs::has_drawable_surface()` helper that gates every
GL/Vulkan dispatch entry point: `main_loop`'s `handle_drawing()`,
`draw_pass_to_window_for_active_backend`, `draw_pass_to_texture_for_active_backend`,
`draw_pass_to_fullscreen`, and `eglSwapBuffers` in `present_window_for_active_backend`.

**Layer 2 — Synchronous Java↔Rust handshake.** `FromJavaMessage::SurfaceDestroyed`
now carries an `Arc<(Mutex<bool>, Condvar)>` ack channel. The JNI binding
blocks the Android UI thread on the condvar (2-second budget, well under
the 5-second ANR threshold) until the render thread confirms it has
released the surface. This is the same pattern `android.opengl.GLSurfaceView`
uses, and it closes the underlying-buffer-recycled-mid-frame race.

**Layer 3 — Defense-in-depth re-bind.** `draw_pass_to_fullscreen` now calls
a new fallible `try_make_current()` every frame, recovering from any GL
context drift caused by foreign code or our own teardown path, and
bailing cleanly if the bind fails instead of crashing inside the driver.

Verified all 5 gated entry points against the `openxr_render_loop` →
`openxr_handle_repaint` path:

- 4 entry points are unreachable in XR mode (XR uses its own swapchains
  and `xrEndFrame`, never `eglSwapBuffers` or the popup overlay path).
- `draw_pass_to_texture_for_active_backend` IS reachable (off-screen UI
  textures composited into the XR scene). To prevent these from being
  wrongly skipped in Vulkan+XR mode after the host surface is recycled,
  added an explicit XR escape hatch to `has_drawable_surface()`: when
  `in_xr_mode && openxr.session.is_some()`, return `true` based purely on
  `vulkan.is_some()`, ignoring the (intentionally nulled) `display.window`.
  This matches the existing `keep_xr_backend_alive` logic in the
  `SurfaceDestroyed` handler.

- `destroy_surface` is now idempotent (safe to call when already null).
- `make_current` asserts on null surface with a descriptive panic message
  instead of crashing inside EGL.
- Lifecycle handlers verify surface creation actually succeeded before
  flipping `surface_alive` to `true` (no false-positive ready signal).

Tested working on my OnePlus Open w/ Android 15.

-------------
* Other fixes: minor change to logging format to include level indicator
* Fix warning in cargo makepad android

* Fix Android platform errors, mostly no draw on start/resume

Also a small related optimization on iOS

------------

* Android: JNI method ID caching (`ndk_utils.rs`)
  * Rewrote the `call_method!` macro to cache `jmethodID` in a per-call-site `static AtomicPtr`. Previously, every JNI call allocated two `CString`s and called `GetObjectClass` + `GetMethodID` from scratch. Now these are resolved once and reused for all subsequent calls. Also deletes the local class reference after first resolution.

* Android: `to_java_update_tex_image` uses cached macro (`android_jni.rs`)
  * Replaced manual `GetObjectClass`/`CString::new`/`GetMethodID` calls with the now-cached `call_bool_method!` macro, eliminating per-frame JNI overhead for video texture updates.

* Android: Touch event coalescing (`android.rs`)
  * When draining pending messages before a RenderLoop frame, consecutive pure-Move touch events are now coalesced — only the last position is dispatched. Start/Stop events are never dropped. This reduces redundant event dispatch during active touch scrolling.

* Android: Black screen fix (`android.rs`)
  * Added `needs_first_draw` flag to `CxOs`. When a `RenderLoop` callback arrives but the surface isn't drawable, the flag is set. When the surface later becomes available, `redraw_all()` is called to ensure the first frame is painted. The flag is also set on `SurfaceDestroyed` so resuming from background always gets a guaranteed first frame.

* iOS: Remove unnecessary `passes_todo.clone()` (`ios.rs`)
  * Removed a redundant `Vec::clone()` in the popup pass draw loop — both the outer and inner loops borrow `passes_todo` immutably.
2026-04-13 21:51:09 +02:00
Kevin Boos
ccecc172e9
Avoid double-shutdown Event dispatch on WIndows (#1034)
Windows was issuing two shutdown events any time the window was closed,
so it no longer does that. Might've been my fault in a previous change,
not sure.
2026-04-13 21:50:55 +02:00
Admin
c925d2a56b mlx otw 2026-04-10 14:48:17 +02:00
Admin
747ef9b2e8 mlx 5x->2x 2026-04-10 14:46:22 +02:00
Kevin Boos
126e848063
Android: fix nondeterminstic crashes when using a bad surface (#1030)
Makepad apps on Android were randomly crashing within the `Cx::render_view`
callstack when the host Activity surface was recycled, e.g., on
background/foreground transitions, rotation, IME show/hide, etc.

Details of the change are generated below:
----

`SurfaceHolder.Callback.surfaceDestroyed` posted a fire-and-forget message
to the render thread and returned to Android immediately, leaving two
overlapping races:

1. The render thread could drain `SurfaceDestroyed` from the mpsc channel,
   call `destroy_surface()` (which does `eglMakeCurrent(NULL, NULL, NULL,
   NULL)` and nulls the EGL surface), then in the *same* `RenderLoop`
   iteration call `handle_drawing()` → `render_view()` and issue GL calls
   with no current EGL context.
2. Even when our Rust side was well-behaved, Android was free to recycle
   the underlying buffer queue the moment `surfaceDestroyed` returned to
   Java, while the render thread was still mid-frame against it.

**Layer 1 — Surface validity tracking.** Added `CxOs::surface_alive`,
flipped synchronously in `SurfaceCreated`/`SurfaceChanged`/`SurfaceDestroyed`
handlers, plus a `CxOs::has_drawable_surface()` helper that gates every
GL/Vulkan dispatch entry point: `main_loop`'s `handle_drawing()`,
`draw_pass_to_window_for_active_backend`, `draw_pass_to_texture_for_active_backend`,
`draw_pass_to_fullscreen`, and `eglSwapBuffers` in `present_window_for_active_backend`.

**Layer 2 — Synchronous Java↔Rust handshake.** `FromJavaMessage::SurfaceDestroyed`
now carries an `Arc<(Mutex<bool>, Condvar)>` ack channel. The JNI binding
blocks the Android UI thread on the condvar (2-second budget, well under
the 5-second ANR threshold) until the render thread confirms it has
released the surface. This is the same pattern `android.opengl.GLSurfaceView`
uses, and it closes the underlying-buffer-recycled-mid-frame race.

**Layer 3 — Defense-in-depth re-bind.** `draw_pass_to_fullscreen` now calls
a new fallible `try_make_current()` every frame, recovering from any GL
context drift caused by foreign code or our own teardown path, and
bailing cleanly if the bind fails instead of crashing inside the driver.

Verified all 5 gated entry points against the `openxr_render_loop` →
`openxr_handle_repaint` path:

- 4 entry points are unreachable in XR mode (XR uses its own swapchains
  and `xrEndFrame`, never `eglSwapBuffers` or the popup overlay path).
- `draw_pass_to_texture_for_active_backend` IS reachable (off-screen UI
  textures composited into the XR scene). To prevent these from being
  wrongly skipped in Vulkan+XR mode after the host surface is recycled,
  added an explicit XR escape hatch to `has_drawable_surface()`: when
  `in_xr_mode && openxr.session.is_some()`, return `true` based purely on
  `vulkan.is_some()`, ignoring the (intentionally nulled) `display.window`.
  This matches the existing `keep_xr_backend_alive` logic in the
  `SurfaceDestroyed` handler.

- `destroy_surface` is now idempotent (safe to call when already null).
- `make_current` asserts on null surface with a descriptive panic message
  instead of crashing inside EGL.
- Lifecycle handlers verify surface creation actually succeeded before
  flipping `surface_alive` to `true` (no false-positive ready signal).

Tested working on my OnePlus Open w/ Android 15.

-------------
* Other fixes: minor change to logging format to include level indicator
* Fix warning in cargo makepad android
2026-04-10 08:13:14 +02:00
Kevin Boos
3d81877bf4
Avoid re-entrant borrows of the IOS_APP global (#1025)
* Avoid re-entrant borrows of the IOS_APP global

I noticed this was happening any time the IME on iOS was used,
so I restructured those usages of IOS_APP to avoid them.
I then noticed that it could happen in other places, so I refactored
those as well.

* Fix missing iOS plist entry
2026-04-09 14:45:37 +02:00
Kevin Boos
d12fa28a8e
Packaging directory-related fixes (for robius-packaging-commands to work) (#1024)
* Packaging directory-related fixes (to allow robius-packagin-commands to work)

* use proper resource loading for macOS packaged apps via NSBundle
2026-04-09 14:45:23 +02:00
Kevin Boos
7b5b05fb29
Fix mouse wheel scrolling on Linux Wayland (#1022)
Now the tab bar will scroll using all four mouse wheel directions
even on Wayland.
2026-04-08 07:36:04 +02:00
Kevin Boos
2374359993
Fix key repeat timer issue, and Event::Shutdown delivery (#1020)
Key repeat (holding down a key) did not work at all on Linux Wayland. The `RepeatInfo` event from the compositor was commented out, and all key events had `is_repeat: false` hardcoded.

- **`xkb_sys.rs`**: Added `xkb_state_get_keymap` FFI binding and a `key_repeats()` method on `XkbState` to check whether a key supports repeat (e.g., modifiers don't repeat).
- **`wayland_state.rs`**:
  - Added `KeyRepeatState` struct and `KEY_REPEAT_TIMER_ID` constant.
  - Added `key_repeat_rate`, `key_repeat_delay`, and `key_repeat` fields to `WaylandState`.
  - Handled the previously-ignored `RepeatInfo` event to store the compositor's repeat rate/delay.
  - On key press: start a one-shot timer with the repeat delay if the key supports repeat.
  - On key release / keyboard leave: cancel the repeat timer.
  - Added `handle_key_repeat_timer()` which fires `KeyDown(is_repeat: true)` and `TextInput` events, transitioning from the initial delay to a steady-state repeating timer.
- **`wayland_app.rs`**: Intercept the key repeat timer ID in the event loop and route it to `handle_key_repeat_timer()` instead of sending a generic `Timer` event.

- **`raw_input.rs`**: The evdev backend already received `KeyAction::KeyRepeat` from the OS but hardcoded `is_repeat: false` and didn't emit `TextInput` events. Fixed both.

- **`select_timer.rs`**: Fixed a pre-existing bug in `stop_timer` where removing a timer from the delta chain didn't adjust the successor's `delta_timeout`. This caused successor timers to fire early by the removed timer's delta. Also changed `update_timers` to use `pop_front()` instead of `stop_timer()` internally, since `select_time_used` already accounts for the removed timer's delta.

--------------

On Linux Wayland (and several other platforms), Makepad apps never received
`Event::Shutdown` when the window was closed via the client-side decoration
close button or when the app called `cx.quit()`.

When the CSD close button is clicked, it pushes `CxOsOp::CloseWindow`, which
is processed by `handle_platform_ops()`. When the last window is removed (or
`CxOsOp::Quit` is handled), this function returns `EventFlow::Exit`. However,
most backends did **not** call `Event::Shutdown` before exiting — only macOS
did it correctly.

Added `call_event_handler(&Event::Shutdown)` in the `handle_platform_ops() → Exit`
path for all affected backends, matching the existing macOS behavior:

- **Linux Wayland** (`linux_wayland.rs`) — added Shutdown call
- **Linux X11** (`linux_x11.rs`) — added Shutdown call
- **Windows** (`windows.rs`) — added Shutdown call
- **Linux Direct** (`linux_direct.rs`) — added Shutdown call
- **OpenHarmony** (`open_harmony.rs`) — added Shutdown call after main loop exit
  (this backend uses `self.os.quit` instead of `EventFlow::Exit`)

- **macOS** — already correct
- **Android** — Shutdown is delivered via `FromJavaMessage::Destroy`
- **iOS / tvOS / Web** — different lifecycle models where explicit shutdown
  doesn't apply (suspended by OS, or no reliable browser mechanism)
2026-04-08 07:35:47 +02:00
Kevin Boos
cc60726b35
Support scrolling while centered, both vertically and horizontally (#1017)
* Support scrolling while centered, both vertically and horizontally

The previous turtle logic didn't allow you to center-align a view
while still making it scrollable. This small fix supports that now,
meaning that you can have:
* a vertically-centered view (`Align: { y: 0.5 }`) that is y-scrollable
* a horizontally-centered view (`Align: {x: 0.5 }`) that is x-scrollable

Also added some simple examples of this to `uizoo`

* fix iOS build
2026-04-07 09:32:47 +02:00
Kevin Boos
fa68f930fa
Show "ghost" dock tab during drag animation. Fix drag-n-drop rules, target zones, etc (#1015)
* Dock: add touch support for Tab/Tab bar interactions (scroll, drag/drop)

Details below:

1. **Finger-based tab drag-and-drop via long press** (tab.rs, android.rs, ios.rs):
   - On touch devices, tab dragging now requires a long press before moving,
     distinguishing it from scroll gestures.
   - Added internal drag-and-drop support for Android and iOS backends,
     synthesizing Drag/Drop/DragEnd events from touch move/up, matching the
     existing Linux X11/Wayland approach.

2. **Finger-based drag-scrolling through the tab bar** (tab.rs, tab_bar.rs):
   - A finger down + move (without long press) on a tab now scrolls the tab bar
     horizontally instead of initiating a tab drag.
   - Includes flick-to-scroll with velocity and decay for natural momentum.
   - Touch tab selection is deferred to finger-up and only fires on a clean tap
     (no long press, no scroll gesture), so scrolling/dragging doesn't
     accidentally select tabs.

3. **Horizontal scroll input for tab bar** (scroll_bar.rs):
   - When `use_vertical_finger_scroll` is enabled on a horizontal scroll bar,
     both horizontal (trackpad) and vertical (mouse wheel) scroll inputs are
     accepted, so trackpad users can scroll the tab list in either direction.

* fix drag/drop on macOS by using internal drag logic.

Fix ghost tab on dock to be much cleaner in terms of behavior

* Cleanup dock tab drag&drop behavior

Make platforms consistent. Switch macOS to internal drag item tracking
instead of OS-native (just for the dock for now).

Ensure ghost tab that gets drawn is consistently hidden (instantly)
upon being dropped in an invalid target zone.
2026-04-06 23:00:13 +02:00
Kevin Boos
ab006d0e25
Dock: add touch support for Tab/Tab bar interactions (scroll, drag/drop) (#1013)
Details below:

1. **Finger-based tab drag-and-drop via long press** (tab.rs, android.rs, ios.rs):
   - On touch devices, tab dragging now requires a long press before moving,
     distinguishing it from scroll gestures.
   - Added internal drag-and-drop support for Android and iOS backends,
     synthesizing Drag/Drop/DragEnd events from touch move/up, matching the
     existing Linux X11/Wayland approach.

2. **Finger-based drag-scrolling through the tab bar** (tab.rs, tab_bar.rs):
   - A finger down + move (without long press) on a tab now scrolls the tab bar
     horizontally instead of initiating a tab drag.
   - Includes flick-to-scroll with velocity and decay for natural momentum.
   - Touch tab selection is deferred to finger-up and only fires on a clean tap
     (no long press, no scroll gesture), so scrolling/dragging doesn't
     accidentally select tabs.

3. **Horizontal scroll input for tab bar** (scroll_bar.rs):
   - When `use_vertical_finger_scroll` is enabled on a horizontal scroll bar,
     both horizontal (trackpad) and vertical (mouse wheel) scroll inputs are
     accepted, so trackpad users can scroll the tab list in either direction.
2026-04-06 16:29:13 +02:00
Admin
c9cabd2554 remove logs 2026-04-05 11:36:11 +02:00
Admin
3968a4aaba stdin 2026-04-05 11:30:53 +02:00
Admin
73544cbf60 churn 2026-04-05 11:28:47 +02:00
Admin
641a158ec5 churn 2026-04-05 11:28:47 +02:00
Admin
26cd960c48 iterating 2026-04-05 11:28:47 +02:00
Kevin Boos
7bcacc33f8
Properly animate caption bar when entering/exiting macOS fullscreen (#1005)
add handlers for "will enter/exit fullscreen" instead of just handling
"did" enter/exit, in order to properly animate. Otherwise it looks
janky for a split second where the traffic light buttons are on top of
the old app content before it refreshes.
2026-04-02 08:31:10 +02:00
Kevin Boos
0f2939945c
Expose window chrome button bounding box in WindowGeom (#1001)
* Expose window chrome button bounding box in `WindowGeom`

This allows apps that wanna draw something in the title/caption bar
to do so in a proper way without potentially drawing over the native
window chrome buttons (on macOS, the traffic light buttons).
Without this it'd be pretty tough to figure that out.

This also auto-sets the caption bar height to be tall enough such that
the window chrome / traffic light buttons are perfectly vertically-centered
in the middle of the caption bar. This was needed on macOS to prevent
things from looking janky as hell on newer macOS versions, which changed
the default size of the traffic chrome buttons.
It'll also be useful for drawing things in the caption bar on linux
or windows too.

Full change set:

- `widgets/src/window.rs`: Hide the caption bar on `LinuxWindow` when
  `!custom_window_chrome` (X11 — WM provides native decorations) directly in
  `sync_caption_bar_state`, removing the need for apps to do this manually.
- `event/window.rs`: Add `window_chrome_buttons: Rect` to `WindowGeom` —
  the bounding box of the OS/app-drawn window chrome buttons in logical window
  coordinates (top-left origin). Non-zero on macOS (traffic lights), Windows
  (min/max/close), and Wayland with `custom_window_chrome`. Zero on all other
  platforms (X11, LinuxDirect, mobile, web). Documented with per-platform
  details and guidance on how to use it for caption-bar layout margins.
- `macos_window.rs`: Add `traffic_lights_geom()` — queries all three
  traffic-light buttons via `standardWindowButton:`, converts their frames
  to Makepad's coordinate system via `convertRect:fromView:`, and returns
  the bounding box as a `Rect`.
- `win32_window.rs`: Populate `window_chrome_buttons` with the right-aligned
  138×29 px bounding box of the three Makepad-drawn caption buttons.
- `linux_wayland.rs`: Populate `window_chrome_buttons` in the
  `WindowGeomChange` handler when `custom_window_chrome: true`, using the
  same right-aligned 138×29 px layout.
- `cx_api.rs`: Add `update_caption_bar_height_script_value()` to push a
  measured height into `mod.widgets.CAPTION_BAR_HEIGHT` on the script heap.
- `window.rs` (DSL): Declare `mod.widgets.CAPTION_BAR_HEIGHT = 27.0` in the
  `script_mod!` block and change `caption_bar.height` from the hardcoded `27`
  to `(mod.widgets.CAPTION_BAR_HEIGHT)`. On `WindowGeomChange`, derive the
  default caption bar height from `window_chrome_buttons` using equal
  top/bottom padding (`pos.y * 2 + size.y`) and trigger a script reapply.
- `platform/src/lib.rs`: Export `LinuxWindowParams`, `WindowGeom`,
  and `SafeAreaInsets`.

* Fix calculation of title bar height based on buttons

ensure dynamic override actually propagates via Rust code

* clearly define system-calculated caption bar height vs manual override

* Fix window drag move bounds to match the caption bar area

remove excess debug logs
2026-04-01 23:11:37 +02:00
Admin
3f2baab26d xr llama and slug 2026-04-01 12:19:03 +02:00
Admin
cb3b36d241 llama + xr 2026-04-01 12:19:03 +02:00
Admin
95c822450b fixup 2026-04-01 12:19:03 +02:00
Admin
5f20c2b6da xr works 2026-04-01 12:19:02 +02:00
Admin
c8280ee338 testing x client 2026-04-01 12:19:02 +02:00
Admin
1c7835fca9 working emitters 2026-04-01 12:19:02 +02:00
Kevin Boos
507bcf35d1
Choose sane defaults for platform-specific title/caption bar config (#1000)
Primarily on Linux, ensure that we show the title/caption bar
and draw it within Makepad (i.e., client-side drawing) if the
DE/WM doesn't show it by default.
This should make things behave as expected on Linux X11 and Wayland
both.
2026-04-01 00:42:29 +02:00
Kevin Boos
f99dee329c
Remove busy-wait loops on Linux (x11 and wayland) (#998)
Tested working with Robrix and a few makepad examples
2026-03-31 08:57:51 +02:00
Kevin Boos
191ac72bf9
Introduce knowledge of device screen bounds/"safe inset areas" (#990)
* Introduce knowledge of device screen bounds/cutous/"safe inset areas"

Tested working on iOS, implemented for Android but not yet tested.

The approach may need to be improved, because it currently restricts
the whole app window to being fully within the safe areas.
We may not necessarily want that, or if we do, then we probably also
need to support setting the base color of the reserved system areas
(beneath the app bounds and above in the notification bar area).

* Use metal scissor rect to prevent SVGs/icons from being mis-drawn in safe areas

This prevents anything from being accidentally drawn in the safe
inset areas when the pass clear_color is transparent. Of course,
we can still draw the pass clear_color in those areas.

* Workaround: apply a scissor rect within safe inset area

Only apply it to clip any DrawSvg/DrawVector-specific draw calls
within the safe inset area.

This is unfortunately still just a hacky solution, because if we
actually do want to draw svg/vectors within that safe inset area,
then we won't be able to.

* Properly fix gpu artifacts when rendering SVGs

The `DrawSvg` vertex shader had a GPU fringe expansion pass designed for `fill_gpu()` mode, where fringe vertices encode per-vertex normals in the `v` and `stroke_dist` fields. SVG rendering used `fill_gpu()`, which produces **coincident-vertex fringe triangles** (body and outer fringe at the same CPU position, expanded on the GPU). These zero-area triangles caused **Metal GPU rasterization artifacts** — stray fragments appearing at unexpected screen positions.

**`draw/src/svg/render.rs`** — Switch SVG fill from `fill_gpu()` to `fill()`. Pre-computed fringe produces vertices at physically different positions (no coincident vertices).

**`draw/src/shader/draw_svg.rs`** — Remove the GPU fringe expansion code from the vertex shader. With pre-computed fringe, the `v` and `stroke_dist` fields are constants (`1.0` and `0.0`), not per-vertex normals. The expansion code was misinterpreting `v=1.0` as a horizontal normal, corrupting vertex positions.

**`libs/apple_sys/src/lib.rs`** — Added `MTLScissorRect` struct (unused now but available for future use).

**`src/home/rooms_sidebar.rs`** — Changed shadow offset from `vec2(1.0, 0.0)` to `vec2(0.0, 10.0)` so the `RoundedShadowView` shadow only draws below the header, eliminating the gray line at the top of the screen (issue 1).

* Expose safe area inset padding to app, don't forcibly apply it to root window

* Fixed safe area insets padding, with support for rotation

We now make these values available to the app dev (see below)
instead of forcibly inserting them as padding on all root windows.

This will allow each app to choose how and when they want to apply said pad values
(or if they want to at all) in an easy way, both at the Splash level
or more dynamically/programmatically at the Rust level.

Required quite a few changes to how things work in the iOS platform plumbing,
also described below in the generated summary:

On iOS and Android, Makepad apps render content behind device cutouts (Dynamic Island, camera notch), home indicators, and rounded screen corners because the framework has no awareness of safe area insets.

Added platform-level safe area inset querying on iOS and Android, exposed the values through both the Splash DSL (`mod.widgets.SAFE_INSET_PAD_*`) and Rust (`cx.display_context.safe_area_insets`), and ensured they update correctly on device rotation.

**New types:**
- `UIEdgeInsets` struct in `libs/apple_sys` for Objective-C interop
- `SafeAreaInsets` struct in `platform/src/event/window.rs` (top/right/bottom/left in logical points)
- Added `safe_area_insets` field to `WindowGeom` and `DisplayContext`

**iOS (`platform/src/os/apple/ios/`):**
- Query `[UIView safeAreaInsets]` from the MTKView in `check_window_geom()`
- Added `viewSafeAreaInsetsDidChange` callback on `MakepadViewController` to detect inset changes on rotation
- Populate `display_context` before `Event::Startup` so values are available during app script initialization
- Fixed MTKView setup: removed redundant `addSubview:` (conflicted with `setRootViewController:`) and added autoresizing mask — both required for safe area propagation on rotation

**Android (`platform/src/os/linux/android/`):**
- Added `SafeAreaInsets` variant to `FromJavaMessage` and corresponding JNI function
- Java side (`ResizingLayout.onApplyWindowInsets`): queries `WindowInsets.Type.systemBars() | displayCutout()` and sends insets to Rust (converted from px to dp)
- Added `safe_area_insets` field to `CxOs`, populated on `SafeAreaInsets` message and included in `WindowGeom` construction
- Added `surfaceOnSafeAreaInsets` native method to `MakepadNative.java`

**Splash DSL variables (`widgets/src/lib.rs`):**
- `mod.widgets.SAFE_INSET_PAD_TOP`
- `mod.widgets.SAFE_INSET_PAD_BOTTOM`
- `mod.widgets.SAFE_INSET_PAD_LEFT`
- `mod.widgets.SAFE_INSET_PAD_RIGHT`
- Values read from `display_context` at widget module initialization (during `Event::Startup`)
- Updated on the script heap via `Cx::update_safe_inset_script_values()` on `WindowGeomChange`

**Rotation support:**
- Added `pending_script_reapply` flag on `Cx` — set when safe area insets change, checked at the end of the platform event loop iteration
- Fires a deferred `LiveEdit` event to re-evaluate and re-apply all Splash widget definitions with updated inset values
- Implemented in both iOS and Android event loops

**StackNavigationView fix (`widgets/src/stack_navigation.rs`):**
- Full-screen stack views now position at `max(safe_area_insets.top, parent_rect.pos.y)` instead of hardcoded `y: 0`, respecting both mobile safe areas and desktop title bars

**All other platforms:**
- Added `..Default::default()` to all `WindowGeom` constructors (macOS, Windows, Linux X11/Wayland/Direct, web, tvOS, OpenHarmony) so the new `safe_area_insets` field defaults to zeros
2026-03-31 08:57:36 +02:00
Admin
eddabcf8ca cleanup 2026-03-29 22:57:11 +02:00
Admin
d0785c5212 cleanup 2026-03-29 22:53:22 +02:00
Admin
ebcf0d58ac cleanup 2026-03-29 22:47:40 +02:00
Admin
3a29497923 optimize 2026-03-29 22:12:33 +02:00
Admin
f8ffda732a optimisations 2026-03-29 21:36:19 +02:00
Admin
0fdc86b528 optimisations 2026-03-29 21:01:06 +02:00
Admin
d83941cf7a optimisations 2026-03-29 20:27:52 +02:00
Admin
3e7fb23e95 fixing tracing 2026-03-29 18:06:14 +02:00
Admin
cf1b38f9d0 deptmap tweaks 2026-03-29 15:47:27 +02:00
Admin
c352bf75e8 clean maps lock 2026-03-28 22:56:30 +01:00
Admin
bc64ac1164 fix refactor 2026-03-28 21:45:27 +01:00