aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Core/Options/QtOptionsPageSettings.cs
blob: 3e9caaeb8fdcdb49c1699143ff17b8003620999b (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
// 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.Collections.Generic;
using Microsoft.Win32;

namespace QtVsTools.Core.Options
{
    using Common;
    using QtVsTools.Common;

    public sealed class QtOptionsPageSettings : SettingsBase<QtOptionsPage>
    {
        public static QtOptionsPageSettings Instance => StaticLazy.Get(() => Instance, () => new());

        public override void SaveSettings()
        {
            using var key = Registry.CurrentUser.CreateSubKey(Resources.SettingsRegistryPath);
            if (key == null)
                return;

            try {
                InitializedEvent.Wait();
                foreach (var kvp in Settings) {
                    switch (kvp.Value) {
                    case null:
                        continue;
                    case bool kvpValue:
                        key.SetValue(kvp.Key, kvpValue ? 1 : 0);
                        break;
                    case QtOptionsPage.Timeout timeout:
                        key.SetValue(kvp.Key, Convert.ToInt32(timeout));
                        break;
                    default:
                        key.SetValue(kvp.Key, kvp.Value);
                        break;
                    }
                }
            } catch (Exception exception) {
                exception.Log();
            }
        }

        protected override Dictionary<string, object> LoadSettings()
        {
            using var registry = Registry.CurrentUser.OpenSubKey(Resources.SettingsRegistryPath);

            var loadedSettings = new Dictionary<string, object>();
            var properties = typeof(QtOptionsPage).GetProperties();

            foreach (var property in properties) {
                if (!Attribute.IsDefined(property, typeof(SettingsAttribute)))
                    continue;
                if (TryGetAttributeKey(property, out (string Key, object Default) tuple))
                    loadedSettings.Add(tuple.Key, registry?.GetValue(tuple.Key) ?? tuple.Default);
            }

            return loadedSettings;
        }

        private QtOptionsPageSettings() => Initialize();

        private static LazyFactory StaticLazy { get; } = new();
    }
}