diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs
index 9a17cb9c56..eb3a60e094 100644
--- a/crates/engine/src/doc_state.rs
+++ b/crates/engine/src/doc_state.rs
@@ -69,6 +69,9 @@ pub struct DocState {
pub recalled_selection: RecalledSelection,
/// Process-unique id of this open document (tab indices shift when tabs close).
pub uid: u64,
+ /// When the document last became the current one: a larger value is more recent
+ /// ([`Session::front_order`]). It is not saved.
+ pub(crate) activated: u64,
/// How many times File → Revert replaced the document's content in its tab
/// ([`Session::replace_document`]). Work started for the document (a file read for Place, a
/// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not
@@ -421,6 +424,7 @@ impl DocState {
last_selection_cmd: None,
recalled_selection: RecalledSelection::default(),
uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
+ activated: 0,
reverts: 0,
history_restores: 0,
opened_as_tab: true,
diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs
index 46ca2824d4..f5c2d5b9a2 100644
--- a/crates/engine/src/script/dom.rs
+++ b/crates/engine/src/script/dom.rs
@@ -18,7 +18,8 @@
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
//! gives, and a script may name the application's members without `app.`, as
//! describes; here
-//! that holds for `activeDocument`, `documents` and `selection`.
+//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active
+//! document, as the same page says.
//!
//! VectorCraft's own rules:
//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever
@@ -29,8 +30,8 @@
//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the
//! active document's selection. A top-level `var selection = ...` does the same and does
//! not make a variable of the script. Assigning `documents` keeps its value.
-//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is
-//! always the active document; VectorCraft does not follow that yet.
+//! - After `documents[0]`, documents are listed from the one active most recently to the one
+//! active longest ago. A change a script makes to a document in the back does not move it.
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
@@ -651,11 +652,11 @@ fn on_doc(
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result,
) -> std::result::Result {
- let (index, active, before, layer) = {
+ let (index, active, before, layer, activated) = {
let s = h.session.borrow();
let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let st = &s.documents()[index];
- (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()))
+ (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()), st.activated)
};
let switch = active != Some(index);
if switch {
@@ -681,6 +682,13 @@ fn on_doc(
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
_ => Ok(()),
};
+ // The switch for the change does not move the document up in `documents`.
+ if switch
+ && back.is_ok()
+ && let Some(st) = h.session.borrow_mut().document_mut(uid)
+ {
+ st.activated = activated;
+ }
let v = r?;
restored?;
back?;
@@ -840,12 +848,17 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer {
Ok(host_ref("Application", &[]))
}
+/// The open documents in the order `documents` lists them ([`Session::front_order`]).
+fn front_docs(s: &Session) -> impl Iterator- {
+ s.front_order().into_iter().map(|i| &s.documents()[i])
+}
+
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
fn docs_at(h: &Host, a: &[Data]) -> Answer {
let s = h.session.borrow();
let at = match arg(a, 1) {
- Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)),
- Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) {
+ Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)),
+ Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) {
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
found => found,
},
@@ -857,7 +870,7 @@ fn docs_at(h: &Host, a: &[Data]) -> Answer {
fn docs_by_name(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
let s = h.session.borrow();
- let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
+ let st = front_docs(&s).find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
Ok(doc_ref(h, st.uid))
}
diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs
index 9e8e8f4163..748d25f7fe 100644
--- a/crates/engine/src/session/documents.rs
+++ b/crates/engine/src/session/documents.rs
@@ -257,11 +257,29 @@ impl Session {
self.reset_tool_for_doc_switch();
}
+ /// The tab indices of the open documents from the front: the current document first, then
+ /// the others from the one that was current most recently to the one current longest ago
+ /// (tab order among documents that have not been current).
+ pub fn front_order(&self) -> Vec {
+ let mut order: Vec = (0..self.docs.len()).collect();
+ order.sort_by_key(|&i| (Some(i) != self.active, std::cmp::Reverse(self.docs[i].activated)));
+ order
+ }
+
+ /// Marks the document in tab `index` as the one current most recently ([`Session::front_order`]).
+ fn stamp_activated(&mut self, index: usize) {
+ let next = self.docs.iter().map(|d| d.activated).max().unwrap_or(0) + 1;
+ if let Some(st) = self.docs.get_mut(index) {
+ st.activated = next;
+ }
+ }
+
pub fn set_active(&mut self, index: usize) -> bool {
if index < self.docs.len() {
let switched = self.active != Some(index);
if switched {
self.reset_tool_for_doc_switch();
+ self.stamp_activated(index);
}
self.active = Some(index);
if switched {
@@ -386,6 +404,7 @@ impl Session {
self.docs.push(st);
let i = self.docs.len() - 1;
self.active = Some(i);
+ self.stamp_activated(i);
self.sync_opened_composite_fonts(i);
self.sync_front_profiles();
if self.depth == 0
@@ -429,6 +448,7 @@ impl Session {
st.history.limit = old.history.limit;
// Same open document (caches keyed by uid stay valid); a new revision redraws it.
st.uid = old.uid;
+ st.activated = old.activated;
// Work started for the content being thrown away is dropped when it finishes.
st.reverts = old.reverts + 1;
st.opened_as_tab = old.opened_as_tab;
@@ -513,6 +533,9 @@ impl Session {
return true;
}
self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) };
+ if let Some(i) = self.active {
+ self.stamp_activated(i);
+ }
self.sync_front_composite_fonts();
self.sync_front_profiles();
true
diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs
index c1aa77e6a6..db924c584d 100644
--- a/crates/engine/src/tests/script_dom.rs
+++ b/crates/engine/src/tests/script_dom.rs
@@ -46,7 +46,7 @@ fn app_documents_track_active_tab_and_new_document() {
let out = log(
&mut s,
"var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\
- app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\
+ app.activeDocument = d[1]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\
vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\
var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\
vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\
@@ -297,7 +297,7 @@ fn selection_assignment_is_atomic_across_invalid_items() {
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
// An item of another document cannot be selected here.
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
- let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];");
+ let e = failure(&mut s, "app.activeDocument.selection = app.documents[1].pageItems[0];");
assert!(e.contains("Cannot select"), "{e}");
}
@@ -324,13 +324,44 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() {
fn an_inactive_document_changes_without_switching_tabs() {
let (mut s, a, _) = doc();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
- log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];");
+ log(&mut s, "var d = app.documents[1]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];");
assert_eq!(s.active_index(), Some(1));
let first = &s.documents()[0];
assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far"));
assert_eq!(first.selection.objects.len(), 1);
}
+#[test]
+fn documents_list_the_current_document_first_then_the_most_recently_current() {
+ let mut s = Session::new();
+ for _ in 0..3 {
+ s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
+ rect(&mut s, 0.0, 0.0, 5.0, 5.0);
+ }
+ let out = log(
+ &mut s,
+ "var t = {}, n = ['A', 'B', 'C'];\
+ for (var i = 0; i < 3; i++) t[app.documents[2 - i].name] = n[i];\
+ function order() { var r = []; for (var i = 0; i < app.documents.length; i++) r.push(t[app.documents[i].name]); return r.join(''); }\
+ var A = app.documents[2], B = app.documents[1], C = app.documents[0];\
+ vc.log(order());\
+ app.activeDocument = A; vc.log(order());\
+ app.activeDocument = B; vc.log(order());\
+ app.activeDocument = app.documents[2]; vc.log(order());\
+ A.pageItems[0].name = 'far'; vc.log(order());\
+ vc.log([app.documents[0] === app.activeDocument, app.documents.getByName(B.name) === B]);",
+ );
+ // A change to a document in the back leaves the order as it was.
+ assert_eq!(out, vec![json!("CBA"), json!("ACB"), json!("BAC"), json!("CBA"), json!("CBA"), json!([true, true])]);
+ // Closing a document in the back keeps the others in their order as the tabs shift.
+ s.execute("document.activate", &json!({"index": 0})).unwrap();
+ s.execute("document.activate", &json!({"index": 1})).unwrap();
+ s.execute("document.activate", &json!({"index": 2})).unwrap();
+ assert_eq!(s.front_order(), vec![2, 1, 0]);
+ s.close_document(0);
+ assert_eq!(s.front_order(), vec![1, 0]);
+}
+
#[test]
fn move_duplicate_and_zorder_obey_parent_order() {
let (mut s, a, b) = doc();
diff --git a/docs/mcp.md b/docs/mcp.md
index 145aa0216e..6b50d12ea1 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -2854,9 +2854,9 @@ other files through `$`:
take a number or a Boolean as the text `String(value)` gives. `String(object)` gives
`[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`,
`[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule).
- Documents are listed in tab order; the same page says `documents[0]` is always the active document, and
- VectorCraft does not follow that yet. VectorCraft's own rules: page items are listed with the
- objects inside groups and compound paths after their group and without layers and ruler guides. A document's
+ `documents[0]` is always the active document, as the same page says. VectorCraft's own rules: the other
+ documents follow from the one active most recently to the one active longest ago, and a change a script
+ makes to a document in the back does not move it in the list; page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides. A document's
`selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates
are points with Y up from the bottom-left corner of the first artboard, or, with
`CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename`