protected override void Initialize()
        {
            base.Initialize();
            VSUtils.ForegroundThreadGuard.BindThread();

            var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
            classificationColorManager = componentModel.DefaultExportProvider.GetExportedValue<ClassificationColorManager>();

            shellService = GetService(typeof(SVsShell)) as IVsShell;

            if (shellService != null)
                ErrorHandler.ThrowOnFailure(shellService.AdviseBroadcastMessages(this, out broadcastEventCookie));

            IServiceContainer serviceContainer = this;
            serviceContainer.AddService(typeof(GeneralOptionsPage),
                delegate { return GetDialogPage(typeof(GeneralOptionsPage)); }, promote:true);
            serviceContainer.AddService(typeof(FantomasOptionsPage),
                delegate { return GetDialogPage(typeof(FantomasOptionsPage)); }, promote:true);

            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            var shell = GetService(typeof(SVsUIShell)) as IVsUIShell;
            var logger = new Logger(ServiceProvider.GlobalProvider);

            if (mcs != null)
            {
                var newFolderMenu = new FolderMenuCommands(DTE.Value, mcs, shell);
                newFolderMenu.SetupCommands();
            }
        }
        private void AdviseBroadcastMessages()
        {
            shellService = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;

            if (shellService != null)
                ErrorHandler.ThrowOnFailure(shellService.AdviseBroadcastMessages(this, out broadcastEventCookie));
        }
Example #3
0
        public void Dispose()
        {
            if (this.solution != null && this.solutionEventsCookie != 0)
            {
                GC.SuppressFinalize(this);
                this.solution.UnadviseSolutionEvents(this.solutionEventsCookie);

                this.AfterSolutionLoaded = null;
                this.BeforeSolutionClosed = null;
                this.AfterSolutionClosed = null;

                this.solutionEventsCookie = 0;
                this.solution = null;
            }

            if (this.shell != null)
            {
                if (this.shellPropertyEventsCookie != 0)
                {
                    this.shell.UnadviseShellPropertyChanges(this.shellPropertyEventsCookie);
                    this.shellPropertyEventsCookie = 0;
                }

                if (this.broadcastMessageEventsCookie != 0)
                {
                    this.shell.UnadviseBroadcastMessages(this.broadcastMessageEventsCookie);
                    this.broadcastMessageEventsCookie = 0;
                }

                this.shell = null;
            }
        }
Example #4
0
        private static bool TryGetKeyBindingScopeName(IVsShell vsShell, RegistryKey keyBindingsKey, string subKeyName, uint? id, out string localizedScopeName)
        {
            try
            {
                using (var subKey = keyBindingsKey.OpenSubKey(subKeyName, writable: false))
                {
                    uint resourceId;
                    if (id.HasValue)
                    {
                        resourceId = id.Value;
                    }
                    else
                    {
                        resourceId = UInt32.Parse((string)subKey.GetValue(null));
                    }

                    var package = Guid.Parse((string)subKey.GetValue("Package"));
                    ErrorHandler.ThrowOnFailure(vsShell.LoadPackageString(ref package, resourceId, out localizedScopeName));
                    return !string.IsNullOrEmpty(localizedScopeName);
                }
            }
            catch (Exception)
            {
                localizedScopeName = null;
                return false;
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ShellEventListener"/> class.
 /// </summary>
 /// <param name="package">The package hosting the event listener.</param>
 /// <param name="shellService">The shell service.</param>
 internal ShellEventListener(EditorConfigPackage package, IVsShell shellService)
     : base(package)
 {
     _shellService = shellService;
     if (_shellService == null) return;
     _shellService.AdviseBroadcastMessages(this, out _broadcastEventCookie);
     _shellService.AdviseShellPropertyChanges(this, out _propertyEventCookie);
 }
 public void Initialize()
 {
     shellService = provider.GetService(typeof(SVsShell)) as IVsShell;
     if (shellService != null)
     {
         ErrorHandler.ThrowOnFailure(shellService.AdviseBroadcastMessages(this, out cookie));
     }
 }
 internal DteInitializer(IVsShell shellService, Action callback)
 {
     this.shellService = shellService;
     this.callback = callback;
     // Set an event handler to detect when the IDE is fully initialized
     int hr = this.shellService.AdviseShellPropertyChanges(this, out cookie);
     ErrorHandler.ThrowOnFailure(hr);
 }
Example #8
0
 internal KeyBindingService(SVsServiceProvider serviceProvider, IOptionsDialogService service, [EditorUtilsImport] IProtectedOperations protectedOperations, IVimApplicationSettings vimApplicationSettings)
 {
     _dte = serviceProvider.GetService<SDTE, _DTE>();
     _vsShell = serviceProvider.GetService<SVsShell, IVsShell>();
     _optionsDialogService = service;
     _protectedOperations = protectedOperations;
     _vimApplicationSettings = vimApplicationSettings;
     _importantScopeSet = new Lazy<HashSet<string>>(CreateImportantScopeSet);
 }
Example #9
0
        public ShellEvents([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
        {
            Guard.NotNull(() => serviceProvider, serviceProvider);

            this.shellService = serviceProvider.GetService<SVsShell, IVsShell>();

            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                this.shellService.AdviseShellPropertyChanges(this, out this.shellCookie));
        }
Example #10
0
        public OptionsManager(IServiceProvider serviceProvider, IVsShell vsShell, IEnumerable<Lazy<IOptionsPage>> optionPages)
        {
            this.serviceProvider = serviceProvider;
            this.vsShell = vsShell;
            this.optionPages = optionPages;

            // This is the same as shellPackage.ApplicationRegistryRoot
            this.registryRoot = VSRegistry.RegistryRoot(serviceProvider, __VsLocalRegistryType.RegType_Configuration, false).Name;
        }
Example #11
0
        public VisualStudioThemeEngine(IServiceProvider serviceProvider)
        {
            dte = (DTE2)serviceProvider.GetService(typeof(SDTE));

            // Register to Visual Studio theme change
            shellService = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;
            if (shellService != null)
                ErrorHandler.ThrowOnFailure(shellService.AdviseBroadcastMessages(this, out broadcastCookie));
        }
        public ReSharperIntegrationBootstrap(IVsShell vsShell, IVsOleServiceProvider vsOleServiceProvider)
        {
            this.vsShell = vsShell;
              this.vsOleServiceProvider = vsOleServiceProvider;

              int fInstalled;
              IsReSharperInstalled = vsShell.IsPackageInstalled(GuidList.ReSharperPkg, out fInstalled) == 0 &&
                             Convert.ToBoolean(fInstalled);
        }
Example #13
0
 internal KeyBindingService(SVsServiceProvider serviceProvider, IOptionsDialogService service, IProtectedOperations protectedOperations, ILegacySettings legacySettings)
 {
     _dte = serviceProvider.GetService<SDTE, _DTE>();
     _vsShell = serviceProvider.GetService<SVsShell, IVsShell>();
     _optionsDialogService = service;
     _protectedOperations = protectedOperations;
     _legacySettings = legacySettings;
     _importantScopeSet = new Lazy<HashSet<string>>(CreateImportantScopeSet);
 }
Example #14
0
        internal ScopeData(IVsShell vsShell)
        {
            if (!TryGetMainScopeNames(vsShell, out _globalScopeName, out _textEditorScopeName))
            {
                _globalScopeName = DefaultGlobalScopeName;
                _textEditorScopeName = DefaultTextEditorScopeName;
            }

            _importantScopeSet = CreateImportantScopeSet(_globalScopeName, _textEditorScopeName);
        }
		private static IVsPackage TryLoadPackage(IVsShell vsShell, Guid packageGuid) {
			IVsPackage package;
			if (vsShell.IsPackageLoaded(ref packageGuid, out package) == VSConstants.S_OK && package != null)
				return package;

			if (vsShell.LoadPackage(ref packageGuid, out package) == VSConstants.S_OK)
				return package;

			return null;
		}
Example #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ShellEventListener"/> class.
 /// </summary>
 /// <param name="package">The package hosting the event listener.</param>
 /// <param name="shellService">The shell service.</param>
 internal ShellEventListener(VSTalkPackage package, IVsShell shellService)
     : base(package)
 {
     _shellService = shellService;
     if (_shellService != null)
     {
         _shellService.AdviseBroadcastMessages(this, out _broadcastEventCookie);
         _shellService.AdviseShellPropertyChanges(this, out _propertyEventCookie);
     }
 }
        internal FallbackKeyProcessorProvider(SVsServiceProvider serviceProvider, IKeyUtil keyUtil, IVimApplicationSettings vimApplicationSettings, IVim vim)
        {
            _dte = (_DTE)serviceProvider.GetService(typeof(_DTE));
            _keyUtil = keyUtil;
            _vimApplicationSettings = vimApplicationSettings;
            _vim = vim;

            _vsShell = (IVsShell)serviceProvider.GetService(typeof(SVsShell));
            _scopeData = new ScopeData(_vsShell);
        }
 internal ExternalEditorManager(SVsServiceProvider serviceProvider, IVsAdapter vsAdapter)
 {
     _vsAdapter = vsAdapter;
     _vsShell = serviceProvider.GetService<SVsShell, IVsShell>();
     _adapterList.Add(new SnippetExternalEditAdapter());
     _isResharperInstalled = CheckResharperInstalled();
     if (_isResharperInstalled)
     {
         _adapterList.Add(new ResharperExternalEditAdapter());
     }
 }
Example #19
0
        public static MarkdownPackage ForceLoadPackage(IVsShell shell)
        {
            Guid packageGuid = new Guid(GuidList.guidMarkdownPackagePkgString);
            IVsPackage package;

            if (VSConstants.S_OK == shell.IsPackageLoaded(ref packageGuid, out package))
                return package as MarkdownPackage;
            else if (ErrorHandler.Succeeded(shell.LoadPackage(ref packageGuid, out package)))
                return package as MarkdownPackage;
            return null;
        }
Example #20
0
        internal ScopeData(IVsShell vsShell)
        {
            if (!TryGetMainScopeNames(vsShell, out _globalScopeName, out _textEditorScopeName, out _solutionExplorerScopeName))
            {
                _globalScopeName = DefaultGlobalScopeName;
                _textEditorScopeName = DefaultTextEditorScopeName;
                _solutionExplorerScopeName = DefaultSolutionExplorerScopeName;
            }

            _scopeKindMap = BuildScopeKindMap();
        }
Example #21
0
		/// <summary>
		/// Initializes the package.  This method is called right after the package is sited, so this is the place
		/// where you can put all the initialization code that rely on services provided by VisualStudio.
		/// </summary>
		protected override async void Initialize() {
			base.Initialize();

			shellService = GetService(typeof(SVsShell)) as IVsShell;

			if (shellService != null) {
				ErrorHandler.ThrowOnFailure(shellService.AdviseShellPropertyChanges(this, out shellPropertyCookie));
			} else {
				await Task.Delay(TimeSpan.FromSeconds(5));
				FullInitialize();
			}
		}
Example #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PackageSettings"/> class.
        /// </summary>
        /// <param name="serviceProvider">The <see cref="ServiceProvider"/> to use.</param>
        /// <param name="machineSettingsRegistryKey">
        /// Relative registry path to machine-level settings. The path is relative to the Visual Studio registry root.
        /// </param>
        protected PackageSettings(ServiceProvider serviceProvider, string machineSettingsRegistryKey)
        {
            Tracer.VerifyNonNullArgument(serviceProvider, "serviceProvider");

            // Read in the Visual Studio registry root.
            IVsShell vsShell = serviceProvider.GetVsShell(classType, Tracer.ConstructorMethodName);
            object   rootPathObj;
            int      hr = vsShell.GetProperty((int)__VSSPROPID.VSSPROPID_VirtualRegistryRoot, out rootPathObj);

            this.visualStudioRegistryRoot = (string)rootPathObj;
            this.machineRootPath          = this.RegistryPathCombine(this.visualStudioRegistryRoot, machineSettingsRegistryKey);

            // Initialize all of the machine settings.
            this.traceLevel = new MachineSettingEnum(this.MachineRootPath, KeyNames.TraceLevel, Tracer.Level.Critical, typeof(Tracer.Level));
        }
Example #23
0
        public void PackageLoadTest()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the Shell Service
                IVsShell shellService = VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsShell)) as IVsShell;
                Assert.IsNotNull(shellService);

                //Validate package load
                IVsPackage package;
                Guid packageGuid = new Guid("C4128D99-2000-41D1-A6C3-704E6C1A3DE2");
                Assert.IsTrue(0 == shellService.LoadPackage(ref packageGuid, out package));
                Assert.IsNotNull(package, "Package failed to load");
            });
        }
Example #24
0
        public static MarkdownPackage ForceLoadPackage(IVsShell shell)
        {
            Guid       packageGuid = new Guid(GuidList.guidMarkdownPackagePkgString);
            IVsPackage package;

            if (VSConstants.S_OK == shell.IsPackageLoaded(ref packageGuid, out package))
            {
                return(package as MarkdownPackage);
            }
            else if (ErrorHandler.Succeeded(shell.LoadPackage(ref packageGuid, out package)))
            {
                return(package as MarkdownPackage);
            }
            return(null);
        }
Example #25
0
 internal ExternalEditorManager(
     SVsServiceProvider serviceProvider,
     IVsAdapter vsAdapter,
     IViewTagAggregatorFactoryService viewTagAggregatorFactoryService)
 {
     _vsAdapter = vsAdapter;
     _viewTagAggregatorFactoryService = viewTagAggregatorFactoryService;
     _vsShell = serviceProvider.GetService <SVsShell, IVsShell>();
     _adapterList.Add(new SnippetExternalEditAdapter());
     _isResharperInstalled = CheckResharperInstalled();
     if (_isResharperInstalled)
     {
         _adapterList.Add(new ResharperExternalEditAdapter());
     }
 }
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            QueryFirstCmd.Initialize(this);
            base.Initialize();

            // sby : set an eventlistener for shell property changes
            IVsShell shellService = GetService(typeof(SVsShell)) as IVsShell;

            if (shellService != null)
            {
                ErrorHandler.ThrowOnFailure(shellService.AdviseShellPropertyChanges(this, out cookie));
            }
            // do it anyway
            zombieProofInitialization();
        }
        private static void Initialize()
        {
            DTE2 dte = ServiceProvider.GetService(typeof(SDTE)) as DTE2;

            _onDteInitialized?.Invoke(dte);

            if (dte != null)
            {
                return;
            }

            IVsShell shellService = ServiceProvider.GetService(typeof(SVsShell)) as IVsShell;

            new DteInitializer(shellService, Initialize);
        }
        public void PackageLoadTest()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the Shell Service
                IVsShell shellService = VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsShell)) as IVsShell;
                Assert.IsNotNull(shellService);

                //Validate package load
                IVsPackage package;
                Guid packageGuid = new Guid(MufflonoSoft.CodingDojoHelperVsExtension.GuidList.guidCodingDojoHelperVsExtensionPkgString);
                Assert.IsTrue(0 == shellService.LoadPackage(ref packageGuid, out package));
                Assert.IsNotNull(package, "Package failed to load");
            });
        }
        public void PackageLoadTest()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the Shell Service
                IVsShell shellService = VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsShell)) as IVsShell;
                Assert.IsNotNull(shellService);

                //Validate package load
                IVsPackage package;
                Guid packageGuid = new Guid(mskold.TfsAdminTools.GuidList.guidTfsAdminToolsPkgString);
                Assert.IsTrue(0 == shellService.LoadPackage(ref packageGuid, out package));
                Assert.IsNotNull(package, "Package failed to load");
            });
        }
Example #30
0
        /// <include file='doc\WindowPane.uex' path='docs/doc[@for="WindowPane.IVsWindowPane.CreatePaneWindow"]/*' />
        /// <internalonly/>
        /// <devdoc>
        /// IVsWindowPane implementation.
        /// </devdoc>
        int IVsWindowPane.CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr pane)
        {
            OnCreate();
            IntPtr hwnd  = Window.Handle;
            int    style = (int)UnsafeNativeMethods.GetWindowLong(hwnd, NativeMethods.GWL_STYLE);

            // set up the required styles of an IVsWindowPane
            style |= (NativeMethods.WS_CLIPSIBLINGS | NativeMethods.WS_CHILD | NativeMethods.WS_VISIBLE);
            style &= ~(NativeMethods.WS_POPUP |
                       NativeMethods.WS_MINIMIZE |
                       NativeMethods.WS_MAXIMIZE |
                       NativeMethods.WS_DLGFRAME |
                       NativeMethods.WS_SYSMENU |
                       NativeMethods.WS_THICKFRAME |
                       NativeMethods.WS_MINIMIZEBOX |
                       NativeMethods.WS_MAXIMIZEBOX);

            UnsafeNativeMethods.SetWindowLong(hwnd, NativeMethods.GWL_STYLE, (IntPtr)style);

            style = (int)UnsafeNativeMethods.GetWindowLong(hwnd, NativeMethods.GWL_EXSTYLE);

            style &= ~(NativeMethods.WS_EX_DLGMODALFRAME |
                       NativeMethods.WS_EX_NOPARENTNOTIFY |
                       NativeMethods.WS_EX_TOPMOST |
                       NativeMethods.WS_EX_MDICHILD |
                       NativeMethods.WS_EX_TOOLWINDOW |
                       NativeMethods.WS_EX_CONTEXTHELP |
                       NativeMethods.WS_EX_APPWINDOW);

            UnsafeNativeMethods.SetWindowLong(hwnd, NativeMethods.GWL_EXSTYLE, (IntPtr)style);
            UnsafeNativeMethods.SetParent(hwnd, (IntPtr)hwndParent);
            UnsafeNativeMethods.SetWindowPos(hwnd, IntPtr.Zero, x, y, cx, cy, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE);
            UnsafeNativeMethods.ShowWindow(hwnd, NativeMethods.SW_SHOWNORMAL);

            // Sync broadcast events so we update our UI when colors/fonts change.
            //
            if (_vsShell == null)
            {
                _vsShell = (IVsShell)GetService(typeof(SVsShell));
                if (_vsShell != null)
                {
                    NativeMethods.ThrowOnFailure(_vsShell.AdviseBroadcastMessages(this, out _broadcastEventCookie));
                }
            }

            pane = hwnd;
            return(NativeMethods.S_OK);
        }
Example #31
0
        public string GetInstallDirectory(IServiceProvider serviceProvider)
        {
            string   str     = (string)null;
            IVsShell service = (IVsShell)serviceProvider.GetService(typeof(SVsShell));

            if (service != null)
            {
                object pvar = (object)null;
                service.GetProperty(-9007, out pvar);
                if (pvar != null)
                {
                    str = pvar as string;
                }
            }
            return(str);
        }
Example #32
0
        /// <summary>
        /// Force load package.
        /// A hack method which is called from analyzers to ensure that the package is loaded before diagnostics are executed.
        /// </summary>
        /// <returns/>
        public static async System.Threading.Tasks.Task ForceLoadPackageAsync()
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsShell shell = await VS.GetServiceAsync <SVsShell, IVsShell>();

            if (shell == null)
            {
                return;
            }

            var packageToBeLoadedGuid = new Guid(PackageGuidString);

            shell.LoadPackage(ref packageToBeLoadedGuid, out var _);
            await System.Threading.Tasks.TaskScheduler.Default;
        }
Example #33
0
        public static Version TryGetReSharperVersion(this IVsShell vsShell)
        {
            if (vsShell == null || !IsPackageInstalled(vsShell, _reSharperPackageGuid))
            {
                return(null);
            }

            IVsPackage vsPackage = TryLoadPackage(vsShell, _reSharperPackageGuid);

            if (vsPackage == null)
            {
                return(null);
            }

            return(vsPackage.GetType().Assembly.GetName().Version);
        }
Example #34
0
        /// <summary>
        /// In general a key processor applies to a specific IWpfTextView but
        /// by not making use of it, the fallback processor can be reused for
        /// multiple text views
        /// </summary>
        internal FallbackKeyProcessor(IVsShell vsShell, _DTE dte, IKeyUtil keyUtil, IVimApplicationSettings vimApplicationSettings, ITextView textView, IVimBuffer vimBuffer, ScopeData scopeData)
        {
            _vsShell = vsShell;
            _dte = dte;
            _keyUtil = keyUtil;
            _vimApplicationSettings = vimApplicationSettings;
            _vimBuffer = vimBuffer;
            _scopeData = scopeData;
            _fallbackCommandList = Enumerable.Empty<FallbackCommand>().ToLookup(x => 'a');

            // Register for key binding changes and get the current bindings
            _vimApplicationSettings.SettingsChanged += OnSettingsChanged;
            GetKeyBindings();

            textView.Closed += OnTextViewClosed;
        }
Example #35
0
        private static void Initialize()
        {
            if (vsShell != null)
            {
                return;
            }
            vsShell = VsServiceProvider.GetService <IVsShell>();

            object objProp;
            int    res = vsShell.GetProperty((int)__VSSPROPID2.VSSPROPID_InstallRootDir, out objProp);

            if (res == VSConstants.S_OK && objProp is string)
            {
                _InstallRootDir = objProp as string;
            }
        }
Example #36
0
        /// <summary>
        /// In general a key processor applies to a specific IWpfTextView but
        /// by not making use of it, the fallback processor can be reused for
        /// multiple text views
        /// </summary>
        internal FallbackKeyProcessor(IVsShell vsShell, _DTE dte, IKeyUtil keyUtil, IVimApplicationSettings vimApplicationSettings, ITextView textView, IVimBuffer vimBuffer, ScopeData scopeData)
        {
            _vsShell = vsShell;
            _dte     = dte;
            _keyUtil = keyUtil;
            _vimApplicationSettings = vimApplicationSettings;
            _vimBuffer           = vimBuffer;
            _scopeData           = scopeData;
            _fallbackCommandList = new List <FallbackCommand>();

            // Register for key binding changes and get the current bindings
            _vimApplicationSettings.SettingsChanged += OnSettingsChanged;
            GetKeyBindings();

            textView.Closed += OnTextViewClosed;
        }
Example #37
0
        /// <include file='doc\VsRegistry.uex' path='docs/doc[@for="VsRegistry.GetOptionRoot"]/*' />
        /// <devdoc>
        ///     Retrieves the shell's root key for VS options, or uses the value of
        ///     GetDefaultBase if we coundn't get the shell service.
        /// </devdoc>
        private static string GetOptionRoot(IServiceProvider serviceProvider)
        {
            string optionRoot;

            IVsShell vsh = (IVsShell)serviceProvider.GetService(typeof(IVsShell));

            if (vsh == null)
            {
                optionRoot = GetDefaultBase();
            }
            else
            {
                optionRoot = vsh.GetProperty(__VSSPROPID.VSSPROPID_VirtualRegistryRoot).ToString();
            }
            return(optionRoot);
        }
Example #38
0
        private static IVsPackage TryLoadPackage(IVsShell vsShell, Guid packageGuid)
        {
            IVsPackage package;

            if (vsShell.IsPackageLoaded(ref packageGuid, out package) == VSConstants.S_OK && package != null)
            {
                return(package);
            }

            if (vsShell.LoadPackage(ref packageGuid, out package) == VSConstants.S_OK)
            {
                return(package);
            }

            return(null);
        }
        /// <summary>
        /// Get the localized strings that represent various keyboard keys. Copied from keynameinfo.cpp in env\msenv\core
        /// </summary>
        private void PopulateKeyMaps()
        {
            Guid shellPkg = CLSID_VsEnvironmentPackage;

            IVsShell shell = Shell;

            foreach (KeyValuePair <Key, uint> kvp in KeyResourceIdMap)
            {
                string keyName;
                if (ErrorHandler.Succeeded(shell.LoadPackageString(ref shellPkg, kvp.Value, out keyName)))
                {
                    this.keyNameKeyIdMap[keyName] = kvp.Key;
                    this.keyIdKeyNameMap[kvp.Key] = keyName;
                }
            }
        }
Example #40
0
 private void CheckVsStarted()
 {
     _vsShell = (IVsShell)VsPackage.GetGlobalService(typeof(SVsShell));
     _vsShell.GetProperty((int)__VSSPROPID4.VSSPROPID_ShellInitialized, out var value);
     if (value is bool)
     {
         if ((bool)value)
         {
             _application.FireStarted();
         }
         else
         {
             _vsShell.AdviseShellPropertyChanges(this, out _vsShellEventsCookie);
         }
     }
 }
Example #41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandManager"/> class.
        /// </summary>
        public CommandManager(
            IServiceProvider serviceProvider,
            IEnumerable<Lazy<ICommandExtension, CommandAttribute>> allCommands,
            IEnumerable<Lazy<ICommandFilter, CommandFilterAttribute>> allFilters,
            IEnumerable<Lazy<ICommandInterceptor, CommandInterceptorAttribute>> allInterceptors)
        {
            this.serviceProvider = serviceProvider;
            this.vsShell = serviceProvider.GetService<SVsShell, IVsShell>();
            this.commandEvents = serviceProvider.GetService<DTE>().Events.CommandEvents;
            this.commands = allCommands;
            this.filters = allFilters;
            this.interceptors = allInterceptors.ToList();

            this.commandEvents.BeforeExecute += OnBeforeExecute;
            this.commandEvents.AfterExecute += OnAfterExecute;
        }
Example #42
0
        public ShellEvents(IServiceProvider serviceProvider)
        {
            Guard.NotNull(() => serviceProvider, serviceProvider);

            this.services = serviceProvider;
            this.shellService = serviceProvider.GetService<SVsShell, IVsShell>();

            object isZombie;
            ErrorHandler.ThrowOnFailure(this.shellService.GetProperty((int)__VSSPROPID.VSSPROPID_Zombie, out isZombie));

            this.IsInitialized = !((bool)isZombie);

            // TODO: see if we still should advise changes if IsInitialized is true at this point?
            ErrorHandler.ThrowOnFailure(
                this.shellService.AdviseShellPropertyChanges(this, out this.shellCookie));
        }
Example #43
0
        /// <summary>
        /// Get the localized names of "Global", "Text Editor" and "Solution Explorer" scope.  I wish there was a
        /// prettier way of doing this.  However there is no API available which provides this information.  We need to directly
        /// query some registry values here
        /// </summary>
        private static bool TryGetMainScopeNames(IVsShell vsShell, out string globalScopeName, out string textEditorScopeName, out string solutionExplorerScopeName)
        {
            globalScopeName           = null;
            textEditorScopeName       = null;
            solutionExplorerScopeName = null;
            try
            {
                using (var rootKey = VSRegistry.RegistryRoot(__VsLocalRegistryType.RegType_Configuration, writable: false))
                {
                    if (rootKey is null)
                    {
                        return(false);
                    }

                    using (var keyBindingsKey = rootKey.OpenSubKey("KeyBindingTables"))
                    {
                        // For "Global".  The id in the registry here is incorrect for Vs 2010+
                        // so hard code the known value
                        if (!TryGetKeyBindingScopeName(vsShell, keyBindingsKey, "{5efc7975-14bc-11cf-9b2b-00aa00573819}", 13018, out globalScopeName))
                        {
                            return(false);
                        }

                        // For "Text Editor".  Many locals don't define this key so it's still considered a success
                        // if we get only the global name.  Just fill in the default here
                        if (!TryGetKeyBindingScopeName(vsShell, keyBindingsKey, "{8B382828-6202-11D1-8870-0000F87579D2}", null, out textEditorScopeName))
                        {
                            textEditorScopeName = DefaultTextEditorScopeName;
                        }

                        // The "Solution Explorer" scope is only relevant starting in VS2013.  By default it contains a lot of
                        // key bindings for '['.  If we can't find the real name just use the default.  We don't want its abscence
                        // to screw up other scopes
                        if (!TryGetKeyBindingScopeName(vsShell, keyBindingsKey, "{3AE79031-E1BC-11D0-8F78-00A0C9110057}", null, out solutionExplorerScopeName))
                        {
                            solutionExplorerScopeName = DefaultSolutionExplorerScopeName;
                        }
                    }
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #44
0
        private static void Initialize()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (vsShell != null)
            {
                return;
            }
            vsShell = VsServiceProvider.GetService <IVsShell>();

            int res = vsShell.GetProperty((int)__VSSPROPID2.VSSPROPID_InstallRootDir, out object o);

            if (res == VSConstants.S_OK && o is string property)
            {
                _InstallRootDir = property;
            }
        }
Example #45
0
        public SolutionSettings(IAnkhServiceProvider context)
            : base(context)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsShell shell = GetService <IVsShell>(typeof(SVsShell));

            if (shell == null)
            {
                throw new InvalidOperationException("IVsShell not available");
            }

            object r;

            if (VSErr.Succeeded(shell.GetProperty((int)__VSSPROPID.VSSPROPID_VirtualRegistryRoot, out r)))
            {
                _vsUserRoot = (string)r;
            }
            else
            {
                _vsUserRoot = @"SOFTWARE\Microsoft\VisualStudio\8.0";
            }

            string baseName = _vsUserRoot;

            if (_vsUserRoot.EndsWith(@"\UserSettings", StringComparison.OrdinalIgnoreCase))
            {
                _inRanu    = true;
                baseName   = _vsUserRoot.Substring(0, _vsUserRoot.Length - 13);
                _vsAppRoot = baseName + @"\Configuration";
            }
            else
            {
                _vsAppRoot = _vsUserRoot;
            }

            if (baseName.StartsWith(@"SOFTWARE\", StringComparison.OrdinalIgnoreCase))
            {
                baseName = baseName.Substring(9); // Should always trigger
            }
            if (baseName.StartsWith(@"Microsoft\", StringComparison.OrdinalIgnoreCase))
            {
                baseName = baseName.Substring(10); // Give non-ms hives a prefix
            }
            _hiveSuffix = baseName;
        }
Example #46
0
        public SolutionEventsListener(IServiceProvider serviceProvider)
        {
            this.InitNullEvents();

            this.solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
            if (this.solution != null)
            {
                this.solution.AdviseSolutionEvents(this, out this.solutionEventsCookie);
            }

            this.shell = (IVsShell)serviceProvider.GetService(typeof(SVsShell));
            if (this.shell != null)
            {
                this.shell.AdviseShellPropertyChanges(this, out this.shellPropertyEventsCookie);
                this.shell.AdviseBroadcastMessages(this, out this.broadcastMessageEventsCookie);
            }
        }
Example #47
0
        /// <summary>
        /// Initializes the package.  This method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override async void Initialize()
        {
            base.Initialize();

            shellService = GetService(typeof(SVsShell)) as IVsShell;

            if (shellService != null)
            {
                ErrorHandler.ThrowOnFailure(shellService.AdviseShellPropertyChanges(this, out shellPropertyCookie));
            }
            else
            {
                await Task.Delay(TimeSpan.FromSeconds(5));

                FullInitialize();
            }
        }
Example #48
0
        /// <summary>
        /// Retrieves the fxcop dierctory location
        /// </summary>
        private static string GetFxCopDirectoryLocation()
        {
            IVsShell shell = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(IVsShell)) as IVsShell;

            Debug.Assert(shell != null, "Could not retrieve the IVsShell service from the global service provider");

            object virtualRegistryRootAsObject;

            // We do not want to throw. If we cannot set the solution related constants we set them to empty string.
            shell.GetProperty((int)__VSSPROPID.VSSPROPID_VirtualRegistryRoot, out virtualRegistryRootAsObject);

            string virtualRegistryRoot = (string)virtualRegistryRootAsObject;

            if (String.IsNullOrEmpty(virtualRegistryRoot))
            {
                return(String.Empty);
            }

            // Ensure there is a trailing backslash
            if (virtualRegistryRoot[virtualRegistryRoot.Length - 1] != Path.DirectorySeparatorChar)
            {
                virtualRegistryRoot += Path.DirectorySeparatorChar;
            }

            virtualRegistryRoot += FxCopRegistryRelativePathEntry;

            using (RegistryKey root = Registry.LocalMachine.OpenSubKey(virtualRegistryRoot))
            {
                if (null == root)
                {
                    return(String.Empty);
                }

                using (RegistryKey key = root.OpenSubKey(FxCopRegistryRelativePathEntry))
                {
                    if (key != null)
                    {
                        string fxcopInstallDir = key.GetValue(FxCopRegistryInstallDirKeyName) as string;

                        return((fxcopInstallDir == null) ? String.Empty : fxcopInstallDir);
                    }
                }
            }

            return(String.Empty);
        }
Example #49
0
        protected override void Initialize()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            _Shell = GetService(typeof(SVsShell)) as IVsShell;
            if (null != mcs)
            {
                SetupCommand(mcs, PkgCmdIDList.cmdidUsusNetCockpit, MenuItemCallback_Cockpit);
                SetupCommand(mcs, PkgCmdIDList.cmdidUsusNetHotspots, MenuItemCallback_Hotspots);
                SetupCommand(mcs, PkgCmdIDList.cmdidUsusNetDistributions, MenuItemCallback_Distributions);
                SetupCommand(mcs, PkgCmdIDList.cmdidUsusNetCleanCode, MenuItemCallback_CleanCode);
                SetupCommand(mcs, PkgCmdIDList.cmdidUsusNetCurrent, MenuItemCallback_Current);
                SetupCommand(mcs, PkgCmdIDList.cmdidUsusNetSqi, MenuItemCallback_Sqi);
            }
        }
Example #50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SolutionEventsListener"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        public SolutionEventsListener(IServiceProvider serviceProvider)
        {
            this.InitNullEvents();

            this.solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
            if (this.solution != null)
            {
                this.solution.AdviseSolutionEvents(this, out this.solutionEventsCookie);
            }

            this.shell = (IVsShell)serviceProvider.GetService(typeof(SVsShell));
            if (this.shell != null)
            {
                this.shell.AdviseShellPropertyChanges(this, out this.shellPropertyEventsCookie);
                this.shell.AdviseBroadcastMessages(this, out this.broadcastMessageEventsCookie);
            }
        }
Example #51
0
        internal static bool IsShellInCommandLineMode(System.IServiceProvider serviceProvider)
        {
            Utilities.ArgumentNotNull("serviceProvider", serviceProvider);

            IVsShell shell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;

            if (shell == null)
            {
                throw new InvalidOperationException();
            }

            object isInCommandLineModeAsObject;

            ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID.VSSPROPID_IsInCommandLineMode, out isInCommandLineModeAsObject));

            return((bool)isInCommandLineModeAsObject);
        }
Example #52
0
        /// <summary>
        /// Gets the installation directory for the current instance of Visual Studio.
        /// </summary>
        /// <returns>Full path to the VS instalation directory</returns>
        public string GetVsInstallDirectory()
        {
            string   installDirectory = null;
            IVsShell shell            = this.GetService(typeof(SVsShell)) as IVsShell;

            if (shell != null)
            {
                object installDirectoryObj;
                shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out installDirectoryObj);
                if (installDirectoryObj != null)
                {
                    installDirectory = installDirectoryObj as string;
                }
            }

            return(installDirectory);
        }
Example #53
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            QueryFirstCmd.Initialize(this);
            await base.InitializeAsync(cancellationToken, progress);

            // sby : set an eventlistener for shell property changes
            IVsShell shellService = await GetServiceAsync(typeof(SVsShell)) as IVsShell;

            if (shellService != null)
            {
                ErrorHandler.ThrowOnFailure(shellService.AdviseShellPropertyChanges(this, out cookie));
            }
            // do it anyway
            zombieProofInitialization();
        }
Example #54
0
        public static bool TryGetPropertyValue(
            this IVsShell shell,
            __VSSPROPID id,
            out IntPtr value
            )
        {
            var hresult = shell.GetProperty((int)id, out var objValue);

            if (ErrorHandler.Succeeded(hresult) && objValue != null)
            {
                value = (IntPtr.Size == 4) ? (IntPtr)(int)objValue : (IntPtr)(long)objValue;
                return(true);
            }

            value = default;
            return(false);
        }
Example #55
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>

        protected override void Initialize()
        {
            base.Initialize();
            FGetCommand.Initialize(this);
            VListWindowCommand.Initialize(this);

            IVsShell shell_service = GetService(typeof(SVsShell)) as IVsShell;

            bool test = true;

            dte2 = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStu‌​dio.Shell.Interop.SD‌​TE));

            _m3dfw_namespace        = null;
            _getFctPtrList_function = null;

            test = false;
        }
Example #56
0
        public ShellEvents(IServiceProvider serviceProvider)
        {
            Guard.NotNull(() => serviceProvider, serviceProvider);

            this.services     = serviceProvider;
            this.shellService = serviceProvider.GetService <SVsShell, IVsShell>();

            object isZombie;

            ErrorHandler.ThrowOnFailure(this.shellService.GetProperty((int)__VSSPROPID.VSSPROPID_Zombie, out isZombie));

            this.IsInitialized = !((bool)isZombie);

            // TODO: see if we still should advise changes if IsInitialized is true at this point?
            ErrorHandler.ThrowOnFailure(
                this.shellService.AdviseShellPropertyChanges(this, out this.shellCookie));
        }
 private static void LoadEDMPackage(IVsShell vsShell)
 {
     Debug.Assert(vsShell != null, "unexpected null value for vsShell");
     IVsPackage package = null;
     if (vsShell != null)
     {
         var packageGuid = PackageConstants.guidEscherPkg;
         var hr = vsShell.IsPackageLoaded(ref packageGuid, out package);
         if (NativeMethods.Failed(hr) || package == null)
         {
             hr = vsShell.LoadPackage(ref packageGuid, out package);
             if (NativeMethods.Failed(hr))
             {
                 var msg = String.Format(CultureInfo.CurrentCulture, Resources.PackageLoadFailureExceptionMessage, hr);
                 throw new InvalidOperationException(msg);
             }
         }
     }
 }
 public void Dispose()
 {
     if (cookie != 0
         && shellService != null)
     {
         try
         {
             shellService.UnadviseBroadcastMessages(cookie);
         }
         catch (Exception)
         {
             // Possibly VS is shutting down so ignore the exception.
         }
         finally
         {
             cookie = 0;
             shellService = null;
         }
     }
     GC.SuppressFinalize(this);
 }
Example #59
0
        /// <include file='doc\WindowPane.uex' path='docs/doc[@for="WindowPane.Dispose1"]' />
        /// <devdoc>
        ///     Called when this window pane is being disposed.
        /// </devdoc>
        protected virtual void Dispose(bool disposing) {

            if (disposing) {

                if (_vsShell != null) {
                    try {
                        // Don't check for return code because here we can't do anything in case of failure.
                        _vsShell.UnadviseBroadcastMessages(_broadcastEventCookie);
                    } catch (COMException) { /* do nothing */ }
                    _vsShell = null;
                    _broadcastEventCookie = 0;
                }

                IWin32Window window = Window;
                if (window is IDisposable) {
                    try {
                    ((IDisposable)window).Dispose();
                    } catch (Exception) {
                        Debug.Fail("Failed to dispose window");
                    }
                }
                window = null;

                if (_commandService != null && _commandService is IDisposable) {
                    try {
                    ((IDisposable)_commandService).Dispose();
                    } catch (Exception) {
                        Debug.Fail("Failed to dispose command service");
                    }
                }
                _commandService = null;

                if (_parentProvider != null)
                    _parentProvider = null;

                if (_helpService != null)
                    _helpService = null;

                // Do not clear _provider.  SetSite will do it for us.

                _zombie = true;
            }
        }
Example #60
0
 internal KeyBindingService(SVsServiceProvider serviceProvider, IOptionsDialogService service)
 {
     _dte = serviceProvider.GetService<SDTE, _DTE>();
     _vsShell = serviceProvider.GetService<SVsShell, IVsShell>();
     _optionsDialogService = service;
 }