From ec37b8e3f9531b7a87bd3ef1fbb8bbda6b6cd3ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A0=81=E5=86=9C=E9=98=BF=E6=A5=A0?= Date: Mon, 16 Nov 2026 15:46:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(updates):=20=E4=BD=BF=E7=94=A8=20Sparkle?= =?UTF-8?q?=20=E4=BB=8E=E5=8F=91=E5=B8=83=20ZIP=20=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E5=B9=B6=E9=87=8D=E5=90=AF=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Config/Kymo-Info.plist | 24 +++ Config/Kymo-adhoc.entitlements | 13 ++ Config/Kymo.entitlements | 11 ++ Config/Sparkle-library-constraint.plist | 18 ++ README.md | 2 +- docs/architecture.md | 4 +- docs/free-test-distribution.md | 12 +- docs/release-update-plan.md | 4 +- docs/releases/v1.5.md | 21 +++ docs/sparkle-update-plan.md | 20 ++ docs/testing.md | 2 +- kymo.xcodeproj/project.pbxproj | 37 +++- .../xcshareddata/swiftpm/Package.resolved | 15 ++ kymo/App/kymoApp.swift | 6 +- kymo/Core/Services/ReleaseUpdates.swift | 171 +++++------------- kymo/Core/Services/SparkleUpdater.swift | 126 +++++++++++++ kymo/Features/MenuBar/MenuPanelView.swift | 18 +- .../Settings/AppearanceSettingsView.swift | 28 ++- kymo/Resources/Localizable.xcstrings | 161 +++++++++++++++++ kymo/UI/Components/UpdateAction.swift | 44 +++++ kymoTests/ReleaseUpdateChecks.swift | 91 +++++----- tools/check.py | 4 +- tools/package_release.py | 103 ++++++++++- 23 files changed, 716 insertions(+), 219 deletions(-) create mode 100644 Config/Kymo-Info.plist create mode 100644 Config/Kymo-adhoc.entitlements create mode 100644 Config/Kymo.entitlements create mode 100644 Config/Sparkle-library-constraint.plist create mode 100644 docs/releases/v1.5.md create mode 100644 docs/sparkle-update-plan.md create mode 100644 kymo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved create mode 100644 kymo/Core/Services/SparkleUpdater.swift create mode 100644 kymo/UI/Components/UpdateAction.swift diff --git a/Config/Kymo-Info.plist b/Config/Kymo-Info.plist new file mode 100644 index 0000000..52cf119 --- /dev/null +++ b/Config/Kymo-Info.plist @@ -0,0 +1,24 @@ + + + + + SUAllowsAutomaticUpdates + + SUEnableAutomaticChecks + + SUEnableInstallerLauncherService + + SUFeedURL + https://git.airnan.cn/wangairnan/Kymo/releases/download/latest/appcast.xml + SUPublicEDKey + jOL7AATUmzgitnDff81drd31wiPcYWDujII/KU+uhYI= + SURequireSignedFeed + + SUScheduledCheckInterval + 21600 + SUShowReleaseNotes + + SUVerifyUpdateBeforeExtraction + + + diff --git a/Config/Kymo-adhoc.entitlements b/Config/Kymo-adhoc.entitlements new file mode 100644 index 0000000..f0257b8 --- /dev/null +++ b/Config/Kymo-adhoc.entitlements @@ -0,0 +1,13 @@ + + + + + com.apple.security.cs.disable-library-validation + + com.apple.security.temporary-exception.mach-lookup.global-name + + $(PRODUCT_BUNDLE_IDENTIFIER)-spks + $(PRODUCT_BUNDLE_IDENTIFIER)-spki + + + diff --git a/Config/Kymo.entitlements b/Config/Kymo.entitlements new file mode 100644 index 0000000..77493f9 --- /dev/null +++ b/Config/Kymo.entitlements @@ -0,0 +1,11 @@ + + + + + com.apple.security.temporary-exception.mach-lookup.global-name + + $(PRODUCT_BUNDLE_IDENTIFIER)-spks + $(PRODUCT_BUNDLE_IDENTIFIER)-spki + + + diff --git a/Config/Sparkle-library-constraint.plist b/Config/Sparkle-library-constraint.plist new file mode 100644 index 0000000..6af2354 --- /dev/null +++ b/Config/Sparkle-library-constraint.plist @@ -0,0 +1,18 @@ + + + + + cdhash + + $in + + + UZ2SEZ68zg8Ox1KdIRiLa0oRoww= + + + YVeicQp6v0Skchu7R9uuirzJd48= + + + + + diff --git a/README.md b/README.md index 162c8a1..f3d1960 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Kymo 是 macOS 菜单栏资源监控工具。菜单栏以竖条显示 CPU、GPU - 网络:接口切换、收发速率与累计字节、路径状态、本地和公网 IP 及复制。 - 进程:PID、名称、CPU、内存 footprint、CPU 平均功率、线程数六列;路径仍支持搜索和右键复制,无横向滚动条;支持列排序及复制,功率缺失始终排末。 -面板支持固定显示、保持唤醒、暂停 / 恢复采样。首行 CPU / GPU / 内存,次行电池 / 存储 / 网络,第三行进程表跨满内容区;默认三行均高 176pt,面板 648×630pt,小屏退为两列或单列并滚动。CPU、GPU 和内存趋势覆盖整卡,电池、存储和网络趋势位于详情下方。电量柱按供电状态着色,月亮标出系统睡眠时段;CPU 系统 / 用户、内存应用 / 联动 / 压缩按分量堆叠,悬浮查询原始历史;存储 / 网络以绘图区 60% 高度零轴上下显示读 / 写、上传 / 下载,内存不再重复显示容量条。每个逻辑核对应一格,以填充高度表示占用;风扇图标沿用转速档位旋转,暂停、隐藏或系统减弱动态效果时停转。数值随采样直接更新。曲线随新采样平滑平移,遵循系统减弱动态效果。资源和进程同时按可见性采样,后台趋势独立控制。面板及亮屏菜单栏指标默认每 2 秒刷新。设置的「菜单栏」页可预览并勾选 CPU、GPU、内存、磁盘和网络,全部取消则显示品牌图标。没有实时展示需求时,可显式开启后台趋势并配置间隔(新配置 30 秒)。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。通过「关于 Kymo」可直接打开设置的关于页,手动检查更新或关闭默认开启的自动检查。发现新版本后,可从关于页前往项目的正式发布页下载。 +面板支持固定显示、保持唤醒、暂停 / 恢复采样。首行 CPU / GPU / 内存,次行电池 / 存储 / 网络,第三行进程表跨满内容区;默认三行均高 176pt,面板 648×630pt,小屏退为两列或单列并滚动。CPU、GPU 和内存趋势覆盖整卡,电池、存储和网络趋势位于详情下方。电量柱按供电状态着色,月亮标出系统睡眠时段;CPU 系统 / 用户、内存应用 / 联动 / 压缩按分量堆叠,悬浮查询原始历史;存储 / 网络以绘图区 60% 高度零轴上下显示读 / 写、上传 / 下载,内存不再重复显示容量条。每个逻辑核对应一格,以填充高度表示占用;风扇图标沿用转速档位旋转,暂停、隐藏或系统减弱动态效果时停转。数值随采样直接更新。曲线随新采样平滑平移,遵循系统减弱动态效果。资源和进程同时按可见性采样,后台趋势独立控制。面板及亮屏菜单栏指标默认每 2 秒刷新。设置的「菜单栏」页可预览并勾选 CPU、GPU、内存、磁盘和网络,全部取消则显示品牌图标。没有实时展示需求时,可显式开启后台趋势并配置间隔(新配置 30 秒)。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。自动检查默认开启,每次启动及运行中每 6 小时检测更新。发现新版时,面板 Kymo 字样右上角的版本角标可点击下载,准备就绪后再次点击即可重启更新。「关于 Kymo」同步显示更新状态、手动检查入口和自动检查开关。 部分硬件指标依赖机型、驱动与权限,缺失值显示为 `--` 或对应状态。GPU 不提供逐核占用;耗电进程显示系统归属的 CPU 能量区间平均功率,注明可读覆盖范围,不代表完整应用总耗电。指标口径和限制见[监控指标](docs/monitoring.md)。 diff --git a/docs/architecture.md b/docs/architecture.md index 0bde47f..f8844eb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -32,7 +32,9 @@ MenuBarPreferences 在 UserDefaults 保存勾选集合,首次全选,空集 设置窗口打开时转为 regular 模式并恢复焦点,SettingsWindowLifecycle 在关闭后恢复 accessory。关闭最后一个窗口不退出应用;退出时清理状态项、窗口、通知和保持唤醒断言。 -应用主菜单和状态项的「关于 Kymo」共用同一导航动作,可从已打开或已关闭的设置窗口直达关于页。ReleaseUpdates 在 App 启动时读取自动检测偏好(默认开启),向项目的 releases/latest 接口请求正式发行信息。版本按数字分段比较,同版本再取发行 ZIP 的构建号。成功后 24 小时复查,失败后 1 小时重试,手动检测可随时发起,同一时刻只保留一个请求。关闭自动检测会取消后台请求和等待。发现更新后,面板显示打开关于页的按钮,关于页提供对应标签的正式发布页链接。 +应用主菜单和状态项的「关于 Kymo」共用同一导航动作,可从已打开或已关闭的设置窗口直达关于页。App 装配 SparkleUpdater 与 ReleaseUpdates。SparkleUpdater 作为 Sparkle 2 的用户界面驱动和委托,启动时沿用已有的 updates.automatic 偏好(默认开启)。开启时在启动后立即检查,后续由 Sparkle 按 SUScheduledCheckInterval(21600 秒)调度。关闭后保留手动检查。Sparkle 检查签名的 appcast,按 CFBundleVersion 识别新版,并处理系统版本、下载与安装兼容性。发现可用更新后结束检测会话,保留可操作角标;点击下载时重新确认目标构建号,版本已变化则展示新目标。面板品牌角标和关于页共享下载、解压准备、重启和错误重试状态。下载并准备好后由用户点击重启,Sparkle 也可在应用自然退出时完成已准备的安装。 + +更新源固定为最新正式 Release 的 appcast.xml 附件,包地址固定到其版本标签。EdDSA 公钥内置于应用;清单须签名,ZIP 在解压前验证。主程序启用 Sparkle 安装服务和两项限定于本应用标识的 Mach 通信权限,通过现有出站网络权限下载。SMARTService 与更新安装器独立。ad-hoc Release 的 Hardened Runtime 库加载约束仅允许锁定的双架构 Sparkle 库哈希及系统库。升级框架时需要核对官方二进制并同步更新约束。 ## 采样、状态与并发 diff --git a/docs/free-test-distribution.md b/docs/free-test-distribution.md index cf34c25..20d0f47 100644 --- a/docs/free-test-distribution.md +++ b/docs/free-test-distribution.md @@ -1,14 +1,20 @@ # Kymo 免费测试包 -当前版本为 **1.4(构建 16)**。主程序与内嵌 SMARTService 共用工程级 MARKETING_VERSION / CURRENT_PROJECT_VERSION,Debug 与 Release 保持一致。 +当前版本为 **1.5(构建 17)**。主程序与内嵌 SMARTService 共用工程级 MARKETING_VERSION / CURRENT_PROJECT_VERSION,Debug 与 Release 保持一致。 ## 构建与校验 ```bash -python3 tools/package_release.py +python3 tools/package_release.py --output dist/v1.5 ``` -工具构建普通 Release,验证主程序与 XPC 的 ad-hoc 签名、Hardened Runtime、权限和包内容,再校验 ZIP 解压后的签名。默认输出到 Git 忽略的 dist/,文件名按实际版本、构建号与架构生成,包含 ZIP 和同名 .sha256;不覆盖已有产物,可用 --output 指定目录。临时构建目录自动清理。 +工具构建普通 Release,验证主程序与 XPC 的 ad-hoc 签名、Hardened Runtime、权限和包内容,再校验 ZIP 解压后的签名。默认输出到 Git 忽略的 dist/,文件名按实际版本、构建号与架构生成,包含 ZIP、同名 .sha256 和签名的 appcast.xml;不覆盖已有产物,可用 --output 指定目录。临时构建目录自动清理。 + +发布机使用钥匙串账户 `cn.airnan.kymo` 中的 Sparkle EdDSA 私钥,公钥在 `Config/Kymo-Info.plist`。首次访问可能出现钥匙串授权。迁移发布机时用 Sparkle 官方 generate_keys 工具安全备份、导入同一密钥。仅制作本地 ZIP 时可加 `--zip-only`。已有含 Sparkle 的发布包可运行 `python3 tools/package_release.py --sign-existing <原始ZIP路径>`,在原包旁生成 appcast.xml。 + +每次发版递增工程构建号。脚本用最终 ZIP 生成清单,验证签名、构建号、长度和标签下载地址。先在对应标签(如 v1.5)的 Release 草稿中上传 ZIP、SHA-256 和 appcast.xml,再发布。固定入口是同一仓库的 `releases/download/latest/appcast.xml`。完整 ZIP 同时用于首次安装和应用内升级。1.4 及更早版本需要从发布页手动安装一次含 Sparkle 的版本。 + +保留上游框架签名,使 ad-hoc Release 的库加载约束能够逐架构固定 Sparkle 的 CDHash。打包时检查主程序签名中的约束和框架实际哈希。变更框架版本时,先核对 SwiftPM 锁定版本与官方分发包,再更新 `Config/Sparkle-library-constraint.plist`;重新签名框架会改变哈希。 下载后在校验文件所在目录执行: diff --git a/docs/release-update-plan.md b/docs/release-update-plan.md index d85b1fc..d168308 100644 --- a/docs/release-update-plan.md +++ b/docs/release-update-plan.md @@ -1,4 +1,6 @@ -# 正式发布检测与关于页 +# 正式发布检测与关于页(1.4) + +此页记录 1.4 的发布页跳转流程。1.5 的应用内更新见 [Sparkle 更新计划](sparkle-update-plan.md)。 Kymo 从自托管仓库手动发布 ZIP 和校验文件。现有设置窗口包含关于页,应用菜单仅提供设置和退出。此次将菜单定向导航、正式发布检测和用户偏好接入同一窗口。 diff --git a/docs/releases/v1.5.md b/docs/releases/v1.5.md new file mode 100644 index 0000000..9304889 --- /dev/null +++ b/docs/releases/v1.5.md @@ -0,0 +1,21 @@ +Kymo 1.5 新增应用内更新,并改进了电池与适配器共同供电时的显示。 + +### 本版更新 + +- 开启自动检查后,Kymo 每次启动时检查更新,运行期间每 6 小时再检查一次。发现新版时,点击面板左上角 Kymo 标志旁的版本角标即可下载,准备好后再次点击即可重启更新。「关于 Kymo」页也能查看进度、手动检查和重试。已有的自动检查偏好会保留。 +- 电池与适配器共同供电时,电池卡片显示两路功率,历史电量柱用颜色区分各自的供电占比。微量适配器输入不再触发共同供电提示。放电时可查看预估续航,充电时显示预计充满时间,仅由适配器供电时隐藏估时行。 +- 面板底部的「运行时长」更名为「开机时长」,明确显示的是 Mac 自上次启动以来的时间。 + +### 下载与安装 + +适用于 Apple Silicon(arm64),需要 macOS 27.0 或更高版本。版本为 **1.5(构建 17)**,采用 ad-hoc 签名,未经 Apple 公证。 + +从 1.4 或更早版本升级,需要手动安装这一次。下载 ZIP,退出 Kymo,解压后将完整的 `kymo.app` 拖入「应用程序」并重新打开。此后的新版可直接在 Kymo 中下载和安装。 + +如需校验下载,将 ZIP 与同名的 `.sha256` 文件放在同一目录,运行以下命令。 + +```sh +shasum -a 256 -c kymo-1.5-17-arm64-adhoc.zip.sha256 +``` + +ZIP 的 SHA-256 为 `cfb7be2f7d6e3b32a25723ab824c2af64e33e100cadfcace32ae719df9475b52`。 diff --git a/docs/sparkle-update-plan.md b/docs/sparkle-update-plan.md new file mode 100644 index 0000000..812108d --- /dev/null +++ b/docs/sparkle-update-plan.md @@ -0,0 +1,20 @@ +# 现有 ZIP 的应用内更新 + +## 目标与范围 + +沿用自托管 Release 的完整应用 ZIP 和现有自动检查偏好。启动时及运行中每六小时检查一次,发现新版后用户可从面板品牌角标或设置关于页下载,再点击重启。首次切换需要手动安装含更新器的版本。 + +## 设计与实施顺序 + +1. 为主应用接入 Sparkle 2 和沙盒安装服务。发布端为最终 ZIP 增加 EdDSA 签名和 appcast 附件,私钥保存在发布机器的钥匙串。保留 Release / SHA-256 分发。 +2. Core 管理检测偏好与更新阶段,Sparkle 负责定时调度,App 装配更新器,MenuBar 和 Settings 映射同一状态与动作。下载、校验、替换整个应用和重新启动由 Sparkle 执行。 +3. 更新三语文本、发版工具和架构说明,构建 Debug / Release。用隔离的两个构建、测试更新源和真实 ZIP 验证下载、重启、保留偏好;检查关闭自动检测、无更新、错误与重试。 +4. 在本页记录验证边界。重点验证 ad-hoc 和 Hardened Runtime 的兼容性、框架内嵌签名、沙盒通信与安装目录权限。用户现有应用和正式发布源不参与升级测试。 + +## 实施与验证记录 + +- 1.5(17)锁定 Sparkle 2.10.1,沿用 1.4 的偏好键。应用启动后立即发起后台检查,后续按 21600 秒的配置调度。自动检查与手动下载独立。 +- 原 ad-hoc Release 直接加载动态库时,dyld 以缺少共同 Team ID 拒绝启动。现使用 Apple 的库加载约束,保留上游框架签名,将 arm64 / x86_64 两个 CDHash 写入主程序签名。实测可启动;另一个隔离副本中重签框架后,dyld 以库加载约束不匹配拒绝载入。[Apple 库加载约束](https://developer.apple.com/videos/play/wwdc2023/10266/) · [Sparkle 沙盒接入](https://sparkle-project.org/documentation/sandboxing/) +- 在独立安装目录和随机 bundle ID 下,使用本地更新源、临时 EdDSA 密钥实测。关于页从 901 下载并重启到 902。重启前关闭自动检测,新进程没有请求清单,手动检查返回已是最新。另一组从真实面板 Kymo 右上角按下下载,改动一个字节的同长度 ZIP 在解压前被拒绝,角标进入重试;恢复原 ZIP 后从角标完成 911 → 912,记录到新进程启动及其自动检查。 +- Debug / Release 构建、原始及解压后的主程序和内嵌服务签名、库加载约束、正式格式 ZIP 的 SHA-256、200 项三语资源、更新状态、实际面板与打包 SMARTService RPC 已验证。正式附件路由用已发布 v1.4 校验文件实测。6 小时周期核对配置和 Sparkle 调度入口,未等待满周期;跨机 Gatekeeper 和需管理员授权的安装未实测。两个真实升级使用测试源,正式更新源需待发版。钥匙串授权弹窗显示期间,设置窗口用例曾因窗口未获焦点失败。授权完成后针对最终 ZIP 解压产物复测,窗口首次显示、焦点恢复、关闭再打开全部通过。 +- 发布钥匙串授权后,已为 1.5(17)的最终 ZIP 生成正式 appcast.xml。使用应用内置公钥独立验证清单和 ZIP 的 Ed25519 签名,并复核 ZIP 的 SHA-256、附件长度和 v1.5 标签下载地址。 diff --git a/docs/testing.md b/docs/testing.md index 772b4ae..cd15ceb 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -42,7 +42,7 @@ python3 tools/check.py --list | CodeIdentityChecks、PanelAssetChecks、KeepAwakeChecks | 签名身份拒绝边界、编译颜色及对比度、真实 IOPM 断言开关与释放 | | NativeMetricDrawingChecks(--gui) | 实际曲线 / 堆叠色带、带符号瓦数零线与两端悬浮点、双向速率面积和零轴、方向 / 悬浮 / 断点及累计边界定位、单点无虚构填充、隐藏序列隔离、缺失点接续与真实断点、悬浮缓存、滚动时间域变换、悬浮停止动画、断点、无渐变 / 遮罩、卸载 | | FanRotorChecks(--gui) | 独立图层多角度 / 多尺寸旋转中心不漂移,原生旋转动画时长、无效 / 零 / 缺失、非活动 / 减弱动态效果及卸载停转 | -| ReleaseUpdateChecks | 稳定标签的数字版本、同版 ZIP 构建号、自动偏好、取消与并发请求合并、手动重试和恢复 | +| ReleaseUpdateChecks | 自动检查偏好迁移、手动检查、双入口共用动作、重复点击、重试与重启回调仅触发一次;真实 ZIP 验证见 [Sparkle 更新计划](sparkle-update-plan.md) | | ResourceCardChecks(--gui) | 生产卡片与曲线真实挂载,190 / 205⅓ / 400pt、浅深色及三语下的整卡背景图区、存储与网络的独立图区及文字换行边界、10pt 三语内存 / 存储详情在固定卡片内的边界、电量柱的固定间距、右缘追加、已满窗口移出、原生图层平移和供电分组、共同供电柱的蓝绿分色、睡眠区间与普通停采的悬浮命中、缺少电量时保留供电状态,以及无电池时的功率曲线、卸载;比较 AppKit 实际尺寸,允许分数点窗口尺寸取整 | | ProcessSectionChecks(--gui) | 生产进程区域固定 176pt,三语 / 浅深色及 340 / 628pt 下移除说明行后表格占满剩余高度且无横向滚动条 | | NativeContentHostChecks(--gui) | 小数末位增减后直接显示最终读数、更新帧与稳定帧像素一致、父环境继承、挂载身份、有限尺寸和卸载 | diff --git a/kymo.xcodeproj/project.pbxproj b/kymo.xcodeproj/project.pbxproj index 879d5df..48f0a6b 100644 --- a/kymo.xcodeproj/project.pbxproj +++ b/kymo.xcodeproj/project.pbxproj @@ -19,6 +19,8 @@ CC1000000000000000000003 /* ProcessMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000004 /* ProcessMetrics.swift */; }; CC1000000000000000000005 /* ProcessEnergy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000006 /* ProcessEnergy.swift */; }; CC1000000000000000000007 /* ProcessEnergyReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000008 /* ProcessEnergyReader.swift */; }; + 1A5000000000000000000001 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = 1A5000000000000000000002 /* Sparkle */; }; + 1A5000000000000000000004 /* Sparkle.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 1A5000000000000000000006 /* Sparkle.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -41,6 +43,13 @@ ); name = "Embed XPC Services"; }; + 1A5000000000000000000005 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + dstPath = ""; + dstSubfolderSpec = 10; + files = (1A5000000000000000000004 /* Sparkle.framework in Embed Frameworks */,); + name = "Embed Frameworks"; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ @@ -58,6 +67,7 @@ CC1000000000000000000006 /* ProcessEnergy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ProcessEnergy.swift; path = kymo/Core/Models/ProcessEnergy.swift; sourceTree = SOURCE_ROOT; }; CC1000000000000000000008 /* ProcessEnergyReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ProcessEnergyReader.swift; path = SMARTService/ProcessEnergyReader.swift; sourceTree = SOURCE_ROOT; }; D9E51E73309338B0000608DE /* kymo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = kymo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 1A5000000000000000000006 /* Sparkle.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = Sparkle.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedRootGroup section */ @@ -77,6 +87,7 @@ D9E51E70309338B0000608DE /* Frameworks */ = { isa = PBXFrameworksBuildPhase; files = ( + 1A5000000000000000000001 /* Sparkle in Frameworks */, ); }; /* End PBXFrameworksBuildPhase section */ @@ -144,6 +155,7 @@ D9E51E70309338B0000608DE /* Frameworks */, D9E51E71309338B0000608DE /* Resources */, BB0000000000000000000004 /* Embed XPC Services */, + 1A5000000000000000000005 /* Embed Frameworks */, ); buildRules = ( ); @@ -154,6 +166,7 @@ D9E51E75309338B0000608DE /* kymo */, ); name = kymo; + packageProductDependencies = (1A5000000000000000000002 /* Sparkle */,); productName = kymo; productReference = D9E51E73309338B0000608DE /* kymo.app */; productType = "com.apple.product-type.application"; @@ -182,6 +195,7 @@ "zh-Hant", Base, ); + packageReferences = (1A5000000000000000000003 /* Sparkle */,); mainGroup = D9E51E6A309338B0000608DE; minimizedProjectReferenceProxies = 1; preferredProjectObjectVersion = 77; @@ -235,6 +249,14 @@ }; /* End PBXTargetDependency section */ +/* Begin XCRemoteSwiftPackageReference section */ + 1A5000000000000000000003 /* Sparkle */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/sparkle-project/Sparkle"; requirement = {kind = exactVersion; version = 2.10.1; }; }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 1A5000000000000000000002 /* Sparkle */ = {isa = XCSwiftPackageProductDependency; package = 1A5000000000000000000003 /* Sparkle */; productName = Sparkle; }; +/* End XCSwiftPackageProductDependency section */ + /* Begin XCBuildConfiguration section */ BB0000000000000000000028 /* Debug configuration for PBXNativeTarget "SMARTService" */ = { isa = XCBuildConfiguration; @@ -303,7 +325,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 16; + CURRENT_PROJECT_VERSION = 17; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; @@ -325,7 +347,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MACOSX_DEPLOYMENT_TARGET = 27.0; - MARKETING_VERSION = 1.4; + MARKETING_VERSION = 1.5; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -371,7 +393,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 16; + CURRENT_PROJECT_VERSION = 17; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEPLOYMENT_POSTPROCESSING = YES; @@ -388,7 +410,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MACOSX_DEPLOYMENT_TARGET = 27.0; - MARKETING_VERSION = 1.4; + MARKETING_VERSION = 1.5; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = macosx; @@ -407,6 +429,9 @@ CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; DEAD_CODE_STRIPPING = YES; + CODE_SIGN_ENTITLEMENTS = Config/Kymo.entitlements; + INFOPLIST_FILE = Config/Kymo-Info.plist; + PACKAGE_SKIP_AUTO_EMBEDDING_DYNAMIC_BINARY_FRAMEWORKS = YES; ENABLE_APP_SANDBOX = YES; ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES; ENABLE_PREVIEWS = YES; @@ -438,6 +463,10 @@ CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; DEAD_CODE_STRIPPING = YES; + CODE_SIGN_ENTITLEMENTS = Config/Kymo-adhoc.entitlements; + LIBRARY_LOAD_CONSTRAINT = "Config/Sparkle-library-constraint.plist"; + INFOPLIST_FILE = Config/Kymo-Info.plist; + PACKAGE_SKIP_AUTO_EMBEDDING_DYNAMIC_BINARY_FRAMEWORKS = YES; ENABLE_APP_SANDBOX = YES; ENABLE_HARDENED_RUNTIME = YES; ENABLE_OUTGOING_NETWORK_CONNECTIONS = YES; diff --git a/kymo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/kymo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..3c98e6a --- /dev/null +++ b/kymo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,15 @@ +{ + "originHash" : "e721da7f9826abdffcb6185e886155efa2514bd6234475f1afa893e29eb258d6", + "pins" : [ + { + "identity" : "sparkle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/sparkle-project/Sparkle", + "state" : { + "revision" : "ab7d71291238df6e0492143b120c9b696a35f603", + "version" : "2.10.1" + } + } + ], + "version" : 3 +} diff --git a/kymo/App/kymoApp.swift b/kymo/App/kymoApp.swift index def65a6..2274676 100644 --- a/kymo/App/kymoApp.swift +++ b/kymo/App/kymoApp.swift @@ -19,6 +19,7 @@ import notify private let awake = KeepAwakeService() private let presentation = SettingsPresentation() private let updates = ReleaseUpdates() + private lazy var updater = SparkleUpdater(updates: updates) private let appearance = AppearancePreferences() private let menuBarPreferences = MenuBarPreferences() private let language = LanguagePreferences() @@ -75,7 +76,7 @@ import notify MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, updates: self.updates, presentation: panel, onOpenSettings: { [weak self] in self?.settingsCommand() - }, onOpenAbout: { [weak self] in self?.aboutCommand() }, onPreferredHeight: { [weak self] height in + }, onPreferredHeight: { [weak self] height in self?.menuBar?.setPreferredContentHeight(height) }) } @@ -110,7 +111,7 @@ import notify NSApp.mainMenu = root } - func applicationDidFinishLaunching(_ notification: Notification) { updates.start() } + func applicationDidFinishLaunching(_ notification: Notification) { updater.start() } @objc private func settingsCommand() { showSettings() } @objc private func aboutCommand() { showSettings(.about) } @@ -127,7 +128,6 @@ import notify workspaceTokens.forEach(NSWorkspace.shared.notificationCenter.removeObserver) workspaceTokens.removeAll() menuBar?.shutdown() - updates.stop() awake.disable() menuBar = nil openSettingsAction = nil diff --git a/kymo/Core/Services/ReleaseUpdates.swift b/kymo/Core/Services/ReleaseUpdates.swift index 23faafe..726735d 100644 --- a/kymo/Core/Services/ReleaseUpdates.swift +++ b/kymo/Core/Services/ReleaseUpdates.swift @@ -1,147 +1,74 @@ import Foundation import Observation -/// The release tag carries the marketing version. Kymo's ZIP also carries its build number. -nonisolated struct PublishedRelease: Decodable, Equatable { - struct Asset: Decodable, Equatable { let name: String } - let tagName: String - let draft: Bool - let prerelease: Bool - let assets: [Asset] - - private enum CodingKeys: String, CodingKey { - case tagName = "tag_name" - case draft, prerelease, assets - } - - static let repository = URL(string: "https://git.airnan.cn/wangairnan/Kymo")! - static let endpoint = URL(string: "https://git.airnan.cn/api/v1/repos/wangairnan/Kymo/releases/latest")! - - var page: URL { Self.repository.appending(path: "releases/tag").appending(component: tagName) } - var version: String { tagName.hasPrefix("v") ? String(tagName.dropFirst()) : tagName } - - private static func components(_ value: String) throws -> [Int] { - var numbers: [Int] = [] - for part in value.components(separatedBy: ".") { - guard !part.isEmpty, part.utf8.allSatisfy({ (48...57).contains($0) }), let n = Int(part) else { - throw URLError(.cannotParseResponse) - } - numbers.append(n) - } - while numbers.last == 0 { numbers.removeLast() } - return numbers - } - - var build: Int? { - let prefix = "kymo-" + version + "-" - return assets.compactMap { asset -> Int? in - let name = asset.name - guard name.hasPrefix(prefix), name.hasSuffix(".zip") else { return nil } - let remainder = name.dropFirst(prefix.count) - guard let separator = remainder.firstIndex(of: "-") else { return nil } - let build = remainder[.. Bool { - guard !draft, !prerelease else { throw URLError(.cannotParseResponse) } - let remote = try Self.components(version) - let local = try Self.components(localVersion) - if remote != local { return local.lexicographicallyPrecedes(remote) } - return build.map { $0 > localBuild } ?? false - } - - static func latest() async throws -> Self { - let config = URLSessionConfiguration.ephemeral - config.urlCache = nil - config.httpCookieStorage = nil - config.urlCredentialStorage = nil - config.timeoutIntervalForRequest = 15 - let session = URLSession(configuration: config) - defer { session.finishTasksAndInvalidate() } - let (data, response) = try await session.data(from: endpoint) - guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) } - return try JSONDecoder().decode(Self.self, from: data) - } -} - +/// Shared by the panel badge and About page. Sparkle owns the actual update session. @MainActor @Observable final class ReleaseUpdates { - enum Phase { case idle, checking, checked, failed } + enum Phase { case idle, checking, current, available, downloading, extracting, ready, restarting, failed } + struct Version: Equatable { + let display: String + let build: String + let infoURL: URL? + var label: String { "v\(display) (\(build))" } + } + private(set) var phase = Phase.idle - private(set) var available: PublishedRelease? + private(set) var version: Version? + private(set) var errorMessage: String? + private(set) var fraction: Double? var automatic: Bool { didSet { - guard automatic != oldValue else { return } + guard oldValue != automatic else { return } defaults.set(automatic, forKey: Self.preferenceKey) - if automatic { check(manual: false) } - else { - timer?.cancel() - if automaticRequest { cancelRequest() } - } + changeAutomatic?(automatic) } } + private static let preferenceKey = "updates.automatic" private let defaults: UserDefaults - private let version: String - private let build: Int - private let fetch: () async throws -> PublishedRelease - @ObservationIgnored private var timer: Task? - @ObservationIgnored private var request: Task? - @ObservationIgnored private var automaticRequest = false + @ObservationIgnored var changeAutomatic: ((Bool) -> Void)? + @ObservationIgnored var beginCheck: (() -> Void)? + @ObservationIgnored var beginDownload: ((Version) -> Void)? + @ObservationIgnored private var restart: (() -> Void)? - init(defaults: UserDefaults = .standard, - version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "", - build: Int = Int(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "") ?? 0, - fetch: @escaping () async throws -> PublishedRelease = PublishedRelease.latest) { + init(defaults: UserDefaults = .standard) { self.defaults = defaults - self.version = version - self.build = build - self.fetch = fetch automatic = defaults.object(forKey: Self.preferenceKey) as? Bool ?? true } - func start() { if automatic { check(manual: false) } } + func check() { + guard [.idle, .available, .current, .failed].contains(phase) else { return } + beginCheck?() + } - func check(manual: Bool = true) { - guard request == nil else { return } - timer?.cancel() - phase = .checking - automaticRequest = !manual - request = Task { [weak self, fetch] in - guard !Task.isCancelled else { return } - do { - let release = try await fetch() - guard !Task.isCancelled, let self else { return } - available = try release.isNewer(than: version, build: build) ? release : nil - phase = .checked - } catch { - guard !Task.isCancelled else { return } - self?.phase = .failed - } - guard let self else { return } - request = nil - automaticRequest = false - if automatic { - let delay: Duration = phase == .failed ? .seconds(3600) : .seconds(86400) - timer = Task { [weak self] in - do { try await Task.sleep(for: delay) } catch { return } - self?.check(manual: false) - } - } + func performAction() { + switch phase { + case .available: + if let version, version.infoURL == nil { beginDownload?(version) } + case .ready: + guard let restart else { return } + self.restart = nil + transition(to: .restarting) + restart() + case .failed, .idle, .current: check() + default: break } } - private func cancelRequest() { - request?.cancel() - request = nil - automaticRequest = false - if phase == .checking { phase = .idle } + func found(_ version: Version) { + self.version = version + transition(to: .available) } - func stop() { - timer?.cancel() - cancelRequest() + func ready(restart: @escaping () -> Void) { + transition(to: .ready) + self.restart = restart + } + + func transition(to phase: Phase, fraction: Double? = nil, error: String? = nil) { + self.phase = phase + self.fraction = fraction + errorMessage = error + restart = nil + if phase == .current || phase == .idle { version = nil } } } diff --git a/kymo/Core/Services/SparkleUpdater.swift b/kymo/Core/Services/SparkleUpdater.swift new file mode 100644 index 0000000..faa092e --- /dev/null +++ b/kymo/Core/Services/SparkleUpdater.swift @@ -0,0 +1,126 @@ +import Foundation +import Sparkle + +@MainActor final class SparkleUpdater: NSObject, SPUUserDriver, SPUUpdaterDelegate { + private let updates: ReleaseUpdates + private lazy var updater = SPUUpdater(hostBundle: .main, applicationBundle: .main, userDriver: self, delegate: self) + private var started = false + private var requestedBuild: String? + private var expectedBytes: UInt64 = 0 + private var receivedBytes: UInt64 = 0 + + init(updates: ReleaseUpdates) { + self.updates = updates + super.init() + updates.changeAutomatic = { [weak self] enabled in self?.updater.automaticallyChecksForUpdates = enabled } + updates.beginCheck = { [weak self] in self?.check() } + updates.beginDownload = { [weak self] in self?.check(download: $0) } + } + + func start() { + guard prepare() else { return } + if updates.automatic { updater.checkForUpdatesInBackground() } + } + + private func prepare() -> Bool { + if started { return true } + do { + if updater.automaticallyChecksForUpdates != updates.automatic { + updater.automaticallyChecksForUpdates = updates.automatic + } + try updater.start() + started = true + return true + } catch { + updates.transition(to: .failed, error: error.localizedDescription) + return false + } + } + + private func check(download: ReleaseUpdates.Version? = nil) { + guard prepare(), !updater.sessionInProgress else { return } + requestedBuild = download?.build + updates.transition(to: .checking) + updater.checkForUpdates() + } + + func show(_ request: SPUUpdatePermissionRequest, reply: @escaping (SUUpdatePermissionResponse) -> Void) { + reply(SUUpdatePermissionResponse(automaticUpdateChecks: updates.automatic, sendSystemProfile: false)) + } + + func showUserInitiatedUpdateCheck(cancellation: @escaping () -> Void) {} + + func showUpdateFound(with appcastItem: SUAppcastItem, state: SPUUserUpdateState, + reply: @escaping (SPUUserUpdateChoice) -> Void) { + guard state.userInitiated || updates.automatic else { reply(.dismiss); return } + let version = ReleaseUpdates.Version(display: appcastItem.displayVersionString, build: appcastItem.versionString, + infoURL: appcastItem.isInformationOnlyUpdate ? appcastItem.infoURL : nil) + updates.found(version) + if state.stage == .installing { + updates.ready { reply(.install) } + } else if state.userInitiated, requestedBuild == version.build, !appcastItem.isInformationOnlyUpdate { + updates.transition(to: .downloading) + reply(.install) + } else { + // Keep the badge, release the session so Sparkle can check again in six hours. + reply(.dismiss) + } + } + + func showUpdateReleaseNotes(with downloadData: SPUDownloadData) {} + func showUpdateReleaseNotesFailedToDownloadWithError(_ error: Error) {} + + func showUpdateNotFoundWithError(_ error: Error, acknowledgement: @escaping () -> Void) { + updates.transition(to: .current) + acknowledgement() + } + + func showUpdaterError(_ error: Error, acknowledgement: @escaping () -> Void) { + updates.transition(to: .failed, error: error.localizedDescription) + acknowledgement() + } + + func showDownloadInitiated(cancellation: @escaping () -> Void) { + expectedBytes = 0 + receivedBytes = 0 + updates.transition(to: .downloading) + } + + func showDownloadDidReceiveExpectedContentLength(_ expectedContentLength: UInt64) { + expectedBytes = expectedContentLength + } + + func showDownloadDidReceiveData(ofLength length: UInt64) { + receivedBytes += length + let fraction = expectedBytes > 0 ? min(1, Double(receivedBytes) / Double(expectedBytes)) : nil + updates.transition(to: .downloading, fraction: fraction) + } + + func showDownloadDidStartExtractingUpdate() { updates.transition(to: .extracting) } + func showExtractionReceivedProgress(_ progress: Double) { updates.transition(to: .extracting, fraction: progress) } + + func showReady(toInstallAndRelaunch reply: @escaping (SPUUserUpdateChoice) -> Void) { + updates.ready { reply(.install) } + } + + func showInstallingUpdate(withApplicationTerminated terminated: Bool, retryTerminatingApplication: @escaping () -> Void) { + if !terminated { updates.ready(restart: retryTerminatingApplication) } + } + + func showUpdateInstalledAndRelaunched(_ relaunched: Bool, acknowledgement: @escaping () -> Void) { + updates.transition(to: .current) + acknowledgement() + } + + func dismissUpdateInstallation() {} + + func updater(_ updater: SPUUpdater, didFinishUpdateCycleFor updateCheck: SPUUpdateCheck, error: Error?) { + requestedBuild = nil + guard let error = error as NSError? else { return } + if error.domain == SUSparkleErrorDomain, error.code == SUError.noUpdateError.rawValue { + updates.transition(to: .current) + } else { + updates.transition(to: .failed, error: error.localizedDescription) + } + } +} diff --git a/kymo/Features/MenuBar/MenuPanelView.swift b/kymo/Features/MenuBar/MenuPanelView.swift index 4709817..5f86911 100644 --- a/kymo/Features/MenuBar/MenuPanelView.swift +++ b/kymo/Features/MenuBar/MenuPanelView.swift @@ -8,7 +8,6 @@ struct MenuPanelView: View { let updates: ReleaseUpdates var presentation = PanelPresentation() var onOpenSettings: () -> Void = {} - var onOpenAbout: () -> Void = {} var onPreferredHeight: (CGFloat) -> Void = { _ in } @Environment(\.locale) var locale @State private var panelSize = PanelLayout.contentSize(visible: NSScreen.main?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1000, height: 760)) @@ -137,7 +136,15 @@ struct MenuPanelView: View { .frame(width: 22, height: 22) HStack(alignment: .top, spacing: 3) { Text("Kymo").font(.system(size: 17, weight: .semibold)) - if let version = Self.version { + if updates.version != nil { + UpdateAction(phase: updates.phase, version: updates.version, compact: true, action: updates.performAction) + .buttonStyle(.plain) + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(Color.accentColor) + .padding(.horizontal, 5).padding(.vertical, 2) + .background(Color.accentColor.opacity(0.12), in: Capsule()) + .offset(y: -2) + } else if let version = Self.version { Text(verbatim: "v" + version) .font(.system(size: 9, weight: .semibold)).monospacedDigit() .padding(.horizontal, 5).padding(.vertical, 1) @@ -206,13 +213,6 @@ struct MenuPanelView: View { } .help(metrics.isPaused ? Text("action.resume") : Text("action.pause")) .accessibilityLabel(metrics.isPaused ? Text("action.resume") : Text("action.pause")) - if updates.available != nil { - Button(action: onOpenAbout) { - Image(systemName: "arrow.down.circle.fill").frame(width: 20, height: 20) - .foregroundStyle(Color.accentColor) - } - .help(Text("updates.available")).accessibilityLabel(Text("updates.available")) - } Button(action: onOpenSettings) { Image(systemName: "gearshape").frame(width: 20, height: 20) } diff --git a/kymo/Features/Settings/AppearanceSettingsView.swift b/kymo/Features/Settings/AppearanceSettingsView.swift index aaac722..6bc1036 100644 --- a/kymo/Features/Settings/AppearanceSettingsView.swift +++ b/kymo/Features/Settings/AppearanceSettingsView.swift @@ -100,24 +100,22 @@ struct AppearanceSettingsView: View { Section { Toggle("updates.automatic", isOn: $updates.automatic) .toggleStyle(.checkbox) + Text("updates.schedule").font(.callout).foregroundStyle(.secondary) HStack { - Button("updates.check") { updates.check() } - .disabled(updates.phase == .checking) - switch updates.phase { - case .idle: EmptyView() - case .checking: Text("updates.checking").foregroundStyle(.secondary) - case .failed: Text("updates.failed").foregroundStyle(.secondary) - case .checked: - if updates.available == nil { Text("updates.current").foregroundStyle(.secondary) } + if let version = updates.version { + Text("updates.new \(version.label)") + } else if updates.phase == .current { + Text("updates.current").foregroundStyle(.secondary) } + Spacer() + UpdateAction(phase: updates.phase, version: updates.version, action: updates.performAction) } - if let release = updates.available { - let display = release.build.map { "\(release.tagName) (\($0))" } ?? release.tagName - LabeledContent { - Link("updates.releasePage", destination: release.page) - } label: { - Text("updates.new \(display)") - } + if updates.phase == .downloading || updates.phase == .extracting { + ProgressView(value: updates.fraction).progressViewStyle(.linear) + } + if let error = updates.errorMessage { + Text(verbatim: error).font(.callout).foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } } } diff --git a/kymo/Resources/Localizable.xcstrings b/kymo/Resources/Localizable.xcstrings index 52ec2a6..1a3df57 100644 --- a/kymo/Resources/Localizable.xcstrings +++ b/kymo/Resources/Localizable.xcstrings @@ -68,6 +68,167 @@ } } }, + "updates.schedule": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check at launch and every 6 hours while Kymo is running." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "开启后,每次启动和运行期间每 6 小时检查一次。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "開啟後,每次啟動和執行期間每 6 小時檢查一次。" + } + } + } + }, + "updates.download": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Download update" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "下载更新" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "下載更新" + } + } + } + }, + "updates.restart": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Restart and update" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "重启并更新" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "重新啟動並更新" + } + } + } + }, + "updates.downloading": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Downloading…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "正在下载…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "正在下載…" + } + } + } + }, + "updates.preparing": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Preparing update…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "正在准备更新…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "正在準備更新…" + } + } + } + }, + "updates.restarting": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Restarting…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "正在重启…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "正在重新啟動…" + } + } + } + }, + "updates.retry": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Retry" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "重试" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "重試" + } + } + } + }, "updates.automatic": { "extractionState": "manual", "localizations": { diff --git a/kymo/UI/Components/UpdateAction.swift b/kymo/UI/Components/UpdateAction.swift new file mode 100644 index 0000000..3a45026 --- /dev/null +++ b/kymo/UI/Components/UpdateAction.swift @@ -0,0 +1,44 @@ +import SwiftUI + +/// The same single action is presented as a compact version badge or a settings button. +struct UpdateAction: View { + let phase: ReleaseUpdates.Phase + let version: ReleaseUpdates.Version? + var compact = false + let action: () -> Void + + var body: some View { + if let url = version?.infoURL, phase == .available { + Link(destination: url) { content("updates.releasePage", symbol: "arrow.up.right") } + } else { + Button(action: action) { + switch phase { + case .available: content("updates.download", symbol: "arrow.down.circle.fill") + case .ready: content("updates.restart", symbol: "arrow.clockwise.circle.fill") + case .checking: content("updates.checking", symbol: "magnifyingglass") + case .downloading: content("updates.downloading", symbol: "arrow.down") + case .extracting: content("updates.preparing", symbol: "shippingbox") + case .restarting: content("updates.restarting", symbol: "arrow.clockwise") + case .failed: content("updates.retry", symbol: "arrow.clockwise") + case .idle, .current: content("updates.check", symbol: "arrow.clockwise") + } + } + .disabled([.checking, .downloading, .extracting, .restarting].contains(phase)) + } + } + + private func content(_ title: LocalizedStringKey, symbol: String) -> some View { + HStack(spacing: 3) { + Image(systemName: symbol) + if compact, let version { + Text(verbatim: "v" + version.display) + } else { + Text(title) + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(title)) + .accessibilityValue(Text(verbatim: version?.label ?? "")) + .help(Text(title)) + } +} diff --git a/kymoTests/ReleaseUpdateChecks.swift b/kymoTests/ReleaseUpdateChecks.swift index 138063b..0ea7fe7 100644 --- a/kymoTests/ReleaseUpdateChecks.swift +++ b/kymoTests/ReleaseUpdateChecks.swift @@ -1,64 +1,55 @@ import Foundation @main struct ReleaseUpdateChecks { - @MainActor static func main() async throws { - func release(_ tag: String, draft: Bool = false, prerelease: Bool = false) -> PublishedRelease { - PublishedRelease(tagName: tag, draft: draft, prerelease: prerelease, assets: [ - .init(name: "kymo-1.3-15-arm64-adhoc.zip"), - .init(name: "kymo-1.3-16-arm64-adhoc.zip.sha256"), - .init(name: "kymo-1.2-99-arm64-adhoc.zip") - ]) - } - let stable = release("v1.3") - let comparisons = try [ - stable.isNewer(than: "1.3.0", build: 15), stable.isNewer(than: "1.3", build: 14), - stable.isNewer(than: "1.2", build: 99), stable.isNewer(than: "2.0", build: 1), - release("v1.10").isNewer(than: "1.9", build: 30) - ] - precondition(comparisons == [false, true, true, false, true]) - precondition(stable.page.absoluteString == "https://git.airnan.cn/wangairnan/Kymo/releases/tag/v1.3") - for invalid in [release("v1.4", draft: true), release("v1.4", prerelease: true), release("v1.4-rc.1"), release("main")] { - precondition((try? invalid.isNewer(than: "1.3", build: 15)) == nil) - } - + @MainActor static func main() { + let app = Bundle(path: CommandLine.arguments[1])! + precondition(app.object(forInfoDictionaryKey: "SUScheduledCheckInterval") as? Int == 6 * 60 * 60) + precondition(app.object(forInfoDictionaryKey: "SUEnableAutomaticChecks") as? Bool == true) + precondition(app.object(forInfoDictionaryKey: "SURequireSignedFeed") as? Bool == true) + precondition(app.object(forInfoDictionaryKey: "SUVerifyUpdateBeforeExtraction") as? Bool == true) let suite = "KymoReleaseUpdateChecks." + UUID().uuidString let defaults = UserDefaults(suiteName: suite)! defer { defaults.removePersistentDomain(forName: suite) } - var pending: [CheckedContinuation] = [] - let updates = ReleaseUpdates(defaults: defaults, version: "1.2", build: 10) { - try await withCheckedThrowingContinuation { pending.append($0) } + let updates = ReleaseUpdates(defaults: defaults) + let release = ReleaseUpdates.Version(display: "1.5", build: "17", infoURL: nil) + var checks = 0, downloads = 0, restarts = 0 + updates.beginCheck = { + checks += 1 + updates.transition(to: .checking) } - func wait(_ condition: () -> Bool) async { - let deadline = ContinuousClock.now.advanced(by: .seconds(3)) - while !condition() && ContinuousClock.now < deadline { await Task.yield() } - precondition(condition()) + updates.beginDownload = { version in + precondition(version == release) + downloads += 1 + updates.transition(to: .downloading) } + precondition(updates.automatic) - updates.start() - updates.check() - await wait { pending.count == 1 } + var changes = [Bool]() + updates.changeAutomatic = { changes.append($0) } updates.automatic = false - precondition(updates.phase == .idle) - let restarted = ReleaseUpdates(defaults: defaults) - restarted.start() - precondition(!restarted.automatic && restarted.phase == .idle) + precondition(changes == [false] && !ReleaseUpdates(defaults: defaults).automatic) updates.check() - await wait { pending.count == 2 } - pending.removeLast().resume(returning: stable) - await wait { updates.phase == .checked } - pending.removeLast().resume(throwing: URLError(.cancelled)) - await Task.yield() - precondition(updates.available == stable && updates.phase == .checked) - updates.automatic = true - await wait { pending.count == 1 } - pending.removeLast().resume(throwing: URLError(.notConnectedToInternet)) - await wait { updates.phase == .failed } updates.check() - await wait { pending.count == 1 } - pending.removeLast().resume(returning: release("v1.0")) - await wait { updates.phase == .checked } - precondition(updates.available == nil) - updates.stop() - print("PASS: release versions and build assets, stable releases, automatic preference, cancellation, single request, manual retry and recovery") + precondition(checks == 1 && updates.phase == .checking) + updates.found(release) + updates.performAction() + updates.performAction() + precondition(downloads == 1) + updates.transition(to: .failed, error: "offline") + updates.performAction() + precondition(checks == 2 && updates.errorMessage == nil) + updates.found(release) + updates.performAction() + updates.transition(to: .extracting, fraction: 0.5) + updates.check() + precondition(checks == 2 && updates.fraction == 0.5) + updates.ready { restarts += 1 } + precondition(restarts == 0 && updates.phase == .ready) + updates.performAction() + updates.performAction() + precondition(restarts == 1 && downloads == 2 && updates.phase == .restarting) + updates.transition(to: .current) + precondition(updates.version == nil) + print("PASS: preserved preference, manual check, shared download/restart actions, busy state, retry and current version") } } diff --git a/tools/check.py b/tools/check.py index 1a962f5..d7324e0 100644 --- a/tools/check.py +++ b/tools/check.py @@ -14,7 +14,7 @@ import uuid ROOT = Path(__file__).resolve().parents[1] CORE = sorted(str(p.relative_to(ROOT)) for folder in ("Models", "Monitors", "Services", "Extensions") - for p in (ROOT / "kymo/Core" / folder).glob("*.swift")) + for p in (ROOT / "kymo/Core" / folder).glob("*.swift") if p.name != "SparkleUpdater.swift") CHECKS = {name: list(CORE) for name in ( "SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks", "GPUStatisticsChecks", "StageCChecks", "BatteryPowerChecks", "MachPortChecks", "ReleaseServiceChecks", "DetailDemandChecks")} @@ -237,7 +237,7 @@ def main(): finally: clean_test_container(bundle) else: - extra = [app] if name in {"LocalizationChecks", "PanelAssetChecks", "MemoryHeaderChecks"} else [] + extra = [app] if name in {"ReleaseUpdateChecks", "LocalizationChecks", "PanelAssetChecks", "MemoryHeaderChecks"} else [] if name == "CodeIdentityChecks": extra = [app, app / "Contents/XPCServices/SMARTService.xpc"] run([executable, *extra], timeout=45) diff --git a/tools/package_release.py b/tools/package_release.py index f3b9388..f8849cc 100644 --- a/tools/package_release.py +++ b/tools/package_release.py @@ -4,12 +4,16 @@ import argparse import hashlib from pathlib import Path import plistlib +import re import shutil import subprocess import tempfile import zipfile +import xml.etree.ElementTree as ET ROOT = Path(__file__).resolve().parents[1] +KEY_ACCOUNT = "cn.airnan.kymo" +RELEASES = "https://git.airnan.cn/wangairnan/Kymo/releases/download" def run(command): @@ -21,6 +25,11 @@ def run(command): def verify(app): run(["codesign", "--verify", "--deep", "--strict", app]) + info = plistlib.loads((app / "Contents/Info.plist").read_bytes()) + identifier = info["CFBundleIdentifier"] + installer = app / "Contents/Frameworks/Sparkle.framework/Versions/B/XPCServices/Installer.xpc" + if not installer.is_dir() or not info.get("SUEnableInstallerLauncherService"): + raise RuntimeError("Missing Sparkle sandbox installer") for target in [app, app / "Contents/XPCServices/SMARTService.xpc"]: details = run(["codesign", "-dvvv", target]).stderr.decode() if "Signature=adhoc" not in details or "runtime)" not in details: @@ -29,20 +38,97 @@ def verify(app): entitlements = plistlib.loads(signed.stdout) expected = {"com.apple.security.app-sandbox": True, "com.apple.security.network.client": True, - "com.apple.security.files.user-selected.read-only": True} if target == app else {} + "com.apple.security.files.user-selected.read-only": True, + "com.apple.security.cs.disable-library-validation": True, + "com.apple.security.temporary-exception.mach-lookup.global-name": + [identifier + "-spks", identifier + "-spki"]} if target == app else {} if entitlements != expected: raise RuntimeError("Unexpected release entitlements: " + str(target)) + # With no Team ID, Hardened Runtime uses an explicit allowlist of Sparkle code hashes. + # Validate both the signed host constraints and every shipped architecture after embedding. + pinned = plistlib.loads((ROOT / "Config/Sparkle-library-constraint.plist").read_bytes()) + hashes = {value.hex() for value in pinned["cdhash"]["$in"]} + details = run(["codesign", "-dvvvv", app]) + constraints = (details.stdout + details.stderr).decode() + if "Has Library Load Constraints" not in constraints or any(h not in constraints for h in hashes): + raise RuntimeError("Host signature is missing the Sparkle library constraint") + framework = app / "Contents/Frameworks/Sparkle.framework" + for arch in run(["lipo", "-archs", framework / "Sparkle"]).stdout.decode().split(): + signature = run(["codesign", "-dvvv", "--arch", arch, framework]).stderr.decode() + digest = re.search(r"^CDHash=([0-9a-f]+)$", signature, re.MULTILINE) + if not digest or digest[1] not in hashes: + raise RuntimeError(f"Embedded Sparkle signature for {arch} does not match the library constraint") for path in app.rglob("*"): if path.name in {".DS_Store", ".git", "xcuserdata"} or path.suffix in {".swift", ".xcstrings", ".md", ".py", ".dSYM"}: raise RuntimeError("Development file in application: " + str(path)) +def archive_info(package): + with zipfile.ZipFile(package) as archive: + if any(not item.filename.startswith("kymo.app/") or ".." in Path(item.filename).parts + for item in archive.infolist()): + raise RuntimeError("Unexpected archive contents") + return plistlib.loads(archive.read("kymo.app/Contents/Info.plist")) + + +def generate_feed(package, info, tools): + public_key = run([tools / "generate_keys", "--account", KEY_ACCOUNT, "-p"]).stdout.decode().strip() + if public_key != info["SUPublicEDKey"]: + raise RuntimeError("Release key does not match the public key embedded in Kymo") + prefix = f"{RELEASES}/v{info['CFBundleShortVersionString']}/" + run([tools / "generate_appcast", "--account", KEY_ACCOUNT, "--download-url-prefix", prefix, + "--maximum-deltas", "0", package.parent]) + feed = package.parent / "appcast.xml" + item = ET.parse(feed).find("./channel/item") + ns = "{http://www.andymatuschak.org/xml-namespaces/sparkle}" + enclosure = item.find("enclosure") if item is not None else None + if (enclosure is None or enclosure.get("url") != prefix + package.name + or enclosure.get("length") != str(package.stat().st_size) + or item.findtext(ns + "version") != info["CFBundleVersion"]): + raise RuntimeError("Appcast does not describe the final release ZIP") + verify_signature = [tools / "sign_update", "--account", KEY_ACCOUNT, "--verify"] + run([*verify_signature, package, enclosure.attrib[ns + "edSignature"]]) + run([*verify_signature, feed]) + return feed + + +def sign_existing(package, work): + package = package.expanduser().resolve(strict=True) + feed = package.parent / "appcast.xml" + if feed.exists(): + raise RuntimeError("appcast.xml already exists in this directory") + info = archive_info(package) + trusted = plistlib.loads((ROOT / "Config/Kymo-Info.plist").read_bytes()) + if info.get("CFBundleIdentifier") != KEY_ACCOUNT or info.get("SUPublicEDKey") != trusted["SUPublicEDKey"]: + raise RuntimeError("ZIP is not a Kymo build for this Sparkle signing key") + archives = work / "archives" + archives.mkdir() + staged = archives / package.name + shutil.copyfile(package, staged) + run(["ditto", "-x", "-k", staged, work / "unpacked"]) + verify(work / "unpacked/kymo.app") + run(["xcodebuild", "-resolvePackageDependencies", "-project", "kymo.xcodeproj", "-scheme", "kymo", + "-derivedDataPath", work / "build"]) + signed = generate_feed(staged, info, work / "build/SourcePackages/artifacts/sparkle/Sparkle/bin") + if staged.read_bytes() != package.read_bytes(): + raise RuntimeError("ZIP changed while generating its appcast") + with feed.open("xb") as result: + result.write(signed.read_bytes()) + print("Signed appcast:", feed) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=ROOT / "dist", help="Output directory (existing ZIPs are preserved)") + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--sign-existing", type=Path, metavar="ZIP", help="Generate appcast.xml beside an existing Kymo release ZIP") + mode.add_argument("--zip-only", action="store_true", help="Build a local test ZIP without a signing key or appcast") args = parser.parse_args() with tempfile.TemporaryDirectory(prefix="kymo-release-") as temp: work = Path(temp) + if args.sign_existing: + sign_existing(args.sign_existing, work) + return print("Building ordinary ad-hoc Release…", flush=True) run(["xcodebuild", "-project", "kymo.xcodeproj", "-scheme", "kymo", "-configuration", "Release", "-derivedDataPath", work / "build", "SWIFT_EMIT_LOC_STRINGS=NO", "SWIFT_ACTIVE_COMPILATION_CONDITIONS=", @@ -52,12 +138,11 @@ def main(): info = plistlib.loads((app / "Contents/Info.plist").read_bytes()) architectures = run(["lipo", "-archs", app / "Contents/MacOS/kymo"]).stdout.decode().strip().replace(" ", "-") name = "kymo-{}-{}-{}-adhoc.zip".format(info["CFBundleShortVersionString"], info["CFBundleVersion"], architectures) - package = work / name + archives = work / "archives" + archives.mkdir() + package = archives / name run(["ditto", "-c", "-k", "--keepParent", "--norsrc", "--noextattr", app, package]) - with zipfile.ZipFile(package) as archive: - if any(not item.filename.startswith("kymo.app/") or ".." in Path(item.filename).parts - or item.filename.startswith("/") for item in archive.infolist()): - raise RuntimeError("Unexpected archive contents") + archive_info(package) unpacked = work / "unpacked" run(["ditto", "-x", "-k", package, unpacked]) verify(unpacked / "kymo.app") @@ -65,11 +150,15 @@ def main(): output.mkdir(parents=True, exist_ok=True) destination = output / name checksum = output / (name + ".sha256") - if destination.exists() or checksum.exists(): + if destination.exists() or checksum.exists() or (not args.zip_only and (output / "appcast.xml").exists()): raise RuntimeError("Output already exists; choose another --output directory") + feed = None if args.zip_only else generate_feed(package, info, work / "build/SourcePackages/artifacts/sparkle/Sparkle/bin") digest = hashlib.sha256(package.read_bytes()).hexdigest() shutil.copy2(package, destination) checksum.write_text(digest + " " + name + "\n") + if feed: + shutil.copy2(feed, output / feed.name) + print("Signed appcast:", output / feed.name) print("PASS: original and extracted app signatures, runtime, entitlements and archive contents") print("Minimum macOS:", info.get("LSMinimumSystemVersion"), "architectures:", architectures) print("ZIP:", destination, "bytes:", destination.stat().st_size)