Skip to content

Commit

Permalink
Merge pull request #624 from CommunityToolkit/component/DependencyPro…
Browse files Browse the repository at this point in the history
…pertyGenerator

🧪 [Experiment] DependencyPropertyGenerator
  • Loading branch information
Arlodotexe authored Jan 27, 2025
2 parents f6e1dc8 + 909b748 commit 75877c1
Show file tree
Hide file tree
Showing 93 changed files with 23,914 additions and 10 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -354,4 +354,4 @@ jobs:
if: ${{ (env.ENABLE_DIAGNOSTICS == 'true' || env.COREHOST_TRACE != '') && always() }}
with:
name: linux-logs
path: ./**/*.*log
path: ./**/*.*log
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static bool IsUwpTarget(Compilation compilation, AnalyzerConfigOptions an
{
if (bool.TryParse(propertyValue, out bool useUwpTools))
{
return true;
return useUwpTools;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
});

// Gather all interfaces, and only enable this branch if the target is a UWP app (the host)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, AppServiceInfo Info)> appServiceHostInfo =
IncrementalValuesProvider<(HierarchyInfo, AppServiceInfo)> appServiceHostInfo =
context.ForAttributeWithMetadataNameAndOptions(
"CommunityToolkit.AppServices.AppServiceAttribute",
static (node, _) => node is InterfaceDeclarationSyntax,
Expand All @@ -105,6 +105,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)

token.ThrowIfCancellationRequested();

// Gather all methods for the app service type
ImmutableArray<MethodInfo> methods = MethodInfo.From(typeSymbol, token);

token.ThrowIfCancellationRequested();
Expand All @@ -113,8 +114,47 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
})
.Where(static item => item.Hierarchy is not null);

// Produce the host type
context.RegisterSourceOutput(appServiceHostInfo, static (context, item) =>
// Also gather all explicitly requested host implementation types
IncrementalValuesProvider<(HierarchyInfo, AppServiceInfo)> additionalAppServiceHostInfo =
context.ForAttributeWithMetadataNameAndOptions(
"CommunityToolkit.AppServices.GeneratedAppServiceHostAttribute",
static (node, _) => true,
static (context, token) =>
{
// Only retrieve host info if the target is a UWP application
if (!Helpers.IsUwpTarget(context.SemanticModel.Compilation, context.GlobalOptions))
{
return default;
}

// Get the target interface
if (context.Attributes[0].ConstructorArguments is not [{ Kind: TypedConstantKind.Type, Value: INamedTypeSymbol appServiceType }])
{
return default;
}

// Check if the current interface is in fact an app service type
if (!appServiceType.TryGetAppServicesNameFromAttribute(out string? appServiceName))
{
return default;
}

token.ThrowIfCancellationRequested();

HierarchyInfo hierarchy = HierarchyInfo.From(appServiceType, appServiceType.Name.Substring(1));

token.ThrowIfCancellationRequested();

ImmutableArray<MethodInfo> methods = MethodInfo.From(appServiceType, token);

token.ThrowIfCancellationRequested();

return (Hierarchy: hierarchy, new AppServiceInfo(methods, appServiceName, appServiceType.GetFullyQualifiedName()));
})
.Where(static item => item.Hierarchy is not null);

// Shared helper to emit all discovered types
static void GenerateAppServiceHostType(SourceProductionContext context, (HierarchyInfo Hierarchy, AppServiceInfo Info) item)
{
ConstructorDeclarationSyntax constructorSyntax = Host.GetConstructorSyntax(item.Hierarchy, item.Info);
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = Host.GetMethodDeclarationsSyntax(item.Info);
Expand All @@ -126,6 +166,10 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
$"/// <summary>A generated host implementation for the <see cref=\"{item.Info.InterfaceFullyQualifiedName}\"/> interface.</summary>");

context.AddSource($"{item.Hierarchy.FilenameHint}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
}

// Produce the host types
context.RegisterSourceOutput(appServiceHostInfo, GenerateAppServiceHostType);
context.RegisterSourceOutput(additionalAppServiceHostInfo, GenerateAppServiceHostType);
}
}
55 changes: 54 additions & 1 deletion components/AppServices/src/AppServiceHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.AppServices.Helpers;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
using Windows.Foundation.Collections;
using Windows.Foundation.Metadata;
using Windows.System.Profile;
using CommunityToolkit.AppServices.Helpers;
using Windows.UI.Core.Preview;

#pragma warning disable CA1068

Expand Down Expand Up @@ -143,6 +144,58 @@ public bool OnBackgroundActivated(BackgroundActivatedEventArgs args)
return true;
}

/// <summary>
/// Handles the app service host shutdown when <see cref="SystemNavigationManagerPreview.CloseRequested"/> is raised.
/// </summary>
/// <param name="args">The args for the close request.</param>
/// <remarks>
/// <para>
/// This method should be used as follows (from <c>App.xaml.cs</c>):
/// <code language="cs">
/// private void OnCloseRequested(object? sender, SystemNavigationCloseRequestedPreviewEventArgs e)
/// {
/// // Any other work, possibly marking the request as handled
///
/// DesktopExtension.OnCloseRequested(e);
/// }
/// </code>
/// </para>
/// <para>
/// The app might be holding a deferral for the app service connection to the extension process, which is currently only completed when the
/// connection is closed. This means that when the application is closed, that deferral will actually try to keep the connection alive, until
/// the OS will eventually force terminate it. This will cause following launches of the app to be delayed until the previous process is
/// completely gone, meaning that closing the app and immediately reopening it will cause it to remain stuck at the splash screen for a few
/// seconds. Note that during this time, no app code is actually executed, it's just that the OS is waiting to terminate the existing connection
/// and fully close the previous instance before allowing a new one to be started. To avoid this issue, this method takes care of fully closing
/// any existing connection (by canceling its associated deferral), when the app is about to exit. This avoids the OS timeout for the connection.
/// </para>
/// </remarks>
public void OnCloseRequested(SystemNavigationCloseRequestedPreviewEventArgs args)
{
// Do nothing if the close request has been handled
if (args.Handled)
{
return;
}

// Remove the registered connection handlers
if (_appServiceConnection is { } appServiceConnection)
{
appServiceConnection.ServiceClosed -= AppServiceConnection_ServiceClosed;
appServiceConnection.RequestReceived -= AppServiceConnection_RequestReceived;

_appServiceConnection = null;
}

// Cancel the deferral, if present
if (_appServiceDeferral is { } appServiceDeferral)
{
appServiceDeferral.Complete();

_appServiceDeferral = null;
}
}

/// <summary>
/// Creates a new <see cref="AppServiceRequest"/> for a given operation.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<RootNamespace>CommunityToolkit.AppServices</RootNamespace>
<PackageId>$(PackageIdPrefix).$(ToolkitComponentName)</PackageId>
<HasWindowsUIXaml>false</HasWindowsUIXaml>
<HasWinUI>false</HasWinUI>
<EnableXamlCompilerMismatchedTfmUnoWorkaround>false</EnableXamlCompilerMismatchedTfmUnoWorkaround>

<!-- This library doesn't need XAML support, so we can just target 17763 (also disable the UWP build tools) -->
<UseUwpTools>false</UseUwpTools>
<UwpTargetFrameworks>uap10.0.17763;net8.0-windows10.0.17763.0;net9.0-windows10.0.17763.0;</UwpTargetFrameworks>
</PropertyGroup>

<!-- Sets this up as a toolkit component's source project -->
Expand All @@ -29,7 +35,7 @@
</PropertyGroup>

<!-- Add the Desktop Extension SDK when on UWP-->
<ItemGroup Condition="'$(IsUwp)' == 'true' AND $([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) != 'windows'">
<ItemGroup Condition="'$(IsUwp)' == 'true' AND '$(MultiTargetPlatformIdentifier)' != 'windows'">
<SDKReference Include="WindowsDesktop, Version=$(TargetPlatformVersion)">
<Name>Windows Desktop Extensions for the UWP</Name>
</SDKReference>
Expand Down
28 changes: 28 additions & 0 deletions components/AppServices/src/GeneratedAppServiceHostAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace CommunityToolkit.AppServices;

/// <summary>
/// An attribute that can be used to request the generator to emit a host implementation of a given app service.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
public sealed class GeneratedAppServiceHostAttribute : Attribute
{
/// <summary>
/// Creates a new <see cref="GeneratedAppServiceHostAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="appServiceType">The type of the app service.</param>
public GeneratedAppServiceHostAttribute(Type appServiceType)
{
AppServiceType = appServiceType;
}

/// <summary>
/// Gets the type of the app service.
/// </summary>
public Type AppServiceType { get; }
}
10 changes: 10 additions & 0 deletions components/DependencyPropertyGenerator/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# All file types:
# - Treat as text
# - Normalize to LF line endings
* text=auto eol=lf

# Explicit settings for well known types
*.cs text eol=lf
*.csproj text eol=lf
*.projitems text eol=lf
*.shprroj text eol=lf
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>

<!-- We're intentionally not always matching the namespace with folder path, to better organize the code -->
<NoWarn>$(NoWarn);IDE0130</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.12.0" PrivateAssets="all" />
<PackageReference Include="PolySharp" Version="1.15.0" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\CommunityToolkit.DependencyPropertyGenerator.SourceGenerators\CommunityToolkit.DependencyPropertyGenerator.SourceGenerators.csproj" />
</ItemGroup>
</Project>
Loading

0 comments on commit 75877c1

Please sign in to comment.