Exemple #1
0
        public static IElementHandler ToHandler(this IElement view, IMauiContext context)
        {
            _ = view ?? throw new ArgumentNullException(nameof(view));
            _ = context ?? throw new ArgumentNullException(nameof(context));

            //This is how MVU works. It collapses views down
            if (view is IReplaceableView ir)
            {
                view = ir.ReplacedView;
            }

            var handler = view.Handler;

            if (handler?.MauiContext != null && handler.MauiContext != context)
            {
                handler = null;
            }


            // TODO Clean up this handler create. Handlers should probably create through the
            // DI.Ext Service provider. We just register them all as transient? possibly?
            if (handler == null)
            {
                var viewType = view.GetType();
                try
                {
                    if (handlersWithConstructors.Contains(viewType))
                    {
                        handler = viewType.CreateTypeWithInjection(context);
                    }
                    else
                    {
                        handler = context.Handlers.GetHandler(viewType);
                    }
                }
                catch (MissingMethodException)
                {
                    handler = viewType.CreateTypeWithInjection(context);
                    if (handler != null)
                    {
                        handlersWithConstructors.Add(view.GetType());
                    }
                }
            }

            if (handler == null)
            {
                throw new HandlerNotFoundException($"Handler not found for view {view}.");
            }

            handler.SetMauiContext(context);

            try
            {
                view.Handler = handler;

                if (handler.VirtualView != view)
                {
                    handler.SetVirtualView(view);
                }
            }
            catch (ToPlatformException)
            {
                throw;
            }
            catch (HandlerNotFoundException)
            {
                throw;
            }
            catch (Exception exc)
            {
                throw new ToPlatformException($"{handler} found for {view} is incompatible", exc);
            }

            return(handler);
        }
 public static AppCompatActivity GetActivity(this IMauiContext mauiContext) =>
 (mauiContext.Context?.GetActivity() as AppCompatActivity)
 ?? throw new InvalidOperationException("AppCompatActivity Not Found");
 public NavigationRootManager(IMauiContext mauiContext)
 {
     _mauiContext = mauiContext;
 }
Exemple #4
0
 public static void Init(IMauiContext context, Assembly resourceAssembly)
 {
     Profile.FrameBegin();
     SetupInit(context, resourceAssembly, null);
     Profile.FrameEnd();
 }
 public StackNavigationManager(IMauiContext mauiContext)
 {
     _mauiContext = mauiContext;
 }
Exemple #6
0
        static void SetupInit(
            IMauiContext context,
            Assembly resourceAssembly,
            InitializationOptions?maybeOptions = null
            )
        {
            var activity = context.Context;

            Profile.FrameBegin();
            Registrar.RegisterRendererToHandlerShim(RendererToHandlerShim.CreateShim);
            if (!IsInitialized)
            {
                // Only need to get this once; it won't change
                ApplicationContext = activity.ApplicationContext;
                MauiContext        = context;
            }

#pragma warning disable 618 // Still have to set this up so obsolete code can function
            Context = activity;
#pragma warning restore 618

            if (!IsInitialized)
            {
                // Only need to do this once
                Profile.FramePartition("ResourceManager.Init");
                ResourceManager.Init(resourceAssembly);
            }

            Profile.FramePartition("Color.SetAccent()");
            // We want this to be updated when we have a new activity (e.g. on a configuration change)
            // This could change if the UI mode changes (e.g., if night mode is enabled)
            Color.SetAccent(GetAccentColor(activity));
            _ColorButtonNormalSet = false;

            if (!IsInitialized)
            {
                // Only need to do this once
                Profile.FramePartition("Log.Listeners");
                Internals.Log.Listeners.Add(new DelegateLogListener((c, m) => Trace.WriteLine(m, c)));
            }

            // We want this to be updated when we have a new activity (e.g. on a configuration change)
            // because AndroidPlatformServices needs a current activity to launch URIs from
            Profile.FramePartition("Device.PlatformServices");

            var androidServices = new AndroidPlatformServices(activity);

            Device.PlatformServices    = androidServices;
            Device.PlatformInvalidator = androidServices;

            // use field and not property to avoid exception in getter
            if (Device.info != null)
            {
                ((AndroidDeviceInfo)Device.info).Dispose();
                Device.info = null;
            }

            // We want this to be updated when we have a new activity (e.g. on a configuration change)
            // because Device.Info watches for orientation changes and we need a current activity for that
            Profile.FramePartition("create AndroidDeviceInfo");
            Device.Info = new AndroidDeviceInfo(activity);

            Profile.FramePartition("setFlags");
            Device.SetFlags(s_flags);

            Profile.FramePartition("AndroidTicker");
            Ticker.SetDefault(null);

            Profile.FramePartition("RegisterAll");

            RegisterCompatRenderers(maybeOptions);

            Profile.FramePartition("Epilog");

            var currentIdiom = TargetIdiom.Unsupported;

            // First try UIModeManager
            using (var uiModeManager = UiModeManager.FromContext(ApplicationContext))
            {
                try
                {
                    var uiMode = uiModeManager?.CurrentModeType ?? UiMode.TypeUndefined;
                    currentIdiom = DetectIdiom(uiMode);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Unable to detect using UiModeManager: {ex.Message}");
                }
            }

            // Then try Configuration
            if (TargetIdiom.Unsupported == currentIdiom)
            {
                var configuration = activity.Resources.Configuration;

                if (configuration != null)
                {
                    var minWidth = configuration.SmallestScreenWidthDp;
                    var isWide   = minWidth >= TabletCrossover;
                    currentIdiom = isWide ? TargetIdiom.Tablet : TargetIdiom.Phone;
                }
                else
                {
                    // Start clutching at straws
                    var metrics = activity.Resources?.DisplayMetrics;

                    if (metrics != null)
                    {
                        var minSize = Math.Min(metrics.WidthPixels, metrics.HeightPixels);
                        var isWide  = minSize * metrics.Density >= TabletCrossover;
                        currentIdiom = isWide ? TargetIdiom.Tablet : TargetIdiom.Phone;
                    }
                }
            }

            Device.SetIdiom(currentIdiom);

            if (SdkInt >= BuildVersionCodes.JellyBeanMr1)
            {
                Device.SetFlowDirection(activity.Resources.Configuration.LayoutDirection.ToFlowDirection());
            }

            if (ExpressionSearch.Default == null)
            {
                ExpressionSearch.Default = new AndroidExpressionSearch();
            }

            IsInitialized = true;
            Profile.FrameEnd();
        }
Exemple #7
0
 protected THandler CreateHandler(IView view, IMauiContext mauiContext = null) =>
 CreateHandler <THandler>(view, mauiContext);
Exemple #8
0
 public ActivationState(IMauiContext context, Foundation.NSDictionary[]?states)
     : this(context, GetPersistedState(states))
 {
 }
Exemple #9
0
 public ActivationState(IMauiContext context, UI.Xaml.LaunchActivatedEventArgs?launchActivatedEventArgs)
     : this(context)
 {
     LaunchActivatedEventArgs = launchActivatedEventArgs;
 }
Exemple #10
0
 internal static ILogger <T>?CreateLogger <T>(this IMauiContext context) =>
 context.Services.CreateLogger <T>();
 public IrSource(IMauiContext context, PositionalViewSelector positionalViewSelector, IVirtualListView virtualListView)
 {
     Context = context;
     PositionalViewSelector = positionalViewSelector;
     VirtualListView        = virtualListView;
 }
Exemple #12
0
 internal static ILogger?CreateLogger(this IMauiContext context, string loggerName) =>
 context.Services.CreateLogger(loggerName);
Exemple #13
0
 public ActivationState(IMauiContext context, Bundle?savedInstance = null)
 {
     Context       = context ?? throw new ArgumentNullException(nameof(context));
     SavedInstance = savedInstance;
 }
 public ShellFlyoutItemAdaptor(Shell shell, IMauiContext context, IEnumerable items, bool hasHeader) : base(items)
 {
     _shell    = shell;
     _context  = context;
     HasHeader = hasHeader;
 }
 public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
 {
     ScopedMauiContext = _mauiContext.MakeScoped(layoutInflater: inflater, fragmentManager: ChildFragmentManager, registerNewNavigationRoot: true);
     return(ScopedMauiContext.GetNavigationRootManager().RootView);
 }
Exemple #16
0
 public ActivationState(IMauiContext context, IPersistedState state)
 {
     Context = context ?? throw new ArgumentNullException(nameof(context));
     State   = state ?? throw new ArgumentNullException(nameof(state));
 }
Exemple #17
0
        static void SetupInit(
            IMauiContext mauiContext,
            UI.Xaml.LaunchActivatedEventArgs launchActivatedEventArgs,
            WindowsBasePage mainWindow,
            IEnumerable <Assembly> rendererAssemblies = null,
            InitializationOptions?maybeOptions        = null)
        {
            MauiContext = mauiContext;
            Registrar.RegisterRendererToHandlerShim(RendererToHandlerShim.CreateShim);

            var accent = (WSolidColorBrush)Microsoft.UI.Xaml.Application.Current.Resources["SystemColorControlAccentBrush"];

            Color.SetAccent(accent.ToFormsColor());

            if (!IsInitialized)
            {
#if !UWP_16299
                Log.Listeners.Add(new DelegateLogListener((c, m) => Debug.WriteLine(LogFormat, c, m)));
#else
                Log.Listeners.Add(new DelegateLogListener((c, m) => Trace.WriteLine(m, c)));
#endif
            }

            if (!UI.Xaml.Application.Current.Resources.ContainsKey("RootContainerStyle"))
            {
                UI.Xaml.Application.Current.Resources.MergedDictionaries.Add(GetTabletResources());
            }

            try
            {
                UI.Xaml.Application.Current.Resources.MergedDictionaries.Add(new UI.Xaml.Controls.XamlControlsResources());
            }
            catch
            {
                Log.Warning("Resources", "Unable to load WinUI resources. Try adding Microsoft.Maui.Controls.Compatibility nuget to UWP project");
            }

            Device.SetIdiom(TargetIdiom.Tablet);
            Device.SetFlowDirection(GetFlowDirection());

            Device.SetFlags(s_flags);

            //TODO WINUI3
            //// use field and not property to avoid exception in getter
            //if (Device.info != null)
            //{
            //	Device.info.Dispose();
            //	Device.info = null;
            //}
            //Device.Info = new WindowsDeviceInfo();

            //TODO WINUI3
            //switch (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily)
            //{
            //	case "Windows.Desktop":
            //		if (Windows.UI.ViewManagement.UIViewSettings.GetForCurrentView().UserInteractionMode ==
            //			Windows.UI.ViewManagement.UserInteractionMode.Touch)
            //			Device.SetIdiom(TargetIdiom.Tablet);
            //		else
            //			Device.SetIdiom(TargetIdiom.Desktop);
            //		break;
            //	case "Windows.Mobile":
            //		Device.SetIdiom(TargetIdiom.Phone);
            //		break;
            //	case "Windows.Xbox":
            //		Device.SetIdiom(TargetIdiom.TV);
            //		break;
            //	default:
            //		Device.SetIdiom(TargetIdiom.Unsupported);
            //		break;
            //}

            ExpressionSearch.Default = new WindowsExpressionSearch();

            Registrar.ExtraAssemblies = rendererAssemblies?.ToArray();
            s_state = launchActivatedEventArgs.UWPLaunchActivatedEventArgs.PreviousExecutionState;

            var dispatcher = mainWindow?.DispatcherQueue ?? System.DispatcherQueue.GetForCurrentThread();

            var platformServices = new WindowsPlatformServices(dispatcher);

            Device.PlatformServices    = platformServices;
            Device.PlatformInvalidator = platformServices;

            if (maybeOptions?.Flags.HasFlag(InitializationFlags.SkipRenderers) != true)
            {
                RegisterCompatRenderers();
            }

            if (mainWindow != null)
            {
                MainWindow = mainWindow;

                //TODO WINUI3
                Platform.UWP.Platform.SubscribeAlertsAndActionSheets();

                mainWindow.LoadApplication(mainWindow.CreateApplication());
                mainWindow.Activate();
            }

            IsInitialized = true;
        }
Exemple #18
0
 public ActivationState(IMauiContext context, Android.OS.Bundle?savedInstance)
     : this(context, GetPersistedState(savedInstance))
 {
     SavedInstance = savedInstance;
 }
Exemple #19
0
 public ActivationState(IMauiContext context)
 {
     Context = context ?? throw new ArgumentNullException(nameof(context));
 }
Exemple #20
0
 public CometView(IMauiContext mauiContext)
 {
     MauiContext = mauiContext;
 }
Exemple #21
0
 public ModalFragment(IMauiContext mauiContext, Page modal)
 {
     _modal             = modal;
     _mauiWindowContext = mauiContext;
 }
Exemple #22
0
 public CometView(CGRect rect, IMauiContext mauiContext) : base(rect)
 {
     MauiContext = mauiContext;
 }
Exemple #23
0
        static void SetupInit(
            IMauiContext context,
            Assembly resourceAssembly,
            InitializationOptions?maybeOptions = null
            )
        {
            var activity = context.Context;

            Profile.FrameBegin();
            Registrar.RegisterRendererToHandlerShim(RendererToHandlerShim.CreateShim);

            // Allow this multiple times to support the app and then the activity
            ApplicationContext = activity.ApplicationContext;
            MauiContext        = context;

            if (!IsInitialized)
            {
                // Only need to do this once
                Profile.FramePartition("ResourceManager.Init");
                ResourceManager.Init(resourceAssembly);
            }

            Profile.FramePartition("Color.SetAccent()");
            // We want this to be updated when we have a new activity (e.g. on a configuration change)
            // This could change if the UI mode changes (e.g., if night mode is enabled)
            Application.AccentColor = GetAccentColor(activity);
            _ColorButtonNormalSet   = false;

            // We want this to be updated when we have a new activity (e.g. on a configuration change)
            // because AndroidPlatformServices needs a current activity to launch URIs from
            Profile.FramePartition("Device.PlatformServices");

            var androidServices = new AndroidPlatformServices(activity);

            Device.PlatformServices    = androidServices;
            Device.PlatformInvalidator = androidServices;

            Profile.FramePartition("RegisterAll");

            if (maybeOptions?.Flags.HasFlag(InitializationFlags.SkipRenderers) != true)
            {
                RegisterCompatRenderers(maybeOptions);
            }

            Profile.FramePartition("Epilog");

            var currentIdiom = TargetIdiom.Unsupported;

            // First try UIModeManager
            using (var uiModeManager = UiModeManager.FromContext(ApplicationContext))
            {
                try
                {
                    var uiMode = uiModeManager?.CurrentModeType ?? UiMode.TypeUndefined;
                    currentIdiom = DetectIdiom(uiMode);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Unable to detect using UiModeManager: {ex.Message}");
                }
            }

            // Then try Configuration
            if (TargetIdiom.Unsupported == currentIdiom)
            {
                var configuration = activity.Resources.Configuration;

                if (configuration != null)
                {
                    var minWidth = configuration.SmallestScreenWidthDp;
                    var isWide   = minWidth >= TabletCrossover;
                    currentIdiom = isWide ? TargetIdiom.Tablet : TargetIdiom.Phone;
                }
                else
                {
                    // Start clutching at straws
                    var metrics = activity.Resources?.DisplayMetrics;

                    if (metrics != null)
                    {
                        var minSize = Math.Min(metrics.WidthPixels, metrics.HeightPixels);
                        var isWide  = minSize * metrics.Density >= TabletCrossover;
                        currentIdiom = isWide ? TargetIdiom.Tablet : TargetIdiom.Phone;
                    }
                }
            }

            Device.SetIdiom(currentIdiom);
            Device.SetFlowDirection(activity.Resources.Configuration.LayoutDirection.ToFlowDirection());

            if (ExpressionSearch.Default == null)
            {
                ExpressionSearch.Default = new AndroidExpressionSearch();
            }

            IsInitialized = true;
            Profile.FrameEnd();
        }
 public static UIWindow GetPlatformWindow(this IMauiContext mauiContext) =>
 mauiContext.Services.GetRequiredService <UIWindow>();
Exemple #25
0
 public static NavigationRootManager GetNavigationRootManager(this IMauiContext mauiContext) =>
 mauiContext.Services.GetRequiredService <NavigationRootManager>();
Exemple #26
0
 public ShellContentView(Context context, View view, IMauiContext mauiContext)
 {
     _mauiContext = mauiContext ?? throw new ArgumentNullException(nameof(mauiContext));
     _context     = new WeakReference <Context>(context);
     View         = view;
 }
Exemple #27
0
 public static Android.App.Activity GetPlatformWindow(this IMauiContext mauiContext) =>
 mauiContext.Services.GetRequiredService <Android.App.Activity>();
 public NavViewFragment(IMauiContext mauiContext)
 {
     _mauiContext = mauiContext;
 }
Exemple #29
0
        /// <include file="../../docs/Microsoft.Maui/ViewExtensions.xml" path="//Member[@MemberName='ToHandler']/Docs" />

        public static IPlatformViewHandler ToHandler(this IView view, IMauiContext context) =>
        (IPlatformViewHandler)ElementExtensions.ToHandler(view, context);
Exemple #30
0
 public static void SetWindowHandler(this PlatformWindow platformWindow, IWindow window, IMauiContext context) =>
 SetHandler(platformWindow, window, context);