diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..fd05618 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,202 @@ +# Rules in this file were initially inferred by Visual Studio IntelliCode from the Template Studio codebase. +# You can modify the rules from these initially generated values to suit your own policies. +# You can learn more about editorconfig here: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference. + +[*.cs] + +#Core editorconfig formatting - indentation + +#use soft tabs (spaces) for indentation +indent_style = space + +#Formatting - new line options + +#place else statements on a new line +csharp_new_line_before_else = true +#require braces to be on a new line for lambdas, methods, control_blocks, types, properties, and accessors (also known as "Allman" style) +csharp_new_line_before_open_brace = all + +#Formatting - organize using options + +#sort System.* using directives alphabetically, and place them before other usings +dotnet_sort_system_directives_first = true + +#Formatting - spacing options + +#require NO space between a cast and the value +csharp_space_after_cast = false +#require a space before the colon for bases or interfaces in a type declaration +csharp_space_after_colon_in_inheritance_clause = true +#require a space after a keyword in a control flow statement such as a for loop +csharp_space_after_keywords_in_control_flow_statements = true +#require a space before the colon for bases or interfaces in a type declaration +csharp_space_before_colon_in_inheritance_clause = true +#remove space within empty argument list parentheses +csharp_space_between_method_call_empty_parameter_list_parentheses = false +#remove space between method call name and opening parenthesis +csharp_space_between_method_call_name_and_opening_parenthesis = false +#do not place space characters after the opening parenthesis and before the closing parenthesis of a method call +csharp_space_between_method_call_parameter_list_parentheses = false +#remove space within empty parameter list parentheses for a method declaration +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +#place a space character after the opening parenthesis and before the closing parenthesis of a method declaration parameter list. +csharp_space_between_method_declaration_parameter_list_parentheses = false + +#Formatting - wrapping options + +#leave code block on separate lines +csharp_preserve_single_line_blocks = false + +#Style - Code block preferences + +#prefer curly braces even for one line of code +csharp_prefer_braces = true:suggestion + +#Style - expression bodied member options + +#prefer expression bodies for accessors +csharp_style_expression_bodied_accessors = true:warning +#prefer block bodies for constructors +csharp_style_expression_bodied_constructors = false:suggestion +#prefer expression bodies for methods +csharp_style_expression_bodied_methods = when_on_single_line:silent +#prefer expression-bodied members for properties +csharp_style_expression_bodied_properties = true:warning + +#Style - expression level options + +#prefer out variables to be declared before the method call +csharp_style_inlined_variable_declaration = false:suggestion +#prefer the language keyword for member access expressions, instead of the type name, for types that have a keyword to represent them +dotnet_style_predefined_type_for_member_access = true:suggestion + +#Style - Expression-level preferences + +#prefer default over default(T) +csharp_prefer_simple_default_expression = true:suggestion +#prefer objects to be initialized using object initializers when possible +dotnet_style_object_initializer = true:suggestion + +#Style - implicit and explicit types + +#prefer var over explicit type in all cases, unless overridden by another code style rule +csharp_style_var_elsewhere = true:suggestion +#prefer var is used to declare variables with built-in system types such as int +csharp_style_var_for_built_in_types = true:suggestion +#prefer var when the type is already mentioned on the right-hand side of a declaration expression +csharp_style_var_when_type_is_apparent = true:suggestion + +#Style - language keyword and framework type options + +#prefer the language keyword for local variables, method parameters, and class members, instead of the type name, for types that have a keyword to represent them +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion + +#Style - Language rules +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning +csharp_style_var_for_built_in_types = true:warning + +#Style - modifier options + +#prefer accessibility modifiers to be declared except for public interface members. This will currently not differ from always and will act as future proofing for if C# adds default interface methods. +dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion + +#Style - Modifier preferences + +#when this rule is set to a list of modifiers, prefer the specified ordering. +csharp_preferred_modifier_order = public,private,protected,internal,static,async,readonly,override,sealed,abstract,virtual:warning +dotnet_style_readonly_field = true:warning + +#Style - Pattern matching + +#prefer pattern matching instead of is expression with type casts +csharp_style_pattern_matching_over_as_with_null_check = true:warning + +#Style - qualification options + +#prefer events not to be prefaced with this. or Me. in Visual Basic +dotnet_style_qualification_for_event = false:suggestion +#prefer fields not to be prefaced with this. or Me. in Visual Basic +dotnet_style_qualification_for_field = false:suggestion +#prefer methods not to be prefaced with this. or Me. in Visual Basic +dotnet_style_qualification_for_method = false:suggestion +#prefer properties not to be prefaced with this. or Me. in Visual Basic +dotnet_style_qualification_for_property = false:suggestion +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:warning +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +[*.{cs,vb}] + +#Style - Unnecessary code rules +csharp_style_unused_value_assignment_preference = discard_variable:warning + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:warning +dotnet_style_prefer_simplified_interpolation = true:suggestion diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/.vsconfig b/.vsconfig new file mode 100644 index 0000000..65d1f73 --- /dev/null +++ b/.vsconfig @@ -0,0 +1,16 @@ +{ + "version": "1.0", + "components": [ + "Microsoft.Component.MSBuild", + "Microsoft.NetCore.Component.Runtime.7.0", + "Microsoft.NetCore.Component.SDK", + "Microsoft.VisualStudio.Component.ManagedDesktop.Core", + "Microsoft.VisualStudio.Component.ManagedDesktop.Prerequisites", + "Microsoft.VisualStudio.Component.NuGet", + "Microsoft.VisualStudio.Component.Windows10SDK.19041", + "Microsoft.VisualStudio.Component.Windows10SDK", + "Microsoft.VisualStudio.ComponentGroup.MSIX.Packaging", + "Microsoft.VisualStudio.ComponentGroup.WindowsAppSDK.Cs", + "Microsoft.VisualStudio.Workload.ManagedDesktop" + ] +} diff --git a/The Untamed Music Player.Core/Contracts/Services/IFileService.cs b/The Untamed Music Player.Core/Contracts/Services/IFileService.cs new file mode 100644 index 0000000..bd06abd --- /dev/null +++ b/The Untamed Music Player.Core/Contracts/Services/IFileService.cs @@ -0,0 +1,10 @@ +namespace The_Untamed_Music_Player.Core.Contracts.Services; + +public interface IFileService +{ + T Read(string folderPath, string fileName); + + void Save(string folderPath, string fileName, T content); + + void Delete(string folderPath, string fileName); +} diff --git a/The Untamed Music Player.Core/Helpers/Json.cs b/The Untamed Music Player.Core/Helpers/Json.cs new file mode 100644 index 0000000..856f3e2 --- /dev/null +++ b/The Untamed Music Player.Core/Helpers/Json.cs @@ -0,0 +1,22 @@ +using Newtonsoft.Json; + +namespace The_Untamed_Music_Player.Core.Helpers; + +public static class Json +{ + public static async Task ToObjectAsync(string value) + { + return await Task.Run(() => + { + return JsonConvert.DeserializeObject(value); + }); + } + + public static async Task StringifyAsync(object value) + { + return await Task.Run(() => + { + return JsonConvert.SerializeObject(value); + }); + } +} diff --git a/The Untamed Music Player.Core/README.md b/The Untamed Music Player.Core/README.md new file mode 100644 index 0000000..906c066 --- /dev/null +++ b/The Untamed Music Player.Core/README.md @@ -0,0 +1,5 @@ +*Recommended Markdown Viewer: [Markdown Editor](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.MarkdownEditor2)* + +## Getting Started + +The Core project contains code that can be [reused across multiple application projects](https://docs.microsoft.com/dotnet/standard/net-standard#net-5-and-net-standard). diff --git a/The Untamed Music Player.Core/Services/FileService.cs b/The Untamed Music Player.Core/Services/FileService.cs new file mode 100644 index 0000000..c51497e --- /dev/null +++ b/The Untamed Music Player.Core/Services/FileService.cs @@ -0,0 +1,41 @@ +using System.Text; + +using Newtonsoft.Json; + +using The_Untamed_Music_Player.Core.Contracts.Services; + +namespace The_Untamed_Music_Player.Core.Services; + +public class FileService : IFileService +{ + public T Read(string folderPath, string fileName) + { + var path = Path.Combine(folderPath, fileName); + if (File.Exists(path)) + { + var json = File.ReadAllText(path); + return JsonConvert.DeserializeObject(json); + } + + return default; + } + + public void Save(string folderPath, string fileName, T content) + { + if (!Directory.Exists(folderPath)) + { + Directory.CreateDirectory(folderPath); + } + + var fileContent = JsonConvert.SerializeObject(content); + File.WriteAllText(Path.Combine(folderPath, fileName), fileContent, Encoding.UTF8); + } + + public void Delete(string folderPath, string fileName) + { + if (fileName != null && File.Exists(Path.Combine(folderPath, fileName))) + { + File.Delete(Path.Combine(folderPath, fileName)); + } + } +} diff --git a/The Untamed Music Player.Core/The Untamed Music Player.Core.csproj b/The Untamed Music Player.Core/The Untamed Music Player.Core.csproj new file mode 100644 index 0000000..dfad77e --- /dev/null +++ b/The Untamed Music Player.Core/The Untamed Music Player.Core.csproj @@ -0,0 +1,17 @@ + + + net9.0 + The_Untamed_Music_Player.Core + AnyCPU;x64;x86 + x86;x64;arm64;AnyCPU + enable + + + + + + + + + + diff --git a/The Untamed Music Player.sln b/The Untamed Music Player.sln new file mode 100644 index 0000000..921380f --- /dev/null +++ b/The Untamed Music Player.sln @@ -0,0 +1,69 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.10.35027.167 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "The Untamed Music Player", "The Untamed Music Player\The Untamed Music Player.csproj", "{FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "The Untamed Music Player.Core", "The Untamed Music Player.Core\The Untamed Music Player.Core.csproj", "{75B34C4A-032F-4EE8-9201-AA6E951514B9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|arm64 = Debug|arm64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|arm64 = Release|arm64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|Any CPU.ActiveCfg = Debug|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|Any CPU.Build.0 = Debug|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|Any CPU.Deploy.0 = Debug|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|arm64.ActiveCfg = Debug|arm64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|arm64.Build.0 = Debug|arm64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|arm64.Deploy.0 = Debug|arm64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|x64.ActiveCfg = Debug|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|x64.Build.0 = Debug|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|x64.Deploy.0 = Debug|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|x86.ActiveCfg = Debug|x86 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|x86.Build.0 = Debug|x86 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Debug|x86.Deploy.0 = Debug|x86 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|Any CPU.ActiveCfg = Release|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|Any CPU.Build.0 = Release|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|Any CPU.Deploy.0 = Release|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|arm64.ActiveCfg = Release|arm64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|arm64.Build.0 = Release|arm64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|arm64.Deploy.0 = Release|arm64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|x64.ActiveCfg = Release|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|x64.Build.0 = Release|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|x64.Deploy.0 = Release|x64 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|x86.ActiveCfg = Release|x86 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|x86.Build.0 = Release|x86 + {FAF574F3-DB0A-4B33-BF19-45CF6396C9F7}.Release|x86.Deploy.0 = Release|x86 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Debug|arm64.ActiveCfg = Debug|arm64 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Debug|arm64.Build.0 = Debug|arm64 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Debug|x64.ActiveCfg = Debug|x64 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Debug|x64.Build.0 = Debug|x64 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Debug|x86.ActiveCfg = Debug|x86 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Debug|x86.Build.0 = Debug|x86 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Release|Any CPU.Build.0 = Release|Any CPU + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Release|arm64.ActiveCfg = Release|arm64 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Release|arm64.Build.0 = Release|arm64 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Release|x64.ActiveCfg = Release|x64 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Release|x64.Build.0 = Release|x64 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Release|x86.ActiveCfg = Release|x86 + {75B34C4A-032F-4EE8-9201-AA6E951514B9}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {AEF480F6-CB86-454F-98FB-9A7464624FB5} + EndGlobalSection +EndGlobal diff --git a/The Untamed Music Player/Activation/ActivationHandler.cs b/The Untamed Music Player/Activation/ActivationHandler.cs new file mode 100644 index 0000000..da15df7 --- /dev/null +++ b/The Untamed Music Player/Activation/ActivationHandler.cs @@ -0,0 +1,17 @@ +namespace The_Untamed_Music_Player.Activation; + +// Extend this class to implement new ActivationHandlers. See DefaultActivationHandler for an example. +// https://github.com/microsoft/TemplateStudio/blob/main/docs/WinUI/activation.md +public abstract class ActivationHandler : IActivationHandler + where T : class +{ + // Override this method to add the logic for whether to handle the activation. + protected virtual bool CanHandleInternal(T args) => true; + + // Override this method to add the logic for your activation handler. + protected abstract Task HandleInternalAsync(T args); + + public bool CanHandle(object args) => args is T && CanHandleInternal((args as T)!); + + public async Task HandleAsync(object args) => await HandleInternalAsync((args as T)!); +} diff --git a/The Untamed Music Player/Activation/DefaultActivationHandler.cs b/The Untamed Music Player/Activation/DefaultActivationHandler.cs new file mode 100644 index 0000000..73b4108 --- /dev/null +++ b/The Untamed Music Player/Activation/DefaultActivationHandler.cs @@ -0,0 +1,29 @@ +using Microsoft.UI.Xaml; + +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Activation; + +public class DefaultActivationHandler : ActivationHandler +{ + private readonly INavigationService _navigationService; + + public DefaultActivationHandler(INavigationService navigationService) + { + _navigationService = navigationService; + } + + protected override bool CanHandleInternal(LaunchActivatedEventArgs args) + { + // None of the ActivationHandlers has handled the activation. + return _navigationService.Frame?.Content == null; + } + + protected async override Task HandleInternalAsync(LaunchActivatedEventArgs args) + { + _navigationService.NavigateTo(typeof(主页ViewModel).FullName!, args.Arguments); + + await Task.CompletedTask; + } +} diff --git a/The Untamed Music Player/Activation/IActivationHandler.cs b/The Untamed Music Player/Activation/IActivationHandler.cs new file mode 100644 index 0000000..597fa47 --- /dev/null +++ b/The Untamed Music Player/Activation/IActivationHandler.cs @@ -0,0 +1,8 @@ +namespace The_Untamed_Music_Player.Activation; + +public interface IActivationHandler +{ + bool CanHandle(object args); + + Task HandleAsync(object args); +} diff --git a/The Untamed Music Player/App.xaml b/The Untamed Music Player/App.xaml new file mode 100644 index 0000000..0ae4112 --- /dev/null +++ b/The Untamed Music Player/App.xaml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + diff --git a/The Untamed Music Player/App.xaml.cs b/The Untamed Music Player/App.xaml.cs new file mode 100644 index 0000000..f4022f7 --- /dev/null +++ b/The Untamed Music Player/App.xaml.cs @@ -0,0 +1,125 @@ +using System.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using The_Untamed_Music_Player.Activation; +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Core.Contracts.Services; +using The_Untamed_Music_Player.Core.Services; +using The_Untamed_Music_Player.Models; +using The_Untamed_Music_Player.Services; +using The_Untamed_Music_Player.ViewModels; +using The_Untamed_Music_Player.Views; + +namespace The_Untamed_Music_Player; + +// To learn more about WinUI 3, see https://docs.microsoft.com/windows/apps/winui/winui3/. +public partial class App : Application +{ + // The .NET Generic Host provides dependency injection, configuration, logging, and other services. + // https://docs.microsoft.com/dotnet/core/extensions/generic-host + // https://docs.microsoft.com/dotnet/core/extensions/dependency-injection + // https://docs.microsoft.com/dotnet/core/extensions/configuration + // https://docs.microsoft.com/dotnet/core/extensions/logging + public IHost Host + { + get; + } + + public static T GetService() + where T : class + { + if ((App.Current as App)!.Host.Services.GetService(typeof(T)) is not T service) + { + throw new ArgumentException($"{typeof(T)} needs to be registered in ConfigureServices within App.xaml.cs."); + } + + return service; + } + + public static WindowEx? MainWindow + { + get; private set; + } + + + public static UIElement? AppTitlebar + { + get; set; + } + + + public App() + { + Debug.WriteLine("App.xaml.cs: Constructor"); + InitializeComponent(); + + Host = Microsoft.Extensions.Hosting.Host. + CreateDefaultBuilder(). + UseContentRoot(AppContext.BaseDirectory). + ConfigureServices((context, services) =>//注册服务信息 + { + // Default Activation Handler + services.AddTransient, DefaultActivationHandler>(); + + // Other Activation Handlers + + // Services + services.AddSingleton(); + services.AddSingleton(); + services.AddTransient(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + // Core Services + services.AddSingleton(); + + // Views and ViewModels + services.AddTransient(); + services.AddTransient(); + services.AddTransient<播放列表ViewModel>(); + services.AddTransient<播放列表Page>(); + services.AddTransient<播放队列ViewModel>(); + services.AddTransient<播放队列Page>(); + services.AddTransient<音乐库ViewModel>(); + services.AddTransient<音乐库Page>(); + services.AddTransient<主页ViewModel>(); + services.AddTransient<主页Page>(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient<歌词Page>(); + services.AddTransient<歌词ViewModel>(); + services.AddTransient<无音乐Page>(); + services.AddTransient<无音乐ViewModel>(); + services.AddTransient<有音乐Page>(); + services.AddTransient<有音乐ViewModel>(); + services.AddTransient<歌曲Page>(); + services.AddTransient<歌曲ViewModel>(); + services.AddTransient<专辑Page>(); + services.AddTransient<专辑ViewModel>(); + services.AddTransient<艺术家Page>(); + services.AddTransient<艺术家ViewModel>(); + + // Configuration + services.Configure(context.Configuration.GetSection(nameof(LocalSettingsOptions))); + }). + Build();//生成容器 + + + Debug.WriteLine($"AppMainWindow is null: {MainWindow == null}"); + Debug.WriteLine("App.xaml.cs: Constructor End"); + } + + protected async override void OnLaunched(LaunchActivatedEventArgs args) + { + base.OnLaunched(args); + MainWindow = new MainWindow(GetService()); + Debug.WriteLine($"OnMainWindow is null: {MainWindow == null}"); + await GetService().ActivateAsync(args); + } +} diff --git a/The Untamed Music Player/Behaviors/NavigationViewHeaderBehavior.cs b/The Untamed Music Player/Behaviors/NavigationViewHeaderBehavior.cs new file mode 100644 index 0000000..ec3ef94 --- /dev/null +++ b/The Untamed Music Player/Behaviors/NavigationViewHeaderBehavior.cs @@ -0,0 +1,122 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Navigation; +using Microsoft.Xaml.Interactivity; + +using The_Untamed_Music_Player.Contracts.Services; + +namespace The_Untamed_Music_Player.Behaviors; + +public class NavigationViewHeaderBehavior : Behavior +{ + private static NavigationViewHeaderBehavior? _current; + + private Page? _currentPage; + + public DataTemplate? DefaultHeaderTemplate + { + get; set; + } + + public object DefaultHeader + { + get => GetValue(DefaultHeaderProperty); + set => SetValue(DefaultHeaderProperty, value); + } + + public static readonly DependencyProperty DefaultHeaderProperty = + DependencyProperty.Register("DefaultHeader", typeof(object), typeof(NavigationViewHeaderBehavior), new PropertyMetadata(null, (d, e) => _current!.UpdateHeader())); + + public static NavigationViewHeaderMode GetHeaderMode(Page item) => (NavigationViewHeaderMode)item.GetValue(HeaderModeProperty); + + public static void SetHeaderMode(Page item, NavigationViewHeaderMode value) => item.SetValue(HeaderModeProperty, value); + + public static readonly DependencyProperty HeaderModeProperty = + DependencyProperty.RegisterAttached("HeaderMode", typeof(bool), typeof(NavigationViewHeaderBehavior), new PropertyMetadata(NavigationViewHeaderMode.Always, (d, e) => _current!.UpdateHeader())); + + public static object GetHeaderContext(Page item) => item.GetValue(HeaderContextProperty); + + public static void SetHeaderContext(Page item, object value) => item.SetValue(HeaderContextProperty, value); + + public static readonly DependencyProperty HeaderContextProperty = + DependencyProperty.RegisterAttached("HeaderContext", typeof(object), typeof(NavigationViewHeaderBehavior), new PropertyMetadata(null, (d, e) => _current!.UpdateHeader())); + + public static DataTemplate GetHeaderTemplate(Page item) => (DataTemplate)item.GetValue(HeaderTemplateProperty); + + public static void SetHeaderTemplate(Page item, DataTemplate value) => item.SetValue(HeaderTemplateProperty, value); + + public static readonly DependencyProperty HeaderTemplateProperty = + DependencyProperty.RegisterAttached("HeaderTemplate", typeof(DataTemplate), typeof(NavigationViewHeaderBehavior), new PropertyMetadata(null, (d, e) => _current!.UpdateHeaderTemplate())); + + protected override void OnAttached() + { + base.OnAttached(); + + var navigationService = App.GetService(); + navigationService.Navigated += OnNavigated; + + _current = this; + } + + protected override void OnDetaching() + { + base.OnDetaching(); + + var navigationService = App.GetService(); + navigationService.Navigated -= OnNavigated; + } + + private void OnNavigated(object sender, NavigationEventArgs e) + { + if (sender is Frame frame && frame.Content is Page page) + { + _currentPage = page; + + UpdateHeader(); + UpdateHeaderTemplate(); + } + } + + private void UpdateHeader() + { + if (_currentPage != null) + { + var headerMode = GetHeaderMode(_currentPage); + if (headerMode == NavigationViewHeaderMode.Never) + { + AssociatedObject.Header = null; + AssociatedObject.AlwaysShowHeader = false; + } + else + { + var headerFromPage = GetHeaderContext(_currentPage); + if (headerFromPage != null) + { + AssociatedObject.Header = headerFromPage; + } + else + { + AssociatedObject.Header = DefaultHeader; + } + + if (headerMode == NavigationViewHeaderMode.Always) + { + AssociatedObject.AlwaysShowHeader = true; + } + else + { + AssociatedObject.AlwaysShowHeader = false; + } + } + } + } + + private void UpdateHeaderTemplate() + { + if (_currentPage != null) + { + var headerTemplate = GetHeaderTemplate(_currentPage); + AssociatedObject.HeaderTemplate = headerTemplate ?? DefaultHeaderTemplate; + } + } +} diff --git a/The Untamed Music Player/Behaviors/NavigationViewHeaderMode.cs b/The Untamed Music Player/Behaviors/NavigationViewHeaderMode.cs new file mode 100644 index 0000000..a1ea4b2 --- /dev/null +++ b/The Untamed Music Player/Behaviors/NavigationViewHeaderMode.cs @@ -0,0 +1,8 @@ +namespace The_Untamed_Music_Player.Behaviors; + +public enum NavigationViewHeaderMode +{ + Always, + Never, + Minimal +} diff --git a/The Untamed Music Player/Contracts/Services/IActivationService.cs b/The Untamed Music Player/Contracts/Services/IActivationService.cs new file mode 100644 index 0000000..2f7f82f --- /dev/null +++ b/The Untamed Music Player/Contracts/Services/IActivationService.cs @@ -0,0 +1,6 @@ +namespace The_Untamed_Music_Player.Contracts.Services; + +public interface IActivationService +{ + Task ActivateAsync(object activationArgs); +} diff --git a/The Untamed Music Player/Contracts/Services/ILocalSettingsService.cs b/The Untamed Music Player/Contracts/Services/ILocalSettingsService.cs new file mode 100644 index 0000000..a4f0b7b --- /dev/null +++ b/The Untamed Music Player/Contracts/Services/ILocalSettingsService.cs @@ -0,0 +1,8 @@ +namespace The_Untamed_Music_Player.Contracts.Services; + +public interface ILocalSettingsService +{ + Task ReadSettingAsync(string key); + + Task SaveSettingAsync(string key, T value); +} diff --git a/The Untamed Music Player/Contracts/Services/INavigationService.cs b/The Untamed Music Player/Contracts/Services/INavigationService.cs new file mode 100644 index 0000000..4aa96bd --- /dev/null +++ b/The Untamed Music Player/Contracts/Services/INavigationService.cs @@ -0,0 +1,23 @@ +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Navigation; + +namespace The_Untamed_Music_Player.Contracts.Services; + +public interface INavigationService +{ + event NavigatedEventHandler Navigated; + + bool CanGoBack + { + get; + } + + Frame? Frame + { + get; set; + } + + bool NavigateTo(string pageKey, object? parameter = null, bool clearNavigation = false); + + bool GoBack(); +} diff --git a/The Untamed Music Player/Contracts/Services/INavigationViewService.cs b/The Untamed Music Player/Contracts/Services/INavigationViewService.cs new file mode 100644 index 0000000..f04b3f9 --- /dev/null +++ b/The Untamed Music Player/Contracts/Services/INavigationViewService.cs @@ -0,0 +1,22 @@ +using Microsoft.UI.Xaml.Controls; + +namespace The_Untamed_Music_Player.Contracts.Services; + +public interface INavigationViewService +{ + IList? MenuItems + { + get; + } + + object? SettingsItem + { + get; + } + + void Initialize(NavigationView navigationView); + + void UnregisterEvents(); + + NavigationViewItem? GetSelectedItem(Type pageType); +} diff --git a/The Untamed Music Player/Contracts/Services/IPageService.cs b/The Untamed Music Player/Contracts/Services/IPageService.cs new file mode 100644 index 0000000..bc96ab4 --- /dev/null +++ b/The Untamed Music Player/Contracts/Services/IPageService.cs @@ -0,0 +1,6 @@ +namespace The_Untamed_Music_Player.Contracts.Services; + +public interface IPageService +{ + Type GetPageType(string key); +} diff --git a/The Untamed Music Player/Contracts/Services/IThemeSelectorService.cs b/The Untamed Music Player/Contracts/Services/IThemeSelectorService.cs new file mode 100644 index 0000000..5239952 --- /dev/null +++ b/The Untamed Music Player/Contracts/Services/IThemeSelectorService.cs @@ -0,0 +1,17 @@ +using Microsoft.UI.Xaml; + +namespace The_Untamed_Music_Player.Contracts.Services; + +public interface IThemeSelectorService +{ + ElementTheme Theme + { + get; + } + + Task InitializeAsync(); + + Task SetThemeAsync(ElementTheme theme); + + Task SetRequestedThemeAsync(); +} diff --git a/The Untamed Music Player/Contracts/ViewModels/INavigationAware.cs b/The Untamed Music Player/Contracts/ViewModels/INavigationAware.cs new file mode 100644 index 0000000..bb9b918 --- /dev/null +++ b/The Untamed Music Player/Contracts/ViewModels/INavigationAware.cs @@ -0,0 +1,8 @@ +namespace The_Untamed_Music_Player.Contracts.ViewModels; + +public interface INavigationAware +{ + void OnNavigatedTo(object parameter); + + void OnNavigatedFrom(); +} diff --git a/The Untamed Music Player/Helpers/AlternatingListViewBehavior.cs b/The Untamed Music Player/Helpers/AlternatingListViewBehavior.cs new file mode 100644 index 0000000..3cd5c36 --- /dev/null +++ b/The Untamed Music Player/Helpers/AlternatingListViewBehavior.cs @@ -0,0 +1,177 @@ +using CommunityToolkit.WinUI; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Media; +using Microsoft.Xaml.Interactivity; +using The_Untamed_Music_Player.Models; +using Windows.Foundation.Collections; + +namespace The_Untamed_Music_Player.Helpers; + +internal class AlternatingListViewBehavior : Behavior +{ + public static readonly DependencyProperty AlternateBackgroundProperty = DependencyProperty.Register( + nameof(AlternateBackground), + typeof(Brush), + typeof(AlternatingListViewBehavior), + new PropertyMetadata(default(Brush))); + + public static readonly DependencyProperty AlternateBorderThicknessProperty = DependencyProperty.Register( + nameof(AlternateBorderThickness), + typeof(Thickness), + typeof(AlternatingListViewBehavior), + new PropertyMetadata(default(Thickness))); + + public static readonly DependencyProperty AlternateBorderBrushProperty = DependencyProperty.Register( + nameof(AlternateBorderBrush), + typeof(Brush), + typeof(AlternatingListViewBehavior), + new PropertyMetadata(default(Brush?))); + + public static readonly DependencyProperty LightThemeBackgroundProperty = DependencyProperty.Register( + nameof(LightThemeBackground), + typeof(Brush), + typeof(AlternatingListViewBehavior), + new PropertyMetadata(new SolidColorBrush(Microsoft.UI.Colors.White))); + + public static readonly DependencyProperty DarkThemeBackgroundProperty = DependencyProperty.Register( + nameof(DarkThemeBackground), + typeof(Brush), + typeof(AlternatingListViewBehavior), + new PropertyMetadata(new SolidColorBrush(Microsoft.UI.Colors.Black))); + + + public Brush LightThemeBackground + { + get => (Brush)GetValue(LightThemeBackgroundProperty); + set => SetValue(LightThemeBackgroundProperty, value); + } + + public Brush DarkThemeBackground + { + get => (Brush)GetValue(DarkThemeBackgroundProperty); + set => SetValue(DarkThemeBackgroundProperty, value); + } + + public Brush? AlternateBorderBrush + { + get => (Brush?)GetValue(AlternateBorderBrushProperty); + set => SetValue(AlternateBorderBrushProperty, value); + } + + public Thickness AlternateBorderThickness + { + get => (Thickness)GetValue(AlternateBorderThicknessProperty); + set => SetValue(AlternateBorderThicknessProperty, value); + } + + public Brush? AlternateBackground + { + get => (Brush?)GetValue(AlternateBackgroundProperty); + set => SetValue(AlternateBackgroundProperty, value); + } + + protected override void OnAttached() + { + base.OnAttached(); + + AssociatedObject.ActualThemeChanged += OnActualThemeChanged; + AssociatedObject.ContainerContentChanging += OnContainerContentChanging; + if (AssociatedObject.Items != null) + { + AssociatedObject.Items.VectorChanged += ItemsOnVectorChanged; + } + } + + protected override void OnDetaching() + { + base.OnDetaching(); + + AssociatedObject.ActualThemeChanged -= OnActualThemeChanged; + AssociatedObject.ContainerContentChanging -= OnContainerContentChanging; + if (AssociatedObject.Items != null) + { + AssociatedObject.Items.VectorChanged -= ItemsOnVectorChanged; + } + } + + private void OnActualThemeChanged(FrameworkElement sender, object args) + { + if (AssociatedObject.Items == null) + { + return; + } + + var currentTheme = Data.SettingsViewModel?.ElementTheme; + AlternateBackground = currentTheme == ElementTheme.Dark ? DarkThemeBackground : LightThemeBackground; + + + for (var i = 0; i < AssociatedObject.Items.Count; i++) + { + if (AssociatedObject.ContainerFromIndex(i) is SelectorItem itemContainer) + { + UpdateAlternateLayout(itemContainer, i); + } + } + } + + private void ItemsOnVectorChanged(IObservableVector sender, IVectorChangedEventArgs args) + { + // If the index is at the end we can ignore + if (args.Index == sender.Count - 1) + { + return; + } + + // Only need to handle Inserted and Removed because we'll handle everything else in the + // OnContainerContentChanging method + if (args.CollectionChange is CollectionChange.ItemInserted or CollectionChange.ItemRemoved) + { + for (var i = (int)args.Index; i < sender.Count; i++) + { + if (AssociatedObject.ContainerFromIndex(i) is SelectorItem itemContainer) + { + UpdateAlternateLayout(itemContainer, i); + } + } + } + } + + private void OnContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) + { + if (args.Phase > 0 || args.InRecycleQueue) + { + return; + } + + UpdateAlternateLayout(args.ItemContainer, args.ItemIndex); + } + + private void UpdateAlternateLayout(SelectorItem itemContainer, int itemIndex) + { + if (itemIndex < 0 || AlternateBackground == null) + { + return; + } + + var evenBackground = AlternateBackground; + itemContainer.Background = itemIndex % 2 == 0 ? evenBackground : null; + if (itemContainer.FindDescendant() is not { } border) + { + return; + } + + if (itemIndex % 2 == 0) + { + border.Background = evenBackground; + border.BorderBrush = AlternateBorderBrush; + border.BorderThickness = AlternateBorderThickness; + } + else + { + border.Background = null; + border.BorderThickness = default; + } + } +} \ No newline at end of file diff --git a/The Untamed Music Player/Helpers/Backdrop.cs b/The Untamed Music Player/Helpers/Backdrop.cs new file mode 100644 index 0000000..d9758be --- /dev/null +++ b/The Untamed Music Player/Helpers/Backdrop.cs @@ -0,0 +1,30 @@ +using Microsoft.UI; +using Windows.UI; +using Windows.UI.Composition; + +namespace The_Untamed_Music_Player.Helpers; + +public class ColorAnimatedBackdrop : CompositionBrushBackdrop +{ + protected override CompositionBrush CreateBrush(Compositor compositor) + { + var brush = compositor.CreateColorBrush(Color.FromArgb(255, 255, 0, 0)); + var animation = compositor.CreateColorKeyFrameAnimation(); + var easing = compositor.CreateLinearEasingFunction(); + animation.InsertKeyFrame(0, Colors.Red, easing); + animation.InsertKeyFrame(.333f, Colors.Green, easing); + animation.InsertKeyFrame(.667f, Colors.Blue, easing); + animation.InsertKeyFrame(1, Colors.Red, easing); + animation.InterpolationColorSpace = CompositionColorSpace.Hsl; + animation.Duration = TimeSpan.FromSeconds(15); + animation.IterationBehavior = AnimationIterationBehavior.Forever; + brush.StartAnimation("Color", animation); + return brush; + } +} + +public class BlurredBackdrop : CompositionBrushBackdrop +{ + protected override CompositionBrush CreateBrush(Windows.UI.Composition.Compositor compositor) + => compositor.CreateHostBackdropBrush(); +} diff --git a/The Untamed Music Player/Helpers/EnumToBooleanConverter.cs b/The Untamed Music Player/Helpers/EnumToBooleanConverter.cs new file mode 100644 index 0000000..c605976 --- /dev/null +++ b/The Untamed Music Player/Helpers/EnumToBooleanConverter.cs @@ -0,0 +1,38 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Data; + +namespace The_Untamed_Music_Player.Helpers; + +public class EnumToBooleanConverter : IValueConverter +{ + public EnumToBooleanConverter() + { + } + + public object Convert(object value, Type targetType, object parameter, string language) + { + if (parameter is string enumString) + { + if (!Enum.IsDefined(typeof(ElementTheme), value)) + { + throw new ArgumentException("ExceptionEnumToBooleanConverterValueMustBeAnEnum"); + } + + var enumValue = Enum.Parse(typeof(ElementTheme), enumString); + + return enumValue.Equals(value); + } + + throw new ArgumentException("ExceptionEnumToBooleanConverterParameterMustBeAnEnumName"); + } + + public object ConvertBack(object value, Type targetType, object parameter, string language) + { + if (parameter is string enumString) + { + return Enum.Parse(typeof(ElementTheme), enumString); + } + + throw new ArgumentException("ExceptionEnumToBooleanConverterParameterMustBeAnEnumName"); + } +} diff --git a/The Untamed Music Player/Helpers/FrameExtensions.cs b/The Untamed Music Player/Helpers/FrameExtensions.cs new file mode 100644 index 0000000..ac3e27a --- /dev/null +++ b/The Untamed Music Player/Helpers/FrameExtensions.cs @@ -0,0 +1,8 @@ +using Microsoft.UI.Xaml.Controls; + +namespace The_Untamed_Music_Player.Helpers; + +public static class FrameExtensions +{ + public static object? GetPageViewModel(this Frame frame) => frame?.Content?.GetType().GetProperty("ViewModel")?.GetValue(frame.Content, null); +} diff --git a/The Untamed Music Player/Helpers/NavigationHelper.cs b/The Untamed Music Player/Helpers/NavigationHelper.cs new file mode 100644 index 0000000..55bcafa --- /dev/null +++ b/The Untamed Music Player/Helpers/NavigationHelper.cs @@ -0,0 +1,21 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; + +namespace The_Untamed_Music_Player.Helpers; + +// Helper class to set the navigation target for a NavigationViewItem. +// +// Usage in XAML: +// +// +// Usage in code: +// NavigationHelper.SetNavigateTo(navigationViewItem, typeof(MainViewModel).FullName); +public class NavigationHelper +{ + public static string GetNavigateTo(NavigationViewItem item) => (string)item.GetValue(NavigateToProperty); + + public static void SetNavigateTo(NavigationViewItem item, string value) => item.SetValue(NavigateToProperty, value); + + public static readonly DependencyProperty NavigateToProperty = + DependencyProperty.RegisterAttached("NavigateTo", typeof(string), typeof(NavigationHelper), new PropertyMetadata(null)); +} diff --git a/The Untamed Music Player/Helpers/ResourceExtensions.cs b/The Untamed Music Player/Helpers/ResourceExtensions.cs new file mode 100644 index 0000000..790c6d4 --- /dev/null +++ b/The Untamed Music Player/Helpers/ResourceExtensions.cs @@ -0,0 +1,10 @@ +using Microsoft.Windows.ApplicationModel.Resources; + +namespace The_Untamed_Music_Player.Helpers; + +public static class ResourceExtensions +{ + private static readonly ResourceLoader _resourceLoader = new(); + + public static string GetLocalized(this string resourceKey) => _resourceLoader.GetString(resourceKey); +} diff --git a/The Untamed Music Player/Helpers/RuntimeHelper.cs b/The Untamed Music Player/Helpers/RuntimeHelper.cs new file mode 100644 index 0000000..e61b182 --- /dev/null +++ b/The Untamed Music Player/Helpers/RuntimeHelper.cs @@ -0,0 +1,20 @@ +using System.Runtime.InteropServices; +using System.Text; + +namespace The_Untamed_Music_Player.Helpers; + +public class RuntimeHelper +{ + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern int GetCurrentPackageFullName(ref int packageFullNameLength, StringBuilder? packageFullName); + + public static bool IsMSIX + { + get + { + var length = 0; + + return GetCurrentPackageFullName(ref length, null) != 15700L; + } + } +} diff --git a/The Untamed Music Player/Helpers/SettingsStorageExtensions.cs b/The Untamed Music Player/Helpers/SettingsStorageExtensions.cs new file mode 100644 index 0000000..68c1af0 --- /dev/null +++ b/The Untamed Music Player/Helpers/SettingsStorageExtensions.cs @@ -0,0 +1,112 @@ +using The_Untamed_Music_Player.Core.Helpers; + +using Windows.Storage; +using Windows.Storage.Streams; + +namespace The_Untamed_Music_Player.Helpers; + +// Use these extension methods to store and retrieve local and roaming app data +// More details regarding storing and retrieving app data at https://docs.microsoft.com/windows/apps/design/app-settings/store-and-retrieve-app-data +public static class SettingsStorageExtensions +{ + private const string FileExtension = ".json"; + + public static bool IsRoamingStorageAvailable(this ApplicationData appData) + { + return appData.RoamingStorageQuota == 0; + } + + public static async Task SaveAsync(this StorageFolder folder, string name, T content) + { + var file = await folder.CreateFileAsync(GetFileName(name), CreationCollisionOption.ReplaceExisting); + var fileContent = await Json.StringifyAsync(content); + + await FileIO.WriteTextAsync(file, fileContent); + } + + public static async Task ReadAsync(this StorageFolder folder, string name) + { + if (!File.Exists(Path.Combine(folder.Path, GetFileName(name)))) + { + return default; + } + + var file = await folder.GetFileAsync($"{name}.json"); + var fileContent = await FileIO.ReadTextAsync(file); + + return await Json.ToObjectAsync(fileContent); + } + + public static async Task SaveAsync(this ApplicationDataContainer settings, string key, T value) + { + settings.SaveString(key, await Json.StringifyAsync(value)); + } + + public static void SaveString(this ApplicationDataContainer settings, string key, string value) + { + settings.Values[key] = value; + } + + public static async Task ReadAsync(this ApplicationDataContainer settings, string key) + { + object? obj; + + if (settings.Values.TryGetValue(key, out obj)) + { + return await Json.ToObjectAsync((string)obj); + } + + return default; + } + + public static async Task SaveFileAsync(this StorageFolder folder, byte[] content, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) + { + if (content == null) + { + throw new ArgumentNullException(nameof(content)); + } + + if (string.IsNullOrEmpty(fileName)) + { + throw new ArgumentException("File name is null or empty. Specify a valid file name", nameof(fileName)); + } + + var storageFile = await folder.CreateFileAsync(fileName, options); + await FileIO.WriteBytesAsync(storageFile, content); + return storageFile; + } + + public static async Task ReadFileAsync(this StorageFolder folder, string fileName) + { + var item = await folder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false); + + if ((item != null) && item.IsOfType(StorageItemTypes.File)) + { + var storageFile = await folder.GetFileAsync(fileName); + var content = await storageFile.ReadBytesAsync(); + return content; + } + + return null; + } + + public static async Task ReadBytesAsync(this StorageFile file) + { + if (file != null) + { + using IRandomAccessStream stream = await file.OpenReadAsync(); + using var reader = new DataReader(stream.GetInputStreamAt(0)); + await reader.LoadAsync((uint)stream.Size); + var bytes = new byte[stream.Size]; + reader.ReadBytes(bytes); + return bytes; + } + + return null; + } + + private static string GetFileName(string name) + { + return string.Concat(name, FileExtension); + } +} diff --git a/The Untamed Music Player/Helpers/TitleBarHelper.cs b/The Untamed Music Player/Helpers/TitleBarHelper.cs new file mode 100644 index 0000000..478825a --- /dev/null +++ b/The Untamed Music Player/Helpers/TitleBarHelper.cs @@ -0,0 +1,95 @@ +using System.Runtime.InteropServices; + +using Microsoft.UI; +using Microsoft.UI.Xaml; + +using Windows.UI; +using Windows.UI.ViewManagement; + +namespace The_Untamed_Music_Player.Helpers; + +// Helper class to workaround custom title bar bugs. +// DISCLAIMER: The resource key names and color values used below are subject to change. Do not depend on them. +// https://github.com/microsoft/TemplateStudio/issues/4516 +internal class TitleBarHelper +{ + private const int WAINACTIVE = 0x00; + private const int WAACTIVE = 0x01; + private const int WMACTIVATE = 0x0006; + + [DllImport("user32.dll")] + private static extern IntPtr GetActiveWindow(); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam); + + public static void UpdateTitleBar(ElementTheme theme) + { + if (App.MainWindow.ExtendsContentIntoTitleBar) + { + if (theme == ElementTheme.Default) + { + var uiSettings = new UISettings(); + var background = uiSettings.GetColorValue(UIColorType.Background); + + theme = background == Colors.White ? ElementTheme.Light : ElementTheme.Dark; + } + + if (theme == ElementTheme.Default) + { + theme = Application.Current.RequestedTheme == ApplicationTheme.Light ? ElementTheme.Light : ElementTheme.Dark; + } + + App.MainWindow.AppWindow.TitleBar.ButtonForegroundColor = theme switch + { + ElementTheme.Dark => Colors.White, + ElementTheme.Light => Colors.Black, + _ => Colors.Transparent + }; + + App.MainWindow.AppWindow.TitleBar.ButtonHoverForegroundColor = theme switch + { + ElementTheme.Dark => Colors.White, + ElementTheme.Light => Colors.Black, + _ => Colors.Transparent + }; + + App.MainWindow.AppWindow.TitleBar.ButtonHoverBackgroundColor = theme switch + { + ElementTheme.Dark => Color.FromArgb(0x33, 0xFF, 0xFF, 0xFF), + ElementTheme.Light => Color.FromArgb(0x33, 0x00, 0x00, 0x00), + _ => Colors.Transparent + }; + + App.MainWindow.AppWindow.TitleBar.ButtonPressedBackgroundColor = theme switch + { + ElementTheme.Dark => Color.FromArgb(0x66, 0xFF, 0xFF, 0xFF), + ElementTheme.Light => Color.FromArgb(0x66, 0x00, 0x00, 0x00), + _ => Colors.Transparent + }; + + App.MainWindow.AppWindow.TitleBar.BackgroundColor = Colors.Transparent; + + var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow); + if (hwnd == GetActiveWindow()) + { + SendMessage(hwnd, WMACTIVATE, WAINACTIVE, IntPtr.Zero); + SendMessage(hwnd, WMACTIVATE, WAACTIVE, IntPtr.Zero); + } + else + { + SendMessage(hwnd, WMACTIVATE, WAACTIVE, IntPtr.Zero); + SendMessage(hwnd, WMACTIVATE, WAINACTIVE, IntPtr.Zero); + } + } + } + + public static void ApplySystemThemeToCaptionButtons() + { + var frame = App.AppTitlebar as FrameworkElement; + if (frame != null) + { + UpdateTitleBar(frame.ActualTheme); + } + } +} diff --git a/The Untamed Music Player/Helpers/WindowsSystemDispatcherQueueHelper.cs b/The Untamed Music Player/Helpers/WindowsSystemDispatcherQueueHelper.cs new file mode 100644 index 0000000..272d418 --- /dev/null +++ b/The Untamed Music Player/Helpers/WindowsSystemDispatcherQueueHelper.cs @@ -0,0 +1,36 @@ +using System.Runtime.InteropServices; + +namespace The_Untamed_Music_Player.Helpers; +public class WindowsSystemDispatcherQueueHelper +{ + [StructLayout(LayoutKind.Sequential)] + private struct DispatcherQueueOptions + { + internal int dwSize; + internal int threadType; + internal int apartmentType; + } + + [DllImport("CoreMessaging.dll")] + private static extern int CreateDispatcherQueueController([In] DispatcherQueueOptions options, [In, Out, MarshalAs(UnmanagedType.IUnknown)] ref object dispatcherQueueController); + + private object m_dispatcherQueueController = null; + public void EnsureWindowsSystemDispatcherQueueController() + { + if (Windows.System.DispatcherQueue.GetForCurrentThread() != null) + { + // one already exists, so we'll just use it. + return; + } + + if (m_dispatcherQueueController == null) + { + DispatcherQueueOptions options; + options.dwSize = Marshal.SizeOf(); + options.threadType = 2; // DQTYPE_THREAD_CURRENT + options.apartmentType = 2; // DQTAT_COM_STA + + _ = CreateDispatcherQueueController(options, ref m_dispatcherQueueController); + } + } +} diff --git a/The Untamed Music Player/MainWindow.xaml b/The Untamed Music Player/MainWindow.xaml new file mode 100644 index 0000000..ca09576 --- /dev/null +++ b/The Untamed Music Player/MainWindow.xaml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + diff --git a/The Untamed Music Player/MainWindow.xaml.cs b/The Untamed Music Player/MainWindow.xaml.cs new file mode 100644 index 0000000..2880ef4 --- /dev/null +++ b/The Untamed Music Player/MainWindow.xaml.cs @@ -0,0 +1,361 @@ +using Microsoft.UI; +using Microsoft.UI.Composition.SystemBackdrops; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Helpers; +using The_Untamed_Music_Player.Models; +using The_Untamed_Music_Player.Views; +using Windows.UI.ViewManagement; +using WinRT; +namespace The_Untamed_Music_Player; + +public sealed partial class MainWindow : WindowEx +{ + private readonly Microsoft.UI.Dispatching.DispatcherQueue dispatcherQueue; + private readonly UISettings settings; + private readonly ILocalSettingsService _localSettingsService; + private WindowsSystemDispatcherQueueHelper? m_wsdqHelper; + private DesktopAcrylicController? m_acrylicController; + private SystemBackdropConfiguration? m_configurationSource; + + private string _selectedMaterial = "Desktop Acrylic"; + /// + /// 选定的窗口材质 + /// + public string SelectedMaterial + { + get => _selectedMaterial; + set => _selectedMaterial = value; + } + + + public MainWindow(ILocalSettingsService localSettingsService) + { + InitializeComponent(); + _localSettingsService = localSettingsService; + InitializeAsync(); + + AppWindow.SetIcon(Path.Combine(AppContext.BaseDirectory, "Assets/WindowIcon.ico")); + Title = "AppDisplayName".GetLocalized(); + ExtendsContentIntoTitleBar = true; + + dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); + settings = new UISettings(); + settings.ColorValuesChanged += Settings_ColorValuesChanged; + + Data.MainWindow = this; + + ShellFrame.Navigate(typeof(ShellPage)); + RootPlayBarFrame.Navigate(typeof(RootPlayBarView)); + + Activated += Window_Activated; + Closed += Window_Closed; + } + + /// + /// 初始化窗口材质 + /// + public async void InitializeAsync() + { + await LoadSelectedMaterialAsync(); + ChangeMaterial(SelectedMaterial); + } + + /// + /// 获取导航页(ShellFrame) + /// + /// + public Frame GetShellFrame() + { + return ShellFrame; + } + + /// + /// 处理在应用程序打开时主题改变时正确更新标题按钮颜色 + /// + /// + /// + private void Settings_ColorValuesChanged(UISettings sender, object args) + { + // 这个调用来自线程外,因此我们需要将其调度到当前应用程序的线程 + dispatcherQueue.TryEnqueue(() => + { + TitleBarHelper.ApplySystemThemeToCaptionButtons(); + }); + } + + /// + /// 尝试设置系统背景为无 + /// + /// + public bool TrySetNoneBackdrop() + { + try + { + SystemBackdrop = null; + return true; + } + catch + { + return false; + } + } + + /// + /// 尝试设置Mica背景 + /// + /// + /// + public bool TrySetMicaBackdrop(bool useMicaAlt = false) + { + try + { + if (MicaController.IsSupported()) + { + var micaBackdrop = new Microsoft.UI.Xaml.Media.MicaBackdrop + { + Kind = useMicaAlt ? MicaKind.BaseAlt : MicaKind.Base + }; + SystemBackdrop = micaBackdrop; + + return true; // Succeeded. + } + return false; // Mica is not supported on this system. + } + catch + { + return false; + } + } + + /// + /// 尝试设置桌面亚克力背景 + /// + /// + public bool TrySetDesktopAcrylicBackdrop() + { + try + { + if (DesktopAcrylicController.IsSupported()) + { + var DesktopAcrylicBackdrop = new Microsoft.UI.Xaml.Media.DesktopAcrylicBackdrop(); + SystemBackdrop = DesktopAcrylicBackdrop; + + return true; // 成功 + } + return false; // 桌面亚克力不受此系统支持 + } + catch + { + return false; + } + } + + /// + /// 尝试设置亚克力背景 + /// + /// + /// + public bool TrySetAcrylicBackdrop(bool useAcrylicThin = false) + { + try + { + if (DesktopAcrylicController.IsSupported()) + { + m_wsdqHelper = new WindowsSystemDispatcherQueueHelper(); + m_wsdqHelper.EnsureWindowsSystemDispatcherQueueController(); + + // 挂钩策略对象到窗口 + m_configurationSource = new SystemBackdropConfiguration(); + ((FrameworkElement)Content).ActualThemeChanged += Window_ThemeChanged; + + // 初始化配置状态 + m_configurationSource.IsInputActive = true; + SetConfigurationSourceTheme(); + + m_acrylicController = new DesktopAcrylicController + { + Kind = useAcrylicThin ? DesktopAcrylicKind.Thin : DesktopAcrylicKind.Base + }; + + // 启用系统背景 + // 注意:确保有“using WinRT;”以支持Window.As<...>()调用。 + m_acrylicController.AddSystemBackdropTarget(this.As()); + m_acrylicController.SetSystemBackdropConfiguration(m_configurationSource); + return true; // 成功 + } + + return false; // 亚克力不受此系统支持 + } + catch + { + return false; + } + } + + /// + /// 尝试设置模糊背景 + /// + /// + public bool TrySetBlurBackdrop() + { + try + { + var blurBackdrop = new BlurredBackdrop(); + SystemBackdrop = blurBackdrop; + return true; + } + catch + { + return false; + } + } + + + /// + /// 尝试设置透明背景 + /// + /// + /// + public bool TrySetTransparentBackdrop(Windows.UI.Color? tintColor = null) + { + try + { + var color = tintColor ?? Colors.Transparent; + var transparentBackdrop = new TransparentTintBackdrop(color); + SystemBackdrop = transparentBackdrop; + return true; + } + catch + { + return false; + } + } + + /// + /// 尝试设置动画背景 + /// + /// + public bool TrySetAnimatedBackdrop() + { + try + { + var animatedBackdrop = new ColorAnimatedBackdrop(); + SystemBackdrop = animatedBackdrop; + return true; + } + catch + { + return false; + } + } + + private void Window_Activated(object sender, WindowActivatedEventArgs args) + { + if (m_configurationSource != null) + { + m_configurationSource.IsInputActive = args.WindowActivationState != WindowActivationState.Deactivated; + } + } + + private void Window_Closed(object sender, WindowEventArgs args) + { + // 确保任何Mica/Acrylic控制器都被释放,以便它不会尝试使用此关闭的窗口。 + if (m_acrylicController != null) + { + m_acrylicController.Dispose(); + m_acrylicController = null; + } + Activated -= Window_Activated; + m_configurationSource = null; + + Data.MusicPlayer.SaveCurrentStateAsync(); + } + + public void ReleaseCurrentBackdropResources() + { + // 释放m_acrylicController的资源,并将其设置为null + if (m_acrylicController != null) + { + m_acrylicController.Dispose(); + m_acrylicController = null; + } + } + + private void Window_ThemeChanged(FrameworkElement sender, object args) + { + if (m_configurationSource != null) + { + SetConfigurationSourceTheme(); + } + } + + private void SetConfigurationSourceTheme() + { + if (m_configurationSource != null) + { + switch (((FrameworkElement)Content).ActualTheme) + { + case ElementTheme.Dark: m_configurationSource.Theme = SystemBackdropTheme.Dark; break; + case ElementTheme.Light: m_configurationSource.Theme = SystemBackdropTheme.Light; break; + case ElementTheme.Default: m_configurationSource.Theme = SystemBackdropTheme.Default; break; + } + } + } + + /// + /// 启动应用时更改选定的材质 + /// + /// + public void ChangeMaterial(string material) + { + try + { + switch (material) + { + case "None": + TrySetNoneBackdrop(); + break; + case "Mica": + TrySetMicaBackdrop(false); + break; + case "Mica Alt": + TrySetMicaBackdrop(true); + break; + case "Desktop Acrylic": + TrySetDesktopAcrylicBackdrop(); + break; + case "Acrylic Base": + TrySetAcrylicBackdrop(false); + break; + case "Acrylic Thin": + TrySetAcrylicBackdrop(true); + break; + case "Blur": + TrySetBlurBackdrop(); + break; + case "Transparent": + TrySetTransparentBackdrop(); + break; + case "Animated": + TrySetAnimatedBackdrop(); + break; + } + } + catch { } + } + + /// + /// 从设置存储读取选定的材质 + /// + /// + public async Task LoadSelectedMaterialAsync() + { + var material = await _localSettingsService.ReadSettingAsync("SelectedMaterial"); + if (!string.IsNullOrEmpty(material)) + { + SelectedMaterial = material; + } + } +} diff --git a/The Untamed Music Player/Models/AlbumInfo.cs b/The Untamed Music Player/Models/AlbumInfo.cs new file mode 100644 index 0000000..b408160 --- /dev/null +++ b/The Untamed Music Player/Models/AlbumInfo.cs @@ -0,0 +1,117 @@ +using System.ComponentModel; +using Microsoft.UI.Xaml.Media.Imaging; + +namespace The_Untamed_Music_Player.Models; +public class AlbumInfo : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + protected void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + //专辑名 + private string? _name; + public string? Name + { + get => _name; + set + { + _name = value; + OnPropertyChanged(nameof(Name)); + } + } + + //专辑封面路径 + private BitmapImage? _cover; + public BitmapImage? Cover + { + get => _cover; + set + { + _cover = value; + OnPropertyChanged(nameof(Cover)); + } + } + + private string? _artist; + public string? Artist + { + get => _artist; + set + { + _artist = value; + OnPropertyChanged(nameof(Artist)); + } + } + + //专辑包含的歌曲数量 + private int _totalNum; + public int TotalNum + { + get => _totalNum; + set + { + _totalNum = value; + OnPropertyChanged(nameof(TotalNum)); + } + } + + private TimeSpan _totalDuration; + public TimeSpan TotalDuration + { + get => _totalDuration; + set + { + _totalDuration = value; + OnPropertyChanged(nameof(TotalDuration)); + } + } + + //专辑发布年份 + private string _year = ""; + public string Year + { + get => _year; + set + { + _year = value; + OnPropertyChanged(nameof(Year)); + } + } + + public AlbumInfo() + { + } + public AlbumInfo(BriefMusicInfo briefmusicInfo) + { + Name = briefmusicInfo.Album; + Year = briefmusicInfo.YearStr; + Cover = briefmusicInfo.Cover; + Artist = briefmusicInfo.ArtistsStr; + TotalDuration = briefmusicInfo.Duration; + TotalNum = 1; + } + + public void Update(BriefMusicInfo briefmusicInfo) + { + TotalNum++; + TotalDuration += briefmusicInfo.Duration; + } + + public string? GetCountAndDuration() + { + if (TotalDuration.Hours > 0) + { + return string.IsNullOrEmpty(Year) + ? $"{TotalNum} 首歌曲·{TotalDuration:hh\\:mm\\:ss} 歌曲长度" + : $"{Year}·{TotalNum} 首歌曲·{TotalDuration:hh\\:mm\\:ss} 歌曲长度"; + } + else + { + return string.IsNullOrEmpty(Year) + ? $"{TotalNum} 首歌曲·{TotalDuration:mm\\:ss} 歌曲长度" + : $"{Year}·{TotalNum} 首歌曲·{TotalDuration:mm\\:ss} 歌曲长度"; + } + } +} diff --git a/The Untamed Music Player/Models/ArtistInfo.cs b/The Untamed Music Player/Models/ArtistInfo.cs new file mode 100644 index 0000000..30c5c66 --- /dev/null +++ b/The Untamed Music Player/Models/ArtistInfo.cs @@ -0,0 +1,142 @@ +using System.ComponentModel; +using Microsoft.UI.Xaml.Media.Imaging; + +namespace The_Untamed_Music_Player.Models; +public class ArtistInfo : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + protected void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + //艺术家名 + private string? _name; + public string? Name + { + get => _name; + set + { + _name = value; + OnPropertyChanged(nameof(Name)); + } + } + + private Dictionary? _albums = []; + public Dictionary? Albums + { + get => _albums; + set + { + _albums = value; + OnPropertyChanged(nameof(Albums)); + } + } + + public string? _genre; + public string? Genre + { + get => _genre; + set + { + _genre = value; + OnPropertyChanged(nameof(Genre)); + } + } + + //封面路径(当作头像,默认为检索到的第一张) + private BitmapImage? _cover; + public BitmapImage? Cover + { + get => _cover; + set + { + _cover = value; + OnPropertyChanged(nameof(Cover)); + } + } + + private TimeSpan _totalDuration; + public TimeSpan TotalDuration + { + get => _totalDuration; + set + { + _totalDuration = value; + OnPropertyChanged(nameof(TotalDuration)); + } + } + + //歌曲数量 + private int _totalMusicNum; + public int TotalMusicNum + { + get => _totalMusicNum; + set + { + _totalMusicNum = value; + OnPropertyChanged(nameof(TotalMusicNum)); + } + } + + private int _totalAlbumNum; + public int TotalAlbumNum + { + get => _totalAlbumNum; + set + { + _totalAlbumNum = value; + OnPropertyChanged(nameof(TotalAlbumNum)); + } + } + + public ArtistInfo(BriefMusicInfo briefMusicInfo, string name) + { + Name = name; + Cover = briefMusicInfo.Cover; + TotalDuration = briefMusicInfo.Duration; + Genre = briefMusicInfo.GenreStr; + TotalMusicNum = 1; + TotalAlbumNum = 1; + if (briefMusicInfo.Album != null && Albums != null) + { + Albums[briefMusicInfo.Album] = new AlbumInfo(briefMusicInfo); + } + } + + public void Update(BriefMusicInfo briefMusicInfo) + { + TotalDuration += briefMusicInfo.Duration; + TotalMusicNum++; + var album = briefMusicInfo.Album; + if (album != null && Albums != null) + { + if (!Albums.TryGetValue(album, out var value)) + { + Albums[album] = new AlbumInfo(briefMusicInfo); + TotalAlbumNum++; + } + else + { + value.Update(briefMusicInfo); + } + } + } + + public string? GetCount() + { + return $"{TotalAlbumNum} 个相册·{TotalMusicNum} 首歌曲·"; + } + + public string? GetDuration() + { + if (TotalDuration.Hours > 0) + { + return $"{TotalDuration.Hours} 小时 {TotalDuration.Minutes} 分钟 {TotalDuration.Seconds} 秒"; + } + else + { + return $"{TotalDuration.Minutes} 分钟 {TotalDuration.Seconds} 秒"; + } + } +} diff --git a/The Untamed Music Player/Models/Data.cs b/The Untamed Music Player/Models/Data.cs new file mode 100644 index 0000000..afd86de --- /dev/null +++ b/The Untamed Music Player/Models/Data.cs @@ -0,0 +1,21 @@ +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.ViewModels; +using The_Untamed_Music_Player.Views; + +namespace The_Untamed_Music_Player.Models; + +public static class Data +{ + public static readonly string[] SupportedAudioTypes = [".flac", ".wav", ".m4a", ".aac", ".mp3", ".wma", ".ogg", ".oga", ".opus"]; + + public static MusicPlayer MusicPlayer { get; set; } = new(App.GetService()); + public static MusicLibrary MusicLibrary { get; set; } = new(); + public static string? SelectedAlbum; + public static string? SelectedArtist; + public static bool IsDetail = false; + public static MainWindow? MainWindow; + public static ShellPage? ShellPage; + public static SettingsViewModel? SettingsViewModel; + public static RootPlayBarViewModel? RootPlayBarViewModel; + public static 歌曲ViewModel? 歌曲ViewModel; +} diff --git a/The Untamed Music Player/Models/LocalSettingsOptions.cs b/The Untamed Music Player/Models/LocalSettingsOptions.cs new file mode 100644 index 0000000..500f15b --- /dev/null +++ b/The Untamed Music Player/Models/LocalSettingsOptions.cs @@ -0,0 +1,14 @@ +namespace The_Untamed_Music_Player.Models; + +public class LocalSettingsOptions +{ + public string? ApplicationDataFolder + { + get; set; + } + + public string? LocalSettingsFile + { + get; set; + } +} diff --git a/The Untamed Music Player/Models/LyricSlice.cs b/The Untamed Music Player/Models/LyricSlice.cs new file mode 100644 index 0000000..b8c8376 --- /dev/null +++ b/The Untamed Music Player/Models/LyricSlice.cs @@ -0,0 +1,126 @@ +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Text.RegularExpressions; + +namespace The_Untamed_Music_Player.Models; +public partial class LyricSlice : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + protected void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private string _content = ""; + public string Content + { + get => _content; + set + { + _content = value; + OnPropertyChanged(nameof(Content)); + } + } + + private double _time; + public double Time + { + get => _time; + set + { + _time = value; + OnPropertyChanged(nameof(Time)); + } + } + + public LyricSlice(double time, string content) + { + Time = time; + Content = content; + } + + [GeneratedRegex(@".*\](.*)")] + private static partial Regex RegexWord(); + + [GeneratedRegex(@"\[([0-9.:]*)\]", RegexOptions.Compiled)] + private static partial Regex RegexTime(); + + public static ObservableCollection GetLyricSlices(string lyric) + { + var lyricSlices = new List(); + + if (string.IsNullOrEmpty(lyric)) + { + return []; + } + var lines = lyric.Split('\n'); + double? lastTime = null;//上一行有歌词的行的时间 + double emptyStartTime = 0;//空白行开始时间 + var inEmptyBlock = false; + var emptyLines = new List(); + foreach (var line in lines) + { + if (line != null) + { + if (line.StartsWith("[ti:") || line.StartsWith("[ar:") || line.StartsWith("[al:") || line.StartsWith("[by:") || line.StartsWith("[offset:"))//歌曲名、艺人名、专辑名、歌词制作人、歌词时间补偿值 + { + continue; + } + + try + { + var regexword = RegexWord();//获取歌词文本的正则表达式 + var regextime = RegexTime();//获取时间戳的正则表达式 + var WORD = regexword.Match(line).Groups[1].Value;//获取歌词文本 + var TIME = regextime.Matches(line);//获取时间戳 + + if (string.IsNullOrWhiteSpace(WORD))//歌词文本为空 + { + if (!inEmptyBlock) + { + emptyStartTime = TIME.Count > 0 ? TimeSpan.Parse("00:" + TIME[0].Groups[1].Value).TotalMilliseconds : lastTime ?? 0;//将时间戳转换为毫秒(只保留第一组, 防止一行歌词里面有多个时间) + if (emptyStartTime == lastTime) + { + emptyStartTime += 1; // 如果空白行和上一行有歌词的行时间相同,空白行的时间加1毫秒 + } + inEmptyBlock = true; + } + } + else + { + if (inEmptyBlock) + { + var emptyEndTime = TIME.Count > 0 ? TimeSpan.Parse("00:" + TIME[0].Groups[1].Value).TotalMilliseconds : lastTime ?? 0; + if (emptyEndTime - emptyStartTime > 5000) + { + lyricSlices.Add(new LyricSlice(emptyStartTime, "•••")); + } + inEmptyBlock = false; + } + + foreach (Match item in TIME) + { + var time = TimeSpan.Parse("00:" + item.Groups[1].Value).TotalMilliseconds; + lyricSlices.Add(new LyricSlice(time, WORD)); + lastTime = time; + } + } + } + catch + { + continue; + } + } + } + if (inEmptyBlock && emptyLines.Count > 0) + { + var emptyEndTime = emptyLines.Last().Time; + if (emptyEndTime - emptyStartTime > 5000) + { + lyricSlices.Add(new LyricSlice(emptyStartTime, "•••")); + } + } + + return new ObservableCollection(lyricSlices.OrderBy(t => t.Time));//将 lyricSlices 列表按时间戳排序。 + } +} diff --git a/The Untamed Music Player/Models/MusicInfo.cs b/The Untamed Music Player/Models/MusicInfo.cs new file mode 100644 index 0000000..7728dcf --- /dev/null +++ b/The Untamed Music Player/Models/MusicInfo.cs @@ -0,0 +1,505 @@ +using System.ComponentModel; +using System.Text; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; + +namespace The_Untamed_Music_Player.Models; + +public class BriefMusicInfo : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + protected void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private string _path = ""; + /// + /// 文件位置 + /// + public string Path + { + get => _path; + set => _path = value; + } + + private string _itemType = ""; + /// + /// 项目类型 + /// + public string ItemType + { + get => _itemType; + set => _itemType = value; + } + + private string _album = ""; + /// + /// 专辑名, 为空时返回"未知专辑" + /// + public string Album + { + get => _album; + set => _album = value; + } + + private string _title = ""; + /// + /// 歌曲名 + /// + public string Title + { + get => _title; + set => _title = value; + } + + private string[] _artists = []; + /// + /// 参与创作的艺术家数组 + /// + public string[] Artists + { + get => _artists; + set + { + if (value?.Length > 0) + { + var tempArtists = Array.Empty(); + foreach (var i in value) + { + if (i.Contains('、')) + { + tempArtists = [.. tempArtists, .. i.Split('、')];//将艺术家名字分割开并存到数组中 + } + else if (i.Contains(',')) + { + tempArtists = [.. tempArtists, .. i.Split(',')]; + } + else if (i.Contains(',')) + { + tempArtists = [.. tempArtists, .. i.Split(',')]; + } + else if (i.Contains('|')) + { + tempArtists = [.. tempArtists, .. i.Split('|')]; + } + else if (i.Contains('/')) + { + tempArtists = [.. tempArtists, .. i.Split('/')]; + } + else + { + tempArtists = [.. tempArtists, .. new[] { i }]; + } + } + _artists = tempArtists.Distinct().ToArray(); + } + else + { + _artists = []; + } + ArtistsStr = GetArtists(); + } + } + + private string _artistsStr = ""; + /// + /// 参与创作的艺术家名, 为空时返回"未知艺术家" + /// + public string ArtistsStr + { + get => _artistsStr; + set => _artistsStr = value; + } + + /// + /// 获取参与创作的艺术家名 + /// + /// + public string GetArtists() + { + if (_artists == null || _artists.Length == 0) + { + return "未知艺术家"; + } + var sb = new StringBuilder(); + foreach (var artist in _artists) + { + sb.Append(artist); + sb.Append(", "); + } + if (sb.Length > 0) + { + sb.Length -= 2; // 去掉最后一个逗号 + } + return sb.ToString(); + } + + private TimeSpan _duration; + /// + /// 时长 + /// + public TimeSpan Duration + { + get => _duration; + set + { + _duration = value; + DurationStr = GetDurationStr(); + } + } + + private string _durationStr = ""; + /// + /// 时长字符串 + /// + public string DurationStr + { + get => _durationStr; + set => _durationStr = value; + } + + /// + /// 获取时长字符串 + /// + /// + public string GetDurationStr() + { + if (Duration.Hours > 0) + { + return $"{Duration:hh\\:mm\\:ss}"; + } + else + { + return $"{Duration:mm\\:ss}"; + } + } + + private uint _year; + /// + /// 发行年份 + /// + public uint Year + { + get => _year; + set + { + _year = value; + YearStr = value.ToString(); + } + } + + private string _yearStr = ""; + /// + /// 发行年份字符串 + /// + public string YearStr + { + get => _yearStr; + set + { + if (value == "0") + { + _yearStr = ""; + } + else + { + _yearStr = value; + } + } + } + + private BitmapImage? _cover; + /// + /// 封面(可能为空) + /// + public BitmapImage? Cover + { + get => _cover; + set => _cover = value; + } + + private string[] _genre = []; + /// + /// 流派数组 + /// + public string[] Genre + { + get => _genre; + set + { + _genre = value; + GenreStr = GetGenre(); + } + } + + private string _genreStr = ""; + /// + /// 流派字符串, 为空时返回"未知流派" + /// + public string GenreStr + { + get => _genreStr; + set + { + _genreStr = value; + OnPropertyChanged(nameof(GenreStr)); + } + } + + /// + /// 获取流派字符串 + /// + /// + public string GetGenre() + { + if (_genre == null || _genre.Length == 0) + { + return "未知流派"; + } + var sb = new StringBuilder(); + foreach (var genre in _genre) + { + sb.Append(genre); + sb.Append(", "); + } + if (sb.Length > 0) + { + sb.Length -= 2; + } + return sb.ToString(); + } + + private DateTimeOffset _modifiedDate; + /// + /// 修改日期 + /// + public DateTimeOffset ModifiedDate + { + get => _modifiedDate; + set => _modifiedDate = value; + } + + /// + /// 获取文本前景色 + /// + /// + /// + /// 如果是当前播放歌曲, 返回主题色, 如果不是, 根据当前主题返回黑色或白色 + public SolidColorBrush GetTextForeground(DetailedMusicInfo currentMusic, ElementTheme elementTheme) + { + if (Path == currentMusic.Path) + { + return (SolidColorBrush)App.Current.Resources["AccentTextFillColorTertiaryBrush"]; + } + + if (elementTheme == ElementTheme.Dark) + { + return new SolidColorBrush(Microsoft.UI.Colors.White); + } + else + { + return new SolidColorBrush(Microsoft.UI.Colors.Black); + } + } + + public BriefMusicInfo() + { + } + + public BriefMusicInfo(string path) + { + try + { + var musicFile = TagLib.File.Create(path); + Path = path; + ModifiedDate = new FileInfo(path).LastWriteTime; + ItemType = System.IO.Path.GetExtension(path).ToLower(); + Album = musicFile.Tag.Album ?? "未知专辑"; + Title = string.IsNullOrEmpty(musicFile.Tag.Title) ? System.IO.Path.GetFileNameWithoutExtension(path) : musicFile.Tag.Title; + Artists = musicFile.Tag.AlbumArtists.Concat(musicFile.Tag.Performers).ToArray().Length != 0 ? [.. musicFile.Tag.AlbumArtists, .. musicFile.Tag.Performers] : ["未知艺术家"]; + Year = musicFile.Tag.Year; + Genre = musicFile.Tag.Genres.Length != 0 ? [.. musicFile.Tag.Genres] : ["未知流派"]; + if (musicFile.Tag.Pictures != null && musicFile.Tag.Pictures.Length != 0) + { + var coverBuffer = musicFile.Tag.Pictures[0].Data.Data; + using var stream = new MemoryStream(coverBuffer); + stream.Seek(0, SeekOrigin.Begin); + Cover = new BitmapImage + { + DecodePixelWidth = 600, + DecodePixelHeight = 600 + }; + Cover.SetSource(stream.AsRandomAccessStream()); + } + Duration = musicFile.Properties.Duration; + } + catch (Exception) + { + Path = path; + ModifiedDate = new FileInfo(path).LastWriteTime; + ItemType = System.IO.Path.GetExtension(path).ToLower(); + Album = "未知专辑"; + Title = System.IO.Path.GetFileNameWithoutExtension(path); + Artists = ["未知艺术家"]; + Genre = ["未知流派"]; + Duration = TimeSpan.Zero; + } + } +} + +public class DetailedMusicInfo : BriefMusicInfo +{ + private string[] _albumArtists = []; + /// + /// 专辑艺术家数组 + /// + public string[] AlbumArtists + { + get => _albumArtists; + set + { + if (value?.Length > 0) + { + var tempArtists = Array.Empty(); + foreach (var i in value) + { + if (i.Contains('、')) + { + tempArtists = [.. tempArtists, .. i.Split('、')]; + } + else if (i.Contains(',')) + { + tempArtists = [.. tempArtists, .. i.Split(',')]; + } + else if (i.Contains(',')) + { + tempArtists = [.. tempArtists, .. i.Split(',')]; + } + else if (i.Contains('|')) + { + tempArtists = [.. tempArtists, .. i.Split('|')]; + } + else if (i.Contains('/')) + { + tempArtists = [.. tempArtists, .. i.Split('/')]; + } + else + { + tempArtists = [.. tempArtists, .. new[] { i }]; + } + } + _albumArtists = tempArtists.Distinct().ToArray(); + } + else + { + _albumArtists = []; + } + } + } + + /// + /// 获取专辑艺术家字符串 + /// + /// + public string GetAlbumArtists() + { + if (_albumArtists == null || _albumArtists.Length == 0) + { + return ""; + } + var sb = new StringBuilder(); + foreach (var artist in _albumArtists) + { + sb.Append(artist); + sb.Append(", "); + } + if (sb.Length > 0) + { + sb.Length -= 2; // 去掉最后一个逗号 + } + return sb.ToString(); + } + + public string _artistAndAlbumStr = ""; + /// + /// 艺术家和专辑名字符串 + /// + public string ArtistAndAlbumStr + { + get => _artistAndAlbumStr; + set => _artistAndAlbumStr = value; + } + + /// + /// 获取艺术家和专辑名字符串 + /// + /// + public string GetArtistAndAlbumStr() + { + var artistsStr = GetArtists(); + if (string.IsNullOrEmpty(artistsStr)) + { + return Album ?? ""; + } + if (string.IsNullOrEmpty(Album)) + { + return artistsStr; + } + return $"{artistsStr} • {Album}"; + } + + private int _bitRate; + /// + /// 比特率 + /// + public int BitRate + { + get => _bitRate; + set => _bitRate = value; + } + + private int _track; + /// + /// 曲目 + /// + public int Track + { + get => _track; + set => _track = value; + } + + private string _lyric = ""; + /// + /// 歌词 + /// + public string Lyric + { + get => _lyric; + set => _lyric = value; + } + + public DetailedMusicInfo() + { + } + + public DetailedMusicInfo(string path) : base(path) + { + try + { + var musicFile = TagLib.File.Create(path); + AlbumArtists = [.. musicFile.Tag.AlbumArtists]; + ArtistAndAlbumStr = GetArtistAndAlbumStr(); + Track = (int)musicFile.Tag.Track; + Lyric = musicFile.Tag.Lyrics ?? ""; + BitRate = musicFile.Properties.AudioBitrate; + } + catch (Exception) + { + AlbumArtists = []; + Track = 0; + BitRate = 0; + } + } +} \ No newline at end of file diff --git a/The Untamed Music Player/Models/MusicLibrary.cs b/The Untamed Music Player/Models/MusicLibrary.cs new file mode 100644 index 0000000..3156455 --- /dev/null +++ b/The Untamed Music Player/Models/MusicLibrary.cs @@ -0,0 +1,347 @@ +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using The_Untamed_Music_Player.Helpers; +using The_Untamed_Music_Player.ViewModels; +using Windows.Storage; + +namespace The_Untamed_Music_Player.Models; +public class MusicLibrary : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + protected void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private ObservableCollection _folders = []; + public ObservableCollection Folders + { + get => _folders; + set + { + _folders = value; + OnPropertyChanged(nameof(SettingsViewModel.EmptyFolderMessageVisibility)); + } + } + + private ObservableCollection _musics = []; + public ObservableCollection Musics + { + get => _musics; + set + { + _musics = value; + OnPropertyChanged(nameof(HasMusics)); + } + } + + public bool HasMusics => Musics.Any(); + + private Dictionary _albums = []; + public Dictionary Albums + { + get => _albums; + set + { + _albums = value; + OnPropertyChanged(nameof(Albums)); + } + } + + private Dictionary _artists = []; + public Dictionary Artists + { + get => _artists; + set + { + _artists = value; + OnPropertyChanged(nameof(Artists)); + } + } + + public MusicLibrary() + { + LoadFoldersAsync(); + } + + public async Task LoadLibrary() + { + if (Folders != null && Folders.Any()) + { + foreach (var folder in Folders) + { + await LoadMusic(folder); + } + } + SortMusicsByModifiedTimeDecending(); + OnPropertyChanged(nameof(Artists)); + OnPropertyChanged(nameof(Albums)); + OnPropertyChanged(nameof(HasMusics)); + } + + public async Task LoadLibraryAgain() + { + Musics?.Clear(); + Artists?.Clear(); + Albums?.Clear(); + if (Folders != null && Folders.Any()) + { + foreach (var folder in Folders) + { + await LoadMusic(folder); + } + } + SortMusicsByModifiedTimeDecending(); + OnPropertyChanged(nameof(Artists)); + OnPropertyChanged(nameof(Albums)); + OnPropertyChanged(nameof(HasMusics)); + } + + public async void LoadFoldersAsync() + { + var folderPaths = await ApplicationData.Current.LocalFolder.ReadAsync>("MusicFolders");// ApplicationData.Current.LocalFolder:获取应用程序的本地存储文件夹。ReadAsync>("MusicFolders"):调用 SettingsStorageExtensions 类中的扩展方法 ReadAsync,从名为 "MusicFolders" 的文件中读取数据,并将其反序列化为 List 类型。 + if (folderPaths != null) + { + foreach (var path in folderPaths) + { + var folder = await StorageFolder.GetFolderFromPathAsync(path); + Folders?.Add(folder); + } + OnPropertyChanged(nameof(SettingsViewModel.EmptyFolderMessageVisibility)); + await Data.MusicLibrary.LoadLibrary(); + } + } + + private async Task LoadMusic(StorageFolder folder) + { + try + { + var allFiles = await folder.GetFilesAsync(); + foreach (var file in allFiles) + { + if (Data.SupportedAudioTypes.Contains(file.FileType.ToLower()) && Musics != null) + { + // 检查 Musics 集合中是否已经存在相同路径的音乐 + if (!Musics.Any(m => m.Path == file.Path)) + { + var briefMusicInfo = new BriefMusicInfo(file.Path); + Musics?.Add(briefMusicInfo); + UpdateAlbumInfo(briefMusicInfo); + UpdateArtistInfo(briefMusicInfo); + } + } + } + var subFolders = await folder.GetFoldersAsync(); + foreach (var subFolder in subFolders) + { + await LoadMusic(subFolder); + } + } + catch (Exception e) + { + Debug.WriteLine(e); + } + } + + private void UpdateAlbumInfo(BriefMusicInfo briefMusicInfo) + { + var album = briefMusicInfo.Album; + if (!string.IsNullOrEmpty(album) && Albums != null) + { + if (!Albums.TryGetValue(album, out var albumInfo)) + { + albumInfo = new AlbumInfo(briefMusicInfo); + Albums[album] = albumInfo; + } + else + { + albumInfo.Update(briefMusicInfo); + } + } + } + + private void UpdateArtistInfo(BriefMusicInfo briefMusicInfo) + { + if (briefMusicInfo.Artists != null && Artists != null) + { + foreach (var artist in briefMusicInfo.Artists) + { + if (!Artists.TryGetValue(artist, out var artistInfo)) + { + artistInfo = new ArtistInfo(briefMusicInfo, artist); + Artists[artist] = artistInfo; + } + else + { + artistInfo.Update(briefMusicInfo); + } + } + } + } + + public ObservableCollection GetMusicByAlbum(AlbumInfo albumInfo) + { + var list = new ObservableCollection(); + var albumName = albumInfo.Name; + if (Musics != null) + { + foreach (var music in Musics) + { + if (music.Album == albumName && music.Path != null) + { + list.Add(new BriefMusicInfo(music.Path)); + } + } + } + return list; + } + + public ObservableCollection GetAlbumByArtist(ArtistInfo artistInfo) + { + var list = new ObservableCollection(); + var artistName = artistInfo.Name; + var albumDict = artistInfo.Albums; + if (Musics != null) + { + foreach (var music in Musics) + { + if (music.Artists != null && music.Artists.Contains(artistName) && music.Album != null && albumDict != null && albumDict.TryGetValue(music.Album, out var albumInfo)) + { + list.Add(albumInfo); + } + } + } + return list; + } + + /// + /// 根据歌曲名升序排序 + /// + public void SortMusicsByTitle() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderBy(m => m.Title)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据歌曲名降序排序 + /// + public void SortMusicsByTitleDescending() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderByDescending(m => m.Title)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据艺术家名升序排序 + /// + public void SortMusicsByArtist() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderBy(m => m.ArtistsStr)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据艺术家名降序排序 + /// + public void SortMusicsByArtistDescending() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderByDescending(m => m.ArtistsStr)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据专辑名升序排序 + /// + public void SortMusicsByAlbum() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderBy(m => m.Album)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据专辑名降序排序 + /// + public void SortMusicsByAlbumDescending() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderByDescending(m => m.Album)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据发行年份升序排序 + /// + public void SortMusicsByYear() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderBy(m => m.Year)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据发行年份降序排序 + /// + public void SortMusicsByYearDescending() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderByDescending(m => m.Year)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据修改日期升序排序 + /// + public void SortMusicsByModifiedTime() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderBy(m => m.ModifiedDate)); + Musics = sortedMusics; + } + GC.Collect(); + } + + /// + /// 根据修改日期降序排序 + /// + public void SortMusicsByModifiedTimeDecending() + { + if (Musics != null) + { + var sortedMusics = new ObservableCollection(Musics.OrderByDescending(m => m.ModifiedDate)); + Musics = sortedMusics; + } + GC.Collect(); + } +} diff --git a/The Untamed Music Player/Models/MusicPlayer.cs b/The Untamed Music Player/Models/MusicPlayer.cs new file mode 100644 index 0000000..56c7844 --- /dev/null +++ b/The Untamed Music Player/Models/MusicPlayer.cs @@ -0,0 +1,975 @@ +using System.Collections.ObjectModel; +using System.ComponentModel; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Views; +using Windows.Media.Core; +using Windows.Media.Playback; +using Windows.Storage; +using Windows.System.Threading; + +namespace The_Untamed_Music_Player.Models; + +public class MusicPlayer : INotifyPropertyChanged +{ + private readonly ILocalSettingsService _localSettingsService; + + public event PropertyChangedEventHandler? PropertyChanged; + protected void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private MediaPlayer _player = new() + { + AudioCategory = MediaPlayerAudioCategory.Media, + }; + /// + /// 音乐播放器 + /// + public MediaPlayer Player + { + get => _player; + set => _player = value; + } + + private string? _playQueueName; + /// + /// 播放队列名 + /// + public string? PlayQueueName + { + get => _playQueueName; + set + { + _playQueueName = value; + OnPropertyChanged(nameof(PlayQueueName)); + } + } + + private ObservableCollection _playQueue = []; + /// + /// 播放队列集合 + /// + public ObservableCollection PlayQueue + { + get => _playQueue; + set => _playQueue = value; + } + + private ObservableCollection _shuffledPlayQueue = []; + /// + /// 随机播放队列集合 + /// + public ObservableCollection ShuffledPlayQueue + { + get => _shuffledPlayQueue; + set => _shuffledPlayQueue = value; + } + + private int _playQueueLength; + /// + /// 播放队列歌曲数量 + /// + public int PlayQueueLength + { + get => _playQueueLength; + set + { + _playQueueLength = value; + OnPropertyChanged(nameof(PlayQueueLength)); + } + } + + private int _playQueueIndex; + /// + /// 当前歌曲在播放队列中的索引 + /// + public int PlayQueueIndex + { + get => _playQueueIndex; + set + { + _playQueueIndex = value; + OnPropertyChanged(nameof(PlayQueueIndex)); + } + } + + private bool _shuffleMode = false; + /// + /// 随机播放模式, true为开启, false为关闭. + /// + public bool ShuffleMode + { + get => _shuffleMode; + set => _shuffleMode = value; + } + + private int _repeatMode = 0; + /// + /// 循环播放模式, 0为不循环, 1为列表循环, 2为单曲循环 + /// + public int RepeatMode + { + get => _repeatMode; + set + { + _repeatMode = value; + OnPropertyChanged(nameof(RepeatMode)); + } + } + + private int _playState; + /// + /// 播放状态, 0为暂停, 1为播放, 2为加载中 + /// + public int PlayState + { + get => _playState; + set + { + _playState = value; + OnPropertyChanged(nameof(PlayState)); + } + } + + private DetailedMusicInfo _currentMusic = new(); + /// + /// 当前播放歌曲 + /// + public DetailedMusicInfo CurrentMusic + { + get => _currentMusic; + set + { + _currentMusic = value; + + //给播放器设置音乐源 + SetSource(value.Path); + CurrentLyric = LyricSlice.GetLyricSlices(value.Lyric); + OnPropertyChanged(nameof(CurrentMusic)); + } + } + + private ObservableCollection _currentLyric = []; + /// + /// 当前歌词切片集合 + /// + public ObservableCollection CurrentLyric + { + get => _currentLyric; + set + { + _currentLyric = value; + OnPropertyChanged(nameof(CurrentLyric)); + } + } + + private int _currentLyricIndex; + /// + /// 当前歌词切片在集合中的索引 + /// + public int CurrentLyricIndex + { + get => _currentLyricIndex; + set + { + _currentLyricIndex = value; + OnPropertyChanged(nameof(CurrentLyricIndex)); + } + } + + /// + /// 线程计时器 + /// + private ThreadPoolTimer? positionUpdateTimer; + + /// + /// 线程锁开启状态, true为开启, false为关闭 + /// + private bool lockable = false; + + /// + /// 播放栏UI + /// + public static RootPlayBarView? PlayBarUI + { + get; set; + } + + /// + /// 歌词页UI + /// + public static 歌词Page? 歌词UI + { + get; set; + } + + private TimeSpan _current; + /// + /// 当前播放时间 + /// + public TimeSpan Current + { + get => _current; + set + { + _current = value; + OnPropertyChanged(nameof(Current)); + } + } + + private TimeSpan _total; + /// + /// 当前歌曲总时长 + /// + public TimeSpan Total + { + get => _total; + set + { + _total = value; + OnPropertyChanged(nameof(Total)); + } + } + + private double _currentPosition; + /// + /// 当前播放进度(百分比) + /// + public double CurrentPosition + { + get => _currentPosition; + set + { + _currentPosition = value; + OnPropertyChanged(nameof(CurrentPosition)); + } + } + + private double _currentVolume = 100; + /// + /// 当前音量 + /// + public double CurrentVolume + { + get => _currentVolume; + set + { + _currentVolume = value; + Player.Volume = CurrentVolume / 100; + OnPropertyChanged(nameof(CurrentVolume)); + } + } + + /// + /// 线程锁, 用于限制对Player的访问 + /// + private readonly Lock mediaLock = new(); + + public MusicPlayer(ILocalSettingsService localSettingsService) + { + _localSettingsService = localSettingsService; + LoadCurrentStateAsync(); + Player.PlaybackSession.PlaybackStateChanged += PlaybackSession_PlaybackStateChanged; + Player.MediaEnded += OnPlaybackStopped; + Player.Volume = CurrentVolume / 100; + Player.CommandManager.IsEnabled = true; + } + + ~MusicPlayer() + { + Player.Dispose(); + } + + /// + /// 按路径播放歌曲 + /// + /// + /// 是否是播放列表中最后一曲 + public void PlaySongByPath(string path, bool isLast = false) + { + lock (mediaLock) + { + if (!isLast) + { + Stop(); + CurrentMusic = new DetailedMusicInfo(path); + if (ShuffleMode) + { + PlayQueueIndex = ShuffledPlayQueue.ToList().FindIndex(x => x.Path == path); + } + else + { + PlayQueueIndex = PlayQueue.ToList().FindIndex(x => x.Path == path); + } + Play(); + } + else + { + Stop(); + CurrentMusic = new DetailedMusicInfo(path); + PlayQueueIndex = PlayQueue.ToList().FindIndex(x => x.Path == path); + } + } + } + + /// + /// 为播放器设置音乐源 + /// + /// + private void SetSource(string path) + { + lock (mediaLock) + { + try + { + var mediaFileTask = StorageFile.GetFileFromPathAsync(path).AsTask(); + mediaFileTask.Wait(); + var mediaFile = mediaFileTask.Result; + Player.Source = MediaSource.CreateFromStorageFile(mediaFile); + Total = Player.PlaybackSession.NaturalDuration; + positionUpdateTimer = ThreadPoolTimer.CreatePeriodicTimer(UpdateTimerHandler, TimeSpan.FromMilliseconds(250), UpdateTimerDestoyed); + } + catch { } + } + } + + /// + /// 设置播放队列 + /// + /// + /// + public async void SetPlayList(string name, ObservableCollection list) + { + PlayQueueName = name; + PlayQueue = new ObservableCollection(list); + PlayQueueLength = list.Count; + if (Data.RootPlayBarViewModel != null) + { + Data.RootPlayBarViewModel.ButtonVisibility = PlayQueue.Any() ? Visibility.Visible : Visibility.Collapsed; + Data.RootPlayBarViewModel.Availability = PlayQueue.Any(); + } + await UpdateShufflePlayQueue(); + } + + /// + /// 计时器更新事件 + /// + /// + private void UpdateTimerHandler(ThreadPoolTimer timer) + { + lock (mediaLock) + { + if (Player != null && !lockable && Player.PlaybackSession.PlaybackState != MediaPlaybackState.None && Player.PlaybackSession.PlaybackState == MediaPlaybackState.Playing) + { + try + { + PlayBarUI?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => + { + + Current = Player.PlaybackSession?.Position ?? TimeSpan.Zero; + Total = Player.PlaybackSession?.NaturalDuration ?? TimeSpan.Zero; + CurrentPosition = 100 * (Current.TotalMilliseconds / Total.TotalMilliseconds); + }); + } + catch { } + try + { + 歌词UI?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => + { + CurrentLyricIndex = GetCurrentLyricIndex((Player.PlaybackSession?.Position ?? TimeSpan.Zero).TotalMilliseconds); + }); + } + catch { } + } + } + } + + /// + /// 获取当前歌词切片索引 + /// + /// + /// + public int GetCurrentLyricIndex(double currentTime) + { + var index = CurrentLyric.ToList().FindIndex(x => x.Time > currentTime); + if (index > 0) + { + index--; + } + if (index < 0) + { + index = CurrentLyric.Count - 1; + } + return index; + } + + /// + /// 计时器销毁事件 + /// + /// + private void UpdateTimerDestoyed(ThreadPoolTimer timer) + { + timer.Cancel(); + positionUpdateTimer?.Cancel(); + positionUpdateTimer = null; + } + + /// + /// 播放状态改变事件 + /// + /// + /// + public void PlaybackSession_PlaybackStateChanged(MediaPlaybackSession sender, object args) + { + try + { + switch (Player?.PlaybackSession.PlaybackState) + { + case MediaPlaybackState.None: + break; + case MediaPlaybackState.Opening: + PlayBarUI?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => + { + PlayState = 2; + }); + break; + case MediaPlaybackState.Buffering: + PlayBarUI?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => + { + PlayState = 2; + }); + break; + case MediaPlaybackState.Playing: + PlayBarUI?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => + { + PlayState = 1; + }); + break; + case MediaPlaybackState.Paused: + PlayBarUI?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => + { + PlayState = 0; + }); + break; + default: + break; + } + } + catch { } + } + + /// + /// 播放结束事件 + /// + /// + /// + private void OnPlaybackStopped(MediaPlayer sender, object args) + { + PlayBarUI?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + if (Player?.PlaybackSession.PlaybackState == MediaPlaybackState.Paused && !lockable) + { + if (RepeatMode == 2) + { + PlaySongByPath(CurrentMusic.Path); + } + else + { + PlayNextSong(); + } + } + }); + } + + /// + /// 播放 + /// + private void Play() + { + Player?.Play(); + } + + /// + /// 暂停 + /// + private void Pause() + { + Player?.Pause(); + } + + /// + /// 停止 + /// + private void Stop() + { + Player?.Pause(); + Current = TimeSpan.Zero; + CurrentPosition = 0; + positionUpdateTimer?.Cancel(); + positionUpdateTimer = null; + } + + /// + /// 播放上一曲 + /// + public void PlayPreviousSong() + { + try + { + switch (ShuffleMode, RepeatMode) + { + case (false, 0): + { + if (PlayQueueIndex > 0) + { + PlaySongByPath(PlayQueue[PlayQueueIndex - 1].Path); + } + else + { + PlaySongByPath(PlayQueue[PlayQueueIndex].Path); + } + break; + } + case (false, 1): + { + { + PlaySongByPath(PlayQueue[(PlayQueueIndex + PlayQueueLength - 1) % PlayQueueLength].Path); + break; + } + } + case (false, 2): + { + if (PlayQueueIndex > 0) + { + PlaySongByPath(PlayQueue[PlayQueueIndex - 1].Path); + } + else + { + PlaySongByPath(PlayQueue[PlayQueueIndex].Path); + } + break; + } + case (true, 0): + { + if (PlayQueueIndex > 0) + { + PlaySongByPath(ShuffledPlayQueue[PlayQueueIndex - 1].Path); + } + else + { + PlaySongByPath(ShuffledPlayQueue[PlayQueueIndex].Path); + } + break; + } + case (true, 1): + { + { + PlaySongByPath(ShuffledPlayQueue[(PlayQueueIndex + PlayQueueLength - 1) % PlayQueueLength].Path); + break; + } + } + case (true, 2): + { + if (PlayQueueIndex > 0) + { + PlaySongByPath(ShuffledPlayQueue[PlayQueueIndex - 1].Path); + } + else + { + PlaySongByPath(ShuffledPlayQueue[PlayQueueIndex].Path); + } + break; + } + default: + break; + } + } + catch { } + } + + /// + /// 播放下一曲 + /// + public void PlayNextSong() + { + try + { + switch (ShuffleMode, RepeatMode) + { + case (false, 0): + { + if (PlayQueueIndex < PlayQueueLength - 1) + { + PlaySongByPath(PlayQueue[PlayQueueIndex + 1].Path); + } + else + { + PlaySongByPath(PlayQueue[0].Path, true); + } + break; + } + case (false, 1): + { + { + PlaySongByPath(PlayQueue[(PlayQueueIndex + 1) % PlayQueueLength].Path); + break; + } + } + case (false, 2): + { + if (PlayQueueIndex < PlayQueueLength - 1) + { + PlaySongByPath(PlayQueue[PlayQueueIndex + 1].Path); + } + else + { + PlaySongByPath(PlayQueue[0].Path, true); + } + break; + } + case (true, 0): + { + if (PlayQueueIndex < PlayQueueLength - 1) + { + PlaySongByPath(ShuffledPlayQueue[PlayQueueIndex + 1].Path); + } + else + { + PlaySongByPath(ShuffledPlayQueue[0].Path, true); + } + break; + } + case (true, 1): + { + { + PlaySongByPath(ShuffledPlayQueue[(PlayQueueIndex + 1) % PlayQueueLength].Path); + break; + } + } + case (true, 2): + { + if (PlayQueueIndex < PlayQueueLength - 1) + { + PlaySongByPath(ShuffledPlayQueue[PlayQueueIndex + 1].Path); + } + else + { + PlaySongByPath(ShuffledPlayQueue[0].Path, true); + } + break; + } + default: + break; + } + } + catch { } + } + + /// + /// 播放按钮更新 + /// + public void PlayPauseUpdate() + { + if (PlayState == 1 || PlayState == 2) + { + Pause(); + } + else + { + Play(); + } + } + + /// + /// 随机播放模式更新 + /// + public async void ShuffleModeUpdate() + { + ShuffleMode = !ShuffleMode; + if (ShuffleMode) + { + await UpdateShufflePlayQueue(); + } + else + { + ShuffledPlayQueue.Clear(); + PlayQueueIndex = PlayQueue.ToList().FindIndex(x => x.Path == CurrentMusic.Path); + } + OnPropertyChanged(nameof(ShuffleMode)); + } + + /// + /// 循环播放模式更新 + /// + public void RepeatModeUpdate() + { + RepeatMode = (RepeatMode + 1) % 3; + } + + /// + /// 随机播放队列更新 + /// + /// + public async Task UpdateShufflePlayQueue() + { + await Task.Run(() => + { + ShuffledPlayQueue = new ObservableCollection([.. PlayQueue.OrderBy(x => Guid.NewGuid())]); + PlayQueueIndex = ShuffledPlayQueue.ToList().FindIndex(x => x.Path == CurrentMusic.Path); + }); + } + + /// + /// 清空播放队列 + /// + public void ClearPlayQueue() + { + Stop(); + Total = TimeSpan.Zero; + PlayQueue.Clear(); + ShuffledPlayQueue.Clear(); + CurrentLyric.Clear(); + PlayQueueName = ""; + PlayQueueIndex = 0; + PlayQueueLength = 0; + if (Data.RootPlayBarViewModel != null) + { + Data.RootPlayBarViewModel.ButtonVisibility = PlayQueue.Any() ? Visibility.Visible : Visibility.Collapsed; + Data.RootPlayBarViewModel.Availability = PlayQueue.Any(); + } + } + + /// + /// 按下滑动条事件 + /// + /// + /// + public void ProgressLock(object sender, PointerRoutedEventArgs e) + { + lockable = true; + Current = TimeSpan.FromMilliseconds((double)((Slider)sender).Value * Total.TotalMilliseconds / 100); + } + + /// + /// 滑动滑动条事件 + /// + /// + /// + public void SliderUpdate(object sender, PointerRoutedEventArgs e) + { + Current = TimeSpan.FromMilliseconds((double)((Slider)sender).Value * Total.TotalMilliseconds / 100); + } + + /// + /// 松开滑动条更新播放进度 + /// + /// + /// + public void ProgressUpdate(object sender, PointerRoutedEventArgs e) + { + Player.PlaybackSession.Position = TimeSpan.FromMilliseconds((double)((Slider)sender).Value * Total.TotalMilliseconds / 100); + Current = Player.PlaybackSession?.Position ?? TimeSpan.Zero; + Total = Player.PlaybackSession?.NaturalDuration ?? TimeSpan.Zero; + CurrentPosition = 100 * (Current.TotalMilliseconds / Total.TotalMilliseconds); + CurrentLyricIndex = GetCurrentLyricIndex((Player.PlaybackSession?.Position ?? TimeSpan.Zero).TotalMilliseconds); + lockable = false; + } + + /// + /// 点击歌词更新播放进度 + /// + /// + public void LyricProgressUpdate(double time) + { + lockable = true; + Player.PlaybackSession.Position = TimeSpan.FromMilliseconds(time); + Current = Player.PlaybackSession?.Position ?? TimeSpan.Zero; + Total = Player.PlaybackSession?.NaturalDuration ?? TimeSpan.Zero; + CurrentPosition = 100 * (Current.TotalMilliseconds / Total.TotalMilliseconds); + CurrentLyricIndex = GetCurrentLyricIndex((Player.PlaybackSession?.Position ?? TimeSpan.Zero).TotalMilliseconds); + lockable = false; + } + + /// + /// 获取歌词字体大小 + /// + /// + /// + /// + public double GetLyricFont(double itemTime, int CurrentLyricIdx) + { + try + { + if (Data.MainWindow?.Width <= 1000) + { + if (itemTime == CurrentLyric[CurrentLyricIdx].Time) + { + return 24; + } + else + { + return 16; + } + } + else + { + if (itemTime == CurrentLyric[CurrentLyricIdx].Time) + { + return 50; + } + else + { + return 20; + } + } + } + catch + { + return 20; + } + } + + /// + /// 获取歌词边距 + /// + /// + /// + /// + public Thickness GetLyricMargin(double itemTime, int CurrentLyricIdx) + { + try + { + if (itemTime == CurrentLyric[CurrentLyricIdx].Time) + { + return new Thickness(0, 40, 0, 40); + } + else + { + return new Thickness(0, 20, 0, 20); + } + } + catch + { + return new Thickness(0, 20, 0, 20); + } + } + + /// + /// 获取歌词透明度 + /// + /// + /// + /// + public double GetLyricOpacity(double itemTime, int CurrentLyricIdx) + { + try + { + if (itemTime == CurrentLyric[CurrentLyricIdx].Time) + { + return 1; + } + else + { + return 0.5; + } + } + catch + { + return 0.5; + } + } + + /// + /// 获取播放队列 + /// + /// + /// + /// + public ObservableCollection GetPlayQueue(string PlayQueueName, bool ShuffleMode) + { + if (ShuffleMode) + { + return ShuffledPlayQueue; + } + else + { + return PlayQueue; + } + } + + /// + /// 保存当前播放状态至设置存储 + /// + public async void SaveCurrentStateAsync() + { + await _localSettingsService.SaveSettingAsync("NotFirstUsed", true); + await _localSettingsService.SaveSettingAsync("CurrentMusic", CurrentMusic.Path); + /*var playqueuepaths = PlayQueue.Select(music => music.Path).ToList(); + await _localSettingsService.SaveSettingAsync("PlayQueuePaths", playqueuepaths); + var shuffledplayqueuepaths = ShuffledPlayQueue.Select(music => music.Path).ToList(); + await _localSettingsService.SaveSettingAsync("ShuffledPlayQueuePaths", shuffledplayqueuepaths); + await _localSettingsService.SaveSettingAsync("PlayQueueIndex", PlayQueueIndex);*/ + await _localSettingsService.SaveSettingAsync("ShuffleMode", ShuffleMode); + await _localSettingsService.SaveSettingAsync("RepeatMode", RepeatMode); + await _localSettingsService.SaveSettingAsync("CurrentVolume", CurrentVolume); + } + + /// + /// 从设置存储中读取当前播放状态 + /// + public async void LoadCurrentStateAsync() + { + var notFirstUsed = await _localSettingsService.ReadSettingAsync("NotFirstUsed"); + var currentMusicPath = await _localSettingsService.ReadSettingAsync("CurrentMusic"); + if (!string.IsNullOrEmpty(currentMusicPath)) + { + CurrentMusic = new DetailedMusicInfo(currentMusicPath); + } + /*var playqueuepaths = await _localSettingsService.ReadSettingAsync>("PlayQueuePaths"); + if (playqueuepaths != null) + { + PlayQueue.Clear(); + foreach (var path in playqueuepaths) + { + if (!string.IsNullOrEmpty(path)) + { + var musicInfo = new BriefMusicInfo(path); + PlayQueue.Add(musicInfo); + } + } + } + var shuffledplayqueuepaths = await _localSettingsService.ReadSettingAsync>("ShuffledPlayQueuePaths"); + if (shuffledplayqueuepaths != null) + { + ShuffledPlayQueue.Clear(); + foreach (var path in shuffledplayqueuepaths) + { + if (!string.IsNullOrEmpty(path)) + { + var musicInfo = new BriefMusicInfo(path); + ShuffledPlayQueue.Add(musicInfo); + } + } + } + PlayQueueIndex = await _localSettingsService.ReadSettingAsync("PlayQueueIndex");*/ + ShuffleMode = await _localSettingsService.ReadSettingAsync("ShuffleMode"); + RepeatMode = await _localSettingsService.ReadSettingAsync("RepeatMode"); + if (notFirstUsed) + { + CurrentVolume = await _localSettingsService.ReadSettingAsync("CurrentVolume"); + } + else + { + CurrentVolume = 100; + } + /*if (Data.RootPlayBarViewModel != null) + { + Data.RootPlayBarViewModel.ButtonVisibility = PlayQueue.Any() ? Visibility.Visible : Visibility.Collapsed; + Data.RootPlayBarViewModel.Availability = PlayQueue.Any(); + }*/ + } +} \ No newline at end of file diff --git a/The Untamed Music Player/Package.appinstaller b/The Untamed Music Player/Package.appinstaller new file mode 100644 index 0000000..c619457 --- /dev/null +++ b/The Untamed Music Player/Package.appinstaller @@ -0,0 +1,17 @@ + + + + + + + + + + + + diff --git a/The Untamed Music Player/Package.appxmanifest b/The Untamed Music Player/Package.appxmanifest new file mode 100644 index 0000000..08df192 --- /dev/null +++ b/The Untamed Music Player/Package.appxmanifest @@ -0,0 +1,76 @@ + + + + + + + + + + The Untamed Music Player + Admin + Assets\StoreLogo.png + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Properties/launchsettings.json b/The Untamed Music Player/Properties/launchsettings.json new file mode 100644 index 0000000..705077d --- /dev/null +++ b/The Untamed Music Player/Properties/launchsettings.json @@ -0,0 +1,10 @@ +{ + "profiles": { + "The Untamed Music Player (Package)": { + "commandName": "MsixPackage" + }, + "The Untamed Music Player (Unpackaged)": { + "commandName": "Project" + } + } +} diff --git a/The Untamed Music Player/README.md b/The Untamed Music Player/README.md new file mode 100644 index 0000000..e24cced --- /dev/null +++ b/The Untamed Music Player/README.md @@ -0,0 +1,27 @@ +*Recommended Markdown Viewer: [Markdown Editor](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.MarkdownEditor2)* + +## Getting Started + +Browse and address `TODO:` comments in `View -> Task List` to learn the codebase and understand next steps for turning the generated code into production code. + +Explore the [WinUI Gallery](https://www.microsoft.com/store/productId/9P3JFPWWDZRC) to learn about available controls and design patterns. + +Relaunch Template Studio to modify the project by right-clicking on the project in `View -> Solution Explorer` then selecting `Add -> New Item (Template Studio)`. + +## Publishing + +For projects with MSIX packaging, right-click on the application project and select `Package and Publish -> Create App Packages...` to create an MSIX package. + +For projects without MSIX packaging, follow the [deployment guide](https://docs.microsoft.com/windows/apps/windows-app-sdk/deploy-unpackaged-apps) or add the `Self-Contained` Feature to enable xcopy deployment. + +## CI Pipelines + +See [README.md](https://github.com/microsoft/TemplateStudio/blob/main/docs/WinUI/pipelines/README.md) for guidance on building and testing projects in CI pipelines. + +## Changelog + +See [releases](https://github.com/microsoft/TemplateStudio/releases) and [milestones](https://github.com/microsoft/TemplateStudio/milestones). + +## Feedback + +Bugs and feature requests should be filed at https://aka.ms/templatestudio. diff --git a/The Untamed Music Player/Services/ActivationService.cs b/The Untamed Music Player/Services/ActivationService.cs new file mode 100644 index 0000000..e6384c7 --- /dev/null +++ b/The Untamed Music Player/Services/ActivationService.cs @@ -0,0 +1,72 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; + +using The_Untamed_Music_Player.Activation; +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Views; + +namespace The_Untamed_Music_Player.Services; + +public class ActivationService : IActivationService +{ + private readonly ActivationHandler _defaultHandler; + private readonly IEnumerable _activationHandlers; + private readonly IThemeSelectorService _themeSelectorService; + private UIElement? _shell = null; + + public ActivationService(ActivationHandler defaultHandler, IEnumerable activationHandlers, IThemeSelectorService themeSelectorService) + { + _defaultHandler = defaultHandler; + _activationHandlers = activationHandlers; + _themeSelectorService = themeSelectorService; + } + + public async Task ActivateAsync(object activationArgs) + { + // Execute tasks before activation. + await InitializeAsync(); + + // Set the MainWindow Content. + if (App.MainWindow.Content == null) + { + _shell = App.GetService(); + App.MainWindow.Content = _shell ?? new Frame(); + } + + // Handle activation via ActivationHandlers. + await HandleActivationAsync(activationArgs); + + // Activate the MainWindow. + App.MainWindow.Activate(); + + // Execute tasks after activation. + await StartupAsync(); + } + + private async Task HandleActivationAsync(object activationArgs) + { + var activationHandler = _activationHandlers.FirstOrDefault(h => h.CanHandle(activationArgs)); + + if (activationHandler != null) + { + await activationHandler.HandleAsync(activationArgs); + } + + if (_defaultHandler.CanHandle(activationArgs)) + { + await _defaultHandler.HandleAsync(activationArgs); + } + } + + private async Task InitializeAsync() + { + await _themeSelectorService.InitializeAsync().ConfigureAwait(false); + await Task.CompletedTask; + } + + private async Task StartupAsync() + { + await _themeSelectorService.SetRequestedThemeAsync(); + await Task.CompletedTask; + } +} diff --git a/The Untamed Music Player/Services/LocalSettingsService.cs b/The Untamed Music Player/Services/LocalSettingsService.cs new file mode 100644 index 0000000..12e01b0 --- /dev/null +++ b/The Untamed Music Player/Services/LocalSettingsService.cs @@ -0,0 +1,86 @@ +using Microsoft.Extensions.Options; + +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Core.Contracts.Services; +using The_Untamed_Music_Player.Core.Helpers; +using The_Untamed_Music_Player.Helpers; +using The_Untamed_Music_Player.Models; +using Windows.Storage; + +namespace The_Untamed_Music_Player.Services; + +public class LocalSettingsService : ILocalSettingsService +{ + private const string _defaultApplicationDataFolder = "The Untamed Music Player/ApplicationData"; + private const string _defaultLocalSettingsFile = "LocalSettings.json"; + + private readonly IFileService _fileService; + private readonly LocalSettingsOptions _options; + + private readonly string _localApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + private readonly string _applicationDataFolder; + private readonly string _localsettingsFile; + + private IDictionary _settings; + + private bool _isInitialized; + + public LocalSettingsService(IFileService fileService, IOptions options) + { + _fileService = fileService; + _options = options.Value; + + _applicationDataFolder = Path.Combine(_localApplicationData, _options.ApplicationDataFolder ?? _defaultApplicationDataFolder); + _localsettingsFile = _options.LocalSettingsFile ?? _defaultLocalSettingsFile; + + _settings = new Dictionary(); + } + + private async Task InitializeAsync() + { + if (!_isInitialized) + { + _settings = await Task.Run(() => _fileService.Read>(_applicationDataFolder, _localsettingsFile)) ?? new Dictionary(); + + _isInitialized = true; + } + } + + public async Task ReadSettingAsync(string key) + { + if (RuntimeHelper.IsMSIX) + { + if (ApplicationData.Current.LocalSettings.Values.TryGetValue(key, out var obj)) + { + return await Json.ToObjectAsync((string)obj); + } + } + else + { + await InitializeAsync(); + + if (_settings != null && _settings.TryGetValue(key, out var obj)) + { + return await Json.ToObjectAsync((string)obj); + } + } + + return default; + } + + public async Task SaveSettingAsync(string key, T value) + { + if (RuntimeHelper.IsMSIX) + { + ApplicationData.Current.LocalSettings.Values[key] = await Json.StringifyAsync(value); + } + else + { + await InitializeAsync(); + + _settings[key] = await Json.StringifyAsync(value); + + await Task.Run(() => _fileService.Save(_applicationDataFolder, _localsettingsFile, _settings)); + } + } +} diff --git a/The Untamed Music Player/Services/NavigationService.cs b/The Untamed Music Player/Services/NavigationService.cs new file mode 100644 index 0000000..1680f8e --- /dev/null +++ b/The Untamed Music Player/Services/NavigationService.cs @@ -0,0 +1,126 @@ +using System.Diagnostics.CodeAnalysis; + +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Navigation; + +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Contracts.ViewModels; +using The_Untamed_Music_Player.Helpers; + +namespace The_Untamed_Music_Player.Services; + +// For more information on navigation between pages see +// https://github.com/microsoft/TemplateStudio/blob/main/docs/WinUI/navigation.md +public class NavigationService : INavigationService +{ + private readonly IPageService _pageService; + private object? _lastParameterUsed; + private Frame? _frame; + + public event NavigatedEventHandler? Navigated; + + public Frame? Frame + { + get + { + if (_frame == null) + { + _frame = App.MainWindow.Content as Frame; + RegisterFrameEvents(); + } + + return _frame; + } + + set + { + UnregisterFrameEvents(); + _frame = value; + RegisterFrameEvents(); + } + } + + [MemberNotNullWhen(true, nameof(Frame), nameof(_frame))] + public bool CanGoBack => Frame != null && Frame.CanGoBack; + + public NavigationService(IPageService pageService) + { + _pageService = pageService; + } + + private void RegisterFrameEvents() + { + if (_frame != null) + { + _frame.Navigated += OnNavigated; + } + } + + private void UnregisterFrameEvents() + { + if (_frame != null) + { + _frame.Navigated -= OnNavigated; + } + } + + public bool GoBack() + { + if (CanGoBack) + { + var vmBeforeNavigation = _frame.GetPageViewModel(); + _frame.GoBack(); + if (vmBeforeNavigation is INavigationAware navigationAware) + { + navigationAware.OnNavigatedFrom(); + } + + return true; + } + + return false; + } + + public bool NavigateTo(string pageKey, object? parameter = null, bool clearNavigation = false) + { + var pageType = _pageService.GetPageType(pageKey); + + if (_frame != null && (_frame.Content?.GetType() != pageType || (parameter != null && !parameter.Equals(_lastParameterUsed)))) + { + _frame.Tag = clearNavigation; + var vmBeforeNavigation = _frame.GetPageViewModel(); + var navigated = _frame.Navigate(pageType, parameter); + if (navigated) + { + _lastParameterUsed = parameter; + if (vmBeforeNavigation is INavigationAware navigationAware) + { + navigationAware.OnNavigatedFrom(); + } + } + + return navigated; + } + + return false; + } + + private void OnNavigated(object sender, NavigationEventArgs e) + { + if (sender is Frame frame) + { + var clearNavigation = (bool)frame.Tag; + if (clearNavigation) + { + frame.BackStack.Clear(); + } + + if (frame.GetPageViewModel() is INavigationAware navigationAware) + { + navigationAware.OnNavigatedTo(e.Parameter); + } + + Navigated?.Invoke(sender, e); + } + } +} diff --git a/The Untamed Music Player/Services/NavigationViewService.cs b/The Untamed Music Player/Services/NavigationViewService.cs new file mode 100644 index 0000000..824b035 --- /dev/null +++ b/The Untamed Music Player/Services/NavigationViewService.cs @@ -0,0 +1,103 @@ +using System.Diagnostics.CodeAnalysis; + +using Microsoft.UI.Xaml.Controls; + +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Helpers; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Services; + +public class NavigationViewService : INavigationViewService +{ + private readonly INavigationService _navigationService; + + private readonly IPageService _pageService; + + private NavigationView? _navigationView; + + public IList? MenuItems => _navigationView?.MenuItems; + + public object? SettingsItem => _navigationView?.SettingsItem; + + public NavigationViewService(INavigationService navigationService, IPageService pageService) + { + _navigationService = navigationService; + _pageService = pageService; + } + + [MemberNotNull(nameof(_navigationView))] + public void Initialize(NavigationView navigationView) + { + _navigationView = navigationView; + _navigationView.BackRequested += OnBackRequested; + _navigationView.ItemInvoked += OnItemInvoked; + } + + public void UnregisterEvents() + { + if (_navigationView != null) + { + _navigationView.BackRequested -= OnBackRequested; + _navigationView.ItemInvoked -= OnItemInvoked; + } + } + + public NavigationViewItem? GetSelectedItem(Type pageType) + { + if (_navigationView != null) + { + return GetSelectedItem(_navigationView.MenuItems, pageType) ?? GetSelectedItem(_navigationView.FooterMenuItems, pageType); + } + + return null; + } + + private void OnBackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args) => _navigationService.GoBack(); + + private void OnItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args) + { + if (args.IsSettingsInvoked) + { + _navigationService.NavigateTo(typeof(SettingsViewModel).FullName!); + } + else + { + var selectedItem = args.InvokedItemContainer as NavigationViewItem; + + if (selectedItem?.GetValue(NavigationHelper.NavigateToProperty) is string pageKey) + { + _navigationService.NavigateTo(pageKey); + } + } + } + + private NavigationViewItem? GetSelectedItem(IEnumerable menuItems, Type pageType) + { + foreach (var item in menuItems.OfType()) + { + if (IsMenuItemForPageType(item, pageType)) + { + return item; + } + + var selectedChild = GetSelectedItem(item.MenuItems, pageType); + if (selectedChild != null) + { + return selectedChild; + } + } + + return null; + } + + private bool IsMenuItemForPageType(NavigationViewItem menuItem, Type sourcePageType) + { + if (menuItem.GetValue(NavigationHelper.NavigateToProperty) is string pageKey) + { + return _pageService.GetPageType(pageKey) == sourcePageType; + } + + return false; + } +} diff --git a/The Untamed Music Player/Services/PageService.cs b/The Untamed Music Player/Services/PageService.cs new file mode 100644 index 0000000..db2038f --- /dev/null +++ b/The Untamed Music Player/Services/PageService.cs @@ -0,0 +1,59 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +using Microsoft.UI.Xaml.Controls; + +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.ViewModels; +using The_Untamed_Music_Player.Views; + +namespace The_Untamed_Music_Player.Services; + +public class PageService : IPageService +{ + private readonly Dictionary _pages = new(); + + public PageService() + { + Configure<主页ViewModel, 主页Page>(); + Configure<音乐库ViewModel, 音乐库Page>(); + Configure<播放队列ViewModel, 播放队列Page>(); + Configure<播放列表ViewModel, 播放列表Page>(); + Configure(); + } + + public Type GetPageType(string key) + { + Type? pageType; + lock (_pages) + { + if (!_pages.TryGetValue(key, out pageType)) + { + throw new ArgumentException($"Page not found: {key}. Did you forget to call PageService.Configure?"); + } + } + + return pageType; + } + + private void Configure() + where VM : ObservableObject + where V : Page + { + lock (_pages) + { + var key = typeof(VM).FullName!; + if (_pages.ContainsKey(key)) + { + throw new ArgumentException($"The key {key} is already configured in PageService"); + } + + var type = typeof(V); + if (_pages.ContainsValue(type)) + { + throw new ArgumentException($"This type is already configured with key {_pages.First(p => p.Value == type).Key}"); + } + + _pages.Add(key, type); + } + } +} diff --git a/The Untamed Music Player/Services/ThemeSelectorService.cs b/The Untamed Music Player/Services/ThemeSelectorService.cs new file mode 100644 index 0000000..9fe2133 --- /dev/null +++ b/The Untamed Music Player/Services/ThemeSelectorService.cs @@ -0,0 +1,63 @@ +using Microsoft.UI.Xaml; + +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Helpers; + +namespace The_Untamed_Music_Player.Services; + +public class ThemeSelectorService : IThemeSelectorService +{ + private const string SettingsKey = "AppBackgroundRequestedTheme"; + + public ElementTheme Theme { get; set; } = ElementTheme.Default; + + private readonly ILocalSettingsService _localSettingsService; + + public ThemeSelectorService(ILocalSettingsService localSettingsService) + { + _localSettingsService = localSettingsService; + } + + public async Task InitializeAsync() + { + Theme = await LoadThemeFromSettingsAsync(); + await Task.CompletedTask; + } + + public async Task SetThemeAsync(ElementTheme theme) + { + Theme = theme; + + await SetRequestedThemeAsync(); + await SaveThemeInSettingsAsync(Theme); + } + + public async Task SetRequestedThemeAsync() + { + if (App.MainWindow.Content is FrameworkElement rootElement) + { + rootElement.RequestedTheme = Theme; + + TitleBarHelper.UpdateTitleBar(Theme); + } + + await Task.CompletedTask; + } + + private async Task LoadThemeFromSettingsAsync() + { + var themeName = await _localSettingsService.ReadSettingAsync(SettingsKey); + + if (Enum.TryParse(themeName, out ElementTheme cacheTheme)) + { + return cacheTheme; + } + + return ElementTheme.Default; + } + + private async Task SaveThemeInSettingsAsync(ElementTheme theme) + { + await _localSettingsService.SaveSettingAsync(SettingsKey, theme.ToString()); + } +} diff --git a/The Untamed Music Player/Strings/en-us/Resources.resw b/The Untamed Music Player/Strings/en-us/Resources.resw new file mode 100644 index 0000000..a7d8f1c --- /dev/null +++ b/The Untamed Music Player/Strings/en-us/Resources.resw @@ -0,0 +1,339 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Untamed Music Player + + + Untamed Music Player + + + Home + + + Music library + + + Play queue + + + Playlists + + + Personalization + + + App theme + + + Light + + + Dark + + + Use system setting + + + About this application + + + © 2024 Untamed Corporation. All rights reserved. + + + Libraries + + + Music library locations + + + Add folder + + + Refresh libraries + + + Refresh + + + No folders are included in this library. + + + If you're not seeing all the media from your library locations, you can re-index your libraries now. + + + Search + + + Properties + + + Equalizer + + + Speed + + + Cast to device + + + Skip back 10 seconds + + + Skip forward 30 seconds + + + Home + + + Playlists + + + Play queue + + + Music + + + Settings + + + We couldn't find any music + + + Your music library doesn't contain any music content. + + + Songs + + + Albums + + + Artists + + + Revome this folder? + + + If you remove the “ + + + “ folder from Music, it won't appear in Music anymore, but won't be deleted. + + + Remove Folder + + + Cancel + + + Manage system indexing settings + + + Did you mean to switch apps? + + + “Media Player” is trying to open “Settings”. + + + Yes + + + No + + + Volume + + + FullScreen (F11) + + + Mini player (Ctrl+M) + + + More options + + + Ctrl+Shift+G + + + Ctrl+Shift+H + + + Ctrl+Shift+J + + + Ctrl+Shift+K + + + Ctrl+Shift+L + + + Previous (Ctrl+B) + + + Next (Ctrl+F) + + + NowPlaying (Ctrl+N) + + + Shuffle: Off (Ctrl+H) + + + Shuffle: On (Ctrl+H) + + + Repeat: Off (Ctrl+T) + + + Repeat: All (Ctrl+T) + + + Repeat: One (Ctrl+T) + + + Home (Ctrl+Shift+F) + + + Music library (Ctrl+R) + + + Play queue (Ctrl+Q) + + + Playlists (Ctrl+Y) + + + Play (Ctrl+P) + + + Pause (Ctrl+P) + + + Seek + + + Remove folder + + + Add a folder to your music library + + \ No newline at end of file diff --git a/The Untamed Music Player/Strings/zh-cn/Resources.resw b/The Untamed Music Player/Strings/zh-cn/Resources.resw new file mode 100644 index 0000000..f3ff6fb --- /dev/null +++ b/The Untamed Music Player/Strings/zh-cn/Resources.resw @@ -0,0 +1,339 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Untamed Music Player + + + Untamed Music Player + + + 主页 + + + 音乐库 + + + 播放队列 + + + 播放列表 + + + 个性化 + + + 应用主题 + + + 浅色 + + + 深色 + + + 使用系统设置 + + + 关于 + + + © 2024 Untamed Corporation。保留所有权利。 + + + + + + 添加文件夹 + + + 音乐库位置 + + + 此库中不包含任何文件夹 + + + 刷新 + + + 刷新库 + + + 如果看不到库位置中的所有媒体,可以立即重新索引库。 + + + 搜索 + + + 属性 + + + 均衡器 + + + 速度 + + + 投放到设备 + + + 快退10秒 + + + 快进30秒 + + + 主页 + + + 播放列表 + + + 播放队列 + + + 音乐 + + + 设置 + + + 找不到任何音乐 + + + 你的音乐库不包含任何音乐内容 + + + 歌曲 + + + 专辑 + + + 艺术家 + + + 删除此文件夹吗? + + + 如果将“ + + + ”文件夹从音乐中移除,则该文件夹不会再出现在音乐中,但不会被删除。 + + + 删除文件夹 + + + 取消 + + + 管理系统索引设置 + + + 你指的是要切换应用吗? + + + “媒体播放器”正在尝试打开“设置”。 + + + + + + + + + 音量 + + + 全屏 (F11) + + + 最小播放器 (Ctrl+M) + + + 更多选项 + + + Ctrl+Shift+J + + + Ctrl+Shift+G + + + Ctrl+Shift+H + + + Ctrl+Shift+K + + + Ctrl+Shift+L + + + 上一个 (Ctrl+B) + + + 下一个 (Ctrl+F) + + + 正在播放 (Ctrl+N) + + + 随机播放: 关 (Ctrl+H) + + + 随机播放: 开 (Ctrl+H) + + + 重复: 关 (Ctrl+T) + + + 重复: 全部 (Ctrl+T) + + + 重复: 单曲 (Ctrl+T) + + + 主页 (Ctrl+Shift+F) + + + 音乐库 (Ctrl+R) + + + 播放队列 (Ctrl+Q) + + + 播放列表 (Ctrl+Y) + + + 播放 (Ctrl+P) + + + 暂停 (Ctrl+P) + + + 定位 + + + 删除文件夹 + + + 将文件夹添加到音乐库 + + \ No newline at end of file diff --git a/The Untamed Music Player/Styles/ButtonStyle.xaml b/The Untamed Music Player/Styles/ButtonStyle.xaml new file mode 100644 index 0000000..283c333 --- /dev/null +++ b/The Untamed Music Player/Styles/ButtonStyle.xaml @@ -0,0 +1,153 @@ + + + + + + diff --git a/The Untamed Music Player/Styles/FontSizes.xaml b/The Untamed Music Player/Styles/FontSizes.xaml new file mode 100644 index 0000000..44904b1 --- /dev/null +++ b/The Untamed Music Player/Styles/FontSizes.xaml @@ -0,0 +1,9 @@ + + + 24 + + 16 + + diff --git a/The Untamed Music Player/Styles/TextBlock.xaml b/The Untamed Music Player/Styles/TextBlock.xaml new file mode 100644 index 0000000..0f9eb84 --- /dev/null +++ b/The Untamed Music Player/Styles/TextBlock.xaml @@ -0,0 +1,20 @@ + + + + + + + \ No newline at end of file diff --git a/The Untamed Music Player/Styles/Thickness.xaml b/The Untamed Music Player/Styles/Thickness.xaml new file mode 100644 index 0000000..96ef0c9 --- /dev/null +++ b/The Untamed Music Player/Styles/Thickness.xaml @@ -0,0 +1,36 @@ + + + 0,36,0,0 + 0,36,0,36 + + 0,24,0,0 + 0,24,0,24 + 24,0,24,0 + 0,0,0,24 + + 12,0,0,0 + 12,0,12,0 + 0,12,0,0 + 0,0,12,0 + 0,12,0,12 + + 8,0,0,0 + 0,8,0,0 + 8,8,8,8 + + 0,4,0,0 + 4,4,4,4 + + 1,1,0,0 + 8,0,0,0 + 0,48,0,0 + 56,34,0,0 + 56,24,56,0 + + 36,24,36,0 + + -12,4,0,0 + + diff --git a/The Untamed Music Player/TemplateStudio.xml b/The Untamed Music Player/TemplateStudio.xml new file mode 100644 index 0000000..0c8e42d --- /dev/null +++ b/The Untamed Music Player/TemplateStudio.xml @@ -0,0 +1,11 @@ + + + + + + + + + + diff --git a/The Untamed Music Player/The Untamed Music Player.csproj b/The Untamed Music Player/The Untamed Music Player.csproj new file mode 100644 index 0000000..e4ef177 --- /dev/null +++ b/The Untamed Music Player/The Untamed Music Player.csproj @@ -0,0 +1,113 @@ + + + WinExe + net9.0-windows10.0.22621.0 + 10.0.22621.0 + The_Untamed_Music_Player + Assets/WindowIcon.ico + app.manifest + x86;x64;arm64 + win-x86;win-x64;win-arm64 + Properties\PublishProfiles\win10-$(Platform).pubxml + enable + enable + true + true + 10.0.22621.0 + x64 + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Always + + + MSBuild:Compile + + + MSBuild:Compile + + + MSBuild:Compile + + + MSBuild:Compile + + + MSBuild:Compile + + + MSBuild:Compile + + + MSBuild:Compile + + + + + + + + + + true + + + + none + + + + none + + + + none + + + + none + + + + none + + + + none + + diff --git a/The Untamed Music Player/Usings.cs b/The Untamed Music Player/Usings.cs new file mode 100644 index 0000000..4cc487e --- /dev/null +++ b/The Untamed Music Player/Usings.cs @@ -0,0 +1 @@ +global using WinUIEx; diff --git a/The Untamed Music Player/ViewModels/RootPlayBarViewModel.cs b/The Untamed Music Player/ViewModels/RootPlayBarViewModel.cs new file mode 100644 index 0000000..96960e4 --- /dev/null +++ b/The Untamed Music Player/ViewModels/RootPlayBarViewModel.cs @@ -0,0 +1,248 @@ +using System.ComponentModel; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media.Animation; +using The_Untamed_Music_Player.Models; +using The_Untamed_Music_Player.Views; + +namespace The_Untamed_Music_Player.ViewModels; +public partial class RootPlayBarViewModel : INotifyPropertyChanged +{ + public static RootPlayBarView? RootPlayBarView; + private Visibility _buttonVisibility = Visibility.Collapsed; + public Visibility ButtonVisibility + { + get => _buttonVisibility; + set + { + _buttonVisibility = value; + OnPropertyChanged(nameof(ButtonVisibility)); + } + } + + private bool _availability = false; + public bool Availability + { + get => _availability; + set + { + _availability = value; + OnPropertyChanged(nameof(Availability)); + } + } + + public event PropertyChangedEventHandler? PropertyChanged; + public void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + public RootPlayBarViewModel() + { + Data.RootPlayBarViewModel = this; + RootPlayBarView?.GetProgressSlider().AddHandler(UIElement.PointerPressedEvent, new PointerEventHandler(Data.MusicPlayer.ProgressLock), true); + RootPlayBarView?.GetProgressSlider().AddHandler(UIElement.PointerMovedEvent, new PointerEventHandler(Data.MusicPlayer.SliderUpdate), true); + RootPlayBarView?.GetProgressSlider().AddHandler(UIElement.PointerReleasedEvent, new PointerEventHandler(Data.MusicPlayer.ProgressUpdate), true); + } + + public string GetCurrent(TimeSpan current) + { + if (current.Hours > 0) + { + return $"{current:hh\\:mm\\:ss}"; + } + else + { + return $"0:{current:mm\\:ss}"; + } + } + + public string GetRemaining(TimeSpan current, TimeSpan total) + { + var remaining = total - current; + if (remaining.Hours > 0) + { + return $"{remaining:hh\\:mm\\:ss}"; + } + else + { + return $"0:{remaining:mm\\:ss}"; + } + } + + public string GetPlayPauseIcon(int playstate) + { + return playstate switch + { + 0 => "\uF5B0", + 1 => "\uF8AE", + 2 => "\uF5B0", + _ => "\uF5B0", + }; + } + + public Visibility GetSliderVisibility(int playstate) + { + return playstate switch + { + 0 => Visibility.Visible, + 1 => Visibility.Visible, + 2 => Visibility.Collapsed, + _ => Visibility.Visible, + }; + } + + public Visibility GetProgressVisibility(int playstate) + { + return playstate switch + { + 0 => Visibility.Collapsed, + 1 => Visibility.Collapsed, + 2 => Visibility.Visible, + _ => Visibility.Collapsed, + }; + } + + public Visibility GetArtistAndAlbumStrVisibility(DetailedMusicInfo detailedmusicinfo) + { + return detailedmusicinfo.ArtistAndAlbumStr == "" ? Visibility.Collapsed : Visibility.Visible; + } + + + public Visibility GetShuffleModeIcon(bool shufflemode) + { + return shufflemode ? Visibility.Collapsed : Visibility.Visible; + } + + public string GetRepeatModeIcon(int repeatmode) + { + return repeatmode switch + { + 0 => "\uF5E7", + 1 => "\uE8EE", + 2 => "\uE8ED", + _ => "\uF5E7", + }; + } + + public string GetVolumeIcon(double volume) + { + if (volume >= 67) + { + return "\uE995"; + } + else if (volume >= 34) + { + return "\uE994"; + } + else if (volume >= 1) + { + return "\uE993"; + } + else + { + return "\uE74F"; + } + } + + public void CoverBtnClickToDetail(object sender, RoutedEventArgs e) + { + if (!Data.IsDetail) + { + if (Data.MainWindow != null) + { + var newPage = new 歌词Page(); + var frame = Data.MainWindow.GetShellFrame(); + + // 创建渐变动画 + var fadeOutAnimation = new DoubleAnimation + { + From = 1.0, + To = 0, + Duration = new Duration(TimeSpan.FromSeconds(0.1)) + }; + + var fadeInAnimation = new DoubleAnimation + { + From = 0, + To = 1.0, + Duration = new Duration(TimeSpan.FromSeconds(0.2)) + }; + + var fadeOutStoryboard = new Storyboard(); + fadeOutStoryboard.Children.Add(fadeOutAnimation); + Storyboard.SetTarget(fadeOutAnimation, frame); + Storyboard.SetTargetProperty(fadeOutAnimation, "Opacity"); + + var fadeInStoryboard = new Storyboard(); + fadeInStoryboard.Children.Add(fadeInAnimation); + Storyboard.SetTarget(fadeInAnimation, frame); + Storyboard.SetTargetProperty(fadeInAnimation, "Opacity"); + + // 动画完成后设置新内容 + fadeOutAnimation.Completed += (s, a) => + { + fadeInStoryboard.Begin(); + frame.Content = newPage; + }; + + fadeOutStoryboard.Begin(); + + if (RootPlayBarView != null) + { + RootPlayBarView.GetCoverBorder().Visibility = Visibility.Collapsed; + } + Data.IsDetail = true; + } + } + else + { + if (Data.MainWindow != null) + { + var mainPage = Data.ShellPage; + var frame = Data.MainWindow.GetShellFrame(); + + // 创建渐变动画 + var fadeOutAnimation = new DoubleAnimation + { + From = 1.0, + To = 0, + Duration = new Duration(TimeSpan.FromSeconds(0.1)) + }; + + var fadeInAnimation = new DoubleAnimation + { + From = 0, + To = 1.0, + Duration = new Duration(TimeSpan.FromSeconds(0.2)) + }; + + var fadeOutStoryboard = new Storyboard(); + fadeOutStoryboard.Children.Add(fadeOutAnimation); + Storyboard.SetTarget(fadeOutAnimation, frame); + Storyboard.SetTargetProperty(fadeOutAnimation, "Opacity"); + + var fadeInStoryboard = new Storyboard(); + fadeInStoryboard.Children.Add(fadeInAnimation); + Storyboard.SetTarget(fadeInAnimation, frame); + Storyboard.SetTargetProperty(fadeInAnimation, "Opacity"); + + // 动画完成后设置新内容 + fadeOutAnimation.Completed += (s, a) => + { + fadeInStoryboard.Begin(); + frame.Content = mainPage; + }; + + fadeOutStoryboard.Begin(); + + if (RootPlayBarView != null) + { + RootPlayBarView.GetCoverBorder().Visibility = Visibility.Visible; + } + Data.IsDetail = false; + GC.Collect(); + } + } + } +} diff --git a/The Untamed Music Player/ViewModels/SettingsViewModel.cs b/The Untamed Music Player/ViewModels/SettingsViewModel.cs new file mode 100644 index 0000000..f9924b2 --- /dev/null +++ b/The Untamed Music Player/ViewModels/SettingsViewModel.cs @@ -0,0 +1,390 @@ +using System.ComponentModel; +using System.Reflection; +using System.Windows.Input; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Microsoft.Windows.ApplicationModel.Resources; +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Helpers; +using The_Untamed_Music_Player.Models; +using Windows.ApplicationModel; +using Windows.Storage; +using Windows.Storage.Pickers; + +namespace The_Untamed_Music_Player.ViewModels; + +public partial class SettingsViewModel : ObservableRecipient, INotifyPropertyChanged +{ + private readonly IThemeSelectorService _themeSelectorService; + private readonly ILocalSettingsService _localSettingsService; + private static readonly ResourceLoader _resourceLoader = new(); + public new event PropertyChangedEventHandler? PropertyChanged; + + protected new void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + [ObservableProperty] + public ElementTheme _elementTheme; + + [ObservableProperty] + private string _versionDescription; + + public ICommand SwitchThemeCommand + { + get; + } + + private bool _isProgressRingActive; + public bool IsProgressRingActive + { + get => _isProgressRingActive; + set + { + SetProperty(ref _isProgressRingActive, value); + OnPropertyChanged(nameof(IsProgressRingActive)); + } + } + + private bool _isRefreshButtonEnabled = true; + public bool IsRefreshButtonEnabled + { + get => _isRefreshButtonEnabled; + set + { + SetProperty(ref _isRefreshButtonEnabled, value); + OnPropertyChanged(nameof(IsRefreshButtonEnabled)); + } + } + + public Visibility EmptyFolderMessageVisibility => Data.MusicLibrary.Folders?.Count > 0 ? Visibility.Collapsed : Visibility.Visible; + + private List _fonts = []; + public List Fonts + { + get => _fonts; + set => _fonts = value; + } + + private FontFamily _selectedFont = new("Microsoft YaHei"); + public FontFamily SelectedFont + { + get => _selectedFont; + set + { + _selectedFont = value; + OnPropertyChanged(nameof(SelectedFont)); + SaveSelectedFontAsync(value.Source); // 保存字体设置 + } + } + + private List _materials = + [ + "None", + "Mica", + "Mica Alt", + "Desktop Acrylic", + "Acrylic Base", + "Acrylic Thin", + "Blur", + "Transparent", + "Animated" + ]; + public List Materials + { + get => _materials; + set => _materials = value; + } + + private string _selectedMaterial = Data.MainWindow?.SelectedMaterial ?? ""; + public string SelectedMaterial + { + get => _selectedMaterial; + set + { + _selectedMaterial = value; + OnPropertyChanged(nameof(SelectedMaterial)); + ChangeMaterial(SelectedMaterial); + SaveSelectedMaterialAsync(value); + } + } + + private bool _isLyricBackgroundVisible; + public bool IsLyricBackgroundVisible + { + get => _isLyricBackgroundVisible; + set + { + _isLyricBackgroundVisible = value; + OnPropertyChanged(nameof(IsLyricBackgroundVisible)); + SaveLyricBackgroundVisibilityAsync(value); + } + } + + public SettingsViewModel(IThemeSelectorService themeSelectorService, ILocalSettingsService localSettingsService) + { + _themeSelectorService = themeSelectorService; + _localSettingsService = localSettingsService; + _elementTheme = _themeSelectorService.Theme; + _versionDescription = GetVersionDescription(); + + SwitchThemeCommand = new RelayCommand( + async (param) => + { + if (ElementTheme != param) + { + ElementTheme = param; + await _themeSelectorService.SetThemeAsync(param); + } + }); + + LoadFonts(); + LoadSelectedFontAsync(); + LoadLyricBackgroundVisibilityAsync(); + Data.SettingsViewModel = this; + } + + public async void PickMusicFolderButton_Click(object sender, RoutedEventArgs e) + { + var openPicker = new FolderPicker(); + + var window = App.MainWindow; + + var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window); + + WinRT.Interop.InitializeWithWindow.Initialize(openPicker, hWnd); + + openPicker.SuggestedStartLocation = PickerLocationId.Desktop; + openPicker.FileTypeFilter.Add("*"); + + var folder = await openPicker.PickSingleFolderAsync(); + if (folder != null) + { + if (!Data.MusicLibrary.Folders.Any(f => f.Path == folder.Path)) + { + Data.MusicLibrary.Folders.Add(folder); + OnPropertyChanged(nameof(EmptyFolderMessageVisibility)); + await SaveFoldersAsync(); + await Data.MusicLibrary.LoadLibraryAgain(); // 重新加载音乐库 + } + } + } + + public void RemoveMusicFolderButtonClick(object sender, RoutedEventArgs e) + { + if (sender is Button button && button.DataContext is StorageFolder folder) + { + RemoveMusicFolder(folder); + } + } + + private async void RemoveMusicFolder(StorageFolder folder) + { + Data.MusicLibrary.Folders?.Remove(folder); + OnPropertyChanged(nameof(EmptyFolderMessageVisibility)); + await SaveFoldersAsync(); + await Data.MusicLibrary.LoadLibraryAgain(); + } + + public async void RefreshButton_Click(object sender, RoutedEventArgs e) + { + IsProgressRingActive = true; + IsRefreshButtonEnabled = false; + await Data.MusicLibrary.LoadLibraryAgain(); + IsProgressRingActive = false; + IsRefreshButtonEnabled = true; + } + + public void LoadFonts() + { + var fontFamilies = Microsoft.Graphics.Canvas.Text.CanvasTextFormat.GetSystemFontFamilies(); + Fonts = [.. fontFamilies.OrderBy(f => f)]; + } + + public void FontComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (e.AddedItems.Count > 0 && e.AddedItems[0] is string selectedFont) + { + SelectedFont = new FontFamily(selectedFont); + } + } + + public void MaterialComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (e.AddedItems.Count > 0 && e.AddedItems[0] is string selectedMaterial) + { + SelectedMaterial = selectedMaterial; + if (Data.MainWindow != null) + { + Data.MainWindow.SelectedMaterial = selectedMaterial; + } + } + } + + public void ChangeMaterial(string material) + { + if (Data.MainWindow?.SelectedMaterial == SelectedMaterial) + { + return; + } + try + { + switch (material) + { + case "None": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => Data.MainWindow?.TrySetNoneBackdrop()); + break; + case "Mica": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + Data.MainWindow?.TrySetNoneBackdrop(); + Data.MainWindow?.TrySetMicaBackdrop(false); + }); + break; + case "Mica Alt": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + Data.MainWindow?.TrySetNoneBackdrop(); + Data.MainWindow?.TrySetMicaBackdrop(true); + }); + break; + case "Desktop Acrylic": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + Data.MainWindow?.TrySetNoneBackdrop(); + Data.MainWindow?.TrySetDesktopAcrylicBackdrop(); + }); + break; + case "Acrylic Base": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + Data.MainWindow?.TrySetNoneBackdrop(); + Data.MainWindow?.TrySetAcrylicBackdrop(false); + }); + break; + case "Acrylic Thin": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + Data.MainWindow?.TrySetNoneBackdrop(); + Data.MainWindow?.TrySetAcrylicBackdrop(true); + }); + break; + case "Blur": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + Data.MainWindow?.TrySetNoneBackdrop(); + Data.MainWindow?.TrySetBlurBackdrop(); + }); + break; + case "Transparent": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + Data.MainWindow?.TrySetNoneBackdrop(); + Data.MainWindow?.TrySetTransparentBackdrop(); + }); + break; + case "Animated": + Data.MainWindow?.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.High, () => + { + Data.MainWindow?.TrySetNoneBackdrop(); + Data.MainWindow?.TrySetAnimatedBackdrop(); + }); + break; + default: + break; + } + } + catch { } + } + + private static string GetVersionDescription() + { + Version version; + + if (RuntimeHelper.IsMSIX) + { + var packageVersion = Package.Current.Id.Version; + + version = new(packageVersion.Major, packageVersion.Minor, packageVersion.Build, packageVersion.Revision); + } + else + { + version = Assembly.GetExecutingAssembly().GetName().Version!; + } + + return $"{"AppDisplayName".GetLocalized()} - {version.Major}.{version.Minor}.{version.Build}.{version.Revision}"; + } + + private static async Task SaveFoldersAsync() + { + var folderPaths = Data.MusicLibrary.Folders?.Select(f => f.Path).ToList();//Folders.Select(f => f.Path):使用 LINQ 查询从 Folders 集合中提取每个 StorageFolder 的路径(Path 属性)。.ToList():将提取的路径集合转换为 List。 + await ApplicationData.Current.LocalFolder.SaveAsync("MusicFolders", folderPaths);// ApplicationData.Current.LocalFolder:获取应用程序的本地存储文件夹。SaveAsync("MusicFolders", folderPaths):调用 SettingsStorageExtensions 类中的扩展方法 SaveAsync,将 folderPaths 列表保存到名为 "MusicFolders" 的文件中。 + } + + private async void LoadSelectedFontAsync() + { + var fontName = await _localSettingsService.ReadSettingAsync("SelectedFont"); + if (!string.IsNullOrEmpty(fontName)) + { + SelectedFont = new FontFamily(fontName); + } + } + + private async void LoadLyricBackgroundVisibilityAsync() + { + var isLyricBackgroundVisible = await _localSettingsService.ReadSettingAsync("IsLyricBackgroundVisible"); + IsLyricBackgroundVisible = isLyricBackgroundVisible; + } + + public void FontComboBox_Loaded(object sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + var selectedFontName = SelectedFont.Source; + var index = Fonts.IndexOf(selectedFontName); + if (index >= 0) + { + comboBox.SelectedIndex = index; + } + } + } + + public void MaterialComboBox_Loaded(object sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + var index = Materials.IndexOf(SelectedMaterial); + if (index >= 0) + { + comboBox.SelectedIndex = index; + } + } + } + + public void LyricBackgroundCheckBox_Loaded(object sender, RoutedEventArgs e) + { + if (sender is ToggleSwitch toggleSwitch) + { + toggleSwitch.IsOn = IsLyricBackgroundVisible; + } + } + + private async void SaveSelectedFontAsync(string fontName) + { + await _localSettingsService.SaveSettingAsync("SelectedFont", fontName); + } + + private async void SaveSelectedMaterialAsync(string material) + { + await _localSettingsService.SaveSettingAsync("SelectedMaterial", material); + } + + private async void SaveLyricBackgroundVisibilityAsync(bool isLyricBackgroundVisible) + { + await _localSettingsService.SaveSettingAsync("IsLyricBackgroundVisible", isLyricBackgroundVisible); + } +} diff --git a/The Untamed Music Player/ViewModels/ShellViewModel.cs b/The Untamed Music Player/ViewModels/ShellViewModel.cs new file mode 100644 index 0000000..8d72c66 --- /dev/null +++ b/The Untamed Music Player/ViewModels/ShellViewModel.cs @@ -0,0 +1,51 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +using Microsoft.UI.Xaml.Navigation; + +using The_Untamed_Music_Player.Contracts.Services; +using The_Untamed_Music_Player.Views; + +namespace The_Untamed_Music_Player.ViewModels; + +public partial class ShellViewModel : ObservableRecipient +{ + [ObservableProperty] + private bool isBackEnabled; + + [ObservableProperty] + private object? selected; + + public INavigationService NavigationService + { + get; + } + + public INavigationViewService NavigationViewService + { + get; + } + + public ShellViewModel(INavigationService navigationService, INavigationViewService navigationViewService) + { + NavigationService = navigationService; + NavigationService.Navigated += OnNavigated; + NavigationViewService = navigationViewService; + } + + private void OnNavigated(object sender, NavigationEventArgs e) + { + IsBackEnabled = NavigationService.CanGoBack; + + if (e.SourcePageType == typeof(SettingsPage)) + { + Selected = NavigationViewService.SettingsItem; + return; + } + + var selectedItem = NavigationViewService.GetSelectedItem(e.SourcePageType); + if (selectedItem != null) + { + Selected = selectedItem; + } + } +} diff --git a/The Untamed Music Player/ViewModels/专辑ViewModel.cs b/The Untamed Music Player/ViewModels/专辑ViewModel.cs new file mode 100644 index 0000000..73ceac0 --- /dev/null +++ b/The Untamed Music Player/ViewModels/专辑ViewModel.cs @@ -0,0 +1,8 @@ +namespace The_Untamed_Music_Player.ViewModels; + +public class 专辑ViewModel +{ + public 专辑ViewModel() + { + } +} diff --git a/The Untamed Music Player/ViewModels/主页ViewModel.cs b/The Untamed Music Player/ViewModels/主页ViewModel.cs new file mode 100644 index 0000000..b5eb3d4 --- /dev/null +++ b/The Untamed Music Player/ViewModels/主页ViewModel.cs @@ -0,0 +1,10 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace The_Untamed_Music_Player.ViewModels; + +public partial class 主页ViewModel : ObservableRecipient +{ + public 主页ViewModel() + { + } +} diff --git a/The Untamed Music Player/ViewModels/播放列表ViewModel.cs b/The Untamed Music Player/ViewModels/播放列表ViewModel.cs new file mode 100644 index 0000000..8efd4a3 --- /dev/null +++ b/The Untamed Music Player/ViewModels/播放列表ViewModel.cs @@ -0,0 +1,10 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace The_Untamed_Music_Player.ViewModels; + +public partial class 播放列表ViewModel : ObservableRecipient +{ + public 播放列表ViewModel() + { + } +} diff --git a/The Untamed Music Player/ViewModels/播放队列ViewModel.cs b/The Untamed Music Player/ViewModels/播放队列ViewModel.cs new file mode 100644 index 0000000..2b18876 --- /dev/null +++ b/The Untamed Music Player/ViewModels/播放队列ViewModel.cs @@ -0,0 +1,75 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using The_Untamed_Music_Player.Models; + +namespace The_Untamed_Music_Player.ViewModels; + +public partial class 播放队列ViewModel : ObservableRecipient +{ + public 播放队列ViewModel() + { + } + + public void Grid_PointerEntered(object sender, PointerRoutedEventArgs e) + { + var grid = sender as Grid; + var checkBox = grid?.FindName("ItemCheckBox") as CheckBox; + var playButton = grid?.FindName("PlayButton") as Button; + var fontIcon = grid?.FindName("MusicFontIcon") as FontIcon; + if (checkBox != null) + { + checkBox.Visibility = Visibility.Visible; + } + if (playButton != null) + { + playButton.Visibility = Visibility.Visible; + } + if (fontIcon != null) + { + fontIcon.Visibility = Visibility.Collapsed; + } + } + + public void Grid_PointerExited(object sender, PointerRoutedEventArgs e) + { + var grid = sender as Grid; + var checkBox = grid?.FindName("ItemCheckBox") as CheckBox; + var playButton = grid?.FindName("PlayButton") as Button; + var fontIcon = grid?.FindName("MusicFontIcon") as FontIcon; + if (checkBox != null) + { + checkBox.Visibility = Visibility.Collapsed; + } + if (playButton != null) + { + playButton.Visibility = Visibility.Collapsed; + } + if (fontIcon != null) + { + fontIcon.Visibility = Visibility.Visible; + } + } + + public void PlayQueueListView_ItemClick(object sender, ItemClickEventArgs e) + { + if (e.ClickedItem is BriefMusicInfo briefMusicInfo) + { + Data.MusicPlayer.PlaySongByPath(briefMusicInfo.Path); + } + } + + public void PlayButton_Click(object sender, RoutedEventArgs e) + { + if (sender is Button button && button.DataContext is BriefMusicInfo briefMusicInfo) + { + Data.MusicPlayer.PlaySongByPath(briefMusicInfo.Path); + } + } + + public void ClearButton_Click(object sender, RoutedEventArgs e) + { + Data.MusicPlayer.ClearPlayQueue(); + } +} diff --git a/The Untamed Music Player/ViewModels/无音乐ViewModel.cs b/The Untamed Music Player/ViewModels/无音乐ViewModel.cs new file mode 100644 index 0000000..67cd78d --- /dev/null +++ b/The Untamed Music Player/ViewModels/无音乐ViewModel.cs @@ -0,0 +1,7 @@ +namespace The_Untamed_Music_Player.ViewModels; +public class 无音乐ViewModel +{ + public 无音乐ViewModel() + { + } +} diff --git a/The Untamed Music Player/ViewModels/有音乐ViewModel.cs b/The Untamed Music Player/ViewModels/有音乐ViewModel.cs new file mode 100644 index 0000000..e334559 --- /dev/null +++ b/The Untamed Music Player/ViewModels/有音乐ViewModel.cs @@ -0,0 +1,8 @@ +namespace The_Untamed_Music_Player.ViewModels; + +public class 有音乐ViewModel +{ + public 有音乐ViewModel() + { + } +} diff --git a/The Untamed Music Player/ViewModels/歌曲ViewModel.cs b/The Untamed Music Player/ViewModels/歌曲ViewModel.cs new file mode 100644 index 0000000..2b4bb75 --- /dev/null +++ b/The Untamed Music Player/ViewModels/歌曲ViewModel.cs @@ -0,0 +1,75 @@ +using System.ComponentModel; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using The_Untamed_Music_Player.Models; + +namespace The_Untamed_Music_Player.ViewModels; + +public class 歌曲ViewModel : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + public void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + public 歌曲ViewModel() + { + Data.歌曲ViewModel = this; + } + + public void SongListView_ItemClick(object sender, ItemClickEventArgs e) + { + if (Data.MusicPlayer.PlayQueueName != "Songs:All" || Data.MusicPlayer.PlayQueue.Count != Data.MusicLibrary.Musics.Count) + { + Data.MusicPlayer.SetPlayList("Songs:All", Data.MusicLibrary.Musics); + } + if (e.ClickedItem is BriefMusicInfo briefMusicInfo) + { + Data.MusicPlayer.PlaySongByPath(briefMusicInfo.Path); + } + } + + public void PlayButton_Click(object sender, RoutedEventArgs e) + { + if (Data.MusicPlayer.PlayQueueName != "Songs:All" || Data.MusicPlayer.PlayQueue.Count != Data.MusicLibrary.Musics.Count) + { + Data.MusicPlayer.SetPlayList("Songs:All", Data.MusicLibrary.Musics); + } + if (sender is Button button && button.DataContext is BriefMusicInfo briefMusicInfo) + { + Data.MusicPlayer.PlaySongByPath(briefMusicInfo.Path); + } + } + + public void Grid_PointerEntered(object sender, PointerRoutedEventArgs e) + { + var grid = sender as Grid; + var checkBox = grid?.FindName("ItemCheckBox") as CheckBox; + var playButton = grid?.FindName("PlayButton") as Button; + if (checkBox != null) + { + checkBox.Visibility = Visibility.Visible; + } + if (playButton != null) + { + playButton.Visibility = Visibility.Visible; + } + } + + public void Grid_PointerExited(object sender, PointerRoutedEventArgs e) + { + var grid = sender as Grid; + var checkBox = grid?.FindName("ItemCheckBox") as CheckBox; + var playButton = grid?.FindName("PlayButton") as Button; + if (checkBox != null) + { + checkBox.Visibility = Visibility.Collapsed; + } + if (playButton != null) + { + playButton.Visibility = Visibility.Collapsed; + } + } +} diff --git a/The Untamed Music Player/ViewModels/歌词ViewModel.cs b/The Untamed Music Player/ViewModels/歌词ViewModel.cs new file mode 100644 index 0000000..c91c089 --- /dev/null +++ b/The Untamed Music Player/ViewModels/歌词ViewModel.cs @@ -0,0 +1,21 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using Microsoft.UI.Xaml.Controls; +using The_Untamed_Music_Player.Models; + +namespace The_Untamed_Music_Player.ViewModels; + +public partial class 歌词ViewModel : ObservableRecipient +{ + public 歌词ViewModel() + { + } + + public void ListView_ItemClick(object sender, ItemClickEventArgs e) + { + if (e.ClickedItem is LyricSlice lyricSlice) + { + var time = lyricSlice.Time; + Data.MusicPlayer.LyricProgressUpdate(time); + } + } +} diff --git a/The Untamed Music Player/ViewModels/艺术家ViewModel.cs b/The Untamed Music Player/ViewModels/艺术家ViewModel.cs new file mode 100644 index 0000000..e56375a --- /dev/null +++ b/The Untamed Music Player/ViewModels/艺术家ViewModel.cs @@ -0,0 +1,8 @@ +namespace The_Untamed_Music_Player.ViewModels; + +public class 艺术家ViewModel +{ + public 艺术家ViewModel() + { + } +} diff --git a/The Untamed Music Player/ViewModels/音乐库ViewModel.cs b/The Untamed Music Player/ViewModels/音乐库ViewModel.cs new file mode 100644 index 0000000..5e8a579 --- /dev/null +++ b/The Untamed Music Player/ViewModels/音乐库ViewModel.cs @@ -0,0 +1,10 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace The_Untamed_Music_Player.ViewModels; + +public partial class 音乐库ViewModel : ObservableRecipient +{ + public 音乐库ViewModel() + { + } +} diff --git a/The Untamed Music Player/Views/RootPlayBarView.xaml b/The Untamed Music Player/Views/RootPlayBarView.xaml new file mode 100644 index 0000000..375a4a9 --- /dev/null +++ b/The Untamed Music Player/Views/RootPlayBarView.xaml @@ -0,0 +1,375 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/RootPlayBarView.xaml.cs b/The Untamed Music Player/Views/RootPlayBarView.xaml.cs new file mode 100644 index 0000000..c276685 --- /dev/null +++ b/The Untamed Music Player/Views/RootPlayBarView.xaml.cs @@ -0,0 +1,31 @@ +using Microsoft.UI.Xaml.Controls; +using The_Untamed_Music_Player.Models; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + +public sealed partial class RootPlayBarView : Page +{ + public RootPlayBarViewModel ViewModel + { + get; + } + + public RootPlayBarView() + { + RootPlayBarViewModel.RootPlayBarView = this; + InitializeComponent(); + ViewModel = App.GetService(); + MusicPlayer.PlayBarUI = this; + DataContext = ViewModel; + } + + public Slider GetProgressSlider() + { + return ProgressSlider; + } + public Border GetCoverBorder() + { + return CoverBorder; + } +} diff --git a/The Untamed Music Player/Views/SettingsPage.xaml b/The Untamed Music Player/Views/SettingsPage.xaml new file mode 100644 index 0000000..dca5332 --- /dev/null +++ b/The Untamed Music Player/Views/SettingsPage.xaml @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/专辑Page.xaml.cs b/The Untamed Music Player/Views/专辑Page.xaml.cs new file mode 100644 index 0000000..cf3f7c4 --- /dev/null +++ b/The Untamed Music Player/Views/专辑Page.xaml.cs @@ -0,0 +1,18 @@ +using Microsoft.UI.Xaml.Controls; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + + +public sealed partial class 专辑Page : Page +{ + public 专辑ViewModel ViewModel + { + get; + } + public 专辑Page() + { + ViewModel = App.GetService<专辑ViewModel>(); + InitializeComponent(); + } +} diff --git a/The Untamed Music Player/Views/主页Page.xaml b/The Untamed Music Player/Views/主页Page.xaml new file mode 100644 index 0000000..a00da99 --- /dev/null +++ b/The Untamed Music Player/Views/主页Page.xaml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/主页Page.xaml.cs b/The Untamed Music Player/Views/主页Page.xaml.cs new file mode 100644 index 0000000..1209445 --- /dev/null +++ b/The Untamed Music Player/Views/主页Page.xaml.cs @@ -0,0 +1,19 @@ +using Microsoft.UI.Xaml.Controls; + +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + +public sealed partial class 主页Page : Page +{ + public 主页ViewModel ViewModel + { + get; + } + + public 主页Page() + { + ViewModel = App.GetService<主页ViewModel>(); + InitializeComponent(); + } +} diff --git a/The Untamed Music Player/Views/播放列表Page.xaml b/The Untamed Music Player/Views/播放列表Page.xaml new file mode 100644 index 0000000..a31ef14 --- /dev/null +++ b/The Untamed Music Player/Views/播放列表Page.xaml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/播放列表Page.xaml.cs b/The Untamed Music Player/Views/播放列表Page.xaml.cs new file mode 100644 index 0000000..5c4e75d --- /dev/null +++ b/The Untamed Music Player/Views/播放列表Page.xaml.cs @@ -0,0 +1,19 @@ +using Microsoft.UI.Xaml.Controls; + +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + +public sealed partial class 播放列表Page : Page +{ + public 播放列表ViewModel ViewModel + { + get; + } + + public 播放列表Page() + { + ViewModel = App.GetService<播放列表ViewModel>(); + InitializeComponent(); + } +} diff --git a/The Untamed Music Player/Views/播放队列Page.xaml b/The Untamed Music Player/Views/播放队列Page.xaml new file mode 100644 index 0000000..319b2b0 --- /dev/null +++ b/The Untamed Music Player/Views/播放队列Page.xaml @@ -0,0 +1,308 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/播放队列Page.xaml.cs b/The Untamed Music Player/Views/播放队列Page.xaml.cs new file mode 100644 index 0000000..867a5ae --- /dev/null +++ b/The Untamed Music Player/Views/播放队列Page.xaml.cs @@ -0,0 +1,34 @@ +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + +public sealed partial class 播放队列Page : Page +{ + public 播放队列ViewModel ViewModel + { + get; + } + + public 播放队列Page() + { + ViewModel = App.GetService<播放队列ViewModel>(); + InitializeComponent(); + } + + private void Grid_PointerEntered(object sender, PointerRoutedEventArgs e) + { + ViewModel.Grid_PointerEntered(sender, e); + } + + private void Grid_PointerExited(object sender, PointerRoutedEventArgs e) + { + ViewModel.Grid_PointerExited(sender, e); + } + + private void PlayButton_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) + { + ViewModel.PlayButton_Click(sender, e); + } +} diff --git a/The Untamed Music Player/Views/无音乐Page.xaml b/The Untamed Music Player/Views/无音乐Page.xaml new file mode 100644 index 0000000..9fd632d --- /dev/null +++ b/The Untamed Music Player/Views/无音乐Page.xaml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/无音乐Page.xaml.cs b/The Untamed Music Player/Views/无音乐Page.xaml.cs new file mode 100644 index 0000000..4b484a5 --- /dev/null +++ b/The Untamed Music Player/Views/无音乐Page.xaml.cs @@ -0,0 +1,20 @@ +using Microsoft.UI.Xaml.Controls; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + + +public sealed partial class 无音乐Page : Page +{ + private readonly SettingsViewModel SettingsViewModel; + public 无音乐ViewModel ViewModel + { + get; + } + public 无音乐Page() + { + ViewModel = App.GetService<无音乐ViewModel>(); + InitializeComponent(); + SettingsViewModel = App.GetService(); + } +} diff --git a/The Untamed Music Player/Views/有音乐Page.xaml b/The Untamed Music Player/Views/有音乐Page.xaml new file mode 100644 index 0000000..aafb482 --- /dev/null +++ b/The Untamed Music Player/Views/有音乐Page.xaml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/有音乐Page.xaml.cs b/The Untamed Music Player/Views/有音乐Page.xaml.cs new file mode 100644 index 0000000..49252c6 --- /dev/null +++ b/The Untamed Music Player/Views/有音乐Page.xaml.cs @@ -0,0 +1,39 @@ +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media.Animation; +using The_Untamed_Music_Player.ViewModels; + + +namespace The_Untamed_Music_Player.Views; + +public sealed partial class 有音乐Page : Page +{ + private readonly SettingsViewModel SettingsViewModel; + private int previousSelectedIndex = 0; + public 有音乐ViewModel ViewModel + { + get; + } + public 有音乐Page() + { + ViewModel = App.GetService<有音乐ViewModel>(); + InitializeComponent(); + SettingsViewModel = App.GetService(); + } + + private void SelectorBar_SelectionChanged(SelectorBar sender, SelectorBarSelectionChangedEventArgs args) + { + var selectedItem = sender.SelectedItem; + var currentSelectedIndex = sender.Items.IndexOf(selectedItem); + var pageType = currentSelectedIndex switch + { + 0 => typeof(歌曲Page), + 1 => typeof(专辑Page), + _ => typeof(艺术家Page), + }; + var slideNavigationTransitionEffect = currentSelectedIndex - previousSelectedIndex > 0 ? SlideNavigationTransitionEffect.FromRight : SlideNavigationTransitionEffect.FromLeft; + + SelectFrame.Navigate(pageType, null, new SlideNavigationTransitionInfo() { Effect = slideNavigationTransitionEffect }); + + previousSelectedIndex = currentSelectedIndex; + } +} diff --git a/The Untamed Music Player/Views/歌曲Page.xaml b/The Untamed Music Player/Views/歌曲Page.xaml new file mode 100644 index 0000000..58fe0fa --- /dev/null +++ b/The Untamed Music Player/Views/歌曲Page.xaml @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/歌曲Page.xaml.cs b/The Untamed Music Player/Views/歌曲Page.xaml.cs new file mode 100644 index 0000000..b3564ae --- /dev/null +++ b/The Untamed Music Player/Views/歌曲Page.xaml.cs @@ -0,0 +1,35 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + +public sealed partial class 歌曲Page : Page +{ + public 歌曲ViewModel ViewModel + { + get; + } + public 歌曲Page() + { + ViewModel = App.GetService<歌曲ViewModel>(); + InitializeComponent(); + //SongListView.ContainerContentChanging += SongListView_Loaded; + } + + private void Grid_PointerEntered(object sender, PointerRoutedEventArgs e) + { + ViewModel.Grid_PointerEntered(sender, e); + } + + private void Grid_PointerExited(object sender, PointerRoutedEventArgs e) + { + ViewModel.Grid_PointerExited(sender, e); + } + + private void PlayButton_Click(object sender, RoutedEventArgs e) + { + ViewModel.PlayButton_Click(sender, e); + } +} \ No newline at end of file diff --git a/The Untamed Music Player/Views/歌词Page.xaml b/The Untamed Music Player/Views/歌词Page.xaml new file mode 100644 index 0000000..5b69f1a --- /dev/null +++ b/The Untamed Music Player/Views/歌词Page.xaml @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/The Untamed Music Player/Views/艺术家Page.xaml.cs b/The Untamed Music Player/Views/艺术家Page.xaml.cs new file mode 100644 index 0000000..dc2f386 --- /dev/null +++ b/The Untamed Music Player/Views/艺术家Page.xaml.cs @@ -0,0 +1,17 @@ +using Microsoft.UI.Xaml.Controls; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + +public sealed partial class 艺术家Page : Page +{ + public 艺术家ViewModel ViewModel + { + get; + } + public 艺术家Page() + { + ViewModel = App.GetService<艺术家ViewModel>(); + InitializeComponent(); + } +} diff --git a/The Untamed Music Player/Views/音乐库Page.xaml b/The Untamed Music Player/Views/音乐库Page.xaml new file mode 100644 index 0000000..db084b5 --- /dev/null +++ b/The Untamed Music Player/Views/音乐库Page.xaml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/The Untamed Music Player/Views/音乐库Page.xaml.cs b/The Untamed Music Player/Views/音乐库Page.xaml.cs new file mode 100644 index 0000000..5c70bbf --- /dev/null +++ b/The Untamed Music Player/Views/音乐库Page.xaml.cs @@ -0,0 +1,41 @@ +using Microsoft.UI.Xaml.Controls; +using The_Untamed_Music_Player.Models; +using The_Untamed_Music_Player.ViewModels; + +namespace The_Untamed_Music_Player.Views; + +public sealed partial class 音乐库Page : Page +{ + public 音乐库ViewModel ViewModel + { + get; + } + + public 音乐库Page() + { + ViewModel = App.GetService<音乐库ViewModel>(); + InitializeComponent(); + Data.MusicLibrary.PropertyChanged += MusicLibrary_PropertyChanged; + UpdateContentFrame(); + } + + private void MusicLibrary_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(Data.MusicLibrary.HasMusics)) + { + UpdateContentFrame(); + } + } + + private void UpdateContentFrame() + { + if (Data.MusicLibrary.HasMusics) + { + ContentFrame.Navigate(typeof(有音乐Page)); + } + else + { + ContentFrame.Navigate(typeof(无音乐Page)); + } + } +} diff --git a/The Untamed Music Player/app.manifest b/The Untamed Music Player/app.manifest new file mode 100644 index 0000000..c1a6a80 --- /dev/null +++ b/The Untamed Music Player/app.manifest @@ -0,0 +1,15 @@ + + + + + + + + + + + true/PM + PerMonitorV2, PerMonitor + + + diff --git a/The Untamed Music Player/appsettings.json b/The Untamed Music Player/appsettings.json new file mode 100644 index 0000000..0d472b5 --- /dev/null +++ b/The Untamed Music Player/appsettings.json @@ -0,0 +1,6 @@ +{ + "LocalSettingsOptions": { + "ApplicationDataFolder": "The_Untamed_Music_Player/ApplicationData", + "LocalSettingsFile": "LocalSettings.json" + } +}