Skip to content

Refactor WASM input and dom-callbacks to work with multithreading #15849

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions samples/ControlCatalog.Browser/ControlCatalog.Browser.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk.WebAssembly">
<PropertyGroup>
<TargetFramework>$(AvsCurrentBrowserTargetFramework)</TargetFramework>
<RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
<WasmMainJSPath>wwwroot/main.js</WasmMainJSPath>
<OutputType>Exe</OutputType>
<WasmEnableThreads>false</WasmEnableThreads>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebuggerSupport>true</DebuggerSupport>
<WasmDebugLevel>5</WasmDebugLevel>
Expand All @@ -22,10 +20,6 @@
<AdditionalUpToDateCheckInput Include="../../src/Browser/Avalonia.Browser/**/*" Visible="false"/>
</ItemGroup>

<ItemGroup>
<WasmExtraFilesToDeploy Include="wwwroot/**" />
</ItemGroup>

<Import Project="../../src/Browser/Avalonia.Browser/build/Avalonia.Browser.props" />
<Import Project="../../src/Browser/Avalonia.Browser/build/Avalonia.Browser.targets" />
</Project>
2 changes: 1 addition & 1 deletion samples/ControlCatalog.Browser/EmbedSample.Browser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public IPlatformHandle CreateControl(bool isSecond, IPlatformHandle parent, Func

static async void AddButton(JSObject parent)
{
await JSHost.ImportAsync("embed.js", "./embed.js");
await JSHost.ImportAsync("embed.js", "../embed.js");
EmbedInterop.AddAppButton(parent);
}
}
Expand Down
9 changes: 6 additions & 3 deletions samples/ControlCatalog.Browser/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,13 @@ await BuildAvaloniaApp()
})
.StartBrowserAppAsync("out", options);

if (Application.Current!.ApplicationLifetime is ISingleTopLevelApplicationLifetime lifetime)
Dispatcher.UIThread.Invoke(() =>
{
lifetime.TopLevel!.RendererDiagnostics.DebugOverlays = RendererDebugOverlays.Fps;
}
if (Application.Current!.ApplicationLifetime is ISingleTopLevelApplicationLifetime lifetime)
{
lifetime.TopLevel!.RendererDiagnostics.DebugOverlays = RendererDebugOverlays.Fps;
}
});
}

// Test with multiple AvaloniaView at once.
Expand Down
6 changes: 6 additions & 0 deletions src/Browser/Avalonia.Browser/Avalonia.Browser.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,10 @@
<InternalsVisibleTo Include="Avalonia.Browser.Blazor, PublicKey=$(AvaloniaPublicKey)" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\..\Shared\RawEventGrouping.cs">
<Link>RawEventGrouping.cs</Link>
</Compile>
</ItemGroup>

</Project>
4 changes: 2 additions & 2 deletions src/Browser/Avalonia.Browser/AvaloniaView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class AvaloniaView

/// <param name="divId">ID of the html element where avalonia content should be rendered.</param>
public AvaloniaView(string divId)
: this(DomHelper.GetElementById(divId) ??
: this(DomHelper.GetElementById(divId, BrowserWindowingPlatform.GlobalThis) ??
throw new Exception($"Element with id '{divId}' was not found in the html document."))
{
}
Expand Down Expand Up @@ -47,7 +47,7 @@ public AvaloniaView(JSObject host)
// Try to get local splash-screen of the specific host.
// If couldn't find - get global one by ID for compatibility.
var splash = DomHelper.GetElementsByClassName("avalonia-splash", host)
?? DomHelper.GetElementById("avalonia-splash");
?? DomHelper.GetElementById("avalonia-splash", BrowserWindowingPlatform.GlobalThis);
if (splash is not null)
{
DomHelper.AddCssClass(splash, "splash-close");
Expand Down
32 changes: 8 additions & 24 deletions src/Browser/Avalonia.Browser/BrowserActivatableLifetime.cs
Original file line number Diff line number Diff line change
@@ -1,36 +1,20 @@
using System;
using Avalonia.Browser.Interop;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;

namespace Avalonia.Browser;

internal class BrowserActivatableLifetime : IActivatableLifetime
internal class BrowserActivatableLifetime : ActivatableLifetimeBase
{
public BrowserActivatableLifetime()
public void OnVisibilityStateChanged(string visibilityState)
{
bool? initiallyVisible = InputHelper.SubscribeVisibilityChange(visible =>
var visible = visibilityState == "visible";
if (visible)
{
initiallyVisible = null;
(visible ? Activated : Deactivated)?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background));
});

// Trigger Activated as an initial state, if web page is visible, and wasn't hidden during initialization.
if (initiallyVisible == true)
OnActivated(ActivationKind.Background);
}
else
{
_ = Dispatcher.UIThread.InvokeAsync(() =>
{
if (initiallyVisible == true)
{
Activated?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background));
}
}, DispatcherPriority.Background);
OnDeactivated(ActivationKind.Background);
}
}

public event EventHandler<ActivatedEventArgs>? Activated;
public event EventHandler<ActivatedEventArgs>? Deactivated;

public bool TryLeaveBackground() => false;
public bool TryEnterBackground() => false;
}
49 changes: 44 additions & 5 deletions src/Browser/Avalonia.Browser/BrowserAppBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Browser.Interop;
using Avalonia.Browser.Rendering;
using Avalonia.Controls;
using Avalonia.Metadata;

namespace Avalonia.Browser;
Expand Down Expand Up @@ -53,6 +55,12 @@ public record BrowserPlatformOptions
/// For more details, see https://github.com/jimmywarting/native-file-system-adapter#a-note-when-downloading-with-the-polyfilled-version.
/// </summary>
public bool PreferFileDialogPolyfill { get; set; }

/// <summary>
/// Defines if Avalonia should create a controlled dispatcher loop on the web worker thread.
/// If used only when WasmEnableThreads is set to true. Default value is true.
/// </summary>
public bool? PreferManagedThreadDispatcher { get; set; } = true;
}

public static class BrowserAppBuilder
Expand All @@ -63,8 +71,9 @@ public static class BrowserAppBuilder
/// <param name="builder">Application builder.</param>
/// <param name="mainDivId">ID of the html element where avalonia content should be rendered.</param>
/// <param name="options">Browser backend specific options.</param>
public static async Task StartBrowserAppAsync(this AppBuilder builder, string mainDivId,
BrowserPlatformOptions? options = null)
public static async Task StartBrowserAppAsync(
this AppBuilder builder,
string mainDivId, BrowserPlatformOptions? options = null)
{
if (mainDivId is null)
{
Expand All @@ -78,8 +87,35 @@ public static async Task StartBrowserAppAsync(this AppBuilder builder, string ma
.AfterApplicationSetup(_ =>
{
lifetime.View = new AvaloniaView(mainDivId);
})
.SetupWithLifetime(lifetime);
});

if (BrowserWindowingPlatform.IsManagedDispatcherEnabled)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect that AvaloniaLocator.Current.GetService<BrowserPlatformOptions>()?.PreferManagedThreadDispatcher != false; check will always succeed regardless of the options parameter passed to StartBrowserAppAsync. Only one registered with .With will be used

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already have AvaloniaLocator.CurrentMutable.Bind<BrowserPlatformOptions>().ToConstant(options); for that case. It's auto-registered.

{
var tcs = new TaskCompletionSource();
var thread = new Thread(() =>
{
try
{
builder
.SetupWithLifetime(lifetime);
tcs.TrySetResult();
builder.Instance!.Run(CancellationToken.None);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
});
#pragma warning disable CA1416
thread.Start();
#pragma warning restore CA1416
await tcs.Task;
}
else
{
builder
.SetupWithLifetime(lifetime);
}
}

/// <summary>
Expand All @@ -102,12 +138,15 @@ public static async Task SetupBrowserAppAsync(this AppBuilder builder, BrowserPl

internal static async Task<AppBuilder> PreSetupBrowser(AppBuilder builder, BrowserPlatformOptions? options)
{
options ??= new BrowserPlatformOptions();
options ??= AvaloniaLocator.Current.GetService<BrowserPlatformOptions>() ?? new BrowserPlatformOptions();
options.FrameworkAssetPathResolver ??= fileName => $"./{fileName}";

AvaloniaLocator.CurrentMutable.Bind<BrowserPlatformOptions>().ToConstant(options);

await AvaloniaModule.ImportMain();

BrowserWindowingPlatform.GlobalThis = DomHelper.GetGlobalThis();

if (BrowserWindowingPlatform.IsThreadingEnabled)
{
await RenderWorker.InitializeAsync();
Expand Down
Loading
Loading