Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions crates/ark/src/plots/graphics_device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,23 @@ pub(crate) struct DeviceContext {
/// negative, but we try to be extra safe.
should_render: Cell<bool>,

/// Tracks whether the current page has a recording that we have not yet
/// notified the frontend about because rendering was held.
///
/// Set when [DeviceContext::process_current_page] defers a notification. Reset once
/// the notification is sent, or when a new page starts. At that point the old page
/// moves to `held_pages` if the frontend has seen it, and is dropped otherwise.
is_notification_deferred: Cell<bool>,

/// Earlier pages that still need an update once rendering is released.
///
/// Code that holds the device around `plot.new()`, for example
/// `plot.default()` or `bxp()`, means the `before.plot.new` hook can only
/// record the previous page and defer its notification. When the new page then starts, we move the previous page
/// here so its final state still reaches the frontend after the hold is
/// released, instead of being lost when `id` changes (posit-dev/positron#17240).
held_pages: RefCell<Vec<PlotId>>,

/// The ID associated with the current plot page.
///
/// Used for looking up a recorded plot so we can replay it with different graphics
Expand Down Expand Up @@ -234,6 +251,8 @@ impl DeviceContext {
is_new_page: Cell::new(true),
is_drawing: Cell::new(false),
should_render: Cell::new(true),
is_notification_deferred: Cell::new(false),
held_pages: RefCell::new(Vec::new()),
id: RefCell::new(Self::new_id()),
comm_ids: RefCell::new(HashMap::new()),
plot_contexts: RefCell::new(HashMap::new()),
Expand Down Expand Up @@ -461,6 +480,13 @@ impl DeviceContext {
if self.is_replaying() {
return;
}

// Only pages the frontend has already seen are owed an update. A page
// that was never shown stays hidden, so `dev.hold()` still suppresses
// intermediate pages.
if self.is_notification_deferred.replace(false) && !self.is_new_page.get() {
self.held_pages.borrow_mut().push(self.id());
}
self.new_positron_page()
}

Expand Down Expand Up @@ -638,6 +664,7 @@ impl DeviceContext {

#[tracing::instrument(level = "trace", skip(self))]
fn on_plot_closed(&self, id: &PlotId) {
self.held_pages.borrow_mut().retain(|held| held != id);
self.comm_ids.borrow_mut().remove(id);
self.plot_contexts.borrow_mut().remove(id);

Expand Down Expand Up @@ -670,6 +697,28 @@ impl DeviceContext {
/// Uses execution context stored via `graphics_on_execute_request()`.
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) fn process_changes(self: &Rc<Self>, console: &Console) {
// Take the held pages before we render anything. Rendering replays a
// recording on another device, which deactivates ours and calls back
// into `process_changes()`. Those nested calls must not render the same
// held pages again. Because of that nested call, the current page is
// always sent before the held updates, so a new page's display or comm
// open reaches the frontend before the earlier page's update. Frontends
// match updates by display ID or comm ID, so this order is fine.
let held_pages = if self.should_render.get() {
std::mem::take(&mut *self.held_pages.borrow_mut())
} else {
Vec::new()
};

self.process_current_page(console);

for id in held_pages {
log::trace!("Processing held changes for plot `id` {id}");
self.process_update_plot(&id, console);
}
}

fn process_current_page(self: &Rc<Self>, console: &Console) {
let id = self.id();

if !self.has_changes.get() {
Expand Down Expand Up @@ -699,10 +748,12 @@ impl DeviceContext {
// Keep `has_changes` set so we re-enter this branch after the hold
// is released (via `hook_holdflush`) and send the notification then.
log::trace!("Deferring notification for plot `id` {id} (rendering held)");
self.is_notification_deferred.replace(true);
return;
}

self.has_changes.replace(false);
self.is_notification_deferred.replace(false);

if self.is_new_page.replace(false) {
self.process_new_plot(&id, console);
Expand Down
39 changes: 39 additions & 0 deletions crates/ark/tests/integration/kernel_notebook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,42 @@ fn test_notebook_plot_lm_shows_all_pages_without_prompting() {
frontend.recv_iopub_idle();
assert_eq!(frontend.recv_shell_execute_reply(), input.execution_count);
}

#[test]
fn test_notebook_plot_layers_kept_when_next_page_starts_in_same_request() {
let frontend = DummyArkFrontendNotebook::lock();

// `plot.default()` holds the device while it calls `plot.new()`, so the
// last layers of page 1 (the red point) are recorded while rendering is
// held. They must still reach the frontend as an update for page 1, not
// be dropped when page 2 starts (posit-dev/positron#17240).
let code = "local({
plot(1:10)
points(5, 5, col = 'red')
plot(1:5)
points(3, 3, col = 'blue')
})";
frontend.send_execute_request(code, ExecuteRequestOptions::default());
frontend.recv_iopub_busy();
let input = frontend.recv_iopub_execute_input();
assert_eq!(input.code, code);

let page_1 = frontend.recv_iopub_display_data_content();
let page_2 = frontend.recv_iopub_display_data_content();
let page_1_id = &page_1.transient["display_id"];
let page_2_id = &page_2.transient["display_id"];
assert_ne!(page_1_id, page_2_id);

// Page 1 gets its held update once `plot.default()` releases the hold.
// The image differs from the first snapshot because it has the red point.
let page_1_update = frontend.recv_iopub_update_display_data_content();
assert_eq!(page_1_update.transient.display_id, *page_1_id);
assert_ne!(page_1_update.data["image/png"], page_1.data["image/png"]);

// Page 2 gets its update when the request completes
let page_2_update = frontend.recv_iopub_update_display_data_content();
assert_eq!(page_2_update.transient.display_id, *page_2_id);

frontend.recv_iopub_idle();
assert_eq!(frontend.recv_shell_execute_reply(), input.execution_count);
}
44 changes: 44 additions & 0 deletions crates/ark/tests/integration/plots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1156,6 +1156,50 @@ stopifnot(id1 == id2)
frontend.recv_shell_execute_reply();
}

/// Positron path: layers drawn on a page just before the next page starts
/// reach that page's comm as an update.
///
/// `plot.default()` holds the device while it calls `plot.new()`, so the red
/// point on page 1 is recorded while rendering is held. Its update must still
/// be sent on page 1's comm after the hold is released
/// (posit-dev/positron#17240).
#[test]
fn test_positron_held_layers_update_previous_page() {
let frontend = DummyArkFrontend::lock();
frontend.open_ui_comm();

let code = r#"
local({
plot(1:10)
points(5, 5, col = "red")
plot(1:5)
points(3, 3, col = "blue")
})
"#;
frontend.send_execute_request(code, ExecuteRequestOptions::default());
frontend.recv_iopub_busy();
frontend.recv_iopub_execute_input();

let open1 = frontend.recv_iopub_comm_open();
let open2 = frontend.recv_iopub_comm_open();
assert_ne!(open1.comm_id, open2.comm_id);

// Page 1 gets its held update once `plot.default()` releases the hold,
// with a fresh rendering of the finished page
let update1 = frontend.recv_iopub_comm_msg();
assert_eq!(update1.comm_id, open1.comm_id);
assert_eq!(update1.data["method"], "update");
assert!(update1.data["params"]["pre_render"]["data"].is_string());

// Page 2 gets its update when the request completes
let update2 = frontend.recv_iopub_comm_msg();
assert_eq!(update2.comm_id, open2.comm_id);

frontend.recv_iopub_ui_prompt_state();
frontend.recv_iopub_idle();
frontend.recv_shell_execute_reply();
}

/// Positron path: `layout()` + multi-plot works like `par(mfrow)`.
///
/// Same as `test_positron_par_multi_panel` but with `layout()` inside a
Expand Down
13 changes: 13 additions & 0 deletions crates/ark_test/src/dummy_frontend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,19 @@ impl DummyArkFrontend {
}
}

/// Receive from IOPub and assert UpdateDisplayData message, returning the content.
/// Automatically skips any Stream messages.
#[track_caller]
pub fn recv_iopub_update_display_data_content(
&self,
) -> amalthea::wire::update_display_data::UpdateDisplayData {
let msg = self.recv_iopub_next();
match msg {
Message::UpdateDisplayData(data) => data.content,
other => panic!("Expected UpdateDisplayData, got {:?}", other),
}
}

/// Receive from IOPub and assert CommMsg message.
/// Automatically skips any Stream messages.
#[track_caller]
Expand Down
Loading