Click here to Skip to main content
15,885,216 members
Articles / Desktop Programming / Windows Forms

BSEtunes

Rate me:
Please Sign up or sign in to vote.
4.67/5 (11 votes)
24 Apr 2010CPOL4 min read 64.6K   4.3K   58  
BSEtunes is a MySQL based, full manageable, networkable single or multiuser jukebox application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BSE.Platten.BO;
using System.Windows.Media.Media3D;
using System.Windows.Resources;
using System.IO;
using System.Globalization;
using BSE.Platten.Audio;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Windows.Media.Animation;

namespace BSE.CoverFlow.WPFLib
{
    /// <summary>
    /// Interaction logic for WindowCoverFlow.xaml
    /// </summary>
    public partial class WindowCoverFlow : Window, IDisposable
    {
        #region Events
        private delegate void ViewStatePlayerPlaysHandler(PlayMode eMode);
        private delegate void ViewStatePlayerPausedHandler(PlayMode eMode);
        private delegate void ViewStatePlayerStoppedHandler(PlayMode eMode);
        private delegate void ViewStatePlayerTrackChangedHandler(PlayMode eMode);
        #endregion

        #region Constants
        #endregion

        #region FieldsPrivate
        private List<CoverItem> m_listCoverFlowItems;
        private Collection<int> m_coverFlowCollection;
        private Queue<CoverItem> m_removeableCoverFlowItems = new Queue<CoverItem>();
        private Queue<int> m_titelIdsToSelect = new Queue<int>(2);
        private WorkingState m_workingState;
        private int m_iVisibleCoversPerSide = 6;
        private ImageSource m_defaultImageSource;
        private int m_iStartPosition;
        private bool m_bDisableMouseHitTesting;
        private CoverItem m_currentCoverItem;
        private ImageSource m_imageSourceBtnPreviousEnabled;
        private ImageSource m_imageSourceBtnPreviousDisabled;
        private ImageSource m_imageSourceBtnNextEnabled;
        private ImageSource m_imageSourceBtnNextDisabled;
        private ImageSource m_imageSourceBtnPlay;
        private ImageSource m_imageSourceBtnPause;
        private BSE.Platten.Audio.CPlayerManager m_playerManager;
        // Track whether Dispose has been called.
        private bool m_bDisposed;
        #endregion

        #region Properties
        //Gets or sets the connection string to the database
        public string ConnectionString
        {
            get;
            set;
        }
        /// <summary>
        /// Sets the CPlayerManager
        /// </summary>
        public CPlayerManager PlayerManager
        {
            private get { return this.m_playerManager; }
            set { this.m_playerManager = value; }
        }
        /// <summary>
        /// Gets the <see cref="ModelVisual3D"/> from the resources.
        /// </summary>
        private ModelVisual3D ModelVisual3D
        {
            get
            {
                return (this.FindResource("modelVisual3D") as ModelVisual3D);
            }
        }
        /// <summary>
        /// Gets the <see cref="Storyboard"/> from the resources.
        /// </summary>
        private Storyboard Storyboard
        {
            get
            {
                return (this.FindResource("modelAnimation") as Storyboard);
            }
        }
        /// <summary>
        /// Gets the <see cref="ImageSource"/> for the default image from the resources.
        /// </summary>
        private ImageSource DefaultImageSource
        {
            get
            {
                if (this.m_defaultImageSource == null)
                {
                    System.Windows.Controls.Image image = this.FindResource("m_imgDefault") as System.Windows.Controls.Image;
                    this.m_defaultImageSource = image.Source;
                    this.m_defaultImageSource.Freeze();
                    image = null;
                }
                return this.m_defaultImageSource;
            }
        }
        /// <summary>
        /// Gets or sets the <see cref="PlayMode"/> in which the player plays.
        /// </summary>
        internal BSE.Platten.Audio.PlayMode PlayMode
        {
            get;
            set;
        }
        /// <summary>
        /// Gets the PlayState enumeration type defines the possible operational states of the PlayerManager
        /// as it plays a digital media file.
        /// </summary>
        internal BSE.Platten.Audio.PlayState PlayState
        {
            get
            {
                if (this.m_playerManager != null)
                {
                    return this.m_playerManager.PlayState;
                }
                return PlayState.Undefined;
            }
        }
        #endregion

        #region MethodsPublic
        public WindowCoverFlow()
        {
            string strAssemblyName = GetAssemblyName();
            this.m_imageSourceBtnNextEnabled = GetBitmapFromResource(
                string.Format(CultureInfo.InvariantCulture, "/{0}{1}", strAssemblyName, Constants.ImageSourceBtnNextEnabled));
            this.m_imageSourceBtnNextDisabled = GetBitmapFromResource(
                string.Format(CultureInfo.InvariantCulture, "/{0}{1}", strAssemblyName, Constants.ImageSourceBtnNextDisabled));
            this.m_imageSourceBtnPreviousEnabled = GetBitmapFromResource(
                string.Format(CultureInfo.InvariantCulture, "/{0}{1}", strAssemblyName, Constants.ImageSourceBtnPreviousEnabled));
            this.m_imageSourceBtnPreviousDisabled = GetBitmapFromResource(
                string.Format(CultureInfo.InvariantCulture, "/{0}{1}", strAssemblyName, Constants.ImageSourceBtnPreviousDisabled));
            this.m_imageSourceBtnPlay = GetBitmapFromResource(
                string.Format(CultureInfo.InvariantCulture, "/{0}{1}", strAssemblyName, Constants.ImageSourceBtnPlay));
            this.m_imageSourceBtnPause = GetBitmapFromResource(
                string.Format(CultureInfo.InvariantCulture, "/{0}{1}", strAssemblyName, Constants.ImageSourceBtnPause));
            
            InitializeComponent();
            
            this.m_btnStop.IsEnabled = false;
            this.m_btnPrevious.IsEnabled = false;
            this.m_btnNext.IsEnabled = false;

            this.m_coverFlowCollection = new Collection<int>();
            this.m_listCoverFlowItems = new List<CoverItem>();
        }
        // Implement IDisposable.
        // Do not make this method virtual.
        // A derived class should not be able to override this method.
        public void Dispose()
        {
            Dispose(true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }
        
        public void LoadCovers()
        {
            if (string.IsNullOrEmpty(this.ConnectionString) == false)
            {
                this.Dispatcher.BeginInvoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    (System.Threading.ThreadStart)delegate()
                {
                    string strCacheDirectory = GetCacheDirectory();
                    CreateCacheFolder(strCacheDirectory);

                    foreach (BSE.Platten.BO.CTrack track in this.m_playerManager.TrackCollection)
                    {
                        int iAlbumId = track.TitelId;
                        if (this.m_coverFlowCollection.Contains(iAlbumId) == false)
                        {
                            this.m_coverFlowCollection.Add(iAlbumId);
                        }
                    }

                    if (this.m_coverFlowCollection.Count < 11)
                    {
                        this.m_iVisibleCoversPerSide = this.m_coverFlowCollection.Count / 2;
                    }

                    int num = 0;
                    int num2 = this.m_iStartPosition + this.m_iVisibleCoversPerSide;

                    foreach (int iAlbumId in this.m_coverFlowCollection)
                    {
                        if (((num >= this.m_iStartPosition) && (num <= (this.m_iStartPosition + (this.m_iVisibleCoversPerSide * 2)))) && (num < this.m_coverFlowCollection.Count))
                        {
                            if (num < num2)
                            {
                                this.CreateCoverItem(((this.m_iVisibleCoversPerSide - num) - this.m_iStartPosition) * -1, iAlbumId);

                            }
                            else if (num > num2)
                            {
                                CreateCoverItem((num - this.m_iStartPosition) - this.m_iVisibleCoversPerSide, iAlbumId);
                            }
                            else
                            {
                                CreateCoverItem(0, iAlbumId);
                            }
                        }
                        num++;
                    }

                    Comparison<CoverItem> comparison = new Comparison<CoverItem>(this.CoverItemComparer);
                    this.m_listCoverFlowItems.Sort(comparison);

                    foreach (CoverItem coverItem in this.m_listCoverFlowItems)
                    {
                        if (coverItem.Position == 0)
                        {
                            this.m_currentCoverItem = coverItem;
                        }
                    }
                    BSE.Platten.BO.CTrack currentTrack = this.m_playerManager.CurrentTrack;
                    this.m_btnPlay.DisplayState = DisplayState.Playing;
                    this.PlayMode = this.m_playerManager.PlayMode;
                    switch (this.PlayState)
                    {
                        case PlayState.Playing:
                            this.m_btnPlay.DisplayState = DisplayState.Paused;
                            PlayerManagerPlays(
                                this, new PlayerManagerStatusChangedEventArgs(this.PlayMode));
                            break;
                        case PlayState.Paused:
                            PlayerManagerPaused(
                                this, new PlayerManagerStatusChangedEventArgs(this.PlayMode));
                            break;
                    }

                    if (currentTrack != null)
                    {
                        this.m_titelIdsToSelect.Enqueue(currentTrack.TitelId);
                    }
                    DequeueCovers();
                });
            }
        }
        /// <summary>
        /// Clears the Coverflow cache directory
        /// </summary>
        public static void ClearCoverFlowCache()
        {
            string strCacheDirectory = GetCacheDirectory();
            if (string.IsNullOrEmpty(strCacheDirectory) == false)
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(strCacheDirectory);
                if (directoryInfo.Exists == true)
                {
                    directoryInfo.Delete(true);
                }
            }
        }
        #endregion

        #region MethodsProtected
        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (this.m_bDisposed == false)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    if (this.m_viewPort3D != null)
                    {
                        Queue<CoverItem> coverItemsToRemove = new Queue<CoverItem>();
                        foreach (CoverItem coverItem in this.m_listCoverFlowItems)
                        {
                            coverItemsToRemove.Enqueue(coverItem);
                        }

                        while (coverItemsToRemove.Count > 0)
                        {
                            CoverItem coverItemToRemove = null;
                            using (coverItemToRemove = coverItemsToRemove.Dequeue())
                            {
                                if (coverItemToRemove != null)
                                {
                                    this.m_listCoverFlowItems.Remove(coverItemToRemove);
                                    this.m_visualModel.Children.Remove(coverItemToRemove.ModelVisual3D);
                                }
                            }
                        }
                        if (this.m_listCoverFlowItems != null)
                        {
                            this.m_listCoverFlowItems = null;
                        }
                        if (this.m_coverFlowCollection != null)
                        {
                            this.m_coverFlowCollection = null;
                        }
                        if (this.m_removeableCoverFlowItems != null)
                        {
                            this.m_removeableCoverFlowItems = null;
                        }
                        if (this.m_titelIdsToSelect != null)
                        {
                            this.m_titelIdsToSelect = null;
                        }
                        if (this.m_currentCoverItem != null)
                        {
                            this.m_currentCoverItem = null;
                        }
                        if (this.m_imageSourceBtnPreviousEnabled != null)
                        {
                            this.m_imageSourceBtnPreviousEnabled = null;
                        }
                        if (this.m_imageSourceBtnPreviousDisabled != null)
                        {
                            this.m_imageSourceBtnPreviousDisabled = null;
                        }
                        if (this.m_imageSourceBtnNextEnabled != null)
                        {
                            this.m_imageSourceBtnNextEnabled = null;
                        }
                        if (this.m_imageSourceBtnNextDisabled != null)
                        {
                            this.m_imageSourceBtnNextDisabled = null;
                        }
                        if (this.m_imageSourceBtnPlay != null)
                        {
                            this.m_imageSourceBtnPlay = null;
                        }
                        if (this.m_imageSourceBtnPause != null)
                        {
                            this.m_imageSourceBtnPause = null;
                        }
                    }
                }
                this.m_bDisposed = true;
            }
        }
        #endregion

        #region MethodsPrivate
        
        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.m_playerManager != null)
            {
                this.m_playerManager.PlayerManagerTrackChanged -= new EventHandler<PlayerManagerStatusChangedEventArgs>(PlayerManagerTrackChanged);
                this.m_playerManager.PlayerManagerPlays -= new EventHandler<PlayerManagerStatusChangedEventArgs>(PlayerManagerPlays);
                this.m_playerManager.PlayerManagerStopped -= new EventHandler<PlayerManagerStatusChangedEventArgs>(PlayerManagerStopped);
                this.m_playerManager.PlayerManagerPaused -= new EventHandler<PlayerManagerStatusChangedEventArgs>(PlayerManagerPaused);
            }
        }
        
        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            if (this.m_playerManager != null)
            {
                this.m_playerManager.PlayerManagerTrackChanged += new EventHandler<PlayerManagerStatusChangedEventArgs>(PlayerManagerTrackChanged);
                this.m_playerManager.PlayerManagerPlays += new EventHandler<PlayerManagerStatusChangedEventArgs>(PlayerManagerPlays);
                this.m_playerManager.PlayerManagerStopped += new EventHandler<PlayerManagerStatusChangedEventArgs>(PlayerManagerStopped);
                this.m_playerManager.PlayerManagerPaused += new EventHandler<PlayerManagerStatusChangedEventArgs>(PlayerManagerPaused);
            }
        }
        
        private void WindowPreviewKeyDown(object sender, KeyEventArgs e)
        {
            Key key = e.Key;
            switch (key)
            {
                case Key.Escape:
                    this.BtnCloseClick(this, new RoutedEventArgs());
                    break;
                case Key.MediaNextTrack:
                    this.BtnNextClick(this, new RoutedEventArgs());
                    break;
                case Key.MediaPreviousTrack:
                    this.BtnPreviousClick(this, new RoutedEventArgs());
                    break;
                case Key.MediaPlayPause:
                    this.BtnPlayClick(this, new RoutedEventArgs());
                    break;
                case Key.MediaStop:
                    this.BtnStopClick(this, new RoutedEventArgs());
                    break;
                case Key.Play:
                    this.BtnPlayClick(this, new RoutedEventArgs());
                    break;
            }
        }
        
        private void WindowMouseDown(object sender, MouseButtonEventArgs e)
        {
            CoverItem selectedCoverItem = null;
            Point positionPoint = e.GetPosition(this.m_viewPort3D);
            var rayMeshGeometry3DHitTestResult = VisualTreeHelper.HitTest(this.m_viewPort3D, positionPoint) as RayMeshGeometry3DHitTestResult;
            if (rayMeshGeometry3DHitTestResult != null)
            {
                ModelVisual3D modelVisual3D = rayMeshGeometry3DHitTestResult.VisualHit as ModelVisual3D;
                foreach (CoverItem coverItem in this.m_listCoverFlowItems)
                {
                    if (coverItem != null)
                    {
                        if (coverItem.Matches(modelVisual3D) == true)
                        {
                            selectedCoverItem = coverItem;
                            break;
                        }
                    }
                }

                if ((selectedCoverItem != null) && (this.m_bDisableMouseHitTesting == false))
                {
                    this.m_bDisableMouseHitTesting = true;
                    DispatcherTimer selectCoverTimer = new DispatcherTimer();
                    selectCoverTimer.Tick += new EventHandler(this.SelectCoverTimerTick);
                    selectCoverTimer.Tag = selectedCoverItem.Position;
                    selectCoverTimer.Start();
                }
            }
        }

        private void SelectCoverTimerTick(object sender, EventArgs e)
        {
            DispatcherTimer dispatcherTimer = sender as DispatcherTimer;
            
            int iPosition = (int)dispatcherTimer.Tag;
            if (iPosition < 0)
            {
                this.MoveLeft();
                iPosition++;
            }
            else if (iPosition > 0)
            {
                this.MoveRight();
                iPosition--;
            }
            dispatcherTimer.Tag = iPosition;
            if (iPosition == 0)
            {
                dispatcherTimer.Stop();
                dispatcherTimer = null;
                foreach (CoverItem coverItem in this.m_listCoverFlowItems)
                {
                    if (coverItem.Position == 0)
                    {
                        this.m_currentCoverItem = coverItem;
                        break;
                    }
                }
                this.m_bDisableMouseHitTesting = false;
                this.m_workingState = WorkingState.None;
                DequeueCovers();
            }
        }

        private void MoveLeft()
        {
            CleanUpOldItems();

            int iIndex = 0;
            int iNewAlbimId = -1;

            foreach (int iAlbumId in this.m_coverFlowCollection)
            {
                if (iIndex == (this.m_iStartPosition - 1))
                {
                    iNewAlbimId = iAlbumId;
                    break;
                }
                iIndex++;
            }

            CoverItem coverItemToRemove = null;
            if (this.m_listCoverFlowItems.Count > 0)
            {
                coverItemToRemove = this.m_listCoverFlowItems[this.m_listCoverFlowItems.Count - 1];
                coverItemToRemove.Storyboard.CurrentStateInvalidated += new EventHandler(this.StoryboardCurrentStateInvalidated);
            }

            if (iNewAlbimId != -1)
            {
                this.CreateCoverItem(-(this.m_iVisibleCoversPerSide + 1), iNewAlbimId);
            }

            if (coverItemToRemove != null)
            {
                if ((this.m_iStartPosition >= (this.m_iVisibleCoversPerSide * -2)) &&
                (coverItemToRemove.Position < -(this.m_iVisibleCoversPerSide - 1)) || (coverItemToRemove.Position > (this.m_iVisibleCoversPerSide - 1)))
                {
                    this.m_removeableCoverFlowItems.Enqueue(coverItemToRemove);
                }
            }
            double yRotation = 0.0;
            double dOffsetX = 0.0;
            double dOffsetY = 0.0;
            double dOffsetZ = 0.0;
            foreach (CoverItem coverItem in this.m_listCoverFlowItems)
            {
                CoverItem.GetOffsetsFromPosition(coverItem.Position + 1, out yRotation, out dOffsetX, out dOffsetY, out dOffsetZ);
                AnimateByParameters(coverItem, yRotation, dOffsetX, dOffsetY, dOffsetZ);
                coverItem.Position++;
            }

            this.m_iStartPosition--;
        }

        private void MoveRight()
        {
            CleanUpOldItems();

            int iIndex = 0;
            int iNewAlbumId = -1;

            foreach (int iAlbumId in this.m_coverFlowCollection)
            {
                if (iIndex == (this.m_iStartPosition + (2 * this.m_iVisibleCoversPerSide) + 1))
                {
                    iNewAlbumId = iAlbumId;
                    break;
                }
                iIndex++;
            }

            CoverItem coverItemToRemove = null;
            if (this.m_listCoverFlowItems.Count > 0)
            {
                coverItemToRemove = this.m_listCoverFlowItems[0];
            }
            if (iNewAlbumId != -1)
            {
                this.CreateCoverItem(this.m_iVisibleCoversPerSide + 1, iNewAlbumId);
            }

            if (coverItemToRemove != null)
            {
                if (coverItemToRemove.Position < -(this.m_iVisibleCoversPerSide - 1))
                {
                    this.m_removeableCoverFlowItems.Enqueue(coverItemToRemove);
                    coverItemToRemove.Storyboard.CurrentStateInvalidated += new EventHandler(this.StoryboardCurrentStateInvalidated);
                }
            }

            double yRotation = 0.0;
            double dOffsetX = 0.0;
            double dOffsetY = 0.0;
            double dOffsetZ = 0.0;
            foreach (CoverItem coverItem in this.m_listCoverFlowItems)
            {
                CoverItem.GetOffsetsFromPosition(coverItem.Position - 1, out yRotation, out dOffsetX, out dOffsetY, out dOffsetZ);
                AnimateByParameters(coverItem, yRotation, dOffsetX, dOffsetY, dOffsetZ);
                coverItem.Position--;
            }

            this.m_iStartPosition++;
        }

        private void StoryboardCurrentStateInvalidated(object sender, EventArgs e)
        {
            ClockGroup group = sender as ClockGroup;
            if (group.CurrentState != ClockState.Active)
            {
                this.CleanUpOldItems();
            }
        }

        private void CleanUpOldItems()
        {
            while (this.m_removeableCoverFlowItems.Count > 0)
            {
                using (CoverItem removedItem = this.m_removeableCoverFlowItems.Dequeue())
                {
                    if (removedItem != null)
                    {
                        this.m_listCoverFlowItems.Remove(removedItem);
                        int index = this.m_visualModel.Children.IndexOf(removedItem.ModelVisual3D);
                        if (index > -1)
                        {
                            this.m_visualModel.Children.RemoveAt(index);
                            foreach (CoverItem coverItem in this.m_listCoverFlowItems)
                            {
                                if (coverItem.Viewport3DIndex > index)
                                {
                                    coverItem.Viewport3DIndex--;
                                    UpdateViewport3DIndex(coverItem);
                                }
                            }
                        }
                    }
                }
            }
        }

        private void AnimateByParameters(CoverItem coverItem, double angle, double offsetX, double offsetY, double offsetZ)
        {
            this.AnimateByParameters(coverItem, angle, offsetX, offsetY, offsetZ, new Duration(TimeSpan.FromSeconds(0.6)));
        }

        private void AnimateByParameters(CoverItem coverItem, double angle, double offsetX, double offsetY, double offsetZ, Duration duration)
        {
            Rotation3DAnimation rotation3DAnimation = coverItem.Storyboard.Children[0] as Rotation3DAnimation;
            ChangeViewport3DIndex(rotation3DAnimation, coverItem.Viewport3DIndex, AnimationProperty.AxisAngleRotation3D);
            rotation3DAnimation.To = new AxisAngleRotation3D(new Vector3D(0, 1, 0), angle);
            rotation3DAnimation.Duration = duration.TimeSpan;

            DoubleAnimation doubleAnimationX = coverItem.Storyboard.Children[1] as DoubleAnimation;
            ChangeViewport3DIndex(doubleAnimationX, coverItem.Viewport3DIndex, AnimationProperty.OffsetX);
            doubleAnimationX.Duration = duration.TimeSpan;
            doubleAnimationX.To = offsetX;

            DoubleAnimation doubleAnimationY = coverItem.Storyboard.Children[2] as DoubleAnimation;
            ChangeViewport3DIndex(doubleAnimationY, coverItem.Viewport3DIndex, AnimationProperty.OffsetY);
            doubleAnimationY.Duration = duration.TimeSpan;
            doubleAnimationY.To = offsetY;

            DoubleAnimation doubleAnimationZ = coverItem.Storyboard.Children[3] as DoubleAnimation;
            ChangeViewport3DIndex(doubleAnimationZ, coverItem.Viewport3DIndex, AnimationProperty.OffsetZ);
            doubleAnimationZ.Duration = duration.TimeSpan;
            doubleAnimationZ.To = offsetZ;

            if (this.m_visualModel.Children.Contains(coverItem.ModelVisual3D))
            {
                coverItem.Storyboard.Begin(this.m_viewPort3D, HandoffBehavior.Compose, true);
            }
        }

        private static void UpdateViewport3DIndex(CoverItem coverItem)
        {
            Rotation3DAnimation rotation3DAnimation = coverItem.Storyboard.Children[0] as Rotation3DAnimation;
            ChangeViewport3DIndex(rotation3DAnimation, coverItem.Viewport3DIndex, AnimationProperty.AxisAngleRotation3D);

            DoubleAnimation doubleAnimationX = coverItem.Storyboard.Children[1] as DoubleAnimation;
            ChangeViewport3DIndex(doubleAnimationX, coverItem.Viewport3DIndex, AnimationProperty.OffsetX);

            DoubleAnimation doubleAnimationY = coverItem.Storyboard.Children[2] as DoubleAnimation;
            ChangeViewport3DIndex(doubleAnimationY, coverItem.Viewport3DIndex, AnimationProperty.OffsetY);

            DoubleAnimation doubleAnimationZ = coverItem.Storyboard.Children[3] as DoubleAnimation;
            ChangeViewport3DIndex(doubleAnimationZ, coverItem.Viewport3DIndex, AnimationProperty.OffsetZ);
        }

        private static void ChangeViewport3DIndex(Timeline animation, int viewport3DIndex, AnimationProperty animationProperty)
        {
            string strPath = string.Empty;
            switch (animationProperty)
            {
                case AnimationProperty.AxisAngleRotation3D:
                    strPath = "(0).[2].(1).[" + viewport3DIndex + "].(2).(3).(4).[0].(5)";
                    break;
                case AnimationProperty.OffsetX:
                    strPath = "(0).[2].(1).[" + viewport3DIndex + "].(2).(3).(4).[1].(5)";
                    break;
                case AnimationProperty.OffsetY:
                    strPath = "(0).[2].(1).[" + viewport3DIndex + "].(2).(3).(4).[1].(5)";
                    break;
                case AnimationProperty.OffsetZ:
                    strPath = "(0).[2].(1).[" + viewport3DIndex + "].(2).(3).(4).[1].(5)";
                    break;
            }
            PropertyPath targetProperty = Storyboard.GetTargetProperty(animation);
            targetProperty.Path = strPath;
            Storyboard.SetTargetProperty(animation, targetProperty);
        }

        private CoverItem CreateCoverItem(int iPosition, int iAlbumId)
        {
            string strCacheDirectory = GetCacheDirectory();
            CoverItem coverItem = new CoverItem(this.ModelVisual3D, this.Storyboard, strCacheDirectory, this.DefaultImageSource, iAlbumId, iPosition, this.ConnectionString);
            coverItem.Viewport3DIndex = this.m_visualModel.Children.Count;
            this.m_visualModel.Children.Add(coverItem.ModelVisual3D);

            if (iPosition < 0)
            {
                this.m_listCoverFlowItems.Insert(0, coverItem);
                return coverItem;
            }

            this.m_listCoverFlowItems.Add(coverItem);
            return coverItem;
        }

        private void BtnPreviousIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.m_imgPrevious != null)
            {
                if (e.NewValue is bool)
                {
                    bool bIsEnabled = (bool)e.NewValue;
                    if (bIsEnabled == true)
                    {
                        this.m_imgPrevious.Source = this.m_imageSourceBtnPreviousEnabled;
                    }
                    else
                    {
                        this.m_imgPrevious.Source = this.m_imageSourceBtnPreviousDisabled;
                    }
                }
            }
        }

        private void BtnNextIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.m_imgNext != null)
            {
                if (e.NewValue is bool)
                {
                    bool bIsEnabled = (bool)e.NewValue;
                    if (bIsEnabled == true)
                    {
                        this.m_imgNext.Source = this.m_imageSourceBtnNextEnabled;
                    }
                    else
                    {
                        this.m_imgNext.Source = this.m_imageSourceBtnNextDisabled;
                    }
                }
            }
        }
        private void BtnCloseClick(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        private void BtnNextClick(object sender, RoutedEventArgs e)
        {
            if (this.m_playerManager.IsNextTrackAvailable == true)
            {
                this.m_playerManager.PlayNextTrack(PlayMode.Random);
            }
        }
        private void BtnPreviousClick(object sender, RoutedEventArgs e)
        {
            if (this.m_playerManager.IsPreviousTrackAvailable == true)
            {
                this.m_playerManager.PlayPreviousTrack(PlayMode.Random);
            }
        }
        private void BtnStopClick(object sender, RoutedEventArgs e)
        {
            if (this.m_playerManager != null)
            {
                this.m_playerManager.Stop();
            }
            BtnCloseClick(sender, e);
        }

        private void BtnPlayClick(object sender, RoutedEventArgs e)
        {
            if (this.m_playerManager != null)
            {
                switch (this.m_btnPlay.DisplayState)
                {
                    case DisplayState.Paused:
                        this.m_playerManager.Play();
                        break;
                    case DisplayState.Playing:
                        this.m_playerManager.Pause();
                        break;
                }
            }
        }

        private void BtnPlayDisplayStateChanged(object sender, RoutedEventArgs e)
        {
            this.m_imgPlay.Source = this.m_imageSourceBtnPlay;
            if (this.m_btnPlay.DisplayState == DisplayState.Playing)
            {
                this.m_imgPlay.Source = this.m_imageSourceBtnPause;
            }
        }

        private void PlayerManagerTrackChanged(object sender, PlayerManagerStatusChangedEventArgs e)
        {
            this.PlayMode = e.PlayMode;
            BSE.Platten.BO.CTrack currentTrack = e.CurrentTrack.Clone() as BSE.Platten.BO.CTrack;
            if (currentTrack != null)
            {
                this.m_titelIdsToSelect.Enqueue(currentTrack.TitelId);
                DequeueCovers();
            }
        }

        private void PlayerManagerPlays(object sender, PlayerManagerStatusChangedEventArgs e)
        {
            Dispatcher.Invoke(
                new ViewStatePlayerPlaysHandler(ViewStatePlayerPlays),
                e.PlayMode);
        }

        private void ViewStatePlayerPlays(PlayMode eMode)
        {
            this.m_btnStop.IsEnabled = true;
            this.m_btnPlay.IsEnabled = true;
            this.m_btnPlay.DisplayState = DisplayState.Playing;
            this.m_btnNext.IsEnabled = false;
            this.m_btnPrevious.IsEnabled = false;
            this.m_txtSong.Text = this.m_playerManager.GetSongTitle();

            switch (eMode)
            {
                case PlayMode.Playlist:
                case PlayMode.Random:
                    if (this.m_playerManager.IsNextTrackAvailable == true)
                    {
                        this.m_btnNext.IsEnabled = true;
                    }
                    if (this.m_playerManager.IsPreviousTrackAvailable == true)
                    {
                        this.m_btnPrevious.IsEnabled = true;
                    }
                    break;
            }
        }

        private void PlayerManagerStopped(object sender, PlayerManagerStatusChangedEventArgs e)
        {
            Dispatcher.Invoke(
                new ViewStatePlayerStoppedHandler(ViewStatePlayerStopped),
                e.PlayMode);
        }

        private void ViewStatePlayerStopped(PlayMode eMode)
        {
            this.m_btnNext.IsEnabled = false;
            this.m_btnPrevious.IsEnabled = false;
            this.m_btnStop.IsEnabled = false;
            this.m_btnPlay.IsEnabled = false;
        }

        private void PlayerManagerPaused(object sender, PlayerManagerStatusChangedEventArgs e)
        {
            Dispatcher.Invoke(
                new ViewStatePlayerPausedHandler(ViewStatePlayerPaused),
                e.PlayMode);
        }

        private void ViewStatePlayerPaused(PlayMode eMode)
        {
            this.m_btnPlay.DisplayState = DisplayState.Paused;
        }

        private void DequeueCovers()
        {
            if (this.m_titelIdsToSelect.Count > 0)
            {
                if (m_workingState == WorkingState.Working)
                {
                    return;
                }
                else
                {
                    this.m_workingState = WorkingState.Working;
                    int iTitelId = this.m_titelIdsToSelect.Dequeue();
                    SelectCurrentCover(iTitelId);
                }
            }
        }

        private void SelectCurrentCover(int iTitelId)
        {
            this.m_bDisableMouseHitTesting = true;
            int iCurrentAlbumPosition = 0;
            int iCounter = 0;
            int iNewAlbumPosition = 0;

            if (iTitelId != 0)
            {
                foreach (int iAlbumId in this.m_coverFlowCollection)
                {
                    if ((this.m_currentCoverItem != null) && (iAlbumId == this.m_currentCoverItem.TitelId))
                    {
                        iCurrentAlbumPosition = iCounter;
                    }
                    if (iAlbumId == iTitelId)
                    {
                        iNewAlbumPosition = iCounter;
                    }
                    iCounter++;
                }

                int iPosition = 0;
                {
                    iPosition = iNewAlbumPosition - iCurrentAlbumPosition;
                }

                if (Math.Abs(iPosition) > Constants.MaxScrollStep)
                {
                    //The value for the abbreviation
                    int iAbbreviationValue = Math.Abs(iPosition) - (2 * this.m_iVisibleCoversPerSide);
                    if (iPosition < 0)
                    {
                        iPosition += iAbbreviationValue;
                        this.m_iStartPosition -= iAbbreviationValue - 1;
                        MoveLeft();
                    }
                    else
                    {
                        iPosition -= iAbbreviationValue ;
                        this.m_iStartPosition += iAbbreviationValue - 1;
                        MoveRight();
                    }
                }

                DispatcherTimer selectCoverItemTimer = new DispatcherTimer();
                selectCoverItemTimer.Tick += new EventHandler(this.SelectCoverTimerTick);
                selectCoverItemTimer.Tag = iPosition;
                if (Math.Abs(iPosition) > 1)
                {
                    selectCoverItemTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
                }
                else
                {
                    selectCoverItemTimer.Interval = new TimeSpan(0, 0, 0, 0, 0);
                }
                selectCoverItemTimer.Start();
            }
        }

        private int CoverItemComparer(CoverItem item1, CoverItem item2)
        {
            if (item1.Position < item2.Position)
            {
                return -1;
            }
            if (item1.Position > item2.Position)
            {
                return 1;
            }
            return 0;
        }

        private static void CreateCacheFolder(string strCacheDirectoryName)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(strCacheDirectoryName);
            if (directoryInfo.Exists == false)
            {
                directoryInfo.Create();
            }
        }

        private static BitmapImage GetBitmapFromResource(string relativeUriString)
        {
            BitmapImage bitmapImage = null;
            // Get the image stream at the specified URI that
            // is relative to the application package root.
            Uri uri = new Uri(relativeUriString, UriKind.Relative);
            StreamResourceInfo streamResourceInfo = Application.GetResourceStream(uri);
            using (Stream stream = streamResourceInfo.Stream)
            {
                // Convert the stream to an Image object.
                bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
                streamResourceInfo = null;
            }
            return bitmapImage;
        }
        /// <summary>
        /// Gets the name of the Coverflow assembly.
        /// </summary>
        /// <returns>the name of the Coverflow assembly as string</returns>
        private static string GetAssemblyName()
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            return assembly.GetName().Name;
        }
        /// <summary>
        /// Gets the name for the Coverflow cache directory
        /// </summary>
        /// <returns>The name for the Coverflow cache as string</returns>
        private static string GetCacheDirectory()
        {
            string strCacheDirectory = null;
            string strAssemblyName = GetAssemblyName();
            if (string.IsNullOrEmpty(strAssemblyName) == false)
            {
                string strApplicationDataPath = System.IO.Path.Combine(
                System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                Constants.ApplicationBaseDataDirectoryName);

                strCacheDirectory = System.IO.Path.Combine(strApplicationDataPath, strAssemblyName);
            }
            return strCacheDirectory;
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions