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
//            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.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading;
using OpenTap.Cli;
using OpenTap.Package;
using OpenTap.Translation;
 
namespace OpenTap.Sdk.New;
 
/// <summary>
/// This class contains helpful utilities for creating translations of packages.
/// </summary>
[Display("translate", Group: "sdk", Description: "Create a new translation template for a package.")]
public class TranslateAction : ICliAction
{
    /// <summary>
    /// The packages to translate
    /// </summary>
    [UnnamedCommandLineArgument(nameof(Package), Description = "The package to translate.")]
    [Display("Package", "The packages to translate")]
    public string Package { get; set; }
 
    private static readonly TraceSource log = Log.CreateSource("Translate");
 
    /// <inheritdoc/>
    public int Execute(CancellationToken cancellationToken)
    {
        // Ensure translations are generated for the default language (english)
        using var session = Session.Create(SessionOptions.OverlayComponentSettings);
        EngineSettings.Current.Language = CultureInfo.InvariantCulture;
 
        var install = Installation.Current;
        if (string.IsNullOrWhiteSpace(Package))
        {
            log.Error($"Please specify a package name.");
            return 1;
        }
        var pkg = install.FindPackage(Package);
        if (pkg == null)
        {
            log.Error($"Package '{Package}' is not installed.");
            return 1;
        }
 
        var outputdir = TranslationManager.TranslationDirectory;
        var outputFileName = Path.Combine(outputdir, pkg.Name + ".resx");
        if (!Directory.Exists(outputdir))
            Directory.CreateDirectory(outputdir);
 
        var types = new List<ITypeData>();
        // first add all plugins
        types.AddRange(TypeData.GetDerivedTypes<ITapPlugin>());
        
        types = [.. types.Distinct()];
 
        static void recursivelyAddReferencedTypes(ITypeData td, HashSet<ITypeData> seen)
        {
            try
            {
                foreach (var mem in td.GetMembers())
                {
                    // These types would be filtered out later anyway, but let's just not even consider them
                    if (mem.TypeDescriptor.Name.StartsWith("System.")
                        || mem.TypeDescriptor.Name.StartsWith("Microsoft."))
                        continue;
                    if (SkipMem(td, mem))
                    {
                        continue;
                    }
                    // Always translate the member type if it is embedded.
                    if (mem.HasAttribute<EmbedPropertiesAttribute>() || SkipType(mem.TypeDescriptor) == false)
                    {
                        if (seen.Add(mem.TypeDescriptor))
                        {
                            recursivelyAddReferencedTypes(mem.TypeDescriptor, seen);
                        }
                    }
                }
            }
            catch
            {
                // This happens if a typedata implementation throws in GetMembers()
                // We cannot really do anything about this
            }
        }
 
        var seen = new HashSet<ITypeData>(types);
        foreach (var td in types)
        {
            recursivelyAddReferencedTypes(td, seen);
        }
 
        types = [.. seen];
 
        {
            // We are not interested in creating a different translation for each 
            // variant of a generic type we use. 
            // Remove all instances of generic types, and add a single reference to the generic variant.
            HashSet<TypeData> add = [];
            HashSet<TypeData> remove = [];
            foreach (var type in types)
            {
                if (AsTypeData(type) is { } td && td.Type.IsGenericType)
                {
                    remove.Add(td);
                    var gen = TypeData.FromType(td.Type.GetGenericTypeDefinition());
                    add.Add(gen);
                }
            }
            types.RemoveAll(remove.Contains);
            types.AddRange(add);
        }
 
        static string normalizePath(string path) => path.Replace('\\', '/');
        var typesSources = types.Select(x => Path.GetFullPath(TypeData.GetTypeDataSource(x).Location))
            .Where(x => x.StartsWith(install.Directory, StringComparison.OrdinalIgnoreCase))
            .Select(x => x.Substring(install.Directory.Length + 1))
            .Select(normalizePath)
            .ToArray();
 
        var outdir = Path.GetDirectoryName(outputFileName);
        if (!string.IsNullOrWhiteSpace(outdir))
            Directory.CreateDirectory(outdir);
 
        var writer = new ResXWriter(outputFileName);
        var packageFiles = new HashSet<string>(pkg.Files.Select(x => normalizePath(x.FileName)), StringComparer.OrdinalIgnoreCase);
        List<ITypeData> packageTypes = [];
        for (int i = 0; i < typesSources.Length; i++)
        {
            if (typesSources[i] == null) continue;
            if (packageFiles.Contains(typesSources[i]))
            {
                packageTypes.Add(types[i]);
            }
        }
 
        if (!packageTypes.Any())
        { 
            log.Error($"0 types discovered for package '{Package}'. This is likely a bug.");
            return 1;
        }
        
        foreach (var type in packageTypes)
        {
            if (SkipType(type))
                continue;
 
            if (type.DescendsTo(typeof(Enum)) && AsTypeData(type)?.Type is Type enumType)
            {
                // Special handling for enums. We need to write each enum variant
                WriteEnumMembers(writer, enumType);
                continue;
            }
 
            if (type.DescendsTo(typeof(IStringLocalizer)) && type.CanCreateInstance && type.CreateInstance() is IStringLocalizer t)
            {
                WriteStringLocalizerStrings(writer, t);
            }
 
            var members = GetMembers(type);
            var typeDisplay = type.GetDisplayAttribute();
 
            WriteAttribute(writer, type.Name, typeDisplay);
            foreach (var mem in members)
            {
                if (SkipMem(type, mem))
                    continue;
                var memDisplay = mem.GetDisplayAttribute();
                WriteAttribute(writer, $"{type.Name}.{mem.Name}", memDisplay);
            }
        }
        
        // Also add all display attributes defined in the plugin
        {
            var assemblyFiles = pkg.Files.Where(f => !f.FileName.StartsWith("Dependencies/")).Where(x =>
                    x.FileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ||
                    x.FileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                .ToArray();
            List<Assembly> assemblies = [];
            foreach (var f in assemblyFiles)
            {
                try
                {
                    var asm = Assembly.LoadFrom(f.FileName);
                    assemblies.Add(asm);
                }
                catch
                {
                    // ignore
                }
            }
 
            foreach (var asm in assemblies)
            {
                foreach (var type in asm.ExportedTypes)
                {
                    if (type.GetCustomAttribute<DisplayAttribute>() is { } typeDisplay)
                    {
                        WriteAttribute(writer, type.FullName, typeDisplay);
                    }
 
                    foreach (var mem in type.GetMembers())
                    {
                        // Inherited members should be translated on the base type. Otherwise translators would
                        // have to duplicate translation of inherited members.
                        if (mem.DeclaringType != type) continue;
                        if (mem.GetCustomAttribute<DisplayAttribute>() is { } memDisplay)
                        {
                            WriteAttribute(writer, $"{type.FullName}.{mem.Name}", memDisplay);
                        }
                    }
                }
            }
        }
        
        writer.Generate();
        log.Info($"Created translation template file at {outputFileName}");
 
        return 0;
    }
 
    private static TypeData AsTypeData(ITypeData type)
    {
        do
        {
            if (type is TypeData td)
                return td;
            type = type?.BaseType;
        } while (type != null);
        return null;
    }
 
    private static void WriteEnumMembers(ResXWriter writer, Type enumType)
    {
        var names = Enum.GetNames(enumType);
        foreach (var name in names)
        {
            MemberInfo type = enumType.GetMember(name).FirstOrDefault();
            DisplayAttribute attr = type.GetCustomAttribute<DisplayAttribute>();
            attr ??= new DisplayAttribute(type.Name, null, Order: -10000, Collapsed: false);
            WriteAttribute(writer, $"{enumType.FullName}.{name}", attr);
        }
    }
 
    private static void WriteStringLocalizerStrings(ResXWriter writer, IStringLocalizer obj)
    {
        var t = obj.GetType();
        HashSet<string> added = [];
        Func<IStringLocalizer, string, string, CultureInfo, string> hook = (localizer, neutral, key, language) =>
        {
            var fullkey = $"{t.FullName}.{key}";
            if (added.Add(fullkey))
                writer.AddResource(fullkey, neutral);
            return neutral;
        };
        // inject hook
        var mgr = typeof(TranslationManager);
        mgr.GetField("TranslateFunction", BindingFlags.Static | BindingFlags.NonPublic)?.SetValue(null, hook);
 
        // we need to call the property getter for all properties to trigger all calls to Translate()
        foreach (var prop in t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
        {
            if (prop.PropertyType != typeof(string) && prop.PropertyType != typeof(FormatString)) continue;
            try
            {
                object owner = prop.GetGetMethod().IsStatic ? null : obj;
                prop.GetValue(owner);
            }
            catch
            {
                // ignore
            }
        }
    }
 
    private static void WriteAttribute(ResXWriter writer, string prefix, DisplayAttribute disp)
    {
        writer.AddResource($"{prefix}.Name", disp.Name ?? "");
        if (!string.IsNullOrWhiteSpace(disp.Description))
            writer.AddResource($"{prefix}.Description", disp.Description ?? "");
        if (disp.Order != DisplayAttribute.DefaultOrder)
        {
            writer.AddResource($"{prefix}.Order", disp.Order);
        }
 
        if (disp.Group.Length > 0)
        {
            writer.AddResource($"{prefix}.Group", string.Join(" \\ ", disp.Group));
        }
    }
 
    static bool SkipType(ITypeData type)
    {
        try
        {
            if (type.DescendsTo(typeof(IStringLocalizer)))
            {
                if (type.CanCreateInstance) return false;
                // Skip abstract types with no error
                if (AsTypeData(type)?.Type?.IsAbstract == true) return true;
                // It is currently a requirement that IStringLocalizer can be instantiated.
                // In the future, we can improve the string detection algorithm to relax this requirement,
                // but for now we should warn the user that this will not work.
                log.Error($"String localizer '{type.Name}' does not have an empty constructor, and will not be translated.");
                return true;
            }
 
            return false;
        }
        catch (Exception ex)
        {
            // ignore. This can happen for bad typedata implementations. We should just ignore the type in this case
            // since we can't translate it if we can't enumerate the members.
            log.Error($"Error reflecting type '{type.Name}'. This type will not be translated.");
            log.Debug(ex);
        } 
        return true;
    }
 
    static IMemberData[] GetMembers(ITypeData type)
    {
        try
        {
            return type.GetMembers().ToArray();
        }
        catch (Exception ex)
        {
            // ignore. This can happen for bad typedata implementations. We should just ignore the type in this case
            // since we can't translate it if we can't enumerate the members.
            log.Error($"Error reflecting type '{type.Name}'. Properties will not be translated.");
            log.Debug(ex);
        }
 
        return [];
    }
 
    static bool SkipMem(ITypeData type, IMemberData mem)
    {
        try
        {
            // If this member is inherited, the translation should happen in the base class.
            if (!Equals(mem.DeclaringType, type))
                return true;
            // Skip the member if it is unbrowsable
            var browsable = mem.GetAttribute<BrowsableAttribute>()?.Browsable;
            if (browsable != null) return !browsable.Value;
            // Otherwise skip the member if it is not writable.
            // This is the primary factor determining whether or not something is visible in most UIs.
            return !mem.Writable;
        }
        catch (Exception ex)
        { 
            log.Error($"Error reflecting member '{type.Name}.{mem.Name}'. This member will not be translated.");
            log.Debug(ex);
            return true;
        }
    }
}