public void Build() { // Get the VS Output Window if (null == mOutputWindowModel.VsOutputWindow) { if (VsServiceProvider.TryGetService(typeof(SVsOutputWindow), out object vsOutputWindow)) { mOutputWindowModel.VsOutputWindow = vsOutputWindow as IVsOutputWindow; } } if (null == mOutputWindowModel.Pane) { // Get the Pane object Guid generalPaneGuid = mOutputWindowModel.PaneGuid; mOutputWindowModel.VsOutputWindow.GetPane(ref generalPaneGuid, out IVsOutputWindowPane pane); // If pane does not exists, create it if (null == pane) { mOutputWindowModel.VsOutputWindow.CreatePane(ref generalPaneGuid, OutputWindowConstants.kPaneName, 0, 1); mOutputWindowModel.VsOutputWindow.GetPane(ref generalPaneGuid, out pane); } mOutputWindowModel.Pane = pane; } }
/// <summary> /// It is called before every command. Update the running state. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnBeforeClangCommand(object sender, EventArgs e) { if (!(sender is OleMenuCommand command)) { return; } if (IsAToolbarCommand(command)) { if (SolutionInfo.AreToolbarCommandsEnabled() == false) { command.Enabled = false; return; } } else if (SolutionInfo.AreContextMenuCommandsEnabled() == false) { command.Enabled = false; return; } if (VsServiceProvider.TryGetService(typeof(DTE), out object dte) && !(dte as DTE2).Solution.IsOpen) { command.Visible = command.Enabled = false; } else if (vsBuildRunning && command.CommandID.ID != CommandIds.kSettingsId) { command.Visible = command.Enabled = false; } else { command.Visible = command.Enabled = command.CommandID.ID != CommandIds.kStopClang ? !running : running; } }
public static void Text(string aText, int aFreezeStatusBar) { UIUpdater.Invoke(() => { if (!VsServiceProvider.TryGetService(typeof(SVsStatusbar), out object statusBarService) || null == statusBarService as IVsStatusbar) { return; } var statusBar = statusBarService as IVsStatusbar; // Make sure the status bar is not frozen if (VSConstants.S_OK != statusBar.IsFrozen(out int frozen)) { return; } if (0 != frozen) { statusBar.FreezeOutput(0); } // Set the status bar text statusBar.SetText(aText); // Freeze the status bar. statusBar.FreezeOutput(aFreezeStatusBar); // Clear the status bar text. if (0 == aFreezeStatusBar) { statusBar.Clear(); } }); }
/// <summary> /// It is called before every command. Update the running state. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnBeforeClangCommand(object sender, EventArgs e) { UIUpdater.Invoke(() => { if (!(sender is OleMenuCommand command)) { return; } if (VsServiceProvider.TryGetService(typeof(DTE), out object dte) && !(dte as DTE2).Solution.IsOpen) { command.Visible = command.Enabled = false; } else if (VsBuildRunning && command.CommandID.ID != CommandIds.kSettingsId) { command.Visible = command.Enabled = false; } else { command.Visible = command.Enabled = command.CommandID.ID != CommandIds.kStopClang ? !Running : Running; } }); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void RunClangCompile(object sender, EventArgs e) { if (mCommandsController.Running) { return; } mCommandsController.Running = true; var task = System.Threading.Tasks.Task.Run(() => { try { if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { DocumentsHandler.SaveActiveDocuments(); AutomationUtil.SaveDirtyProjects((dte as DTE2).Solution); } CollectSelectedItems(false, ScriptConstants.kAcceptedFileExtensions); RunScript(OutputWindowConstants.kComplileCommand); } catch (Exception exception) { VsShellUtilities.ShowMessageBox(AsyncPackage, exception.Message, "Error", OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } }).ContinueWith(tsk => mCommandsController.OnAfterClangCommand()); }
private async Task OnMSVCBuildSucceededAsync() { var runClang = SettingsProvider.CompilerSettingsModel.ClangAfterMSVC; if (runClang == false || SolutionInfo.ContainsCppProject() == false) { return; } var exitCode = int.MaxValue; if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { exitCode = (dte as DTE2).Solution.SolutionBuild.LastBuildInfo; } // VS compile detected errors and there is not necessary to run clang compile if (exitCode != 0) { return; } // Run clang compile after the VS compile succeeded OnBeforeClangCommand(CommandIds.kCompileId); await CompileCommand.Instance.RunClangCompileAsync(CommandIds.kCompileId, CommandUILocation.ContextMenu); OnAfterClangCommand(); }
public override void OnBuildDone(vsBuildScope Scope, vsBuildAction Action) { if (false == mExecuteCompile) { return; } var exitCode = int.MaxValue; if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { exitCode = (dte as DTE2).Solution.SolutionBuild.LastBuildInfo; } // VS compile detected errors and there is not necessary to run clang compile if (0 != exitCode) { mExecuteCompile = false; return; } // Run clang compile after the VS compile succeeded RunClangCompile(new object(), new EventArgs()); mExecuteCompile = false; }
private async System.Threading.Tasks.Task OnMSVCBuildSucceededAsync() { if (!CompileCommand.Instance.VsCompileFlag) { return; } var exitCode = int.MaxValue; if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { exitCode = (dte as DTE2).Solution.SolutionBuild.LastBuildInfo; } // VS compile detected errors and there is not necessary to run clang compile if (0 != exitCode) { CompileCommand.Instance.VsCompileFlag = false; return; } // Run clang compile after the VS compile succeeded OnBeforeClangCommand(CommandIds.kCompileId); await CompileCommand.Instance.RunClangCompileAsync(CommandIds.kCompileId, CommandUILocation.ContextMenu); CompileCommand.Instance.VsCompileFlag = false; OnAfterClangCommand(); }
private void OnBuildDoneClangCompile() { if (false == CompileCommand.Instance.VsCompileFlag) { return; } var exitCode = int.MaxValue; if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { exitCode = (dte as DTE2).Solution.SolutionBuild.LastBuildInfo; } // VS compile detected errors and there is not necessary to run clang compile if (0 != exitCode) { CompileCommand.Instance.VsCompileFlag = false; return; } // Run clang compile after the VS compile succeeded CompileCommand.Instance.RunClangCompile(CommandIds.kCompileId); CompileCommand.Instance.VsCompileFlag = false; }
public async Task LoadTestAsync(string guidString, bool expectedSuccess) { //Arrange await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IVsShell7 shell = (IVsShell7)ServiceProvider.GlobalProvider.GetService(typeof(SVsShell)); await UnitTestUtility.LoadPackageAsync(); VsServiceProvider.TryGetService(typeof(DTE), out object dteService); //Act var dte = dteService as DTE; Commands2 commands = dte.Commands as Commands2; Assumes.Present(shell); var guid = Guid.Parse(guidString); //Assert if (expectedSuccess) { await shell.LoadPackageAsync(ref guid); } else { await Assert.ThrowsAnyAsync <Exception>(async() => await shell.LoadPackageAsync(ref guid)); } }
// Open the changed files in the editor public static void Open(object source, FileSystemEventArgs e) { if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { (dte as DTE2).ExecuteCommand(kOpenCommand, e.FullPath); } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void RunClangTidy(object sender, EventArgs e) { if (mCommandsController.Running) { return; } mCommandsController.Running = true; mFix = SetTidyFixParameter(sender); var task = System.Threading.Tasks.Task.Run(() => { try { DocumentsHandler.SaveActiveDocuments(); if (!VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { return; } var dte2 = dte as DTE2; AutomationUtil.SaveDirtyProjects(dte2.Solution); CollectSelectedItems(false, ScriptConstants.kAcceptedFileExtensions); using (var silentFileController = new SilentFileChangerController()) { using (var fileChangerWatcher = new FileChangerWatcher()) { if (mFix || mTidyOptions.AutoTidyOnSave) { fileChangerWatcher.OnChanged += FileOpener.Open; string solutionFolderPath = dte2.Solution.FullName .Substring(0, dte2.Solution.FullName.LastIndexOf('\\')); fileChangerWatcher.Run(solutionFolderPath); FilePathCollector fileCollector = new FilePathCollector(); var filesPath = fileCollector.Collect(mItemsCollector.GetItems).ToList(); silentFileController.SilentFiles(filesPath); silentFileController.SilentFiles(dte2.Documents); } RunScript(OutputWindowConstants.kTidyCodeCommand, mTidyOptions, mTidyChecks, mTidyCustomChecks, mClangFormatView, mFix); } } } catch (Exception exception) { VsShellUtilities.ShowMessageBox(AsyncPackage, exception.Message, "Error", OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } finally { mForceTidyToFix = false; } }).ContinueWith(tsk => mCommandsController.OnAfterClangCommand()); }
/// <summary> /// Stop ignoring the file changes for a certain files /// </summary> public void Resume(SilentFileChangerModel aSilentFileChanger) { if (null == aSilentFileChanger) { return; } if (!aSilentFileChanger.IsSuspended || null == aSilentFileChanger.PersistDocData) { return; } if (null != aSilentFileChanger.PersistDocData && aSilentFileChanger.ReloadDocumentFlag) { aSilentFileChanger.PersistDocData.ReloadDocData(0); } if (!VsServiceProvider.TryGetService(typeof(SVsFileChangeEx), out object vsFileChangeService) || null == vsFileChangeService as IVsFileChangeEx) { return; } var vsFileChange = vsFileChangeService as IVsFileChangeEx; aSilentFileChanger.IsSuspended = false; ErrorHandler.ThrowOnFailure(vsFileChange.SyncFile(aSilentFileChanger.DocumentFileName)); ErrorHandler.ThrowOnFailure(vsFileChange.IgnoreFile(0, aSilentFileChanger.DocumentFileName, 0)); if (aSilentFileChanger.FileChangeControl != null) { ErrorHandler.ThrowOnFailure(aSilentFileChanger.FileChangeControl.IgnoreFileChanges(0)); } }
public CommandController(AsyncPackage aAsyncPackage) { if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var dte2 = dte as DTE2; mCommand = dte2.Commands as Commands2; } }
public void RunClangTidy(int aCommandId) { if (mCommandsController.Running) { return; } mCommandsController.Running = true; var task = System.Threading.Tasks.Task.Run(() => { try { DocumentsHandler.SaveActiveDocuments(); if (!VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { return; } var dte2 = dte as DTE2; AutomationUtil.SaveDirtyProjects(dte2.Solution); CollectSelectedItems(false, ScriptConstants.kAcceptedFileExtensions); using (var silentFileController = new SilentFileChangerController()) { using (var fileChangerWatcher = new FileChangerWatcher()) { var tidySettings = SettingsProvider.GetSettingsPage(typeof(ClangTidyOptionsView)) as ClangTidyOptionsView; if (CommandIds.kTidyFixId == aCommandId || tidySettings.AutoTidyOnSave) { fileChangerWatcher.OnChanged += FileOpener.Open; string solutionFolderPath = dte2.Solution.FullName .Substring(0, dte2.Solution.FullName.LastIndexOf('\\')); fileChangerWatcher.Run(solutionFolderPath); FilePathCollector fileCollector = new FilePathCollector(); var filesPath = fileCollector.Collect(mItemsCollector.GetItems).ToList(); silentFileController.SilentFiles(filesPath); silentFileController.SilentFiles(dte2.Documents); } RunScript(aCommandId); } } } catch (Exception exception) { VsShellUtilities.ShowMessageBox(AsyncPackage, exception.Message, "Error", OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } }).ContinueWith(tsk => DispatcherHandler.Invoke(() => mCommandsController.OnAfterClangCommand(), DispatcherPriority.Background)); }
private void ShowToolbare() { if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var cbs = ((CommandBars)(dte as DTE2).CommandBars); CommandBar cb = cbs["Clang Power Tools"]; cb.Visible = true; } }
/// <summary> /// Create a new instance of silent file changer model /// </summary> public void Build() { var docData = IntPtr.Zero; try { if (!VsServiceProvider.TryGetService(typeof(SVsRunningDocumentTable), out object vsRunningDocTable) || null == vsRunningDocTable as IVsRunningDocumentTable) { return; } ErrorHandler.ThrowOnFailure((vsRunningDocTable as IVsRunningDocumentTable).FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, mSilentFileChangerModel.DocumentFileName, out IVsHierarchy hierarchy, out uint itemId, out docData, out uint docCookie)); if ((docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL) || docData == IntPtr.Zero) { return; } if (!VsServiceProvider.TryGetService(typeof(SVsFileChangeEx), out object vsFileChange) || null == vsFileChange as IVsFileChangeEx) { return; } ErrorHandler.ThrowOnFailure((vsFileChange as IVsFileChangeEx).IgnoreFile(0, mSilentFileChangerModel.DocumentFileName, 1)); if (docData == IntPtr.Zero) { return; } var unknown = Marshal.GetObjectForIUnknown(docData); if (!(unknown is IVsPersistDocData)) { return; } mSilentFileChangerModel.PersistDocData = (IVsPersistDocData)unknown; if (!(mSilentFileChangerModel.PersistDocData is IVsDocDataFileChangeControl)) { return; } mSilentFileChangerModel.FileChangeControl = mSilentFileChangerModel.PersistDocData as IVsDocDataFileChangeControl; } catch (InvalidCastException e) { Trace.WriteLine("Exception" + e.Message); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } }
/// <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 Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { // Switches to the UI thread in order to consume some services used in command initialization await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await RegisterVsServicesAsync(); TaskErrorViewModel.Errors.Clear(); SquiggleViewModel.Squiggles.Clear(); mCommandController = new CommandController(this); CommandTestUtility.CommandController = mCommandController; var vsOutputWindow = VsServiceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; mOutputWindowController = new OutputWindowController(); mOutputWindowController.Initialize(this, vsOutputWindow); mRunningDocTableEvents = new RunningDocTableEvents(this); mErrorWindowController = new ErrorWindowController(this); #region Get Pointer to IVsSolutionEvents if (VsServiceProvider.TryGetService(typeof(SVsSolution), out object vsSolutionService)) { var vsSolution = vsSolutionService as IVsSolution; UnadviseSolutionEvents(vsSolution); AdviseSolutionEvents(vsSolution); } #endregion // Get the build and command events from DTE if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var dte2 = dte as DTE2; mBuildEvents = dte2.Events.BuildEvents; mCommandEvents = dte2.Events.CommandEvents; mDteEvents = dte2.Events.DTEEvents; } mSettingsHandler = new SettingsHandler(); mSettingsHandler.InitializeSettings(); await mCommandController.InitializeCommandsAsync(this); mSettingsProvider = new SettingsProvider(); RegisterToEvents(); LicenseController mLicenseController = new LicenseController(); await mLicenseController.CheckLicenseAsync(); await base.InitializeAsync(cancellationToken, progress); }
public static ProjectItem GetProjectItemOfActiveWindow() { if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var activeWindow = (dte as DTE2).ActiveWindow; activeWindow.Activate(); return(activeWindow.ProjectItem); } return(null); }
/// <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 Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { // Switches to the UI thread in order to consume some services used in command initialization await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await RegisterVsServicesAsync(); mCommandController = new CommandController(this); CommandTestUtility.CommandController = mCommandController; var vsOutputWindow = VsServiceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; mOutputWindowController = new OutputWindowController(); mOutputWindowController.Initialize(this, vsOutputWindow); mRunningDocTableEvents = new RunningDocTableEvents(this); mErrorWindowController = new ErrorWindowController(this); #region Get Pointer to IVsSolutionEvents if (VsServiceProvider.TryGetService(typeof(SVsSolution), out object vsSolutionService)) { var vsSolution = vsSolutionService as IVsSolution; UnadviseSolutionEvents(vsSolution); AdviseSolutionEvents(vsSolution); } #endregion // Get-Set the build and command events from DTE if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var dte2 = dte as DTE2; mBuildEvents = dte2.Events.BuildEvents; mCommandEvents = dte2.Events.CommandEvents; mDteEvents = dte2.Events.DTEEvents; windowEvents = dte2.Events.WindowEvents; } var settingsHandler = new SettingsHandler(); settingsHandler.InitializeSettings(); await settingsHandler.InitializeAccountSettingsAsync(); string version = SettingsProvider.GeneralSettingsModel.Version; ShowToolbar(version); UpdateVersion(version); //.SafeFireAndForget(); await mCommandController.InitializeCommandsAsync(this); RegisterToEvents(); await base.InitializeAsync(cancellationToken, progress); }
public async Task FileChangeService_SuccessfulRegistrationAsync() { //Arrange await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); await UnitTestUtility.LoadPackageAsync(); VsServiceProvider.TryGetService(typeof(SVsFileChangeEx), out object fileChangeService); // Assert Assert.NotNull(fileChangeService as IVsFileChangeEx); }
public void Show() { var outputWindow = mOutputWindowBuilder.GetResult(); UIUpdater.Invoke(() => { outputWindow.Pane.Activate(); if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { (dte as DTE2).ExecuteCommand("View.Output", string.Empty); } }); }
/// <summary> /// Get the name of the active document /// </summary> public static List <string> GetDocumentsToIgnore() { List <string> documentsToIgnore = new List <string>(); DTE vsServiceProvider = VsServiceProvider.TryGetService(typeof(DTE), out object dte) ? (dte as DTE) : null; SelectedItems selectedDocuments = vsServiceProvider.SelectedItems; for (int i = 1; i <= selectedDocuments.Count; i++) { documentsToIgnore.Add(selectedDocuments.Item(i).Name); } return(documentsToIgnore); }
public void CollectSelectedFiles(ProjectItem aProjectItem) { try { // if the command has been given from tab file // will be just one file selected if (null != aProjectItem) { AddProjectItem(aProjectItem); return; } // the command has been given from Solution Explorer or toolbar Array selectedItems = null; if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { selectedItems = (dte as DTE2).ToolWindows.SolutionExplorer.SelectedItems as Array; } if (null == selectedItems || 0 == selectedItems.Length) { return; } foreach (UIHierarchyItem item in selectedItems) { if (item.Object is Solution) { GetProjectsFromSolution(item.Object as Solution); } else if (item.Object is Project) { AddProject(item.Object as Project); } else if (item.Object is ProjectItem) { GetProjectItem(item.Object as ProjectItem); } } } catch (Exception) { } }
private void ShowToolbar(string version) { // Detect the first install if (!string.IsNullOrWhiteSpace(version)) { return; } // Show the toolbar on the first install if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var cbs = ((CommandBars)(dte as DTE2).CommandBars); CommandBar cb = cbs["Clang Power Tools"]; cb.Enabled = true; cb.Visible = true; } }
public void RunStopClangCommand() { System.Threading.Tasks.Task.Run(() => { try { mRunningProcesses.Kill(); if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { string solutionPath = (dte as DTE2).Solution.FullName; string solutionFolder = solutionPath.Substring(0, solutionPath.LastIndexOf('\\')); mPCHCleaner.Remove(solutionFolder); } mDirectoriesPath.Clear(); } catch (Exception) { } }); }
public void CollectActiveProjectItem() { try { DTE vsServiceProvider = VsServiceProvider.TryGetService(typeof(DTE), out object dte) ? (dte as DTE) : null; Document activeDocument = vsServiceProvider.ActiveDocument; if (activeDocument != null) { CurrentProjectItem activeProjectItem = new CurrentProjectItem(activeDocument.ProjectItem); items.Add(activeProjectItem); } } catch (Exception e) { throw new Exception(e.Message); } }
public static void Animation(vsStatusAnimation aAnimation, int aEnableAnimation) { UIUpdater.Invoke(() => { if (!VsServiceProvider.TryGetService(typeof(SVsStatusbar), out object statusBarService) || null == statusBarService as IVsStatusbar) { return; } var statusBar = statusBarService as IVsStatusbar; // Use the standard Visual Studio icon for building. object icon = (short)Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Build; // Display the icon in the Animation region. statusBar.Animation(aEnableAnimation, ref icon); }); }
private Document FindDocumentByCookie(uint docCookie) { Document document = null; try { var documentInfo = mRunningDocumentTable.GetDocumentInfo(docCookie); if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { document = (dte as DTE).Documents.Cast <Document>().FirstOrDefault(doc => doc.FullName == documentInfo.Moniker); } } catch (Exception) { } return(document); }
public void Show() { if (!SettingsProvider.CompilerSettingsModel.ShowOutputWindow) { return; } var outputWindow = outputWindowBuilder.GetResult(); UIUpdater.InvokeAsync(() => { outputWindow.Pane.Activate(); if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { (dte as DTE2).ExecuteCommand("View.Output", string.Empty); } VsWindowController.Activate(VsWindowController.PreviousWindow); }).SafeFireAndForget(); }