VsInteractiveWindowCommandFilter.cs 19.0 KB
Newer Older
1 2 3 4 5
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

// Dumps commands in QueryStatus and Exec.
// #define DUMP_COMMANDS

D
dino 已提交
6 7
using System;
using System.Collections.Generic;
8 9 10 11 12
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
D
dino 已提交
13
using Microsoft.VisualStudio.Utilities;
14

15
namespace Microsoft.VisualStudio.InteractiveWindow.Shell
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
{
    internal sealed class VsInteractiveWindowCommandFilter : IOleCommandTarget
    {
        //
        // Command filter chain: 
        // *window* -> VsTextView -> ... -> *pre-language + the current language service's filter* -> editor services -> *preEditor* -> editor
        //
        private IOleCommandTarget _preLanguageCommandFilter;
        private IOleCommandTarget _editorServicesCommandFilter;
        private IOleCommandTarget _preEditorCommandFilter;
        private IOleCommandTarget _editorCommandFilter;
        // we route undo/redo commands to this target:
        internal IOleCommandTarget currentBufferCommandHandler;
        internal IOleCommandTarget firstLanguageServiceCommandFilter;
        private readonly IInteractiveWindow _window;
        internal readonly IVsTextView textViewAdapter;
        private readonly IWpfTextViewHost _textViewHost;
D
dino 已提交
33 34
        internal readonly IEnumerable<Lazy<IVsInteractiveWindowOleCommandTargetProvider, ContentTypeMetadata>> _oleCommandTargetProviders;
        internal readonly IContentTypeRegistryService _contentTypeRegistry;
35

D
dino 已提交
36
        public VsInteractiveWindowCommandFilter(IVsEditorAdaptersFactoryService adapterFactory, IInteractiveWindow window, IVsTextView textViewAdapter, IVsTextBuffer bufferAdapter, IEnumerable<Lazy<IVsInteractiveWindowOleCommandTargetProvider, ContentTypeMetadata>> oleCommandTargetProviders, IContentTypeRegistryService contentTypeRegistry)
37 38
        {
            _window = window;
D
dino 已提交
39 40
            _oleCommandTargetProviders = oleCommandTargetProviders;
            _contentTypeRegistry = contentTypeRegistry;
J
Jared Parsons 已提交
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
            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;
        }

        private IOleCommandTarget TextViewCommandFilterChain
        {
            get
            {
                // Non-character command processing starts with WindowFrame which calls ReplWindow.Exec.
                // We need to invoke the view's Exec method in order to invoke its full command chain 
                // (features add their filters to the view).
                return (IOleCommandTarget)textViewAdapter;
            }
        }

        #region IOleCommandTarget

        public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
            var nextTarget = TextViewCommandFilterChain;

            return nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
        }

        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var nextTarget = TextViewCommandFilterChain;

            return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
        }

        #endregion

        public IWpfTextViewHost TextViewHost
        {
            get
            {
                return _textViewHost;
            }
        }

        private enum CommandFilterLayer
        {
            PreLanguage,
            PreEditor
        }

        private sealed class CommandFilter : IOleCommandTarget
        {
            private readonly VsInteractiveWindowCommandFilter _window;
            private readonly CommandFilterLayer _layer;

            public CommandFilter(VsInteractiveWindowCommandFilter window, CommandFilterLayer layer)
            {
                _window = window;
                _layer = layer;
            }

            public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
            {
                switch (_layer)
                {
                    case CommandFilterLayer.PreLanguage:
                        return _window.PreLanguageCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);

                    case CommandFilterLayer.PreEditor:
                        return _window.PreEditorCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
                }

                throw new InvalidOperationException();
            }

            public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
            {
                switch (_layer)
                {
                    case CommandFilterLayer.PreLanguage:
                        return _window.PreLanguageCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

                    case CommandFilterLayer.PreEditor:
                        return _window.PreEditorCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                }

                throw new InvalidOperationException();
            }
        }

        private int PreEditorCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
154 155 156 157 158 159 160 161 162 163 164
            if (pguidCmdGroup == Guids.InteractiveCommandSetId)
            {
                switch ((CommandIds)prgCmds[0].cmdID)
                {
                    case CommandIds.BreakLine:
                        prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled;
                        prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
                        return VSConstants.S_OK;
                }
            }

165 166 167 168 169 170 171 172 173 174 175 176
            return _editorCommandFilter.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
        }

        private int PreEditorCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var nextTarget = _editorCommandFilter;

            if (pguidCmdGroup == Guids.InteractiveCommandSetId)
            {
                switch ((CommandIds)nCmdID)
                {
                    case CommandIds.BreakLine:
177
                        if (_window.Operations.BreakLine())
178 179 180 181 182 183 184 185 186 187 188
                        {
                            return VSConstants.S_OK;
                        }
                        break;
                }
            }
            else if (pguidCmdGroup == VSConstants.VSStd2K)
            {
                switch ((VSConstants.VSStd2KCmdID)nCmdID)
                {
                    case VSConstants.VSStd2KCmdID.RETURN:
189
                        if (_window.Operations.Return())
190 191 192 193 194 195 196 197 198 199 200
                        {
                            return VSConstants.S_OK;
                        }
                        break;

                    // TODO: 
                    //case VSConstants.VSStd2KCmdID.DELETEWORDLEFT:
                    //case VSConstants.VSStd2KCmdID.DELETEWORDRIGHT:
                    //    break;

                    case VSConstants.VSStd2KCmdID.BACKSPACE:
201
                        if (_window.Operations.Backspace())
202 203 204 205 206 207 208 209 210 211
                        {
                            return VSConstants.S_OK;
                        }
                        break;


                    case VSConstants.VSStd2KCmdID.UP:

                        if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown)
                        {
212
                            _window.Operations.HistoryPrevious();
213 214 215 216 217 218 219
                            return VSConstants.S_OK;
                        }
                        break;

                    case VSConstants.VSStd2KCmdID.DOWN:
                        if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown)
                        {
220
                            _window.Operations.HistoryNext();
221 222 223 224 225 226 227
                            return VSConstants.S_OK;
                        }
                        break;

                    case VSConstants.VSStd2KCmdID.CANCEL:
                        if (_window.TextView.Selection.IsEmpty)
                        {
228
                            _window.Operations.Cancel();
229 230 231 232
                        }
                        break;

                    case VSConstants.VSStd2KCmdID.BOL:
233
                        _window.Operations.Home(false);
234 235 236
                        return VSConstants.S_OK;

                    case VSConstants.VSStd2KCmdID.BOL_EXT:
237
                        _window.Operations.Home(true);
238 239 240
                        return VSConstants.S_OK;

                    case VSConstants.VSStd2KCmdID.EOL:
241
                        _window.Operations.End(false);
242 243 244
                        return VSConstants.S_OK;

                    case VSConstants.VSStd2KCmdID.EOL_EXT:
245
                        _window.Operations.End(true);
246 247 248 249 250 251 252 253 254
                        return VSConstants.S_OK;
                }
            }
            else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
            {
                // undo/redo support:
                switch ((VSConstants.VSStd97CmdID)nCmdID)
                {
                    case VSConstants.VSStd97CmdID.Paste:
255
                        _window.Operations.Paste();
256 257 258
                        return VSConstants.S_OK;

                    case VSConstants.VSStd97CmdID.Cut:
259
                        _window.Operations.Cut();
260 261 262
                        return VSConstants.S_OK;

                    case VSConstants.VSStd97CmdID.Delete:
263
                        if (_window.Operations.Delete())
264 265 266 267 268 269
                        {
                            return VSConstants.S_OK;
                        }
                        break;

                    case VSConstants.VSStd97CmdID.SelectAll:
270
                        _window.Operations.SelectAll();
271 272 273 274 275 276 277 278 279
                        return VSConstants.S_OK;
                }
            }

            return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
        }

        private int PreLanguageCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
D
dino 已提交
280
            var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter;
281 282 283 284 285 286 287 288 289

            if (pguidCmdGroup == Guids.InteractiveCommandSetId)
            {
                switch ((CommandIds)prgCmds[0].cmdID)
                {
                    case CommandIds.HistoryNext:
                    case CommandIds.HistoryPrevious:
                    case CommandIds.SearchHistoryNext:
                    case CommandIds.SearchHistoryPrevious:
J
Jared Parsons 已提交
290
                    case CommandIds.SmartExecute:
291 292
                        // TODO: Submit?
                        prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled;
D
dino 已提交
293 294
                        prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
                        return VSConstants.S_OK;
295 296
                    case CommandIds.AbortExecution:
                        prgCmds[0].cmdf = _window.IsRunning ? CommandEnabled : CommandDisabled;
D
dino 已提交
297 298
                        prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
                        return VSConstants.S_OK;
299 300
                    case CommandIds.Reset:
                        prgCmds[0].cmdf = !_window.IsResetting ? CommandEnabled : CommandDisabled;
D
dino 已提交
301 302
                        prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
                        return VSConstants.S_OK;
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
                    default:
                        prgCmds[0].cmdf = CommandEnabled;
                        break;
                }
                prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
            }
            else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
            {
                // undo/redo support:
                switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID)
                {
                    case VSConstants.VSStd97CmdID.Undo:
                    case VSConstants.VSStd97CmdID.MultiLevelUndo:
                    case VSConstants.VSStd97CmdID.MultiLevelUndoList:
                    case VSConstants.VSStd97CmdID.Redo:
                    case VSConstants.VSStd97CmdID.MultiLevelRedo:
                    case VSConstants.VSStd97CmdID.MultiLevelRedoList:
                        return currentBufferCommandHandler.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
                }
            }

324 325 326
            if (nextTarget != null)
            {
                var result = nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
327 328 329
#if DUMP_COMMANDS
            //DumpCmd("QS", result, ref pguidCmdGroup, prgCmds[0].cmdID, prgCmds[0].cmdf);
#endif
330 331 332
                return result;
            }
            return VSConstants.E_FAIL;
333 334 335 336 337 338 339 340 341 342
        }

        private int PreLanguageCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter;

            if (pguidCmdGroup == Guids.InteractiveCommandSetId)
            {
                switch ((CommandIds)nCmdID)
                {
D
dino 已提交
343
                    case CommandIds.AbortExecution: _window.Evaluator.AbortExecution(); return VSConstants.S_OK;
344 345 346 347 348
                    case CommandIds.Reset: _window.Operations.ResetAsync(); return VSConstants.S_OK;
                    case CommandIds.SmartExecute: _window.Operations.ExecuteInput(); return VSConstants.S_OK;
                    case CommandIds.HistoryNext: _window.Operations.HistoryNext(); return VSConstants.S_OK;
                    case CommandIds.HistoryPrevious: _window.Operations.HistoryPrevious(); return VSConstants.S_OK;
                    case CommandIds.ClearScreen: _window.Operations.ClearView(); return VSConstants.S_OK;
349
                    case CommandIds.SearchHistoryNext:
350
                        _window.Operations.HistorySearchNext();
351 352
                        return VSConstants.S_OK;
                    case CommandIds.SearchHistoryPrevious:
353
                        _window.Operations.HistorySearchPrevious();
354 355 356 357 358 359 360 361
                        return VSConstants.S_OK;
                }
            }
            else if (pguidCmdGroup == VSConstants.VSStd2K)
            {
                switch ((VSConstants.VSStd2KCmdID)nCmdID)
                {
                    case VSConstants.VSStd2KCmdID.TYPECHAR:
362
                        _window.Operations.Delete();
363 364 365
                        break;

                    case VSConstants.VSStd2KCmdID.RETURN:
366
                        if (_window.Operations.TrySubmitStandardInput())
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
                        {
                            return VSConstants.S_OK;
                        }
                        break;
                    case VSConstants.VSStd2KCmdID.SHOWCONTEXTMENU:
                        ShowContextMenu();
                        return VSConstants.S_OK;
                }
            }
            else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
            {
                // undo/redo support:
                switch ((VSConstants.VSStd97CmdID)nCmdID)
                {
                    case VSConstants.VSStd97CmdID.Undo:
                    case VSConstants.VSStd97CmdID.MultiLevelUndo:
                    case VSConstants.VSStd97CmdID.MultiLevelUndoList:
                    case VSConstants.VSStd97CmdID.Redo:
                    case VSConstants.VSStd97CmdID.MultiLevelRedo:
                    case VSConstants.VSStd97CmdID.MultiLevelRedoList:
                        return currentBufferCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                }
            }

            int res = nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
#if DUMP_COMMANDS
            DumpCmd("Exec", result, ref pguidCmdGroup, nCmdID, 0);
#endif
            return res;
        }

        private void ShowContextMenu()
        {
            var uishell = (IVsUIShell)InteractiveWindowPackage.GetGlobalService(typeof(SVsUIShell));
            if (uishell != null)
            {
                var pt = System.Windows.Forms.Cursor.Position;
                var position = new[] { new POINTS { x = (short)pt.X, y = (short)pt.Y } };
                var guid = Guids.InteractiveCommandSetId;
                ErrorHandler.ThrowOnFailure(uishell.ShowContextMenu(0, ref guid, (int)MenuIds.InteractiveWindowContextMenu, position, this));
            }
        }

        private const uint CommandEnabled = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
        private const uint CommandDisabled = (uint)(OLECMDF.OLECMDF_SUPPORTED);
        private const uint CommandDisabledAndHidden = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED);

        private bool CaretAtEnd
        {
            get
            {
                var caret = _window.TextView.Caret;
                return caret.Position.BufferPosition.Position == caret.Position.BufferPosition.Snapshot.Length;
            }
        }

        private bool UseSmartUpDown
        {
            get
            {
                return _window.TextView.Options.GetOptionValue(InteractiveWindowOptions.SmartUpDown);
            }
        }

        public IOleCommandTarget EditorServicesCommandFilter
        {
            get
            {
                return _editorServicesCommandFilter;
            }
        }
    }
}