Skip to content

Commit

Permalink
Fix browser issue with dispatcher used before initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
maxkatz6 committed Jan 16, 2024
1 parent 07f5eda commit fc43c7e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
5 changes: 5 additions & 0 deletions src/Browser/Avalonia.Browser/BrowserAppBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public static async Task StartBrowserAppAsync(this AppBuilder builder, string ma
.AfterSetup(_ =>
{
lifetime.View = new AvaloniaView(mainDivId);
lifetime.CompleteSetup();
})
.SetupWithLifetime(lifetime);
}
Expand All @@ -77,6 +78,10 @@ public static async Task SetupBrowserAppAsync(this AppBuilder builder, BrowserPl

var lifetime = new BrowserSingleViewLifetime();
builder
.AfterSetup(_ =>
{
lifetime.CompleteSetup();
})
.SetupWithLifetime(lifetime);
}

Expand Down
36 changes: 20 additions & 16 deletions src/Browser/Avalonia.Browser/BrowserSingleViewLifetime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,18 @@ internal class BrowserSingleViewLifetime : ISingleViewApplicationLifetime, IActi
{
public BrowserSingleViewLifetime()
{
bool? initiallyVisible = InputHelper.SubscribeVisibilityChange(visible =>
_initiallyVisible = InputHelper.SubscribeVisibilityChange(visible =>
{
initiallyVisible = null;
(visible ? Activated : Deactivated)?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background));
_initiallyVisible = null;
var eventToTrigger = (visible ? Activated : Deactivated);
Dispatcher.UIThread.Invoke(
() => eventToTrigger?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background)),
DispatcherPriority.Background);
});

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

public AvaloniaView? View;
private bool? _initiallyVisible;

public Control? MainView
{
Expand Down Expand Up @@ -61,5 +53,17 @@ private void EnsureView()
public event EventHandler<ActivatedEventArgs>? Deactivated;

public bool TryLeaveBackground() => false;
public bool TryEnterBackground() => true;
public bool TryEnterBackground() => false;

internal void CompleteSetup()
{
// Trigger Activated as an initial state, if web page is visible, and wasn't hidden during initialization.
Dispatcher.UIThread.Invoke(() =>
{
if (_initiallyVisible == true)
{
Activated?.Invoke(this, new ActivatedEventArgs(ActivationKind.Background));
}
}, DispatcherPriority.Background);
}
}

0 comments on commit fc43c7e

Please sign in to comment.