From bbafa06df23e7756a9ad828e4ff32a41dc089796 Mon Sep 17 00:00:00 2001 From: ycastonguay Date: Sat, 17 Aug 2013 23:50:42 -0400 Subject: [PATCH] Windows: Library Browser in Main window is now partially working. UpdateLibrary window can now be opened. More cleanup in frmMain.cs. Related to issue #422. --- .../Services/InitializationService.cs | 36 + ...lsSongGridViewQueryConfigurationSection.cs | 10 +- .../Configuration/MPfmConfiguration.cs | 10 +- .../MPfm.Windows/Classes/Forms/frmFirstRun.cs | 20 +- MPfm/MPfm.Windows/Classes/Forms/frmMain.cs | 1031 +++-------------- ...signer.cs => frmUpdateLibrary.Designer.cs} | 10 +- .../Classes/Forms/frmUpdateLibrary.cs | 337 ++++++ ...braryStatus.resx => frmUpdateLibrary.resx} | 0 .../Classes/Forms/frmUpdateLibraryStatus.cs | 564 --------- MPfm/MPfm.Windows/Classes/Program.cs | 32 +- MPfm/MPfm.Windows/MPfm.Windows.csproj | 14 +- 11 files changed, 595 insertions(+), 1469 deletions(-) rename MPfm/MPfm.Windows/Classes/Forms/{frmUpdateLibraryStatus.Designer.cs => frmUpdateLibrary.Designer.cs} (99%) create mode 100644 MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.cs rename MPfm/MPfm.Windows/Classes/Forms/{frmUpdateLibraryStatus.resx => frmUpdateLibrary.resx} (100%) delete mode 100644 MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.cs diff --git a/MPfm/MPfm.MVP/Services/InitializationService.cs b/MPfm/MPfm.MVP/Services/InitializationService.cs index 394b97a4..50b62f07 100644 --- a/MPfm/MPfm.MVP/Services/InitializationService.cs +++ b/MPfm/MPfm.MVP/Services/InitializationService.cs @@ -52,6 +52,11 @@ public InitializationService(IAudioFileCacheService audioFileCacheService, ISync /// public void Initialize() { + //// Get application data folder path + //// Vista/Windows7: C:\Users\%username%\AppData\Roaming\ + //// XP: C:\Documents and Settings\%username%\Application Data\ + //applicationDataFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MPfm"; + // Check if the .MPfm directory exists string directoryPath = ConfigurationHelper.HomeDirectory; if(!Directory.Exists(directoryPath)) @@ -104,6 +109,37 @@ void LoadConfiguration() //ConfigurationHelper.Save(ConfigurationHelper.ConfigurationFilePath, MPfmConfig.Instance); //EQPreset preset = EQPresetHelper.Load("/Users/animal/Documents/test.txt"); //EQPresetHelper.Save("/Users/animal/Documents/test.txt", new EQPreset()); + + + // Also create peak file directory if it doesn't exist + + //// Check if the configuration file exists + //if (File.Exists(configurationFilePath)) + //{ + // // Load configuration values + // config.Load(); + + // // Load peak file options + // bool? peakFileUseCustomDirectory = Config.GetKeyValueGeneric("PeakFile_UseCustomDirectory"); + // string peakFileCustomDirectory = Config.GetKeyValue("PeakFile_CustomDirectory"); + + // // Set peak file directory + // if (peakFileUseCustomDirectory.HasValue && peakFileUseCustomDirectory.Value) + // { + // // Set custom peak file directory + // PeakFileFolderPath = peakFileCustomDirectory; + // } + // else + // { + // // Set default peak file directory + // PeakFileFolderPath = applicationDataFolderPath + "\\Peak Files\\"; + // } + //} + //else + //{ + // // Set default peak file directory + // PeakFileFolderPath = applicationDataFolderPath + "\\Peak Files\\"; + //} } void LoadLibrary() diff --git a/MPfm/MPfm.Windows/Classes/Configuration/Controls/ControlsSongGridViewQueryConfigurationSection.cs b/MPfm/MPfm.Windows/Classes/Configuration/Controls/ControlsSongGridViewQueryConfigurationSection.cs index fdd4fedb..b40fde51 100644 --- a/MPfm/MPfm.Windows/Classes/Configuration/Controls/ControlsSongGridViewQueryConfigurationSection.cs +++ b/MPfm/MPfm.Windows/Classes/Configuration/Controls/ControlsSongGridViewQueryConfigurationSection.cs @@ -32,10 +32,10 @@ namespace MPfm /// public class ControlsSongGridViewQueryConfigurationSection { - /// - /// Tree library node type. - /// - public TreeLibraryNodeType NodeType { get; set; } + ///// + ///// Tree library node type. + ///// + //public TreeLibraryNodeType NodeType { get; set; } /// /// Audio file identifier. /// @@ -59,7 +59,7 @@ public class ControlsSongGridViewQueryConfigurationSection public ControlsSongGridViewQueryConfigurationSection() { // Set default values - NodeType = TreeLibraryNodeType.AllSongs; + //NodeType = TreeLibraryNodeType.AllSongs; AudioFileId = Guid.Empty; PlaylistId = Guid.Empty; ArtistName = string.Empty; diff --git a/MPfm/MPfm.Windows/Classes/Configuration/MPfmConfiguration.cs b/MPfm/MPfm.Windows/Classes/Configuration/MPfmConfiguration.cs index 76f4d4b4..739d9320 100644 --- a/MPfm/MPfm.Windows/Classes/Configuration/MPfmConfiguration.cs +++ b/MPfm/MPfm.Windows/Classes/Configuration/MPfmConfiguration.cs @@ -243,10 +243,10 @@ public void Load() // Check if this XML element was found if (elementSongGridViewQuery != null) { - // Get node type - TreeLibraryNodeType nodeType; - Enum.TryParse(XMLHelper.GetAttributeValue(elementSongGridViewQuery, "type"), out nodeType); - controlsSection.SongGridView.Query.NodeType = nodeType; + //// Get node type + //TreeLibraryNodeType nodeType; + //Enum.TryParse(XMLHelper.GetAttributeValue(elementSongGridViewQuery, "type"), out nodeType); + //controlsSection.SongGridView.Query.NodeType = nodeType; // Set other query properties controlsSection.SongGridView.Query.AudioFileId = XMLHelper.GetAttributeValueGeneric(elementSongGridViewQuery, "audioFileId"); @@ -468,7 +468,7 @@ public void RefreshXML() XElement elementControlsPlaylistGridViewColumns = new XElement("columns"); // Song browser query - elementControlsSongGridViewQuery.Add(XMLHelper.NewAttribute("type", controlsSection.SongGridView.Query.NodeType.ToString())); + //elementControlsSongGridViewQuery.Add(XMLHelper.NewAttribute("type", controlsSection.SongGridView.Query..ToString())); elementControlsSongGridViewQuery.Add(XMLHelper.NewAttribute("audioFileId", controlsSection.SongGridView.Query.AudioFileId.ToString())); elementControlsSongGridViewQuery.Add(XMLHelper.NewAttribute("playlistId", controlsSection.SongGridView.Query.PlaylistId.ToString())); elementControlsSongGridViewQuery.Add(XMLHelper.NewAttribute("artistName", controlsSection.SongGridView.Query.ArtistName)); diff --git a/MPfm/MPfm.Windows/Classes/Forms/frmFirstRun.cs b/MPfm/MPfm.Windows/Classes/Forms/frmFirstRun.cs index f16806b9..5dae309f 100644 --- a/MPfm/MPfm.Windows/Classes/Forms/frmFirstRun.cs +++ b/MPfm/MPfm.Windows/Classes/Forms/frmFirstRun.cs @@ -156,19 +156,19 @@ private void btnCancelWizard_Click(object sender, EventArgs e) /// Event arguments private void btnNext_Click(object sender, EventArgs e) { - // Get selected driver - DriverComboBoxItem driver = (DriverComboBoxItem)cboDrivers.SelectedItem; + //// Get selected driver + //DriverComboBoxItem driver = (DriverComboBoxItem)cboDrivers.SelectedItem; - // Get selected device - Device device = (Device)cboOutputDevices.SelectedItem; + //// Get selected device + //Device device = (Device)cboOutputDevices.SelectedItem; - // Save configuration - Main.Config.Audio.Device = device; - Main.Config.Audio.DriverType = driver.DriverType; + //// Save configuration + //Main.Config.Audio.Device = device; + //Main.Config.Audio.DriverType = driver.DriverType; - int frequency = 44100; - int.TryParse(cboSampleRate.Text, out frequency); - Main.Config.Audio.Mixer.Frequency = frequency; + //int frequency = 44100; + //int.TryParse(cboSampleRate.Text, out frequency); + //Main.Config.Audio.Mixer.Frequency = frequency; // Close wizard DialogResult = System.Windows.Forms.DialogResult.OK; diff --git a/MPfm/MPfm.Windows/Classes/Forms/frmMain.cs b/MPfm/MPfm.Windows/Classes/Forms/frmMain.cs index 94b2bef5..6898c6e4 100644 --- a/MPfm/MPfm.Windows/Classes/Forms/frmMain.cs +++ b/MPfm/MPfm.Windows/Classes/Forms/frmMain.cs @@ -45,12 +45,6 @@ namespace MPfm.Windows.Classes.Forms /// public partial class frmMain : BaseForm, IMainView { - // Private variables - private Stream fileTracing = null; - private TextWriterTraceListener textTraceListener = null; - private string configurationFilePath = string.Empty; - private string databaseFilePath = string.Empty; - private string logFilePath = string.Empty; private string initOpenNodeArtist = string.Empty; private string initOpenNodeArtistAlbum = string.Empty; private string initOpenNodeAlbum = string.Empty; @@ -81,26 +75,6 @@ public partial class frmMain : BaseForm, IMainView /// public TreeNode nodeRecentlyPlayed = null; - /// - /// Timer for updating song position. - /// - public System.Windows.Forms.Timer timerSongPosition = null; - - /// - /// Private value for the Config property. - /// - private MPfmConfiguration config = null; - /// - /// This contains the configuration values for MPfm. - /// - public MPfmConfiguration Config - { - get - { - return config; - } - } - #endregion #region Initialization @@ -118,330 +92,34 @@ public frmMain(Action onViewReady) : base (onViewReady) /// Event arguments private void frmMain_Load(object sender, EventArgs e) { - // Load configuration - try - { - // Get assembly version - Assembly assembly = Assembly.GetExecutingAssembly(); - - // Set form title - this.Text = "MPfm: Music Player for Musicians - " + assembly.GetName().Version.ToString(); - - //// Get application data folder path - //// Vista/Windows7: C:\Users\%username%\AppData\Roaming\ - //// XP: C:\Documents and Settings\%username%\Application Data\ - //applicationDataFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MPfm"; - - //// Check if the folder exists - //if (!Directory.Exists(applicationDataFolderPath)) - //{ - // // Create directory - // frmSplash.SetStatus("Creating application data folder..."); - // Directory.CreateDirectory(applicationDataFolderPath); - //} - - //// Set paths - //configurationFilePath = applicationDataFolderPath + "\\MPfm.Configuration.xml"; - //databaseFilePath = applicationDataFolderPath + "\\MPfm.Database.db"; - //logFilePath = applicationDataFolderPath + "\\MPfm.Log.txt"; - - //// Set control paths - //waveFormMarkersLoops.PeakFileDirectory = peakFileFolderPath + "\\"; - - //// Initialize tracing - //frmSplash.SetStatus("Main form init -- Initializing tracing..."); - - //// Check if trace file exists - //if (!File.Exists(logFilePath)) - //{ - // // Create file - // fileTracing = File.Create(logFilePath); - //} - //else - //{ - // try - // { - // // Open file - // fileTracing = File.Open(logFilePath, FileMode.Append); - // } - // catch - // { - // throw; - // } - //} - - //// Configure trace - //textTraceListener = new TextWriterTraceListener(fileTracing); - //Trace.Listeners.Add(textTraceListener); - - //// Start log - //Tracing.LogWithoutTimeStamp(""); - //Tracing.LogWithoutTimeStamp("******************************************************************************"); - //Tracing.LogWithoutTimeStamp("MPfm: Music Player for Musicians - Version " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); - //Tracing.LogWithoutTimeStamp("Started at: " + DateTime.Now.ToString()); - //Tracing.LogWithoutTimeStamp(""); - - //// Output paths - //Tracing.Log("Main form init -- Application data folder: " + applicationDataFolderPath); - //Tracing.Log("Main form init -- Configuration file path: " + configurationFilePath); - //Tracing.Log("Main form init -- Database file path: " + databaseFilePath); - //Tracing.Log("Main form init -- Log file path: " + logFilePath); - - //// Create configuration with default settings - //Tracing.Log("Main form init -- Loading configuration..."); - //frmSplash.SetStatus("Loading configuration..."); - //config = new MPfmConfiguration(configurationFilePath); - - //// Check if the configuration file exists - //if (File.Exists(configurationFilePath)) - //{ - // // Load configuration values - // config.Load(); - - // // Load peak file options - // bool? peakFileUseCustomDirectory = Config.GetKeyValueGeneric("PeakFile_UseCustomDirectory"); - // string peakFileCustomDirectory = Config.GetKeyValue("PeakFile_CustomDirectory"); - - // // Set peak file directory - // if (peakFileUseCustomDirectory.HasValue && peakFileUseCustomDirectory.Value) - // { - // // Set custom peak file directory - // PeakFileFolderPath = peakFileCustomDirectory; - // } - // else - // { - // // Set default peak file directory - // PeakFileFolderPath = applicationDataFolderPath + "\\Peak Files\\"; - // } - //} - //else - //{ - // // Set default peak file directory - // PeakFileFolderPath = applicationDataFolderPath + "\\Peak Files\\"; - //} - - //// Check if the peak folder exists - //if (!Directory.Exists(PeakFileFolderPath)) - //{ - // // Create directory - // frmSplash.SetStatus("Creating peak file folder..."); - // Directory.CreateDirectory(PeakFileFolderPath); - //} - - //try - //{ - // // Check if the database file exists - // if (!File.Exists(databaseFilePath)) - // { - // // Create database file - // frmSplash.SetStatus("Creating database file..."); - // MPfm.Library.Library.CreateDatabaseFile(databaseFilePath); - // } - //} - //catch (Exception ex) - //{ - // throw new Exception("Error initializing MPfm: Could not create database file!", ex); - //} - - //try - //{ - // // Check current database version - // string databaseVersion = MPfm.Library.Library.GetDatabaseVersion(databaseFilePath); - - // // Extract major/minor - // string[] currentVersionSplit = databaseVersion.Split('.'); - - // // Check integrity of the setting value (should be split in 2) - // if (currentVersionSplit.Length != 2) - // { - // throw new Exception("Error fetching database version; the setting value is invalid!"); - // } - - // int currentMajor = 0; - // int currentMinor = 0; - // int.TryParse(currentVersionSplit[0], out currentMajor); - // int.TryParse(currentVersionSplit[1], out currentMinor); - - // // Is this earlier than 1.04? - // if (currentMajor == 1 && currentMinor < 4) - // { - // // Set buffer size - // Config.Audio.Mixer.BufferSize = 1000; - // } - - // // Check if the database needs to be updated - // MPfm.Library.Library.CheckIfDatabaseVersionNeedsToBeUpdated(databaseFilePath); - //} - //catch (Exception ex) - //{ - // throw new Exception("Error initializing MPfm: The MPfm database could not be updated!", ex); - //} - } - catch (Exception ex) - { - Tracing.Log("Configuration error:" + ex.Message); - //frmSplash.SetError("Configuration error: " + ex.Message); - } - - //try - //{ - // // Create player - // Tracing.Log("Main form init -- Loading player..."); - // frmSplash.SetStatus("Loading player..."); - - // player = new MPfm.Player.Player(new Device(), Config.Audio.Mixer.Frequency, Config.Audio.Mixer.BufferSize, Config.Audio.Mixer.UpdatePeriod, false); - // player.OnPlaylistIndexChanged += new Player.Player.PlaylistIndexChanged(player_OnPlaylistIndexChanged); - //} - //catch - //{ - // throw; - //} - - //// Check if it's the first time the user runs the application - //if (Config.GetKeyValueGeneric("FirstRun") == null || - // Config.GetKeyValueGeneric("FirstRun") == true) - //{ - // // Display the first run wizard - // frmFirstRun formFirstRun = new frmFirstRun(this); - // DialogResult dialogResultFirstRun = formFirstRun.ShowDialog(); - - // // Evaluate user response - // if (dialogResultFirstRun == System.Windows.Forms.DialogResult.Cancel) - // { - // // User clicked cancel; exit the application immediately - // Application.Exit(); - // return; - // } - // else - // { - // // Wizard is done: set first run to false - // Config.SetKeyValue("FirstRun", false); - // } - - // // Save initial configuration - // Config.Save(); - //} - - //// Create player - //try - //{ - // Device device = null; - // Tracing.Log("Main form init -- Initializing device..."); - // frmSplash.SetStatus("Initializing device..."); - - // // Get configuration values - // DriverType driverType = Config.Audio.DriverType; - // string deviceName = Config.Audio.Device.Name; - - // // Check configured driver type - // if (driverType == DriverType.DirectSound) - // { - // // Try to find the configured device - // device = DeviceHelper.FindOutputDevice(DriverType.DirectSound, deviceName); - // } - // else if (driverType == DriverType.ASIO) - // { - // // Try to find the configured device - // device = DeviceHelper.FindOutputDevice(DriverType.ASIO, deviceName); - // } - // else if (driverType == DriverType.WASAPI) - // { - // // Try to find the configured device - // device = DeviceHelper.FindOutputDevice(DriverType.WASAPI, deviceName); - // } - - // // Check if the device was found - // if (device == null) - // { - // // Select default device instead (DirectSound, default device) - // device = new Device(); - // } - - // // Initialize device - // player.InitializeDevice(device, Config.Audio.Mixer.Frequency); - - // // Create timer - // timerSongPosition = new System.Windows.Forms.Timer(); - // timerSongPosition.Interval = 10; - // timerSongPosition.Tick += new EventHandler(timerSongPosition_Tick); - // timerSongPosition.Enabled = true; - //} - //catch (Exception ex) - //{ - // // Set error in splash and hide splash - // frmSplash.SetStatus("Error initializing device!"); - // frmSplash.HideSplash(); - - // // Display message box with error - // this.TopMost = true; - // MessageBox.Show("There was an error while initializing the player device.\nYou can delete the MPfm.Configuration.xml file in the MPfm application data folder (" + applicationDataFolderPath + ") to reset the configuration and display the First Run screen.\n\nException information:\nMessage: " + ex.Message + "\nStack trace: " + ex.StackTrace, "Error initializing player!", MessageBoxButtons.OK, MessageBoxIcon.Error); - // Tracing.Log("Main form init -- Player init error: " + ex.Message + "\nStack trace: " + ex.StackTrace); - - // // Exit application - // Application.Exit(); - // return; - //} - - //try - //{ - // // Load library - // Tracing.Log("Main form init -- Loading library..."); - // frmSplash.SetStatus("Loading library..."); - // library = new Library.Library(databaseFilePath); - //} - //catch (Exception ex) - //{ - // // Set error in splash and hide splash - // frmSplash.SetStatus("Error initializing library!"); - // frmSplash.HideSplash(); - - // // Display message box with error - // this.TopMost = true; - // MessageBox.Show("There was an error while initializing the library.\nYou can delete the MPfm.Database.db file in the MPfm application data folder (" + applicationDataFolderPath + ") to reset the library.\n\nException information:\nMessage: " + ex.Message + "\nStack trace: " + ex.StackTrace, "Error initializing library!", MessageBoxButtons.OK, MessageBoxIcon.Error); - // Tracing.Log("Main form init -- Library init error: " + ex.Message + "\nStack trace: " + ex.StackTrace); - - // // Exit application - // Application.Exit(); - // return; - //} - - // Load UI - try - { - // Hide update library progress by default - ShowUpdateLibraryProgress(false); - } - catch (Exception ex) - { - // Set error in splash and hide splash - //frmSplash.SetStatus("Error initializing UI!"); - frmSplash.HideSplash(); - - // Display message box with error - this.TopMost = true; - MessageBox.Show("There was an error while initializing the UI.\nYou can delete the MPfm.Configuration.xml file in the MPfm application data folder to reset the configuration and display the First Run screen.\n\nException information:\nMessage: " + ex.Message + "\nStack trace: " + ex.StackTrace, "Error initializing player!", MessageBoxButtons.OK, MessageBoxIcon.Error); - Tracing.Log("UI error: " + ex.Message + "\nStack trace: " + ex.StackTrace); - - // Exit application - Application.Exit(); - return; - } + Assembly assembly = Assembly.GetExecutingAssembly(); + this.Text = "MPfm: Music Player for Musicians - " + assembly.GetName().Version.ToString(); + + ShowUpdateLibraryProgress(false); + + // TODO: Determine first run with InitializationService + // TODO: When starting player, try to reuse the last configured device with DeviceHelper.FindOutputDevice + // TODO: Apply configuration + // TODO: Expand nodes to what was opened in the last session + + // Populate the supported formats + comboSoundFormat.Items.Clear(); + comboSoundFormat.Items.Add("All"); + comboSoundFormat.Items.Add("APE"); + comboSoundFormat.Items.Add("FLAC"); + comboSoundFormat.Items.Add("MP3"); + comboSoundFormat.Items.Add("MPC"); + comboSoundFormat.Items.Add("OGG"); + comboSoundFormat.Items.Add("WMA"); + comboSoundFormat.Items.Add("WV"); + comboSoundFormat.SelectedIndex = 0; + lblPeakFileWarning.Visible = false; try { Tracing.Log("Main form init -- Applying configuration..."); //frmSplash.SetStatus("Applying configuration..."); - //// Resetting display - //lblCurrentAlbumTitle.Text = string.Empty; - //lblCurrentArtistName.Text = string.Empty; - //lblCurrentSongTitle.Text = string.Empty; - //lblCurrentFilePath.Text = string.Empty; - //lblBitrate.Text = string.Empty; - //lblSoundFormat.Text = string.Empty; - //lblBitsPerSample.Text = string.Empty; - //lblFrequency.Text = string.Empty; - //// Load window configuration (position, size, column sizes, etc.) //LoadWindowConfiguration(); @@ -470,16 +148,6 @@ private void frmMain_Load(object sender, EventArgs e) //// Get media type filter configuration and set media type before refreshing the tree library //string filterSoundFormat = Config.GetKeyValue("FilterSoundFormat"); - //// Populate the supported formats - //comboSoundFormat.Items.Clear(); - //comboSoundFormat.Items.Add("All"); - //comboSoundFormat.Items.Add("APE"); - //comboSoundFormat.Items.Add("FLAC"); - //comboSoundFormat.Items.Add("MP3"); - //comboSoundFormat.Items.Add("MPC"); - //comboSoundFormat.Items.Add("OGG"); - //comboSoundFormat.Items.Add("WMA"); - //comboSoundFormat.Items.Add("WV"); ////Array audioFileFormats = Enum.GetValues(typeof(AudioFileFormat)); ////foreach (AudioFileFormat audioFileFormat in audioFileFormats) @@ -1136,23 +804,23 @@ public void player_OnPlaylistIndexChanged(PlayerPlaylistIndexChangedData data) /// Event arguments private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { - if (e.CloseReason == CloseReason.FormOwnerClosing || - e.CloseReason == CloseReason.UserClosing) - { - // Check configuration values - if (Config.GetKeyValueGeneric("ShowTray") == true && - Config.GetKeyValueGeneric("HideTray") == true) - { - e.Cancel = true; - this.Hide(); - return; - } - } + //if (e.CloseReason == CloseReason.FormOwnerClosing || + // e.CloseReason == CloseReason.UserClosing) + //{ + // // Check configuration values + // if (Config.GetKeyValueGeneric("ShowTray") == true && + // Config.GetKeyValueGeneric("HideTray") == true) + // { + // e.Cancel = true; + // this.Hide(); + // return; + // } + //} - Tracing.Log("Main form -- Closing MPfm..."); + //Tracing.Log("Main form -- Closing MPfm..."); - // Save configuration - SaveWindowConfiguration(); + //// Save configuration + //SaveWindowConfiguration(); e.Cancel = false; //// Close player if not null @@ -1400,7 +1068,6 @@ private void miHelpLicense_Click(object sender, EventArgs e) } catch (Exception ex) { - // Display message box MessageBox.Show("Error: " + ex.Message + "\n" + ex.StackTrace, "Error opening license file", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1419,7 +1086,6 @@ private void miHelpWebsite_Click(object sender, EventArgs e) } catch (Exception ex) { - // Display message box MessageBox.Show("Error: " + ex.Message + "\n" + ex.StackTrace, "Error opening web browser", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1438,7 +1104,6 @@ private void miHelpBlog_Click(object sender, EventArgs e) } catch (Exception ex) { - // Display message box MessageBox.Show("Error: " + ex.Message + "\n" + ex.StackTrace, "Error opening web browser", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1457,7 +1122,6 @@ private void miHelpSourceForge_Click(object sender, EventArgs e) } catch (Exception ex) { - // Display message box MessageBox.Show("Error: " + ex.Message + "\n" + ex.StackTrace, "Error opening web browser", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1476,7 +1140,6 @@ private void miHelpDownload_Click(object sender, EventArgs e) } catch (Exception ex) { - // Display message box MessageBox.Show("Error: " + ex.Message + "\n" + ex.StackTrace, "Error opening web browser", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1495,7 +1158,6 @@ private void miHelpRoadmap_Click(object sender, EventArgs e) } catch (Exception ex) { - // Display message box MessageBox.Show("Error: " + ex.Message + "\n" + ex.StackTrace, "Error opening web browser", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1514,7 +1176,6 @@ private void miHelpChangeLog_Click(object sender, EventArgs e) } catch (Exception ex) { - // Display message box MessageBox.Show("Error: " + ex.Message + "\n" + ex.StackTrace, "Error opening web browser", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1528,16 +1189,12 @@ private void miHelpReportBug_Click(object sender, EventArgs e) { try { - // Display message box + // Open website in default browser if (MessageBox.Show("Thank you for taking the time to report a bug. It is truly appreciated.\n\nTo report a bug in the Mantis bug tracker, you need to login or register a new account. You can only submit bugs in the MPfm/Support project.\n\nFor more information, consult this web page: http://www.mp4m.org/support.", "Report a new bug", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == System.Windows.Forms.DialogResult.OK) - { - // Open website in default browser Process.Start("http://www.mp4m.org/mantis/login_page.php"); - } } catch (Exception ex) { - // Display message box MessageBox.Show("Error: " + ex.Message + "\n" + ex.StackTrace, "Error opening web browser", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -1580,8 +1237,7 @@ private void btnUpdateLibrary_Click(object sender, EventArgs e) /// Event arguments private void btnPlay_Click(object sender, EventArgs e) { - // Start playback of currently selected item - PlaySelectedSongQuery(); + OnPlayerPlay(); } /// @@ -1591,13 +1247,7 @@ private void btnPlay_Click(object sender, EventArgs e) /// Event sender /// Event arguments private void btnPause_Click(object sender, EventArgs e) - { - //// Validate player - //if (player == null || player.Playlist == null || !player.IsPlaying) - //{ - // return; - //} - + { //// Check pause status //if (player.IsPaused) //{ @@ -1615,9 +1265,6 @@ private void btnPause_Click(object sender, EventArgs e) // timerUpdateSongPositionPanel.Enabled = false; // timerUpdateOutputMeter.Enabled = false; //} - - //// Set pause - //player.Pause(); } /// @@ -1639,19 +1286,7 @@ private void btnStop_Click(object sender, EventArgs e) /// Event arguments private void btnNextSong_Click(object sender, EventArgs e) { - //// Validate player - //if (player == null || player.Playlist == null || !player.IsPlaying) - //{ - // return; - //} - - //// Skip to next song in player - //player.Next(); - - //// Refresh controls - //RefreshSongControls(); - //RefreshMarkers(); - //RefreshLoops(); + OnPlayerNext(); } /// @@ -1662,19 +1297,7 @@ private void btnNextSong_Click(object sender, EventArgs e) /// Event arguments private void btnPreviousSong_Click(object sender, EventArgs e) { - // // Validate player - // if (player == null || player.Playlist == null || !player.IsPlaying) - // { - // return; - // } - - // // Go to previous song in player - // player.Previous(); - - // // Refresh controls - // RefreshSongControls(); - // RefreshMarkers(); - // RefreshLoops(); + OnPlayerPrevious(); } /// @@ -1846,15 +1469,6 @@ public void RefreshPeakFileDirectorySizeWarning() //} } - /// - /// Refreshes all the controls in the main form. - /// - public void RefreshAll() - { - RefreshTreeLibrary(); - RefreshSongBrowser(); - } - /// /// Refreshes the controls in the "Current Song" panel and the different /// playback buttons. By default, does not update the playlist window. @@ -1952,28 +1566,28 @@ public void RefreshSongBrowserPlayIcon(Guid newAudioFileId) /// public void RefreshSongBrowser() { - // If no node has been selected - if (treeLibraryBrowser.SelectedNode == null) - { - // Filter all songs - RefreshSongBrowser(new SongQuery()); - return; - } + //// If no node has been selected + //if (treeLibraryBrowser.SelectedNode == null) + //{ + // // Filter all songs + // RefreshSongBrowser(new SongQuery()); + // return; + //} - // Cast the tree node metadata - TreeLibraryNodeMetadata metadata = (TreeLibraryNodeMetadata)treeLibraryBrowser.SelectedNode.Tag; + //// Cast the tree node metadata + //TreeLibraryNodeMetadata metadata = (TreeLibraryNodeMetadata)treeLibraryBrowser.SelectedNode.Tag; - // Set the current song browser query from the selected node metadata - querySongBrowser = metadata.Query; + //// Set the current song browser query from the selected node metadata + //querySongBrowser = metadata.Query; - // Set config - Config.Controls.SongGridView.Query.ArtistName = querySongBrowser.ArtistName; - Config.Controls.SongGridView.Query.AlbumTitle = querySongBrowser.AlbumTitle; - Config.Controls.SongGridView.Query.PlaylistId = querySongBrowser.PlaylistId; - Config.Save(); + ////// Set config + ////Config.Controls.SongGridView.Query.ArtistName = querySongBrowser.ArtistName; + ////Config.Controls.SongGridView.Query.AlbumTitle = querySongBrowser.AlbumTitle; + ////Config.Controls.SongGridView.Query.PlaylistId = querySongBrowser.PlaylistId; + ////Config.Save(); - // Refresh song browser - RefreshSongBrowser(querySongBrowser); + //// Refresh song browser + //RefreshSongBrowser(querySongBrowser); } /// @@ -2179,74 +1793,6 @@ public void RefreshLoops() //} } - /// - /// Refreshes the tree view control presenting the library. - /// - public void RefreshTreeLibrary() - { - // Declare the selected node - TreeNode selectedNode = null; - - // Supress repainting the TreeView until we're done (to prevent flicker) - treeLibraryBrowser.BeginUpdate(); - - // Make sure the tree is empty - treeLibraryBrowser.Nodes.Clear(); - - // Create the main nodes - nodeAllSongs = new TreeNode("All Songs"); - nodeAllSongs.ImageIndex = 12; - nodeAllSongs.SelectedImageIndex = 12; - nodeAllSongs.Tag = new TreeLibraryNodeMetadata(TreeLibraryNodeType.AllSongs, new SongQuery()); - - if (querySongBrowser.Type == SongQueryType.None) - { - selectedNode = nodeAllSongs; - } - - // Create the artist list node - nodeAllArtists = new TreeNode("Artists"); - nodeAllArtists.ImageIndex = 16; - nodeAllArtists.SelectedImageIndex = 16; - nodeAllArtists.Tag = new TreeLibraryNodeMetadata(TreeLibraryNodeType.AllArtists, new SongQuery()); - nodeAllArtists.Nodes.Add("dummy", "dummy"); - - nodeAllAlbums = new TreeNode("Albums"); - nodeAllAlbums.ImageIndex = 17; - nodeAllAlbums.SelectedImageIndex = 17; - nodeAllAlbums.Tag = new TreeLibraryNodeMetadata(TreeLibraryNodeType.AllAlbums, new SongQuery()); - nodeAllAlbums.Nodes.Add("dummy", "dummy"); - - //nodeAllPlaylists = new TreeNode("Playlists"); - //nodeAllPlaylists.ImageIndex = 4; - //nodeAllPlaylists.SelectedImageIndex = 4; - //nodeAllPlaylists.Tag = new TreeLibraryNodeMetadata(TreeLibraryNodeType.AllPlaylists, new SongQuery(SongQueryType.None)); - //nodeAllPlaylists.Nodes.Add("dummy", "dummy"); - - //nodeRecentlyPlayed = new TreeNode("Recently Played"); - //nodeRecentlyPlayed.ImageIndex = 18; - //nodeRecentlyPlayed.SelectedImageIndex = 18; - //nodeRecentlyPlayed.Tag = new TreeLibraryNodeMetadata(TreeLibraryNodeType.RecentlyPlayed, new SongQuery()); - - //if (this.currentSongBrowserQueryType == "RecentlyPlayed") - //{ - // selectedNode = nodeRecentlyPlayed; - //} - - // Add main nodes to the treeview - treeLibraryBrowser.Nodes.Add(nodeAllSongs); - treeLibraryBrowser.Nodes.Add(nodeAllArtists); - treeLibraryBrowser.Nodes.Add(nodeAllAlbums); - //treeLibrary.Nodes.Add(nodeAllPlaylists); - //treeLibrary.Nodes.Add(nodeRecentlyPlayed); - - // Set selected node - treeLibraryBrowser.SelectedNode = selectedNode; - - // Set update done - treeLibraryBrowser.EndUpdate(); - } - /// /// Refreshes the "Repeat" button in the main form toolbar. /// @@ -2292,17 +1838,17 @@ public void RefreshRepeatButton() /// public void PlaySelectedView() { - // Is there at least one item? - if (viewSongs2.Items.Count > 0) - { - // Select the first song - //viewSongs2.SelectedItems = null; - viewSongs2.ClearSelectedItems(); - viewSongs2.Items[0].IsSelected = true; + //// Is there at least one item? + //if (viewSongs2.Items.Count > 0) + //{ + // // Select the first song + // //viewSongs2.SelectedItems = null; + // viewSongs2.ClearSelectedItems(); + // viewSongs2.Items[0].IsSelected = true; - // Play newly selected song - PlaySelectedSongQuery(); - } + // // Play newly selected song + // PlaySelectedSongQuery(); + //} } /// @@ -2535,13 +2081,10 @@ private void trackPosition_MouseMove(object sender, MouseEventArgs e) private void trackTimeShiftingNew_OnTrackBarValueChanged() { //double multiplier = 1 / ((double)trackTimeShifting.Value / 100); - //lblTimeShifting.Text = trackTimeShifting.Value.ToString() + " %"; - //Player.TimeShifting = trackTimeShifting.Value; } - /// /// Fires when the user releases the mouse button on the Volume slider. Saves the final value. /// @@ -2550,7 +2093,7 @@ private void trackTimeShiftingNew_OnTrackBarValueChanged() private void trackVolume_MouseUp(object sender, MouseEventArgs e) { //Config["Volume"] = trackVolume.Value.ToString(); - Config.Audio.Mixer.Volume = faderVolume.Value; + //Config.Audio.Mixer.Volume = faderVolume.Value; } /// @@ -2699,9 +2242,7 @@ private void picAlbum_MouseClick(object sender, MouseEventArgs e) private void menuSongBrowser_Opening(object sender, CancelEventArgs e) { if (viewSongs2.SelectedItems.Count == 0) - { e.Cancel = true; - } } /// @@ -2711,11 +2252,7 @@ private void menuSongBrowser_Opening(object sender, CancelEventArgs e) private void viewSongs2_OnSelectedIndexChanged(SongGridViewSelectedIndexChangedData data) { // Check if a selection has been made - bool enabled = true; - if (viewSongs2.SelectedItems.Count == 0) - { - enabled = false; - } + bool enabled = viewSongs2.SelectedItems.Count != 0; // Set buttons if (btnPlaySelectedSong.Enabled != enabled) @@ -2728,7 +2265,7 @@ private void viewSongs2_OnSelectedIndexChanged(SongGridViewSelectedIndexChangedD // Set selected song in config if (viewSongs2.SelectedItems.Count > 0) { - Config.Controls.SongGridView.Query.AudioFileId = viewSongs2.SelectedItems[0].AudioFile.Id; + //Config.Controls.SongGridView.Query.AudioFileId = viewSongs2.SelectedItems[0].AudioFile.Id; } } @@ -2753,16 +2290,12 @@ private void btnEditSongMetadata_Click(object sender, EventArgs e) { // Check if at least one item is selected if (viewSongs2.SelectedItems.Count == 0) - { return; - } // Get audio file from item metadata (check for null) AudioFile audioFile = viewSongs2.SelectedItems[0].AudioFile; if (audioFile == null) - { return; - } // Open window EditSongMetadata(audioFile.FilePath); @@ -3024,70 +2557,12 @@ private void workerTreeLibrary_RunWorkerCompleted(object sender, RunWorkerComple /// Event arguments private void treeLibrary_BeforeExpand(object sender, TreeViewCancelEventArgs e) { - // Check if the arguments are valid + Console.WriteLine("frmMain - treeLibrary_BeforeExpand"); if (e == null || e.Node == null) - { - return; - } - - // Detect if the child node is a dummy node (indicating we have to fetch the data) - if (e.Node.Nodes.Count > 0 && e.Node.Nodes[0].Text != "dummy") - { - // The child nodes have been generated or are static return; - } - // Cast the tree node metadata - TreeLibraryNodeMetadata metadata = (TreeLibraryNodeMetadata)e.Node.Tag; - - // Check if the metadata is valid - if (metadata == null) - { - return; - } - - // Is the worker already busy fetching other information? - if (workerTreeLibrary.IsBusy) - { - MessageBox.Show("Error fetch data for the tree library item. A process is already running.\nPlease wait until the process is done before expanding another node.", "Error fetching tree library items!", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); - return; - } - - // Cancel the expand since we're getting the objects in a background thread - e.Cancel = true; - - // Set node title to expand - e.Node.Text = e.Node.Text + " (expanding...)"; - - // Create arguments - WorkerTreeLibraryArgs args = new WorkerTreeLibraryArgs(); - args.TreeNodeToUpdate = e.Node; - - // Check the node type - if (metadata.NodeType == TreeLibraryNodeType.Artist) - { - // Fill arguments - args.OperationType = WorkerTreeLibraryOperationType.GetArtistAlbums; - args.ArtistName = metadata.Query.ArtistName; - } - else if (metadata.NodeType == TreeLibraryNodeType.AllArtists) - { - // Fill arguments - args.OperationType = WorkerTreeLibraryOperationType.GetArtists; - } - else if (metadata.NodeType == TreeLibraryNodeType.AllAlbums) - { - // Fill arguments - args.OperationType = WorkerTreeLibraryOperationType.GetAlbums; - } - else if (metadata.NodeType == TreeLibraryNodeType.AllPlaylists) - { - // Fill arguments - args.OperationType = WorkerTreeLibraryOperationType.GetPlaylists; - } - - // Start background worker process - workerTreeLibrary.RunWorkerAsync(args); + var entity = (LibraryBrowserEntity) e.Node.Tag; + OnTreeNodeExpanded(entity, e.Node); } /// @@ -3098,11 +2573,8 @@ private void treeLibrary_BeforeExpand(object sender, TreeViewCancelEventArgs e) private void treeLibrary_BeforeSelect(object sender, TreeViewCancelEventArgs e) { e.Cancel = true; - if (e.Action == TreeViewAction.ByMouse || e.Action == TreeViewAction.Unknown) - { e.Cancel = false; - } } /// @@ -3112,19 +2584,14 @@ private void treeLibrary_BeforeSelect(object sender, TreeViewCancelEventArgs e) /// Event arguments private void treeLibrary_AfterSelect(object sender, TreeViewEventArgs e) { - //if (e.Action == TreeViewAction.ByMouse || e.Action == TreeViewAction.Unknown) + Console.WriteLine("frmMain - treeLibrary_AfterSelect"); + if (e == null || e.Node == null) + return; + if (e.Action == TreeViewAction.ByMouse) { - // Set current tree node type in config - TreeLibraryNodeMetadata metadata = (TreeLibraryNodeMetadata)e.Node.Tag; - if (metadata != null) - { - // Set node type - Config.Controls.SongGridView.Query.NodeType = metadata.NodeType; - } - - // Refresh song browser - RefreshSongBrowser(); + var entity = (LibraryBrowserEntity)e.Node.Tag; + OnTreeNodeSelected(entity); } } @@ -3136,9 +2603,7 @@ private void treeLibrary_AfterSelect(object sender, TreeViewEventArgs e) private void treeLibrary_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == MouseButtons.Right) - { treeLibraryBrowser.SelectedNode = e.Node; - } } /// @@ -3149,17 +2614,13 @@ private void treeLibrary_NodeMouseClick(object sender, TreeNodeMouseClickEventAr /// Event arguments private void treeLibrary_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { - // Check for null if(e.Node == null) - { return; - } // Cast metadata - TreeLibraryNodeMetadata metadata = (TreeLibraryNodeMetadata)e.Node.Tag; + //TreeLibraryNodeMetadata metadata = (TreeLibraryNodeMetadata)e.Node.Tag; PlaySelectedView(); - } /// @@ -3191,12 +2652,9 @@ private void workerAlbumArt_DoWork(object sender, DoWorkEventArgs e) // Get image from library Image image = MPfm.Library.Library.GetAlbumArtFromID3OrFolder(songPath); - // Check if image is null + // Resize image with quality AA if (image != null) - { - // Resize image with quality AA image = ImageManipulation.ResizeImage(image, picAlbum.Size.Width, picAlbum.Size.Height); - } e.Result = image; } @@ -3210,20 +2668,9 @@ private void workerAlbumArt_DoWork(object sender, DoWorkEventArgs e) private void workerAlbumArt_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // Invoke UI updates - MethodInvoker methodUIUpdate = delegate - { - // Get image + MethodInvoker methodUIUpdate = delegate { Image image = (Image)e.Result; - - // Check if image is null - if (image != null) - { - picAlbum.Image = image; - } - else - { - picAlbum.Image = null; - } + picAlbum.Image = image ?? null; }; // Check if invoking is necessary @@ -3264,9 +2711,7 @@ private void ShowApplication() else { if (WindowState == FormWindowState.Minimized) - { WindowState = FormWindowState.Normal; - } TopMost = true; TopMost = false; @@ -3328,8 +2773,6 @@ private void menuLibrary_Opening(object sender, CancelEventArgs e) //miTreeLibraryDeletePlaylist.Tag = metadata; } - //private UpdateLibrary updateLibrary = null; - /// /// Displays the Update Library Status window and updates the library /// using the mode passed in parameter. @@ -3920,18 +3363,18 @@ private void viewSongs2_OnColumnClick(SongGridViewColumnClickData data) /// If true, the panel will be shown. public void ShowUpdateLibraryProgress(bool show) { - //// Check if the panel needs to be shown - //if (show) - //{ - // // The update library progress panel is 102 pixels high. - // treeLibraryBrowser.Height -= 102; - // panelUpdateLibraryProgress.Visible = true; - //} - //else - //{ - // treeLibraryBrowser.Height += 102; - // panelUpdateLibraryProgress.Visible = false; - //} + // Check if the panel needs to be shown + if (show) + { + // The update library progress panel is 102 pixels high. + treeLibraryBrowser.Height -= 102; + panelUpdateLibraryProgress.Visible = true; + } + else + { + treeLibraryBrowser.Height += 102; + panelUpdateLibraryProgress.Visible = false; + } } /// @@ -3957,15 +3400,6 @@ public void EnableTooltips(bool enable) // formUpdateLibraryStatus.toolTip.Active = enable; } - /// - /// Resets the current song browser query and refreshes all controls. - /// - public void ResetQuery() - { - querySongBrowser = new SongQuery(); - RefreshAll(); - } - #region IMainView implementation public Action OnViewDestroy { get; set; } @@ -3995,6 +3429,15 @@ public void ResetQuery() public void PlayerError(Exception ex) { + MethodInvoker methodUIUpdate = delegate + { + MessageBox.Show(string.Format("An error occured in Player: {0}", ex), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + }; + + if (InvokeRequired) + BeginInvoke(methodUIUpdate); + else + methodUIUpdate.Invoke(); } public void ShowView(bool shown) @@ -4003,10 +3446,83 @@ public void ShowView(bool shown) public void RefreshLibraryBrowser(IEnumerable entities) { + MethodInvoker methodUIUpdate = delegate + { + treeLibraryBrowser.BeginUpdate(); + treeLibraryBrowser.Nodes.Clear(); + + foreach (var entity in entities) + { + var node = new TreeNode(entity.Title); + node.Tag = entity; + switch (entity.Type) + { + case LibraryBrowserEntityType.AllSongs: + node.ImageIndex = 12; + node.SelectedImageIndex = 12; + break; + case LibraryBrowserEntityType.Artists: + node.ImageIndex = 16; + node.SelectedImageIndex = 16; + break; + case LibraryBrowserEntityType.Albums: + node.ImageIndex = 17; + node.SelectedImageIndex = 17; + break; + } + + if (entity.Type != LibraryBrowserEntityType.AllSongs) + node.Nodes.Add("dummy", "dummy"); + + treeLibraryBrowser.Nodes.Add(node); + } + + treeLibraryBrowser.EndUpdate(); + }; + + if (InvokeRequired) + BeginInvoke(methodUIUpdate); + else + methodUIUpdate.Invoke(); } public void RefreshLibraryBrowserNode(LibraryBrowserEntity entity, IEnumerable entities, object userData) { + Console.WriteLine("frmMain - RefreshLibraryBrowserNode - entities.Count: {0}", entities.Count()); + MethodInvoker methodUIUpdate = delegate { + var node = (TreeNode) userData; + treeLibraryBrowser.BeginUpdate(); + + foreach (var childEntity in entities) + { + var childNode = new TreeNode(childEntity.Title); + childNode.Tag = childEntity; + switch (childEntity.Type) + { + case LibraryBrowserEntityType.Artist: + childNode.ImageIndex = 16; + childNode.SelectedImageIndex = 16; + break; + case LibraryBrowserEntityType.Album: + case LibraryBrowserEntityType.ArtistAlbum: + childNode.ImageIndex = 17; + childNode.SelectedImageIndex = 17; + break; + } + + if (childEntity.Type != LibraryBrowserEntityType.Song) + childNode.Nodes.Add("dummy", "dummy"); + + node.Nodes.Add(node); + } + + treeLibraryBrowser.EndUpdate(); + }; + + if (InvokeRequired) + BeginInvoke(methodUIUpdate); + else + methodUIUpdate.Invoke(); } public void RefreshSongBrowser(IEnumerable audioFiles) @@ -4040,196 +3556,9 @@ public void RefreshPlayerVolume(PlayerVolumeEntity entity) public void RefreshPlayerTimeShifting(PlayerTimeShiftingEntity entity) { } - #endregion - - } - - #region Classes and enums - - /// - /// Defines the data structure for reporting progress when generating a wave form - /// for the Loops and Markers UI. - /// - public class WorkerWaveFormLoopsMarkersReportProgress - { - /// - /// Indicates how many bytes are read. - /// - public uint BytesRead { get; set; } - /// - /// Indicates the total number of bytes to read. - /// - public uint TotalBytes { get; set; } - /// - /// Indicates the percentage done. - /// - public float PercentageDone { get; set; } - /// - /// WaveDataMinMax data structure. - /// - public WaveDataMinMax WaveDataMinMax { get; set; } - } - - /// - /// Defines the arguments passed to the background worker of the tree library. This - /// allows the background worker to get the type of operation it needs to do. - /// - public class WorkerTreeLibraryArgs - { - /// - /// Operation type. - /// - public WorkerTreeLibraryOperationType OperationType { get; set; } - /// - /// Indicates which tree node to update. - /// - public TreeNode TreeNodeToUpdate { get; set; } - /// - /// Artist name. - /// - public string ArtistName { get; set; } - } - - /// - /// Defines the results coming out of the background worker of the tree library. - /// - public class WorkerTreeLibraryResult - { - /// - /// Operation type. - /// - public WorkerTreeLibraryOperationType OperationType { get; set; } - /// - /// Indicates which tree node to update. - /// - public TreeNode TreeNodeToUpdate { get; set; } - /// - /// Artist name. - /// - public string ArtistName { get; set; } - /// - /// List of album titles. - /// - public List Albums { get; set; } - /// - /// List of artist names. - /// - public List Artists { get; set; } - /// - /// List of albums (key = artist name, value = album title). - /// - public Dictionary> AllAlbums { get; set; } - } - - /// - /// Defines what kind of operation the background worker process needs to do. - /// - public enum WorkerTreeLibraryOperationType - { - /// - /// Gets all artists. - /// - GetArtists = 0, - /// - /// Gets all albums from a specific artist. - /// - GetArtistAlbums = 1, - /// - /// Gets all albums. - /// - GetAlbums = 2, - /// - /// Gets all playlists. - /// - GetPlaylists = 3 } - /// - /// Defines what the tree library node represents (artist, album, playlist, etc.) - /// - public enum TreeLibraryNodeType - { - /// - /// "All" node type. - /// - All = 0, - /// - /// "All songs" node type. - /// - AllSongs = 1, - /// - /// "All artists" node type. - /// - AllArtists = 2, - /// - /// "All albums" node type. - /// - AllAlbums = 3, - /// - /// "All playlists" node type. - /// - AllPlaylists = 4, - /// - /// "Artist" node type. - /// - Artist = 5, - /// - /// "Album" node type. - /// - Album = 6, - /// - /// "Artist/Album" node type. - /// - ArtistAlbum = 7, - /// - /// "Playlist" node type. - /// - Playlist = 8, - /// - /// "Recently played" node type. - /// - RecentlyPlayed = 9 - } - - /// - /// Data structure used with the Tag property of the tree library TreeNode object. - /// Contains the type of node and its query. - /// - public class TreeLibraryNodeMetadata - { - /// - /// Defines the node type. - /// - public TreeLibraryNodeType NodeType { get; set; } - - /// - /// Defines the query associated with this node type. - /// - public SongQuery Query { get; set; } - - /// - /// Default constructor for the TreeLibraryNodeMetadata class. - /// - public TreeLibraryNodeMetadata() - { - } - - /// - /// Constructor for the TreeLibraryNodeMetadata class. Requires the - /// node type and query. - /// - /// Node type - /// Query - public TreeLibraryNodeMetadata(TreeLibraryNodeType nodeType, SongQuery query) - { - NodeType = nodeType; - Query = query; - } - } - - #endregion - } diff --git a/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.Designer.cs b/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.Designer.cs similarity index 99% rename from MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.Designer.cs rename to MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.Designer.cs index 26dfb140..74aeb44e 100644 --- a/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.Designer.cs +++ b/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.Designer.cs @@ -1,4 +1,4 @@ -// Copyright © 2011-2013 Yanick Castonguay +// Copyright © 2011-2013 Yanick Castonguay // // This file is part of MPfm. // @@ -17,7 +17,7 @@ namespace MPfm.Windows.Classes.Forms { - partial class frmUpdateLibraryStatus + partial class frmUpdateLibrary { /// /// Required designer variable. @@ -101,7 +101,7 @@ private void InitializeComponent() MPfm.WindowsControls.CustomFont customFont17 = new MPfm.WindowsControls.CustomFont(); MPfm.WindowsControls.TextGradient textGradient17 = new MPfm.WindowsControls.TextGradient(); MPfm.WindowsControls.CustomFont customFont18 = new MPfm.WindowsControls.CustomFont(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmUpdateLibraryStatus)); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmUpdateLibrary)); this.workerUpdateLibrary = new System.ComponentModel.BackgroundWorker(); this.workerTimer = new System.ComponentModel.BackgroundWorker(); this.saveLogDialog = new System.Windows.Forms.SaveFileDialog(); @@ -139,8 +139,6 @@ private void InitializeComponent() // this.workerTimer.WorkerReportsProgress = true; this.workerTimer.WorkerSupportsCancellation = true; - this.workerTimer.DoWork += new System.ComponentModel.DoWorkEventHandler(this.workerTimer_DoWork); - this.workerTimer.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.workerTimer_ProgressChanged); // // saveLogDialog // @@ -799,7 +797,7 @@ private void InitializeComponent() this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; - this.Name = "frmUpdateLibraryStatus"; + this.Name = "frmUpdateLibrary"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Update Library"; diff --git a/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.cs b/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.cs new file mode 100644 index 00000000..eb6985e9 --- /dev/null +++ b/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.cs @@ -0,0 +1,337 @@ +// Copyright © 2011-2013 Yanick Castonguay +// +// This file is part of MPfm. +// +// MPfm 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. +// +// MPfm is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with MPfm. If not, see . + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Text; +using System.Windows.Forms; +using MPfm.Library.Objects; +using MPfm.Library.UpdateLibrary; +using MPfm.MVP.Views; + +namespace MPfm.Windows.Classes.Forms +{ + /// + /// Update Library window. This window is displayed when the application + /// is updating the library. + /// + public partial class frmUpdateLibrary : BaseForm, IUpdateLibraryView + { + public frmUpdateLibrary(Action onViewReady) + : base(onViewReady) + { + InitializeComponent(); + ViewIsReady(); + + //lblTitle.Text = "Updating"; + //lblMessage.Text = "Calculating..."; + } + + /// + /// Fires when the form is shown. The form is shown when the user has started the update process. + /// + /// Sender + /// Arguments + private void frmUpdateLibraryStatus_Shown(object sender, EventArgs e) + { + // Stop any song playing + //Main.Player.Stop(); + + // Reset buttons + btnCancel.Enabled = true; + btnOK.Enabled = false; + btnSaveLog.Enabled = false; + + //// Reset log + //sbLog = new StringBuilder(1000); + + //// Start timer + //timerEnabled = true; + //workerTimer.RunWorkerAsync(); + + //// Reset variables + //startTime = DateTime.Now; + //startTimeAddFiles = DateTime.MinValue; + //listAlbums = new List(); + + // Update UI + lblEstimatedTimeLeft.Text = "Estimated time left: Calculating..."; + + // Start the update process + //Main.Library.UpdateLibrary(mode, FilePaths, FolderPath); + } + + private void btnOK_Click(object sender, EventArgs e) + { + // Refresh controls on the main form + Cursor.Current = Cursors.WaitCursor; + + // Reset query and refresh all controls + //Main.ResetQuery(); + //Main.RefreshAll(); + + Cursor.Current = Cursors.Default; + + // Close this form + this.Close(); + } + + private void btnCancel_Click(object sender, EventArgs e) + { + //// Set the cancel update library flag to true + //Main.Library.CancelUpdateLibrary = true; + + //// Reset buttons + //btnOK.Enabled = true; + //btnCancel.Enabled = false; + } + + private void btnSaveLog_Click(object sender, EventArgs e) + { + //// Generate the name of the log + //saveLogDialog.FileName = "MPfm_UpdateLibraryLog_" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString("00") + "-" + DateTime.Now.Day.ToString("00") + ".txt"; + + //// Display the save dialog + //if (saveLogDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) + //{ + // TextWriter tw = null; + // try + // { + // // Open text writer + // tw = new StreamWriter(saveLogDialog.FileName); + + // foreach (String item in lbLog.Items) + // { + // tw.WriteLine(item); + // } + // } + // catch (Exception ex) + // { + // // Display error + // MessageBox.Show("Failed to save the file to " + saveLogDialog.FileName + "!\n\nException:\n" + ex.Message + "\n" + ex.StackTrace, "Failed to save the file", MessageBoxButtons.OK, MessageBoxIcon.Error); + // } + // finally + // { + // tw.Close(); + // } + //} + } + + ///// + ///// Fires when the update library process sends a progress changed message. + ///// + ///// Update data + //private void Library_OnUpdateLibraryProgress(UpdateLibraryProgressData data) + //{ + // //// Invoke UI updates + // //MethodInvoker methodUIUpdate = delegate + // //{ + // // // Check if there is an error + // // if (data.Error != null) + // // { + // // //string errorMessage = "Error: Cannot add this file to the library - " + status.errorInformation + "\n\nFile Path: " + status.filePath + "\nReason: " + status.error.Message; + // // string errorMessage; + + // // if (!String.IsNullOrEmpty(data.FilePath)) + // // { + // // errorMessage = data.FilePath + "\n"; + // // } + // // else + // // { + // // errorMessage = "====================\n"; + // // } + + // // errorMessage += " Error: " + data.Error.Message; + + // // if (data.Error.InnerException != null) + // // { + // // errorMessage += "\n " + data.Error.InnerException.Message; + // // } + // // errorMessage += "\n"; + + // // // Log for file + // // sbLog.Insert(0, errorMessage); + + // // // Add to log screen + // // lbLog.Items.Insert(0, "Error reading " + Path.GetFileName(data.FilePath) + ": " + data.Error.Message); + + // // lblMessage.Text = data.Message; + // // lblProgress.Text = data.Percentage.ToString("0.000") + " %"; + // // progressBar.Value = Convert.ToInt32(data.Percentage); + // // } + // // else + // // { + // // // Update UI + // // if (data.CurrentFilePosition > 0 && data.TotalNumberOfFiles > 0) + // // { + // // // Set start time when the process has finished finding the files and is ready to add files into library + // // if (startTimeAddFiles == DateTime.MinValue) + // // { + // // startTimeAddFiles = DateTime.Now; + // // } + + // // // Calculate time elapsed + // // TimeSpan timeElapsed = DateTime.Now.Subtract(startTimeAddFiles); + + // // // Update title + // // lblTitle.Text = data.Title + " (file " + data.CurrentFilePosition.ToString() + " of " + data.TotalNumberOfFiles.ToString() + ")"; + + // // // Calculate time remaining + // // double msPerFile = timeElapsed.TotalMilliseconds / data.CurrentFilePosition; + // // double remainingTime = (data.TotalNumberOfFiles - data.CurrentFilePosition) * msPerFile; + // // TimeSpan timeRemaining = new TimeSpan(0, 0, 0, 0, (int)remainingTime); + + // // // Update estimated time left (from more precise to more vague) + // // if (timeRemaining.TotalSeconds == 0) + // // { + // // lblEstimatedTimeLeft.Text = "Estimated time left : N/A"; + // // } + // // else if (timeRemaining.Minutes == 1) + // // { + // // lblEstimatedTimeLeft.Text = "Estimated time left : 1 minute"; + // // } + // // else if (timeRemaining.TotalSeconds <= 10) + // // { + // // lblEstimatedTimeLeft.Text = "Estimated time left : A few seconds"; + // // } + // // else if (timeRemaining.TotalSeconds <= 30) + // // { + // // lblEstimatedTimeLeft.Text = "Estimated time left : Less than 30 seconds"; + // // } + // // else if (timeRemaining.TotalSeconds <= 60) + // // { + // // lblEstimatedTimeLeft.Text = "Estimated time left : Less than a minute"; + // // } + // // else + // // { + // // lblEstimatedTimeLeft.Text = "Estimated time left : " + timeRemaining.Minutes.ToString() + " minutes"; + // // } + // // } + // // else + // // { + // // lblTitle.Text = data.Title; + // // } + // // lblMessage.Text = data.Message; + // // lblProgress.Text = data.Percentage.ToString("0.000") + " %"; + // // progressBar.Value = Convert.ToInt32(data.Percentage); + + // // if (!String.IsNullOrEmpty(data.LogEntry)) + // // { + // // sbLog.Insert(0, data.LogEntry + "\n"); + // // } + + // // // Update song if exists + // // if (data.Song != null) + // // { + // // //lblArtist.Text = data.Song.ArtistName; + // // //lblAlbum.Text = data.Song.AlbumTitle; + // // //lblSongTitle.Text = data.Song.SongTitle; + + // // // Check if the folder has already been treated (we want to get the ID3 + // // // image just once per album. This speeds up the update library process a lot.) + + // // ////string path = Path.GetDirectoryName(data.FilePath); + // // //string artistAlbum = data.Song.ArtistName + " - " + data.Song.AlbumTitle; + // // //if (!listAlbums.Contains(artistAlbum)) + // // //{ + // // // try + // // // { + // // // // Get album art from ID3 tag or folder.jpg + // // // Image image = MPfm.Library.Library.GetAlbumArtFromID3OrFolder(data.FilePath); + + // // // // If image is null... + // // // if (image == null) + // // // { + // // // // Display nothing + // // // picAlbum.Image = null; + // // // } + // // // else + // // // { + // // // // Update the album art + // // // picAlbum.Image = ImageManipulation.ResizeImage(image, picAlbum.Size.Width, picAlbum.Size.Height); + // // // } + + // // // // Add the folder in the list of folders + // // // listAlbums.Add(artistAlbum); + // // // } + // // // catch (Exception ex) + // // // { + // // // // Do nothing since this is only album art. + // // // } + // // //} + + // // //lbLog.Items.Insert(0, data.LogEntry); + // // //if (lbLog.Items.Count > 1000) + // // //{ + // // // lbLog.Items.RemoveAt(lbLog.Items.Count - 1); + // // //} + // // } + // // else + // // { + // // //lblArtist.Text = string.Empty; + // // //lblAlbum.Text = string.Empty; + // // //lblSongTitle.Text = string.Empty; + // // //picAlbum.Image = null; + // // } + // // } + // //}; + + // //// Check if invoking is necessary + // //if (InvokeRequired) + // //{ + // // BeginInvoke(methodUIUpdate); + // //} + // //else + // //{ + // // methodUIUpdate.Invoke(); + // //} + + // ////if (data.ProgressUndefined) + // ////{ + // //// progressBar.Style = ProgressBarStyle.Continuous; + // ////} + // ////else + // ////{ + // //// progressBar.Style = ProgressBarStyle.Marquee; + // //// lblProgress.Text = data.Percentage.ToString("0.00") + " %"; + // //// progressBar.Value = Convert.ToInt32(data.Percentage); + // ////} + //} + + #region IUpdateLibraryView implementation + + public Action, string> OnStartUpdateLibrary { get; set; } + public Action OnCancelUpdateLibrary { get; set; } + + public void RefreshStatus(UpdateLibraryEntity entity) + { + } + + public void AddToLog(string entry) + { + } + + public void ProcessEnded(bool canceled) + { + } + + #endregion + + } +} diff --git a/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.resx b/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.resx similarity index 100% rename from MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.resx rename to MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibrary.resx diff --git a/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.cs b/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.cs deleted file mode 100644 index b480c453..00000000 --- a/MPfm/MPfm.Windows/Classes/Forms/frmUpdateLibraryStatus.cs +++ /dev/null @@ -1,564 +0,0 @@ -// Copyright © 2011-2013 Yanick Castonguay -// -// This file is part of MPfm. -// -// MPfm 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. -// -// MPfm is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with MPfm. If not, see . - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; -using System.Text; -using System.Windows.Forms; -using MPfm.Library.UpdateLibrary; - -namespace MPfm.Windows.Classes.Forms -{ - /// - /// Update Library window. This window is displayed when the application - /// is updating the library. - /// - public partial class frmUpdateLibraryStatus : Form - { - // Private variables - private UpdateLibraryMode mode; - private StringBuilder sbLog = new StringBuilder(); - private DateTime startTime; - private DateTime startTimeAddFiles; - private TimeSpan timeElapsed; - private List listAlbums = null; - private bool timerEnabled = false; - - /// - /// Private value for the Main property. - /// - private frmMain main = null; - /// - /// Hook to the main form. - /// - public frmMain Main - { - get - { - return main; - } - } - - /// - /// Private value for the FilePaths property. - /// - private List filePaths = null; - /// - /// Indicates the list of audio file paths to update. - /// - public List FilePaths - { - get - { - return filePaths; - } - } - - /// - /// Private value for the FolderPath property. - /// - private string folderPath = string.Empty; - /// - /// Indicates the folder path to update. - /// - public string FolderPath - { - get - { - return folderPath; - } - } - - /// - /// Default constructor for the Update Library Status window. - /// This updates the whole library. - /// - /// Hook to main form - public frmUpdateLibraryStatus(frmMain main) - { - // Initialize the form - InitializeForm(main, UpdateLibraryMode.WholeLibrary, null, null); - } - - /// - /// Constructor for the Update Library Status window. - /// This is the constructor for the SpecificFiles mode. You must pass - /// the files to update in parameter as a string List. - /// - /// Hook to main form - /// Files to update - public frmUpdateLibraryStatus(frmMain main, List filePaths) - { - // Initialize the form - InitializeForm(main, UpdateLibraryMode.SpecificFiles, filePaths, null); - } - - /// - /// Constructor for the Update Library Status window. - /// This is the constructor for the SpecificFolder mode. You must pass - /// the folder to update in parameter. - /// - /// Hook to main form - /// Folder path - public frmUpdateLibraryStatus(frmMain main, string folderPath) - { - // Initialize the form - InitializeForm(main, UpdateLibraryMode.SpecificFolder, null, folderPath); - } - - /// - /// Initializes the form. Needs a handle to the main form and the mode must be specified - /// with the accompagnied parameters. - /// - /// Handle to the main form - /// Update Library Status Window mode - /// File paths (for the SpecificFiles mode) - /// Folder path (for the SpecificFolder mode) - private void InitializeForm(frmMain main, UpdateLibraryMode mode, List filePaths, string folderPath) - { - // Initialize private variables - InitializeComponent(); - this.main = main; - this.mode = mode; - this.filePaths = filePaths; - this.folderPath = folderPath; - - // Update UI - lblTitle.Text = "Updating"; - lblMessage.Text = "Calculating..."; - //lblArtist.Text = string.Empty; - //lblAlbum.Text = string.Empty; - //lblSongTitle.Text = string.Empty; - - // Set update library events - //main.Library.OnUpdateLibraryProgress += new MPfm.Library.Library.UpdateLibraryProgress(Library_OnUpdateLibraryProgress); - //main.Library.OnUpdateLibraryFinished += new MPfm.Library.Library.UpdateLibraryFinished(Library_OnUpdateLibraryFinished); - } - - /// - /// Fires when the form is shown. The form is shown when the user has started the update process. - /// - /// Sender - /// Arguments - private void frmUpdateLibraryStatus_Shown(object sender, EventArgs e) - { - // Stop any song playing - //Main.Player.Stop(); - - // Reset buttons - btnCancel.Enabled = true; - btnOK.Enabled = false; - btnSaveLog.Enabled = false; - - // Reset log - sbLog = new StringBuilder(1000); - - // Start timer - timerEnabled = true; - workerTimer.RunWorkerAsync(); - - // Reset variables - startTime = DateTime.Now; - startTimeAddFiles = DateTime.MinValue; - listAlbums = new List(); - - // Update UI - lblEstimatedTimeLeft.Text = "Estimated time left: Calculating..."; - - // Start the update process - //Main.Library.UpdateLibrary(mode, FilePaths, FolderPath); - } - - #region Control Events - - /// - /// Fires when the user presses the OK button. - /// - /// Sender - /// Arguments - private void btnOK_Click(object sender, EventArgs e) - { - // Refresh controls on the main form - Cursor.Current = Cursors.WaitCursor; - - // Reset query and refresh all controls - Main.ResetQuery(); - //Main.RefreshAll(); - - Cursor.Current = Cursors.Default; - - // Close this form - this.Close(); - } - - /// - /// Fires when the user presses the Cancel button. - /// - /// Sender - /// Arguments - private void btnCancel_Click(object sender, EventArgs e) - { - //// Set the cancel update library flag to true - //Main.Library.CancelUpdateLibrary = true; - - //// Reset buttons - //btnOK.Enabled = true; - //btnCancel.Enabled = false; - } - - /// - /// Occurs when the user clicks on the "Save Log" button. - /// Displays a "Save file to" dialog and saves the log as a text file. - /// - /// Event sender - /// Event arguments - private void btnSaveLog_Click(object sender, EventArgs e) - { - //// Generate the name of the log - //saveLogDialog.FileName = "MPfm_UpdateLibraryLog_" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString("00") + "-" + DateTime.Now.Day.ToString("00") + ".txt"; - - //// Display the save dialog - //if (saveLogDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - //{ - // TextWriter tw = null; - // try - // { - // // Open text writer - // tw = new StreamWriter(saveLogDialog.FileName); - - // foreach (String item in lbLog.Items) - // { - // tw.WriteLine(item); - // } - // } - // catch (Exception ex) - // { - // // Display error - // MessageBox.Show("Failed to save the file to " + saveLogDialog.FileName + "!\n\nException:\n" + ex.Message + "\n" + ex.StackTrace, "Failed to save the file", MessageBoxButtons.OK, MessageBoxIcon.Error); - // } - // finally - // { - // tw.Close(); - // } - //} - } - - #endregion - - #region Player Events - - /// - /// Fires when the update library process is over. - /// - private void Library_OnUpdateLibraryFinished(UpdateLibraryFinishedData data) - { - //if (data.Successful) - //{ - // // Success - // lblProgress.Text = "100%"; - // progressBar.Value = 100; - // lblMessage.Text = "The update library process has finished successfully."; - // lblTitle.Text = "Update library successful"; - //} - //else if (data.Cancelled) - //{ - // // Cancel - // lblProgress.Text = "0%"; - // progressBar.Value = 0; - // lblMessage.Text = "The update library process was cancelled by the user."; - // lblTitle.Text = "Update library process cancelled"; - //} - //else if (!data.Successful) - //{ - // // Fail - // lblProgress.Text = "0%"; - // progressBar.Value = 0; - // lblMessage.Text = "The update library process has failed."; - // lblTitle.Text = "Update library failed"; - //} - - //lblEstimatedTimeLeft.Text = "Estimated time left: N/A"; - - //// Stop timer - //timerEnabled = false; - ////workerTimer.CancelAsync(); - - //// Refresh song cache - //Main.Library.RefreshCache(); - - //// Set buttons - //btnCancel.Enabled = false; - //btnOK.Enabled = true; - //btnSaveLog.Enabled = true; - } - - /// - /// Fires when the update library process sends a progress changed message. - /// - /// Update data - private void Library_OnUpdateLibraryProgress(UpdateLibraryProgressData data) - { - // Invoke UI updates - MethodInvoker methodUIUpdate = delegate - { - // Check if there is an error - if (data.Error != null) - { - //string errorMessage = "Error: Cannot add this file to the library - " + status.errorInformation + "\n\nFile Path: " + status.filePath + "\nReason: " + status.error.Message; - string errorMessage; - - if (!String.IsNullOrEmpty(data.FilePath)) - { - errorMessage = data.FilePath + "\n"; - } - else - { - errorMessage = "====================\n"; - } - - errorMessage += " Error: " + data.Error.Message; - - if (data.Error.InnerException != null) - { - errorMessage += "\n " + data.Error.InnerException.Message; - } - errorMessage += "\n"; - - // Log for file - sbLog.Insert(0, errorMessage); - - // Add to log screen - lbLog.Items.Insert(0, "Error reading " + Path.GetFileName(data.FilePath) + ": " + data.Error.Message); - - lblMessage.Text = data.Message; - lblProgress.Text = data.Percentage.ToString("0.000") + " %"; - progressBar.Value = Convert.ToInt32(data.Percentage); - } - else - { - // Update UI - if (data.CurrentFilePosition > 0 && data.TotalNumberOfFiles > 0) - { - // Set start time when the process has finished finding the files and is ready to add files into library - if (startTimeAddFiles == DateTime.MinValue) - { - startTimeAddFiles = DateTime.Now; - } - - // Calculate time elapsed - TimeSpan timeElapsed = DateTime.Now.Subtract(startTimeAddFiles); - - // Update title - lblTitle.Text = data.Title + " (file " + data.CurrentFilePosition.ToString() + " of " + data.TotalNumberOfFiles.ToString() + ")"; - - // Calculate time remaining - double msPerFile = timeElapsed.TotalMilliseconds / data.CurrentFilePosition; - double remainingTime = (data.TotalNumberOfFiles - data.CurrentFilePosition) * msPerFile; - TimeSpan timeRemaining = new TimeSpan(0, 0, 0, 0, (int)remainingTime); - - // Update estimated time left (from more precise to more vague) - if (timeRemaining.TotalSeconds == 0) - { - lblEstimatedTimeLeft.Text = "Estimated time left : N/A"; - } - else if (timeRemaining.Minutes == 1) - { - lblEstimatedTimeLeft.Text = "Estimated time left : 1 minute"; - } - else if (timeRemaining.TotalSeconds <= 10) - { - lblEstimatedTimeLeft.Text = "Estimated time left : A few seconds"; - } - else if (timeRemaining.TotalSeconds <= 30) - { - lblEstimatedTimeLeft.Text = "Estimated time left : Less than 30 seconds"; - } - else if (timeRemaining.TotalSeconds <= 60) - { - lblEstimatedTimeLeft.Text = "Estimated time left : Less than a minute"; - } - else - { - lblEstimatedTimeLeft.Text = "Estimated time left : " + timeRemaining.Minutes.ToString() + " minutes"; - } - } - else - { - lblTitle.Text = data.Title; - } - lblMessage.Text = data.Message; - lblProgress.Text = data.Percentage.ToString("0.000") + " %"; - progressBar.Value = Convert.ToInt32(data.Percentage); - - if (!String.IsNullOrEmpty(data.LogEntry)) - { - sbLog.Insert(0, data.LogEntry + "\n"); - } - - // Update song if exists - if (data.Song != null) - { - //lblArtist.Text = data.Song.ArtistName; - //lblAlbum.Text = data.Song.AlbumTitle; - //lblSongTitle.Text = data.Song.SongTitle; - - // Check if the folder has already been treated (we want to get the ID3 - // image just once per album. This speeds up the update library process a lot.) - - ////string path = Path.GetDirectoryName(data.FilePath); - //string artistAlbum = data.Song.ArtistName + " - " + data.Song.AlbumTitle; - //if (!listAlbums.Contains(artistAlbum)) - //{ - // try - // { - // // Get album art from ID3 tag or folder.jpg - // Image image = MPfm.Library.Library.GetAlbumArtFromID3OrFolder(data.FilePath); - - // // If image is null... - // if (image == null) - // { - // // Display nothing - // picAlbum.Image = null; - // } - // else - // { - // // Update the album art - // picAlbum.Image = ImageManipulation.ResizeImage(image, picAlbum.Size.Width, picAlbum.Size.Height); - // } - - // // Add the folder in the list of folders - // listAlbums.Add(artistAlbum); - // } - // catch (Exception ex) - // { - // // Do nothing since this is only album art. - // } - //} - - //lbLog.Items.Insert(0, data.LogEntry); - //if (lbLog.Items.Count > 1000) - //{ - // lbLog.Items.RemoveAt(lbLog.Items.Count - 1); - //} - } - else - { - //lblArtist.Text = string.Empty; - //lblAlbum.Text = string.Empty; - //lblSongTitle.Text = string.Empty; - //picAlbum.Image = null; - } - } - }; - - // Check if invoking is necessary - if (InvokeRequired) - { - BeginInvoke(methodUIUpdate); - } - else - { - methodUIUpdate.Invoke(); - } - - //if (data.ProgressUndefined) - //{ - // progressBar.Style = ProgressBarStyle.Continuous; - //} - //else - //{ - // progressBar.Style = ProgressBarStyle.Marquee; - // lblProgress.Text = data.Percentage.ToString("0.00") + " %"; - // progressBar.Value = Convert.ToInt32(data.Percentage); - //} - } - - #endregion - - #region Background Worker - - /// - /// Occurs when the background worker for the Update Library is started. - /// This is the method that refreshes the UI. - /// - /// Event sender - /// Event arguments - private void workerTimer_DoWork(object sender, DoWorkEventArgs e) - { - // Loop until timer is over - while(timerEnabled) - { - System.Threading.Thread.Sleep(50); - - // Invoke UI updates - MethodInvoker methodUIUpdate = delegate - { - // Make sure the worker is still operational - if (workerTimer.IsBusy) - { - try - { - workerTimer.ReportProgress(0); - } - catch - { - // Do nothing. There are so many updates that missing one is not very important. - } - } - }; - - // Check if invoking is necessary - if (InvokeRequired) - { - BeginInvoke(methodUIUpdate); - } - else - { - methodUIUpdate.Invoke(); - } - - }; - } - - /// - /// Occurs when the background worker receives an update for the progress. - /// - /// Event sender - /// Event arguments - private void workerTimer_ProgressChanged(object sender, ProgressChangedEventArgs e) - { - // Update time - timeElapsed = DateTime.Now.Subtract(startTime); - string mins = string.Empty; - if (timeElapsed.Minutes >= 2) - { - mins = "minutes"; - } - else - { - mins = "minute"; - } - - lblTimeElapsed.Text = "Time elapsed : " + timeElapsed.Minutes.ToString() + ":" + timeElapsed.Seconds.ToString("00") + " " + mins; - } - - #endregion - - } -} diff --git a/MPfm/MPfm.Windows/Classes/Program.cs b/MPfm/MPfm.Windows/Classes/Program.cs index 5da8b286..bf753c8b 100644 --- a/MPfm/MPfm.Windows/Classes/Program.cs +++ b/MPfm/MPfm.Windows/Classes/Program.cs @@ -41,37 +41,25 @@ static class Program [STAThread] static void Main() { - try - { - // Check if an instance of the application is already running - string proc = Process.GetCurrentProcess().ProcessName; - Process[] processes = Process.GetProcessesByName(proc); - - // If the number of processes is greater or equal to 2 (one instance already running + this new instance) - if (processes.Length >= 2) - { - // Ask the user if it allows another instance of the application - if (MessageBox.Show("At least one other instance of MPfm is already running.\n\nClick OK to continue or Cancel to exit the application.", "Multiple instances of MPfm running", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel) - { - // The user wants to exit the application - return; - } - } - } - catch - { - throw; - } + // Check if an instance of the application is already running + string proc = Process.GetCurrentProcess().ProcessName; + Process[] processes = Process.GetProcessesByName(proc); + + // Ask the user if it allows another instance of the application + if (processes.Length >= 2) + if (MessageBox.Show("At least one other instance of MPfm is already running.\n\nClick OK to continue or Cancel to exit the application.", "Multiple instances of MPfm running", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel) + return; // Set application defaults Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); + // Finish IoC registration Bootstrapper.GetContainer().Register().AsSingleton(); Bootstrapper.GetContainer().Register().AsSingleton(); Bootstrapper.GetContainer().Register().AsMultiInstance(); Bootstrapper.GetContainer().Register().AsMultiInstance(); - //Bootstrapper.GetContainer().Register().AsMultiInstance(); + Bootstrapper.GetContainer().Register().AsMultiInstance(); Bootstrapper.GetContainer().Register().AsMultiInstance(); Bootstrapper.GetContainer().Register().AsMultiInstance(); Bootstrapper.GetContainer().Register().AsMultiInstance(); diff --git a/MPfm/MPfm.Windows/MPfm.Windows.csproj b/MPfm/MPfm.Windows/MPfm.Windows.csproj index b3da637b..198b713a 100644 --- a/MPfm/MPfm.Windows/MPfm.Windows.csproj +++ b/MPfm/MPfm.Windows/MPfm.Windows.csproj @@ -169,11 +169,11 @@ frmVisualizer.cs - + Form - - frmUpdateLibraryStatus.cs + + frmUpdateLibrary.cs Form @@ -219,9 +219,9 @@ frmSyncMenu.cs - + Designer - frmUpdateLibraryStatus.cs + frmUpdateLibrary.cs frmThemes.cs @@ -434,7 +434,9 @@ MPfm.WindowsControls - + + + rem copy $(ProjectDir)\Lib\taglib-sharp.dll $(TargetDir)