Skip to content

Commit

Permalink
Merge pull request #10816 from unoplatform/dev/jela/resource-resolution
Browse files Browse the repository at this point in the history
fix(resw): Adjust resources resolution
  • Loading branch information
jeromelaban authored Jan 12, 2023
2 parents e0fe6df + 7cb9abd commit 630d8c8
Show file tree
Hide file tree
Showing 8 changed files with 252 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.20.0" />
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="3.1.6" />
<PackageReference Include="Mono.Cecil" Version="0.11.4" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)'=='net461'">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,8 @@ public List<KeyValuePair<string, string>> Generate(GenerationRunInfo generationR
var lastBinaryUpdateTime = GetLastBinaryUpdateTime();

var resourceKeys = GetResourceKeys(_generatorContext.CancellationToken);
TryGenerateUnoResourcesKeyAttribute(resourceKeys);

var filesFull = new XamlFileParser(_excludeXamlNamespaces, _includeXamlNamespaces, _metadataHelper)
.ParseFiles(_xamlSourceFiles, _generatorContext.CancellationToken);

Expand Down Expand Up @@ -378,6 +380,14 @@ public List<KeyValuePair<string, string>> Generate(GenerationRunInfo generationR
}
}

private void TryGenerateUnoResourcesKeyAttribute(ImmutableHashSet<string> resourceKeys)
{
if (!resourceKeys.IsEmpty)
{
_generatorContext.AddSource("LocalizationResources", "[assembly: global::System.Reflection.AssemblyMetadata(\"UnoHasLocalizationResources\", \"True\")]");
}
}

#if !NETFRAMEWORK
private List<KeyValuePair<string, string>> ProcessParsingException(Exception e)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ internal partial class XamlFileGenerator
/// </summary>
private readonly Dictionary<INamedTypeSymbol, int> _xamlAppliedTypes = new Dictionary<INamedTypeSymbol, int>();

private readonly INamedTypeSymbol _assemblyMetadataSymbol;

private readonly INamedTypeSymbol _elementStubSymbol;
private readonly INamedTypeSymbol _contentPresenterSymbol;
private readonly INamedTypeSymbol _stringSymbol;
Expand Down Expand Up @@ -273,6 +275,7 @@ public XamlFileGenerator(
_relativePath = PathHelper.GetRelativePath(_targetPath, _fileDefinition.FilePath);
_stringSymbol = _metadataHelper.Compilation.GetSpecialType(SpecialType.System_String);
_objectSymbol = _metadataHelper.Compilation.GetSpecialType(SpecialType.System_Object);
_assemblyMetadataSymbol = (INamedTypeSymbol)_metadataHelper.FindTypeByFullName("System.Reflection.AssemblyMetadataAttribute");
_elementStubSymbol = (INamedTypeSymbol)_metadataHelper.GetTypeByFullName(XamlConstants.Types.ElementStub);
_setterSymbol = (INamedTypeSymbol)_metadataHelper.GetTypeByFullName(XamlConstants.Types.Setter);
_contentPresenterSymbol = (INamedTypeSymbol)_metadataHelper.GetTypeByFullName(XamlConstants.Types.ContentPresenter);
Expand Down Expand Up @@ -735,80 +738,41 @@ private void GenerateResourceLoader(IndentedStringBuilder writer)

writer.AppendLineIndented($"global::Windows.ApplicationModel.Resources.ResourceLoader.AddLookupAssembly(GetType().Assembly);");

foreach (var reference in _metadataHelper.Compilation.ExternalReferences)
foreach (var reference in _metadataHelper.Compilation.References)
{
string? GetFilePath()
{
if (reference is PortableExecutableReference per && File.Exists(per.FilePath))
{
return per.FilePath;
}
else if (File.Exists(reference.Display))
{
return reference.Display;
}
else
{
return null;
}
}

var referenceFilePath = GetFilePath();

if (referenceFilePath != null)
{
BuildResourceLoaderFromFilePath(writer, referenceFilePath);
}
else if(reference is CompilationReference cr)
{
// Skip local references for non-compiled targets (it can
// happen when using C# hot reload)
}
else
{
throw new InvalidOperationException($"Unsupported resource type for {reference.Display} ({reference.GetType()})");
}
}
if(_metadataHelper.Compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assembly)
{
BuildResourceLoaderFromAssembly(writer, assembly);
}
else
{
throw new InvalidOperationException($"Unsupported resource type for {reference.Display} ({reference.GetType()})");
}
}
}

private void BuildResourceLoaderFromFilePath(IndentedStringBuilder writer, string? referenceFilePath)
{
using var stream = File.OpenRead(referenceFilePath);
private void BuildResourceLoaderFromAssembly(IndentedStringBuilder writer, IAssemblySymbol assembly)
{
var hasUnoHasLocalizationResources = assembly.GetAttributes().Any(a =>
SymbolEqualityComparer.Default.Equals(a.AttributeClass, _assemblyMetadataSymbol)
&& a.ConstructorArguments.Length == 2
&& a.ConstructorArguments[0].Value is "UnoHasLocalizationResources"
&& (a.ConstructorArguments[1].Value?.ToString().Equals("True", StringComparison.OrdinalIgnoreCase) ?? false));

#if NETSTANDARD2_0
// Using is conditional to netstandard2 when running under netcore
// disposing the assembly crashes the mono runtime under macos.
using
#endif
var asm = Mono.Cecil.AssemblyDefinition.ReadAssembly(stream);
// Legacy behavior relying on the fact that GlobalStaticResources is generated using the default namespace.
var hasGlobalStaticResources = assembly.GetTypeByMetadataName(assembly.Name + ".GlobalStaticResources") is not null;

if (asm.MainModule.HasResources && asm.MainModule.Resources.Any(r => r.Name.EndsWith("upri", StringComparison.Ordinal)))
if (hasUnoHasLocalizationResources || hasGlobalStaticResources)
{
if (asm.Name.Name == "Uno.UI")
{
// Avoid the use of assembly lookup as we already know the assembly
writer.AppendLineIndented($"global::Windows.ApplicationModel.Resources.ResourceLoader.AddLookupAssembly(typeof(global::Windows.UI.Xaml.FrameworkElement).Assembly);");
}
else
{
if (_isWasm)
{
var anchorType = asm.MainModule.Types.FirstOrDefault(t => t.Name == "GlobalStaticResources" && t.IsPublic)
?? asm.MainModule.Types.FirstOrDefault(t => t.IsPublic && t.CustomAttributes.None(c => c.AttributeType.Name == "Obsolete"));

if (anchorType != null)
{
// Use a public type to get the assembly to work around a WASM assembly loading issue
writer.AppendLineIndented($"global::Windows.ApplicationModel.Resources.ResourceLoader.AddLookupAssembly(typeof(global::{anchorType.FullName}).Assembly); /* {asm.FullName} */");
}
}
else
{
writer.AppendLineIndented($"global::Windows.ApplicationModel.Resources.ResourceLoader.AddLookupAssembly(global::System.Reflection.Assembly.Load(\"{asm.FullName}\"));");
}
}
writer.AppendLineIndented($"global::Windows.ApplicationModel.Resources.ResourceLoader.AddLookupAssembly(global::System.Reflection.Assembly.Load(\"{assembly.Name}\"));");
}
}
else
{
#if DEBUG
writer.AppendLineIndented($"/* Assembly {assembly} does not contain UnoHasLocalizationResources */");
#endif
}
}

/// <summary>
/// Processes a top-level control definition.
Expand Down
6 changes: 6 additions & 0 deletions src/Uno.UI.RuntimeTests/Resources/en-US/Resources.resw
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,10 @@
<data name="RuntimeTests_AdditionalResource" xml:space="preserve">
<value>RuntimeTest Additional Resource</value>
</data>
<data name="SomePrefix/When_xUid_With_Prefix.Text" xml:space="preserve">
<value>en-US Value for SomePrefix/When_xUid_With_Prefix</value>
</data>
<data name="When_xUid.Text" xml:space="preserve">
<value>en-US Value for When_xUid</value>
</data>
</root>
123 changes: 123 additions & 0 deletions src/Uno.UI.RuntimeTests/Resources/en-US/TopLevelNamedRuntimeTests.resw
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="When_xUid_Explicit.Text" xml:space="preserve">
<value>en-US Value for When_xUid_Explicit in TopLevelNamedRuntimeTests</value>
</data>
</root>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<UserControl x:Class="Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml.Controls.When_xUid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">

<StackPanel>
<TextBlock x:Uid="When_xUid"
x:FieldModifier="public"
x:Name="defaultResolver" />
<TextBlock x:Uid="/TopLevelNamedRuntimeTests/When_xUid_Explicit"
x:FieldModifier="public"
x:Name="namedResolver" />
<TextBlock x:Uid="SomePrefix/When_xUid_With_Prefix"
x:FieldModifier="public"
x:Name="defaultResolverWithPrefix" />
</StackPanel>
</UserControl>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236

namespace Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml.Controls
{
public sealed partial class When_xUid : UserControl
{
public When_xUid()
{
this.InitializeComponent();
}
}
}
33 changes: 33 additions & 0 deletions src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_xUid.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#nullable enable
#if !WINDOWS_UWP
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Private.Infrastructure;
using Uno.UI.Extensions;
using Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml.Controls;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml
{
[TestClass]
[RunsOnUIThread]
public class Given_xUid
{
[TestMethod]
[RunsOnUIThread]
public void When_xUid()
{
var SUT = new When_xUid();

TestServices.WindowHelper.WindowContent = SUT;

Assert.AreEqual("en-US Value for When_xUid", SUT.defaultResolver.Text);
Assert.AreEqual("en-US Value for When_xUid_Explicit in TopLevelNamedRuntimeTests", SUT.namedResolver.Text);
Assert.AreEqual("en-US Value for SomePrefix/When_xUid_With_Prefix", SUT.defaultResolverWithPrefix.Text);
}
}
}
#endif

0 comments on commit 630d8c8

Please sign in to comment.