Host the craft-ui runtime: install, frame input, close path, update dialogs on a DialogHost, fonts through craft_ui::fonts::load, app-local capture slot and font menu

This commit is contained in:
aiongg
2026-11-24 16:54:17 +00:00
parent d7470ccc3b
commit b119944dc9
17 changed files with 503 additions and 93 deletions
+4 -1
View File
@@ -16,7 +16,6 @@ craft-mime = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs",
craft-pdf = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-jsonrpc = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-quit = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-dpx = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-ps = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", default-features = false, features = ["read"] }
@@ -129,6 +128,10 @@ half = "2.7"
# Shared UI and the complete egui family select reviewed immutable commits below.
craft-ui = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-behavior = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-host = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-keymap = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-theme = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
craft-window = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" }
# `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()`
# and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate.
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
+4 -2
View File
@@ -113,8 +113,8 @@ impl eframe::App for WebApp {
}
/// The browser host's logic tick: run queued UI actions, tick the shared app, poll API replies, flush Render
/// Queue downloads, persist the session snapshot when enabled, publish GPU/frame-worker/disk-cache info and close
/// the IME pass.
/// Queue downloads, persist the session snapshot when enabled, publish GPU/frame-worker/disk-cache info, close
/// the IME pass and run the root window's close path.
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
let actions = ACTIONS.with(|a| std::mem::take(&mut *a.borrow_mut()));
for f in actions {
@@ -146,6 +146,7 @@ impl eframe::App for WebApp {
diskcache::configure(d.disk_cache_enabled, d.disk_cache_max_gb, storage::quota());
api::set_info("diskCache", diskcache::stats());
self.app.finish_ime_logic(ctx);
self.app.close_path(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
@@ -277,6 +278,7 @@ pub async fn start(canvas_id: String) -> Result<(), JsValue> {
canvas,
eframe::WebOptions::default(),
Box::new(move |cc| {
effectcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
EffectcraftApp::install_ime_reset_hooks(&cc.egui_ctx);
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
// The page owns this shared presentation device; worker devices retain their
+3 -2
View File
@@ -299,6 +299,7 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result {
"EffectCraft",
options,
Box::new(move |cc| {
effectcraft_ui_egui::framework::install(&cc.egui_ctx)?;
EffectcraftApp::install_ime_reset_hooks(&cc.egui_ctx);
match &cc.wgpu_render_state {
Some(rs) => {
@@ -548,7 +549,7 @@ struct Desktop {
impl eframe::App for Desktop {
/// The desktop host's logic tick: update the macOS menu bar, run the shared app tick, close the IME pass, show the
/// file dialogs asked for and, last, hand a close to the platform quit.
/// file dialogs asked for and, last, the root window's close path.
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
self.menu_sync.before(&mut self.app, |app| self.menu.update(app, ctx));
@@ -560,7 +561,7 @@ impl eframe::App for Desktop {
if let Some(asked) = &self.file_dialogs {
file_dialogs::show_asked(asked, frame, ctx);
}
effectcraft_ui_egui::panels::unsaved::quit_on_close(ctx);
self.app.close_path(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
+1 -1
View File
@@ -440,7 +440,7 @@ mod tests {
// The decoded image has already taken four pixels from this budget.
let mut pixels_left = 4;
let mut warnings = vec![];
let clamped = cm::TextureRef { image: 0, uv_set: 0, wrap: [cm::Wrap::Clamp; 2] };
let clamped = cm::TextureRef { image: 0, uv_set: 0, wrap: [cm::Wrap::Clamp; 2], transform: None };
let first = ensure_texture(&scene, &decoded, clamped, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).unwrap();
let shared = ensure_texture(&scene, &decoded, clamped, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).unwrap();
+4 -1
View File
@@ -13,7 +13,10 @@ workspace = true
craft-mime = { workspace = true }
craft-ui = { workspace = true }
craft-behavior = { workspace = true }
craft-quit = { workspace = true, features = ["ui"] }
craft-host = { workspace = true }
craft-keymap = { workspace = true }
craft-theme = { workspace = true }
craft-window = { workspace = true }
effectcraft-time = { workspace = true }
effectcraft-geom = { workspace = true }
effectcraft-color = { workspace = true }
+13 -5
View File
@@ -128,6 +128,8 @@ impl EffectcraftApp {
template_thumbs: Default::default(),
template_list: None,
updates_rt: updates_ui::Runtime::default(),
framework_dialogs: craft_ui::dialog::DialogHost::new(),
framework_host: crate::framework::host(),
}
.with_ui_commands()
}
@@ -158,10 +160,12 @@ impl eframe::App for EffectcraftApp {
}
}
/// Feed pending synthetic input into `raw_input` only once fonts are ready (so a non-drawing pass never consumes
/// Hand the runtime this frame's root values (`before_input`), then feed pending synthetic input into `raw_input`
/// only once fonts are ready (so a non-drawing pass never consumes
/// a batch), then prepare pointer wrapping; ending a numeric scrub clears the history merge key so the next edit
/// starts a new undo step.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
self.before_input(ctx);
raw_input.events.append(&mut self.forwarded.events);
raw_input.dropped_files.append(&mut self.forwarded.files);
let injected = self.synthetic_in_flight || !self.synthetic.is_empty();
@@ -177,19 +181,23 @@ impl eframe::App for EffectcraftApp {
}
}
/// The logic-only tick: run `tick`, close the IME pass with `finish_ime_logic` and, last, hand a close to the
/// platform quit (`panels::unsaved::quit_on_close`). It does not read pass-time
/// input state (events, pointer and time are stale here), only the viewport information eframe refreshed.
/// The logic-only tick: run `tick`, close the IME pass with `finish_ime_logic` and, last, the root window's close
/// path (`close_path`, which asks about unsaved changes, and on macOS quits through the platform). It does not
/// read pass-time input state (events, pointer and time are stale here), only the viewport information eframe
/// refreshed. A close request must be answered while hidden too; an answered file dialog can change the project,
/// so the tick's dialog answers run first.
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
// Never `ctx.input(|i| i.time)` here: `Context::run_logic` leaves events, pointer state and
// time at the previous full pass's values (only the viewport information is refreshed).
self.tick(ctx, frame);
self.finish_ime_logic(ctx);
crate::panels::unsaved::quit_on_close(ctx);
self.close_path(ctx);
}
/// Draw one UI pass through `draw`.
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
#[cfg(not(target_arch = "wasm32"))]
crate::framework::before_ui(ui.ctx(), &*frame);
self.draw(ui, frame);
}
}
+2 -12
View File
@@ -122,11 +122,6 @@ impl EffectcraftApp {
}
});
}
// Do not interpret a close as permission to abandon the still-running script. Once
// Stop finishes it, the normal unsaved-changes prompt can handle a new close request.
if ctx.input(|i| i.viewport().close_requested()) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
self.drain_control(ctx, self.now);
ctx.request_repaint_after(std::time::Duration::from_millis(50));
}
@@ -187,9 +182,6 @@ impl EffectcraftApp {
self.apply_gpu_failure(ctx);
if self.gpu_failure_applied == Some(true) {
self.close_after_device_loss(ctx);
// On macOS the app quits through `-[NSApplication terminate:]` instead of closing the
// window while AppKit's run loop is running (#341).
craft_quit::on_close_request(ctx);
return;
}
if self.session.script_ui.render_host.is_some() {
@@ -281,10 +273,6 @@ impl EffectcraftApp {
self.tick_script_render(ctx);
return;
}
// A close request (the window's button, Quit, `app.quit`) must be answered while hidden.
// An answered file dialog can change the project, so the answers above run first. The host
// calls `panels::unsaved::quit_on_close` last in its `logic`.
panels::unsaved::on_close_requested(self, ctx);
let title = panels::unsaved::window_title(self);
if title != self.window_title {
ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));
@@ -494,6 +482,7 @@ impl EffectcraftApp {
if let Some(rect) = crate::color_picker::take_automation(&ctx) {
self.auto.add("colorPicker.eyedropper", rect, "Eyedropper");
}
crate::framework::return_window_keys(&ctx);
let tab_had_widget_focus = ctx.egui_wants_keyboard_input();
menus::handle_shortcuts(self, &ctx);
if !ctx.input(|i| i.pointer.primary_down()) {
@@ -544,6 +533,7 @@ impl EffectcraftApp {
panels::learn::coach(self, &ctx);
let lift = panels::media_panels::import_card(self, ui, full);
self.draw_toast(ui, full, lift);
self.framework_dialogs.run(ui);
}
/// Workspace-layout auto-save: a background write that also runs while hidden, once the
+3 -4
View File
@@ -17,10 +17,9 @@ impl EffectcraftApp {
ctx.set_theme(theme::theme_preference(&p.appearance.appearance_mode, self.ui.theme.is_light()));
let tips = p.general.show_tool_tips;
ctx.all_styles_mut(|s| s.interaction.tooltip_delay = if tips { 0.5 } else { f32::INFINITY });
// Settings ▸ Appearance ▸ UI Scale (#284). egui's own Ctrl+= / Ctrl+- / Ctrl+0 zoom stays
// off: Ctrl+0 is Window ▸ Project, and the scale is a setting.
ctx.options_mut(|o| o.zoom_with_keyboard = false);
ctx.set_zoom_factor(p.appearance.ui_scale as f32 / 100.0);
// Settings ▸ Appearance ▸ UI Scale (#284) is the runtime's root scale (`frame_input`), which
// writes the zoom factor; egui's own Ctrl+= / Ctrl+- / Ctrl+0 zoom is off under the runtime
// (Ctrl+0 is Window ▸ Project).
self.ui.cache_when_idle = p.previews.cache_frames_when_idle;
self.ui.viewer.fast_preview = p.previews.fast_previews;
// No limit of its own below the common budget on the desktop, the browser's cap there:
+3 -3
View File
@@ -206,7 +206,7 @@ impl EffectcraftApp {
fn drain_completed_screenshots(&mut self, geom: DrawGeometry) {
let mut i = 0;
while i < self.pending_screenshots.len() {
let taken = self.pending_screenshots.get(i).and_then(|s| s.slot.as_ref()).and_then(craft_ui::capture::CaptureSlot::take);
let taken = self.pending_screenshots.get(i).and_then(|s| s.slot.as_ref()).and_then(crate::capture::CaptureSlot::take);
let Some(result) = taken else {
i += 1;
continue;
@@ -324,7 +324,7 @@ impl EffectcraftApp {
continue;
}
};
let (slot, callback) = craft_ui::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_SHOT_BYTES);
let (slot, callback) = crate::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_SHOT_BYTES);
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback));
let s = &mut self.pending_screenshots[i];
s.slot = Some(slot);
@@ -356,7 +356,7 @@ mod tests {
assert!(app.session.refuse_export(&text).is_ok());
let (tx, rx) = std::sync::mpsc::channel();
app.admit_screenshot(&ctx, Some(text.clone()), ShotTarget::Window, tx);
let (slot, callback) = craft_ui::capture::CaptureSlot::new(&ctx, egui::ViewportId::ROOT, MAX_SHOT_BYTES);
let (slot, callback) = crate::capture::CaptureSlot::new(&ctx, egui::ViewportId::ROOT, MAX_SHOT_BYTES);
let shot = app.pending_screenshots.last_mut().unwrap();
shot.issued = Some(geom);
shot.slot = Some(slot);
+211
View File
@@ -0,0 +1,211 @@
//! One-shot completion slots for `ui.screenshot` captures.
//!
//! The app keeps request ids, paths, deadlines, settling and budgets in its request record
//! (`control::PendingShot`). A slot only correlates one capture with one record, checks the image against
//! a per-image byte bound, and wakes the owning viewport.
//!
//! [`CaptureSlot::new`] sends nothing: send its callback with [`egui::ViewportCommand::Screenshot`]
//! when the capture is due. The callback holds only a weak reference to the slot, so dropping the
//! slot releases its image and makes a late result inert. Every retry needs a
//! fresh slot and callback.
//!
//! The slot holds a strong [`egui::Context`]: keep it in the app's request record, never in
//! `Context`-owned data, which would form a cycle.
use std::mem::size_of;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use egui::{Color32, ColorImage, Context, ScreenshotCallback, ViewportId};
/// Why a completed screenshot was rejected and released.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CaptureError {
/// The checked pixel count, or its byte count, overflowed `usize`.
DimensionsOverflow { width: usize, height: usize },
/// The pixel buffer does not match the dimensions, or the image has no area.
MalformedImage { width: usize, height: usize, pixels: usize },
/// The image is larger than the slot's per-image byte bound.
ImageTooLarge { bytes: usize, max_bytes: usize },
}
impl core::fmt::Display for CaptureError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::DimensionsOverflow { width, height } => {
write!(f, "screenshot dimensions {width}×{height} overflow the checked pixel or byte count")
}
Self::MalformedImage { width, height, pixels } => write!(f, "screenshot has {pixels} pixels for its {width}×{height} dimensions"),
Self::ImageTooLarge { bytes, max_bytes } => write!(f, "screenshot uses {bytes} bytes, over the {max_bytes}-byte per-image limit"),
}
}
}
impl std::error::Error for CaptureError {}
enum SlotState {
Pending,
Ready(Result<Arc<ColorImage>, CaptureError>),
Taken,
Cancelled,
}
struct Shared {
state: Mutex<SlotState>,
/// The live request owns the strong context; the callback only upgrades it briefly to wake.
context: Context,
viewport: ViewportId,
max_image_bytes: usize,
}
/// The live request side of a capture. Dropping it cancels the completion and releases any
/// retained image.
#[must_use = "the slot must be kept alive to receive and take the screenshot"]
pub(crate) struct CaptureSlot {
shared: Arc<Shared>,
}
impl CaptureSlot {
/// A completion slot for a capture of `viewport` and its one-shot callback. `max_image_bytes`
/// bounds this one image; the app reserves its aggregate budget itself.
pub(crate) fn new(context: &Context, viewport: ViewportId, max_image_bytes: usize) -> (Self, ScreenshotCallback) {
let shared = Arc::new(Shared { state: Mutex::new(SlotState::Pending), context: context.clone(), viewport, max_image_bytes });
let weak = Arc::downgrade(&shared);
let callback = ScreenshotCallback::new(move |image| complete(&weak, image));
(Self { shared }, callback)
}
/// The completed result, at most once; `None` while pending and after an
/// earlier take. The request record knows which.
pub(crate) fn take(&self) -> Option<Result<Arc<ColorImage>, CaptureError>> {
let mut state = lock(&self.shared.state);
if !matches!(&*state, SlotState::Ready(_)) {
return None;
}
match core::mem::replace(&mut *state, SlotState::Taken) {
SlotState::Ready(result) => Some(result),
_ => None,
}
}
}
impl Drop for CaptureSlot {
fn drop(&mut self) {
close(&self.shared);
}
}
impl core::fmt::Debug for CaptureSlot {
/// The viewport only: logging never holds or dumps screenshot contents.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CaptureSlot").field("viewport", &self.shared.viewport).finish_non_exhaustive()
}
}
/// Locks the slot state, recovering from poisoning. Release the guard before calling into the
/// context: a repaint observer may take or cancel re-entrantly.
fn lock(state: &Mutex<SlotState>) -> MutexGuard<'_, SlotState> {
state.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Marks the slot closed; the retained image drops after the mutex is released.
fn close(shared: &Shared) {
let previous = {
let mut state = lock(&shared.state);
core::mem::replace(&mut *state, SlotState::Cancelled)
};
drop(previous);
}
/// Checks and stores a completed image, then wakes the owning viewport, with the slot lock
/// released. A cancelled, taken or dropped slot stores nothing and does not wake.
fn complete(weak: &Weak<Shared>, image: Arc<ColorImage>) {
let Some(shared) = weak.upgrade() else { return };
let result = checked_image(image, shared.max_image_bytes);
let wake = {
let mut state = lock(&shared.state);
if matches!(&*state, SlotState::Pending) {
*state = SlotState::Ready(result);
true
} else {
false
}
};
if wake {
shared.context.request_repaint_of(shared.viewport);
}
}
/// `image` when it has area, its buffer matches its size, and its byte count (checked) is within
/// `max_image_bytes`.
fn checked_image(image: Arc<ColorImage>, max_image_bytes: usize) -> Result<Arc<ColorImage>, CaptureError> {
let [width, height] = image.size;
if width == 0 || height == 0 {
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
}
let pixels = width.checked_mul(height).ok_or(CaptureError::DimensionsOverflow { width, height })?;
let bytes = pixels.checked_mul(size_of::<Color32>()).ok_or(CaptureError::DimensionsOverflow { width, height })?;
if image.pixels.len() != pixels {
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
}
if bytes > max_image_bytes {
return Err(CaptureError::ImageTooLarge { bytes, max_bytes: max_image_bytes });
}
Ok(image)
}
#[cfg(test)]
mod tests {
use super::*;
fn image(size: [usize; 2]) -> Arc<ColorImage> {
Arc::new(ColorImage::filled(size, Color32::RED))
}
fn observe_repaints(ctx: &Context) -> Arc<Mutex<Vec<ViewportId>>> {
let requests = Arc::new(Mutex::new(Vec::new()));
let observed = requests.clone();
ctx.set_repaint_observer(move |info| observed.lock().unwrap().push(info.viewport_id));
requests
}
#[test]
fn a_completion_wakes_its_viewport_and_is_taken_once() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let viewport = ViewportId::from_hash_of("window");
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
assert!(slot.take().is_none(), "pending");
let shot = image([2, 1]);
callback.complete(shot.clone());
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &shot));
assert!(slot.take().is_none(), "taken once");
assert_eq!(*requests.lock().unwrap(), [viewport]);
}
#[test]
fn a_dropped_slot_releases_a_late_image_without_waking() {
let ctx = Context::default();
let requests = observe_repaints(&ctx);
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
drop(slot);
let late = image([2, 2]);
let weak = Arc::downgrade(&late);
callback.complete(late);
assert!(weak.upgrade().is_none());
assert!(requests.lock().unwrap().is_empty());
}
#[test]
fn oversized_malformed_and_overflowing_images_are_errors() {
let ctx = Context::default();
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
callback.complete(image([3, 3]));
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 36, max_bytes: 16 }))));
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [2, 2], source_size: egui::Vec2::ZERO, pixels: vec![Color32::RED; 3] }));
assert!(matches!(slot.take(), Some(Err(CaptureError::MalformedImage { width: 2, height: 2, pixels: 3 }))));
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
callback.complete(Arc::new(ColorImage { size: [usize::MAX, 2], source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
assert!(matches!(slot.take(), Some(Err(CaptureError::DimensionsOverflow { .. }))));
}
}
+153
View File
@@ -0,0 +1,153 @@
//! The craft-ui runtime, hosted from EffectCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`EffectcraftApp::before_input`] in `raw_input_hook`,
//! [`EffectcraftApp::close_path`] last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests
//! install with [`install_headless`]. The framework dialogs run on [`EffectcraftApp::framework_dialogs`] after
//! EffectCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of EffectCraft's own egui
//! widgets has the keyboard. [`return_window_keys`] puts the window's Escape and plain Enter back into egui's input
//! for EffectCraft's own handlers; the Composition viewer is declared to the runtime with [`host_canvas`], which keeps
//! Tab, the edit chords and the clipboard events in egui's input for EffectCraft's shortcuts.
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::Overrides;
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{CommandInput, CommandSet as _, NavCommand, QuitCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::system::WindowSystem;
use egui::ViewportId;
use crate::EffectcraftApp;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The id every OS window of the app carries, as the desktop entry and the update app name it.
const APP_ID: &str = "ai.storyteller.effectcraft";
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. EffectCraft's own definitions
/// ([`crate::theme::install`]) replace it before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>) -> Result<(), String> {
let spec = craft_ui::InstallSpec::new(shell, windows).app_id(APP_ID);
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Installs the runtime on the desktop window's context, once, before the first pass. EffectCraft keeps the system
/// title bar, so the window gets no frame decision.
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context) -> Result<(), String> {
let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env());
install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows))
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows)) {
log::warn!("{error}");
}
}
/// Who EffectCraft is to the framework's dialogs (the update dialogs show its name and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "effectcraft", name: "EffectCraft", version: env!("CARGO_PKG_VERSION") })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.effectcraft.png"))
.build(),
)
}
/// EffectCraft's own shortcut table keeps the keys the framework binds by default: Cmd+Q is `app.quit`, and F6 is
/// free for the user to bind there, so the framework's quit and pane moves are unbound. Overrides are keyed by command
/// id, which the command sets give.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
for id in [QuitCommand::Quit.id(), NavCommand::NextPane.id(), NavCommand::PreviousPane.id()] {
overrides.insert(id, Vec::new());
}
Arc::new(overrides)
})
.clone()
}
impl EffectcraftApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode and interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
embed::before_input(ctx, |output| self.frame_input(ctx, output));
}
/// The root values of this frame. EffectCraft registers no commands with the runtime (its own shortcut table runs
/// every key, [`command_overrides`]) and lets it toggle no chrome, so the output carries nothing it acts on. The
/// interface scale is Settings > Appearance > UI Scale; the runtime writes it to the context. While one of
/// EffectCraft's own dialogs or a command's file dialog is up, the runtime blocks the panels floated into windows
/// of their own.
pub(crate) fn frame_input(&mut self, ctx: &egui::Context, _output: FrameOutput) -> FrameInput {
let mode = if self.tokens.kind.is_light() { craft_theme::Mode::Light } else { craft_theme::Mode::Dark };
let scale = self.session.prefs.appearance.ui_scale as f32 / 100.0;
let root = RootEnv::new().mode(mode).scale(Scale::new(scale));
let app_modal = self.floats_blocked(ctx).then_some(ViewportId::ROOT);
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host)).app_modal(app_modal)
}
/// The framework's part of `App::logic`, after EffectCraft's own: the root window's close path
/// ([`crate::panels::unsaved::close_decision`]).
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || crate::panels::unsaved::close_decision(self));
}
}
/// Declares the Composition viewer `id`, drawn in this pass, as the window's document canvas. With nothing focused it
/// is the window's key target: Tab (the Composition Mini-Flowchart), the edit chords and the clipboard events stay in
/// egui's input for EffectCraft's shortcuts.
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) {
const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL);
craft_ui::runtime::focus::host_canvas(ctx, id, KEYS);
}
/// Puts the window's Escape and plain Enter (the keys the runtime routes to no component while nothing has framework
/// focus) back into egui's input as key presses, first in the pass, so EffectCraft's dialogs, popups, tools and
/// shortcuts read them from egui as they read every other key.
pub(crate) fn return_window_keys(ctx: &egui::Context) {
for (key, intent) in [(egui::Key::Escape, Intent::Cancel), (egui::Key::Enter, Intent::Submit)] {
if take_window_intent(ctx, intent) {
ctx.input_mut(|i| {
let modifiers = i.modifiers;
i.events.insert(0, egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers });
});
}
}
}
/// Takes the window's `intent` when it is there: no later reader sees it.
fn take_window_intent(ctx: &egui::Context, intent: Intent) -> bool {
let mut taken = false;
with_window_intents(ctx, false, |intents| {
taken = intents.take(intent.clone());
taken
});
taken
}
/// Whether the close decision is `Close`.
pub(crate) fn decide(close: bool) -> CloseDecision {
if close { CloseDecision::Close } else { CloseDecision::Hold }
}
+7 -1
View File
@@ -21,6 +21,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
pub mod audio;
pub mod automation;
pub mod bench;
pub(crate) mod capture;
pub mod color_picker;
pub mod control;
pub mod credits;
@@ -28,6 +29,7 @@ pub mod display_gpu;
pub mod dock;
pub mod dock_ui;
mod expression_diagnostics;
pub mod framework;
pub mod frames;
pub mod gpu_failure;
pub mod header;
@@ -103,7 +105,7 @@ struct PendingShot {
/// The geometry epoch bound to the issued capture command, if it was issued.
issued: Option<DrawGeometry>,
/// The shared completion slot; dropping it cancels a late callback.
slot: Option<craft_ui::capture::CaptureSlot>,
slot: Option<crate::capture::CaptureSlot>,
/// Bytes reserved against [`EffectcraftApp::shot_bytes`].
reserved_bytes: usize,
/// Geometry retries used.
@@ -472,6 +474,10 @@ pub struct EffectcraftApp {
/// Audio scrubbing's open output (Ctrl/Cmd-drag the current time, `playback.scrubAudio`).
pub scrub: Option<audio::AudioScrub>,
pub(crate) updates_rt: updates_ui::Runtime,
/// The framework dialogs (the update dialogs), run once per pass after EffectCraft's own UI.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Who EffectCraft is to the framework's dialogs.
pub(crate) framework_host: std::sync::Arc<craft_host::Host>,
/// Audio panel VU meters.
pub meter: audio::Meter,
/// Waveform peak summaries per footage item (see `panels::waveform`).
+28 -6
View File
@@ -795,11 +795,6 @@ pub(super) fn font_picker(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: egui:
let changed = search.changed();
let mut open = true;
// The search lives in the field; the menu's header is the filter row, its list the fonts.
let menu = craft_ui::combo::Menu::new(ui, &search)
.open(&mut open)
.height(380.0)
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.style(egui::style::StyleModifier::default());
let app_ref = &mut *app;
let header = |ui: &mut egui::Ui| {
ui.set_width(rect.width().max(180.0));
@@ -922,7 +917,7 @@ pub(super) fn font_picker(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: egui:
}
chosen
};
let chosen = menu.show_ui_with_header(header, list).flatten();
let chosen = header_menu(&search, &mut open, FONT_MENU_HEIGHT, header, list).flatten();
if chosen.is_some() || !open || escape {
ui.data_mut(|d| {
d.insert_temp(id.with("open"), false);
@@ -1095,6 +1090,33 @@ fn fit_preview(lines: &[Vec<[f32; 2]>], room: Rect, baseline: f32) -> Option<(f3
Some((k, o))
}
/// The tallest the font menu gets, its header included.
const FONT_MENU_HEIGHT: f32 = 380.0;
/// A menu under `field` while `open` is true: `header` stays at the top and the list it hands its result to scrolls
/// under it, the whole menu up to `height` tall and at least as wide as the field. A click outside closes it (`open`
/// turns false). Returns what `list` returned, or `None` while the menu is closed.
fn header_menu<H, R>(
field: &egui::Response,
open: &mut bool,
height: f32,
header: impl FnOnce(&mut egui::Ui) -> H,
list: impl FnOnce(&mut egui::Ui, H) -> R,
) -> Option<R> {
egui::Popup::from_response(field)
.open_bool(open)
.width(field.rect.width())
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show(|ui| {
ui.set_min_width(ui.available_width());
ui.set_max_height(height);
let header = header(ui);
egui::ScrollArea::vertical().max_height(ui.available_height().max(0.0)).show(ui, |ui| list(ui, header)).inner
})
.map(|shown| shown.inner)
}
#[cfg(test)]
mod tests {
use super::*;
+25 -37
View File
@@ -55,25 +55,24 @@ fn ask(app: &mut EffectcraftApp, id: &str, params: &Value) -> bool {
true
}
/// The window's close button (and Quit, which closes it): keep the window open and ask.
pub fn on_close_requested(app: &mut EffectcraftApp, ctx: &egui::Context) {
if !ctx.input(|i| i.viewport().close_requested()) || app.dialog_state.unsaved.quitting {
return;
/// The root window's close decision, which the runtime's close path (`crate::framework`, `close_path`) asks when the
/// window's close button, Quit or `app.quit` closes the window. A lost graphics device and an answered Quit prompt
/// close; a running script render holds the window (a close is no permission to abandon the script, and once Stop
/// finishes it a new close is asked about as usual); a modified project holds it while the Unsaved Changes prompt
/// asks. On macOS a close that nothing holds quits through the platform (the runtime's close path).
pub fn close_decision(app: &mut EffectcraftApp) -> craft_ui::shell::embed::CloseDecision {
if app.device_lost_close.is_some() {
return crate::framework::decide(true);
}
if app.session.script_ui.render_host.is_some() {
return crate::framework::decide(false);
}
if app.dialog_state.unsaved.quitting {
return crate::framework::decide(true);
}
// Logged, so a window that closes on its own shows it (#234).
log::info!("the window was asked to close");
if ask(app, "app.quit", &json!({})) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
}
/// On macOS a close that nothing held open quits through `-[NSApplication terminate:]` instead:
/// closing the window while AppKit's run loop is running crashes on a Mac with a Touch Bar
/// (#341). `on_exit` still runs. A desktop host calls it last in `logic`, after
/// `EffectcraftApp::tick` (which runs [`on_close_requested`]) and its own work. Returns whether
/// that quit was scheduled; other platforms close the window as before.
pub fn quit_on_close(ctx: &egui::Context) -> bool {
craft_quit::on_close_request(ctx)
crate::framework::decide(!ask(app, "app.quit", &json!({})))
}
/// The project's display name: its file name, or `Untitled Project.ecproj`.
@@ -204,6 +203,7 @@ mod tests {
fn app() -> (EffectcraftApp, egui::Context) {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let app = EffectcraftApp::new(effectcraft_engine::Session::default());
crate::theme::install(&ctx, &app.tokens, crate::i18n::language(&app));
(app, ctx)
@@ -218,29 +218,17 @@ mod tests {
}
let mut out = ctx.run_ui(raw, |ui| {
app.auto.begin_frame();
on_close_requested(app, ui.ctx());
app.close_path(ui.ctx());
crate::panels::dialogs::show(app, ui.ctx());
});
out.textures_delta.clear();
out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.commands.contains(&egui::ViewportCommand::CancelClose))
}
/// One frame of the dialogs with the window's close button pressed, through
/// [`on_close_requested`] and then [`quit_on_close`] as the app runs them; returns whether the
/// close was canceled and whether the platform quit was scheduled.
fn close_frame(app: &mut EffectcraftApp, ctx: &egui::Context) -> (bool, bool) {
let mut raw = egui::RawInput::default();
raw.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close);
let mut quits = false;
let mut out = ctx.run_ui(raw, |ui| {
app.auto.begin_frame();
on_close_requested(app, ui.ctx());
quits = quit_on_close(ui.ctx());
crate::panels::dialogs::show(app, ui.ctx());
});
out.textures_delta.clear();
let canceled = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.commands.contains(&egui::ViewportCommand::CancelClose));
(canceled, quits)
/// One frame of the dialogs with the window's close button pressed, through the runtime's close path as the app
/// runs it; returns whether the close was canceled (held, or taken by the platform quit on macOS).
fn close_frame(app: &mut EffectcraftApp, ctx: &egui::Context) -> bool {
frame(app, ctx, true)
}
fn modified(app: &mut EffectcraftApp) {
@@ -401,7 +389,7 @@ mod tests {
fn closing_a_saved_project_quits_through_the_platform_on_macos() {
let (mut app, ctx) = app();
let macos = cfg!(target_os = "macos");
assert_eq!(close_frame(&mut app, &ctx), (macos, macos));
assert_eq!(close_frame(&mut app, &ctx), macos);
assert!(app.dialog.is_none(), "nothing to ask");
}
@@ -409,14 +397,14 @@ mod tests {
fn closing_a_modified_project_asks_before_the_platform_quit() {
let (mut app, ctx) = app();
modified(&mut app);
assert_eq!(close_frame(&mut app, &ctx), (true, false), "the prompt holds the window and nothing quits");
assert!(close_frame(&mut app, &ctx), "the prompt holds the window");
assert_eq!(app.dialog, Some(Dialog::UnsavedChanges));
answer_with(&mut app, &ctx, Answer::Cancel);
assert!(app.session.is_dirty() && !app.dialog_state.unsaved.quitting);
assert_eq!(close_frame(&mut app, &ctx), (true, false), "asked again after Cancel");
assert!(close_frame(&mut app, &ctx), "asked again after Cancel");
answer_with(&mut app, &ctx, Answer::Discard);
let macos = cfg!(target_os = "macos");
assert_eq!(close_frame(&mut app, &ctx), (macos, macos), "Don't Save quits");
assert_eq!(close_frame(&mut app, &ctx), macos, "Don't Save closes");
}
/// While the window is minimized or hidden, eframe runs `App::logic` without `App::ui` and
+1
View File
@@ -885,6 +885,7 @@ fn phase_menu(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, v: &m
// Interaction.
let resp = ui.interact(area, egui::Id::unique("viewer-interact"), Sense::click_and_drag());
crate::framework::host_canvas(ui.ctx(), resp.id);
let menu_hits_id = egui::Id::unique(("viewer-menu-hits", cid.0));
// A right-click an overlay took (the Cryptomatte eyedropper's) opens the menu too.
let forwarded = ui.data_mut(|d| d.remove_temp::<egui::Pos2>(egui::Id::unique(FORWARDED_SECONDARY)));
+1 -1
View File
@@ -393,7 +393,7 @@ pub fn install(ctx: &egui::Context, t: &Tokens, language: &str) {
stack.push("noto-symbols2".into());
}
install_script_fallbacks(&mut fonts, language);
ctx.set_fonts(fonts);
craft_ui::fonts::load(ctx, fonts);
apply_visuals(ctx, t);
}
+40 -17
View File
@@ -1,9 +1,12 @@
//! Software updates, background check at startup, and startup prompt modal.
//! Software updates, background check at startup, and startup prompt modal, as craft-update's
//! dialogs on the app's [`DialogHost`](craft_ui::dialog::DialogHost).
use crate::EffectcraftApp;
#[cfg(not(target_arch = "wasm32"))]
use craft_update::dialog::{CheckResultDialog, CheckResultResponse};
use craft_ui::dialog::DialogResult;
#[cfg(not(target_arch = "wasm32"))]
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
#[cfg(not(target_arch = "wasm32"))]
use craft_update::updater::{Action, Status, Updater};
@@ -60,7 +63,7 @@ pub(crate) fn restart_to_update(rt: &mut Runtime, ctx: &egui::Context, clean: bo
}
// Without a prompt this only takes the close a finished installation queued, so a save after
// Cancel does not close the app.
let _ = rt.updater.show_if(ctx, true);
let _ = rt.updater.take_close(true);
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
@@ -82,9 +85,9 @@ pub(crate) fn tick(app: &mut EffectcraftApp, ctx: &egui::Context) {
{
let rt = &mut app.updates_rt;
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now(ctx);
rt.updater.check_now();
} else if rt.startup_check {
rt.updater.check_at_start(ctx);
rt.updater.check_at_start();
}
rt.updater.tick(ctx);
}
@@ -101,28 +104,48 @@ pub(crate) fn result_window_open(open: bool, status: &Status, check_requested: b
!matches!(status, Status::Idle) || (open && check_requested)
}
/// One pass of the update flow, before the dialog host runs: answers the result dialog closed in
/// the last pass, drives the update prompt, and keeps the result dialog open and current while it
/// answers Help ▸ Check for Updates or the updater has something to report.
pub(crate) fn show(app: &mut EffectcraftApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
{
// The restart helper is scheduled before the app closes, so no update starts over unsaved work.
let clean = !app.session.is_dirty();
match app.updates_rt.updater.show_if(ctx, clean) {
// Answered before the dialog is kept open below, so a dismissed outcome does not open again at once.
match app.framework_dialogs.take::<UpdateCheckDialog>() {
Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => app.updates_rt.updater.check_now(),
Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => restart_to_update(&mut app.updates_rt, ctx, clean),
Some(DialogResult::Ok(CheckChoice::Update)) => {
app.updates_rt.updater.request_install(clean);
}
Some(DialogResult::Ok(CheckChoice::Download)) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())),
// Closing the dialog dismisses the outcome it showed.
Some(_) => {
app.updates_rt.manual_window_open = false;
app.updates_rt.updater.dismiss_status();
}
None => {}
}
match app.updates_rt.updater.run(&mut app.framework_dialogs, clean) {
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
Action::None => {}
_ => {}
}
let rt = &mut app.updates_rt;
rt.manual_window_open = result_window_open(rt.manual_window_open, rt.updater.status(), rt.check_requested);
if rt.manual_window_open {
match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) {
CheckResultResponse::None => {}
CheckResultResponse::Close => {
rt.manual_window_open = false;
rt.updater.dismiss_status();
}
CheckResultResponse::CheckAgain => rt.updater.check_now(ctx),
CheckResultResponse::RestartToUpdate => restart_to_update(rt, ctx, clean),
}
let shows = rt.manual_window_open;
let (status, installing, message) = (rt.updater.status().clone(), rt.updater.is_installing(), rt.updater.status_message());
let dialogs = &mut app.framework_dialogs;
if shows && !dialogs.is_open::<UpdateCheckDialog>() {
dialogs.open(UpdateCheckDialog::new(env!("CARGO_PKG_VERSION")));
} else if !shows && dialogs.is_open::<UpdateCheckDialog>() {
dialogs.cancel::<UpdateCheckDialog>(ctx);
}
if let Some(dialog) = dialogs.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status);
dialog.set_installing(installing);
dialog.set_message(message);
}
}