aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Package/Package/DteEventsHandler.cs
blob: 147f0eceb8f359db480dc0d775f8060d018211bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

using System;
using System.IO;
using System.Linq;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.VCProjectEngine;

using Tasks = System.Threading.Tasks;

namespace QtVsTools
{
    using Core;
    using Core.CMake;
    using Core.MsBuild;
    using Core.Options;
    using VisualStudio;
    using static Core.Common.Utils;

    internal class DteEventsHandler
    {
        private readonly DTE dte;
        private readonly SolutionEvents solutionEvents;
        private readonly DocumentEvents documentEvents;
        private readonly ProjectItemsEvents projectItemsEvents;
        private VCProjectEngineEvents vcProjectEngineEvents;
        private readonly CommandEvents f1HelpEvents;
        private WindowEvents windowEvents;
        private readonly OutputWindowEvents outputWindowEvents;

        public delegate void ProjectConfigurationDelegate(ProjectConfigurationEventArgs args);
        public event ProjectConfigurationDelegate ProjectConfigurationChanged;

        public DteEventsHandler(DTE _dte)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            dte = _dte;
            var events = dte.Events as Events2;

            documentEvents = events?.DocumentEvents;
            if (documentEvents != null)
                documentEvents.DocumentSaved += DocumentSaved;

            projectItemsEvents = events?.ProjectItemsEvents;
            if (projectItemsEvents != null) {
                projectItemsEvents.ItemAdded += ProjectItemsEvents_ItemAdded;
                projectItemsEvents.ItemRemoved += ProjectItemsEvents_ItemRemoved;
                projectItemsEvents.ItemRenamed += ProjectItemsEvents_ItemRenamed;
            }

            solutionEvents = events?.SolutionEvents;
            if (solutionEvents != null) {
                solutionEvents.ProjectAdded += SolutionEvents_ProjectAdded;
                solutionEvents.ProjectRemoved += SolutionEvents_ProjectRemoved;
                solutionEvents.Opened += SolutionEvents_Opened;
                solutionEvents.AfterClosing += SolutionEvents_AfterClosing;
            }

            if (dte.MainWindow?.Visible == false) {
                windowEvents = events?.WindowEvents;
                if (windowEvents != null)
                    windowEvents.WindowActivated += WindowEvents_WindowActivated;
            } else {
                VsMainWindowActivated(); // might happen without splash screen, direct .sln loading
            }

            outputWindowEvents = events?.OutputWindowEvents;
            if (outputWindowEvents != null)
                outputWindowEvents.PaneUpdated += OutputWindowEvents_PaneUpdated;

            if (VsShell.FolderWorkspace.OnActiveWorkspaceChanged != null)
                VsShell.FolderWorkspace.OnActiveWorkspaceChanged += OnActiveWorkspaceChangedAsync;

            f1HelpEvents = events?.CommandEvents[typeof(VSConstants.VSStd97CmdID).GUID.ToString("B"),
                (int)VSConstants.VSStd97CmdID.F1Help];
            if (f1HelpEvents != null)
                f1HelpEvents.BeforeExecute += F1HelpEvents_BeforeExecute;

            foreach (var vcProject in HelperFunctions.ProjectsInSolution(dte)) {
                if (MsBuildProject.GetOrAdd(vcProject) is { } project)
                    InitializeMsBuildProjectProject(project);
            }
        }

        private async Tasks.Task OnActiveWorkspaceChangedAsync(object sender, EventArgs args)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            OnActiveWorkspaceChanged();
        }

        public void OnActiveWorkspaceChanged()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var workspace = VsShell.FolderWorkspace?.CurrentWorkspace;
            if (workspace != null)
                CMakeProject.Load(workspace);
            else
                CMakeProject.Unload();
        }

        private void WindowEvents_WindowActivated(Window gotFocus, Window lostFocus)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (dte.MainWindow?.Visible == true) {
                windowEvents.WindowActivated -= WindowEvents_WindowActivated;
                windowEvents = null;
                VsMainWindowActivated();
            }
        }

        private static void VsMainWindowActivated()
        {
            if (QtVersionManager.GetVersions().Length == 0)
                Notifications.NoQtVersion.Show();
            if (QtOptionsPage.NotifyInstalled && TestVersionInstalled())
                Notifications.NotifyInstall.Show();
            if (QtOptionsPage.NotifySearchDevRelease)
                Notifications.NotifySearchDevRelease.Show();
            if (QtOptionsPage.AutoActivatePane)
                Messages.ActivateMessagePane();
        }

        private static bool TestVersionInstalled()
        {
            var newVersion = true;
            var versionFile = Path.Combine(PackageInstallPath, "lastversion.txt");
            if (File.Exists(versionFile)) {
                var lastVersion = File.ReadAllText(versionFile);
                newVersion = lastVersion != Version.PRODUCT_VERSION;
            }
            if (newVersion)
                File.WriteAllText(versionFile, Version.PRODUCT_VERSION);
            return newVersion;
        }

        private void OutputWindowEvents_PaneUpdated(EnvDTE.OutputWindowPane pane)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (pane is not { Name: "Solution" })
                return;
            var dteProjects = dte.Solution.Projects.Cast<Project>().ToList();
            foreach (var dteProject in dteProjects) {
                if (MsBuildProject.GetOrAdd(dteProject.Object as VCProject) is not { } project)
                    continue;
                if (project.GetPropertyValue("QT_CMAKE_TEMPLATE") != "true")
                    continue;
                outputWindowEvents.PaneUpdated -= OutputWindowEvents_PaneUpdated;
                pane.Clear();
                outputWindowEvents.PaneUpdated += OutputWindowEvents_PaneUpdated;
                return;
            }
        }

        private void F1HelpEvents_BeforeExecute(
            string guid, int id, object customIn, object customOut, ref bool cancelDefault)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (QtOptionsPage.TryQtHelpOnF1Pressed) {
                if (!QtHelp.ShowEditorContextHelp()) {
                    Messages.Print("No help match was found. You can still try to search online at "
                        + "https://doc.qt.io" + ".", false, true);
                }
                cancelDefault = true;
            }
        }

        public void Disconnect()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (documentEvents != null)
                documentEvents.DocumentSaved -= DocumentSaved;

            if (projectItemsEvents != null) {
                projectItemsEvents.ItemAdded -= ProjectItemsEvents_ItemAdded;
                projectItemsEvents.ItemRemoved -= ProjectItemsEvents_ItemRemoved;
                projectItemsEvents.ItemRenamed -= ProjectItemsEvents_ItemRenamed;
            }

            if (solutionEvents != null) {
                solutionEvents.ProjectAdded -= SolutionEvents_ProjectAdded;
                solutionEvents.Opened -= SolutionEvents_Opened;
                solutionEvents.AfterClosing -= SolutionEvents_AfterClosing;
            }

            if (vcProjectEngineEvents != null)
                vcProjectEngineEvents.ItemPropertyChange2 -= OnVcProjectEngineItemPropertyChange2;

            if (windowEvents != null)
                windowEvents.WindowActivated -= WindowEvents_WindowActivated;

            if (outputWindowEvents != null)
                outputWindowEvents.PaneUpdated -= OutputWindowEvents_PaneUpdated;
        }

        private void DocumentSaved(Document document)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (document.ProjectItem?.ContainingProject?.Object is not VCProject vcProject)
                return;

            if (MsBuildProject.GetOrAdd(vcProject) is not { } qtPro)
                return;

            if (qtPro.VcProject.Files is not IVCCollection files)
                return;

            if (files.Item(document.FullName) is not VCFile file)
                return;

            if (HelperFunctions.IsUicFile(file.Name) && !QtUic.HasUicItemType(file)) {
                QtUic.SetUicItemType(file);
                return;
            }

            if (HelperFunctions.IsQrcFile(file.Name) && !QtRcc.HasRccItemType(file)) {
                QtRcc.SetRccItemType(file);
                return;
            }

            if (!HelperFunctions.IsSourceFile(file.Name) && !HelperFunctions.IsHeaderFile(file.Name))
                return;

            if (HelperFunctions.HasQObjectDeclaration(file)) {
                if (!QtMoc.HasMocItemType(file))
                    QtMoc.SetMocItemType(file);
            } else {
                if (QtMoc.HasMocItemType(file))
                    QtMoc.RemoveMocItemType(file);
            }
        }

        private void ProjectItemsEvents_ItemAdded(ProjectItem projectItem)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (HelperFunctions.GetSelectedQtProject(dte) is not { } qtPro)
                return;

            if (qtPro.VcProject.Files is not IVCCollection projectFiles)
                return;

            var vcFile = projectFiles.Cast<VCFile>().FirstOrDefault(file =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                return string.Equals(file.Name, projectItem.Name, IgnoreCase);
            });

            var vcFileName = vcFile?.Name;
            if (string.IsNullOrEmpty(vcFileName))
                return;

            try {
                if (HelperFunctions.IsSourceFile(vcFileName)) {
                    if (vcFileName.StartsWith("moc_", IgnoreCase))
                        return;
                    if (vcFileName.StartsWith("qrc_", IgnoreCase)) {
                        // Do not use precompiled headers with these files
                        MsBuildProject.SetPCHOption(vcFile, pchOption.pchNone);
                        return;
                    }
                    var pcHeaderThrough = qtPro.GetPrecompiledHeaderThrough();
                    if (pcHeaderThrough != null) {
                        var pcHeaderCreator = pcHeaderThrough.Remove(pcHeaderThrough.LastIndexOf('.')) + ".cpp";
                        if (vcFileName.EndsWith(pcHeaderCreator, IgnoreCase)
                            && CxxStream.ContainsNotCommented(vcFile,
                                $"#include \"{pcHeaderThrough}\"", IgnoreCase, false)) {
                            //File is used to create precompiled headers
                            MsBuildProject.SetPCHOption(vcFile, pchOption.pchCreateUsingSpecific);
                            return;
                        }
                    }
                    if (HelperFunctions.HasQObjectDeclaration(vcFile))
                        QtMoc.SetMocItemType(vcFile);
                } else if (HelperFunctions.IsHeaderFile(vcFileName)) {
                    if (vcFileName.StartsWith("ui_", IgnoreCase))
                        return;
                    if (HelperFunctions.HasQObjectDeclaration(vcFile))
                        QtMoc.SetMocItemType(vcFile);
                } else if (HelperFunctions.IsUicFile(vcFileName)) {
                    QtUic.SetUicItemType(vcFile);
                    qtPro.Refresh();
                } else if (HelperFunctions.IsQrcFile(vcFileName)) {
                    QtRcc.SetRccItemType(vcFile);
                } else if (HelperFunctions.IsTranslationFile(vcFileName)) {
                    Translation.RunLUpdate(vcFile);
                }
            } catch {
                // ignored
            }
        }

        private void ProjectItemsEvents_ItemRemoved(ProjectItem projectItem)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (HelperFunctions.GetSelectedQtProject(dte) is not { } project)
                return;
            project.RemoveGeneratedFiles(projectItem.Name);
        }

        private void ProjectItemsEvents_ItemRenamed(ProjectItem projectItem, string oldName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (string.IsNullOrEmpty(oldName))
                return;
            if (HelperFunctions.GetSelectedQtProject(dte) is not { } project)
                return;

            project.RemoveGeneratedFiles(oldName);
            ProjectItemsEvents_ItemAdded(projectItem);
        }

        private void SolutionEvents_ProjectAdded(Project dteProject)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // Ignore non-VC projects and temp projects created by Qt/CMake wizard
            if (MsBuildProject.GetOrAdd(dteProject.Object as VCProject) is not { } project
                || project.GetPropertyValue("QT_CMAKE_TEMPLATE") == "true") {
                return;
            }

            InitializeMsBuildProjectProject(project);
        }

        private static void SolutionEvents_ProjectRemoved(Project dteProject)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            MsBuildProject.Remove(dteProject.FullName);
        }

        public void SolutionEvents_Opened()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            foreach (var vcProject in HelperFunctions.ProjectsInSolution(dte)) {
                if (MsBuildProject.GetOrAdd(vcProject) is { } project)
                    InitializeMsBuildProjectProject(project);
            }
        }

        private static void SolutionEvents_AfterClosing()
        {
            MsBuildProject.Reset();
        }

        // Retrieves the VCProjectEngine from the given project and registers a handler for
        // VCProjectEngineEvents.
        private void InitializeMsBuildProjectProject(MsBuildProject project)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            project.SolutionPath = dte.Solution.FullName;
            project.Refresh(); //forcefully update IntelliSense

            if (vcProjectEngineEvents != null)
                return;

            if (project.VcProject is not { VCProjectEngine: VCProjectEngine vcProjectEngine })
                return;

            vcProjectEngineEvents = vcProjectEngine.Events as VCProjectEngineEvents;
            if (vcProjectEngineEvents == null)
                return;
            try {
                vcProjectEngineEvents.ItemPropertyChange2 += OnVcProjectEngineItemPropertyChange2;
            } catch {
                Messages.DisplayErrorMessage("VCProjectEngine events could not be registered.");
            }
        }

        private void OnVcProjectEngineItemPropertyChange2(object item, string propertySheet,
            string itemType, string propertyName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (item is not VCConfiguration vcConfiguration)
                return;

            if (MsBuildProject.GetOrAdd(vcConfiguration.project as VCProject) is not { } project)
                return;

            if (!propertyName.StartsWith("Qt") || propertyName == "QtTouchProperty")
                return;

            project.Refresh(vcConfiguration.Name);
            ProjectConfigurationChanged?.Invoke(new ProjectConfigurationEventArgs
            {
                ProjectPath = project.VcProjectPath,
                ConfigurationName = vcConfiguration.Name
            });
        }
    }
}