chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Linq;
 
namespace OpenTap
{
    class ComponentSettingsContext
    {
        static readonly TraceSource log = Log.CreateSource("Settings");
 
        readonly Memorizer<Type, ComponentSettings> objectCache;
        readonly Dictionary<string, string> groupDir = new Dictionary<string, string>();
        readonly Queue<TapSerializer> flushQueues = new Queue<TapSerializer>();
 
        public bool readOnlyContext = false;
 
        public ComponentSettingsContext()
        {
            objectCache = new Memorizer<Type, ComponentSettings>(Load);
        }
 
        string settingsDirectoryRoot = Path.Combine(ExecutorClient.ExeDir, "Settings");
 
        void Invalidate(IList<ComponentSettings> setting)
        {
            // Settings can be co-dependent. Example: Connections and Instruments.
            // So we need to invalidate all the settings,  invoke the event afterwards.
            foreach (var componentSetting in setting)
                objectCache.Invalidate(componentSetting.GetType());
            foreach (var componentSetting in setting)
                componentSetting.InvokeInvalidate();
        }
 
        public void InvalidateAllSettings()
        {
            var cachedComponentSettings = objectCache.GetResults()
                .Where(x => x != null)
                .ToArray();
            Invalidate(cachedComponentSettings);
        }
 
        public void SaveAllCurrentSettings()
        {
            foreach (var cacheType in xmlCache.Keys.ToArray())
                GetCurrent(cacheType);
            foreach (var comp in objectCache.GetResults().Where(x => x != null))
                Save(comp);
        }
 
        public event EventHandler CacheInvalidated;
 
 
        /// <summary> Directory root for platform settings. </summary>    
        public string SettingsDirectoryRoot
        {
            get => settingsDirectoryRoot;
            set
            {
                settingsDirectoryRoot = value;
                InvalidateAllSettings();
            }
        }
 
        public void Reload() => CacheInvalidated?.Invoke(this, new EventArgs());
 
        public void Invalidate(Type t) => Invalidate(ComponentSettings.GetCurrent(t).AsSingle());
 
        public string GetSaveFilePath(Type type)
        {
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            if (type.DescendsTo(typeof(ComponentSettings)) == false)
                throw new ArgumentException(
                    "Type must inherit from ComponentSettings, otherwise it does not have a settings file.",
                    nameof(type));
            var settingsGroup = type.GetAttribute<SettingsGroupAttribute>();
 
            bool isProfile = settingsGroup?.Profile ?? false;
            string groupName = settingsGroup == null ? "" : settingsGroup.GroupName;
 
            // DisplayAttribute.GetFullName() joins the groups with ' \ ', but adding this space makes the save path invalid.
            var disp = type.GetDisplayAttribute();
            var groups = disp.Group.Length == 0 ? new[] { disp.Name } : disp.Group.Append(disp.Name);
            string fullName = string.Join("\\", groups);
 
            return Path.Combine(GetSettingsDirectory(groupName, isProfile),
                fullName + ".xml");
        }
 
        public void Save(ComponentSettings setting)
        {
            if (readOnlyContext) throw new Exception("Cannot save a read-only component settings context");
            EnsureSettingsDirectoryExists(setting.GroupName, setting.profile);
 
            string path = GetSaveFilePath(setting.GetType());
            string dir = Path.GetDirectoryName(path);
            if (dir != "" && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            var sw = Stopwatch.StartNew();
 
            using (var str = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                using (var xmlWriter =
                    System.Xml.XmlWriter.Create(str, new System.Xml.XmlWriterSettings { Indent = true }))
                    new TapSerializer().Serialize(xmlWriter, setting);
            }
 
            log.Debug(sw, "Saved {0} to {1}", setting.GetType().Name, path);
        }
 
        public void EnsureSettingsDirectoryExists(string groupName, bool isProfile = true)
        {
            if (!Directory.Exists(SettingsDirectoryRoot))
                Directory.CreateDirectory(SettingsDirectoryRoot);
            if (!Directory.Exists(GetSettingsDirectory(groupName, isProfile)))
                Directory.CreateDirectory(GetSettingsDirectory(groupName, isProfile));
        }
 
        /// <summary>
        /// The directory where the settings are loaded from / saved to.
        /// </summary>
        /// <param name="groupName">Name of the settings group.</param>
        /// <param name="isProfile">If the settings group uses profiles, we load the default profile.</param>
        /// <returns></returns>
        public string GetSettingsDirectory(string groupName, bool isProfile = true)
        {
            if (groupName == null)
                throw new ArgumentNullException(nameof(groupName));
            if (isProfile == false)
                return Path.Combine(SettingsDirectoryRoot, groupName);
            if (!groupDir.ContainsKey(groupName))
            {
                var file = Path.Combine(SettingsDirectoryRoot, groupName, "CurrentProfile");
 
                if (File.Exists(file))
                    groupDir[groupName] = File.ReadAllText(file);
                else
                    groupDir[groupName] = "Default";
            }
 
 
            return Path.Combine(SettingsDirectoryRoot, groupName, groupDir[groupName]);
        }
 
        public ComponentSettings GetCurrent(Type settingsType)
        {
            lock (flushQueues)
            {
                if (flushQueues.Count == 0)
                {
                    var result = objectCache.Invoke(settingsType);
                    while (flushQueues.Count > 0)
                        flushQueues.Dequeue().Flush();
                    return result;
                }
            }
 
            return objectCache.Invoke(settingsType);
        }
 
        public void SetCurrent(Stream xmlFileStream, out IEnumerable<XmlError> errors)
        {
            xmlFileStream.Position = 0;
            using (var mem = new MemoryStream())
            {
                xmlFileStream.CopyTo(mem);
                mem.Position = 0;
                try
                {
                    var doc = XDocument.Load(mem, LoadOptions.SetLineInfo);
                    if (doc.Root.Attribute("type") is null)
                    {
                        errors = new[]
                        {
                            new XmlError(doc.Root,
                                "Stream does not contain valid ComponentSettings. Unable to determine ComponentSettings type from root attribute.")
                        };
                        return;
                    }
 
                    ITypeData typedata = TypeData.GetTypeData(doc.Root.Attribute(TapSerializer.typeName).Value);
                    xmlCache[typedata.AsTypeData().Type] = mem.ToArray();
                    Invalidate(typedata.AsTypeData().Type);
                    errors = ComponentSettings.GetCurrent(typedata)?.loadErrors ?? Array.Empty<XmlError>();
                }
                catch (XmlException ex)
                {
                    errors = new[] { new XmlError(null, ex.Message, ex) };
                }
            }
        }
 
        public void SetCurrent(Stream xmlFileStream)
        {
            xmlFileStream.Position = 0;
            using (var mem = new MemoryStream())
            {
                xmlFileStream.CopyTo(mem);
                mem.Position = 0;
                try
                {
                    var doc = XDocument.Load(mem);
                    if (doc.Root.Attribute("type") is null)
                    {
                        mem.Position = 0;
                        throw new InvalidDataException($"Stream does not contain valid ComponentSettings. Unable to determine ComponentSettings type from root attribute. Content: {Encoding.UTF8.GetString(mem.ToArray())}");
                    }
                    ITypeData typedata = TypeData.GetTypeData(doc.Root.Attribute(TapSerializer.typeName).Value);
                    xmlCache[typedata.AsTypeData().Type] = mem.ToArray();
                    Invalidate(typedata.AsTypeData().Type);
                }
                catch (XmlException ex)
                {
                    mem.Position = 0;
                    throw new InvalidDataException($"Stream does not contain valid ComponentSettings. Unable to parse XML. Content: {Encoding.UTF8.GetString(mem.ToArray())}", ex);
                }
            }
        }
 
        public ComponentSettings GetCurrentFromCache(Type settingsType) =>
            objectCache.GetCached(settingsType);
 
        /// <summary>
        /// Loads a new instance of the settings for a given component.
        /// </summary>
        /// <param name="settingsType">The type of the component settings to load (this type must be a descendant of <see cref="ComponentSettings"/>).</param>
        /// <returns>Returns the settings.</returns>
        public ComponentSettings Load(Type settingsType)
        {
            xmlCache.TryGetValue(settingsType, out byte[] cachedXml);
 
            string path = GetSaveFilePath(settingsType);
            Stopwatch timer = Stopwatch.StartNew();
 
            ComponentSettings settings = null;
            if (cachedXml != null || File.Exists(path))
            {
                try
                {
                    Stream reader;
                    if (cachedXml != null)
                        reader = new MemoryStream(cachedXml);
                    else reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
 
                    using (var str = reader)
                    {
                        var serializer = new TapSerializer();
                        lock (flushQueues)
                            flushQueues.Enqueue(serializer);
                        settings = (ComponentSettings)serializer.Deserialize(str, false,
                            TypeData.FromType(settingsType), path: path);
                        settings.loadErrors = serializer.XmlErrors?.ToArray();
                    }
                }
                catch (Exception ex) when (ex.InnerException is System.ComponentModel.LicenseException lex)
                {
                    log.Warning("Unable to load '{0}'. {1}", settingsType.GetDisplayAttribute().GetFullName(),
                        lex.Message);
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        if (ex.InnerException.Message.StartsWith("The specified type was not recognized"))
                            log.Warning("Error loading settings file for {0}. {1}.", settingsType.Name,
                                ex.InnerException.Message);
                        else
                            log.Warning(
                                "Error loading settings file for {0}. Is it an old version? A new file will be created with default values.",
                                settingsType.Name);
                    }
 
                    log.Debug(ex);
                }
 
                log.Debug(timer, "{0} loaded from {1}", settingsType.Name, path);
            }
 
            if (settings == null)
            {
                try
                {
                    settings = (ComponentSettings)Activator.CreateInstance(settingsType);
                }
                catch (TargetInvocationException ex)
                {
                    log.Error("Could not create '{0}': {1}", settingsType.GetDisplayAttribute().Name,
                        ex.InnerException.Message);
                    log.Debug(ex);
                    return null;
                }
                catch (Exception e)
                {
                    log.Error("Caught exception while creating instance of '{0}'", settingsType.FullName);
                    log.Debug(e);
                    return null;
                }
 
                settings.Initialize();
 
                log.Debug(timer,
                    "No settings file exists for {0}. A new instance with default values has been created.",
                    settingsType.Name);
            }
 
            return settings;
        }
 
        public void SetSettingsProfile(string groupName, string profileName)
        {
            if (groupName == null)
                throw new ArgumentNullException(nameof(groupName));
            if (profileName == null)
                throw new ArgumentNullException(nameof(profileName));
 
            if (GetSettingsDirectory(groupName) == profileName)
                return;
 
            if (ComponentSettings.PersistSettingGroups)
            {
                try
                {
                    EnsureSettingsDirectoryExists(groupName);
                }
                catch
                {
                }
 
                var currentSettingsFile = Path.Combine(SettingsDirectoryRoot, groupName, "CurrentProfile");
                if (File.Exists(currentSettingsFile))
                    File.SetAttributes(currentSettingsFile, FileAttributes.Normal);
                File.WriteAllText(currentSettingsFile,
                    FileSystemHelper.GetRelativePath(Path.GetFullPath(Path.Combine(SettingsDirectoryRoot, groupName)),
                        Path.GetFullPath(profileName)));
                File.SetAttributes(currentSettingsFile, FileAttributes.Hidden);
            }
 
            groupDir[groupName] = profileName;
            InvalidateAllSettings();
        }
 
        readonly Dictionary<Type, byte[]> xmlCache = new Dictionary<Type, byte[]>();
 
        public ComponentSettingsContext Clone()
        {
            var session = new ComponentSettingsContext
            {
                SettingsDirectoryRoot = settingsDirectoryRoot,
            };
            var loadedSettings = objectCache.GetResults().Where(x => x != null).ToArray();
            var serializer = new TapSerializer();
            var mem = new MemoryStream();
            foreach (var setting in loadedSettings)
            {
                mem.Seek(0, SeekOrigin.Begin);
                mem.SetLength(0);
 
                serializer.Serialize(mem, setting);
                session.xmlCache[setting.GetType()] = mem.ToArray();
            }
 
            return session;
        }
    }
}