namespace gehGassi.Toolkit.Extensions.Window { /// /// Helpers for managing the safe area of an application window and helpers for changing the system bars appearance on Android. /// public static partial class WindowExtensions { private static readonly Dictionary>> windowSafeAreaListeners = new Dictionary>>(); private static readonly Dictionary safeAreas = new Dictionary(); /// /// Subscribes to safe area changes of the window. /// /// The window whose safe area changes you want to subscribe. /// The listener that obtains safe area insets of type . public static void SubscribeToSafeAreaChanges(this IWindow window, Action listener) { if (window is not Element elementWindow) return; AddListener(elementWindow.Id, listener); listener?.Invoke(GetSafeArea(elementWindow.Id)); } /// /// Unsubscribes from safe area changes of the window. /// /// The window whose safe area changes you want to unsubscribe. /// The listener that you want to remove from subscription. public static void UnsubscribeFromSafeAreaChanges(this IWindow window, Action listener) { if (window is Element elementWindow) RemoveListener(elementWindow.Id, listener); } private static void AddListener(Guid windowId, Action listener) { if (!windowSafeAreaListeners.ContainsKey(windowId)) windowSafeAreaListeners[windowId] = new List>(); if (!windowSafeAreaListeners[windowId].Contains(listener)) windowSafeAreaListeners[windowId].Add(listener); } private static void RemoveListener(Guid windowId, Action listener) { if (windowSafeAreaListeners.ContainsKey(windowId)) windowSafeAreaListeners[windowId].Remove(listener); } private static Thickness GetSafeArea(Guid windowId) { if (!safeAreas.ContainsKey(windowId)) safeAreas[windowId] = new Thickness(0); return safeAreas[windowId]; } private static void InvokeListenersIfChanged(Guid windowId, Thickness safeArea) { if (!safeAreas.ContainsKey(windowId)) safeAreas[windowId] = new Thickness(0); if (safeAreas[windowId] == safeArea) return; safeAreas[windowId] = safeArea; if (!windowSafeAreaListeners.ContainsKey(windowId)) windowSafeAreaListeners[windowId] = new List>(); foreach (var listener in windowSafeAreaListeners[windowId]) { listener?.Invoke(safeAreas[windowId]); } } } }