diff --git a/.github/actions/spelling/expect.txt b/.github/actions/spelling/expect.txt index 2750868b50..04411b1c7f 100644 --- a/.github/actions/spelling/expect.txt +++ b/.github/actions/spelling/expect.txt @@ -198,6 +198,7 @@ FOF FOLDERID FONTCHANGE FONTHASH +fontlayout FORPARSING foundfr fsanitize @@ -621,6 +622,7 @@ tcs tellp temppath testexampleinstaller +TESTFONT thiscouldbeapc THREADENTRY threehundred diff --git a/doc/release-notes/1.31/6619-font-installation-and-inventory.md b/doc/release-notes/1.31/6619-font-installation-and-inventory.md new file mode 100644 index 0000000000..716e5e07e9 --- /dev/null +++ b/doc/release-notes/1.31/6619-font-installation-and-inventory.md @@ -0,0 +1,9 @@ +## Bug Fixes + +### Minor Bug Fixes + +* Fixed font installation failures when different files in a package select the same collision-adjusted filename. +* Fixed installation, repair, and removal of fonts with filenames longer than 128 characters. +* Fixed font filename collisions exceeding the Windows filename length limit during installation and repair. +* Fixed malformed font package registrations preventing other packages or versions from appearing in detailed font listings. +* Improved font listing, package enumeration, and source indexing performance by reusing registry data and indexing filenames. diff --git a/src/AppInstallerCLICore/Workflows/FontFlow.cpp b/src/AppInstallerCLICore/Workflows/FontFlow.cpp index 199879164b..4a2fb6598a 100644 --- a/src/AppInstallerCLICore/Workflows/FontFlow.cpp +++ b/src/AppInstallerCLICore/Workflows/FontFlow.cpp @@ -300,6 +300,30 @@ namespace AppInstaller::CLI::Workflow } } + void FontRepairImpl(Execution::Context& context) + { + const auto& installedPackage = context.Get(); + Fonts::FontContext fontContext; + fontContext.InstallerSource = InstallerSource::WinGet; + fontContext.Scope = Manifest::ConvertToScopeEnum(installedPackage->GetMetadata()[Repository::PackageVersionMetadata::InstalledScope]); + fontContext.PackageId = ConvertToUTF16(installedPackage->GetProperty(Repository::PackageVersionProperty::Moniker)); + fontContext.PackageVersion = ConvertToUTF16(installedPackage->GetProperty(Repository::PackageVersionProperty::Version)); + + if (fontContext.Scope != Manifest::ScopeEnum::Machine) + { + AICLI_RETURN_IF_TERMINATED(context << EnsureNotRunningWithNonDefaultFullToken); + } + if (fontContext.Scope == Manifest::ScopeEnum::Machine && !Runtime::IsRunningAsAdmin()) + { + context.Reporter.Error() << Resource::String::CommandRequiresAdmin << std::endl; + AICLI_TERMINATE_CONTEXT(APPINSTALLER_CLI_ERROR_COMMAND_REQUIRES_ADMIN); + } + + context.Reporter.Info() << Resource::String::RepairFlowStartingPackageRepair << std::endl; + const auto result = Fonts::RepairFontPackage(fontContext); + context.Add(result.HResult); + } + void FontUninstallImpl(Execution::Context& context) { try diff --git a/src/AppInstallerCLICore/Workflows/FontFlow.h b/src/AppInstallerCLICore/Workflows/FontFlow.h index ede1cb8383..f33f55bbb3 100644 --- a/src/AppInstallerCLICore/Workflows/FontFlow.h +++ b/src/AppInstallerCLICore/Workflows/FontFlow.h @@ -23,6 +23,12 @@ namespace AppInstaller::CLI::Workflow // Outputs: None void FontInstallImpl(Execution::Context& context); + // Repairs the installed font package's files and registrations. + // Required Args: None + // Inputs: InstalledPackageVersion + // Outputs: OperationReturnCode + void FontRepairImpl(Execution::Context& context); + // Uninstalls the font package. // Checks both the selected package scope and the effective target scope before using installed data. // Required Args: None diff --git a/src/AppInstallerCLICore/Workflows/RepairFlow.cpp b/src/AppInstallerCLICore/Workflows/RepairFlow.cpp index 970d05bb3b..814a44fb6e 100644 --- a/src/AppInstallerCLICore/Workflows/RepairFlow.cpp +++ b/src/AppInstallerCLICore/Workflows/RepairFlow.cpp @@ -7,6 +7,7 @@ #include "Workflows/DownloadFlow.h" #include "Workflows/ArchiveFlow.h" #include "Workflows/InstallFlow.h" +#include "Workflows/FontFlow.h" #include "Workflows/PromptFlow.h" #include "winget/ManifestCommon.h" #include "AppInstallerDeployment.h" @@ -235,6 +236,7 @@ namespace AppInstaller::CLI::Workflow context.Add(repairCommand); } + // MSI, font, and non-Store MSIX repair use installed metadata without an available installer. bool IsInstallerMappingRequired(Execution::Context& context) { InstallerTypeEnum installerTypeEnum = GetInstalledType(context); @@ -242,6 +244,7 @@ namespace AppInstaller::CLI::Workflow switch (installerTypeEnum) { case InstallerTypeEnum::Msi: + case InstallerTypeEnum::Font: return false; case InstallerTypeEnum::Msix: // For MSIX packages that are from the Microsoft Store, selecting an installer is required. @@ -362,6 +365,13 @@ namespace AppInstaller::CLI::Workflow MSStoreRepair; } break; + case InstallerTypeEnum::Font: + { + context << + FontRepairImpl << + ReportRepairResult("Font", APPINSTALLER_CLI_ERROR_EXEC_REPAIR_FAILED, true); + } + break; case InstallerTypeEnum::Portable: default: THROW_HR(HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)); @@ -400,6 +410,12 @@ namespace AppInstaller::CLI::Workflow } break; case InstallerTypeEnum::MSStore: + case InstallerTypeEnum::Font: + break; + case InstallerTypeEnum::Zip: + THROW_HR_IF(HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED), + !context.Contains(Execution::Data::Installer) || + context.Get()->EffectiveInstallerType() != InstallerTypeEnum::Font); break; case InstallerTypeEnum::Portable: default: @@ -503,8 +519,6 @@ namespace AppInstaller::CLI::Workflow void SelectApplicableInstallerIfNecessary(Execution::Context& context) { - // For MSI installers, the platform provides built-in support for repair via msiexec, hence no need to select an installer. - // Similarly, for MSIX packages that are not from the Microsoft Store, selecting an installer is not required. if (IsInstallerMappingRequired(context)) { context << diff --git a/src/AppInstallerCLIE2ETests/FontCommand.cs b/src/AppInstallerCLIE2ETests/FontCommand.cs index bbf97013d8..fdc8ed3a1e 100644 --- a/src/AppInstallerCLIE2ETests/FontCommand.cs +++ b/src/AppInstallerCLIE2ETests/FontCommand.cs @@ -6,7 +6,9 @@ namespace AppInstallerCLIE2ETests { + using System.IO; using AppInstallerCLIE2ETests.Helpers; + using Microsoft.Win32; using NUnit.Framework; /// @@ -31,14 +33,19 @@ public void InstallFont_UserScope() { var fontPackageName = "AppInstallerTest.TestFont"; var fontPackageVersion = "1.0.0.0"; - var installResult = TestCommon.RunAICLICommand("install", fontPackageName); + var installResult = TestCommon.RunAICLICommand("install", $"{fontPackageName} --scope User"); Assert.That(installResult.ExitCode, Is.EqualTo(Constants.ErrorCode.S_OK)); - Assert.That(installResult.StdOut, Does.Contain("Successfully installed")); - TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, TestCommon.Scope.User); - - var uninstallResult = TestCommon.RunAICLICommand("uninstall", fontPackageName); - Assert.That(uninstallResult.ExitCode, Is.EqualTo(Constants.ErrorCode.S_OK)); - TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, TestCommon.Scope.User, false); + try + { + Assert.That(installResult.StdOut, Does.Contain("Successfully installed")); + TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, new[] { Constants.FontFileName }, TestCommon.Scope.User); + } + finally + { + var uninstallResult = TestCommon.RunAICLICommand("uninstall", $"{fontPackageName} --scope User"); + Assert.That(uninstallResult.ExitCode, Is.EqualTo(Constants.ErrorCode.S_OK)); + TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, new[] { Constants.FontFileName }, TestCommon.Scope.User, false); + } } /// @@ -52,11 +59,52 @@ public void InstallFont_MachineScope() var result = TestCommon.RunAICLICommand("install", $"{fontPackageName} --scope Machine"); Assert.That(result.ExitCode, Is.EqualTo(Constants.ErrorCode.S_OK)); Assert.That(result.StdOut, Does.Contain("Successfully installed")); - TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, TestCommon.Scope.Machine); + TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, new[] { Constants.FontFileName }, TestCommon.Scope.Machine); var uninstallResult = TestCommon.RunAICLICommand("uninstall", fontPackageName); Assert.That(uninstallResult.ExitCode, Is.EqualTo(Constants.ErrorCode.S_OK)); - TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, TestCommon.Scope.Machine, false); + TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, new[] { Constants.FontFileName }, TestCommon.Scope.Machine, false); + } + + /// + /// Test repair of a user font's discovery registration. + /// + [Test] + public void RepairFont_UserScope() + { + var fontPackageName = "AppInstallerTest.TestFont"; + var fontPackageVersion = "1.0.0.0"; + var installResult = TestCommon.RunAICLICommand("install", $"{fontPackageName} --scope User"); + Assert.That(installResult.ExitCode, Is.EqualTo(Constants.ErrorCode.S_OK)); + try + { + using (var fontsKey = Registry.CurrentUser.OpenSubKey(Constants.FontsSubKey, true)) + using (var packageKey = fontsKey.OpenSubKey( + $"Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\\{fontPackageName}\\{fontPackageVersion}")) + { + Assert.That(packageKey, Is.Not.Null); + var names = packageKey.GetValueNames(); + Assert.That(names, Is.Not.Empty); + foreach (var name in names) + { + var installedPath = packageKey.GetValue(name).ToString(); + var registrationName = Path.GetFileName(installedPath); + Assert.That(fontsKey.GetValue(registrationName), Is.EqualTo(installedPath)); + fontsKey.DeleteValue(registrationName); + } + } + + var repairResult = TestCommon.RunAICLICommand("repair", $"{fontPackageName} --scope User"); + Assert.That(repairResult.ExitCode, Is.EqualTo(Constants.ErrorCode.S_OK)); + Assert.That(repairResult.StdOut, Does.Contain("Repair operation completed successfully.")); + TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, new[] { Constants.FontFileName }, TestCommon.Scope.User); + } + finally + { + var uninstallResult = TestCommon.RunAICLICommand("uninstall", $"{fontPackageName} --scope User"); + Assert.That(uninstallResult.ExitCode, Is.EqualTo(Constants.ErrorCode.S_OK)); + TestCommon.VerifyFontPackage(fontPackageName, fontPackageVersion, new[] { Constants.FontFileName }, TestCommon.Scope.User, false); + } } /// diff --git a/src/AppInstallerCLIE2ETests/Helpers/TestCommon.cs b/src/AppInstallerCLIE2ETests/Helpers/TestCommon.cs index e6e9d4c78b..cc323371b1 100644 --- a/src/AppInstallerCLIE2ETests/Helpers/TestCommon.cs +++ b/src/AppInstallerCLIE2ETests/Helpers/TestCommon.cs @@ -376,58 +376,57 @@ public static string GetFontsDirectory(Scope scope) /// /// Name of the package. /// Name of the package version. + /// Original filenames of the package's fonts. /// Scope. /// If package should exist. public static void VerifyFontPackage( string packageName, string packageVersion, + IEnumerable expectedFileNames, Scope scope = Scope.User, bool shouldExist = true) { RegistryKey baseKey = (scope == Scope.Machine) ? Registry.LocalMachine : Registry.CurrentUser; var fileList = new List(); - using (RegistryKey fontsRegistryKey = baseKey.OpenSubKey(Constants.FontsSubKey, true)) + using (RegistryKey fontsRegistryKey = baseKey.OpenSubKey(Constants.FontsSubKey)) { - using var winGetRootKey = fontsRegistryKey.OpenSubKey("Microsoft.DesktopAppInstaller_8wekyb3d8bbwe"); - if (shouldExist) - { - Assert.That(winGetRootKey, Is.Not.Null); - } - else + if (!shouldExist) { + using var installedVersion = fontsRegistryKey?.OpenSubKey( + $"Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\\{packageName}\\{packageVersion}"); + Assert.That(installedVersion, Is.Null); return; } - using var packageNameSubkey = winGetRootKey.OpenSubKey(packageName); - if (shouldExist) - { - Assert.That(packageNameSubkey, Is.Not.Null); - } - - if (packageNameSubkey is not null) - { - using var versionSubkey = packageNameSubkey.OpenSubKey(packageVersion); + Assert.That(fontsRegistryKey, Is.Not.Null); + using var winGetRootKey = fontsRegistryKey.OpenSubKey("Microsoft.DesktopAppInstaller_8wekyb3d8bbwe"); + Assert.That(winGetRootKey, Is.Not.Null); - if (shouldExist) - { - Assert.That(versionSubkey, Is.Not.Null); - } - else - { - Assert.That(versionSubkey, Is.Null); - } + using var packageNameSubkey = winGetRootKey.OpenSubKey(packageName); + Assert.That(packageNameSubkey, Is.Not.Null); - if (versionSubkey is not null) - { - var valueNames = versionSubkey.GetValueNames(); - foreach (var valueName in valueNames) - { - fileList.Add(versionSubkey.GetValue(valueName).ToString()); - } + using var versionSubkey = packageNameSubkey.OpenSubKey(packageVersion); + Assert.That(versionSubkey, Is.Not.Null); - Assert.That(fileList.Count, Is.EqualTo(valueNames.Length)); - } + Assert.That(expectedFileNames, Is.Not.Empty); + var valueNames = versionSubkey.GetValueNames(); + Assert.That(valueNames, Is.EquivalentTo(expectedFileNames)); + foreach (var valueName in valueNames) + { + Assert.That(versionSubkey.GetValueKind(valueName), Is.EqualTo(RegistryValueKind.String)); + var installedPath = (string)versionSubkey.GetValue(valueName, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + Assert.That(installedPath, Is.Not.Null.And.Not.Empty); + Assert.That(Path.IsPathFullyQualified(installedPath), Is.True); + Assert.That(Path.GetDirectoryName(installedPath), Is.EqualTo(GetFontsDirectory(scope)).IgnoreCase); + fileList.Add(installedPath); + + var registrationName = Path.GetFileName(installedPath); + var expectedRegistration = scope == Scope.Machine ? registrationName : installedPath; + Assert.That( + fontsRegistryKey.GetValue(registrationName, null, RegistryValueOptions.DoNotExpandEnvironmentNames), + Is.EqualTo(expectedRegistration)); + Assert.That(fontsRegistryKey.GetValueKind(registrationName), Is.EqualTo(RegistryValueKind.String)); } } diff --git a/src/AppInstallerCLITests/Fonts.cpp b/src/AppInstallerCLITests/Fonts.cpp index a86731dab4..054515ca98 100644 --- a/src/AppInstallerCLITests/Fonts.cpp +++ b/src/AppInstallerCLITests/Fonts.cpp @@ -2,6 +2,7 @@ // Licensed under the MIT License. #include "pch.h" #include "TestCommon.h" +#include "TestHooks.h" #include #include #include @@ -15,6 +16,799 @@ constexpr std::string_view s_FontFile = "TestFont.ttf"; constexpr std::string_view s_FontFileTemp = "TestFont_temp.ttf"; constexpr std::string_view s_InvalidFontFile = "Installer-Good.msix"; +namespace +{ + constexpr std::wstring_view s_WinGetFontPrefix = L"Microsoft.DesktopAppInstaller_8wekyb3d8bbwe"; + + struct FontLayoutTest + { + FontLayoutTest() : + FontLayoutTest(AppInstaller::Registry::Key::OpenIfExists(HKEY_CURRENT_USER, std::wstring{}, 0, KEY_ALL_ACCESS)) + { + } + + explicit FontLayoutTest(AppInstaller::Registry::Key registryRoot) : + RegistryRoot(std::move(registryRoot)), + // Font registration keys require non-volatile ancestors. + RegistryPath(L"WinGetFontLayoutTests_" + Directory.GetPath().filename().wstring()), + RegistryHive(AppInstaller::Registry::Key::Create(RegistryRoot, RegistryPath)), + UserPath(AppInstaller::Runtime::GetPathDetailsFor(AppInstaller::Runtime::PathName::FontsUserInstallLocation)), + MachinePath(AppInstaller::Runtime::GetPathDetailsFor(AppInstaller::Runtime::PathName::FontsMachineInstallLocation)) + { + AppInstaller::Runtime::TestHook_SetPathOverride(AppInstaller::Runtime::PathName::FontsUserInstallLocation, RootPath(ScopeEnum::User)); + AppInstaller::Runtime::TestHook_SetPathOverride(AppInstaller::Runtime::PathName::FontsMachineInstallLocation, RootPath(ScopeEnum::Machine)); + TestHook_SetGetFontRegistryHive_Override([this](ScopeEnum scope) { return Hive(scope); }); + TestHook_SetFontSessionChangesDisabled(true); + } + + ~FontLayoutTest() + { + TestHook_SetGetFontRegistryHive_Override({}); + TestHook_SetFontSessionChangesDisabled(false); + TestHook_SetPackageFontFilesReadCallback({}); + TestHook_SetFontRegistrationsReadCallback({}); + AppInstaller::Runtime::TestHook_SetPathOverride(AppInstaller::Runtime::PathName::FontsUserInstallLocation, UserPath); + AppInstaller::Runtime::TestHook_SetPathOverride(AppInstaller::Runtime::PathName::FontsMachineInstallLocation, MachinePath); + AppInstaller::Registry::Key::DeleteTree(RegistryRoot, RegistryPath); + } + + std::filesystem::path RootPath(ScopeEnum scope) const + { + return Directory.GetPath() / AppInstaller::Manifest::ScopeToString(scope); + } + + AppInstaller::Registry::Key Hive(ScopeEnum scope) const + { + return AppInstaller::Registry::Key::Create(RegistryHive, AppInstaller::Utility::ConvertToUTF16(AppInstaller::Manifest::ScopeToString(scope))); + } + + AppInstaller::Registry::Key Root(ScopeEnum scope) const + { + return AppInstaller::Registry::Key::Create(Hive(scope), GetFontRegistryRoot()); + } + + FontContext Context(ScopeEnum scope) const + { + FontContext result; + result.Scope = scope; + result.InstallerSource = InstallerSource::WinGet; + result.PackageId = L"TestPackage"; + result.PackageVersion = L"1.0.0.0"; + return result; + } + + std::wstring PackagePath(const FontContext& context) const + { + return GetFontRegistryRoot() + L"\\" + std::wstring(s_WinGetFontPrefix) + L"\\" + context.PackageId + L"\\" + context.PackageVersion; + } + + AppInstaller::Registry::Key Package(const FontContext& context) const + { + return AppInstaller::Registry::Key::Create(Hive(context.Scope), PackagePath(context)); + } + + std::filesystem::path AddPackageDirectoryFont(const FontContext& context) + { + const auto path = RootPath(context.Scope) / s_WinGetFontPrefix / context.PackageId / context.PackageVersion / s_FontFile; + CopyFont(path); + Package(context).SetValue(L"Font title", path.wstring()); + return path; + } + + void CopyFont(const std::filesystem::path& path) const + { + std::filesystem::create_directories(path.parent_path()); + std::filesystem::copy_file(TestDataFile(s_FontFile).GetPath(), path); + } + + TestCommon::TempDirectory Directory{ "FontLayout" }; + AppInstaller::Registry::Key RegistryRoot; + std::wstring RegistryPath; + AppInstaller::Registry::Key RegistryHive; + AppInstaller::Filesystem::PathDetails UserPath; + AppInstaller::Filesystem::PathDetails MachinePath; + }; + + std::wstring RegistryString(const AppInstaller::Registry::Key& key, const std::wstring& name) + { + auto value = key[name]; + REQUIRE(value.has_value()); + REQUIRE(value->GetType() == AppInstaller::Registry::Value::Type::String); + return value->GetValue(); + } + + std::vector RegistryValueNames(const AppInstaller::Registry::Key& key) + { + std::vector result; + for (const auto& value : key.Values()) + { + result.push_back(value.Name()); + } + return result; + } + + std::filesystem::path ExtendedLengthPath(const std::filesystem::path& path) + { + return L"\\\\?\\" + path.wstring(); + } +} + +TEST_CASE("FontLayout_InstallWithVolatileSharedTestTree", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + const TempDirectory directory{ "FontRegistry" }; + const auto registryPath = directory.GetPath().filename().wstring(); + auto cleanup = wil::scope_exit([&]() + { + AppInstaller::Registry::Key::DeleteTree(HKEY_CURRENT_USER, registryPath); + }); + auto registryRoot = AppInstaller::Registry::Key::Create(HKEY_CURRENT_USER, registryPath); + AppInstaller::Registry::Key::Create(registryRoot, L"Software\\Microsoft\\WinGet", REG_OPTION_VOLATILE); + REQUIRE_THROWS_HR( + AppInstaller::Registry::Key::Create(registryRoot, L"Software\\Microsoft\\WinGet\\FontLayoutTests"), + HRESULT_FROM_WIN32(ERROR_CHILD_MUST_BE_VOLATILE)); + + FontLayoutTest layout{ std::move(registryRoot) }; + auto context = layout.Context(scope); + const auto source = layout.Directory.GetPath() / "Source" / s_FontFile; + const auto destination = layout.RootPath(scope) / s_FontFile; + layout.CopyFont(source); + context.AddPackageFile(source); + REQUIRE(InstallFontPackage(context).HResult == S_OK); + REQUIRE(RegistryString(layout.Package(context), L"TestFont.ttf") == destination.wstring()); + REQUIRE(RegistryString(layout.Root(scope), L"TestFont.ttf") == + (scope == ScopeEnum::Machine ? destination.filename().wstring() : destination.wstring())); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_InstallRepairAndUninstall", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + const auto otherScope = scope == ScopeEnum::User ? ScopeEnum::Machine : ScopeEnum::User; + auto context = Context(scope); + const auto source = Directory.GetPath() / "Source" / s_FontFile; + const auto destination = RootPath(scope) / s_FontFile; + const std::vector expectedNames{ std::string{ s_FontFile } }; + CopyFont(source); + context.AddPackageFile(source); + + REQUIRE(InstallFontPackage(context).HResult == S_OK); + REQUIRE(GetFontRegistryRoot() == L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"); + REQUIRE(std::filesystem::exists(destination)); + REQUIRE_FALSE(std::filesystem::exists(source)); + REQUIRE_FALSE(std::filesystem::exists(RootPath(scope) / s_WinGetFontPrefix)); + REQUIRE(RegistryValueNames(Package(context)) == expectedNames); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == destination.wstring()); + REQUIRE(RegistryValueNames(Root(scope)) == expectedNames); + REQUIRE(RegistryString(Root(scope), L"TestFont.ttf") == + (scope == ScopeEnum::Machine ? destination.filename().wstring() : destination.wstring())); + REQUIRE_FALSE(AppInstaller::Registry::Key::OpenIfExists(Hive(otherScope), GetFontRegistryRoot())); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::OK); + auto inventory = GetInstalledFontFiles(); + REQUIRE(inventory.size() == 1); + REQUIRE(inventory[0].InstallerSource == InstallerSource::WinGet); + REQUIRE(inventory[0].Scope == scope); + + Root(scope).DeleteValue(L"TestFont.ttf"); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::Corrupt); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(RegistryValueNames(Package(context)) == expectedNames); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == destination.wstring()); + REQUIRE(RegistryValueNames(Root(scope)) == expectedNames); + REQUIRE(RegistryString(Root(scope), L"TestFont.ttf") == + (scope == ScopeEnum::Machine ? destination.filename().wstring() : destination.wstring())); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::OK); + REQUIRE(GetInstalledFontFiles().size() == 1); + + const auto unrelated = RootPath(scope) / "Unrelated.ttf"; + CopyFont(unrelated); + Root(scope).SetValue(L"Unrelated.ttf", unrelated.wstring()); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(std::filesystem::exists(destination)); + REQUIRE_FALSE(Root(scope)[std::wstring{ L"TestFont.ttf" }].has_value()); + REQUIRE_FALSE(AppInstaller::Registry::Key::OpenIfExists(Hive(scope), PackagePath(context))); + REQUIRE(std::filesystem::exists(unrelated)); + REQUIRE(RegistryString(Root(scope), L"Unrelated.ttf") == unrelated.wstring()); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_FileAndRegistryCollisions", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + auto first = Context(scope); + const auto source = Directory.GetPath() / "Source" / s_FontFile; + CopyFont(source); + CopyFont(RootPath(scope) / s_FontFile); + Root(scope).SetValue(L"TestFont0.ttf", L"Unrelated.ttf"); + first.AddPackageFile(source); + REQUIRE(InstallFontPackage(first).HResult == S_OK); + const auto firstDestination = RootPath(scope) / "TestFont1.ttf"; + const std::vector expectedNames{ std::string{ s_FontFile } }; + REQUIRE(RegistryValueNames(Package(first)) == expectedNames); + REQUIRE(RegistryString(Package(first), L"TestFont.ttf") == firstDestination.wstring()); + REQUIRE(RegistryString(Root(scope), L"TestFont1.ttf") == + (scope == ScopeEnum::Machine ? firstDestination.filename().wstring() : firstDestination.wstring())); + REQUIRE(ValidateFontPackage(first).Status == FontStatus::OK); + + auto second = Context(scope); + second.PackageId = L"OtherPackage"; + const auto otherSource = Directory.GetPath() / "OtherSource" / s_FontFile; + CopyFont(otherSource); + second.AddPackageFile(otherSource); + REQUIRE(InstallFontPackage(second).HResult == S_OK); + const auto secondDestination = RootPath(scope) / "TestFont2.ttf"; + REQUIRE(RegistryValueNames(Package(second)) == expectedNames); + REQUIRE(RegistryString(Package(second), L"TestFont.ttf") == secondDestination.wstring()); + REQUIRE(RegistryString(Root(scope), L"TestFont2.ttf") == + (scope == ScopeEnum::Machine ? secondDestination.filename().wstring() : secondDestination.wstring())); + REQUIRE(UninstallFontPackage(first).HResult == S_OK); + REQUIRE_FALSE(Root(scope)[std::wstring{ L"TestFont1.ttf" }].has_value()); + REQUIRE_FALSE(AppInstaller::Registry::Key::OpenIfExists(Hive(scope), PackagePath(first))); + REQUIRE(std::filesystem::exists(secondDestination)); + REQUIRE(RegistryString(Root(scope), L"TestFont2.ttf") == + (scope == ScopeEnum::Machine ? secondDestination.filename().wstring() : secondDestination.wstring())); + REQUIRE(ValidateFontPackage(second).Status == FontStatus::OK); + REQUIRE(RegistryString(Root(scope), L"TestFont0.ttf") == L"Unrelated.ttf"); + REQUIRE(std::filesystem::exists(RootPath(scope) / s_FontFile)); + REQUIRE(UninstallFontPackage(second).HResult == S_OK); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_DistinctSourceNamesShareDestinationCandidate", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + auto context = Context(scope); + const auto existing = RootPath(scope) / s_FontFile; + const auto firstSource = Directory.GetPath() / "Source" / s_FontFile; + const auto secondSource = Directory.GetPath() / "Source" / "TestFont0.ttf"; + const auto firstDestination = RootPath(scope) / "TestFont0.ttf"; + const auto secondDestination = RootPath(scope) / "TestFont00.ttf"; + CopyFont(existing); + CopyFont(firstSource); + CopyFont(secondSource); + context.AddPackageFile(firstSource); + context.AddPackageFile(secondSource); + + REQUIRE(InstallFontPackage(context).HResult == S_OK); + REQUIRE(std::filesystem::exists(firstDestination)); + REQUIRE(std::filesystem::exists(secondDestination)); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == firstDestination.wstring()); + REQUIRE(RegistryString(Package(context), L"TestFont0.ttf") == secondDestination.wstring()); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::OK); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == firstDestination.wstring()); + REQUIRE(RegistryString(Package(context), L"TestFont0.ttf") == secondDestination.wstring()); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(std::filesystem::exists(firstDestination)); + REQUIRE_FALSE(std::filesystem::exists(secondDestination)); + REQUIRE(std::filesystem::exists(existing)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_LongFilenamesWithCollisions", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + const auto nameLength = GENERATE(size_t{ 128 }, size_t{ 129 }); + auto context = Context(scope); + const auto stem = std::string(nameLength - 4, 'f'); + const std::filesystem::path name = stem + ".ttf"; + const auto existing = RootPath(scope) / name; + const auto source = Directory.GetPath() / "Source" / name; + const auto destination = RootPath(scope) / (stem + "0.ttf"); + CopyFont(existing); + CopyFont(source); + context.AddPackageFile(source); + + REQUIRE(InstallFontPackage(context).HResult == S_OK); + REQUIRE(std::filesystem::exists(destination)); + REQUIRE(RegistryString(Package(context), name.wstring()) == destination.wstring()); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::OK); + Root(scope).DeleteValue(destination.filename().wstring()); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(RegistryString(Package(context), name.wstring()) == destination.wstring()); + REQUIRE(RegistryString(Root(scope), destination.filename().wstring()) == + (scope == ScopeEnum::Machine ? destination.filename().wstring() : destination.wstring())); + REQUIRE(GetInstalledFontFiles().size() == 1); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(std::filesystem::exists(destination)); + REQUIRE_FALSE(Root(scope)[destination.filename().wstring()].has_value()); + REQUIRE(std::filesystem::exists(existing)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_RejectsUnsafeFilenames", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + const std::string unsafeName = GENERATE("", "..\\Font.ttf", "NUL.ttf", "Font.ttf:stream", "Font.ttf. "); + const bool invalidPath = GENERATE(false, true); + auto context = Context(scope); + const auto installed = RootPath(scope) / s_FontFile; + CopyFont(installed); + const auto registryName = invalidPath ? std::wstring{ L"TestFont.ttf" } : AppInstaller::Utility::ConvertToUTF16(unsafeName); + const auto filePath = invalidPath ? RootPath(scope) / unsafeName : installed; + Package(context).SetValue(registryName, filePath.wstring()); + + REQUIRE(RepairFontPackage(context).HResult == APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED); + REQUIRE(UninstallFontPackage(context).HResult == APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED); + REQUIRE(RegistryString(Package(context), registryName) == filePath.wstring()); + REQUIRE(std::filesystem::exists(installed)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_MaximumFilenameCollisions", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + const bool supplementaryCharacter = GENERATE(false, true); + const int suffix = GENERATE(0, 10); + auto context = Context(scope); + // Extended-length paths isolate the filename component limit from MAX_PATH. + const auto root = ExtendedLengthPath(RootPath(scope)); + AppInstaller::Runtime::TestHook_SetPathOverride(scope == ScopeEnum::Machine ? + AppInstaller::Runtime::PathName::FontsMachineInstallLocation : AppInstaller::Runtime::PathName::FontsUserInstallLocation, root); + auto cleanup = wil::scope_exit([&]() { std::filesystem::remove_all(ExtendedLengthPath(Directory.GetPath())); }); + const auto stem = std::wstring(249, L'f') + (supplementaryCharacter ? L"\U0001F600" : L"ff"); + const std::filesystem::path name = stem + L".ttf"; + const auto source = ExtendedLengthPath(Directory.GetPath()) / "Source" / name; + const auto existing = root / name; + const auto destination = root / + (std::wstring(suffix == 0 && !supplementaryCharacter ? 250 : 249, L'f') + std::to_wstring(suffix) + L".ttf"); + REQUIRE(name.wstring().size() == 255); + CopyFont(source); + CopyFont(existing); + for (int i = 0; i < suffix; ++i) + { + Root(scope).SetValue(std::wstring(supplementaryCharacter ? 249 : 250, L'f') + std::to_wstring(i) + L".ttf", L"Unrelated.ttf"); + } + context.AddPackageFile(source); + + REQUIRE(InstallFontPackage(context).HResult == S_OK); + REQUIRE(std::filesystem::exists(destination)); + REQUIRE(RegistryString(Package(context), name.wstring()) == destination.wstring()); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::OK); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + const auto inventory = GetInstalledFontFiles(); + REQUIRE(inventory.size() == static_cast(suffix + 1)); + REQUIRE(std::count_if(inventory.begin(), inventory.end(), [&](const auto& font) + { + return font.InstallerSource == InstallerSource::WinGet && font.FilePath == destination && font.Status == FontStatus::OK; + }) == 1); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(std::filesystem::exists(destination)); + REQUIRE(std::filesystem::exists(existing)); + REQUIRE(RegistryValueNames(Root(scope)).size() == static_cast(suffix)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_RepairMigratesMaximumFilename", "[fonts][fontlayout]") +{ + auto context = Context(ScopeEnum::User); + const auto root = ExtendedLengthPath(RootPath(context.Scope)); + AppInstaller::Runtime::TestHook_SetPathOverride(AppInstaller::Runtime::PathName::FontsUserInstallLocation, root); + auto cleanup = wil::scope_exit([&]() { std::filesystem::remove_all(ExtendedLengthPath(Directory.GetPath())); }); + const std::filesystem::path name = std::wstring(251, L'f') + L".ttf"; + const auto source = root / s_WinGetFontPrefix / context.PackageId / context.PackageVersion / name; + const auto existing = root / name; + const auto destination = root / (std::wstring(250, L'f') + L"0.ttf"); + CopyFont(source); + CopyFont(existing); + Package(context).SetValue(L"Font title", source.wstring()); + Root(context.Scope).SetValue(L"Font title (TrueType)", source.wstring()); + + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(std::filesystem::exists(destination)); + REQUIRE_FALSE(std::filesystem::exists(source)); + REQUIRE_FALSE(Package(context)[std::wstring{ L"Font title" }].has_value()); + REQUIRE_FALSE(Root(context.Scope)[std::wstring{ L"Font title (TrueType)" }].has_value()); + REQUIRE(RegistryString(Package(context), name.wstring()) == destination.wstring()); + REQUIRE(RegistryString(Root(context.Scope), destination.filename().wstring()) == destination.wstring()); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(std::filesystem::exists(destination)); + REQUIRE(std::filesystem::exists(existing)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_InventoryReadsMappingsOncePerVersion", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + auto context = Context(scope); + for (const auto& version : { L"1.0", L"2.0" }) + { + context.PackageVersion = version; + for (int i = 0; i < 3; ++i) + { + const auto name = L"Font" + std::to_wstring(i) + L".ttf"; + const auto installed = RootPath(scope) / (context.PackageVersion + name); + CopyFont(installed); + Package(context).SetValue(name, installed.wstring()); + Root(scope).SetValue(installed.filename().wstring(), + scope == ScopeEnum::Machine ? installed.filename().wstring() : installed.wstring()); + } + } + + size_t mappingReads = 0; + size_t registrationReads = 0; + TestHook_SetPackageFontFilesReadCallback([&]() { ++mappingReads; }); + TestHook_SetFontRegistrationsReadCallback([&]() { ++registrationReads; }); + const auto inventory = GetInstalledFontFiles(); + REQUIRE(inventory.size() == 6); + REQUIRE(mappingReads == 2); + REQUIRE(registrationReads == 1); + for (const auto& font : inventory) + { + REQUIRE(font.InstallerSource == InstallerSource::WinGet); + REQUIRE(font.Status == FontStatus::OK); + REQUIRE(font.InstallPath == font.FilePath); + } + + mappingReads = 0; + registrationReads = 0; + const auto packages = GetInstalledFontPackages(scope); + REQUIRE(packages.size() == 2); + REQUIRE(mappingReads == 2); + REQUIRE(registrationReads == 1); + for (const auto& package : packages) + { + REQUIRE(package.Status == FontStatus::OK); + } + + const auto added = RootPath(scope) / L"Added.ttf"; + CopyFont(added); + Package(context).SetValue(L"Added.ttf", added.wstring()); + Root(scope).SetValue(L"Added.ttf", scope == ScopeEnum::Machine ? added.filename().wstring() : added.wstring()); + mappingReads = 0; + REQUIRE(GetInstalledFontFiles().size() == 7); + REQUIRE(mappingReads == 2); + + Root(scope).DeleteValue(L"1.0Font0.ttf"); + mappingReads = 0; + registrationReads = 0; + const auto changedPackages = GetInstalledFontPackages(scope); + REQUIRE(changedPackages.size() == 2); + REQUIRE(mappingReads == 2); + REQUIRE(registrationReads == 1); + REQUIRE(std::count_if(changedPackages.begin(), changedPackages.end(), [&](const auto& package) + { + return package.PackageVersion == L"1.0" && package.Status == FontStatus::Corrupt; + }) == 1); + + Package(context).SetValue(L"Invalid.ttf", DWORD{ 1 }); + mappingReads = 0; + registrationReads = 0; + const auto updatedPackages = GetInstalledFontPackages(scope); + REQUIRE(updatedPackages.size() == 2); + REQUIRE(mappingReads == 2); + REQUIRE(registrationReads == 1); + REQUIRE(std::count_if(updatedPackages.begin(), updatedPackages.end(), [&](const auto& package) + { + return package.PackageVersion == context.PackageVersion && package.Status == FontStatus::Unknown; + }) == 1); + REQUIRE(RepairFontPackage(context).HResult == APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED); + REQUIRE(UninstallFontPackage(context).HResult == APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_InventoryReadsRegistrationsOncePerScope", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + const auto fontCount = GENERATE(3, 10); + auto context = Context(scope); + for (int i = 0; i < fontCount; ++i) + { + const auto name = L"Font" + std::to_wstring(i) + L".ttf"; + const auto installed = RootPath(scope) / name; + CopyFont(installed); + Package(context).SetValue(name, installed.wstring()); + if (i % 2 == 0) + { + const auto registeredName = L"FONT" + std::to_wstring(i) + L".TTF"; + const auto registeredPath = scope == ScopeEnum::Machine ? + std::filesystem::path{ L"." } / registeredName : RootPath(scope) / L"." / registeredName; + Root(scope).SetValue(name, registeredPath.wstring()); + } + } + Root(scope).SetValue(L"Alias", (RootPath(scope) / L"FONT0.TTF").wstring()); + Root(scope).SetValue(L"Invalid", DWORD{ 1 }); + const auto external = RootPath(scope) / L"External.ttf"; + CopyFont(external); + Root(scope).SetValue(L"External font", scope == ScopeEnum::Machine ? external.filename().wstring() : external.wstring()); + const auto missing = RootPath(scope) / L"Missing.ttf"; + Root(scope).SetValue(L"Missing font", missing.wstring()); + + size_t registrationReads = 0; + TestHook_SetFontRegistrationsReadCallback([&]() { ++registrationReads; }); + const auto inventory = GetInstalledFontFiles(); + REQUIRE(registrationReads == 1); + REQUIRE(inventory.size() == static_cast(fontCount + 2)); + for (int i = 0; i < fontCount; ++i) + { + const auto installed = RootPath(scope) / (L"Font" + std::to_wstring(i) + L".ttf"); + REQUIRE(std::count_if(inventory.begin(), inventory.end(), [&](const auto& font) + { + return font.Scope == scope && font.InstallerSource == InstallerSource::WinGet && + font.FilePath == installed && font.InstallPath == installed && + font.Status == (i % 2 == 0 ? FontStatus::OK : FontStatus::Corrupt); + }) == 1); + } + REQUIRE(std::count_if(inventory.begin(), inventory.end(), [&](const auto& font) + { + return font.Scope == scope && font.InstallerSource == InstallerSource::Unknown && + font.FilePath == external && font.Title == L"External font" && font.Status == FontStatus::OK; + }) == 1); + REQUIRE(std::count_if(inventory.begin(), inventory.end(), [&](const auto& font) + { + return font.Scope == scope && font.InstallerSource == InstallerSource::Unknown && + font.FilePath == missing && font.Status == FontStatus::Corrupt; + }) == 1); + + const auto addedRegistration = RootPath(scope) / L"Font1.ttf"; + Root(scope).SetValue(L"Font1.ttf", addedRegistration.wstring()); + registrationReads = 0; + const auto updated = GetInstalledFontFiles(); + REQUIRE(registrationReads == 1); + REQUIRE(updated.size() == inventory.size()); + REQUIRE(std::count_if(updated.begin(), updated.end(), [&](const auto& font) + { + return font.Scope == scope && font.InstallerSource == InstallerSource::WinGet && + font.FilePath == addedRegistration && font.Status == FontStatus::OK; + }) == 1); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_InventoryContinuesAfterInvalidPackage", "[fonts][fontlayout]") +{ + const bool nonStringValue = GENERATE(false, true); + auto invalidContext = Context(ScopeEnum::Machine); + invalidContext.PackageId = L"InvalidPackage"; + const auto invalidPackageFont = RootPath(invalidContext.Scope) / "InvalidPackage.ttf"; + CopyFont(invalidPackageFont); + Package(invalidContext).SetValue(L"InvalidPackage.ttf", invalidPackageFont.wstring()); + if (nonStringValue) + { + Package(invalidContext).SetValue(L"Invalid.ttf", DWORD{ 1 }); + } + else + { + Package(invalidContext).SetValue(L"Invalid.ttf", (Directory.GetPath() / "Outside.ttf").wstring()); + } + + for (const auto scope : { ScopeEnum::Machine, ScopeEnum::User }) + { + auto context = Context(scope); + const auto installed = RootPath(scope) / s_FontFile; + CopyFont(installed); + Package(context).SetValue(L"TestFont.ttf", installed.wstring()); + Root(scope).SetValue(L"TestFont.ttf", + scope == ScopeEnum::Machine ? installed.filename().wstring() : installed.wstring()); + } + const auto external = RootPath(ScopeEnum::Machine) / "External.ttf"; + CopyFont(external); + Root(ScopeEnum::Machine).SetValue(L"External.ttf", external.filename().wstring()); + + const auto inventory = GetInstalledFontFiles(); + REQUIRE(inventory.size() == 3); + for (const auto scope : { ScopeEnum::Machine, ScopeEnum::User }) + { + REQUIRE(std::count_if(inventory.begin(), inventory.end(), [&](const auto& font) + { + return font.Scope == scope && font.PackageId == L"TestPackage" && + font.InstallerSource == InstallerSource::WinGet && + font.FilePath == RootPath(scope) / s_FontFile; + }) == 1); + } + REQUIRE(std::count_if(inventory.begin(), inventory.end(), [&](const auto& font) + { + return font.Scope == ScopeEnum::Machine && font.InstallerSource == InstallerSource::Unknown && + font.FilePath == external; + }) == 1); + REQUIRE(RepairFontPackage(invalidContext).HResult == APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED); + REQUIRE(UninstallFontPackage(invalidContext).HResult == APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED); + REQUIRE(std::filesystem::exists(invalidPackageFont)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_UnicodeCaseInsensitiveRegistrations", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + const auto names = GENERATE( + std::make_pair(L"\u03C3.ttf", L"\u03C2.TTF"), + std::make_pair(L"\u00E9.ttf", L"\u00C9.TTF")); + auto context = Context(scope); + const auto installed = RootPath(scope) / names.first; + const auto registered = RootPath(scope) / names.second; + CopyFont(installed); + Package(context).SetValue(installed.filename().wstring(), installed.wstring()); + Root(scope).SetValue(registered.filename().wstring(), + scope == ScopeEnum::Machine ? registered.filename().wstring() : registered.wstring()); + context.AddPackageFile(installed); + + const auto inventory = GetInstalledFontFiles(); + REQUIRE(inventory.size() == 1); + REQUIRE(inventory[0].InstallerSource == InstallerSource::WinGet); + REQUIRE(inventory[0].Status == FontStatus::OK); + const auto packages = GetInstalledFontPackages(scope); + REQUIRE(packages.size() == 1); + REQUIRE(packages[0].Status == FontStatus::OK); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::OK); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(Root(scope)[registered.filename().wstring()].has_value()); + REQUIRE_FALSE(std::filesystem::exists(installed)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_InventoryContinuesAfterInvalidVersion", "[fonts][fontlayout]") +{ + const bool nonStringValue = GENERATE(false, true); + auto invalidContext = Context(ScopeEnum::User); + invalidContext.PackageVersion = GENERATE(L"1.0", L"2.0"); + AddPackageDirectoryFont(invalidContext); + if (nonStringValue) + { + Package(invalidContext).SetValue(L"Invalid.ttf", DWORD{ 1 }); + } + else + { + Package(invalidContext).SetValue(L"Invalid.ttf", (Directory.GetPath() / "Outside.ttf").wstring()); + } + + auto context = Context(ScopeEnum::User); + context.PackageVersion = invalidContext.PackageVersion == L"1.0" ? L"2.0" : L"1.0"; + const auto installed = AddPackageDirectoryFont(context); + + const auto inventory = GetInstalledFontFiles(); + REQUIRE(inventory.size() == 1); + REQUIRE(inventory[0].PackageId == context.PackageId); + REQUIRE(inventory[0].PackageVersion == context.PackageVersion); + REQUIRE(inventory[0].Scope == context.Scope); + REQUIRE(inventory[0].InstallerSource == InstallerSource::WinGet); + REQUIRE(inventory[0].FilePath == installed); + REQUIRE(inventory[0].InstallPath == installed); + REQUIRE(inventory[0].Status == FontStatus::Corrupt); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_RepairMigratesPackageDirectory", "[fonts][fontlayout]") +{ + const bool keepDirectory = GENERATE(false, true); + auto context = Context(ScopeEnum::User); + const auto source = AddPackageDirectoryFont(context); + const auto sentinel = source.parent_path() / "keep.txt"; + if (keepDirectory) + { + std::ofstream{ sentinel } << "Keep this file"; + } + CopyFont(RootPath(context.Scope) / s_FontFile); + context.AddPackageFile(source); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::Corrupt); + const auto packages = GetInstalledFontPackages(context.Scope); + REQUIRE(packages.size() == 1); + REQUIRE(packages[0].Status == FontStatus::Corrupt); + + REQUIRE(RepairFontPackage(context).HResult == S_OK); + const auto destination = RootPath(context.Scope) / "TestFont0.ttf"; + REQUIRE(std::filesystem::exists(destination)); + REQUIRE_FALSE(std::filesystem::exists(source)); + REQUIRE(std::filesystem::exists(source.parent_path()) == keepDirectory); + REQUIRE_FALSE(Package(context)[std::wstring{ L"Font title" }].has_value()); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == destination.wstring()); + REQUIRE(RegistryString(Root(context.Scope), L"TestFont0.ttf") == destination.wstring()); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == destination.wstring()); + REQUIRE(GetInstalledFontFiles().size() == 1); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE(std::filesystem::exists(RootPath(context.Scope) / s_FontFile)); + REQUIRE(std::filesystem::exists(sentinel) == keepDirectory); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_InstalledPathTakesPrecedenceOverSourceName", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + auto context = Context(scope); + const auto first = RootPath(scope) / "TestFont0.ttf"; + const auto second = RootPath(scope) / "TestFont00.ttf"; + CopyFont(first); + CopyFont(second); + Package(context).SetValue(L"TestFont0.ttf", second.wstring()); + Package(context).SetValue(L"TestFont.ttf", first.wstring()); + REQUIRE(CreateFontFileInfo(context, first).InstallPath == first); + REQUIRE(CreateFontFileInfo(context, second).InstallPath == second); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_RejectsDuplicateSourceFilenames", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + const auto names = GENERATE( + std::make_pair(L"TestFont.ttf", L"TestFont.ttf"), + std::make_pair(L"TestFont.ttf", L"TESTFONT.TTF"), + std::make_pair(L"\u03C3.ttf", L"\u03C2.TTF"), + std::make_pair(L"\u00DF.ttf", L"ss.ttf")); + auto context = Context(scope); + const auto first = Directory.GetPath() / "First" / names.first; + const auto second = Directory.GetPath() / "Second" / names.second; + CopyFont(first); + CopyFont(second); + context.AddPackageFile(first); + context.AddPackageFile(second); + const auto validation = ValidateFontPackage(context); + REQUIRE(validation.Result == FontResult::Error); + REQUIRE(validation.HResult == APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED); + REQUIRE(std::filesystem::exists(first)); + REQUIRE(std::filesystem::exists(second)); + REQUIRE_FALSE(std::filesystem::exists(RootPath(scope) / names.first)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_RepairPreservesUnicodeMapping", "[fonts][fontlayout]") +{ + auto context = Context(ScopeEnum::User); + const auto source = RootPath(context.Scope) / s_WinGetFontPrefix / context.PackageId / context.PackageVersion / L"\u00E9.ttf"; + const auto destination = RootPath(context.Scope) / source.filename(); + CopyFont(source); + Package(context).SetValue(L"\u00C9.TTF", source.wstring()); + Root(context.Scope).SetValue(L"Font title", source.wstring()); + + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(RegistryString(Package(context), source.filename().wstring()) == destination.wstring()); + REQUIRE_FALSE(Root(context.Scope)[std::wstring{ L"Font title" }].has_value()); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(std::filesystem::exists(destination)); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_RepairMoveFailurePreservesMappings", "[fonts][fontlayout]") +{ + auto context = Context(ScopeEnum::User); + const auto source = AddPackageDirectoryFont(context); + Root(context.Scope).SetValue(L"Font title", source.wstring()); + wil::unique_hfile lock{ CreateFileW(source.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) }; + REQUIRE(lock); + REQUIRE(RepairFontPackage(context).Result() == FontResult::Error); + REQUIRE(std::filesystem::exists(source)); + REQUIRE_FALSE(std::filesystem::exists(RootPath(context.Scope) / s_FontFile)); + REQUIRE(RegistryString(Package(context), L"Font title") == source.wstring()); + REQUIRE_FALSE(Package(context)[std::wstring{ L"TestFont.ttf" }].has_value()); + REQUIRE(RegistryString(Root(context.Scope), L"Font title") == source.wstring()); + REQUIRE_FALSE(Root(context.Scope)[std::wstring{ L"TestFont.ttf" }].has_value()); + lock.reset(); + REQUIRE(RepairFontPackage(context).HResult == S_OK); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_MissingFileRepairAndUninstall", "[fonts][fontlayout]") +{ + const auto scope = GENERATE(ScopeEnum::User, ScopeEnum::Machine); + auto context = Context(scope); + const auto missing = RootPath(scope) / s_FontFile; + Package(context).SetValue(L"TestFont.ttf", missing.wstring()); + Root(scope).SetValue(L"TestFont.ttf", missing.wstring()); + REQUIRE(RepairFontPackage(context).HResult == APPINSTALLER_CLI_ERROR_FONT_FILE_NOT_FOUND); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == missing.wstring()); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(Root(scope)[std::wstring{ L"TestFont.ttf" }].has_value()); + REQUIRE_FALSE(AppInstaller::Registry::Key::OpenIfExists(Hive(scope), PackagePath(context))); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_RejectsFilesOutsideFontLocations", "[fonts][fontlayout]") +{ + auto context = Context(ScopeEnum::User); + const auto unrelated = Directory.GetPath() / "Other" / s_FontFile; + CopyFont(unrelated); + Package(context).SetValue(L"TestFont.ttf", unrelated.wstring()); + REQUIRE(RepairFontPackage(context).HResult == APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED); + REQUIRE(UninstallFontPackage(context).HResult == APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED); + REQUIRE(std::filesystem::exists(unrelated)); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == unrelated.wstring()); +} + +TEST_CASE_METHOD(FontLayoutTest, "FontLayout_ReinstallUsesFlatDirectory", "[fonts][fontlayout]") +{ + auto context = Context(ScopeEnum::User); + context.Force = GENERATE(false, true); + const auto installed = AddPackageDirectoryFont(context); + const bool missingFile = GENERATE(false, true); + if (missingFile) + { + std::filesystem::remove(installed); + } + const auto source = Directory.GetPath() / "Source" / s_FontFile; + CopyFont(source); + context.AddPackageFile(source); + REQUIRE(InstallFontPackage(context).HResult == S_OK); + REQUIRE_FALSE(std::filesystem::exists(installed)); + REQUIRE(RegistryString(Package(context), L"TestFont.ttf") == (RootPath(context.Scope) / s_FontFile).wstring()); + REQUIRE(ValidateFontPackage(context).Status == FontStatus::OK); + REQUIRE(UninstallFontPackage(context).HResult == S_OK); +} + TEST_CASE("GetInstalledFonts", "[fonts]") { FontCatalog fontCatalog; diff --git a/src/AppInstallerCLITests/RepairFlow.cpp b/src/AppInstallerCLITests/RepairFlow.cpp index 4a44f6e861..665b275e29 100644 --- a/src/AppInstallerCLITests/RepairFlow.cpp +++ b/src/AppInstallerCLITests/RepairFlow.cpp @@ -4,16 +4,19 @@ #include "TestHooks.h" #include "TestSource.h" #include "WorkflowCommon.h" +#include #include +#include #include using namespace TestCommon; using namespace AppInstaller::CLI::Execution; +using namespace AppInstaller::Manifest; using namespace AppInstaller::Repository; TEST_CASE("RepairFlow_AdminContextRejectsUserScopeBeforePreparation", "[RepairFlow][workflow]") { - const auto installedType = GENERATE("Burn", "Msi"); + const auto installedType = GENERATE("Burn", "Msi", "Font"); CAPTURE(installedType); TestHook::SetIsRunningWithNonDefaultFullToken_Override tokenOverride(true); @@ -29,4 +32,73 @@ TEST_CASE("RepairFlow_AdminContextRejectsUserScopeBeforePreparation", "[RepairFl context << AppInstaller::CLI::Workflow::RepairSinglePackage; REQUIRE_TERMINATED_WITH(context, APPINSTALLER_CLI_ERROR_ADMIN_CONTEXT_ACTION_PROHIBITED); + REQUIRE_FALSE(context.Contains(Data::OperationReturnCode)); +} + +TEST_CASE("RepairFlow_FontUsesInstalledMetadata", "[RepairFlow][workflow]") +{ + TestHook::SetIsRunningWithNonDefaultFullToken_Override tokenOverride(false); + const HRESULT repairResult = GENERATE(S_OK, APPINSTALLER_CLI_ERROR_FONT_FILE_NOT_FOUND); + std::ostringstream output; + TestContext context{ output, std::cin }; + auto previousThreadGlobals = context.SetForCurrentThread(); + auto manifest = YamlParser::CreateFromPath(TestDataFile("InstallFlowTest_Exe.yaml")); + TestPackageVersion::MetadataMap metadata + { + { PackageVersionMetadata::InstalledType, "Font" }, + { PackageVersionMetadata::InstalledScope, "User" }, + }; + context.Add(TestPackageVersion::Make(manifest, metadata)); + context.Override({ AppInstaller::CLI::Workflow::FontRepairImpl, [repairResult](TestContext& repairContext) + { + repairContext.Add(static_cast(repairResult)); + }, 1 }); + + context << + AppInstaller::CLI::Workflow::SelectApplicableInstallerIfNecessary << + AppInstaller::CLI::Workflow::RepairSinglePackage; + + REQUIRE_FALSE(context.Contains(Data::Installer)); + INFO(output.str()); + if (SUCCEEDED(repairResult)) + { + REQUIRE_FALSE(context.IsTerminated()); + REQUIRE(output.str().find("Repair operation completed successfully.") != std::string::npos); + } + else + { + REQUIRE_TERMINATED_WITH(context, APPINSTALLER_CLI_ERROR_EXEC_REPAIR_FAILED); + } +} + +TEST_CASE("RepairFlow_FontBlocksElevatedUserRepair", "[RepairFlow][workflow]") +{ + TestHook::SetIsRunningWithNonDefaultFullToken_Override tokenOverride(true); + std::ostringstream output; + TestContext context{ output, std::cin }; + auto previousThreadGlobals = context.SetForCurrentThread(); + auto manifest = YamlParser::CreateFromPath(TestDataFile("InstallFlowTest_Exe.yaml")); + TestPackageVersion::MetadataMap metadata + { + { PackageVersionMetadata::InstalledType, "Font" }, + { PackageVersionMetadata::InstalledScope, "User" }, + }; + context.Add(TestPackageVersion::Make(manifest, metadata)); + context << AppInstaller::CLI::Workflow::FontRepairImpl; + REQUIRE_TERMINATED_WITH(context, APPINSTALLER_CLI_ERROR_ADMIN_CONTEXT_ACTION_PROHIBITED); + REQUIRE_FALSE(context.Contains(Data::OperationReturnCode)); + REQUIRE(output.str().find("non-administrator context") != std::string::npos); +} + +TEST_CASE("RepairFlow_ArchiveFontNeedsNoExternalRepairInfo", "[RepairFlow][workflow]") +{ + std::ostringstream output; + TestContext context{ output, std::cin }; + auto previousThreadGlobals = context.SetForCurrentThread(); + auto manifest = YamlParser::CreateFromPath(TestDataFile("InstallFlowTest_Exe.yaml")); + manifest.Installers[0].BaseInstallerType = InstallerTypeEnum::Zip; + manifest.Installers[0].NestedInstallerType = InstallerTypeEnum::Font; + context.Add(manifest.Installers[0]); + context << AppInstaller::CLI::Workflow::GetRepairInfo; + REQUIRE_FALSE(context.IsTerminated()); } diff --git a/src/AppInstallerCLITests/TestHooks.h b/src/AppInstallerCLITests/TestHooks.h index f386c8eabd..cb61986a6b 100644 --- a/src/AppInstallerCLITests/TestHooks.h +++ b/src/AppInstallerCLITests/TestHooks.h @@ -63,6 +63,15 @@ namespace AppInstaller void TestHook_SetDeployedPackageStore_Override(std::function(const SourceDetails&)>* value); } + namespace Fonts + { + using GetFontRegistryHiveFunc = std::function; + void TestHook_SetGetFontRegistryHive_Override(GetFontRegistryHiveFunc value); + void TestHook_SetFontSessionChangesDisabled(bool value); + void TestHook_SetPackageFontFilesReadCallback(std::function value); + void TestHook_SetFontRegistrationsReadCallback(std::function value); + } + namespace Logging { void TestHook_SetTelemetryOverride(std::shared_ptr ttl); diff --git a/src/AppInstallerCommonCore/Fonts.cpp b/src/AppInstallerCommonCore/Fonts.cpp index 2cd3ee4d6d..123ccbfe02 100644 --- a/src/AppInstallerCommonCore/Fonts.cpp +++ b/src/AppInstallerCommonCore/Fonts.cpp @@ -15,11 +15,40 @@ #include #include #include +#include using namespace AppInstaller::Utility; namespace AppInstaller::Fonts { +#ifndef AICLI_DISABLE_TEST_HOOKS + using GetFontRegistryHiveFunc = std::function; + static GetFontRegistryHiveFunc s_GetFontRegistryHiveOverride; + static std::function s_PackageFontFilesReadCallback; + static std::function s_FontRegistrationsReadCallback; + static bool s_FontSessionChangesDisabled = false; + + void TestHook_SetGetFontRegistryHive_Override(GetFontRegistryHiveFunc value) + { + s_GetFontRegistryHiveOverride = std::move(value); + } + + void TestHook_SetFontSessionChangesDisabled(bool value) + { + s_FontSessionChangesDisabled = value; + } + + void TestHook_SetPackageFontFilesReadCallback(std::function value) + { + s_PackageFontFilesReadCallback = std::move(value); + } + + void TestHook_SetFontRegistrationsReadCallback(std::function value) + { + s_FontRegistrationsReadCallback = std::move(value); + } +#endif + namespace { constexpr std::wstring_view s_FontsPathSubkey = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"; @@ -28,8 +57,40 @@ namespace AppInstaller::Fonts constexpr std::wstring_view s_IdentifierPrefix = L"FONT"; constexpr std::wstring_view s_Separator = L"\\"; constexpr std::wstring_view s_FontsWinGetPrefix = L"Microsoft.DesktopAppInstaller_8wekyb3d8bbwe"; + constexpr size_t s_MaxFontFileNameLength = 255; const int s_RemoveFontResourceMaxTries = 1000; + Registry::Key GetFontRegistryHive(Manifest::ScopeEnum scope) + { +#ifndef AICLI_DISABLE_TEST_HOOKS + if (s_GetFontRegistryHiveOverride) + { + return s_GetFontRegistryHiveOverride(scope); + } +#endif + + switch (scope) + { + case Manifest::ScopeEnum::User: + return Registry::Key(HKEY_CURRENT_USER, L"", 0UL, MAXIMUM_ALLOWED); + case Manifest::ScopeEnum::Machine: + return Registry::Key(HKEY_LOCAL_MACHINE, L"", 0UL, MAXIMUM_ALLOWED); + case Manifest::ScopeEnum::Unknown: + default: + THROW_HR(E_INVALIDARG); + } + } + + std::string GetFontPathKey(const std::filesystem::path& path) + { + return FoldCase(static_cast(path.lexically_normal().u8string())); + } + + bool FontPathsEqual(const std::filesystem::path& left, const std::filesystem::path& right) + { + return GetFontPathKey(left) == GetFontPathKey(right); + } + std::wstring GetFontFileTitle(const std::filesystem::path& fontFilePath) { // This code can fail in a number of ways, including if the file isn't actually @@ -102,63 +163,116 @@ namespace AppInstaller::Fonts std::filesystem::path GetRootFontPath(Manifest::ScopeEnum scope) { - if (scope == Manifest::ScopeEnum::Machine) + switch (scope) { + case Manifest::ScopeEnum::Machine: return Runtime::GetPathTo(Runtime::PathName::FontsMachineInstallLocation); - } - else - { + case Manifest::ScopeEnum::User: return Runtime::GetPathTo(Runtime::PathName::FontsUserInstallLocation); + case Manifest::ScopeEnum::Unknown: + default: + THROW_HR(E_INVALIDARG); } } - std::filesystem::path GetFontFileInstallPath(const FontContext& context) + std::filesystem::path GetUserFontPackagePath(const FontContext& context) { - auto path = GetRootFontPath(context.Scope); + AssertPackageInformation(context); + return GetRootFontPath(Manifest::ScopeEnum::User) / s_FontsWinGetPrefix / context.PackageId / context.PackageVersion; + } - switch (context.InstallerSource) + bool IsFontFileNameSafe(const std::filesystem::path& name) + { + if (name.empty() || name != name.filename()) { - case InstallerSource::Unknown: - // Unknown installer is assumed to be installed in the default location for machine. - // For a user installed font it could be anywhere. - break; - case InstallerSource::WinGet: - // WinGet installed packages have two formats depending on the scope. - // For Per-user we use subfolders for better robustness and cleaner format. - // For Per-machine we must use a single folder due to a system requirement, - // so the root path is the machine install path. - if (context.Scope == Manifest::ScopeEnum::User) - { - AssertPackageInformation(context); - path /= s_FontsWinGetPrefix; - path /= context.PackageId; - path /= context.PackageVersion; - } + return false; + } - break; - default: - THROW_HR_MSG(E_UNEXPECTED, "Undefined InstallerSource."); + try + { + const auto value = name.u8string(); + return MakeSuitablePathPart(value) == value; } + catch (...) + { + return false; + } + } - return path; + void AssertFontFilePath(const FontContext& context, const std::filesystem::path& path) + { + const bool inRoot = FontPathsEqual(path.parent_path(), GetRootFontPath(context.Scope)); + const bool inPackage = context.Scope == Manifest::ScopeEnum::User && + FontPathsEqual(path.parent_path(), GetUserFontPackagePath(context)); + THROW_HR_IF_MSG(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, + !path.is_absolute() || !IsFontFileNameSafe(path.filename()) || (!inRoot && !inPackage), + "Font path is outside the package's font locations: %ls", path.c_str()); } - // For machine-installed fonts the files all reside in the same folder. We need a unique name that is reasonably human - // readable. The way system fonts normally do this is by appending a number to the end of the file stem. We will follow - // the same pattern by using the original file and adding a number until we arrive at a unique filename. - std::filesystem::path GetUniquePathForDestination(const std::filesystem::path& source, const std::filesystem::path& destination) + struct PackageFontFile { - const auto stem = source.stem(); - const auto ext = source.extension(); + std::wstring RegistryName; + std::filesystem::path OriginalFileName; + std::filesystem::path FilePath; + }; + + std::vector GetPackageFontFiles(const FontContext& context) + { +#ifndef AICLI_DISABLE_TEST_HOOKS + if (s_PackageFontFilesReadCallback) + { + s_PackageFontFilesReadCallback(); + } +#endif + + auto hive = GetFontRegistryHive(context.Scope); + auto key = Registry::Key::OpenIfExists(hive, GetFontRegistryPath(context)); + std::vector result; + if (!key) + { + return result; + } + for (const auto& entry : key.Values()) + { + auto value = entry.Value(); + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, + !value || value->GetType() != Registry::Value::Type::String); + + PackageFontFile file; + file.RegistryName = ConvertToUTF16(entry.Name()); + file.FilePath = value->GetValue(); + AssertFontFilePath(context, file.FilePath); + file.OriginalFileName = context.Scope == Manifest::ScopeEnum::User && + FontPathsEqual(file.FilePath.parent_path(), GetUserFontPackagePath(context)) ? + file.FilePath.filename() : std::filesystem::path(file.RegistryName); + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, + !IsFontFileNameSafe(file.OriginalFileName)); + result.push_back(std::move(file)); + } + return result; + } + + // Files and registry value names share the scope's font namespace. + std::filesystem::path GetUniquePathForDestination(const std::filesystem::path& source, Manifest::ScopeEnum scope) + { + const auto destination = GetRootFontPath(scope); + auto hive = GetFontRegistryHive(scope); + auto root = Registry::Key::OpenIfExists(hive, std::wstring{ s_FontsPathSubkey }); + const auto stem = source.stem().wstring(); + const auto ext = source.extension().wstring(); auto uniqueName = source.filename(); auto candidatePath = destination / uniqueName; int index = 0; - while (std::filesystem::exists(candidatePath)) + while (std::filesystem::exists(candidatePath) || (root && root[uniqueName.wstring()].has_value())) { - std::filesystem::path appendId = { std::to_string(index) }; - uniqueName = stem; - uniqueName += appendId; - uniqueName += ext; + const auto suffix = std::to_wstring(index); + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, suffix.size() + ext.size() > s_MaxFontFileNameLength); + auto stemLength = std::min(stem.size(), s_MaxFontFileNameLength - suffix.size() - ext.size()); + if (stemLength > 0 && stemLength < stem.size() && IS_HIGH_SURROGATE(stem[stemLength - 1])) + { + --stemLength; + } + uniqueName = stem.substr(0, stemLength) + suffix + ext; candidatePath = destination / uniqueName; index++; } @@ -166,6 +280,170 @@ namespace AppInstaller::Fonts return candidatePath; } + std::optional GetRegisteredFontInstallPath(const FontContext& context, const std::filesystem::path& filePath) + { + const auto files = GetPackageFontFiles(context); + for (const auto& file : files) + { + if (FontPathsEqual(file.FilePath, filePath)) + { + return file.FilePath; + } + } + for (const auto& file : files) + { + if (FontPathsEqual(file.OriginalFileName, filePath.filename())) + { + return file.FilePath; + } + } + return std::nullopt; + } + + using FontRegistryEntry = std::pair; + using FontPathSet = std::unordered_set; + + std::vector GetFontRegistrations(Manifest::ScopeEnum scope, + const std::optional& filePath = std::nullopt) + { + auto hive = GetFontRegistryHive(scope); + auto root = Registry::Key::OpenIfExists(hive, std::wstring{ s_FontsPathSubkey }); + std::vector result; + if (!root) + { + return result; + } +#ifndef AICLI_DISABLE_TEST_HOOKS + if (s_FontRegistrationsReadCallback) + { + s_FontRegistrationsReadCallback(); + } +#endif + const auto rootPath = GetRootFontPath(scope); + for (const auto& entry : root.Values()) + { + auto value = entry.Value(); + if (!value || value->GetType() != Registry::Value::Type::String) + { + continue; + } + + auto data = value->GetValue(); + std::filesystem::path registeredPath = data; + if (registeredPath.is_relative()) + { + registeredPath = rootPath / registeredPath; + } + if (!filePath || FontPathsEqual(registeredPath, filePath.value())) + { + result.emplace_back(ConvertToUTF16(entry.Name()), std::move(data)); + } + } + return result; + } + + FontPathSet GetRegisteredFontPaths(const std::filesystem::path& rootPath, const std::vector& registrations) + { + FontPathSet result; + result.reserve(registrations.size()); + for (const auto& registration : registrations) + { + std::filesystem::path registeredPath = registration.second; + if (registeredPath.is_relative()) + { + registeredPath = rootPath / registeredPath; + } + result.emplace(GetFontPathKey(registeredPath)); + } + return result; + } + + void UnregisterFontFile(Manifest::ScopeEnum scope, const std::filesystem::path& filePath) + { + auto hive = GetFontRegistryHive(scope); + auto root = Registry::Key::OpenIfExists(hive, std::wstring{ s_FontsPathSubkey }, 0UL, KEY_ALL_ACCESS); + for (const auto& entry : GetFontRegistrations(scope, filePath)) + { + root.DeleteValue(entry.first); + } + } + + void RegisterFontFile(const FontContext& context, const std::filesystem::path& originalFileName, const std::filesystem::path& installPath) + { + AssertFontFilePath(context, installPath); + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, + !FontPathsEqual(installPath.parent_path(), GetRootFontPath(context.Scope))); + auto hive = GetFontRegistryHive(context.Scope); + auto root = Registry::Key::Create(hive, std::wstring{ s_FontsPathSubkey }); + const auto valueName = installPath.filename().wstring(); + if (root[valueName]) + { + const auto registrations = GetFontRegistrations(context.Scope, installPath); + THROW_HR_IF_MSG(APPINSTALLER_CLI_ERROR_FONT_INSTALL_FAILED, + std::none_of(registrations.begin(), registrations.end(), [&](const auto& entry) + { return ICUCaseInsensitiveEquals(ConvertToUTF8(entry.first), ConvertToUTF8(valueName)); }), + "Font registration is owned by another file: %ls", valueName.c_str()); + } + + auto package = Registry::Key::Create(hive, GetFontRegistryPath(context)); + const auto originalName = originalFileName.wstring(); + if (const auto existing = package[originalName]) + { + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, existing->GetType() != Registry::Value::Type::String); + const std::filesystem::path existingPath = existing->GetValue(); + const bool packageFile = context.Scope == Manifest::ScopeEnum::User && + FontPathsEqual(existingPath.parent_path(), GetUserFontPackagePath(context)) && + FontPathsEqual(existingPath.filename(), originalFileName); + THROW_HR_IF_MSG(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, + !FontPathsEqual(existingPath, installPath) && !packageFile, + "Font package mapping is owned by another file: %ls", originalName.c_str()); + } + package.SetValue(originalName, installPath.wstring()); + root.SetValue(valueName, context.Scope == Manifest::ScopeEnum::Machine ? + installPath.filename().wstring() : installPath.wstring()); + } + + void AddFontToSession(const std::filesystem::path& path) + { +#ifndef AICLI_DISABLE_TEST_HOOKS + if (s_FontSessionChangesDisabled) + { + return; + } +#endif + const auto fontsAdded = ::AddFontResource(path.c_str()); + if (fontsAdded == 0) + { + AICLI_LOG(Core, Warning, << "Failed to add font resource: " << path); + } + else + { + AICLI_LOG(Core, Info, << "Added " << fontsAdded << " fonts to the session."); + } + } + + void RemoveEmptyUserFontPackageDirectories(const FontContext& context) + { + if (context.Scope != Manifest::ScopeEnum::User) + { + return; + } + + auto path = GetUserFontPackagePath(context); + for (size_t i = 0; i < 3; ++i) + { + if (std::filesystem::exists(path)) + { + if (!std::filesystem::is_empty(path)) + { + break; + } + std::filesystem::remove(path); + } + path = path.parent_path(); + } + } + std::vector GetFontFilePaths(const wil::com_ptr& fontFace) { UINT32 fileCount = 0; @@ -204,6 +482,12 @@ namespace AppInstaller::Fonts void RemoveAllFontResources(const std::filesystem::path& filePath) { +#ifndef AICLI_DISABLE_TEST_HOOKS + if (s_FontSessionChangesDisabled) + { + return; + } +#endif // The recommended uninstall method of a font is to call RemoveFontResource until it fails, // This is not guaranteed to remove the file from use, but it is the best we have. // https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-removefontresourcea @@ -220,6 +504,12 @@ namespace AppInstaller::Fonts void NotifyFontChange() { +#ifndef AICLI_DISABLE_TEST_HOOKS + if (s_FontSessionChangesDisabled) + { + return; + } +#endif // Send the WM_FONTCHANGE message so the system and apps know that there has been a font change. // Sometimes this does not have an error when it returns non-zero. To avoid random assert failures // we will not try to log failures for this call. If it fails it does not affect install state. @@ -227,79 +517,78 @@ namespace AppInstaller::Fonts AICLI_LOG(Core, Info, << "Notified system of font change: " << sendResult); } - // Checks the registry path for the file specified, and returns the key value if it finds one. - std::optional CheckRegistryForFontFileReference(const std::wstring& registryPath, const std::filesystem::path& filePath, Manifest::ScopeEnum scope) + void MigrateFontFile(const FontContext& context, const PackageFontFile& file) { - try - { - const auto& hive = scope == Manifest::ScopeEnum::Machine ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - const auto& key = Registry::Key::OpenIfExists(hive, registryPath, 0UL, KEY_READ); - if (key) + auto hive = GetFontRegistryHive(context.Scope); + auto package = Registry::Key::OpenIfExists(hive, GetFontRegistryPath(context), 0UL, KEY_ALL_ACCESS); + const auto destination = GetUniquePathForDestination(file.OriginalFileName, context.Scope); + const auto registrations = GetFontRegistrations(context.Scope, file.FilePath); + const auto originalName = file.OriginalFileName.wstring(); + const auto originalMapping = package[originalName]; + bool sourceRemoved = false; + bool sourceUnloaded = false; + bool mappingChanged = false; + bool destinationCreated = false; + auto rollback = wil::scope_exit([&]() { - // Check for the file being present in this key. - for (const auto& valueRef : key.Values()) + if (!destinationCreated) { - const auto& value = valueRef.Value(); - if (!value.has_value() || (value.value().GetType() != Registry::Value::Type::String)) + return; + } + try + { + if (sourceRemoved) { - continue; + std::filesystem::copy_file(destination, file.FilePath); } - const auto& valueName = ConvertToUTF16(valueRef.Name()); - const std::filesystem::path& valuePath = { value->GetValue() }; - if (valuePath.is_relative()) + if (mappingChanged) { - // Relative value is OK, just compare the filenames. - // We will assume this is in the standard font paths. - if (valuePath.filename() == filePath.filename()) + if (originalMapping) { - return valueName; + package.SetValue(originalName, originalMapping->GetValue()); } - } - else - { - if (valuePath == filePath) + else { - return valueName; + package.DeleteValue(originalName); } + package.SetValue(file.RegistryName, file.FilePath.wstring()); } - } - } - } - CATCH_LOG(); - - return std::nullopt; - } - - // The package registry for machine installed fonts stores the package filename as a registry value. - // This is so we can map the original package filename to the installed filename since they may be different. - std::optional GetRegisteredMachineFontInstallPath(const std::wstring& registryPath, const std::filesystem::path& filePath) - { - try - { - const auto& key = Registry::Key::OpenIfExists(HKEY_LOCAL_MACHINE, registryPath, 0UL, KEY_READ); - if (key) - { - for (const auto& valueRef : key.Values()) - { - const auto& value = valueRef.Value(); - if (!value.has_value() || (value.value().GetType() != Registry::Value::Type::String)) + UnregisterFontFile(context.Scope, destination); + auto root = Registry::Key::Create(hive, std::wstring{ s_FontsPathSubkey }); + for (const auto& registration : registrations) { - continue; + root.SetValue(registration.first, registration.second); } - - const auto& valueName = ConvertToUTF16(valueRef.Name()); - if (valueName == filePath.filename()) + std::filesystem::remove(destination); + if (sourceUnloaded) { - const std::filesystem::path& valuePath = { value->GetValue() }; - return valuePath; + AddFontToSession(file.FilePath); } } - } + catch (...) + { + LOG_CAUGHT_EXCEPTION(); + AICLI_LOG(Core, Error, << "Font repair rollback failed for " << file.FilePath); + } + }); + + std::filesystem::copy_file(file.FilePath, destination); + destinationCreated = true; + mappingChanged = true; + RegisterFontFile(context, file.OriginalFileName, destination); + UnregisterFontFile(context.Scope, file.FilePath); + RemoveAllFontResources(file.FilePath); + sourceUnloaded = true; + THROW_HR_IF(APPINSTALLER_CLI_ERROR_EXEC_REPAIR_FAILED, !std::filesystem::remove(file.FilePath)); + sourceRemoved = true; + if (!ICUCaseInsensitiveEquals(ConvertToUTF8(file.RegistryName), ConvertToUTF8(originalName))) + { + package.DeleteValue(file.RegistryName); } - CATCH_LOG(); - - return std::nullopt; + rollback.release(); + AddFontToSession(destination); } + } FontResult FontOperationResult::Result() const @@ -338,181 +627,171 @@ namespace AppInstaller::Fonts return stream.str(); } - // Creates font file info used for install, validation, and enumeration. - FontFileInfo CreateFontFileInfo(const FontContext& context, const std::filesystem::path& filePath, const std::wstring& title) + namespace { - auto fileInfo = FontFileInfo(); - fileInfo.FilePath = filePath; - fileInfo.PackageIdentifier = context.GetPackageIdentifier(); - fileInfo.PackageId = context.PackageId; - fileInfo.PackageVersion = context.PackageVersion; - fileInfo.InstallerSource = context.InstallerSource; - fileInfo.Scope = context.Scope; - fileInfo.Title = title; - - // For font file paths in the registry, we may have a relative filename (because the path is assumed). - if (fileInfo.FilePath.is_relative()) + // Creates font file info used for install, validation, and enumeration. + FontFileInfo CreateFontFileInfoImpl(const FontContext& context, const std::filesystem::path& filePath, + const std::wstring& title, const std::optional& installedPath, + std::optional isRegistered = std::nullopt) { - // Relative path is assumed to be relative to the default location for the scope. - // We are assuming that a relative file path input refers to an already-installed file. - auto fullPath = GetRootFontPath(fileInfo.Scope); - fullPath /= fileInfo.FilePath; - fileInfo.FilePath = std::move(fullPath); - } + auto fileInfo = FontFileInfo(); + fileInfo.FilePath = filePath; + fileInfo.PackageIdentifier = context.GetPackageIdentifier(); + fileInfo.PackageId = context.PackageId; + fileInfo.PackageVersion = context.PackageVersion; + fileInfo.InstallerSource = context.InstallerSource; + fileInfo.Scope = context.Scope; + fileInfo.Title = title; + + // For font file paths in the registry, we may have a relative filename (because the path is assumed). + if (fileInfo.FilePath.is_relative()) + { + // Relative path is assumed to be relative to the default location for the scope. + // We are assuming that a relative file path input refers to an already-installed file. + auto fullPath = GetRootFontPath(fileInfo.Scope); + fullPath /= fileInfo.FilePath; + fileInfo.FilePath = std::move(fullPath); + } - // Get information about the font file itself. - auto fontCatalog = FontCatalog(); - fileInfo.WinGetSupported = fontCatalog.IsFontFileSupported(fileInfo.FilePath, fileInfo.FileType); - if (fileInfo.WinGetSupported && fileInfo.Title.empty()) - { - try + // Get information about the font file itself. + auto fontCatalog = FontCatalog(); + fileInfo.WinGetSupported = fontCatalog.IsFontFileSupported(fileInfo.FilePath, fileInfo.FileType); + if (fileInfo.WinGetSupported && fileInfo.Title.empty()) { - fileInfo.Title = GetFontFileTitle(fileInfo.FilePath); + try + { + fileInfo.Title = GetFontFileTitle(fileInfo.FilePath); + } + CATCH_LOG(); } - CATCH_LOG(); - } - if (fileInfo.Title.empty()) - { - // If the title is still empty (such as failure to set it from the File), use the Filename - fileInfo.Title = fileInfo.FilePath.filename().wstring(); - } + if (fileInfo.Title.empty()) + { + // If the title is still empty (such as failure to set it from the File), use the Filename + fileInfo.Title = fileInfo.FilePath.filename().wstring(); + } - fileInfo.RegistryPackagePath = GetFontRegistryPath(context); - if (fileInfo.Scope == Manifest::ScopeEnum::Machine && fileInfo.InstallerSource == InstallerSource::WinGet) - { - // Machine fonts from WinGet still install into the Font folder but we track package source separately - // due to limited information in the Font registry and all font files being in the same key and folder. + fileInfo.RegistryPackagePath = GetFontRegistryPath(context); fileInfo.RegistryInstallPath = s_FontsPathSubkey; - } - else - { - // User-installed and non-Winget fonts have same registry package path and install path. - fileInfo.RegistryInstallPath = fileInfo.RegistryPackagePath; - } - // Check if the file is already in the install path, in which case this is a query. - auto const& installPath = GetFontFileInstallPath(context); - if (installPath == fileInfo.FilePath.parent_path()) - { - fileInfo.InstallPath = fileInfo.FilePath; - } - else - { - if (fileInfo.InstallerSource == InstallerSource::WinGet && fileInfo.Scope == Manifest::ScopeEnum::Machine) + auto registeredPath = installedPath; + if (!registeredPath && context.InstallerSource == InstallerSource::WinGet) { - // Machine installed WinGet fonts must have a non-conflicting filename in the root font folder. - // To ensure a unique font name and allow different versions to exist side by side, the install file - // name may be a different name from the original package install. To account for this, the Package - // registry location uses the original filename as the registry value name and the value as the - // resulting path. If we are installing a machine font that already exists, we must check to see - // if this file already has a mapping defined. - const auto& installedFilePath = GetRegisteredMachineFontInstallPath(fileInfo.RegistryPackagePath, fileInfo.FilePath.filename()); - if (installedFilePath.has_value()) - { - fileInfo.InstallPath = installedFilePath.value(); - } - else - { - // File not already defined, we need to create a non-conflicting filename. - // Machine-installed WinGet must provide a non-conflicting filename to the root install location. - fileInfo.InstallPath = GetUniquePathForDestination(fileInfo.FilePath, installPath); - } + registeredPath = GetRegisteredFontInstallPath(context, fileInfo.FilePath); + } + if (registeredPath) + { + fileInfo.InstallPath = registeredPath.value(); + } + else if (context.InstallerSource == InstallerSource::Unknown) + { + fileInfo.InstallPath = fileInfo.FilePath; } else { - fileInfo.InstallPath = installPath / fileInfo.FilePath.filename(); + fileInfo.InstallPath = GetUniquePathForDestination(fileInfo.FilePath, context.Scope); } - } - - // If our font file is registered it will exist in the install path and have a registry value. - const auto& registryTitle = CheckRegistryForFontFileReference(fileInfo.RegistryInstallPath, fileInfo.InstallPath, fileInfo.Scope); - if (fileInfo.Title.empty()) - { - // Use the registry title or filename if we still dont' know. - if (registryTitle.has_value()) + fileInfo.IsFontFileInstalled = std::filesystem::exists(fileInfo.InstallPath); + fileInfo.IsFontFileRegistered = isRegistered.has_value() ? + isRegistered.value() : !GetFontRegistrations(fileInfo.Scope, fileInfo.InstallPath).empty(); + if (fileInfo.IsFontFileInstalled && fileInfo.IsFontFileRegistered) { - fileInfo.Title = registryTitle.value(); + fileInfo.Status = FontStatus::OK; + } + else if (fileInfo.IsFontFileInstalled || fileInfo.IsFontFileRegistered) + { + fileInfo.Status = FontStatus::Corrupt; } else { - fileInfo.Title = fileInfo.FilePath.filename().wstring(); + fileInfo.Status = FontStatus::Absent; } - } - fileInfo.IsFontFileInstalled = std::filesystem::exists(fileInfo.InstallPath) ? true : false; - fileInfo.IsFontFileRegistered = registryTitle.has_value() ? true : false; - if (fileInfo.IsFontFileInstalled && fileInfo.IsFontFileRegistered) - { - fileInfo.Status = FontStatus::OK; - } - else if (fileInfo.IsFontFileInstalled || fileInfo.IsFontFileRegistered) - { - fileInfo.Status = FontStatus::Corrupt; + return fileInfo; } - else - { - fileInfo.Status = FontStatus::Absent; - } - - return fileInfo; - } - FontValidationResult ValidateFontPackage(FontContext& context) - { - AssertPackageInformation(context); + FontValidationResult ValidateFontPackageImpl(FontContext& context, + std::optional> installedRegistrationPaths) + { + AssertPackageInformation(context); - auto result = FontValidationResult(); + auto result = FontValidationResult(); - AICLI_LOG(Core, Info, << "Validating font package: " << context.PackageId.c_str() << " " << context.PackageVersion.c_str()); + AICLI_LOG(Core, Info, << "Validating font package: " << context.PackageId.c_str() << " " << context.PackageVersion.c_str()); - try - { - // Create font file info for each package file - for (const auto& file : context.PackageFiles) - { - result.FontFileInfos.push_back(CreateFontFileInfo(context, file)); - } - - // We create an overall status for the validation with the following determination: - // If ALL of the files are OK, the package is OK. - // If ALL of the files are Absent, the package is Absent. - // If there is any combination, the package is Corrupt. - // We must check each file info to see if the package is supported by WinGet. - // If any file is unsupported then there are unsupported fonts in the package. - for (const auto& fontFileInfo : result.FontFileInfos) + try { - if (!fontFileInfo.WinGetSupported) + const bool installedFiles = installedRegistrationPaths.has_value(); + const auto packageFiles = installedFiles ? GetPackageFontFiles(context) : std::vector{}; + const auto fileCount = installedFiles ? packageFiles.size() : context.PackageFiles.size(); + FontPathSet fileNames; + fileNames.reserve(fileCount); + for (size_t i = 0; i < fileCount; ++i) { - result.HasUnsupportedFonts = true; + const auto& file = installedFiles ? packageFiles[i].FilePath : context.PackageFiles[i]; + THROW_HR_IF_MSG(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, + !fileNames.emplace(GetFontPathKey(file.filename())).second, + "Font package contains duplicate filenames: %ls", file.filename().c_str()); + std::optional isRegistered; + if (installedRegistrationPaths) + { + const auto& registeredPaths = installedRegistrationPaths->get(); + isRegistered = registeredPaths.find(GetFontPathKey(file)) != registeredPaths.end(); + } + result.FontFileInfos.push_back(CreateFontFileInfoImpl(context, file, {}, + installedFiles ? std::optional{ file } : std::nullopt, isRegistered)); } - if (fontFileInfo.Status != result.Status) + // We create an overall status for the validation with the following determination: + // If ALL of the files are OK, the package is OK. + // If ALL of the files are Absent, the package is Absent. + // If there is any combination, the package is Corrupt. + // We must check each file info to see if the package is supported by WinGet. + // If any file is unsupported then there are unsupported fonts in the package. + for (const auto& fontFileInfo : result.FontFileInfos) { - if (result.Status == FontStatus::Unknown) + if (!fontFileInfo.WinGetSupported) { - // This is the first status we've seen, make it the default. - result.Status = fontFileInfo.Status; + result.HasUnsupportedFonts = true; } - else + + if (fontFileInfo.Status != result.Status) { - // Previous status now differs from current status, package is corrupt. - result.Status = FontStatus::Corrupt; + if (result.Status == FontStatus::Unknown) + { + // This is the first status we've seen, make it the default. + result.Status = fontFileInfo.Status; + } + else + { + // Previous status now differs from current status, package is corrupt. + result.Status = FontStatus::Corrupt; + } } } + + result.Result = FontResult::Success; + } + catch (...) + { + LOG_CAUGHT_EXCEPTION(); + result.HResult = APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED; + result.Result = FontResult::Error; } - result.Result = FontResult::Success; - } - catch (...) - { - LOG_CAUGHT_EXCEPTION(); - result.HResult = APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED; - result.Result = FontResult::Error; + return result; } + } - return result; + FontFileInfo CreateFontFileInfo(const FontContext& context, const std::filesystem::path& filePath, const std::wstring& title) + { + return CreateFontFileInfoImpl(context, filePath, title, std::nullopt); + } + + FontValidationResult ValidateFontPackage(FontContext& context) + { + return ValidateFontPackageImpl(context, std::nullopt); } FontOperationResult InstallFontPackage(FontContext& context) @@ -534,7 +813,7 @@ namespace AppInstaller::Fonts } // Validate the package data was all processed successfully. - const auto& validationResult = ValidateFontPackage(context); + auto validationResult = ValidateFontPackage(context); if (validationResult.Result != FontResult::Success) { result.HResult = winrt::hresult(APPINSTALLER_CLI_ERROR_FONT_FILE_NOT_SUPPORTED); @@ -558,13 +837,15 @@ namespace AppInstaller::Fonts return result; } - // We will attempt a cleanup / force install if either this is a forced install or the package was not in a good state. - if (validationResult.Status == FontStatus::Corrupt || context.Force) + const auto installRoot = GetRootFontPath(context.Scope); + const bool usesPackageDirectory = std::any_of(validationResult.FontFileInfos.begin(), validationResult.FontFileInfos.end(), + [&](const auto& info) { return !FontPathsEqual(info.InstallPath.parent_path(), installRoot); }); + if (validationResult.Status == FontStatus::Corrupt || context.Force || usesPackageDirectory) { // Force install of a font can have problems because if the font is already there then it // may be in use. The scenarios for using force is if a prior install attempt failed, so // we will try to clean up the existing font registration so it may be successful this time. - AICLI_LOG(Core, Info, << "Package is corrupt or forced install, attempting to remove any existing registration."); + AICLI_LOG(Core, Info, << "Removing existing font package mappings before installation."); auto uninstallResult = UninstallFontPackage(context); if (uninstallResult.Result() != FontResult::Success) { @@ -572,6 +853,14 @@ namespace AppInstaller::Fonts AICLI_LOG(Core, Error, << "Font cleanup uninstall failed: " << context.PackageId.c_str() << " - " << AppInstaller::Logging::SetHRFormat << uninstallResult.HResult); return result; } + + validationResult = ValidateFontPackage(context); + if (validationResult.Result != FontResult::Success || validationResult.HasUnsupportedFonts) + { + result.HResult = APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED; + AICLI_LOG(Core, Error, << "Font validation failed after cleanup: " << context.PackageId.c_str()); + return result; + } } AICLI_LOG(Core, Info, << "Starting install of " << context.PackageId.c_str()); @@ -579,72 +868,37 @@ namespace AppInstaller::Fonts try { // Install each file from the file info. - for (const auto& fontFileInfo : validationResult.FontFileInfos) + for (auto& fontFileInfo : validationResult.FontFileInfos) { - // Font install step 1: Copy file to winget package identifiable location. + const auto registeredPath = GetRegisteredFontInstallPath(context, fontFileInfo.FilePath); + fontFileInfo.InstallPath = registeredPath ? registeredPath.value() : + GetUniquePathForDestination(fontFileInfo.FilePath, context.Scope); AICLI_LOG(Core, Info, << "Moving " << fontFileInfo.FilePath << " to " << fontFileInfo.InstallPath); if (!std::filesystem::exists(fontFileInfo.InstallPath.parent_path())) { std::filesystem::create_directories(fontFileInfo.InstallPath.parent_path()); } - // The file should not be present, but if it is, do another attempt to remove it. - if (std::filesystem::exists(fontFileInfo.InstallPath)) - { - // Try to remove font resource to avoid file-in-use. - RemoveAllFontResources(fontFileInfo.InstallPath); - if (!std::filesystem::remove(fontFileInfo.InstallPath)) + // Copying into the Fonts directory makes the file visible to system font discovery. + std::filesystem::copy_file(fontFileInfo.FilePath, fontFileInfo.InstallPath); + auto removeUnregisteredFile = wil::scope_exit([&]() { - AICLI_LOG(Core, Error, << "Font file already exists and was unable to be removed."); - THROW_HR(APPINSTALLER_CLI_ERROR_FONT_INSTALL_FAILED); - } - } - - if (context.Scope == Manifest::ScopeEnum::Machine) - { - // Using std::filesystem::rename does not work when installing into the system Fonts - // folder; the system does not recognize the font files. std::filesystem::copy_file does work. - std::filesystem::copy_file(fontFileInfo.FilePath, fontFileInfo.InstallPath); - std::filesystem::remove(fontFileInfo.FilePath); - } - else - { - // We prefer to use rename where it works. - AppInstaller::Filesystem::RenameFile(fontFileInfo.FilePath, fontFileInfo.InstallPath); - } + try + { + std::filesystem::remove(fontFileInfo.InstallPath); + } + catch (...) + { + LOG_CAUGHT_EXCEPTION(); + AICLI_LOG(Core, Error, << "Failed removing font file after installation failure: " << fontFileInfo.InstallPath); + } + }); AICLI_LOG(Core, Info, << "Adding " << fontFileInfo.Title.c_str() << " to " << fontFileInfo.InstallPath); - if (context.Scope == Manifest::ScopeEnum::User) - { - auto key = Registry::Key::Create(HKEY_CURRENT_USER, fontFileInfo.RegistryInstallPath); - key.SetValue(fontFileInfo.Title, fontFileInfo.InstallPath, REG_SZ); - } - else - { - // Machine install we set two keys, one for source information, and one for the actual install. - // The value name is the source filename so we can map this later for validation. - auto sourceKey = Registry::Key::Create(HKEY_LOCAL_MACHINE, fontFileInfo.RegistryPackagePath, 0UL, KEY_ALL_ACCESS); - sourceKey.SetValue(fontFileInfo.FilePath.filename(), fontFileInfo.InstallPath, REG_SZ); - - // Machine font install uses relative filename. Use filename as value to avoid collisions in the key. - auto installKey = Registry::Key::OpenIfExists(HKEY_LOCAL_MACHINE, fontFileInfo.RegistryInstallPath, 0UL, KEY_ALL_ACCESS); - installKey.SetValue(fontFileInfo.InstallPath.filename(), fontFileInfo.InstallPath.filename(), REG_SZ); - } - - // Add Font Resource to the session. - const auto& fontsAdded = ::AddFontResource(fontFileInfo.InstallPath.c_str()); - if (fontsAdded == 0) - { - // AddFontResource does not add additional information for us, so we dont know why they were not added, - // only that they were not added. At this point the "install" is successful, but we were not able to - // add the font to the system, which means subsequent adds on session start may also fail, but is not - // guaranteed to fail. We will note it in the log and carry on. - AICLI_LOG(Core, Warning, << "Failed to add font resource: " << fontFileInfo.InstallPath); - } - else - { - AICLI_LOG(Core, Info, << "Added " << fontsAdded << " fonts to the session."); - } + RegisterFontFile(context, fontFileInfo.FilePath.filename(), fontFileInfo.InstallPath); + std::filesystem::remove(fontFileInfo.FilePath); + removeUnregisteredFile.release(); + AddFontToSession(fontFileInfo.InstallPath); } result.HResult = S_OK; @@ -678,120 +932,114 @@ namespace AppInstaller::Fonts return result; } - FontOperationResult UninstallFontPackage(FontContext& context) + FontOperationResult RepairFontPackage(FontContext& context) { - FontOperationResult result; - - if (context.InstallerSource != InstallerSource::WinGet) - { - throw std::logic_error("Only WinGet format of font package uninstall is supported."); - } - AssertPackageInformation(context); - - const auto& installFolderPath = GetFontFileInstallPath(context); - const auto& installPackagePath = GetFontRegistryPath(context); - std::vector filesToRemove; + THROW_HR_IF(E_INVALIDARG, context.InstallerSource != InstallerSource::WinGet); + FontOperationResult result; try { - auto hive = context.Scope == Manifest::ScopeEnum::Machine ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - auto key = Registry::Key::OpenIfExists(hive, installPackagePath, 0ul, KEY_ALL_ACCESS); + auto files = GetPackageFontFiles(context); + THROW_HR_IF(APPINSTALLER_CLI_ERROR_NO_REPAIR_INFO_FOUND, files.empty()); - if (key) + FontCatalog catalog; + for (size_t i = 0; i < files.size(); ++i) { - // Assume all values in this key are fonts related to this package. - for (const auto& fontEntry : key.Values()) + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_FILE_NOT_FOUND, !std::filesystem::is_regular_file(files[i].FilePath)); + DWRITE_FONT_FILE_TYPE fileType; + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_FILE_NOT_SUPPORTED, !catalog.IsFontFileSupported(files[i].FilePath, fileType)); + for (size_t j = 0; j < i; ++j) { - auto value = fontEntry.Value(); - if (!value.has_value() || (value.value().GetType() != Registry::Value::Type::String)) - { - // Not a valid entry, nothing to do here. - continue; - } - - std::filesystem::path filePath = { value->GetValue() }; - if (!std::filesystem::exists(filePath)) - { - // File doesn't exist, nothing to do here. - continue; - } - - // The font may be in use by the system or other apps, it needs to be removed from - // from use or at least attempted to be removed from use. - RemoveAllFontResources(filePath); - filesToRemove.push_back(filePath); + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_VALIDATION_FAILED, + FontPathsEqual(files[i].FilePath, files[j].FilePath) || + FontPathsEqual(files[i].OriginalFileName, files[j].OriginalFileName)); } + } - // Delete the key - if (!Registry::Key::DeleteTree(hive, installPackagePath)) + const auto rootPath = GetRootFontPath(context.Scope); + for (const auto& file : files) + { + if (FontPathsEqual(file.FilePath.parent_path(), rootPath)) { - AICLI_LOG(Core, Warning, << "Failed removing registry tree " << installPackagePath.c_str()); + RegisterFontFile(context, file.OriginalFileName, file.FilePath); + RemoveAllFontResources(file.FilePath); + AddFontToSession(file.FilePath); + continue; } - if (context.Scope == Manifest::ScopeEnum::Machine) - { - // Machine installed fonts also have an entry in the System font registry. - // We have to find the values that have the filename as data. - auto machineFontRoot = Registry::Key::OpenIfExists(HKEY_LOCAL_MACHINE, s_FontsPathSubkey.data(), 0ul, KEY_ALL_ACCESS); - - for (const auto& file : filesToRemove) - { - machineFontRoot.DeleteValue(file.filename()); - } - } + MigrateFontFile(context, file); } + + RemoveEmptyUserFontPackageDirectories(context); } catch (...) { + result.HResult = wil::ResultFromCaughtException(); LOG_CAUGHT_EXCEPTION(); + AICLI_LOG(Core, Error, << "Font repair failed for " << context.PackageId.c_str()); + } - // For uninstall we will log the error and continue trying to remove it, since we have partial remove and are in an unknown state. - AICLI_LOG(Core, Error, << "Failed removing fonts in the registry."); + NotifyFontChange(); + return result; + } + + FontOperationResult UninstallFontPackage(FontContext& context) + { + AssertPackageInformation(context); + THROW_HR_IF(E_INVALIDARG, context.InstallerSource != InstallerSource::WinGet); + FontOperationResult result; + + std::vector files; + try + { + files = GetPackageFontFiles(context); + } + catch (...) + { + LOG_CAUGHT_EXCEPTION(); + AICLI_LOG(Core, Error, << "Failed reading font package mappings."); + result.HResult = APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED; + return result; } - // Remove any font files. - for (const auto& file : filesToRemove) + auto hive = GetFontRegistryHive(context.Scope); + auto package = Registry::Key::OpenIfExists(hive, GetFontRegistryPath(context), 0UL, KEY_ALL_ACCESS); + for (const auto& file : files) { try { - if (std::filesystem::exists(file)) + RemoveAllFontResources(file.FilePath); + if (std::filesystem::exists(file.FilePath)) { - // TODO: Add robustness for files-in-use scenarios. - std::filesystem::remove(file); + THROW_HR_IF(APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED, !std::filesystem::remove(file.FilePath)); } + UnregisterFontFile(context.Scope, file.FilePath); + package.DeleteValue(file.RegistryName); } catch (...) { LOG_CAUGHT_EXCEPTION(); - AICLI_LOG(Core, Error, << "Failed removing font files."); - result.HResult = winrt::hresult(APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED); + AICLI_LOG(Core, Error, << "Failed removing font file or registration: " << file.FilePath); + result.HResult = APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED; } } - if (context.Scope == Manifest::ScopeEnum::User) + if (result.Result() == FontResult::Success) { - // User installed fonts also have an install folder, we will clean that up as well. - if (std::filesystem::exists(installFolderPath)) + try { - try + if (package) { - const auto& parent = installFolderPath.parent_path(); - std::filesystem::remove_all(installFolderPath); - - // This may have been the only version installed, so remove parent if empty. - if (std::filesystem::is_empty(parent)) - { - std::filesystem::remove(parent); - } - } - catch (...) - { - // Font files have already been removed at this point, so failure to delete - // this folder is not a failure of removing the fonts. - LOG_CAUGHT_EXCEPTION(); - AICLI_LOG(Core, Error, << "Failed removing font folders."); + Registry::Key::DeleteTree(hive, GetFontRegistryPath(context)); } + RemoveEmptyUserFontPackageDirectories(context); + } + catch (...) + { + LOG_CAUGHT_EXCEPTION(); + AICLI_LOG(Core, Error, << "Failed removing font package metadata or directories."); + result.HResult = APPINSTALLER_CLI_ERROR_FONT_UNINSTALL_FAILED; } } @@ -957,13 +1205,20 @@ namespace AppInstaller::Fonts try { - auto wingetMachineFonts = std::unordered_map(); - // Iterate through scopes for machine and user for (const auto& scope : { Manifest::ScopeEnum::Machine, Manifest::ScopeEnum::User }) { - auto hive = scope == Manifest::ScopeEnum::Machine ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + FontPathSet wingetFonts; + auto hive = GetFontRegistryHive(scope); auto root = Registry::Key::OpenIfExists(hive, std::wstring{ s_FontsPathSubkey }); + if (!root) + { + continue; + } + + const auto registrations = GetFontRegistrations(scope); + const auto rootPath = GetRootFontPath(scope); + const auto registeredPaths = GetRegisteredFontPaths(rootPath, registrations); // There are two supported scenarios for tracking sub-keys. // 1) We created the subkey, therefore it is a winget installed font. @@ -979,66 +1234,63 @@ namespace AppInstaller::Fonts // Assume all sub-keys are WinGet Packages for (const auto& packageSubKey : subkeyKey) { - // All sub-keys should be versions of the package. - auto wingetPackageSubKey = packageSubKey.Open(); - for (const auto& versionSubKey : wingetPackageSubKey) + try { - auto packageId = ConvertToUTF16(packageSubKey.Name()); - auto version = ConvertToUTF16(versionSubKey.Name()); - auto packageVersionSubKey = versionSubKey.Open(); - for (const auto& versionValue : packageVersionSubKey.Values()) + // All sub-keys should be versions of the package. + auto wingetPackageSubKey = packageSubKey.Open(); + for (const auto& versionSubKey : wingetPackageSubKey) { - // Values are the files. - auto value = versionValue.Value(); - if (!value.has_value() || (value.value().GetType() != Registry::Value::Type::String)) + try { - continue; + auto packageId = ConvertToUTF16(packageSubKey.Name()); + auto version = ConvertToUTF16(versionSubKey.Name()); + auto context = FontContext(); + context.Scope = scope; + context.InstallerSource = InstallerSource::WinGet; + context.PackageId = packageId; + context.PackageVersion = version; + const auto packageFiles = GetPackageFontFiles(context); + for (const auto& file : packageFiles) + { + const auto pathKey = GetFontPathKey(file.FilePath); + auto fontFile = CreateFontFileInfoImpl(context, file.FilePath, {}, file.FilePath, + registeredPaths.find(pathKey) != registeredPaths.end()); + fontFiles.push_back(std::move(fontFile)); + wingetFonts.emplace(pathKey); + } } - - std::filesystem::path filePath = { value->GetValue() }; - if (scope == Manifest::ScopeEnum::Machine) + catch (...) { - // Capture the filename for winget machine fonts so we can avoid duplicates. - wingetMachineFonts[filePath.filename()] = true; + LOG_CAUGHT_EXCEPTION(); + AICLI_LOG(Core, Error, << "Failed getting font file information for: " << + packageSubKey.Name().c_str() << '|' << versionSubKey.Name().c_str()); } - - auto context = FontContext(); - context.Scope = scope; - context.InstallerSource = InstallerSource::WinGet; - context.PackageId = packageId; - context.PackageVersion = version; - auto fontFile = CreateFontFileInfo(context, filePath, ConvertToUTF16(versionValue.Name())); - fontFiles.push_back(std::move(fontFile)); } } + catch (...) + { + LOG_CAUGHT_EXCEPTION(); + AICLI_LOG(Core, Error, << "Failed getting font file information for: " << packageSubKey.Name().c_str()); + } } } } // All remaining values in the root are externally installed fonts. - for (const auto& rootValue : root.Values()) + for (const auto& registration : registrations) { - auto value = rootValue.Value(); - if (!value.has_value() || (value.value().GetType() != Registry::Value::Type::String)) + std::filesystem::path filePath = registration.second; + const auto registeredPath = filePath.is_relative() ? rootPath / filePath : filePath; + if (wingetFonts.find(GetFontPathKey(registeredPath)) != wingetFonts.end()) { continue; } - std::filesystem::path filePath = { value->GetValue() }; - if (scope == Manifest::ScopeEnum::Machine) - { - // Skip it if this is already identified in the WinGet machine fonts. - if (wingetMachineFonts[filePath.filename()]) - { - continue; - } - } - auto context = FontContext(); context.Scope = scope; context.InstallerSource = InstallerSource::Unknown; context.PackageId = filePath.filename(); - auto fontFile = CreateFontFileInfo(context, filePath, ConvertToUTF16(rootValue.Name())); + auto fontFile = CreateFontFileInfoImpl(context, filePath, registration.first, std::nullopt, true); fontFiles.push_back(std::move(fontFile)); } } @@ -1058,9 +1310,14 @@ namespace AppInstaller::Fonts try { - auto hive = scope == Manifest::ScopeEnum::Machine ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + auto hive = GetFontRegistryHive(scope); auto root = Registry::Key::OpenIfExists(hive, s_FontsPathSubkey.data(), 0UL, KEY_READ); + if (!root) + { + return fontPackages; + } + const auto registeredPaths = GetRegisteredFontPaths(GetRootFontPath(scope), GetFontRegistrations(scope)); for (const auto& subkey : root) { auto subkeyName = ConvertToUTF16(subkey.Name()); @@ -1084,20 +1341,7 @@ namespace AppInstaller::Fonts context.PackageId = packageId; context.PackageVersion = version; - auto packageVersionSubKey = versionSubKey.Open(); - for (const auto& versionValue : packageVersionSubKey.Values()) - { - auto value = versionValue.Value(); - if (!value.has_value() || (value.value().GetType() != Registry::Value::Type::String)) - { - continue; - } - - std::filesystem::path filePath = { value->GetValue() }; - context.AddPackageFile(filePath); - } - - auto validationResult = ValidateFontPackage(context); + auto validationResult = ValidateFontPackageImpl(context, std::cref(registeredPaths)); if (validationResult.Status != FontStatus::Absent) { auto packageInfo = FontPackageInfo(); diff --git a/src/AppInstallerCommonCore/Public/winget/Fonts.h b/src/AppInstallerCommonCore/Public/winget/Fonts.h index abc2bf90d5..66bf286941 100644 --- a/src/AppInstallerCommonCore/Public/winget/Fonts.h +++ b/src/AppInstallerCommonCore/Public/winget/Fonts.h @@ -125,6 +125,8 @@ namespace AppInstaller::Fonts FontOperationResult InstallFontPackage(FontContext& context); + FontOperationResult RepairFontPackage(FontContext& context); + FontOperationResult UninstallFontPackage(FontContext& context); std::wstring GetFontRegistryRoot();