コード例 #1
0
ファイル: HelpCommand.cs プロジェクト: GloryChou/roslyn
        private bool ParseArguments(IInteractiveWindow window, string arguments, out string commandName, out IInteractiveWindowCommand command)
        {
            string name = arguments.Split(s_whitespaceChars)[0];

            if (name.Length == 0)
            {
                command = null;
                commandName = null;
                return true;
            }

            var commands = window.GetInteractiveCommands();
            string prefix = commands.CommandPrefix;

            // display help on a particular command:
            command = commands[name];

            if (command == null && name.StartsWith(prefix, StringComparison.Ordinal))
            {
                name = name.Substring(prefix.Length);
                command = commands[name];
            }

            commandName = name;
            return command != null;
        }
コード例 #2
0
        internal Task Execute(IInteractiveWindow interactiveWindow, string title)
        {
            ImmutableArray<string> references, referenceSearchPaths, sourceSearchPaths, namespacesToImport;
            string projectDirectory;

            if (GetProjectProperties(out references, out referenceSearchPaths, out sourceSearchPaths, out namespacesToImport, out projectDirectory))
            {
                // Now, we're going to do a bunch of async operations.  So create a wait
                // indicator so the user knows something is happening, and also so they cancel.
                var waitIndicator = GetWaitIndicator();
                var waitContext = waitIndicator.StartWait(title, InteractiveEditorFeaturesResources.BuildingProject, allowCancel: true);

                var resetInteractiveTask = ResetInteractiveAsync(
                    interactiveWindow,
                    references,
                    referenceSearchPaths,
                    sourceSearchPaths,
                    namespacesToImport,
                    projectDirectory,
                    waitContext);

                // Once we're done resetting, dismiss the wait indicator and focus the REPL window.
                return resetInteractiveTask.SafeContinueWith(
                    _ =>
                    {
                        waitContext.Dispose();
                        ExecutionCompleted?.Invoke(this, new EventArgs());
                    },
                    TaskScheduler.FromCurrentSynchronizationContext());
            }

            return Task.CompletedTask;
        }
コード例 #3
0
        public VsInteractiveWindowCommandFilter(IVsEditorAdaptersFactoryService adapterFactory, IInteractiveWindow window, IVsTextView textViewAdapter, IVsTextBuffer bufferAdapter, IEnumerable<Lazy<IVsInteractiveWindowOleCommandTargetProvider, ContentTypeMetadata>> oleCommandTargetProviders, IContentTypeRegistryService contentTypeRegistry)
        {
            _window = window;
            _oleCommandTargetProviders = oleCommandTargetProviders;
            _contentTypeRegistry = contentTypeRegistry;

            this.textViewAdapter = textViewAdapter;

            // make us a code window so we'll have the same colors as a normal code window.
            IVsTextEditorPropertyContainer propContainer;
            ErrorHandler.ThrowOnFailure(((IVsTextEditorPropertyCategoryContainer)textViewAdapter).GetPropertyCategory(Microsoft.VisualStudio.Editor.DefGuidList.guidEditPropCategoryViewMasterSettings, out propContainer));
            propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewComposite_AllCodeWindowDefaults, true);
            propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGlobalOpt_AutoScrollCaretOnTextEntry, true);

            // editor services are initialized in textViewAdapter.Initialize - hook underneath them:
            _preEditorCommandFilter = new CommandFilter(this, CommandFilterLayer.PreEditor);
            ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preEditorCommandFilter, out _editorCommandFilter));

            textViewAdapter.Initialize(
                (IVsTextLines)bufferAdapter,
                IntPtr.Zero,
                (uint)TextViewInitFlags.VIF_HSCROLL | (uint)TextViewInitFlags.VIF_VSCROLL | (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
                new[] { new INITVIEW { fSelectionMargin = 0, fWidgetMargin = 0, fVirtualSpace = 0, fDragDropMove = 1 } });

            // disable change tracking because everything will be changed
            var textViewHost = adapterFactory.GetWpfTextViewHost(textViewAdapter);

            _preLanguageCommandFilter = new CommandFilter(this, CommandFilterLayer.PreLanguage);
            ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preLanguageCommandFilter, out _editorServicesCommandFilter));

            _textViewHost = textViewHost;
        }
コード例 #4
0
ファイル: LoadCommand.cs プロジェクト: ninjeff/roslyn
        public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments)
        {
            var engine = window.Evaluator as InteractiveEvaluator;
            if (engine != null)
            {
                int i = 0;
                string path;

                if (!CommandArgumentsParser.ParsePath(arguments, ref i, out path) || path == null)
                {
                    ReportInvalidArguments(window);
                    return ExecutionResult.Failed;
                }

                if (!CommandArgumentsParser.ParseTrailingTrivia(arguments, ref i))
                {
                    window.ErrorOutputWriter.WriteLine(string.Format(EditorFeaturesResources.UnexpectedText, arguments.Substring(i)));
                    return ExecutionResult.Failed;
                }

                return engine.LoadCommandAsync(path);
            }

            return ExecutionResult.Failed;
        }
コード例 #5
0
 public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) {
     var eval = window.GetPythonDebugReplEvaluator();
     if (eval != null) {
         eval.DisplayProcesses();
     }
     return ExecutionResult.Succeeded;
 }
コード例 #6
0
 public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) {
     var eval = window.Evaluator as PythonDebugReplEvaluator;
     if (eval != null) {
         eval.StepInto();
     }
     return ExecutionResult.Succeeded;
 }
コード例 #7
0
        public Task<ExecutionResult> Execute(IReplWindow window, string arguments)
        {
            var eval = window.Evaluator as JReplEvaluator;
            if (eval != null) {
                if (eval.AttachEnabled) {
                    string error = eval.AttachDebugger();
                    if (error != null) {
                        window.WriteError("Failed to attach: " + error);
                    }
                } else {
                    window.WriteError(
            "Attaching to an interactive window requires enabling attach " +
            "support in Tools->Options->J Tools->Interactive Windows." +
            Environment.NewLine + Environment.NewLine +
            "This will cause the debugger to track necessary state to enable " +
            "debugging until the attach is requested.  Once enabled the " +
            "interactive window will need to be reset for the change to take " +
            "effect.");
                }
            } else {
                window.WriteError("attach only supports J interactive windows");
            }

            return ExecutionResult.Succeeded;
        }
コード例 #8
0
        IWpfTextView IInteractiveWindowEditorFactoryService.CreateTextView(IInteractiveWindow window, ITextBuffer buffer, ITextViewRoleSet roles)
        {
            WpfTestCase.RequireWpfFact($"Creates an IWpfTextView in {nameof(InteractiveWindowEditorsFactoryService)}");

            var textView = _textEditorFactoryService.CreateTextView(buffer, roles);
            return _textEditorFactoryService.CreateTextViewHost(textView, false).TextView;
        }
コード例 #9
0
        public void Initialize()
        {
            // We have to show the window at least once to ensure the interactive service is loaded.
            ShowWindow(waitForPrompt: false);
            CloseWindow();

            _interactiveWindow = AcquireInteractiveWindow();
        }
コード例 #10
0
ファイル: SwitchModuleCommand.cs プロジェクト: borota/JTVS
 public Task<ExecutionResult> Execute(IReplWindow window, string arguments)
 {
     var remoteEval = window.Evaluator as IMultipleScopeEvaluator;
     if (remoteEval != null) {
         remoteEval.SetScope(arguments);
     }
     return ExecutionResult.Succeeded;
 }
コード例 #11
0
ファイル: SwitchModuleCommand.cs プロジェクト: jsschultz/PTVS
 public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) {
     var remoteEval = window.Evaluator as IMultipleScopeEvaluator;
     Debug.Assert(remoteEval != null, "Evaluator does not support switching scope");
     if (remoteEval != null) {
         remoteEval.SetScope(arguments);
     }
     return ExecutionResult.Succeeded;
 }
コード例 #12
0
 public Task<ExecutionResult> Execute(IReplWindow window, string arguments)
 {
     var eval = window.Evaluator as JDebugReplEvaluator;
     if (eval != null) {
         eval.DisplayProcesses();
     }
     return ExecutionResult.Succeeded;
 }
        ITextBuffer IInteractiveWindowEditorFactoryService.CreateAndActivateBuffer(IInteractiveWindow window) {
            IContentType contentType;
            if (!window.Properties.TryGetProperty(typeof(IContentType), out contentType)) {
                contentType = _contentTypeRegistry.GetContentType(ContentType);
            }

            return _textBufferFactoryService.CreateTextBuffer(contentType);
        }
コード例 #14
0
 public IWpfTextViewHost GetTextViewHost(IInteractiveWindow window)
 {
     var cmdFilter = GetCommandFilter(window);
     if (cmdFilter != null)
     {
         return cmdFilter.TextViewHost;
     }
     return null;
 }
コード例 #15
0
        public RInteractiveWindowVisualComponent(IInteractiveWindow interactiveWindow, IVisualComponentContainer<IInteractiveWindowVisualComponent> container) {
            InteractiveWindow = interactiveWindow;
            Container = container;

            var textView = interactiveWindow.TextView;
            Controller = ServiceManagerBase.GetService<ICommandTarget>(textView);
            Control = textView.VisualElement;
            interactiveWindow.Properties.AddProperty(typeof(IInteractiveWindowVisualComponent), this);
        }
コード例 #16
0
 public TestInteractiveCommandHandler(
     IInteractiveWindow interactiveWindow,
     IContentTypeRegistryService contentTypeRegistryService,
     IEditorOptionsFactoryService editorOptionsFactoryService,
     IEditorOperationsFactoryService editorOperationsFactoryService)
     : base(contentTypeRegistryService, editorOptionsFactoryService, editorOperationsFactoryService)
 {
     _interactiveWindow = interactiveWindow;
 }
コード例 #17
0
 public MockInteractiveWindowCommands(
     IInteractiveWindow window,
     string prefix,
     IEnumerable<IInteractiveWindowCommand> commands
 ) {
     CommandPrefix = prefix;
     _window = window;
     _commands = commands.ToList();
 }
コード例 #18
0
ファイル: EchoReplCommand.cs プロジェクト: borota/JTVS
 public Task<ExecutionResult> Execute(IReplWindow window, string arguments)
 {
     arguments = arguments.ToLowerInvariant();
     if (arguments == "on") {
         window.SetOptionValue(ReplOptions.ShowOutput, true);
     } else {
         window.SetOptionValue(ReplOptions.ShowOutput, false);
     }
     return ExecutionResult.Succeeded;
 }
コード例 #19
0
ファイル: RSessionCallback.cs プロジェクト: Microsoft/RTVS
        public RSessionCallback(IInteractiveWindow interactiveWindow, IRSession session, IRSettings settings, ICoreShell coreShell, IFileSystem fileSystem) {
            _interactiveWindow = interactiveWindow;
            _session = session;
            _settings = settings;
            _coreShell = coreShell;
            _fileSystem = fileSystem;

            var workflowProvider = _coreShell.ExportProvider.GetExportedValue<IRInteractiveWorkflowProvider>();
            _workflow = workflowProvider.GetOrCreate();
        }
コード例 #20
0
ファイル: ResetInteractive.cs プロジェクト: Rickinio/roslyn
        private async Task ResetInteractiveAsync(
            IInteractiveWindow interactiveWindow,
            ImmutableArray<string> referencePaths,
            ImmutableArray<string> referenceSearchPaths,
            ImmutableArray<string> sourceSearchPaths,
            ImmutableArray<string> projectNamespaces,
            string projectDirectory,
            IWaitContext waitContext)
        {
            // First, open the repl window.
            IInteractiveEvaluator evaluator = interactiveWindow.Evaluator;

            // If the user hits the cancel button on the wait indicator, then we want to stop the
            // build.
            using (waitContext.CancellationToken.Register(() =>
                CancelBuildProject(), useSynchronizationContext: true))
            {
                // First, start a build.
                // If the build fails do not reset the REPL.
                var builtSuccessfully = await BuildProject().ConfigureAwait(true);
                if (!builtSuccessfully)
                {
                    return;
                }
            }

            // Then reset the REPL
            waitContext.Message = InteractiveEditorFeaturesResources.Resetting_Interactive;
            await interactiveWindow.Operations.ResetAsync(initialize: true).ConfigureAwait(true);

            // TODO: load context from an rsp file.

            // Now send the reference paths we've collected to the repl.
            // The SetPathsAsync method is not available through an Interface.
            // Execute the method only if the cast to a concrete InteractiveEvaluator succeeds.
            InteractiveEvaluator interactiveEvaluator = evaluator as InteractiveEvaluator;
            if (interactiveEvaluator != null)
            {
                await interactiveEvaluator.SetPathsAsync(referenceSearchPaths, sourceSearchPaths, projectDirectory).ConfigureAwait(true);
            }

            var editorOptions = _editorOptionsFactoryService.GetOptions(interactiveWindow.CurrentLanguageBuffer);
            var importReferencesCommand = referencePaths.Select(_createReference);
            await interactiveWindow.SubmitAsync(importReferencesCommand).ConfigureAwait(true);

            // Project's default namespace might be different from namespace used within project.
            // Filter out namespace imports that do not exist in interactive compilation.
            IEnumerable<string> namespacesToImport = await GetNamespacesToImportAsync(projectNamespaces, interactiveWindow).ConfigureAwait(true);
            var importNamespacesCommand = namespacesToImport.Select(_createImport).Join(editorOptions.GetNewLineCharacter());

            if (!string.IsNullOrWhiteSpace(importNamespacesCommand))
            {
                await interactiveWindow.SubmitAsync(new[] { importNamespacesCommand }).ConfigureAwait(true);
            }
        }
コード例 #21
0
        public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments)
        {
            bool initialize;
            if (!TryParseArguments(arguments, out initialize))
            {
                ReportInvalidArguments(window);
                return ExecutionResult.Failed;
            }

            return window.Operations.ResetAsync(initialize);
        }
コード例 #22
0
 public TestInteractiveCommandHandler(
     IInteractiveWindow interactiveWindow,
     IContentTypeRegistryService contentTypeRegistryService,
     IEditorOptionsFactoryService editorOptionsFactoryService,
     IEditorOperationsFactoryService editorOperationsFactoryService,
     IWaitIndicator waitIndicator)
     : base(contentTypeRegistryService, editorOptionsFactoryService, editorOperationsFactoryService, waitIndicator)
 {
     _interactiveWindow = interactiveWindow;
     _sendToInteractiveSubmissionProvider = new CSharpSendToInteractiveSubmissionProvider();
 }
コード例 #23
0
ファイル: ResetCommand.cs プロジェクト: REALTOBIZ/roslyn
        public override Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments)
        {
            int noConfigStart, noConfigEnd;
            if (!TryParseArguments(arguments, out noConfigStart, out noConfigEnd))
            {
                ReportInvalidArguments(window);
                return ExecutionResult.Failed;
            }

            return ((InteractiveWindow)window).ResetAsync(initialize: noConfigStart > -1);
        }
コード例 #24
0
 public IInteractiveWindowCommands CreateInteractiveCommands(
     IInteractiveWindow window,
     string prefix,
     IEnumerable<IInteractiveWindowCommand> commands
 ) {
     return window.Properties.GetOrCreateSingletonProperty(() => new MockInteractiveWindowCommands(
         window,
         prefix,
         commands
     ));
 }
コード例 #25
0
        internal InteractiveWindowTestHost()
        {
            _exportProvider = new CompositionContainer(
                s_lazyCatalog.Value,
                CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);

            var contentTypeRegistryService = _exportProvider.GetExport<IContentTypeRegistryService>().Value;
            Evaluator = new TestInteractiveEvaluator();
            Window = _exportProvider.GetExport<IInteractiveWindowFactoryService>().Value.CreateWindow(Evaluator);
            Window.InitializeAsync().Wait();
        }
コード例 #26
0
        internal InteractiveWindowTestHost(Action<InteractiveWindow.State> stateChangedHandler = null)
        {
            ExportProvider = new CompositionContainer(
                s_lazyCatalog.Value,
                CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);

            var contentTypeRegistryService = ExportProvider.GetExport<IContentTypeRegistryService>().Value;
            Evaluator = new TestInteractiveEngine(contentTypeRegistryService);
            Window = ExportProvider.GetExport<IInteractiveWindowFactoryService>().Value.CreateWindow(Evaluator);
            ((InteractiveWindow)Window).StateChanged += stateChangedHandler;
            Window.InitializeAsync().Wait();
        }
コード例 #27
0
        IWpfTextView IInteractiveWindowEditorFactoryService.CreateTextView(IInteractiveWindow window, ITextBuffer buffer, ITextViewRoleSet roles)
        {
            var bufferAdapter = _adapterFactory.CreateVsTextBufferAdapterForSecondaryBuffer(_provider, buffer);

            // Create and initialize text view adapter.
            // WARNING: This might trigger various services like IntelliSense, margins, taggers, etc.
            var textViewAdapter = _adapterFactory.CreateVsTextViewAdapter(_provider, roles);

            var commandFilter = new VsInteractiveWindowCommandFilter(_adapterFactory, window, textViewAdapter, bufferAdapter, _oleCommandTargetProviders, _contentTypeRegistry);
            window.Properties[typeof(VsInteractiveWindowCommandFilter)] = commandFilter;
            return commandFilter.TextViewHost.TextView;
        }
コード例 #28
0
ファイル: ResetCommand.cs プロジェクト: GloryChou/roslyn
        public override Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments)
        {
            int noConfigStart, noConfigEnd;
            bool? init = ParseArguments(arguments, out noConfigStart, out noConfigEnd);
            if (init == null)
            {
                ReportInvalidArguments(window);
                return ExecutionResult.Failed;
            }

            return ((InteractiveWindow)window).ResetAsync(init.Value);
        }
コード例 #29
0
        internal InteractiveWindowTestHost(Action<InteractiveWindow.State> stateChangedHandler = null)
        {
            SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());

            _exportProvider = new CompositionContainer(
                _lazyCatalog.Value,
                CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);

            var contentTypeRegistryService = _exportProvider.GetExport<IContentTypeRegistryService>().Value;
            _window = _exportProvider.GetExport<IInteractiveWindowFactoryService>().Value.CreateWindow(new TestInteractiveEngine(contentTypeRegistryService));
            ((InteractiveWindow)_window).StateChanged += stateChangedHandler;
            _window.InitializeAsync().PumpingWait();
        }
コード例 #30
0
        public InteractiveWindowTestHost()
        {
            SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());

            var types = new[] { typeof(TestInteractiveEngine), typeof(InteractiveWindow) }.Concat(GetVisualStudioTypes());
            _exportProvider = new CompositionContainer(
                new AggregateCatalog(types.Select(t => new AssemblyCatalog(t.Assembly))),
                CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);

            var contentTypeRegistryService = _exportProvider.GetExport<IContentTypeRegistryService>().Value;
            _window = _exportProvider.GetExport<IInteractiveWindowFactoryService>().Value.CreateWindow(new TestInteractiveEngine(contentTypeRegistryService));

            _window.InitializeAsync().PumpingWait();
        }
コード例 #31
0
        internal Commands(IInteractiveWindow window, string prefix, IEnumerable <IInteractiveWindowCommand> commands, IContentTypeRegistryService contentTypeRegistry = null, IStandardClassificationService classificationRegistry = null)
        {
            CommandPrefix = prefix;
            _window       = window;

            Dictionary <string, IInteractiveWindowCommand> commandsDict = new Dictionary <string, IInteractiveWindowCommand>();

            foreach (var command in commands)
            {
                int length = 0;
                foreach (var name in command.Names)
                {
                    if (commandsDict.ContainsKey(name))
                    {
                        throw new InvalidOperationException(string.Format(InteractiveWindowResources.DuplicateCommand, string.Join(", ", command.Names)));
                    }
                    if (length != 0)
                    {
                        length += _commandSeparator.Length;
                    }
                    length += name.Length;

                    commandsDict[name] = command;
                }
                if (length == 0)
                {
                    throw new InvalidOperationException(string.Format(InteractiveWindowResources.MissingCommandName, command.GetType().Name));
                }
                _maxCommandNameLength = Math.Max(_maxCommandNameLength, length);
            }

            _commands = commandsDict;

            _classificationRegistry = classificationRegistry;

            if (contentTypeRegistry != null)
            {
                _commandContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
            }

            if (window != null)
            {
                window.SubmissionBufferAdded += Window_SubmissionBufferAdded;
                window.Properties[typeof(IInteractiveWindowCommands)] = this;
            }
        }
コード例 #32
0
        ITextBuffer IInteractiveWindowEditorFactoryService.CreateAndActivateBuffer(IInteractiveWindow window, IContentType contentType)
        {
            // create buffer adapter to support undo/redo:
            var bufferAdapter = _adapterFactory.CreateVsTextBufferAdapter(_provider, contentType);

            bufferAdapter.InitializeContent("", 0);

            var commandFilter = GetCommandFilter(window);

            if (commandFilter.currentBufferCommandHandler != null)
            {
                ((IVsPersistDocData)commandFilter.currentBufferCommandHandler).Close();
            }

            commandFilter.currentBufferCommandHandler = (IOleCommandTarget)bufferAdapter;

            return(_adapterFactory.GetDocumentBuffer(bufferAdapter));
        }
コード例 #33
0
        private static void AppendTextWithEscapes(
            IInteractiveWindow window,
            string text,
            bool addNewLine,
            bool isError
            )
        {
            int start = 0, escape = text.IndexOf("\x1b[");
            var colors = window.OutputBuffer.Properties.GetOrCreateSingletonProperty(
                ReplOutputClassifier.ColorKey,
                () => new List <ColoredSpan>()
                );
            ConsoleColor?color = null;

            Span span;
            var  write = isError ? (Func <string, Span>)window.WriteError : window.Write;

            while (escape >= 0)
            {
                span = write(text.Substring(start, escape - start));
                if (span.Length > 0)
                {
                    colors.Add(new ColoredSpan(span, color));
                }

                start  = escape + 2;
                color  = GetColorFromEscape(text, ref start);
                escape = text.IndexOf("\x1b[", start);
            }

            var rest = text.Substring(start);

            if (addNewLine)
            {
                rest += Environment.NewLine;
            }

            span = write(rest);
            if (span.Length > 0)
            {
                colors.Add(new ColoredSpan(span, color));
            }
        }
コード例 #34
0
        private ReplEditFilter(
            IVsTextView vsTextView,
            ITextView textView,
            IEditorOperations editorOps,
            IServiceProvider serviceProvider,
            IOleCommandTarget next
            )
        {
            _vsTextView      = vsTextView;
            _textView        = textView;
            _editorOps       = editorOps;
            _serviceProvider = serviceProvider;
            _componentModel  = _serviceProvider.GetComponentModel();
            _pyService       = _serviceProvider.GetPythonToolsService();
            _interactive     = _textView.TextBuffer.GetInteractiveWindow();
            _next            = next;

            if (_interactive != null)
            {
                _selectEval = _interactive.Evaluator as SelectableReplEvaluator;
            }

            if (_selectEval != null)
            {
                _selectEval.EvaluatorChanged           += EvaluatorChanged;
                _selectEval.AvailableEvaluatorsChanged += AvailableEvaluatorsChanged;
            }

            var mse = _interactive?.Evaluator as IMultipleScopeEvaluator;

            if (mse != null)
            {
                _scopeListVisible                = mse.EnableMultipleScopes;
                mse.AvailableScopesChanged      += AvailableScopesChanged;
                mse.MultipleScopeSupportChanged += MultipleScopeSupportChanged;
            }

            if (_next == null && _interactive != null)
            {
                ErrorHandler.ThrowOnFailure(vsTextView.AddCommandFilter(this, out _next));
            }
        }
コード例 #35
0
        internal InteractiveWindowTestHost(Action <InteractiveWindow.State> stateChangedHandler = null)
        {
            try
            {
                ExportProvider = new CompositionContainer(
                    s_lazyCatalog.Value,
                    CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);

                Evaluator = new TestInteractiveEngine();
                Window    = ExportProvider.GetExport <IInteractiveWindowFactoryService>().Value.CreateWindow(Evaluator);
                ((InteractiveWindow)Window).StateChanged += stateChangedHandler;
                Window.InitializeAsync().Wait();
            }
            catch (ReflectionTypeLoadException e)
            {
                Assert.False(true,
                             e.Message +
                             "LoaderExceptions: " +
                             Environment.NewLine +
                             string.Join(Environment.NewLine, e.LoaderExceptions.Select(l => l.Message)));
            }
        }
コード例 #36
0
ファイル: KeyProcessor.cs プロジェクト: skrutsick/RTVS
        public override void PreviewKeyDown(KeyEventArgs args)
        {
            if (_interactiveWindow == null)
            {
                _interactiveWindow = _textView.TextBuffer.GetInteractiveWindow();
                if (_interactiveWindow == null)
                {
                    return;
                }
            }

            var tb = _interactiveWindow.CurrentLanguageBuffer;

            if (tb == null || !tb.ContentType.IsOfType(RContentTypeDefinition.ContentType))
            {
                return;
            }

            var vk = KeyInterop.VirtualKeyFromKey(args.Key);

            // VK_0 to VK_Z, VK_OEM*
            if ((vk >= 0x30 && vk <= 0x5A) || (vk >= 0xBA && vk <= 0xC0) || (vk >= 0xDB && vk <= 0xDF))
            {
                var spans = _textView.TextBuffer.GetReadOnlyExtents(new Text.Span(0, _textView.TextBuffer.CurrentSnapshot.Length));
                var caret = _textView.Caret.Position.BufferPosition;
                var span  = spans.FirstOrDefault(s => s.Contains(caret.Position));
                if (span != default(Span))
                {
                    try {
                        var viewPoint = _textView.BufferGraph.MapUpToBuffer(new SnapshotPoint(tb.CurrentSnapshot, tb.CurrentSnapshot.Length), PointTrackingMode.Positive, PositionAffinity.Predecessor, _textView.TextBuffer);
                        if (viewPoint.HasValue)
                        {
                            _textView.Caret.MoveTo(viewPoint.Value);
                        }
                    } catch (ArgumentException) { }
                }
                base.PreviewKeyDown(args);
            }
        }
コード例 #37
0
        public void Show(IInteractiveWindow theWindow, DockingState state)
        {
            DockContent dockableWindow = theWindow as DockContent;

            if (dockableWindow != null)
            {
                DockState dockState = DockState.Document;
                if (state == DockingState.DockRight)
                {
                    dockState = DockState.DockRight;
                }
                else if (state == DockingState.Float)
                {
                    dockState = DockState.Float;
                }

                this.dockPanel.Invoke((MethodInvoker) delegate
                {
                    dockableWindow.Show(this.dockPanel, dockState);
                });
            }
        }
コード例 #38
0
        internal Commands(IInteractiveWindow window, string prefix, IEnumerable <IInteractiveWindowCommand> commands, IContentTypeRegistryService contentTypeRegistry = null, IStandardClassificationService classificationRegistry = null)
        {
            CommandPrefix = prefix;
            this.window   = window;

            Dictionary <string, IInteractiveWindowCommand> commandsDict = new Dictionary <string, IInteractiveWindowCommand>();

            foreach (var command in commands)
            {
                if (command.Name == null)
                {
                    continue;
                }

                if (commandsDict.ContainsKey(command.Name))
                {
                    throw new InvalidOperationException(string.Format(InteractiveWindowResources.DuplicateCommand, command.Name));
                }

                commandsDict[command.Name] = command;
            }

            this.commands = commandsDict;

            this.maxCommandNameLength = (this.commands.Count > 0) ? this.commands.Values.Select(command => command.Name.Length).Max() : 0;

            this.classificationRegistry = classificationRegistry;
            if (contentTypeRegistry != null)
            {
                this.commandContentType = contentTypeRegistry.GetContentType(InteractiveContentTypeNames.InteractiveCommandContentType);
            }

            if (window != null)
            {
                window.SubmissionBufferAdded += Window_SubmissionBufferAdded;
                window.Properties[typeof(IInteractiveWindowCommands)] = this;
            }
        }
コード例 #39
0
        public void SetLanguage(IInteractiveWindow window, Guid languageServiceGuid)
        {
            // REVIEW: What happens to the current input buffer here?
            // REVIEW: What happens when the window is already initialized?
            GetDispatcher(window).CheckAccess();

            var commandFilter = GetCommandFilter(window);

            commandFilter.firstLanguageServiceCommandFilter = null;
            var provider = _oleCommandTargetProviders.OfContentType(window.Evaluator.ContentType, _contentTypeRegistry);

            if (provider != null)
            {
                var targetFilter = commandFilter.firstLanguageServiceCommandFilter ?? GetCommandFilter(window).EditorServicesCommandFilter;
                var target       = provider.GetCommandTarget(window.TextView, targetFilter);
                if (target != null)
                {
                    commandFilter.firstLanguageServiceCommandFilter = target;
                }
            }

            SetEditorOptions(window.TextView.Options, languageServiceGuid);
        }
コード例 #40
0
        public bool SupportsCodeFixes(Document document)
        {
            SourceText sourceText;

            if (document.TryGetText(out sourceText))
            {
                ITextBuffer buffer = sourceText.Container.TryGetTextBuffer();
                if (buffer != null)
                {
                    IInteractiveEvaluator evaluator = (IInteractiveEvaluator)buffer.Properties[typeof(IInteractiveEvaluator)];
                    IInteractiveWindow    window    = evaluator?.CurrentWindow;
                    if (window?.CurrentLanguageBuffer == buffer)
                    {
                        // These are only correct if we're on the UI thread.
                        // Otherwise, they're guesses and they might change immediately even if they're correct.
                        // If we return true and the buffer later becomes readonly, it appears that the
                        // the code fix simply has no effect.
                        return(!window.IsResetting && !window.IsRunning);
                    }
                }
            }

            return(false);
        }
コード例 #41
0
        protected void ReportInvalidArguments(IInteractiveWindow window)
        {
            var commands = (IInteractiveWindowCommands)window.Properties[typeof(IInteractiveWindowCommands)];

            commands.DisplayCommandUsage(this, window.ErrorOutputWriter, displayDetails: false);
        }
コード例 #42
0
 public abstract Task <ExecutionResult> Execute(IInteractiveWindow window, string arguments);
コード例 #43
0
 public void Dispose()
 {
     _evaluator?.Dispose();
     _evaluator = null;
     _window    = null;
 }
コード例 #44
0
 private InteractiveWindowWrapper(IInteractiveWindow interactiveWindow)
 {
     _interactiveWindow = interactiveWindow;
 }
コード例 #45
0
        private static async Task PasteReplCode(
            IInteractiveWindow window,
            string pasting,
            PythonLanguageVersion version
            )
        {
            // there's some text in the buffer...
            var view  = window.TextView;
            var caret = view.Caret;

            if (view.Selection.IsActive && !view.Selection.IsEmpty)
            {
                foreach (var span in view.Selection.SelectedSpans)
                {
                    foreach (var normalizedSpan in view.BufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeInclusive, window.CurrentLanguageBuffer))
                    {
                        normalizedSpan.Snapshot.TextBuffer.Delete(normalizedSpan);
                    }
                }
            }

            var curBuffer  = window.CurrentLanguageBuffer;
            var inputPoint = view.BufferGraph.MapDownToBuffer(
                caret.Position.BufferPosition,
                PointTrackingMode.Positive,
                curBuffer,
                PositionAffinity.Successor
                );


            // if we didn't find a location then see if we're in a prompt, and if so, then we want
            // to insert after the prompt.
            if (caret.Position.BufferPosition != window.TextView.TextBuffer.CurrentSnapshot.Length)
            {
                for (int i = caret.Position.BufferPosition + 1;
                     inputPoint == null && i <= window.TextView.TextBuffer.CurrentSnapshot.Length;
                     i++)
                {
                    inputPoint = view.BufferGraph.MapDownToBuffer(
                        new SnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, i),
                        PointTrackingMode.Positive,
                        curBuffer,
                        PositionAffinity.Successor
                        );
                }
            }

            if (inputPoint == null)
            {
                // we didn't find a point to insert, insert at the beginning.
                inputPoint = new SnapshotPoint(curBuffer.CurrentSnapshot, 0);
            }

            // we want to insert the pasted code at the caret, but we also want to
            // respect the stepping.  So first grab the code before and after the caret.
            string startText = curBuffer.CurrentSnapshot.GetText(0, inputPoint.Value);

            string endText = curBuffer.CurrentSnapshot.GetText(
                inputPoint.Value,
                curBuffer.CurrentSnapshot.Length - inputPoint.Value);


            var splitCode = JoinToCompleteStatements(SplitAndDedent(startText + pasting + endText), version).ToList();

            curBuffer.Delete(new Span(0, curBuffer.CurrentSnapshot.Length));

            bool supportMultiple = await window.GetSupportsMultipleStatements();

            if (supportMultiple)
            {
                await window.SubmitAsync(new[] { string.Join(Environment.NewLine, splitCode) });
            }
            else if (splitCode.Count == 1)
            {
                curBuffer.Insert(0, splitCode[0]);
                var viewPoint = view.BufferGraph.MapUpToBuffer(
                    new SnapshotPoint(curBuffer.CurrentSnapshot, Math.Min(inputPoint.Value.Position + pasting.Length, curBuffer.CurrentSnapshot.Length)),
                    PointTrackingMode.Positive,
                    PositionAffinity.Successor,
                    view.TextBuffer
                    );

                if (viewPoint != null)
                {
                    view.Caret.MoveTo(viewPoint.Value);
                }
            }
            else if (splitCode.Count != 0)
            {
                var lastCode = splitCode[splitCode.Count - 1];
                splitCode.RemoveAt(splitCode.Count - 1);

                while (splitCode.Any())
                {
                    var code = splitCode[0];
                    splitCode.RemoveAt(0);
                    await window.SubmitAsync(new[] { code });

                    supportMultiple = await window.GetSupportsMultipleStatements();

                    if (supportMultiple)
                    {
                        // Might have changed while we were executing
                        break;
                    }
                }

                if (supportMultiple)
                {
                    // Submit all remaning lines of code
                    await window.SubmitAsync(new[] { string.Join(Environment.NewLine, splitCode) });
                }
                else
                {
                    window.CurrentLanguageBuffer.Insert(0, lastCode);
                }
            }
            else
            {
                window.CurrentLanguageBuffer.Insert(0, startText + pasting + endText);
            }
        }
コード例 #46
0
        internal static IVsInteractiveWindow GetVsInteractiveWindow(IInteractiveWindow window)
        {
            IVsInteractiveWindow wnd = null;

            return((window?.Properties.TryGetProperty(VsInteractiveWindowKey, out wnd) ?? false) ? wnd : null);
        }
コード例 #47
0
ファイル: MockReplWindow.cs プロジェクト: yepeiwen/PTVS
 public static Task <ExecutionResult> _Initialize(this IInteractiveEvaluator self, IInteractiveWindow window)
 {
     self.CurrentWindow = window;
     return(self.InitializeAsync());
 }
コード例 #48
0
 public InteractiveWindowHistoryTests()
 {
     _testHost = new InteractiveWindowTestHost();
     _window = _testHost.Window;
     _operations = _window.Operations;
 }
コード例 #49
0
 private void FlushOutput(IInteractiveWindow window)
 {
     // Give interactive window writer time to process message queue
     UIThreadHelper.Instance.DoEvents(400);
     window.FlushOutput();
 }
コード例 #50
0
        public Task <ExecutionResult> Execute(IInteractiveWindow window, string arguments)
        {
            var finder = new FileFinder(arguments);

            var eval = window.GetPythonEvaluator();

            if (eval != null)
            {
                finder.Search(eval.Configuration.WorkingDirectory);
                foreach (var p in eval.Configuration.SearchPaths)
                {
                    finder.Search(p);
                }
            }

            finder.ThrowIfNotFound();
            string commandPrefix = "$";
            string lineBreak     = window.TextView.Options.GetNewLineCharacter();

            IEnumerable <string> lines = File.ReadLines(finder.Filename);
            IEnumerable <string> submissions;

            if (eval != null)
            {
                submissions = ReplEditFilter.JoinToCompleteStatements(lines, eval.LanguageVersion).Where(CommentPrefixPredicate);
            }
            else
            {
                // v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
                // and using this class it would be hit.
                var submissionList    = new List <string>();
                var currentSubmission = new List <string>();

                foreach (var line in lines)
                {
                    if (line.StartsWith(_commentPrefix))
                    {
                        continue;
                    }

                    if (line.StartsWith(commandPrefix))
                    {
                        AddSubmission(submissionList, currentSubmission, lineBreak);

                        submissionList.Add(line);
                        currentSubmission.Clear();
                    }
                    else
                    {
                        currentSubmission.Add(line);
                    }
                }

                AddSubmission(submissionList, currentSubmission, lineBreak);

                submissions = submissionList;
            }

            window.SubmitAsync(submissions);
            return(ExecutionResult.Succeeded);
        }
コード例 #51
0
        internal static int GetVsInteractiveWindowId(IInteractiveWindow window)
        {
            int id = -1;

            return((window?.Properties.TryGetProperty(VsInteractiveWindowId, out id) ?? false) ? id : -1);
        }
コード例 #52
0
 public VsInteractiveWindowCommandFilter GetCommandFilter(IInteractiveWindow window)
 {
     return((VsInteractiveWindowCommandFilter)window.Properties[typeof(VsInteractiveWindowCommandFilter)]);
 }
コード例 #53
0
 protected abstract Task <IEnumerable <string> > GetNamespacesToImportAsync(IEnumerable <string> namespacesToImport, IInteractiveWindow interactiveWindow);
コード例 #54
0
 protected override Task <IEnumerable <string> > GetNamespacesToImportAsync(IEnumerable <string> namespacesToImport, IInteractiveWindow interactiveWindow)
 {
     return(Task.FromResult((IEnumerable <string>)NamespacesToImport));
 }
コード例 #55
0
        public VsInteractiveWindowCommandFilter(IVsEditorAdaptersFactoryService adapterFactory, IInteractiveWindow window, IVsTextView textViewAdapter, IVsTextBuffer bufferAdapter)
        {
            _window = window;
            this.textViewAdapter = textViewAdapter;

            // make us a code window so we'll have the same colors as a normal code window.
            IVsTextEditorPropertyContainer propContainer;

            ErrorHandler.ThrowOnFailure(((IVsTextEditorPropertyCategoryContainer)textViewAdapter).GetPropertyCategory(Microsoft.VisualStudio.Editor.DefGuidList.guidEditPropCategoryViewMasterSettings, out propContainer));
            propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewComposite_AllCodeWindowDefaults, true);
            propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGlobalOpt_AutoScrollCaretOnTextEntry, true);

            // editor services are initialized in textViewAdapter.Initialize - hook underneath them:
            _preEditorCommandFilter = new CommandFilter(this, CommandFilterLayer.PreEditor);
            ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preEditorCommandFilter, out _editorCommandFilter));

            textViewAdapter.Initialize(
                (IVsTextLines)bufferAdapter,
                IntPtr.Zero,
                (uint)TextViewInitFlags.VIF_HSCROLL | (uint)TextViewInitFlags.VIF_VSCROLL | (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
                new[] { new INITVIEW {
                            fSelectionMargin = 0, fWidgetMargin = 0, fVirtualSpace = 0, fDragDropMove = 1
                        } });

            // disable change tracking because everything will be changed
            var textViewHost = adapterFactory.GetWpfTextViewHost(textViewAdapter);

            _preLanguageCommandFilter = new CommandFilter(this, CommandFilterLayer.PreLanguage);
            ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preLanguageCommandFilter, out _editorServicesCommandFilter));

            _textViewHost = textViewHost;
        }
コード例 #56
0
 internal InteractiveWindowWriter(IInteractiveWindow window, SortedSpans spans)
 {
     Debug.Assert(window != null);
     this.window = window;
     this.spans  = spans;
 }
コード例 #57
0
 public override Task <ExecutionResult> Execute(IInteractiveWindow window, string arguments)
 {
     window.Operations.ClearView();
     return(ExecutionResult.Succeeded);
 }
コード例 #58
0
 private Dispatcher GetDispatcher(IInteractiveWindow window)
 {
     return(((FrameworkElement)window.TextView).Dispatcher);
 }
コード例 #59
0
 public IInteractiveWindowCommands CreateInteractiveCommands(IInteractiveWindow window, string prefix, IEnumerable <IInteractiveWindowCommand> commands)
 {
     return(new Commands(window, prefix, commands.ToArray(), _contentTypeRegistry, _standardClassification));
 }
コード例 #60
0
ファイル: VsResetInteractive.cs プロジェクト: y87feng/roslyn
        protected override async Task <IEnumerable <string> > GetNamespacesToImportAsync(IEnumerable <string> namespacesToImport, IInteractiveWindow interactiveWindow)
        {
            var document    = interactiveWindow.CurrentLanguageBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
            var compilation = await document.Project.GetCompilationAsync().ConfigureAwait(true);

            return(namespacesToImport.Where(ns => compilation.GlobalNamespace.GetQualifiedNamespace(ns) != null));
        }