예제 #1
0
        private void InitControls()
        {
            ToolTipService.SetToolTip(ExitCompactOverlayButton, _resourceLoader.GetString("App_ExitCompactOverlayMode_Text"));
            RootSplitView.PaneOpening       += delegate { SettingsFrame.Navigate(typeof(SettingsPage), null, new SuppressNavigationTransitionInfo()); };
            RootSplitView.PaneClosed        += delegate { NotepadsCore.FocusOnSelectedTextEditor(); };
            NewSetButton.Click              += delegate { NotepadsCore.OpenNewTextEditor(_defaultNewFileName); };
            MainMenuButton.Click            += (sender, args) => FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
            MenuCreateNewButton.Click       += (sender, args) => NotepadsCore.OpenNewTextEditor(_defaultNewFileName);
            MenuCreateNewWindowButton.Click += async(sender, args) => await OpenNewAppInstance();

            MenuOpenFileButton.Click += async(sender, args) => await OpenNewFiles();

            MenuSaveButton.Click += async(sender, args) => await Save(NotepadsCore.GetSelectedTextEditor(), saveAs : false);

            MenuSaveAsButton.Click += async(sender, args) => await Save(NotepadsCore.GetSelectedTextEditor(), saveAs : true);

            MenuSaveAllButton.Click += async(sender, args) =>
            {
                var success = false;
                foreach (var textEditor in NotepadsCore.GetAllTextEditors())
                {
                    if (await Save(textEditor, saveAs: false, ignoreUnmodifiedDocument: true, rebuildOpenRecentItems: false))
                    {
                        success = true;
                    }
                }
                if (success)
                {
                    await BuildOpenRecentButtonSubItems();
                }
            };
            MenuFindButton.Click           += (sender, args) => NotepadsCore.GetSelectedTextEditor()?.ShowFindAndReplaceControl(showReplaceBar: false);
            MenuReplaceButton.Click        += (sender, args) => NotepadsCore.GetSelectedTextEditor()?.ShowFindAndReplaceControl(showReplaceBar: true);
            MenuFullScreenButton.Click     += (sender, args) => EnterExitFullScreenMode();
            MenuCompactOverlayButton.Click += (sender, args) => EnterExitCompactOverlayMode();
            MenuPrintButton.Click          += async(sender, args) => await Print(NotepadsCore.GetSelectedTextEditor());

            MenuPrintAllButton.Click += async(sender, args) => await PrintAll(NotepadsCore.GetAllTextEditors());

            MenuSettingsButton.Click += (sender, args) => RootSplitView.IsPaneOpen = true;

            MainMenuButtonFlyout.Opening += (sender, o) =>
            {
                var selectedTextEditor = NotepadsCore.GetSelectedTextEditor();
                if (selectedTextEditor == null)
                {
                    MenuSaveButton.IsEnabled     = false;
                    MenuSaveAsButton.IsEnabled   = false;
                    MenuFindButton.IsEnabled     = false;
                    MenuReplaceButton.IsEnabled  = false;
                    MenuPrintButton.IsEnabled    = false;
                    MenuPrintAllButton.IsEnabled = false;
                }
                else if (selectedTextEditor.IsEditorEnabled() == false)
                {
                    MenuSaveButton.IsEnabled    = selectedTextEditor.IsModified;
                    MenuSaveAsButton.IsEnabled  = true;
                    MenuFindButton.IsEnabled    = false;
                    MenuReplaceButton.IsEnabled = false;
                }
                else
                {
                    MenuSaveButton.IsEnabled    = selectedTextEditor.IsModified;
                    MenuSaveAsButton.IsEnabled  = true;
                    MenuFindButton.IsEnabled    = true;
                    MenuReplaceButton.IsEnabled = true;

                    if (PrintManager.IsSupported())
                    {
                        MenuPrintButton.IsEnabled    = !string.IsNullOrEmpty(selectedTextEditor.GetText());
                        MenuPrintAllButton.IsEnabled = NotepadsCore.HaveNonemptyTextEditor();
                    }
                }

                MenuFullScreenButton.Text = _resourceLoader.GetString(ApplicationView.GetForCurrentView().IsFullScreenMode ?
                                                                      "App_ExitFullScreenMode_Text" : "App_EnterFullScreenMode_Text");
                MenuCompactOverlayButton.Text = _resourceLoader.GetString(ApplicationView.GetForCurrentView().ViewMode == ApplicationViewMode.CompactOverlay ?
                                                                          "App_ExitCompactOverlayMode_Text" : "App_EnterCompactOverlayMode_Text");
                MenuSaveAllButton.IsEnabled = NotepadsCore.HaveUnsavedTextEditor();
            };

            if (!App.IsFirstInstance)
            {
                MainMenuButton.Foreground    = new SolidColorBrush(ThemeSettingsService.AppAccentColor);
                MenuSettingsButton.IsEnabled = false;
            }
        }
예제 #2
0
        /// <summary>
        /// Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate.
        /// In simplest terms, this means the method is called just before a UI element displays in your app.
        /// Override this method to influence the default post-template logic of a class.
        /// </summary>
        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            LeftSeparator  = GetTemplateChild("LeftSeparator") as FrameworkElement;
            RightSeparator = GetTemplateChild("RightSeparator") as FrameworkElement;

            var rootGrid = GetTemplateChild("RootGrid") as FrameworkElement;

            if (rootGrid != null)
            {
                rootGrid.DoubleTapped   += Grid_DoubleTapped;
                rootGrid.PointerEntered += Grid_PointerMoved;
                rootGrid.PointerMoved   += Grid_PointerMoved;
                rootGrid.Tapped         += OnPointerMoved;
                rootGrid.PointerExited  += Grid_PointerExited;

                AppBarButtonStyle = rootGrid.Resources["AppBarButtonStyle"] as Style;
            }

            var commandBar = GetTemplateChild("MediaControlsCommandBar") as CommandBar;

            CommandBar = commandBar;
            if (commandBar != null)
            {
                commandBar.LayoutUpdated += CommandBar_LayoutUpdated;
            }

            ControlPanelGrid = GetTemplateChild("ControlPanelGrid") as FrameworkElement;

            ErrorTextBlock = GetTemplateChild("ErrorTextBlock") as TextBlock;

            ProgressSlider = GetTemplateChild("ProgressSlider") as Slider;
            if (ProgressSlider != null)
            {
                ProgressSlider.Minimum       = 0;
                ProgressSlider.Maximum       = 1000;
                ProgressSlider.ValueChanged += ProgressSlider_ValueChanged;
            }
            TimeTextGrid = GetTemplateChild("TimeTextGrid") as FrameworkElement;
            VolumeSlider = GetTemplateChild("VolumeSlider") as Slider;
            if (VolumeSlider != null)
            {
                VolumeSlider.ValueChanged += VolumeSlider_ValueChanged;
                UpdateVolume();
            }
            PlayPauseButton       = GetTemplateChild("PlayPauseButton") as FrameworkElement;
            PlayPauseButtonOnLeft = GetTemplateChild("PlayPauseButtonOnLeft") as FrameworkElement;
            ZoomButton            = GetTemplateChild("ZoomButton") as FrameworkElement;
            FullWindowButton      = GetTemplateChild("FullWindowButton") as FrameworkElement;
            StopButton            = GetTemplateChild("StopButton") as FrameworkElement;
            DeinterlaceModeButton = GetTemplateChild("DeinterlaceModeButton") as FrameworkElement;

            TimeElapsedTextBlock   = GetTemplateChild("TimeElapsedElement") as TextBlock;
            TimeRemainingTextBlock = GetTemplateChild("TimeRemainingElement") as TextBlock;

            var deinterlaceModeMenu = GetTemplateChild("DeinterlaceModeMenu") as MenuFlyout;

            DeinterlaceModeMenu = deinterlaceModeMenu;
            if (deinterlaceModeMenu != null)
            {
                var deinterlaceModeType = typeof(DeinterlaceMode);
                ToggleMenuFlyoutItem menuItem;
                string deinterlaceModeName;

                foreach (var deinterlaceMode in AvailableDeinterlaceModes)
                {
                    deinterlaceModeName = Enum.GetName(deinterlaceModeType, deinterlaceMode);
                    menuItem            = new ToggleMenuFlyoutItem()
                    {
                        Text = ResourceLoader?.GetString($"{deinterlaceModeType.Name}_{deinterlaceModeName}") ?? deinterlaceModeName,
                        Tag  = deinterlaceMode
                    };
                    menuItem.Click += DeinterlaceModeMenuItem_Click;
                    deinterlaceModeMenu.Items.Add(menuItem);
                }
            }

            AddTracksMenu("AudioTracksSelectionMenu", TrackType.Audio, "AudioSelectionAvailable", "AudioSelectionUnavailable");
            AddTracksMenu("CCSelectionSelectionMenu", TrackType.Subtitle, "CCSelectionAvailable", "CCSelectionUnavailable", true);

            SetButtonClick(PlayPauseButtonOnLeft, PlayPauseButton_Click);
            SetButtonClick(PlayPauseButton, PlayPauseButton_Click);
            SetButtonClick(ZoomButton, ZoomButton_Click);
            SetButtonClick(FullWindowButton, FullWindowButton_Click);
            SetButtonClick(StopButton, StopButton_Click);
            var audioMuteButton = GetTemplateChild("AudioMuteButton");

            SetButtonClick(audioMuteButton, AudioMuteButton_Click);

            SetToolTip(DeinterlaceModeButton, "DeinterlaceFilter");
            SetToolTip(ZoomButton, "AspectRatio");
            SetToolTip("VolumeMuteButton", "Volume");
            SetToolTip(audioMuteButton, "Mute");
            SetToolTip("CCSelectionButton", "ShowClosedCaptionMenu");
            SetToolTip("AudioTracksSelectionButton", "ShowAudioSelectionMenu");
            SetToolTip(StopButton, "Stop");
            SetToolTip(PlayPauseButton, "Play");
            SetToolTip(PlayPauseButtonOnLeft, "Play");

            UpdateMediaTransportControlMode();
            UpdateSeekBarVisibility();
            UpdatePlayPauseButton();
            UpdateZoomButton();
            UpdateFullWindowButton();
            UpdateStopButton();
            UpdateMuteState();
            UpdateDeinterlaceModeButton();
            UpdateDeinterlaceMode();

            ApplicationView.GetForCurrentView().VisibleBoundsChanged += (sender, args) => UpdateFullWindowState();
            UpdateFullWindowState();

            Timer.Tick += Timer_Tick;
        }
예제 #3
0
        public Rectangle GetHinge()
        {
            if (!ApiInformation.IsMethodPresent("global::Windows.UI.ViewManagement.ApplicationView", "GetSpanningRects"))
            {
                return(Rectangle.Zero);
            }

            if (!IsSpanned)
            {
                return(Rectangle.Zero);
            }

            var screen = DisplayInformation.GetForCurrentView();


#if UWP_18362
            var applicationView = ApplicationView.GetForCurrentView();
            List <global::Windows.Foundation.Rect> spanningRects = null;

#if UWP_19000
            spanningRects = applicationView.GetSpanningRects().ToList();
#endif

            if (spanningRects?.Count == 2)
            {
                if (!IsLandscape)
                {
                    var x          = spanningRects[0].Width;
                    var hingeWidth = spanningRects[1].X - x;
                    return(new Rectangle(x, 0, hingeWidth, ScaledPixels(screen.ScreenHeightInRawPixels)));
                }
                else
                {
                    var y           = spanningRects[0].Height;
                    var hingeHeight = spanningRects[1].Y - y;
                    return(new Rectangle(0, y, ScaledPixels(screen.ScreenWidthInRawPixels), hingeHeight));
                }
            }
#endif

            // fall back to hard coded
            Rectangle returnValue = Rectangle.Zero;

            if (IsLandscape)
            {
                if (IsSpanned)
                {
                    returnValue = new Rectangle(0, 664 + 24, ScaledPixels(screen.ScreenWidthInRawPixels), 0);
                }
                else
                {
                    returnValue = new Rectangle(0, 664, ScaledPixels(screen.ScreenWidthInRawPixels), 0);
                }
            }
            else
            {
                returnValue = new Rectangle(720, 0, 0, ScaledPixels(screen.ScreenHeightInRawPixels));
            }

            return(returnValue);
        }
예제 #4
0
 public async Task SwapProjection()
 {
     try
     {
         if (projecting)
         {
             await ProjectionManager.SwapDisplaysForViewsAsync(externalViewId, ApplicationView.GetForCurrentView().Id);
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine("SwapProjection: " + ex.Message);
     }
 }
예제 #5
0
 public static WindowInformation CreateForCurrentView()
 {
     return(new WindowInformation(
                CoreApplication.GetCurrentView(),
                ApplicationView.GetForCurrentView()));
 }
예제 #6
0
        public static void UpdateSystemCaptionButtonColors()
        {
            var titleBar = ApplicationView.GetForCurrentView().TitleBar;

            titleBar.ButtonForegroundColor = ThemeHelper.IsDarkTheme() ? Colors.White : Colors.Black;
        }
예제 #7
0
        private void OnFullScreenClick(object sender, RoutedEventArgs e)
        {
            var view = ApplicationView.GetForCurrentView();

            view.TryEnterFullScreenMode();
        }
예제 #8
0
        public SettingsPageViewModel(
            PageManager pageManager,
            NotificationService toastService,
            Services.DialogService dialogService,
            PlayerSettings playerSettings,
            NGSettings ngSettings,
            RankingSettings rankingSettings,
            ActivityFeedSettings activityFeedSettings,
            AppearanceSettings appearanceSettings,
            CacheSettings cacheSettings,
            ApplicationLayoutManager applicationLayoutManager
            )
        {
            ToastNotificationService = toastService;
            NgSettings               = ngSettings;
            RankingSettings          = rankingSettings;
            _HohoemaDialogService    = dialogService;
            PlayerSettings           = playerSettings;
            NgSettings               = ngSettings;
            RankingSettings          = rankingSettings;
            ActivityFeedSettings     = activityFeedSettings;
            AppearanceSettings       = appearanceSettings;
            CacheSettings            = cacheSettings;
            ApplicationLayoutManager = applicationLayoutManager;

            // NG Video Owner User Id
            NGVideoOwnerUserIdEnable = NgSettings.ToReactivePropertyAsSynchronized(x => x.NGVideoOwnerUserIdEnable);
            NGVideoOwnerUserIds      = NgSettings.NGVideoOwnerUserIds
                                       .ToReadOnlyReactiveCollection();

            OpenUserPageCommand = new DelegateCommand <UserIdInfo>(userIdInfo =>
            {
                pageManager.OpenPageWithId(HohoemaPageType.UserInfo, userIdInfo.UserId);
            });

            // NG Keyword on Video Title
            NGVideoTitleKeywordEnable = NgSettings.ToReactivePropertyAsSynchronized(x => x.NGVideoTitleKeywordEnable);
            NGVideoTitleKeywords      = new ReactiveProperty <string>();
            NGVideoTitleKeywordError  = NGVideoTitleKeywords
                                        .Select(x =>
            {
                if (x == null)
                {
                    return(null);
                }

                var keywords     = x.Split('\r');
                var invalidRegex = keywords.FirstOrDefault(keyword =>
                {
                    Regex regex = null;
                    try
                    {
                        regex = new Regex(keyword);
                    }
                    catch { }
                    return(regex == null);
                });

                if (invalidRegex == null)
                {
                    return(null);
                }
                else
                {
                    return($"Error in \"{invalidRegex}\"");
                }
            })
                                        .ToReadOnlyReactiveProperty();

            // アピアランス

            var currentTheme = App.GetTheme();

            SelectedTheme = new ReactiveProperty <ElementTheme>(AppearanceSettings.Theme, mode: ReactivePropertyMode.DistinctUntilChanged);

            SelectedTheme.Subscribe(theme =>
            {
                AppearanceSettings.Theme = theme;

                ApplicationTheme appTheme;
                if (theme == ElementTheme.Default)
                {
                    appTheme = Views.Helpers.SystemThemeHelper.GetSystemTheme();
                }
                else if (theme == ElementTheme.Dark)
                {
                    appTheme = ApplicationTheme.Dark;
                }
                else
                {
                    appTheme = ApplicationTheme.Light;
                }

                App.SetTheme(appTheme);

                var appView = ApplicationView.GetForCurrentView();
                if (appTheme == ApplicationTheme.Light)
                {
                    appView.TitleBar.ButtonForegroundColor         = Colors.Black;
                    appView.TitleBar.ButtonHoverBackgroundColor    = Colors.DarkGray;
                    appView.TitleBar.ButtonHoverForegroundColor    = Colors.Black;
                    appView.TitleBar.ButtonInactiveForegroundColor = Colors.Gray;
                }
                else
                {
                    appView.TitleBar.ButtonForegroundColor         = Colors.White;
                    appView.TitleBar.ButtonHoverBackgroundColor    = Colors.DimGray;
                    appView.TitleBar.ButtonHoverForegroundColor    = Colors.White;
                    appView.TitleBar.ButtonInactiveForegroundColor = Colors.DarkGray;
                }
            });



            IsDefaultFullScreen = new ReactiveProperty <bool>(ApplicationView.PreferredLaunchWindowingMode == ApplicationViewWindowingMode.FullScreen);
            IsDefaultFullScreen.Subscribe(x =>
            {
                if (x)
                {
                    ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.FullScreen;
                }
                else
                {
                    ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto;
                }
            });

            StartupPageType = AppearanceSettings
                              .ToReactivePropertyAsSynchronized(x => x.StartupPageType);

            AppearanceSettings.ObserveProperty(x => x.Locale, isPushCurrentValueAtFirst: false).Subscribe(locale =>
            {
                I18NPortable.I18N.Current.Locale = locale;
            });

            // キャッシュ
            DefaultCacheQuality                 = CacheSettings.ToReactivePropertyAsSynchronized(x => x.DefaultCacheQuality);
            IsAllowDownloadOnMeteredNetwork     = CacheSettings.ToReactivePropertyAsSynchronized(x => x.IsAllowDownloadOnMeteredNetwork);
            DefaultCacheQualityOnMeteredNetwork = CacheSettings.ToReactivePropertyAsSynchronized(x => x.DefaultCacheQualityOnMeteredNetwork);

            // シェア
            IsLoginTwitter           = new ReactiveProperty <bool>(/*TwitterHelper.IsLoggedIn*/ false);
            TwitterAccountScreenName = new ReactiveProperty <string>(/*TwitterHelper.TwitterUser?.ScreenName ?? ""*/);


            // アバウト
            var version = Windows.ApplicationModel.Package.Current.Id.Version;

#if DEBUG
            VersionText = $"{version.Major}.{version.Minor}.{version.Build} DEBUG";
#else
            VersionText = $"{version.Major}.{version.Minor}.{version.Build}";
#endif


            var dispatcher = Window.Current.CoreWindow.Dispatcher;
            LisenceSummary.Load()
            .ContinueWith(async prevResult =>
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    var lisenceSummary = prevResult.Result;

                    LisenceItems = lisenceSummary.Items
                                   .OrderBy(x => x.Name)
                                   .Select(x => new LisenceItemViewModel(x))
                                   .ToList();
                    RaisePropertyChanged(nameof(LisenceItems));
                });
            });


            IsDebugModeEnabled = new ReactiveProperty <bool>((App.Current as App).IsDebugModeEnabled, mode: ReactivePropertyMode.DistinctUntilChanged);
            IsDebugModeEnabled.Subscribe(isEnabled =>
            {
                (App.Current as App).IsDebugModeEnabled = isEnabled;
            })
            .AddTo(_CompositeDisposable);
        }
예제 #9
0
        internal void RaiseNativeSizeChanged()
        {
            var display           = (ContextHelper.Current as Activity)?.WindowManager?.DefaultDisplay;
            var fullScreenMetrics = new DisplayMetrics();

#pragma warning disable 618
            display?.GetMetrics(outMetrics: fullScreenMetrics);
#pragma warning restore 618

            var newBounds = ViewHelper.PhysicalToLogicalPixels(new Rect(0, 0, fullScreenMetrics.WidthPixels, fullScreenMetrics.HeightPixels));

            var statusBarSize = GetLogicalStatusBarSize();

            var statusBarSizeExcluded = IsStatusBarTranslucent() ?
                                        // The real metrics excluded the StatusBar only if it is plain.
                                        // We want to subtract it if it is translucent. Otherwise, it will be like we subtract it twice.
                                        statusBarSize :
                                        0;
            var navigationBarSizeExcluded = GetLogicalNavigationBarSizeExcluded();

            // Actually, we need to check visibility of nav bar and status bar since the insets don't
            UpdateInsetsWithVisibilities();

            var orientation = DisplayInformation.GetForCurrentView().CurrentOrientation;

            Rect CalculateVisibleBounds(double excludedStatusBarHeight)
            {
                var topHeightExcluded = Math.Max(Insets.Top, excludedStatusBarHeight);
                var newVisibleBounds  = new Rect();

                switch (orientation)
                {
                // StatusBar on top, NavigationBar on right
                case DisplayOrientations.Landscape:
                    newVisibleBounds = new Rect(
                        x: newBounds.X + Insets.Left,
                        y: newBounds.Y + topHeightExcluded,
                        width: newBounds.Width - (Insets.Left + Math.Max(Insets.Right, navigationBarSizeExcluded)),
                        height: newBounds.Height - topHeightExcluded - Insets.Bottom
                        );
                    break;

                // StatusBar on top, NavigationBar on left
                case DisplayOrientations.LandscapeFlipped:
                    newVisibleBounds = new Rect(
                        x: newBounds.X + Math.Max(Insets.Left, navigationBarSizeExcluded),
                        y: newBounds.Y + topHeightExcluded,
                        width: newBounds.Width - (Math.Max(Insets.Left, navigationBarSizeExcluded) + Insets.Right),
                        height: newBounds.Height - topHeightExcluded - Insets.Bottom
                        );
                    break;

                // StatusBar on top, NavigationBar on bottom
                default:
                    newVisibleBounds = new Rect(
                        x: newBounds.X + Insets.Left,
                        y: newBounds.Y + topHeightExcluded,
                        width: newBounds.Width - (Insets.Left + Insets.Right),
                        height: newBounds.Height - topHeightExcluded - Math.Max(Insets.Bottom, navigationBarSizeExcluded)
                        );
                    break;
                }

                return(newVisibleBounds);
            }

            var visibleBounds     = CalculateVisibleBounds(statusBarSizeExcluded);
            var trueVisibleBounds = CalculateVisibleBounds(statusBarSize);
            ApplicationView.GetForCurrentView()?.SetVisibleBounds(visibleBounds);
            ApplicationView.GetForCurrentView()?.SetTrueVisibleBounds(trueVisibleBounds);

            if (Bounds != newBounds)
            {
                Bounds = newBounds;

                RaiseSizeChanged(
                    new Windows.UI.Core.WindowSizeChangedEventArgs(
                        new Windows.Foundation.Size(Bounds.Width, Bounds.Height)
                        )
                    );
            }
        }
예제 #10
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 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.Navigated += OnNavigated;

                // Register a handler for BackRequested events and set the
                // visibility of the Back button
                SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
                    rootFrame.CanGoBack ?
                    AppViewBackButtonVisibility.Visible :
                    AppViewBackButtonVisibility.Collapsed;

                rootFrame.NavigationFailed += OnNavigationFailed;

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

                // Place the frame in the current Window.  Holds the NavigationView and navigation stack.
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    var setup = new Setup(rootFrame);
                    setup.Initialize();

                    var start = Mvx.Resolve <IMvxAppStart>();
                    start.Start();
                }

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

                //draw into the title bar
                CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

                //remove the solid-colored backgrounds behind the caption controls and system back button
                ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;

                // Set active window colors
                titleBar.ButtonBackgroundColor        = Colors.Transparent;
                titleBar.ForegroundColor              = Colors.White;
                titleBar.BackgroundColor              = Colors.Green;
                titleBar.ButtonForegroundColor        = Colors.White;
                titleBar.ButtonHoverForegroundColor   = Colors.White;
                titleBar.ButtonHoverBackgroundColor   = Colors.LightSlateGray;
                titleBar.ButtonPressedForegroundColor = Colors.Gray;
                titleBar.ButtonPressedBackgroundColor = Colors.LightGray;

                // Set inactive window colors
                titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
                titleBar.InactiveForegroundColor       = Colors.Gray;
                titleBar.ButtonInactiveForegroundColor = Colors.Gray;
                titleBar.ButtonInactiveBackgroundColor = Colors.LightSlateGray;
            }
        }
예제 #11
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 void OnLaunched(LaunchActivatedEventArgs e)
        {
            ViewModelLocator = (ViewModelLocator)Current.Resources["Locator"];

            #region Custom Title/Status Bar
            if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
            {
                var sb = StatusBar.GetForCurrentView();
                if (sb != null)
                {
                    sb.BackgroundColor = Colors.Black;
                    sb.ForegroundColor = Colors.White;
                }
            }

            if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView"))
            {
                var tb = ApplicationView.GetForCurrentView().TitleBar;
                ApplicationView.GetForCurrentView().Title = "Dojo [BETA]";
                if (tb != null)
                {
                    tb.BackgroundColor =
                        tb.ButtonPressedBackgroundColor =
                            tb.ButtonBackgroundColor    =
                                Colors.Black;
                    tb.ForegroundColor           =
                        tb.ButtonForegroundColor =
                            Colors.White;
                }
            }

            CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
            coreTitleBar.ExtendViewIntoTitleBar = false;
            #endregion

            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.Navigated        += OnRootFrameNavigated;
                rootFrame.NavigationFailed += OnNavigationFailed;
                SystemNavigationManager.GetForCurrentView().BackRequested += (s, args) =>
                {
                    rootFrame.GoBack();
                    args.Handled = true;
                };

                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();
            }
        }
예제 #12
0
        public MainPage()
        {
            this.InitializeComponent();

            try
            {
                NavigationCacheMode = NavigationCacheMode.Disabled;
                ApplicationView.GetForCurrentView().Title = AppResources.AppName;
                nvMain.PaneTitle = "NvMainNavigationViewPaneTitle".T();
                //nvMain.SettingsItem

                NavigationCacheMode = NavigationCacheMode.Enabled;
            }
            catch (Exception ex)
            {
                ex.Message.T().ShowMessage("ERROR".T());
            }

            #region Extented the supported string charsets
            //
            // Add GBK/Shift-JiS... to Encoding Supported
            // 使用CodePagesEncodingProvider去注册扩展编码。
            //
            try
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            }
            catch (Exception ex)
            {
                ex.Message.T().ShowMessage("ERROR".T());
            }
            #endregion

            #region Add Back Shortcut Key to Alt+Back
            // add keyboard accelerators for backwards navigation
            //KeyboardAccelerator GoBack = new KeyboardAccelerator();
            //GoBack.Key = VirtualKey.GoBack;
            //GoBack.Invoked += BackInvoked;
            //this.KeyboardAccelerators.Add(GoBack);

            //KeyboardAccelerator AltLeft = new KeyboardAccelerator();
            //AltLeft.Key = VirtualKey.Left;
            //AltLeft.Invoked += BackInvoked;
            //this.KeyboardAccelerators.Add(AltLeft);
            //// ALT routes here
            //AltLeft.Modifiers = VirtualKeyModifiers.Menu;
            #endregion

            #region Load Custom Simplified <=> Traditional Phrases
            Common.TongWen.Core.LoadCustomPhrase();
            #endregion

            #region 将应用扩展到标题栏
            try
            {
                //draw into the title bar
                CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
                //CustomTitleBar.Height = CoreApplication.GetCurrentView().TitleBar.Height;
                //Window.Current.SetTitleBar(GridTitleBar);

                SetTheme(Settings.GetTheme(), false);
            }
            catch (Exception ex)
            {
                ex.Message.T().ShowMessage("ERROR".T());
            }
            #endregion

            try
            {
                ContentFrame.Navigated += NvMain_Navigated;

                nvMain.IsPaneOpen = false;
                nvMain.Header     = nvMain.PaneTitle;
                ContentFrame.Navigate(typeof(Pages.TextPage), this);
            }
            catch (Exception ex)
            {
                ex.Message.T().ShowMessage("ERROR".T());
            }
        }
예제 #13
0
        private void ResizeView(Size size)
        {
            var view = ApplicationView.GetForCurrentView();

            view.TryResizeView(size);
        }
예제 #14
0
        protected override void OnActivated(IActivatedEventArgs args)
        {
            ApplicationViewTitleBar TitleBar = ApplicationView.GetForCurrentView().TitleBar;

            TitleBar.ButtonBackgroundColor         = Colors.Transparent;
            TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent;

            CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

            if (args is CommandLineActivatedEventArgs CmdArgs)
            {
                string[] Arguments = CmdArgs.Operation.Arguments.Split(" ", StringSplitOptions.RemoveEmptyEntries);

                if (Window.Current.Content is Frame frame)
                {
                    if (frame.Content is MainPage Main && Main.Nav.Content is TabViewContainer TabContainer)
                    {
                        if (Arguments.Length > 1)
                        {
                            string Path = string.Join(" ", Arguments.Skip(1));

                            if (string.IsNullOrWhiteSpace(Path) || Regex.IsMatch(Path, @"::\{[0-9A-F\-]+\}", RegexOptions.IgnoreCase))
                            {
                                TabContainer.CreateNewTab(null, Array.Empty <string>());
                            }
                            else
                            {
                                TabContainer.CreateNewTab(null, Path == "." ? CmdArgs.Operation.CurrentDirectoryPath : Path);
                            }
                        }
                        else
                        {
                            TabContainer.CreateNewTab(null, Array.Empty <string>());
                        }
                    }
                }
                else
                {
                    string Path = string.Join(" ", Arguments.Skip(1));

                    if (Arguments.Length > 1)
                    {
                        if (string.IsNullOrWhiteSpace(Path) || Regex.IsMatch(Path, @"::\{[0-9A-F\-]+\}", RegexOptions.IgnoreCase))
                        {
                            ExtendedSplash extendedSplash = new ExtendedSplash(CmdArgs.SplashScreen);
                            Window.Current.Content = extendedSplash;
                        }
                        else
                        {
                            ExtendedSplash extendedSplash = new ExtendedSplash(CmdArgs.SplashScreen, new string[] { Path == "." ? CmdArgs.Operation.CurrentDirectoryPath : Path });
                            Window.Current.Content = extendedSplash;
                        }
                    }
                    else
                    {
                        ExtendedSplash extendedSplash = new ExtendedSplash(CmdArgs.SplashScreen);
                        Window.Current.Content = extendedSplash;
                    }
                }
            }
            else if (args is ProtocolActivatedEventArgs ProtocalArgs)
            {
                if (!string.IsNullOrWhiteSpace(ProtocalArgs.Uri.AbsolutePath))
                {
                    ExtendedSplash extendedSplash = new ExtendedSplash(ProtocalArgs.SplashScreen, Uri.UnescapeDataString(ProtocalArgs.Uri.AbsolutePath).Split("||", StringSplitOptions.RemoveEmptyEntries));
                    Window.Current.Content = extendedSplash;
                }
                else
                {
                    ExtendedSplash extendedSplash = new ExtendedSplash(ProtocalArgs.SplashScreen);
                    Window.Current.Content = extendedSplash;
                }
            }
            else if (args is not ToastNotificationActivatedEventArgs)
            {
                ExtendedSplash extendedSplash = new ExtendedSplash(args.SplashScreen);
                Window.Current.Content = extendedSplash;
            }

            Window.Current.Activate();
        }
예제 #15
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)
        {
            CustomFrame rootFrame = Window.Current.Content as CustomFrame;

            // 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 CustomFrame();

                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 a boolean as navigation parameter,
                    // indicating whether the user is logged in or not

                    if (await AuthService.checkAuth())
                    {
                        await rootFrame.Navigate(typeof(MainPage), true);
                    }
                    else
                    {
                        await rootFrame.Navigate(typeof(MainPage), false);
                    }
                }

                if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView"))
                {
                    var view = ApplicationView.GetForCurrentView();
                    view.SetPreferredMinSize(new Size(width: 800, height: 600));

                    var titleBar = ApplicationView.GetForCurrentView().TitleBar;
                    if (titleBar != null)
                    {
                        titleBar.BackgroundColor = titleBar.ButtonBackgroundColor = (Color)App.Current.Resources["SystemAltHighColor"];
                    }
                }

                if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
                {
                    var statusBar = StatusBar.GetForCurrentView();
                    statusBar.BackgroundOpacity = 100;
                    statusBar.BackgroundColor   = (Color)Current.Resources["SystemAltHighColor"];
                }

                // Ensure the current window is active
                Window.Current.Activate();
            }
        }
예제 #16
0
 protected override void ReleaseManagedResources()
 {
     ApplicationView.GetForCurrentView().Consolidated                  -= OnConsolidated;
     SystemNavigationManager.GetForCurrentView().BackRequested         -= OnBackRequested;
     SystemNavigationManagerPreview.GetForCurrentView().CloseRequested -= OnCloseRequested;
 }
예제 #17
0
        protected override void OnActivated(IActivatedEventArgs args)
        {
            Frame rootFrame    = Window.Current.Content as Frame;
            var   coreTitleBar = CoreApplication.GetCurrentView().TitleBar;

            coreTitleBar.ExtendViewIntoTitleBar = true;

            ApplicationView.GetForCurrentView().TitleBar.ButtonForegroundColor = (Color)Current.Resources["SystemAccentColor"];
            ApplicationView.GetForCurrentView().TitleBar.ButtonBackgroundColor = Colors.Transparent;
            ApplicationView.GetForCurrentView().TitleBar.ButtonHoverForegroundColor = (Color)Current.Resources["SystemAccentColor"];
            ApplicationView.GetForCurrentView().TitleBar.ButtonHoverBackgroundColor = Colors.Transparent;

            // Do not repeat app initialization when the Window already has content
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

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

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

            Tuple <Type, object> destination = new Tuple <Type, object>(typeof(Views.HomeView), null);

            if (args.Kind == ActivationKind.Protocol)
            {
                ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
                // TODO: Handle URI activation
                // The received URI is eventArgs.Uri.AbsoluteUri

                // Removes the uwpcommunity:// from the URI
                string path = eventArgs.Uri.ToString()
                              .Remove(0, eventArgs.Uri.Scheme.Length + 3);
                var queryParams = HttpUtility.ParseQueryString(eventArgs.Uri.Query.Replace("\r", String.Empty).Replace("\n", String.Empty));
                if (path.StartsWith("projects"))
                {
                    destination = new Tuple <Type, object>(typeof(Views.ProjectsView), queryParams);
                }
                else if (path.StartsWith("launch"))
                {
                    destination = new Tuple <Type, object>(typeof(Views.LaunchView), queryParams);
                }
                else if (path.StartsWith("dashboard"))
                {
                    destination = new Tuple <Type, object>(typeof(Views.DashboardView), queryParams);
                }
                else if (path.StartsWith("llamabingo"))
                {
                    destination = new Tuple <Type, object>(typeof(Views.Subviews.LlamaBingo), queryParams);
                }
            }
            rootFrame.Navigate(typeof(MainPage), destination);

            SettingsManager.ApplyAppTheme(SettingsManager.GetAppTheme());
            SettingsManager.ApplyUseDebugApi(SettingsManager.GetUseDebugApi());

            // Ensure the current window is active
            Window.Current.Activate();
        }
예제 #18
0
 private async void CloseButton_Click(object sender, RoutedEventArgs e)
 {
     await ApplicationView.GetForCurrentView().TryConsolidateAsync();
 }
예제 #19
0
        /// <summary>
        /// 최종 사용자가 응용 프로그램을 정상적으로 시작할 때 호출됩니다. 다른 진입점은
        /// 특정 파일을 여는 등 응용 프로그램을 시작할 때
        /// </summary>
        /// <param name="e">시작 요청 및 프로세스에 대한 정보입니다.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            #region for Mobile Center
            // Get the user's geographic region and its two-letter identifier for this region.
            var geographicRegion = new Windows.Globalization.GeographicRegion();
            var code             = geographicRegion.CodeTwoLetter;

            //MobileCenter.LogLevel = LogLevel.Verbose;
            MobileCenter.SetCountryCode(code);
            MobileCenter.Start("f7981365-4bfc-4008-a33e-e293fa5e575d", typeof(Analytics), typeof(Crashes));
            #endregion

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                //this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            Frame rootFrame = Window.Current.Content as Frame;

            // 창에 콘텐츠가 이미 있는 경우 앱 초기화를 반복하지 말고,
            // 창이 활성화되어 있는지 확인하십시오.
            if (rootFrame == null)
            {
                //MVVM 초기화
                GalaSoft.MvvmLight.Threading.DispatcherHelper.Initialize();
                FontHelper.FontDAO = SimpleIoc.Default.GetInstance <FontDAO>();

                // 탐색 컨텍스트로 사용할 프레임을 만들고 첫 페이지로 이동합니다.
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: 이전에 일시 중지된 응용 프로그램에서 상태를 로드합니다.
                }

                // 현재 창에 프레임 넣기
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    //이전에 풀스크린으로 끝났었다면 강제로 종료시킴
                    if (IsMobile)
                    {
                        var cv = ApplicationView.GetForCurrentView();
                        if (cv.IsFullScreenMode)
                        {
                            cv.ExitFullScreenMode();
                        }
                    }
                    // 탐색 스택이 복원되지 않으면 첫 번째 페이지로 돌아가고
                    // 필요한 정보를 탐색 매개 변수로 전달하여 새 페이지를
                    // 구성합니다.
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
                // 현재 창이 활성 창인지 확인
                Window.Current.Activate();
            }
        }
예제 #20
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 void OnLaunched(LaunchActivatedEventArgs e)
        {
            var loaded = Core.Initialize();

            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;

                Xamarin.Forms.Forms.Init(e);

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

                // 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(loaded ? typeof(MainPage) : typeof(SelectTypePage), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();

            var coreBar = CoreApplication.GetCurrentView().TitleBar;

            coreBar.ExtendViewIntoTitleBar = true;
            var titleBar = ApplicationView.GetForCurrentView().TitleBar;

            titleBar.ButtonBackgroundColor = titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
            titleBar.ButtonForegroundColor = Colors.Black;

            return;


            var themeColor = Color.FromArgb(255, 33, 150, 243);

            titleBar.BackgroundColor = themeColor;

            var foregroundColor = Color.FromArgb(255, 255, 255, 255);

            titleBar.ForegroundColor              = foregroundColor;
            titleBar.InactiveBackgroundColor      = Colors.Transparent;
            titleBar.InactiveForegroundColor      = foregroundColor;
            titleBar.ButtonBackgroundColor        = titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
            titleBar.ButtonHoverBackgroundColor   = Color.FromArgb(0x88, 0xFF, 0xFF, 0xFF);
            titleBar.ButtonPressedBackgroundColor = Color.FromArgb(0x88, 0x00, 0x00, 0x00);
            titleBar.ButtonForegroundColor        = foregroundColor;
        }
예제 #21
0
 private void OnLoaded(object sender, RoutedEventArgs e)
 {
     Loaded -= OnLoaded;
     ApplicationView.GetForCurrentView().SetPreferredMinSize(new Windows.Foundation.Size(300, 300));
 }
예제 #22
0
 public void Initialize()
 {
     MainViewId     = ApplicationView.GetForCurrentView().Id;
     MainDispatcher = Window.Current.Dispatcher;
 }
예제 #23
0
        void AddNativeControls(NestedNativeControlGalleryPage page)
        {
            if (page.NativeControlsAdded)
            {
                return;
            }

            StackLayout sl = page.Layout;

            // Create and add a native TextBlock
            var originalText = "I am a native TextBlock";
            var textBlock    = new TextBlock
            {
                Text       = originalText,
                FontSize   = 14,
                FontFamily = new FontFamily("HelveticaNeue")
            };

            sl?.Children.Add(textBlock);

            // Create and add a native Button
            var button = new Microsoft.UI.Xaml.Controls.Button {
                Content = "Toggle Font Size", Height = 80
            };

            button.Click += (sender, args) => { textBlock.FontSize = textBlock.FontSize == 14 ? 24 : 14; };

            sl?.Children.Add(button.ToView());

            // Create a control which we know doesn't behave correctly with regard to measurement
            var difficultControl = new BrokenNativeControl
            {
                Text = "Not Sized/Arranged Properly"
            };

            var difficultControl2 = new BrokenNativeControl
            {
                Text = "Fixed"
            };

            // Add the misbehaving controls, one with a custom delegate for ArrangeOverrideDelegate
            sl?.Children.Add(difficultControl);
            sl?.Children.Add(difficultControl2,
                             arrangeOverrideDelegate: (renderer, finalSize) =>
            {
                if (finalSize.Width <= 0 || double.IsInfinity(finalSize.Width))
                {
                    return(null);
                }

                FrameworkElement frameworkElement = renderer.Control;

                frameworkElement.Measure(finalSize);

                // The broken control always tries to size itself to the screen width
                // So figure that out and we'll know how far off it's laying itself out
                var bounds         = ApplicationView.GetForCurrentView().VisibleBounds;
                double scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
                var screenWidth    = new Size(bounds.Width * scaleFactor, bounds.Height * scaleFactor);

                // We can re-center it by offsetting it during the Arrange call
                double diff = Math.Abs(screenWidth.Width - finalSize.Width) / -2;
                frameworkElement.Arrange(new Windows.Foundation.Rect(diff, 0, finalSize.Width - diff, finalSize.Height));

                // Arranging the control to the left will make it show up past the edge of the stack layout
                // We can fix that by clipping it manually
                var clip = new RectangleGeometry {
                    Rect = new Windows.Foundation.Rect(-diff, 0, finalSize.Width, finalSize.Height)
                };
                frameworkElement.Clip = clip;

                return(finalSize);
            }
                             );

            page.NativeControlsAdded = true;
        }
예제 #24
0
        // TODO WTS: Displays a view as a standalone
        // You can use the resulting ViewLifeTileControl to interact with the new window.
        public async Task <ViewLifetimeControl> TryShowAsStandaloneAsync(string windowTitle, Type pageType)
        {
            ViewLifetimeControl viewControl = await CreateViewLifetimeControlAsync(windowTitle, pageType);

            SecondaryViews.Add(viewControl);
            viewControl.StartViewInUse();
            var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(viewControl.Id, ViewSizePreference.Default, ApplicationView.GetForCurrentView().Id, ViewSizePreference.Default);

            viewControl.StopViewInUse();
            return(viewControl);
        }
예제 #25
0
        public void Show()
        {
            var appView = ApplicationView.GetForCurrentView();

            popup = new Popup();
            //popup.HorizontalOffset = appView.VisibleBounds.Width;
            //popup.VerticalOffset = appView.VisibleBounds.Height;
            popup.Child             = this;
            this.Height             = appView.VisibleBounds.Height;
            this.Width              = appView.VisibleBounds.Width;
            this.contentGrid.Width  = this.Width / 3;
            this.contentGrid.Height = this.Height / 3;
            EventHandler <Windows.UI.Core.BackRequestedEventArgs> PageNavHelper_BeforeBackRequest = (s, e) =>
            {
                if (popup.IsOpen)
                {
                    e.Handled    = true;
                    popup.IsOpen = false;
                }
            };

            TypedEventHandler <ApplicationView, object> handler = (s, e) =>
            {
                try
                {
                    if (popup.IsOpen)
                    {
                        //popup.HorizontalOffset = appView.VisibleBounds.Width;
                        //popup.VerticalOffset = appView.VisibleBounds.Height;
                        this.Height             = appView.VisibleBounds.Height;
                        this.Width              = appView.VisibleBounds.Width;
                        this.contentGrid.Width  = this.Width / 3;
                        this.contentGrid.Height = this.Height / 3;
                    }
                }
                catch (Exception ex)
                {
                    MainPage.ShowErrorMessage(ex.Message);
                    return;
                }
            };

            //TappedEventHandler tapped = (s, e) =>
            //{
            //    if (popup.IsOpen)
            //    {
            //            //popup.IsOpen = false;
            //    }
            //};
            popup.Opened += (s, e) =>
            {
                this.Visibility = Visibility.Visible;
                appView.VisibleBoundsChanged += handler;
            };

            popup.Closed += (s, e) =>
            {
                this.Visibility = Visibility.Collapsed;
                appView.VisibleBoundsChanged -= handler;
            };

            popup.IsOpen = true;
        }
예제 #26
0
        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            if (SettingsHelper.IsAuthorized)
            {
                if (args is ShareTargetActivatedEventArgs share)
                {
                    var package   = new DataPackage();
                    var operation = share.ShareOperation.Data;
                    if (operation.Contains(StandardDataFormats.ApplicationLink))
                    {
                        package.SetApplicationLink(await operation.GetApplicationLinkAsync());
                    }
                    if (operation.Contains(StandardDataFormats.Bitmap))
                    {
                        package.SetBitmap(await operation.GetBitmapAsync());
                    }
                    //if (operation.Contains(StandardDataFormats.Html))
                    //{
                    //    package.SetHtmlFormat(await operation.GetHtmlFormatAsync());
                    //}
                    //if (operation.Contains(StandardDataFormats.Rtf))
                    //{
                    //    package.SetRtf(await operation.GetRtfAsync());
                    //}
                    if (operation.Contains(StandardDataFormats.StorageItems))
                    {
                        package.SetStorageItems(await operation.GetStorageItemsAsync());
                    }
                    if (operation.Contains(StandardDataFormats.Text))
                    {
                        package.SetText(await operation.GetTextAsync());
                    }
                    //if (operation.Contains(StandardDataFormats.Uri))
                    //{
                    //    package.SetUri(await operation.GetUriAsync());
                    //}
                    if (operation.Contains(StandardDataFormats.WebLink))
                    {
                        package.SetWebLink(await operation.GetWebLinkAsync());
                    }

                    ShareOperation = share.ShareOperation;
                    DataPackage    = package.GetView();

                    var options = new LauncherOptions();
                    options.TargetApplicationPackageFamilyName = Package.Current.Id.FamilyName;

                    await Launcher.LaunchUriAsync(new Uri("tg://"), options);
                }
                else if (args is VoiceCommandActivatedEventArgs voice)
                {
                    Execute.Initialize();

                    SpeechRecognitionResult speechResult = voice.Result;
                    string command = speechResult.RulePath[0];

                    if (command == "ShowAllDialogs")
                    {
                        NavigationService.NavigateToMain(null);
                    }
                    if (command == "ShowSpecificDialog")
                    {
                        //#TODO: Fix that this'll open a specific dialog
                        NavigationService.NavigateToMain(null);
                    }
                    else
                    {
                        NavigationService.NavigateToMain(null);
                    }
                }
                else if (args is ContactPanelActivatedEventArgs contact)
                {
                    var backgroundBrush = Application.Current.Resources["TelegramBackgroundTitlebarBrush"] as SolidColorBrush;
                    contact.ContactPanel.HeaderColor = backgroundBrush.Color;

                    var annotationStore = await ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite);

                    var store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);

                    if (store != null && annotationStore != null)
                    {
                        var full = await store.GetContactAsync(contact.Contact.Id);

                        if (full == null)
                        {
                            NavigationService.NavigateToMain(null);
                        }
                        else
                        {
                            var annotations = await annotationStore.FindAnnotationsForContactAsync(full);

                            var first = annotations.FirstOrDefault();
                            if (first == null)
                            {
                                NavigationService.NavigateToMain(null);
                            }
                            else
                            {
                                var remote = first.RemoteId;
                                if (int.TryParse(remote.Substring(1), out int userId))
                                {
                                    NavigationService.Navigate(typeof(DialogPage), new TLPeerUser {
                                        UserId = userId
                                    });
                                }
                                else
                                {
                                    NavigationService.NavigateToMain(null);
                                }
                            }
                        }
                    }
                    else
                    {
                        NavigationService.NavigateToMain(null);
                    }
                }
                else if (args is ProtocolActivatedEventArgs protocol)
                {
                    Execute.Initialize();

                    if (ShareOperation != null)
                    {
                        ShareOperation.ReportCompleted();
                        ShareOperation = null;
                    }

                    if (NavigationService?.Frame?.Content is MainPage page)
                    {
                        page.Activate(protocol.Uri);
                    }
                    else
                    {
                        NavigationService.NavigateToMain(protocol.Uri.ToString());
                    }
                }
                else
                {
                    Execute.Initialize();

                    var activate = args as ToastNotificationActivatedEventArgs;
                    var launched = args as LaunchActivatedEventArgs;
                    var launch   = activate?.Argument ?? launched?.Arguments;

                    if (NavigationService?.Frame?.Content is MainPage page)
                    {
                        page.Activate(launch);
                    }
                    else
                    {
                        NavigationService.NavigateToMain(launch);
                    }
                }
            }
            else
            {
                Execute.Initialize();

                NavigationService.Navigate(typeof(IntroPage));
            }

            Window.Current.Activated         -= Window_Activated;
            Window.Current.Activated         += Window_Activated;
            Window.Current.VisibilityChanged -= Window_VisibilityChanged;
            Window.Current.VisibilityChanged += Window_VisibilityChanged;
            Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -= Dispatcher_AcceleratorKeyActivated;
            Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated;

            UpdateBars();
            ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(320, 500));
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;

            Theme.Current.Update();
            NotifyThemeChanged();

            Task.Run(() => OnStartSync());
            //return Task.CompletedTask;
        }
예제 #27
0
 private void UnregisterForEvents()
 {
     ApplicationView.GetForCurrentView().Consolidated -= ViewConsolidated;
 }
예제 #28
0
        public override async void OnStart(StartKind startKind, IActivatedEventArgs args)
        {
            Logger.AppStart();

            TimeBombHelper.Initialize();

            DispatcherHelper.Initialize();
            CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

            if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView"))
            {
                var appView = ApplicationView.GetForCurrentView();
                appView.TitleBar.ButtonBackgroundColor         = Colors.Transparent;
                appView.TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
            }

            await AudioService.Instance.LoadState();

            var vk = SimpleIoc.Default.GetInstance <Vk>();

            vk.Language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;

            var lastFm = Ioc.Resolve <LastFm>();

            lastFm.SessionKey = AppState.LastFmSession?.Key;

            if (AppState.VkToken == null || AppState.VkToken.HasExpired)
            {
                NavigationService.Navigate(typeof(LoginView));
            }
            else
            {
                vk.AccessToken = AppState.VkToken;
                Messenger.Default.Send(new MessageUserAuthChanged {
                    IsLoggedIn = true
                });

                if (AppState.StartPage == StartPage.Mymusic)
                {
                    NavigationService.Navigate(typeof(MyMusicView));
                }
                else
                {
                    NavigationService.Navigate(typeof(ExploreView));
                }
            }

            //if (TimeBombHelper.HasExpired())
            //{
            //    var dialog = new MessageDialog(Utils.Helpers.Resources.GetStringByKey("TimeBomb_ExpiredContent"), Utils.Helpers.Resources.GetStringByKey("TimeBomb_ExpiredTitle"));
            //    dialog.Commands.Add(new UICommand(Utils.Helpers.Resources.GetStringByKey("TimeBomb_Install"), async command =>
            //    {
            //        await Launcher.LaunchUriAsync(new Uri("https://www.microsoft.com/store/apps/9wzdncrdmsq3"));
            //    }));

            //    dialog.Commands.Add(new UICommand(Utils.Helpers.Resources.GetStringByKey("Close")));

            //    await dialog.ShowAsync();

            //    Application.Current.Exit();
            //}
        }
예제 #29
0
        public async Task When_Too_Large_For_Any_Fallback()
        {
            var target = new TextBlock
            {
                Text = "Anchor",
                VerticalAlignment = VerticalAlignment.Bottom
            };

            var stretchedTargetWrapper = new Border
            {
                MinHeight           = 600,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top,
                Child = target
            };

            var windowHeight = ApplicationView.GetForCurrentView().VisibleBounds.Height;

            var flyoutContent = new Ellipse
            {
                Width  = 90,
                Height = windowHeight * 1.5,
                Fill   = new SolidColorBrush(Colors.Tomato)
            };

            var presenterStyle = new Style
            {
                TargetType = typeof(FlyoutPresenter),
                Setters    =
                {
                    new Setter(FrameworkElement.MaxHeightProperty, windowHeight * 1.7)
                }
            };

            var flyout = new Flyout
            {
                FlyoutPresenterStyle = presenterStyle,
                Content   = flyoutContent,
                Placement = FlyoutPlacementMode.Top
            };

            TestServices.WindowHelper.WindowContent = stretchedTargetWrapper;

            await TestServices.WindowHelper.WaitForLoaded(target);

            try
            {
                FlyoutBase.SetAttachedFlyout(target, flyout);
                FlyoutBase.ShowAttachedFlyout(target);

                await TestServices.WindowHelper.WaitForLoaded(flyoutContent);

                var contentScreenBounds = flyoutContent.GetOnScreenBounds();
                var contentCenter       = contentScreenBounds.GetCenter();
                var targetScreenBounds  = target.GetOnScreenBounds();
                var targetCenter        = targetScreenBounds.GetCenter();

                var presenter = await TestServices.WindowHelper.WaitForNonNull(() => flyoutContent.FindFirstParent <FlyoutPresenter>());

                VerifyRelativeContentPosition(HorizontalPosition.Center,
                                              VerticalPosition.BeyondTop,
                                              presenter, // The content itself is in a ScrollViewer and its bounds will exceed the visible area
                                              0,
                                              target
                                              );
            }
            finally
            {
                flyout.Hide();
            }
        }
예제 #30
0
        public NotepadsMainPage()
        {
            InitializeComponent();

            _defaultNewFileName = _resourceLoader.GetString("TextEditor_DefaultNewFileName");

            NotificationCenter.Instance.SetNotificationDelegate(this);

            // Setup theme
            ThemeSettingsService.AppBackground = RootGrid;
            ThemeSettingsService.SetRequestedTheme();

            // Setup custom Title Bar
            Window.Current.SetTitleBar(AppTitleBar);

            // Setup status bar
            ShowHideStatusBar(EditorSettingsService.ShowStatusBar);
            EditorSettingsService.OnStatusBarVisibilityChanged += (sender, visibility) =>
            {
                if (ApplicationView.GetForCurrentView().ViewMode != ApplicationViewMode.CompactOverlay)
                {
                    ShowHideStatusBar(visibility);
                }
            };

            // Session backup and restore toggle
            EditorSettingsService.OnSessionBackupAndRestoreOptionChanged += async(sender, isSessionBackupAndRestoreEnabled) =>
            {
                if (isSessionBackupAndRestoreEnabled)
                {
                    SessionManager.IsBackupEnabled = true;
                    SessionManager.StartSessionBackup(startImmediately: true);
                }
                else
                {
                    SessionManager.IsBackupEnabled = false;
                    SessionManager.StopSessionBackup();
                    await SessionManager.ClearSessionDataAsync();
                }
            };

            // Sharing
            Windows.ApplicationModel.DataTransfer.DataTransferManager.GetForCurrentView().DataRequested += MainPage_DataRequested;
            Windows.UI.Core.Preview.SystemNavigationManagerPreview.GetForCurrentView().CloseRequested   += MainPage_CloseRequested;

            Window.Current.VisibilityChanged += WindowVisibilityChangedEventHandler;
            Window.Current.SizeChanged       += WindowSizeChanged;

            InitControls();

            // Init shortcuts
            _keyboardCommandHandler = GetKeyboardCommandHandler();

            //Register for printing
            if (!PrintManager.IsSupported())
            {
                MenuPrintButton.Visibility        = Visibility.Collapsed;
                MenuPrintAllButton.Visibility     = Visibility.Collapsed;
                PrintSettingsSeparator.Visibility = Visibility.Collapsed;
            }
            else
            {
                PrintArgs.RegisterForPrinting(this);
            }
        }