/Application/GUI/Windows/MainWindow.xaml.cs
C# | 4225 lines | 3044 code | 419 blank | 762 comment | 855 complexity | 9652eeb869a0fa5525fb94a2d665a38c MD5 | raw file
- /**
- * MainWindow.xaml.cs
- *
- * The logic behind the main window. Contains
- * the code that connects the different part
- * of Stoffi. Sort of like the spider in the net.
- *
- * * * * * * * * *
- *
- * This code is part of the Stoffi Music Player Project.
- * Visit our website at: stoffiplayer.com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version
- * 3 of the License, or (at your option) any later version.
- *
- * See stoffiplayer.com/license for more information.
- **/
-
- using GlassLib;
- using System;
- using System.ComponentModel;
- using System.Collections;
- using System.Collections.ObjectModel;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.Configuration;
- using System.Windows.Data;
- using System.Globalization;
- using System.IO;
- using System.Reflection;
- using System.Threading;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Threading;
- using System.Windows.Interop;
- using System.Windows.Shell;
- using Hardcodet.Wpf.TaskbarNotification;
- using Microsoft.WindowsAPICodePack.Dialogs;
- using Microsoft.Win32;
- using Tomers.WPF.Localization;
-
- namespace Stoffi
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- public partial class StoffiWindow : Window, INotifyPropertyChanged
- {
- #region Members
-
- private KeyboardListener kListener = new KeyboardListener();
- public ContextMenu trayMenu;
- public MenuItem trayMenuShow;
- public MenuItem trayMenuPlay;
- public MenuItem trayMenuNext;
- public MenuItem trayMenuPrev;
- public MenuItem trayMenuExit;
- private ContextMenu addMenu;
- public MenuItem addMenuFile;
- public MenuItem addMenuFolder;
- public MenuItem addMenuPlaylist;
- private ContextMenu showMenu;
- public MenuItem showMenuDetailsPane;
- public MenuItem showMenuMenuBar;
- private ContextMenu toolsMenu;
- public MenuItem toolsMenuImporter;
- public MenuItem toolsMenuExporter;
- public MenuItem toolsMenuGenerate;
- public Microsoft.WindowsAPICodePack.Taskbar.ThumbnailToolbarButton taskbarPrev;
- public Microsoft.WindowsAPICodePack.Taskbar.ThumbnailToolbarButton taskbarPlay;
- public Microsoft.WindowsAPICodePack.Taskbar.ThumbnailToolbarButton taskbarNext;
- public TaskbarIcon trayIcon;
- private WindowState oldWindowState = WindowState.Minimized;
- private WindowState currentWindowState = WindowState.Normal;
- public System.Windows.Shell.JumpList jumpList;
- public System.Windows.Shell.JumpTask jumpTaskPlay;
- public System.Windows.Shell.JumpTask jumpTaskNext;
- public System.Windows.Shell.JumpTask jumpTaskPrev;
- private bool glassEffect = true;
- private List<Key> currentPressedKeys = new List<Key>();
- public Microsoft.WindowsAPICodePack.Taskbar.TabbedThumbnail taskbarPreview;
- private EditableTextBlock etbInEdit = null;
- private Equalizer equalizer = null;
- private DispatcherTimer resortDelay = new DispatcherTimer();
- private List<string> pathsThatWasChanged = new List<string>();
- public MenuItem listMenuPlay = new MenuItem();
- public MenuItem listMenuRemove = new MenuItem();
- public MenuItem listMenuDelete = new MenuItem();
- public MenuItem listMenuInfo = new MenuItem();
- public MenuItem listMenuQueue = new MenuItem();
- public MenuItem listMenuAddToNew = new MenuItem();
- public MenuItem listMenuAddToPlaylist = new MenuItem();
- public MenuItem listMenuRemoveFromPlaylist = new MenuItem();
- public MenuItem listMenuWatchOnYouTube = new MenuItem();
- public MenuItem listMenuShareSong = new MenuItem();
- private ContextMenu listMenu = new ContextMenu();
- private string dialogPath = @"C:\";
- private DispatcherTimer sourceModifiedDelay = new DispatcherTimer();
- private Hashtable sourceModifiedTracks = new Hashtable();
- private bool doRestart = false;
- private TrackData currentlySelectedTrack = null;
- private ScannerCallback sourceModifiedCallback;
- private bool resumeWhenBack = false; // whether or not to resume playback at login/unlock
- private object sourceModifiedCallbackParams;
- private bool initialized = false;
- private bool showMediaError = false; // whether or not to show errors from media manager as popup
-
- #endregion
-
- #region Properties
-
- /// <summary>
- /// The total time of all tracks in the history (in seconds)
- /// </summary>
- public double HistoryTime { get; private set; }
-
- /// <summary>
- /// The total time of all tracks in the queue (in seconds)
- /// </summary>
- public double QueueTime { get; private set; }
-
- /// <summary>
- /// The total time of all tracks in the library (in seconds)
- /// </summary>
- public double LibraryTime { get; private set; }
-
- /// <summary>
- /// A table of the TrackList for each playlist
- /// </summary>
- public Hashtable PlaylistTrackLists { get; private set; }
-
- /// <summary>
- /// The height of the details pane
- /// </summary>
- public double DetailsPaneHeight
- {
- get { return SettingsManager.DetailsPaneHeight; }
- set { SettingsManager.DetailsPaneHeight = value; }
- }
-
- #endregion
-
- #region Constructor
-
- /// <summary>
- ///
- /// </summary>
- public StoffiWindow()
- {
- U.L(LogLevel.Debug, "MAIN", "Creating main window");
- //SettingsManager.FirstRun = true;
- //*********** Next ***********/
- // TODO: In-place track edit
- // TODO: Images (currently playing, queue) in front of t + style
- // TODO: Images (currently playing) in front of playlists/library
- // TODO: MusicBrainz
- // TODO: Jumplist: playlists
- // TODO: Drag search text
- // TODO: Track score (how good is it?)
- // TODO: Last.fm support
- // TODO: Spotify
- // TODO: Spectrum
- // TODO: Views (album, artist, genre, all)
- // TODO: Playlist view
- // TODO: Network sources
- // TODO: Device sources
- // TODO: Tools for cutting track
- // TODO: Album cover download
- // TODO: Lyrics
- // TODO: Radio
- // TODO: TaskDialogs
- // TODO: Wikipedia
- // TODO: Social music
-
- U.L(LogLevel.Debug, "MAIN", "Setting culture");
- LanguageContext.Instance.Culture = CultureInfo.GetCultureInfo(SettingsManager.Language);
-
- if (!Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.IsPlatformSupported)
- {
- MessageBox.Show(U.T("MessageOldWindows", "Message"), U.T("MessageOldWindows", "Title"), MessageBoxButton.OK, MessageBoxImage.Error);
- Application.Current.Shutdown();
- return;
- }
-
- U.L(LogLevel.Debug, "MAIN", "Initialize");
- InitializeComponent();
- U.L(LogLevel.Debug, "MAIN", "Initialized");
-
- // we have to remove controls from their parent so "LastChildFill" doesn't screw everything up
- // we add them later on when they are toggled
- MainContainer.Children.Remove(ControlPanel);
- }
-
- #endregion
-
- #region Methods
-
- #region Public
-
- /// <summary>
- /// Restarts the application
- /// </summary>
- public void Restart()
- {
- doRestart = true;
- this.Close();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="modifiers"></param>
- /// <returns></returns>
- public String GetModifiersAsText(List<Key> modifiers)
- {
- String txt = "";
- foreach (Key k in modifiers)
- {
- if (k == Key.LeftCtrl || k == Key.RightCtrl) txt += "Ctrl+";
- else if (k == Key.LeftAlt || k == Key.RightAlt) txt += "Alt+";
- else if (k == Key.LWin || k == Key.RWin) txt += "Win+";
- else if (k == Key.LeftShift || k == Key.RightShift) txt += "Shift+";
- }
- if (txt.Length > 0) return txt.Substring(0, txt.Length - 1);
- else return "";
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="k"></param>
- /// <returns></returns>
- public String KeyToString(Key k)
- {
- switch (k)
- {
- case Key.NumPad0:
- return "0 (numpad)";
- case Key.NumPad1:
- return "1 (numpad)";
- case Key.NumPad2:
- return "2 (numpad)";
- case Key.NumPad3:
- return "3 (numpad)";
- case Key.NumPad4:
- return "4 (numpad)";
- case Key.NumPad5:
- return "5 (numpad)";
- case Key.NumPad6:
- return "6 (numpad)";
- case Key.NumPad7:
- return "7 (numpad)";
- case Key.NumPad8:
- return "8 (numpad)";
- case Key.NumPad9:
- return "9 (numpad)";
- case Key.D0:
- return "0";
- case Key.D1:
- return "1";
- case Key.D2:
- return "2";
- case Key.D3:
- return "3";
- case Key.D4:
- return "4";
- case Key.D5:
- return "5";
- case Key.D6:
- return "6";
- case Key.D7:
- return "7";
- case Key.D8:
- return "8";
- case Key.D9:
- return "9";
- case Key.OemComma:
- return ",";
- case Key.OemPeriod:
- return ".";
- case Key.Subtract:
- return "-";
- case Key.Multiply:
- return "*";
- case Key.Divide:
- return "/";
- case Key.Add:
- return "+";
- case Key.Back:
- return "Backspace";
- case Key.OemMinus:
- return "-";
- case Key.CapsLock:
- return "CapsLock";
- case Key.Scroll:
- return "ScrollLock";
- case Key.PrintScreen:
- return "PrintScreen";
- case Key.Return:
- return "Enter";
- case Key.PageDown:
- return "PageDown";
- case Key.PageUp:
- return "PageUp";
-
- // TODO: hardcoded temporary fix
- case Key.Oem3:
- return "ยด";
- case Key.OemPlus:
- return "=";
- case Key.OemOpenBrackets:
- return "[";
- case Key.Oem6:
- return "]";
- case Key.Oem5:
- return @"\";
- case Key.Oem1:
- return ";";
- case Key.OemQuotes:
- return "'";
- case Key.OemQuestion:
- return "/";
-
- default:
- return k.ToString();
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="argument"></param>
- public void CallFromSecondInstance(String argument)
- {
- if (argument == "/play")
- {
- PlayPause();
- }
- else if (argument == "/next")
- {
- MediaManager.Next();
- if (SettingsManager.MediaState != MediaState.Playing)
- MediaManager.Tick(null, null);
- }
- else if (argument == "/previous")
- {
- MediaManager.Previous();
- if (SettingsManager.MediaState != MediaState.Playing)
- MediaManager.Tick(null, null);
- }
- else
- {
- if (File.Exists(argument))
- {
- // file is a playlist
- if (PlaylistManager.IsSupported(argument))
- {
- PlaylistData pl = PlaylistManager.LoadPlaylist(argument);
- if (pl != null)
- {
- NavigationPane.SwitchNavigation("Playlist:" + pl.Name);
- if (pl.Tracks.Count > 0)
- {
- MediaManager.Load(pl.Tracks[0]);
- MediaManager.Play();
- }
- }
- }
-
- // file is a track
- else if (MediaManager.IsSupported(argument))
- {
- Open(argument);
- }
- }
- // TODO: bring to front
- }
- }
-
- /// <summary>
- /// Retrives the currently selected track list's source.
- /// </summary>
- /// <returns>The collection used as ItemsSource for the current track list</returns>
- public ObservableCollection<TrackData> GetCurrentTrackCollection()
- {
- if (SettingsManager.CurrentSelectedNavigation == "History")
- return SettingsManager.HistoryTracks;
- else if (SettingsManager.CurrentSelectedNavigation == "Queue")
- return SettingsManager.QueueTracks;
- else if (SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- {
- PlaylistData p = PlaylistManager.FindPlaylist(SettingsManager.CurrentSelectedNavigation.Split(new[] { ':' }, 2)[1]);
- if (p == null) return null;
- return p.Tracks;
- }
- else if (SettingsManager.CurrentSelectedNavigation == "Files")
- return SettingsManager.FileTracks;
- else if (SettingsManager.CurrentSelectedNavigation == "YouTube")
- return YouTubeManager.TrackSource;
- else
- return null;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <returns></returns>
- public ViewDetails GetCurrentTrackList()
- {
- if (SettingsManager.CurrentSelectedNavigation == "History")
- return HistoryTracks;
- else if (SettingsManager.CurrentSelectedNavigation == "Queue")
- return QueueTracks;
- else if (SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- return (ViewDetails)PlaylistTrackLists[SettingsManager.CurrentSelectedNavigation.Split(new[] { ':' }, 2)[1]];
- else if (SettingsManager.CurrentSelectedNavigation == "Files")
- return FileTracks;
- else if (SettingsManager.CurrentSelectedNavigation == "YouTube")
- return YouTubeContainer.YouTubeTracks;
- else
- return null;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <returns></returns>
- public ViewDetails GetActiveTrackList()
- {
- string can = SettingsManager.CurrentActiveNavigation;
- if (can == "History" || can == "Queue")
- can = SettingsManager.CurrentTrack == null ? "Files" : SettingsManager.CurrentTrack.Source;
-
- if (can.StartsWith("Playlist:"))
- {
- PlaylistData p = PlaylistManager.FindPlaylist(can.Split(new[] { ':' }, 2)[1]);
- if (p != null)
- return (ViewDetails)PlaylistTrackLists[p.Name];
- }
- if (can == "YouTube")
- return YouTubeContainer.YouTubeTracks;
- else
- return FileTracks;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="name"></param>
- public void OnPropertyChanged(string name)
- {
- if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name));
- }
-
- #endregion
-
- #region Private
-
- /// <summary>
- /// Play the currently selected track
- /// </summary>
- /// <param name="resume">Resume at the current position if the selected track is the CurrentTrack</param>
- private void Play(bool resume = false)
- {
- showMediaError = true;
-
- if (resume && SettingsManager.CurrentTrack != null)
- MediaManager.Play();
-
- else if (GetCurrentTrackList().SelectedItem is TrackData)
- {
- string pl = "";
-
- if (SettingsManager.CurrentSelectedNavigation == "Library")
- pl = "";
- else if (SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- pl = SettingsManager.CurrentSelectedNavigation.Split(new[]{':'},2)[1];
-
- TrackData track = GetCurrentTrackList().SelectedItem as TrackData;
- MediaManager.TrackCollection = GetCurrentTrackList().Items;
-
- if (SettingsManager.CurrentSelectedNavigation == "History")
- SettingsManager.HistoryIndex = SettingsManager.HistoryTracks.IndexOf(track);
- else
- SettingsManager.HistoryIndex = SettingsManager.HistoryTracks.Count;
-
- SettingsManager.CurrentActiveNavigation = SettingsManager.CurrentSelectedNavigation;
-
- if (SettingsManager.CurrentActiveNavigation.StartsWith("Playlist:"))
- PlaylistManager.CurrentPlaylist = SettingsManager.CurrentActiveNavigation.Split(new[] { ':' }, 2)[1];
- else
- PlaylistManager.CurrentPlaylist = "";
-
-
- MediaManager.Stop();
- MediaManager.Load(track);
- MediaManager.Play();
- }
- }
-
- /// <summary>
- /// Toggle the play and pause state
- /// </summary>
- private void PlayPause()
- {
- if (SettingsManager.MediaState == MediaState.Playing)
- SettingsManager.MediaState = MediaState.Paused;
- else
- SettingsManager.MediaState = MediaState.Playing;
- }
-
- /// <summary>
- /// Removes a set of tracks from a given collection of tracks.
- /// </summary>
- /// <param name="tracksToRemove">The tracks to remove</param>
- /// <param name="tracks">The collection from where to remove the tracks</param>
- private void RemoveTracks(SortedList<string, TrackData> tracksToRemove, ObservableCollection<TrackData> tracks)
- {
- for (int i = 0; i < tracks.Count; i++)
- {
- if (tracksToRemove.ContainsKey(tracks[i].Path))
- {
- tracks.RemoveAt(i--);
- }
- }
- }
-
- /// <summary>
- /// Removes a set of tracks from a given collection of tracks.
- /// </summary>
- /// <param name="tracksToRemove">The tracks to remove</param>
- /// <param name="tracks">The collection from where to remove the tracks</param>
- private void RemoveTracks(SortedList<string, TrackData> tracksToRemove, List<TrackData> tracks)
- {
- for (int i = 0; i < tracks.Count; i++)
- {
- if (tracksToRemove.ContainsKey(tracks[i].Path))
- {
- tracks.RemoveAt(i--);
- }
- }
- }
-
- /// <summary>
- /// Removes tracks with a given filename for a specific collection of tracks
- /// </summary>
- /// <param name="filename">The filename of the tracks to remove</param>
- /// <param name="tracks">The collection of tracks from which to remove</param>
- private void RemoveTrack(String filename, ObservableCollection<TrackData> tracks)
- {
- for (int i = 0; i < tracks.Count; i++)
- {
- if (tracks[i].Path == filename)
- {
- tracks.RemoveAt(i);
- break;
- }
- }
- }
-
- /// <summary>
- /// Removes tracks with a given filename for a specific list of tracks
- /// </summary>
- /// <param name="filename">The filename of the tracks to remove</param>
- /// <param name="tracks">The list of tracks from which to remove</param>
- private void RemoveTrack(String filename, List<TrackData> tracks)
- {
- for (int i = 0; i < tracks.Count; i++)
- {
- if (tracks[i].Path == filename)
- {
- tracks.RemoveAt(i);
- break;
- }
- }
- }
-
- /// <summary>
- /// Reapply the sorting on a tracklist
- /// </summary>
- /// <param name="tl">The tracklist to re-sort</param>
- /// <param name="paths">A list of the paths that was changed</param>
- private void ResortTracklist(ViewDetails tl, List<string> paths)
- {
- bool resort = false;
- foreach (TrackData t in SettingsManager.FileTracks)
- {
- if (paths.Contains(t.Path))
- {
- resort = true;
- break;
- }
- }
- if (resort)
- {
- if (tl.Items.SortDescriptions.Count > 0)
- {
- SortDescription sd = tl.Items.SortDescriptions[0];
- tl.Items.SortDescriptions.Remove(sd);
- tl.Items.SortDescriptions.Insert(0, sd);
- }
- }
- }
-
- /// <summary>
- /// Load a file and add it according to the AddPolicy and play
- /// it according to the PlayPolicy
- /// </summary>
- /// <param name="filename">The filename of the track</param>
- /// <param name="forcePlay">Whether or not to override the PlayPolicy</param>
- private void Open(string filename, bool forcePlay = false)
- {
- U.L(LogLevel.Debug, "MAIN", "Opening " + filename);
- OpenAddPolicy DoAdd = SettingsManager.OpenAddPolicy;
- OpenPlayPolicy DoPlay = SettingsManager.OpenPlayPolicy;
- TrackData track = null;
-
- // add track
- if (DoAdd == OpenAddPolicy.Library || DoAdd == OpenAddPolicy.LibraryAndPlaylist)
- {
- // add track to library if needed
- track = FilesystemManager.GetTrack(filename);
- if (track == null)
- {
- U.L(LogLevel.Debug, "MAIN", "Adding to collection");
- FilesystemManager.AddSource(new SourceData()
- {
- Data = filename,
- Include = true,
- HumanType = U.T("SourcesTypeFile"),
- Type = SourceType.File
- });
- track = FilesystemManager.GetTrack(filename);
- }
-
- if (track == null)
- U.L(LogLevel.Warning, "MAIN", "Could not add track to Library: " + filename);
-
- // add track to current playlist as well
- if (DoAdd == OpenAddPolicy.LibraryAndPlaylist && track != null)
- {
- if (SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- {
- U.L(LogLevel.Debug, "MAIN", "Adding to current playlist");
- String playlistName = SettingsManager.CurrentSelectedNavigation.Split(new[]{':'},2)[1];
- List<object> tracks = new List<object>();
- tracks.Add(track);
- PlaylistManager.AddToPlaylist(tracks, playlistName);
- }
- }
- }
-
- // play track
- if (DoPlay != OpenPlayPolicy.DoNotPlay || forcePlay)
- {
- // create track if it is null
- if (track == null)
- {
- U.L(LogLevel.Debug, "MAIN", "Creating track");
- track = FilesystemManager.CreateTrack(filename);
- if (track == null)
- {
- U.L(LogLevel.Warning, "MAIN", "Could not create track for: " + filename);
- return;
- }
- FilesystemManager.UpdateTrack(track);
- }
-
- if (DoPlay == OpenPlayPolicy.Play || forcePlay)
- {
- U.L(LogLevel.Debug, "MAIN", "Playing track");
- MediaManager.Stop();
- MediaManager.Load(track);
- MediaManager.Play();
-
- if (DoAdd == OpenAddPolicy.LibraryAndPlaylist && SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- SettingsManager.CurrentActiveNavigation = SettingsManager.CurrentSelectedNavigation;
- else if (DoAdd == OpenAddPolicy.Library)
- SettingsManager.CurrentActiveNavigation = "Library";
- }
-
- else if (DoPlay == OpenPlayPolicy.BackOfQueue)
- MediaManager.Queue(new List<TrackData>() { track });
-
- else if (DoPlay == OpenPlayPolicy.FrontOfQueue)
- MediaManager.Queue(new List<TrackData>() { track }, 0);
- }
- }
-
- /// <summary>
- /// Creates a playlist track list and navigation items
- /// </summary>
- /// <param name="playlist">The data for the playlist to create</param>
- /// <param name="select">Whether to select the playlist after it has been created</param>
- private void CreatePlaylist(PlaylistData playlist, bool select = true)
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- // create track list
- ViewDetails vd = new ViewDetails();
- Grid.SetRow(vd, 1);
- TrackContainer.Children.Add(vd);
- vd.ItemsSource = playlist.Tracks;
- playlist.Tracks.CollectionChanged +=
- new System.Collections.Specialized.NotifyCollectionChangedEventHandler(vd.ItemsSource_CollectionChanged);
- if (playlist.ListConfig == null)
- {
- ViewDetailsConfig vdc = SettingsManager.CreateListConfig();
- SettingsManager.InitViewDetailsConfig(vdc);
- vdc.HasNumber = true;
- playlist.ListConfig = vdc;
- }
- if (PlaylistTrackLists.ContainsKey(playlist.Name))
- PlaylistTrackLists.Remove(playlist.Name);
- PlaylistTrackLists.Add(playlist.Name, vd);
- vd.ContextMenu = listMenu;
- vd.Visibility = Visibility.Collapsed;
- vd.BorderThickness = new Thickness(0);
- vd.ItemsSource = playlist.Tracks;
- vd.Config = playlist.ListConfig;
- vd.FilterMatch = TrackList_SearchMatch;
- vd.SelectionChanged += new SelectionChangedEventHandler(TrackList_SelectionChanged);
- vd.MouseDoubleClick += new MouseButtonEventHandler(TrackList_MouseDoubleClick);
- vd.ContextMenuOpening += new ContextMenuEventHandler(TrackList_ContextMenuOpening);
- vd.FilesDropped += new FileDropEventHandler(TrackList_FilesDropped);
- vd.MoveItem += new MoveItemEventHandler(TrackList_MoveItem);
-
- // create the item in the navigation tree
- TreeViewItem item = new TreeViewItem();
- item.Selected += NavigationPane.Playlist_Selected;
- item.Drop += NavigationPane.Playlist_Drop;
- item.KeyDown += NavigationPlaylist_KeyDown;
- item.Tag = playlist.Name;
- item.Padding = new Thickness(8, 0, 0, 0);
-
- StackPanel sp = new StackPanel();
- sp.Orientation = System.Windows.Controls.Orientation.Horizontal;
-
- Image img = new Image();
- img.Source = Utilities.GetIcoImage("pack://application:,,,/GUI/Images/Icons/DiscAudio.ico", 16, 16);
- img.Width = 16;
- img.Height = 16;
- sp.Children.Add(img);
-
- EditableTextBlock etb = new EditableTextBlock();
- etb.EnteredEditMode += new EventHandler(EditableTextBlock_EnteredEditMode);
- etb.Text = playlist.Name;
- etb.Margin = new Thickness(5, 0, 5, 0);
- etb.Edited += NavigationPane.Playlist_Edited;
- sp.Children.Add(etb);
-
- item.Header = sp;
- item.ContextMenuOpening += new ContextMenuEventHandler(NavigationPane.Playlist_ContextMenuOpening);
- item.ContextMenu = NavigationPane.playlistMenu;
- NavigationPane.Playlists.Items.Insert(NavigationPane.Playlists.Items.Count - 1, item);
- if (select)
- item.Focus();
-
- // create list context menu items
- MenuItem miAdd = new MenuItem();
- miAdd.Header = playlist.Name;
- miAdd.Click += new RoutedEventHandler(listMenuAddToPlaylist_Click);
- listMenuAddToPlaylist.Visibility = System.Windows.Visibility.Visible;
- listMenuAddToPlaylist.Items.Insert(listMenuAddToPlaylist.Items.Count - 1, miAdd);
-
- MenuItem miDel = new MenuItem();
- miDel.Header = playlist.Name;
- miDel.Click += new RoutedEventHandler(listMenuRemoveFromPlaylist_Click);
- listMenuRemoveFromPlaylist.Visibility = System.Windows.Visibility.Visible;
- listMenuRemoveFromPlaylist.Items.Add(miDel);
-
- PlaybackControls.Search.AddPlaylist(playlist);
- }));
- }
-
- /// <summary>
- /// Updates the visibility of a given element according to the settings
- /// </summary>
- /// <param name="element">The element to update (menubar or details)</param>
- private void UpdateVisibility(string element)
- {
- switch (element)
- {
- case "menubar":
- bool mv = SettingsManager.MenuBarVisibile;
- showMenuMenuBar.IsChecked = mv;
- MenuItemViewMenuBar.IsChecked = mv;
- MenuBar.Visibility = mv ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
- break;
-
- case "details":
- bool dv = SettingsManager.DetailsPaneVisible;
- showMenuDetailsPane.IsChecked = dv;
- MenuItemViewDetailsPane.IsChecked = dv;
- DetailsRow.MinHeight = (dv ? 80 : 0);
- DetailsRow.Height = new GridLength((dv ? SettingsManager.DetailsPaneHeight : 0));
- DetailsPane.Visibility = dv ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
- HorizontalSplitter.Visibility = dv ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
- break;
- }
- }
-
- /// <summary>
- /// Updates the strings around the GUI, that are hardcoded, according to the current Language
- /// </summary>
- private void UpdateGUIStrings()
- {
- // change column headers of list views
- foreach (ViewDetailsColumn c in SettingsManager.SourceListConfig.Columns)
- {
- if (c.Binding == "HumanType") c.Text = U.T("ColumnType");
- else if (c.Binding == "Data") c.Text = U.T("ColumnLocation");
- }
- foreach (ViewDetailsColumn c in SettingsManager.YouTubeListConfig.Columns)
- {
- if (c.Binding == "Artist") c.Text = U.T("ColumnArtist");
- else if (c.Binding == "Title") c.Text = U.T("ColumnTitle");
- else if (c.Binding == "Path") c.Text = U.T("ColumnPath");
- else if (c.Binding == "Length") c.Text = U.T("ColumnLength");
- }
- foreach (ViewDetailsColumn c in SettingsManager.FileListConfig.Columns)
- {
- if (c.Binding == "Artist") c.Text = U.T("ColumnArtist");
- else if (c.Binding == "Title") c.Text = U.T("ColumnTitle");
- else if (c.Binding == "Album") c.Text = U.T("ColumnAlbum");
- else if (c.Binding == "Genre") c.Text = U.T("ColumnGenre");
- else if (c.Binding == "LastPlayed") c.Text = U.T("ColumnLastPlayed");
- else if (c.Binding == "Length") c.Text = U.T("ColumnLength");
- else if (c.Binding == "PlayCount") c.Text = U.T("ColumnPlayCount");
- else if (c.Binding == "Path") c.Text = U.T("ColumnPath");
- else if (c.Binding == "Track") c.Text = U.T("ColumnTrack");
- else if (c.Binding == "Year") c.Text = U.T("ColumnYear");
- }
- foreach (ViewDetailsColumn c in SettingsManager.QueueListConfig.Columns)
- {
- if (c.Binding == "Artist") c.Text = U.T("ColumnArtist");
- else if (c.Binding == "Title") c.Text = U.T("ColumnTitle");
- else if (c.Binding == "Album") c.Text = U.T("ColumnAlbum");
- else if (c.Binding == "Genre") c.Text = U.T("ColumnGenre");
- else if (c.Binding == "LastPlayed") c.Text = U.T("ColumnLastPlayed");
- else if (c.Binding == "Length") c.Text = U.T("ColumnLength");
- else if (c.Binding == "PlayCount") c.Text = U.T("ColumnPlayCount");
- else if (c.Binding == "Path") c.Text = U.T("ColumnPath");
- else if (c.Binding == "Track") c.Text = U.T("ColumnTrack");
- else if (c.Binding == "Year") c.Text = U.T("ColumnYear");
- }
- foreach (ViewDetailsColumn c in SettingsManager.HistoryListConfig.Columns)
- {
- if (c.Binding == "Artist") c.Text = U.T("ColumnArtist");
- else if (c.Binding == "Title") c.Text = U.T("ColumnTitle");
- else if (c.Binding == "Album") c.Text = U.T("ColumnAlbum");
- else if (c.Binding == "Genre") c.Text = U.T("ColumnGenre");
- else if (c.Binding == "LastPlayed") c.Text = U.T("ColumnPlayed");
- else if (c.Binding == "Length") c.Text = U.T("ColumnLength");
- else if (c.Binding == "PlayCount") c.Text = U.T("ColumnPlayCount");
- else if (c.Binding == "Path") c.Text = U.T("ColumnPath");
- else if (c.Binding == "Track") c.Text = U.T("ColumnTrack");
- else if (c.Binding == "Year") c.Text = U.T("ColumnYear");
- }
- foreach (PlaylistData p in SettingsManager.Playlists)
- foreach (ViewDetailsColumn c in p.ListConfig.Columns)
- {
- if (c.Binding == "Artist") c.Text = U.T("ColumnArtist");
- else if (c.Binding == "Title") c.Text = U.T("ColumnTitle");
- else if (c.Binding == "Album") c.Text = U.T("ColumnAlbum");
- else if (c.Binding == "Genre") c.Text = U.T("ColumnGenre");
- else if (c.Binding == "LastPlayed") c.Text = U.T("ColumnPlayed");
- else if (c.Binding == "Length") c.Text = U.T("ColumnLength");
- else if (c.Binding == "PlayCount") c.Text = U.T("ColumnPlayCount");
- else if (c.Binding == "Path") c.Text = U.T("ColumnPath");
- else if (c.Binding == "Track") c.Text = U.T("ColumnTrack");
- else if (c.Binding == "Year") c.Text = U.T("ColumnYear");
- }
-
- // change source types
- foreach (SourceData s in SettingsManager.Sources)
- switch (s.Type)
- {
- case SourceType.File:
- s.HumanType = U.T("SourcesTypeFile");
- break;
-
- case SourceType.Folder:
- s.HumanType = U.T("SourcesTypeFolder");
- break;
-
- case SourceType.Library:
- s.HumanType = U.T("SourcesTypeLibrary");
- break;
- }
-
- // change shortcuts
- ControlPanel.GlobalLabel.Content = U.T("ShortcutGlobal");
- foreach (TextBlock t in ControlPanel.ShortcutTitles)
- t.Text = U.T((string)t.Tag);
- foreach (TextBlock t in ControlPanel.ShortcutDescriptions)
- t.Text = U.T((string)t.Tag);
- foreach (Label l in ControlPanel.ShortcutLabels)
- l.Content = U.T((string)l.Tag);
-
- // change menus
- trayMenuShow.Header = U.T("TrayShow");
- trayMenuPlay.Header = U.T("TrayPlay");
- trayMenuNext.Header = U.T("TrayNext");
- trayMenuPrev.Header = U.T("TrayPrev");
- trayMenuExit.Header = U.T("TrayExit");
- taskbarPlay.Tooltip = U.T("TaskbarPlay");
- taskbarNext.Tooltip = U.T("TaskbarNext");
- taskbarPrev.Tooltip = U.T("TaskbarPrev");
- jumpTaskPlay.Title = U.T("JumpPlay", "Title");
- jumpTaskNext.Title = U.T("JumpNext", "Title");
- jumpTaskPrev.Title = U.T("JumpPrev", "Title");
- jumpTaskPlay.Description = U.T("JumpPlay", "Description");
- jumpTaskNext.Description = U.T("JumpNext", "Description");
- jumpTaskPrev.Description = U.T("JumpPrev", "Description");
- listMenuAddToPlaylist.Header = U.T("MenuAddToPlaylist", "Header");
- listMenuAddToNew.Header = U.T("MenuCreateNew", "Header");
- listMenuDelete.Header = U.T("MenuDelete");
- listMenuInfo.Header = U.T("MenuInfo");
- listMenuPlay.Header = U.T("MenuPlay");
- listMenuQueue.Header = U.T("MenuQueue");
- listMenuRemove.Header = U.T("MenuRemove");
- listMenuRemoveFromPlaylist.Header = U.T("MenuRemoveFromPlaylist", "Header");
- listMenuWatchOnYouTube.Header = U.T("MenuWatchOnYouTube");
- listMenuShareSong.Header = U.T("MenuShareSong");
- addMenuFile.Header = U.T("ToolbarAddTrack");
- addMenuFolder.Header = U.T("ToolbarAddFolder");
- addMenuPlaylist.Header = U.T("ToolbarAddPlaylist");
- showMenuDetailsPane.Header = U.T("ToolbarDetailsPane");
- showMenuMenuBar.Header = U.T("ToolbarMenuBar");
- toolsMenuExporter.Header = U.T("ToolbarExporter");
- toolsMenuImporter.Header = U.T("ToolbarImporter");
- toolsMenuGenerate.Header = U.T("ToolbarGeneratePlaylist");
- NavigationPane.playlistMenuRemove.Header = U.T("MenuRemovePlaylist");
- NavigationPane.playlistMenuRename.Header = U.T("MenuRenamePlaylist");
- NavigationPane.playlistMenuSave.Header = U.T("MenuSavePlaylist");
- NavigationPane.playlistMenuShare.Header = U.T("MenuSharePlaylist");
- NavigationPane.CreateNewPlaylistETB.Text = U.T("NavigationCreateNew");
- ControlPanel.menuRemove.Header = U.T("MenuRemove");
-
- // change tracklist header
- string csn = SettingsManager.CurrentSelectedNavigation;
- switch (csn)
- {
- case "Files":
- InfoPaneTitle.Text = U.T("NavigationFilesTitle");
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)LibraryTime)); ;
- InfoPaneTracks.Text = SettingsManager.FileTracks.Count.ToString() + " " + U.T("HeaderTracks");
- break;
-
- case "Queue":
- InfoPaneTitle.Text = U.T("NavigationQueueTitle");
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)QueueTime)); ;
- InfoPaneTracks.Text = SettingsManager.QueueTracks.Count.ToString() + " " + U.T("HeaderTracks");
- break;
-
- case "History":
- InfoPaneTitle.Text = U.T("NavigationHistoryTitle");
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)HistoryTime)); ;
- InfoPaneTracks.Text = SettingsManager.HistoryTracks.Count.ToString() + " " + U.T("HeaderTracks");
- break;
-
- default:
- if (csn.StartsWith("Playlist:"))
- {
- PlaylistData p = PlaylistManager.FindPlaylist(csn.Split(new[] { ':' }, 2)[1]);
- InfoPaneTitle.Text = U.T("NavigationPlaylistTitle") + " '" + p.Name + "'";
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)p.Time)); ;
- InfoPaneTracks.Text = p.Tracks.Count.ToString() + " " + U.T("HeaderTracks");
- }
- break;
- }
- }
-
- /// <summary>
- /// Will repaint the glass effect behind the playback pane.
- /// </summary>
- private void RefreshGlassEffect()
- {
- try
- {
- Dwm.Glass[this].Enabled = true;
- Thickness foo = new Thickness(1, 75, 1, 1);
- Dwm.Glass[this].Margins = foo;
- Background = Brushes.Transparent;
- glassEffect = true;
- }
- catch (Exception e)
- {
- U.L(LogLevel.Warning, "MAIN", "Could not set glass effect: " + e.Message);
- if (System.Windows.Forms.VisualStyles.VisualStyleInformation.DisplayName == "")
- Background = SystemColors.ControlBrush;
- else
- Background = SystemColors.GradientActiveCaptionBrush;
- glassEffect = false;
- }
- }
-
- /// <summary>
- /// Initializes the GUI
- /// </summary>
- private void InitGUI()
- {
- U.L(LogLevel.Debug, "MAIN", "Init settings manager");
- SettingsManager.Initialize();
-
- U.L(LogLevel.Debug, "MAIN", "Init service manager");
- ServiceManager.Initialize();
-
- // create playlists
- ThreadStart PlaylistThread = delegate()
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- if (SettingsManager.CurrentSelectedNavigation == "YouTube")
- NavigationPane.Youtube.Focus();
- else if (SettingsManager.CurrentSelectedNavigation == "Queue")
- NavigationPane.Queue.Focus();
- else if (SettingsManager.CurrentSelectedNavigation == "History")
- NavigationPane.History.Focus();
- else if (!SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- NavigationPane.Files.Focus();
-
- // create playlists
- PlaylistManager.Initialize();
-
- foreach (PlaylistData playlist in SettingsManager.Playlists)
- CreatePlaylist(playlist, false);
-
- PlaylistManager.PlaylistModified += new ModifiedEventHandler(PlaylistManager_PlaylistModified);
- PlaylistManager.PlaylistRenamed += new RenamedEventHandler(PlaylistManager_PlaylistRenamed);
-
- // if csn == playlist: select
- if (SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- {
- string name = SettingsManager.CurrentSelectedNavigation.Split(new[] { ':' }, 2)[1];
- foreach (TreeViewItem tvi in NavigationPane.Playlists.Items)
- {
- if ((string)tvi.Tag == name)
- {
- tvi.Focus();
- break;
- }
- }
- }
- }));
- };
-
- ThreadStart GUIThread = delegate()
- {
- // init media manager
- ThreadStart MediaManagerThread = delegate()
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- MediaManager.Initialize(new WindowInteropHelper(this).Handle);
- MediaManager.Browser = NowPlayingContainer.Browser;
-
- // load the track collection
- if (SettingsManager.CurrentActiveNavigation == "Queue")
- MediaManager.TrackCollection = QueueTracks.Items;
- else if (SettingsManager.CurrentActiveNavigation == "History")
- MediaManager.TrackCollection = HistoryTracks.Items;
- else if (SettingsManager.CurrentActiveNavigation == "YouTube")
- MediaManager.TrackCollection = YouTubeContainer.YouTubeTracks.Items;
- else if (SettingsManager.CurrentActiveNavigation.StartsWith("Playlist:"))
- {
- string pname = SettingsManager.CurrentActiveNavigation.Split(new[] { ':' }, 2)[1];
- ViewDetails p = (ViewDetails)PlaylistTrackLists[pname];
- if (p == null)
- MediaManager.TrackCollection = FileTracks.Items;
- else
- MediaManager.TrackCollection = p.Items;
- }
- else
- MediaManager.TrackCollection = FileTracks.Items;
-
- // check if we have any command line arguments
- String[] arguments = Environment.GetCommandLineArgs();
- if (arguments.Length > 1)
- {
- if (arguments[1] == "/play") MediaManager.Play();
- else if (arguments[1] == "/pause") MediaManager.Pause();
- else if (arguments[1] == "/stop") MediaManager.Stop();
- else if (arguments[1] == "/next") MediaManager.Next();
- else if (arguments[1] == "/previous") MediaManager.Previous();
-
- else if (File.Exists(arguments[1]) && MediaManager.IsSupported(arguments[1]))
- {
- Open(arguments[1], true);
- }
- }
- }));
- };
-
- // init upgrade manager
- ThreadStart UpgradeManagerThread = delegate()
- {
- UpgradeManager.Initialize(new TimeSpan(0, 60, 0));
- UpgradeManager.Probe(null, null);
- };
-
- // init filesystem manager
- ThreadStart FilesystemManagerThread = delegate()
- {
- FilesystemManager.Initialize();
-
- if (SettingsManager.FirstRun)
- {
- FilesystemManager.ScanLibraries(true, false);
- if (SettingsManager.Sources.Count == 0)
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- Welcome dialog = new Welcome();
- dialog.ShowDialog();
- FilesystemManager.ScanSources();
- }));
- }
-
- SettingsManager.FirstRun = false;
- }
- else
- FilesystemManager.ScanLibraries(true);
- };
-
- // calculate play time
- ThreadStart PTThread = delegate()
- {
- LibraryTime = 0;
- QueueTime = 0;
- HistoryTime = 0;
- if (SettingsManager.FileTracks != null)
- foreach (TrackData track in SettingsManager.FileTracks)
- LibraryTime += track.RawLength;
- if (SettingsManager.QueueTracks != null)
- foreach (TrackData track in SettingsManager.QueueTracks)
- QueueTime += track.RawLength;
- if (SettingsManager.HistoryTracks != null)
- foreach (TrackData track in SettingsManager.HistoryTracks)
- HistoryTime += track.RawLength;
- };
-
- Thread mm_thread = new Thread(MediaManagerThread);
- Thread um_thread = new Thread(UpgradeManagerThread);
- Thread fm_thread = new Thread(FilesystemManagerThread);
- Thread pt_thread = new Thread(PTThread);
- mm_thread.Name = "Init Media Manager";
- um_thread.Name = "Init Upgrade Manager";
- fm_thread.Name = "Init Filesystem Manager";
- pt_thread.Name = "Playing Time Thread";
- mm_thread.Priority = ThreadPriority.BelowNormal;
- um_thread.Priority = ThreadPriority.BelowNormal;
- fm_thread.Priority = ThreadPriority.BelowNormal;
- pt_thread.Priority = ThreadPriority.BelowNormal;
- mm_thread.Start();
- um_thread.Start();
- fm_thread.Start();
- pt_thread.Start();
-
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- FileTracks.Config = SettingsManager.FileListConfig;
- HistoryTracks.Config = SettingsManager.HistoryListConfig;
- QueueTracks.Config = SettingsManager.QueueListConfig;
- ControlPanel.SourceList.Config = SettingsManager.SourceListConfig;
- YouTubeContainer.YouTubeTracks.Config = SettingsManager.YouTubeListConfig;
-
- FileTracks.ItemsSource = SettingsManager.FileTracks;
- QueueTracks.ItemsSource = SettingsManager.QueueTracks;
- HistoryTracks.ItemsSource = SettingsManager.HistoryTracks;
- ControlPanel.SourceList.ItemsSource = SettingsManager.Sources;
- YouTubeContainer.Search(SettingsManager.YouTubeListConfig.Filter);
- }));
-
- SettingsManager.FileTracks.CollectionChanged += new NotifyCollectionChangedEventHandler(FileTracks.ItemsSource_CollectionChanged);
- SettingsManager.QueueTracks.CollectionChanged += new NotifyCollectionChangedEventHandler(QueueTracks.ItemsSource_CollectionChanged);
- SettingsManager.HistoryTracks.CollectionChanged += new NotifyCollectionChangedEventHandler(HistoryTracks.ItemsSource_CollectionChanged);
- SettingsManager.QueueTracks.CollectionChanged += new NotifyCollectionChangedEventHandler(QueueTracks_CollectionChanged);
- SettingsManager.HistoryTracks.CollectionChanged += new NotifyCollectionChangedEventHandler(HistoryTracks_CollectionChanged);
- SettingsManager.FileTracks.CollectionChanged += new NotifyCollectionChangedEventHandler(LibraryTracks_CollectionChanged);
-
- jumpTaskPlay = new JumpTask()
- {
- Title = U.T("JumpPlay", "Title"),
- Arguments = "/play",
- Description = U.T("JumpPlay", "Description"),
- IconResourceIndex = -1,
- ApplicationPath = Assembly.GetEntryAssembly().CodeBase,
- };
-
- jumpTaskNext = new JumpTask()
- {
- Title = U.T("JumpNext", "Title"),
- Arguments = "/next",
- Description = U.T("JumpNext", "Description"),
- IconResourceIndex = -1,
- ApplicationPath = Assembly.GetEntryAssembly().CodeBase,
- };
-
- jumpTaskPrev = new JumpTask()
- {
- Title = U.T("JumpPrev", "Title"),
- Arguments = "/previous",
- Description = U.T("JumpPrev", "Description"),
- IconResourceIndex = -1,
- ApplicationPath = Assembly.GetEntryAssembly().CodeBase,
- };
-
- jumpList = new JumpList();
- jumpList.JumpItems.Add(jumpTaskPlay);
- jumpList.JumpItems.Add(jumpTaskNext);
- jumpList.JumpItems.Add(jumpTaskPrev);
- jumpList.ShowRecentCategory = true;
- jumpList.ShowFrequentCategory = true;
-
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- PlaybackControls.VolumeSlide.Value = SettingsManager.Volume;
-
- NavigationColumn.Width = new GridLength(SettingsManager.NavigationPaneWidth);
- double h = SettingsManager.DetailsPaneHeight;
- DetailsRow.Height = new GridLength(h);
-
- UpdateVisibility("menubar");
- UpdateVisibility("details");
-
- ControlPanel.InitShortcuts();
- JumpList.SetJumpList(Application.Current, jumpList);
-
- UpdateGUIStrings();
- }));
-
- };
-
- Thread pl_thread = new Thread(PlaylistThread);
- Thread gui_thread = new Thread(GUIThread);
- pl_thread.Name = "Init Playlist Manager";
- gui_thread.Name = "Init managers and GUI";
- pl_thread.Priority = ThreadPriority.BelowNormal;
- gui_thread.Priority = ThreadPriority.BelowNormal;
- pl_thread.Start();
- gui_thread.Start();
- }
-
- #endregion
-
- #region Event handlers
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- U.L(LogLevel.Debug, "MAIN", "Loaded");
-
- System.Windows.Forms.Application.EnableVisualStyles();
-
- WindowState = (WindowState)Enum.Parse(typeof(WindowState), SettingsManager.WinState);
-
- kListener.KeyDown += new RawKeyEventHandler(KListener_KeyDown);
- kListener.KeyUp += new RawKeyEventHandler(KListener_KeyUp);
-
- addMenu = new ContextMenu();
- showMenu = new ContextMenu();
- toolsMenu = new ContextMenu();
-
- addMenuFile = new MenuItem();
- addMenuFile.Header = U.T("ToolbarAddTrack");
- addMenuFile.Click += AddFile_Clicked;
-
- addMenuFolder = new MenuItem();
- addMenuFolder.Header = U.T("ToolbarAddFolder");
- addMenuFolder.Click += AddFolder_Clicked;
-
- addMenuPlaylist = new MenuItem();
- addMenuPlaylist.Header = U.T("ToolbarAddPlaylist");
- addMenuPlaylist.Click += OpenPlaylist_Clicked;
-
- showMenuDetailsPane = new MenuItem();
- showMenuDetailsPane.Header = U.T("ToolbarDetailsPane");
- showMenuDetailsPane.IsCheckable = true;
- showMenuDetailsPane.Click += ToggleDetailsPane;
-
- showMenuMenuBar = new MenuItem();
- showMenuMenuBar.Header = U.T("ToolbarMenuBar");
- showMenuMenuBar.IsCheckable = true;
- showMenuMenuBar.Click += ToggleMenuBar;
-
- toolsMenuImporter = new MenuItem();
- toolsMenuImporter.Header = U.T("ToolbarImporter");
- toolsMenuImporter.Click += Importer_Clicked;
-
- toolsMenuExporter = new MenuItem();
- toolsMenuExporter.Header = U.T("ToolbarExporter");
- toolsMenuExporter.Click += Exporter_Clicked;
-
- toolsMenuGenerate = new MenuItem();
- toolsMenuGenerate.Header = U.T("ToolbarGeneratePlaylist");
- toolsMenuGenerate.Click += GeneratePlaylist_Clicked;
-
- addMenu.Items.Add(addMenuFile);
- addMenu.Items.Add(addMenuFolder);
- addMenu.Items.Add(addMenuPlaylist);
- showMenu.Items.Add(showMenuMenuBar);
- showMenu.Items.Add(showMenuDetailsPane);
- toolsMenu.Items.Add(toolsMenuImporter);
- toolsMenu.Items.Add(toolsMenuExporter);
- toolsMenu.Items.Add(toolsMenuGenerate);
- addMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
- showMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
- toolsMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
-
- listMenuAddToPlaylist.Header = U.T("MenuAddToPlaylist", "Header");
- listMenuDelete.Header = U.T("MenuDelete");
- listMenuDelete.Click += new RoutedEventHandler(listMenuDelete_Click);
- listMenuInfo.Header = U.T("MenuInfo");
- listMenuInfo.Click += new RoutedEventHandler(listMenuInfo_Click);
- listMenuPlay.Header = U.T("MenuPlay");
- listMenuPlay.Click += new RoutedEventHandler(listMenuPlay_Click);
- listMenuWatchOnYouTube.Header = U.T("MenuWatchOnYouTube");
- listMenuWatchOnYouTube.Click += new RoutedEventHandler(listMenuWatchOnYouTube_Click);
- listMenuQueue.Header = U.T("MenuQueue");
- listMenuQueue.Click += new RoutedEventHandler(listMenuQueue_Click);
- listMenuRemove.Header = U.T("MenuRemove");
- listMenuRemove.Click += new RoutedEventHandler(listMenuRemove_Click);
- listMenuRemoveFromPlaylist.Header = U.T("MenuRemoveFromPlaylist", "Header");
- listMenuRemoveFromPlaylist.Visibility = System.Windows.Visibility.Collapsed;
-
- listMenuAddToNew = new MenuItem();
- listMenuAddToNew.Header = U.T("MenuCreateNew", "Header");
- listMenuAddToNew.FontStyle = FontStyles.Italic;
- listMenuAddToNew.Click += new RoutedEventHandler(listMenuAddToPlaylist_Click);
- listMenuAddToPlaylist.Items.Add(listMenuAddToNew);
-
- listMenu.Items.Add(listMenuPlay);
- listMenu.Items.Add(listMenuQueue);
- listMenu.Items.Add(new Separator());
- listMenu.Items.Add(listMenuAddToPlaylist);
- listMenu.Items.Add(listMenuRemoveFromPlaylist);
- listMenu.Items.Add(listMenuRemove);
- listMenu.Items.Add(listMenuDelete);
- listMenu.Items.Add(new Separator());
- listMenu.Items.Add(listMenuWatchOnYouTube);
- listMenu.Items.Add(listMenuInfo);
-
- PlaylistTrackLists = new Hashtable();
-
- //// TODO: remove all these lines
- ////FileTracks.ParentWindow = this;
- ////QueueTracks.ParentWindow = this;
- ////HistoryTracks.ParentWindow = this;
- ControlPanel.ParentWindow = this;
- NavigationPane.ParentWindow = this;
- PlaybackControls.ParentWindow = this;
-
- FileTracks.ContextMenu = listMenu;
- HistoryTracks.ContextMenu = listMenu;
- QueueTracks.ContextMenu = listMenu;
- YouTubeContainer.YouTubeTracks.ContextMenu = listMenu;
-
- YouTubeContainer.YouTubeTracks.MouseDoubleClick += new MouseButtonEventHandler(TrackList_MouseDoubleClick);
- YouTubeContainer.YouTubeTracks.SelectionChanged += new SelectionChangedEventHandler(TrackList_SelectionChanged);
- YouTubeContainer.YouTubeTracks.ContextMenuOpening += new ContextMenuEventHandler(TrackList_ContextMenuOpening);
- YouTubeContainer.YouTubeTracks.MoveItem += new MoveItemEventHandler(TrackList_MoveItem);
-
- sourceModifiedDelay.Tick += new EventHandler(SourceModifiedDelay_Tick);
- sourceModifiedDelay.Interval = new TimeSpan(0, 0, 0, 1, 500);
-
- SettingsManager.PropertyChanged += new PropertyChangedWithValuesEventHandler(SettingsManager_PropertyChanged);
-
- NavigationPane.CreateNewPlaylistETB.EnteredEditMode += new EventHandler(EditableTextBlock_EnteredEditMode);
-
- U.ListenForShortcut = true;
-
- SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
-
- String defaultAlbumArt = "/GUI/Images/AlbumArt/Default.jpg";
-
- //// rough detection of aero vs classic
- //// you'll se a lot more of these around the code
- if (System.Windows.Forms.VisualStyles.VisualStyleInformation.DisplayName == "")
- {
- // applying classic theme
- SolidColorBrush scb = (SolidColorBrush)FindResource("DetailsPaneKey");
- scb.Color = SystemColors.ControlTextColor;
- scb = (SolidColorBrush)FindResource("DetailsPaneValue");
- scb.Color = SystemColors.ControlTextColor;
- scb = (SolidColorBrush)FindResource("InfoPaneTitle");
- scb.Color = SystemColors.ControlTextColor;
- scb = (SolidColorBrush)FindResource("InfoPaneText");
- scb.Color = SystemColors.ControlTextColor;
-
- MainFrame.BorderBrush = SystemColors.ControlBrush;
- MainFrame.Background = SystemColors.ControlBrush;
- MainContainer.Background = SystemColors.ControlBrush;
- InfoPane.Background = SystemColors.WindowBrush;
- VerticalSplitter.Background = SystemColors.ControlBrush;
-
- TopToolbar.Style = null;
- AddButton.Style = (Style)FindResource("ClassicToolbarButtonStyle");
- ShowButton.Style = (Style)FindResource("ClassicToolbarButtonStyle");
- ToolsButton.Style = (Style)FindResource("ClassicToolbarButtonStyle");
- EqualizerButton.Style = (Style)FindResource("ClassicToolbarButtonStyle");
- PreferencesButton.Style = (Style)FindResource("ClassicToolbarButtonStyle");
- HelpButton.Style = (Style)FindResource("ClassicToolbarSmallButtonStyle");
- DetailsPane.Style = (Style)FindResource("ClassicDetailsPaneStyle");
-
- OuterBottomRight.BorderBrush = SystemColors.ControlLightLightBrush;
- OuterTopLeft.BorderBrush = SystemColors.ControlDarkBrush;
- InnerBottomRight.BorderBrush = SystemColors.ControlDarkBrush;
- InnerTopLeft.BorderBrush = SystemColors.ControlLightLightBrush;
-
- ControlPanel.SourceTitle.Style = (Style)FindResource("ClassicControlPanelTitleStyle");
- ControlPanel.AboutTitle.Style = (Style)FindResource("ClassicControlPanelTitleStyle");
- ControlPanel.ShortcutTitle.Style = (Style)FindResource("ClassicControlPanelTitleStyle");
- ControlPanel.GeneralTitle.Style = (Style)FindResource("ClassicControlPanelTitleStyle");
- defaultAlbumArt = "/GUI/Images/AlbumArt/Classic.jpg";
- }
-
- // create system tray icon
- trayIcon = (TaskbarIcon)FindResource("NotifyIcon");
- trayIcon.TrayToolTip = new TrayToolTip(this);
- trayIcon.TrayLeftMouseUp += TaskbarClicked;
- trayMenu = new ContextMenu();
- trayMenuShow = new MenuItem();
- trayMenuExit = new MenuItem();
- trayMenuPlay = new MenuItem();
- trayMenuNext = new MenuItem();
- trayMenuPrev = new MenuItem();
- trayMenuShow.Header = U.T("TrayShow");
- trayMenuExit.Header = U.T("TrayExit");
- trayMenuPlay.Header = U.T("TrayPlay");
- trayMenuNext.Header = U.T("TrayNext");
- trayMenuPrev.Header = U.T("TrayPrev");
- trayMenuShow.Click += TrayShow_Clicked;
- trayMenuExit.Click += TrayExit_Clicked;
- trayMenuPlay.Click += TrayPlayPause_Clicked;
- trayMenuNext.Click += TrayNext_Clicked;
- trayMenuPrev.Click += TrayPrevious_Clicked;
- trayMenu.Items.Add(trayMenuShow);
- trayMenu.Items.Add(new Separator());
- trayMenu.Items.Add(trayMenuPlay);
- trayMenu.Items.Add(trayMenuNext);
- trayMenu.Items.Add(trayMenuPrev);
- trayMenu.Items.Add(new Separator());
- trayMenu.Items.Add(trayMenuExit);
- trayIcon.ContextMenu = trayMenu;
-
- //// create glass effect
- RefreshGlassEffect();
-
- System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal);
-
- //// create thumbnail buttons
- taskbarPrev = new Microsoft.WindowsAPICodePack.Taskbar.ThumbnailToolbarButton(Properties.Resources.Previous, U.T("TaskbarPrev"));
- taskbarPrev.Enabled = true;
- taskbarPrev.Click += TaskbarPrevious_Clicked;
- taskbarPlay = new Microsoft.WindowsAPICodePack.Taskbar.ThumbnailToolbarButton(Properties.Resources.Play, U.T("TaskbarPlay"));
- taskbarPlay.Enabled = true;
- taskbarPlay.Click += TaskbarPlayPause_Clicked;
- taskbarNext = new Microsoft.WindowsAPICodePack.Taskbar.ThumbnailToolbarButton(Properties.Resources.Next, U.T("TaskbarNext"));
- taskbarNext.Enabled = true;
- taskbarNext.Click += TaskbarNext_Clicked;
- Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.ThumbnailToolbars.AddButtons(
- new WindowInteropHelper(this).Handle,
- new Microsoft.WindowsAPICodePack.Taskbar.ThumbnailToolbarButton[] { taskbarPrev, taskbarPlay, taskbarNext }
- );
-
- resortDelay.Interval = new TimeSpan(0, 0, 0, 0, 500);
- resortDelay.Tick += new EventHandler(ResortDelay_Tick);
-
- FilesystemManager.SourceModified += new SourceModifiedEventHandler(FilesystemManager_SourceModified);
- FilesystemManager.TrackModified += new PropertyChangedEventHandler(FilesystemManager_TrackModified);
- FilesystemManager.PathModified += new PathModifiedEventHandler(FilesystemManager_PathModified);
- FilesystemManager.PathRenamed += new RenamedEventHandler(FilesystemManager_PathRenamed);
- FilesystemManager.ProgressChanged += new ProgressChangedEventHandler(FilesystemManager_ProgressChanged);
- FilesystemManager.SourceAdded += new SourcesModifiedEventHandler(FilesystemManager_SourceAdded);
- FilesystemManager.SourceRemoved += new SourcesModifiedEventHandler(FilesystemManager_SourceRemoved);
- FilesystemManager.DefaultAlbumArt = defaultAlbumArt;
-
- MediaManager.TrackSwitched += new TrackSwitchedEventHandler(MediaManager_TrackSwitched);
- MediaManager.ConnectionProblem += new EventHandler(MediaManager_ConnectionProblem);
- MediaManager.SearchMatch = TrackList_SearchMatch;
-
- UpgradeManager.Checked += new EventHandler(UpgradeManager_Checked);
- UpgradeManager.ErrorOccured += new ErrorEventHandler(UpgradeManager_ErrorOccured);
- UpgradeManager.ProgressChanged += new ProgressChangedEventHandler(UpgradeManager_ProgressChanged);
- UpgradeManager.Upgraded += new EventHandler(UpgradeManager_Upgraded);
- UpgradeManager.UpgradeFound += new EventHandler(UpgradeManager_UpgradeFound);
-
- FileTracks.SelectionChanged += new SelectionChangedEventHandler(TrackList_SelectionChanged);
- FileTracks.MouseDoubleClick += new MouseButtonEventHandler(TrackList_MouseDoubleClick);
- FileTracks.ContextMenuOpening += new ContextMenuEventHandler(TrackList_ContextMenuOpening);
- FileTracks.FilesDropped += new FileDropEventHandler(TrackList_FilesDropped);
- FileTracks.MoveItem += new MoveItemEventHandler(TrackList_MoveItem);
- FileTracks.FilterMatch = TrackList_SearchMatch;
-
- HistoryTracks.SelectionChanged += new SelectionChangedEventHandler(TrackList_SelectionChanged);
- HistoryTracks.MouseDoubleClick += new MouseButtonEventHandler(TrackList_MouseDoubleClick);
- HistoryTracks.ContextMenuOpening += new ContextMenuEventHandler(TrackList_ContextMenuOpening);
- HistoryTracks.FilesDropped += new FileDropEventHandler(TrackList_FilesDropped);
- HistoryTracks.MoveItem += new MoveItemEventHandler(TrackList_MoveItem);
- HistoryTracks.FilterMatch = TrackList_SearchMatch;
-
- QueueTracks.SelectionChanged += new SelectionChangedEventHandler(TrackList_SelectionChanged);
- QueueTracks.MouseDoubleClick += new MouseButtonEventHandler(TrackList_MouseDoubleClick);
- QueueTracks.ContextMenuOpening += new ContextMenuEventHandler(TrackList_ContextMenuOpening);
- QueueTracks.FilesDropped += new FileDropEventHandler(TrackList_FilesDropped);
- QueueTracks.MoveItem += new MoveItemEventHandler(TrackList_MoveItem);
- QueueTracks.FilterMatch = TrackList_SearchMatch;
-
- YouTubePlayerInterface ypi = new YouTubePlayerInterface();
- ypi.ErrorOccured += new ErrorEventHandler(YouTube_ErrorOccured);
- ypi.NoFlashDetected += new EventHandler(YouTube_NoFlashDetected);
- ypi.PlayerReady += new EventHandler(YouTube_PlayerReady);
-
- // WebBrowser will not load if it's not visible
- // so we remove it from now playing...
- NowPlayingContainer.Video.Children.Remove(NowPlayingContainer.Browser);
- // ...put it inside main window...
- TrackContainer.Children.Add(NowPlayingContainer.Browser);
- // ...and remove it from here quickly again...
- TrackContainer.Children.Remove(NowPlayingContainer.Browser);
- NowPlayingContainer.Browser.Visibility = System.Windows.Visibility.Collapsed;
- // (man this was fugly :P)
-
- NowPlayingContainer.Browser.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
- NowPlayingContainer.Browser.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
- NowPlayingContainer.Browser.Width = double.NaN;
- NowPlayingContainer.Browser.Height = double.NaN;
- NowPlayingContainer.Browser.ObjectForScripting = ypi;
- NowPlayingContainer.NoVideoMessage.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
- NowPlayingContainer.NoVideoMessage.Visibility = System.Windows.Visibility.Visible;
-
- if (YouTubeManager.IsYouTube(SettingsManager.CurrentTrack))
- {
- NowPlayingContainer.NoVideoMessage.Visibility = System.Windows.Visibility.Collapsed;
- NowPlayingContainer.Browser.Visibility = System.Windows.Visibility.Visible;
- }
-
- U.L(LogLevel.Debug, "MAIN", "Startup complete");
-
- ThreadStart GUIThread = delegate()
- {
- InitGUI();
- };
- Thread gui_thread = new Thread(GUIThread);
- gui_thread.Name = "Init GUI Thread";
- gui_thread.Priority = ThreadPriority.BelowNormal;
- gui_thread.Start();
-
- //long timestamp = (long)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds);
- //string newVersion = timestamp.ToString();
- //Console.WriteLine(String.Format("Timestamp: {0}", timestamp));
- }
-
- /// <summary>
- /// Invoked when the user switches the session.
- /// Eg: lock or log off
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
- {
- if ((e.Reason == SessionSwitchReason.SessionLock && SettingsManager.PauseWhileLocked) ||
- (e.Reason == SessionSwitchReason.SessionLogoff && SettingsManager.PauseWhileLoggedOut))
- {
- resumeWhenBack = SettingsManager.MediaState == MediaState.Playing;
- MediaManager.Pause();
- }
- else if (resumeWhenBack &&
- (e.Reason == SessionSwitchReason.SessionLogon || e.Reason == SessionSwitchReason.SessionUnlock))
- {
- MediaManager.Play();
- resumeWhenBack = false;
- }
- }
-
- /// <summary>
- /// Invoked when a playlist is modified
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void PlaylistManager_PlaylistModified(object sender, ModifiedEventArgs e)
- {
- PlaylistData playlist = sender as PlaylistData;
-
- if (e.Type == ModifyType.Created)
- {
- CreatePlaylist(playlist);
- }
- else if (e.Type == ModifyType.Removed)
- {
- ((ViewDetails)PlaylistTrackLists[playlist.Name]).Visibility = Visibility.Collapsed;
- PlaylistTrackLists.Remove(playlist.Name);
-
- // remove from context menu
- for (int i = 0; i < listMenuAddToPlaylist.Items.Count; i++)
- {
- if ((string)((MenuItem)listMenuAddToPlaylist.Items[i]).Header == playlist.Name)
- {
- listMenuAddToPlaylist.Items.RemoveAt(i);
- break;
- }
- }
- for (int i = 0; i < listMenuRemoveFromPlaylist.Items.Count; i++)
- {
- if ((string)((MenuItem)listMenuRemoveFromPlaylist.Items[i]).Header == playlist.Name)
- {
- listMenuRemoveFromPlaylist.Items.RemoveAt(i);
- break;
- }
- }
- if (listMenuRemoveFromPlaylist.Items.Count == 0)
- listMenuRemoveFromPlaylist.Visibility = System.Windows.Visibility.Collapsed;
-
- PlaybackControls.Search.RemovePlaylist(playlist);
-
- for (int i = 0; i < NavigationPane.Playlists.Items.Count; i++)
- {
- TreeViewItem tvi = (TreeViewItem)NavigationPane.Playlists.Items[i];
- if (tvi.Header is StackPanel)
- {
- EditableTextBlock tb = ((StackPanel)tvi.Header).Children[1] as EditableTextBlock;
- if (tb.Text == playlist.Name)
- {
- NavigationPane.historyList.Remove(tvi);
- if (tvi.IsSelected)
- {
- if (NavigationPane.historyList.Count > 0)
- {
- TreeViewItem prevItem = NavigationPane.historyList[NavigationPane.historyList.Count - 1];
- prevItem.IsSelected = true;
- prevItem.Focus();
- }
- else
- {
- if (SettingsManager.Playlists.Count > 0)
- ((TreeViewItem)NavigationPane.Playlists.Items[0]).IsSelected = true;
- else
- NavigationPane.Library.IsSelected = true;
- }
- }
- NavigationPane.Playlists.Items.Remove(tvi);
- break;
- }
- }
- }
-
- // fix navigation references
- if (SettingsManager.CurrentSelectedNavigation == "Playlist:" + playlist.Name)
- SettingsManager.CurrentSelectedNavigation = "Files";
- if (SettingsManager.CurrentActiveNavigation == "Playlist:" + playlist.Name)
- SettingsManager.CurrentActiveNavigation = "Files";
- }
- }
-
- /// <summary>
- /// Invoked when a playlist is renamed
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void PlaylistManager_PlaylistRenamed(object sender, RenamedEventArgs e)
- {
- PlaylistData playlist = sender as PlaylistData;
-
- // rename key value in hashtable of tracklists
- PlaylistTrackLists.Add(e.Name, PlaylistTrackLists[e.OldName]);
- PlaylistTrackLists.Remove(e.OldName);
-
- // rename list context menu items
- foreach (MenuItem mi in listMenuAddToPlaylist.Items)
- if ((string)mi.Header == e.OldName)
- mi.Header = e.Name;
- foreach (MenuItem mi in listMenuRemoveFromPlaylist.Items)
- if ((string)mi.Header == e.OldName)
- mi.Header = e.Name;
- PlaybackControls.Search.RenamePlaylist(e.OldName, e.Name);
-
- // rename navigation items
- foreach (TreeViewItem item in NavigationPane.Playlists.Items)
- {
- StackPanel sp = item.Header as StackPanel;
- EditableTextBlock etb = sp.Children[1] as EditableTextBlock;
- if (etb.Text == e.OldName)
- {
- etb.Text = e.Name;
- etb.Focus();
- break;
- }
- }
-
- playlist.Name = e.Name;
-
- // fix navigation references
- if (SettingsManager.CurrentSelectedNavigation == "Playlist:" + e.OldName)
- SettingsManager.CurrentSelectedNavigation = "Playlist:" + e.Name;
- if (SettingsManager.CurrentActiveNavigation == "Playlist:" + e.OldName)
- SettingsManager.CurrentActiveNavigation = "Playlist:" + e.Name;
- }
-
- /// <summary>
- /// Invoked when the progress of an upgrade changes
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void UpgradeManager_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- ProgressState ps = e.UserState as ProgressState;
- ControlPanel.UpgradeProgressInfo.Text = ps.Message;
- ControlPanel.UpgradeProgressBar.Value = e.ProgressPercentage;
- ControlPanel.UpgradeProgressBar.IsIndeterminate = ps.IsIndetermined;
- TaskbarItemInfo.ProgressValue = (double)e.ProgressPercentage / 100;
- TaskbarItemInfo.ProgressState = (ps.IsIndetermined ? TaskbarItemProgressState.Indeterminate : TaskbarItemProgressState.Normal);
- }));
- }
-
- /// <summary>
- /// Invoked when an error occurs during an upgrade
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="message">The error message</param>
- private void UpgradeManager_ErrorOccured(object sender, string message)
- {
- U.L(LogLevel.Debug, "MAIN", "Upgrade manager encountered an error: " + message);
- Dispatcher.Invoke(new Action(delegate
- {
- if (TaskbarItemInfo != null)
- TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
- ControlPanel.UpgradeMessageText.Text = message;
- ControlPanel.UpgradeMessageIcon.Source = new BitmapImage(new Uri("/GUI/Images/Icons/Error.ico", UriKind.RelativeOrAbsolute));
- ControlPanel.UpgradeMessage.Visibility = System.Windows.Visibility.Visible;
- if (UpgradeManager.Policy == UpgradePolicy.Manual)
- ControlPanel.EnableUpgradeCheck();
- else if (UpgradeManager.Policy == UpgradePolicy.Notify && UpgradeManager.ForceDownload)
- ControlPanel.EnableUpgradeDo();
- }));
- }
-
- /// <summary>
- /// Invoked when an upgrade is found
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void UpgradeManager_UpgradeFound(object sender, EventArgs e)
- {
- U.L(LogLevel.Debug, "MAIN", "Upgrade manager found upgrade");
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- ControlPanel.UpgradeMessageText.Text = U.T("UpgradeFound");
- ControlPanel.UpgradeMessageIcon.Source = new BitmapImage(new Uri("/GUI/Images/Icons/Info.ico", UriKind.RelativeOrAbsolute));
- ControlPanel.UpgradeMessage.Visibility = System.Windows.Visibility.Visible;
- ControlPanel.EnableUpgradeDo();
- if (TaskbarItemInfo != null)
- TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
-
- if (SettingsManager.UpgradePolicy == UpgradePolicy.Notify)
- {
- TrayNotification notification = new TrayNotification(this);
- trayIcon.ShowCustomBalloon(notification, System.Windows.Controls.Primitives.PopupAnimation.Fade, 3600000);
- ControlPanel.PrefDoUpgrade.Visibility = Visibility.Visible;
- }
- }));
- }
-
- /// <summary>
- /// Invoked when a check for upgrades has been performed
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void UpgradeManager_Checked(object sender, EventArgs e)
- {
- U.L(LogLevel.Debug, "MAIN", "Upgrade manager completed check");
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- TimeSpan _ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0));
- SettingsManager.UpgradeCheck = (long)_ts.TotalSeconds;
- ControlPanel.UpdateUpgradeCheck();
- if (TaskbarItemInfo != null)
- TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
-
- if (UpgradeManager.Policy == UpgradePolicy.Manual && !UpgradeManager.Found)
- {
- ControlPanel.EnableUpgradeCheck();
- ControlPanel.UpgradeMessageIcon.Source = new BitmapImage(new Uri("/GUI/Images/Icons/Info.ico", UriKind.RelativeOrAbsolute));
- ControlPanel.UpgradeMessageText.Text = U.T("UpgradeNotFound");
- ControlPanel.UpgradeMessage.Visibility = System.Windows.Visibility.Visible;
- }
- }));
- }
-
- /// <summary>
- /// Invoked when the application has been upgraded
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void UpgradeManager_Upgraded(object sender, EventArgs e)
- {
- U.L(LogLevel.Debug, "MAIN", "Upgrade manager has upgraded Stoffi");
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- ControlPanel.PrefDoUpgrade.Visibility = Visibility.Collapsed;
- ControlPanel.UpgradeProgress.Visibility = Visibility.Collapsed;
- if (TaskbarItemInfo != null)
- TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
- if (SettingsManager.UpgradePolicy == UpgradePolicy.Manual)
- {
- ControlPanel.EnableRestart();
- ControlPanel.UpgradeMessageText.Text = U.T("UpgradePending");
- ControlPanel.UpgradeMessageIcon.Source = new BitmapImage(new Uri("/GUI/Images/Icons/Info.ico", UriKind.RelativeOrAbsolute));
- ControlPanel.UpgradeMessage.Visibility = System.Windows.Visibility.Visible;
- }
- else
- ControlPanel.UpgradeMessage.Visibility = Visibility.Collapsed;
- }));
- }
-
- /// <summary>
- /// Invoked when there's a problem with the Internet connection.
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void MediaManager_ConnectionProblem(object sender, EventArgs e)
- {
- if (showMediaError)
- {
- showMediaError = false;
- MessageBox.Show(U.T("MessageConnectionProblem", "Message"),
- U.T("MessageConnectionProblem", "Title"), MessageBoxButton.OK, MessageBoxImage.Error);
- }
- }
-
- /// <summary>
- /// Invoked when the media manager switches from one track to another
- /// </summary>
- /// <param name="e">The event data</param>
- private void MediaManager_TrackSwitched(TrackSwitchedEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- ViewDetails tl = GetCurrentTrackList();
- if (tl == null) return;
-
- ListViewItem lvi = tl.ItemContainerGenerator.ContainerFromItem(e.OldTrack) as ListViewItem;
- if (lvi != null)
- {
- Point trackLoc = lvi.TranslatePoint(new Point(0, 0), tl);
- double trackListHeight = tl.ActualHeight;
- double trackHeight = lvi.ActualHeight;
-
- if (trackLoc.Y + trackHeight > 0 || trackLoc.Y <= trackListHeight)
- tl.ScrollIntoView(MediaManager.GetSourceTrack(e.NewTrack));
- }
-
- if (trayIcon != null) ((TrayToolTip)trayIcon.TrayToolTip).SetTrack(e.NewTrack);
-
- if (SettingsManager.ShowOSD)
- {
- TrayNotification notification = new TrayNotification(e.NewTrack, this);
- if (trayIcon != null)
- trayIcon.ShowCustomBalloon(notification, System.Windows.Controls.Primitives.PopupAnimation.Fade, 4000);
- }
-
- // TODO: This hangs Stoffi sometimes for a few seconds
- JumpTask jumpTask = new JumpTask()
- {
- Title = e.NewTrack.Artist + " - " + e.NewTrack.Title,
- Arguments = e.NewTrack.Path,
- Description = e.NewTrack.Artist + " - " + e.NewTrack.Title,
- IconResourcePath = "C:\\Windows\\System32\\imageres.dll",
- IconResourceIndex = 190,
- ApplicationPath = Assembly.GetEntryAssembly().CodeBase,
- };
-
- JumpList.AddToRecentCategory(jumpTask);
- }));
- }
-
- /// <summary>
- /// Invoked when the user clicks Next inside the Properties window
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Properties_NextClick(object sender, EventArgs e)
- {
- PropertiesWindow pw = sender as PropertiesWindow;
- ViewDetails trackList = GetCurrentTrackList();
- ItemCollection items = trackList.Items;
- List<TrackData> t = new List<TrackData>();
-
- for (int i = (trackList.IndexOf(pw.Tracks[pw.Tracks.Count - 1]) + 1) % items.Count; // use % to wrap
- t.Count < pw.Tracks.Count;
- i = ++i % items.Count) // use % to wrap
- {
- // find next non-youtube
- TrackData track = (TrackData)trackList.GetItemAt(i);
- int end = (i - 1 + items.Count) % items.Count; // stop when checking this far
- while (YouTubeManager.IsYouTube(track) && i != end)
- {
- i = ++i % items.Count; // use % to wrap
- track = (TrackData)trackList.GetItemAt(i);
- }
-
- // add if any non-youtube
- if (i < items.Count)
- t.Add(track);
- }
-
- if (t.Count > 0)
- pw.AddTracks(t);
- // else?
- }
-
- /// <summary>
- /// Invoked when the user clicks Previous inside the Properties window
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Properties_PrevClick(object sender, EventArgs e)
- {
- PropertiesWindow pw = sender as PropertiesWindow;
- ViewDetails trackList = GetCurrentTrackList();
- ItemCollection items = trackList.Items;
- List<TrackData> t = new List<TrackData>();
-
- for (int i = (trackList.IndexOf(pw.Tracks[0]) - 1 + items.Count) % items.Count; // use % to wrap
- t.Count < pw.Tracks.Count;
- i = --i + items.Count % items.Count) // use % to wrap
- {
- // find next non-youtube
- TrackData track = (TrackData)trackList.GetItemAt(i);
- int end = (i + 1) % items.Count; // stop when checking this far
- while (YouTubeManager.IsYouTube(track) && i != end)
- {
- i = --i + items.Count % items.Count; // use % to wrap
- if (i < 0) i = items.Count + i;
- track = (TrackData)trackList.GetItemAt(i);
- }
-
- // add if any non-youtube
- if (i < items.Count)
- t.Add(track);
- }
-
- t.Reverse();
- if (t.Count > 0)
- pw.AddTracks(t);
- }
-
- /// <summary>
- /// Invoked when an editable text block enters edit mode
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void EditableTextBlock_EnteredEditMode(object sender, EventArgs e)
- {
- etbInEdit = sender as EditableTextBlock;
- }
-
- /// <summary>
- /// Invoked when the user doubleclicks a track in a track list
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void TrackList_MouseDoubleClick(object sender, RoutedEventArgs e)
- {
- Play();
- }
-
- /// <summary>
- /// Invoked when the user right-clicks the track list
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void TrackList_ContextMenuOpening(object sender, ContextMenuEventArgs e)
- {
- if (SettingsManager.CurrentSelectedNavigation == "Queue")
- listMenuQueue.Visibility = System.Windows.Visibility.Collapsed;
-
- else
- listMenuQueue.Visibility = System.Windows.Visibility.Visible;
-
- bool containsYouTube = false;
- bool containsFiles = false;
- bool isPlaying = true;
- bool isQueued = false;
- ViewDetails vd = sender as ViewDetails;
- foreach (TrackData t in vd.SelectedItems)
- {
- if (YouTubeManager.IsYouTube(t))
- containsYouTube = true;
- else
- containsFiles = true;
-
- if (SettingsManager.CurrentTrack == null || SettingsManager.CurrentTrack.Path != t.Path || SettingsManager.MediaState != MediaState.Playing)
- isPlaying = false;
- if (!isQueued)
- foreach (TrackData u in SettingsManager.QueueTracks)
- if (t.Path == u.Path)
- isQueued = true;
- }
-
- listMenuInfo.Visibility = containsYouTube ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
- listMenuRemove.Visibility = containsFiles ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
- listMenuDelete.Visibility = containsFiles ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
- listMenuWatchOnYouTube.Visibility = containsYouTube ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
- listMenuShareSong.Visibility = containsYouTube && ServiceManager.Linked ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
-
- listMenuPlay.Header = (isPlaying ? U.T("MenuPause") : U.T("MenuPlay"));
- listMenuQueue.Header = (isQueued ? U.T("MenuDequeue") : U.T("MenuQueue"));
- }
-
- /// <summary>
- /// Invoked when the user clicks play in the track list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuPlay_Click(object sender, RoutedEventArgs e)
- {
- MenuItem mi = sender as MenuItem;
- if ((string)mi.Header == U.T("MenuPlay"))
- Play(false);
- else
- MediaManager.Pause();
- }
-
- /// <summary>
- /// Invoked when the user clicks remove in the track list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuRemove_Click(object sender, RoutedEventArgs e)
- {
- int i = GetCurrentTrackList().SelectedIndex;
- List<TrackData> tracks = new List<TrackData>();
- foreach (TrackData track in GetCurrentTrackList().SelectedItems)
- tracks.Add(track);
-
- // stop playing if removing active tracks
- foreach (TrackData t in tracks)
- {
- if (t.IsActive)
- {
- MediaManager.Stop();
- break;
- }
- }
-
- // remove from whole collection
- if (SettingsManager.CurrentSelectedNavigation == "Files")
- {
- foreach (TrackData track in tracks)
- {
- RemoveTrack(track.Path, SettingsManager.FileTracks);
- RemoveTrack(track.Path, SettingsManager.QueueTracks);
- RemoveTrack(track.Path, SettingsManager.HistoryTracks);
- foreach (PlaylistData p in SettingsManager.Playlists)
- RemoveTrack(track.Path, p.Tracks);
-
- SourceData source = FilesystemManager.GetSource(track.Path);
-
- // remove from sources?
- if (FilesystemManager.PathIsAdded(track.Path) && source != null)
- FilesystemManager.RemoveSource(source);
- else if (!FilesystemManager.PathIsIgnored(track.Path))
- FilesystemManager.AddSource(new SourceData
- {
- Data = track.Path,
- Ignore = true,
- Icon = "pack://application:,,,/GUI/Images/Icons/FileAudio.ico",
- HumanType = U.T("SourcesTypeFile"),
- Type = SourceType.File
- });
- }
- }
-
- // dequeue
- else if (SettingsManager.CurrentSelectedNavigation == "Queue")
- MediaManager.Dequeue(tracks);
-
- // remove from history
- else if (SettingsManager.CurrentSelectedNavigation == "History")
- {
- foreach (TrackData track in tracks)
- {
- if (SettingsManager.HistoryTracks.IndexOf(track) <= SettingsManager.HistoryIndex)
- SettingsManager.HistoryIndex--;
- RemoveTrack(track.Path, SettingsManager.HistoryTracks);
- }
-
- if (SettingsManager.HistoryIndex > SettingsManager.HistoryTracks.Count)
- SettingsManager.HistoryIndex = SettingsManager.HistoryTracks.Count;
- }
-
- // remove from playlist
- else
- {
- string pl = SettingsManager.CurrentSelectedNavigation.Split(new[]{':'},2)[1];
- PlaylistManager.RemoveFromPlaylist(tracks, pl);
- }
-
- // refresh selection
- if (GetCurrentTrackList().Items.Count > 0)
- {
- if (i >= GetCurrentTrackList().Items.Count)
- GetCurrentTrackList().SelectedIndex = GetCurrentTrackList().Items.Count - 1;
- else
- GetCurrentTrackList().SelectedIndex = i;
- }
-
- }
-
- /// <summary>
- /// Invoked when the user clicks delete in the track list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuDelete_Click(object sender, RoutedEventArgs e)
- {
- if (MessageBox.Show(U.T("MessageConfirmDelete", "Message"), U.T("MessageConfirmDelete", "Title"),
- MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes)
- {
- int i = GetCurrentTrackList().SelectedIndex;
- List<TrackData> tracks = new List<TrackData>();
- foreach (TrackData track in GetCurrentTrackList().SelectedItems)
- tracks.Add(track);
- foreach (TrackData t in tracks)
- {
- if (t.IsActive)
- {
- MediaManager.Stop();
- break;
- }
- }
- foreach (TrackData track in tracks)
- {
- try
- {
- File.Delete(track.Path);
- }
- catch (Exception exc)
- {
- MessageBox.Show(exc.Message, U.T("MessageErrorDeleting", "Title"), MessageBoxButton.OK, MessageBoxImage.Error);
- }
- }
-
- if (GetCurrentTrackList().Items.Count > 0)
- {
- if (i >= GetCurrentTrackList().Items.Count)
- GetCurrentTrackList().SelectedIndex = GetCurrentTrackList().Items.Count - 1;
- else
- GetCurrentTrackList().SelectedIndex = i;
- }
- }
- }
-
- /// <summary>
- /// Invoked when the user clicks information in the track list's
- /// context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuInfo_Click(object sender, RoutedEventArgs e)
- {
- if (GetCurrentTrackList().SelectedItems.Count > 0)
- {
- List<TrackData> tracks = new List<TrackData>();
- foreach (TrackData t in GetCurrentTrackList().SelectedItems)
- if (!YouTubeManager.IsYouTube(t))
- tracks.Add(t);
-
- PropertiesWindow dialog = new PropertiesWindow(tracks);
- dialog.NextClick += new EventHandler(Properties_NextClick);
- dialog.PreviousClick += new EventHandler(Properties_PrevClick);
- dialog.ShowDialog();
- }
- }
-
- /// <summary>
- /// Invoked when the user clicks add to a playlist in the track
- /// list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuAddToPlaylist_Click(object sender, RoutedEventArgs e)
- {
- if (sender is MenuItem)
- {
- MenuItem item = sender as MenuItem;
- String name = item.Header.ToString();
-
- if (name == U.T("MenuCreateNew", "Header"))
- {
- NavigationPane.AddToPlaylistQueue.Clear();
- foreach (TrackData track in GetCurrentTrackList().SelectedItems)
- NavigationPane.AddToPlaylistQueue.Add(track);
- NavigationPane.CreateNewPlaylistETB.IsInEditMode = true;
- }
- else
- {
- List<object> tracks = new List<object>();
- foreach (TrackData track in GetCurrentTrackList().SelectedItems)
- tracks.Add(track);
- PlaylistManager.AddToPlaylist(tracks, name);
- }
- }
- }
-
- /// <summary>
- /// Invoked when the user clicks add to a new playlist in the
- /// track list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuAddToNew_Click(object sender, RoutedEventArgs e)
- {
- NavigationPane.AddToPlaylistQueue.Clear();
- foreach (TrackData track in GetCurrentTrackList().SelectedItems)
- NavigationPane.AddToPlaylistQueue.Add(track);
-
- NavigationPane.CreateNewPlaylistETB.IsInEditMode = true;
- }
-
- /// <summary>
- /// Invoked when the user clicks remove from a playlist in
- /// the track list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuRemoveFromPlaylist_Click(object sender, RoutedEventArgs e)
- {
- if (sender is MenuItem)
- {
- MenuItem item = sender as MenuItem;
- String name = item.Header.ToString();
-
- List<TrackData> tracks = new List<TrackData>();
- foreach (TrackData track in GetCurrentTrackList().SelectedItems)
- tracks.Add(track);
- PlaylistManager.RemoveFromPlaylist(tracks, name);
- }
- }
-
- /// <summary>
- /// Invoked when the user clicks queue/dequeue in the track
- /// list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuQueue_Click(object sender, RoutedEventArgs e)
- {
- List<TrackData> tracks = new List<TrackData>();
- foreach (TrackData track in GetCurrentTrackList().SelectedItems)
- tracks.Add(track);
-
- MenuItem mi = sender as MenuItem;
- if ((string)mi.Header == U.T("MenuQueue"))
- MediaManager.Queue(tracks);
- else
- MediaManager.Dequeue(tracks);
-
- }
-
- /// <summary>
- /// Invoked when the user clicks to watch a track on YouTube
- /// in the track list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuWatchOnYouTube_Click(object sender, RoutedEventArgs e)
- {
- if (GetCurrentTrackList().SelectedItems.Count > 0)
- {
- List<TrackData> tracks = new List<TrackData>();
- foreach (TrackData t in GetCurrentTrackList().SelectedItems)
- if (YouTubeManager.IsYouTube(t))
- tracks.Add(t);
-
- foreach (TrackData track in tracks)
- {
- string vid = track.Path.Substring(10);
- MediaManager.Pause();
- int autoplay = tracks.Count > 0 && tracks.IndexOf(track) > 0 ? 0 : 1;
- System.Diagnostics.Process.Start(String.Format("http://www.youtube.com/watch?v={0}&autoplay={1}&feature=stoffi", vid, autoplay));
- }
- }
- }
-
- /// <summary>
- /// Invoked when the user clicks to share a YouTube track
- /// in the track list's context menu
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void listMenuShareSong_Click(object sender, RoutedEventArgs e)
- {
- if (GetCurrentTrackList().SelectedItems.Count > 0)
- {
- List<TrackData> tracks = new List<TrackData>();
- foreach (TrackData t in GetCurrentTrackList().SelectedItems)
- if (YouTubeManager.IsYouTube(t))
- tracks.Add(t);
-
- foreach (TrackData track in tracks)
- {
- ServiceManager.ShareSong(track);
- }
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void KListener_KeyDown(object sender, RawKeyEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate() { KeyPressed(e.key, e.key, true); }));
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void KListener_KeyUp(object sender, RawKeyEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate() { KeyReleased(e.key, e.key); }));
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void NavigationPlaylist_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.Key == Key.F2)
- NavigationPane.RenamePlaylist_Clicked(sender, null);
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void OpenPlaylist_Clicked(object sender, RoutedEventArgs e)
- {
- Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
- dialog.Title = "Open Playlist";
- dialog.DefaultExt = ".pls";
- dialog.Filter = "Playlists (.pls)|*.pls|Playlists (.m3u)|*.m3u";
- bool result = (bool)dialog.ShowDialog();
- if (result == true)
- PlaylistManager.LoadPlaylist(dialog.FileName);
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="key"></param>
- /// <param name="sysKey"></param>
- private void KeyReleased(Key key, Key sysKey)
- {
- if (!U.ListenForShortcut) return;
-
- if (key == Key.System && (sysKey == Key.LeftAlt || sysKey == Key.RightAlt || sysKey == Key.LeftCtrl))
- {
- if (currentPressedKeys.Contains(sysKey)) currentPressedKeys.Remove(sysKey);
- }
- else if (key == Key.RightShift)
- {
- if (currentPressedKeys.Contains(Key.LeftShift)) currentPressedKeys.Remove(Key.LeftShift);
- }
- else
- {
- if (currentPressedKeys.Contains(key)) currentPressedKeys.Remove(key);
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="key"></param>
- /// <param name="sysKey"></param>
- /// <param name="global"></param>
- /// <returns></returns>
- private bool KeyPressed(Key key, Key sysKey, bool global = false)
- {
- // catch media keys
- switch (key)
- {
- case Key.MediaPlayPause:
- if (!global && kListener.CheckHandlers()) return false;
- PlayPause();
- return true;
- case Key.MediaStop:
- MediaManager.Pause();
- return true;
- case Key.MediaNextTrack:
- if (!global && kListener.CheckHandlers()) return false;
- MediaManager.Next(true);
- return true;
- case Key.MediaPreviousTrack:
- if (!global && kListener.CheckHandlers()) return false;
- MediaManager.Previous();
- return true;
- default:
- break;
- }
-
- // are we listening?
- if (!U.ListenForShortcut) return false;
-
- switch (key)
- {
- // convert right shift to left shift
- case Key.RightShift:
- if (!currentPressedKeys.Contains(Key.LeftShift)) currentPressedKeys.Add(Key.LeftShift);
- return false;
- // catch modifier keys
- case Key.LeftShift:
- case Key.LeftCtrl:
- case Key.LeftAlt:
- case Key.LWin:
- case Key.RightCtrl:
- case Key.RightAlt:
- case Key.RWin:
- if (!currentPressedKeys.Contains(key)) currentPressedKeys.Add(key);
- return false;
-
- // catch alt/left ctrl key when disguised as system key
- case Key.System:
- if (sysKey == Key.LeftAlt || sysKey == Key.RightAlt || sysKey == Key.LeftCtrl)
- {
- if (!currentPressedKeys.Contains(sysKey)) currentPressedKeys.Add(sysKey);
- return false;
- }
- break;
-
- // ignore these keys
- case Key.None:
- case Key.DeadCharProcessed:
- return false;
-
- default:
- break;
- }
-
- // turn key combination into string
- // TODO: convert Oem keys to nice strings
- String currentKey = key == Key.System ? KeyToString(sysKey) : KeyToString(key);
- String txt = GetModifiersAsText(currentPressedKeys);
- if (txt.Length > 0) txt += "+" + currentKey;
- else txt = currentKey;
-
- // find matching shortcut
- KeyboardShortcut sc = SettingsManager.GetKeyboardShortcut(SettingsManager.GetCurrentShortcutProfile(), txt);
-
- // hardcoded shortcuts
- if (!global)
- {
- if (txt == "Ctrl+A")
- {
- ViewDetails tl = GetCurrentTrackList();
- if (tl != null && tl.IsVisible)
- {
- tl.SelectAll();
- tl.Focus();
- }
- }
- }
-
- if (sc == null) return false;
-
- // skip if we received a global event but shortcut is not set to global
- // and prevent the shortcut from being executed twice if set to global
- if (sc.IsGlobal != global && kListener.CheckHandlers()) return false;
-
- // execute command
- if (sc.Category == "Application")
- {
- if (sc.Name == "Add track")
- {
- currentPressedKeys.Clear();
- AddFile_Clicked(null, null);
- }
- else if (sc.Name == "Add folder")
- {
- currentPressedKeys.Clear();
- AddFolder_Clicked(null, null);
- }
- else if (sc.Name == "Open playlist")
- {
- currentPressedKeys.Clear();
- OpenPlaylist_Clicked(null, null);
- }
- else if (sc.Name == "Help")
- {
- currentPressedKeys.Clear();
- Help_Clicked(null, null);
- }
- else if (sc.Name == "Minimize")
- {
- currentPressedKeys.Clear();
- Hide_Clicked(null, null);
- }
- else if (sc.Name == "Restore")
- {
- currentPressedKeys.Clear();
- TaskbarClicked(null, null);
- }
- else if (sc.Name == "Close")
- Close_Clicked(null, null);
- }
- else if (sc.Category == "MainWindow")
- {
- if (sc.Name == "Library")
- {
- NavigationPane.SwitchNavigation("Files");
- }
- if (sc.Name == "Now playing")
- {
- NavigationPane.SwitchNavigation("NowPlaying");
- }
- else if (sc.Name == "Queue")
- {
- NavigationPane.SwitchNavigation("Queue");
- }
- else if (sc.Name == "History")
- {
- NavigationPane.SwitchNavigation("History");
- }
- else if (sc.Name == "Playlists")
- {
- MainContainer.Children.Remove(ControlPanel);
- MusicPanel.Visibility = System.Windows.Visibility.Visible;
- PlaybackControls.Search.Box.IsEnabled = true;
- NavigationPane.Playlists.Focus();
- }
- else if (sc.Name == "Create playlist")
- {
- MainContainer.Children.Remove(ControlPanel);
- MusicPanel.Visibility = System.Windows.Visibility.Visible;
- PlaybackControls.Search.Box.IsEnabled = true;
- NavigationPane.CreateNewPlaylist.Focus();
- }
- else if (sc.Name == "Tracklist")
- {
- MainContainer.Children.Remove(ControlPanel);
- MusicPanel.Visibility = System.Windows.Visibility.Visible;
- PlaybackControls.Search.Box.IsEnabled = true;
- GetCurrentTrackList().Focus();
- }
- else if (sc.Name == "Search")
- {
- currentPressedKeys.Clear();
- PlaybackControls.Search.Box.Focus();
- }
- else if (sc.Name == "General preferences")
- {
- MusicPanel.Visibility = System.Windows.Visibility.Collapsed;
- if (!MainContainer.Children.Contains(ControlPanel)) MainContainer.Children.Add(ControlPanel);
- PlaybackControls.Search.Box.IsEnabled = false;
- ControlPanel.SwitchTab(Stoffi.ControlPanel.Tab.General);
- }
- else if (sc.Name == "Library sources")
- {
- MusicPanel.Visibility = System.Windows.Visibility.Collapsed;
- if (!MainContainer.Children.Contains(ControlPanel)) MainContainer.Children.Add(ControlPanel);
- PlaybackControls.Search.Box.IsEnabled = false;
- ControlPanel.SwitchTab(Stoffi.ControlPanel.Tab.Sources);
- }
- else if (sc.Name == "Services")
- {
- MusicPanel.Visibility = System.Windows.Visibility.Collapsed;
- if (!MainContainer.Children.Contains(ControlPanel)) MainContainer.Children.Add(ControlPanel);
- PlaybackControls.Search.Box.IsEnabled = false;
- ControlPanel.SwitchTab(Stoffi.ControlPanel.Tab.Services);
- }
- else if (sc.Name == "Keyboard shortcuts")
- {
- MusicPanel.Visibility = System.Windows.Visibility.Collapsed;
- if (!MainContainer.Children.Contains(ControlPanel)) MainContainer.Children.Add(ControlPanel);
- PlaybackControls.Search.Box.IsEnabled = false;
- ControlPanel.SwitchTab(Stoffi.ControlPanel.Tab.Shortcuts);
- }
- else if (sc.Name == "About")
- {
- MusicPanel.Visibility = System.Windows.Visibility.Collapsed;
- if (!MainContainer.Children.Contains(ControlPanel)) MainContainer.Children.Add(ControlPanel);
- PlaybackControls.Search.Box.IsEnabled = false;
- ControlPanel.SwitchTab(Stoffi.ControlPanel.Tab.About);
- }
- else if (sc.Name == "Toggle details pane")
- ToggleDetailsPane(null, null);
-
- else if (sc.Name == "Toggle menu bar")
- ToggleMenuBar(null, null);
- }
- else if (sc.Category == "MediaCommands")
- {
- if (sc.Name == "Play or pause")
- PlayPause();
-
- else if (sc.Name == "Next")
- MediaManager.Next();
-
- else if (sc.Name == "Previous")
- MediaManager.Previous();
-
- else if (sc.Name == "Increase volume")
- PlaybackControls.VolumeSlide.Value += 0.5;
-
- else if (sc.Name == "Decrease volume")
- PlaybackControls.VolumeSlide.Value -= 0.5;
-
- else if (sc.Name == "Seek forward")
- PlaybackControls.SongProgress.Value += PlaybackControls.SongProgress.Maximum / 50;
-
- else if (sc.Name == "Seek backward")
- PlaybackControls.SongProgress.Value -= PlaybackControls.SongProgress.Maximum / 50;
-
- else if (sc.Name == "Toggle shuffle")
- PlaybackControls.Shuffle_Click(null, null);
-
- else if (sc.Name == "Toggle repeat")
- PlaybackControls.Repeat_Click(null, null);
-
- else if (sc.Name == "Add bookmark")
- {
- double pos = MediaManager.CreateBookmark();
- if (pos >= 0)
- PlaybackControls.AddBookmark(pos);
- }
-
- else if (sc.Name == "Jump to first bookmark")
- MediaManager.JumpToFirstBookmark();
-
- else if (sc.Name == "Jump to last bookmark")
- MediaManager.JumpToLastBookmark();
-
- else if (sc.Name == "Jump to previous bookmark")
- MediaManager.JumpToPreviousBookmark();
-
- else if (sc.Name == "Jump to next bookmark")
- MediaManager.JumpToNextBookmark();
-
- else if (sc.Name.StartsWith("Jump to bookmark "))
- MediaManager.JumpToBookmark(Convert.ToInt32(sc.Name.Substring(17)));
-
- else if (sc.Name == "Jump to current track")
- {
- NavigationPane.SwitchNavigation(SettingsManager.CurrentActiveNavigation);
- GetCurrentTrackList().SelectItem(SettingsManager.CurrentTrack);
- }
- }
- else if (sc.Category == "Track")
- {
- ViewDetails tl = GetCurrentTrackList();
- if (tl == null) return false;
-
- ListViewItem lvi = (ListViewItem)tl.ItemContainerGenerator.ContainerFromItem(tl.SelectedItem);
- if (lvi == null) return false;
-
- bool focused = tl.IsFocused;
- foreach (object i in tl.SelectedItems)
- if (((ListViewItem)tl.ItemContainerGenerator.ContainerFromItem(i)).IsFocused)
- focused = true;
-
- if (!focused) return false;
-
- if (sc.Name == "Queue and dequeue")
- {
- List<TrackData> tracks = new List<TrackData>();
- foreach (TrackData track in GetCurrentTrackList().SelectedItems)
- tracks.Add(track);
-
- MediaManager.ToggleQueue(tracks);
- }
- else if (sc.Name == "Remove track")
- listMenuRemove_Click(null, null);
-
- else if (sc.Name == "Play track")
- listMenuPlay_Click(null, null);
-
- else if (sc.Name == "View information")
- {
- currentPressedKeys.Clear();
- listMenuInfo_Click(null, null);
- }
- }
- return true;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TaskbarPlayPause_Clicked(object sender, Microsoft.WindowsAPICodePack.Taskbar.ThumbnailButtonClickedEventArgs e)
- {
- PlayPause();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TaskbarNext_Clicked(object sender, Microsoft.WindowsAPICodePack.Taskbar.ThumbnailButtonClickedEventArgs e)
- {
- MediaManager.Next();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TaskbarPrevious_Clicked(object sender, Microsoft.WindowsAPICodePack.Taskbar.ThumbnailButtonClickedEventArgs e)
- {
- MediaManager.Previous();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Equalizer_Clicked(object sender, RoutedEventArgs e)
- {
- if (equalizer == null || !equalizer.Activate())
- {
- equalizer = new Equalizer();
- double l = SettingsManager.EqualizerLeft;
- double t = SettingsManager.EqualizerTop;
-
- if (l < 0)
- l = (System.Windows.SystemParameters.PrimaryScreenWidth / 2) - (equalizer.Width / 2);
- if (t < 0)
- t = (System.Windows.SystemParameters.PrimaryScreenHeight / 2) - (equalizer.Height / 2);
-
- equalizer.Owner = App.Current.MainWindow;
- equalizer.Show();
- equalizer.Left = l;
- equalizer.Top = t;
- }
- else
- equalizer.Activate();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Preferences_Clicked(object sender, RoutedEventArgs e)
- {
- MusicPanel.Visibility = System.Windows.Visibility.Collapsed;
- if (!MainContainer.Children.Contains(ControlPanel)) MainContainer.Children.Add(ControlPanel);
- PlaybackControls.Search.Box.IsEnabled = false;
- ControlPanel.SwitchTab(Stoffi.ControlPanel.Tab.General);
- }
-
- /// <summary>
- /// Invoked when the user clicks "Import"
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Importer_Clicked(object sender, RoutedEventArgs e)
- {
- Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
- dialog.Title = "Import Configuration";
- dialog.DefaultExt = ".scf";
- dialog.Filter = "Stoffi Configuration File (*.scf)|*.scf";
- bool result = (bool)dialog.ShowDialog();
- if (result == true)
- SettingsManager.Import(dialog.FileName);
- }
-
- /// <summary>
- /// Invoked when the user clicks "Export"
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Exporter_Clicked(object sender, RoutedEventArgs e)
- {
- Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();
- dialog.Title = "Export Configuration";
- dialog.DefaultExt = ".scf";
- dialog.Filter = "Stoffi Configuration File (*.scf)|*.scf";
- bool result = (bool)dialog.ShowDialog();
- if (result == true)
- {
- SettingsManager.Export(dialog.FileName);
- }
- }
-
- /// <summary>
- /// Invoked when the user clicks "Generate playlist"
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void GeneratePlaylist_Clicked(object sender, RoutedEventArgs e)
- {
- GeneratePlaylist d = new GeneratePlaylist();
- d.Show();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void About_Clicked(object sender, RoutedEventArgs e)
- {
- MusicPanel.Visibility = System.Windows.Visibility.Collapsed;
- if (!MainContainer.Children.Contains(ControlPanel)) MainContainer.Children.Add(ControlPanel);
- PlaybackControls.Search.Box.IsEnabled = false;
- ControlPanel.SwitchTab(Stoffi.ControlPanel.Tab.About);
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Help_Clicked(object sender, RoutedEventArgs e)
- {
- System.Diagnostics.Process.Start("http://www.stoffiplayer.com/help?ref=stoffi");
- }
-
- /// <summary>
- /// Invoked when the user clicks "Add" in the toolbar
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Add_Clicked(object sender, RoutedEventArgs e)
- {
- addMenu.PlacementTarget = AddButton;
- addMenu.IsOpen = !addMenu.IsOpen;
- }
-
- /// <summary>
- /// Invoked when the user clicks "Show" in the toolbar
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Show_Clicked(object sender, RoutedEventArgs e)
- {
- showMenu.PlacementTarget = ShowButton;
- showMenu.IsOpen = !showMenu.IsOpen;
- }
-
- /// <summary>
- /// Invoked when the user clicks "Tools" in the toolbar
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Tools_Clicked(object sender, RoutedEventArgs e)
- {
- toolsMenu.PlacementTarget = ToolsButton;
- toolsMenu.IsOpen = !toolsMenu.IsOpen;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void AddFile_Clicked(object sender, RoutedEventArgs e)
- {
- Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog dialog = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();
- Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult result = dialog.ShowDialog();
- if (result == Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.OK)
- {
- if (FilesystemManager.PathIsAdded(dialog.FileName))
- MessageBox.Show(
- U.T("MessageAlreadyAddedSource", "Message"),
- U.T("MessageAlreadyAddedSource", "Title"),
- MessageBoxButton.OK, MessageBoxImage.Information);
- else
- {
- SourceData s = new SourceData();
- s.Data = dialog.FileName;
- s.HumanType = U.T("SourcesTypeFile");
- s.Type = SourceType.File;
- s.Include = true;
- s.Icon = "pack://application:,,,/GUI/Images/Icons/FileAudio.ico";
- FilesystemManager.AddSource(s);
- }
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void AddFolder_Clicked(object sender, RoutedEventArgs e)
- {
- System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
- dialog.SelectedPath = dialogPath;
- System.Windows.Forms.DialogResult result = dialog.ShowDialog();
- if (result == System.Windows.Forms.DialogResult.OK)
- {
- if (FilesystemManager.PathIsAdded(dialog.SelectedPath))
- MessageBox.Show(
- U.T("MessageAlreadyAddedSource", "Message"),
- U.T("MessageAlreadyAddedSource", "Title"),
- MessageBoxButton.OK, MessageBoxImage.Information);
- else
- {
- SourceData s = new SourceData();
- s.Data = dialog.SelectedPath;
- s.HumanType = U.T("SourcesTypeFolder");
- s.Type = SourceType.Folder;
- s.Include = true;
- s.Icon = "pack://application:,,,/GUI/Images/Icons/Folder.ico";
- FilesystemManager.AddSource(s);
- }
- }
- dialogPath = dialog.SelectedPath;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void IgnoreFile_Clicked(object sender, RoutedEventArgs e)
- {
- Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog dialog = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();
- Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult result = dialog.ShowDialog();
- if (result == Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.OK)
- {
- if (FilesystemManager.PathIsIgnored(dialog.FileName))
- MessageBox.Show(
- U.T("MessageAlreadyAddedSource", "Message"),
- U.T("MessageAlreadyAddedSource", "Title"),
- MessageBoxButton.OK, MessageBoxImage.Information);
- else
- {
- SourceData s = new SourceData();
- s.Data = dialog.FileName;
- s.HumanType = U.T("SourcesTypeFile");
- s.Type = SourceType.File;
- s.Ignore = true;
- s.Icon = "pack://application:,,,/GUI/Images/Icons/FileAudio.ico";
- FilesystemManager.AddSource(s);
- }
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void IgnoreFolder_Clicked(object sender, RoutedEventArgs e)
- {
- System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
- dialog.SelectedPath = dialogPath;
- System.Windows.Forms.DialogResult result = dialog.ShowDialog();
- if (result == System.Windows.Forms.DialogResult.OK)
- {
- if (FilesystemManager.PathIsIgnored(dialog.SelectedPath))
- MessageBox.Show(
- U.T("MessageAlreadyAddedSource", "Message"),
- U.T("MessageAlreadyAddedSource", "Title"),
- MessageBoxButton.OK, MessageBoxImage.Information);
- else
- {
- SourceData s = new SourceData();
- s.Data = dialog.SelectedPath;
- s.HumanType = U.T("SourcesTypeFolder");
- s.Type = SourceType.Folder;
- s.Ignore = true;
- s.Icon = "pack://application:,,,/GUI/Images/Icons/Folder.ico";
- FilesystemManager.AddSource(s);
- }
- }
- dialogPath = dialog.SelectedPath;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Hide_Clicked(object sender, RoutedEventArgs e)
- {
- WindowState = System.Windows.WindowState.Minimized;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Close_Clicked(object sender, RoutedEventArgs e)
- {
- Close();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void RemoveBookmarkClicked(object sender, EventArgs e)
- {
- Bookmark bm = sender as Bookmark;
- if (bm != null)
- {
- MediaManager.RemoveBookmark(bm.Position);
- PlaybackControls.RemoveBookmark(bm.Position);
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void ToggleDetailsPane(object sender, RoutedEventArgs e)
- {
- SettingsManager.DetailsPaneVisible = !SettingsManager.DetailsPaneVisible;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void ToggleMenuBar(object sender, RoutedEventArgs e)
- {
- if (SettingsManager.MenuBarVisibile)
- {
- showMenuMenuBar.IsChecked = false;
- MenuItemViewMenuBar.IsChecked = false;
- }
- else
- {
- showMenuMenuBar.IsChecked = true;
- MenuItemViewMenuBar.IsChecked = true;
- }
-
- SettingsManager.MenuBarVisibile = !SettingsManager.MenuBarVisibile;
- MenuBar.Visibility = SettingsManager.MenuBarVisibile ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void ChangeSize(object sender, SizeChangedEventArgs e)
- {
- SettingsManager.WinWidth = ActualWidth;
- SettingsManager.WinHeight = ActualHeight;
- PlaybackControls.Compress(ActualWidth);
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void ChangePos(object sender, EventArgs e)
- {
- SettingsManager.WinTop = Top;
- SettingsManager.WinLeft = Left;
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TaskbarClicked(object sender, RoutedEventArgs e)
- {
- if (WindowState != System.Windows.WindowState.Minimized)
- {
- oldWindowState = WindowState;
- WindowState = System.Windows.WindowState.Minimized;
- }
- else
- {
- WindowState = oldWindowState;
- Activate();
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TrayShow_Clicked(object sender, RoutedEventArgs e)
- {
- if (WindowState == System.Windows.WindowState.Minimized)
- WindowState = oldWindowState;
- Activate();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TrayPlayPause_Clicked(object sender, RoutedEventArgs e)
- {
- PlayPause();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TrayNext_Clicked(object sender, RoutedEventArgs e)
- {
- MediaManager.Next();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TrayPrevious_Clicked(object sender, RoutedEventArgs e)
- {
- MediaManager.Previous();
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TrayExit_Clicked(object sender, RoutedEventArgs e)
- {
- trayMenu.Visibility = System.Windows.Visibility.Hidden;
- Close_Clicked(sender, e);
- }
-
- /// <summary>
- /// Updates the scan indicator
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void FilesystemManager_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- switch ((string)e.UserState)
- {
- case "start":
- ScanProgressBar.Value = 0;
- ScanProgressBar.IsIndeterminate = true;
- ScanProgress.Visibility = System.Windows.Visibility.Visible;
- break;
-
- case "progress":
- ScanProgressBar.IsIndeterminate = false;
- ScanProgressBar.Value = e.ProgressPercentage;
- break;
-
- case "done":
- ScanProgress.Visibility = System.Windows.Visibility.Collapsed;
- break;
- }
- }));
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Window_Closing(object sender, CancelEventArgs e)
- {
- if (UpgradeManager.InProgress)
- {
- if (MessageBox.Show(U.T("MessageUpgradeInProgress", "Message"),
- U.T("MessageUpgradeInProgress", "Title"),
- MessageBoxButton.YesNo,
- MessageBoxImage.Warning,
- MessageBoxResult.No) == MessageBoxResult.No)
- {
- e.Cancel = true;
- return;
- }
- }
-
- kListener.Dispose();
- CloseProgress cp = new CloseProgress();
- try
- {
- cp.Owner = this;
- }
- catch { }
- cp.ShowDialog();
- if (doRestart)
- System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
- }
-
- /// <summary>
- /// Invoked when the window become active
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Window_Activated(object sender, EventArgs e)
- {
- RefreshGlassEffect();
- }
-
- /// <summary>
- /// Invoked when the window becomes inactive
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Window_Deactivated(object sender, EventArgs e)
- {
- if (!glassEffect && System.Windows.Forms.VisualStyles.VisualStyleInformation.DisplayName != "")
- Background = SystemColors.GradientInactiveCaptionBrush;
-
- if (etbInEdit != null)
- {
- etbInEdit.IsInEditMode = false;
- etbInEdit = null;
- }
- }
-
- /// <summary>
- /// Invoked when the user moves the mouse over the window
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Window_MouseMove(object sender, MouseEventArgs e)
- {
- //if (GetCurrentTrackList() != null)
- // GetCurrentTrackList().ClearDropTarget();
- }
-
- /// <summary>
- /// Invoked when the window changes state
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Window_StateChanged(object sender, EventArgs e)
- {
- oldWindowState = currentWindowState;
- currentWindowState = WindowState;
- SettingsManager.WinState = WindowState.ToString();
-
- if (SettingsManager.MinimizeToTray)
- ShowInTaskbar = WindowState != System.Windows.WindowState.Minimized;
- }
-
- /// <summary>
- /// Invoked when a key is pressed
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Window_KeyDown(object sender, KeyEventArgs e)
- {
- if (KeyPressed(e.Key, e.SystemKey))
- e.Handled = true;
- }
-
- /// <summary>
- /// Invoked when a key is released
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Window_KeyUp(object sender, KeyEventArgs e)
- {
- KeyReleased(e.Key, e.SystemKey);
- }
-
- /// <summary>
- /// Invoked when the left mouse button is pressed
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- if (etbInEdit != null && etbInEdit.IsInEditMode)
- {
- EditableTextBlock etb = ViewDetailsUtilities.TryFindParent<EditableTextBlock>((DependencyObject)e.OriginalSource);
- if (etb == null || etb != etbInEdit)
- {
- etbInEdit.Done();
- etbInEdit = null;
- }
- }
- }
-
- /// <summary>
- /// Event handler that saves the changed width of the navigation pane
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void VerticalSplitter_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
- {
- SettingsManager.NavigationPaneWidth = NavigationColumn.Width.Value;
- }
-
- /// <summary>
- /// Event handler that saves the changed height of the details pane
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void HorizontalSplitter_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
- {
- SettingsManager.DetailsPaneHeight = DetailsRow.Height.Value;
- }
-
- /// <summary>
- /// Prevents the size of DetailsPane from become too large
- /// because of the behaviour of the GridSplitter.
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void DetailsPane_SizeChanged(object sender, SizeChangedEventArgs e)
- {
- double a = MainFrame.ActualHeight;
- double b = RootPanel.ActualHeight;
- double total = MainFrame.ActualHeight;
- double occupied = TopToolbar.ActualHeight + MusicPane.ActualHeight;
- double free = total - occupied;
-
- if (DetailsRow.Height.Value > free)
- DetailsRow.Height = new GridLength(free);
- }
-
- /// <summary>
- /// Invoked when a field is edited inside the details pane.
- /// Will update the file tags.
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void DetailsPane_FieldEdited(object sender, FieldEditedEventArgs e)
- {
- switch (e.Field)
- {
- case "Artist":
- currentlySelectedTrack.Artist = e.Value;
- break;
-
- case "Album":
- currentlySelectedTrack.Album = e.Value;
- break;
-
- case "Title":
- currentlySelectedTrack.Title = e.Value;
- break;
-
- case "Genre":
- currentlySelectedTrack.Genre = e.Value;
- break;
-
- case "Year":
- currentlySelectedTrack.Year = Convert.ToUInt32(e.Value);
- break;
- }
-
- try
- {
- FilesystemManager.SaveTrack(currentlySelectedTrack);
- DetailsPane.SetField(e.Field, e.Value);
- }
- catch (Exception exc)
- {
- MessageBox.Show("Error saving: " + currentlySelectedTrack.Path + "\n\n" + exc.Message, "Could Not Write Tag", MessageBoxButton.OK, MessageBoxImage.Error);
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void FilesystemManager_SourceModified(object sender, SourceModifiedEventArgs e)
- {
- sourceModifiedDelay.Stop();
-
- sourceModifiedCallback = e.Callback;
- sourceModifiedCallbackParams = e.CallbackParams;
-
- if (sourceModifiedTracks.ContainsKey(e.Track))
- sourceModifiedTracks[e.Track] = e.ModificationType;
- else
- sourceModifiedTracks.Add(e.Track, e.ModificationType);
-
- sourceModifiedDelay.Start();
- }
-
- /// <summary>
- /// Invoked when a source has been added
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void FilesystemManager_SourceAdded(object sender, SourcesModifiedEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- SettingsManager.Sources.Add(e.Source);
- }));
- }
-
- /// <summary>
- /// Invoked when a source has been removed
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void FilesystemManager_SourceRemoved(object sender, SourcesModifiedEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- SettingsManager.Sources.Remove(e.Source);
- }));
- }
-
- /// <summary>
- /// Invoked when something happens to a track.
- /// Updates the library/queue/history time and the TrackList(s) of the parent.
- /// </summary>
- /// <param name="sender">Sender of the event</param>
- /// <param name="e">Event arguments</param>
- private void FilesystemManager_TrackModified(object sender, PropertyChangedEventArgs e)
- {
- TrackData track = sender as TrackData;
- if (!pathsThatWasChanged.Contains(track.Path))
- {
- pathsThatWasChanged.Add(track.Path);
- resortDelay.Stop();
- resortDelay.Start();
- }
-
- if (e.PropertyName != "RawLength") return;
-
- // update time trackers
- LibraryTime += track.diff;
-
- if (SettingsManager.QueueTracks.Contains(track))
- QueueTime += track.diff;
-
- if (SettingsManager.HistoryTracks.Contains(track))
- HistoryTime += track.diff;
-
- foreach (PlaylistData p in SettingsManager.Playlists)
- if (p.Tracks.Contains(track))
- p.Time += track.diff;
-
- if (GetCurrentTrackList() != null && GetCurrentTrackList().Items.Contains(track))
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- if (SettingsManager.CurrentSelectedNavigation == "Files")
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)LibraryTime));
- else if (SettingsManager.CurrentSelectedNavigation == "History")
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)HistoryTime));
- else if (SettingsManager.CurrentSelectedNavigation == "Queue")
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)QueueTime));
- else if (SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- {
- String playlistName = SettingsManager.CurrentSelectedNavigation.Split(new[]{':'},2)[1];
- PlaylistData pl = PlaylistManager.FindPlaylist(playlistName);
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)pl.Time));
- }
- }));
- }
- }
-
- /// <summary>
- /// Invoked when a file or folder has been renamed
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void FilesystemManager_PathRenamed(object sender, RenamedEventArgs e)
- {
- foreach (TrackData track in SettingsManager.FileTracks)
- if (track.Path.StartsWith(e.OldName))
- track.Path = track.Path.Replace(e.OldName, e.Name);
-
- foreach (TrackData track in SettingsManager.HistoryTracks)
- if (track.Path.StartsWith(e.OldName))
- track.Path = track.Path.Replace(e.OldName, e.Name);
-
- foreach (TrackData track in SettingsManager.QueueTracks)
- if (track.Path.StartsWith(e.OldName))
- track.Path = track.Path.Replace(e.OldName, e.Name);
-
- foreach (PlaylistData playlist in SettingsManager.Playlists)
- foreach (TrackData track in playlist.Tracks)
- if (track.Path.StartsWith(e.OldName))
- track.Path = track.Path.Replace(e.OldName, e.Name);
-
- foreach (SourceData src in SettingsManager.Sources)
- if (src.Data.StartsWith(e.OldName))
- src.Data.Replace(e.OldName, e.Name);
- }
-
- /// <summary>
- /// Invoked when a change is detected in a file
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void FilesystemManager_PathModified(object sender, PathModifiedEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- foreach (TrackData track in SettingsManager.FileTracks)
- if (track.Path == e.Path)
- FilesystemManager.UpdateTrack(track);
-
- foreach (TrackData track in SettingsManager.QueueTracks)
- if (track.Path == e.Path)
- FilesystemManager.UpdateTrack(track);
-
- foreach (TrackData track in SettingsManager.HistoryTracks)
- if (track.Path == e.Path)
- FilesystemManager.UpdateTrack(track);
-
- foreach (PlaylistData playlist in SettingsManager.Playlists)
- foreach (TrackData track in playlist.Tracks)
- if (track.Path == e.Path)
- FilesystemManager.UpdateTrack(track);
- }));
- }
-
- /// <summary>
- /// Invoked when a property of the settings manager changes
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void SettingsManager_PropertyChanged(object sender, PropertyChangedWithValuesEventArgs e)
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- switch (e.PropertyName)
- {
- case "DetailsPaneHeight":
- DetailsRow.Height = new GridLength(SettingsManager.DetailsPaneHeight);
- break;
-
- case "DetailsPaneVisible":
- UpdateVisibility("details");
- break;
-
- case "MenuBarVisible":
- UpdateVisibility("menubar");
- break;
-
- case "NavigationPaneWidth":
- NavigationColumn.Width = new GridLength(SettingsManager.NavigationPaneWidth);
- break;
-
- case "Language":
- LanguageContext.Instance.Culture = CultureInfo.GetCultureInfo(SettingsManager.Language);
- UpdateGUIStrings();
- break;
-
- case "CurrentActiveNavigation":
- ViewDetails vd = GetActiveTrackList();
- if (vd != null) MediaManager.TrackCollection = vd.Items;
- else MediaManager.TrackCollection = FileTracks.Items;
- break;
-
- case "CurrentTrack":
- if (SettingsManager.CurrentTrack == null)
- {
- NowPlayingContainer.InfoPaneTitle.Text = U.T("PlaybackEmpty");
- NowPlayingContainer.InfoPaneArtist.Text = "";
- }
- else
- {
- NowPlayingContainer.InfoPaneTitle.Text = SettingsManager.CurrentTrack.Title;
- NowPlayingContainer.InfoPaneArtist.Text = SettingsManager.CurrentTrack.Artist;
- }
- break;
-
- case "MediaState":
- switch (SettingsManager.MediaState)
- {
- case MediaState.Playing:
- if (taskbarPlay != null) taskbarPlay.Icon = Properties.Resources.Pause;
- if (trayMenuPlay != null) trayMenuPlay.Header = "Pause";
- if (jumpTaskPlay != null) jumpTaskPlay.Title = "Pause";
- if (YouTubeManager.IsYouTube(SettingsManager.CurrentTrack))
- {
- MediaManager.Browser.Visibility = System.Windows.Visibility.Visible;
- if (!NowPlayingContainer.Video.Children.Contains(MediaManager.Browser))
- NowPlayingContainer.Video.Children.Add(MediaManager.Browser);
- NowPlayingContainer.NoVideoMessage.Visibility = System.Windows.Visibility.Collapsed;
- }
- else
- {
- MediaManager.Browser.Visibility = System.Windows.Visibility.Collapsed;
- NowPlayingContainer.Video.Children.Remove(MediaManager.Browser);
- NowPlayingContainer.NoVideoMessage.Visibility = System.Windows.Visibility.Visible;
- }
- break;
-
- case MediaState.Paused:
- case MediaState.Stopped:
- if (taskbarPlay != null) taskbarPlay.Icon = Properties.Resources.Play;
- if (trayMenuPlay != null) trayMenuPlay.Header = "Play";
- if (jumpTaskPlay != null) jumpTaskPlay.Title = "Play";
- break;
- }
- break;
-
- case "QueueListConfig":
- QueueTracks.Config = SettingsManager.QueueListConfig;
- break;
-
- case "HistoryListConfig":
- HistoryTracks.Config = SettingsManager.HistoryListConfig;
- break;
-
- case "FileListConfig":
- FileTracks.Config = SettingsManager.FileListConfig;
- break;
- }
- }));
- }
-
- /// <summary>
- /// Invoked when an error occured in the YouTube player
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="message">The error message</param>
- private void YouTube_ErrorOccured(object sender, string message)
- {
- int errorCode = Convert.ToInt32(message);
- if (showMediaError)
- {
- showMediaError = false;
- switch (errorCode)
- {
- case 2:
- MessageBox.Show(
- U.T("MessageYouTubeBadParams", "Message"),
- U.T("MessageYouTubeBadParams", "Title"),
- MessageBoxButton.OK,
- MessageBoxImage.Error
- );
- break;
-
- case 100:
- MessageBox.Show(
- U.T("MessageYouTubeNotFound", "Message"),
- U.T("MessageYouTubeNotFound", "Title"),
- MessageBoxButton.OK,
- MessageBoxImage.Error
- );
- break;
-
- case 101:
- case 150: // restricted
- MediaManager.Next();
- break;
-
- default:
- MessageBox.Show(
- U.T("MessageYouTubeUnknown", "Message"),
- String.Format(U.T("MessageYouTubeUnknown", "Title"), message),
- MessageBoxButton.OK,
- MessageBoxImage.Error
- );
- break;
- }
- MediaManager.Stop();
- }
- }
-
- /// <summary>
- /// Invoked when the YouTube player complains that there is no flash installed
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void YouTube_NoFlashDetected(object sender, EventArgs e)
- {
- if (showMediaError)
- {
- showMediaError = false;
- YouTubeManager.HasFlash = false;
- MessageBoxResult r = MessageBox.Show(
- U.T("MessageNoFlash", "Message"),
- U.T("MessageNoFlash", "Title"),
- MessageBoxButton.YesNo,
- MessageBoxImage.Error
- );
- if (r == MessageBoxResult.Yes)
- {
- System.Diagnostics.Process.Start("IEXPLORE.EXE", "http://get.adobe.com/flashplayer");
- }
- MediaManager.Stop();
- }
-
- }
-
- /// <summary>
- /// Invoked when the YouTube player is ready
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void YouTube_PlayerReady(object sender, EventArgs e)
- {
- YouTubeManager.HasFlash = true;
- MediaManager.LoadYouTube();
- }
-
- /// <summary>
- /// Adds or removes a track from the library collection
- /// </summary>
- /// <param name="sender">The sender of the event (the timer)</param>
- /// <param name="e">The event data</param>
- private void SourceModifiedDelay_Tick(object sender, EventArgs e)
- {
- sourceModifiedDelay.Stop();
- ScanProgressBar.IsIndeterminate = true;
- ScanProgress.Visibility = System.Windows.Visibility.Visible;
-
- ThreadStart GUIScanThread = delegate()
- {
- // copy the tracks into two lists
- SortedSet<string> trackPaths = new SortedSet<string>();
- List<TrackData> tracksToAdd = new List<TrackData>();
- SortedList<string, TrackData> tracksToRemove = new SortedList<string, TrackData>();
- List<TrackData> tracksToUpdate = new List<TrackData>();
- foreach (DictionaryEntry de in sourceModifiedTracks)
- {
- SourceModificationType modType = (SourceModificationType)de.Value;
- TrackData track = (TrackData)de.Key;
- if (modType == SourceModificationType.Added)
- tracksToAdd.Add(track);
- else if (modType == SourceModificationType.Removed)
- {
- if (!tracksToRemove.ContainsKey(track.Path))
- tracksToRemove.Add(track.Path, track);
- }
- else
- tracksToUpdate.Add(de.Key as TrackData);
- }
- sourceModifiedTracks.Clear();
-
- // copy the observable collections so we can work on them
- // outside the gui thread
- ObservableCollection<TrackData> files = new ObservableCollection<TrackData>();
- foreach (TrackData t in SettingsManager.FileTracks)
- {
- files.Add(t);
- trackPaths.Add(t.Path);
- }
-
- // add tracks
- for (int j=0; j < tracksToAdd.Count; j++)
- {
- TrackData track = tracksToAdd[j];
- if (trackPaths.Contains(track.Path))
- tracksToAdd.RemoveAt(j--);
- else
- files.Add(track);
- }
-
- // update source for file list
- U.L(LogLevel.Debug, "MAIN", "Adding tracks to GUI list");
- Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(delegate()
- {
- SettingsManager.FileTracks = files;
- SettingsManager.FileTracks.CollectionChanged += new NotifyCollectionChangedEventHandler(LibraryTracks_CollectionChanged);
- FileTracks.ItemsSource = files;
- if (SettingsManager.CurrentSelectedNavigation == "Files")
- InfoPaneTracks.Text = SettingsManager.FileTracks.Count + " " + U.T("HeaderTracks", "Text");
- ScanProgressBar.IsIndeterminate = false;
- }));
-
- // remove tracks
- U.L(LogLevel.Debug, "MAIN", "Tracks to remove: " + tracksToRemove.Count);
- if (tracksToRemove.Count > 0)
- {
- U.L(LogLevel.Debug, "MAIN", "Removing tracks");
- Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(delegate()
- {
- foreach (PlaylistData p in SettingsManager.Playlists)
- RemoveTracks(tracksToRemove, p.Tracks);
- RemoveTracks(tracksToRemove, SettingsManager.QueueTracks);
- RemoveTracks(tracksToRemove, SettingsManager.HistoryTracks);
- RemoveTracks(tracksToRemove, SettingsManager.FileTracks);
- }));
- }
-
- // update tracks
- double progressDelta = 100.0 / (double)(tracksToAdd.Count + tracksToUpdate.Count);
- U.L(LogLevel.Debug, "MAIN", "Updating tracks");
- DateTime start = DateTime.Now;
- int numTracks = tracksToAdd.Count + tracksToUpdate.Count;
- double progress = 0;
- for (int j=0; j < tracksToAdd.Count; j++)
- {
- TrackData track = tracksToAdd[j];
- if (FilesystemManager.ProgramIsClosed) return;
- FilesystemManager.UpdateTrack(track, false);
- if (j % 100 == 0)
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- ScanProgressBar.Value = progress;
- }));
- }
- progress += progressDelta;
- }
- for (int j=0; j < tracksToUpdate.Count; j++)
- {
- TrackData track = tracksToUpdate[j];
- if (FilesystemManager.ProgramIsClosed) return;
- FilesystemManager.UpdateTrack(track, false);
- if (j % 100 == 0)
- {
- Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
- {
- ScanProgressBar.Value = progress;
- }));
- }
- progress += progressDelta;
- }
- TimeSpan ts = (DateTime.Now - start);
- double time = Math.Round(ts.TotalMilliseconds / numTracks, 2);
- U.L(LogLevel.Debug, "FILESYSTEM", String.Format("Scanning meta took {0} seconds, an average of {1} ms/track", Math.Round(ts.TotalSeconds, 2), time));
-
- // hide progressbar
- Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(delegate()
- {
- ScanProgress.Visibility = System.Windows.Visibility.Collapsed;
- }));
-
- // call callback
- if (sourceModifiedCallback != null)
- sourceModifiedCallback(sourceModifiedCallbackParams);
- sourceModifiedCallback = null;
- sourceModifiedCallbackParams = null;
-
- U.L(LogLevel.Debug, "MAIN", "Scan complete");
-
- };
- Thread gs_thread = new Thread(GUIScanThread);
- gs_thread.Name = "GUI scan updater";
- gs_thread.IsBackground = true;
- gs_thread.Priority = ThreadPriority.Lowest;
- gs_thread.Start();
- }
-
- /// <summary>
- /// Reapplies the sorting on a TrackList when a track was changed.
- ///
- /// This method is called from a Timer in order to prevent many calls from being made in a short period of time.
- /// </summary>
- /// <param name="sender">The sender of the event (the timer)</param>
- /// <param name="e">The event data</param>
- private void ResortDelay_Tick(object sender, EventArgs e)
- {
- resortDelay.IsEnabled = false;
- ResortTracklist(FileTracks, pathsThatWasChanged);
- ResortTracklist(HistoryTracks, pathsThatWasChanged);
- ResortTracklist(QueueTracks, pathsThatWasChanged);
- foreach (DictionaryEntry o in PlaylistTrackLists)
- ResortTracklist((ViewDetails)o.Value, pathsThatWasChanged);
- pathsThatWasChanged.Clear();
- }
-
- /// <summary>
- /// Invoked when something happens to the library collection.
- /// Updates the library time and the library TrackList.
- /// </summary>
- /// <param name="sender">Sender of the event</param>
- /// <param name="e">Event arguments</param>
- private void LibraryTracks_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
- {
- LibraryTime = 0;
- foreach (TrackData t in SettingsManager.FileTracks)
- LibraryTime += t.RawLength;
-
- if (SettingsManager.CurrentSelectedNavigation == "Files")
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- InfoPaneTracks.Text = SettingsManager.FileTracks.Count + " " + U.T("HeaderTracks", "Text");
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)LibraryTime));
- }));
- }
- }
-
- /// <summary>
- /// Invoked when something happens to the queue collection.
- /// Updates the queue time and the queue TrackList.
- /// </summary>
- /// <param name="sender">Sender of the event</param>
- /// <param name="e">Event arguments</param>
- private void QueueTracks_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
- {
- QueueTime = 0;
- foreach (TrackData t in SettingsManager.QueueTracks)
- QueueTime += t.RawLength;
-
- if (SettingsManager.CurrentSelectedNavigation == "Queue")
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- // are all selected items removed?
- bool allRemoved = true;
- foreach (TrackData selectedTrack in QueueTracks.SelectedItems)
- {
- if (!e.OldItems.Contains(selectedTrack))
- {
- allRemoved = false;
- break;
- }
- }
-
- LanguageDictionary dictionary = LanguageDictionary.GetDictionary(LanguageContext.Instance.Culture);
- string tracks = dictionary.Translate("HeaderTracks", "Text", "tracks", typeof(string)) as string;
- InfoPaneTracks.Text = SettingsManager.QueueTracks.Count + " " + U.T("HeaderTracks", "Text");
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)QueueTime));
-
- // select the last item that is not being removed
- if (allRemoved && QueueTracks.SelectedItems.Count > 0)
- {
- if (QueueTracks.Items.Count > 0)
- {
- int indexToSelect = e.OldStartingIndex >= QueueTracks.Items.Count ? QueueTracks.Items.Count - 1 : e.OldStartingIndex;
- QueueTracks.FocusAndSelectItem(indexToSelect);
- }
- }
- }));
- }
- }
-
- /// <summary>
- /// Invoked when something happens to the history collection.
- /// Updates the history time and the history TrackList.
- /// </summary>
- /// <param name="sender">Sender of the event</param>
- /// <param name="e">Event arguments</param>
- private void HistoryTracks_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
- {
- HistoryTime = 0;
- foreach (TrackData t in SettingsManager.HistoryTracks)
- HistoryTime += t.RawLength;
-
- if (SettingsManager.CurrentSelectedNavigation == "History")
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- LanguageDictionary dictionary = LanguageDictionary.GetDictionary(LanguageContext.Instance.Culture);
- string tracks = dictionary.Translate("HeaderTracks", "Text", "tracks", typeof(string)) as string;
- InfoPaneTracks.Text = SettingsManager.HistoryTracks.Count + " " + U.T("HeaderTracks", "Text");
- InfoPaneDuration.Text = U.TimeSpanToLongString(new TimeSpan(0, 0, (int)HistoryTime));
- }));
- }
- }
-
- /// <summary>
- /// Invoked when the selection of a track list changes
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void TrackList_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- ViewDetails vd = sender as ViewDetails;
- if (vd.SelectedItem == null)
- DetailsPane.Clear();
- else
- {
- TrackData track = vd.SelectedItem as TrackData;
- currentlySelectedTrack = track;
- DetailsPane.Clear();
- DetailsPane.Description = MediaManager.TrackType(track);
-
- if (YouTubeManager.IsYouTube(track))
- {
- DetailsPane.Title = track.Title;
- DetailsPane.AddField(U.T("ColumnArtist"), track.Artist);
- DetailsPane.AddField(U.T("ColumnViews"), track.Views);
- DetailsPane.AddField(U.T("ColumnPath"), YouTubeManager.GetURL(track));
- }
- else
- {
- DetailsPane.Title = Path.GetFileName(track.Path);
- DetailsPane.AddField(U.T("ColumnArtist"), track.Artist, true);
- DetailsPane.AddField(U.T("ColumnTitle"), track.Title, true);
- DetailsPane.AddField(U.T("ColumnAlbum"), track.Album, true);
- DetailsPane.AddField(U.T("ColumnGenre"), track.Genre, true);
- DetailsPane.AddField(U.T("ColumnLength"), track.Length);
- if (File.Exists(track.Path))
- {
- FileInfo fi = new FileInfo(track.Path);
- DetailsPane.AddField(U.T("ColumnSize"), U.HumanSize(fi.Length));
- }
- DetailsPane.AddField(U.T("ColumnBitrate"), String.Format(U.T("BeatsPerMinute"), track.Bitrate));
- DetailsPane.AddField(U.T("ColumnYear"), track.Year.ToString(), true);
- DetailsPane.AddField(U.T("ColumnPlayCount"), track.PlayCount.ToString());
- DetailsPane.AddField(U.T("ColumnLastPlayed"), track.LastPlayed);
- DetailsPane.AddField(U.T("ColumnChannels"), track.Channels.ToString());
- DetailsPane.AddField(U.T("ColumnSampleRate"), track.SampleRate.ToString());
- DetailsPane.AddField(U.T("ColumnCodecs"), track.Codecs);
- DetailsPane.AddField(U.T("ColumnPath"), track.Path);
- }
-
- // set image in a background thread
- ThreadStart DetailsImageThread = delegate()
- {
- Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(delegate()
- {
- DetailsPane.Image = FilesystemManager.GetImageTag(track);
- }));
- };
- Thread di_thread = new Thread(DetailsImageThread);
- di_thread.Name = "Details Image";
- di_thread.IsBackground = true;
- di_thread.Priority = ThreadPriority.Lowest;
- di_thread.Start();
- }
- }
-
- /// <summary>
- /// Evaluates if a given track matches a specific string
- /// </summary>
- /// <param name="item">The track to match</param>
- /// <param name="needles">The string to match the track against</param>
- /// <returns>true if the track matches the string, otherwise false</returns>
- private bool TrackList_SearchMatch(object item, string needles)
- {
- if (needles == null || needles == "") return true;
-
- TrackData track = (TrackData)item;
-
- String artist = track.Artist == null ? "" : track.Artist.ToLower();
- String album = track.Album == null ? "" : track.Album.ToLower();
- String title = track.Title == null ? "" : track.Title.ToLower();
- String genre = track.Genre == null ? "" : track.Genre.ToLower();
- String year = track.Year.ToString().ToLower();
- String path = track.Path.ToLower();
-
- foreach (String needle in needles.ToLower().Split(' '))
- {
- if (!artist.Contains(needle) &&
- !album.Contains(needle) &&
- !title.Contains(needle) &&
- !genre.Contains(needle) &&
- !year.Contains(needle) &&
- !path.Contains(needle))
- return false;
- }
- return true;
- }
-
- /// <summary>
- /// Invoked when files are dropped on a track list
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void TrackList_FilesDropped(object sender, FileDropEventArgs e)
- {
- ViewDetails vd = GetCurrentTrackList();
- if (vd == null || vd == HistoryTracks) return;
-
- foreach (string path in e.Paths)
- {
- // create callback params
- List<object> l = new List<object>();
- l.Add(vd as object);
- l.Add(e as object);
- l.Add(path as object);
-
- // add source?
- bool addSource = false;
- foreach (SourceData source in SettingsManager.Sources)
- {
- if (source.Data == path)
- {
- addSource = true;
- break;
- }
- }
- if (!addSource)
- FilesystemManager.AddSource(path, TrackList_MoveNewlyAdded, l as object);
- else
- TrackList_MoveNewlyAdded(l as object);
- }
- }
-
- /// <summary>
- /// Invoked when a new source has been added after a file drop
- /// after the scan has finished.
- /// </summary>
- /// <param name="param">
- /// A list of three objects:
- /// * The ViewDetails that was dropped upon
- /// * The FileDropEventArgs containing the event data for the drop
- /// * The string of the path that was scanned
- /// </param>
- private void TrackList_MoveNewlyAdded(object param)
- {
- Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
- {
- // extract parameters
- List<object> l = param as List<object>;
- ViewDetails vd = l[0] as ViewDetails;
- FileDropEventArgs e = l[1] as FileDropEventArgs;
- string path = l[2] as string;
-
- // remove sorting but keep positions
- vd.ClearSort(true);
-
- int p = e.Position;
-
- if (vd == FileTracks)
- {
- for (int i = 0; i < SettingsManager.FileTracks.Count; i++)
- {
- TrackData t = SettingsManager.FileTracks[i];
- if (t.Path.StartsWith(path) && i != (i >= p ? p : p - 1))
- {
- SettingsManager.FileTracks.Remove(t);
- if (i >= p) // move back
- {
- SettingsManager.FileTracks.Insert(p++, t);
- }
- else // move forward
- {
- SettingsManager.FileTracks.Insert(p - 1, t);
- i--;
- }
- }
- }
- }
- else
- {
- ObservableCollection<TrackData> source = GetCurrentTrackCollection();
- if (source != null)
- {
- List<TrackData> libTracks = U.GetTracks(SettingsManager.FileTracks, path);
-
- if (vd == QueueTracks)
- {
- MediaManager.Queue(libTracks, e.Position);
- }
- else if (SettingsManager.CurrentSelectedNavigation.StartsWith("Playlist:"))
- {
- String playlistName = SettingsManager.CurrentSelectedNavigation.Split(new[] { ':' }, 2)[1];
- PlaylistManager.AddToPlaylist(libTracks, playlistName, e.Position);
- }
- }
- // find tracks in library
- // each track:
- // if addSource:
- // check for tracks in track list
- // if found: move and break
- // insert
- Console.WriteLine("check each track, move or insert to queue/playlist at " + e.Position);
- }
- }));
- }
-
- /// <summary>
- /// Invoked when an item needs to be moved in a track list
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void TrackList_MoveItem(object sender, MoveItemEventArgs e)
- {
- TrackData track = e.Item as TrackData;
- ViewDetails vd = sender as ViewDetails;
- ObservableCollection<TrackData> tracks = GetCurrentTrackCollection();
- int i = tracks.IndexOf(track);
- Console.WriteLine(String.Format("[moveitem] #{0}->{1}: {2} - {3}", e.Position, i, track.Artist, track.Title));
- if (i == e.Position) return; // already at position
- int j = i < e.Position ? e.Position - 1 : e.Position;
- Console.WriteLine(String.Format("[inserting] #{0}: {1} - {2}", j, track.Artist, track.Title));
- tracks.Remove(track);
- tracks.Insert(j, track);
-
- }
-
- /// <summary>
- /// Invoked when the upgrade button is clicked.
- /// Will restart the application.
- /// </summary>
- /// <param name="sender">The sender of the event</param>
- /// <param name="e">The event data</param>
- private void UpgradeButton_Click(object sender, RoutedEventArgs e)
- {
- Restart();
- }
-
- #endregion
-
- #endregion
-
- #region Events
-
- /// <summary>
- ///
- /// </summary>
- public event PropertyChangedEventHandler PropertyChanged;
-
- #endregion
- }
- }