Skip to content

Commit 210bac8

Browse files
committed
Add initial capability of plot
1 parent f56ae3f commit 210bac8

2 files changed

Lines changed: 50 additions & 7 deletions

File tree

R/notebook.R

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,25 @@ local({
77
eval(expr, env)
88
}
99

10+
plot_file <- file.path(tempdir(), "plot.png")
11+
null_dev_id <- c(pdf = 2L)
12+
null_dev_size <- c(7 + pi, 7 + pi)
13+
14+
options(
15+
device = function(...) {
16+
pdf(NULL,
17+
width = null_dev_size[[1L]],
18+
height = null_dev_size[[2L]],
19+
bg = "white")
20+
dev.control(displaylist = "enable")
21+
}
22+
)
23+
24+
check_null_dev <- function() {
25+
identical(dev.cur(), null_dev_id) &&
26+
identical(dev.size(), null_dev_size)
27+
}
28+
1029
ls.str(env)
1130
while (TRUE) {
1231
con <- try(socketConnection(host = "127.0.0.1", port = env$port,
@@ -22,7 +41,17 @@ local({
2241
str <- tryCatch({
2342
expr <- parse(text = request$expr)
2443
out <- withVisible(eval(expr, globalenv()))
25-
if (out$visible) {
44+
if (check_null_dev()) {
45+
record <- recordPlot()
46+
png(filename = plot_file)
47+
replayPlot(record)
48+
dev.off()
49+
dev.off()
50+
res <- list(
51+
type = "plot",
52+
result = plot_file
53+
)
54+
} else if (out$visible) {
2655
print_text <- utils::capture.output(print(out$value))
2756
res <- list(
2857
type = "text",

src/notebook.ts

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import net = require('net');
33
import { spawn, ChildProcess } from 'child_process';
44
import { dirname } from 'path';
55
import getPort = require('get-port');
6+
import * as fs from 'fs';
67

78
interface REvalOutput {
89
type: 'text' | 'plot' | 'viewer' | 'browser' | 'error';
@@ -304,13 +305,26 @@ export class RNotebookProvider implements vscode.NotebookContentProvider, vscode
304305
cell.metadata.runStartTime = start;
305306
cell.metadata.executionOrder = ++this.runIndex;
306307
const output = await notebook.eval(cell);
307-
if (output.type === 'error') {
308-
throw new Error(output.result);
308+
switch (output.type) {
309+
case 'text':
310+
cell.outputs = [{
311+
outputKind: vscode.CellOutputKind.Text,
312+
text: output.result,
313+
}];
314+
break;
315+
case 'plot':
316+
const plotData = fs.readFileSync(output.result);
317+
const buffer = new Buffer(plotData).toString('base64');
318+
cell.outputs = [{
319+
outputKind: vscode.CellOutputKind.Rich,
320+
data: {
321+
'image/png': buffer,
322+
}
323+
}];
324+
break;
325+
case 'error':
326+
throw new Error(output.result);
309327
}
310-
cell.outputs = [{
311-
outputKind: vscode.CellOutputKind.Text,
312-
text: output.result,
313-
}];
314328
cell.metadata.runState = vscode.NotebookCellRunState.Success;
315329
cell.metadata.lastRunDuration = +new Date() - start;
316330
} catch (e) {

0 commit comments

Comments
 (0)