Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 6 additions & 1 deletion crates/amalthea/src/comm/connections_comm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ pub struct ObjectSchema {
pub name: String,

/// The object type (table, catalog, schema)
pub kind: String
pub kind: String,

/// Indicates if the object has children that can be listed. This property
/// is optional and when omitted, it is assumed that the object may have
/// children unless its kind is 'field'.
pub has_children: Option<bool>
}

/// FieldSchema in Schemas
Expand Down
47 changes: 45 additions & 2 deletions crates/amalthea/src/comm/ui_comm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@ pub struct Range {
pub end: Position
}

/// Source information for preview content
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PreviewSource {
/// The type of source that opened the preview
#[serde(rename = "type")]
pub preview_source_type: PreviewSourceType,

/// The ID of the source (session_id or terminal process ID)
pub id: String
}

/// Possible values for Kind in OpenEditor
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, strum_macros::Display, strum_macros::EnumString)]
pub enum OpenEditorKind {
Expand All @@ -110,6 +121,34 @@ pub enum OpenEditorKind {
Uri
}

/// Possible values for Destination in ShowHtmlFile
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, strum_macros::Display, strum_macros::EnumString)]
pub enum ShowHtmlFileDestination {
#[serde(rename = "plot")]
#[strum(to_string = "plot")]
Plot,

#[serde(rename = "viewer")]
#[strum(to_string = "viewer")]
Viewer,

#[serde(rename = "editor")]
#[strum(to_string = "editor")]
Editor
}

/// Possible values for Type in PreviewSource
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, strum_macros::Display, strum_macros::EnumString)]
pub enum PreviewSourceType {
#[serde(rename = "runtime")]
#[strum(to_string = "runtime")]
Runtime,

#[serde(rename = "terminal")]
#[strum(to_string = "terminal")]
Terminal
}

/// Parameters for the DidChangePlotsRenderSettings method.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DidChangePlotsRenderSettingsParams {
Expand Down Expand Up @@ -305,6 +344,9 @@ pub struct ModifyEditorSelectionsParams {
pub struct ShowUrlParams {
/// The URL to display
pub url: String,

/// Optional source information for the URL
pub source: Option<PreviewSource>,
}

/// Parameters for the ShowHtmlFile method.
Expand All @@ -317,8 +359,9 @@ pub struct ShowHtmlFileParams {
/// superseded by the title in the HTML file.
pub title: String,

/// Whether the HTML file is a plot-like object
pub is_plot: bool,
/// Where the file should be shown in Positron: as an interactive plot, in
/// the viewer pane, or in a new editor tab.
pub destination: ShowHtmlFileDestination,

/// The desired height of the HTML viewer, in pixels. The special value 0
/// indicates that no particular height is desired, and -1 indicates that
Expand Down
1 change: 1 addition & 0 deletions crates/ark/src/connections/r_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ impl RConnection {
.map(|(name, kind)| ObjectSchema {
name: name.clone(),
kind: kind.clone(),
has_children: None,
})
.collect::<Vec<_>>();

Expand Down
2 changes: 1 addition & 1 deletion crates/ark/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ impl PendingInputs {

let input = if harp::get_option_bool("keep.source") {
_srcfile = Some(SrcFile::new_virtual_empty_filename(input.into()));
harp::ParseInput::SrcFile(&_srcfile.unwrap())
harp::ParseInput::SrcFile(_srcfile.as_ref().unwrap())
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked into this again and just learned about a neat Rust feature called lifetime extension.

I originally thought I needed _srcfile to be stored at top-level so I could pass a reference to it. But that's not what happens even in the original version of the code! Since unwrap() takes self here, the value is moved out of _srcfile into a temporary. We then take a reference to it, and Rust extends the lifetime of the temporary to match that of the reference (which is tied to input).

More info at: https://doc.rust-lang.org/reference/destructors.html#temporary-lifetime-extension

With your change, we're creating a new Option containing a reference, so unwrapping it doesn't consume _srcfile.

But armed with the knowledge of lifetime extension we can write this much cleaner version:

        let input = if harp::get_option_bool("keep.source") {
            harp::ParseInput::SrcFile(&SrcFile::new_virtual_empty_filename(input.into()))
        } else {
            harp::ParseInput::Text(input)
        };

Can you please revert your change? Merging it would cause a conflict with PRs/branches of mine. I'll implement the new approach suggested above in these branches.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I made this change was that locally I can't even build ark without it. The original code generates this fatal error on my machine:

error[E0716]: temporary value dropped while borrowed
   --> crates/ark/src/interface.rs:340:40
    |
338 |         let input = if harp::get_option_bool("keep.source") {
    |             ----- borrow later stored here
339 |             _srcfile = Some(SrcFile::new_virtual_empty_filename(input.into()));
340 |             harp::ParseInput::SrcFile(&_srcfile.unwrap())
    |                                        ^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
341 |         } else {
    |         - temporary value is freed at the end of this statement
    |
    = note: consider using a `let` binding to create a longer lived value

Incidentally your proposed version doesn't compile for me either:

   Compiling ark v0.1.220 (/Users/jmcphers/git2/ark/crates/ark)
error[E0716]: temporary value dropped while borrowed
   --> crates/ark/src/interface.rs:337:40
    |
336 |         let input = if harp::get_option_bool("keep.source") {
    |             ----- borrow later stored here
337 |             harp::ParseInput::SrcFile(&SrcFile::new_virtual_empty_filename(input.into()))
    |                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
338 |         } else {
    |         - temporary value is freed at the end of this statement
    |
    = note: consider using a `let` binding to create a longer lived value

Probably has to do with the version of Rust I'm using? I'm on 1.87.

I did revert the change, since it doesn't seem to be causing any trouble in CI.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh I'm on 1.89. Good to know!

This is from the 1.89 changelog and explains the difference: rust-lang/rust#140593

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've bumped the minimum version to 1.89 on main to avoid such issues in the future.

} else {
harp::ParseInput::Text(input)
};
Expand Down
6 changes: 3 additions & 3 deletions crates/ark/src/modules/positron/html_widgets.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#
# html_widgets.R
#
# Copyright (C) 2023-2024 Posit Software, PBC. All rights reserved.
# Copyright (C) 2023-2025 Posit Software, PBC. All rights reserved.
#
#
#' @export
Expand All @@ -14,7 +14,7 @@
tmp_file <- htmltools::html_print(rendered, viewer = NULL)

# Guess whether this is a plot-like widget based on its sizing policy.
is_plot <- isTRUE(x$sizingPolicy$knitr$figure)
destination <- if (isTRUE(x$sizingPolicy$knitr$figure)) 'plot' else 'viewer'
Comment thread
jmcphers marked this conversation as resolved.
Outdated

# Derive the height of the viewer pane from the sizing policy of the widget.
height <- .ps.validate.viewer.height(x$sizingPolicy$viewer$paneHeight)
Expand All @@ -30,7 +30,7 @@

# Pass the widget to the viewer. Positron will assemble the final HTML
# document from these components.
.ps.Call("ps_html_viewer", tmp_file, label, height, is_plot)
.ps.Call("ps_html_viewer", tmp_file, label, height, destination)
}

#' @export
Expand Down
11 changes: 10 additions & 1 deletion crates/ark/src/modules/positron/options.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#
# options.R
#
# Copyright (C) 2023-2024 Posit Software, PBC. All rights reserved.
# Copyright (C) 2023-2025 Posit Software, PBC. All rights reserved.
#
#

Expand Down Expand Up @@ -36,3 +36,12 @@ options(plumber.docs.callback = function(url) {
options(shiny.launch.browser = function(url) {
.ps.ui.showUrl(url)
})

# Show Profvis output in the viewer
options(profvis.print = function(x) {
# Render the HTML content to a temporary file
tmp_file <- htmltools::html_print(x, viewer = NULL)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably worth a note that hmtltools is an (indirect) dependency of profvis

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess passing the background color to htmltools::html_print() would be asking too much? 😄

Image

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I was first implementing htmlwidgets support I actually hooked this up, which was when I discovered that most htmlwidgets are not theme-aware and always render in dark/black colors, so setting the background to black made them unreadable.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same deal for profvis 😂
image


# Pass the file to the viewer
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is rather annoying that it doesn't resize. It means the window of text that you are reading is quite small to read.

It does resize in RStudio, I wonder what is different there?

Screen.Recording.2025-12-15.at.2.03.40.PM.mov

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the nudge, I think I figured it out ... the trick is to force it to render in standalone mode by rendering to tags first. (That's not how RStudio does it, but works here.) db02e6f

.ps.Call("ps_html_viewer", tmp_file, "R Profile", -1L, "editor")
})
1 change: 1 addition & 0 deletions crates/ark/src/ui/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ pub unsafe extern "C-unwind" fn ps_ui_set_selection_ranges(ranges: SEXP) -> anyh
pub fn send_show_url_event(url: &str) -> anyhow::Result<()> {
let params = ShowUrlParams {
url: url.to_string(),
source: None,
};
let event = UiFrontendEvent::ShowUrl(params);

Expand Down
21 changes: 14 additions & 7 deletions crates/ark/src/viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//
//

use amalthea::comm::ui_comm::ShowHtmlFileDestination;
use amalthea::comm::ui_comm::ShowHtmlFileParams;
use amalthea::comm::ui_comm::UiFrontendEvent;
use amalthea::socket::iopub::IOPubMessage;
Expand Down Expand Up @@ -53,7 +54,7 @@ pub unsafe extern "C-unwind" fn ps_html_viewer(
url: SEXP,
label: SEXP,
height: SEXP,
is_plot: SEXP,
destination: SEXP,
) -> anyhow::Result<SEXP> {
// Convert url to a string; note that we are only passed URLs that
// correspond to files in the temporary directory.
Expand All @@ -76,12 +77,18 @@ pub unsafe extern "C-unwind" fn ps_html_viewer(
}
},
SessionMode::Console => {
let is_plot = RObject::view(is_plot).to::<bool>();
let is_plot = match is_plot {
Ok(is_plot) => is_plot,
let destination = match RObject::view(destination).to::<String>() {
Ok(s) => s.parse::<ShowHtmlFileDestination>().unwrap_or_else(|_| {
log::warn!(
"`destination` must be one of 'plot', 'editor', or 'viewer'"
Comment thread
jmcphers marked this conversation as resolved.
Outdated
);
ShowHtmlFileDestination::Viewer
}),
Err(err) => {
log::warn!("Can't convert `is_plot` into a bool, using `false` as a fallback: {err:?}");
false
log::warn!(
"Can't convert `destination` to a string, using 'viewer' as a fallback: {err}"
);
ShowHtmlFileDestination::Viewer
},
};

Expand All @@ -98,7 +105,7 @@ pub unsafe extern "C-unwind" fn ps_html_viewer(
path,
title: label,
height,
is_plot,
destination,
};

let event = UiFrontendEvent::ShowHtmlFile(params);
Expand Down
1 change: 1 addition & 0 deletions crates/ark/tests/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ fn obj(name: &str, kind: &str) -> ObjectSchema {
ObjectSchema {
name: String::from(name),
kind: String::from(kind),
has_children: None,
}
}

Expand Down