From 14d644c7811dbe9ee309951e430626a9421d3322 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 22 Aug 2026 10:09:00 -0700 Subject: [PATCH] Don't copy updater progress tool app to caches directory (#2900) As part of this change, SUStatus window is now being created programmatically rather than from a nib, so the nib does not need to be loaded in the progress tool (Updater.app) nor duplicated. The localizations this helper tool needs are also now being autogenerated. In the Updater.app, since the app can be swapped, we will minimize what needs to be loaded from disk. Also, the progress Updater app is no longer brought up the from when its status window shows, which could cause it to show up as a recent app entry in the Dock. I used AI to re-generate the SUStatus window programmatically, which I've verified have same properties as the removed xib, and to create the python script to generate the localization header for the Updater app which I've reviewed. --- .github/workflows/ci.yml | 9 + .../generate_progress_tool_localizations.py | 153 ++++++++++++++ InstallerLauncher/SUInstallerLauncher.m | 47 +---- Sparkle.xcodeproj/project.pbxproj | 10 +- .../InstallerProgress-Info.plist | 4 +- .../InstallerProgressAppController.m | 45 +---- .../InstallerProgressDelegate.h | 1 - .../SPUInstallerProgressLocalizedStrings.h | 189 ++++++++++++++++++ .../InstallerProgress/ShowInstallerProgress.m | 118 +++-------- Sparkle/SPUInstallerDriver.m | 51 ----- Sparkle/SPUStandardUserDriver.m | 1 - Sparkle/SUStatus.xib | 124 ------------ Sparkle/SUStatusController.m | 187 ++++++++++++----- 13 files changed, 534 insertions(+), 405 deletions(-) create mode 100755 Configurations/generate_progress_tool_localizations.py create mode 100644 Sparkle/InstallerProgress/SPUInstallerProgressLocalizedStrings.h delete mode 100644 Sparkle/SUStatus.xib diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 335dc5ba..230ded5c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,15 @@ jobs: with: submodules: true fetch-depth: 0 + - name: Check Installer Progress localizations are up to date + if: ${{ matrix.upload-dist }} + run: | + python3 Configurations/generate_progress_tool_localizations.py + if [ -n "$(git status --porcelain -- Sparkle/InstallerProgress/SPUInstallerProgressLocalizedStrings.h Sparkle/InstallerProgress/InstallerProgress-Info.plist)" ]; then + echo "::error::Sparkle/InstallerProgress/SPUInstallerProgressLocalizedStrings.h or InstallerProgress-Info.plist is out of date. Run Configurations/generate_progress_tool_localizations.py and commit the result." + git diff -- Sparkle/InstallerProgress/SPUInstallerProgressLocalizedStrings.h Sparkle/InstallerProgress/InstallerProgress-Info.plist + exit 1 + fi - name: Build Unit Tests env: DEVELOPER_DIR: ${{ matrix.xcode-path }} diff --git a/Configurations/generate_progress_tool_localizations.py b/Configurations/generate_progress_tool_localizations.py new file mode 100755 index 00000000..186d9d48 --- /dev/null +++ b/Configurations/generate_progress_tool_localizations.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +# +# generate_progress_tool_localizations.py +# +# The Installer Progress helper is a minimal tool that minimizes loading resolve resources. +# This script reads the localizations from Sparkle/*.lproj/Sparkle.strings +# and generates a header with the handful of strings the tool needs. +# It also keeps CFBundleLocalizations in InstallerProgress-Info.plist in sync +# with the set of locales found. +# +# This script must be re-run by hand after changing any of the strings below in +# Sparkle/*.lproj/Sparkle.strings, or after adding/removing a locale. +# Output is deterministic between runs. + +import glob +import json +import os +import plistlib +import subprocess +import sys + +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +REPO_ROOT = os.path.dirname(SCRIPT_DIR) +SPARKLE_DIR = os.path.join(REPO_ROOT, "Sparkle") +OUTPUT_HEADER = os.path.join(REPO_ROOT, "Sparkle", "InstallerProgress", "SPUInstallerProgressLocalizedStrings.h") +INFO_PLIST = os.path.join(REPO_ROOT, "Sparkle", "InstallerProgress", "InstallerProgress-Info.plist") + +# Fixed order so regenerating the header without content changes never reorders keys +REQUIRED_KEYS = ( + "Cancel Update", + "Installing update…", + "Updating %@", +) + +# Base.lproj holds the canonical/development-language (English) strings, but "Base" +# is not a real locale identifier for +[NSBundle preferredLocalizationsFromArray:] +# to match against, so it's keyed as "en" in the generated table. +LPROJ_LOCALE_OVERRIDES = { + "Base": "en", +} + + +def load_strings(strings_path): + result = subprocess.run( + ["plutil", "-convert", "json", "-o", "-", strings_path], + capture_output=True, + check=True, + text=True, + ) + return json.loads(result.stdout) + + +def objc_string_literal(value): + escaped = value.replace("\\", "\\\\").replace('"', '\\"') + escaped = escaped.replace("\n", "\\n").replace("\t", "\\t") + return '@"' + escaped + '"' + + +def collect_localizations(): + localizations = {} + + lproj_dirs = sorted(glob.glob(os.path.join(SPARKLE_DIR, "*.lproj"))) + for lproj_dir in lproj_dirs: + lproj_name = os.path.basename(lproj_dir)[: -len(".lproj")] + locale = LPROJ_LOCALE_OVERRIDES.get(lproj_name, lproj_name) + + strings_path = os.path.join(lproj_dir, "Sparkle.strings") + if not os.path.isfile(strings_path): + continue + + table = load_strings(strings_path) + + localized_values = {} + for key in REQUIRED_KEYS: + value = table.get(key) + if value is None: + print("warning: %s.lproj/Sparkle.strings is missing key %r" % (lproj_name, key), file=sys.stderr) + continue + localized_values[key] = value + + if localized_values: + localizations[locale] = localized_values + + return localizations + + +def generate_header(localizations): + lines = [] + lines.append("//") + lines.append("// SPUInstallerProgressLocalizedStrings.h") + lines.append("// Sparkle") + lines.append("//") + lines.append("// This file is auto-generated by Configurations/generate_progress_tool_localizations.py") + lines.append("// Do not edit by hand. Re-run the script after changing the strings below in") + lines.append("// Sparkle/*.lproj/Sparkle.strings") + lines.append("//") + lines.append("") + lines.append("#import ") + lines.append("") + lines.append("static NSDictionary *> *const SPUInstallerProgressLocalizedStringsTable = @{") + for locale in sorted(localizations.keys()): + lines.append(' @"%s": @{' % locale) + for key in REQUIRED_KEYS: + value = localizations[locale].get(key) + if value is None: + continue + lines.append(" %s: %s," % (objc_string_literal(key), objc_string_literal(value))) + lines.append(" },") + lines.append("};") + lines.append("") + return "\n".join(lines) + + +def update_info_plist_localizations(locales): + with open(INFO_PLIST, "rb") as f: + plist = plistlib.load(f) + + sorted_locales = sorted(locales) + if plist.get("CFBundleLocalizations") == sorted_locales: + print("%s is already up to date (%d locales)" % (INFO_PLIST, len(sorted_locales))) + return + + plist["CFBundleLocalizations"] = sorted_locales + + # sort_keys=False preserves the existing top-level key order, so only + # CFBundleLocalizations's contents change in the diff + with open(INFO_PLIST, "wb") as f: + plistlib.dump(plist, f, fmt=plistlib.FMT_XML, sort_keys=False) + + print("Wrote %s (%d locales)" % (INFO_PLIST, len(sorted_locales))) + +def update_header(localizations): + header_contents = generate_header(localizations) + + if os.path.isfile(OUTPUT_HEADER): + with open(OUTPUT_HEADER, "r", encoding="utf-8") as f: + if f.read() == header_contents: + print("%s is already up to date (%d locales)" % (OUTPUT_HEADER, len(localizations))) + return + + with open(OUTPUT_HEADER, "w", encoding="utf-8") as f: + f.write(header_contents) + + print("Wrote %s (%d locales)" % (OUTPUT_HEADER, len(localizations))) + + +def main(): + localizations = collect_localizations() + update_header(localizations) + update_info_plist_localizations(localizations.keys()) + +if __name__ == "__main__": + main() diff --git a/InstallerLauncher/SUInstallerLauncher.m b/InstallerLauncher/SUInstallerLauncher.m index ed6828c2..ecd999dd 100644 --- a/InstallerLauncher/SUInstallerLauncher.m +++ b/InstallerLauncher/SUInstallerLauncher.m @@ -32,7 +32,7 @@ @implementation SUInstallerLauncher -- (BOOL)submitProgressToolAtPath:(NSString *)progressToolPath withHostBundle:(NSBundle *)hostBundle inSystemDomainForInstaller:(BOOL)inSystemDomainForInstaller copiedApplication:(BOOL)copiedApplication SPU_OBJC_DIRECT +- (BOOL)submitProgressToolAtPath:(NSString *)progressToolPath withHostBundle:(NSBundle *)hostBundle inSystemDomainForInstaller:(BOOL)inSystemDomainForInstaller SPU_OBJC_DIRECT { SUFileManager *fileManager = [[SUFileManager alloc] init]; @@ -53,7 +53,7 @@ NSString *hostBundleIdentifier = hostBundle.bundleIdentifier; assert(hostBundleIdentifier != nil); - NSArray *arguments = @[executablePath, hostBundlePath, @(inSystemDomainForInstaller).stringValue, @(copiedApplication).stringValue]; + NSArray *arguments = @[executablePath, hostBundlePath, @(inSystemDomainForInstaller).stringValue]; // The progress tool can only be ran as the logged in user, not as root CFStringRef domain = kSMDomainUserLaunchd; @@ -525,52 +525,11 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, BOOL rootUser } } - // It may be tempting here to validate/match the signature of the installer and progress tool, however this is not very reliable - // We can't compare the signature of this framework/XPC service (depending how it's run) to the host bundle because - // they could be different (eg: take a look at sparkle-cli). We also can't easily tell if the signature of the service/framework is the same as the bundle it's inside. - // The service/framework also need not even be signed in the first place. We'll just assume for now the original bundle hasn't been tampered with - - // Don't create cache directories or copy the progress tool app outside of the bundle for root user, - // because the app will not start if it's contained inside directories owned by root, - // and un-doing that opens up potential security issues. - // Eventually we will also want to not copy the tool app in the !rootUser case, minimizing risk - // by not making that change yet. - BOOL copyProgressTool = !rootUser; - NSString *progressToolPath; - if (copyProgressTool) { - NSString *cachePath = [SPULocalCacheDirectory cachePathForBundleIdentifier:hostBundleIdentifier]; - - NSString *rootLauncherCachePath = [cachePath stringByAppendingPathComponent:@"Launcher"]; - - [SPULocalCacheDirectory removeOldItemsInDirectory:rootLauncherCachePath]; - - NSString *launcherCachePath = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootLauncherCachePath]; - - if (launcherCachePath == nil) { - SULog(SULogLevelError, @"Failed to create cache directory for progress tool in %@", rootLauncherCachePath); - completionHandler(SUInstallerLauncherFailure, inSystemDomain); - return; - } - - progressToolPath = [launcherCachePath stringByAppendingPathComponent:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME@".app"]; - - NSError *copyError = nil; - // SUFileManager is more reliable for copying files around - SUFileManager *fileManager = [[SUFileManager alloc] init]; - if (![fileManager copyItemAtURL:[NSURL fileURLWithPath:progressToolResourcePath] toURL:[NSURL fileURLWithPath:progressToolPath] error:©Error]) { - SULog(SULogLevelError, @"Failed to copy progress tool to cache: %@", copyError); - completionHandler(SUInstallerLauncherFailure, inSystemDomain); - return; - } - } else { - progressToolPath = progressToolResourcePath; - } - SUInstallerLauncherStatus installerStatus = [self submitInstallerAtPath:installerPath withHostBundle:hostBundle iconBundlePath:mainBundle.bundlePath updaterIdentifier:updaterIdentifier userName:userName homeDirectory:homeDirectory mainBundleName:mainBundleName inSystemDomain:inSystemDomain rootUser:rootUser]; BOOL submittedProgressTool = NO; if (installerStatus == SUInstallerLauncherSuccess) { - submittedProgressTool = [self submitProgressToolAtPath:progressToolPath withHostBundle:hostBundle inSystemDomainForInstaller:inSystemDomain copiedApplication:copyProgressTool]; + submittedProgressTool = [self submitProgressToolAtPath:progressToolResourcePath withHostBundle:hostBundle inSystemDomainForInstaller:inSystemDomain]; if (!submittedProgressTool) { SULog(SULogLevelError, @"Failed to submit progress tool job"); diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 4c27b852..65a808e4 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -53,7 +53,6 @@ 14958C6F19AEBC980061B14F /* test-pubkey.pem in Resources */ = {isa = PBXBuildFile; fileRef = 14958C6C19AEBC610061B14F /* test-pubkey.pem */; }; 1EAA4C8B2132C7BF00604473 /* ReleaseNotesColorStyle.css in Resources */ = {isa = PBXBuildFile; fileRef = 1EAA4C8A2132C7BF00604473 /* ReleaseNotesColorStyle.css */; }; 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 55C14BEF136EF21700649790 /* SUStatus.xib in Resources */ = {isa = PBXBuildFile; fileRef = 55C14BD8136EF00C00649790 /* SUStatus.xib */; }; 55C14F06136EF6DB00649790 /* SULog.h in Headers */ = {isa = PBXBuildFile; fileRef = 55C14F04136EF6DB00649790 /* SULog.h */; }; 55C14F07136EF6DB00649790 /* SULog.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14F05136EF6DB00649790 /* SULog.m */; }; 55E6F33319EC9F6C00005E76 /* SUErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 55E6F33219EC9F6C00005E76 /* SUErrors.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -434,7 +433,6 @@ 72EB736129BEB36100FBCEE7 /* DevSignedAppVersion2.zip in Resources */ = {isa = PBXBuildFile; fileRef = 72EB736029BEB36100FBCEE7 /* DevSignedAppVersion2.zip */; }; 72EB87EA1CB8798800C37F42 /* ShowInstallerProgress.m in Sources */ = {isa = PBXBuildFile; fileRef = 72EB87E91CB8798800C37F42 /* ShowInstallerProgress.m */; }; 72EB87EB1CB8859100C37F42 /* Updater.app in Copy Tools */ = {isa = PBXBuildFile; fileRef = 721C24451CB753E6005440CB /* Updater.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; - 72EB87EC1CB8887E00C37F42 /* SUStatus.xib in Resources */ = {isa = PBXBuildFile; fileRef = 55C14BD8136EF00C00649790 /* SUStatus.xib */; }; 72EE17FB26D1CC8800C58B19 /* SUInstallerLauncher+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 72EE17FA26D1CBC000C58B19 /* SUInstallerLauncher+Private.h */; settings = {ATTRIBUTES = (Private, ); }; }; 72EE17FC26D1CC9D00C58B19 /* SPUInstallationType.h in Headers */ = {isa = PBXBuildFile; fileRef = 7214B8851D45AD9A00CB5CED /* SPUInstallationType.h */; settings = {ATTRIBUTES = (Private, ); }; }; 72EE181926DAE70900C58B19 /* SPUUpdateCheck.h in Headers */ = {isa = PBXBuildFile; fileRef = 72EE181826DAE6E100C58B19 /* SPUUpdateCheck.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -957,7 +955,6 @@ 4607BEA21948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = nb; path = nb.lproj/Sparkle.strings; sourceTree = ""; }; 525A278F133D6AE900FD8D70 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; 555CF29A196C52330000B31E /* el */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = el; path = el.lproj/Sparkle.strings; sourceTree = ""; }; - 55C14BD8136EF00C00649790 /* SUStatus.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = SUStatus.xib; sourceTree = ""; }; 55C14F04136EF6DB00649790 /* SULog.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SULog.h; sourceTree = ""; }; 55C14F05136EF6DB00649790 /* SULog.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SULog.m; sourceTree = ""; }; 55C14F31136EFC2400649790 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; @@ -1344,6 +1341,8 @@ 72B767E51C9CFD7200A07552 /* SPUAutomaticUpdateDriver.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPUAutomaticUpdateDriver.m; sourceTree = ""; }; 72BC6C3C275027BF0083F14B /* SparkleTestCodeSign_apfs.dmg */ = {isa = PBXFileReference; lastKnownFileType = file; path = SparkleTestCodeSign_apfs.dmg; sourceTree = ""; }; 72BEBFEE1D7287560019146B /* SUSpotlightImporterTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUSpotlightImporterTest.swift; sourceTree = ""; }; + 72C4E01F30340BE400DAF61C /* SPUInstallerProgressLocalizedStrings.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUInstallerProgressLocalizedStrings.h; sourceTree = ""; }; + 72C4E02030340C2B00DAF61C /* generate_progress_tool_localizations.py */ = {isa = PBXFileReference; lastKnownFileType = text.script.python; path = generate_progress_tool_localizations.py; sourceTree = ""; }; 72C56E072EFDFB850005A484 /* SPUExtractSignedFeed.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUExtractSignedFeed.h; sourceTree = ""; }; 72C56E082EFDFB850005A484 /* SPUExtractSignedFeed.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SPUExtractSignedFeed.m; sourceTree = ""; }; 72C56E0F2EFEF10B0005A484 /* Signing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Signing.swift; sourceTree = ""; }; @@ -1727,7 +1726,6 @@ children = ( 8DC2EF5A0486A6940098B216 /* Sparkle-Info.plist */, 61AAE8220A321A7F00D8810D /* Sparkle.strings */, - 55C14BD8136EF00C00649790 /* SUStatus.xib */, 729C51272E58015600D7365A /* SUUpdatePermissionPrompt.xib */, 72FE54412E56A14100227A91 /* SUUpdateAlert.xib */, ); @@ -2161,6 +2159,7 @@ 72D954801CBACC35006F28BD /* InstallerProgressAppController.m */, 72D954851CBAD4AE006F28BD /* InstallerProgressDelegate.h */, 72D954821CBAD34F006F28BD /* main.m */, + 72C4E01F30340BE400DAF61C /* SPUInstallerProgressLocalizedStrings.h */, 72D954841CBAD418006F28BD /* ShowInstallerProgress.h */, 72EB87E91CB8798800C37F42 /* ShowInstallerProgress.m */, 722194511D3BF987004C34FF /* SPUInstallerAgentProtocol.h */, @@ -2492,6 +2491,7 @@ 72045CE426FEE708004F96E5 /* strip-framework.sh */, 720C192827127A3800740C8E /* release-move-tag.sh */, 720B4C2325EBFAFD005A0592 /* link-tools.sh */, + 72C4E02030340C2B00DAF61C /* generate_progress_tool_localizations.py */, ); path = Configurations; sourceTree = ""; @@ -3197,7 +3197,6 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 72EB87EC1CB8887E00C37F42 /* SUStatus.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3250,7 +3249,6 @@ 61AAE8280A321A7F00D8810D /* Sparkle.strings in Resources */, 1EAA4C8B2132C7BF00604473 /* ReleaseNotesColorStyle.css in Resources */, 72FE54422E56A14100227A91 /* SUUpdateAlert.xib in Resources */, - 55C14BEF136EF21700649790 /* SUStatus.xib in Resources */, 729C51282E58015600D7365A /* SUUpdatePermissionPrompt.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Sparkle/InstallerProgress/InstallerProgress-Info.plist b/Sparkle/InstallerProgress/InstallerProgress-Info.plist index d7dc4d54..9415c157 100644 --- a/Sparkle/InstallerProgress/InstallerProgress-Info.plist +++ b/Sparkle/InstallerProgress/InstallerProgress-Info.plist @@ -30,13 +30,13 @@ 1 CFBundleLocalizations - en - ca ar + ca cs da de el + en es fa fi diff --git a/Sparkle/InstallerProgress/InstallerProgressAppController.m b/Sparkle/InstallerProgress/InstallerProgressAppController.m index 8859063d..fc56a979 100644 --- a/Sparkle/InstallerProgress/InstallerProgressAppController.m +++ b/Sparkle/InstallerProgress/InstallerProgressAppController.m @@ -11,7 +11,6 @@ #import "SPUMessageTypes.h" #import "SULog.h" #import "SULog+NSError.h" -#import "SUApplicationInfo.h" #import "SPUInstallerAgentProtocol.h" #import "SUInstallerAgentInitiationProtocol.h" #import "StatusInfo.h" @@ -62,14 +61,13 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; BOOL _submittedLauncherJob; BOOL _willTerminate; BOOL _applicationInitiallyAlive; - BOOL _copiedApplication; } - (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray *)arguments delegate:(id)delegate { self = [super init]; if (self != nil) { - if (arguments.count != 4) { + if (arguments.count != 3) { SULog(SULogLevelError, @"Error: Invalid number of arguments supplied: %@", arguments); [self cleanupAndExitWithStatus:EXIT_FAILURE error:nil]; } @@ -115,10 +113,6 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; _application = application; _delegate = delegate; - BOOL copiedApplication = arguments[3].boolValue; - [delegate loadLocalizationStringsFromHost:host copiedApplication:copiedApplication]; - _copiedApplication = copiedApplication; - _connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUInstallerAgentProtocol)]; _connection.exportedObject = self; @@ -195,28 +189,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; [_statusInfo invalidate]; [_connection invalidate]; - - if (_copiedApplication) { - // Remove the agent bundle; it is assumed this bundle is in a temporary/cache/support directory - NSError *theError = nil; - NSString *bundlePath = [[NSBundle mainBundle] bundlePath]; - - if (![[NSFileManager defaultManager] removeItemAtPath:bundlePath error:&theError]) { - SULog(SULogLevelError, @"Couldn't remove agent bundle: %@.", theError); - } else { - // There should be nothing else in the parent temporary directory given to us, - // so let us try to remove it. Note rmdir() will fail if there are unexpectably other - // items present - NSString *parentDirectory = bundlePath.stringByDeletingLastPathComponent; - const char *fileSystemRepresentation = parentDirectory.fileSystemRepresentation; - if (fileSystemRepresentation != NULL) { - if (rmdir(fileSystemRepresentation) != 0) { - SULog(SULogLevelError, @"Failed to remove parent agent bundle directory: %@: %d", parentDirectory, errno); - } - } - } - } - + exit(status); } @@ -448,19 +421,9 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; { dispatch_async(dispatch_get_main_queue(), ^{ if (!self->_willTerminate) { - // Show app icon in the dock - ProcessSerialNumber psn = { 0, kCurrentProcess }; - TransformProcessType(&psn, kProcessTransformToForegroundApplication); - - // Note: the application icon needs to be set after showing the icon in the dock - self->_application.applicationIconImage = [SUApplicationInfo bestIconForHost:self->_oldHost]; - // Activate ourselves otherwise we will probably be in the background - if (@available(macOS 14, *)) { - [self->_application activate]; - } else { - [self->_application activateIgnoringOtherApps:YES]; - } + // See comments in -[SPUStandardUserDriver _activateApplication] for why -activate is not used + [self->_application activateIgnoringOtherApps:YES]; [self->_delegate installerProgressShouldDisplayWithHost:self->_oldHost]; } diff --git a/Sparkle/InstallerProgress/InstallerProgressDelegate.h b/Sparkle/InstallerProgress/InstallerProgressDelegate.h index 7cf6684e..887b1bb8 100644 --- a/Sparkle/InstallerProgress/InstallerProgressDelegate.h +++ b/Sparkle/InstallerProgress/InstallerProgressDelegate.h @@ -14,7 +14,6 @@ NS_ASSUME_NONNULL_BEGIN @protocol InstallerProgressDelegate -- (void)loadLocalizationStringsFromHost:(SUHost *)host copiedApplication:(BOOL)copiedApplication; - (void)installerProgressShouldDisplayWithHost:(SUHost *)host; - (void)installerProgressShouldStop; diff --git a/Sparkle/InstallerProgress/SPUInstallerProgressLocalizedStrings.h b/Sparkle/InstallerProgress/SPUInstallerProgressLocalizedStrings.h new file mode 100644 index 00000000..c60796e7 --- /dev/null +++ b/Sparkle/InstallerProgress/SPUInstallerProgressLocalizedStrings.h @@ -0,0 +1,189 @@ +// +// SPUInstallerProgressLocalizedStrings.h +// Sparkle +// +// This file is auto-generated by Configurations/generate_progress_tool_localizations.py +// Do not edit by hand. Re-run the script after changing the strings below in +// Sparkle/*.lproj/Sparkle.strings +// + +#import + +static NSDictionary *> *const SPUInstallerProgressLocalizedStringsTable = @{ + @"ar": @{ + @"Cancel Update": @"إلغاء التحديث", + @"Updating %@": @"تحديث %@", + }, + @"ca": @{ + @"Installing update…": @"Instal·lant l'actualització…", + @"Updating %@": @"Actualitzant %@", + }, + @"cs": @{ + @"Cancel Update": @"Zrušit aktualizaci", + @"Installing update…": @"Instaluje se aktualizace…", + @"Updating %@": @"Aktualizuje se %@", + }, + @"da": @{ + @"Cancel Update": @"Annuller opdatering", + @"Installing update…": @"Installerer opdatering…", + @"Updating %@": @"Opdaterer %@", + }, + @"de": @{ + @"Cancel Update": @"Aktualisierung abbrechen", + @"Installing update…": @"Update installieren …", + @"Updating %@": @"Aktualisierung von %@", + }, + @"el": @{ + @"Cancel Update": @"Ακύρωση Ενημέρωσης", + @"Installing update…": @"Εγκατάσταση ενημέρωσης…", + @"Updating %@": @"Ενημέρωση %@", + }, + @"en": @{ + @"Cancel Update": @"Cancel Update", + @"Installing update…": @"Installing update…", + @"Updating %@": @"Updating %@", + }, + @"es": @{ + @"Cancel Update": @"Cancelar actualización", + @"Installing update…": @"Instalando actualización…", + @"Updating %@": @"Actualizando %@", + }, + @"fa": @{ + @"Cancel Update": @"لغو به‌روزرسانی", + @"Installing update…": @"در حال نصب به‌روزرسانی", + @"Updating %@": @"%@ در حال به‌روزرسانی", + }, + @"fi": @{ + @"Cancel Update": @"Peruuta päivitykset", + @"Installing update…": @"Päivitys asennetaan…", + @"Updating %@": @"Päivitetään %@", + }, + @"fr": @{ + @"Cancel Update": @"Annuler la mise à jour", + @"Installing update…": @"Installation de la mise à jour…", + @"Updating %@": @"Mise à jour de %@", + }, + @"he": @{ + @"Cancel Update": @"בטל את העדכון", + @"Installing update…": @"מתקין את העדכון", + @"Updating %@": @"עדכון %@", + }, + @"hr": @{ + @"Cancel Update": @"Prekini aktualiziranje", + @"Installing update…": @"Instaliranje nadogradnje …", + @"Updating %@": @"%@ se aktualizira", + }, + @"hu": @{ + @"Cancel Update": @"Frissítés megszakítása", + @"Updating %@": @"%@ frissítése", + }, + @"is": @{ + @"Installing update…": @"Set inn uppfærslu…", + @"Updating %@": @"Uppfæri %@", + }, + @"it": @{ + @"Cancel Update": @"Annulla Aggiornamento", + @"Installing update…": @"Installazione aggiornamento in corso…", + @"Updating %@": @"Aggiornamento di %@", + }, + @"ja": @{ + @"Cancel Update": @"アップデートを中止", + @"Installing update…": @"アップデートをインストールしています…", + @"Updating %@": @"%@をアップデート中", + }, + @"ko": @{ + @"Cancel Update": @"업데이트 취소", + @"Installing update…": @"설치 중…", + @"Updating %@": @"%@ 업데이트 중", + }, + @"nb": @{ + @"Cancel Update": @"Avbryt oppdateringen", + @"Installing update…": @"Installerer oppdateringen…", + @"Updating %@": @"Oppdaterer %@", + }, + @"nl": @{ + @"Cancel Update": @"Annuleer update", + @"Installing update…": @"Update installeren…", + @"Updating %@": @"%@ bijwerken…", + }, + @"nn": @{ + @"Cancel Update": @"Avbryt oppdateringa", + @"Installing update…": @"Installerer oppdateringa…", + @"Updating %@": @"Oppdaterer %@", + }, + @"pl": @{ + @"Cancel Update": @"Anuluj uaktualnianie", + @"Installing update…": @"Instalowanie uaktualnienia…", + @"Updating %@": @"Uaktualniam %@", + }, + @"pt-BR": @{ + @"Cancel Update": @"Cancelar Atualização", + @"Installing update…": @"Instalando atualização…", + @"Updating %@": @"Atualizando o app %@", + }, + @"pt-PT": @{ + @"Cancel Update": @"Cancelar actualização", + @"Installing update…": @"A instalar actualização…", + @"Updating %@": @"A actualizar o %@", + }, + @"ro": @{ + @"Cancel Update": @"Anulează actualizarea", + @"Installing update…": @"Instalează actualizarea…", + @"Updating %@": @"Actualizează %@", + }, + @"ru": @{ + @"Cancel Update": @"Отменить обновление", + @"Installing update…": @"Устанавливаю обновление…", + @"Updating %@": @"Обновляю %@", + }, + @"sk": @{ + @"Cancel Update": @"Zrušiť aktualizáciu", + @"Installing update…": @"Inštaluje sa aktualizácia…", + @"Updating %@": @"Aktualizuje sa %@", + }, + @"sl": @{ + @"Cancel Update": @"Prekliči posodabljanje", + @"Installing update…": @"Nameščanje posodobitve …", + @"Updating %@": @"Posodabljam %@", + }, + @"sv": @{ + @"Cancel Update": @"Avbryt uppdatering", + @"Installing update…": @"Installerar uppdatering…", + @"Updating %@": @"Uppdaterar %@", + }, + @"th": @{ + @"Cancel Update": @"ยกเลิกอัพเดท", + @"Installing update…": @"กำลังติดตั้งอัพเดท…", + @"Updating %@": @"กำลังอัพเดท %@", + }, + @"tr": @{ + @"Cancel Update": @"Güncellemeden Vazgeç", + @"Installing update…": @"Güncelleme kuruluyor…", + @"Updating %@": @"%@ güncelleniyor", + }, + @"uk": @{ + @"Cancel Update": @"Відмінити оновлення", + @"Installing update…": @"Встановлюю оновлення…", + @"Updating %@": @"Оновлюю %@", + }, + @"vi": @{ + @"Cancel Update": @"Hủy cập nhật", + @"Installing update…": @"Đang cài đặt bản cập nhật…", + @"Updating %@": @"Đang cập nhật %@", + }, + @"zh_CN": @{ + @"Cancel Update": @"取消更新", + @"Installing update…": @"正在安装更新…", + @"Updating %@": @"正在更新%@", + }, + @"zh_HK": @{ + @"Cancel Update": @"取消更新", + @"Installing update…": @"安裝緊更新⋯", + @"Updating %@": @"更新緊 %@", + }, + @"zh_TW": @{ + @"Cancel Update": @"取消更新", + @"Installing update…": @"正在安裝更新項目⋯", + @"Updating %@": @"正在更新%@", + }, +}; diff --git a/Sparkle/InstallerProgress/ShowInstallerProgress.m b/Sparkle/InstallerProgress/ShowInstallerProgress.m index 2a088942..1aec3e24 100644 --- a/Sparkle/InstallerProgress/ShowInstallerProgress.m +++ b/Sparkle/InstallerProgress/ShowInstallerProgress.m @@ -10,108 +10,50 @@ #import "ShowInstallerProgress.h" #import "SUStatusController.h" #import "SUHost.h" -#import "SULocalizations.h" + +#if SPARKLE_COPY_LOCALIZATIONS +#import "SPUInstallerProgressLocalizedStrings.h" +#endif @implementation ShowInstallerProgress { SUStatusController *_statusController; - NSString *_updatingString; - NSString *_cancelUpdateTitle; - NSString *_installingUpdateTitle; } -- (void)createStatusControllerWithHost:(SUHost *)host SPU_OBJC_DIRECT +#if SPARKLE_COPY_LOCALIZATIONS +// SPUInstallerProgressLocalizedStringsTable is generated at development time (by Configurations/generate_progress_tool_localizations.py) +static NSDictionary *SUBestMatchingInstallerProgressLocalizedStrings(void) { - _statusController = [[SUStatusController alloc] initWithHost:host windowTitle:_updatingString centerPointValue:nil minimizable:NO closable:NO]; + NSArray *availableLocalizations = SPUInstallerProgressLocalizedStringsTable.allKeys; + NSArray *preferredLocalizations = [NSBundle preferredLocalizationsFromArray:availableLocalizations]; + NSString *bestLocalization = preferredLocalizations.firstObject ?: @"en"; + return SPUInstallerProgressLocalizedStringsTable[bestLocalization] ?: SPUInstallerProgressLocalizedStringsTable[@"en"]; } - -- (void)loadLocalizationStringsFromHost:(SUHost *)host copiedApplication:(BOOL)copiedApplication -{ - // Try to retrieve localization strings from the old bundle if possible - // We won't display these strings until installerProgressShouldDisplayWithHost: - // (which will be after the update is trusted) - // If we fail to load localizations in any way, we default to English - -#if SPARKLE_COPY_LOCALIZATIONS - NSBundle *hostSparkleBundle; - { - NSURL *hostSparkleURL = [host.bundle.privateFrameworksURL URLByAppendingPathComponent:@"Sparkle.framework" isDirectory:YES]; - if (hostSparkleURL == nil) { - hostSparkleBundle = nil; - } else { - hostSparkleBundle = [NSBundle bundleWithURL:hostSparkleURL]; - } - } #endif - - NSString *updatingString; - { - NSString *hostNameFromBundle = host.name; - NSString *hostName = (hostNameFromBundle != nil) ? hostNameFromBundle : @""; - -#if SPARKLE_COPY_LOCALIZATIONS - { - NSString *updatingFormatStringFromBundle = (hostSparkleBundle != nil) ? SULocalizedStringFromTableInBundle(@"Updating %@", @"Sparkle", hostSparkleBundle, nil) : nil; - - if (updatingFormatStringFromBundle != nil) { - // Replacing the %@ will be a bit safer than using +[NSString stringWithFormat:] - updatingString = [updatingFormatStringFromBundle stringByReplacingOccurrencesOfString:@"%@" withString:hostName]; - } else { - updatingString = [@"Updating " stringByAppendingString:hostName]; - } - } -#else - { - updatingString = [@"Updating " stringByAppendingString:hostName]; - } -#endif - } - - _updatingString = updatingString; - - NSString *cancelUpdateTitle; -#if SPARKLE_COPY_LOCALIZATIONS - { - NSString *cancelUpdateTitleFromBundle = (hostSparkleBundle != nil) ? SULocalizedStringFromTableInBundle(@"Cancel Update", @"Sparkle", hostSparkleBundle, @"") : nil; - cancelUpdateTitle = (cancelUpdateTitleFromBundle != nil) ? cancelUpdateTitleFromBundle : @"Cancel Update"; - } -#else - { - cancelUpdateTitle = @"Cancel Update"; - } -#endif - _cancelUpdateTitle = cancelUpdateTitle; - - NSString *installingUpdateTitle; -#if SPARKLE_COPY_LOCALIZATIONS - { - NSString *installingUpdateTitleFromBundle = (hostSparkleBundle != nil) ? SULocalizedStringFromTableInBundle(@"Installing update…", @"Sparkle", hostSparkleBundle, @"") : nil; - installingUpdateTitle = (installingUpdateTitleFromBundle != nil) ? installingUpdateTitleFromBundle : @"Installing update…"; - } -#else - { - installingUpdateTitle = @"Installing update…"; - } -#endif - - _installingUpdateTitle = installingUpdateTitle; - - // Initialize status controller immediately if app isn't copied, before the app may be swapped/removed - // This gaurantees we will be able to load the nib - if (!copiedApplication) { - [self createStatusControllerWithHost:host]; - } -} - (void)installerProgressShouldDisplayWithHost:(SUHost *)host { - if (_statusController == nil) { - [self createStatusControllerWithHost:host]; - } +#if SPARKLE_COPY_LOCALIZATIONS + NSDictionary *localizedStrings = SUBestMatchingInstallerProgressLocalizedStrings(); +#else + NSDictionary *localizedStrings = @{}; +#endif + + NSString *hostNameFromBundle = host.name; + NSString *hostName = (hostNameFromBundle != nil) ? hostNameFromBundle : @""; + + NSString *updatingFormatString = localizedStrings[@"Updating %@"] ?: @"Updating %@"; + NSString *updatingString = [updatingFormatString stringByReplacingOccurrencesOfString:@"%@" withString:hostName]; + + NSString *cancelUpdateTitle = localizedStrings[@"Cancel Update"] ?: @"Cancel Update"; + + NSString *installingUpdateTitle = localizedStrings[@"Installing update…"] ?: @"Installing update…"; - [_statusController setButtonTitle:_cancelUpdateTitle target:nil action:nil isDefault:NO accessibilityIdentifier:@"SUStatusCancel"]; + _statusController = [[SUStatusController alloc] initWithHost:host windowTitle:updatingString centerPointValue:nil minimizable:NO closable:NO]; - [_statusController beginActionWithTitle:_installingUpdateTitle maxProgressValue:0 statusText:@""]; + [_statusController setButtonTitle:cancelUpdateTitle target:nil action:nil isDefault:NO accessibilityIdentifier:@"SUStatusCancel"]; + + [_statusController beginActionWithTitle:installingUpdateTitle maxProgressValue:0 statusText:@""]; [_statusController showWindow:self]; } diff --git a/Sparkle/SPUInstallerDriver.m b/Sparkle/SPUInstallerDriver.m index d780ee3b..c35129d6 100644 --- a/Sparkle/SPUInstallerDriver.m +++ b/Sparkle/SPUInstallerDriver.m @@ -41,17 +41,6 @@ @end #endif -// Note: we don't want to directly pull in AppKit here especially if the main application does not need it -@interface NSObject (ActivationAPIs) -// NSApplication -+ (id)sharedApplication; -- (void)yieldActivationToApplication:(id)application; - -// NSRunningApplication -+ (NSArray *)runningApplicationsWithBundleIdentifier:(NSString *)bundleIdentifier; -- (NSURL *)bundleURL; -@end - @interface SPUInstallerDriver () @end @@ -557,46 +546,6 @@ _relaunch = relaunch; - // If AppKit is loaded, we will yield to our Sparkle progress app - // This will let the system know it should be okay for the progress agent to activate itself (if necessary) - // Note we don't want to directly pull in AppKit here especially if the main application does not need it - if (showUI) { - if (@available(macOS 14, *)) { - // Make sure we are not root before using AppKit API - if (geteuid() != 0) { - Class applicationClass = NSClassFromString(@"NSApplication"); - if ([applicationClass respondsToSelector:@selector(sharedApplication)]) { - NSObject *application = [applicationClass sharedApplication]; - - if ([application respondsToSelector:@selector(yieldActivationToApplication:)]) { - Class runningApplicationClass = NSClassFromString(@"NSRunningApplication"); - if ([runningApplicationClass respondsToSelector:@selector(runningApplicationsWithBundleIdentifier:)]) { - NSArray *runningApplications = [runningApplicationClass runningApplicationsWithBundleIdentifier:@SPARKLE_INSTALLER_PROGRESS_TOOL_BUNDLE_ID]; - - NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; - - id targetRunningApplication = nil; - for (id runningApplication in runningApplications) { - if ([(NSObject *)runningApplication respondsToSelector:@selector(bundleURL)]) { - NSURL *bundleURL = [(NSObject *)runningApplication bundleURL]; - - if (hostBundleIdentifier != nil && [bundleURL.pathComponents containsObject:hostBundleIdentifier]) { - targetRunningApplication = runningApplication; - break; - } - } - } - - if (targetRunningApplication != nil) { - [application yieldActivationToApplication:targetRunningApplication]; - } - } - } - } - } - } - } - // The user can request trying to relaunch/quit the app multiple times // Avoid re-notifying the delegate twice if (!_notifiedDelegateInstallationWillFinish) { diff --git a/Sparkle/SPUStandardUserDriver.m b/Sparkle/SPUStandardUserDriver.m index 0369779a..db79aa0e 100644 --- a/Sparkle/SPUStandardUserDriver.m +++ b/Sparkle/SPUStandardUserDriver.m @@ -546,7 +546,6 @@ #endif _checkingController = [[SUStatusController alloc] initWithHost:_host windowTitle:SULocalizedStringFromTableInBundle(@"Software Update", SPARKLE_TABLE, sparkleBundle, nil) centerPointValue:nil minimizable:NO closable:NO]; - [[_checkingController window] center]; // Force the checking controller to load its window. [_checkingController beginActionWithTitle:SULocalizedStringFromTableInBundle(@"Checking for updates…", SPARKLE_TABLE, sparkleBundle, nil) maxProgressValue:0.0 statusText:nil]; [_checkingController setButtonTitle:SULocalizedStringFromTableInBundle(@"Cancel", SPARKLE_TABLE, sparkleBundle, nil) target:self action:@selector(cancelCheckForUpdates:) isDefault:NO accessibilityIdentifier:@"SUStatusCancel"]; diff --git a/Sparkle/SUStatus.xib b/Sparkle/SUStatus.xib deleted file mode 100644 index c505f8d6..00000000 --- a/Sparkle/SUStatus.xib +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - NSIsNil - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Sparkle/SUStatusController.m b/Sparkle/SUStatusController.m index 22f277bb..2a3cf00c 100644 --- a/Sparkle/SUStatusController.m +++ b/Sparkle/SUStatusController.m @@ -26,19 +26,15 @@ static NSString *const SUStatusControllerTouchBarIdentifier = @"" SPARKLE_BUNDLE @implementation SUStatusController { - NSString *_windowTitle; NSValue *_centerPointValue; NSString *_title; NSString *_buttonTitle; SUHost *_host; NSButton *_touchBarButton; - - IBOutlet NSButton *_actionButton; - IBOutlet NSTextField *_statusTextField; - IBOutlet NSProgressIndicator *_progressBar; - - BOOL _minimizable; - BOOL _closable; + + NSTextField *_titleField; + NSButton *_actionButton; + NSProgressIndicator *_progressBar; } @synthesize title = _title; @@ -49,15 +45,145 @@ static NSString *const SUStatusControllerTouchBarIdentifier = @"" SPARKLE_BUNDLE - (instancetype)initWithHost:(SUHost *)aHost windowTitle:(NSString *)windowTitle centerPointValue:(NSValue *)centerPointValue minimizable:(BOOL)minimizable closable:(BOOL)closable { - self = [super initWithWindowNibName:@"SUStatus" owner:self]; - if (self) + NSWindow *window; + NSImageView *imageView; + NSTextField *titleField; + NSProgressIndicator *progressBar; + NSButton *actionButton; + NSTextField *statusTextField; + { + NSWindowStyleMask styleMask = NSWindowStyleMaskTitled; + if (minimizable) { + styleMask |= NSWindowStyleMaskMiniaturizable; + } + if (closable) { + styleMask |= NSWindowStyleMaskClosable; + } + + window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 400, 107) styleMask:styleMask backing:NSBackingStoreBuffered defer:NO]; + window.identifier = @"SUStatus"; + window.title = windowTitle; + window.releasedWhenClosed = NO; + window.allowsToolTipsWhenApplicationIsInactive = NO; + window.autorecalculatesKeyViewLoop = NO; + // Don't let this window make other active windows exit in Stage Manager + window.collectionBehavior = NSWindowCollectionBehaviorFullScreenAuxiliary; + window.contentMinSize = NSMakeSize(213, 107); + + NSView *contentView = window.contentView; + + imageView = [[NSImageView alloc] initWithFrame:NSZeroRect]; + imageView.translatesAutoresizingMaskIntoConstraints = NO; + imageView.refusesFirstResponder = YES; + imageView.imageAlignment = NSImageAlignLeft; + imageView.imageScaling = NSImageScaleAxesIndependently; + imageView.image = [SUApplicationInfo bestIconForHost:aHost]; + [contentView addSubview:imageView]; + + NSView *statusContainerView = [[NSView alloc] initWithFrame:NSZeroRect]; + statusContainerView.translatesAutoresizingMaskIntoConstraints = NO; + [contentView addSubview:statusContainerView]; + + titleField = [NSTextField labelWithString:@""]; + titleField.translatesAutoresizingMaskIntoConstraints = NO; + titleField.focusRingType = NSFocusRingTypeNone; + titleField.font = [NSFont boldSystemFontOfSize:[NSFont systemFontSize]]; + titleField.textColor = [NSColor controlTextColor]; + [titleField setContentHuggingPriority:750 forOrientation:NSLayoutConstraintOrientationVertical]; + // Don't let the title string line wrap + [titleField setContentCompressionResistancePriority:1000 forOrientation:NSLayoutConstraintOrientationHorizontal]; + [statusContainerView addSubview:titleField]; + + progressBar = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect]; + progressBar.translatesAutoresizingMaskIntoConstraints = NO; + progressBar.wantsLayer = YES; + progressBar.style = NSProgressIndicatorStyleBar; + progressBar.indeterminate = YES; + progressBar.maxValue = 100; + [progressBar setContentHuggingPriority:750 forOrientation:NSLayoutConstraintOrientationVertical]; + [progressBar setUsesThreadedAnimation:YES]; + [statusContainerView addSubview:progressBar]; + + actionButton = [NSButton buttonWithTitle:@"" target:nil action:NULL]; + actionButton.translatesAutoresizingMaskIntoConstraints = NO; + if (@available(macOS 26, *)) { + actionButton.controlSize = NSControlSizeLarge; + } + [actionButton setContentHuggingPriority:750 forOrientation:NSLayoutConstraintOrientationVertical]; + actionButton.accessibilityIdentifier = @"SUStatusButton"; + [contentView addSubview:actionButton]; + + statusTextField = [NSTextField labelWithString:@""]; + [statusTextField setFont:[NSFont monospacedDigitSystemFontOfSize:0 weight:NSFontWeightRegular]]; + statusTextField.translatesAutoresizingMaskIntoConstraints = NO; + statusTextField.focusRingType = NSFocusRingTypeNone; + statusTextField.textColor = [NSColor controlTextColor]; + [statusTextField setContentHuggingPriority:750 forOrientation:NSLayoutConstraintOrientationVertical]; + // Make horizontal compression resistance required for the status text field + [statusTextField setContentCompressionResistancePriority:1000 forOrientation:NSLayoutConstraintOrientationHorizontal]; + [contentView addSubview:statusTextField]; + + [NSLayoutConstraint activateConstraints:@[ + // Status container's internal layout + [NSLayoutConstraint constraintWithItem:statusContainerView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:titleField attribute:NSLayoutAttributeTrailing multiplier:1 constant:0], + [NSLayoutConstraint constraintWithItem:statusContainerView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:progressBar attribute:NSLayoutAttributeBottom multiplier:1 constant:0], + [NSLayoutConstraint constraintWithItem:titleField attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:statusContainerView attribute:NSLayoutAttributeTop multiplier:1 constant:0], + [NSLayoutConstraint constraintWithItem:statusContainerView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:progressBar attribute:NSLayoutAttributeTrailing multiplier:1 constant:0], + [NSLayoutConstraint constraintWithItem:titleField attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:statusContainerView attribute:NSLayoutAttributeLeading multiplier:1 constant:0], + [NSLayoutConstraint constraintWithItem:progressBar attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:statusContainerView attribute:NSLayoutAttributeLeading multiplier:1 constant:0], + [NSLayoutConstraint constraintWithItem:progressBar attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:titleField attribute:NSLayoutAttributeBottom multiplier:1 constant:8], + + // imageView + [imageView.widthAnchor constraintEqualToConstant:64], + [imageView.heightAnchor constraintEqualToConstant:64], + [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeTop multiplier:1 constant:4], + [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeLeading multiplier:1 constant:20], + + // statusContainerView position + [NSLayoutConstraint constraintWithItem:statusContainerView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:imageView attribute:NSLayoutAttributeCenterY multiplier:1 constant:0], + [NSLayoutConstraint constraintWithItem:statusContainerView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:imageView attribute:NSLayoutAttributeTrailing multiplier:1 constant:8], + [NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:statusContainerView attribute:NSLayoutAttributeTrailing multiplier:1 constant:20], + + // statusTextField position + [NSLayoutConstraint constraintWithItem:statusTextField attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:imageView attribute:NSLayoutAttributeTrailing multiplier:1 constant:8], + [NSLayoutConstraint constraintWithItem:statusTextField attribute:NSLayoutAttributeFirstBaseline relatedBy:NSLayoutRelationEqual toItem:actionButton attribute:NSLayoutAttributeFirstBaseline multiplier:1 constant:0], + + // actionButton position + [NSLayoutConstraint constraintWithItem:actionButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:statusContainerView attribute:NSLayoutAttributeBottom multiplier:1 constant:8], + [NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:actionButton attribute:NSLayoutAttributeBottom multiplier:1 constant:20], + [NSLayoutConstraint constraintWithItem:actionButton attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:statusTextField attribute:NSLayoutAttributeTrailing multiplier:1 constant:25], + [NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:actionButton attribute:NSLayoutAttributeTrailing multiplier:1 constant:20], + [actionButton.widthAnchor constraintGreaterThanOrEqualToConstant:100], + ]]; + } + + self = [super initWithWindow:window]; + if (self != nil) { _host = aHost; - _centerPointValue = centerPointValue; - _minimizable = minimizable; - _closable = closable; - _windowTitle = [windowTitle copy]; + _titleField = titleField; + _actionButton = actionButton; + _progressBar = progressBar; [self setShouldCascadeWindows:NO]; + + // Finish setting up bindings + { + NSRect windowFrame = window.frame; + + if (centerPointValue != nil) { + NSPoint centerPoint = centerPointValue.pointValue; + [window setFrameOrigin:NSMakePoint(centerPoint.x - windowFrame.size.width / 2.0, centerPoint.y - windowFrame.size.height / 2.0)]; + } else { + [window center]; + } + + [titleField bind:NSValueBinding toObject:self withKeyPath:@"title" options:nil]; + [progressBar bind:NSMaxValueBinding toObject:self withKeyPath:@"maxProgressValue" options:nil]; + [progressBar bind:NSValueBinding toObject:self withKeyPath:@"progressValue" options:nil]; + [actionButton bind:NSTitleBinding toObject:self withKeyPath:@"buttonTitle" options:nil]; + [statusTextField bind:NSValueBinding toObject:self withKeyPath:@"statusText" options:nil]; + [statusTextField bind:NSHiddenBinding toObject:self withKeyPath:@"statusText" options:@{NSValueTransformerNameBindingOption: NSIsNilTransformerName}]; + } } return self; } @@ -67,39 +193,6 @@ static NSString *const SUStatusControllerTouchBarIdentifier = @"" SPARKLE_BUNDLE return [NSString stringWithFormat:@"%@ <%@>", [self class], _host.bundlePath]; } -- (void)windowDidLoad -{ - NSWindow *window = self.window; - NSRect windowFrame = window.frame; - - if (_centerPointValue != nil) { - NSPoint centerPoint = _centerPointValue.pointValue; - [window setFrameOrigin:NSMakePoint(centerPoint.x - windowFrame.size.width / 2.0, centerPoint.y - windowFrame.size.height / 2.0)]; - } else { - [window center]; - } - - if (_minimizable) { - window.styleMask = (NSWindowStyleMask)(window.styleMask | NSWindowStyleMaskMiniaturizable); - } - if (_closable) { - window.styleMask = (NSWindowStyleMask)(window.styleMask | NSWindowStyleMaskClosable); - } - [_progressBar setUsesThreadedAnimation:YES]; - [_statusTextField setFont:[NSFont monospacedDigitSystemFontOfSize:0 weight:NSFontWeightRegular]]; - - if (@available(macOS 26, *)) { - _actionButton.controlSize = NSControlSizeLarge; - } - - window.title = _windowTitle; -} - -- (NSImage *)applicationIcon -{ - return [SUApplicationInfo bestIconForHost:_host]; -} - - (void)beginActionWithTitle:(NSString *)aTitle maxProgressValue:(double)aMaxProgressValue statusText:(NSString *)aStatusText { self.title = aTitle;