Skip to content
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
144 changes: 114 additions & 30 deletions src/Sentry.Maui/Internal/MauiDeviceData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,24 +82,12 @@ public static void ApplyMauiDeviceData(this Device device, IDiagnosticLogger? lo
}

#if MACCATALYST || IOS
if (MainThread.IsMainThread)
{
CaptureDisplayInfo();
}
else
{
// On iOS and Mac Catalyst, Accessing DeviceDisplay.Current must be done on the UI thread or else an
// exception will be thrown.
// See https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/device/display?view=net-maui-8.0&tabs=macios#platform-differences
using var resetEvent = new ManualResetEventSlim(false);
// ReSharper disable once AccessToDisposedClosure - not disposed until lambda completes
MainThread.BeginInvokeOnMainThread(() => CaptureDisplayInfo(resetEvent));
resetEvent.Wait();
}
device.ApplyCocoaDisplayInfo(logger);
#elif ANDROID
device.ApplyAndroidDisplayInfo();
#else
CaptureDisplayInfo();
// Stryker disable once all : unit tests return early above, because DeviceInfo reports an unknown platform
device.ApplyDisplayInfo(DeviceDisplay.MainDisplayInfo);
#endif

// https://docs.microsoft.com/dotnet/maui/platform-integration/device/vibrate
Expand Down Expand Up @@ -138,28 +126,124 @@ public static void ApplyMauiDeviceData(this Device device, IDiagnosticLogger? lo
// Log, but swallow the exception so we can continue sending events
logger?.LogError(ex, "Error getting MAUI device information.");
}
}

#if !ANDROID
void CaptureDisplayInfo(ManualResetEventSlim? resetEvent = null)
internal static void ApplyDisplayInfo(this Device device, DisplayInfo display)
{
// https://docs.microsoft.com/dotnet/maui/platform-integration/device/display
device.ScreenResolution ??= $"{(int)display.Width}x{(int)display.Height}";
device.ScreenDensity ??= (float)display.Density;
device.Orientation ??= display.Orientation switch
{
DisplayOrientation.Portrait => DeviceOrientation.Portrait,
DisplayOrientation.Landscape => DeviceOrientation.Landscape,
_ => null
};
// device.ScreenDpi ??= ?
// ? = display.RefreshRate;
// ? = display.Rotation;
}
#endif

#if MACCATALYST || IOS
private static readonly TimeSpan DisplayInfoTimeout = TimeSpan.FromMilliseconds(10);
private static StrongBox<DisplayInfo>? LastDisplayInfo;
private static TaskCompletionSource? PendingRead;
private static Task? TimedOutRead;

internal static void ApplyCocoaDisplayInfo(this Device device, IDiagnosticLogger? logger)
{
// On iOS and Mac Catalyst, Accessing DeviceDisplay.Current must be done on the UI thread or else an
// exception will be thrown.
// See https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/device/display?view=net-maui-8.0&tabs=macios#platform-differences
if (MainThread.IsMainThread)
{
device.ApplyDisplayInfo(ReadDisplayInfo());
return;
}

var read = RefreshDisplayInfo(logger);
if (read != Volatile.Read(ref TimedOutRead) && !read.Wait(DisplayInfoTimeout))
{
Volatile.Write(ref TimedOutRead, read);
}
if (Volatile.Read(ref LastDisplayInfo) is { } lastDisplayInfo)
{
device.ApplyDisplayInfo(lastDisplayInfo.Value);
}
}

internal static Task RefreshDisplayInfo(IDiagnosticLogger? logger)
{
if (MainThread.IsMainThread)
{
TryReadDisplayInfo(logger);
return Task.CompletedTask;
}

if (Volatile.Read(ref PendingRead) is { } pending)
{
return pending.Task;
}

var read = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
if (Interlocked.CompareExchange(ref PendingRead, read, null) is { } raced)
{
return raced.Task;
}

try
{
// https://docs.microsoft.com/dotnet/maui/platform-integration/device/display
var display = DeviceDisplay.MainDisplayInfo;
device.ScreenResolution ??= $"{(int)display.Width}x{(int)display.Height}";
device.ScreenDensity ??= (float)display.Density;
device.Orientation ??= display.Orientation switch
MainThread.BeginInvokeOnMainThread(() =>
{
DisplayOrientation.Portrait => DeviceOrientation.Portrait,
DisplayOrientation.Landscape => DeviceOrientation.Landscape,
_ => null
};
// device.ScreenDpi ??= ?
// ? = display.RefreshRate;
// ? = display.Rotation;
resetEvent?.Set();
try
{
TryReadDisplayInfo(logger);
}
finally
{
CompleteRead(read);
}
});
}
#endif
catch (Exception ex)
{
CompleteRead(read);
logger?.LogError(ex, "Error scheduling a refresh of the MAUI display information.");
}

return read.Task;
}

private static void CompleteRead(TaskCompletionSource read)
{
Interlocked.CompareExchange(ref PendingRead, null, read);
read.TrySetResult();
}

private static void TryReadDisplayInfo(IDiagnosticLogger? logger)
{
try
{
ReadDisplayInfo();
}
catch (Exception ex)
{
logger?.LogError(ex, "Error refreshing the MAUI display information.");
}
}

internal static void ClearLastDisplayInfo() => Volatile.Write(ref LastDisplayInfo, null);

private static DisplayInfo ReadDisplayInfo()
{
var displayInfo = DeviceDisplay.MainDisplayInfo;
Volatile.Write(ref LastDisplayInfo, new StrongBox<DisplayInfo>(displayInfo));
return displayInfo;
}
#endif

#if ANDROID
// MAUI's DeviceDisplay can abort the process when read concurrently: https://github.com/dotnet/maui/issues/40510
private static void ApplyAndroidDisplayInfo(this Device device)
Expand Down
43 changes: 41 additions & 2 deletions src/Sentry.Maui/Internal/ScreenshotAttachment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ internal class ScreenshotAttachmentContent : IAttachmentContent
private static readonly Lock JniLock = new();
#endif

#if __IOS__
private static readonly TimeSpan MainThreadTimeout = TimeSpan.FromSeconds(1);
private static Task<Stream>? AbandonedCapture;
#endif

public ScreenshotAttachmentContent(SentryMauiOptions options)
{
_options = options;
Expand Down Expand Up @@ -71,13 +76,47 @@ Stream CaptureScreenBlocking()
}
else
{
if (Volatile.Read(ref AbandonedCapture) is { IsCompleted: false })
{
_options.LogWarning("The main thread hasn't run the previous screenshot capture yet. Sending the event without a screenshot.");
return stream;
}

// Screenshots have to be captured from the UI thread on iOS
stream = MainThread.InvokeOnMainThreadAsync(async () =>
var abandoned = new StrongBox<bool>();
var capture = MainThread.InvokeOnMainThreadAsync(async () =>
{
if (Volatile.Read(ref abandoned.Value))
{
return Stream.Null;
}

var screen = await Screenshot.Default.CaptureAsync().ConfigureAwait(true);

return await screen.OpenReadAsync(ScreenshotFormat.Jpeg).ConfigureAwait(true);
}).ConfigureAwait(false).GetAwaiter().GetResult();
});

if (Task.WaitAny([capture], MainThreadTimeout) == -1)
{
Volatile.Write(ref abandoned.Value, true);
Volatile.Write(ref AbandonedCapture, capture);
_options.LogWarning("The main thread didn't capture the screenshot within {0} ms. Sending the event without it.",
MainThreadTimeout.TotalMilliseconds);
capture.ContinueWith(static late =>
{
if (late.Status == TaskStatus.RanToCompletion)
{
late.Result.Dispose();
}
else
{
_ = late.Exception;
}
}, TaskContinuationOptions.ExecuteSynchronously);
return stream;
}

stream = capture.ConfigureAwait(false).GetAwaiter().GetResult();
}
#elif __ANDROID__
// Capturing screenshots is not threadsafe on Android
Expand Down
4 changes: 4 additions & 0 deletions src/Sentry.Maui/Internal/SentryMauiInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ public void Initialize(IServiceProvider services)
var options = services.GetRequiredService<IOptions<SentryMauiOptions>>().Value;
var disposer = services.GetRequiredService<Disposer>();

#if IOS || MACCATALYST
MauiDeviceData.RefreshDisplayInfo(options.DiagnosticLogger);
#endif

// Initialize the Sentry SDK.
var disposable = SentrySdk.Init(options);
options.ApplyConfigureScopeCallbacks(HubAdapter.Instance);
Expand Down
109 changes: 109 additions & 0 deletions test/Sentry.Maui.Tests/Internal/MauiDeviceDataTests.Cocoa.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System.Diagnostics;
using Sentry.Maui.Internal;
using Device = Sentry.Protocol.Device;

namespace Sentry.Maui.Tests.Internal;

public class MauiDeviceDataTests
{
private static readonly TimeSpan MainThreadBlockLimit = TimeSpan.FromSeconds(10);
private static readonly TimeSpan WorkLimit = TimeSpan.FromSeconds(5);

[Fact]
public async Task ApplyCocoaDisplayInfo_OffMainThreadWhileMainThreadIsBlocked_AppliesLastDisplayInfoAfterOneShortWait()
{
// Arrange
var expected = await MainThread.InvokeOnMainThreadAsync(() =>
{
MauiDeviceData.RefreshDisplayInfo(null);
return DeviceDisplay.MainDisplayInfo;
});
var devices = Enumerable.Range(0, 20).Select(_ => new Device()).ToArray();

// Act
var laterEvents = await RunOffMainThreadWhileMainThreadIsBlockedAsync(() =>
{
devices[0].ApplyCocoaDisplayInfo(null);
var timer = Stopwatch.StartNew();
foreach (var device in devices.Skip(1))
{
device.ApplyCocoaDisplayInfo(null);
}
timer.Stop();
return timer;
});

// Assert
laterEvents.Should().NotBeNull();
laterEvents.Elapsed.Should().BeLessThan(TimeSpan.FromMilliseconds(50), "only the first event should wait for the blocked main thread");
devices.Should().AllSatisfy(device =>
{
device.ScreenResolution.Should().Be($"{(int)expected.Width}x{(int)expected.Height}");
device.ScreenDensity.Should().Be((float)expected.Density);
});
}

[Fact]
public async Task ApplyMauiDeviceData_OffMainThreadWhileMainThreadIsFree_AppliesFreshDisplayInfo()
{
for (var round = 0; round < 2; round++)
{
string resolution = null;
for (var attempt = 0; attempt < 20 && resolution is null; attempt++)
{
// Arrange
MauiDeviceData.ClearLastDisplayInfo();
var device = new Device();

// Act
await Task.Run(() => device.ApplyMauiDeviceData(null, null));
await Task.Run(() => MainThread.InvokeOnMainThreadAsync(() => { }));
resolution = device.ScreenResolution;
}

// Assert
resolution.Should().NotBeNull($"round {round} should apply the display info read on the main thread");
}
}

[Fact]
public async Task ScreenshotAttachmentContent_OffMainThreadWhileMainThreadIsBlocked_GivesUpWithoutScreenshot()
{
// Arrange
var logger = new InMemoryDiagnosticLogger();
var content = new ScreenshotAttachmentContent(new SentryMauiOptions { Debug = true, DiagnosticLogger = logger });

// Act
var streams = await RunOffMainThreadWhileMainThreadIsBlockedAsync(() => new[] { content.GetStream(), content.GetStream() });

// Assert
streams.Should().NotBeNull();
streams.Should().AllSatisfy(stream => stream.Length.Should().Be(0));
logger.Entries.Where(entry => entry.Level == SentryLevel.Warning).Select(entry => entry.Message).Should().SatisfyRespectively(
first => first.Should().StartWith("The main thread didn't capture the screenshot"),
second => second.Should().StartWith("The main thread hasn't run the previous screenshot capture"));
}

private static async Task<T> RunOffMainThreadWhileMainThreadIsBlockedAsync<T>(Func<T> work) where T : class
{
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new ManualResetEventSlim();
MainThread.BeginInvokeOnMainThread(() =>
{
entered.SetResult();
release.Wait(MainThreadBlockLimit);
});
await entered.Task.ConfigureAwait(false);

try
{
var task = Task.Run(work);
var finished = await Task.WhenAny(task, Task.Delay(WorkLimit)).ConfigureAwait(false);
return finished == task ? task.Result : null;
}
finally
{
release.Set();
}
}
}
Loading
Loading