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
//            Copyright Keysight Technologies 2012-2025
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
 
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Xml.Linq;
 
namespace OpenTap.Translation;
 
internal interface ITranslationProvider
{
    DisplayAttribute GetDisplayAttribute(IReflectionData mem);
    DisplayAttribute GetDisplayAttribute(Enum e, string name);
    string GetString(string key);
}
 
internal class ResXTranslationProvider : ITranslationProvider, IDisposable
{
    private TapThread _updateThread = null; 
    private readonly object StartUpdateThreadLock = new();
    void MaybeStartUpdateThread()
    {
        if (_updateThread != null) return;
        lock (StartUpdateThreadLock)
        {
            // If we got the lock after the update thread was initialized, we shouldn't initialie it again
            if (_updateThread != null) return;
            
            // If we are starting the update thread for the first time, we should block while initializing translations.
            UpdateInvalidatedMappings();
            
            TapThread.WithNewContext(() =>
            {
                _updateThread = TapThread.Start(() =>
                {
                    while (!TapThread.Current.AbortToken.IsCancellationRequested)
                    {
                        try
                        {
                            Thread.Sleep(TimeSpan.FromSeconds(5));
                            UpdateInvalidatedMappings();
                        }
                        catch
                        {
                            // we don't need to handle exceptions here, but we should ensure the update thread doesn't die
                        }
                    }
                });
            });
        }
    }
 
    public void Dispose()
    {
        _updateThread?.Abort();
    }
 
    public CultureInfo Culture { get; }
    private readonly Dictionary<string, string> CacheFileInvalidationTable = [];
    public ResXTranslationProvider(CultureInfo culture, IEnumerable<string> files)
    {
        Culture = culture;
        foreach (var file in files)
        {
            // Set the initial invalidation key for all files
            CacheFileInvalidationTable[file] = string.Empty;
        }
    }
 
    static string AttributeValue(XElement x, string name) => x.Attributes(name).FirstOrDefault()?.Value;
    static string ElementValue(XElement x, string name) => x.Elements(name).FirstOrDefault()?.Value;
 
    DisplayAttribute ComputeDisplayAttribute(string key, DisplayAttribute neutral)
    {
        bool translated = false;
        string name = neutral.Name;
        string description = neutral.Description;
        string group = string.Join(" \\ ", neutral.Group);
        double order = neutral.Order;
 
        if (GetString($"{key}.Name") is string tname)
        {
            name = tname;
            translated = true;
        }
        if (GetString($"{key}.Description") is string tdesc)
        {
            description = tdesc;
            translated = true;
        }
        if (GetString($"{key}.Group") is string tgroup)
        {
            group = tgroup;
            translated = true;
        }
        if (GetString($"{key}.Order") is string tord && double.TryParse(tord, out var o))
        {
            order = o;
            translated = true;
        }
 
        if (translated)
        {
            return new DisplayAttribute(Culture, name, description, group, order, neutral.Collapsed) { NeutralDisplayAttribute = neutral };
        }
        return neutral;
    }
 
    DisplayAttribute ComputeDisplayAttribute(Enum e, string name)
    {
        var enumType = e.GetType();
        var key = enumType.FullName + $".{name}";
        var fallback = enumType.GetMember(name).FirstOrDefault().GetDisplayAttribute();
        return ComputeDisplayAttribute(key, fallback);
    }
 
    DisplayAttribute ComputeDisplayAttribute(IReflectionData mem)
    {
        var key = mem switch
        {
            IMemberData imem => $"{imem.DeclaringType.Name}.{imem.Name}",
            // If the type is generic, the lookup key should not include the generic type parameter
            ITypeData td2 when td2.AsTypeData()?.Type is { } tp && tp.IsGenericType
                => TypeData.FromType(tp.GetGenericTypeDefinition()).Name,
            ITypeData tmem => tmem.Name,
            _ => mem.Name
        };
 
        var fallback = DefaultDisplayAttribute.GetUntranslatedDisplayAttribute(mem);
        return ComputeDisplayAttribute(key, fallback);
    }
 
    private ImmutableDictionary<IReflectionData, DisplayAttribute> _displayLookup = ImmutableDictionary<IReflectionData, DisplayAttribute>.Empty;
    private ImmutableDictionary<Enum, DisplayAttribute> _enumDisplayLookup = ImmutableDictionary<Enum, DisplayAttribute>.Empty;
    private ImmutableDictionary<string, string> _stringLookup = ImmutableDictionary<string, string>.Empty;
 
    private static readonly TraceSource log = Log.CreateSource("Translation");
    void UpdateInvalidatedMappings()
    {
        var newDict = new Dictionary<string, string>();
        foreach (var file in CacheFileInvalidationTable.Keys.ToArray())
        {
            var invalidationKey = GetCacheMarker(file);
            if (CacheFileInvalidationTable[file] != invalidationKey)
            {
                CacheFileInvalidationTable[file] = invalidationKey;
                try
                {
                    var resxDoc = XDocument.Load(file);
 
                    if (resxDoc.Root == null)
                        throw new Exception("Invalid XML");
 
                    foreach (var ele in resxDoc.Root.Elements("data"))
                    {
                        if (AttributeValue(ele, "name") is { } translationKey
                                && ElementValue(ele, "value") is { } translatedValue)
                        {
                            newDict[translationKey] = translatedValue;
                        }
                    }
                    log.Debug($"Reloaded translation file '{file}'.");
                }
                catch(Exception e)
                {
                    log.Error($"Unable to load translation resource file {file}.");
                    log.Debug(e);
                }
                _stringLookup = _stringLookup.SetItems(newDict);
                _displayLookup = ImmutableDictionary<IReflectionData, DisplayAttribute>.Empty;
                _enumDisplayLookup = ImmutableDictionary<Enum, DisplayAttribute>.Empty;
            }
        }
 
        static string GetCacheMarker(string file)
        {
            string key = string.Empty;
            if (File.Exists(file))
            {
                var fi = new FileInfo(file);
                key = $"{fi.LastWriteTimeUtc}.{fi.Length}";
            }
            return key;
        }
    }
 
    public DisplayAttribute GetDisplayAttribute(IReflectionData mem)
    {
        if (_displayLookup.TryGetValue(mem, out var disp)) return disp;
        disp = ComputeDisplayAttribute(mem);
        _displayLookup = _displayLookup.SetItem(mem, disp);
        return disp;
    }
 
    public DisplayAttribute GetDisplayAttribute(Enum e, string name)
    {
        if (_enumDisplayLookup.TryGetValue(e, out var disp)) return disp;
        disp = ComputeDisplayAttribute(e, name);
        _enumDisplayLookup = _enumDisplayLookup.SetItem(e, disp);
        return disp;
    }
 
    public string GetString(string key)
    {
        MaybeStartUpdateThread();
        return _stringLookup.TryGetValue(key, out var val) ? val : null;
    }
}