Пример #1
0
        private IInteractiveWindowVisualComponent CreateInteractiveWindow(int id)
        {
            var workflow = _workflowProvider.GetOrCreate();

            _services.Tasks().Wait(() => workflow.GetOrCreateVisualComponentAsync(id), out var result);
            return(result);
        }
Пример #2
0
        public async Task InteractiveWindowIntegration01()
        {
            var workflow = UIThreadHelper.Instance.Invoke(() => _workflowProvider.GetOrCreate());
            var history  = (IRHistoryVisual)workflow.History;
            var session  = workflow.RSession;

            using (await UIThreadHelper.Instance.Invoke(() => workflow.GetOrCreateVisualComponentAsync())) {
                workflow.ActiveWindow.Should().NotBeNull();
                session.IsHostRunning.Should().BeTrue();

                var eval   = workflow.ActiveWindow.InteractiveWindow.Evaluator;
                var result = await eval.ExecuteCodeAsync("x <- c(1:10)\r\n");

                result.Should().Be(ExecutionResult.Success);
                history.HasEntries.Should().BeTrue();
                history.HasSelectedEntries.Should().BeFalse();
                history.SelectHistoryEntry(0);
                history.HasSelectedEntries.Should().BeTrue();

                var textBuffer = _textBufferFactory.CreateTextBuffer(_contentTypeRegistryService.GetContentType(RContentTypeDefinition.ContentType));
                var textView   = UIThreadHelper.Instance.Invoke(() => _textEditorFactory.CreateTextView(textBuffer, _textEditorFactory.DefaultRoles));

                history.SendSelectedToTextView(textView);
                var text = textBuffer.CurrentSnapshot.GetText();
                text.Should().Be("x <- c(1:10)");

                UIThreadHelper.Instance.Invoke(() => textView.Close());
            }
        }
Пример #3
0
        private IInteractiveWindowVisualComponent CreateInteractiveWindow(int id)
        {
            var workflow = _workflowProvider.GetOrCreate();
            var task     = workflow.GetOrCreateVisualComponentAsync(id);

            _services.Tasks().Wait(task);
            return(task.GetAwaiter().GetResult());
        }
Пример #4
0
 public CommandStatusResult GetCommandStatus(IImmutableSet <IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus)
 {
     if (commandId == RPackageCommandId.icmdSetDirectoryHere && nodes.Count == 1)
     {
         var  session = _interactiveWorkflowProvider.GetOrCreate().RSession;
         bool enabled = session != null && session.IsHostRunning && !session.IsRemote;
         return(new CommandStatusResult(true, commandText, enabled ? CommandStatus.Enabled | CommandStatus.Supported : CommandStatus.Supported));
     }
     return(CommandStatusResult.Unhandled);
 }
Пример #5
0
        public override CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg)
        {
            if (!TaskAvailable())
            {
                return(CommandResult.Disabled);
            }

            IMarkdownFlavorPublishHandler flavorHandler = GetFlavorHandler(TextView.TextBuffer);

            if (flavorHandler == null)
            {
                return(CommandResult.Disabled);
            }

            var workflow = _workflowProvider.GetOrCreate();

            _lastCommandTask = Task.Run(async() => {
                // Get list of installed packages and verify that all the required ones are installed
                var packages = await workflow.Packages.GetInstalledPackagesAsync();
                if (packages.Any(p => p.Package.EqualsIgnoreCase(flavorHandler.RequiredPackageName)))
                {
                    // Text buffer operations should be performed in UI thread
                    await Services.MainThread().SwitchToAsync();
                    if (await CheckPrerequisitesAsync())
                    {
                        var textBuffer = SaveFile();
                        if (textBuffer != null)
                        {
                            var inputFilePath = textBuffer.GetFilePath();
                            _outputFilePath   = Path.ChangeExtension(inputFilePath, FileExtension);

                            try {
                                _fs.DeleteFile(_outputFilePath);
                            } catch (IOException ex) {
                                Services.UI().ShowErrorMessage(ex.Message);
                                return;
                            }

                            var session = workflow.RSession;
                            await flavorHandler.PublishAsync(session, Services, inputFilePath, _outputFilePath, Format, textBuffer.GetEncoding()).ContinueWith(t => LaunchViewer());
                        }
                    }
                }
                else
                {
                    await Services.ShowErrorMessageAsync(Resources.Error_PackageMissing.FormatInvariant(flavorHandler.RequiredPackageName));
                }
            });

            return(CommandResult.Executed);
        }
Пример #6
0
        public IEnumerable <ICommand> GetCommands(ITextView textView, ITextBuffer textBuffer)
        {
            var interactiveWorkflow = _interactiveWorkflowProvider.GetOrCreate();
            var sendToReplCommand   = new SendHistoryToReplCommand(textView, _historyProvider, interactiveWorkflow);
            var sendToSourceCommand = new SendHistoryToSourceCommand(textView, _historyProvider, interactiveWorkflow, _contentTypeRegistry, _textViewTracker);

            return(new ICommand[] {
                new LoadHistoryCommand(textView, _historyProvider, interactiveWorkflow),
                new SaveHistoryCommand(textView, _historyProvider, interactiveWorkflow),
                sendToReplCommand,
                sendToSourceCommand,
                new DeleteSelectedHistoryEntriesCommand(textView, _historyProvider, interactiveWorkflow),
                new DeleteAllHistoryEntriesCommand(textView, _historyProvider, interactiveWorkflow),
                new HistoryWindowVsStd2KCmdIdReturnCommand(textView, sendToReplCommand, sendToSourceCommand),
                new HistoryWindowVsStd97CmdIdSelectAllCommand(textView, _historyProvider, interactiveWorkflow),
                new HistoryWindowVsStd2KCmdIdUp(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdUpExt(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdDown(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdDownExt(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdLeftExt(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdRightExt(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdHome(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdEnd(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdPageUp(textView, _historyProvider),
                new HistoryWindowVsStd2KCmdIdPageDown(textView, _historyProvider),
                new ToggleMultilineHistorySelectionCommand(textView, _historyProvider, interactiveWorkflow),
                new CopySelectedHistoryCommand(textView, _historyProvider, interactiveWorkflow)
            });
        }
Пример #7
0
 public RDebugLaunchProvider(ConfiguredProject configuredProject, IRInteractiveWorkflowVisualProvider interactiveWorkflowProvider, IProjectSystemServices pss)
     : base(configuredProject)
 {
     _properties          = configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>();
     _interactiveWorkflow = interactiveWorkflowProvider.GetOrCreate();
     _pss = pss;
 }
Пример #8
0
        public string GetCodeColorsCss()
        {
            var sb       = new StringBuilder();
            var workflow = _workflowProvider.GetOrCreate();

            if (workflow.ActiveWindow?.TextView != null)
            {
                var map = _formatMapService.GetClassificationFormatMap(workflow.ActiveWindow.TextView);
                foreach (var cssCodeProp in _cssPropertyMap)
                {
                    var props = map.GetTextProperties(_classificationRegistryService.GetClassificationType(cssCodeProp.ClassificationTypeName));
                    sb.AppendLine(Invariant(
                                      $@"code > span.{cssCodeProp.CssClassName} {{
    color: {CssColorFromBrush(props.ForegroundBrush)};
}}
"));
                }

                foreach (var cssCodeProp in _prePropertyMap)
                {
                    var props = map.GetTextProperties(_classificationRegistryService.GetClassificationType(cssCodeProp.ClassificationTypeName));
                    sb.AppendLine(Invariant(
                                      $@"pre .{cssCodeProp.CssClassName} {{
    color: {CssColorFromBrush(props.ForegroundBrush)};
}}"
                                      ));
                }
            }
            return(sb.ToString());
        }
Пример #9
0
        public RInteractiveEvaluatorTest(IServiceContainer services)
        {
            var settings = services.GetService <IRSettings>();

            settings.RCodePage = 1252;

            _workflowProvider = services.GetService <IRInteractiveWorkflowVisualProvider>();
            _workflow         = UIThreadHelper.Instance.Invoke(() => _workflowProvider.GetOrCreate());
        }
        private async Task <IRInteractiveWorkflow> CreateWorkflowAsync()
        {
            var workflow = UIThreadHelper.Instance.Invoke(() => _workflowProvider.GetOrCreate());
            var settings = _services.GetService <IRSettings>();
            await workflow.RSessions.TrySwitchBrokerAsync(nameof(PackageManagerIntegrationTest));

            await workflow.RSession.EnsureHostStartedAsync(new RHostStartupInfo (settings.CranMirror, codePage : settings.RCodePage), new RHostClientTestApp(), 50000);

            return(workflow);
        }
Пример #11
0
        public Task <CommandStatusResult> GetCommandStatusAsync(IImmutableSet <IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus)
        {
            var session = _interactiveWorkflowProvider.GetOrCreate().RSession;

            if (commandId == RPackageCommandId.icmdSendToRemote && session.IsHostRunning && session.IsRemote)
            {
                return(Task.FromResult(new CommandStatusResult(true, commandText, CommandStatus.Enabled | CommandStatus.Supported)));
            }
            return(Task.FromResult(CommandStatusResult.Unhandled));
        }
Пример #12
0
 public RPlotIntegrationTest(IServiceContainer services, TestMethodFixture testMethod, TestFilesFixture testFiles)
 {
     _workflowProvider = services.GetService <TestRInteractiveWorkflowProvider>();
     _workflow         = _workflowProvider.GetOrCreate();
     _plotDeviceVisualComponentContainerFactory  = services.GetService <TestRPlotDeviceVisualComponentContainerFactory>();
     _plotHistoryVisualComponentContainerFactory = services.GetService <IRPlotHistoryVisualComponentContainerFactory>();
     _testMethod = testMethod.MethodInfo;
     _testFiles  = testFiles;
     _ui         = _workflow.Shell.UI() as TestUIServices;
 }
Пример #13
0
        public ReplCommandTest()
        {
            _debuggerModeTracker = new VsDebuggerModeTracker(_coreShell);
            _coreShell.ServiceManager.AddService(new TestRToolsSettings());

            _workflowProvider = TestRInteractiveWorkflowProviderFactory.Create(
                connectionsProvider: new ConnectionManagerProvider(new TestStatusBar(), _coreShell),
                debuggerModeTracker: _debuggerModeTracker);
            _workflow = _workflowProvider.GetOrCreate();
        }
Пример #14
0
        public ReplCommandTest(IServiceContainer services)
        {
            var coreShell = services.GetService <ICoreShell>();

            _debuggerModeTracker = new VsDebuggerModeTracker(coreShell);

            _workflowProvider = TestRInteractiveWorkflowProviderFactory.Create(
                connectionsProvider: new ConnectionManagerProvider(services),
                debuggerModeTracker: _debuggerModeTracker);
            _workflow = _workflowProvider.GetOrCreate();
        }
Пример #15
0
        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.GetOrCreateVisualComponentAsync();

                window.Container.Show(focus: true, immediate: false);
            }

            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 = _coreShell.FileSystem().FileExists(rdataPath) && await GetLoadDefaultWorkspace(rdataPath);

                if (loadDefaultWorkspace)
                {
                    await _session.LoadWorkspaceAsync(rdataPath);
                }
                await _session.SetWorkingDirectoryAsync(_projectDirectory);

                _toolsSettings.WorkingDirectory = _projectDirectory;
            }

            _history.TryLoadFromFile(Path.Combine(_projectDirectory, DefaultRHistoryName));

            CheckSurveyNews();
        }
Пример #16
0
        protected override void Handle()
        {
            var interactiveWorkflow = _interactiveWorkflowProvider.GetOrCreate();
            var window = interactiveWorkflow.ActiveWindow;

            if (window != null)
            {
                window.Container.Show(focus: true, immediate: false);
                return;
            }

            interactiveWorkflow
            .GetOrCreateVisualComponentAsync()
            .ContinueOnRanToCompletion(w => w.Container.Show(focus: true, immediate: false));
        }
Пример #17
0
        public IEnumerable <ICommand> GetCommands(ITextView textView, ITextBuffer textBuffer)
        {
            var workflow = _workflowProvider.GetOrCreate();

            if (workflow.ActiveWindow == null)
            {
                workflow.GetOrCreateVisualComponentAsync()
                .ContinueOnRanToCompletion(w => w.Container.Show(focus: false, immediate: false));
            }

            return(new ICommand[] {
                new ClearReplCommand(textView, workflow),
                new ShowContextMenuCommand(textView, MdGuidList.MdPackageGuid, MdGuidList.MdCmdSetGuid, (int)MarkdownContextMenuId.MD, _services)
            });
        }
Пример #18
0
        public async Task <bool> TryHandleCommandAsync(IImmutableSet <IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
        {
            if (commandId == RPackageCommandId.icmdSourceSelectedFiles || commandId == RPackageCommandId.icmdSourceSelectedFilesWithEcho)
            {
                bool echo = commandId == RPackageCommandId.icmdSourceSelectedFilesWithEcho;

                IFileSystem          fs     = new FileSystem();
                IEnumerable <string> rFiles = Enumerable.Empty <string>();

                var workflow = _interactiveWorkflowProvider.GetOrCreate();
                try {
                    var session = workflow.RSession;
                    if (session.IsRemote)
                    {
                        var files = nodes.GetSelectedNodesPaths().Where(x =>
                                                                        Path.GetExtension(x).EqualsIgnoreCase(RContentTypeDefinition.FileExtension) &&
                                                                        fs.FileExists(x));

                        var    properties  = _configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>();
                        string projectDir  = Path.GetDirectoryName(_configuredProject.UnconfiguredProject.FullPath);
                        string projectName = properties.GetProjectName();
                        string remotePath  = await properties.GetRemoteProjectPathAsync();

                        await SendToRemoteAsync(files, projectDir, projectName, remotePath);

                        rFiles = files.Select(p => p.MakeRelativePath(projectDir).ProjectRelativePathToRemoteProjectPath(remotePath, projectName));
                    }
                    else
                    {
                        rFiles = nodes.GetSelectedNodesPaths().Where(x =>
                                                                     Path.GetExtension(x).EqualsIgnoreCase(RContentTypeDefinition.FileExtension) &&
                                                                     fs.FileExists(x));
                    }

                    workflow.Operations.SourceFiles(rFiles, echo);
                } catch (IOException ex) {
                    _shell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_CannotTransferFile, ex.Message));
                }
                catch (RHostDisconnectedException) {
                    workflow.ActiveWindow.InteractiveWindow.WriteErrorLine(Resources.Error_CannotTransferNoRSession);
                }
                return(true);
            }
            return(false);
        }
Пример #19
0
        public IEnumerable <ICommand> GetCommands(ITextView textView, ITextBuffer textBuffer)
        {
            var workflow = _workflowProvider.GetOrCreate();

            if (workflow.ActiveWindow == null)
            {
                workflow.GetOrCreateVisualComponentAsync()
                .ContinueOnRanToCompletion(w => w.Container.Show(focus: false, immediate: false));
            }

            return(new ICommand[] {
                new ShowContextMenuCommand(textView, RGuidList.RPackageGuid, RGuidList.RCmdSetGuid, (int)RContextMenuId.R, workflow.Shell.Services),
                new SendToReplCommand(textView, workflow),
                new ClearReplCommand(textView, workflow),
                new GoToFormattingOptionsCommand(textView, workflow.Shell.Services),
                new WorkingDirectoryCommand(workflow)
            });
        }
Пример #20
0
        private Task <IInteractiveWindowVisualComponent> CreateInteractiveWindow(int id)
        {
            var workflow = _workflowProvider.GetOrCreate();

            return(workflow.GetOrCreateVisualComponentAsync(id));
        }
Пример #21
0
        private async Task SendToRemoteWorkerAsync(IEnumerable <string> files, string projectDir, string projectName, string remotePath, IProgress <ProgressDialogData> progress, CancellationToken ct)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var      workflow = _interactiveWorkflowProvider.GetOrCreate();
            IConsole console  = new InteractiveWindowConsole(workflow);

            try {
                var session = workflow.RSession;
                int count   = 0;
                int total   = files.Count();

                progress.Report(new ProgressDialogData(0, Resources.Info_CompressingFiles));

                if (ct.IsCancellationRequested)
                {
                    return;
                }

                List <string> paths = new List <string>();
                // Compression phase : 1 of 3 phases.
                string compressedFilePath = string.Empty;
                compressedFilePath = _fs.CompressFiles(files, projectDir, new Progress <string>((p) => {
                    Interlocked.Increment(ref count);
                    int step = (count * 100 / total) / 3; // divide by 3, this is for compression phase.
                    progress.Report(new ProgressDialogData(step, Resources.Info_CompressingFile.FormatInvariant(Path.GetFileName(p), _fs.FileSize(p))));
                    string dest = p.MakeRelativePath(projectDir).ProjectRelativePathToRemoteProjectPath(remotePath, projectName);
                    paths.Add($"{Resources.Info_LocalFilePath.FormatInvariant(p)}{Environment.NewLine}{Resources.Info_RemoteFilePath.FormatInvariant(dest)}");
                }), ct);

                if (ct.IsCancellationRequested)
                {
                    return;
                }

                using (var fts = new DataTransferSession(session, _fs)) {
                    long size = _fs.FileSize(compressedFilePath);

                    // Transfer phase: 2 of 3 phases
                    var remoteFile = await fts.SendFileAsync(compressedFilePath, true, new Progress <long>((b) => {
                        int step = 33;                                         // start with 33% to indicate compression phase is done.
                        step += (int)((((double)b / (double)size) * 100) / 3); // divide by 3, this is for transfer phase.
                        progress.Report(new ProgressDialogData(step, Resources.Info_TransferringFilesWithSize.FormatInvariant(b, size)));
                    }), ct);

                    if (ct.IsCancellationRequested)
                    {
                        return;
                    }

                    // Extract phase: 3 of 3 phases
                    // start with 66% completion to indicate compression and transfer phases are done.
                    progress.Report(new ProgressDialogData(66, Resources.Info_ExtractingFilesInRHost));
                    await session.EvaluateAsync <string>($"rtvs:::save_to_project_folder({remoteFile.Id}, {projectName.ToRStringLiteral()}, '{remotePath.ToRPath()}')", REvaluationKind.Normal, ct);

                    progress.Report(new ProgressDialogData(100, Resources.Info_TransferringFilesDone));

                    paths.ForEach((s) => console.WriteLine(s));
                }
            } catch (TaskCanceledException) {
                console.WriteErrorLine(Resources.Info_FileTransferCanceled);
            } catch (RHostDisconnectedException rhdex) {
                console.WriteErrorLine(Resources.Error_CannotTransferNoRSession.FormatInvariant(rhdex.Message));
            } catch (Exception ex) when(ex is UnauthorizedAccessException || ex is IOException)
            {
                _ui.ShowErrorMessage(Resources.Error_CannotTransferFile.FormatInvariant(ex.Message));
            }
        }