Skip to content

Support ansi hyperlinks in the console and build - #10299

Closed
romainfrancois wants to merge 56 commits into
rstudio:mainfrom
romainfrancois:ansi_anchor_1941
Closed

romainfrancois wants to merge 56 commits into
rstudio:mainfrom
romainfrancois:ansi_anchor_1941

Conversation

@romainfrancois

@romainfrancois romainfrancois commented Jan 3, 2022 •

Copy link
Copy Markdown
Contributor

Intent

Adresses #1941

Approach

Automated Tests

QA Notes

This code:

# pak::pak("r-lib/cli")
library(cli)
library(glue)

tf <- tempfile()
writeLines(c("bla bla", "yada yada yada"), tf)

port <- .rs.httpdPort()

links <- c(
  style_hyperlink('open in browser: dplyr::summarise()'   , 'https://dplyr.tidyverse.org/reference/summarise.html' ),
  style_hyperlink('open in viewer: dplyr::summarise()'    , 'https://dplyr.tidyverse.org/reference/summarise.html', c(target = "viewer" )),
  style_hyperlink('open file'                             , glue('file://{tf}')),
  style_hyperlink('open file at line 2'                   , glue('file://{tf}:2')),
  style_hyperlink('open file at line 2, column 6'         , glue('file://{tf}:2:6')),
  
  
  style_hyperlink('open help page ?stats::rnorm'          , glue("http://localhost:{port}/library/stats/html/rnorm.html")),
  style_hyperlink('open help page ?mean'                  , glue("http://localhost:{port}/library/base/html/mean.html"))
)

writeLines(links)

will produce these links in the console:

image

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

@romainfrancois

This comment has been minimized.

@romainfrancois

This comment has been minimized.

{
Event.sinkEvents(element, Event.ONCLICK);
Event.setEventListener(element, event -> {
// TODO: call the RemoteServer.consoleFollowHyperlink([url], [params]) method

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.

I don't know how to call RemoteServer.consoleFollowHyperlink([url], [params]).

Probably something to @Inject somehow ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Right, you'd need to inject the appropriate "*ServerOperations" class, either in the class constructor, or via an explicit RStudioGinjector.injectMembers(this) call in the constructor, with an appropriate injected initialize() method defined. For example:

@Inject
private void initialize(EventBus events,
FilesServerOperations server,
RStudioAPIServerOperations apiServer,
Commands commands)
{
events_ = events;
server_ = server;
apiServer_ = apiServer;
commands_ = commands;
}

RStudioGinjector.INSTANCE.injectMembers(this);

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. I'll try to go the initialize() route

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.

That seems to work, although the class already had an @Inject constructor, so perhaps I'll move that there, but I suppose I would have to make some sort of fake ConsoleServerOperations for the new VirtualConsole() code in tests ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think that's true. I'm not sure what the cleanest way to mock that in our tests would be...

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.

So then maybe it's easier if it's extracted to a simpler VirtualConsoleOperations interface.

int flags,
ServerRequestCallback<Void> requestCallback);

void consoleFollowHyperlink(String url, String link_params, ServerRequestCallback<Void> requestCallback);

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.

Is this the right class for this ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think this is fine, but if you felt strongly then a separate VirtualConsoleServerOperations class might be a better fit.

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.

At least as a learning exercise, I'll try to make it a separate class/interface.

@romainfrancois

romainfrancois commented Jan 6, 2022 •

Copy link
Copy Markdown
Contributor Author

Now able to display links and have them do things through and rpc call, i.e.

hyperlink <- function(text, url, params = NULL) {
  paste0("\u001B]8;", params,";", url, "\u0007", text, "\u001B]8;;\u0007")
}
library(dplyr)

rlang::inform(c(
  x   = paste0("Incorrect use of ", hyperlink("dplyr::summarise()", "-", "type=help:topic=summarise")), 
  i   = glue::glue("More info in this {hyperlink('article', 'https://dplyr.tidyverse.org/reference/summarise.html' )}"),
  ">" = glue::glue("{hyperlink('DESCRIPTION', 'DESCRIPTION', 'type=file:line=5' )}")
))

gives :

image

clicking on the dplyr::summarise() link will open the help page for summarise() thanks to .rs.showHelpTopic(), clicking the article link opens the page through utils::browseURL(), clicking on DESCRIPTION opens the file at line 5 ...

The hyperlink is made of 3 things: the url, the text and params, which is either "" or a : separated list of name=value. The 3 things are received by this rpc handler:

.rs.addJsonRpcHandler("console_follow_hyperlink", function(url, text, params)
{
  if (identical(params, "")){
    utils::browseURL(url)
  } else {
    options <- strsplit(params, ":")[[1]]
    
    names <- sapply(options, function(param) sub("=.*$", "", param))
    options <- lapply(options, function(param) sub("^[^=]*=", "", param))
    names(options) <- names
    
    if (is.null(options$type)) {
      options$type <- ""
    }
    
    switch(
      options$type,
      help = .rs.showHelpTopic(options$topic, NULL),
      file = {
        file <- url
        line <- as.numeric(options$line)
        if (length(line) == 0L) line <- -1L
        
        col <- as.numeric(options$col)
        if (length(col) == 0L) col <- -1L
        
        .rs.api.navigateToFile(url, line = line, col = col)          
      },
      stop(paste0("Can't handle link <", url, "> with params <", params, ">"))
    )
  }
  
})

There are also some ideas in #2530 about various types of links.

@romainfrancois romainfrancois changed the title identify ansi hyperlinks Support ansi hyperlinks in the console Jan 6, 2022
@romainfrancois

romainfrancois commented Jan 7, 2022 •

Copy link
Copy Markdown
Contributor Author

This works in the build pane too, i.e. see r-lib/testthat#1544

@romainfrancois romainfrancois changed the title Support ansi hyperlinks in the console Support ansi hyperlinks in the console and build Jan 7, 2022
@kevinushey

Copy link
Copy Markdown
Collaborator

Awesome work! Let me know if you think the PR is ready for review.

@kevinushey kevinushey mentioned this pull request Jan 7, 2022
4 tasks
@kevinushey

Copy link
Copy Markdown
Collaborator

One other thing to consider: right now, this PR is tailored to hyperlinks. How hard would it be to make the existing code generic enough to handle other custom escapes? (I guess one of the bigger challenges would be handling these escapes when they're embedded in each other.)

@kevinushey
kevinushey requested a review from gtritchie January 7, 2022 22:52
@kevinushey

Copy link
Copy Markdown
Collaborator

I'm asking @gtritchie to take a look as well since he's the most familiar with our VirtualConsole implementation.

@romainfrancois

Copy link
Copy Markdown
Contributor Author

hyperlinks are actually in addition to other escapes that were already in use for colors, etc ... (bold, italic, ...). It would be worth reviewing other kinds of escapes. @gaborcsardi might have some ideas.

For the hyperlinks, using [params] and its name=value separated by : is a bit cumbersome, for the use case we currently have in mind. We discussed with @hadley having all the information in the uri, e.g. :

  • http://www.example.com : open with utils::browseURL()
  • viewer::https://www.example.com : open with the rstudio viewer
  • file::[/some/file/path]#[row],[col] : navigate to file in source editor: are there security considerations here ?
  • help::stats/rnorm: open help page for stats::rnorm

From the user's point of view, at the moment things would go through cli::style_hyperlink(text=, url=) but probably later via the {.url notation in cli: r-lib/cli#386 Perhaps we can also have {.help or something.

Perhaps also something to View() a data

We probably also need to add a title to the <span> so that hovering the link gives a clue about what it points to.

@gaborcsardi

Copy link
Copy Markdown
Contributor

We discussed with @hadley having all the information in the uri

Yes, I think having it in the URI would be better.

romainfrancois added a commit to romainfrancois/testthat that referenced this pull request Jan 10, 2022
@romainfrancois

This comment has been minimized.

}
}

.rs.api.navigateToFile(file, line = line, col = col, moveCursor = TRUE)

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.

This opens the file at the right location, but this does not seem to always move the focus. Or more accurately, it does but then the focus goes back to the console.

server_.consoleFollowHyperlink(hyperlink_.url_, text, hyperlink_.params_, new VoidServerRequestCallback());
});

// for now, perhaps a dedicated style would be better

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.

I'm not sure where to add a new specific style for links ? cc @gtritchie

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The console styles (along with the terminal, aka xterm) are part of the themes, so I think you'd need to add a new style to all the various themes you see in Options / Appearances, and also deal with what to do with third-party themes that don't have the new one. For now, if it looks ok, I think using the existing xterm style is reasonable. @MariaSemple did a lot of the theming work so she might have thoughts (and know if I'm totally off base here).

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.

I'll look into adding a xtermHyperlink style. We might want to fine tune how they are displayed. For example cli (not using style_hyperlink() yet, until r-lib/cli#386) uses:

image

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Gary is on base :). We should have a fallback/default in case user-themes are missing a rule for this class, but we should add a rule for each of the themes we ship (see here: https://github.com/rstudio/rstudio/blob/main/src/cpp/session/resources/themes/)

params_ = params;
}

public String getTitle() {

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.

Should this adapt to the type of link ? "Open help page for ...", "Open the viewer ..." ?

@gaborcsardi

Copy link
Copy Markdown
Contributor

Current supports these uri:

Do we actually need the help:: etc. prefixes? URIs already have a scheme, can't we just use that?

E.g.

file://DESCRIPTION
file:///Users/gaborcsardi/works/cli/DESCRIPTION
rstatshelp://stats/rnorm

@romainfrancois

Copy link
Copy Markdown
Contributor Author

Yeah that's probably better. And potentially the links would be meaningful to other cli besides rstudio.

We just then need a way to differentiate when we want a link to open in the viewer, e.g.

http://www.example.com
http://www.example.com?target=viewer
viewer::http://example.com

@gaborcsardi

Copy link
Copy Markdown
Contributor

We just then need a way to differentiate when we want a link to open in the viewer, e.g.

Yeah, isn't there some RStudio config setting for that? Maybe we can reuse that for the default?

I don't like the

http://www.example.com?target=viewer

form because that interferes with passing query parameters to the URI.

Maybe the param tag in the ANSI seq is good for this, and then other CLIs and GUIs can just ignore it and still handle the URL properly?

@romainfrancois

This comment has been minimized.

@romainfrancois

Copy link
Copy Markdown
Contributor Author

Or maybe params = list(target = "viewer") if we don't want ...

@romainfrancois

Copy link
Copy Markdown
Contributor Author

Thanks @kevinushey and @gtritchie. This now uses <a>.

@kevinushey kevinushey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM other than one import. Are there any other changes we want to make for now, or is this ready for merge?

@romainfrancois

Copy link
Copy Markdown
Contributor Author

I think this needs some testing inspired from the tests related to colors. The other thing is that the pull request targets main. Should it be rebased to target spotted-wakerobin ?

@kevinushey

Copy link
Copy Markdown
Collaborator

Yes, I think we should target for spotted-wakerobin.

@romainfrancois romainfrancois mentioned this pull request Jan 24, 2022
2 of 4 tasks
@romainfrancois

Copy link
Copy Markdown
Contributor Author

(replaced by #10416 that targets spotted-wakerobin branch).

lionel- pushed a commit to romainfrancois/testthat that referenced this pull request Feb 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants