Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Windows and Linux: one title bar with the app icon (no stacked OS bar); long context menus scroll (#986)

BFlat244a99c39f2c
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index 82f3346dd..39915f72e 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -43,6 +43,11 @@ use photocraft_ui_egui::PhotocraftApp;
/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon.
const APP_ID: &str = "ai.storyteller.photocraft";
+/// Windows and Linux: no OS title bar; the app's top bar is the title bar, with its own caption
+/// buttons and edge resizing (`photocraft_ui_egui::titlebar`), as Photoshop does on Windows. macOS
+/// keeps its traffic lights over the integrated title strip.
+const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
+
/// The main window: 1440 × 900 (shrunk to fit the monitor, and maximized on the first frame
/// when it still doesn't fit, `work_area::fit_window`), centred on the main monitor. Without
/// `centered`, Windows cascades each new window from the top-left corner, so it opened at a
@@ -56,6 +61,7 @@ fn native_options() -> eframe::NativeOptions {
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([760.0, 480.0])
.with_drag_and_drop(true)
+ .with_decorations(!CUSTOM_TITLEBAR)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false),
@@ -267,6 +273,7 @@ fn main() -> eframe::Result {
}
let mut app = PhotocraftApp::new(Session::new(), services);
app.integrated_titlebar = cfg!(target_os = "macos");
+ app.custom_titlebar = CUSTOM_TITLEBAR;
// Only the title bar's free gap drags the window, never the menus (mac_window.rs).
#[cfg(target_os = "macos")]
mac_window::disable_native_title_drag();
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index 3599a4642..18879cc8d 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -23,6 +23,8 @@ photocraft-text = { workspace = true }
photocraft-vector = { workspace = true }
# Reading files to open them (bounded reads, a clear error for files larger than memory).
photocraft-format = { workspace = true }
+# Decoding the brand mark's PNG (`brand.rs`); already linked through photocraft-io.
+photocraft-codecs = { workspace = true }
egui = { workspace = true }
egui_extras = { version = "0.36", default-features = false, features = ["svg"] }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
@@ -38,9 +40,6 @@ sys-locale = "=0.3.2"
[dev-dependencies]
egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }
-# Only for examples/snapshot.rs (offscreen UI renders of real files).
-# Only for examples/interactive_bench.rs (JPEG encode, .pcraft saves).
-photocraft-codecs = { workspace = true }
# Benchmark helpers for the `--json` benches `cargo xtask perf` runs (in-process RSS, percentiles).
photocraft-testkit = { workspace = true }
# Only for examples/perf_scenarios.rs (a 500-brush .abr for the #210 import row).
diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rs
index d93354b37..d135528db 100644
--- a/crates/ui-egui/examples/snapshot.rs
+++ b/crates/ui-egui/examples/snapshot.rs
@@ -8,6 +8,7 @@
//!
//! `--safe-gpu` draws the canvas on the CPU path, like the app's `--safe-gpu` launch.
//! `--wayland-notice` previews the native file drag-and-drop guidance shown in Wayland sessions.
+//! `--custom-titlebar` draws the Windows/Linux title bar (caption buttons in the top bar).
//!
//! `--monitor 1366x768 --window-top 31` simulates the display the window is on (in points) and
//! where its content starts on it, e.g. a window running under a Windows taskbar.
@@ -57,6 +58,7 @@ fn main() {
let safe_gpu = args.iter().any(|a| a == "--safe-gpu");
// `--background-jobs`: long commands run as background jobs, as in the desktop app (#210).
let background_jobs = args.iter().any(|a| a == "--background-jobs");
+ let custom_titlebar = args.iter().any(|a| a == "--custom-titlebar");
// `--settle-ms N`: keep rendering frames for N ms before the capture (e.g. mid-job).
let settle_ms: u64 = arg(&args, "--settle-ms").and_then(|s| s.parse().ok()).unwrap_or(0);
let mut harness =
@@ -66,6 +68,7 @@ fn main() {
services.is_wayland = wayland_notice;
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
app.background_jobs = background_jobs;
+ app.custom_titlebar = custom_titlebar;
// `--safe-gpu`: the CPU canvas, as the desktop app's `--safe-gpu` launch.
if safe_gpu {
app.perf.gpu_info.selected = "cpu".into();
diff --git a/crates/ui-egui/src/brand.rs b/crates/ui-egui/src/brand.rs
new file mode 100644
index 000000000..c36019131
--- /dev/null
+++ b/crates/ui-egui/src/brand.rs
@@ -0,0 +1,81 @@
+//! The PhotoCraft brand mark at the left of the title bar: the app icon (the kitsune,
+//! `assets/app-icon/`, see its README), where Photoshop shows its "Ps" tile. The PNG carries the
+//! icon's rounded corners; it is decoded once per context into a mipmapped texture, so it stays
+//! crisp at the title bar's size on any display scale.
+
+use egui::{Color32, Context, Id, Rect, TextureHandle, TextureOptions, Ui, pos2};
+use photocraft_codecs::{ChannelLayout, SampleType};
+
+/// 128 px: sharp at 20 pt on a 3× display, and the mipmaps keep it clean at 1×.
+const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.photocraft.png");
+
+/// The icon's pixels (one transparent pixel if it couldn't be decoded, which a test rules out).
+fn decode() -> egui::ColorImage {
+ let rgba = photocraft_codecs::decode(ICON_PNG).ok().map(|img| img.convert(ChannelLayout::Rgba, SampleType::U8));
+ match rgba {
+ Some(img) if img.data().len() == img.width() as usize * img.height() as usize * 4 => {
+ egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.data())
+ }
+ _ => egui::ColorImage::filled([1, 1], Color32::TRANSPARENT),
+ }
+}
+
+/// The icon texture, uploaded on first use and kept in the context.
+fn texture(ctx: &Context) -> TextureHandle {
+ let id = Id::new("photocraft-brand-mark");
+ if let Some(tex) = ctx.data(|d| d.get_temp::<TextureHandle>(id)) {
+ return tex;
+ }
+ let options = TextureOptions { mipmap_mode: Some(egui::TextureFilter::Linear), ..TextureOptions::LINEAR };
+ let tex = ctx.load_texture("photocraft-brand-mark", decode(), options);
+ ctx.data_mut(|d| d.insert_temp(id, tex.clone()));
+ tex
+}
+
+/// Where the mark was painted this frame (tests and screenshots).
+fn rect_id() -> Id {
+ Id::new("photocraft-brand-mark-rect")
+}
+
+/// Paint the mark into `r` (square).
+pub fn paint_mark(ui: &Ui, r: Rect) {
+ let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
+ ui.painter().image(texture(ui.ctx()).id(), r, uv, Color32::WHITE);
+ ui.ctx().data_mut(|d| d.insert_temp(rect_id(), r));
+}
+
+/// The rect the mark was last painted into.
+#[cfg(test)]
+pub fn mark_rect(ctx: &Context) -> Option<Rect> {
+ ctx.data(|d| d.get_temp(rect_id()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_icon_decodes_to_a_rounded_128_px_tile() {
+ let img = decode();
+ assert_eq!(img.size, [128, 128]);
+ // Rounded corners: the corner pixel is transparent, the centre opaque.
+ assert_eq!(img.pixels[0].a(), 0);
+ assert_eq!(img.pixels[64 * 128 + 64].a(), 255);
+ }
+
+ #[test]
+ fn the_title_bar_paints_the_icon_from_one_cached_texture() {
+ let ctx = Context::default();
+ crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]);
+ let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let mut frame = || {
+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::panels::title_bar(&mut app, ui));
+ let uploads = out.textures_delta.set.values().flat_map(|d| d.iter()).filter(|d| d.image.size() == [128, 128]).count();
+ out.textures_delta.clear();
+ uploads
+ };
+ assert_eq!(frame(), 1, "uploaded on first use");
+ assert_eq!(frame(), 0, "then reused");
+ assert!(mark_rect(&ctx).is_some());
+ }
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index ad8ca4fef..55be4e886 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1103,14 +1103,16 @@ fn tab_context_items(index: usize, count: usize) -> [(&'static str, &'static str
}
fn tab_context_menu(ui: &mut egui::Ui, index: usize, count: usize) -> Option<(&'static str, serde_json::Value)> {
- ui.set_min_width(170.0);
- for (label, id, params, enabled) in tab_context_items(index, count) {
- if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() {
- ui.close();
- return Some((id, params));
+ crate::widgets::menu_scroll(ui, |ui| {
+ ui.set_min_width(170.0);
+ for (label, id, params, enabled) in tab_context_items(index, count) {
+ if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() {
+ ui.close();
+ return Some((id, params));
+ }
}
- }
- None
+ None
+ })
}
/// Apply tab-strip clicks: a document tab shows that document, an opening tab its progress, and
diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs
index e86a9c408..72d7d1991 100644
--- a/crates/ui-egui/src/canvas_tool_menu.rs
+++ b/crates/ui-egui/src/canvas_tool_menu.rs
@@ -318,16 +318,18 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) {
v.widgets.hovered.corner_radius = egui::CornerRadius::same(3);
ui.spacing_mut().item_spacing.y = 0.0;
ui.set_width(200.0);
- for row in rows(&menu) {
- let Some((label, command)) = *row else {
- ui.separator();
- continue;
- };
- let item = egui::Button::selectable(mode_checked(app, &menu, command), tl!(label)).min_size(egui::vec2(200.0, 20.0));
- if ui.add_enabled(entry_enabled(app, &menu, command), item).clicked() {
- selected = Some(command);
+ crate::widgets::menu_scroll(ui, |ui| {
+ for row in rows(&menu) {
+ let Some((label, command)) = *row else {
+ ui.separator();
+ continue;
+ };
+ let item = egui::Button::selectable(mode_checked(app, &menu, command), tl!(label)).min_size(egui::vec2(200.0, 20.0));
+ if ui.add_enabled(entry_enabled(app, &menu, command), item).clicked() {
+ selected = Some(command);
+ }
}
- }
+ });
});
});
if let Some(command) = selected {
diff --git a/crates/ui-egui/src/channels_panel.rs b/crates/ui-egui/src/channels_panel.rs
index 44fa4fd36..8f06a5436 100644
--- a/crates/ui-egui/src/channels_panel.rs
+++ b/crates/ui-egui/src/channels_panel.rs
@@ -228,43 +228,45 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
}
resp.context_menu(|ui| {
- ui.set_min_width(210.0);
- let a = &mut actions;
- match row {
- Row::Alpha(i) => {
- let ch = &doc.channels[i];
- item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": i }));
- item(ui, a, "Delete Channel", "channel.delete", json!({ "channel": i }));
- item(ui, a, "Rename Channel…", "ui.renameChannel", json!(i));
- ui.separator();
- if ch.spot.is_some() {
- item(ui, a, "Merge Spot Channel", "channel.mergeSpot", json!({ "channel": i }));
- item(ui, a, "Convert to Alpha Channel", "channel.options", json!({ "channel": i, "indicates": "masked" }));
- } else {
- indicates_items(ui, a, json!(i), ch.indicates);
- overlay_colors(ui, a, json!(i));
+ crate::widgets::menu_scroll(ui, |ui| {
+ ui.set_min_width(210.0);
+ let a = &mut actions;
+ match row {
+ Row::Alpha(i) => {
+ let ch = &doc.channels[i];
+ item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": i }));
+ item(ui, a, "Delete Channel", "channel.delete", json!({ "channel": i }));
+ item(ui, a, "Rename Channel…", "ui.renameChannel", json!(i));
+ ui.separator();
+ if ch.spot.is_some() {
+ item(ui, a, "Merge Spot Channel", "channel.mergeSpot", json!({ "channel": i }));
+ item(ui, a, "Convert to Alpha Channel", "channel.options", json!({ "channel": i, "indicates": "masked" }));
+ } else {
+ indicates_items(ui, a, json!(i), ch.indicates);
+ overlay_colors(ui, a, json!(i));
+ }
+ }
+ Row::QuickMask => {
+ item(ui, a, "Exit Quick Mask", "select.editInQuickMaskMode", json!({ "on": false }));
+ indicates_items(ui, a, json!("quickMask"), doc.quick_mask.as_ref().map(|q| q.indicates).unwrap_or_default());
+ overlay_colors(ui, a, json!("quickMask"));
+ }
+ Row::Composite | Row::Color(_) => {
+ item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": row.reference() }));
+ }
+ Row::LayerMask => {
+ let enabled = masked.as_ref().and_then(|l| l.mask.as_ref()).is_none_or(|m| m.enabled);
+ item(ui, a, if enabled { "Disable Layer Mask" } else { "Enable Layer Mask" }, "layer.layerMask.enabled", json!({}));
+ item(ui, a, "Delete Layer Mask", "layer.layerMask.delete", json!({}));
}
}
- Row::QuickMask => {
- item(ui, a, "Exit Quick Mask", "select.editInQuickMaskMode", json!({ "on": false }));
- indicates_items(ui, a, json!("quickMask"), doc.quick_mask.as_ref().map(|q| q.indicates).unwrap_or_default());
- overlay_colors(ui, a, json!("quickMask"));
- }
- Row::Composite | Row::Color(_) => {
- item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": row.reference() }));
- }
- Row::LayerMask => {
- let enabled = masked.as_ref().and_then(|l| l.mask.as_ref()).is_none_or(|m| m.enabled);
- item(ui, a, if enabled { "Disable Layer Mask" } else { "Enable Layer Mask" }, "layer.layerMask.enabled", json!({}));
- item(ui, a, "Delete Layer Mask", "layer.layerMask.delete", json!({}));
- }
- }
- ui.separator();
- item(ui, a, "New Channel…", "channel.new", json!({}));
- item(ui, a, "New Spot Channel…", "channel.newSpot", json!({}));
- ui.separator();
- item(ui, a, "Split Channels", "channel.split", json!({}));
- item(ui, a, "Merge Channels…", "channel.merge", json!({}));
+ ui.separator();
+ item(ui, a, "New Channel…", "channel.new", json!({}));
+ item(ui, a, "New Spot Channel…", "channel.newSpot", json!({}));
+ ui.separator();
+ item(ui, a, "Split Channels", "channel.split", json!({}));
+ item(ui, a, "Merge Channels…", "channel.merge", json!({}));
+ });
});
}
});
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 2a44cdaa5..fe39ec5fa 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -37,6 +37,9 @@
Open Recent Otevřít nedávné
Clear Recent Files Vymazat nedávné soubory
Close Zavřít
+ Minimize Minimalizovat
+ Maximize Maximalizovat
+ Restore Obnovit
Close All Zavřít vše
Close Others Zavřít ostatní
Save Uložit
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index e4b208644..9aab0e713 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -33,6 +33,9 @@
Open Recent Zuletzt geöffnete Dateien
Clear Recent Files Zuletzt geöffnete Dateien leeren
Close Schließen
+ Minimize Minimieren
+ Maximize Maximieren
+ Restore Wiederherstellen
Close All Alle schließen
Close Others Andere schließen
Save Speichern
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 2861e3d15..05674bddd 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -29,6 +29,9 @@
Open Recent Archivos recientes
Clear Recent Files Vaciar archivos recientes
Close Cerrar
+ Minimize Minimizar
+ Maximize Maximizar
+ Restore Restaurar
Close All Cerrar todo
Close Others Cerrar otros
Save Guardar
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index a9b82b2e1..d2d78de42 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -35,6 +35,9 @@
Open Recent Ouvrir un fichier récent
Clear Recent Files Effacer la liste des fichiers récents
Close Fermer
+ Minimize Réduire
+ Maximize Agrandir
+ Restore Restaurer
Close All Tout fermer
Close Others Fermer les autres
Save Enregistrer
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 6141779b8..14b9e0349 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -28,6 +28,9 @@
Open Recent Terakhir Dibuka
Clear Recent Files Hapus Daftar Berkas Terakhir
Close Tutup
+ Minimize Minimalkan
+ Maximize Maksimalkan
+ Restore Pulihkan
Close All Tutup Semua
Close Others Tutup Lainnya
Save Simpan
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 5ba347aa4..ff89aae9e 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -29,6 +29,9 @@
Open Recent Apri recenti
Clear Recent Files Cancella file recenti
Close Chiudi
+ Minimize Riduci a icona
+ Maximize Ingrandisci
+ Restore Ripristina
Close All Chiudi tutto
Close Others Chiudi altri
Save Salva
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index b5b7a3436..5d0808994 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -33,6 +33,9 @@
Open Recent 最近使ったファイルを開く
Clear Recent Files 最近使ったファイルを消去
Close 閉じる
+ Minimize 最小化
+ Maximize 最大化
+ Restore 元に戻す(縮小)
Close All すべて閉じる
Close Others ほかを閉じる
Save 保存
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 6de7ea2da..33f18f19d 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -25,6 +25,9 @@
Open Recent 최근 파일 열기
Clear Recent Files 최근 파일 목록 지우기
Close 닫기
+ Minimize 최소화
+ Maximize 최대화
+ Restore 이전 크기로 복원
Close All 모두 닫기
Close Others 다른 문서 닫기
Save 저장
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 041365a1e..1540aba88 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -32,6 +32,9 @@
Open Recent Abrir recentes
Clear Recent Files Limpar arquivos recentes
Close Fechar
+ Minimize Minimizar
+ Maximize Maximizar
+ Restore Restaurar
Close All Fechar tudo
Close Others Fechar outros
Save Salvar
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 75b47f286..43ac74aad 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -39,6 +39,9 @@
Open Recent Открыть недавние
Clear Recent Files Очистить список недавних файлов
Close Закрыть
+ Minimize Свернуть
+ Maximize Развернуть
+ Restore Свернуть в окно
Close All Закрыть все
Close Others Закрыть остальные
Save Сохранить
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 0df66ac8b..3bf703044 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -29,6 +29,9 @@
Open Recent 打开最近文件
Clear Recent Files 清除最近文件
Close 关闭
+ Minimize 最小化
+ Maximize 最大化
+ Restore 向下还原
Close All 关闭全部
Close Others 关闭其他
Save 保存
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 4f9a94eb8..6c86e7ac5 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -37,6 +37,9 @@
Open Recent 最近開啟的檔案
Clear Recent Files 清除最近檔案
Close 關閉
+ Minimize 最小化
+ Maximize 最大化
+ Restore 向下還原
Close All 全部關閉
Close Others 關閉其他
Save 儲存
diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rs
index 8a1702db0..69d074f00 100644
--- a/crates/ui-egui/src/layer_menu_ui.rs
+++ b/crates/ui-egui/src/layer_menu_ui.rs
@@ -79,44 +79,46 @@ pub fn entries(l: &Layer, multi: bool, has_selection: bool) -> Vec<Entry> {
/// Render the menu. Pushes `(command, params)` actions; `Value::Null` params mean "invoke like the
/// menu item" (opens the command's dialog when it has one).
pub fn show(app: &crate::PhotocraftApp, ui: &mut egui::Ui, l: &Layer, on_set: bool, actions: &mut Vec<(String, Value)>) -> bool {
- ui.set_min_width(220.0);
- let mut rename = false;
- let mut last_sep = true;
- let has_selection = app.session.active().is_some_and(|s| s.doc.selection.is_some());
- for e in entries(l, on_set, has_selection) {
- match e {
- None => {
- if !last_sep {
- ui.separator();
- }
- last_sep = true;
- }
- Some((label, id)) => {
- // Skip commands this build doesn't have rather than showing dead items.
- if photocraft_engine::commands::find(id).is_none() && !crate::menu_catalog::CATALOG.iter().any(|m| m.3 == id) {
- continue;
+ crate::widgets::menu_scroll(ui, |ui| {
+ ui.set_min_width(220.0);
+ let mut rename = false;
+ let mut last_sep = true;
+ let has_selection = app.session.active().is_some_and(|s| s.doc.selection.is_some());
+ for e in entries(l, on_set, has_selection) {
+ match e {
+ None => {
+ if !last_sep {
+ ui.separator();
+ }
+ last_sep = true;
}
- last_sep = false;
- // Enablement is exact for the active layer (or the selection); another row is
- // selected first when clicked, so its items stay available.
- let is_active = app.session.active().is_some_and(|s| s.active_layer == Some(l.id));
- let enabled = if on_set || is_active { crate::menus::is_enabled(app, id) } else { true };
- if ui.add_enabled(enabled, egui::Button::new(tl!(&label))).clicked() {
- if !on_set {
- actions.push(("layer.select".into(), json!({"layer": l.id.0})));
+ Some((label, id)) => {
+ // Skip commands this build doesn't have rather than showing dead items.
+ if photocraft_engine::commands::find(id).is_none() && !crate::menu_catalog::CATALOG.iter().any(|m| m.3 == id) {
+ continue;
+ }
+ last_sep = false;
+ // Enablement is exact for the active layer (or the selection); another row is
+ // selected first when clicked, so its items stay available.
+ let is_active = app.session.active().is_some_and(|s| s.active_layer == Some(l.id));
+ let enabled = if on_set || is_active { crate::menus::is_enabled(app, id) } else { true };
+ if ui.add_enabled(enabled, egui::Button::new(tl!(&label))).clicked() {
+ if !on_set {
+ actions.push(("layer.select".into(), json!({"layer": l.id.0})));
+ }
+ actions.push((id.into(), Value::Null));
+ ui.close();
}
- actions.push((id.into(), Value::Null));
- ui.close();
}
}
}
- }
- ui.separator();
- if ui.button(tl!("Rename Layer…")).clicked() {
- rename = true;
- ui.close();
- }
- rename
+ ui.separator();
+ if ui.button(tl!("Rename Layer…")).clicked() {
+ rename = true;
+ ui.close();
+ }
+ rename
+ })
}
#[cfg(test)]
@@ -170,6 +172,43 @@ mod tests {
}
}
+ #[test]
+ fn a_long_layer_menu_stays_inside_a_short_window_and_scrolls() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 32, "height": 24})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap();
+ let app = crate::PhotocraftApp::new(s, crate::Services::default());
+ let layer = {
+ let st = app.session.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().clone()
+ };
+ let ctx = egui::Context::default();
+ crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]);
+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 300.0));
+ let id = egui::Id::new("layer-menu-probe");
+ let mut content = 0.0;
+ for _ in 0..4 {
+ let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() };
+ let mut out = ctx.run_ui(input, |ui| {
+ // Opened low in the window, like a right-click on a bottom Layers row.
+ egui::Area::new(id).order(egui::Order::Foreground).default_pos(egui::pos2(300.0, 250.0)).show(ui.ctx(), |ui| {
+ egui::Frame::menu(ui.style()).show(ui, |ui| {
+ let start = ui.next_widget_position().y;
+ show(&app, ui, &layer, false, &mut Vec::new());
+ content = ui.min_rect().bottom() - start;
+ });
+ });
+ });
+ out.textures_delta.clear();
+ }
+ let rect = ctx.memory(|m| m.area_rect(id)).expect("the menu was shown");
+ assert!(screen.contains_rect(rect), "the menu moves up and stays inside the window: {rect:?}");
+ assert!(rect.height() < screen.height(), "{rect:?}");
+ let rows = entries(&layer, false, false).iter().flatten().count();
+ assert!(rows >= 15, "Photoshop's layer menu is long: {rows} rows");
+ assert!(content < rect.height() + 1.0, "the rows scroll inside the menu instead of running off the window");
+ }
+
#[test]
fn edit_contents_is_available_only_for_smart_objects() {
let mut s = photocraft_engine::Session::new();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 91e2c30ea..bb40e4025 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -21,6 +21,7 @@ pub mod adjust_preview;
pub mod adjust_ui;
pub mod analysis_ui;
pub mod artboard_ui;
+mod brand;
pub mod brush_panel;
pub mod brush_picker;
pub mod brush_preview;
@@ -121,6 +122,7 @@ mod tab_strip;
pub mod theme;
pub mod tiff_options_ui;
mod timeline_ui;
+mod titlebar;
pub mod tone;
pub mod tool_feedback;
pub mod transform_tex;
@@ -342,6 +344,9 @@ pub struct PhotocraftApp {
styled: bool,
/// Whether the window uses an integrated (transparent) macOS title bar.
pub integrated_titlebar: bool,
+ /// Windows and Linux: the window has no OS decorations and the app's top bar is the title bar
+ /// (caption buttons, window dragging and edge resizing, `titlebar`).
+ pub custom_titlebar: bool,
fonts_ready: bool,
/// Screen rect of the main canvas last frame (for overlays and the navigator).
pub last_canvas_rect: egui::Rect,
@@ -478,6 +483,7 @@ impl PhotocraftApp {
frame: 0,
styled: false,
integrated_titlebar: false,
+ custom_titlebar: false,
fonts_ready: false,
last_canvas_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)),
drop_canvas_rect: None,
@@ -1078,6 +1084,9 @@ impl eframe::App for PhotocraftApp {
canvas::extra_windows(self, &ctx);
notices::show(self, &ctx);
gpu_status::show_fallback(self, &ctx);
+ if self.custom_titlebar {
+ titlebar::resize_zones(ui);
+ }
// A device lost while drawing this frame: switch to the CPU canvas before the next one.
gpu_status::check(self, &ctx);
self.automation_input = false;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 4763ff5d2..233299465 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -297,12 +297,17 @@ fn color_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
// ----------------------------------------------------------------------------- title bar
+/// The app's top bar: brand mark, menus, the document title and the workspace controls. With
+/// [`PhotocraftApp::custom_titlebar`] (Windows and Linux) it is also the window's title bar, as in
+/// Photoshop on Windows: the caption buttons take its right end (`titlebar`).
pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
+ let custom = app.custom_titlebar;
let left = if cfg!(target_os = "macos") && app.integrated_titlebar { 78 } else { 10 };
- egui::Panel::top("title_bar")
+ let right = if custom { 0 } else { 10 };
+ let bar = egui::Panel::top("title_bar")
.exact_size(if t.pro { 32.0 } else { 38.0 })
- .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin { left, right: 10, top: 0, bottom: 0 }))
+ .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin { left, right, top: 0, bottom: 0 }))
.show(ui, |ui| {
let full = ui.max_rect();
// Only the free gap between the menus and the right-hand controls drags the window: a
@@ -324,33 +329,57 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
// whatever room is left between them, shortened or dropped rather than drawn over them.
let (mut menus_right, mut controls_left) = (full.left(), full.right());
ui.horizontal_centered(|ui| {
+ let side = if t.pro { 18.0 } else { 20.0 };
+ let (mark, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover());
+ crate::brand::paint_mark(ui, mark);
+ ui.add_space(6.0);
menus_right = crate::menus::menu_bar(app, ui);
- controls_left = ui
- .with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- ui.spacing_mut().item_spacing.x = 6.0;
- let mut ws = app.ui.workspace.clone();
- let opts = [
- // Keys stay English (`apply_workspace` matches them); the dropdown
- // shows the labels in the UI language.
- ("Essentials".to_string(), tl!("Essentials")),
- ("Photography".to_string(), tl!("Photography")),
- ("Painting".to_string(), tl!("Painting")),
- ("Graphic and Web".to_string(), tl!("Graphic and Web")),
- ];
- if widgets::dropdown(ui, "workspace", &mut ws, &opts, 130.0) {
- app.ui.workspace = ws;
- crate::menus::apply_workspace(app);
- }
- if icons::button(ui, "search", 28.0, app.ui.palette_open, &crate::shortcuts::tip_label(app, "Search commands", "edit.search")).clicked()
- {
- app.ui.palette_open = !app.ui.palette_open;
- }
- let theme_icon = if t.dark() { "sun" } else { "moon" };
- if icons::button(ui, theme_icon, 28.0, false, tl!("Switch theme")).clicked() {
- let next = app.ui.theme.next();
- app.set_theme(ui.ctx(), next);
- }
- // Always one click away: the community Discord.
+ // The menu bar takes the whole row, so the right-hand group gets its own rect:
+ // from the menus to the bar's end, or to the caption buttons.
+ let right_edge = if custom { full.right() - crate::titlebar::WIDTH - 4.0 } else { full.right() };
+ let group = egui::Rect::from_min_max(egui::pos2((menus_right + TITLE_GAP).min(right_edge), full.top()), egui::pos2(right_edge, full.bottom()));
+ let mut group_ui = ui.new_child(egui::UiBuilder::new().max_rect(group).layout(egui::Layout::right_to_left(egui::Align::Center)));
+ controls_left = {
+ let ui = &mut group_ui;
+ ui.spacing_mut().item_spacing.x = 6.0;
+ let mut ws = app.ui.workspace.clone();
+ let opts = [
+ // Keys stay English (`apply_workspace` matches them); the dropdown
+ // shows the labels in the UI language.
+ ("Essentials".to_string(), tl!("Essentials")),
+ ("Photography".to_string(), tl!("Photography")),
+ ("Painting".to_string(), tl!("Painting")),
+ ("Graphic and Web".to_string(), tl!("Graphic and Web")),
+ ];
+ // A narrow bar drops what is also in a menu, Discord first (below), then
+ // the theme toggle (Preferences), then search (Edit › Search), and narrows
+ // the switcher (Window › Workspace) before anything runs over.
+ let room = ui.available_width();
+ let icons_shown: u8 = if room >= WORKSPACE_MIN + 2.0 * ICON_SLOT {
+ 2
+ } else if room >= WORKSPACE_MIN + ICON_SLOT {
+ 1
+ } else {
+ 0
+ };
+ let ws_width = (room - f32::from(icons_shown) * ICON_SLOT - 6.0).clamp(WORKSPACE_MIN, 130.0);
+ if room >= WORKSPACE_MIN && widgets::dropdown(ui, "workspace", &mut ws, &opts, ws_width) {
+ app.ui.workspace = ws;
+ crate::menus::apply_workspace(app);
+ }
+ if icons_shown >= 1
+ && icons::button(ui, "search", 28.0, app.ui.palette_open, &crate::shortcuts::tip_label(app, "Search commands", "edit.search")).clicked()
+ {
+ app.ui.palette_open = !app.ui.palette_open;
+ }
+ let theme_icon = if t.dark() { "sun" } else { "moon" };
+ if icons_shown >= 2 && icons::button(ui, theme_icon, 28.0, false, tl!("Switch theme")).clicked() {
+ let next = app.ui.theme.next();
+ app.set_theme(ui.ctx(), next);
+ }
+ // The community Discord, one click away while the bar has room for it
+ // (narrow windows drop it first; it is also Help › Discord).
+ if ui.available_width() >= DISCORD_ROOM {
let discord = egui::Button::image_and_text(
icons::image("message-square", 14.0, t.text_dim),
egui::RichText::new(tl!("Discord")).color(t.text_dim).size(12.0),
@@ -359,9 +388,9 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if ui.add(discord).on_hover_text(format!("Join the ArtCraft Discord ({})", crate::links::DISCORD)).clicked() {
crate::links::open(app, ui.ctx(), crate::links::DISCORD);
}
- ui.min_rect().left()
- })
- .inner;
+ }
+ ui.min_rect().left()
+ };
});
ui.ctx().data_mut(|d| d.insert_temp(span_id, (menus_right, controls_left)));
let font = theme::medium(13.0);
@@ -377,10 +406,18 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.painter().galley(egui::pos2(menus_right + TITLE_GAP, full.center().y - g.size().y / 2.0), g, t.text_dim);
}
});
+ if custom {
+ crate::titlebar::caption_buttons(app, ui, bar.response.rect);
+ }
}
/// Minimum space kept between the window title and the menus or controls beside it.
const TITLE_GAP: f32 = 16.0;
+/// Free room the title bar needs after its other controls to show the Discord button.
+const DISCORD_ROOM: f32 = 120.0;
+/// The workspace switcher's narrowest width, and one 28 pt title-bar icon with its spacing.
+const WORKSPACE_MIN: f32 = 90.0;
+const ICON_SLOT: f32 = 34.0;
/// Left edge for a title `width` wide: centred on `center` when it fits between the menus
/// (ending at `menus_right`) and the right-hand controls (starting at `controls_left`), else
diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs
index 3ede04413..cf1cf8059 100644
--- a/crates/ui-egui/src/theme.rs
+++ b/crates/ui-egui/src/theme.rs
@@ -112,6 +112,9 @@ pub struct Tokens {
pub histogram_bg: Color32,
/// Channel intensity of scope outlines and hue markers.
pub histogram_level: u8,
+ /// The custom title bar's Close button while hovered (Windows' red), and its glyph.
+ pub caption_close: Color32,
+ pub caption_close_text: Color32,
}
impl Tokens {
@@ -173,6 +176,8 @@ impl Tokens {
row_selected: Color32::from_rgb(82, 82, 82),
histogram_bg: Color32::from_rgb(40, 40, 40),
histogram_level: 225,
+ caption_close: Color32::from_rgb(196, 43, 28),
+ caption_close_text: Color32::WHITE,
},
ThemeKind::Studio => Tokens {
kind,
@@ -209,6 +214,8 @@ impl Tokens {
row_selected: Color32::TRANSPARENT,
histogram_bg: Color32::from_rgb(14, 14, 15),
histogram_level: 225,
+ caption_close: Color32::from_rgb(196, 43, 28),
+ caption_close_text: Color32::WHITE,
},
ThemeKind::StudioLight => Tokens {
kind,
@@ -245,6 +252,8 @@ impl Tokens {
row_selected: Color32::TRANSPARENT,
histogram_bg: Color32::from_gray(40),
histogram_level: 240,
+ caption_close: Color32::from_rgb(196, 43, 28),
+ caption_close_text: Color32::WHITE,
},
ThemeKind::Classic => Tokens {
kind,
@@ -281,6 +290,8 @@ impl Tokens {
row_selected: Color32::from_rgb(10, 36, 106),
histogram_bg: Color32::from_gray(40),
histogram_level: 240,
+ caption_close: Color32::from_rgb(196, 43, 28),
+ caption_close_text: Color32::WHITE,
},
}
}
@@ -661,6 +672,8 @@ pub mod live {
};
}
c!(
+ caption_close,
+ caption_close_text,
chrome,
canvas,
canvas_dot,
diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs
new file mode 100644
index 000000000..03af8b0d7
--- /dev/null
+++ b/crates/ui-egui/src/titlebar.rs
@@ -0,0 +1,342 @@
+//! The window's own title bar on Windows and Linux, where the window has no OS decorations
+//! ([`PhotocraftApp::custom_titlebar`]): the app's top bar (`panels::title_bar`) is the title bar,
+//! as in Photoshop on Windows. The free gap between its menus and controls drags the window and a
+//! double-click there maximizes it (`panels::title_bar`, on every platform); caption buttons at
+//! the far right minimize, maximize/restore and close, and thin invisible zones along the window's
+//! edges resize it.
+
+use egui::{CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2};
+use serde_json::json;
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+
+/// One caption button: as wide as the native Windows ones.
+pub const BUTTON_WIDTH: f32 = 46.0;
+/// The three caption buttons together.
+pub const WIDTH: f32 = 3.0 * BUTTON_WIDTH;
+/// Resize zone thickness along an edge, and the side of a corner zone.
+const EDGE: f32 = 5.0;
+const CORNER: f32 = 12.0;
+
+#[derive(Clone, Copy, PartialEq, Debug)]
+enum Caption {
+ Minimize,
+ Maximize,
+ Close,
+}
+
+/// Left to right.
+const CAPTIONS: [Caption; 3] = [Caption::Minimize, Caption::Maximize, Caption::Close];
+
+/// Caption button ids (stable, so tests and agents can find them).
+fn caption_id(c: Caption) -> Id {
+ Id::new(("titlebar-caption", c as u8))
+}
+
+fn maximized(ctx: &egui::Context) -> bool {
+ ctx.input(|i| i.viewport().maximized.unwrap_or(false))
+}
+
+fn toggle_maximize(ctx: &egui::Context) {
+ ctx.send_viewport_cmd(ViewportCommand::Maximized(!maximized(ctx)));
+}
+
+/// Minimize, Maximize/Restore and Close at the right end of `bar` (the title bar's outer rect),
+/// full bar height, flush with the window's edge (even if the bar's contents run wider) so a
+/// maximized window's corner hits Close. Close runs File › Exit, which asks about unsaved
+/// documents first.
+pub fn caption_buttons(app: &mut PhotocraftApp, ui: &mut Ui, bar: Rect) {
+ let t = Tokens::get(ui.ctx());
+ let max = maximized(ui.ctx());
+ let right = bar.right().min(ui.ctx().content_rect().right());
+ let mut clicked = None;
+ for (i, c) in CAPTIONS.into_iter().enumerate() {
+ let r = Rect::from_min_size(pos2(right - WIDTH + i as f32 * BUTTON_WIDTH, bar.top()), vec2(BUTTON_WIDTH, bar.height()));
+ let resp = ui.interact(r, caption_id(c), Sense::click());
+ let close = c == Caption::Close;
+ let fill = match (resp.is_pointer_button_down_on(), resp.hovered()) {
+ (true, _) if close => t.caption_close.gamma_multiply(0.8),
+ (_, true) if close => t.caption_close,
+ (true, _) => t.pressed,
+ (_, true) => t.hover,
+ _ => egui::Color32::TRANSPARENT,
+ };
+ ui.painter().rect_filled(r, 0.0, fill);
+ let ink = if close && resp.hovered() { t.caption_close_text } else { t.icon };
+ paint_glyph(ui, c, max, r.center(), Stroke::new(1.0, ink));
+ let tip = match c {
+ Caption::Minimize => tl!("Minimize"),
+ Caption::Maximize if max => tl!("Restore"),
+ Caption::Maximize => tl!("Maximize"),
+ Caption::Close => tl!("Close"),
+ };
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tip));
+ if resp.on_hover_text(tip).clicked() {
+ clicked = Some(c);
+ }
+ }
+ match clicked {
+ Some(Caption::Minimize) => ui.ctx().send_viewport_cmd(ViewportCommand::Minimized(true)),
+ Some(Caption::Maximize) => toggle_maximize(ui.ctx()),
+ Some(Caption::Close) => {
+ let ctx = ui.ctx().clone();
+ let _ = crate::menus::invoke(app, &ctx, "file.exit", json!({}));
+ }
+ None => {}
+ }
+}
+
+/// The 10 pt line glyphs of the caption buttons.
+fn paint_glyph(ui: &Ui, c: Caption, maximized: bool, at: egui::Pos2, s: Stroke) {
+ let p = ui.painter();
+ let g = Rect::from_center_size(at, vec2(10.0, 10.0));
+ match c {
+ Caption::Minimize => {
+ p.line_segment([g.left_center(), g.right_center()], s);
+ }
+ // Restore: a front square with the corner of the one behind it.
+ Caption::Maximize if maximized => {
+ let front = Rect::from_min_max(g.min + vec2(0.0, 2.0), g.max - vec2(2.0, 0.0));
+ p.rect_stroke(front, 0.0, s, egui::StrokeKind::Middle);
+ p.line(vec![g.min + vec2(2.0, 2.0), g.min + vec2(2.0, 0.0), g.right_top(), g.max - vec2(0.0, 2.0), g.max - vec2(2.0, 2.0)], s);
+ }
+ Caption::Maximize => {
+ p.rect_stroke(g, 0.0, s, egui::StrokeKind::Middle);
+ }
+ Caption::Close => {
+ p.line_segment([g.left_top(), g.right_bottom()], s);
+ p.line_segment([g.right_top(), g.left_bottom()], s);
+ }
+ }
+}
+
+/// The edge and corner zones of a window with content rect `w`: (zone, direction, cursor). Corners
+/// come last so they win where they overlap the edges.
+fn zones(w: Rect) -> [(Rect, ResizeDirection, CursorIcon); 8] {
+ use ResizeDirection::*;
+ let (e, c) = (EDGE, CORNER);
+ [
+ (Rect::from_min_max(w.left_top(), pos2(w.right(), w.top() + e)), North, CursorIcon::ResizeVertical),
+ (Rect::from_min_max(pos2(w.left(), w.bottom() - e), w.right_bottom()), South, CursorIcon::ResizeVertical),
+ (Rect::from_min_max(w.left_top(), pos2(w.left() + e, w.bottom())), West, CursorIcon::ResizeHorizontal),
+ (Rect::from_min_max(pos2(w.right() - e, w.top()), w.right_bottom()), East, CursorIcon::ResizeHorizontal),
+ (Rect::from_min_size(w.left_top(), vec2(c, c)), NorthWest, CursorIcon::ResizeNwSe),
+ (Rect::from_min_size(w.right_top() - vec2(c, 0.0), vec2(c, c)), NorthEast, CursorIcon::ResizeNeSw),
+ (Rect::from_min_size(w.left_bottom() - vec2(0.0, c), vec2(c, c)), SouthWest, CursorIcon::ResizeNeSw),
+ (Rect::from_min_size(w.right_bottom() - vec2(c, c), vec2(c, c)), SouthEast, CursorIcon::ResizeNwSe),
+ ]
+}
+
+/// Invisible resize zones along the window's edges, above everything else; a press in one starts
+/// an OS resize in that direction. None while the window is maximized or full screen.
+pub fn resize_zones(ui: &mut Ui) {
+ let ctx = ui.ctx().clone();
+ if maximized(&ctx) || ctx.input(|i| i.viewport().fullscreen.unwrap_or(false)) {
+ return;
+ }
+ let w = ctx.content_rect();
+ let layer = LayerId::new(Order::Foreground, Id::new("titlebar-resize"));
+ let zui = ui.new_child(egui::UiBuilder::new().layer_id(layer).max_rect(w));
+ for (i, (r, dir, cursor)) in zones(w).into_iter().enumerate() {
+ let resp = zui.interact(r, Id::new(("titlebar-resize", i)), Sense::drag()).on_hover_cursor(cursor);
+ if resp.drag_started_by(PointerButton::Primary) {
+ ctx.send_viewport_cmd(ViewportCommand::BeginResize(dir));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use egui::{Event, Pos2, RawInput, ViewportId};
+ use photocraft_engine::Session;
+
+ /// A headless window `width` pt wide showing the title bar and the resize zones.
+ struct Win {
+ ctx: egui::Context,
+ app: PhotocraftApp,
+ width: f32,
+ time: f64,
+ maximized: bool,
+ }
+
+ impl Win {
+ fn new(width: f32) -> Self {
+ let ctx = egui::Context::default();
+ PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]);
+ let mut app = PhotocraftApp::new(Session::new(), crate::Services::default());
+ app.custom_titlebar = true;
+ Self { ctx, app, width, time: 0.0, maximized: false }
+ }
+
+ fn frame(&mut self, events: Vec<Event>) -> egui::FullOutput {
+ self.time += 0.05;
+ let mut input =
+ RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, 600.0))), time: Some(self.time), events, ..Default::default() };
+ if let Some(v) = input.viewports.get_mut(&ViewportId::ROOT) {
+ v.maximized = Some(self.maximized);
+ }
+ let app = &mut self.app;
+ let mut out = self.ctx.run_ui(input, |ui| {
+ crate::panels::title_bar(app, ui);
+ resize_zones(ui);
+ });
+ out.textures_delta.clear();
+ out
+ }
+
+ /// Frames for a pointer gesture: move to `path[0]`, press, move along `path`, release. The
+ /// viewport commands the frames sent.
+ fn gesture(&mut self, path: &[Pos2]) -> Vec<ViewportCommand> {
+ let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true)]];
+ events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)]));
+ events.push(vec![button(*path.last().unwrap_or(&path[0]), false)]);
+ events.into_iter().flat_map(|e| self.frame(e).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()).collect()
+ }
+
+ fn click(&mut self, p: Pos2) -> Vec<ViewportCommand> {
+ self.gesture(&[p])
+ }
+
+ fn caption(&self, c: Caption) -> Rect {
+ self.ctx.read_response(caption_id(c)).map(|r| r.rect).unwrap_or(Rect::NOTHING)
+ }
+
+ /// The bar's clickable widgets other than its drag gap and the caption buttons.
+ fn bar_widgets(&self) -> Vec<Rect> {
+ let skip = CAPTIONS.map(caption_id);
+ self.ctx.viewport(|v| {
+ v.prev_pass
+ .widgets
+ .layers()
+ .filter(|(l, _)| l.order != Order::Foreground)
+ .flat_map(|(_, ws)| ws.iter())
+ .filter(|w| w.sense.senses_click() && !w.sense.senses_drag() && w.rect.top() < 30.0 && !skip.contains(&w.id))
+ .map(|w| w.rect)
+ .collect()
+ })
+ }
+ }
+
+ fn texts(out: &egui::FullOutput) -> Vec<(String, Rect)> {
+ fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) {
+ match s {
+ egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))),
+ egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)),
+ _ => {}
+ }
+ }
+ let mut v = vec![];
+ out.shapes.iter().for_each(|c| walk(&c.shape, &mut v));
+ v
+ }
+
+ fn button(p: Pos2, pressed: bool) -> Event {
+ Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }
+ }
+
+ #[test]
+ fn caption_buttons_take_the_right_end_and_nothing_overlaps_them() {
+ for width in [760.0, 1100.0, 1440.0] {
+ let mut w = Win::new(width);
+ w.frame(vec![]);
+ let out = w.frame(vec![]);
+ let [min, max, close] = CAPTIONS.map(|c| w.caption(c));
+ assert_eq!((close.right(), close.top()), (width, 0.0), "Close sits in the window's corner at {width}");
+ assert!(close.height() >= 32.0 && [min, max, close].iter().all(|r| r.width() == BUTTON_WIDTH));
+ assert_eq!((min.right(), max.right()), (max.left(), close.left()));
+ let widgets = w.bar_widgets();
+ assert!(widgets.len() >= 10, "menus, search, theme, workspace: {widgets:?}");
+ for a in &widgets {
+ assert!(a.right() <= min.left(), "{a:?} runs into the caption buttons at {width}");
+ }
+ // Wide windows show the whole group; the narrowest drops Discord (also Help › Discord).
+ let has_discord = texts(&out).iter().any(|(t, _)| t == "Discord");
+ assert_eq!(has_discord, width > 1000.0, "Discord at {width}");
+ }
+ }
+
+ #[test]
+ fn the_brand_mark_leads_the_bar() {
+ let mut w = Win::new(1440.0);
+ w.frame(vec![]);
+ let out = w.frame(vec![]);
+ let mark = crate::brand::mark_rect(&w.ctx).expect("the brand mark is painted");
+ let file = texts(&out).into_iter().find(|(t, _)| t == "File").map(|(_, r)| r).expect("the File menu title");
+ assert!(mark.right() < file.left(), "the mark sits left of the menus: {mark:?} {file:?}");
+ assert!(mark.left() < 20.0 && mark.width() >= 16.0, "{mark:?}");
+ }
+
+ #[test]
+ fn close_runs_file_exit_which_asks_about_unsaved_work() {
+ let mut w = Win::new(1100.0);
+ w.frame(vec![]);
+ let close = w.caption(Caption::Close).center();
+ let cmds = w.click(close);
+ // File › Exit asks the window to close; the unsaved-changes guard (`discard_ui`) then
+ // decides, so the caption button and the menu item behave the same.
+ assert!(cmds.iter().any(|c| matches!(c, ViewportCommand::Close)), "{cmds:?}");
+ }
+
+ #[test]
+ fn minimize_and_maximize_follow_the_window_state() {
+ let mut w = Win::new(1100.0);
+ w.frame(vec![]);
+ let (min, max) = (w.caption(Caption::Minimize).center(), w.caption(Caption::Maximize).center());
+ assert!(w.click(min).contains(&ViewportCommand::Minimized(true)));
+ assert!(w.click(max).contains(&ViewportCommand::Maximized(true)));
+ w.maximized = true;
+ assert!(w.click(max).contains(&ViewportCommand::Maximized(false)), "Restore");
+ }
+
+ #[test]
+ fn empty_bar_space_drags_and_double_click_maximizes() {
+ let mut w = Win::new(1440.0);
+ w.frame(vec![]);
+ let empty = pos2(980.0, 16.0);
+ assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space");
+ let cmds = w.gesture(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]);
+ assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}");
+ let mut cmds = w.click(empty);
+ cmds.extend(w.click(empty));
+ assert!(cmds.contains(&ViewportCommand::Maximized(true)), "{cmds:?}");
+ w.maximized = true;
+ w.time += 1.0;
+ let mut cmds = w.click(empty);
+ cmds.extend(w.click(empty));
+ assert!(cmds.contains(&ViewportCommand::Maximized(false)), "{cmds:?}");
+ // Widgets keep their clicks: dragging from a menu title doesn't move the window.
+ let file = texts(&w.frame(vec![])).into_iter().find(|(t, _)| t == "File").map(|(_, r)| r.center());
+ let file = file.expect("the File menu title");
+ let cmds = w.gesture(&[file, file + vec2(12.0, 4.0), file + vec2(30.0, 8.0)]);
+ assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}");
+ }
+
+ #[test]
+ fn edge_zones_resize_unless_maximized() {
+ use ResizeDirection::*;
+ let mut w = Win::new(1000.0);
+ w.frame(vec![]);
+ for (p, dir) in [
+ (pos2(1.0, 300.0), West),
+ (pos2(998.0, 300.0), East),
+ (pos2(500.0, 1.0), North),
+ (pos2(500.0, 598.0), South),
+ (pos2(2.0, 2.0), NorthWest),
+ (pos2(997.0, 3.0), NorthEast),
+ (pos2(3.0, 597.0), SouthWest),
+ (pos2(998.0, 598.0), SouthEast),
+ ] {
+ let cmds = w.gesture(&[p, p + vec2(6.0, 6.0)]);
+ assert_eq!(cmds, vec![ViewportCommand::BeginResize(dir)], "at {p:?}");
+ }
+ let out = w.frame(vec![Event::PointerMoved(pos2(1.0, 300.0))]);
+ assert_eq!(out.platform_output.cursor_icon, CursorIcon::ResizeHorizontal);
+ // Maximized: no zones, and the window's top-right corner is Close.
+ w.maximized = true;
+ let cmds = w.gesture(&[pos2(1.0, 300.0), pos2(8.0, 300.0)]);
+ assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::BeginResize(_))), "{cmds:?}");
+ assert!(w.click(pos2(999.5, 0.5)).iter().any(|c| matches!(c, ViewportCommand::Close)));
+ }
+}
diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs
index 8f3624ea3..619515013 100644
--- a/crates/ui-egui/src/vector_ui.rs
+++ b/crates/ui-egui/src/vector_ui.rs
@@ -810,16 +810,18 @@ pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
action = Some(("path.rename", json!({"name": "work", "to": format!("Path {n}")})));
}
resp.context_menu(|ui| {
- ui.set_min_width(190.0);
- let entry = PathEntry { name: name.clone(), path: path.clone(), kind: *kind };
- let can_paint = app.session.active().and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))).is_some_and(|l| l.surface().is_some());
- for (label, cmd, params) in path_context_actions(&entry, &doc) {
- let enabled = !matches!(cmd, "path.fill" | "path.stroke") || can_paint;
- if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() {
- action = Some((cmd, params));
- ui.close();
+ crate::widgets::menu_scroll(ui, |ui| {
+ ui.set_min_width(190.0);
+ let entry = PathEntry { name: name.clone(), path: path.clone(), kind: *kind };
+ let can_paint = app.session.active().and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))).is_some_and(|l| l.surface().is_some());
+ for (label, cmd, params) in path_context_actions(&entry, &doc) {
+ let enabled = !matches!(cmd, "path.fill" | "path.stroke") || can_paint;
+ if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() {
+ action = Some((cmd, params));
+ ui.close();
+ }
}
- }
+ });
});
ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator));
}
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index be5f34f46..1131d3e98 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -523,6 +523,24 @@ pub fn dropdown<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, op
changed
}
+/// The body of a right-click menu: as tall as its items up to the part of the window that can be
+/// seen (clear of a taskbar a too-tall window runs under, #315), scrolling past that, so long
+/// context menus (a layer's, the canvas tools') stay reachable on small windows instead of running
+/// off the bottom. egui moves a popup up to keep it in the window, so a menu opened low on the
+/// screen first shifts up and only scrolls when it is taller than the window.
+pub fn menu_scroll<R>(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R {
+ // The popup frame's margin and stroke, and a small gap to the window's edges.
+ let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE;
+ let room = (crate::work_area::visible_rect(ui.ctx()).height() - frame).max(MENU_MIN_HEIGHT);
+ // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), so ask for
+ // the whole room: the area still shrinks to its rows when they need less.
+ egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner
+}
+
+/// Gap kept between a context menu and the window's edges, and the shortest it gets.
+const MENU_EDGE: f32 = 4.0;
+const MENU_MIN_HEIGHT: f32 = 120.0;
+
/// The colour picker popup of a colour swatch: a click on `swatch` toggles it, a click outside
/// closes it. While open, its left edge stays where it first showed (at the swatch, or further
/// left when the window edge needs it), below the swatch or above it as room allows. The picker's
diff --git a/docs/ui-design.md b/docs/ui-design.md
index f282de653..f6bea9146 100644
--- a/docs/ui-design.md
+++ b/docs/ui-design.md
@@ -48,10 +48,20 @@ curl -sfL -o assets/icons/<name>.svg https://raw.githubusercontent.com/lucide-ic
Where the font lacks a symbol (e.g. ∠ ↦ ▔), draw it with the painter or use a Lucide icon; never ship
missing-glyph boxes. Check every new panel with the offscreen snapshot tool (`docs/development.md`).
+## Title bar
+
+The app's top bar (`panels::title_bar`) starts with the brand mark (the app icon, `brand.rs`), then the menus, the document title and the workspace controls, like Photoshop's Ps tile and menu row.
+
+- **Windows and Linux:** the window has no OS decorations, so there is one bar, not two stacked. The top bar is the title bar (`titlebar.rs`): Minimize, Maximize/Restore and Close (red on hover, `caption_close` tokens) sit flush in the window's top-right corner, the free gap between the menus and the controls drags the window and a double-click there maximizes it, and invisible 5 pt edges (12 pt corners) resize it. Close runs File › Exit, so unsaved documents are asked about first.
+- **macOS:** the traffic lights sit over the integrated title strip (`integrated_titlebar`).
+- **Narrow windows** drop controls that are also in a menu before anything overlaps: Discord (Help › Discord), then the theme toggle, then search (Edit › Search), then the workspace switcher narrows (Window › Workspace).
+
## Menus
`menu_catalog.rs` holds Photoshop's menu tree (standard command names, order, separators, default shortcuts). Items whose id matches an engine or UI command are live; others render disabled until implemented. Give new commands the catalogue's id (for example `image.imageSize`) and they light up in the right place automatically.
+Menus never run off the window: the menu bar's menus and submenus scroll with arrows (`menu_nav::level`), and long right-click menus (Layers, canvas tools, Channels, Paths, document tabs) wrap their rows in `widgets::menu_scroll`, so they move up to fit and scroll only when taller than the visible window.
+
## Automation for visual checks
Use `ui.click {x,y}`, `ui.move`, `ui.key` and `ui.type` (synthetic input in screen points) to open menus, popups and context menus, then `ui.screenshot`.