//private Visual _topBarVisual;
        //private Visual _botBarVisual;

        private GalleryView()
        {
            InitializeComponent();

            Layer.Visibility  = Visibility.Collapsed;
            TopBar.Visibility = Visibility.Collapsed;
            BotBar.Visibility = Visibility.Collapsed;

            _mediaPlayer = new MediaPlayerElement {
                Style = Resources["yolo"] as Style
            };
            _mediaPlayer.AreTransportControlsEnabled = true;
            _mediaPlayer.TransportControls           = Transport;
            _mediaPlayer.SetMediaPlayer(new MediaPlayer());
            _mediaPlayer.MediaPlayer.PlaybackSession.PlaybackStateChanged += OnPlaybackStateChanged;

            _layerVisual = ElementCompositionPreview.GetElementVisual(Layer);
            //_topBarVisual = ElementCompositionPreview.GetElementVisual(TopBar);
            //_botBarVisual = ElementCompositionPreview.GetElementVisual(BotBar);

            //_layerVisual.Opacity = 0;
            //_topBarVisual.Offset = new Vector3(0, -48, 0);
            //_botBarVisual.Offset = new Vector3(0, 48, 0);

            if (ApiInformation.IsMethodPresent("Windows.UI.Xaml.Hosting.ElementCompositionPreview", "SetImplicitShowAnimation"))
            {
                var easing   = ConnectedAnimationService.GetForCurrentView().DefaultEasingFunction;
                var duration = ConnectedAnimationService.GetForCurrentView().DefaultDuration;

                var topShowAnimation = Window.Current.Compositor.CreateVector3KeyFrameAnimation();
                topShowAnimation.InsertKeyFrame(0.0f, new Vector3(0, -48, 0), easing);
                topShowAnimation.InsertKeyFrame(1.0f, new Vector3(), easing);
                topShowAnimation.Target   = nameof(Visual.Offset);
                topShowAnimation.Duration = duration;

                var botHideAnimation = Window.Current.Compositor.CreateVector3KeyFrameAnimation();
                botHideAnimation.InsertKeyFrame(0.0f, new Vector3(), easing);
                botHideAnimation.InsertKeyFrame(1.0f, new Vector3(0, 48, 0), easing);
                botHideAnimation.Target   = nameof(Visual.Offset);
                botHideAnimation.Duration = duration;

                var topHideAnimation = Window.Current.Compositor.CreateVector3KeyFrameAnimation();
                topHideAnimation.InsertKeyFrame(0.0f, new Vector3(), easing);
                topHideAnimation.InsertKeyFrame(1.0f, new Vector3(0, -48, 0), easing);
                topHideAnimation.Target   = nameof(Visual.Offset);
                topHideAnimation.Duration = duration;

                var botShowAnimation = Window.Current.Compositor.CreateVector3KeyFrameAnimation();
                botShowAnimation.InsertKeyFrame(0.0f, new Vector3(0, 48, 0), easing);
                botShowAnimation.InsertKeyFrame(1.0f, new Vector3(), easing);
                botShowAnimation.Target   = nameof(Visual.Offset);
                botShowAnimation.Duration = duration;

                var layerShowAnimation = Window.Current.Compositor.CreateScalarKeyFrameAnimation();
                layerShowAnimation.InsertKeyFrame(0.0f, 0.0f, easing);
                layerShowAnimation.InsertKeyFrame(1.0f, 1.0f, easing);
                layerShowAnimation.Target   = nameof(Visual.Opacity);
                layerShowAnimation.Duration = duration;

                var layerHideAnimation = Window.Current.Compositor.CreateScalarKeyFrameAnimation();
                layerHideAnimation.InsertKeyFrame(0.0f, 1.0f, easing);
                layerHideAnimation.InsertKeyFrame(1.0f, 0.0f, easing);
                layerHideAnimation.Target   = nameof(Visual.Opacity);
                layerHideAnimation.Duration = duration;

                ElementCompositionPreview.SetImplicitShowAnimation(TopBar, topShowAnimation);
                ElementCompositionPreview.SetImplicitHideAnimation(TopBar, topHideAnimation);
                ElementCompositionPreview.SetImplicitShowAnimation(BotBar, botShowAnimation);
                ElementCompositionPreview.SetImplicitHideAnimation(BotBar, botHideAnimation);
                ElementCompositionPreview.SetImplicitShowAnimation(Layer, layerShowAnimation);
                ElementCompositionPreview.SetImplicitHideAnimation(Layer, layerHideAnimation);
            }
        }
        public Rectangle GetHinge()
        {
            if (!ApiInformation.IsMethodPresent("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 <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);
        }
Esempio n. 3
0
 public static bool IsCompactOverlaySupported(this ApplicationView view)
 {
     return(ApiInformation.IsMethodPresent("Windows.UI.ViewManagement.ApplicationView", "IsViewModeSupported") && view.IsViewModeSupported(ApplicationViewMode.CompactOverlay));
 }
Esempio n. 4
0
        private static void OnMethodNamePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var obj        = (IsMethodPresentStateTrigger)d;
            var methodName = (string)e.NewValue;
            var typeName   = obj.TypeName;

            obj.IsActive = (!string.IsNullOrWhiteSpace(methodName) && !string.IsNullOrWhiteSpace(typeName) && ApiInformation.IsMethodPresent(typeName, methodName));
        }
        /// <summary>
        /// Uses Composition API to get the UIElement and sets an ExpressionAnimation
        /// The ExpressionAnimation uses the height of the UIElement to calculate an opacity value
        /// for the Header as it is scrolling off-screen. The opacity reaches 0 when the Header
        /// is entirely scrolled off.
        /// </summary>
        /// <returns><c>true</c> if the assignment was successful; otherwise, <c>false</c>.</returns>
        private bool AssignAnimation()
        {
            StopAnimation();

            // Confirm that Windows.UI.Xaml.Hosting.ElementCompositionPreview is available (Windows 10 10586 or later).
            if (!ApiInformation.IsMethodPresent("Windows.UI.Xaml.Hosting.ElementCompositionPreview", nameof(ElementCompositionPreview.GetScrollViewerManipulationPropertySet)))
            {
                // Just return true since it's not supported
                return(true);
            }

            if (AssociatedObject == null)
            {
                return(false);
            }

            if (_scrollViewer == null)
            {
                _scrollViewer = AssociatedObject as ScrollViewer ?? AssociatedObject.FindDescendant <ScrollViewer>();
            }

            if (_scrollViewer == null)
            {
                return(false);
            }

            if (_scrollProperties == null)
            {
                _scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(_scrollViewer);
            }

            if (_scrollProperties == null)
            {
                return(false);
            }

            // Implicit operation: Find the Header object of the control if it uses ListViewBase
            if (HeaderElement == null)
            {
                var listElement = AssociatedObject as Windows.UI.Xaml.Controls.ListViewBase ?? AssociatedObject.FindDescendant <Windows.UI.Xaml.Controls.ListViewBase>();

                if (listElement != null)
                {
                    HeaderElement = listElement.Header as UIElement;
                }
            }

            var headerElement = HeaderElement as FrameworkElement;

            if (headerElement == null || headerElement.RenderSize.Height == 0)
            {
                return(false);
            }

            if (_headerVisual == null)
            {
                _headerVisual = ElementCompositionPreview.GetElementVisual(headerElement);
            }

            if (_headerVisual == null)
            {
                return(false);
            }

            headerElement.SizeChanged -= ScrollHeader_SizeChanged;
            headerElement.SizeChanged += ScrollHeader_SizeChanged;

            _scrollViewer.GotFocus -= ScrollViewer_GotFocus;
            _scrollViewer.GotFocus += ScrollViewer_GotFocus;

            var compositor = _scrollProperties.Compositor;

            if (_animationProperties == null)
            {
                _animationProperties = compositor.CreatePropertySet();
                _animationProperties.InsertScalar("OffsetY", 0.0f);
            }

            _previousVerticalScrollOffset = _scrollViewer.VerticalOffset;

            var expressionAnimation = compositor.CreateExpressionAnimation($"max(animationProperties.OffsetY - ScrollingProperties.Translation.Y, 0)");

            expressionAnimation.SetReferenceParameter("ScrollingProperties", _scrollProperties);
            expressionAnimation.SetReferenceParameter("animationProperties", _animationProperties);

            _headerVisual.StartAnimation("Offset.Y", expressionAnimation);

            return(true);
        }
Esempio n. 6
0
        private async void mbAskForReview_Response(object sender, MessageBoxResponse e)
        {
            try
            {
                switch (e.Response)
                {
                // Review
                case 0:

                    try
                    {
                        if (ApiInformation.IsMethodPresent("Windows.Services.Store.StoreRequestHelper", "SendRequestAsync"))
                        {
                            var result = await Windows.Services.Store.StoreRequestHelper.SendRequestAsync(
                                Windows.Services.Store.StoreContext.GetDefault(), 16, String.Empty);

                            // If showing dialog succeeded
                            if (result.ExtendedError == null)
                            {
                                // We don't want exceptions parsing here to cause fallback behavior
                                try
                                {
                                    var    jsonObject = Newtonsoft.Json.Linq.JObject.Parse(result.Response);
                                    string status     = jsonObject.SelectToken("status")?.ToString() ?? "";

                                    var props = new Dictionary <string, string>()
                                    {
                                        { "Status", status }
                                    };
                                    if (status == "success")
                                    {
                                        bool updated = jsonObject.SelectToken("data")?.Value <bool>("updated") ?? false;
                                        props.Add("Updated", updated.ToString());
                                    }

                                    TelemetryExtension.Current?.TrackEvent("ReviewAppResponse", props);
                                }
                                catch (Exception ex)
                                {
                                    TelemetryExtension.Current?.TrackException(ex);
                                }

                                // We don't continue falling back at all
                                return;
                            }

                            TelemetryExtension.Current?.TrackException(result.ExtendedError);
                        }
                    }
                    catch (Exception ex)
                    {
                        TelemetryExtension.Current?.TrackException(ex);
                        // Fall back to normal
                    }

                    await Launcher.LaunchUriAsync(new Uri("ms-windows-store://review/?ProductId=9wzdncrfj25v"));

                    break;

                // Email dev
                case 1:
                    AboutView.EmailDeveloper(ViewModel);
                    break;
                }
            }

            catch (Exception ex)
            {
                TelemetryExtension.Current?.TrackException(ex);
            }
        }
Esempio n. 7
0
        private async void Properties_Loaded(object sender, RoutedEventArgs e)
        {
            AppSettings.ThemeModeChanged += AppSettings_ThemeModeChanged;
            if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
            {
                // Set window size in the loaded event to prevent flickering
                if (WindowDecorationsHelper.IsWindowDecorationsAllowed)
                {
                    appWindow.TitleBar.SetPreferredVisibility(AppWindowTitleBarVisibility.AlwaysHidden);
                    appWindow.Frame.DragRegionVisuals.Add(TitleBarDragArea);

                    crossIcon.Foreground = ThemeHelper.RootTheme switch
                    {
                        ElementTheme.Default => new SolidColorBrush((Color)Application.Current.Resources["SystemBaseHighColor"]),
                        ElementTheme.Light => new SolidColorBrush(Colors.Black),
                        ElementTheme.Dark => new SolidColorBrush(Colors.White),
                        _ => new SolidColorBrush((Color)Application.Current.Resources["SystemBaseHighColor"])
                    };

                    var micaIsSupported = ApiInformation.IsMethodPresent("Windows.UI.Composition.Compositor", "TryCreateBlurredWallpaperBackdropBrush");
                    if (micaIsSupported)
                    {
                        micaBrush = new Brushes.MicaBrush(false);
                        (micaBrush as Brushes.MicaBrush).SetAppWindow(appWindow);
                        Frame.Background = micaBrush;
                    }
                    else
                    {
                        Microsoft.UI.Xaml.Controls.BackdropMaterial.SetApplyToRootOrPageBackground(sender as Control, true);
                    }

                    var duration = new Duration(TimeSpan.FromMilliseconds(280));

                    RectHoverAnim = new Storyboard();
                    var RectHoverColorAnim = new ColorAnimation();
                    RectHoverColorAnim.Duration       = duration;
                    RectHoverColorAnim.From           = Colors.Transparent;
                    RectHoverColorAnim.To             = Color.FromArgb(255, 232, 17, 35);
                    RectHoverColorAnim.EasingFunction = new SineEase();
                    Storyboard.SetTarget(RectHoverColorAnim, CloseRect);
                    Storyboard.SetTargetProperty(RectHoverColorAnim, "(Rectangle.Fill).(SolidColorBrush.Color)");
                    RectHoverAnim.Children.Add(RectHoverColorAnim);

                    RectUnHoverAnim = new Storyboard();
                    var RectUnHoverColorAnim = new ColorAnimation();
                    RectUnHoverColorAnim.Duration       = duration;
                    RectUnHoverColorAnim.To             = Colors.Transparent;
                    RectUnHoverColorAnim.From           = Color.FromArgb(255, 232, 17, 35);
                    RectUnHoverColorAnim.EasingFunction = new SineEase();
                    Storyboard.SetTarget(RectUnHoverColorAnim, CloseRect);
                    Storyboard.SetTargetProperty(RectUnHoverColorAnim, "(Rectangle.Fill).(SolidColorBrush.Color)");
                    RectUnHoverAnim.Children.Add(RectUnHoverColorAnim);

                    CrossHoverAnim = new Storyboard();
                    var CrossHoverColorAnim = new ColorAnimation();
                    CrossHoverColorAnim.Duration       = duration;
                    CrossHoverColorAnim.From           = ((SolidColorBrush)crossIcon.Foreground).Color;
                    CrossHoverColorAnim.To             = Colors.White;
                    CrossHoverColorAnim.EasingFunction = new SineEase();
                    Storyboard.SetTarget(CrossHoverColorAnim, crossIcon);
                    Storyboard.SetTargetProperty(CrossHoverColorAnim, "(PathIcon.Foreground).(SolidColorBrush.Color)");
                    CrossHoverAnim.Children.Add(CrossHoverColorAnim);

                    CrossUnHoverAnim = new Storyboard();
                    var CrossUnHoverColorAnim = new ColorAnimation();
                    CrossUnHoverColorAnim.Duration       = duration;
                    CrossUnHoverColorAnim.To             = ((SolidColorBrush)crossIcon.Foreground).Color;
                    CrossUnHoverColorAnim.From           = Colors.White;
                    CrossUnHoverColorAnim.EasingFunction = new SineEase();
                    Storyboard.SetTarget(CrossUnHoverColorAnim, crossIcon);
                    Storyboard.SetTargetProperty(CrossUnHoverColorAnim, "(PathIcon.Foreground).(SolidColorBrush.Color)");
                    CrossUnHoverAnim.Children.Add(CrossUnHoverColorAnim);
                }
                else
                {
                    Microsoft.UI.Xaml.Controls.BackdropMaterial.SetApplyToRootOrPageBackground(sender as Control, true);

                    TitleBar = ApplicationView.GetForCurrentView().TitleBar;
                    TitleBar.ButtonBackgroundColor         = Colors.Transparent;
                    TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
                    Window.Current.SetTitleBar(TitleBarDragArea);
                }
                await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => AppSettings.UpdateThemeElements.Execute(null));
            }
            else
            {
                Microsoft.UI.Xaml.Controls.BackdropMaterial.SetApplyToRootOrPageBackground(sender as Control, true);
                propertiesDialog         = DependencyObjectHelpers.FindParent <ContentDialog>(this);
                propertiesDialog.Closed += PropertiesDialog_Closed;
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Uses Composition API to get the UIElement and sets an ExpressionAnimation
        /// The ExpressionAnimation uses the height of the UIElement to calculate an opacity value
        /// for the Header as it is scrolling off-screen. The opacity reaches 0 when the Header
        /// is entirely scrolled off.
        /// </summary>
        /// <returns><c>true</c> if the assignment was successful; otherwise, <c>false</c>.</returns>
        private bool AssignAnimation()
        {
            StopAnimation();

            // Confirm that Windows.UI.Xaml.Hosting.ElementCompositionPreview is available (Windows 10 10586 or later).
            if (!ApiInformation.IsMethodPresent("Windows.UI.Xaml.Hosting.ElementCompositionPreview", nameof(ElementCompositionPreview.GetScrollViewerManipulationPropertySet)))
            {
                // Just return true since it's not supported
                return(true);
            }

            if (AssociatedObject == null)
            {
                return(false);
            }

            if (_scrollViewer == null)
            {
                _scrollViewer = AssociatedObject as ScrollViewer ?? AssociatedObject.FindDescendant <ScrollViewer>();
            }

            if (_scrollViewer == null)
            {
                return(false);
            }

            var listView = AssociatedObject as Windows.UI.Xaml.Controls.ListViewBase ?? AssociatedObject.FindDescendant <Windows.UI.Xaml.Controls.ListViewBase>();

            if (listView != null && listView.ItemsPanelRoot != null)
            {
                Canvas.SetZIndex(listView.ItemsPanelRoot, -1);
            }

            if (_scrollProperties == null)
            {
                _scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(_scrollViewer);
            }

            if (_scrollProperties == null)
            {
                return(false);
            }

            // Implicit operation: Find the Header object of the control if it uses ListViewBase
            if (HeaderElement == null && listView != null)
            {
                HeaderElement = listView.Header as UIElement;
            }

            var headerElement = HeaderElement as FrameworkElement;

            if (headerElement == null || headerElement.RenderSize.Height == 0)
            {
                return(false);
            }

            if (_headerVisual == null)
            {
                _headerVisual = ElementCompositionPreview.GetElementVisual(headerElement);
            }

            if (_headerVisual == null)
            {
                return(false);
            }

            _scrollViewer.ViewChanged -= ScrollViewer_ViewChanged;
            _scrollViewer.ViewChanged += ScrollViewer_ViewChanged;

            _scrollViewer.GotFocus -= ScrollViewer_GotFocus;
            _scrollViewer.GotFocus += ScrollViewer_GotFocus;

            headerElement.SizeChanged -= ScrollHeader_SizeChanged;
            headerElement.SizeChanged += ScrollHeader_SizeChanged;

            var compositor = _scrollProperties.Compositor;

            if (_animationProperties == null)
            {
                _animationProperties = compositor.CreatePropertySet();
                _animationProperties.InsertScalar("OffsetY", 0.0f);
            }

            var propSetOffset       = _animationProperties.GetReference().GetScalarProperty("OffsetY");
            var scrollPropSet       = _scrollProperties.GetSpecializedReference <ManipulationPropertySetReferenceNode>();
            var expressionAnimation = ExpressionFunctions.Max(ExpressionFunctions.Min(propSetOffset, -scrollPropSet.Translation.Y), 0);

            _headerVisual.StartAnimation("Offset.Y", expressionAnimation);

            return(true);
        }
Esempio n. 9
0
        /// <summary>
        /// Вызывается при обычном запуске приложения пользователем.  Будут использоваться другие точки входа,
        /// например, если приложение запускается для открытия конкретного файла.
        /// </summary>
        /// <param name="e">Сведения о запросе и обработке запуска.</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

            // CoreApplication.EnablePrelaunch was introduced in Windows 10 version 1607
            bool canEnablePrelaunch = ApiInformation.IsMethodPresent("Windows.ApplicationModel.Core.CoreApplication", "EnablePrelaunch");

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

                // Associate the frame with a SuspensionManager key
                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                }

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

            if (e.PrelaunchActivated == false)
            {
                // On Windows 10 version 1607 or later, this code signals that this app wants to participate in prelaunch
                if (canEnablePrelaunch)
                {
                    TryEnablePrelaunch();
                }

                // TODO: This is not a prelaunch activation. Perform operations which
                // assume that the user explicitly launched the app such as updating
                // the online presence of the user on a social network, updating a
                // what's new feed, etc.

                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                //MainPage is always in rootFrame so we don't have to worry about restoring the navigation state on resume
                rootFrame.Navigate(typeof(MainPage), e.Arguments);

                rootFrame.CacheSize = 2;
            }

            if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 2))
            {
                await ConfigureJumpList();
            }

            if (rootFrame.Content == null)
            {
                if (!rootFrame.Navigate(typeof(MainPage)))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            // Ensure the current window is active
            Window.Current.Activate();
        }
Esempio n. 10
0
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            ScrollingHost.ViewChanged += ScrollingHost_ViewChanged;
            SharedMedia.ViewChanged   += SharedMedia_ViewChanged;

            return;

            var properties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(ScrollingHost);
            var header     = ElementCompositionPreview.GetElementVisual(HeaderPanel);
            var info       = ElementCompositionPreview.GetElementVisual(ScrollingInfo);

            var photo    = ElementCompositionPreview.GetElementVisual(Photo);
            var title    = ElementCompositionPreview.GetElementVisual(LabelTitle);
            var subtitle = ElementCompositionPreview.GetElementVisual(Subtitle);
            var action   = ElementCompositionPreview.GetElementVisual(SendMessage);

            if (ApiInformation.IsMethodPresent("Windows.UI.Composition.Compositor", "CreateLinearGradientBrush"))
            {
                var overlay  = photo.Compositor.CreateSpriteVisual();
                var gradient = overlay.Compositor.CreateLinearGradientBrush();
                gradient.ColorStops.Add(overlay.Compositor.CreateColorGradientStop(0, ((SolidColorBrush)App.Current.Resources["PageHeaderBackgroundBrush"]).Color));
                gradient.ColorStops.Add(overlay.Compositor.CreateColorGradientStop(1, ((SolidColorBrush)App.Current.Resources["PageSubHeaderBackgroundBrush"]).Color));
                gradient.StartPoint = new Vector2();
                gradient.EndPoint   = new Vector2(0, 1);
                overlay.Brush       = gradient;
                overlay.Size        = new Vector2((float)HeaderOverlay.ActualWidth, (float)HeaderOverlay.ActualHeight);

                HeaderOverlay.SizeChanged += (s, args) =>
                {
                    overlay.Size = args.NewSize.ToVector2();
                };

                ElementCompositionPreview.SetElementChildVisual(HeaderOverlay, overlay);

                var animOverlay = header.Compositor.CreateExpressionAnimation("Min(76, -Min(scrollViewer.Translation.Y, 0)) / 38");
                animOverlay.SetReferenceParameter("scrollViewer", properties);

                overlay.StartAnimation("Scale.Y", animOverlay);
            }

            var animClip = header.Compositor.CreateExpressionAnimation("Min(76, -Min(scrollViewer.Translation.Y, 0))");

            animClip.SetReferenceParameter("scrollViewer", properties);

            header.Clip = header.Compositor.CreateInsetClip(0, -32, -12, 0);
            header.Clip.StartAnimation("BottomInset", animClip);


            var animPhotoOffsetY = header.Compositor.CreateExpressionAnimation("-(Min(76, -Min(scrollViewer.Translation.Y, 0)) / 76 * 41)");

            animPhotoOffsetY.SetReferenceParameter("scrollViewer", properties);

            var animPhotoOffsetX = header.Compositor.CreateExpressionAnimation("Min(76, -Min(scrollViewer.Translation.Y, 0)) / 76 * 28");

            animPhotoOffsetX.SetReferenceParameter("scrollViewer", properties);

            var animPhotoScale = header.Compositor.CreateExpressionAnimation("1 -(Min(76, -Min(scrollViewer.Translation.Y, 0)) / 76 * (34 / 64))");

            animPhotoScale.SetReferenceParameter("scrollViewer", properties);

            photo.StartAnimation("Offset.Y", animPhotoOffsetY);
            photo.StartAnimation("Offset.X", animPhotoOffsetX);
            photo.StartAnimation("Scale.X", animPhotoScale);
            photo.StartAnimation("Scale.Y", animPhotoScale);


            var animTitleY = header.Compositor.CreateExpressionAnimation("-(Min(76, -Min(scrollViewer.Translation.Y, 0)) / 76 * 58)");

            animTitleY.SetReferenceParameter("scrollViewer", properties);

            var animTitleX = header.Compositor.CreateExpressionAnimation("-(Min(76, -Min(scrollViewer.Translation.Y, 0)) / 76 * 6)");

            animTitleX.SetReferenceParameter("scrollViewer", properties);

            title.StartAnimation("Offset.Y", animTitleY);
            title.StartAnimation("Offset.X", animTitleX);
            subtitle.StartAnimation("Offset.Y", animTitleY);
            subtitle.StartAnimation("Offset.X", animTitleX);


            var animInfoY = header.Compositor.CreateExpressionAnimation("-(Min(76, -Min(scrollViewer.Translation.Y, 0)) / 76 * 40)");

            animInfoY.SetReferenceParameter("scrollViewer", properties);

            var animOpacity = header.Compositor.CreateExpressionAnimation("1 -(Min(76, -Min(scrollViewer.Translation.Y, 0)) / 76)");

            animOpacity.SetReferenceParameter("scrollViewer", properties);

            info.StartAnimation("Offset.Y", animInfoY);
            info.StartAnimation("Opacity", animOpacity);

            action.CenterPoint = new Vector3(18);
            action.StartAnimation("Opacity", animOpacity);
            action.StartAnimation("Scale.X", animOpacity);
            action.StartAnimation("Scale.Y", animOpacity);
        }
Esempio n. 11
0
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var deferral = args.GetDeferral();
            var message  = args.Request.Message;

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

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

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

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

                                return;
                            }

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

                                _phoneViewExists = true;

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

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

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

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

                                await _phoneView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    _phoneView.SetCall(tuple);
                                });
                            }
                        }
                    }
                    else if (caption.Equals("voip.setCallRating") && req is TLInputPhoneCall peer)
                    {
                        Execute.BeginOnUIThread(async() =>
                        {
                            var dialog  = new PhoneCallRatingView();
                            var confirm = await dialog.ShowAsync();
                            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();
            }
        }
        /// <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)
        {
            if (e.PrelaunchActivated)
            {
                return;
            }

            // Initialize the constant for the app display name, used for tile and toast previews
            if (Constants.ApplicationDisplayName == null)
            {
                Constants.ApplicationDisplayName = (await Package.Current.GetAppListEntriesAsync())[0].DisplayInfo.DisplayName;
            }

            // Set title bar colors
            if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView"))
            {
                var   titleBar       = ApplicationView.GetForCurrentView().TitleBar;
                Color blueBrush      = default(Color);
                Color lightGreyBrush = default(Color);
                Color greyBrush03    = default(Color);
                Color greyBrush01    = default(Color);
                blueBrush      = (Color)Resources["Blue-01"];
                lightGreyBrush = (Color)Resources["Grey-04"];
                greyBrush03    = (Color)Resources["Grey-03"];
                greyBrush01    = (Color)Resources["Grey-01"];

                if (titleBar != null)
                {
                    titleBar.ButtonBackgroundColor = greyBrush03;
                    titleBar.ButtonForegroundColor = lightGreyBrush;
                    titleBar.BackgroundColor       = greyBrush01;
                    titleBar.ForegroundColor       = lightGreyBrush;
                }
            }

            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait | DisplayOrientations.PortraitFlipped;

            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(Shell), e.Arguments);
                }

                // Status bar
                if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar") &&
                    ApiInformation.IsMethodPresent("Windows.UI.ViewManagement.StatusBar", nameof(StatusBar.HideAsync)))
                {
                    StatusBar statusBar = StatusBar.GetForCurrentView();

                    // Hide the status bar
                    await statusBar.HideAsync();
                }

                // Ensure the current window is active
                Window.Current.Activate();
            }
        }
Esempio n. 13
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)
        {
            await logWriter.InitializeAsync("debug.log");

            Logger.Info($"App launched. Prelaunch: {e.PrelaunchActivated}");

            //start tracking app usage
            SystemInformation.Instance.TrackAppUse(e);

            bool canEnablePrelaunch = ApiInformation.IsMethodPresent("Windows.ApplicationModel.Core.CoreApplication", "EnablePrelaunch");

            await EnsureSettingsAndConfigurationAreBootstrapped();

            _ = InitializeAppComponentsAsync().ContinueWith(t => Logger.Warn(t.Exception, "Error during InitializeAppComponentsAsync()"), TaskContinuationOptions.OnlyOnFaulted);

            var rootFrame = EnsureWindowIsInitialized();

            if (e.PrelaunchActivated == false)
            {
                if (canEnablePrelaunch)
                {
                    TryEnablePrelaunch();
                }

                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, new SuppressNavigationTransitionInfo());
                }
                else
                {
                    if (!(string.IsNullOrEmpty(e.Arguments) && MainPageViewModel.AppInstances.Count > 0))
                    {
                        await MainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), e.Arguments);
                    }
                }

                // Ensure the current window is active
                Window.Current.Activate();
                Window.Current.CoreWindow.Activated += CoreWindow_Activated;
            }
            else
            {
                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, new SuppressNavigationTransitionInfo());
                }
                else
                {
                    if (!(string.IsNullOrEmpty(e.Arguments) && MainPageViewModel.AppInstances.Count > 0))
                    {
                        await MainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), e.Arguments);
                    }
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Uses Composition API to get the UIElement and sets an ExpressionAnimation
        /// The ExpressionAnimation uses the height of the UIElement to calculate an opacity value
        /// for the Header as it is scrolling off-screen. The opacity reaches 0 when the Header
        /// is entirely scrolled off.
        /// </summary>
        private void AssignAnimation()
        {
            StopAnimation();

            // Confirm that Windows.UI.Xaml.Hosting.ElementCompositionPreview is available (Windows 10 10586 or later).
            if (!ApiInformation.IsMethodPresent("Windows.UI.Xaml.Hosting.ElementCompositionPreview", nameof(ElementCompositionPreview.GetScrollViewerManipulationPropertySet)))
            {
                return;
            }

            if (AssociatedObject == null)
            {
                return;
            }

            if (_scrollViewer == null)
            {
                _scrollViewer = AssociatedObject as ScrollViewer ?? AssociatedObject.FindDescendant <ScrollViewer>();
            }

            if (_scrollViewer == null)
            {
                return;
            }

            if (_scrollProperties == null)
            {
                _scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(_scrollViewer);
            }

            if (_scrollProperties == null)
            {
                return;
            }

            // Implicit operation: Find the Header object of the control if it uses ListViewBase
            if (HeaderElement == null)
            {
                var listElement = AssociatedObject as ListViewBase ?? AssociatedObject.FindDescendant <ListViewBase>();

                if (listElement != null)
                {
                    HeaderElement = listElement.Header as UIElement;
                }
            }

            if (HeaderElement == null)
            {
                return;
            }

            if (!(HeaderElement is FrameworkElement))
            {
                return;
            }

            if (_headerVisual == null)
            {
                _headerVisual = ElementCompositionPreview.GetElementVisual((UIElement)HeaderElement);
            }

            if (_headerVisual == null)
            {
                return;
            }

            (HeaderElement as FrameworkElement).SizeChanged -= ScrollHeader_SizeChanged;
            (HeaderElement as FrameworkElement).SizeChanged += ScrollHeader_SizeChanged;

            var compositor = _scrollProperties.Compositor;

            if (_animationProperties == null)
            {
                _animationProperties = compositor.CreatePropertySet();
                _animationProperties.InsertScalar("OffsetY", 0.0f);
            }

            _previousVerticalScrollOffset = _scrollViewer.VerticalOffset;

            ExpressionAnimation expressionAnimation = compositor.CreateExpressionAnimation($"max(animationProperties.OffsetY - ScrollingProperties.Translation.Y, 0)");

            expressionAnimation.SetReferenceParameter("ScrollingProperties", _scrollProperties);
            expressionAnimation.SetReferenceParameter("animationProperties", _animationProperties);

            _headerVisual.StartAnimation("Offset.Y", expressionAnimation);
        }