private static async Task CreateNewWindowAsync(string id, Type page, object par)
        {
            await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                //if (Data.TmpData.OpenedWindows.TryGetValue(id, out int value))
                //{
                //    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(value);
                //}
                //else
                {
                    int newViewId = -1;

                    CoreApplicationView newView = CoreApplication.CreateNewView();

                    await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        var newWindow    = Window.Current;
                        var newAppView   = ApplicationView.GetForCurrentView();
                        var sysnm        = Windows.UI.Core.SystemNavigationManager.GetForCurrentView();
                        var frame        = new Frame();
                        frame.Navigated += (s, e) =>
                        {
                            if (frame.Content is IBackable)
                            {
                                sysnm.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
                            }
                            else
                            {
                                sysnm.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
                            }
                        };
                        sysnm.BackRequested += (s, e) =>
                        {
                            if (frame.Content is IBackable iba)
                            {
                                if (!iba.GoBack())
                                {
                                    var a = Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                    {
                                        Window.Current.Close();
                                    });
                                }
                                else
                                {
                                    e.Handled = true;
                                }
                            }
                        };
                        newWindow.Closed += async(s, e) =>
                        {
                            Window.Current.Content = null;
                            await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                            {
                                Data.TmpData.OpenedWindows.Remove(id);
                            });
                        };
                        frame.Navigate(page, par);
                        newWindow.Content = frame;
                        newWindow.Activate();
                        newViewId = newAppView.Id;
                    });
                    Data.TmpData.OpenedWindows[id] = newViewId;
                    var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
                }
            });
Exemplo n.º 2
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
                // Ensure the current window is active
                Window.Current.Activate();
            }


            // Create 2 secondary views
            if (_viewIds.Count < 2)
            {
                CoreApplicationView newView = CoreApplication.CreateNewView();
                int newViewId = 0;
                await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    Frame frame            = new Frame();
                    Window.Current.Content = frame;
                    Window.Current.Activate();
                    ApplicationView appView = ApplicationView.GetForCurrentView();
                    newViewId     = appView.Id;
                    appView.Title = newViewId.ToString();
                    _viewIds.Add(newViewId);
                });

                bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
            }
            else
            {
                // Switch to first secondary view, BUT focuses on last secondary view :/
                Debug.WriteLine("Switching to secondary view with id: " + _viewIds[0]);
                await ApplicationViewSwitcher.SwitchAsync(_viewIds[0]);
            }
        }
Exemplo n.º 3
0
        private async void BtnNext1_Click(object sender, RoutedEventArgs e)
        {
            if (filename.Visibility == Visibility.Collapsed)
            {
                try
                {
                    if (!String.IsNullOrWhiteSpace(userCreate.Text))
                    {
                        // Add User's Name to Local Settings
                        settings.Values["Name"] = userCreate.Text;

                        //Add Back Up Credentials to local settings and check if valid password
                        if (backupPassword.IsEnabled && !String.IsNullOrWhiteSpace(backupPassword.Password) && checkValidPassword(backupPassword.Password))
                        {
                            settings.Values["Backup"] = backupPassword.Password;
                        }
                        else if (backupPassword.IsEnabled && (String.IsNullOrWhiteSpace(backupPassword.Password) || !checkValidPassword(backupPassword.Password)))
                        {
                            // Getting fancy with custom exceptions
                            throw new InvalidPasswordException("Invalid Password");
                        }
                    }
                    else
                    {
                        throw new InvalidNameException("Invalid Name");
                    }

                    if (lockCheck.IsChecked == true)
                    {
                        settings.Values["Lock"] = "true";
                    }
                    else
                    {
                        settings.Values["Lock"] = "false";
                    }

                    filename.Visibility       = Visibility.Visible;
                    fileselect.Visibility     = Visibility.Visible;
                    preview.Visibility        = Visibility.Visible;
                    backupPassword.Visibility = Visibility.Collapsed;
                    userCreate.Visibility     = Visibility.Collapsed;
                    lockCheck.Visibility      = Visibility.Collapsed;

                    Title.Text = "Let's Pick a Picture";
                }
                catch (Exception ex)
                {
                    if (ex is InvalidPasswordException)
                    {
                        retrieveMsgDialog("Please enter a valid backup password", ex.Message);
                    }
                    else if (ex is InvalidNameException)
                    {
                        retrieveMsgDialog("Please enter a valid name", ex.Message);
                    }
                }
            }
            else
            {
                // Navigating to the next page, Password Creation
                CoreApplicationView view = CoreApplication.CreateNewView();
                int newViewId            = 0;
                await view.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    // C# Lambda Expression

                    Frame frame = new Frame();
                    frame.Navigate(typeof(Password));
                    Window.Current.Content = frame;
                    Window.Current.Activate();

                    newViewId = ApplicationView.GetForCurrentView().Id;
                });

                await ApplicationViewSwitcher.SwitchAsync(newViewId);
            }
        }
Exemplo n.º 4
0
 private async void OnUnlockClick(object sender, Windows.UI.Xaml.RoutedEventArgs e)
 {
     var context = ServiceLocator.Current.GetService <IContextService>();
     await ApplicationViewSwitcher.SwitchAsync(context.MainViewID);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Call this method in Unity App Thread can switch to Plan View, create and show a new XAML View.
        /// </summary>
        /// <typeparam name="TReturnValue"></typeparam>
        /// <param name="xamlPageName"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public IEnumerator OnLaunchXamlView <TReturnValue>(string xamlPageName, Action <TReturnValue> callback, object pageNavigateParameter = null)
        {
            bool isCompleted = false;

#if !UNITY_EDITOR && UNITY_WSA && !(ENABLE_IL2CPP && NET_STANDARD_2_0)
            object returnValue          = null;
            CoreApplicationView newView = CoreApplication.CreateNewView();
            int newViewId = 0;
            var dispt     = newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                //This happens when User switch view back to Main App manually
                //void CoreWindow_VisibilityChanged(CoreWindow sender, VisibilityChangedEventArgs args)
                //{
                //    if (args.Visible == false)
                //    {
                //        CallbackReturnValue(null);
                //    }
                //}
                //newView.CoreWindow.VisibilityChanged += CoreWindow_VisibilityChanged;
                //Frame frame = new Frame();
                //var pageType = Type.GetType(Windows.UI.Xaml.Application.Current.GetType().AssemblyQualifiedName.Replace(".App,", $".{xamlPageName},"));
                //var appv = ApplicationView.GetForCurrentView();
                //newViewId = appv.Id;
                //var cb = new Action<object>(rval =>
                //{
                //    returnValue = rval;
                //    isCompleted = true;
                //});
                //frame.Navigate(pageType,pageNavigateParameter);
                //CallbackDictionary[newViewId] = cb;
                //Window.Current.Content = frame;
                //Window.Current.Activate();
            }).AsTask();
            yield return(new WaitUntil(() => dispt.IsCompleted || dispt.IsCanceled || dispt.IsFaulted));

            Task viewShownTask = null;
            UnityEngine.WSA.Application.InvokeOnUIThread(
                () =>
            {
                viewShownTask = ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId).AsTask();
            },
                true);
            yield return(new WaitUntil(() => viewShownTask.IsCompleted || viewShownTask.IsCanceled || viewShownTask.IsFaulted));

            yield return(new WaitUntil(() => isCompleted));

            try
            {
                if (returnValue is TReturnValue)
                {
                    callback?.Invoke((TReturnValue)returnValue);
                }
                else
                {
                    callback?.Invoke(default(TReturnValue));
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
#else
            isCompleted = true;
            yield return(new WaitUntil(() => isCompleted));
#endif
        }
Exemplo n.º 6
0
        public static async Task OpenPropertiesWindowAsync(object item, IShellPage associatedInstance)
        {
            if (item == null)
            {
                return;
            }

            if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
            {
                if (WindowDecorationsHelper.IsWindowDecorationsAllowed)
                {
                    AppWindow appWindow = await AppWindow.TryCreateAsync();

                    Frame frame = new Frame();
                    frame.RequestedTheme = ThemeHelper.RootTheme;
                    frame.Navigate(typeof(Properties), new PropertiesPageNavigationArguments()
                    {
                        Item = item,
                        AppInstanceArgument = associatedInstance
                    }, new SuppressNavigationTransitionInfo());
                    ElementCompositionPreview.SetAppWindowContent(appWindow, frame);
                    (frame.Content as Properties).appWindow = appWindow;

                    appWindow.TitleBar.ExtendsContentIntoTitleBar = true;
                    appWindow.Title            = "PropertiesTitle".GetLocalized();
                    appWindow.PersistedStateId = "Properties";
                    WindowManagementPreview.SetPreferredMinSize(appWindow, new Size(460, 550));

                    bool windowShown = await appWindow.TryShowAsync();

                    if (windowShown)
                    {
                        // Set window size again here as sometimes it's not resized in the page Loaded event
                        appWindow.RequestSize(new Size(460, 550));

                        DisplayRegion displayRegion   = ApplicationView.GetForCurrentView().GetDisplayRegions()[0];
                        Point         pointerPosition = CoreWindow.GetForCurrentThread().PointerPosition;
                        appWindow.RequestMoveRelativeToDisplayRegion(displayRegion,
                                                                     new Point(pointerPosition.X - displayRegion.WorkAreaOffset.X, pointerPosition.Y - displayRegion.WorkAreaOffset.Y));
                    }
                }
                else
                {
                    CoreApplicationView newWindow = CoreApplication.CreateNewView();
                    ApplicationView     newView   = null;

                    await newWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        Frame frame          = new Frame();
                        frame.RequestedTheme = ThemeHelper.RootTheme;
                        frame.Navigate(typeof(Properties), new PropertiesPageNavigationArguments()
                        {
                            Item = item,
                            AppInstanceArgument = associatedInstance
                        }, new SuppressNavigationTransitionInfo());
                        Window.Current.Content = frame;
                        Window.Current.Activate();

                        newView = ApplicationView.GetForCurrentView();
                        newWindow.TitleBar.ExtendViewIntoTitleBar = true;
                        newView.Title            = "PropertiesTitle".GetLocalized();
                        newView.PersistedStateId = "Properties";
                        newView.SetPreferredMinSize(new Size(460, 550));

                        bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newView.Id);
                        if (viewShown && newView != null)
                        {
                            // Set window size again here as sometimes it's not resized in the page Loaded event
                            newView.TryResizeView(new Size(460, 550));
                        }
                    });
                }
            }
            else
            {
                var propertiesDialog = new PropertiesDialog();
                propertiesDialog.propertiesFrame.Tag = propertiesDialog;
                propertiesDialog.propertiesFrame.Navigate(typeof(Properties), new PropertiesPageNavigationArguments()
                {
                    Item = item,
                    AppInstanceArgument = associatedInstance
                }, new SuppressNavigationTransitionInfo());
                await propertiesDialog.ShowAsync(ContentDialogPlacement.Popup);
            }
        }
Exemplo n.º 7
0
        private async Task CreateNewTerminalWindow(string startupDirectory)
        {
            var id = await CreateSecondaryView <MainViewModel>(typeof(MainPage), true, startupDirectory).ConfigureAwait(true);

            await ApplicationViewSwitcher.TryShowAsStandaloneAsync(id);
        }
Exemplo n.º 8
0
 private async void OpenMainWindow()
 {
     await ApplicationViewSwitcher.TryShowAsStandaloneAsync(ApplicationView.GetApplicationViewIdForWindow(CoreApplication.MainView.CoreWindow));
 }
Exemplo n.º 9
0
 public async Task GoBackToMainViewAsync()
 {
     await ApplicationViewSwitcher.TryShowAsStandaloneAsync(mainViewId);
 }
Exemplo n.º 10
0
        public async Task <ViewLifetimeControl> OpenAsync(Type page, object parameter = null, string title = null,
                                                          ViewSizePreference size     = ViewSizePreference.UseHalf, int session = 0, string id = "0")
        {
            Logger.Info($"Page: {page}, Parameter: {parameter}, Title: {title}, Size: {size}");

            var currentView = ApplicationView.GetForCurrentView();

            title ??= currentView.Title;



            if (parameter != null && _windows.TryGetValue(parameter, out IDispatcherContext value))
            {
                var newControl = await value.DispatchAsync(async() =>
                {
                    var control    = ViewLifetimeControl.GetForCurrentView();
                    var newAppView = ApplicationView.GetForCurrentView();

                    await ApplicationViewSwitcher
                    .SwitchAsync(newAppView.Id, currentView.Id, ApplicationViewSwitchingOptions.Default);

                    return(control);
                }).ConfigureAwait(false);

                return(newControl);
            }
            else
            {
                //if (ApiInformation.IsPropertyPresent("Windows.UI.ViewManagement.ApplicationView", "PersistedStateId"))
                //{
                //    try
                //    {
                //        ApplicationView.ClearPersistedState("Calls");
                //    }
                //    catch { }
                //}

                var newView    = CoreApplication.CreateNewView();
                var dispatcher = new DispatcherContext(newView.DispatcherQueue);

                if (parameter != null)
                {
                    _windows[parameter] = dispatcher;
                }

                var bounds = Window.Current.Bounds;

                var newControl = await dispatcher.DispatchAsync(async() =>
                {
                    var newWindow    = Window.Current;
                    var newAppView   = ApplicationView.GetForCurrentView();
                    newAppView.Title = title;

                    if (ApiInformation.IsPropertyPresent("Windows.UI.ViewManagement.ApplicationView", "PersistedStateId"))
                    {
                        newAppView.PersistedStateId = "Floating";
                    }

                    var control       = ViewLifetimeControl.GetForCurrentView();
                    control.Released += (s, args) =>
                    {
                        if (parameter != null)
                        {
                            _windows.TryRemove(parameter, out IDispatcherContext _);
                        }

                        //newWindow.Close();
                    };

                    var nav = BootStrapper.Current.NavigationServiceFactory(BootStrapper.BackButton.Ignore, BootStrapper.ExistingContent.Exclude, session, id, false);
                    nav.Navigate(page, parameter);
                    newWindow.Content = BootStrapper.Current.CreateRootElement(nav);
                    newWindow.Activate();

                    await ApplicationViewSwitcher
                    .TryShowAsStandaloneAsync(newAppView.Id, ViewSizePreference.Default, currentView.Id, size);
                    //newAppView.TryResizeView(new Windows.Foundation.Size(360, bounds.Height));
                    newAppView.TryResizeView(new Size(360, 640));

                    return(control);
                }).ConfigureAwait(false);

                return(newControl);
            }
        }
Exemplo n.º 11
0
        public async Task <ViewLifetimeControl> OpenAsync(Func <ViewLifetimeControl, UIElement> content, object parameter, double width, double height, ApplicationViewMode viewMode)
        {
            if (_windows.TryGetValue(parameter, out IDispatcherContext value))
            {
                var newControl = await value.DispatchAsync(async() =>
                {
                    var control    = ViewLifetimeControl.GetForCurrentView();
                    var newAppView = ApplicationView.GetForCurrentView();

                    var preferences        = ViewModePreferences.CreateDefault(viewMode);
                    preferences.CustomSize = new Size(width, height);

                    await ApplicationViewSwitcher
                    .TryShowAsViewModeAsync(newAppView.Id, viewMode, preferences);

                    return(control);
                }).ConfigureAwait(false);

                return(newControl);
            }
            else
            {
                var newView    = CoreApplication.CreateNewView();
                var dispatcher = new DispatcherContext(newView.Dispatcher);
                _windows[parameter] = dispatcher;

                var newControl = await dispatcher.DispatchAsync(async() =>
                {
                    var newWindow     = Window.Current;
                    newWindow.Closed += (s, args) =>
                    {
                        _windows.TryRemove(parameter, out _);
                    };
                    newWindow.CoreWindow.Closed += (s, args) =>
                    {
                        _windows.TryRemove(parameter, out _);
                    };

                    var newAppView           = ApplicationView.GetForCurrentView();
                    newAppView.Consolidated += (s, args) =>
                    {
                        _windows.TryRemove(parameter, out _);
                        newWindow.Close();
                    };

                    if (ApiInformation.IsPropertyPresent("Windows.UI.ViewManagement.ApplicationView", "PersistedStateId"))
                    {
                        newAppView.PersistedStateId = "Calls";
                    }

                    var control       = ViewLifetimeControl.GetForCurrentView();
                    control.Released += (s, args) =>
                    {
                        _windows.TryRemove(parameter, out _);
                        newWindow.Close();
                    };

                    newWindow.Content = content(control);
                    newWindow.Activate();

                    var preferences        = ViewModePreferences.CreateDefault(viewMode);
                    preferences.CustomSize = new Size(width, height);

                    await ApplicationViewSwitcher.TryShowAsViewModeAsync(newAppView.Id, viewMode, preferences);

                    return(control);
                }).ConfigureAwait(false);

                return(newControl);
            }
        }
Exemplo n.º 12
0
 public async Task SwitchToMainViewAsync()
 {
     await ApplicationViewSwitcher.SwitchAsync(this.MainViewId);
 }
Exemplo n.º 13
0
        public async Task ShowNew()
        {
            var id = await CreateNewWindow(typeof(MainPage), true);

            bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(id);
        }
Exemplo n.º 14
0
 public static async void ShowMainView()
 {
     bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(MainView.Id);
 }
 private async Task SwitchViewCommandExecute()
 {
     await ApplicationViewSwitcher.SwitchAsync(App.MainViewId);
 }
Exemplo n.º 16
0
        private void OnAppLaunch(IActivatedEventArgs args, string argument)
        {
            // Uncomment the following lines to display frame-rate and per-frame CPU usage info.
            //#if _DEBUG
            //    if (IsDebuggerPresent())
            //    {
            //        DebugSettings->EnableFrameRateCounter = true;
            //    }
            //#endif

            args.SplashScreen.Dismissed += DismissedEventHandler;

            var           rootFrame = (Window.Current.Content as Frame);
            WeakReference weak      = new WeakReference(this);

            float minWindowWidth  = (float)((double)Resources[ApplicationResourceKeys.Globals.AppMinWindowWidth]);
            float minWindowHeight = (float)((double)Resources[ApplicationResourceKeys.Globals.AppMinWindowHeight]);
            Size  minWindowSize   = SizeHelper.FromDimensions(minWindowWidth, minWindowHeight);

            ApplicationView          appView       = ApplicationView.GetForCurrentView();
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

            // For very first launch, set the size of the calc as size of the default standard mode
            if (!localSettings.Values.ContainsKey("VeryFirstLaunch"))
            {
                localSettings.Values["VeryFirstLaunch"] = false;
                appView.SetPreferredMinSize(minWindowSize);
                appView.TryResizeView(minWindowSize);
            }
            else
            {
                ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto;
            }

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) // PC Family
                {
                    // Disable the system view activation policy during the first launch of the app
                    // only for PC family devices and not for phone family devices
                    try
                    {
                        ApplicationViewSwitcher.DisableSystemViewActivationPolicy();
                    }
                    catch (Exception)
                    {
                        // Log that DisableSystemViewActionPolicy didn't work
                    }
                }

                // Create a Frame to act as the navigation context
                rootFrame = App.CreateFrame();

                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), argument))
                {
                    // We couldn't navigate to the main page, kill the app so we have a good
                    // stack to debug
                    throw new SystemException();
                }

                SetMinWindowSizeAndThemeAndActivate(rootFrame, minWindowSize);
                m_mainViewId = ApplicationView.GetForCurrentView().Id;
                AddWindowToMap(WindowFrameService.CreateNewWindowFrameService(rootFrame, false, weak));
            }
            else
            {
                // For first launch, LaunchStart is logged in constructor, this is for subsequent launches.

                // !Phone check is required because even in continuum mode user interaction mode is Mouse not Touch
                if ((UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse) &&
                    (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
                {
                    // If the pre-launch hasn't happened then allow for the new window/view creation
                    if (!m_preLaunched)
                    {
                        var newCoreAppView = CoreApplication.CreateNewView();
                        _ = newCoreAppView.Dispatcher.RunAsync(
                            CoreDispatcherPriority.Normal, async() =>
                        {
                            if (weak.Target is App that)
                            {
                                var newRootFrame = App.CreateFrame();

                                SetMinWindowSizeAndThemeAndActivate(newRootFrame, minWindowSize);

                                if (!newRootFrame.Navigate(typeof(MainPage), argument))
                                {
                                    // We couldn't navigate to the main page, kill the app so we have a good
                                    // stack to debug
                                    throw new SystemException();
                                }

                                var frameService = WindowFrameService.CreateNewWindowFrameService(newRootFrame, true, weak);
                                that.AddWindowToMap(frameService);

                                var dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

                                // CSHARP_MIGRATION_ANNOTATION:
                                // class SafeFrameWindowCreation is being interpreted into a IDisposable class
                                // in order to enhance its RAII capability that was written in C++/CX
                                using (var safeFrameServiceCreation = new SafeFrameWindowCreation(frameService, that))
                                {
                                    int newWindowId = ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread());

                                    ActivationViewSwitcher activationViewSwitcher = null;
                                    var activateEventArgs = (args as IViewSwitcherProvider);
                                    if (activateEventArgs != null)
                                    {
                                        activationViewSwitcher = activateEventArgs.ViewSwitcher;
                                    }

                                    if (activationViewSwitcher != null)
                                    {
                                        _ = activationViewSwitcher.ShowAsStandaloneAsync(newWindowId, ViewSizePreference.Default);
                                        safeFrameServiceCreation.SetOperationSuccess(true);
                                    }
                                    else
                                    {
                                        var activatedEventArgs = (args as IApplicationViewActivatedEventArgs);
                                        if ((activatedEventArgs != null) && (activatedEventArgs.CurrentlyShownApplicationViewId != 0))
                                        {
                                            // CSHARP_MIGRATION_ANNOTATION:
                                            // here we don't use ContinueWith() to interpret origin code because we would like to
                                            // pursue the design of class SafeFrameWindowCreate whichi was using RAII to ensure
                                            // some states get handled properly when its instance is being destructed.
                                            //
                                            // To achieve that, SafeFrameWindowCreate has been reinterpreted using IDisposable
                                            // pattern, which forces we use below way to keep async works being controlled within
                                            // a same code block.
                                            var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
                                                frameService.GetViewId(),
                                                ViewSizePreference.Default,
                                                activatedEventArgs.CurrentlyShownApplicationViewId,
                                                ViewSizePreference.Default);
                                            // SafeFrameServiceCreation is used to automatically remove the frame
                                            // from the list of frames if something goes bad.
                                            safeFrameServiceCreation.SetOperationSuccess(viewShown);
                                        }
                                    }
                                }
                            }
                        });
 private async Task HideViewCommandExecute()
 {
     await ApplicationViewSwitcher.SwitchAsync(App.MainViewId,
                                               ApplicationView.GetForCurrentView().Id,
                                               ApplicationViewSwitchingOptions.ConsolidateViews);
 }
 private async void Button_Click(object sender, RoutedEventArgs e)
 {
     await ApplicationViewSwitcher.TryShowAsStandaloneAsync(_MainViewId);
 }
Exemplo n.º 19
0
        public static async Task <List <int> > OpenFilesAndCreateNewTabsFiles(int IDList, StorageListTypes type)
        {
            var list_ids = new List <int>();

            switch (type)
            {
            case StorageListTypes.LocalStorage:
                var opener = new FileOpenPicker();
                opener.ViewMode = PickerViewMode.Thumbnail;
                opener.SuggestedStartLocation = PickerLocationId.ComputerFolder;
                opener.FileTypeFilter.Add("*");

                IReadOnlyList <StorageFile> files = await opener.PickMultipleFilesAsync();

                foreach (StorageFile file in files)
                {
                    await Task.Run(() =>
                    {
                        if (file != null)
                        {
                            StorageApplicationPermissions.FutureAccessList.Add(file);
                            var tab = new InfosTab {
                                TabName = file.Name, TabStorageMode = type, TabContentType = ContentType.File, CanBeDeleted = true, CanBeModified = true, TabOriginalPathContent = file.Path, TabInvisibleByDefault = false, TabType = LanguagesHelper.GetLanguageType(file.Name)
                            };

                            int id_tab = Task.Run(async() => { return(await TabsWriteManager.CreateTabAsync(tab, IDList, false)); }).Result;
                            if (Task.Run(async() => { return(await new StorageRouter(TabsAccessManager.GetTabViaID(new TabID {
                                    ID_Tab = id_tab, ID_TabsList = IDList
                                }), IDList).ReadFile(true)); }).Result)
                            {
                                Messenger.Default.Send(new STSNotification {
                                    Type = TypeUpdateTab.NewTab, ID = new TabID {
                                        ID_Tab = id_tab, ID_TabsList = IDList
                                    }
                                });
                            }

                            list_ids.Add(id_tab);
                        }
                    });
                }
                break;

            case StorageListTypes.OneDrive:
                var currentAV = ApplicationView.GetForCurrentView(); var newAV = CoreApplication.CreateNewView();

                await newAV.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    async() =>
                {
                    var newWindow    = Window.Current;
                    var newAppView   = ApplicationView.GetForCurrentView();
                    newAppView.Title = "OneDrive explorer";

                    var frame = new Frame();
                    frame.Navigate(typeof(OnedriveExplorer), new Tuple <OnedriveExplorerMode, TabID>(OnedriveExplorerMode.SelectFile, new TabID {
                        ID_TabsList = IDList
                    }));
                    newWindow.Content = frame;
                    newWindow.Activate();

                    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
                        newAppView.Id,
                        ViewSizePreference.UseHalf,
                        currentAV.Id,
                        ViewSizePreference.UseHalf);
                });

                break;
            }

            return(list_ids);
        }
Exemplo n.º 20
0
        public async Task <ViewLifetimeControl> OpenAsync(Type page, object parameter = null, string title = null,
                                                          ViewSizePreference size     = ViewSizePreference.UseHalf, int session = 0, string id = "0")
        {
            WriteLine($"Page: {page}, Parameter: {parameter}, Title: {title}, Size: {size}");

            var currentView = ApplicationView.GetForCurrentView();

            title = title ?? currentView.Title;



            if (parameter != null && _windows.TryGetValue(parameter, out DispatcherWrapper value))
            {
                var newControl = await value.Dispatch(async() =>
                {
                    var control    = ViewLifetimeControl.GetForCurrentView();
                    var newAppView = ApplicationView.GetForCurrentView();

                    var preferences        = ViewModePreferences.CreateDefault(ApplicationViewMode.Default);
                    preferences.CustomSize = new Windows.Foundation.Size(360, 640);

                    await ApplicationViewSwitcher
                    .SwitchAsync(newAppView.Id, currentView.Id, ApplicationViewSwitchingOptions.Default);

                    return(control);
                }).ConfigureAwait(false);

                return(newControl);
            }
            else
            {
                var newView    = CoreApplication.CreateNewView();
                var dispatcher = new DispatcherWrapper(newView.Dispatcher);

                if (parameter != null)
                {
                    _windows[parameter] = dispatcher;
                }

                var bounds = Window.Current.Bounds;

                var newControl = await dispatcher.Dispatch(async() =>
                {
                    var newWindow    = Window.Current;
                    var newAppView   = ApplicationView.GetForCurrentView();
                    newAppView.Title = title;

                    var control       = ViewLifetimeControl.GetForCurrentView();
                    control.Released += (s, args) =>
                    {
                        if (parameter != null)
                        {
                            _windows.TryRemove(parameter, out DispatcherWrapper ciccio);
                        }

                        newWindow.Close();
                    };

                    var nav = BootStrapper.Current.NavigationServiceFactory(BootStrapper.BackButton.Ignore, BootStrapper.ExistingContent.Exclude, session, id, false);
                    control.NavigationService = nav;
                    nav.Navigate(page, parameter);
                    newWindow.Content = BootStrapper.Current.CreateRootElement(nav);
                    newWindow.Activate();

                    await ApplicationViewSwitcher
                    .TryShowAsStandaloneAsync(newAppView.Id, ViewSizePreference.Default, currentView.Id, size);
                    //newAppView.TryResizeView(new Windows.Foundation.Size(360, bounds.Height));
                    newAppView.TryResizeView(new Windows.Foundation.Size(360, 640));

                    return(control);
                }).ConfigureAwait(false);

                return(newControl);
            }
        }
Exemplo n.º 21
0
        public async void NavigateToWallet(string address = null)
        {
            Type page;

            if (_protoService.Options.WalletPublicKey != null)
            {
                try
                {
                    var vault      = new PasswordVault();
                    var credential = vault.Retrieve($"{_protoService.SessionId}", _protoService.Options.WalletPublicKey);
                }
                catch
                {
                    // Credentials for this account wallet don't exist anymore.
                    _protoService.Options.WalletPublicKey = null;
                }
            }

            if (_protoService.Options.WalletPublicKey != null)
            {
                if (address == null)
                {
                    page = typeof(WalletPage);
                }
                else
                {
                    page = typeof(WalletSendPage);
                }
            }
            else
            {
                page = typeof(WalletCreatePage);
            }

            //page = typeof(WalletCreatePage);

            //Navigate(page, address);
            //return;

            if (_walletLifetime == null)
            {
                _walletLifetime = await OpenAsync(page, address);

                _walletLifetime.Released += (s, args) =>
                {
                    _walletLifetime = null;
                };

                if (_walletLifetime.NavigationService is NavigationService service)
                {
                    service.SerializationService = TLSerializationService.Current;
                }
            }
            else
            {
                await _walletLifetime.CoreDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    _walletLifetime.NavigationService.Navigate(page, address);
                });

                await ApplicationViewSwitcher.TryShowAsStandaloneAsync(_walletLifetime.Id, ViewSizePreference.Default, ApplicationView.GetApplicationViewIdForWindow(Window.Current.CoreWindow), ViewSizePreference.UseHalf);
            }
        }
Exemplo n.º 22
0
        public async Task <ViewLifetimeControl> OpenAsync(Func <UIElement> content, object parameter, double width, double height)
        {
            if (_windows.TryGetValue(parameter, out DispatcherWrapper value))
            {
                var newControl = await value.Dispatch(async() =>
                {
                    var control    = ViewLifetimeControl.GetForCurrentView();
                    var newAppView = ApplicationView.GetForCurrentView();

                    var preferences        = ViewModePreferences.CreateDefault(ApplicationViewMode.CompactOverlay);
                    preferences.CustomSize = new Size(width, height);

                    await ApplicationViewSwitcher
                    .TryShowAsViewModeAsync(newAppView.Id, ApplicationViewMode.CompactOverlay, preferences);

                    return(control);
                }).ConfigureAwait(false);

                return(newControl);
            }
            else
            {
                var newView    = CoreApplication.CreateNewView();
                var dispatcher = new DispatcherWrapper(newView.Dispatcher);
                _windows[parameter] = dispatcher;

                var bounds = Window.Current.Bounds;

                var newControl = await dispatcher.Dispatch(async() =>
                {
                    var newWindow     = Window.Current;
                    newWindow.Closed += (s, args) =>
                    {
                        _windows.TryRemove(parameter, out DispatcherWrapper ciccio);
                    };
                    newWindow.CoreWindow.Closed += (s, args) =>
                    {
                        _windows.TryRemove(parameter, out DispatcherWrapper ciccio);
                    };

                    var newAppView           = ApplicationView.GetForCurrentView();
                    newAppView.Consolidated += (s, args) =>
                    {
                        _windows.TryRemove(parameter, out DispatcherWrapper ciccio);
                        newWindow.Close();
                    };

                    var control       = ViewLifetimeControl.GetForCurrentView();
                    control.Released += (s, args) =>
                    {
                        _windows.TryRemove(parameter, out DispatcherWrapper ciccio);
                        newWindow.Close();
                    };

                    newWindow.Content = content();
                    newWindow.Activate();

                    var preferences        = ViewModePreferences.CreateDefault(ApplicationViewMode.CompactOverlay);
                    preferences.CustomSize = new Size(width, height);

                    await ApplicationViewSwitcher
                    .TryShowAsViewModeAsync(newAppView.Id, ApplicationViewMode.CompactOverlay, preferences);

                    return(control);
                }).ConfigureAwait(false);

                return(newControl);
            }
        }
Exemplo n.º 23
0
        protected override async void OnFileActivated(FileActivatedEventArgs args)
        {
            // TODO: Handle file activation

            // The number of files received is args.Files.Size
            // The first file is args.Files[0].Name

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(320, 320));

                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                NavigationManager = SystemNavigationManager.GetForCurrentView();
                NavigationManager.BackRequested += (a, b) => OnBackRequested(a, b);

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(MainPage), args.Files[0]);
                ApplicationView.GetForCurrentView().Title = args.Files[0].Name.Substring(0, args.Files[0].Name.Length - 4);

                NavigationManager = SystemNavigationManager.GetForCurrentView();
                NavigationManager.BackRequested += OnBackRequested;
            }
            else
            {
                if (!ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
                {
                    var selectedView = await createMainPageAsync(args.Files[0].Name.Substring(0, args.Files[0].Name.Length - 4));

                    if (null != selectedView)
                    {
                        selectedView.StartViewInUse();
                        var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
                            selectedView.Id,
                            ViewSizePreference.Default,
                            ApplicationView.GetForCurrentView().Id,
                            ViewSizePreference.Default
                            );

                        await selectedView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            ((Frame)Window.Current.Content).Navigate(typeof(MainPage), args.Files[0]);
                            Window.Current.Activate();
                        });

                        selectedView.StopViewInUse();
                    }

                    NavigationManager = SystemNavigationManager.GetForCurrentView();
                    NavigationManager.BackRequested += OnBackRequested;
                }
            }

            Window.Current.Activate();
        }
Exemplo n.º 24
0
        private async void AnimatedSwitch_Click(object sender, RoutedEventArgs e)
        {
            // The sample demonstrates a general strategy for doing custom animations when switching view
            // It's technically only possible to animate the contents of a particular view. But, it is possible
            // to animate the outgoing view to some common visual (like a blank background), have the incoming
            // view draw that same visual, switch in the incoming window (which will be imperceptible to the
            // user since both windows will be showing the same thing), then animate the contents of the incoming
            // view in from the common visual.
            var selectedItem = ViewChooser.SelectedItem as ViewLifetimeControl;

            if (selectedItem != null)
            {
                try
                {
                    // Prevent the view from being closed while switching to it
                    selectedItem.StartViewInUse();

                    // Signal that the window is about to be switched to
                    // If the view is already shown to the user, then the app
                    // shouldn't run any extra animations
                    var  currentId     = ApplicationView.GetForCurrentView().Id;
                    bool isViewVisible = await ApplicationViewSwitcher.PrepareForCustomAnimatedSwitchAsync(
                        selectedItem.Id,
                        currentId,
                        ApplicationViewSwitchingOptions.SkipAnimation);

                    // The view may already be on screen, in which case there's no need to animate its
                    // contents (or animate out the contents of the current window)
                    if (!isViewVisible)
                    {
                        // The view isn't visible, so animate it on screen
                        lastFadeOutTime = DateTime.Now;

                        // Make the current view totally blank. The incoming view is also
                        // going to be totally blank when the two windows switch
                        await FadeOutContents();

                        // Once the current view is blank, switch in the other window
                        await selectedItem.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            var currentPage = (SecondaryViewPage)((Frame)Window.Current.Content).Content;
                            // More details are in SecondaryViewPage.xaml.cs
                            // This function makes the view totally blank, swaps the two view (which
                            // is not apparent to the user since both windows are blank), then animates
                            // in the content of newly visible view
                            currentPage.SwitchAndAnimate(currentId);
                        });
                    }
                    selectedItem.StopViewInUse();
                }
                catch (InvalidOperationException)
                {
                    // The view could be in the process of closing, and
                    // this thread just hasn't updated. As part of being closed,
                    // this thread will be informed to clean up its list of
                    // views (see SecondaryViewPage.xaml.cs)
                }
                catch (TaskCanceledException)
                {
                    rootPage.NotifyUser("The animation was canceled. It may have timed out", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Select a window to see a switch animation. You can create a window in scenario 1", NotifyType.ErrorMessage);
            }
        }
Exemplo n.º 25
0
        private async Task <PlayerViewManager> GetEnsureSecondaryView()
        {
            if (IsMainView && SecondaryCoreAppView == null)
            {
                var playerView = CoreApplication.CreateNewView();


                HohoemaSecondaryViewFrameViewModel vm = null;
                int                id   = 0;
                ApplicationView    view = null;
                INavigationService ns   = null;
                await playerView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    // SecondaryViewのスケジューラをセットアップ
                    SecondaryViewScheduler = new CoreDispatcherScheduler(playerView.Dispatcher);

                    playerView.TitleBar.ExtendViewIntoTitleBar = true;

                    var content = new Views.HohoemaSecondaryViewFrame();
                    ns          = NavigationService.Create(content.Frame, playerView.CoreWindow);

                    vm = content.DataContext as HohoemaSecondaryViewFrameViewModel;

                    Window.Current.Content = content;

                    id = ApplicationView.GetApplicationViewIdForWindow(playerView.CoreWindow);

                    view = ApplicationView.GetForCurrentView();

                    view.TitleBar.ButtonBackgroundColor         = Windows.UI.Colors.Transparent;
                    view.TitleBar.ButtonInactiveBackgroundColor = Windows.UI.Colors.Transparent;

                    Window.Current.Activate();

                    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(id, ViewSizePreference.UseHalf, MainViewId, ViewSizePreference.UseHalf);

                    // ウィンドウサイズの保存と復元
                    if (Services.Helpers.DeviceTypeHelper.IsDesktop)
                    {
                        var localObjectStorageHelper = App.Current.Container.Resolve <Microsoft.Toolkit.Uwp.Helpers.LocalObjectStorageHelper>();
                        if (localObjectStorageHelper.KeyExists(secondary_view_size))
                        {
                            view.TryResizeView(localObjectStorageHelper.Read <Size>(secondary_view_size));
                        }

                        view.VisibleBoundsChanged += View_VisibleBoundsChanged;
                    }

                    view.Consolidated += SecondaryAppView_Consolidated;
                });

                SecondaryAppView     = view;
                _SecondaryViewVM     = vm;
                SecondaryCoreAppView = playerView;
                SecondaryViewPlayerNavigationService = ns;

                App.Current.Container.GetContainer().RegisterInstance(SECONDARY_VIEW_PLAYER_NAVIGATION_SERVICE, SecondaryViewPlayerNavigationService);
            }

            return(this);
        }
        public async Task ActivateAsync(object activationArgs)
        {
            if (IsActivation(activationArgs))
            {
                // Initialize things like registering background task before the app is loaded
                await InitializeAsync();

                // We spawn a separate Window for files.
                if (activationArgs is FileActivatedEventArgs fileArgs)
                {
                    bool mainView = Window.Current.Content == null;
                    void CreateView()
                    {
                        FontMapView map = new FontMapView
                        {
                            IsStandalone = true,
                        };

                        _ = map.ViewModel.LoadFromFileArgsAsync(fileArgs);

                        // You have to activate the window in order to show it later.
                        Window.Current.Content = map;
                        Window.Current.Activate();
                    }

                    var view = await WindowService.CreateViewAsync(CreateView, false);

                    await WindowService.TrySwitchToWindowAsync(view, mainView);

                    return;
                }

                // Do not repeat app initialization when the Window already has content,
                // just ensure that the window is active
                if (WindowService.MainWindow == null)
                {
                    void CreateMainView()
                    {
                        // Create a Frame to act as the navigation context and navigate to the first page
                        Window.Current.Content = new Frame();
                        NavigationService.Frame.NavigationFailed += (sender, e) => throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
                        NavigationService.Frame.Navigated        += OnFrameNavigated;

                        if (SystemNavigationManager.GetForCurrentView() != null)
                        {
                            SystemNavigationManager.GetForCurrentView().BackRequested += OnAppViewBackButtonRequested;
                        }
                    }

                    var view = await WindowService.CreateViewAsync(CreateMainView, true);

                    await WindowService.TrySwitchToWindowAsync(view, true);
                }
                else
                {
                    /* Main Window exists, make it show */
                    _ = ApplicationViewSwitcher.TryShowAsStandaloneAsync(WindowService.MainWindow.View.Id);
                    WindowService.MainWindow.CoreView.CoreWindow.Activate();
                }
            }



            try
            {
                var activationHandler = GetActivationHandlers()?.FirstOrDefault(h => h.CanHandle(activationArgs));
                if (activationHandler != null)
                {
                    await activationHandler.HandleAsync(activationArgs);
                }
            }
            catch
            {
            }

            if (IsActivation(activationArgs))
            {
                var defaultHandler = new DefaultLaunchActivationHandler(_defaultNavItem);
                if (defaultHandler.CanHandle(activationArgs))
                {
                    await defaultHandler.HandleAsync(activationArgs);
                }

                DispatcherHelper.Initialize();

                // Ensure the current window is active
                Window.Current.Activate();

                ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto;

                // Tasks after activation
                await StartupAsync();
            }
        }
Exemplo n.º 27
0
        public async void CreateTool()
        {
            var num = CoreApplication.Views.Count();

            //if (localSettings.Values["newViewId"] != null)
            //    ApplicationViewSwitcher.SwitchAsync(Convert.ToInt32(localSettings.Values["newViewId"])).Close();
            if (localSettings.Values["ItemCount"] == null)
            {
                localSettings.Values["ItemCount"] = 0;
            }
            int count = (int)localSettings.Values["ItemCount"];
            List <DataTemple> datalist = new List <DataTemple>();
            var allData = conn.Query <DataTemple>("select *from DataTemple");

            switch (count)
            {
            case 1:
                string a1 = localSettings.Values["DesktopKey0"].ToString();
                foreach (var item in allData)
                {
                    if (item.Schedule_name == a1)
                    {
                        datalist.Add(item);
                    }
                }
                break;

            case 2:
                string b1 = localSettings.Values["DesktopKey0"].ToString();
                string b2 = localSettings.Values["DesktopKey1"].ToString();
                foreach (var item in allData)
                {
                    if (item.Schedule_name == b1 || item.Schedule_name == b2)
                    {
                        datalist.Add(item);
                    }
                }
                break;

            case 3:
                string c1 = localSettings.Values["DesktopKey0"].ToString();
                string c2 = localSettings.Values["DesktopKey1"].ToString();
                string c3 = localSettings.Values["DesktopKey2"].ToString();
                foreach (var item in allData)
                {
                    if (item.Schedule_name == c1 || item.Schedule_name == c2 || item.Schedule_name == c3)
                    {
                        datalist.Add(item);
                    }
                }
                break;

            default:
                return;
            }
            //var num = CoreApplication.Views.Count();
            //coreWindow.Activate();
            //CoreApplication.GetCurrentView();
            CoreApplicationView newView = CoreApplication.CreateNewView();
            int newViewId = 0;
            await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                Frame frame = new Frame();
                frame.Navigate(typeof(DesktopTool), datalist, new SuppressNavigationTransitionInfo());
                Window.Current.Content = frame;
                Window.Current.Activate();
                newViewId = ApplicationView.GetForCurrentView().Id;
                localSettings.Values["newViewId"] = newViewId;
            });

            bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);

            localSettings.Values["DesktopPin"] = false;
        }
Exemplo n.º 28
0
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var deferral = args.GetDeferral();
            var message  = args.Request.Message;

            try
            {
                if (message.ContainsKey("caption") && message.ContainsKey("request"))
                {
                    var caption = message["caption"] as string;
                    var buffer  = message["request"] as string;
                    var req     = TLSerializationService.Current.Deserialize(buffer);

                    if (caption.Equals("voip.getUser") && req is TLPeerUser userPeer)
                    {
                        var user = InMemoryCacheService.Current.GetUser(userPeer.UserId);
                        if (user != null)
                        {
                            await args.Request.SendResponseAsync(new ValueSet { { "result", TLSerializationService.Current.Serialize(user) } });
                        }
                        else
                        {
                            await args.Request.SendResponseAsync(new ValueSet { { "error", TLSerializationService.Current.Serialize(new TLRPCError {
                                        ErrorMessage = "USER_NOT_FOUND", ErrorCode = 404
                                    }) } });
                        }
                    }
                    else if (caption.Equals("voip.getConfig"))
                    {
                        var config = InMemoryCacheService.Current.GetConfig();
                        await args.Request.SendResponseAsync(new ValueSet { { "result", TLSerializationService.Current.Serialize(config) } });
                    }
                    else if (caption.Equals("voip.callInfo") && req is byte[] data)
                    {
                        using (var from = new TLBinaryReader(data))
                        {
                            var tupleBase = new TLTuple <int, TLPhoneCallBase, TLUserBase, string>(from);
                            var tuple     = new TLTuple <TLPhoneCallState, TLPhoneCallBase, TLUserBase, string>((TLPhoneCallState)tupleBase.Item1, tupleBase.Item2, tupleBase.Item3, tupleBase.Item4);

                            if (tuple.Item2 is TLPhoneCallDiscarded)
                            {
                                if (_phoneView != null)
                                {
                                    var newView = _phoneView;
                                    _phoneViewExists = false;
                                    _phoneView       = null;

                                    await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                    {
                                        newView.SetCall(tuple);
                                        newView.Dispose();
                                        Window.Current.Close();
                                    });
                                }

                                return;
                            }

                            if (_phoneViewExists == false)
                            {
                                VoIPCallTask.Log("Creating VoIP UI", "Creating VoIP UI");

                                _phoneViewExists = true;

                                PhoneCallPage       newPlayer = null;
                                CoreApplicationView newView   = CoreApplication.CreateNewView();
                                var newViewId = 0;
                                await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    newPlayer = new PhoneCallPage();
                                    Window.Current.Content = newPlayer;
                                    Window.Current.Activate();
                                    newViewId = ApplicationView.GetForCurrentView().Id;

                                    newPlayer.SetCall(tuple);
                                    _phoneView = newPlayer;
                                });

                                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                                {
                                    if (ApiInformation.IsMethodPresent("Windows.UI.ViewManagement.ApplicationView", "IsViewModeSupported") && ApplicationView.GetForCurrentView().IsViewModeSupported(ApplicationViewMode.CompactOverlay))
                                    {
                                        var preferences        = ViewModePreferences.CreateDefault(ApplicationViewMode.CompactOverlay);
                                        preferences.CustomSize = new Size(340, 200);

                                        var viewShown = await ApplicationViewSwitcher.TryShowAsViewModeAsync(newViewId, ApplicationViewMode.CompactOverlay, preferences);
                                    }
                                    else
                                    {
                                        //await ApplicationViewSwitcher.SwitchAsync(newViewId);
                                        await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
                                    }
                                });
                            }
                            else if (_phoneView != null)
                            {
                                VoIPCallTask.Log("VoIP UI already exists", "VoIP UI already exists");

                                await _phoneView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    _phoneView.SetCall(tuple);
                                });
                            }
                        }
                    }
                    else if (caption.Equals("voip.setCallRating") && req is TLInputPhoneCall peer)
                    {
                        Execute.BeginOnUIThread(async() =>
                        {
                            var dialog  = new PhoneCallRatingView();
                            var confirm = await dialog.ShowQueuedAsync();
                            if (confirm == ContentDialogResult.Primary)
                            {
                                await MTProtoService.Current.SetCallRatingAsync(peer, dialog.Rating, dialog.Rating >= 0 && dialog.Rating <= 3 ? dialog.Comment : null);
                            }
                        });
                    }
                    else
                    {
                        var response = await MTProtoService.Current.SendRequestAsync <object>(caption, req as TLObject);

                        if (response.IsSucceeded)
                        {
                            await args.Request.SendResponseAsync(new ValueSet { { "result", TLSerializationService.Current.Serialize(response.Result) } });
                        }
                        else
                        {
                            await args.Request.SendResponseAsync(new ValueSet { { "error", TLSerializationService.Current.Serialize(response.Error) } });
                        }
                    }
                }
            }
            finally
            {
                deferral.Complete();
            }
        }
Exemplo n.º 29
0
 public async Task CloseViewAsync()
 {
     int currentId = ApplicationView.GetForCurrentView().Id;
     await ApplicationViewSwitcher.SwitchAsync(MainViewId, currentId, ApplicationViewSwitchingOptions.ConsolidateViews);
 }
Exemplo n.º 30
0
        public override void Run()
        {
            UIElement main;

            try
            {
                string layoutString = layoutSetting.XamlString.Value;
                layoutFactory = () => (LayoutRoot)XamlReader.Load(layoutString);
                var layout = layoutFactory();
                main = new MainView {
                    MainContent = layout.MainWindow.LoadContent()
                };
                viewIds = layout.SubWindows.Select(x => x.Id).Append("Settings").ToArray();
            }
            catch
            {
                layoutFactory = () =>
                {
                    var l = new LayoutRoot();
                    Application.LoadComponent(l, new Uri("ms-appx:///Layout/Default.xaml"));
                    return(l);
                };
                var layout = layoutFactory();
                main = new MainView {
                    MainContent = layout.MainWindow.LoadContent()
                };
                viewIds = layout.SubWindows.Select(x => x.Id).Append("Settings").ToArray();
            }

            InitWindow();
            new UISettings().ColorValuesChanged += async(sender, _) =>
            {
                foreach (var view in CoreApplication.Views)
                {
                    await view.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                                                   ApplicationView.GetForCurrentView().TitleBar.ButtonForegroundColor = sender.GetColorValue(UIColorType.Foreground));
                }
            };

            var style = new Style
            {
                TargetType = typeof(ViewPresenter),
            };

            style.Setters.Add(new Setter(ViewPresenter.ViewSourceProperty, Views));
            Application.Current.Resources[typeof(ViewPresenter)]        = style;
            Application.Current.Resources[ViewSwitcher.SwitchActionKey] = new Action <string>(async viewId =>
            {
                if (applicationViewIds.TryGetValue(viewId, out int id))
                {
                    await ApplicationViewSwitcher.SwitchAsync(id);
                    return;
                }

                if (viewIds.Contains(viewId))
                {
                    var coreView = CoreApplication.CreateNewView();
                    await coreView.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                    {
                        CoreApplication.GetCurrentView().Properties["Id"] = viewId;
                        var view = ApplicationView.GetForCurrentView();
                        applicationViewIds[viewId] = view.Id;

                        InitWindow();
                        if (viewId == "Settings")
                        {
                            Window.Current.Content = new SettingsView(CreateSettingViews(), localizationService);
                        }
                        else
                        {
                            Window.Current.Content = new SubView {
                                ActualContent = layoutFactory()[viewId].LoadContent()
                            }
                        };

                        view.Consolidated += (s, e) =>
                        {
                            Window.Current.Content = null;
                            applicationViewIds.TryRemove(viewId, out _);
                        };

                        Window.Current.Activate();
                    });
                    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(applicationViewIds[viewId]);
                }
            });

            Window.Current.Content = main;
            gameProvider.Enabled   = true;
        }