VsInteractiveWindowCommandFilter.cs 17.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 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 154 155 156 157 158 159 160
// 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

using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Editor.InteractiveWindow;

namespace Roslyn.VisualStudio.InteractiveWindow
{
    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;

        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;
        }

        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)
        {
            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:
161
                        if (_window.Operations.BreakLine())
162 163 164 165 166 167 168 169 170 171 172
                        {
                            return VSConstants.S_OK;
                        }
                        break;
                }
            }
            else if (pguidCmdGroup == VSConstants.VSStd2K)
            {
                switch ((VSConstants.VSStd2KCmdID)nCmdID)
                {
                    case VSConstants.VSStd2KCmdID.RETURN:
173
                        if (_window.Operations.Return())
174 175 176 177 178 179 180 181 182 183 184
                        {
                            return VSConstants.S_OK;
                        }
                        break;

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

                    case VSConstants.VSStd2KCmdID.BACKSPACE:
185
                        if (_window.Operations.Backspace())
186 187 188 189 190 191 192 193 194 195
                        {
                            return VSConstants.S_OK;
                        }
                        break;


                    case VSConstants.VSStd2KCmdID.UP:

                        if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown)
                        {
196
                            _window.Operations.HistoryPrevious();
197 198 199 200 201 202 203
                            return VSConstants.S_OK;
                        }
                        break;

                    case VSConstants.VSStd2KCmdID.DOWN:
                        if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown)
                        {
204
                            _window.Operations.HistoryNext();
205 206 207 208 209 210 211
                            return VSConstants.S_OK;
                        }
                        break;

                    case VSConstants.VSStd2KCmdID.CANCEL:
                        if (_window.TextView.Selection.IsEmpty)
                        {
212
                            _window.Operations.Cancel();
213 214 215 216
                        }
                        break;

                    case VSConstants.VSStd2KCmdID.BOL:
217
                        _window.Operations.Home(false);
218 219 220
                        return VSConstants.S_OK;

                    case VSConstants.VSStd2KCmdID.BOL_EXT:
221
                        _window.Operations.Home(true);
222 223 224
                        return VSConstants.S_OK;

                    case VSConstants.VSStd2KCmdID.EOL:
225
                        _window.Operations.End(false);
226 227 228
                        return VSConstants.S_OK;

                    case VSConstants.VSStd2KCmdID.EOL_EXT:
229
                        _window.Operations.End(true);
230 231 232 233 234 235 236 237 238
                        return VSConstants.S_OK;
                }
            }
            else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
            {
                // undo/redo support:
                switch ((VSConstants.VSStd97CmdID)nCmdID)
                {
                    case VSConstants.VSStd97CmdID.Paste:
239
                        _window.Operations.Paste();
240 241 242
                        return VSConstants.S_OK;

                    case VSConstants.VSStd97CmdID.Cut:
243
                        _window.Operations.Cut();
244 245 246
                        return VSConstants.S_OK;

                    case VSConstants.VSStd97CmdID.Delete:
247
                        if (_window.Operations.Delete())
248 249 250 251 252 253
                        {
                            return VSConstants.S_OK;
                        }
                        break;

                    case VSConstants.VSStd97CmdID.SelectAll:
254
                        _window.Operations.SelectAll();
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
                        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)
        {
            var nextTarget = firstLanguageServiceCommandFilter;

            if (pguidCmdGroup == Guids.InteractiveCommandSetId)
            {
                switch ((CommandIds)prgCmds[0].cmdID)
                {
                    case CommandIds.HistoryNext:
                    case CommandIds.HistoryPrevious:
                    case CommandIds.SearchHistoryNext:
                    case CommandIds.SearchHistoryPrevious:
                        // TODO: Submit?
                        prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled;
                        break;
                    case CommandIds.AbortExecution:
                        prgCmds[0].cmdf = _window.IsRunning ? CommandEnabled : CommandDisabled;
                        break;
                    case CommandIds.Reset:
                        prgCmds[0].cmdf = !_window.IsResetting ? CommandEnabled : CommandDisabled;
                        break;
                    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);
                }
            }

304 305 306
            if (nextTarget != null)
            {
                var result = nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
307 308 309
#if DUMP_COMMANDS
            //DumpCmd("QS", result, ref pguidCmdGroup, prgCmds[0].cmdID, prgCmds[0].cmdf);
#endif
310 311 312
                return result;
            }
            return VSConstants.E_FAIL;
313 314 315 316 317 318 319 320 321 322 323
        }

        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)
                {
                    case CommandIds.AbortExecution: _window.AbortCommand(); return VSConstants.S_OK;
324 325 326 327 328
                    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;
329
                    case CommandIds.SearchHistoryNext:
330
                        _window.Operations.HistorySearchNext();
331 332
                        return VSConstants.S_OK;
                    case CommandIds.SearchHistoryPrevious:
333
                        _window.Operations.HistorySearchPrevious();
334 335 336 337 338 339 340 341
                        return VSConstants.S_OK;
                }
            }
            else if (pguidCmdGroup == VSConstants.VSStd2K)
            {
                switch ((VSConstants.VSStd2KCmdID)nCmdID)
                {
                    case VSConstants.VSStd2KCmdID.TYPECHAR:
342
                        _window.Operations.Delete();
343 344 345
                        break;

                    case VSConstants.VSStd2KCmdID.RETURN:
346
                        if (_window.Operations.TrySubmitStandardInput())
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 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
                        {
                            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;
            }
        }
    }
}