/// <summary>
        /// Determines whether the language for the specified project item is included by options.
        /// </summary>
        /// <param name="projectItem">The project item.</param>
        /// <returns>True if the document language is included, otherwise false.</returns>
        private bool IsProjectItemLanguageIncludedByOptions(ProjectItem projectItem)
        {
            var extension = GetProjectItemExtension(projectItem);

            if (extension.Equals(".js", StringComparison.CurrentCultureIgnoreCase))
            {
                // Make an exception for JavaScript files - they may incorrectly return the HTML
                // language service.
                return(Settings.Default.Cleaning_IncludeJavaScript);
            }

            var languageService     = EditorFactory.GetLanguageService(extension);
            var languageServiceGuid = languageService?.ToLowerInvariant();

            switch (languageServiceGuid)
            {
            case "{694dd9b6-b865-4c5b-ad85-86356e9c88dc}": return(Settings.Default.Cleaning_IncludeCSharp);

            case "{b2f072b0-abc1-11d0-9d62-00c04fd9dfd9}": return(Settings.Default.Cleaning_IncludeCPlusPlus);

            case "{a764e898-518d-11d2-9a89-00c04f79efc3}": return(Settings.Default.Cleaning_IncludeCSS);

            case "{bc6dd5a5-d4d6-4dab-a00d-a51242dbaf1b}": return(Settings.Default.Cleaning_IncludeFSharp);

            case "{9bbfd173-9770-47dc-b191-651b7ff493cd}":
            case "{58e975a0-f8fe-11d2-a6ae-00104bcc7269}": return(Settings.Default.Cleaning_IncludeHTML);

            case "{59e2f421-410a-4fc9-9803-1f4e79216be8}": return(Settings.Default.Cleaning_IncludeJavaScript);

            case "{71d61d27-9011-4b17-9469-d20f798fb5c0}": return(Settings.Default.Cleaning_IncludeJavaScript);

            case "{18588c2a-9945-44ad-9894-b271babc0582}": return(Settings.Default.Cleaning_IncludeJSON);

            case "{7b22909e-1b53-4cc7-8c2b-1f5c5039693a}": return(Settings.Default.Cleaning_IncludeLESS);

            case "{16b0638d-251a-4705-98d2-5251112c4139}": return(Settings.Default.Cleaning_IncludePHP);

            case "{1c4711f1-3766-4f84-9516-43fa4169cc36}": return(Settings.Default.Cleaning_IncludePowerShell);

            case "{29c0d8e0-c01c-412b-bee8-7a7a253a31e6}": return(Settings.Default.Cleaning_IncludeR);

            case "{5fa499f6-2cec-435b-bfce-53bbe29f37f6}": return(Settings.Default.Cleaning_IncludeSCSS);

            case "{4a0dddb5-7a95-4fbf-97cc-616d07737a77}": return(Settings.Default.Cleaning_IncludeTypeScript);

            case "{e34acdc0-baae-11d0-88bf-00a0c9110049}": return(Settings.Default.Cleaning_IncludeVB);

            case "{cd53c9a1-6bc2-412b-be36-cc715ed8dd41}":
            case "{c9164055-039b-4669-832d-f257bd5554d4}": return(Settings.Default.Cleaning_IncludeXAML);

            case "{f6819a78-a205-47b5-be1c-675b3c7f0b8e}": return(Settings.Default.Cleaning_IncludeXML);

            default:
                OutputWindowHelper.DiagnosticWriteLine(
                    $"CodeCleanupAvailabilityLogic.IsProjectItemLanguageIncludedByOptions picked up an unrecognized language service guid '{languageServiceGuid}'");
                return(Settings.Default.Cleaning_IncludeEverythingElse);
            }
        }
 /// <summary>
 /// Removes the code model associated with the specified document if it exists.
 /// </summary>
 /// <param name="document">The document.</param>
 internal void RemoveCodeModel(Document document)
 {
     lock (_cache)
     {
         if (_cache.Remove(document.FullName))
         {
             OutputWindowHelper.DiagnosticWriteLine($"CodeModelCache.RemoveCodeModel from cache for '{document.FullName}'");
         }
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Marks the code model associated with the specified document as stale if it exists.
        /// </summary>
        /// <param name="document">The document.</param>
        internal void StaleCodeModel(Document document)
        {
            CodeModel codeModel;

            if (_cache.TryGetValue(document.FullName, out codeModel))
            {
                codeModel.IsStale = true;
                OutputWindowHelper.DiagnosticWriteLine($"CodeModelCache.StaleCodeModel in cache for '{document.FullName}'");
            }
        }
        /// <summary>
        /// Event raised when the build of an individual project is done.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="projectConfig">The project config.</param>
        /// <param name="platform">The platform.</param>
        /// <param name="solutionConfig">The solution config.</param>
        /// <param name="success">True if project build was successful, otherwise false.</param>
        private void BuildEvents_OnBuildProjConfigDone(string project, string projectConfig, string platform, string solutionConfig, bool success)
        {
            var buildProjConfigDone = BuildProjConfigDone;

            if (buildProjConfigDone != null)
            {
                OutputWindowHelper.DiagnosticWriteLine("BuildProgressEventListener.BuildProjConfigDone raised");

                buildProjConfigDone(project, projectConfig, platform, solutionConfig, success);
            }
        }
        /// <summary>
        /// Event raised when a build begins.
        /// </summary>
        /// <param name="scope">The scope.</param>
        /// <param name="action">The action.</param>
        private void BuildEvents_OnBuildBegin(vsBuildScope scope, vsBuildAction action)
        {
            var buildBegin = BuildBegin;

            if (buildBegin != null)
            {
                OutputWindowHelper.DiagnosticWriteLine("BuildProgressEventListener.BuildBegin raised");

                buildBegin(scope, action);
            }
        }
        /// <summary>
        /// Event raised when the build of an individual project begins.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="projectConfig">The project config.</param>
        /// <param name="platform">The platform.</param>
        /// <param name="solutionConfig">The solution config.</param>
        private void BuildEvents_OnBuildProjConfigBegin(string project, string projectConfig, string platform, string solutionConfig)
        {
            var buildProjConfigBegin = BuildProjConfigBegin;

            if (buildProjConfigBegin != null)
            {
                OutputWindowHelper.DiagnosticWriteLine("BuildProgressEventListener.BuildProjConfigBegin raised");

                buildProjConfigBegin(project, projectConfig, platform, solutionConfig);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Raises the window change event.
        /// </summary>
        /// <param name="document">The document that got focus, may be null.</param>
        private void RaiseWindowChange(Document document)
        {
            var onWindowChange = OnWindowChange;

            if (onWindowChange != null)
            {
                OutputWindowHelper.DiagnosticWriteLine($"WindowEventListener.OnWindowChange raised for '{(document != null ? document.FullName : "(null)")}'");

                onWindowChange(document);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// An event handler for a solution being closed.
        /// </summary>
        private void SolutionEvents_AfterClosing()
        {
            var onSolutionClosed = OnSolutionClosed;

            if (onSolutionClosed != null)
            {
                OutputWindowHelper.DiagnosticWriteLine("SolutionEventListener.OnSolutionClosed raised");

                onSolutionClosed();
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// An event handler for a document closing.
        /// </summary>
        /// <param name="document">The document that is closing.</param>
        private void DocumentEvents_DocumentClosing(Document document)
        {
            var onDocumentClosing = OnDocumentClosing;

            if (onDocumentClosing != null)
            {
                OutputWindowHelper.DiagnosticWriteLine($"DocumentEventListener.OnDocumentClosing raised for '{(document != null ? document.FullName : "(null)")}'");

                onDocumentClosing(document);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Raises the <see cref="CodeModelBuilt" /> event.
        /// </summary>
        /// <param name="codeModel">The code model.</param>
        private void RaiseCodeModelBuilt(CodeModel codeModel)
        {
            var codeModelBuilt = CodeModelBuilt;
            if (codeModelBuilt != null)
            {
                OutputWindowHelper.DiagnosticWriteLine(
                    $"CodeModelManager.CodeModelBuilt raised for '{codeModel.Document.FullName}'");

                codeModelBuilt(codeModel);
            }
        }
 /// <summary>
 ///     Attempts to retrieve the file name for the specified project item.
 /// </summary>
 /// <param name="projectItem">The project item.</param>
 /// <returns>The filename of the project item if available, otherwise null.</returns>
 internal static string GetFileName(this ProjectItem projectItem)
 {
     try
     {
         return(projectItem.FileNames[1]);
     }
     catch (Exception ex)
     {
         OutputWindowHelper.DiagnosticWriteLine("Unable to retrieve ProjectItem file name", ex);
         return(null);
     }
 }
Exemplo n.º 12
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress);

            await JoinableTaskFactory.RunAsync(VsTaskRunContext.UIThreadNormalPriority, async delegate
            {
                timer          = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds);
                timer.Elapsed += Timer_Elapsed;
                DTE.Events.SolutionEvents.AfterClosing += SolutionEvents_AfterClosing;
                DTE.Events.SolutionEvents.Opened       += SolutionEvents_Opened;
                var assemblyCatalog            = new AssemblyCatalog(typeof(GitLabPackage).Assembly);
                CompositionContainer container = new CompositionContainer(assemblyCatalog);
                container.ComposeParts(this);
                var mcs = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
                if (mcs != null)
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
                    try
                    {
                        foreach (var item in new[]
                        {
                            PackageIds.OpenMaster,
                            PackageIds.OpenBranch,
                            PackageIds.OpenRevision,
                            PackageIds.OpenRevisionFull,
                            PackageIds.OpenBlame,
                            PackageIds.OpenCommits,
                            PackageIds.OpenCreateSnippet,
                            PackageIds.OpenFromUrl
                        })
                        {
                            var menuCommandID           = new CommandID(PackageGuids.guidOpenOnGitLabCmdSet, (int)item);
                            var menuItem                = new OleMenuCommand(ExecuteCommand, menuCommandID);
                            menuItem.BeforeQueryStatus += MenuItem_BeforeQueryStatus;
                            mcs.AddCommand(menuItem);
                        }
                        var IssuesToolmenuCommandID           = new CommandID(PackageGuids.guidIssuesToolWindowPackageCmdSet, (int)PackageIds.IssuesToolWindowCommandId);
                        var IssuesToolmenuItem                = new OleMenuCommand(this.ShowToolWindow, IssuesToolmenuCommandID);
                        IssuesToolmenuItem.BeforeQueryStatus += MenuItem_BeforeQueryStatus;
                        IssuesToolmenuItem.Enabled            = false;
                        mcs.AddCommand(IssuesToolmenuItem);
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.DiagnosticWriteLine(ex.Message);
                    }
                }
                else
                {
                    OutputWindowHelper.DiagnosticWriteLine("mcs 为空");
                }
            });
        }
Exemplo n.º 13
0
        /// <summary>
        /// Determines whether the language for the specified document is included by options.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>True if the document language is included, otherwise false.</returns>
        private bool IsDocumentLanguageIncludedByOptions(Document document)
        {
            var projectItem = document.ProjectItem;
            var extension   = GetProjectItemExtension(projectItem);

            if (extension.Equals(".php", StringComparison.CurrentCultureIgnoreCase))
            {
                // Make an exception for PHP files - they may incorrectly return the HTML
                // language service.
                return(Settings.Default.Cleaning_IncludePHP);
            }

            switch (document.GetCodeLanguage())
            {
            case CodeLanguage.CPlusPlus: return(Settings.Default.Cleaning_IncludeCPlusPlus);

            case CodeLanguage.CSharp: return(Settings.Default.Cleaning_IncludeCSharp);

            case CodeLanguage.CSS: return(Settings.Default.Cleaning_IncludeCSS);

            case CodeLanguage.FSharp: return(Settings.Default.Cleaning_IncludeFSharp);

            case CodeLanguage.HTML: return(Settings.Default.Cleaning_IncludeHTML);

            case CodeLanguage.JavaScript: return(Settings.Default.Cleaning_IncludeJavaScript);

            case CodeLanguage.JSON: return(Settings.Default.Cleaning_IncludeJSON);

            case CodeLanguage.LESS: return(Settings.Default.Cleaning_IncludeLESS);

            case CodeLanguage.PHP: return(Settings.Default.Cleaning_IncludePHP);

            case CodeLanguage.PowerShell: return(Settings.Default.Cleaning_IncludePowerShell);

            case CodeLanguage.R: return(Settings.Default.Cleaning_IncludeR);

            case CodeLanguage.SCSS: return(Settings.Default.Cleaning_IncludeSCSS);

            case CodeLanguage.TypeScript: return(Settings.Default.Cleaning_IncludeTypeScript);

            case CodeLanguage.VisualBasic: return(Settings.Default.Cleaning_IncludeVB);

            case CodeLanguage.XAML: return(Settings.Default.Cleaning_IncludeXAML);

            case CodeLanguage.XML: return(Settings.Default.Cleaning_IncludeXML);

            default:
                OutputWindowHelper.DiagnosticWriteLine(
                    $"CodeCleanupAvailabilityLogic.IsDocumentLanguageIncludedByOptions picked up an unrecognized document language '{document.Language}'");
                return(Settings.Default.Cleaning_IncludeEverythingElse);
            }
        }
        /// <summary>
        /// Determines if the specified document can be cleaned up.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="allowUserPrompts">A flag indicating if user prompts should be allowed.</param>
        /// <returns>True if item can be cleaned up, otherwise false.</returns>
        internal bool CanCleanupDocument(Document document, bool allowUserPrompts = false)
        {
            if (!IsCleanupEnvironmentAvailable())
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupDocument returned false due to the cleanup environment not being available.");
                return(false);
            }

            if (document == null)
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupDocument returned false due to a null document.");
                return(false);
            }

            if (!IsDocumentLanguageIncludedByOptions(document))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupDocument returned false for '{document.FullName}' due to the document language not being included within CodeMaid Options.");
                return(false);
            }

            if (IsDocumentExcludedBecauseExternal(document, allowUserPrompts))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupDocument returned false for '{document.FullName}' due to the document being external to the solution.");
                return(false);
            }

            if (IsFileNameExcludedByOptions(document.FullName))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupDocument returned false for '{document.FullName}' due to the file name being excluded within CodeMaid Options.");
                return(false);
            }

            if (!IsFileNameIncludedByOptions(document.FullName))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupDocument returned false for '{document.FullName}' due to the file name not being included within CodeMaid Options.");
                return(false);
            }

            if (IsParentCodeGeneratorExcludedByOptions(document))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupDocument returned false for '{document.FullName}' due to a parent code generator.");
                return(false);
            }

            if (HasAutoGeneratedHeader(document))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupDocument returned false for '{document.FullName}' due to an auto-generated header.");
                return(false);
            }

            return(true);
        }
 /// <summary>
 ///     Attempts to retrieve the parent project item for the specified project item.
 /// </summary>
 /// <param name="projectItem">The project item.</param>
 /// <returns>The parent project item, otherwise null.</returns>
 internal static ProjectItem GetParentProjectItem(this ProjectItem projectItem)
 {
     try
     {
         var parentProjectItem = projectItem.Collection?.Parent as ProjectItem;
         return(parentProjectItem);
     }
     catch (Exception ex)
     {
         OutputWindowHelper.DiagnosticWriteLine("Unable to retrieve parent ProjectItem", ex);
         return(null);
     }
 }
 /// <summary>
 ///     Determines if the specified project item is a physical file.
 /// </summary>
 /// <param name="projectItem">The project item.</param>
 /// <returns>True if the project item is a physical file, otherwise false.</returns>
 internal static bool IsPhysicalFile(this ProjectItem projectItem)
 {
     try
     {
         return(string.Equals(projectItem.Kind, Constants.vsProjectItemKindPhysicalFile, StringComparison.OrdinalIgnoreCase));
     }
     catch (Exception ex)
     {
         // Some ProjectItem types (e.g. WiX) may throw an error when accessing the Kind member.
         OutputWindowHelper.DiagnosticWriteLine("Unable to determine if ProjectItem is a physical file", ex);
         return(false);
     }
 }
Exemplo n.º 17
0
        /// <summary 代码清理逻辑> Attempts to run code
        /// cleanup on the specified document.
        /// </summary> <param name="document">The
        /// document for cleanup.</param>
        internal void Cleanup(Document document)
        {
            if (!_codeCleanupAvailabilityLogic.CanCleanupDocument(document, true))
            {
                return;
            }

            // Make sure the document to be cleaned
            // up is active, required for some
            // commands like format document.
            document.Activate();

            // Check for designer windows being
            // active, which should not proceed
            // with cleanup as the code isn't truly active.
            if (document.ActiveWindow.Caption.EndsWith(" [Design]"))
            {
                return;
            }

            if (_package.ActiveDocument != document)
            {
                OutputWindowHelper.WarningWriteLine($"Activation was not completed before cleaning began for '{document.Name}'");
            }

            // Conditionally start cleanup with reorganization.
            if (Settings.Default.Reorganizing_RunAtStartOfCleanup)
            {
                _codeReorganizationManager.Reorganize(document);
            }

            new UndoTransactionHelper(_package, string.Format(Resources.CodeMaidCleanupFor0, document.Name)).Run(
                delegate
            {
                //通过判断文档对应的语言类型,调用对应的清理方法来执行
                var cleanupMethod = FindCodeCleanupMethod(document);
                if (cleanupMethod != null)
                {
                    OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupManager.Cleanup started for '{document.FullName}'");
                    _package.IDE.StatusBar.Text = string.Format(Resources.CodeMaidIsCleaning0, document.Name);

                    // Perform the set of
                    // configured cleanups
                    // based on the language.
                    cleanupMethod(document);

                    _package.IDE.StatusBar.Text = string.Format(Resources.CodeMaidCleaned0, document.Name);
                    OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupManager.Cleanup completed for '{document.FullName}'");
                }
            });
        }
Exemplo n.º 18
0
        /// <summary>
        /// Attempts to run code cleanup on the specified document.
        /// </summary>
        /// <param name="document">The document for cleanup.</param>
        /// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param>
        internal void Cleanup(Document document, bool isAutoSave = false)
        {
            if (!_codeCleanupAvailabilityLogic.ShouldCleanup(document, true))
            {
                return;
            }

            // Make sure the document to be cleaned up is active, required for some commands like
            // format document.
            document.Activate();

            if (_package.ActiveDocument != document)
            {
                OutputWindowHelper.WarningWriteLine(
                    string.Format("Activation was not completed before cleaning began for '{0}'", document.Name));
            }

            // Conditionally start cleanup with reorganization.
            if (Settings.Default.Reorganizing_RunAtStartOfCleanup)
            {
                _codeReorderManager.Reorganize(document, isAutoSave);
            }

            _undoTransactionHelper.Run(
                () => !(isAutoSave && Settings.Default.General_SkipUndoTransactionsDuringAutoCleanupOnSave),
                delegate
            {
                var cleanupMethod = FindCodeCleanupMethod(document);
                if (cleanupMethod != null)
                {
                    OutputWindowHelper.DiagnosticWriteLine(
                        string.Format("CodeCleanupManager.Cleanup started for '{0}'", document.FullName));

                    _package.IDE.StatusBar.Text = string.Format("CodeMaid is cleaning '{0}'...", document.Name);

                    // Perform the set of configured cleanups based on the language.
                    cleanupMethod(document, isAutoSave);

                    _package.IDE.StatusBar.Text = string.Format("CodeMaid cleaned '{0}'.", document.Name);

                    OutputWindowHelper.DiagnosticWriteLine(
                        string.Format("CodeCleanupManager.Cleanup completed for '{0}'", document.FullName));
                }
            },
                delegate(Exception ex)
            {
                OutputWindowHelper.ExceptionWriteLine(
                    string.Format("Stopped cleaning '{0}'", document.Name), ex);
                _package.IDE.StatusBar.Text = string.Format("CodeMaid stopped cleaning '{0}'.  See output window for more details.", document.Name);
            });
        }
Exemplo n.º 19
0
        /// <summary>
        /// Determines whether the language for the specified document is included by options.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>True if the document language is included, otherwise false.</returns>
        private bool IsDocumentLanguageIncludedByOptions(Document document)
        {
            var projectItem = document.ProjectItem;
            var extension   = GetProjectItemExtension(projectItem);

            if (extension.Equals(".php", StringComparison.CurrentCultureIgnoreCase))
            {
                // Make an exception for PHP files - they may incorrectly return the HTML
                // language service.
                return(Settings.Default.Cleaning_IncludePHP);
            }

            switch (document.Language)
            {
            case "Basic": return(Settings.Default.Cleaning_IncludeVB);

            case "CSharp": return(Settings.Default.Cleaning_IncludeCSharp);

            case "C/C++": return(Settings.Default.Cleaning_IncludeCPlusPlus);

            case "CSS": return(Settings.Default.Cleaning_IncludeCSS);

            case "F#": return(Settings.Default.Cleaning_IncludeFSharp);

            case "HTML":
            case "HTMLX": return(Settings.Default.Cleaning_IncludeHTML);

            case "JavaScript":
            case "JScript":
            case "Node.js": return(Settings.Default.Cleaning_IncludeJavaScript);

            case "JSON": return(Settings.Default.Cleaning_IncludeJSON);

            case "LESS": return(Settings.Default.Cleaning_IncludeLESS);

            case "PowerShell": return(Settings.Default.Cleaning_IncludePowerShell);

            case "SCSS": return(Settings.Default.Cleaning_IncludeSCSS);

            case "TypeScript": return(Settings.Default.Cleaning_IncludeTypeScript);

            case "XAML": return(Settings.Default.Cleaning_IncludeXAML);

            case "XML": return(Settings.Default.Cleaning_IncludeXML);

            default:
                OutputWindowHelper.DiagnosticWriteLine(
                    string.Format("CodeCleanupAvailabilityLogic.IsDocumentLanguageIncludedByOptions picked up an unrecognized document language '{0}'", document.Language));
                return(false);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Called when a message is broadcast to the environment window.
        /// </summary>
        /// <param name="msg">The notification message.</param>
        /// <param name="wParam">The word value parameter.</param>
        /// <param name="lParam">The long integer parameter.</param>
        /// <returns>S_OK if successful, otherwise an error code.</returns>
        public int OnBroadcastMessage(uint msg, IntPtr wParam, IntPtr lParam)
        {
            if (msg == WM_SYSCOLORCHANGE)
            {
                var environmentColorChanged = EnvironmentColorChanged;
                if (environmentColorChanged != null)
                {
                    OutputWindowHelper.DiagnosticWriteLine("ShellEventListener.EnvironmentColorChanged raised");

                    environmentColorChanged();
                }
            }

            return(VSConstants.S_OK);
        }
        /// <summary>
        /// Called when a document is about to be saved.
        /// </summary>
        /// <param name="docCookie">An abstract value representing the document about to be saved.</param>
        /// <returns>S_OK if successful, otherwise an error code.</returns>
        public int OnBeforeSave(uint docCookie)
        {
            var beforeSave = BeforeSave;

            if (beforeSave != null)
            {
                Document document = GetDocumentFromCookie(docCookie);

                OutputWindowHelper.DiagnosticWriteLine($"RunningDocumentTableEventListener.BeforeSave raised for '{(document != null ? document.FullName : "(null)")}'");

                beforeSave(document);
            }

            return(VSConstants.S_OK);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Called when a shell property has changed.
        /// </summary>
        /// <param name="propid">The id of the property that changed.</param>
        /// <param name="var">The new value of the property.</param>
        /// <returns>S_OK if successful, otherwise an error code.</returns>
        public int OnShellPropertyChange(int propid, object var)
        {
            // Check if the zombie state property of the shell has changed to false.
            if ((int)__VSSPROPID.VSSPROPID_Zombie == propid && ((bool)var == false))
            {
                var shellAvailable = ShellAvailable;
                if (shellAvailable != null)
                {
                    OutputWindowHelper.DiagnosticWriteLine("ShellEventListener.ShellAvailable raised");

                    shellAvailable();
                }
            }

            return(VSConstants.S_OK);
        }
        /// <summary>
        /// Called when a document has been saved.
        /// </summary>
        /// <param name="docCookie">An abstract value representing the document about to be saved.</param>
        /// <returns>S_OK if successful, otherwise an error code.</returns>
        public int OnAfterSave(uint docCookie)
        {
            var afterSave = AfterSave;

            if (afterSave != null)
            {
                Document document = GetDocumentFromCookie(docCookie);

                OutputWindowHelper.DiagnosticWriteLine(
                    string.Format("RunningDocumentTableEventListener.AfterSave raised for '{0}'", document != null ? document.FullName : "(null)"));

                afterSave(document);
            }

            return(VSConstants.S_OK);
        }
        /// <summary>
        ///     Determines if the specified project item is external to the solution.
        /// </summary>
        /// <param name="projectItem">The project item.</param>
        /// <returns>True if the project item is external, otherwise false.</returns>
        internal static bool IsExternal(this ProjectItem projectItem)
        {
            try
            {
                if (projectItem.Collection == null || !projectItem.IsPhysicalFile())
                {
                    return(true);
                }

                return(projectItem.Collection.OfType <ProjectItem>().All(x => x.Object != projectItem.Object));
            }
            catch (Exception ex)
            {
                OutputWindowHelper.DiagnosticWriteLine("Unable to determine if ProjectItem is external", ex);
                return(false);
            }
        }
Exemplo n.º 25
0
        protected override void Initialize()
        {
            base.Initialize();
            OutputWindowHelper.DiagnosticWriteLine("Initialize");
            timer          = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds);
            timer.Elapsed += Timer_Elapsed;
            DTE.Events.SolutionEvents.AfterClosing += SolutionEvents_AfterClosing;
            DTE.Events.SolutionEvents.Opened       += SolutionEvents_Opened;


            var assemblyCatalog            = new AssemblyCatalog(typeof(GitLabPackage).Assembly);
            CompositionContainer container = new CompositionContainer(assemblyCatalog);

            container.ComposeParts(this);
            var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (mcs != null)
            {
                foreach (var item in new[]
                {
                    PackageCommanddIDs.OpenMaster,
                    PackageCommanddIDs.OpenBranch,
                    PackageCommanddIDs.OpenRevision,
                    PackageCommanddIDs.OpenRevisionFull,
                    PackageCommanddIDs.OpenBlame,
                    PackageCommanddIDs.OpenCommits,
                    PackageCommanddIDs.CreateSnippet,
                })
                {
                    var menuCommandID = new CommandID(PackageGuids.guidOpenOnGitLabCmdSet, (int)item);
                    var menuItem      = new OleMenuCommand(ExecuteCommand, menuCommandID);
                    menuItem.BeforeQueryStatus += MenuItem_BeforeQueryStatus;
                    mcs.AddCommand(menuItem);
                    OutputWindowHelper.DiagnosticWriteLine("Initialize" + menuItem.Text);
                }
                var IssuesToolmenuCommandID = new CommandID(PackageGuids.IssuesToolWindowCmdSet, (int)PackageCommanddIDs.IssuesToolWindows);
                var IssuesToolmenuItem      = new OleMenuCommand(this.ShowToolWindow, IssuesToolmenuCommandID);
                IssuesToolmenuItem.BeforeQueryStatus += MenuItem_BeforeQueryStatus;
                mcs.AddCommand(IssuesToolmenuItem);
            }
            else
            {
                OutputWindowHelper.DiagnosticWriteLine("mcs 为空");
            }
        }
Exemplo n.º 26
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress);

            await JoinableTaskFactory.RunAsync(VsTaskRunContext.UIThreadNormalPriority, async delegate
            {
                // Added the following line to prevent the error "Due to high risk of deadlock you cannot call GetService from a background thread in an AsyncPackage derived class"
                var assemblyCatalog            = new AssemblyCatalog(typeof(GiteePackage).Assembly);
                CompositionContainer container = new CompositionContainer(assemblyCatalog);
                container.ComposeParts(this);
                var mcs = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
                if (mcs != null)
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
                    try
                    {
                        new [] {
                            PackageIds.OpenMaster,
                            PackageIds.OpenBranch,
                            PackageIds.OpenRevision,
                            PackageIds.OpenRevisionFull,
                            PackageIds.OpenBlame,
                            PackageIds.OpenCommits,
                            PackageIds.OpenFromUrl,
                            PackageIds.OpenCreateSnippet,
                            PackageIds.OpenWebIDE
                        }.ToList().ForEach(item =>
                        {
                            var menuCommandID           = new CommandID(PackageGuids.guidGitee4VSCmdSet, (int)item);
                            var menuItem                = new OleMenuCommand(ExecuteCommand, menuCommandID);
                            menuItem.BeforeQueryStatus += MenuItem_BeforeQueryStatus;
                            mcs.AddCommand(menuItem);
                        });
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.DiagnosticWriteLine(ex.Message);
                    }
                }
                else
                {
                    OutputWindowHelper.DiagnosticWriteLine("OleMenuCommandService  is null");
                }
            });
        }
Exemplo n.º 27
0
        /// <summary>
        /// Loads all lazy initialized values for items within the code model.
        /// </summary>
        /// <param name="codeModel">The code model.</param>
        private void LoadLazyInitializedValues(CodeModel codeModel)
        {
            try
            {
                OutputWindowHelper.DiagnosticWriteLine(
                    $"CodeModelManager.LoadLazyInitializedValues for '{codeModel.Document.FullName}'");

                foreach (var codeItem in codeModel.CodeItems)
                {
                    codeItem.LoadLazyInitializedValues();
                }
            }
            catch (Exception ex)
            {
                OutputWindowHelper.ExceptionWriteLine(
                    $"Unable to load lazy initialized values for '{codeModel.Document.FullName}'", ex);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Retrieves a <see cref="SetCodeItems"/> of CodeItems within the specified document. If
        /// the code items are already available they will be returned, otherwise an event will be
        /// raised once the code items have been asynchronously built.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="loadLazyInitializedValues">
        /// A flag indicating if lazy initialized values should be immediately loaded.
        /// </param>
        /// <returns>
        /// The set of code items within the document if already available, otherwise null.
        /// </returns>
        internal SetCodeItems RetrieveAllCodeItemsAsync(Document document, bool loadLazyInitializedValues = false)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            // If asynchronous loading has been disabled, redirect to the synchronous version.
            if (!Settings.Default.General_LoadModelsAsynchronously)
            {
                return(RetrieveAllCodeItems(document, loadLazyInitializedValues));
            }

            OutputWindowHelper.DiagnosticWriteLine(
                string.Format("CodeModelManager.RetrieveAllCodeItemsAsync for '{0}'", document.FullName));

            var codeModel = _codeModelCache.GetCodeModel(document);

            if (codeModel.IsBuilding)
            {
                // Exit out and wait for the event to be raised.
                return(null);
            }

            if (codeModel.IsStale)
            {
                // Asynchronously build the code items then raise an event.
                Task.Run(() =>
                {
                    BuildCodeItems(codeModel);

                    if (loadLazyInitializedValues)
                    {
                        LoadLazyInitializedValues(codeModel);
                    }

                    RaiseCodeModelBuilt(codeModel);
                });

                return(null);
            }

            return(codeModel.CodeItems);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Determines if the specified project item can be cleaned up.
        /// </summary>
        /// <param name="projectItem">The project item.</param>
        /// <returns>True if item can be cleaned up, otherwise false.</returns>
        internal bool CanCleanupProjectItem(ProjectItem projectItem)
        {
            if (!IsCleanupEnvironmentAvailable())
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupProjectItem returned false due to the cleanup environment not being available.");
                return(false);
            }

            if (projectItem == null)
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupProjectItem returned false due to a null project item.");
                return(false);
            }

            var projectItemFileName = projectItem.GetFileName();

            if (!projectItem.IsPhysicalFile())
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupProjectItem returned false for '{projectItemFileName}' due to the project item not being a physical file.");
                return(false);
            }

            if (!IsProjectItemLanguageIncludedByOptions(projectItem))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupProjectItem returned false for '{projectItemFileName}' due to the project item language not being included within CodeMaid Options.");
                return(false);
            }

            if (IsFileNameExcludedByOptions(projectItemFileName))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupProjectItem returned false for '{projectItemFileName}' due to the file name being excluded within CodeMaid Options.");
                return(false);
            }

            if (IsParentCodeGeneratorExcludedByOptions(projectItem))
            {
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupProjectItem returned false for '{projectItemFileName}' due to a parent code generator.");
                return(false);
            }

            return(true);
        }
Exemplo n.º 30
0
        /// <summary>
        /// An event handler for a line being changed.
        /// </summary>
        /// <param name="startPoint">The starting point of the change.</param>
        /// <param name="endPoint">The ending point of the change.</param>
        /// <param name="hint">A hint as to the type of change that has occurred.</param>
        private void TextEditorEvents_LineChanged(TextPoint startPoint, TextPoint endPoint, int hint)
        {
            var textDocument = startPoint?.Parent;

            if (textDocument == null)
            {
                return;
            }

            var document = startPoint.Parent.Parent;

            var onLineChanged = OnLineChanged;

            if (onLineChanged != null && document != null)
            {
                OutputWindowHelper.DiagnosticWriteLine($"TextEditorEventListener.OnLineChanged raised for '{document.FullName}'");

                onLineChanged(document);
            }
        }