private async Task InstallPackageAsync(IRSessionEvaluation eval, string packageName, string libPath) { var code = $"install.packages(\"{packageName}\", verbose=FALSE, quiet=TRUE)"; var evalResult = await eval.EvaluateAsync(code, REvaluationKind.Normal); WaitForPackageInstalled(libPath, packageName); }
private async System.Threading.Tasks.Task CopyToClipboardAsBitmapAsync() { if (_rSession != null) { string fileName = Path.GetTempFileName(); using (IRSessionEvaluation eval = await _rSession.BeginEvaluationAsync()) { await eval.ExportToBitmapAsync("bmp", fileName, _lastPixelWidth, _lastPixelHeight, _lastResolution); VsAppShell.Current.DispatchOnUIThread( () => { try { // Use Begin/EndInit to avoid locking the file on disk var image = new BitmapImage(); image.BeginInit(); image.UriSource = new Uri(fileName); image.CacheOption = BitmapCacheOption.OnLoad; image.EndInit(); Clipboard.SetImage(image); SafeFileDelete(fileName); } catch (Exception e) when(!e.IsCriticalException()) { MessageBox.Show(string.Format(Resources.PlotCopyToClipboardError, e.Message)); } }); } } }
private async Task <bool> IsFunction(string name) { if (Keywords.IsKeyword(name)) { return(false); } string expression = $"tryCatch(is.function({name}), error = function(e) {{ }})"; AstRoot ast = RParser.Parse(expression); if (ast.Errors.Count > 0) { return(false); } var sessionProvider = EditorShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>(); IRSession session = sessionProvider.GetOrCreate(GuidList.InteractiveWindowRSessionGuid); if (session != null) { using (IRSessionEvaluation eval = await session.BeginEvaluationAsync()) { try { return(await eval.EvaluateAsync <bool>(expression, REvaluationKind.Normal)); } catch (RException) { } } } return(false); }
private async Task <bool> IsFunction(string name) { if (Keywords.IsKeyword(name)) { return(false); } string expression = $"tryCatch(is.function({name}), error = function(e) {{ }})"; AstRoot ast = RParser.Parse(expression); if (ast.Errors.Count > 0) { return(false); } var sessionProvider = EditorShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>(); IRSession session = sessionProvider.GetOrCreate(GuidList.InteractiveWindowRSessionGuid, null); if (session != null) { using (IRSessionEvaluation eval = await session.BeginEvaluationAsync(isMutating: false)) { REvaluationResult result = await eval.EvaluateAsync(expression); if (result.ParseStatus == RParseStatus.OK && !string.IsNullOrEmpty(result.StringResult) && (result.StringResult == "T" || result.StringResult == "TRUE")) { return(true); } } } return(false); }
private async System.Threading.Tasks.Task ExportAsImageAsync(string fileName, string deviceName) { if (_rSession != null) { using (IRSessionEvaluation eval = await _rSession.BeginEvaluationAsync()) { await eval.ExportToBitmapAsync(deviceName, fileName, _lastPixelWidth, _lastPixelHeight, _lastResolution); } } }
private async System.Threading.Tasks.Task ExportAsPdfAsync(string fileName) { if (_rSession != null) { using (IRSessionEvaluation eval = await _rSession.BeginEvaluationAsync()) { await eval.ExportToPdfAsync(fileName, PixelsToInches(_lastPixelWidth), PixelsToInches(_lastPixelHeight)); } } }
public Task<IRSessionEvaluation> BeginEvaluationAsync(bool isMutating = true, CancellationToken cancellationToken = default(CancellationToken)) { _eval = new RSessionEvaluationMock(); BeforeRequest?.Invoke(this, new RRequestEventArgs(_eval.Contexts, Prompt, 4096, true)); if (isMutating) { Mutated?.Invoke(this, EventArgs.Empty); } return Task.FromResult(_eval); }
public static Task <REvaluationResult> SetVsCranSelection(this IRSessionEvaluation evaluation, string mirrorUrl) { var script = @" local({ r <- getOption('repos') r['CRAN'] <- '" + mirrorUrl + @"' options(repos = r)})"; return(evaluation.EvaluateAsync(script)); }
public Task <IRSessionEvaluation> BeginEvaluationAsync(CancellationToken cancellationToken = default(CancellationToken)) { _eval = new RSessionEvaluationMock(); BeforeRequest?.Invoke(this, new RRequestEventArgs(_eval.Contexts, Prompt, 4096, true)); if (_eval.IsMutating) { Mutated?.Invoke(this, EventArgs.Empty); } return(Task.FromResult(_eval)); }
public static Task <REvaluationResult> SetVsGraphicsDevice(this IRSessionEvaluation evaluation) { var script = @" attach(as.environment(list(ide = function() { rtvs:::graphics.ide.new() })), name='rtvs::graphics::ide') options(device='ide') grDevices::deviceIsInteractive('ide') "; return(evaluation.EvaluateAsync(script)); }
public static Task <REvaluationResult> SetVsHelpRedirection(this IRSessionEvaluation evaluation) { var script = @"options(help_type = 'html') options(browser = function(url) { .Call('Microsoft.R.Host::Call.send_message', 'Browser', rtvs:::toJSON(url)) })"; return(evaluation.EvaluateAsync(script)); }
public static Task <REvaluationResult> SetChangeDirectoryRedirection(this IRSessionEvaluation evaluation) { var script = @"utils::assignInNamespace('setwd', function(dir) { old <- .Internal(setwd(dir)) .Call('Microsoft.R.Host::Call.send_message', '~/', rtvs:::toJSON(dir)) invisible(old) }, 'base')"; return(evaluation.EvaluateAsync(script)); }
public Task CancelAllAsync() { if (_eval != null) { AfterRequest?.Invoke(this, new RRequestEventArgs(_eval.Contexts, Prompt, 4096, true)); _eval = null; } else if (_inter != null) { AfterRequest?.Invoke(this, new RRequestEventArgs(_inter.Contexts, Prompt, 4096, true)); _inter = null; } return Task.CompletedTask; }
private static async Task LoadRtvsPackage(IRSessionEvaluation eval, string libPath) { await eval.ExecuteAsync(Invariant($@" if (!base::isNamespaceLoaded('rtvs')) {{ base::loadNamespace('rtvs', lib.loc = {libPath.ToRStringLiteral()}) }} if (rtvs:::version != {rtvsPackageVersion}) {{ warning('This R session was created using an incompatible version of RTVS, and may misbehave or crash when used with this version. Click ""Reset"" to replace it with a new clean session.'); }} ")); }
public static Task SetLocalLibsAsync(IRSessionEvaluation eval, params string[] libPaths) { foreach (var libPath in libPaths.Where(libPath => !Directory.Exists(libPath))) { Directory.CreateDirectory(libPath); } var paths = string.Join(",", libPaths.Select(p => p.ToRPath().ToRStringLiteral())); var code = $".libPaths(c({paths}))"; return(eval.ExecuteAsync(code)); }
public Task CancelAllAsync() { if (_eval != null) { AfterRequest?.Invoke(this, new RRequestEventArgs(_eval.Contexts, Prompt, 4096, true)); _eval = null; } else if (_inter != null) { AfterRequest?.Invoke(this, new RRequestEventArgs(_inter.Contexts, Prompt, 4096, true)); _inter = null; } return(Task.CompletedTask); }
private static async Task ShowDefaultHelpPageAsync() { var workflow = VsAppShell.Current.ExportProvider.GetExportedValue <IRInteractiveWorkflowProvider>().GetOrCreate(); var session = workflow.RSession; if (session.IsHostRunning) { try { using (IRSessionEvaluation evaluation = await session.BeginEvaluationAsync()) { await evaluation.EvaluateAsync("help.start()", REvaluationKind.Normal); } } catch (OperationCanceledException) { } } }
private static async Task LoadRtvsPackage(IRSessionEvaluation eval) { var libPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetAssemblyPath()); var res = await eval.EvaluateAsync(Invariant($"base::loadNamespace('rtvs', lib.loc = {libPath.ToRStringLiteral()})")); if (res.ParseStatus != RParseStatus.OK) { throw new InvalidDataException("Failed to parse loadNamespace('rtvs'): " + res.ParseStatus); } else if (res.Error != null) { throw new InvalidDataException("Failed to execute loadNamespace('rtvs'): " + res.Error); } }
private static async Task ShowDefaultHelpPageAsync() { var rSessionProvider = VsAppShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>(); var session = rSessionProvider.GetInteractiveWindowRSession(); if (session.IsHostRunning) { try { using (IRSessionEvaluation evaluation = await session.BeginEvaluationAsync(isMutating: false)) { await evaluation.EvaluateAsync("help.start()" + Environment.NewLine); } } catch (RException) { } catch (OperationCanceledException) { } } }
private async Task ShowHelpOnCurrentAsync(string prefix, string item) { try { using (IRSessionEvaluation evaluation = await _workflow.RSession.BeginEvaluationAsync()) { REvaluationResult result = await evaluation.EvaluateAsync(prefix + item, REvaluationKind.Normal); if (result.ParseStatus == RParseStatus.OK && string.IsNullOrEmpty(result.Error)) { if (string.IsNullOrEmpty(result.StringResult) || result.StringResult == "NA") { prefix = "??"; } } else { // Parsing or other errors, bail out Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Evaluation of help expression failed. Error: {0}, Status: {1}", result.Error, result.ParseStatus)); } } } catch (RException) { } catch (OperationCanceledException) { } // Now actually request the help. First call may throw since 'starting help server...' // message in REPL is actually an error (comes in red) so we'll get RException. int retries = 0; while (retries < 3) { using (IRSessionInteraction interaction = await _workflow.RSession.BeginInteractionAsync(isVisible: false)) { try { await interaction.RespondAsync(prefix + item + Environment.NewLine); } catch (RException ex) { if ((uint)ex.HResult == 0x80131500) { // Typically 'starting help server...' so try again retries++; continue; } } catch (OperationCanceledException) { } } break; } }
public async Task <PlotHistoryInfo> GetHistoryInfoAsync() { if (_rSession == null || !_rSession.IsHostRunning) { return(new PlotHistoryInfo()); } REvaluationResult result; using (IRSessionEvaluation eval = await _rSession.BeginEvaluationAsync()) { result = await eval.PlotHistoryInfo(); } return(new PlotHistoryInfo( (int)result.JsonResult[0].ToObject(typeof(int)), (int)result.JsonResult[1].ToObject(typeof(int)))); }
private async System.Threading.Tasks.Task CopyToClipboardAsMetafileAsync() { if (_rSession != null) { string fileName = Path.GetTempFileName(); using (IRSessionEvaluation eval = await _rSession.BeginEvaluationAsync()) { await eval.ExportToMetafileAsync(fileName, PixelsToInches(_lastPixelWidth), PixelsToInches(_lastPixelHeight), _lastResolution); VsAppShell.Current.DispatchOnUIThread( () => { try { var mf = new System.Drawing.Imaging.Metafile(fileName); Clipboard.SetData(DataFormats.EnhancedMetafile, mf); SafeFileDelete(fileName); } catch (Exception e) when(!e.IsCriticalException()) { MessageBox.Show(string.Format(Resources.PlotCopyToClipboardError, e.Message)); } }); } } }
public IsolatedRSessionEvaluation(IRSession session, IRSessionEvaluation evaluation) { _session = session; _evaluation = evaluation; }
public static Task <REvaluationResult> LoadWorkspace(this IRSessionEvaluation evaluation, string path) { return(evaluation.EvaluateNonReentrantAsync($"load('{path.Replace('\\', '/')}', .GlobalEnv)\n")); }
public static Task <REvaluationResult> SaveWorkspace(this IRSessionEvaluation evaluation, string path) { return(evaluation.EvaluateNonReentrantAsync($"save.image(file='{path.Replace('\\', '/')}')\n")); }
public static Task OptionsSetWidth(this IRSessionEvaluation evaluation, int width) { return(evaluation.EvaluateNonReentrantAsync($"options(width=as.integer({width}))\n")); }
public static Task <REvaluationResult> PlotHistoryInfo(this IRSessionEvaluation evaluation) { var script = @"rtvs:::toJSON(rtvs:::graphics.ide.historyinfo())"; return(evaluation.EvaluateAsync(script, REvaluationKind.Json)); }
private static async Task LoadRtvsPackage(IRSessionEvaluation eval, string libPath) { await eval.ExecuteAsync(Invariant($"base::loadNamespace('rtvs', lib.loc = {libPath.ToRStringLiteral()})")); }
public static Task SetLocalLibraryAsync(IRSessionEvaluation eval, MethodInfo testMethod, TestFilesFixture testFiles) { return(SetLocalLibsAsync(eval, Path.Combine(testFiles.LibraryDestinationPath, testMethod.Name))); }
public static Task SetLocalRepoAsync(IRSessionEvaluation eval, TestFilesFixture testFiles) => SetLocalRepoAsync(eval, GetRepoPath(testFiles));
public static Task SetLocalRepoAsync(IRSessionEvaluation eval, string localRepoPath) { var code = $"options(repos=list(LOCAL=\"file:///{localRepoPath.ToRPath()}\"))"; return(eval.ExecuteAsync(code)); }
private static async Task LoadRtvsPackage(IRSessionEvaluation eval) { var libPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetAssemblyPath()); await eval.ExecuteAsync(Invariant($"base::loadNamespace('rtvs', lib.loc = {libPath.ToRStringLiteral()})")); }