Exemplo n.º 1
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.º 2
0
        protected override async void OnActivated(IActivatedEventArgs args)
        {
            if (args.Kind == ActivationKind.Protocol)
            {
                ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
                // TODO: Handle URI activation
                // The received URI is eventArgs.Uri.AbsoluteUri
                if (string.IsNullOrEmpty(eventArgs.Uri.Query))
                {
                    if (Window.Current.Content == null)
                    {
                        OnLaunched(null);
                    }
                    else
                    {
                        // TODO:
                        // seems like nothing to do.
                    }
                }
                else
                {
                    var query = HttpUtility.ParseQueryString(eventArgs.Uri.Query);
                    if (query["action"] != null)
                    {
                        switch (query["action"])
                        {
                        case "ext-setting":
                            if (Window.Current.Content == null)
                            {
                                // 创建要充当导航上下文的框架,并导航到第一页
                                rootFrame = new Frame();

                                // 将框架放在当前窗口中
                                Window.Current.Content = rootFrame;
                                rootFrame.Navigate(typeof(AboutPage));
                            }
                            else
                            {
                                CoreApplicationView newView = CoreApplication.CreateNewView();
                                int newViewId = 0;
                                await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    Frame frame = new Frame();
                                    frame.Navigate(typeof(ExtSettings));
                                    Window.Current.Content = frame;
                                    // You have to activate the window in order to show it later.
                                    Window.Current.Activate();

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

                                bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
                            }
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }
Exemplo n.º 3
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;
        }
Exemplo n.º 4
0
        private async void PinP_Click(object sender, RoutedEventArgs e)
        {
            if (!WvvPinPPage.IsSupported)
            {
                return;
            }

            if (null == mVideoFile)
            {
                var v = pickAndPlay(PinP_Click);
                return;
            }

            IPinPPlayer oldPlayer;

            if (mPinPPlayer.TryGetTarget(out oldPlayer) && null != oldPlayer)
            {
                oldPlayer.Close();
                return;
            }

            await WvvPinPPage.OpenPinP(MediaSource.CreateFromStorageFile(mVideoFile), 0, new Size(150, 300), (player, clientData) =>
            {
                //var timer = new DispatcherTimer();
                //timer.Interval = TimeSpan.FromSeconds(3);
                //timer.Tick += (x, a) =>
                //{
                //    player.Close();
                //};
                //timer.Start();
                player.Closed += (s, o) =>
                {
                    mPinPPlayer.SetTarget(null);
                };
                mPinPPlayer.SetTarget(player);
            });

#if false
            CoreApplicationView newView = CoreApplication.CreateNewView();
            int newViewId = 0;
            await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                Frame frame = new Frame();
                frame.Navigate(typeof(WvvPinPPage), mVideoFile);
                Window.Current.Content = frame;
                // You have to activate the window in order to show it later.

                //SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += (s, a) =>
                //{
                //    Debug.WriteLine("Close Requested");
                //};

                //Window.Current.Closed += (s, a) =>
                //{
                //    Debug.WriteLine("Closed");
                //};
                //Window.Current.Activated += (s, a) =>
                //{
                //    Debug.WriteLine(String.Format("Activated {0}", a.WindowActivationState.ToString()));
                //};
                //Window.Current.VisibilityChanged += (s, a) =>
                //{
                //    Debug.WriteLine(String.Format("Visibility Changed {0}", a.Visible.ToString()));
                //};
                Window.Current.Activate();

                newViewId = ApplicationView.GetForCurrentView().Id;
                await ApplicationView.GetForCurrentView().TryEnterViewModeAsync(ApplicationViewMode.CompactOverlay);
            });

            bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
#endif
        }
Exemplo n.º 5
0
        private void SelectMenu(string MenuName)
        {
            foreach (SettingsMenu menu in DefaultSettings.DefaultSettingsMenuList)
            {
                if (menu.Name == MenuName)
                {
                    //Delete the controls of the ancient menu
                    MenuControls.Children.Clear();

                    //Add the new controls of selected menu
                    foreach (Setting SettingControl in menu.Settings)
                    {
                        switch (SettingControl.Type)
                        {
                        case SettingType.Checkbox:
                            ToggleSwitch Switch = new ToggleSwitch();
                            Switch.Style      = (Style)Application.Current.Resources["SwitchControl"];
                            Switch.Margin     = new Thickness(0, 20, 0, 0);
                            Switch.Foreground = GlobalVariables.CurrentTheme.MainColorFont;
                            Switch.Background = GlobalVariables.CurrentTheme.MainColor;
                            Switch.Header     = SettingControl.Description;

                            if (AppSettings.Values.ContainsKey(SettingControl.VarSaveName))
                            {
                                Switch.IsOn = (bool)AppSettings.Values[SettingControl.VarSaveName];
                            }
                            else
                            {
                                Switch.IsOn = (bool)SettingControl.VarSaveDefaultContent;
                            }

                            Switch.Toggled += ((e, f) =>
                            {
                                ToggleSwitch SwitchContent = (ToggleSwitch)e;
                                AppSettings.Values[SettingControl.VarSaveName] = SwitchContent.IsOn;
                                Messenger.Default.Send(new SettingsNotification {
                                    SettingsUpdatedName = menu.Name
                                });
                            });


                            MenuControls.Children.Add(Switch);
                            break;

                        case SettingType.TextboxText:
                            StackPanel TextBoxControl = new StackPanel();
                            TextBoxControl.Margin = new Thickness(0, 20, 0, 0);

                            TextBlock TitleTextBox = new TextBlock();
                            TitleTextBox.FontSize     = 15;
                            TitleTextBox.TextWrapping = TextWrapping.Wrap;
                            TitleTextBox.Text         = SettingControl.Description;
                            TitleTextBox.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;

                            TextBoxControl.Children.Add(TitleTextBox);

                            TextBox TextBox = new TextBox();
                            TextBox.Margin = new Thickness(5, 5, 0, 0);

                            TextBox.Style = (Style)Application.Current.Resources["RoundTextBox"];
                            TextBox.Width = 150; TextBox.Height = 25;
                            //TextBox.PlaceholderText = "";
                            TextBox.FontSize = 14; TextBox.Background = GlobalVariables.CurrentTheme.SecondaryColor; TextBox.Foreground = GlobalVariables.CurrentTheme.SecondaryColorFont;
                            TextBox.KeyDown += ((e, f) =>
                            {
                                if (f.KeyStatus.RepeatCount == 1)
                                {
                                    if (f.Key == Windows.System.VirtualKey.Enter)
                                    {
                                        Messenger.Default.Send(new SettingsNotification {
                                            SettingsUpdatedName = menu.Name
                                        });
                                    }
                                }
                            });

                            TextBoxControl.Children.Add(TextBox);
                            MenuControls.Children.Add(TextBoxControl);
                            break;

                        case SettingType.TextboxNumber:
                            StackPanel TextBoxNmbControl = new StackPanel();
                            TextBoxNmbControl.Margin = new Thickness(0, 20, 0, 0);

                            TextBlock TitleTextBoxNmb = new TextBlock();
                            TitleTextBoxNmb.FontSize     = 15;
                            TitleTextBoxNmb.TextWrapping = TextWrapping.Wrap;
                            TitleTextBoxNmb.Text         = SettingControl.Description;
                            TitleTextBoxNmb.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;

                            TextBoxNmbControl.Children.Add(TitleTextBoxNmb);

                            TextBox TextBoxNmb = new TextBox();
                            TextBoxNmb.Margin = new Thickness(5, 5, 0, 0);

                            TextBoxNmb.Style = (Style)Application.Current.Resources["RoundTextBox"];
                            TextBoxNmb.Width = 150; TextBoxNmb.Height = 25;
                            TextBoxNmb.HorizontalAlignment = HorizontalAlignment.Left;
                            TextBoxNmb.FontSize            = 14; TextBoxNmb.Background = GlobalVariables.CurrentTheme.SecondaryColor; TextBoxNmb.Foreground = GlobalVariables.CurrentTheme.SecondaryColorFont;

                            if (AppSettings.Values.ContainsKey(SettingControl.VarSaveName))
                            {
                                TextBoxNmb.Text = ((int)AppSettings.Values[SettingControl.VarSaveName]).ToString();
                            }
                            else
                            {
                                TextBoxNmb.Text = ((int)SettingControl.VarSaveDefaultContent).ToString();
                            }

                            TextBoxNmb.KeyDown += ((e, f) =>
                            {
                                if (f.Key == Windows.System.VirtualKey.Enter)
                                {
                                    f.Handled = false;
                                    if (string.IsNullOrEmpty(TextBoxNmb.Text))
                                    {
                                        AppSettings.Values[SettingControl.VarSaveName] = (int)SettingControl.VarSaveDefaultContent;
                                    }
                                    else
                                    {
                                        AppSettings.Values[SettingControl.VarSaveName] = int.Parse(TextBoxNmb.Text);
                                    }
                                    Messenger.Default.Send(new SettingsNotification {
                                        SettingsUpdatedName = menu.Name
                                    });

                                    return;
                                }

                                if (f.Key.ToString().Equals("Back"))
                                {
                                    f.Handled = false;
                                    return;
                                }

                                for (int i = 0; i < 10; i++)
                                {
                                    if (f.Key.ToString() == string.Format("Number{0}", i))
                                    {
                                        f.Handled = false;
                                        return;
                                    }
                                }

                                f.Handled = true;
                            });

                            TextBoxNmbControl.Children.Add(TextBoxNmb);
                            MenuControls.Children.Add(TextBoxNmbControl);
                            break;

                        case SettingType.Link:
                            StackPanel LinkControl = new StackPanel();
                            LinkControl.Margin = new Thickness(0, 20, 0, 0);

                            TextBlock TitleLink = new TextBlock();
                            TitleLink.FontSize     = 15;
                            TitleLink.TextWrapping = TextWrapping.Wrap;
                            TitleLink.Text         = SettingControl.Description;
                            TitleLink.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;

                            LinkControl.Children.Add(TitleLink);

                            TextBlock Link = new TextBlock();
                            Link.Margin       = new Thickness(5, 5, 0, 0);
                            Link.FontSize     = 12;
                            Link.TextWrapping = TextWrapping.Wrap;
                            Link.FontStyle    = FontStyle.Italic;
                            Link.FontWeight   = FontWeights.Light;
                            Link.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;

                            Underline UnderlineText = new Underline();
                            Run       TextLink      = new Run();
                            TextLink.Text = (string)SettingControl.Parameter;
                            UnderlineText.Inlines.Add(TextLink);
                            Link.Inlines.Add(UnderlineText);

                            Link.PointerPressed += (async(e, f) =>
                            {
                                TextBlock LinkContent = (TextBlock)e;
                                await Windows.System.Launcher.LaunchUriAsync(new Uri(LinkContent.Text));
                            });

                            Link.PointerEntered += ((e, f) =>
                            {
                                Window.Current.CoreWindow.PointerCursor = new CoreCursor(CoreCursorType.Hand, 1);
                            });

                            Link.PointerExited += ((e, f) =>
                            {
                                Window.Current.CoreWindow.PointerCursor = new CoreCursor(CoreCursorType.Arrow, 1);
                            });

                            LinkControl.Children.Add(Link);
                            MenuControls.Children.Add(LinkControl);
                            break;

                        case SettingType.SecondDescription:
                            StackPanel DescriptionControl = new StackPanel();
                            DescriptionControl.Margin = new Thickness(0, 20, 0, 0);

                            TextBlock TitleDescription = new TextBlock();
                            TitleDescription.FontSize     = 15;
                            TitleDescription.TextWrapping = TextWrapping.Wrap;
                            TitleDescription.Text         = SettingControl.Description;
                            TitleDescription.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;

                            DescriptionControl.Children.Add(TitleDescription);

                            TextBlock Description = new TextBlock();
                            Description.Margin       = new Thickness(5, 5, 0, 0);
                            Description.TextWrapping = TextWrapping.Wrap;
                            Description.FontSize     = 13;
                            Description.FontWeight   = FontWeights.Light;
                            Description.Text         = (string)SettingControl.Parameter;
                            Description.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;

                            DescriptionControl.Children.Add(Description);
                            MenuControls.Children.Add(DescriptionControl);
                            break;

                        case SettingType.Separator:
                            Grid SeparatorControl = new Grid();
                            SeparatorControl.Margin = new Thickness(0, 20, 0, 0);
                            SeparatorControl.HorizontalAlignment = HorizontalAlignment.Stretch;

                            SeparatorControl.ColumnDefinitions.Add(new ColumnDefinition {
                                Width = GridLength.Auto
                            });
                            SeparatorControl.ColumnDefinitions.Add(new ColumnDefinition {
                                Width = new GridLength(1, GridUnitType.Star)
                            });

                            TextBlock TitleSeparator = new TextBlock();
                            TitleSeparator.FontSize   = 17;
                            TitleSeparator.FontWeight = FontWeights.SemiBold;
                            TitleSeparator.Text       = SettingControl.Description;
                            TitleSeparator.Foreground = GlobalVariables.CurrentTheme.MainColorFont;

                            SeparatorControl.Children.Add(TitleSeparator);

                            Rectangle RectSeparator = new Rectangle();
                            Grid.SetColumn(RectSeparator, 1);
                            RectSeparator.Height              = 2;
                            RectSeparator.Margin              = new Thickness(5, 2, 0, 0);
                            RectSeparator.VerticalAlignment   = VerticalAlignment.Center;
                            RectSeparator.HorizontalAlignment = HorizontalAlignment.Stretch;
                            RectSeparator.Fill = GlobalVariables.CurrentTheme.MainColorFont;

                            SeparatorControl.Children.Add(RectSeparator);
                            MenuControls.Children.Add(SeparatorControl);
                            break;

                        case SettingType.License:
                            StackPanel LicenseControl = new StackPanel();
                            LicenseControl.Margin = new Thickness(0, 20, 0, 0);

                            TextBlock TitleLicense = new TextBlock();
                            TitleLicense.TextWrapping = TextWrapping.Wrap;
                            TitleLicense.FontSize     = 15;
                            TitleLicense.Text         = SettingControl.Description;
                            TitleLicense.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;

                            LicenseControl.Children.Add(TitleLicense);

                            TextBlock Author = new TextBlock();
                            Author.TextWrapping = TextWrapping.Wrap;
                            Author.Margin       = new Thickness(5, 5, 0, 0);
                            Author.FontSize     = 12;
                            Author.FontWeight   = FontWeights.Light;
                            Author.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;
                            Author.Text         = ((Tuple <string, string>)SettingControl.Parameter).Item1;

                            LicenseControl.Children.Add(Author);

                            Button LicenseButton = new Button();
                            LicenseButton.Margin     = new Thickness(0, 5, 0, 0);
                            LicenseButton.Content    = GlobalVariables.GlobalizationRessources.GetString("settings-buttonlicense");
                            LicenseButton.FontSize   = 14;
                            LicenseButton.Foreground = GlobalVariables.CurrentTheme.MainColorFont;
                            LicenseButton.Background = GlobalVariables.CurrentTheme.MainColor;
                            LicenseButton.Click     += (async(e, f) => {
                                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 = SettingControl.Description + " " + ((Tuple <string, string>)SettingControl.Parameter).Item1;

                                    var frame = new Frame();
                                    frame.Navigate(typeof(LicenseView), ((Tuple <string, string>)SettingControl.Parameter).Item2);
                                    newWindow.Content = frame;
                                    newWindow.Activate();

                                    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
                                        newAppView.Id,
                                        ViewSizePreference.UseHalf,
                                        currentAV.Id,
                                        ViewSizePreference.UseHalf);
                                });
                            });
                            LicenseControl.Children.Add(LicenseButton);

                            MenuControls.Children.Add(LicenseControl);
                            break;

                        case SettingType.ComboBox:
                            StackPanel ListControl = new StackPanel();
                            ListControl.Margin = new Thickness(0, 20, 0, 0);

                            TextBlock TitleList = new TextBlock();
                            TitleList.TextWrapping = TextWrapping.Wrap;
                            TitleList.FontSize     = 15;
                            TitleList.Text         = SettingControl.Description;
                            TitleList.Foreground   = GlobalVariables.CurrentTheme.MainColorFont;

                            ListControl.Children.Add(TitleList);

                            ComboBox List = new ComboBox();
                            List.Margin     = new Thickness(5, 5, 0, 0);
                            List.FontSize   = 14;
                            List.FontWeight = FontWeights.Light;
                            List.Foreground = GlobalVariables.CurrentTheme.MainColorFont;
                            List.Background = GlobalVariables.CurrentTheme.MainColor;

                            List.SelectionChanged += ((e, f) =>
                            {
                                if (List.SelectedIndex != -1)
                                {
                                    AppSettings.Values[SettingControl.VarSaveName] = List.SelectedValue;
                                    Messenger.Default.Send(new SettingsNotification {
                                        SettingsUpdatedName = menu.Name
                                    });
                                }
                            });

                            foreach (string Item in (List <string>)SettingControl.Parameter)
                            {
                                List.Items.Add(Item);
                                if (AppSettings.Values.ContainsKey(SettingControl.VarSaveName))
                                {
                                    if (Item == (string)AppSettings.Values[SettingControl.VarSaveName])
                                    {
                                        List.SelectedIndex = (List.Items.Count - 1);
                                    }
                                }
                                else
                                {
                                    if (Item == (string)SettingControl.VarSaveDefaultContent)
                                    {
                                        List.SelectedIndex = (List.Items.Count - 1);
                                    }
                                }
                            }

                            ListControl.Children.Add(List);
                            MenuControls.Children.Add(ListControl);

                            break;
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        private async void ToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            var button = (ToggleButton)sender;

            // Get our encoder properties
            var frameRateItem  = (FrameRateItem)FrameRateComboBox.SelectedItem;
            var resolutionItem = (ResolutionItem)ResolutionComboBox.SelectedItem;
            var bitrateItem    = (BitrateItem)BitrateComboBox.SelectedItem;

            if (UseCaptureItemToggleSwitch.IsOn)
            {
                resolutionItem.IsZero();
            }

            var width     = resolutionItem.Resolution.Width;
            var height    = resolutionItem.Resolution.Height;
            var bitrate   = bitrateItem.Bitrate;
            var frameRate = frameRateItem.FrameRate;

            if (UseCaptureItemToggleSwitch.IsOn)
            {
                resolutionItem.IsZero();
            }

            // Get our capture item
            var picker = new GraphicsCapturePicker();
            var item   = await picker.PickSingleItemAsync();

            if (item == null)
            {
                button.IsChecked = false;
                return;
            }

            // Use the capture item's size for the encoding if desired
            if (UseCaptureItemToggleSwitch.IsOn)
            {
                width  = (uint)item.Size.Width;
                height = (uint)item.Size.Height;

                // Even if we're using the capture item's real size,
                // we still want to make sure the numbers are even.
                // Some encoders get mad if you give them odd numbers.
                width  = EnsureEven(width);
                height = EnsureEven(height);
            }

            // Put videos in the temp folder
            var tempFile = await GetTempFileAsync();

            _tempFile = tempFile;

            // Tell the user we've started recording

            var visual    = ElementCompositionPreview.GetElementVisual(Ellipse);
            var animation = visual.Compositor.CreateScalarKeyFrameAnimation();

            animation.InsertKeyFrame(0, 1);
            animation.InsertKeyFrame(1, 0);
            animation.Duration          = TimeSpan.FromMilliseconds(1500);
            animation.IterationBehavior = AnimationIterationBehavior.Forever;
            visual.StartAnimation("Opacity", animation);

            RecordIcon.Visibility = Visibility.Collapsed;
            StopIcon.Visibility   = Visibility.Visible;
            Ellipse.Visibility    = Visibility.Visible;
            ToolTip toolTip = new ToolTip();

            toolTip.Content = "Stop recording";
            ToolTipService.SetToolTip(MainButton, toolTip);
            AutomationProperties.SetName(MainButton, "Stop recording");
            MainTextBlock.Text = "recording...";
            var originalBrush = MainTextBlock.Foreground;

            MainTextBlock.Foreground = new SolidColorBrush(Colors.Red);

            // Kick off the encoding
            try
            {
                using (var stream = await tempFile.OpenAsync(FileAccessMode.ReadWrite))
                    using (_encoder = new Encoder(_device, item))
                    {
                        var encodesuccess = await _encoder.EncodeAsync(
                            stream,
                            width, height, bitrate,
                            frameRate);

                        if (encodesuccess == false)
                        {
                            ContentDialog errorDialog = new ContentDialog
                            {
                                Title           = "Recording failed",
                                Content         = "Windows cannot encode your video",
                                CloseButtonText = "OK"
                            };
                            await errorDialog.ShowAsync();
                        }
                    }
                MainTextBlock.Foreground = originalBrush;
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex);

                var message = GetMessageForHResult(ex.HResult);
                if (message == null)
                {
                    message = $"Whoops, something went wrong!\n0x{ex.HResult:X8} - {ex.Message}";
                }
                ContentDialog errorDialog = new ContentDialog
                {
                    Title           = "Recording failed",
                    Content         = message,
                    CloseButtonText = "OK"
                };
                await errorDialog.ShowAsync();

                button.IsChecked = false;
                visual.StopAnimation("Opacity");

                Ellipse.Visibility       = Visibility.Collapsed;
                MainTextBlock.Text       = "failure";
                MainTextBlock.Foreground = originalBrush;
                RecordIcon.Visibility    = Visibility.Visible;
                StopIcon.Visibility      = Visibility.Collapsed;
                toolTip.Content          = "Start recording";
                ToolTipService.SetToolTip(MainButton, toolTip);
                AutomationProperties.SetName(MainButton, "Start recording");
                await _tempFile.DeleteAsync();

                return;
            }

            // At this point the encoding has finished,
            // tell the user we're now saving

            MainButton.IsChecked = false;
            MainTextBlock.Text   = "";
            visual.StopAnimation("Opacity");
            Ellipse.Visibility    = Visibility.Collapsed;
            RecordIcon.Visibility = Visibility.Visible;
            StopIcon.Visibility   = Visibility.Collapsed;
            ToolTip newtoolTip = new ToolTip();

            toolTip.Content = "Start recording";
            ToolTipService.SetToolTip(MainButton, toolTip);
            AutomationProperties.SetName(MainButton, "Start recording");

            if (PreviewToggleSwitch.IsOn)
            {
                CoreApplicationView newView = CoreApplication.CreateNewView();
                int newViewId = 0;
                await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var preview = new VideoPreviewPage(_tempFile);
                    ApplicationViewTitleBar formattableTitleBar = ApplicationView.GetForCurrentView().TitleBar;
                    formattableTitleBar.ButtonBackgroundColor   = Colors.Transparent;
                    CoreApplicationViewTitleBar coreTitleBar    = CoreApplication.GetCurrentView().TitleBar;
                    coreTitleBar.ExtendViewIntoTitleBar         = true;
                    Window.Current.Content = preview;
                    Window.Current.Activate();
                    newViewId = ApplicationView.GetForCurrentView().Id;
                });

                bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
            }
            else
            {
                ContentDialog dialog = new SaveDialog(_tempFile);
                await dialog.ShowAsync();
            }
        }
Exemplo n.º 7
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.signalBars") && req is byte[] data2)
                    {
                        using (var from = new TLBinaryReader(data2))
                        {
                            var tuple = new TLTuple <int>(from);

                            if (_phoneView != null)
                            {
                                await _phoneView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    _phoneView.SetSignalBars(tuple.Item1);
                                });
                            }
                        }
                    }
                    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.º 8
0
 public async Task GoBackToMainViewAsync()
 {
     await ApplicationViewSwitcher.TryShowAsStandaloneAsync(mainViewId);
 }
 private async void Button_Click(object sender, RoutedEventArgs e)
 {
     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
 private async void OpenMainWindow()
 {
     await ApplicationViewSwitcher.TryShowAsStandaloneAsync(ApplicationView.GetApplicationViewIdForWindow(CoreApplication.MainView.CoreWindow));
 }
Exemplo n.º 12
0
        public async Task ShowNew()
        {
            var id = await CreateNewWindow(typeof(MainPage), true);

            bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(id);
        }
Exemplo n.º 13
0
 public static async void ShowMainView()
 {
     bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(MainView.Id);
 }
        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.º 15
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();

                    var frameFacade = new FrameFacadeAdapter(content.Frame, EventAggregator);

                    var sessionStateService = new SessionStateService();

                    //sessionStateService.RegisterFrame(frameFacade, "secondary_view_player");
                    ns = new FrameNavigationService(frameFacade
                                                    , (pageToken) =>
                    {
                        if (pageToken == nameof(Views.VideoPlayerPage))
                        {
                            return(typeof(Views.VideoPlayerPage));
                        }
                        else if (pageToken == nameof(Views.LivePlayerPage))
                        {
                            return(typeof(Views.LivePlayerPage));
                        }
                        else
                        {
                            return(typeof(Views.BlankPage));
                        }
                    }, sessionStateService);

                    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.RegisterInstance(SECONDARY_VIEW_PLAYER_NAVIGATION_SERVICE, SecondaryViewPlayerNavigationService);
            }

            return(this);
        }
Exemplo n.º 16
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.º 17
0
        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);
                }

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

                ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto;

                // Tasks after activation
                await StartupAsync();
            }
        }
Exemplo n.º 18
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.º 19
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() =>
                        {
                            var that = weak.Target as App;
                            if (that != null)
                            {
                                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);
                                        }
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        ActivationViewSwitcher activationViewSwitcher = null;
                        var activateEventArgs = (args as IViewSwitcherProvider);
                        if (activateEventArgs != null)
                        {
                            activationViewSwitcher = activateEventArgs.ViewSwitcher;
                        }

                        if (activationViewSwitcher != null)
                        {
                            _ = activationViewSwitcher.ShowAsStandaloneAsync(
                                ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()), ViewSizePreference.Default);
                        }
                        else
                        {
                            TraceLogger.GetInstance().LogError(ViewMode.None, "App.OnAppLaunch", "Null_ActivationViewSwitcher");
                        }
                    }
                    // Set the preLaunched flag to false
                    m_preLaunched = false;
                }
                else // for touch devices
                {
                    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
                        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();
                        }
                    }
                    if (ApplicationView.GetForCurrentView().ViewMode != ApplicationViewMode.CompactOverlay)
                    {
                        if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
                        {
                            // for tablet mode: since system view activation policy is disabled so do ShowAsStandaloneAsync if activationViewSwitcher exists in
                            // activationArgs
                            ActivationViewSwitcher activationViewSwitcher = null;
                            var activateEventArgs = (args as IViewSwitcherProvider);
                            if (activateEventArgs != null)
                            {
                                activationViewSwitcher = activateEventArgs.ViewSwitcher;
                            }
                            if (activationViewSwitcher != null)
                            {
                                var viewId = (args as IApplicationViewActivatedEventArgs).CurrentlyShownApplicationViewId;
                                if (viewId != 0)
                                {
                                    _ = activationViewSwitcher.ShowAsStandaloneAsync(viewId);
                                }
                            }
                        }
                        // Ensure the current window is active
                        Window.Current.Activate();
                    }
                }
            }
        }
Exemplo n.º 20
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.º 21
0
        private async Task CreateNewTerminalWindow(string startupDirectory, bool showProfileSelection)
        {
            var id = await CreateSecondaryView <MainViewModel>(typeof(MainPage), true, showProfileSelection, startupDirectory).ConfigureAwait(true);

            await ApplicationViewSwitcher.TryShowAsStandaloneAsync(id);
        }
Exemplo n.º 22
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.º 23
0
        private async Task <HohoemaViewManager> GetEnsureSecondaryView()
        {
            if (CoreAppView == null)
            {
                var playerView = CoreApplication.CreateNewView();


                HohoemaSecondaryViewFrameViewModel vm = null;
                int                id   = 0;
                ApplicationView    view = null;
                INavigationService ns   = null;
                await playerView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    playerView.TitleBar.ExtendViewIntoTitleBar = true;

                    var content = new Views.HohoemaSecondaryViewFrame();

                    var frameFacade = new FrameFacadeAdapter(content.Frame);

                    var sessionStateService = new SessionStateService();

                    ns = new FrameNavigationService(frameFacade
                                                    , (pageToken) =>
                    {
                        if (pageToken == nameof(Views.VideoPlayerPage))
                        {
                            return(typeof(Views.VideoPlayerPage));
                        }
                        else if (pageToken == nameof(Views.LivePlayerPage))
                        {
                            return(typeof(Views.LivePlayerPage));
                        }
                        else
                        {
                            return(typeof(Views.BlankPage));
                        }
                    }, sessionStateService);


                    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.Default, MainView.Id, ViewSizePreference.Default);

                    // ウィンドウサイズの保存と復元
                    if (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;
                });

                ViewId            = id;
                AppView           = view;
                _SecondaryViewVM  = vm;
                CoreAppView       = playerView;
                NavigationService = ns;
            }

            NowShowingSecondaryView = true;

            return(this);
        }
Exemplo n.º 24
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.º 25
0
        public async Task ActivateAsync(object args)
        {
            if (args is IActivatedEventArgs)
            {
                // Initialize things like registering background task before the app is loaded
                // Only when activation has UI
                await initialization?.Invoke();
            }

            var activationHandler = handlers?.FirstOrDefault(h => h.CanHandle(args));

            // Default activation and ALL Normal activations (exclude Background, Hosted and Custom activations)
            if (activationHandler == null || activationHandler.Strategy == ActivationStrategy.Normal)
            {
                // Do not repeat app initialization when the Window already has content,
                // just ensure that the window is active
                if (Window.Current.Content == null)
                {
                    // Create a Frame to act as the navigation context and navigate to the first page
                    var rootFrame = new Frame();
                    if (shell != null)
                    {
                        rootFrame.Navigate(shell);
                    }
                    Window.Current.Content = rootFrame;
                }

                // If there is already a view showing, then the app is a multi-view
                if (args is IApplicationViewActivatedEventArgs viewArgs && viewArgs.CurrentlyShownApplicationViewId != 0)
                {
                    // Since this is a Normal Activation, the app must make the MainView available first
                    await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        int mainViewId = ApplicationView.GetApplicationViewIdForWindow(CoreApplication.MainView.CoreWindow);
                        await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
                            mainViewId,
                            ViewSizePreference.Default,
                            viewArgs.CurrentlyShownApplicationViewId,
                            ViewSizePreference.Default);
                    });
                }
            }
            // Share Target, File Open Picker, File Save Picker, Contact Panel activation
            // Hosted handlers must be assured that they can use the current Window's content as a Frame for their navigation context
            else if (activationHandler.Strategy == ActivationStrategy.Hosted)
            {
                Window.Current.Content = new Frame();
            }
            // Background activations do not need UI so we are not going to initialize the current Window's content
            // Other activations must handle their own UI logic in their implementations (HandleAsync)

            if (activationHandler != null)
            {
                // Normal activations can request for a navigation context (in this case, a Frame) to be used in their HandleAsync logic
                // Pickers can just use Window.Current.Content as Frame to have a navigation context
                // Background activation does not show any UI so can continue without navigation context
                // Custom activations must manually set the Window.Current.Content in their implementation
                if (activationHandler.Strategy == ActivationStrategy.Normal)
                {
                    // We used a Lazy object for this because the navigation context is only relevant after
                    // setting the content of the current Window with a Shell or a Frame
                    activationHandler.SetNavigationContext(navigationContext.Value);
                }
                await activationHandler.Handle(args);
            }

            // If no handler was found or a handler with a normal strategy was found but did not set a content to the navigation context, the default handler kicks in
            if (activationHandler == null || (activationHandler.Strategy == ActivationStrategy.Normal && navigationContext.Value?.Content == null))
            {
                defaultHandler.SetNavigationContext(navigationContext.Value);
                await defaultHandler.Handle(args);
            }

            if (args is IActivatedEventArgs)
            {
                // Ensure the current window is active
                Window.Current.Activate();

                // Default activation and All normal activations (exclude Background, Hosted and Custom activations)
                if (activationHandler == null || activationHandler.Strategy == ActivationStrategy.Normal)
                {
                    // Tasks after activation
                    await startup?.Invoke();
                }
            }
        }
Exemplo n.º 26
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]);
            }
        }
        /// <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
            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.º 28
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);

            //if (ApiInformation.IsTypePresent("Windows.UI.WindowManagement.AppWindow"))
            //{
            //    var window = _walletWindow;
            //    if (window == null)
            //    {
            //        var nav = BootStrapper.Current.NavigationServiceFactory(BootStrapper.BackButton.Ignore, BootStrapper.ExistingContent.Exclude, 0, "0", false);
            //        var frame = BootStrapper.Current.CreateRootElement(nav);
            //        nav.Navigate(page, address);

            //        window = await AppWindow.TryCreateAsync();
            //        window.PersistedStateId = "Wallet";
            //        window.TitleBar.ExtendsContentIntoTitleBar = true;
            //        window.Closed += (s, args) =>
            //        {
            //            _walletWindow = null;
            //            frame = null;
            //            window = null;
            //        };

            //        _walletWindow = window;
            //        ElementCompositionPreview.SetAppWindowContent(window, frame);
            //    }

            //    window.RequestSize(new Windows.Foundation.Size(360, 640));
            //    await window.TryShowAsync();
            //    window.RequestSize(new Windows.Foundation.Size(360, 640));
            //    window.RequestMoveAdjacentToCurrentView();
            //}

            //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);
            }
        }