Skip to content

Commit

Permalink
Simplify code by using new C# features
Browse files Browse the repository at this point in the history
  • Loading branch information
jbe2277 committed Nov 25, 2023
1 parent 7f0dd9d commit 9398939
Show file tree
Hide file tree
Showing 53 changed files with 171 additions and 278 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,15 @@ public ManagerController(IShellService shellService, IEnvironmentService environ
this.managerStatusService = managerStatusService;
this.fileSystemWatcherService = fileSystemWatcherService;
this.managerViewModel = managerViewModel;
musicFiles = new ObservableCollection<MusicFile>();
updateSubDirectoriesCommand = new DelegateCommand(UpdateSubDirectories);
navigateDirectoryUpCommand = new DelegateCommand(NavigateDirectoryUp, CanNavigateDirectoryUp);
navigateHomeCommand = new DelegateCommand(NavigateHome);
navigatePublicHomeCommand = new DelegateCommand(NavigatePublicHome);
loadRecursiveCommand = new DelegateCommand(LoadRecursive);
navigateToSelectedSubDirectoryCommand = new DelegateCommand(NavigateToSelectedSubDirectory);
showMusicPropertiesCommand = new DelegateCommand(ShowMusicProperties);
deleteSelectedFilesCommand = new DelegateCommand(DeleteSelectedFiles);
musicFiles = [];
updateSubDirectoriesCommand = new(UpdateSubDirectories);
navigateDirectoryUpCommand = new(NavigateDirectoryUp, CanNavigateDirectoryUp);
navigateHomeCommand = new(NavigateHome);
navigatePublicHomeCommand = new(NavigatePublicHome);
loadRecursiveCommand = new(LoadRecursive);
navigateToSelectedSubDirectoryCommand = new(NavigateToSelectedSubDirectory);
showMusicPropertiesCommand = new(ShowMusicProperties);
deleteSelectedFilesCommand = new(DeleteSelectedFiles);
}

private ManagerViewModel ManagerViewModel => managerViewModel.Value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public ModuleController(Lazy<ShellService> shellService, ISettingsService settin
this.playlistController = playlistController;
this.transcodingController = transcodingController;
this.shellViewModel = shellViewModel;
playlistManager = new PlaylistManager();
playlistManager = new();
settingsService.ErrorOccurred += (sender, e) => Log.Default.Error(e.Error, "Error in SettingsService");
appSettings = settingsService.Get<AppSettings>();
playlistSettings = settingsService.Get<PlaylistSettings>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public MusicPropertiesController(IShellService shellService, IMusicFileContext m
this.musicFileContext = musicFileContext;
this.selectionService = selectionService;
this.musicPropertiesViewModel = musicPropertiesViewModel;
changeTrackerService = new ChangeTrackerService();
musicFilesToSaveAfterPlaying = new HashSet<MusicFile>();
changeTrackerService = new();
musicFilesToSaveAfterPlaying = [];
}

public PlaylistManager PlaylistManager { get; set; } = null!;
Expand All @@ -49,7 +49,7 @@ public void Shutdown()

if (musicFilesToSaveAfterPlaying.Any())
{
allFilesSavedCompletion = new TaskCompletionSource<object?>();
allFilesSavedCompletion = new();
shellService.AddTaskToCompleteBeforeShutdown(allFilesSavedCompletion.Task);
}
}
Expand Down Expand Up @@ -78,7 +78,7 @@ private async Task SaveDirtyFilesAsync()

private async Task SaveMusicFilesToSaveAfterPlayingAsync()
{
var tasks = musicFilesToSaveAfterPlaying.ToArray().Select(x => SaveChangesAsync(x));
var tasks = musicFilesToSaveAfterPlaying.ToArray().Select(SaveChangesAsync);
await Task.WhenAll(tasks);
}

Expand All @@ -98,7 +98,7 @@ private async Task SaveChangesAsync(MusicFile musicFile)
}
else
{
allFilesToSave = new[] { musicFile };
allFilesToSave = [ musicFile ];
}

// Filter out the music file that is currently playing
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ public PlayerController(IShellService shellService, IEnvironmentService environm
this.playlistService = playlistService;
this.playerViewModel = playerViewModel;
this.infoViewModelFactory = infoViewModelFactory;
playAllCommand = new DelegateCommand(PlayAll, CanPlayAll);
playSelectedCommand = new DelegateCommand(PlaySelected, CanPlaySelected);
enqueueAllCommand = new DelegateCommand(EnqueueAll, CanEnqueueAll);
enqueueSelectedCommand = new DelegateCommand(EnqueueSelected, CanEnqueueSelected);
previousTrackCommand = new DelegateCommand(PreviousTrack, CanPreviousTrack);
nextTrackCommand = new DelegateCommand(NextTrack, CanNextTrack);
infoCommand = new DelegateCommand(ShowInfo);
showMusicPropertiesCommand = new DelegateCommand(ShowMusicProperties);
showPlaylistCommand = new DelegateCommand(ShowPlaylist);
playAllCommand = new(PlayAll, CanPlayAll);
playSelectedCommand = new(PlaySelected, CanPlaySelected);
enqueueAllCommand = new(EnqueueAll, CanEnqueueAll);
enqueueSelectedCommand = new(EnqueueSelected, CanEnqueueSelected);
previousTrackCommand = new(PreviousTrack, CanPreviousTrack);
nextTrackCommand = new(NextTrack, CanNextTrack);
infoCommand = new(ShowInfo);
showMusicPropertiesCommand = new(ShowMusicProperties);
showPlaylistCommand = new(ShowPlaylist);
}

public PlaylistManager PlaylistManager { get; set; } = null!;
Expand Down Expand Up @@ -198,21 +198,9 @@ private void PlaylistManagerPropertyChanged(object? sender, PropertyChangedEvent
}
}

private void UpdateCommands()
{
previousTrackCommand.RaiseCanExecuteChanged();
nextTrackCommand.RaiseCanExecuteChanged();
}
private void UpdateCommands() => DelegateCommand.RaiseCanExecuteChanged(previousTrackCommand, nextTrackCommand);

private void MusicFilesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
playAllCommand.RaiseCanExecuteChanged();
enqueueAllCommand.RaiseCanExecuteChanged();
}
private void MusicFilesCollectionChanged(object? _, NotifyCollectionChangedEventArgs e) => DelegateCommand.RaiseCanExecuteChanged(playAllCommand, enqueueAllCommand);

private void SelectedMusicFilesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
playSelectedCommand.RaiseCanExecuteChanged();
enqueueSelectedCommand.RaiseCanExecuteChanged();
}
private void SelectedMusicFilesCollectionChanged(object? _, NotifyCollectionChangedEventArgs e) => DelegateCommand.RaiseCanExecuteChanged(playSelectedCommand, enqueueSelectedCommand);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using Waf.MusicManager.Applications.Properties;
using Waf.MusicManager.Applications.Services;
using Waf.MusicManager.Applications.ViewModels;
using Waf.MusicManager.Domain;
using Waf.MusicManager.Domain.MusicFiles;
using Waf.MusicManager.Domain.Playlists;

Expand Down Expand Up @@ -43,14 +42,14 @@ public PlaylistController(IFileDialogService fileDialogService, IShellService sh
this.musicFileContext = musicFileContext;
this.playerService = playerService;
this.musicPropertiesService = musicPropertiesService;
playSelectedCommand = new DelegateCommand(PlaySelected, CanPlaySelected);
removeSelectedCommand = new DelegateCommand(RemoveSelected, CanRemoveSelected);
showMusicPropertiesCommand = new DelegateCommand(ShowMusicProperties);
openListCommand = new DelegateCommand(OpenList);
saveListCommand = new DelegateCommand(SaveList);
clearListCommand = new DelegateCommand(ClearList);
openPlaylistFileType = new FileType(Resources.Playlist, IFileService.PlaylistFileExtensions);
savePlaylistFileType = new FileType(Resources.Playlist, IFileService.PlaylistFileExtensions[0]);
playSelectedCommand = new(PlaySelected, CanPlaySelected);
removeSelectedCommand = new(RemoveSelected, CanRemoveSelected);
showMusicPropertiesCommand = new(ShowMusicProperties);
openListCommand = new(OpenList);
saveListCommand = new(SaveList);
clearListCommand = new(ClearList);
openPlaylistFileType = new(Resources.Playlist, IFileService.PlaylistFileExtensions);
savePlaylistFileType = new(Resources.Playlist, IFileService.PlaylistFileExtensions[0]);
}

public PlaylistSettings PlaylistSettings { get; set; } = null!;
Expand Down Expand Up @@ -214,9 +213,5 @@ private void PlaylistViewModelPropertyChanged(object? sender, PropertyChangedEve
if (e.PropertyName == nameof(PlaylistViewModel.SelectedPlaylistItem)) UpdateCommands();
}

private void UpdateCommands()
{
playSelectedCommand.RaiseCanExecuteChanged();
removeSelectedCommand.RaiseCanExecuteChanged();
}
private void UpdateCommands() => DelegateCommand.RaiseCanExecuteChanged(playSelectedCommand, removeSelectedCommand);
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ public TranscodingController(IMessageService messageService, IShellService shell
this.transcodingService = transcodingService;
this.transcoder = transcoder;
this.transcodingListViewModel = transcodingListViewModel;
cancellationTokenSources = new Dictionary<TranscodeItem, CancellationTokenSource>();
convertToMp3AllCommand = new DelegateCommand(ConvertToMp3All, CanConvertToMp3All);
convertToMp3SelectedCommand = new DelegateCommand(ConvertToMp3Selected, CanConvertToMp3Selected);
cancelAllCommand = new DelegateCommand(CancelAll, CanCancelAll);
cancelSelectedCommand = new DelegateCommand(CancelSelected, CanCancelSelected);
throttler = new SemaphoreSlim(Environment.ProcessorCount); // Do not dispose the throttler; it is used after Shutdown to cancel the open tasks
transcodingManager = new TranscodingManager();
throttledMusicFilesCollectionChangedAction = new ThrottledAction(ThrottledMusicFilesCollectionChanged, ThrottledActionMode.InvokeOnlyIfIdleForDelayTime, TimeSpan.FromMilliseconds(10));
cancellationTokenSources = [];
convertToMp3AllCommand = new(ConvertToMp3All, CanConvertToMp3All);
convertToMp3SelectedCommand = new(ConvertToMp3Selected, CanConvertToMp3Selected);
cancelAllCommand = new(CancelAll, CanCancelAll);
cancelSelectedCommand = new(CancelSelected, CanCancelSelected);
throttler = new(Environment.ProcessorCount); // Do not dispose the throttler; it is used after Shutdown to cancel the open tasks
transcodingManager = new();
throttledMusicFilesCollectionChangedAction = new(ThrottledMusicFilesCollectionChanged, ThrottledActionMode.InvokeOnlyIfIdleForDelayTime, TimeSpan.FromMilliseconds(10));
}

private TranscodingListViewModel TranscodingListViewModel => transcodingListViewModel.Value;
Expand All @@ -60,7 +60,7 @@ public void Initialize()
transcodingService.CancelAllCommand = cancelAllCommand;
transcodingService.CancelSelectedCommand = cancelSelectedCommand;

shellService.TranscodingListView = new Lazy<object>(InitializeTranscodingListView);
shellService.TranscodingListView = new(InitializeTranscodingListView);

shellService.Closing += ShellServiceClosing;
selectionService.MusicFiles.CollectionChanged += (sender, e) => throttledMusicFilesCollectionChangedAction.InvokeAccumulated();
Expand All @@ -71,7 +71,7 @@ public void Shutdown()
{
if (cancellationTokenSources.Any())
{
allTranscodingsCanceledCompletion = new TaskCompletionSource<object?>();
allTranscodingsCanceledCompletion = new();
CancelAll();
shellService.AddTaskToCompleteBeforeShutdown(allTranscodingsCanceledCompletion.Task);
}
Expand All @@ -82,7 +82,7 @@ private object InitializeTranscodingListView()
TranscodingListViewModel.TranscodingManager = transcodingManager;
TranscodingListViewModel.InsertFilesAction = InsertFiles;
TranscodingListViewModel.InsertMusicFilesAction = InsertMusicFiles;
CollectionChangedEventManager.AddHandler((INotifyCollectionChanged)TranscodingListViewModel.SelectedTranscodeItems, SelectedTranscodeItemsCollectionChanged);
CollectionChangedEventManager.AddHandler(TranscodingListViewModel.SelectedTranscodeItems, SelectedTranscodeItemsCollectionChanged);
return TranscodingListViewModel.View;
}

Expand Down Expand Up @@ -179,9 +179,9 @@ private async void TranscodeAsync(MusicFile musicFile)
finally
{
cancellationTokenSources.Remove(transcodeItem);
if (allTranscodingsCanceledCompletion != null && !cancellationTokenSources.Any())
if (!cancellationTokenSources.Any())
{
allTranscodingsCanceledCompletion.SetResult(null);
allTranscodingsCanceledCompletion?.SetResult(null);
}
UpdateCancelCommands();
Log.Default.Trace("End Transcode: {0} > {1}", musicFile.FileName, destinationFileName);
Expand Down Expand Up @@ -217,20 +217,12 @@ private async Task TranscodeAsyncCore(TranscodeItem transcodeItem, uint bitrate,
<= 256000 => 256000,
_ => 320000
};

private void ThrottledMusicFilesCollectionChanged()
{
convertToMp3AllCommand.RaiseCanExecuteChanged();
convertToMp3SelectedCommand.RaiseCanExecuteChanged();
}

private void ThrottledMusicFilesCollectionChanged() => DelegateCommand.RaiseCanExecuteChanged(convertToMp3AllCommand, convertToMp3SelectedCommand);

private void SelectedMusicFilesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => convertToMp3SelectedCommand.RaiseCanExecuteChanged();

private void SelectedTranscodeItemsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => UpdateCancelCommands();

private void UpdateCancelCommands()
{
cancelAllCommand.RaiseCanExecuteChanged();
cancelSelectedCommand.RaiseCanExecuteChanged();
}
private void UpdateCancelCommands() => DelegateCommand.RaiseCanExecuteChanged(cancelAllCommand, cancelSelectedCommand);
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
namespace Waf.MusicManager.Applications.DataModels;
using Waf.MusicManager.Applications.Services;

namespace Waf.MusicManager.Applications.DataModels;

public class FolderBrowserDataModel : Model
{
private string userPath = "";
private string currentPath = null!;
private IReadOnlyList<FolderItem> subDirectories = Array.Empty<FolderItem>();
private IReadOnlyList<FolderItem> subDirectories = [];
private FolderItem? selectedSubDirectory;

public string UserPath
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace Waf.MusicManager.Applications.DataModels;

public class MusicFileDataModel : Model
{
private IWeakEventProxy? musicFilePropertyChangedProxy;

public MusicFileDataModel(MusicFile musicFile)
{
MusicFile = musicFile;
Expand All @@ -14,21 +16,21 @@ public MusicFileDataModel(MusicFile musicFile)
}
else
{
PropertyChangedEventManager.AddHandler(musicFile, MusicFilePropertyChanged, "");
musicFilePropertyChangedProxy = WeakEvent.PropertyChanged.Add(musicFile, MusicFilePropertyChanged);
}
}

public MusicFile MusicFile { get; }

public string ArtistsString => string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", MusicFile.IsMetadataLoaded ? MusicFile.Metadata.Artists : Array.Empty<string>());
public string ArtistsString => string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator + " ", MusicFile.IsMetadataLoaded ? MusicFile.Metadata.Artists : []);

private void MetadataLoaded() => PropertyChangedEventManager.AddHandler(MusicFile.Metadata, MetadataPropertyChanged, "");

private void MusicFilePropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(MusicFile.IsMetadataLoaded))
{
PropertyChangedEventManager.RemoveHandler(MusicFile, MusicFilePropertyChanged, "");
WeakEvent.TryRemove(ref musicFilePropertyChangedProxy);
MetadataLoaded();
RaisePropertyChanged(nameof(ArtistsString));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class SearchFilterDataModel : Model
private string artistFilter = "";
private string titleFilter = "";
private string albumFilter = "";
private IReadOnlyList<string> genreFilter = Array.Empty<string>();
private IReadOnlyList<string> genreFilter = [];
private FilterOperator ratingFilterOperator;
private uint ratingFilter;
private uint? fromYearFilter;
Expand Down Expand Up @@ -144,7 +144,7 @@ public void Clear()
ArtistFilter = "";
TitleFilter = "";
AlbumFilter = "";
if (GenreFilter.Any()) GenreFilter = Array.Empty<string>();
if (GenreFilter.Any()) GenreFilter = [];
FromYearFilter = "";
ToYearFilter = "";
RatingFilter = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,19 @@ namespace Waf.MusicManager.Applications.Properties;
[DataContract]
public sealed class PlaylistSettings : UserSettingsBase
{
[DataMember(Name = "FileNames")] private readonly List<string> fileNames = new();
[DataMember(Name = "FileNames")] private readonly List<string> fileNames = [];

[DataMember] public string? LastPlayedFileName { get; set; }

[DataMember] public TimeSpan LastPlayedFilePosition { get; set; }

public IReadOnlyList<string> FileNames { get { return fileNames; } }
public IReadOnlyList<string> FileNames => fileNames;

public void ReplaceAll(IEnumerable<string> newFileNames)
{
fileNames.Clear();
fileNames.AddRange(newFileNames);
}

protected override void SetDefaultValues()
{
}
protected override void SetDefaultValues() { }
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
namespace Waf.MusicManager.Applications.Services;

internal class ApplicationBusyContext : IDisposable
internal sealed class ApplicationBusyContext(Action<ApplicationBusyContext> disposeCallback) : IDisposable
{
private readonly Action<ApplicationBusyContext> disposeCallback;

public ApplicationBusyContext(Action<ApplicationBusyContext> disposeCallback)
{
this.disposeCallback = disposeCallback;
}

public void Dispose() => disposeCallback(this);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,7 @@ namespace Waf.MusicManager.Applications.Services;

internal class ChangeTrackerService : IChangeTrackerService
{
private readonly HashSet<Entity> entitiesWithChanges;

public ChangeTrackerService()
{
entitiesWithChanges = new HashSet<Entity>();
}
private readonly HashSet<Entity> entitiesWithChanges = [];

public IEnumerable<Entity> GetEntitiesWithChanges() => entitiesWithChanges.ToArray();

Expand Down
Loading

0 comments on commit 9398939

Please sign in to comment.