Implemented progress dialog while indexing music

This commit is contained in:
Daniel Brunner
2017-07-09 16:57:27 +02:00
parent 8f8982bbe6
commit 3214c186e8
6 changed files with 439 additions and 88 deletions

112
MusicOrganizer/IndexDialog.Designer.cs generated Normal file
View File

@@ -0,0 +1,112 @@
namespace MusicOrganizer
{
partial class IndexDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.statusLabel = new System.Windows.Forms.Label();
this.progressBar = new System.Windows.Forms.ProgressBar();
this.continueButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.backgroundWorker = new System.ComponentModel.BackgroundWorker();
this.SuspendLayout();
//
// statusLabel
//
this.statusLabel.AutoSize = true;
this.statusLabel.Location = new System.Drawing.Point(13, 13);
this.statusLabel.Name = "statusLabel";
this.statusLabel.Size = new System.Drawing.Size(92, 20);
this.statusLabel.TabIndex = 0;
this.statusLabel.Text = "statusLabel";
//
// progressBar
//
this.progressBar.Location = new System.Drawing.Point(17, 36);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(568, 35);
this.progressBar.TabIndex = 1;
//
// continueButton
//
this.continueButton.Enabled = false;
this.continueButton.Location = new System.Drawing.Point(469, 77);
this.continueButton.Name = "continueButton";
this.continueButton.Size = new System.Drawing.Size(116, 41);
this.continueButton.TabIndex = 3;
this.continueButton.Text = "Continue";
this.continueButton.UseVisualStyleBackColor = true;
this.continueButton.Click += new System.EventHandler(this.continueButton_Click);
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(347, 77);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(116, 41);
this.cancelButton.TabIndex = 4;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// backgroundWorker
//
this.backgroundWorker.WorkerReportsProgress = true;
this.backgroundWorker.WorkerSupportsCancellation = true;
this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork);
this.backgroundWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker_ProgressChanged);
this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);
//
// IndexDialog
//
this.AcceptButton = this.continueButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(597, 130);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.continueButton);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.statusLabel);
this.Name = "IndexDialog";
this.Text = "IndexDialog";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.IndexDialog_FormClosing);
this.Load += new System.EventHandler(this.IndexDialog_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label statusLabel;
private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.Button continueButton;
private System.Windows.Forms.Button cancelButton;
private System.ComponentModel.BackgroundWorker backgroundWorker;
}
}

View File

@@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace MusicOrganizer
{
internal partial class IndexDialog : Form
{
private string musicFolder;
private List<Item> items;
private string[] paths;
public List<Item> Items { get { return items; } }
public IndexDialog()
{
InitializeComponent();
}
public DialogResult Execute()
{
using (var dialog = new FolderBrowserDialog())
{
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
return DialogResult.Cancel;
if (string.IsNullOrWhiteSpace(dialog.SelectedPath))
return DialogResult.Cancel;
musicFolder = dialog.SelectedPath;
}
if (!musicFolder.EndsWith("\\") && !musicFolder.EndsWith("/"))
musicFolder += Path.DirectorySeparatorChar;
again0:
try
{
paths = Directory.GetFileSystemEntries(musicFolder, "*.mp3", SearchOption.AllDirectories);
}
catch (Exception ex)
{
var result = MessageBox.Show(string.Format("Error occured when collecting files\n\n{0}", ex.Message), "Error occured", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
switch (result)
{
case DialogResult.Retry: goto again0;
case DialogResult.Cancel: return DialogResult.Cancel;
default: throw new Exception("Unknown option clicked.");
}
}
return ShowDialog();
}
private void IndexDialog_Load(object sender, EventArgs e)
{
backgroundWorker.RunWorkerAsync();
}
private void IndexDialog_FormClosing(object sender, FormClosingEventArgs e)
{
if (backgroundWorker.IsBusy)
{
e.Cancel = true;
if (!backgroundWorker.CancellationPending)
backgroundWorker.CancelAsync();
}
}
private void continueButton_Click(object sender, EventArgs e)
{
if (!backgroundWorker.IsBusy)
{
DialogResult = DialogResult.OK;
Close();
}
}
private void cancelButton_Click(object sender, EventArgs e)
{
if (backgroundWorker.IsBusy)
{
if(!backgroundWorker.CancellationPending)
backgroundWorker.CancelAsync();
cancelButton.Enabled = false;
}
else
{
DialogResult = DialogResult.Cancel;
Close();
}
}
private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
items = new List<Item>();
for (int i = 0; i < paths.Length; i++)
{
var path = paths[i];
var statusStr = Path.GetFileName(path) + ": ";
if(worker.CancellationPending)
{
worker.ReportProgress(i * 100 / paths.Length, statusStr + "Cancelled!");
e.Cancel = true;
return;
}
TagLib.File file;
try
{
file = TagLib.File.Create(path);
}
catch (Exception ex)
{
worker.ReportProgress(i * 100 / paths.Length, statusStr + "Exception!\r\n" + ex.Message);
Thread.Sleep(5000);
continue;
}
string relativePath;
if (path.StartsWith(musicFolder))
relativePath = path.Remove(0, musicFolder.Length);
else
relativePath = path;
items.Add(new Item
{
filename = path,
relativeFilename = relativePath,
artist = file.Tag.FirstPerformer,
title = file.Tag.Title,
bpm = string.Format("{0}BPM", file.Tag.BeatsPerMinute)
});
worker.ReportProgress((i + 1) * 100 / paths.Length, statusStr + "Ok!");
}
}
private void backgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
statusLabel.Text = e.UserState as string;
}
private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
DialogResult = DialogResult.Cancel;
Close();
}
else
{
cancelButton.Enabled = false;
continueButton.Enabled = true;
}
}
}
}

View File

@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="backgroundWorker.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

13
MusicOrganizer/Item.cs Normal file
View File

@@ -0,0 +1,13 @@
using System;
namespace MusicOrganizer
{
internal struct Item
{
public string filename;
public string relativeFilename;
public string artist;
public string title;
public string bpm;
}
}

View File

@@ -7,15 +7,6 @@ namespace MusicOrganizer
{
public partial class MainForm : Form
{
struct Item
{
public string filename;
public string relativeFilename;
public string artist;
public string title;
public string bpm;
}
private List<Item> items;
public MainForm()
@@ -28,88 +19,17 @@ namespace MusicOrganizer
private void button1_Click(object sender, EventArgs e)
{
string musicFolder;
using (var dialog = new FolderBrowserDialog())
using (var dialog = new IndexDialog())
{
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
return;
if (string.IsNullOrWhiteSpace(dialog.SelectedPath))
return;
musicFolder = dialog.SelectedPath;
}
if (!musicFolder.EndsWith("\\") && !musicFolder.EndsWith("/"))
musicFolder += Path.DirectorySeparatorChar;
string[] paths;
again1:
try
{
paths = Directory.GetFileSystemEntries(musicFolder, "*.mp3", SearchOption.AllDirectories);
}
catch(Exception ex)
{
var result = MessageBox.Show(string.Format("Error occured when collecting files\n\n{0}", ex.Message), "Error occured", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
switch(result)
if(dialog.Execute() == DialogResult.OK)
{
case DialogResult.Retry: goto again1;
case DialogResult.Cancel: return;
default: throw new Exception("Unknown option clicked.");
items = dialog.Items;
objectListView1.SetObjects(items);
objectListView1.AutoResizeColumns();
button2.Enabled = items.Count > 0;
}
}
var newItems = new List<Item>();
foreach (var path in paths)
{
TagLib.File file;
again2:
try
{
file = TagLib.File.Create(path);
}
catch(Exception ex)
{
var result = MessageBox.Show(string.Format("Error occured when processing file\n\n{0}\n\n{1}", path, ex.Message), "Error occured", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
switch(result)
{
case DialogResult.Abort: return;
case DialogResult.Retry: goto again2;
case DialogResult.Ignore: continue;
default: throw new Exception("Unknown option clicked.");
}
}
string relativePath;
if (path.StartsWith(musicFolder))
relativePath = path.Remove(0, musicFolder.Length);
else
relativePath = path;
newItems.Add(new Item
{
filename = path,
relativeFilename = relativePath,
artist = file.Tag.FirstPerformer,
title = file.Tag.Title,
bpm = string.Format("{0}BPM", file.Tag.BeatsPerMinute)
});
}
items = newItems;
objectListView1.SetObjects(items);
objectListView1.AutoResizeColumns();
button2.Enabled = items.Count > 0;
}
private void button2_Click(object sender, EventArgs e)

View File

@@ -5,7 +5,7 @@
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FCCFFEFE-15D8-47CF-8345-1B901C7B105A}</ProjectGuid>
<OutputType>Exe</OutputType>
<OutputType>WinExe</OutputType>
<RootNamespace>MusicOrganizer</RootNamespace>
<AssemblyName>MusicOrganizer</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
@@ -31,6 +31,9 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject>MusicOrganizer.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="policy.2.0.taglib-sharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=db62eba44689b5b0, processorArchitecture=MSIL">
<HintPath>..\packages\taglib.2.1.0.0\lib\policy.2.0.taglib-sharp.dll</HintPath>
@@ -50,6 +53,13 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="IndexDialog.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="IndexDialog.Designer.cs">
<DependentUpon>IndexDialog.cs</DependentUpon>
</Compile>
<Compile Include="Item.cs" />
<Compile Include="MainForm.cs">
<SubType>Form</SubType>
</Compile>
@@ -78,6 +88,9 @@
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="IndexDialog.resx">
<DependentUpon>IndexDialog.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon>
</EmbeddedResource>