aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Wizards/Util/FileExistsInFilterValidationRule.cs
blob: f11d74625e40aeef514ffc358bc963ad103031f9 (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
// 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.Globalization;
using System.Linq;
using System.Windows.Controls;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace QtVsTools.Wizards.Util
{
    using Core;
    using VisualStudio;

    internal class FileExistsInFilterValidationRule : VCLanguageManagerValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (value is not string @string)
                return new ValidationResult(false, @"Invalid file name.");

            if (GetSelectedDteProject() is not { } project)
                return ValidationResult.ValidResult;

            var files = HelperFunctions.GetProjectFiles(project, Filter);
            if (files == null || files.Count == 0)
                return ValidationResult.ValidResult;

            var fileName = @string.ToUpperInvariant();
            return files.FirstOrDefault(x => x.ToUpperInvariant() == fileName) == null
                ? ValidationResult.ValidResult
                : new ValidationResult(false, @"File already exists.");
        }

        public FilesToList Filter { get; set; }

        private static Project GetSelectedDteProject()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (VsServiceProvider.GetService<SDTE, DTE>() is not { } dte)
                return null;

            try {
                if (dte.ActiveSolutionProjects is not Array projects || projects.Length == 0)
                    return null;
                return projects.GetValue(0) as Project;
            } catch (Exception exception) {
                exception.Log();
            }
            return null;
        }
    }
}