public static Task SmoothSetAsync(this FrameworkElement @this, DependencyProperty dp, double targetvalue,
            TimeSpan iDuration, CancellationToken iCancellationToken)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            DoubleAnimation anim = new DoubleAnimation(targetvalue, new Duration(iDuration));
            PropertyPath p = new PropertyPath("(0)", dp);
            Storyboard.SetTargetProperty(anim, p);
            Storyboard sb = new Storyboard();
            sb.Children.Add(anim);
            EventHandler handler = null;
            handler = delegate
            {
                sb.Completed -= handler;
                sb.Remove(@this);
                @this.SetValue(dp, targetvalue);
                tcs.TrySetResult(null);
            };
            sb.Completed += handler;
            sb.Begin(@this, true);

            iCancellationToken.Register(() =>
            {
                double v = (double)@this.GetValue(dp);  
                sb.Stop(); 
                sb.Remove(@this); 
                @this.SetValue(dp, v);
                tcs.TrySetCanceled();
            });

            return tcs.Task;
        }
 // Token: 0x06001699 RID: 5785 RVA: 0x000706F6 File Offset: 0x0006E8F6
 internal override void Invoke(FrameworkElement containingFE, FrameworkContentElement containingFCE, Storyboard storyboard)
 {
     if (containingFE != null)
     {
         storyboard.Remove(containingFE);
         return;
     }
     storyboard.Remove(containingFCE);
 }
Example #3
0
        /// <summary>
        ///     Called when it's time to execute this storyboard action
        /// </summary>
        internal override void Invoke(FrameworkElement containingFE, FrameworkContentElement containingFCE, Storyboard storyboard)
        {
            Debug.Assert(containingFE != null || containingFCE != null,
                         "Caller of internal function failed to verify that we have a FE or FCE - we have neither.");

            if (containingFE != null)
            {
                storyboard.Remove(containingFE);
            }
            else
            {
                storyboard.Remove(containingFCE);
            }
        }
Example #4
0
    /// <summary>
    ///     Called when it's time to execute this storyboard action
    /// </summary> 
    internal override void Invoke( FrameworkElement containingFE, FrameworkContentElement containingFCE, Storyboard storyboard )
    { 
        Debug.Assert( containingFE != null || containingFCE != null, 
            "Caller of internal function failed to verify that we have a FE or FCE - we have neither." );
 
        if( containingFE != null )
        {
            storyboard.Remove(containingFE);
        } 
        else
        { 
            storyboard.Remove(containingFCE); 
        }
    } 
 public StepFiveControl(MainWindow window)
 {
     InitializeComponent();
     countdownControl.Initial(200, 170, 200,60);
     countdownControl.CountdownCompleted += () => {
         countdownControl.Visibility = Visibility.Collapsed;
         PlaySound();
     };
     sb = Resources["sb1"] as Storyboard;
     media.MediaEnded += OnSceneOver;
     media.MediaFailed += (sender, args) =>
     {
         _isMediaPlaying = false;
     };
     media.MediaOpened += (s, e) =>
     {
         //Panel.SetZIndex(media, 999);
         //border.Visibility = Visibility.Collapsed;
         //media.Opacity = 1;
         sb.Begin(media, true);
     };
     sb.Completed += (s, e) =>
     {
         sb.Remove(media);
         media.Opacity = 1;
     };
     Window = window;
 }
Example #6
0
 public void Remove(FrameworkElement target, INameScope nameScope, object layerOwner)
 {
     if (Storyboard != null)
     {
         Storyboard.Remove(target, nameScope, layerOwner);
     }
 }
 public void Show()
 {
     XGrid.OpacityMask = this.Resources["OpenBrush"] as LinearGradientBrush;
     _stb = this.Resources["OpenBoard"] as Storyboard;
     _stb.Completed += (s, e) =>
     {
         if (_stb == null)
             return;
         _stb.Remove();
         _stb = null;
         XGrid.OpacityMask = null;
         _mainWindow.StateSwitch(State.Setting);
     };
     _stb.Begin();
 }
 public void Hide()
 {
     XGrid.OpacityMask = this.Resources["CloseBrush"] as LinearGradientBrush;
     _stb = this.Resources["CloseBoard"] as Storyboard;
     _stb.Completed += (s, e) =>
     {
         if (_stb == null)
             return;
         _stb.Remove();
         _stb = null;
         XGrid.OpacityMask = this.Resources["OpenBrush"] as LinearGradientBrush;
         SettingInstant.Save();
         _mainWindow.StateSwitch(State.Normal);
     };
     _stb.Begin();
 }
 public static void SmoothSet(this FrameworkElement @this, DependencyProperty dp, double targetvalue, TimeSpan iDuration)
 {
     DoubleAnimation anim = new DoubleAnimation(targetvalue, new Duration(iDuration));
     PropertyPath p = new PropertyPath("(0)", dp);
     Storyboard.SetTargetProperty(anim, p);
     Storyboard sb = new Storyboard();
     sb.Children.Add(anim);
     EventHandler handler = null;
     handler = delegate
     {
         sb.Completed -= handler;
         sb.Remove(@this);
         @this.SetValue(dp, targetvalue);
     };
     sb.Completed += handler;
     sb.Begin(@this, true);
 }
 public StepOneControl(MainWindow window)
 {
     InitializeComponent();
     sb = Resources["sb1"] as Storyboard;
     timer.Interval = new TimeSpan(0, 0, Appconfig.AutoPlayInterval);
     timer.Tick += timer_Tick;
     timer.Start();
     media.MediaEnded += OnSceneOver;
     media.MediaFailed += (sender, args) =>
     {
         _isMediaPlaying = false;
     };
     media.MediaOpened += (s, e) =>
     {
         //Panel.SetZIndex(media, 999);
         //border.Visibility = Visibility.Collapsed;
         //media.Opacity = 1;
         sb.Begin(media, true);
     };
     sb.Completed += (s, e) =>
     {
         sb.Remove(media);
         media.Opacity = 1;
     };
     Window = window;
     ElementAnimControl.LeftCount = new int[7] { 4, 3, 3, 3, 3, 3, 3 };
     ElementAnimControl.RightCount = new int[7] { 3, 3, 3, 3, 3, 3, 4 };
     ElementAnimControl.Initial(Appconfig.TiltImagesDirName);
     ElementAnimControl.PlayRightNextPage += i =>
     {
         HandOption.Instance.Page1State = HandDirection.R;
         window.Pause();
         _isMediaPlaying = true;
         ShowMedia();
     };
     ElementAnimControl.PlayLeftNextPage += i =>
     {
         HandOption.Instance.Page1State = HandDirection.L;
         window.Pause();
         _isMediaPlaying = true;
         ShowMedia();
     };
 }
Example #11
0
        public void StoryboardBasicTest()
        {
            DoubleAnimation widthAnimation = new DoubleAnimation { To = 100 };
            DoubleAnimation heightAnimation = new DoubleAnimation { From = 100 };

            Storyboard storyboard = new Storyboard();
            storyboard.Children.Add(widthAnimation);
            storyboard.Children.Add(heightAnimation);

            FrameworkElement element = new FrameworkElement { Width = 0, Height = 0 };

            Storyboard.SetTarget(widthAnimation, element);
            Storyboard.SetTargetProperty(widthAnimation, PropertyPath.FromDependencyProperty(FrameworkElement.WidthProperty));

            Storyboard.SetTarget(heightAnimation, element);
            Storyboard.SetTargetProperty(heightAnimation, PropertyPath.FromDependencyProperty(FrameworkElement.HeightProperty));

            TestRootClock rootClock = new TestRootClock();
            element.SetAnimatableRootClock(new AnimatableRootClock(rootClock, true));
            storyboard.Begin(element);

            rootClock.Tick(TimeSpan.FromSeconds(0));
            Assert.AreEqual(0, element.Width);
            Assert.AreEqual(100, element.Height);

            rootClock.Tick(TimeSpan.FromSeconds(0.1));
            Assert.AreEqual(10, element.Width);
            Assert.AreEqual(90, element.Height);

            rootClock.Tick(TimeSpan.FromSeconds(1));
            Assert.AreEqual(100, element.Width);
            Assert.AreEqual(0, element.Height);

            storyboard.Seek(element, TimeSpan.FromSeconds(0.5));
            rootClock.Tick(TimeSpan.FromSeconds(1));
            Assert.AreEqual(50, element.Width);
            Assert.AreEqual(50, element.Height);

            storyboard.Remove(element);
            rootClock.Tick(TimeSpan.FromSeconds(1));
            Assert.AreEqual(0, element.Width);
            Assert.AreEqual(0, element.Height);
        }
Example #12
0
        /*******************************************************************************************
         * btn_newGame_Click
         * - Função iniciar novo jogo
        *******************************************************************************************/
        private void btn_newGame_Click(object sender, RoutedEventArgs e)
        {
            storyboard = this.TryFindResource("luckyNum_anim") as Storyboard;

            storyboard.Remove(luckyRouletteNum);
            /*
            foreach (Image chip in winningChips_list)
            {
                storyboard.Stop(chip);
            }

            storyboard.SkipToFill();
            */

            clearBets();
            btn_newGame.Visibility = Visibility.Hidden;
            bola.Visibility = Visibility.Hidden;
            openTable.IsEnabled = true;
            chipGrid.IsEnabled = true;
            lbl_hint.Content = "Selecione a ficha para apostar!";
        }
 public void LoadRightImage()
 {
     Image2.Source = new BitmapImage(new Uri(_imagePathList[_current - 1], UriKind.RelativeOrAbsolute));
     Image1.OpacityMask = this.Resources["CloseBrush"] as LinearGradientBrush;
     _stb = this.Resources["CloseBoard"] as Storyboard;
     _stb.Completed += (s, e) =>
     {
         if (_stb == null)
             return;
         _stb.Remove();
         _stb = null;
         Image1.Source = Image2.Source;
         Image1.OpacityMask = null;
         _current--;
         _mainWindow.StateSwitch(State.Normal);
         _mainWindow.CheckButton();
     };
     _stb.Begin();
 }
Example #14
0
        void PanelLayoutUpdated(object sender, EventArgs e)
        {
            // At this point, the panel has moved the children to the new locations, but hasn't

              // been rendered

              foreach (UIElement child in _panel.Children)
              {

              // Figure out where child actually is right now. This is a combination of where the

              // panel put it and any render transform currently applied

            //  Point currentPosition = child.TransformToAncestor(_panel).Transform(new Point());
             Vector vectorNow =  VisualTreeHelper.GetOffset(child);
             Point currentPosition = new Point(vectorNow.X, vectorNow.Y);

              // See what transform is being applied

              Transform currentTransform = child.RenderTransform;

              // Compute where the panel actually arranged it to

              Point arrangePosition = currentPosition;

              // If we had previously stored an arrange position, see if it has moved

              if (child.GetValue(PreviousRectProperty) != DependencyProperty.UnsetValue)
              {
                  var savedRect = PanelAnimation.GetPreviousRect(child);

                  Point savedArrangePosition = savedRect.TopLeft;

                  // If the arrange position hasn't changed, then we've already set up animations, etc

                  // and don't need to do anything

                  if (!AreReallyClose(savedArrangePosition, arrangePosition))
                  {

                      // If we apply the current transform to the saved arrange position, we'll see where

                      // it was last rendered

                     // Point lastRenderPosition = currentTransform.Transform(savedArrangePosition);

                      Point lastRenderPosition = savedArrangePosition;

                      // Transform the child from the new location back to the old position

                      TranslateTransform newTransform = new TranslateTransform();

                      child.RenderTransform = newTransform;

                      Storyboard transition = new Storyboard();
                      var xAnimation = MakeAnimation(lastRenderPosition.X - arrangePosition.X);
                      var yAnimation = MakeAnimation(lastRenderPosition.Y - arrangePosition.Y);

                      Storyboard.SetTarget(xAnimation, child);
                      Storyboard.SetTargetProperty(xAnimation, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
                     // Storyboard.SetTarget(child, xAnimation);

                      Storyboard.SetTarget(yAnimation, child);
                      Storyboard.SetTargetProperty(yAnimation, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.Y)"));
                    //  Storyboard.SetTarget( yAnimation);
                      transition.Children.Add(xAnimation);
                      transition.Children.Add(yAnimation);
                      transition.Duration = TimeSpan.FromMilliseconds(1000);
                      transition.Completed += (s, ev) => {
                       // transition.be
                          transition.Remove();
                      };
                      transition.Begin((FrameworkElement)child,true);

                      //transition.Children.Add()

                      // Decay the transformation with an animation

                    //  newTransform.BeginAnimation(TranslateTransform.XProperty, MakeAnimation(lastRenderPosition.X - arrangePosition.X));

            //                      newTransform.BeginAnimation(TranslateTransform.YProperty, MakeAnimation(lastRenderPosition.Y - arrangePosition.Y));

                  }

              }

              // Save off the previous arrange position

            //  child.SetValue(SavedArrangePositionProperty, arrangePosition);
              PanelAnimation.SetPreviousRect(child, new Rect(arrangePosition, child.DesiredSize));

              }
        }
        private bool TrySetVerticalOffset(double offset)
        {
            if (_IsScrolling)
                return false;

            _IsScrolling = true;

            double oldoff = VerticalOffset;
            double newoffset = CalculateVerticalOffset(offset);

            double delta = Math.Abs(oldoff - newoffset);

            if (delta == 0)
            {
                _IsScrolling = false;
                return false;
            }

            if (delta > ViewportHeight)
            {
                VerticalOffset = newoffset;
                if (ScrollOwner != null)
                    ScrollOwner.InvalidateScrollInfo();
 
                _IsScrolling = false;
                _ScrollingOffset = 0;
                InvalidateMeasure();
               
            }
            else
            {
                double deltatrans =  (oldoff - newoffset) * ItemHeight;
                DoubleAnimation anim = new DoubleAnimation(deltatrans, new Duration(TimeToTransition));
                PropertyPath p = new PropertyPath("(0).(1)", RenderTransformProperty, TranslateTransform.YProperty);
                Storyboard.SetTargetProperty(anim, p);
                Storyboard sb = new Storyboard();
                sb.Children.Add(anim);
                EventHandler handler = null;
                handler = delegate
                {
                    sb.Completed -= handler;
                    sb.Remove(this);
                    _transform.Y = deltatrans;
                    VerticalOffset = newoffset;

                    _IsScrolling = false;
                    _ScrollingOffset = 0;

                    InvalidateMeasure();
                    //_transform.X = 0;

                    if (ScrollOwner != null)
                        ScrollOwner.InvalidateScrollInfo();
                };
                sb.Completed += handler;
                _IsScrolling = true;

                if (oldoff - newoffset > 0)
                    _ScrollingOffset = (int)(newoffset - oldoff);

                VerticalOffset = newoffset;
                InvalidateMeasure();

                Action Ba = () => sb.Begin(this, true);
                this.Dispatcher.BeginInvoke(Ba, DispatcherPriority.Input);
            }
            return true;
        }
Example #16
0
        private void FlyingGet(List<Card.Ruban> rubans,
            double x1, double y1, double x2, double y2, bool fade)
        {
            //<Canvas x:Name="cardLock" Canvas.Left="80" Canvas.Top="90"
            // Width="450" Height="125" Background="LightCoral"/>
            Canvas flyingBody = new Canvas() { Width = 450, Height = 125 };
            //flyingBody.Background = new SolidColorBrush(Colors.LightCoral);
            Canvas.SetLeft(flyingBody, x1);
            Canvas.SetTop(flyingBody, y1);
            flyingBody.Visibility = Visibility.Visible;
            // Clear Tux
            int sz = rubans.Count;
            for (int i = 0; i < sz; ++i)
            {
                rubans[i].Index = i;
                Canvas.SetLeft(rubans[i], i * 30);
                flyingBody.Children.Add(rubans[i]);
            }
            lock (aniCanvas.Children)
            {
                aniCanvas.Children.Add(flyingBody);
            }
            DoubleAnimation aniAppr = new DoubleAnimation() { From = 0, To = 1, Duration = SURA };
            Storyboard.SetTarget(aniAppr, flyingBody);
            Storyboard.SetTargetProperty(aniAppr, new PropertyPath(UIElement.OpacityProperty));
            aniAppr.BeginTime = TimeSpan.FromSeconds(0);

            DoubleAnimation aniX = new DoubleAnimation() { From = x1, To = x2, Duration = DURA };
            Storyboard.SetTarget(aniX, flyingBody);
            Storyboard.SetTargetProperty(aniX, new PropertyPath(Canvas.LeftProperty));
            aniX.BeginTime = SURA;

            DoubleAnimation aniY = new DoubleAnimation() { From = y1, To = y2, Duration = DURA };
            Storyboard.SetTarget(aniY, flyingBody);
            Storyboard.SetTargetProperty(aniY, new PropertyPath(Canvas.TopProperty));
            aniY.BeginTime = SURA;

            Storyboard sb = new Storyboard();
            sb.Children.Add(aniAppr);
            sb.Children.Add(aniX);
            sb.Children.Add(aniY);

            if (fade)
            {
                DoubleAnimation aniFade = new DoubleAnimation() { From = 1, To = 0, Duration = SURA };
                Storyboard.SetTarget(aniFade, flyingBody);
                Storyboard.SetTargetProperty(aniFade, new PropertyPath(UIElement.OpacityProperty));
                aniFade.BeginTime = SURA + DURA;
                sb.Children.Add(aniFade);
            }

            sb.Begin();
            new Thread(delegate()
            {
                if (fade)
                    Thread.Sleep(SURA + DURA + SURA);
                else
                    Thread.Sleep(SURA + DURA);
                aniCanvas.Dispatcher.BeginInvoke((Action)(() =>
                {
                    lock (aniCanvas.Children)
                    {
                        aniCanvas.Children.Remove(flyingBody);
                    }
                    sb.Remove();
                }));
            }).Start();
        }
Example #17
0
        private void FlyingShow(List<Card.Ruban> rubans, double x, double y, bool isLong)
        {
            Canvas flyingBody = new Canvas() { Width = 450, Height = 125 };
            Canvas.SetLeft(flyingBody, x);
            Canvas.SetTop(flyingBody, y);
            flyingBody.Visibility = Visibility.Visible;
            // Clear Tux
            int sz = rubans.Count;
            for (int i = 0; i < sz; ++i)
            {
                rubans[i].Index = i;
                Canvas.SetLeft(rubans[i], i * 30);
                flyingBody.Children.Add(rubans[i]);
            }
            lock (aniCanvas.Children)
            {
                aniCanvas.Children.Add(flyingBody);
            }
            TimeSpan holdDura = isLong ? LDURA : DURA;
            DoubleAnimation aniAppr = new DoubleAnimation() { From = 0, To = 1, Duration = SURA };
            Storyboard.SetTarget(aniAppr, flyingBody);
            Storyboard.SetTargetProperty(aniAppr, new PropertyPath(UIElement.OpacityProperty));
            aniAppr.BeginTime = TimeSpan.FromSeconds(0);

            DoubleAnimation aniFade = new DoubleAnimation() { From = 1, To = 0, Duration = SURA };
            Storyboard.SetTarget(aniFade, flyingBody);
            Storyboard.SetTargetProperty(aniFade, new PropertyPath(UIElement.OpacityProperty));
            aniFade.BeginTime = SURA + holdDura;

            Storyboard sb = new Storyboard();
            sb.Children.Add(aniAppr);
            sb.Children.Add(aniFade);

            sb.Begin();
            new Thread(delegate()
            {
                Thread.Sleep(SURA + holdDura + SURA);
                aniCanvas.Dispatcher.BeginInvoke((Action)(() =>
                {
                    lock (aniCanvas.Children)
                    {
                        aniCanvas.Children.Remove(flyingBody);
                    }
                    sb.Remove();
                }));
            }).Start();
        }
        private void SetHorizontalOffset(double offset, bool DoScroll)
        {
            if (_IsScrolling)
                return;

            _IsScrolling = true;

            double old = HorizontalOffset;
            offset = Normalizeoffset(offset);
            double offsetx = -offset * CollPerView * SpaceHeigthX;
            double delta = old - offset;

            if ((Math.Abs(delta) > 1) || !DoScroll)
            {
                _transform.X = offsetx;
                HorizontalOffset = offset;
                if (ScrollOwner != null)
                    ScrollOwner.InvalidateScrollInfo();
  
                _IsScrolling = false;
                InvalidateMeasure(); //neededd
              
            }
            else
            {
                DoubleAnimation anim = new DoubleAnimation(offsetx, new Duration(TimeSpan.FromSeconds(0.3)));
                anim.AccelerationRatio = 0.2;
                anim.DecelerationRatio = 0.2;
                PropertyPath p = new PropertyPath("(0).(1)", RenderTransformProperty, TranslateTransform.XProperty);
                Storyboard.SetTargetProperty(anim, p);
                Storyboard sb = new Storyboard();
                sb.Children.Add(anim);
                EventHandler handler = null;
                handler = delegate
                {
                    sb.Completed -= handler;
                    sb.Remove(this);
                    _transform.X = offsetx;
                    _IsScrolling = false;
                    _ScrollingOffset = 0;
                    HorizontalOffset = offset;
                    InvalidateMeasure();

                    if (ScrollOwner != null)
                        ScrollOwner.InvalidateScrollInfo();
                };
                sb.Completed += handler;

                if (delta < 0)
                    _ScrollingOffset = (int)(delta);

                HorizontalOffset = offset;
                InvalidateMeasure();

                Action Ba = () => sb.Begin(this, true);
                this.Dispatcher.BeginInvoke(Ba, DispatcherPriority.Input);
            }


        }
Example #19
0
        private void FlyingUp(ContentControl uc, double x1, double y1, double x2, double y2)
        {
            //<Canvas x:Name="cardLock" Canvas.Left="80" Canvas.Top="90"
            // Width="450" Height="125" Background="LightCoral"/>
            Canvas flyingBody = new Canvas() { Width = 450, Height = 125 };
            //flyingBody.Background = new SolidColorBrush(Colors.LightCoral);
            Canvas.SetLeft(flyingBody, x1);
            Canvas.SetTop(flyingBody, y1);
            flyingBody.Visibility = Visibility.Visible;
            Canvas.SetLeft(uc, 0);
            flyingBody.Children.Add(uc);
            lock (aniCanvas.Children)
            {
                aniCanvas.Children.Add(flyingBody);
            }
            DoubleAnimation aniAppr = new DoubleAnimation() { From = 0, To = 1, Duration = LSURA };
            Storyboard.SetTarget(aniAppr, flyingBody);
            Storyboard.SetTargetProperty(aniAppr, new PropertyPath(UIElement.OpacityProperty));
            aniAppr.BeginTime = TimeSpan.FromSeconds(0);

            DoubleAnimation aniX = new DoubleAnimation() { From = x1, To = x2, Duration = DURA };
            Storyboard.SetTarget(aniX, flyingBody);
            Storyboard.SetTargetProperty(aniX, new PropertyPath(Canvas.LeftProperty));
            aniX.BeginTime = LSURA;

            DoubleAnimation aniY = new DoubleAnimation() { From = y1, To = y2, Duration = DURA };
            Storyboard.SetTarget(aniY, flyingBody);
            Storyboard.SetTargetProperty(aniY, new PropertyPath(Canvas.TopProperty));
            aniY.BeginTime = LSURA;

            Storyboard sb = new Storyboard();
            sb.Children.Add(aniAppr);
            sb.Children.Add(aniX);
            sb.Children.Add(aniY);

            DoubleAnimation aniFade = new DoubleAnimation() { From = 1, To = 0, Duration = SURA };
            Storyboard.SetTarget(aniFade, flyingBody);
            Storyboard.SetTargetProperty(aniFade, new PropertyPath(UIElement.OpacityProperty));
            aniFade.BeginTime = LSURA + DURA;
            sb.Children.Add(aniFade);

            sb.Begin();
            new Thread(delegate()
            {
                Thread.Sleep(LSURA + DURA + SURA);
                aniCanvas.Dispatcher.BeginInvoke((Action)(() =>
                {
                    lock (aniCanvas.Children)
                    {
                        aniCanvas.Children.Remove(flyingBody);
                    }
                    sb.Remove();
                }));
            }).Start();
        }
        private void AnimateToDestination(bool? Destination, double SpeedRation = 1)
        {
            if ((_Init == false) || (ActualWidth == 0))
                return;

            _OffBorder.Visibility = Visibility.Visible;
            _OnBorder.Visibility = Visibility.Visible;

            double Dest = DoubleTransFromChecked(Destination);
            double dist = Math.Abs(_Transf.X - Dest);



            if (dist != 0)
            {
                this._Im.MouseLeftButtonUp -= _Im_MouseLeftButtonUp;
                Storyboard sb = new Storyboard();

                DoubleAnimation db = new DoubleAnimation();

                db.To = Dest;

                db.Duration = TimeSpan.FromMilliseconds(dist * 100 / (SpeedRation * this.AnimationSpeed));

                Storyboard.SetTarget(db, this._Wholle);
                Storyboard.SetTargetProperty(db, new PropertyPath("RenderTransform.X"));

                sb.Children.Add(db);
                EventHandler handler = null;
                handler = delegate
                {
                    sb.Completed -= handler;
                    sb.Remove();
                    _Transf.X = Dest;
                    ChangeCheckFromPos();
                    this._Im.MouseLeftButtonUp += _Im_MouseLeftButtonUp;
                };

                sb.Completed += handler;

                sb.Begin();
            }
            else
            {
                ChangeCheckFromPos();
            }
        }
Example #21
0
        private void Animate()
        {
            currentStoryboard = new Storyboard();
            NextSlideImageView.Opacity = 0;
            NextSlideImageView.Visibility = Visibility.Visible;
            NextSlideImageView.Source = slides[nextSlideIndex].SlideImage;

            var opacityAnimation1 = new DoubleAnimation {
                From = 0,
                To = 1,
                Duration = TimeSpan.FromSeconds(0.5)
            };

            var opacityAnimation2 = new DoubleAnimation {
                From = 1,
                To = 0,
                Duration = TimeSpan.FromSeconds(0.5)
            };

            Storyboard.SetTarget(opacityAnimation1, NextSlideImageView);
            Storyboard.SetTarget(opacityAnimation2, SlideImageView);
            Storyboard.SetTargetProperty(opacityAnimation1, new PropertyPath(OpacityProperty));
            Storyboard.SetTargetProperty(opacityAnimation2, new PropertyPath(OpacityProperty));

            currentStoryboard.Children.Add(opacityAnimation1);
            currentStoryboard.Children.Add(opacityAnimation2);

            currentStoryboard.Completed += (sender1, eventArgs) => {
                if (nextSlideIndex < 0) return;
                currentSlideIndex = nextSlideIndex;
                SlideImageView.Source = slides[currentSlideIndex].SlideImage;
                nextSlideIndex = -1;
                SlideImageView.Opacity = 1;
                NextSlideImageView.Visibility = Visibility.Hidden;
                currentStoryboard.Remove(this);
                currentStoryboard = null;
            };

            // start animation
            currentStoryboard.Begin(this, true);
        }
Example #22
0
        private void AnimatePause()
        {
            currentStoryboard = new Storyboard();
            NextSlideImageView.Visibility = Visibility.Hidden;

            var opacityAnimation = new DoubleAnimation {
                From = isPaused ? 1 : 0,
                To = isPaused ? 0 : 1,
                Duration = TimeSpan.FromSeconds(0.5)
            };

            Storyboard.SetTarget(opacityAnimation, SlideImageView);
            Storyboard.SetTargetProperty(opacityAnimation, new PropertyPath(OpacityProperty));

            currentStoryboard.Children.Add(opacityAnimation);

            currentStoryboard.Completed += (sender1, eventArgs) => {
                if (currentStoryboard == null) return;
                currentStoryboard.Remove(this);
                currentStoryboard = null;
                SlideImageView.Opacity = isPaused ? 0 : 1;
            };

            // start animation
            currentStoryboard.Begin(this, true);
        }
Example #23
0
		public void AnimateToOffset(double offset)
		{
			Storyboard sb = new Storyboard();
			var anim = new DoubleAnimation(offset, new Duration(TimeSpan.FromSeconds(0.5)));
			Storyboard.SetTarget(anim, this);
			Storyboard.SetTargetProperty(anim, new PropertyPath("NavigationOffset"));

			sb.Children.Add(anim);

			EventHandler handler = null;
			handler = delegate
			          	{
			          		NavigationOffset = offset;
			          		sb.Completed -= handler;
			          		sb.Remove();
			          	};

			sb.Completed += handler;

			sb.Begin();
		}
Example #24
0
        public Agent(string name)
        {
            InitializeComponent();

            this.characterName = name;
            this.cachedBitmapImageDictionary = new Dictionary<string, BitmapImage>();
            this.cachedMotionList = new List<Motion>();
            this.fadeStoryboardDictionary = new Dictionary<Storyboard, Window>();
            this.imageStoryboardDictionary = new Dictionary<Image, Storyboard>();
            this.queue = new System.Collections.Queue();
            this.motionQueue = new Queue<Motion>();
            this.ContextMenu = new ContextMenu();

            MenuItem opacityMenuItem = new MenuItem();
            MenuItem scalingMenuItem = new MenuItem();
            MenuItem refreshMenuItem = new MenuItem();
            MenuItem topmostMenuItem = new MenuItem();
            MenuItem showInTaskbarMenuItem = new MenuItem();
            MenuItem muteMenuItem = new MenuItem();
            MenuItem charactersMenuItem = new MenuItem();
            MenuItem updateMenuItem = new MenuItem();
            MenuItem exitMenuItem = new MenuItem();
            double opacity = 1;
            double scale = 2;

            opacityMenuItem.Header = Properties.Resources.Opacity;

            do
            {
                MenuItem menuItem = new MenuItem();

                menuItem.Header = String.Concat(((int)Math.Floor(opacity * 100)).ToString(System.Globalization.CultureInfo.CurrentCulture), Properties.Resources.Percent);
                menuItem.Tag = opacity;
                menuItem.Click += new RoutedEventHandler(delegate
                {
                    foreach (Window window in Application.Current.Windows)
                    {
                        Agent agent = window as Agent;

                        if (agent != null)
                        {
                            agent.opacity = (double)menuItem.Tag;

                            Storyboard storyboard1 = new Storyboard();
                            DoubleAnimation doubleAnimation1 = new DoubleAnimation(agent.Opacity, agent.opacity, TimeSpan.FromMilliseconds(500));

                            foreach (KeyValuePair<Storyboard, Window> kvp in agent.fadeStoryboardDictionary)
                            {
                                kvp.Key.Stop(kvp.Value);
                            }

                            agent.fadeStoryboardDictionary.Clear();

                            if (agent.Opacity < agent.opacity)
                            {
                                SineEase sineEase = new SineEase();

                                sineEase.EasingMode = EasingMode.EaseOut;
                                doubleAnimation1.EasingFunction = sineEase;
                            }
                            else if (agent.Opacity > agent.opacity)
                            {
                                SineEase sineEase = new SineEase();

                                sineEase.EasingMode = EasingMode.EaseIn;
                                doubleAnimation1.EasingFunction = sineEase;
                            }

                            doubleAnimation1.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                            {
                                if (((Clock)s).CurrentState == ClockState.Filling)
                                {
                                    agent.Opacity = agent.opacity;
                                    storyboard1.Remove(agent);
                                    agent.fadeStoryboardDictionary.Remove(storyboard1);
                                }
                            });

                            storyboard1.Children.Add(doubleAnimation1);

                            Storyboard.SetTargetProperty(doubleAnimation1, new PropertyPath(Window.OpacityProperty));

                            agent.fadeStoryboardDictionary.Add(storyboard1, agent);
                            agent.BeginStoryboard(storyboard1, HandoffBehavior.SnapshotAndReplace, true);

                            if (agent.balloon.Opacity != 1)
                            {
                                Storyboard storyboard2 = new Storyboard();
                                DoubleAnimation doubleAnimation2 = new DoubleAnimation(agent.balloon.Opacity, 1, TimeSpan.FromMilliseconds(500));
                                SineEase sineEase = new SineEase();

                                sineEase.EasingMode = EasingMode.EaseOut;

                                doubleAnimation2.EasingFunction = sineEase;
                                doubleAnimation2.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                                {
                                    if (((Clock)s).CurrentState == ClockState.Filling)
                                    {
                                        agent.balloon.Opacity = 1;
                                        storyboard2.Remove(agent.balloon);
                                        agent.fadeStoryboardDictionary.Remove(storyboard2);
                                    }
                                });

                                storyboard2.Children.Add(doubleAnimation2);

                                Storyboard.SetTargetProperty(doubleAnimation2, new PropertyPath(Window.OpacityProperty));

                                agent.fadeStoryboardDictionary.Add(storyboard2, agent.balloon);
                                agent.balloon.BeginStoryboard(storyboard2, HandoffBehavior.SnapshotAndReplace, true);
                            }
                        }
                    }
                });

                opacityMenuItem.Items.Add(menuItem);
                opacity -= 0.1;
            } while (Math.Floor(opacity * 100) > 0);

            scalingMenuItem.Header = Properties.Resources.Scaling;

            do
            {
                MenuItem menuItem = new MenuItem();

                menuItem.Header = String.Concat(((int)Math.Floor(scale * 100)).ToString(System.Globalization.CultureInfo.CurrentCulture), Properties.Resources.Percent);
                menuItem.Tag = scale;
                menuItem.Click += new RoutedEventHandler(delegate
                {
                    foreach (Window window in Application.Current.Windows)
                    {
                        Agent agent = window as Agent;

                        if (agent != null)
                        {
                            agent.scale = (double)menuItem.Tag;

                            foreach (Character character in from character in Script.Instance.Characters where character.Name.Equals(agent.characterName) select character)
                            {
                                Storyboard storyboard = new Storyboard();
                                DoubleAnimation doubleAnimation1 = new DoubleAnimation(agent.ZoomScaleTransform.ScaleX, agent.scale, TimeSpan.FromMilliseconds(500));
                                DoubleAnimation doubleAnimation2 = new DoubleAnimation(agent.ZoomScaleTransform.ScaleY, agent.scale, TimeSpan.FromMilliseconds(500));
                                DoubleAnimation doubleAnimation3 = new DoubleAnimation(agent.LayoutRoot.Width, character.Size.Width * agent.scale, TimeSpan.FromMilliseconds(500));
                                DoubleAnimation doubleAnimation4 = new DoubleAnimation(agent.LayoutRoot.Height, character.Size.Height * agent.scale, TimeSpan.FromMilliseconds(500));

                                if (agent.scaleStoryboard != null)
                                {
                                    agent.scaleStoryboard.Stop(agent.LayoutRoot);
                                }

                                if (agent.ZoomScaleTransform.ScaleX < agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseOut;
                                    doubleAnimation1.EasingFunction = sineEase;
                                }
                                else if (agent.ZoomScaleTransform.ScaleX > agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseIn;
                                    doubleAnimation1.EasingFunction = sineEase;
                                }

                                if (agent.ZoomScaleTransform.ScaleY < agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseOut;
                                    doubleAnimation2.EasingFunction = sineEase;
                                }
                                else if (agent.ZoomScaleTransform.ScaleY > agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseIn;
                                    doubleAnimation2.EasingFunction = sineEase;
                                }

                                if (agent.LayoutRoot.Width < character.Size.Width * agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseOut;
                                    doubleAnimation3.EasingFunction = sineEase;
                                }
                                else if (agent.LayoutRoot.Width > character.Size.Width * agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseIn;
                                    doubleAnimation3.EasingFunction = sineEase;
                                }

                                if (agent.LayoutRoot.Height < character.Size.Height * agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseOut;
                                    doubleAnimation4.EasingFunction = sineEase;
                                }
                                else if (agent.LayoutRoot.Height > character.Size.Height * agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseIn;
                                    doubleAnimation4.EasingFunction = sineEase;
                                }

                                storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                                {
                                    if (((Clock)s).CurrentState == ClockState.Filling)
                                    {
                                        agent.ZoomScaleTransform.ScaleX = agent.scale;
                                        agent.ZoomScaleTransform.ScaleY = agent.scale;

                                        foreach (Character c in from c in Script.Instance.Characters where c.Name.Equals(agent.characterName) select c)
                                        {
                                            agent.LayoutRoot.Width = c.Size.Width * agent.scale;
                                            agent.LayoutRoot.Height = c.Size.Height * agent.scale;
                                        }

                                        storyboard.Remove(agent.LayoutRoot);
                                        agent.scaleStoryboard = null;
                                    }
                                });
                                storyboard.Children.Add(doubleAnimation1);
                                storyboard.Children.Add(doubleAnimation2);
                                storyboard.Children.Add(doubleAnimation3);
                                storyboard.Children.Add(doubleAnimation4);

                                Storyboard.SetTargetProperty(doubleAnimation1, new PropertyPath("(0).(1).(2)", ContentControl.ContentProperty, Canvas.RenderTransformProperty, ScaleTransform.ScaleXProperty));
                                Storyboard.SetTargetProperty(doubleAnimation2, new PropertyPath("(0).(1).(2)", ContentControl.ContentProperty, Canvas.RenderTransformProperty, ScaleTransform.ScaleYProperty));
                                Storyboard.SetTargetProperty(doubleAnimation3, new PropertyPath(ContentControl.WidthProperty));
                                Storyboard.SetTargetProperty(doubleAnimation4, new PropertyPath(ContentControl.HeightProperty));

                                agent.scaleStoryboard = storyboard;
                                agent.LayoutRoot.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true);
                            }
                        }
                    }
                });

                scalingMenuItem.Items.Add(menuItem);
                scale -= 0.25;
            } while (Math.Floor(scale * 100) > 0);

            refreshMenuItem.Header = Properties.Resources.Refresh;
            refreshMenuItem.Click += new RoutedEventHandler(delegate
            {
                foreach (Window window in Application.Current.Windows)
                {
                    Agent agent = window as Agent;

                    if (agent != null)
                    {
                        agent.Render();
                    }
                }
            });
            topmostMenuItem.Header = Properties.Resources.Topmost;
            topmostMenuItem.IsCheckable = true;
            topmostMenuItem.Click += new RoutedEventHandler(delegate
            {
                foreach (Window window in Application.Current.Windows)
                {
                    if (window is Agent && window == Application.Current.MainWindow)
                    {
                        window.Topmost = topmostMenuItem.IsChecked;
                    }
                }
            });
            showInTaskbarMenuItem.Header = Properties.Resources.ShowInTaskbar;
            showInTaskbarMenuItem.IsCheckable = true;
            showInTaskbarMenuItem.Click += new RoutedEventHandler(delegate
            {
                foreach (Window window in Application.Current.Windows)
                {
                    if (window is Agent)
                    {
                        window.ShowInTaskbar = showInTaskbarMenuItem.IsChecked;
                    }
                }
            });
            muteMenuItem.Header = Properties.Resources.Mute;
            muteMenuItem.IsCheckable = true;
            muteMenuItem.Click += new RoutedEventHandler(delegate
            {
                foreach (Window window in Application.Current.Windows)
                {
                    Agent agent = window as Agent;

                    if (agent != null)
                    {
                        agent.isMute = muteMenuItem.IsChecked;
                    }
                }
            });
            charactersMenuItem.Header = Properties.Resources.Characters;
            updateMenuItem.Header = Properties.Resources.Update;
            updateMenuItem.Click += new RoutedEventHandler(delegate
            {
                Script.Instance.Update(true);
            });
            exitMenuItem.Header = Properties.Resources.Exit;
            exitMenuItem.Click += new RoutedEventHandler(delegate
            {
                if (Script.Instance.Enabled)
                {
                    Script.Instance.Enabled = false;
                }
            });

            this.ContextMenu.Items.Add(opacityMenuItem);
            this.ContextMenu.Items.Add(scalingMenuItem);
            this.ContextMenu.Items.Add(refreshMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(topmostMenuItem);
            this.ContextMenu.Items.Add(showInTaskbarMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(muteMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(charactersMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(updateMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(exitMenuItem);
            this.ContextMenu.Opened += new RoutedEventHandler(delegate
            {
                Agent agent = Application.Current.MainWindow as Agent;

                if (agent != null)
                {
                    foreach (MenuItem menuItem in opacityMenuItem.Items)
                    {
                        menuItem.IsChecked = Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.Opacity * 100);
                    }

                    foreach (MenuItem menuItem in scalingMenuItem.Items)
                    {
                        menuItem.IsChecked = Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.ZoomScaleTransform.ScaleX * 100) && Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.ZoomScaleTransform.ScaleY * 100);
                    }

                    topmostMenuItem.IsChecked = agent.Topmost;
                    showInTaskbarMenuItem.IsChecked = agent.ShowInTaskbar;
                    muteMenuItem.IsChecked = agent.isMute;

                    List<MenuItem> menuItemList = new List<MenuItem>(charactersMenuItem.Items.Cast<MenuItem>());
                    HashSet<string> pathHashSet = new HashSet<string>();
                    LinkedList<KeyValuePair<Character, string>> characterLinkedList = new LinkedList<KeyValuePair<Character, string>>();

                    foreach (Character character in Script.Instance.Characters)
                    {
                        string path = Path.IsPathRooted(character.Script) ? character.Script : Path.GetFullPath(character.Script);

                        if (!pathHashSet.Contains(path))
                        {
                            pathHashSet.Add(path);
                        }

                        characterLinkedList.AddLast(new KeyValuePair<Character, string>(character, path));
                    }

                    List<KeyValuePair<string, string>> keyValuePairList = (from fileName in Directory.EnumerateFiles(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "*", SearchOption.AllDirectories) let extension = Path.GetExtension(fileName) let isZip = extension.Equals(".zip", StringComparison.OrdinalIgnoreCase) where isZip || extension.Equals(".xml", StringComparison.OrdinalIgnoreCase) select new KeyValuePair<bool, string>(isZip, fileName)).Concat(from path in pathHashSet select new KeyValuePair<bool, string>(Path.GetExtension(path).Equals(".zip", StringComparison.OrdinalIgnoreCase), path)).Aggregate<KeyValuePair<bool, string>, List<KeyValuePair<string, string>>>(new List<KeyValuePair<string, string>>(), (list, kvp1) =>
                    {
                        if (!list.Exists(delegate (KeyValuePair<string, string> kvp2)
                        {
                            return kvp2.Value.Equals(kvp1.Value);
                        }))
                        {
                            if (kvp1.Key)
                            {
                                FileStream fs = null;

                                try
                                {
                                    fs = new FileStream(kvp1.Value, FileMode.Open, FileAccess.Read, FileShare.Read);

                                    using (ZipArchive zipArchive = new ZipArchive(fs))
                                    {
                                        fs = null;

                                        foreach (ZipArchiveEntry zipArchiveEntry in from zipArchiveEntry in zipArchive.Entries where zipArchiveEntry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) select zipArchiveEntry)
                                        {
                                            Stream stream = null;

                                            try
                                            {
                                                stream = zipArchiveEntry.Open();

                                                foreach (string attribute in from attribute in ((System.Collections.IEnumerable)XDocument.Load(stream).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select attribute.Value)
                                                {
                                                    list.Add(new KeyValuePair<string, string>(attribute, kvp1.Value));
                                                }
                                            }
                                            catch
                                            {
                                                return list;
                                            }
                                            finally
                                            {
                                                if (stream != null)
                                                {
                                                    stream.Close();
                                                }
                                            }
                                        }
                                    }
                                }
                                finally
                                {
                                    if (fs != null)
                                    {
                                        fs.Close();
                                    }
                                }
                            }
                            else
                            {
                                FileStream fs = null;

                                try
                                {
                                    fs = new FileStream(kvp1.Value, FileMode.Open, FileAccess.Read, FileShare.Read);

                                    foreach (string attribute in from attribute in ((System.Collections.IEnumerable)XDocument.Load(fs).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select attribute.Value)
                                    {
                                        list.Add(new KeyValuePair<string, string>(attribute, kvp1.Value));
                                    }
                                }
                                catch
                                {
                                    return list;
                                }
                                finally
                                {
                                    if (fs != null)
                                    {
                                        fs.Close();
                                    }
                                }
                            }
                        }

                        return list;
                    });

                    charactersMenuItem.Items.Clear();

                    keyValuePairList.Sort(delegate (KeyValuePair<string, string> kvp1, KeyValuePair<string, string> kvp2)
                    {
                        return String.Compare(kvp1.Key, kvp2.Key, StringComparison.CurrentCulture);
                    });
                    keyValuePairList.ForEach(delegate (KeyValuePair<string, string> kvp)
                    {
                        for (LinkedListNode<KeyValuePair<Character, string>> nextLinkedListNode = characterLinkedList.First; nextLinkedListNode != null; nextLinkedListNode = nextLinkedListNode.Next)
                        {
                            if (nextLinkedListNode.Value.Key.Name.Equals(kvp.Key) && nextLinkedListNode.Value.Value.Equals(kvp.Value))
                            {
                                MenuItem selectedMenuItem = menuItemList.Find(delegate (MenuItem menuItem)
                                {
                                    return kvp.Key.Equals(menuItem.Header as string) && kvp.Value.Equals(menuItem.Tag as string) && (menuItem.IsChecked || menuItem.HasItems);
                                });

                                if (selectedMenuItem == null)
                                {
                                    selectedMenuItem = new MenuItem();
                                    selectedMenuItem.Header = kvp.Key;
                                    selectedMenuItem.Tag = kvp.Value;
                                }
                                else
                                {
                                    selectedMenuItem.Items.Clear();
                                    menuItemList.Remove(selectedMenuItem);
                                }

                                charactersMenuItem.Items.Add(selectedMenuItem);

                                List<MenuItem> childMenuItemList = new List<MenuItem>();
                                Dictionary<string, SortedSet<int>> dictionary = new Dictionary<string, SortedSet<int>>();
                                List<string> motionTypeList = new List<string>();

                                this.cachedMotionList.ForEach(delegate (Motion motion)
                                {
                                    if (motion.Type != null)
                                    {
                                        SortedSet<int> sortedSet;

                                        if (dictionary.TryGetValue(motion.Type, out sortedSet))
                                        {
                                            if (!sortedSet.Contains(motion.ZIndex))
                                            {
                                                sortedSet.Add(motion.ZIndex);
                                            }
                                        }
                                        else
                                        {
                                            sortedSet = new SortedSet<int>();
                                            sortedSet.Add(motion.ZIndex);
                                            dictionary.Add(motion.Type, sortedSet);
                                            motionTypeList.Add(motion.Type);
                                        }
                                    }
                                });

                                motionTypeList.Sort(delegate (string s1, string s2)
                                {
                                    return String.Compare(s1, s2, StringComparison.CurrentCulture);
                                });
                                motionTypeList.ForEach(delegate (string type)
                                {
                                    foreach (MenuItem menuItem in selectedMenuItem.Items)
                                    {
                                        if (type.Equals(menuItem.Header as string))
                                        {
                                            if (nextLinkedListNode.Value.Key.HasTypes)
                                            {
                                                menuItem.IsChecked = nextLinkedListNode.Value.Key.Types.Contains(menuItem.Header as string);
                                            }
                                            else
                                            {
                                                menuItem.IsChecked = false;
                                            }

                                            childMenuItemList.Add(menuItem);

                                            return;
                                        }
                                    }

                                    MenuItem childMenuItem = new MenuItem();

                                    childMenuItem.Header = type;
                                    childMenuItem.Tag = nextLinkedListNode.Value.Key.Name;
                                    childMenuItem.Click += new RoutedEventHandler(delegate
                                    {
                                        string tag = childMenuItem.Tag as string;

                                        if (tag != null)
                                        {
                                            foreach (Character c in from c in Script.Instance.Characters where c.Name.Equals(tag) select c)
                                            {
                                                foreach (Window window in Application.Current.Windows)
                                                {
                                                    Agent a = window as Agent;

                                                    if (a != null && c.Name.Equals(a.characterName))
                                                    {
                                                        string header = childMenuItem.Header as string;

                                                        a.Render();

                                                        if (c.Types.Contains(header))
                                                        {
                                                            c.Types.Remove(header);
                                                        }
                                                        else if (header != null)
                                                        {
                                                            SortedSet<int> sortedSet1;

                                                            if (dictionary.TryGetValue(header, out sortedSet1))
                                                            {
                                                                foreach (string s in c.Types.ToArray())
                                                                {
                                                                    SortedSet<int> sortedSet2;

                                                                    if (dictionary.TryGetValue(s, out sortedSet2) && sortedSet1.SequenceEqual(sortedSet2))
                                                                    {
                                                                        c.Types.Remove(s);
                                                                    }
                                                                }
                                                            }

                                                            c.Types.Add(header);
                                                        }

                                                        foreach (Image image in a.Canvas.Children.Cast<Image>())
                                                        {
                                                            Image i = image;
                                                            Motion motion = i.Tag as Motion;

                                                            if (motion != null)
                                                            {
                                                                List<string> typeList = null;
                                                                bool isVisible;

                                                                if (motion.Type == null)
                                                                {
                                                                    typeList = new List<string>();
                                                                    a.cachedMotionList.ForEach(delegate (Motion m)
                                                                    {
                                                                        if (m.ZIndex == motion.ZIndex)
                                                                        {
                                                                            typeList.Add(m.Type);
                                                                        }
                                                                    });
                                                                }

                                                                if (typeList == null)
                                                                {
                                                                    if (c.HasTypes)
                                                                    {
                                                                        typeList = new List<string>();
                                                                        a.cachedMotionList.ForEach(delegate (Motion m)
                                                                        {
                                                                            if (m.ZIndex == motion.ZIndex && c.Types.Contains(m.Type))
                                                                            {
                                                                                typeList.Add(m.Type);
                                                                            }
                                                                        });
                                                                        isVisible = typeList.Count > 0 && typeList.LastIndexOf(motion.Type) == typeList.Count - 1;
                                                                    }
                                                                    else
                                                                    {
                                                                        isVisible = false;
                                                                    }
                                                                }
                                                                else if (c.HasTypes)
                                                                {
                                                                    isVisible = !typeList.Exists(delegate (string t)
                                                                    {
                                                                        return c.Types.Contains(t);
                                                                    });
                                                                }
                                                                else
                                                                {
                                                                    isVisible = true;
                                                                }

                                                                if (isVisible && (i.Visibility != Visibility.Visible || i.OpacityMask != null))
                                                                {
                                                                    LinearGradientBrush linearGradientBrush = i.OpacityMask as LinearGradientBrush;

                                                                    if (linearGradientBrush == null)
                                                                    {
                                                                        GradientStopCollection gradientStopCollection = new GradientStopCollection();

                                                                        gradientStopCollection.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0));
                                                                        gradientStopCollection.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 1));

                                                                        i.OpacityMask = linearGradientBrush = new LinearGradientBrush(gradientStopCollection, new Point(0.5, 0), new Point(0.5, 1));
                                                                    }

                                                                    Storyboard storyboard;
                                                                    ColorAnimation colorAnimation1 = new ColorAnimation(linearGradientBrush.GradientStops[0].Color, Color.FromArgb(Byte.MaxValue, 0, 0, 0), TimeSpan.FromMilliseconds(250));
                                                                    ColorAnimation colorAnimation2 = new ColorAnimation(linearGradientBrush.GradientStops[1].Color, Color.FromArgb(Byte.MaxValue, 0, 0, 0), TimeSpan.FromMilliseconds(250));
                                                                    SineEase sineEase1 = new SineEase();
                                                                    SineEase sineEase2 = new SineEase();

                                                                    if (a.imageStoryboardDictionary.TryGetValue(i, out storyboard))
                                                                    {
                                                                        storyboard.Stop(i);
                                                                        a.imageStoryboardDictionary[i] = storyboard = new Storyboard();
                                                                    }
                                                                    else
                                                                    {
                                                                        storyboard = new Storyboard();
                                                                        a.imageStoryboardDictionary.Add(i, storyboard);
                                                                    }

                                                                    sineEase1.EasingMode = sineEase2.EasingMode = EasingMode.EaseInOut;

                                                                    colorAnimation1.EasingFunction = sineEase1;
                                                                    colorAnimation2.BeginTime = TimeSpan.FromMilliseconds(250);
                                                                    colorAnimation2.EasingFunction = sineEase2;

                                                                    storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                                                                    {
                                                                        if (((Clock)s).CurrentState == ClockState.Filling)
                                                                        {
                                                                            i.OpacityMask = null;
                                                                            a.Render();
                                                                            storyboard.Remove(i);
                                                                            a.imageStoryboardDictionary.Remove(i);
                                                                        }
                                                                    });
                                                                    storyboard.Children.Add(colorAnimation1);
                                                                    storyboard.Children.Add(colorAnimation2);

                                                                    Storyboard.SetTargetProperty(colorAnimation1, new PropertyPath("(0).(1)[0].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty));
                                                                    Storyboard.SetTargetProperty(colorAnimation2, new PropertyPath("(0).(1)[1].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty));

                                                                    i.Visibility = Visibility.Visible;
                                                                    i.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true);
                                                                }
                                                                else if (!isVisible && (i.Visibility == Visibility.Visible || i.OpacityMask != null))
                                                                {
                                                                    LinearGradientBrush linearGradientBrush = i.OpacityMask as LinearGradientBrush;

                                                                    if (linearGradientBrush == null)
                                                                    {
                                                                        GradientStopCollection gradientStopCollection = new GradientStopCollection();

                                                                        gradientStopCollection.Add(new GradientStop(Color.FromArgb(Byte.MaxValue, 0, 0, 0), 0));
                                                                        gradientStopCollection.Add(new GradientStop(Color.FromArgb(Byte.MaxValue, 0, 0, 0), 1));

                                                                        i.OpacityMask = linearGradientBrush = new LinearGradientBrush(gradientStopCollection, new Point(0.5, 0), new Point(0.5, 1));
                                                                    }

                                                                    Storyboard storyboard;
                                                                    ColorAnimation colorAnimation1 = new ColorAnimation(linearGradientBrush.GradientStops[0].Color, Color.FromArgb(0, 0, 0, 0), TimeSpan.FromMilliseconds(250));
                                                                    ColorAnimation colorAnimation2 = new ColorAnimation(linearGradientBrush.GradientStops[1].Color, Color.FromArgb(0, 0, 0, 0), TimeSpan.FromMilliseconds(250));
                                                                    SineEase sineEase1 = new SineEase();
                                                                    SineEase sineEase2 = new SineEase();

                                                                    if (a.imageStoryboardDictionary.TryGetValue(i, out storyboard))
                                                                    {
                                                                        storyboard.Stop(i);
                                                                        a.imageStoryboardDictionary[i] = storyboard = new Storyboard();
                                                                    }
                                                                    else
                                                                    {
                                                                        storyboard = new Storyboard();
                                                                        a.imageStoryboardDictionary.Add(i, storyboard);
                                                                    }

                                                                    sineEase1.EasingMode = sineEase2.EasingMode = EasingMode.EaseInOut;

                                                                    colorAnimation1.EasingFunction = sineEase1;
                                                                    colorAnimation2.BeginTime = TimeSpan.FromMilliseconds(250);
                                                                    colorAnimation2.EasingFunction = sineEase2;

                                                                    storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                                                                    {
                                                                        if (((Clock)s).CurrentState == ClockState.Filling)
                                                                        {
                                                                            i.OpacityMask = null;
                                                                            a.Render();
                                                                            storyboard.Remove(i);
                                                                            a.imageStoryboardDictionary.Remove(i);
                                                                        }
                                                                    });
                                                                    storyboard.Children.Add(colorAnimation1);
                                                                    storyboard.Children.Add(colorAnimation2);

                                                                    Storyboard.SetTargetProperty(colorAnimation1, new PropertyPath("(0).(1)[0].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty));
                                                                    Storyboard.SetTargetProperty(colorAnimation2, new PropertyPath("(0).(1)[1].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty));

                                                                    i.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    });

                                    if (nextLinkedListNode.Value.Key.HasTypes)
                                    {
                                        childMenuItem.IsChecked = nextLinkedListNode.Value.Key.Types.Contains(childMenuItem.Header as string);
                                    }
                                    else
                                    {
                                        childMenuItem.IsChecked = false;
                                    }

                                    childMenuItemList.Add(childMenuItem);
                                });

                                selectedMenuItem.Items.Clear();

                                if (childMenuItemList.Count > 0)
                                {
                                    selectedMenuItem.IsChecked = false;
                                    childMenuItemList.ForEach(delegate (MenuItem mi)
                                    {
                                        selectedMenuItem.Items.Add(mi);
                                    });
                                }
                                else
                                {
                                    selectedMenuItem.IsChecked = true;
                                }

                                characterLinkedList.Remove(nextLinkedListNode);

                                return;
                            }
                        }

                        MenuItem unselectedMenuItem = menuItemList.Find(delegate (MenuItem menuItem)
                        {
                            return kvp.Key.Equals(menuItem.Header as string) && kvp.Value.Equals(menuItem.Tag as string) && !menuItem.IsChecked && !menuItem.HasItems;
                        });

                        if (unselectedMenuItem == null)
                        {
                            unselectedMenuItem = new MenuItem();
                            unselectedMenuItem.Header = kvp.Key;
                            unselectedMenuItem.Tag = kvp.Value;
                            unselectedMenuItem.Click += new RoutedEventHandler(delegate
                            {
                                string tag = unselectedMenuItem.Tag as string;

                                if (tag != null)
                                {
                                    List<Character> characterList = new List<Character>();

                                    if (Path.GetExtension(tag).Equals(".zip", StringComparison.OrdinalIgnoreCase))
                                    {
                                        FileStream fs = null;

                                        try
                                        {
                                            fs = new FileStream(tag, FileMode.Open, FileAccess.Read, FileShare.Read);

                                            using (ZipArchive zipArchive = new ZipArchive(fs))
                                            {
                                                fs = null;

                                                StringBuilder stringBuilder = new StringBuilder(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));

                                                if (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).LastIndexOf(Path.DirectorySeparatorChar) != Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).Length - 1)
                                                {
                                                    stringBuilder.Append(Path.DirectorySeparatorChar);
                                                }

                                                string path = tag.StartsWith(stringBuilder.ToString(), StringComparison.Ordinal) ? tag.Remove(0, stringBuilder.Length) : tag;

                                                foreach (ZipArchiveEntry zipArchiveEntry in from zipArchiveEntry in zipArchive.Entries where zipArchiveEntry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) select zipArchiveEntry)
                                                {
                                                    Stream stream = null;

                                                    try
                                                    {
                                                        stream = zipArchiveEntry.Open();

                                                        foreach (string a in from a in ((System.Collections.IEnumerable)XDocument.Load(stream).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select a.Value)
                                                        {
                                                            Character character = new Character();

                                                            character.Name = a;
                                                            character.Script = path;

                                                            characterList.Add(character);
                                                        }
                                                    }
                                                    catch
                                                    {
                                                        return;
                                                    }
                                                    finally
                                                    {
                                                        if (stream != null)
                                                        {
                                                            stream.Close();
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        finally
                                        {
                                            if (fs != null)
                                            {
                                                fs.Close();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        FileStream fs = null;

                                        try
                                        {
                                            fs = new FileStream(tag, FileMode.Open, FileAccess.Read, FileShare.Read);

                                            StringBuilder stringBuilder = new StringBuilder(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));

                                            if (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).LastIndexOf(Path.DirectorySeparatorChar) != Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).Length - 1)
                                            {
                                                stringBuilder.Append(Path.DirectorySeparatorChar);
                                            }

                                            string path = tag.StartsWith(stringBuilder.ToString(), StringComparison.Ordinal) ? tag.Remove(0, stringBuilder.Length) : tag;

                                            foreach (string a in from a in ((System.Collections.IEnumerable)XDocument.Load(fs).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select a.Value)
                                            {
                                                Character character = new Character();

                                                character.Name = a;
                                                character.Script = path;

                                                characterList.Add(character);
                                            }
                                        }
                                        catch
                                        {
                                            return;
                                        }
                                        finally
                                        {
                                            if (fs != null)
                                            {
                                                fs.Close();
                                            }
                                        }
                                    }

                                    if (characterList.Count > 0)
                                    {
                                        Switch(characterList);
                                    }
                                }
                            });
                        }
                        else
                        {
                            menuItemList.Remove(unselectedMenuItem);
                        }

                        charactersMenuItem.Items.Add(unselectedMenuItem);
                    });
                }
            });

            if (this == Application.Current.MainWindow)
            {
                System.Configuration.Configuration config = null;
                string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                if (Directory.Exists(directory))
                {
                    string fileName = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                    foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config") where fileName.Equals(Path.GetFileNameWithoutExtension(s)) select s)
                    {
                        System.Configuration.ExeConfigurationFileMap exeConfigurationFileMap = new System.Configuration.ExeConfigurationFileMap();

                        exeConfigurationFileMap.ExeConfigFilename = s;
                        config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, System.Configuration.ConfigurationUserLevel.None);
                    }
                }

                if (config == null)
                {
                    config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                }

                if (config.AppSettings.Settings["Left"] != null && config.AppSettings.Settings["Top"] != null)
                {
                    if (config.AppSettings.Settings["Left"].Value.Length > 0 && config.AppSettings.Settings["Top"].Value.Length > 0)
                    {
                        this.Left = Double.Parse(config.AppSettings.Settings["Left"].Value, System.Globalization.CultureInfo.InvariantCulture);
                        this.Top = Double.Parse(config.AppSettings.Settings["Top"].Value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }

                if (config.AppSettings.Settings["Opacity"] != null)
                {
                    if (config.AppSettings.Settings["Opacity"].Value.Length > 0)
                    {
                        this.opacity = Double.Parse(config.AppSettings.Settings["Opacity"].Value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }

                if (config.AppSettings.Settings["Scale"] != null)
                {
                    if (config.AppSettings.Settings["Scale"].Value.Length > 0)
                    {
                        this.scale = this.ZoomScaleTransform.ScaleX = this.ZoomScaleTransform.ScaleY = Double.Parse(config.AppSettings.Settings["Scale"].Value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }

                if (config.AppSettings.Settings["Topmost"] != null)
                {
                    if (config.AppSettings.Settings["Topmost"].Value.Length > 0)
                    {
                        this.Topmost = Boolean.Parse(config.AppSettings.Settings["Topmost"].Value);
                    }
                }

                if (config.AppSettings.Settings["ShowInTaskbar"] != null)
                {
                    if (config.AppSettings.Settings["ShowInTaskbar"].Value.Length > 0)
                    {
                        this.ShowInTaskbar = Boolean.Parse(config.AppSettings.Settings["ShowInTaskbar"].Value);
                    }
                }

                if (config.AppSettings.Settings["DropShadow"] != null)
                {
                    if (config.AppSettings.Settings["DropShadow"].Value.Length > 0)
                    {
                        if (Boolean.Parse(config.AppSettings.Settings["DropShadow"].Value))
                        {
                            DropShadowEffect dropShadowEffect = new DropShadowEffect();

                            dropShadowEffect.Color = Colors.Black;
                            dropShadowEffect.BlurRadius = 10;
                            dropShadowEffect.Direction = 270;
                            dropShadowEffect.ShadowDepth = 0;
                            dropShadowEffect.Opacity = 0.5;

                            if (dropShadowEffect.CanFreeze)
                            {
                                dropShadowEffect.Freeze();
                            }

                            this.Canvas.Effect = dropShadowEffect;
                        }
                    }
                }

                if (config.AppSettings.Settings["Mute"] != null)
                {
                    if (config.AppSettings.Settings["Mute"].Value.Length > 0)
                    {
                        this.isMute = Boolean.Parse(config.AppSettings.Settings["Mute"].Value);
                    }
                }

                if (config.AppSettings.Settings["FrameRate"] != null)
                {
                    if (config.AppSettings.Settings["FrameRate"].Value.Length > 0)
                    {
                        this.frameRate = Double.Parse(config.AppSettings.Settings["FrameRate"].Value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }
            }
            else
            {
                Agent agent = Application.Current.MainWindow as Agent;

                if (agent != null)
                {
                    this.opacity = agent.opacity;
                    this.scale = this.ZoomScaleTransform.ScaleX = this.ZoomScaleTransform.ScaleY = agent.scale;
                    this.Topmost = agent.Topmost;
                    this.ShowInTaskbar = agent.ShowInTaskbar;

                    if (agent.Canvas.Effect != null)
                    {
                        DropShadowEffect dropShadowEffect = new DropShadowEffect();

                        dropShadowEffect.Color = Colors.Black;
                        dropShadowEffect.BlurRadius = 10;
                        dropShadowEffect.Direction = 270;
                        dropShadowEffect.ShadowDepth = 0;
                        dropShadowEffect.Opacity = 0.5;

                        if (dropShadowEffect.CanFreeze)
                        {
                            dropShadowEffect.Freeze();
                        }

                        this.Canvas.Effect = dropShadowEffect;
                    }

                    this.isMute = agent.isMute;
                    this.frameRate = agent.frameRate;
                }
            }

            this.balloon = new Balloon();
            this.balloon.Title = this.Title;
            this.balloon.SizeChanged += new SizeChangedEventHandler(delegate (object s, SizeChangedEventArgs e)
            {
                foreach (Character character in from character in Script.Instance.Characters where character.Name.Equals(this.characterName) select character)
                {
                    this.balloon.Left = this.Left + (this.Width - e.NewSize.Width) / 2;
                    this.balloon.Top = this.Top - e.NewSize.Height + character.Origin.Y * this.ZoomScaleTransform.ScaleY;
                }
            });
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate
            {
                Run();

                return null;
            }), null);

            Microsoft.Win32.SystemEvents.PowerModeChanged += new Microsoft.Win32.PowerModeChangedEventHandler(this.OnPowerModeChanged);
        }
        private void PrivateSetVerticalOffset(double offset)
        {
            if (_IsScrolling)
                return;

            double oldoff = VerticalOffset;
            double newoffset = CalculateVerticallOffset(offset);

            double delta = Math.Abs(oldoff - newoffset);

            if (delta == 0)
                return;

            //if (delta> 1)
            if (delta > ViewportHeight)
            {
                _transform.Y = -newoffset * _SpaceHeigthY;
                VerticalOffset = newoffset;
                if (ScrollOwner != null)
                    ScrollOwner.InvalidateScrollInfo();

                _IsScrolling = false;
                _ScrollingOffset = 0;
      
                InvalidateMeasure(); //needed for virtualization
                return;
            }


            DoubleAnimation anim = new DoubleAnimation(-newoffset * _SpaceHeigthY, new Duration(TimeSpan.FromSeconds(0.2)));
            PropertyPath p = new PropertyPath("(0).(1)", RenderTransformProperty, TranslateTransform.YProperty);
            Storyboard.SetTargetProperty(anim, p);
            Storyboard sb = new Storyboard();
            sb.Children.Add(anim);
            EventHandler handler = null;
            handler = delegate
            {
                sb.Completed -= handler;
                sb.Remove(this);
                _transform.Y = -newoffset * _SpaceHeigthY;
                VerticalOffset = newoffset;
                _IsScrolling = false;
                _ScrollingOffset = 0;
                //CleanupItems();
                InvalidateMeasure();

                if (ScrollOwner != null)
                    ScrollOwner.InvalidateScrollInfo();

                //InvalidateMeasure();
            };
            sb.Completed += handler;
            //sb.Begin(this, true);
            _IsScrolling = true;
            //if (oldoff - newoffset == -1)
            //    _ScrollingOffset = -1;
            if (oldoff - newoffset <0)
                _ScrollingOffset = (int)(oldoff - newoffset);

            VerticalOffset = newoffset;
            InvalidateMeasure();
            //sb.Begin(this, true);
            ////this.Dispatcher.BeginInvoke((Action)InvalidateMeasure,null);

            Action Ba = () => sb.Begin(this, true);
            this.Dispatcher.BeginInvoke(Ba, DispatcherPriority.Input);
        }
        private void PushMessage()
        {
            if (_IsChanging)
                return;

            if (_Queue.Count==0)
                return;
      
            _IsChanging = true;
      
            _Next = _Queue.Dequeue();
            Next.Content = _Next;

            Storyboard sb = new Storyboard();

            DoubleAnimation db = new DoubleAnimation();
            db.From = 0;
            db.To = -30;
            db.Duration = TransitionTime;

            Storyboard.SetTarget(db, this.Panel);
            Storyboard.SetTargetProperty(db, new PropertyPath("RenderTransform.Y"));

            sb.Children.Add(db);

            EventHandler handler = null;
            handler = delegate
            {
                Current.Content = Next.Content; 
                Transf.Y = 0;
                sb.Completed -= handler;
                sb.Remove();                       
                _IsChanging = false;
                PushMessage();
            };

            sb.Completed += handler;

            sb.Begin();
           
        }
 private static void Reanimate(ChromeTabItem tab, double left, double duration, Action completed)
 {
     if(tab == null)
     {
         return;
     }
     Thickness offset = new Thickness(left, 0, -left, 0);
     ThicknessAnimation moveBackAnimation = new ThicknessAnimation(tab.Margin, offset, new Duration(TimeSpan.FromSeconds(duration)));
     Storyboard.SetTarget(moveBackAnimation, tab);
     Storyboard.SetTargetProperty(moveBackAnimation, new PropertyPath(FrameworkElement.MarginProperty));
     Storyboard sb = new Storyboard();
     sb.Children.Add(moveBackAnimation);
     sb.Completed += (o, ea) =>
     {
         sb.Remove();
         if(completed != null)
         {
             completed();
         }
     };
     sb.Begin();
 }
        protected virtual void OnIsOpenChanged(bool oldIsOpen, bool newIsOpen)
        {
            if (newIsOpen && !oldIsOpen)
            {
                IsOpening = true;

                OnOpening(new RoutedEventArgs(OpeningEvent, this));

                if (TransitionMode == ApplicationBarTransitionMode.None)
                {
                    Mouse.Capture(this, CaptureMode.SubTree);

                    _isOpen = true;
                    InvalidateArrange();

                    OnOpened(new RoutedEventArgs(OpenedEvent, this));

                    IsOpening = false;
                }
                else
                {
                    var storyboard = new Storyboard
                                         {
                                             FillBehavior = FillBehavior.Stop
                                         };

                    Timeline animation;
                    switch (TransitionMode)
                    {
                        case ApplicationBarTransitionMode.Fade:
                            animation = new DoubleAnimation(0d, 1d, General.GetMinimumDuration(this));
                            Storyboard.SetTarget(animation, this);
                            Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
                            // NOTE: Lack of contracts
                            Contract.Assume(storyboard.Children != null);
                            storyboard.Children.Add(animation);
                            break;
                        case ApplicationBarTransitionMode.Slide:
                            animation = new DoubleAnimation(0d, DesiredSize.Height, General.GetMinimumDuration(this));
                            Storyboard.SetTarget(animation, this);
                            Storyboard.SetTargetProperty(animation, new PropertyPath("Height"));
                            // NOTE: Lack of contracts
                            Contract.Assume(storyboard.Children != null);
                            storyboard.Children.Add(animation);
                            break;
                    }

                    storyboard.Completed += (sender, e) =>
                    {
                        storyboard.Stop(this);
                        storyboard.Remove(this);

                        OnOpened(new RoutedEventArgs(OpenedEvent, this));

                        IsOpening = false;
                    };

                    if (!StaysOpen)
                    {
                        Mouse.Capture(this, CaptureMode.SubTree);
                    }

                    storyboard.Freeze();
                    storyboard.Begin(this, true);

                    _isOpen = true;
                    InvalidateArrange();
                }
            }
            if (!newIsOpen && oldIsOpen)
            {
                IsClosing = true;

                OnClosing(new RoutedEventArgs(ClosingEvent, this));

                if (TransitionMode == ApplicationBarTransitionMode.None)
                {
                    Mouse.Capture(null);

                    _isOpen = false;
                    InvalidateArrange();

                    OnClosed(new RoutedEventArgs(ClosedEvent, this));

                    IsClosing = false;
                }
                else
                {
                    var storyboard = new Storyboard
                                         {
                                             FillBehavior = FillBehavior.Stop
                                         };

                    Timeline animation;
                    switch (TransitionMode)
                    {
                        case ApplicationBarTransitionMode.Fade:
                            animation = new DoubleAnimation(1d, 0d, General.GetMinimumDuration(this));
                            Storyboard.SetTarget(animation, this);
                            Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
                            // NOTE: Lack of contracts
                            Contract.Assume(storyboard.Children != null);
                            storyboard.Children.Add(animation);
                            break;
                        case ApplicationBarTransitionMode.Slide:
                            animation = new DoubleAnimation(DesiredSize.Height, 0d, General.GetMinimumDuration(this));
                            Storyboard.SetTarget(animation, this);
                            Storyboard.SetTargetProperty(animation, new PropertyPath("Height"));
                            // NOTE: Lack of contracts
                            Contract.Assume(storyboard.Children != null);
                            storyboard.Children.Add(animation);
                            break;
                    }

                    storyboard.Completed += (sender, e) =>
                    {
                        storyboard.Stop(this);
                        storyboard.Remove(this);

                        if (!StaysOpen)
                        {
                            Mouse.Capture(null);
                        }

                        _isOpen = false;
                        InvalidateArrange();

                        OnClosed(new RoutedEventArgs(ClosedEvent, this));

                        IsClosing = false;
                    };

                    storyboard.Freeze();
                    storyboard.Begin(this, true);
                }
            }
        }