aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Core/QtVersionManager.cs
blob: 808520494831c5fb6b6253611ff8c3e3eec5f91f (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
// 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 Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.VCProjectEngine;
using Microsoft.Win32;

namespace QtVsTools.Core
{
    using MsBuild;
    using static Common.Utils;

    /// <summary>
    /// Summary description for QtVersionManager.
    /// </summary>
    public static class QtVersionManager
    {
        private const string VersionsKey = "Versions";

        public static string[] GetVersions()
        {
            var key = Registry.CurrentUser.OpenSubKey(Resources.RegistryPath, false);
            if (key == null)
                return Array.Empty<string>();
            var versionKey = key.OpenSubKey(VersionsKey, false);
            return versionKey?.GetSubKeyNames() ?? Array.Empty<string>();
        }

        public static string GetInstallPath(string version)
        {
            if (version == "$(DefaultQtVersion)")
                version = GetDefaultVersion();
            if (version == "$(QTDIR)")
                return Environment.GetEnvironmentVariable("QTDIR");
            if (string.IsNullOrEmpty(version))
                return null;
            var key = Registry.CurrentUser.OpenSubKey(Resources.RegistryPath, false);
            var versionKey = key?.OpenSubKey(Path.Combine(VersionsKey, version), false);
            return versionKey?.GetValue("InstallDir") as string;
        }

        public static string GetInstallPath(MsBuildProject project)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var version = project?.QtVersion;
            if (version == "$(DefaultQtVersion)")
                version = GetDefaultVersion();
            return version == null ? null : GetInstallPath(version);
        }

        /// <summary>
        /// Sanitizes the provided version name by removing leading and trailing whitespaces,
        /// and replacing backslashes with underscores.
        /// </summary>
        /// <param name="name">The version name to be sanitized.</param>
        /// <returns>A sanitized version of the input name.</returns>
        public static string SanitizeVersionName(string name)
        {
            return name?.Trim().Replace('\\', '_');
        }

        public static void SaveVersion(string versionName, string path, bool checkPath = true)
        {
            var verName = SanitizeVersionName(versionName);
            if (string.IsNullOrEmpty(verName))
                return;
            var dir = string.Empty;
            if (verName != "$(QTDIR)") {
                DirectoryInfo di;
                try {
                    di = new DirectoryInfo(path);
                } catch {
                    di = null;
                }
                if (di?.Exists == true) {
                    dir = di.FullName;
                } else if (!checkPath) {
                    dir = path;
                } else {
                    return;
                }
            }

            using var key = Registry.CurrentUser.CreateSubKey(Resources.RegistryPath);
            if (key == null) {
                Messages.Print("ERROR: root registry key creation failed");
                return;
            }

            using var versionKey = key.CreateSubKey(Path.Combine(VersionsKey, verName));
            if (versionKey == null) {
                Messages.Print("ERROR: version registry key creation failed");
            } else {
                versionKey.SetValue("InstallDir", dir);
            }
        }

        public static bool HasVersion(string versionName)
        {
            if (string.IsNullOrEmpty(versionName))
                return false;
            return Registry.CurrentUser.OpenSubKey(Path.Combine(Resources.VersionsRegistryPath,
                versionName), false) != null;
        }

        public static void RemoveVersion(string versionName)
        {
            var key = Registry.CurrentUser.OpenSubKey(Resources.VersionsRegistryPath, true);
            if (key == null)
                return;
            key.DeleteSubKey(versionName);
            key.Close();
        }

        private static bool IsVersionAvailable(string version)
        {
            return GetVersions().Any(ver => version == ver);
        }

        public static void SaveProjectQtVersion(MsBuildProject project, string version)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!IsVersionAvailable(version) && version != "$(DefaultQtVersion)")
                return;

            if (project?.VcProject.Configurations is not IVCCollection configurations)
                return;

            foreach (VCConfiguration3 config in configurations)
                config.SetPropertyValue("QtSettings", true, "QtInstall", version);
        }

        public static string GetDefaultVersion()
        {
            var defaultVersion = GetDefaultVersionName();
            if (defaultVersion == null) {
                var key = Registry.CurrentUser.OpenSubKey(Resources.VersionsRegistryPath, false);
                if (key != null) {
                    var versions = GetVersions();
                    if (versions is { Length: > 0 })
                        defaultVersion = versions[versions.Length - 1];
                    if (defaultVersion != null)
                        SaveDefaultVersion(defaultVersion);
                }
                if (defaultVersion == null) {
                    // last fallback... try QTDIR
                    var qtDir = Environment.GetEnvironmentVariable("QTDIR");
                    if (string.IsNullOrEmpty(qtDir))
                        return null;
                    var name = Path.GetFileName(qtDir);
                    SaveVersion(name, Path.GetFullPath(qtDir));
                    if (SaveDefaultVersion(name))
                        defaultVersion = name;
                }
            }
            return VersionExists(defaultVersion) ? defaultVersion : null;
        }

        public static string GetDefaultVersionName()
        {
            try {
                return Registry.CurrentUser.OpenSubKey(Resources.VersionsRegistryPath)
                    ?.GetValue("DefaultQtVersion") as string;
            } catch (Exception exception) {
                Messages.Print("Cannot read the name of the default Qt version.");
                exception.Log();
            }
            return null;
        }

        public static string GetDefaultVersionInstallPath()
        {
            try {
                var defaultVersion = GetDefaultVersionName();
                if (string.IsNullOrEmpty(defaultVersion))
                    return Path.GetFileName(Environment.GetEnvironmentVariable("QTDIR"));

                return Registry.CurrentUser.OpenSubKey(
                    $"{Resources.VersionsRegistryPath}\\{defaultVersion}")?
                    .GetValue("InstallDir") as string;
            } catch (Exception exception) {
                Messages.Print("Cannot read the install path of the default Qt version.");
                exception.Log();
            }
            return null;
        }

        public static bool SaveDefaultVersion(string version)
        {
            if (version == "$(DefaultQtVersion)")
                return false;
            var key = Registry.CurrentUser.CreateSubKey(Resources.VersionsRegistryPath);
            if (key == null)
                return false;

            version = SanitizeVersionName(version);
            if (string.IsNullOrEmpty(version))
                return false;
            key.SetValue("DefaultQtVersion", version);
            return true;
        }

        public static bool VersionExists(string version)
        {
            if (version == "$(DefaultQtVersion)")
                version = GetDefaultVersion();
            if (string.IsNullOrEmpty(version))
                return false;

            var regExp = new System.Text.RegularExpressions.Regex(@"\$\(.*\)");
            return regExp.IsMatch(version) || Directory.Exists(GetInstallPath(version));
        }

        public static void MoveRegisteredQtVersions()
        {
            try {
                if (Registry.CurrentUser.OpenSubKey(Resources.ObsoleteRegistryPath, true)
                    is not { } key)
                    return;

                const string valueName = "Copied";
                if (key.GetValue(valueName) != null)
                    return;

                // TODO v3.2.0: Use MoveRegistryKeys and delete source keys
                CopyRegistryKeys(Resources.ObsoleteRegistryPath, Resources.RegistryPath);
                MoveRegistryKeys(Resources.RegistryPath + "\\Qt5VS2017",
                    Resources.SettingsRegistryPath);

                key.SetValue(valueName, "");
            } catch (Exception exception) {
                exception.Log();
            }
        }
    }
}