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
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace CommunityToolkit.Maui.Extensions;
// https://github.com/dotnet/maui/blob/main/src/Controls/src/Core/Platform/PageExtensions.cs
static class PageExtensions
{
internal static Page GetCurrentPage(this Window window) => GetCurrentPage(window.Page ?? throw new InvalidOperationException($"{nameof(Page)} cannot be null."));
Comment thread
TheCodeTraveler marked this conversation as resolved.
Resolved

internal static Page GetCurrentPage(this Page currentPage)
{
if (currentPage.Navigation.ModalStack.LastOrDefault() is Page modal)
Expand Down Expand Up @@ -50,6 +52,6 @@ public static bool Exists
return CurrentPage.GetParentWindow().Handler?.PlatformView is not null;
}
}
static Page CurrentPage => GetCurrentPage(Application.Current?.Windows[^1].Page ?? throw new InvalidOperationException($"{nameof(Page)} cannot be null."));
static Page CurrentPage => (Application.Current?.Windows[^1] ?? throw new InvalidOperationException($"{nameof(Window)} cannot be null.")).GetCurrentPage();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ protected override MauiMediaElement CreatePlatformView()
/// <inheritdoc/>
protected override void DisconnectHandler(MauiMediaElement platformView)
{
if(OperatingSystem.IsIOSVersionAtLeast(16) || OperatingSystem.IsMacCatalystVersionAtLeast(16, 1))
{
platformView.DetachFromParentViewController();
}

platformView.Dispose();
Dispose();

Expand All @@ -42,4 +47,9 @@ partial void PlatformDispose()
playerViewController?.Dispose();
playerViewController = null;
}

partial void PlatformRefreshPlaybackControlsVisibility(bool shouldShowPlaybackControls)
{
PlatformView?.RefreshPlaybackControlsVisibility(shouldShowPlaybackControls);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public static void MapAspect(MediaElementHandler handler, MediaElement mediaElem
public static void MapShouldShowPlaybackControls(MediaElementHandler handler, MediaElement mediaElement)
{
handler.MediaManager?.UpdateShouldShowPlaybackControls();
handler.PlatformRefreshPlaybackControlsVisibility(mediaElement.ShouldShowPlaybackControls);
}

/// <summary>
Expand All @@ -97,6 +98,8 @@ public static void MapSource(MediaElementHandler handler, MediaElement mediaElem
handler.MediaManager?.UpdateSource();
}

partial void PlatformRefreshPlaybackControlsVisibility(bool shouldShowPlaybackControls);

/// <summary>
/// Maps the <see cref="Core.IMediaElement.Speed"/> property between the abstract
/// <see cref="MediaElement"/> and platform counterpart.
Expand Down
240 changes: 132 additions & 108 deletions src/CommunityToolkit.Maui.MediaElement/Views/MauiMediaElement.macios.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Versioning;
using AVKit;
using CommunityToolkit.Maui.Extensions;
using CommunityToolkit.Maui.Views;
using UIKit;

Expand All @@ -11,157 +11,181 @@ namespace CommunityToolkit.Maui.Core.Views;
/// </summary>
public class MauiMediaElement : UIView
{
readonly AVPlayerViewController playerViewController;
readonly UIView playerView;

/// <summary>
/// Initializes a new instance of the <see cref="MauiMediaElement"/> class.
/// </summary>
/// <param name="playerViewController">The <see cref="AVPlayerViewController"/> that acts as the platform media player.</param>
/// <param name="virtualView">The <see cref="MediaElement"/> used as the VirtualView for this <see cref="MauiMediaElement"/>.</param>
/// <exception cref="NullReferenceException">Thrown when <paramref name="playerViewController"/><c>.View</c> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">Thrown when <paramref name="playerViewController"/><c>.View</c> is <see langword="null"/>.</exception>
public MauiMediaElement(AVPlayerViewController playerViewController, MediaElement virtualView)
{
ArgumentNullException.ThrowIfNull(playerViewController.View);
playerViewController.View.Frame = Bounds;
#if IOS16_0_OR_GREATER || MACCATALYST16_1_OR_GREATER
// On iOS 16+ and macOS 13+ the AVPlayerViewController has to be added to a parent ViewController, otherwise the transport controls won't be displayed.
ArgumentNullException.ThrowIfNull(virtualView);

UIViewController? viewController;
this.playerViewController = playerViewController;
playerView = playerViewController.View ?? throw new InvalidOperationException($"{nameof(playerViewController)}.{nameof(playerViewController.View)} cannot be null.");
playerView.Frame = Bounds;
AddSubview(playerView);
TryAttachToParentViewController();
}

// If any of the Parents in the VisualTree of MediaElement uses a UIViewController for their PlatformView, use it as the child ViewController
// This enables support for UI controls like CommunityToolkit.Maui.Popup whose PlatformView is a UIViewController (e.g. `public class MauiPopup : UIViewController`)
// To find the UIViewController, we traverse `MediaElement.Parent` until a Parent using UIViewController is located
if (virtualView.TryFindParentPlatformView(out UIViewController? parentUIViewController))
{
viewController = parentUIViewController;
}
// If none of the Parents in the VisualTree of MediaElement use a UIViewController, we can use the ViewController in the PageHandler
// To find the PageHandler, we traverse `MediaElement.Parent` until the Page is located
else if (virtualView.TryFindParent<Page>(out var page)
&& page.Handler?.PlatformView is UIView pageView)
/// <inheritdoc/>
public override void LayoutSubviews()
{
base.LayoutSubviews();
playerView.Frame = Bounds;
TryAttachToParentViewController();
}

/// <inheritdoc/>
public override void MovedToSuperview()
{
base.MovedToSuperview();
TryAttachToParentViewController();
}

/// <inheritdoc/>
public override void MovedToWindow()
{
base.MovedToWindow();
TryAttachToParentViewController();
}

/// <summary>
/// Forces AVKit to rebuild the player view hierarchy after playback controls are enabled.
/// </summary>
/// <param name="shouldShowPlaybackControls"><see langword="true"/> when playback controls should be visible.</param>
public void RefreshPlaybackControlsVisibility(bool shouldShowPlaybackControls)
{
if (!shouldShowPlaybackControls)
{
viewController = GetViewController(pageView) ?? GetCurrentUIViewController();
return;
}
// If the parent Page cannot be found, MediaElement is being used inside a DataTemplate. I.e. The MediaElement is being used inside a CarouselView or a CollectionView
// The top-most parent is null when MediaElement is placed in a DataTemplate because DataTemplates defer loading until they are about to be displayed on the screen
// When the MediaElement is used inside a DataTemplate, we must retrieve its CarouselViewHandler / CollectionViewHandler
// To retrieve its CarouselViewHandler / CollectionViewHandler, we must traverse all VisualElements on the current page
else

TryAttachToParentViewController(forceReattach: true);

SetNeedsLayout();
LayoutIfNeeded();
playerView.SetNeedsLayout();
playerView.LayoutIfNeeded();
playerView.SetNeedsDisplay();
}

/// <summary>
/// Removes the player view controller from its current parent.
/// </summary>
/// <remarks>
/// The player view controller is added as a child controller in <see cref="TryAttachToParentViewController"/>.
/// When the handler is disconnected the parent still retains the child controller, so it must be removed
/// here to avoid leaving a stale/disposed child controller in the parent view controller.
/// </remarks>
[SupportedOSPlatform("ios16.0")]
[SupportedOSPlatform("maccatalyst16.1")]
public void DetachFromParentViewController()
{
if (playerViewController.ParentViewController is not null)
{
ArgumentNullException.ThrowIfNull(virtualView);
playerViewController.WillMoveToParentViewController(null);

if (!TryGetCurrentPage(out var currentPage))
if (playerViewController.View is UIView attachedView)
{
throw new InvalidOperationException("Cannot find current page");
attachedView.RemoveFromSuperview();
}

// look for an ItemsView (e.g. CarouselView or CollectionView) on page
if (TryGetItemsViewOnPage(currentPage, out var itemsView))
{
viewController = GetViewController(itemsView);
}
// If we don't find an ItemsView, default to the current UIViewController
else
{
viewController = GetCurrentUIViewController();
}
playerViewController.RemoveFromParentViewController();
}
}


if (viewController?.View is not null)
void TryAttachToParentViewController(bool forceReattach = false)
{
if (!OperatingSystem.IsIOSVersionAtLeast(16) && !OperatingSystem.IsMacCatalystVersionAtLeast(16, 1))
{
// Zero out the safe area insets of the AVPlayerViewController
UIEdgeInsets insets = viewController.View.SafeAreaInsets;
playerViewController.AdditionalSafeAreaInsets =
new UIEdgeInsets(insets.Top * -1, insets.Left, insets.Bottom * -1, insets.Right);
return;
}

// Add the View from the AVPlayerViewController to the parent ViewController
viewController.AddChildViewController(playerViewController);
if (!TryGetParentViewController(out var viewController) || viewController.View is not UIView parentView)
{
return;
}
#endif
AddSubview(playerViewController.View);
}

static bool TryGetItemsViewOnPage(Page currentPage, [NotNullWhen(true)] out ItemsView? itemsView)
{
var itemsViewsOnPage = currentPage.GetVisualTreeDescendants().OfType<ItemsView>().ToList();
switch (itemsViewsOnPage.Count)
if (IsAdditionalSafeAreaInsetsStale(parentView))
{
case > 1:
// We are unable to determine which ItemsView contains the MediaElement when multiple ItemsView are being used in the same page
// TODO: Add support for MediaElement in an ItemsView on a Page containing multiple ItemsViews
throw new NotSupportedException("MediaElement does not currently support pages containing multiple ItemsViews (eg multiple CarouselViews + CollectionViews)");
case 1:
itemsView = itemsViewsOnPage[0];
return true;
case <= 0:
itemsView = null;
return false;
ApplySafeAreaInsets(parentView);
}
}

static UIViewController? GetViewController(ItemsView itemsView)
{
return itemsView.Handler?.PlatformView switch
if (!forceReattach && ReferenceEquals(playerViewController.ParentViewController, viewController))
{
UIView platformView => GetViewController(platformView) ?? GetCurrentUIViewController(),
null => throw new InvalidOperationException("Handler cannot be null"),
_ => throw new NotSupportedException($"{itemsView.Handler.PlatformView.GetType()} not yet supported")
};
}
return;
}

static UIViewController? GetViewController(UIView view)
{
for (UIResponder? responder = view; responder is not null; responder = responder.NextResponder)
if (playerViewController.ParentViewController is UIViewController previousParent)
{
if (responder is UIViewController viewController)
if (playerViewController.View is UIView attachedView)
{
return viewController;
attachedView.RemoveFromSuperview();
}

AddSubview(playerView);
playerView.Frame = Bounds;
playerViewController.WillMoveToParentViewController(null);
playerViewController.RemoveFromParentViewController();
}

return null;
ApplySafeAreaInsets(parentView);
viewController.AddChildViewController(playerViewController);
playerViewController.DidMoveToParentViewController(viewController);
Comment thread
TheCodeTraveler marked this conversation as resolved.
Resolved
}

static UIViewController? GetCurrentUIViewController()
[SupportedOSPlatform("ios16.0")]
[SupportedOSPlatform("maccatalyst16.1")]
bool IsAdditionalSafeAreaInsetsStale(UIView parentView)
{
var rootViewController = UIApplication.SharedApplication.ConnectedScenes
.OfType<UIWindowScene>()
.SelectMany(static scene => scene.Windows)
.FirstOrDefault(static window => window.IsKeyWindow)?
.RootViewController;
UIEdgeInsets expected = CreateSafeAreaInsets(parentView);
UIEdgeInsets actual = playerViewController.AdditionalSafeAreaInsets;

while (rootViewController?.PresentedViewController is not null)
{
rootViewController = rootViewController.PresentedViewController;
}
return actual.Top != expected.Top
|| actual.Left != expected.Left
|| actual.Bottom != expected.Bottom
|| actual.Right != expected.Right;
}

return rootViewController;
[SupportedOSPlatform("ios16.0")]
[SupportedOSPlatform("maccatalyst16.1")]
void ApplySafeAreaInsets(UIView parentView)
{
playerViewController.AdditionalSafeAreaInsets = CreateSafeAreaInsets(parentView);
}

static bool TryGetCurrentPage([NotNullWhen(true)] out Page? currentPage)
[SupportedOSPlatform("ios16.0")]
[SupportedOSPlatform("maccatalyst16.1")]
static UIEdgeInsets CreateSafeAreaInsets(UIView parentView)
{
currentPage = null;
UIEdgeInsets insets = parentView.SafeAreaInsets;
return new UIEdgeInsets(insets.Top * -1, insets.Left, insets.Bottom * -1, insets.Right);
}

if (Application.Current?.Windows is null)
{
return false;
}
[SupportedOSPlatform("ios16.0")]
[SupportedOSPlatform("maccatalyst16.1")]
bool TryGetParentViewController([NotNullWhen(true)] out UIViewController? viewController)
{
viewController = GetViewControllerFromResponderChain();
return viewController is not null;
}

if (Application.Current.Windows.Count is 0)
[SupportedOSPlatform("ios16.0")]
[SupportedOSPlatform("maccatalyst16.1")]
UIViewController? GetViewControllerFromResponderChain()
{
for (UIResponder? responder = NextResponder; responder is not null; responder = responder.NextResponder)
{
throw new InvalidOperationException("Unable to find active Window");
if (responder is UIViewController viewController)
{
return viewController;
}
}

if (Application.Current.Windows.Count > 1)
{
// We are unable to determine which Window contains the ItemsView that contains the MediaElement when multiple ItemsView are being used in the same page
// TODO: Add support for MediaElement in an ItemsView in a multi-window application
throw new NotSupportedException("MediaElement is not currently supported in multi-window applications");
}
if (Application.Current.Windows[0].Page is Page page)
{
currentPage = page.GetCurrentPage();
return true;
}
return false;
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ public partial class MediaManager : IDisposable
{
Player = Player
};
PlayerViewController.ShowsPlaybackControls = MediaElement.ShouldShowPlaybackControls;

// Pre-initialize Volume and Muted properties to the player object
Player.Muted = MediaElement.ShouldMute;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using FluentAssertions;
using Xunit;
using ParentWindow = CommunityToolkit.Maui.Extensions.PageExtensions.ParentWindow;
using CommunityToolkit.Maui.Extensions;

namespace CommunityToolkit.Maui.UnitTests.Views;

Expand Down Expand Up @@ -43,8 +44,6 @@ public void Exists_WhenParentWindowHandlerPlatformViewIsNull_ReturnsFalse()
var mockPage = new ContentPage();
mockWindow.Page = mockPage;
Application.Current.OpenWindow(mockWindow);

// Simulate a scenario where the handler is set but the platform view is null
mockWindow.Handler = new MockWindowHandler();

ParentWindow.Exists.Should().BeFalse();
Expand All @@ -60,7 +59,7 @@ public void Exists_WhenAllConditionsAreMet_ReturnsTrue()
mockWindow.Page = mockPage;
Application.Current.OpenWindow(mockWindow);

// Simulate a scenario where all conditions are met

mockWindow.Handler = new MockWindowHandler { PlatformView = new object() };

ParentWindow.Exists.Should().BeTrue();
Expand Down
Loading