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);
        }
Esempio n. 2
0
        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));
                        }
                    });
                }
            }
        }
Esempio n. 3
0
        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);
        }
Esempio n. 4
0
        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);
        }
Esempio n. 5
0
 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);
         }
     }
 }
Esempio n. 6
0
 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));
         }
     }
 }
Esempio n. 7
0
        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));
        }
Esempio n. 9
0
 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));
 }
Esempio n. 10
0
        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));
        }
Esempio n. 11
0
        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));
        }
Esempio n. 12
0
        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));
        }
Esempio n. 13
0
 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;
 }
Esempio n. 14
0
        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.');
}}
"));
        }
Esempio n. 15
0
        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));
        }
Esempio n. 16
0
 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);
 }
Esempio n. 17
0
        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) { }
            }
        }
Esempio n. 18
0
        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);
            }
        }
Esempio n. 19
0
        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) { }
            }
        }
Esempio n. 20
0
        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;
            }
        }
Esempio n. 21
0
        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))));
        }
Esempio n. 22
0
        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));
                        }
                    });
                }
            }
        }
Esempio n. 23
0
 public IsolatedRSessionEvaluation(IRSession session, IRSessionEvaluation evaluation)
 {
     _session    = session;
     _evaluation = evaluation;
 }
Esempio n. 24
0
        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);
            }
        }
Esempio n. 25
0
 public static Task <REvaluationResult> LoadWorkspace(this IRSessionEvaluation evaluation, string path)
 {
     return(evaluation.EvaluateNonReentrantAsync($"load('{path.Replace('\\', '/')}', .GlobalEnv)\n"));
 }
Esempio n. 26
0
 public static Task <REvaluationResult> SaveWorkspace(this IRSessionEvaluation evaluation, string path)
 {
     return(evaluation.EvaluateNonReentrantAsync($"save.image(file='{path.Replace('\\', '/')}')\n"));
 }
Esempio n. 27
0
 public static Task OptionsSetWidth(this IRSessionEvaluation evaluation, int width)
 {
     return(evaluation.EvaluateNonReentrantAsync($"options(width=as.integer({width}))\n"));
 }
Esempio n. 28
0
        public static Task <REvaluationResult> PlotHistoryInfo(this IRSessionEvaluation evaluation)
        {
            var script = @"rtvs:::toJSON(rtvs:::graphics.ide.historyinfo())";

            return(evaluation.EvaluateAsync(script, REvaluationKind.Json));
        }
Esempio n. 29
0
 private static async Task LoadRtvsPackage(IRSessionEvaluation eval, string libPath)
 {
     await eval.ExecuteAsync(Invariant($"base::loadNamespace('rtvs', lib.loc = {libPath.ToRStringLiteral()})"));
 }
Esempio n. 30
0
 public static Task SetLocalLibraryAsync(IRSessionEvaluation eval, MethodInfo testMethod, TestFilesFixture testFiles)
 {
     return(SetLocalLibsAsync(eval, Path.Combine(testFiles.LibraryDestinationPath, testMethod.Name)));
 }
Esempio n. 31
0
 public static Task SetLocalRepoAsync(IRSessionEvaluation eval, TestFilesFixture testFiles) => SetLocalRepoAsync(eval, GetRepoPath(testFiles));
Esempio n. 32
0
        public static Task SetLocalRepoAsync(IRSessionEvaluation eval, string localRepoPath)
        {
            var code = $"options(repos=list(LOCAL=\"file:///{localRepoPath.ToRPath()}\"))";

            return(eval.ExecuteAsync(code));
        }
Esempio n. 33
0
 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()})"));
 }