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); } } }
internal async Task <string> GetRWorkingDirectoryAsync() { await TaskUtilities.SwitchToBackgroundThread(); try { using (var evaluation = await _session.BeginEvaluationAsync(false)) { return(await evaluation.GetWorkingDirectory()); } } catch (TaskCanceledException) { } return(null); }
public async Task InteractDuringBrowse() { var tracer = await _session.TraceExecutionAsync(); using (var sf = new SourceFile("x <- 'old'; browser()")) { var browse = new TaskCompletionSource <bool>(); tracer.Browse += (s, e) => { browse.TrySetResult(true); }; await sf.Source(_session); await browse.Task; using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("x <- 'new'\n"); } string x; using (var eval = await _session.BeginEvaluationAsync()) { x = await eval.EvaluateAsync <string>("x", REvaluationKind.Normal); } x.Should().Be("new"); } }
public async Task InteractDuringBrowse() { using (var debugSession = new DebugSession(_session)) { using (var sf = new SourceFile("x <- 'old'; browser()")) { var browse = new TaskCompletionSource <bool>(); debugSession.Browse += (s, e) => { browse.TrySetResult(true); }; await sf.Source(_session); await browse.Task; using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("x <- 'new'\n"); } REvaluationResult x; using (var eval = await _session.BeginEvaluationAsync()) { x = await eval.EvaluateAsync("x"); } x.StringResult.Should().Be("new"); } } }
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); }
public async Task Serialize(string expr, string json) { if (json == SameAsInput) { json = expr; } using (var eval = await _session.BeginEvaluationAsync()) { var res = await eval.EvaluateAsync(expr, REvaluationKind.Json); res.Error.Should().BeNullOrEmpty(); res.JsonResult.Should().NotBeNull(); var actualJson = JsonConvert.SerializeObject(res.JsonResult); actualJson.Should().Be(json); } }
private async Task ProjectUnloading(object sender, EventArgs args) { VsAppShell.Current.AssertIsOnMainThread(); _unconfiguredProject.ProjectUnloading -= ProjectUnloading; _fileWatcher.Dispose(); if (!_fileSystem.DirectoryExists(_projectDirectory)) { return; } if (_toolsSettings.AlwaysSaveHistory) { _history.TrySaveToFile(Path.Combine(_projectDirectory, DefaultRHistoryName)); } var rdataPath = Path.Combine(_projectDirectory, DefaultRDataName); var saveDefaultWorkspace = await GetSaveDefaultWorkspace(rdataPath); if (!_session.IsHostRunning) { return; } Task.Run(async() => { using (var evaluation = await _session.BeginEvaluationAsync()) { if (saveDefaultWorkspace) { await evaluation.SaveWorkspaceAsync(rdataPath); } await evaluation.SetDefaultWorkingDirectoryAsync(); } }).SilenceException <RException>().SilenceException <MessageTransportException>().DoNotWait(); }
private async Task GetEnvironmentAsync() { await TaskUtilities.SwitchToBackgroundThread(); REvaluationResult result; using (var evaluation = await _rSession.BeginEvaluationAsync()) { result = await evaluation.EvaluateAsync("rtvs:::getEnvironments(sys.frame(sys.nframe()))", REvaluationKind.Json); } Debug.Assert(result.JsonResult != null); var envs = new List <REnvironment>(); var jarray = result.JsonResult as JArray; if (jarray != null) { foreach (var jsonItem in jarray) { envs.Add(new REnvironment(jsonItem)); } } VsAppShell.Current.DispatchOnUIThread(() => { OnEnvironmentChanged(new REnvironmentChangedEventArgs(envs)); }); }
private async Task EvalLibrariesAsync(IRSession session, string deparsedLibraries) { var code = string.Format(".libPaths(eval(parse(text={0})))", deparsedLibraries.ToRStringLiteral()); using (var eval = await session.BeginEvaluationAsync()) { await WrapRException(eval.ExecuteAsync(code)); } }
private static async Task GetScheduleEvaluationTask(this IRSession session, Func <IRSessionEvaluation, Task> function) { await TaskUtilities.SwitchToBackgroundThread(); using (var evaluation = await session.BeginEvaluationAsync()) { await function(evaluation); } }
public async Task Serialize(string expr, string json) { using (var eval = await _session.BeginEvaluationAsync()) { var res = await eval.EvaluateAsync(Invariant($"rtvs:::toJSON({expr})")); res.Error.Should().BeNullOrEmpty(); res.StringResult.Should().Be(json); } }
private async Task LoadWorkspace(IRSession session, string file) { REvaluationResult result; using (var evaluation = await session.BeginEvaluationAsync()) { result = await evaluation.LoadWorkspace(file); } if (result.Error != null) { var message = string.Format(CultureInfo.CurrentCulture, Resources.LoadWorkspaceFailedMessageFormat, file, result.Error); VsAppShell.Current.ShowErrorMessage(message); } }
public async Task InitializeProjectFromDiskAsync() { await Project.CreateInMemoryImport(); _fileWatcher.Start(); await _threadHandling.SwitchToUIThread(); // Make sure R package is loaded VsAppShell.EnsurePackageLoaded(RGuidList.RPackageGuid); // Verify project is not on a network share and give warning if it is CheckRemoteDrive(_projectDirectory); _workflow = _workflowProvider.GetOrCreate(); _session = _workflow.RSession; _history = _workflow.History; if (_workflow.ActiveWindow == null) { var window = await _workflow.GetOrCreateVisualComponent(_componentContainerFactory); window.Container.Show(true); } try { await _session.HostStarted; } catch (Exception) { return; } // TODO: need to compute the proper paths for remote, but they might not even exist if the project hasn't been deployed. // https://github.com/Microsoft/RTVS/issues/2223 if (!_session.IsRemote) { var rdataPath = Path.Combine(_projectDirectory, DefaultRDataName); bool loadDefaultWorkspace = _fileSystem.FileExists(rdataPath) && await GetLoadDefaultWorkspace(rdataPath); using (var evaluation = await _session.BeginEvaluationAsync()) { if (loadDefaultWorkspace) { await evaluation.LoadWorkspaceAsync(rdataPath); } await evaluation.SetWorkingDirectoryAsync(_projectDirectory); } _toolsSettings.WorkingDirectory = _projectDirectory; } _history.TryLoadFromFile(Path.Combine(_projectDirectory, DefaultRHistoryName)); CheckSurveyNews(); }
private async Task LoadWorkspace(IRSession session, string file) { using (var evaluation = await session.BeginEvaluationAsync()) { try { await evaluation.LoadWorkspaceAsync(file); } catch (RException ex) { var message = string.Format(CultureInfo.CurrentCulture, Resources.LoadWorkspaceFailedMessageFormat, file, ex.Message); VsAppShell.Current.ShowErrorMessage(message); } catch (OperationCanceledException) { } } }
private async Task <REvaluationResult> CallIconvListAsync() { await TaskUtilities.SwitchToBackgroundThread(); IRSession rSession = GetRSession(); REvaluationResult result; using (var evaluator = await rSession.BeginEvaluationAsync()) { result = await evaluator.EvaluateAsync("as.list(iconvlist())", REvaluationKind.Json); } return(result); }
private async Task <REvaluationResult> EvaluateAsyncAsync(string expression) { await TaskUtilities.SwitchToBackgroundThread(); IRSession rSession = GetRSession(); REvaluationResult result; using (var evaluator = await rSession.BeginEvaluationAsync()) { result = await evaluator.EvaluateAsync(expression, REvaluationKind.Mutating); } return(result); }
/// <summary> /// Asynchronously fetches RD data on the function from R. /// When RD data is available, invokes specified callback /// passing funation name and the RD data extracted from R. /// </summary> public void GetFunctionRdData(string functionName, string packageName, Action <string> rdDataAvailableCallback) { Task.Run(async() => { await CreateSessionAsync(); using (var eval = await _session.BeginEvaluationAsync()) { string command = GetCommandText(functionName, packageName); REvaluationResult result = await eval.EvaluateAsync(command); if (result.ParseStatus == RParseStatus.OK && result.StringResult != null && result.StringResult.Length > 2) { rdDataAvailableCallback(result.StringResult); } } }); }
public static async Task <string> GetRUserDirectoryAsync(this IRSession session) { if (session.IsHostRunning) { await TaskUtilities.SwitchToBackgroundThread(); try { using (var evaluation = await session.BeginEvaluationAsync()) { return(await evaluation.GetRUserDirectory()); } } catch (OperationCanceledException) { } } return(null); }
private async Task SaveWorkspace(string file) { REvaluationResult result; using (var evaluation = await _rSession.BeginEvaluationAsync()) { result = await evaluation.SaveWorkspace(file); } if (result.Error != null) { var message = string.Format(CultureInfo.CurrentCulture, Resources.SaveWorkspaceFailedMessageFormat, file, result.Error); VsAppShell.Current.ShowErrorMessage(message); } }
public async Task InitializeProjectFromDiskAsync() { await Project.CreateInMemoryImport(); _fileWatcher.Start(); // Force REPL window up and continue only when it is shown await _threadHandling.SwitchToUIThread(); // Make sure R package is loaded VsAppShell.EnsurePackageLoaded(RGuidList.RPackageGuid); // Verify project is not on a network share and give warning if it is CheckRemoteDrive(_projectDirectory); _workflow = _workflowProvider.GetOrCreate(); _session = _workflow.RSession; _history = _workflow.History; if (_workflow.ActiveWindow == null) { var window = await _workflow.GetOrCreateVisualComponent(_componentContainerFactory); window.Container.Show(true); } try { await _session.HostStarted; } catch (Exception) { return; } var rdataPath = Path.Combine(_projectDirectory, DefaultRDataName); bool loadDefaultWorkspace = _fileSystem.FileExists(rdataPath) && await GetLoadDefaultWorkspace(rdataPath); using (var evaluation = await _session.BeginEvaluationAsync()) { if (loadDefaultWorkspace) { await evaluation.LoadWorkspace(rdataPath); } await evaluation.SetWorkingDirectory(_projectDirectory); } _toolsSettings.WorkingDirectory = _projectDirectory; _history.TryLoadFromFile(Path.Combine(_projectDirectory, DefaultRHistoryName)); CheckSurveyNews(); }
public async Task RCreateGetDestroyBlobs() { using (var eval = await _session.BeginEvaluationAsync()) { var createResult = await eval.EvaluateAsync("rtvs:::create_blob(as.raw(1:10))", REvaluationKind.Normal); createResult.Result.Should().NotBeNull(); var blobId = ((JValue)createResult.Result).Value <ulong>(); var actualData = await eval.EvaluateAsync <byte[]>($"rtvs:::get_blob({blobId})", REvaluationKind.Normal); byte[] expectedData = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; actualData.Should().Equal(expectedData); await eval.ExecuteAsync($"rtvs:::destroy_blob({blobId})"); } }
/// <summary> /// Asynchronously fetches RD data on the function from R. /// When RD data is available, invokes specified callback /// passing funation name and the RD data extracted from R. /// </summary> public void GetFunctionRdData(string functionName, string packageName, Action <string> rdDataAvailableCallback) { Task.Run(async() => { await CreateSessionAsync(); using (var eval = await _session.BeginEvaluationAsync()) { string command = GetCommandText(functionName, packageName); string rd; try { rd = await eval.EvaluateAsync <string>(command, REvaluationKind.Normal); } catch (RException) { return; } rdDataAvailableCallback(rd); } }); }
private static async Task CreateCsvAndStartProcess(IREvaluationResultInfo result, IRSession session, string file) { await TaskUtilities.SwitchToBackgroundThread(); var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator; var dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; using (var e = await session.BeginEvaluationAsync()) { await e.EvaluateAsync($"write.table({result.Expression}, qmethod='double', col.names=NA, file={file.ToRPath().ToRStringLiteral()}, sep={sep.ToRStringLiteral()}, dec={dec.ToRStringLiteral()})", REvaluationKind.Normal); } if (File.Exists(file)) { Process.Start(file); } }
public static async Task <IGridData <string> > GetGridDataAsync(string expression, GridRange?gridRange, IRSession rSession = null) { await TaskUtilities.SwitchToBackgroundThread(); if (rSession == null) { rSession = VsAppShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>().GetInteractiveWindowRSession(); if (rSession == null) { throw new InvalidOperationException(Invariant($"{nameof(IRSessionProvider)} failed to return RSession for {nameof(EvaluationWrapper)}")); } } string rows = gridRange?.Rows.ToRString(); string columns = gridRange?.Columns.ToRString(); REvaluationResult?result = null; using (var evaluator = await rSession.BeginEvaluationAsync()) { result = await evaluator.EvaluateAsync($"rtvs:::grid.dput(rtvs:::grid.data({expression}, {rows}, {columns}))", REvaluationKind.Normal); if (result.Value.ParseStatus != RParseStatus.OK || result.Value.Error != null) { throw new InvalidOperationException($"Grid data evaluation failed{Environment.NewLine} {result}"); } } GridData data = null; if (result.HasValue) { data = GridParser.Parse(result.Value.StringResult.ToUnicodeQuotes()); if (gridRange.HasValue) { data.Range = gridRange.Value; } if ((data.ValidHeaderNames.HasFlag(GridData.HeaderNames.Row) && data.RowNames.Count != data.Range.Rows.Count) || (data.ValidHeaderNames.HasFlag(GridData.HeaderNames.Column) && data.ColumnNames.Count != data.Range.Columns.Count)) { throw new InvalidOperationException("Header names lengths are different from data's length"); } } return(data); }
private static async Task CreateCsvAndStartProcess(IREvaluationResultInfo result, IRSession session, string fileName, IFileSystem fileSystem, IProcessServices processServices) { await TaskUtilities.SwitchToBackgroundThread(); var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator; var dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; using (var e = await session.BeginEvaluationAsync()) { var csvData = await e.EvaluateAsync <byte[]>($"rtvs:::export_to_csv({result.Expression}, sep={sep.ToRStringLiteral()}, dec={dec.ToRStringLiteral()})", REvaluationKind.Normal); fileSystem.FileWriteAllBytes(fileName, csvData); } if (fileSystem.FileExists(fileName)) { processServices.Start(fileName); } }
public static async Task <IGridData <string> > GetGridDataAsync(IRSession rSession, string expression, GridRange?gridRange, ISortOrder sortOrder = null) { await TaskUtilities.SwitchToBackgroundThread(); string rows = gridRange?.Rows.ToRString(); string columns = gridRange?.Columns.ToRString(); string rowSelector = (sortOrder != null && !sortOrder.IsEmpty) ? sortOrder.GetRowSelector() : ""; string expr = Invariant($"rtvs:::grid_data({expression}, {rows}, {columns}, {rowSelector})"); using (var evaluator = await rSession.BeginEvaluationAsync()) { try { return(await evaluator.EvaluateAsync <GridData>(expr, REvaluationKind.Normal)); } catch (RException ex) { var message = Invariant($"Grid data evaluation failed:{Environment.NewLine}{ex.Message}"); GeneralLog.Write(message); return(null); } } }
private static async Task CreateCsvAndStartProcess(IREvaluationResultInfo result, IRSession session, string fileName, IFileSystem fileSystem, IProgress <ProgressDialogData> progress) { await TaskUtilities.SwitchToBackgroundThread(); var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator; var dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; using (var e = await session.BeginEvaluationAsync()) { var csvDataBlobId = await e.EvaluateAsync <ulong>($"rtvs:::export_to_csv({result.Expression}, sep={sep.ToRStringLiteral()}, dec={dec.ToRStringLiteral()})", REvaluationKind.Normal); using (DataTransferSession dts = new DataTransferSession(session, fileSystem)) { var total = await session.GetBlobSizeAsync(csvDataBlobId, CancellationToken.None); progress.Report(new ProgressDialogData(0, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV)); await dts.FetchFileAsync(new RBlobInfo(csvDataBlobId), fileName, true, new Progress <long>(b => { var step = (int)(b * 100 / total); progress.Report(new ProgressDialogData(step, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV)); })); progress.Report(new ProgressDialogData(100, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV)); } } }
private async Task ProjectUnloading(object sender, EventArgs args) { _unconfiguredProject.ProjectUnloading -= ProjectUnloading; _fileWatcher.Dispose(); if (!_session.IsHostRunning) { return; } if (!_fileSystem.DirectoryExists(_projectDirectory)) { return; } var rdataPath = Path.Combine(_projectDirectory, DefaultRDataName); var saveDefaultWorkspace = await GetSaveDefaultWorkspace(rdataPath); Task.Run(async() => { try { using (var evaluation = await _session.BeginEvaluationAsync()) { if (saveDefaultWorkspace) { await evaluation.SaveWorkspace(rdataPath); } await evaluation.SetDefaultWorkingDirectory(); } } catch (OperationCanceledException) { return; } if (saveDefaultWorkspace || _toolsSettings.AlwaysSaveHistory) { await _threadHandling.SwitchToUIThread(); _history.TrySaveToFile(Path.Combine(_projectDirectory, DefaultRHistoryName)); } }).DoNotWait(); }
public static async Task<IGridData<string>> GetGridDataAsync(string expression, GridRange gridRange, IRSession rSession = null) { await TaskUtilities.SwitchToBackgroundThread(); if (rSession == null) { rSession = VsAppShell.Current.ExportProvider.GetExportedValue<IRSessionProvider>().GetInteractiveWindowRSession(); if (rSession == null) { throw new InvalidOperationException(Invariant($"{nameof(IRSessionProvider)} failed to return RSession for {nameof(EvaluationWrapper)}")); } } string rows = gridRange.Rows.ToRString(); string columns = gridRange.Columns.ToRString(); REvaluationResult? result = null; using (var evaluator = await rSession.BeginEvaluationAsync(false)) { result = await evaluator.EvaluateAsync($"rtvs:::grid.dput(rtvs:::grid.data({expression}, {rows}, {columns}))", REvaluationKind.Normal); if (result.Value.ParseStatus != RParseStatus.OK || result.Value.Error != null) { throw new InvalidOperationException($"Grid data evaluation failed:{result}"); } } GridData data = null; if (result.HasValue) { data = GridParser.Parse(result.Value.StringResult.ToUnicodeQuotes()); data.Range = gridRange; if ((data.ValidHeaderNames.HasFlag(GridData.HeaderNames.Row) && data.RowNames.Count != gridRange.Rows.Count) || (data.ValidHeaderNames.HasFlag(GridData.HeaderNames.Column) && data.ColumnNames.Count != gridRange.Columns.Count)) { throw new InvalidOperationException("Header names lengths are different from data's length"); } } return data; }
protected virtual async Task <bool> TryHandleCommandAsyncInternal(IProjectTree rDataNode) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); MessageButtons messageResult = VsAppShell.Current.ShowMessage(string.Format(CultureInfo.CurrentCulture, Resources.LoadWorkspaceIntoGlobalEnvironment, rDataNode.FilePath), MessageButtons.YesNo); if (messageResult == MessageButtons.No) { return(true); } using (var evaluation = await _session.BeginEvaluationAsync()) { var result = await evaluation.LoadWorkspace(rDataNode.FilePath); if (result.Error != null) { var message = string.Format(CultureInfo.CurrentCulture, Resources.LoadWorkspaceFailedMessageFormat, rDataNode.FilePath, result.Error); VsAppShell.Current.ShowErrorMessage(message); } } return(true); }
public async Task InitializeProjectFromDiskAsync() { await Project.CreateInMemoryImport(); _fileWatcher.Start(); // Force REPL window up and continue only when it is shown await _threadHandling.SwitchToUIThread(); // Make sure R package is loaded VsAppShell.EnsurePackageLoaded(RGuidList.RPackageGuid); // Verify project is not on a network share and give warning if it is CheckRemoteDrive(_projectDirectory); _workflow = _workflowProvider.GetOrCreate(); _session = _workflow.RSession; _history = _workflow.History; if (_workflow.ActiveWindow == null) { var window = await _workflow.GetOrCreateVisualComponent(_componentContainerFactory); window.Container.Show(true); } try { await _session.HostStarted; } catch (Exception) { return; } var rdataPath = Path.Combine(_projectDirectory, DefaultRDataName); bool loadDefaultWorkspace = _fileSystem.FileExists(rdataPath) && await GetLoadDefaultWorkspace(rdataPath); using (var evaluation = await _session.BeginEvaluationAsync()) { if (loadDefaultWorkspace) { await evaluation.LoadWorkspace(rdataPath); } await evaluation.SetWorkingDirectory(_projectDirectory); } _toolsSettings.WorkingDirectory = _projectDirectory; _history.TryLoadFromFile(Path.Combine(_projectDirectory, DefaultRHistoryName)); }