mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-03 22:40:27 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06b3cf848f | ||
|
|
19f531c23d | ||
|
|
546549a29c | ||
|
|
46db6fe21e | ||
|
|
a43f4c6258 | ||
|
|
006189ca48 | ||
|
|
cbf4e580c1 | ||
|
|
4d9b7d39bf |
+179
-134
@@ -463,6 +463,46 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
|
||||
}
|
||||
|
||||
/// Runs the app with the windowless root when `windowless` is set, and with the visible root when it is not. eframe
|
||||
/// refuses a windowless root on a session that cannot run it before it calls the creator, which then stays in its
|
||||
/// cell for a retry with the visible root: the app always starts.
|
||||
fn run_with_visible_root_fallback(
|
||||
creator: eframe::AppCreator<'static>,
|
||||
windowless: Arc<std::sync::atomic::AtomicBool>,
|
||||
mut options: eframe::NativeOptions,
|
||||
) -> eframe::Result {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let creator = std::rc::Rc::new(std::cell::RefCell::new(Some(creator)));
|
||||
let name = wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity());
|
||||
let run = |options: eframe::NativeOptions| {
|
||||
let creator = creator.clone();
|
||||
eframe::run_native(
|
||||
name,
|
||||
options,
|
||||
Box::new(move |cc| match creator.borrow_mut().take() {
|
||||
Some(create) => create(cc),
|
||||
None => Err("the app was already created".into()),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let on = windowless.load(Relaxed);
|
||||
// The clone keeps no event-loop hook, which only the X11 start sets and that start is windowed.
|
||||
let mut visible_root = on.then(|| options.clone());
|
||||
if on {
|
||||
options.root_viewport_mode = eframe::RootViewportMode::Windowless;
|
||||
}
|
||||
let result = run(options);
|
||||
if let Err(eframe::Error::UnsupportedConfiguration(reason)) = &result
|
||||
&& let Some(options) = visible_root.take()
|
||||
&& creator.borrow().is_some()
|
||||
{
|
||||
log::warn!("windowless root unavailable ({reason}); starting with a visible root window");
|
||||
windowless.store(false, Relaxed);
|
||||
return run(options);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Parses the command line, installs logging and the panic hook, restores preferences and window
|
||||
/// geometry, opens requested documents or the Start screen, starts the control server when
|
||||
/// asked, and runs the eframe event loop.
|
||||
@@ -705,147 +745,152 @@ fn main() -> eframe::Result {
|
||||
let noticed_for_exit = unclean_notice_shown.clone();
|
||||
let noticed_in_window = unclean_notice_shown.clone();
|
||||
let exit_settings = settings.clone();
|
||||
let result = eframe::run_native(
|
||||
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let _ = repaint.set(ctx.clone());
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// The interface language: the saved choice, else the system's.
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(Arc::new(file_service))
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
|
||||
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
// separator (#838).
|
||||
let region = region::system();
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
// The custom dictionary's words (#40) count as loaded settings.
|
||||
if prefs::enabled()
|
||||
&& let Some(path) = prefs::user_dict_path()
|
||||
{
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
// The root window is never shown (ADR 0001): eframe runs a windowless root and every document is a child
|
||||
// window. X11, XWayland and BSD on X11 cannot, so they keep the visible root (the ADR's amendment). The mode
|
||||
// is read by the app creator, which runs once the mode is settled.
|
||||
let windowless = Arc::new(std::sync::atomic::AtomicBool::new(!x11));
|
||||
let windowless_in_app = windowless.clone();
|
||||
let creator: eframe::AppCreator<'static> = Box::new(move |cc| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let _ = repaint.set(ctx.clone());
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
};
|
||||
// The interface language: the saved choice, else the system's.
|
||||
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
|
||||
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
|
||||
let host = Arc::new(
|
||||
Host::builder(wordcraft_ui_egui::APP)
|
||||
.i18n(wordcraft_ui_egui::i18n::catalogs())
|
||||
.files(Arc::new(file_service))
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.lang(lang.craft_lang())
|
||||
.build(),
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let mut spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
// The runtime and eframe must agree on the root.
|
||||
if windowless_in_app.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
spec = spec.windowless_root();
|
||||
}
|
||||
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
|
||||
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
|
||||
// The system region picks the new document's paper, the units and the decimal
|
||||
// separator (#838).
|
||||
let region = region::system();
|
||||
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(®ion) };
|
||||
let mut session = Session::new(doc);
|
||||
session.system_region = region;
|
||||
// The custom dictionary's words (#40) count as loaded settings.
|
||||
if prefs::enabled()
|
||||
&& let Some(path) = prefs::user_dict_path()
|
||||
{
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
|
||||
if let Some(state) = &cc.wgpu_render_state {
|
||||
let info = state.adapter.get_info();
|
||||
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
|
||||
if software {
|
||||
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
|
||||
if let Some(state) = &cc.wgpu_render_state {
|
||||
let info = state.adapter.get_info();
|
||||
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
|
||||
if software {
|
||||
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
|
||||
}
|
||||
app.set_software_drawing(software);
|
||||
app.set_software_drawing(software);
|
||||
}
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.replace_startup_document(doc);
|
||||
}
|
||||
app.tell_about_font_downloads();
|
||||
if prefs::enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// the OS hands over later open on top of it and close it.
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
// A Word template named here starts a new document based on it (#3433).
|
||||
for f in files {
|
||||
if let Err(e) = app.open_from_platform(&f, None) {
|
||||
app.report_open_failure(&f, &e);
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
let doc = app.session.blank_document();
|
||||
app.replace_startup_document(doc);
|
||||
}
|
||||
app.tell_about_font_downloads();
|
||||
if prefs::enabled()
|
||||
&& let Some(dir) = wordcraft_control_key::settings_dir()
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
|
||||
log::warn!("local recovery unavailable: {e}");
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) =
|
||||
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
app = app.with_control(ControlChannel::new(rx));
|
||||
control_server = Some(started);
|
||||
}
|
||||
// Nothing to open (no files, no sample, no control channel driving the editor): start
|
||||
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
|
||||
// the OS hands over later open on top of it and close it.
|
||||
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
|
||||
app.start_screen();
|
||||
}
|
||||
// A Word template named here starts a new document based on it (#3433).
|
||||
for f in files {
|
||||
if let Err(e) = app.open_from_platform(&f, None) {
|
||||
app.report_open_failure(&f, &e);
|
||||
}
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
}
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
}),
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: native_menu::install(&ctx, &app),
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
});
|
||||
let result = run_with_visible_root_fallback(creator, windowless, options);
|
||||
// The exit hook has run; this is the no-op fallback for a start that created no window.
|
||||
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
// The app is dropped by now: whatever it saved on the way out is in the store.
|
||||
|
||||
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sel_result(s)
|
||||
})
|
||||
.key("Mod+W / Mod+F4")
|
||||
.params(r#"{"force"?: bool (desktop app's control channel and MCP bridge only: without it a document with unsaved changes is an error and stays open; with it the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
|
||||
.params(r#"{"save"?: bool (desktop app's control channel and MCP bridge only: save the document, then close it), "force"?: bool (desktop app's control channel and MCP bridge only: without save or force a document with unsaved changes is an error and stays open; with force the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("file.closeDocument", "Close Document", "Agents", close_document)
|
||||
.params(r#"{"id"?: n (an open document, see view.switchWindows; default the active one), "force"?: bool (discard unsaved changes; without it a document with unsaved changes is an error and stays open)} → {"closed": id, "active": id, "documents": [{"id", "title", "path", "dirty", "active"}]}; closing the last document leaves a new blank one"#)
|
||||
|
||||
@@ -402,7 +402,7 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
}
|
||||
let mut updates: Vec<(usize, String)> = Vec::new();
|
||||
for (k, o) in p.objects.iter().enumerate() {
|
||||
let InlineObject::Field { instr, result, locked: false, .. } = o else { continue };
|
||||
let InlineObject::Field { instr, locked: false, .. } = o else { continue };
|
||||
// A table formula reads the cells around its own cell again.
|
||||
if instr.trim_start().starts_with('=') {
|
||||
if let Some((tp, r, c)) = path.cell()
|
||||
@@ -425,15 +425,12 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
let created = s.doc.core.created.trim();
|
||||
// CREATEDATE shows when the document was created (ECMA-376 §17.16.5.11). A new
|
||||
// document, never saved, has no creation date yet and saving stamps now. A
|
||||
// file opened without one, or with one that can't be read, keeps any result
|
||||
// it already has; when inserted with none, it shows today's date (the date
|
||||
// a save would stamp).
|
||||
let text = if name == "CREATEDATE"
|
||||
&& let Some((unix, offset)) = created_at(created)
|
||||
{
|
||||
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
|
||||
} else if name != "CREATEDATE" || result.is_empty() || (created.is_empty() && s.path.is_none()) {
|
||||
// file opened without one, or with one that can't be read, keeps the result
|
||||
// it has.
|
||||
let text = if name != "CREATEDATE" || (created.is_empty() && s.path.is_none()) {
|
||||
crate::cmd::insert::format_date_in(&pic, lang.as_deref())
|
||||
} else if let Some((unix, offset)) = created_at(created) {
|
||||
crate::cmd::insert::format_date_at_in(&pic, lang.as_deref(), unix, offset)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -556,26 +556,6 @@ fn createdate_without_a_readable_creation_date() {
|
||||
assert_eq!(fields(&s)[0].1, crate::cmd::insert::format_date("yyyy-MM"));
|
||||
}
|
||||
|
||||
/// Inserting CREATEDATE into an opened file that has no creation date (plain text, Markdown, or a
|
||||
/// DOCX without `dcterms:created`) shows today's date rather than an empty result, while an
|
||||
/// existing field with a cached result keeps it.
|
||||
#[test]
|
||||
fn createdate_inserted_into_opened_file_without_creation_date() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Notes"));
|
||||
s.path = Some(std::env::temp_dir().join("notes.txt"));
|
||||
s.doc.core.created.clear();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#, "result": "2019-05"})).unwrap();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
|
||||
let expected = crate::cmd::insert::format_date("yyyy-MM");
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), expected.clone()]);
|
||||
// An unreadable creation date behaves the same way: cached results stay, empty ones fill in.
|
||||
s.doc.core.created = "sometime in May".into();
|
||||
s.run("insert.field", &json!({"instr": r#"CREATEDATE \@ "yyyy-MM""#})).unwrap();
|
||||
let results: Vec<String> = fields(&s).into_iter().map(|f| f.1).collect();
|
||||
assert_eq!(results, ["2019-05".to_string(), expected.clone(), expected]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_tabs_ignore_nonentries() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Before\nContents\nOld\t9\nAfter"));
|
||||
|
||||
@@ -12675,12 +12675,10 @@ fn outline_level_changes_are_undoable() {
|
||||
assert!(s.run("outline.level", &json!({"level": 12})).is_err());
|
||||
assert!(s.run("outline.level", &json!({})).is_err());
|
||||
// Every outline command survives junk parameters in Outline view.
|
||||
let reg = cmd::registry();
|
||||
for spec in reg.all().iter().filter(|c| c.id.starts_with("outline.")) {
|
||||
for spec in cmd::registry().all().iter().filter(|c| c.id.starts_with("outline.")) {
|
||||
for j in [json!(null), json!({"block": 99999, "level": "x", "value": 5}), json!({"block": -1, "level": 0})] {
|
||||
let mut s = outline_doc();
|
||||
let r = s.run(spec.id, &j);
|
||||
assert!(!caught_panic(®, &r), "{} panicked on {j}: {r:?}", spec.id);
|
||||
let _ = s.run(spec.id, &j);
|
||||
let _ = s.layout();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,7 +363,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
}
|
||||
floats.insert(oi, r);
|
||||
}
|
||||
let rel = rel_exclusions(&excl, 0.0, y, applied);
|
||||
let rel = rel_exclusions(&excl, 0.0, y);
|
||||
if !rel.is_empty() {
|
||||
pl = ctx.para_labelled(p, width, table, &rel, applied, label);
|
||||
}
|
||||
|
||||
@@ -219,10 +219,8 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
|
||||
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, false))
|
||||
}
|
||||
|
||||
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
|
||||
/// `space_before` the space before it that the flow laid out above it.
|
||||
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
|
||||
let before = if space_before > 0.0 { space_before } else { 0.0 };
|
||||
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`.
|
||||
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32) -> Vec<para::Exclusion> {
|
||||
excl.iter()
|
||||
.map(|(r, tb, c, side, table)| para::Exclusion {
|
||||
top: r.y - y0,
|
||||
@@ -234,11 +232,10 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before:
|
||||
side: *side,
|
||||
table: *table,
|
||||
})
|
||||
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
|
||||
// room, with that space laid out again below them (#7143). Any ending at or above it
|
||||
// (like side-wrapping areas above the first line) cannot reach the paragraph and is
|
||||
// dropped so paragraphs below keep empty exclusions and hit the cache (#8613).
|
||||
.filter(|e| e.bottom > 0.0 || (e.top_bottom && e.bottom > -before))
|
||||
// Top-and-Bottom areas above the first line can still take room: they sit in the
|
||||
// paragraph's space before, which Word lays out again below them (#7143). Side-wrapping
|
||||
// areas there are above the text and take no room, as before.
|
||||
.filter(|e| e.bottom > 0.0 || e.top_bottom)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -531,7 +528,7 @@ fn anchor_floats_but(
|
||||
}
|
||||
}
|
||||
}
|
||||
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0, before);
|
||||
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0);
|
||||
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
|
||||
(rects, pl, rel)
|
||||
}
|
||||
@@ -867,7 +864,7 @@ pub(crate) fn place_objects(ctx: &mut Ctx, req: &ObjectPlacement) -> (Vec<Placed
|
||||
/// touch its lines and are left out.
|
||||
pub(crate) fn continued_exclusions(rel: &[para::Exclusion], excl: &[WrapArea], x0: f32, y: f32, t: f32, width: f32) -> Vec<para::Exclusion> {
|
||||
let before = rel.iter().filter(|e| e.top < t).map(|e| para::Exclusion { bottom: e.bottom.min(t), ..e.clone() });
|
||||
let here = rel_exclusions(excl, x0, y - t, 0.0)
|
||||
let here = rel_exclusions(excl, x0, y - t)
|
||||
.into_iter()
|
||||
.filter(|e| e.bottom > t && e.right > -width && e.left < 2.0 * width)
|
||||
.map(|e| if e.top < t && e.contour.is_none() { para::Exclusion { top: t, ..e } } else { e });
|
||||
|
||||
@@ -70,8 +70,6 @@ pub(super) fn snap_chars(b: &mut Builder, text: &str, grid: &Grid) {
|
||||
g.dx += shift;
|
||||
}
|
||||
c.adv = adv;
|
||||
// The snapped advance no longer includes the shaped kerning adjustment.
|
||||
c.kern = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -268,13 +268,13 @@ impl<'e> Breaker<'e> {
|
||||
let lo = self.row_left(pl);
|
||||
// A Top-and-Bottom object ending in the paragraph's space before (or reaching into
|
||||
// its first line) is a block the first line must start below, with that space before
|
||||
// laid out again under it (#7143). Exclusions are relative to the first line's
|
||||
// original top (0), so keep the band anchored there (`[-before, est_h]`) even after
|
||||
// `row_spans` or `skip_row` moves `self.top` down past a side-wrapping object (#8614):
|
||||
// only the space the flow actually laid out above 0 holds a space-before obstruction.
|
||||
// laid out again under it (#7143). Exclusions are relative to the first line, so look
|
||||
// `space_before` above it too: the space the flow actually laid out, so an object
|
||||
// above a gap that collapsing, contextual spacing or a page top removed takes no
|
||||
// room, while the part of a merged gap that was laid out still does.
|
||||
if self.first && self.space_before > 0.0 {
|
||||
let before = self.space_before;
|
||||
let row = (-before, self.est_h + before, self.table_h);
|
||||
let row = (self.top - before, self.est_h + before, self.table_h);
|
||||
if let Some(below) = self
|
||||
.exclusions
|
||||
.iter()
|
||||
|
||||
@@ -8896,73 +8896,6 @@ fn moved_kept_paragraph_lays_out_no_space_before_under_an_object_at_its_top() {
|
||||
assert!((top - bottom).abs() < 0.01, "the first line {top} starts at the rule's bottom {bottom}, with no space before laid out above it");
|
||||
}
|
||||
|
||||
/// #8614: when a side-wrapping object pushes the first line down before it is placed, the
|
||||
/// space-before Top-and-Bottom band must stay anchored to the first line's original top (0), not
|
||||
/// shift down with `self.top` into the paragraph's area and re-apply `space_before` below a
|
||||
/// Top-and-Bottom object ending there.
|
||||
#[test]
|
||||
fn side_wrapping_push_does_not_shift_space_before_band_into_para_area() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
const BEFORE: f32 = 12.0;
|
||||
|
||||
let build = |with_top_bottom: bool| {
|
||||
let mut d = Document::from_text("Anchor line.\nProbe line with several words in it.");
|
||||
for block in &mut d.body {
|
||||
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
}
|
||||
}
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(1).map(Arc::make_mut) {
|
||||
p.props.space_before = Some(BEFORE);
|
||||
}
|
||||
let plain = lay(&d);
|
||||
let top_of = |l: &DocLayout, block: u32| {
|
||||
l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
Placed::Lines { story: StoryRef::Body, path, y, .. } if path.0 == [block] => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let anchor_y = top_of(&plain, 0);
|
||||
let probe_y = top_of(&plain, 1);
|
||||
|
||||
// Full-width side-wrapping object starting at the probe's original top and extending 30 pt
|
||||
// down, pushing the probe's first line to probe_y + 30.
|
||||
let side = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: probe_y - anchor_y, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(500.0, 30.0, side), &Default::default()).unwrap();
|
||||
|
||||
if with_top_bottom {
|
||||
// Top-and-Bottom object inside the side-wrapped vertical span (18..22 pt below probe_y),
|
||||
// below the original first line [0, 14] and above the Square object's bottom (30).
|
||||
let tb = Float {
|
||||
wrap: Wrap::TopAndBottom,
|
||||
h_rel: Anchor::Column,
|
||||
v_rel: Anchor::Paragraph,
|
||||
y: probe_y + 18.0 - anchor_y,
|
||||
..Default::default()
|
||||
};
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 4.0, tb), &Default::default()).unwrap();
|
||||
}
|
||||
let l = lay(&d);
|
||||
top_of(&l, 1)
|
||||
};
|
||||
|
||||
let plain_wrap_top = build(false);
|
||||
let with_tb_top = build(true);
|
||||
assert!(
|
||||
(with_tb_top - plain_wrap_top).abs() < 0.01,
|
||||
"probe first line {with_tb_top} must stay at plain-wrap position {plain_wrap_top} without re-applying space_before"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_follows_its_paragraph_to_the_next_page() {
|
||||
crate::test_fonts();
|
||||
@@ -19719,78 +19652,3 @@ fn evict_unused_caps_stale_entries_across_repeated_edits() {
|
||||
assert!(c.len() <= base + 1025, "stale cache entries must be bounded (got {}, base {base})", c.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// #8613: a Top-and-Bottom object ending above a paragraph's applied space before cannot affect
|
||||
/// it, so paragraphs below keep empty exclusions and hit the cache when shifted vertically, and
|
||||
/// paragraphs below it in a box are not laid out twice.
|
||||
#[test]
|
||||
fn top_and_bottom_float_above_space_before_keeps_cache_hits_on_shift() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
let mut d = Document::from_text(&"line\n".repeat(12));
|
||||
for block in &mut d.body {
|
||||
if let wordcraft_doc::Block::Para(p) = Arc::make_mut(block) {
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
}
|
||||
}
|
||||
if let Some(wordcraft_doc::Block::Para(p)) = d.body.get_mut(4).map(Arc::make_mut) {
|
||||
p.props.space_before = Some(12.0);
|
||||
}
|
||||
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
|
||||
d.insert_object(&Pos::body(0, 0), rect_shape(144.0, 10.0, f), &Default::default()).unwrap();
|
||||
|
||||
let mut c = LayoutCache::new();
|
||||
let before = layout(&d, &mut c, &LayoutOptions::default());
|
||||
let y_before = before.caret(&Pos::body(6, 0)).unwrap().top;
|
||||
let misses = c.misses;
|
||||
|
||||
d.insert_text(&Pos::body(2, 0), &"word ".repeat(30), &Default::default()).unwrap();
|
||||
let after = layout(&d, &mut c, &LayoutOptions::default());
|
||||
let y_after = after.caret(&Pos::body(6, 0)).unwrap().top;
|
||||
assert!(y_after > y_before + 10.0, "paragraphs below shifted down ({y_before} -> {y_after})");
|
||||
assert_eq!(c.misses, misses + 1, "only the edited paragraph should miss the cache");
|
||||
}
|
||||
|
||||
/// #8613: in table cells and other boxes, paragraphs below a Top-and-Bottom float (and clear of
|
||||
/// its space-before band) get empty exclusions, so they are laid out once and hit the cache when
|
||||
/// shifted vertically.
|
||||
#[test]
|
||||
fn top_and_bottom_float_in_cell_keeps_cache_hits_on_shift() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
let mut d = Document::new();
|
||||
let mut t = Table::new(1, 1, 468.0);
|
||||
t.props.fixed = true;
|
||||
t.rows[0].cells[0].blocks = (0..6)
|
||||
.map(|i| {
|
||||
let mut p = Paragraph::with_text(&format!("cell line {i}"), Default::default());
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(12.0));
|
||||
p.props.space_before = Some(0.0);
|
||||
p.props.space_after = Some(0.0);
|
||||
wordcraft_doc::para_block(p)
|
||||
})
|
||||
.collect();
|
||||
d.body = vec![Arc::new(wordcraft_doc::Block::Table(t))];
|
||||
let cell_pos = |para: usize| Pos { story: StoryRef::Body, path: Path(vec![0, 0, 0, para as u32]), off: 0 };
|
||||
let f = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
|
||||
d.insert_object(&cell_pos(0), rect_shape(100.0, 10.0, f), &Default::default()).unwrap();
|
||||
|
||||
let mut c = LayoutCache::new();
|
||||
let before = layout(&d, &mut c, &LayoutOptions::default());
|
||||
let y_before = before.caret(&cell_pos(4)).unwrap().top;
|
||||
// Paragraph 0 holds the float so it lays out twice; paragraphs 1..6 sit below it and lay out once each.
|
||||
assert_eq!(c.misses, 7, "paragraphs below the float should be laid out only once");
|
||||
let misses = c.misses;
|
||||
|
||||
d.insert_text(&cell_pos(1), &"word ".repeat(30), &Default::default()).unwrap();
|
||||
let after = layout(&d, &mut c, &LayoutOptions::default());
|
||||
let y_after = after.caret(&cell_pos(4)).unwrap().top;
|
||||
assert!(y_after > y_before + 10.0, "cell paragraphs below shifted down ({y_before} -> {y_after})");
|
||||
assert_eq!(c.misses, misses + 1, "only the edited cell paragraph should miss the cache");
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use crate::*;
|
||||
use wordcraft_doc::Pos;
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{DocGrid, DocGridType};
|
||||
|
||||
@@ -98,39 +97,3 @@ fn character_grid_places_east_asian_text_on_the_pitch() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exact_character_grid_line_fits_all_its_cells_with_kerning() {
|
||||
crate::test_fonts();
|
||||
let text = "AVAVAVAVAVAVAVAVAVAV";
|
||||
let mut grid = with_grid(text, DocGridType::SnapToChars, 0);
|
||||
let styles = std::sync::Arc::make_mut(&mut grid.styles);
|
||||
styles.default_chr.font = Some("Inter".into());
|
||||
styles.default_chr.kern = Some(1.0);
|
||||
|
||||
let set_width = |doc: &mut Document, width: f32| {
|
||||
let indent = doc.last_section.text_width() - width;
|
||||
doc.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent)).unwrap();
|
||||
};
|
||||
|
||||
// In proportional text the fifth letter still needs its unkerned width at a line break.
|
||||
let mut plain = grid.clone();
|
||||
plain.last_section.doc_grid = None;
|
||||
let wide = lay(&plain);
|
||||
let para = wide.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
|
||||
let kern = para.clusters[4].kern;
|
||||
assert!(kern < -0.02, "the test font must kern the pair across the break");
|
||||
set_width(&mut plain, paired - kern / 2.0);
|
||||
assert_eq!(super::body_lines(&lay(&plain), text)[0], "AVAV");
|
||||
|
||||
let size = para::Grid::of(&grid, &grid.last_section).font_size;
|
||||
grid.last_section.doc_grid.as_mut().unwrap().char_space = DocGrid::char_space_for(20.0, size);
|
||||
let pitch = grid.last_section.grid_char_pitch(size).unwrap();
|
||||
set_width(&mut grid, 5.0 * pitch);
|
||||
for kern in [0.0, 1.0] {
|
||||
std::sync::Arc::make_mut(&mut grid.styles).default_chr.kern = Some(kern);
|
||||
let got = super::body_lines(&lay(&grid), text);
|
||||
assert_eq!(got[0], "AVAVA", "kerning threshold {kern}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +133,6 @@ impl WordApp {
|
||||
user_origin: false,
|
||||
read_aloud_error: None,
|
||||
autosave_path: None,
|
||||
read_from: None,
|
||||
saves_in_flight: Vec::new(),
|
||||
fallback_chooser: false,
|
||||
font_generation: wordcraft_fonts::FontDb::global().generation(),
|
||||
|
||||
@@ -176,11 +176,7 @@ impl WordApp {
|
||||
return Err(e.into());
|
||||
}
|
||||
if id == "file.autosave" {
|
||||
let r = self.set_autosave(¶ms);
|
||||
if let Err(e) = &r {
|
||||
self.status(e.clone());
|
||||
}
|
||||
return r;
|
||||
return self.set_autosave(¶ms);
|
||||
}
|
||||
if let Some(r) = table_pen::toggle(self, id, ¶ms) {
|
||||
return r;
|
||||
@@ -330,8 +326,13 @@ impl WordApp {
|
||||
self.recovery_seen = true;
|
||||
self.sync_document();
|
||||
}
|
||||
if let Ok(v) = &r {
|
||||
self.note_file_on_disk(id, ¶ms, v);
|
||||
// An explicit save to the document's own file lets AutoSave keep writing there.
|
||||
if let Ok(v) = &r
|
||||
&& matches!(id, "file.save" | "file.saveAs")
|
||||
&& v.get("saved").and_then(Value::as_bool) == Some(true)
|
||||
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
|
||||
{
|
||||
self.autosave_path = self.session.path.clone();
|
||||
}
|
||||
// A Markdown file edited in the formatted view was written out again, not kept as it was.
|
||||
if let Ok(v) = &r
|
||||
@@ -348,9 +349,6 @@ impl WordApp {
|
||||
if self.autosave_path.as_ref() == Some(&old) {
|
||||
self.autosave_path = self.session.path.clone();
|
||||
}
|
||||
if self.read_from.as_ref() == Some(&old) {
|
||||
self.read_from = self.session.path.clone();
|
||||
}
|
||||
let old = old.to_string_lossy();
|
||||
self.ui.recent.retain(|r| *r != old);
|
||||
}
|
||||
@@ -436,25 +434,6 @@ impl WordApp {
|
||||
r
|
||||
}
|
||||
|
||||
/// Which file on disk the document is in, after `file.save`, `file.saveAs` or `file.open`.
|
||||
fn note_file_on_disk(&mut self, id: &str, params: &Value, v: &Value) {
|
||||
// An explicit save to the document's own file lets AutoSave keep writing there.
|
||||
if matches!(id, "file.save" | "file.saveAs")
|
||||
&& v.get("saved").and_then(Value::as_bool) == Some(true)
|
||||
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
|
||||
{
|
||||
self.autosave_path = self.session.path.clone();
|
||||
self.read_from = self.session.path.clone();
|
||||
}
|
||||
// A file read from disk may have AutoSave turned on for it; one opened from bytes only
|
||||
// names a file it never read.
|
||||
// `file.open` without a path only asks for the picker, and `data` that isn't a string is
|
||||
// ignored (the file is read from disk).
|
||||
if id == "file.open" && params.get("path").and_then(Value::as_str).is_some() && v.get("alreadyOpen").and_then(Value::as_bool) == Some(false) {
|
||||
self.read_from = if params.get("data").and_then(Value::as_str).is_some() { None } else { self.session.path.clone() };
|
||||
}
|
||||
}
|
||||
|
||||
fn after_command(&mut self, id: &str) {
|
||||
self.canvas.glide.restart(craft::platform::clock::monotonic_ms());
|
||||
if id == "view.outline" {
|
||||
|
||||
@@ -285,6 +285,16 @@ impl WordApp {
|
||||
if self.raise_closing().is_some() {
|
||||
return CloseDecision::Hold;
|
||||
}
|
||||
// Nothing is open, so nothing to ask about (also under a windowless root, whose last document window going is
|
||||
// what asks).
|
||||
if self.session.documents().is_empty() {
|
||||
return CloseDecision::Close;
|
||||
}
|
||||
// A windowless root has no window of its own: its close is a quit (the OS quit, or the last document window
|
||||
// going), never one window's close.
|
||||
if self.ctx.as_ref().is_some_and(craft::ui::runtime::windows::windowless_root) {
|
||||
return if self.close_requested() { CloseDecision::Close } else { CloseDecision::Hold };
|
||||
}
|
||||
if self.closes_a_window() {
|
||||
// The root window's close button closes that window alone (File › Close in it, which asks
|
||||
// about unsaved changes first); the framework leaves the root's window open on `Hold`, and
|
||||
@@ -544,6 +554,16 @@ impl WordApp {
|
||||
if self.closes_only_its_window("file.close", params) && self.close_window_only() {
|
||||
return Ok(json!({"closed": true, "window": true}));
|
||||
}
|
||||
if params.get("save").and_then(Value::as_bool) == Some(true) {
|
||||
// A comment still being typed refuses before anything is written.
|
||||
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
|
||||
return Err(e.into());
|
||||
}
|
||||
// Automation's `save: true`: write the document, then close it. Never a prompt (spec rule 8).
|
||||
if let Some(pending) = self.save_for_close()? {
|
||||
return Ok(pending);
|
||||
}
|
||||
}
|
||||
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
|
||||
return Err(e.into());
|
||||
}
|
||||
@@ -578,6 +598,24 @@ impl WordApp {
|
||||
Ok(json!({"closed": true}))
|
||||
}
|
||||
|
||||
/// `file.close` with `save: true`: save the shown document if it has unsaved work. `Some` is
|
||||
/// the reply when the save finishes later (the browser's picker). A document with no file
|
||||
/// to write has nowhere to save without asking, so that is an error, not a prompt.
|
||||
fn save_for_close(&mut self) -> Result<Option<Value>, String> {
|
||||
if !self.document_unsaved() {
|
||||
return Ok(None);
|
||||
}
|
||||
if self.session.path.is_none() || self.legacy_word_path() {
|
||||
return Err("the document has no file to save to: use file.saveAs first, or pass {\"force\": true} to discard it".into());
|
||||
}
|
||||
match self.save_for_prompt()? {
|
||||
PromptSave::Saved => Ok(None),
|
||||
// lean: only the browser picker saves later and it has no control channel, so the close is not resumed.
|
||||
PromptSave::Later => Ok(Some(json!({"pending": "save"}))),
|
||||
PromptSave::NotSaved => Err("the document was not saved, so it stays open".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// These paths have readers but no writer, so an interactive save needs another format.
|
||||
pub(super) fn legacy_word_path(&self) -> bool {
|
||||
self.session
|
||||
@@ -684,31 +722,13 @@ impl WordApp {
|
||||
self.autosave && self.autosave_block().is_none()
|
||||
}
|
||||
|
||||
/// What the AutoSave switch can't lift: [`Self::autosave_block`], less a file read from disk
|
||||
/// here, which the switch turns on (#3307). A document opened from bytes stays blocked.
|
||||
pub fn autosave_switch_block(&self) -> Option<AutoSaveBlock> {
|
||||
self.autosave_block().filter(|b| *b != AutoSaveBlock::NotSavedHere || self.read_from != self.session.path)
|
||||
}
|
||||
|
||||
/// `file.autosave` (the AutoSave switch, and scripts): `value` turns AutoSave on or off;
|
||||
/// without it, it toggles what the switch shows. Turning it on for a document AutoSave can't
|
||||
/// cover is an error that says why, instead of a switch that is on but saves nothing (#196).
|
||||
/// Turning it on for a file only opened here is the go-ahead a save gives (#3307), when the
|
||||
/// document was read from that file; turning it off withdraws the go-ahead for this document.
|
||||
pub(super) fn set_autosave(&mut self, params: &Value) -> Result<Value, String> {
|
||||
let on = match params.get("value") {
|
||||
None => !self.autosaves(),
|
||||
Some(Value::Bool(on)) => *on,
|
||||
Some(_) => return Err("`value` must be true or false".into()),
|
||||
};
|
||||
if on && self.autosave_block().is_some() {
|
||||
if let Some(block) = self.autosave_switch_block() {
|
||||
return Err(block.reason());
|
||||
}
|
||||
self.autosave_path = self.session.path.clone();
|
||||
}
|
||||
if !on {
|
||||
self.autosave_path = None;
|
||||
let on = params.get("value").and_then(Value::as_bool).unwrap_or(!self.autosaves());
|
||||
if on && let Some(block) = self.autosave_block() {
|
||||
return Err(block.reason());
|
||||
}
|
||||
self.autosave = on;
|
||||
self.session.autosave = on;
|
||||
|
||||
@@ -30,7 +30,7 @@ struct BalloonItems {
|
||||
}
|
||||
|
||||
/// Comment balloons in the markup area right of each page, joined to their anchors, with each comment's replies in
|
||||
/// its card. Clicking a card selects it, like Word: a double click makes its text editable in place, with Reply, Resolve and
|
||||
/// its card. Clicking a card selects it, like Word: its text becomes editable in place, with Reply, Resolve and
|
||||
/// Delete (the same commands as the Comments pane).
|
||||
pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::PageViewOutput, layout: &DocLayout) {
|
||||
app.canvas.balloon_rects.clear();
|
||||
@@ -63,26 +63,6 @@ pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::P
|
||||
for edit in shown.edits {
|
||||
apply(app, &cards, edit);
|
||||
}
|
||||
open_edit_on_double_click(app, ui);
|
||||
}
|
||||
|
||||
/// A double click on the selected card's own text opens its comment for editing, as craft's comments pane does. A click
|
||||
/// that lands in a field or on a button (Reply, Resolve, the menu) is not one.
|
||||
// lean: mouse only; a keyboard path (Enter/F2 on the selected card) is a follow-up.
|
||||
fn open_edit_on_double_click(app: &mut WordApp, ui: &Ui) {
|
||||
let Some(id) = app.canvas.selected_balloon() else { return };
|
||||
if app.canvas.comments.editing.is_some() || ui.ctx().egui_wants_keyboard_input() {
|
||||
return;
|
||||
}
|
||||
let at = ui.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary).then(|| i.pointer.interact_pos())).flatten();
|
||||
let Some(at) = at else { return };
|
||||
let on_card = app.canvas.balloon_rects.iter().any(|(i, r)| *i == id && r.contains(at));
|
||||
if !on_card || !crate::app::command_board::command_enabled(app, "review.editComment") {
|
||||
return;
|
||||
}
|
||||
let Some(c) = app.session.doc.comments.get(&id) else { return };
|
||||
let text = app.session.doc.plain_text(StoryRef::Part(c.part));
|
||||
app.canvas.comments.edit(thread_id(id), 0, text);
|
||||
}
|
||||
|
||||
/// Applies what a card reported through the commands the Comments pane uses.
|
||||
@@ -263,17 +243,25 @@ fn write_back(app: &mut WordApp, id: u32) {
|
||||
let _ = crate::panes::commit_reply(app, id);
|
||||
}
|
||||
|
||||
/// Makes comment `id` the selected card, writing back the draft of the one edited before. As in Word, selecting a card
|
||||
/// puts no message into edit (that hides its Reply); an edit starts on a double click on the selected card.
|
||||
/// Makes comment `id` the selected card with its own text open for editing, writing back the draft of the one edited
|
||||
/// before. The card selects itself on a click; this opens its edit so the field has the keyboard.
|
||||
fn focus_balloon(app: &mut WordApp, id: u32) {
|
||||
let before = app.canvas.comments.editing.as_ref().and_then(|(t, ..)| app_id(*t)).filter(|b| *b != id);
|
||||
if let Some(before) = before {
|
||||
write_back(app, before);
|
||||
}
|
||||
app.canvas.comments.selected = craft::behavior::Selection::single(thread_id(id));
|
||||
// Where comments can't change (a read-only document) the card is selected with no edit open: nothing is typed.
|
||||
let editable = crate::app::command_board::command_enabled(app, "review.editComment");
|
||||
let text = app.session.doc.comments.get(&id).filter(|_| editable).map(|c| app.session.doc.plain_text(StoryRef::Part(c.part)));
|
||||
let thread = thread_id(id);
|
||||
let comments = &mut app.canvas.comments;
|
||||
comments.selected = craft::behavior::Selection::single(thread);
|
||||
if comments.editing.as_ref().is_none_or(|(t, ..)| *t != thread) {
|
||||
comments.editing = text.map(|t| (thread, 0, t));
|
||||
}
|
||||
}
|
||||
|
||||
/// Select a comment's balloon (no edit opens), writing back any edit in the one selected before.
|
||||
/// Select a comment's balloon (its text gets the keyboard), writing back any edit in the one selected before.
|
||||
pub fn select_balloon(app: &mut WordApp, id: u32) {
|
||||
if app.canvas.selected_balloon() == Some(id) {
|
||||
return;
|
||||
|
||||
@@ -46,20 +46,6 @@ fn click_at(h: &mut H, at: Pos2) {
|
||||
steps(h, 3);
|
||||
}
|
||||
|
||||
/// A primary double click at `at`: two clicks a few frames apart, inside egui's double click delay.
|
||||
fn double_click_at(h: &mut H, at: Pos2) {
|
||||
// Let the click before it age out, or the pair would count as a triple click.
|
||||
steps(h, 40);
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
for _ in 0..2 {
|
||||
h.event(button(at, egui::PointerButton::Primary, true));
|
||||
h.app_frame();
|
||||
h.event(button(at, egui::PointerButton::Primary, false));
|
||||
h.app_frame();
|
||||
}
|
||||
steps(h, 3);
|
||||
}
|
||||
|
||||
/// A primary drag from `from` to `to` in six moves.
|
||||
fn drag_between(h: &mut H, from: Pos2, to: Pos2) {
|
||||
h.event(egui::Event::PointerMoved(from));
|
||||
@@ -209,7 +195,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
|
||||
let step = 4.5_f32;
|
||||
let near = |stops: &[(f32, TabAlign)], want: f32| stops.len() == 1 && stops[0].1 == TabAlign::Center && (stops[0].0 - want).abs() <= step;
|
||||
// Lets the double-click time pass before the next press.
|
||||
let settle = |h: &mut H| steps(h, 40);
|
||||
let settle = |h: &mut H| steps(h, 30);
|
||||
let stops = |h: &H| {
|
||||
let s = &h.state().session;
|
||||
let para = s.doc.para_at(&s.sel.focus).expect("a paragraph");
|
||||
@@ -267,27 +253,19 @@ fn comment_harness() -> (H, u32) {
|
||||
a.run("select.text", json!({"text": "text"})).unwrap();
|
||||
let id = a.run("review.newComment", json!({"text": "Original"})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
(window_dt(a, Some(1.0 / 60.0)), id)
|
||||
(window(a), id)
|
||||
}
|
||||
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected with no edit open (as in Word), then
|
||||
/// a double click opens its message for editing, and takes the keyboard in its field.
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected and its own
|
||||
/// edit has the keyboard in its field.
|
||||
fn click_balloon(h: &mut H, id: u32) {
|
||||
select_balloon_card(h, id);
|
||||
open_edit(h, id);
|
||||
}
|
||||
|
||||
/// Double-clicks comment `id`'s card to open message 0 for editing, unless a draft is already open (a refused one
|
||||
/// is kept), and clicks into its field. Nothing opens where comments can't change.
|
||||
fn open_edit(h: &mut H, id: u32) {
|
||||
if crate::app::command_board::command_enabled(h.state(), "review.editComment") {
|
||||
if h.state().canvas.comments.editing.is_none() {
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
double_click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert!(h.state().canvas.comments.editing.is_some(), "a double click on the card opens its edit");
|
||||
}
|
||||
steps(h, 2);
|
||||
}
|
||||
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
|
||||
steps(h, 2);
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
|
||||
// The selected card opens its own edit, a framework text field, which takes the keyboard by a click in it
|
||||
// (none opens where comments can't change).
|
||||
use egui::accesskit::Role;
|
||||
let field = h
|
||||
.query_by_role_and_label(Role::MultilineTextInput, "Edit")
|
||||
@@ -299,15 +277,6 @@ fn open_edit(h: &mut H, id: u32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clicks comment `id`'s card (from no selected balloon): it is selected with no edit open, so Reply shows.
|
||||
fn select_balloon_card(h: &mut H, id: u32) {
|
||||
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
|
||||
steps(h, 2);
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
|
||||
}
|
||||
|
||||
/// Types `text` into the field that has the keyboard.
|
||||
fn type_in(h: &mut H, text: &str) {
|
||||
h.event(egui::Event::Text(text.into()));
|
||||
@@ -358,7 +327,7 @@ fn an_empty_comment_balloon_deletes() {
|
||||
}
|
||||
let id = a.run("review.newComment", json!({})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
let mut h = window_dt(a, Some(1.0 / 60.0));
|
||||
let mut h = window(a);
|
||||
click_balloon(&mut h, id);
|
||||
let resolve = h.get_by_label("Resolve").rect().center();
|
||||
click_at(&mut h, resolve);
|
||||
@@ -413,7 +382,7 @@ fn a_refused_comment_edit_keeps_the_draft() {
|
||||
#[test]
|
||||
fn replying_to_a_comment_from_its_balloon_posts_the_reply() {
|
||||
let (mut h, id) = comment_harness();
|
||||
select_balloon_card(&mut h, id);
|
||||
click_balloon(&mut h, id);
|
||||
h.get_by_label("Reply").click();
|
||||
steps(&mut h, 3);
|
||||
type_in(&mut h, "A reply");
|
||||
|
||||
@@ -76,43 +76,16 @@ fn new_app() -> WordApp {
|
||||
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
|
||||
}
|
||||
|
||||
/// How [`autosave_harness`] has the saved file in its window.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Reopen {
|
||||
/// The window that saved it.
|
||||
No,
|
||||
/// Opened in a fresh window, read from disk.
|
||||
FromDisk,
|
||||
/// Opened in a fresh window from its bytes, which only names the file.
|
||||
FromBytes,
|
||||
}
|
||||
|
||||
/// A saved .docx (so AutoSave can cover it), or the same file opened in a fresh window as
|
||||
/// `reopen` says, with the title bar drawn over it. `files` answers a later Save As pick.
|
||||
fn autosave_harness(
|
||||
reopen: Reopen,
|
||||
files: &std::sync::Arc<craft::host::ScriptedFiles>,
|
||||
) -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}-{reopen:?}", std::process::id()));
|
||||
/// A saved .docx (so AutoSave can cover it) in the harness.
|
||||
fn autosave_harness() -> (egui_kittest::Harness<'static, WordApp>, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("wordcraft-ui-autosave-label-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("draft.docx");
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
|
||||
.with_host(std::sync::Arc::new(craft::host::Host::builder(crate::APP).files(files.clone()).build()));
|
||||
let mut a = new_app();
|
||||
a.run("text.insert", json!({"text": "Hello"})).unwrap();
|
||||
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert!(a.autosaves(), "a saved .docx is covered by AutoSave");
|
||||
if reopen != Reopen::No {
|
||||
a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default())
|
||||
.with_host(std::sync::Arc::new(craft::host::Host::builder(crate::APP).files(files.clone()).build()));
|
||||
if reopen == Reopen::FromBytes {
|
||||
let data = wordcraft_engine::cmd::insert::base64_encode(&std::fs::read(&path).unwrap());
|
||||
a.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap();
|
||||
} else {
|
||||
a.run("file.open", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
}
|
||||
assert!(!a.autosaves(), "an opened file waits for the user's go-ahead");
|
||||
}
|
||||
let h = harness(a);
|
||||
(h, dir)
|
||||
}
|
||||
@@ -120,8 +93,7 @@ fn autosave_harness(
|
||||
/// #3370: clicking the AutoSave switch label toggles AutoSave on and off.
|
||||
#[test]
|
||||
fn clicking_the_autosave_label_toggles_autosave() {
|
||||
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
|
||||
let (mut h, dir) = autosave_harness(Reopen::No, &files);
|
||||
let (mut h, dir) = autosave_harness();
|
||||
assert!(h.state().autosaves());
|
||||
h.get_by_label("AutoSave").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
@@ -132,35 +104,6 @@ fn clicking_the_autosave_label_toggles_autosave() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #3307: a file opened, not saved, in this window had the switch greyed out, and clicking it
|
||||
/// asked for Save As. Clicking it now turns AutoSave on for that file.
|
||||
#[test]
|
||||
fn clicking_autosave_on_an_opened_file_turns_it_on() {
|
||||
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
|
||||
let (mut h, dir) = autosave_harness(Reopen::FromDisk, &files);
|
||||
h.get_by_label("AutoSave").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(h.state().autosaves(), "the switch turned AutoSave on");
|
||||
assert!(h.state().dialog_host.is_empty() && h.state().file_dialog.is_none(), "without Save As");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A document opened from bytes only names its file, so the switch can't hand that file to
|
||||
/// AutoSave: it shows the block and clicking it asks for Save As, after which AutoSave is on.
|
||||
#[test]
|
||||
fn clicking_autosave_on_a_document_opened_from_bytes_asks_for_save_as() {
|
||||
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new());
|
||||
let (mut h, dir) = autosave_harness(Reopen::FromBytes, &files);
|
||||
assert_eq!(h.state().autosave_switch_block(), Some(crate::AutoSaveBlock::NotSavedHere));
|
||||
let copy = dir.join("copy.docx");
|
||||
files.queue(craft::host::Picked::Paths(vec![copy.clone()]));
|
||||
h.get_by_label("AutoSave").click();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
assert!(copy.is_file(), "Save As saved a copy");
|
||||
assert!(h.state().autosaves(), "AutoSave covers the copy");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #701: the arrow beside Undo lists the session's undo steps, newest first; clicking the third
|
||||
/// row undoes three steps at once.
|
||||
#[test]
|
||||
@@ -801,11 +744,8 @@ fn the_autosave_knob_sits_right_when_on_and_mirrors_right_to_left() {
|
||||
a.ui.language = "en".into();
|
||||
// Mark the document as saved here without touching disk (`session.dirty` stays false).
|
||||
let path = std::path::PathBuf::from("draft.docx");
|
||||
// A save to the document's own file records both (`note_file_on_disk`): the file is read
|
||||
// from disk, so the switch can be turned on again after it has been turned off.
|
||||
a.session.path = Some(path.clone());
|
||||
a.autosave_path = Some(path.clone());
|
||||
a.read_from = Some(path);
|
||||
a.autosave_path = Some(path);
|
||||
|
||||
let mut h = harness(a);
|
||||
// Arabic UI labels draw even when built without `CRAFT_FONTS_DIR` (embedded Arabic faces).
|
||||
|
||||
@@ -104,8 +104,7 @@ fn leading(app: &mut WordApp, ui: &mut Ui) -> Option<egui::Rect> {
|
||||
/// The AutoSave switch: off and with the reason as its tooltip when AutoSave can't cover the document (#196,
|
||||
/// #176); a click then offers Save As where that helps. Returns the rect it took.
|
||||
fn autosave(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
// A file read from disk here is off, not blocked: the switch turns it on (#3307).
|
||||
let block = app.autosave_switch_block();
|
||||
let block = app.autosave_block();
|
||||
let on = app.autosaves() && block.is_none();
|
||||
let tip = block.as_ref().map_or_else(|| tl!("AutoSave saves every change to the file (needs a saved document)").to_string(), |b| b.reason());
|
||||
// The small switch, as the old title bar drew it.
|
||||
|
||||
@@ -5,7 +5,7 @@ use craft::automation::control::{ControlRequest, Reply};
|
||||
use craft::automation::dialogs;
|
||||
use craft::automation::synthetic::input_method;
|
||||
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost};
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost, windowless_root};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::screenshots::render_png;
|
||||
@@ -81,6 +81,13 @@ pub(crate) fn close_refused(app: &WordApp, id: &str, params: &Value) -> Option<&
|
||||
// The document the command closes: `file.close` the shown one, `file.closeDocument` the one
|
||||
// its `id` names (the active one by default) (#3274).
|
||||
let target = match id {
|
||||
// `save: true` is saved, then closed, by `file.close` itself (spec rule 8); a comment
|
||||
// still being typed is not saved by that, so it still refuses.
|
||||
"file.close" if params.get("save").and_then(Value::as_bool) == Some(true) => {
|
||||
let force = params.get("force").and_then(Value::as_bool) == Some(true);
|
||||
let target = app.session.document_id();
|
||||
return (!force && app.document_has_comment_drafts(target)).then_some(COMMENT_UNSAVED);
|
||||
}
|
||||
"file.close" => app.session.document_id(),
|
||||
"file.closeDocument" => match params.get("id") {
|
||||
None | Some(Value::Null) => app.session.document_id(),
|
||||
@@ -89,7 +96,8 @@ pub(crate) fn close_refused(app: &WordApp, id: &str, params: &Value) -> Option<&
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
close_refused_for(app, target, params)
|
||||
let refusal = close_refused_for(app, target, params);
|
||||
if id == "file.close" && refusal == Some(UNSAVED) { Some(UNSAVED_CLOSE) } else { refusal }
|
||||
}
|
||||
|
||||
/// The refusal for closing the document `target` with unsaved work in it: the same work the
|
||||
@@ -109,6 +117,9 @@ fn close_refused_for(app: &WordApp, target: u64, params: &Value) -> Option<&'sta
|
||||
}
|
||||
|
||||
const UNSAVED: &str = "the document has unsaved changes: save it first, or pass {\"force\": true} to discard them and close";
|
||||
/// `file.close` also takes `save` (spec rule 8).
|
||||
const UNSAVED_CLOSE: &str =
|
||||
"unsaved changes: pass save or force ({\"save\": true} writes the document, then closes; {\"force\": true} closes without saving)";
|
||||
const COMMENT_UNSAVED: &str = "a comment is still being edited: finish it first, or pass {\"force\": true} to discard it";
|
||||
|
||||
/// Quitting closes every open document, so unsaved work needs the same explicit `force` as
|
||||
@@ -406,7 +417,25 @@ fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
ok(json!({}))
|
||||
}
|
||||
// Close the active window through the same guard as its OS close button.
|
||||
"ui.closeWindow" => ok(json!({"requested": WindowHost::of(ctx).act(app.active_viewport(), WindowAction::Close)})),
|
||||
// `window` names another window by its key; none means the active one (spec rule 8).
|
||||
"ui.closeWindow" => {
|
||||
let viewport = match p.get("window").filter(|w| !w.is_null()) {
|
||||
None => app.active_viewport(),
|
||||
Some(w) => match w.as_u64().and_then(|key| app.window_viewport(key)) {
|
||||
Some(v) => v,
|
||||
None => return err("`window` is not an open window: use a key from view.switchWindows"),
|
||||
},
|
||||
};
|
||||
// Spec rule 4: a close while a Save prompt is up only raises that prompt, so nothing was requested.
|
||||
if app.raise_closing().is_some() {
|
||||
return ok(json!({"requested": false, "reason": "a Save prompt is already open: answer it first"}));
|
||||
}
|
||||
// A windowless root is no window: closing it would end the app, not close a window.
|
||||
if viewport == egui::ViewportId::ROOT && windowless_root(ctx) {
|
||||
return err("no document window is open");
|
||||
}
|
||||
ok(json!({"requested": WindowHost::of(ctx).act(viewport, WindowAction::Close)}))
|
||||
}
|
||||
"ui.clipboard" => clipboard(ctx, p),
|
||||
"ui.replayAt" => {
|
||||
let Some(at) = p.get("at").and_then(Value::as_f64) else { return err("missing `at`") };
|
||||
|
||||
@@ -20,8 +20,6 @@ use crate::{WordApp, panes};
|
||||
pub(crate) struct Parked {
|
||||
/// [`WordApp`]'s `autosave_path`: the file AutoSave writes this document to.
|
||||
autosave_path: Option<std::path::PathBuf>,
|
||||
/// [`WordApp`]'s `read_from`: the file on disk this document was read from or saved to.
|
||||
read_from: Option<std::path::PathBuf>,
|
||||
/// The comment panel's selection and the comment and reply text typed in this document and not
|
||||
/// yet written to it.
|
||||
comments: craft::review::ui::CommentsPanelState,
|
||||
@@ -104,11 +102,7 @@ impl WordApp {
|
||||
if from == to {
|
||||
return false;
|
||||
}
|
||||
let leaving = Parked {
|
||||
autosave_path: self.autosave_path.take(),
|
||||
read_from: self.read_from.take(),
|
||||
comments: std::mem::take(&mut self.canvas.comments),
|
||||
};
|
||||
let leaving = Parked { autosave_path: self.autosave_path.take(), comments: std::mem::take(&mut self.canvas.comments) };
|
||||
if self.session.is_open(from) {
|
||||
self.parked.insert(from, leaving);
|
||||
}
|
||||
@@ -116,7 +110,6 @@ impl WordApp {
|
||||
let seen = back.is_some();
|
||||
let back = back.unwrap_or_default();
|
||||
self.autosave_path = back.autosave_path;
|
||||
self.read_from = back.read_from;
|
||||
self.canvas.comments = back.comments;
|
||||
let session = &self.session;
|
||||
self.parked.retain(|d, _| session.is_open(*d));
|
||||
|
||||
@@ -167,6 +167,19 @@ fn imported_word_close_waits_for_save_as_and_keeps_failed_or_cancelled_drafts()
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Spec rules 5 and 6: cancelling the Save As a quit's Save opened cancels the quit.
|
||||
#[test]
|
||||
fn cancelling_save_as_cancels_the_quit() {
|
||||
let (mut a, files) = async_app();
|
||||
a.run("text.insert", json!({"text": "Draft"})).unwrap();
|
||||
assert!(!a.quit());
|
||||
assert_eq!(a.run("ui.saveChanges", json!({"answer": "save"})).unwrap()["pending"], "saveAs");
|
||||
answer(&files, None);
|
||||
assert_eq!(a.poll_file_dialog().unwrap().unwrap()["done"], false);
|
||||
assert!(a.closing.is_none() && !a.quit_requested && a.session.dirty, "nothing closes, nothing is lost");
|
||||
assert!(!a.quit(), "the next quit asks again");
|
||||
}
|
||||
|
||||
/// A late Save As answer belongs to the imported document that opened the picker: once that
|
||||
/// document is closed, it writes nothing.
|
||||
#[test]
|
||||
|
||||
@@ -509,9 +509,6 @@ pub struct WordApp {
|
||||
/// there. A file that was merely opened isn't rewritten until the user saves it: saving drops
|
||||
/// whatever WordCraft can't represent (content controls, charts, macros…).
|
||||
autosave_path: Option<std::path::PathBuf>,
|
||||
/// The file on disk the document was read from or saved to. A document opened from bytes
|
||||
/// (`file.open` with `data`) only names a file, so the AutoSave switch can't cover it.
|
||||
read_from: Option<std::path::PathBuf>,
|
||||
/// Web: saves the browser's picker hasn't finished yet (#1315).
|
||||
saves_in_flight: Vec<SaveInFlight>,
|
||||
/// The Save Changes prompt this window is running and the command it holds back.
|
||||
|
||||
@@ -20,7 +20,7 @@ pub enum AutoSaveBlock {
|
||||
Unsaved,
|
||||
/// A file in a format that can't keep everything (Markdown, plain text, HTML…), by file name.
|
||||
Format { name: String },
|
||||
/// A file that was opened but not yet saved in this session; the switch shows off and lifts it.
|
||||
/// A file that was opened but not yet saved in this session.
|
||||
NotSavedHere,
|
||||
}
|
||||
|
||||
|
||||
@@ -3251,99 +3251,6 @@ fn autosave_is_unavailable_in_the_browser() {
|
||||
assert!(err.contains("browser"), "{err}");
|
||||
}
|
||||
|
||||
/// #3307: an opened file isn't rewritten until the user says so, but the switch says so
|
||||
/// without Save As: turning it on lets AutoSave write the file.
|
||||
#[test]
|
||||
fn turning_autosave_on_covers_a_file_only_opened_here() {
|
||||
let dir = scratch("autosave-opened");
|
||||
let path = dir.join("report.docx");
|
||||
let mut a = typed();
|
||||
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let mut b = app();
|
||||
b.run("file.open", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(b.autosave_block(), Some(AutoSaveBlock::NotSavedHere));
|
||||
assert_eq!(b.autosave_switch_block(), None, "the switch lifts it itself");
|
||||
b.run("text.insert", json!({"text": "Opened "})).unwrap();
|
||||
b.autosave_tick(monotonic_ms() + 10_000.0);
|
||||
assert!(b.session.dirty, "opening alone never rewrites the file");
|
||||
assert!(b.run("file.autosave", json!({"value": "false"})).is_err());
|
||||
assert!(!b.autosaves(), "a value that isn't a bool grants nothing");
|
||||
assert_eq!(b.run("file.autosave", json!({})).unwrap(), json!({"value": true}));
|
||||
assert!(b.autosaves());
|
||||
b.autosave_tick(monotonic_ms() + 20_000.0);
|
||||
assert!(!b.session.dirty, "AutoSave wrote the opened file");
|
||||
assert!(b.run("file.autosave", json!({"value": false})).is_ok());
|
||||
assert!(!b.autosaves());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `file.open` with `data` only names the file: the switch mustn't let AutoSave write a file of
|
||||
/// that name, which may hold something else entirely.
|
||||
#[test]
|
||||
fn the_autosave_switch_refuses_a_document_opened_from_bytes() {
|
||||
let dir = scratch("autosave-bytes");
|
||||
let path = dir.join("other.docx");
|
||||
let mut a = typed();
|
||||
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let on_disk = std::fs::read(&path).unwrap();
|
||||
let files = Arc::new(ScriptedFiles::new());
|
||||
let mut b = app_with_files(files.clone());
|
||||
let data = wordcraft_engine::cmd::insert::base64_encode(&on_disk);
|
||||
b.execute("file.open", json!({"path": path.to_string_lossy(), "data": data})).unwrap();
|
||||
assert_eq!(b.autosave_block(), Some(AutoSaveBlock::NotSavedHere));
|
||||
assert_eq!(b.autosave_switch_block(), Some(AutoSaveBlock::NotSavedHere), "the switch shows the block");
|
||||
assert!(b.run("file.autosave", json!({"value": true})).is_err());
|
||||
b.status = None;
|
||||
let err = b.run("file.autosave", json!({})).unwrap_err();
|
||||
assert_eq!(status_text(&b), Some(err.as_str()), "the status bar says why");
|
||||
b.run("text.insert", json!({"text": "Bytes "})).unwrap();
|
||||
b.autosave_tick(monotonic_ms() + 10_000.0);
|
||||
assert!(b.session.dirty);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), on_disk, "the named file is untouched");
|
||||
// Open without a path only asks for the picker: it isn't a read of the shown file.
|
||||
script_pick(&files, None);
|
||||
b.run("file.open", json!({"path": null})).unwrap();
|
||||
assert!(b.run("file.autosave", json!({"value": true})).is_err(), "the picker request grants nothing");
|
||||
// A `data` that isn't a string is ignored and the file is read from disk.
|
||||
let mut c = app();
|
||||
c.run("file.open", json!({"path": path.to_string_lossy(), "data": null})).unwrap();
|
||||
assert!(c.run("file.autosave", json!({"value": true})).is_ok(), "read from disk");
|
||||
// Saving is still the way: then AutoSave covers the file.
|
||||
b.run("file.save", json!({})).unwrap();
|
||||
assert!(b.autosaves());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// AutoSave turned off in one document stays off there when another document turns it on: the
|
||||
/// preference is shared, but each document's go-ahead is its own.
|
||||
#[test]
|
||||
fn autosave_turned_off_stays_off_when_another_document_turns_it_on() {
|
||||
let dir = scratch("autosave-two");
|
||||
let (first_path, second_path) = (dir.join("first.docx"), dir.join("second.docx"));
|
||||
let mut c = typed();
|
||||
c.run("file.save", json!({"path": second_path.to_string_lossy()})).unwrap();
|
||||
let mut a = typed();
|
||||
a.run("file.save", json!({"path": first_path.to_string_lossy()})).unwrap();
|
||||
let first = a.session.document_id();
|
||||
let saved = std::fs::read(&first_path).unwrap();
|
||||
assert!(a.autosaves());
|
||||
a.run("file.autosave", json!({"value": false})).unwrap();
|
||||
a.run("file.open", json!({"path": second_path.to_string_lossy()})).unwrap();
|
||||
assert_ne!(a.session.document_id(), first, "the second file opens beside the first");
|
||||
a.run("file.autosave", json!({"value": true})).unwrap();
|
||||
assert!(a.autosaves());
|
||||
a.show_document(first).unwrap();
|
||||
assert!(!a.autosaves(), "the first document's switch is still off");
|
||||
a.run("text.insert", json!({"text": "Later "})).unwrap();
|
||||
a.autosave_tick(monotonic_ms() + 10_000.0);
|
||||
assert!(a.session.dirty);
|
||||
assert_eq!(std::fs::read(&first_path).unwrap(), saved, "the first file is untouched");
|
||||
// Turned back on, it covers the file it was saved to without another save.
|
||||
a.run("file.autosave", json!({"value": true})).unwrap();
|
||||
assert!(a.autosaves());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Cancelling the Open picker (Mod+O) left the document as it was but turned AutoSave off.
|
||||
#[test]
|
||||
fn cancelling_open_keeps_autosave() {
|
||||
|
||||
@@ -186,7 +186,6 @@ impl WordApp {
|
||||
clipboard_published: _,
|
||||
// Per document: the shown document's, swapped with `parked` on a document switch.
|
||||
autosave_path: _,
|
||||
read_from: _,
|
||||
parked: _,
|
||||
// Per window.
|
||||
ui,
|
||||
|
||||
+108
-22
@@ -30,7 +30,8 @@
|
||||
use craft::ui::contract::{BodyCx, Props as _, ShowContainer as _, SizeLimits};
|
||||
// PLAN: assumed `craft::ui::runtime::env::WindowKey` is the facade path of ui-contract's `runtime/env/shell.rs` `WindowKey`.
|
||||
use craft::ui::runtime::env::WindowKey;
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost};
|
||||
use craft::ui::runtime::memory::SaveKey;
|
||||
use craft::ui::runtime::windows::{WindowAction, WindowHost, windowless_root};
|
||||
use craft::ui::shell::DocumentWindow;
|
||||
use craft::ui::style::StyleCx;
|
||||
use craft::window::{Document, WindowId, WindowList, WindowMenu};
|
||||
@@ -112,6 +113,11 @@ pub struct Windows {
|
||||
/// Whether the root OS window had focus in the last pass; a [`DocumentWindow`] reports its own gain
|
||||
/// (`focus_gained`), the root's is read from the window host's facts.
|
||||
root_focused: bool,
|
||||
/// Whether the root entry's window got its first placement (windowless root only: the root has
|
||||
/// no OS window to take the saved place, so the first document window does).
|
||||
root_placed: bool,
|
||||
/// Documents whose window could not open: they get no new window, or every frame would retry.
|
||||
failed_open: Vec<u64>,
|
||||
}
|
||||
|
||||
impl Windows {
|
||||
@@ -119,7 +125,16 @@ impl Windows {
|
||||
pub(crate) fn new(doc: u64) -> Windows {
|
||||
let mut list = WindowList::new();
|
||||
let id = list.open(Window::new(doc, None, None, false));
|
||||
Windows { native: cfg!(not(target_arch = "wasm32")), list, root: id, shown: id, arranged: arrange::State::default(), root_focused: false }
|
||||
Windows {
|
||||
native: cfg!(not(target_arch = "wasm32")),
|
||||
list,
|
||||
root: id,
|
||||
shown: id,
|
||||
arranged: arrange::State::default(),
|
||||
root_focused: false,
|
||||
root_placed: false,
|
||||
failed_open: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether documents get native windows of their own.
|
||||
@@ -192,7 +207,7 @@ impl Windows {
|
||||
/// The viewport window `id` draws in, while its OS window is open: the root's for the root
|
||||
/// entry, else the one the window host names for the window's container.
|
||||
fn viewport_of(&self, ctx: &egui::Context, id: WindowId) -> Option<ViewportId> {
|
||||
if id == self.root {
|
||||
if id == self.root && !windowless_root(ctx) {
|
||||
return Some(ViewportId::ROOT);
|
||||
}
|
||||
WindowHost::of(ctx).viewport_of(window_container_id(id))
|
||||
@@ -212,11 +227,21 @@ impl WordApp {
|
||||
|
||||
/// The egui viewport of the active window, the one focused last: control input,
|
||||
/// `ui.screenshot` and `ui.resize` are its. The root viewport when the windows don't have
|
||||
/// viewports of their own (the web app, embedded viewports) or the window has none yet.
|
||||
/// viewports of their own (the web app, embedded viewports). With a windowless root it is always a
|
||||
/// document viewport (the root has no window to draw, screenshot or take input), the first open one
|
||||
/// when the active window has none yet; the root only before any document window exists.
|
||||
pub fn active_viewport(&self) -> ViewportId {
|
||||
let Some(ctx) = self.ctx.as_ref().filter(|ctx| self.windows.native && WindowHost::of(ctx).opens_windows()) else { return ViewportId::ROOT };
|
||||
let id = self.windows.list.active().unwrap_or(self.windows.shown);
|
||||
self.windows.viewport_of(ctx, id).unwrap_or(ViewportId::ROOT)
|
||||
let own = self.windows.viewport_of(ctx, id);
|
||||
if windowless_root(ctx) { own.or_else(|| self.windows.viewports(ctx).first().copied()) } else { own }.unwrap_or(ViewportId::ROOT)
|
||||
}
|
||||
|
||||
/// The viewport of the window with key `key` (the number `view.switchWindows` and the window
|
||||
/// menu give): `None` when there is no such window or its OS window isn't open yet.
|
||||
pub fn window_viewport(&self, key: u64) -> Option<ViewportId> {
|
||||
let ctx = self.ctx.as_ref().filter(|ctx| self.windows.native && WindowHost::of(ctx).opens_windows())?;
|
||||
self.windows.viewport(ctx, key)
|
||||
}
|
||||
|
||||
/// Whether a close request for the root viewport closes only the window drawn there: true
|
||||
@@ -382,7 +407,12 @@ impl WordApp {
|
||||
let behind = self.windows.list.active();
|
||||
let active = self.session.document_id();
|
||||
for d in self.session.documents() {
|
||||
if d.id == active || Some(d.id) == self.no_document || d.id == self.shown_document || self.windows.of_doc(d.id).is_some() {
|
||||
if d.id == active
|
||||
|| Some(d.id) == self.no_document
|
||||
|| d.id == self.shown_document
|
||||
|| self.windows.of_doc(d.id).is_some()
|
||||
|| self.windows.failed_open.contains(&d.id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
self.windows.list.open(Window::new(d.id, Some(Box::new(WindowUi::new(d.id))), None, true));
|
||||
@@ -462,7 +492,9 @@ impl WordApp {
|
||||
w.requests.push(req.clone());
|
||||
}
|
||||
if let Some(ctx) = &self.ctx {
|
||||
ctx.request_repaint_of(self.windows.viewport(ctx, key).unwrap_or(ViewportId::ROOT));
|
||||
ctx.request_repaint_of(
|
||||
self.windows.viewport(ctx, key).or_else(|| self.windows.viewports(ctx).first().copied()).unwrap_or(ViewportId::ROOT),
|
||||
);
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -535,22 +567,28 @@ impl WordApp {
|
||||
self.after_windows();
|
||||
return;
|
||||
}
|
||||
let raise_root = self.windows.list.get_mut(self.windows.root).is_some_and(|w| std::mem::take(&mut w.raise));
|
||||
if raise_root {
|
||||
WindowHost::of(&ctx).act(ViewportId::ROOT, WindowAction::Focus);
|
||||
}
|
||||
self.draw_entry(ui, self.windows.root.get());
|
||||
let root = self.windows.root;
|
||||
// The root window gaining OS focus makes its entry the active one, as a child's `focus_gained` does.
|
||||
let root_focused = WindowHost::of(&ctx).facts(ViewportId::ROOT).is_some_and(|facts| facts.focused);
|
||||
if root_focused && !std::mem::replace(&mut self.windows.root_focused, root_focused) {
|
||||
self.windows.list.focus(root);
|
||||
// A windowless root has no window: its entry is a document window like the others. With a
|
||||
// visible root (X11) the root window draws the root entry itself.
|
||||
let windowless = windowless_root(&ctx);
|
||||
if !windowless {
|
||||
let raise_root = self.windows.list.get_mut(root).is_some_and(|w| std::mem::take(&mut w.raise));
|
||||
if raise_root {
|
||||
WindowHost::of(&ctx).act(ViewportId::ROOT, WindowAction::Focus);
|
||||
}
|
||||
self.draw_entry(ui, root.get());
|
||||
// The root window gaining OS focus makes its entry the active one, as a child's `focus_gained` does.
|
||||
let root_focused = WindowHost::of(&ctx).facts(ViewportId::ROOT).is_some_and(|facts| facts.focused);
|
||||
if root_focused && !std::mem::replace(&mut self.windows.root_focused, root_focused) {
|
||||
self.windows.list.focus(root);
|
||||
}
|
||||
self.windows.root_focused = root_focused;
|
||||
}
|
||||
self.windows.root_focused = root_focused;
|
||||
let menu = self.window_menu();
|
||||
let step = StyleCx::with_root(&ctx, |cx| cx.tokens.size.window.cascade);
|
||||
let ids: Vec<WindowId> = self.windows.list.ids().filter(|&id| id != root).collect();
|
||||
let ids: Vec<WindowId> = self.windows.list.ids().filter(|&id| windowless || id != root).collect();
|
||||
let mut closes = Vec::new();
|
||||
let mut failed = Vec::new();
|
||||
for id in ids {
|
||||
let Some(w) = self.windows.list.get_mut(id) else { continue };
|
||||
let (raise, place) = (std::mem::take(&mut w.raise), std::mem::take(&mut w.place));
|
||||
@@ -560,17 +598,36 @@ impl WordApp {
|
||||
if raise {
|
||||
window = window.raise();
|
||||
}
|
||||
let main = windowless && id == root;
|
||||
if main {
|
||||
// Every frame, so the place is saved as the user moves or sizes the window.
|
||||
window = window.remember(SaveKey::new("wordcraft.main_window"));
|
||||
}
|
||||
if place && let Some(rect) = self.cascade_from(ui, id, step) {
|
||||
window = window.first_placed(rect);
|
||||
} else if main && !std::mem::replace(&mut self.windows.root_placed, true) {
|
||||
// The first window takes the place the root window had: the saved one, else the default size.
|
||||
let default = egui::Rect::from_min_size(egui::pos2(80.0, 60.0), egui::vec2(1440.0, 920.0));
|
||||
window = window.first_placed(default);
|
||||
}
|
||||
let out = window.show(ui, |ui, cx| self.draw_window(ui, cx, id)).output;
|
||||
let mut drawn = false;
|
||||
let out = window
|
||||
.show(ui, |ui, cx| {
|
||||
drawn = true;
|
||||
self.draw_window(ui, cx, id)
|
||||
})
|
||||
.output;
|
||||
if out.focus_gained {
|
||||
self.windows.list.focus(id);
|
||||
}
|
||||
if out.close_requested.is_some() {
|
||||
closes.push(id);
|
||||
// Asked to close without ever drawing: the window could not be opened.
|
||||
if drawn { closes.push(id) } else { failed.push(id) }
|
||||
}
|
||||
}
|
||||
for id in failed {
|
||||
self.window_failed_to_open(id);
|
||||
}
|
||||
self.window_events(&closes);
|
||||
self.after_windows();
|
||||
}
|
||||
@@ -623,13 +680,42 @@ impl WordApp {
|
||||
/// host asks about ([`WordApp::close_requested`]).
|
||||
fn window_events(&mut self, closes: &[WindowId]) {
|
||||
for &id in closes {
|
||||
if self.quit_requested || self.windows.list.len() <= 1 || !self.windows.list.contains(id) {
|
||||
if self.quit_requested || !self.windows.list.contains(id) {
|
||||
continue;
|
||||
}
|
||||
self.close_window(id.get());
|
||||
if self.windows.list.len() > 1 {
|
||||
self.close_window(id.get());
|
||||
} else if self.ctx.as_ref().is_some_and(windowless_root) {
|
||||
// The only window has no root to take its close: it asks as a quit does, which
|
||||
// ends the app once every document is answered for.
|
||||
if self.raise_closing().is_none()
|
||||
&& self.close_requested()
|
||||
&& let Some(ctx) = &self.ctx
|
||||
{
|
||||
WindowHost::of(ctx).act(ViewportId::ROOT, WindowAction::Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Window `id` was asked to close before it drew: the OS refused it (no window or surface). Its
|
||||
/// entry goes without a Save prompt and the person is told; the document stays open. With no
|
||||
/// other window the app has nothing to show and ends.
|
||||
fn window_failed_to_open(&mut self, id: WindowId) {
|
||||
let Some(doc) = self.windows.list.get(id).map(|w| w.doc) else { return };
|
||||
let name = self.session.documents().into_iter().find(|d| d.id == doc).map(|d| d.title).unwrap_or_default();
|
||||
log::error!("window for document {doc} could not be opened");
|
||||
if self.windows.list.len() <= 1 {
|
||||
// lean: no window to tell the person in; the log has it. Quit rather than run with nothing.
|
||||
self.quit_requested = true;
|
||||
return;
|
||||
}
|
||||
self.windows.failed_open.push(doc);
|
||||
self.windows.list.close(id);
|
||||
self.settle_windows();
|
||||
self.status(crate::i18n::fmt(tl!("A window for “{name}” could not be opened, so that document has no window."), &[("name", &name)]));
|
||||
}
|
||||
|
||||
/// The close button of window `key` (not the last one): File › Close in that window, which
|
||||
/// asks about unsaved changes first.
|
||||
pub(crate) fn close_window(&mut self, key: u64) {
|
||||
|
||||
@@ -38,6 +38,13 @@ impl Rig {
|
||||
Rig { kit: Kit::with(spec), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
|
||||
}
|
||||
|
||||
/// A rig whose root is a windowless logical root: every document window is a child.
|
||||
fn windowless() -> Rig {
|
||||
let spec = craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::ui::testing::windows::FakeSystem::new()))
|
||||
.windowless_root();
|
||||
Rig { kit: Kit::with(spec), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
|
||||
}
|
||||
|
||||
fn ctx(&self) -> egui::Context {
|
||||
self.kit.ctx.clone()
|
||||
}
|
||||
@@ -1100,3 +1107,169 @@ fn mod_shift_v_with_nothing_copied_pastes_text_in_second_window() {
|
||||
rig.frame(&mut a);
|
||||
assert_eq!(text(&a), "pasted", "Mod+Shift+V with nothing copied pastes text in the second OS window");
|
||||
}
|
||||
|
||||
/// A control-channel request, answered as the channel answers it.
|
||||
fn ctl(a: &mut WordApp, rig: &Rig, method: &str, params: serde_json::Value) -> serde_json::Value {
|
||||
let (req, _) = ControlRequest::new(method, params);
|
||||
match crate::control::handle(a, &rig.ctx(), &req) {
|
||||
Reply::Done(v) => v,
|
||||
_ => json!({"ok": false, "error": "not a reply"}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Spec rule 8: `file.close` on unsaved work needs `save` (write, then close) or `force`; a
|
||||
/// document with no file can't be saved without asking, so `save` refuses it.
|
||||
#[test]
|
||||
fn file_close_over_control_needs_save_or_force_and_save_writes_first() {
|
||||
let path = docx_on_disk("close-save", "First");
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("First");
|
||||
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
|
||||
a.run("file.autosave", json!({"value": false})).unwrap();
|
||||
a.run("text.insert", json!({"text": " edited"})).unwrap();
|
||||
let first = a.session.document_id();
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Draft"})).unwrap();
|
||||
let draft = a.session.document_id();
|
||||
rig.frames(&mut a, 2);
|
||||
a.show_window(a.windows.of_doc(first).unwrap());
|
||||
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close"}));
|
||||
assert_eq!(r["ok"], false);
|
||||
assert!(r["error"].as_str().unwrap().contains("pass save or force"), "{r}");
|
||||
assert!(a.session.is_open(first) && a.closing.is_none(), "refused: nothing closes and nothing asks");
|
||||
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"save": true}}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert!(!a.session.is_open(first) && a.closing.is_none());
|
||||
let mut saved = Session::new(wordcraft_doc::Document::new());
|
||||
saved.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(saved.doc.plain_text(StoryRef::Body).trim(), "First edited");
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
|
||||
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"save": true}}));
|
||||
assert_eq!(r["ok"], false, "a never-saved document has nowhere to save: {r}");
|
||||
assert!(a.session.is_open(draft) && a.closing.is_none());
|
||||
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"force": true}}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert!(!a.session.is_open(draft));
|
||||
}
|
||||
|
||||
/// Spec rule 8: `ui.closeWindow` closes the active window, or the one `window` names.
|
||||
#[test]
|
||||
fn ui_closewindow_closes_the_active_window_or_the_one_named() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("One");
|
||||
rig.frames(&mut a, 2);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let middle = a.windows.shown();
|
||||
let middle_vp = a.active_viewport();
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let active_vp = a.active_viewport();
|
||||
assert_ne!(middle_vp, active_vp);
|
||||
let r = ctl(&mut a, &rig, "ui.closeWindow", json!({"window": middle}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
rig.frame(&mut a);
|
||||
assert!(rig.sent(middle_vp, &ViewportCommand::Close) && !rig.sent(active_vp, &ViewportCommand::Close), "only the named window");
|
||||
ctl(&mut a, &rig, "ui.closeWindow", json!({}));
|
||||
rig.frame(&mut a);
|
||||
assert!(rig.sent(active_vp, &ViewportCommand::Close), "no `window`: the active one");
|
||||
assert_eq!(ctl(&mut a, &rig, "ui.closeWindow", json!({"window": 9999}))["ok"], false);
|
||||
}
|
||||
|
||||
/// Spec rule 3: clicking another window while the Save prompt is up brings the prompt back
|
||||
/// (existing focus handling already does; this pins it).
|
||||
#[test]
|
||||
fn clicking_another_window_while_a_prompt_is_up_raises_the_prompt() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("First");
|
||||
rig.frames(&mut a, 2);
|
||||
let first = a.windows.shown();
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Second"})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let child = a.active_viewport();
|
||||
a.close_window(first);
|
||||
rig.frame(&mut a);
|
||||
let owner = a.closing.as_ref().unwrap().window;
|
||||
assert_eq!(owner, first);
|
||||
rig.focus(child);
|
||||
let mut raised = false;
|
||||
for _ in 0..3 {
|
||||
rig.frame(&mut a);
|
||||
raised |= rig.sent(ViewportId::ROOT, &ViewportCommand::Focus);
|
||||
}
|
||||
assert!(raised, "the prompt's window comes to the front");
|
||||
assert_eq!(a.closing.as_ref().map(|c| c.window), Some(first), "still the one prompt, still its window's");
|
||||
}
|
||||
|
||||
/// Spec rule 6: Quit asks about each unsaved document in turn; Cancel on the second stops the
|
||||
/// quit and leaves the remaining windows as they were. A following quit then asks again.
|
||||
#[test]
|
||||
fn quit_with_three_modified_documents_asks_three_times_and_cancel_keeps_two() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("One");
|
||||
rig.frames(&mut a, 2);
|
||||
for t in ["Two", "Three"] {
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": t})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
}
|
||||
assert_eq!(a.window_count(), 3);
|
||||
assert!(!a.quit());
|
||||
assert_eq!(prompt(&a).as_deref(), Some("saveChanges"));
|
||||
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
assert_eq!(prompt(&a).as_deref(), Some("saveChanges"), "the second asks");
|
||||
a.run("ui.saveChanges", json!({"answer": "cancel"})).unwrap();
|
||||
assert!(!a.quit_requested && a.closing.is_none());
|
||||
rig.frames(&mut a, 2);
|
||||
assert_eq!((a.window_count(), a.session.documents().len()), (2, 2), "Cancel keeps the two that are left");
|
||||
assert!(!a.quit(), "the next quit asks again");
|
||||
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
assert!(a.quit_requested);
|
||||
}
|
||||
|
||||
/// Spec rule 1 with the windowless root: the first window is a child like the rest, nothing draws in the root, and
|
||||
/// closing the first of two windows closes that window's document and leaves the other as it was.
|
||||
#[test]
|
||||
fn windowless_root_draws_every_document_in_a_child_and_closes_exactly_the_requested_one() {
|
||||
let mut rig = Rig::windowless();
|
||||
let mut a = app("First");
|
||||
let first_doc = a.session.document_id();
|
||||
rig.frames(&mut a, 2);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Second"})).unwrap();
|
||||
let second_doc = a.session.document_id();
|
||||
rig.frames(&mut a, 3);
|
||||
let viewports = a.windows.viewports(&rig.ctx());
|
||||
assert_eq!(viewports.len(), 2);
|
||||
assert!(!viewports.contains(&ViewportId::ROOT), "the root is no document window");
|
||||
assert_ne!(a.active_viewport(), ViewportId::ROOT);
|
||||
let first_vp = viewports[0];
|
||||
rig.close(first_vp);
|
||||
rig.frames(&mut a, 2);
|
||||
assert_eq!(a.closing.as_ref().unwrap().guard.current(), Some(&first_doc), "the window closed is the one asked about");
|
||||
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
assert!(!a.session.is_open(first_doc) && a.session.is_open(second_doc));
|
||||
assert_eq!(text(&a), "Second");
|
||||
assert_eq!(a.window_count(), 1);
|
||||
}
|
||||
|
||||
/// `ui.closeWindow` says so when nothing was asked: a Save prompt is already up (spec rule 4).
|
||||
#[test]
|
||||
fn ui_closewindow_reports_not_requested_while_a_prompt_is_up() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("One");
|
||||
rig.frames(&mut a, 2);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Two"})).unwrap();
|
||||
rig.frames(&mut a, 2);
|
||||
let first = a.windows.root_key();
|
||||
a.close_window(first);
|
||||
rig.frame(&mut a);
|
||||
assert!(a.closing.is_some());
|
||||
let r = ctl(&mut a, &rig, "ui.closeWindow", json!({}));
|
||||
assert_eq!(r["result"]["requested"], false, "{r}");
|
||||
}
|
||||
|
||||
@@ -13,6 +13,14 @@ draws the document itself, so there it stays as it is. The mechanism comes
|
||||
from the prototype in storytold/craft-libs#584; the framework docs (`docs/craft-framework.md` in
|
||||
craft-libs) will carry it.
|
||||
|
||||
## Amendment 2026-12-03: X11 keeps a visible root
|
||||
|
||||
On X11, XWayland and BSD on X11, egui's windowless root (`RootViewportMode::Windowless`, storytold/egui#91)
|
||||
returns `UnsupportedConfiguration`. There WordCraft falls back to the visible windowed root. The close
|
||||
rules in [the spec](../specs/multi-window-close.md) still apply: the window the user closes is the one that
|
||||
goes, and nothing adopts another document. Revisit when egui supports the windowless root on X11 (asked of
|
||||
Skylar, 2026-12-03).
|
||||
|
||||
## Considered options
|
||||
|
||||
- **Root takes over another document** (the old behaviour): no framework change, but it is the reported bug,
|
||||
|
||||
@@ -115,7 +115,7 @@ let apps move windows, so there Arrange All and Side by Side only resize.
|
||||
| `ui.dialog.set` | `dialog` (an `id` from `ui.inspect`'s `dialogs`, or `"top"`), `field` and `value`, or `fields` (`[{"field", "value"}]`, all or none) | sets the dialog's fields |
|
||||
| `ui.dialog.confirm` | `dialog`, `choice?` (which button of a prompt) | answers OK, as the default button does |
|
||||
| `ui.dialog.cancel` | `dialog` | closes the dialog, as Escape does |
|
||||
| `ui.closeWindow` | — | the root window's close button: unsaved work brings up the Save prompt; the reply's `requested` says whether the close was asked for |
|
||||
| `ui.closeWindow` | `window?` | the close button of the window with that key (from `view.switchWindows`), the active window by default: unsaved work brings up the Save prompt in that window; the reply's `requested` says whether the close was asked for (false while a Save prompt is already open: answer it first); errors "no document window is open" when only the windowless root remains |
|
||||
| `ui.clipboard` | `text?`, `html?`, `rtf?`, `png?` (base64) | puts those flavours on the clipboard; the reply's `offered` lists them |
|
||||
| `ui.replayAt` | `at` (0–1) | holds Ink Replay at that fraction of its length, while Ink Replay is on |
|
||||
| `app.quit` | `force?` | quits (see [Closing the document](#closing-the-document)) |
|
||||
@@ -215,7 +215,8 @@ discard unsaved work is **refused with an error** (the app keeps running and the
|
||||
save first (`file.save`), or pass `{"force": true}` to discard the changes and go ahead.
|
||||
|
||||
`file.close` closes the shown document, so it is refused while that document has unsaved
|
||||
changes; the bare form `{"method": "file.close", "params": {"force": true}}` (a method name that is a
|
||||
changes (`unsaved changes: pass save or force`); `{"save": true}` writes it first (a document with no
|
||||
file yet is an error, never a prompt) and then closes it; the bare form `{"method": "file.close", "params": {"force": true}}` (a method name that is a
|
||||
command id) is guarded the same way, and only a boolean `true` counts as `force`. A document
|
||||
without unsaved changes closes at once (#1268). Closing closes the document and its window, and
|
||||
the window focused before it becomes the active one. The last window stays open with no page,
|
||||
|
||||
+2
-1
@@ -218,7 +218,8 @@ document: the tool works on that document and the active one stays active.
|
||||
|
||||
An id that names no open document, or a value that isn't a whole number from 0 up, is a tool error.
|
||||
`execute` with `view.switchWindows {"id": n}` makes a document active, and `file.closeDocument
|
||||
{"id": n, "force"?: true}` closes one (unsaved changes need `force`). Through `--connect`, `doc`
|
||||
{"id": n, "force"?: true}` closes one (unsaved changes need `force`); `file.close {"save"?: true, "force"?: true}` closes the shown
|
||||
document, and unsaved changes need `save` (write, then close) or `force`. Through `--connect`, `doc`
|
||||
reaches the app's control channel (see [Open documents](control-protocol.md#open-documents)); the
|
||||
app's window keeps showing the document it showed. `screenshot`, `click` and `key` act on the
|
||||
window, so they work on the document on screen.
|
||||
|
||||
Reference in New Issue
Block a user