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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using OpenTap.Package.Ipc;
using Tap.Shared;
 
namespace OpenTap.Package
{
    /// <summary>
    /// Represents an OpenTAP installation in a specific directory.
    /// </summary>
    public class Installation
    {
        static TraceSource log = Log.CreateSource("Installation");
 
        /// <summary>
        /// Path to the installation
        /// </summary>
        public string Directory { get; }
 
        /// <summary>
        /// Get a unique identifier for this OpenTAP installation.
        /// The identifier is computed from hashing a uniquely generated machine ID combined with the hash of the installation directory.
        /// </summary>
        public string Id 
        {
            get
            {
                if(string.IsNullOrWhiteSpace(id))
                    id = $"{MurMurHash3.Hash(GetMachineId()):X8}{MurMurHash3.Hash(Directory):X8}";
                return id;
            }
        }
        private string id { get; set; }
        internal static string GetMachineId()
        {
            var idPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create), "OpenTap", "OpenTapGeneratedId");
            string id = default(Guid).ToString(); // 00000000-0000-0000-0000-000000000000
 
            try
            {
                if (File.Exists(idPath))
                {
                    if (Guid.TryParse(File.ReadAllText(idPath), out Guid parsedGuid)) // In the assumable rare case that a user tampers with the OpenTapGeneratedId file.
                    {
                        id = parsedGuid.ToString();
                        return id;
                    }
                }
                
                id = Guid.NewGuid().ToString();
                if (System.IO.Directory.Exists(Path.GetDirectoryName(idPath)) == false)
                    System.IO.Directory.CreateDirectory(Path.GetDirectoryName(idPath));
                File.WriteAllText(idPath, id);
            }
            catch (Exception e)
            {
                log.Error("Failed to read machine ID. See debug messages for more information");
                log.Debug(e);
            }
 
            return id;
        }
 
 
        /// <summary>
        /// Initialize an instance of a OpenTAP installation.
        /// </summary>
        /// <param name="directory"></param>
        public Installation(string directory)
        {
            this.Directory = directory ?? throw new ArgumentNullException(nameof(directory));
        }
 
        /// <summary>
        /// Check if it is an installation folder that contains packages other than system-wide packages
        /// </summary>
        public bool IsInstallationFolder => GetPackages().Any(x => x.IsSystemWide() == false);
 
        private static Installation current;
 
        /// <summary>
        /// Get the installation of the currently running tap process
        /// </summary>
        public static Installation Current => current ??= new Installation(ExecutorClient.ExeDir);
 
        /// <summary> Target installation architecture. This could be anything as 32-bit is supported on 64bit systems.</summary>
        internal CpuArchitecture Architecture => GetOpenTapPackage()?.Architecture ?? ArchitectureHelper.GuessBaseArchitecture;
 
        /// <summary> The target installation OS, should be either Windows, MacOS or Linux. </summary>
        internal string OS
        {
            get
            {
                if (OperatingSystem.Current == OperatingSystem.Windows)
                    return "Windows";
                if (OperatingSystem.Current == OperatingSystem.MacOS)
                    return "MacOS";
                return "Linux";
            }
        }
 
 
        /// <summary>
        /// Invalidate cached package list. This should only be called if changes have been made to the installation by circumventing OpenTAP APIs.
        /// </summary>
        public void Invalidate()
        {
            fileMap.Clear();
            // Force GetPackages() to repopulate packages next time it is called
            invalidate = true;
        }
 
        bool invalidate;
        readonly ConcurrentDictionary<string, PackageDef> fileMap = new ConcurrentDictionary<string, PackageDef>();
 
        /// <summary>
        /// Get the installed package which provides the file specified by the string.
        /// If multiple packages provide the file the package is chosen arbitrarily.
        /// </summary>
        /// <param name="file">An absolute or relative path to the file</param>
        /// <returns></returns>
        public PackageDef FindPackageContainingFile(string file)
        {
            InvalidateIfChanged();
 
            try
            {
                var invalid = Path.GetInvalidPathChars();
                if (file.Any(ch => invalid.Contains(ch))) return null;
                var name = Path.GetFileName(file);
                invalid = Path.GetInvalidFileNameChars();
                if (name.Any(ch => invalid.Contains(ch))) return null;
                // The path API is not 100% consistent. In some circumstances 'GetFullPath' will
                // still throw even if there are no illegal characters in the filename or path name.
                _ = Path.GetFullPath(file);
            }
            catch
            {
                // This means the filename is invalid on some way not covered by Path.GetInvalidPathChars.
                // This is fine, and it definitely means the file is not contained in a package
                return null;
            }
 
            var installDir = ExecutorClient.ExeDir;
 
            // Compute the absolute path in order to ensure the file exists, and normalize the path so it matches the format in package.xml files
            var abs = Path.IsPathRooted(file)
                ? Path.GetFullPath(file) // If the path is rooted, use the full path
                : Path.GetFullPath(Path.Combine(installDir, file)); // otherwise, append the relative path to the install dir
 
            // abs must be contained within installDir
            if (abs.Length <= installDir.Length)
                return null;
 
            // Path case sensitivity is file system dependent. Typically Windows and MacOS will be case-insensitive,
            // and Linux will be case-sensitive, but not always. TODO: check if path file system is case sensitive
            var stringComparer = OperatingSystem.Current == OperatingSystem.Linux
                ? StringComparison.Ordinal
                : StringComparison.OrdinalIgnoreCase;
            // Ensure the file is in a subdirectory of the installation. Otherwise it is not contained in a package.
            if (!abs.StartsWith(installDir, stringComparer))
                return null;
 
            // Compute the relative path and normalize directory separators
            var relative = abs.Substring(installDir.Length + 1).Replace('\\', '/');
 
            // Fully initialize fileMap as needed whenever it is cleared
            if (fileMap.Count == 0)
            {
                foreach (var package in GetPackages())
                {
                    foreach (var packageFile in package.Files)
                    {
                        var fileName = packageFile.FileName.Replace('\\', '/');
                        fileMap.TryAdd(fileName, package);
                    }
                }
            }
 
            if (fileMap.TryGetValue(relative, out var result))
                return result;
            return null;
        }
 
        /// <summary>
        /// Get the installed package which provides the type specified by pluginType.
        /// If multiple packages provide the type the package is chosen arbitrarily.
        /// </summary>
        /// <param name="pluginType"></param>
        /// <returns></returns>
        public PackageDef FindPackageContainingType(ITypeData pluginType)
        {
            var source = TypeData.GetTypeDataSource(pluginType);
            if (source == null) return null;
            // sourceFile is normally a .DLL, but may also be other things, e.g .py-file.
            var sourceFile = source.Location;
            if (string.IsNullOrWhiteSpace(sourceFile)) return null;
 
            var assemblyPath = Path.GetFullPath(sourceFile);
            var installPath = Path.GetFullPath(Directory);
 
            // The assembly must be rooted in the installation
            if (assemblyPath.StartsWith(installPath) == false)
                return null;
 
            return FindPackageContainingFile(assemblyPath);
        }
 
        private Dictionary<string, PackageDef> packageCache;
        private long previousChangeId = -1;
 
        // Keeps track of which warnings about duplicate packages has been emitted.
        static readonly HashSet<string> duplicateLogWarningsEmitted = new HashSet<string>();
 
        /// <summary>
        /// Invalidate caches if the installation has changed.
        /// </summary>
        private void InvalidateIfChanged()
        {
            long changeId = IsolatedPackageAction.GetChangeId(Directory);
 
            if (changeId != previousChangeId)
            {
                Invalidate();
                previousChangeId = changeId;
            }
        }
        /// <summary>
        /// Returns package definition list of installed packages in the TAP installation defined in the constructor, and system-wide packages.
        /// Results are cached, and Invalidate must be called if changes to the installation are made by circumventing OpenTAP APIs.
        /// </summary>
        public List<PackageDef> GetPackages() => GetPackagesLookup().Values.ToList();
        /// <summary>
        /// Returns package definition list of installed packages in the TAP installation defined in the constructor, and system-wide packages.
        /// Results are cached, and Invalidate must be called if changes to the installation are made by circumventing OpenTAP APIs.
        /// </summary>
        public List<PackageDef> GetPackages(bool validOnly) => GetPackagesLookup().Values.Where(pkg => pkg.IsValid()).ToList();
 
        /// <summary> Finds an installed package by name. Returns null if the package was not found. </summary>
        public PackageDef FindPackage(string name) => GetPackagesLookup().TryGetValue(name, out var package) ? package : null;
 
        /// <summary>
        /// Returns package definition list of installed packages in the TAP installation defined in the constructor, and system-wide packages.
        /// Results are cached, and Invalidate must be called if changes to the installation are made by circumventing OpenTAP APIs.
        /// </summary>
        /// <returns></returns>
        Dictionary<string, PackageDef> GetPackagesLookup()
        {
            InvalidateIfChanged();
 
            if (packageCache == null || invalidate)
            {
                Dictionary<string, PackageDef> plugins = new Dictionary<string, PackageDef>();
                List<PackageDef> duplicatePlugins = new List<PackageDef>();
                List<string> package_files = new List<string>();
 
                // Add normal package from OpenTAP folder
                package_files.AddRange(PackageDef.GetPackageMetadataFilesInTapInstallation(Directory));
 
                string normalizePath(string s)
                {
                    return Path.GetFullPath(s)
                        .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
                        .ToUpperInvariant();
                }
 
                // Add system wide packages
                if (normalizePath(Directory) != normalizePath(PackageDef.SystemWideInstallationDirectory))
                    package_files.AddRange(PackageDef.GetSystemWidePackages());
 
                foreach (var file in package_files)
                {
                    var package = installedPackageMemorizer.Invoke(file);
                    if (package == null) continue;
 
#pragma warning disable 618
                    package.Location = file;
#pragma warning restore 618
                    package.PackageSource = new InstalledPackageDefSource
                    {
                        Installation = this,
                        PackageDefFilePath = file
                    };
 
                    if (!plugins.ContainsKey(package.Name))
                    {
                        plugins.Add(package.Name, package);
                    }
                    else
                    {
                        duplicatePlugins.Add(package);
 
                    }
                }
 
                foreach (var p in duplicatePlugins.GroupBy(p => p.Name))
                {
                    lock (warningsLock)
                    {
                        if (duplicateLogWarningsEmitted.Add(p.Key))
                            log.Warning(
                                $"Duplicate {p.Key} packages detected. Consider removing some of the duplicate package definitions:\n" +
                                $"{string.Join("\n", p.Append(plugins[p.Key]).Select(x => " - " + ((InstalledPackageDefSource)x.PackageSource).PackageDefFilePath))}");
                    }
                }
 
 
 
                invalidate = false;
                packageCache = plugins;
            }
 
            return packageCache;
        }
 
        private static object warningsLock = new object();
 
 
        /// <summary>
        /// Get a package definition of OpenTAP engine.
        /// </summary>
        /// <returns></returns>
        public PackageDef GetOpenTapPackage()
        {
            if (GetPackagesLookup().TryGetValue("OpenTAP", out var opentap))
                return opentap;
            return null;
        }
 
 
        /// <summary>
        /// Memorizer which returns null when a cyclic memorizer call is detected.
        /// This prevents ugly and misleading error messages from occurring during
        /// calls to Installation.Current.GetPackages() from ITypeDataProvider implementations
        /// </summary>
        class IgnoreCyclicCallMemorizer<T1, T2, T3> : Memorizer<T1, T2, T3>
        {
            public IgnoreCyclicCallMemorizer(Func<T1, T2> func) : base(null, func)
            {
 
            }
 
            public override T2 OnCyclicCallDetected(T1 key)
            {
                return default;
            }
        }
 
 
        static IMemorizer<string, PackageDef> installedPackageMemorizer = new IgnoreCyclicCallMemorizer<string, PackageDef, string>(loadPackageDef)
        {
            Validator = file => new FileInfo(file).LastWriteTimeUtc.Ticks
        };
        static PackageDef loadPackageDef(string file)
        {
            try
            {
                using (var f = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                    return PackageDef.FromXml(f);
            }
            catch (Exception e)
            {
                log.Warning("Unable to read package file '{0}'. Moving it to '.broken'", file);
                log.Debug(e);
                var brokenfile = file + ".broken";
                if (File.Exists(brokenfile))
                    File.Delete(brokenfile);
                File.Move(file, brokenfile);
            }
            return null;
        }
 
        #region Package Change IPC
        /// <summary>
        /// Maintains a running number that increments whenever a plugin is installed.
        /// </summary>
        private class ChangeId : SharedState
        {
            public ChangeId(string dir) : base(".package_definitions_change_ID", dir)
            {
 
            }
 
            public long GetChangeId()
            {
                return Read<long>(0);
            }
 
            public void SetChangeId(long value)
            {
                Write(0, value);
            }
 
            public static async Task WaitForChange()
            {
                var changeId = new ChangeId(Path.GetDirectoryName(typeof(SharedState).Assembly.Location));
                var id = changeId.GetChangeId();
                while (changeId.GetChangeId() == id)
                    await Task.Delay(500);
            }
 
            public static void WaitForChangeBlocking()
            {
                var changeId = new ChangeId(Path.GetDirectoryName(typeof(SharedState).Assembly.Location));
                var id = changeId.GetChangeId();
                while (changeId.GetChangeId() == id)
                    Thread.Sleep(500);
            }
        }
 
        internal void AnnouncePackageChange()
        {
            using (var changeId = new ChangeId(this.Directory))
                changeId.SetChangeId(changeId.GetChangeId() + 1);
        }
 
        private bool IsMonitoringPackageChange = false;
        private void MonitorPackageChange()
        {
            if (!IsMonitoringPackageChange)
            {
                IsMonitoringPackageChange = true;
                TapThread.Start(() =>
                {
                    while (true)
                    {
                        ChangeId.WaitForChangeBlocking();
                        PackageChanged();
                    }
                });
            }
        }
 
        private Action PackageChanged;
        /// <summary>
        /// Event invoked when a package is installed/uninstalled from this installation.
        /// </summary>
        public event Action PackageChangedEvent
        {
            add
            {
                MonitorPackageChange();
                PackageChanged += value;
            }
            remove
            {
                PackageChanged -= value;
            }
        }
        #endregion
    }
}