Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(windows): tell you when a new version is out and download the right one for your PC

wquguru7d921996c43a
diff --git a/site/changelog.json b/site/changelog.json
index 36508b1..4220a58 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -201,6 +201,11 @@
"title": "Windows 上会议应用挂断、或很久没人说话时,自动结束会议、整理纪要。",
"text": "Zoom、腾讯会议、飞书、Teams 等挂断后结束;没人说话时先提醒,也可以在设置 › 结束会议里改成直接结束或一直记录。"
},
+ {
+ "kind": "new",
+ "title": "Windows 上有新版本时会提示,点“下载”拿这台电脑对应的版本。",
+ "text": "启动时和之后每 4 小时去 GitHub 看一次,任务栏面板顶部和设置 › 关于里显示新版本;下载后解压,替换旧的知了。"
+ },
{
"kind": "improved",
"title": "Windows 上结束会议前先问一句“结束这场会议?”。",
diff --git a/windows/README.md b/windows/README.md
index a1493d1..98d6cb0 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -5,6 +5,7 @@ Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪
- 抓声音:WASAPI 进程回环,排除知了自己(Windows 10 2004 起)。
- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求同时返回语言、原文和译文;需要 Ling key。
- 纪要、记录格式、提示词、多语言文案都和 Mac 版一致;文案的英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Windows 独有的在 `src/Cicada/Strings/`。
+- 新版本:启动时和每 4 小时查一次 GitHub Releases(`UpdateChecker`),只认带 Windows zip 的发布;有新版本时托盘面板和设置 › 关于提示,浏览器下载这台电脑对应架构的 zip,还不能自动替换。开发版只在设了 `CICADA_UPDATE_FEED` 或用 `updatefeed` 调试命令时才查。
## 目录
diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.cs
index 62864d1..c04a016 100644
--- a/windows/src/Cicada.Core/Settings.cs
+++ b/windows/src/Cicada.Core/Settings.cs
@@ -39,6 +39,8 @@ public sealed class AppSettings
[JsonPropertyName("endWithApp")] public bool EndWithApp { get; set; } = true;
[JsonPropertyName("silenceEnd")] public string SilenceEnd { get; set; } = "prompt";
[JsonPropertyName("silenceMinutes")] public double SilenceMinutes { get; set; } = 10;
+ /// When GitHub Releases last answered an update check (UpdateChecker).
+ [JsonPropertyName("updateLastChecked")] public DateTimeOffset? UpdateLastChecked { get; set; }
[JsonIgnore] public string TargetCode => Target == "system" ? Languages.FromSystem(CultureInfo.CurrentUICulture.Name) : Target;
[JsonIgnore] public string NotesCode => NotesLanguage == "system" ? TargetCode : NotesLanguage;
diff --git a/windows/src/Cicada.Core/UpdateChecker.cs b/windows/src/Cicada.Core/UpdateChecker.cs
new file mode 100644
index 0000000..2f7cf0c
--- /dev/null
+++ b/windows/src/Cicada.Core/UpdateChecker.cs
@@ -0,0 +1,155 @@
+using System.Runtime.InteropServices;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Cicada;
+
+/// Checks GitHub Releases for a Windows build newer than the running one, as the Mac's
+/// UpdateChecker: at launch, then whenever the last answer is 4 hours old (a 15-minute tick, so a
+/// laptop that sleeps a lot still checks), and when the tray panel opens once it is an hour old.
+/// Failures (offline, rate-limited, the repository not public: 404) are silent. This only finds
+/// the update; the app offers the zip for download (no in-place install yet).
+public sealed class UpdateChecker
+{
+ public sealed record Update(string Version, string Page, string? Zip, long Size);
+
+ public static readonly TimeSpan Every = TimeSpan.FromHours(4);
+ public static readonly TimeSpan Stale = TimeSpan.FromHours(1);
+
+ /// `CICADA_UPDATE_FEED` (or the `updatefeed` debug command) points at another release JSON,
+ /// a list or a single release; a file path or file:// URL works, for testing.
+ /// The list, not `releases/latest`: a release that ships only the Mac, Android or Linux has no
+ /// Windows zip, so the newest Windows release may be further down.
+ public string Feed { get; set; } = Environment.GetEnvironmentVariable("CICADA_UPDATE_FEED") is { Length: > 0 } f
+ ? f : "https://api.github.com/repos/wquguru/cicada/releases?per_page=20";
+
+ /// The running version, three parts ("1.4.0"), from VERSION via Directory.Build.props.
+ public string Current { get; set; } = "0";
+
+ /// The newer release, or null (none, or not checked yet).
+ public Update? Available { get; private set; }
+ /// When the feed last answered; kept in settings across launches.
+ public DateTimeOffset? LastChecked { get; private set; }
+ public event Action? Changed;
+
+ readonly HttpClient http;
+ readonly Action<DateTimeOffset> remember;
+ Timer? timer;
+ int checking;
+
+ public UpdateChecker(DateTimeOffset? lastChecked, Action<DateTimeOffset> remember, HttpMessageHandler? handler = null)
+ {
+ LastChecked = lastChecked;
+ this.remember = remember;
+ http = handler is null ? new HttpClient() : new HttpClient(handler);
+ http.Timeout = TimeSpan.FromSeconds(20);
+ // GitHub's API refuses requests without a User-Agent.
+ http.DefaultRequestHeaders.UserAgent.ParseAdd("Cicada-Windows");
+ http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json");
+ }
+
+ public void Start()
+ {
+ _ = Check();
+ timer = new Timer(_ => _ = CheckIfDue(Every), null, TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(15));
+ }
+
+ public Task CheckIfDue(TimeSpan age) => Due(LastChecked, DateTimeOffset.UtcNow, age) ? Check() : Task.CompletedTask;
+
+ public static bool Due(DateTimeOffset? last, DateTimeOffset now, TimeSpan age) =>
+ // A clock set back leaves `last` in the future: check rather than wait for it.
+ last is not { } l || now - l >= age || l > now;
+
+ /// False when the feed couldn't be reached or answered with something unexpected.
+ public async Task<bool> Check()
+ {
+ if (Interlocked.Exchange(ref checking, 1) == 1) return true;
+ try
+ {
+ var text = await Read(Feed);
+ if (Decode(text) is not { } releases) { Log.Debug("update: feed unreadable"); return false; }
+ var newest = NewestWindows(releases, Arch);
+ LastChecked = DateTimeOffset.UtcNow;
+ remember(LastChecked.Value);
+ Available = newest is not null && IsNewer(newest.Version, Current) ? newest : null;
+ Log.Debug($"update: checked, latest Windows {newest?.Version ?? "none"}, running {Current}");
+ Changed?.Invoke();
+ return true;
+ }
+ catch (Exception e) { Log.Debug($"update: check failed {e.GetType().Name}"); return false; }
+ finally { Volatile.Write(ref checking, 0); }
+ }
+
+ async Task<string> Read(string feed)
+ {
+ if (Uri.TryCreate(feed, UriKind.Absolute, out var uri) && uri.IsFile) return await File.ReadAllTextAsync(uri.LocalPath);
+ if (!feed.Contains("://")) return await File.ReadAllTextAsync(feed);
+ using var r = await http.GetAsync(feed);
+ r.EnsureSuccessStatusCode();
+ return await r.Content.ReadAsStringAsync();
+ }
+
+ /// The zip this PC should run: ARM64 on an ARM PC (even when this copy is the emulated x64 one).
+ public static string Arch => RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "ARM64" : "x64";
+
+ public static List<Release>? Decode(string text)
+ {
+ try
+ {
+ using var doc = JsonDocument.Parse(text);
+ return doc.RootElement.ValueKind switch
+ {
+ JsonValueKind.Array => doc.RootElement.Deserialize<List<Release>>(),
+ JsonValueKind.Object => doc.RootElement.Deserialize<Release>() is { TagName.Length: > 0 } one ? [one] : null,
+ _ => null,
+ };
+ }
+ catch (JsonException) { return null; }
+ }
+
+ /// The newest published release with a Windows zip. A release without one only carries other
+ /// platforms (Windows had no change), so it is skipped. On ARM, an x64-only release still counts.
+ public static Update? NewestWindows(IEnumerable<Release> releases, string arch)
+ {
+ Update? best = null;
+ foreach (var r in releases)
+ {
+ if (r.Draft || r.Prerelease || r.Assets is null) continue;
+ var zip = r.Assets.FirstOrDefault(a => IsZip(a.Name, arch)) ?? (arch == "x64" ? null : r.Assets.FirstOrDefault(a => IsZip(a.Name, "x64")));
+ if (zip is null) continue;
+ var u = new Update(r.TagName.TrimStart('v'), r.HtmlUrl, zip.Url, zip.Size);
+ if (best is null || IsNewer(u.Version, best.Version)) best = u;
+ }
+ return best;
+ static bool IsZip(string name, string arch) => name.StartsWith("Cicada-") && name.EndsWith($"-Windows-{arch}.zip");
+ }
+
+ /// Dotted numeric versions: "2.10.0" is newer than "2.9.1".
+ public static bool IsNewer(string a, string b)
+ {
+ var x = a.Split('.').Select(p => int.TryParse(p, out var n) ? n : 0).ToArray();
+ var y = b.Split('.').Select(p => int.TryParse(p, out var n) ? n : 0).ToArray();
+ for (int i = 0; i < Math.Max(x.Length, y.Length); i++)
+ {
+ int l = i < x.Length ? x[i] : 0, r = i < y.Length ? y[i] : 0;
+ if (l != r) return l > r;
+ }
+ return false;
+ }
+
+ public sealed class Release
+ {
+ [JsonPropertyName("tag_name")] public string TagName { get; set; } = "";
+ [JsonPropertyName("html_url")] public string HtmlUrl { get; set; } = "";
+ [JsonPropertyName("draft")] public bool Draft { get; set; }
+ [JsonPropertyName("prerelease")] public bool Prerelease { get; set; }
+ [JsonPropertyName("assets")] public List<Asset>? Assets { get; set; }
+ }
+
+ public sealed class Asset
+ {
+ [JsonPropertyName("name")] public string Name { get; set; } = "";
+ [JsonPropertyName("browser_download_url")] public string? Url { get; set; }
+ [JsonPropertyName("size")] public long Size { get; set; }
+ }
+}
diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.cs
index 4b7a235..1605b72 100644
--- a/windows/src/Cicada/App.cs
+++ b/windows/src/Cicada/App.cs
@@ -45,6 +45,13 @@ sealed class Controller
public readonly ListenEngine Listen;
public readonly SpeakEngine Speak;
public readonly WindowsVoice WindowsVoice = new();
+ public readonly UpdateChecker Updates;
+ /// 检查更新 in settings: null, or the result of the last manual check for a few seconds.
+ public string? UpdateCheck { get; private set; }
+ bool checksUpdates;
+ /// The tray panel opened: check in the background once the last answer is an hour old.
+ public void PanelOpened() { if (checksUpdates) _ = Updates.CheckIfDue(UpdateChecker.Stale); }
+ public static string Version => typeof(Controller).Assembly.GetName().Version?.ToString(3) ?? "0";
PushToTalk? talk;
SpeakBar? speakBar;
DeviceRecorder? mic;
@@ -90,6 +97,8 @@ sealed class Controller
Notes.Changed += Changed;
Store.Changed += _ => Changed();
Store.Words += id => Dispatch.BeginInvoke(() => HeardWords(id));
+ Updates = new UpdateChecker(Settings.UpdateLastChecked, at => Dispatch.BeginInvoke(() => { Settings.UpdateLastChecked = at; Settings.Save(); })) { Current = Version };
+ Updates.Changed += UpdatesChanged;
}
public void Launch()
@@ -109,6 +118,8 @@ sealed class Controller
talk.Released += () => Dispatch.BeginInvoke(PressEnded);
Log.Debug($"audio: speakers {Endpoints.Default(Endpoints.Flow.Render)?.Name ?? "none"}, mic {Endpoints.Microphone()?.Name ?? "none"}, cable {(Endpoints.Cable() is null ? "absent" : "present")}");
DebugServer.Start(this);
+ // A dev build isn't what a release replaces: it checks only when pointed at a test feed.
+ if (!Paths.Dev || Environment.GetEnvironmentVariable("CICADA_UPDATE_FEED") is { Length: > 0 }) { checksUpdates = true; Updates.Start(); }
var watch = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
watch.Tick += (_, _) => _ = WatchEnd();
watch.Start();
@@ -124,6 +135,9 @@ sealed class Controller
UpdateTray();
});
+ /// Only update news re-renders settings: Changed fires on every line heard.
+ void UpdatesChanged() => Dispatch.BeginInvoke(() => { Changed(); settingsWindow?.UpdatesChanged(); });
+
// MARK: Tray (the Mac's menu bar panel)
void SetUpTray()
@@ -207,6 +221,7 @@ sealed class Controller
else menu.Items.Add(Item(L("开始听"), () => _ = ToggleListening(), Hotkey.Label.Replace('+', ' ')));
menu.Items.Add(Settings.View == "subtitles" ? Item(L("换成纪要"), () => SetView("notes")) : Item(L("换成字幕条"), () => SetView("subtitles")));
menu.Items.Add(new Separator());
+ if (Updates.Available is { } update) menu.Items.Add(Item(LF("有新版本 %@", update.Version), DownloadUpdate, ink: Palette.AccentText));
menu.Items.Add(Item(L("会议记录"), () => ShowRecords()));
menu.Items.Add(Item(L("设置"), ShowSettings));
menu.Items.Add(new Separator());
@@ -494,6 +509,8 @@ sealed class Controller
settingsWindow.Activate();
}
+ public void SettingsPage(string id) => settingsWindow?.Show(id);
+
public void SetView(string view)
{
Settings.View = view;
@@ -520,6 +537,38 @@ sealed class Controller
Changed();
}
+ // MARK: Updates
+
+ /// 下载: the browser fetches this PC's zip (or opens the release page when there is none).
+ /// Replacing the app in place comes later.
+ public void DownloadUpdate()
+ {
+ if (Updates.Available is not { } u) return;
+ Open(u.Zip ?? u.Page);
+ Log.Debug($"update: download {u.Version}");
+ }
+
+ public void OpenReleaseNotes() { if (Updates.Available is { } u) Open(u.Page); }
+
+ static void Open(string url)
+ {
+ try { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true }); }
+ catch (Exception e) { Log.Debug($"update: open failed {e.GetType().Name}"); }
+ }
+
+ /// 检查更新: says 正在检查… / 已是最新版本 / 连不上 GitHub for a few seconds.
+ public async Task CheckForUpdates()
+ {
+ if (UpdateCheck == L("正在检查…")) return;
+ UpdateCheck = L("正在检查…");
+ UpdatesChanged();
+ var reached = await Updates.Check();
+ UpdateCheck = Updates.Available is not null ? null : reached ? L("已是最新版本") : L("连不上 GitHub,请稍后再试");
+ UpdatesChanged();
+ await Task.Delay(4000);
+ if (UpdateCheck != L("正在检查…")) { UpdateCheck = null; UpdatesChanged(); }
+ }
+
public bool HotkeyRegistered => hotkey?.Registered ?? false;
public void SettingsChanged()
{
@@ -569,6 +618,8 @@ sealed class Controller
["autostart"] = AutoStart.Enabled,
["ending"] = Ending is { } p ? $"{EndingTitle(p)} · {EndingLeft(p)}" : null,
["autoEnded"] = AutoEnded,
+ ["update"] = Updates.Available?.Version,
+ ["updateChecked"] = Updates.LastChecked?.ToString("o"),
["inCall"] = endWatch is { } w ? string.Join(",", w.InCall.Values) : null,
};
}
@@ -576,7 +627,8 @@ sealed class Controller
/// Debug commands over a named pipe (\\.\pipe\cicada-dev), dev builds only: the Windows
/// counterpart of the Mac's `tools/lsctl`. One command per connection, one JSON line back.
/// state | start | stop | feed <wav> | sample | view notes|subtitles | capture on|off
-/// show notes|records|settings | quit
+/// show notes|records|settings [page]|flyout|menu | quit
+/// updatefeed <url or file> | checkupdate
/// calls <program=name,…>|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep
static class DebugServer
{
@@ -624,7 +676,7 @@ static class DebugServer
case "capture": app.Settings.ShowInCapture = arg == "on"; app.Settings.Save(); app.CaptureSettingChanged(); break;
case "show":
if (arg == "records") app.ShowRecords();
- else if (arg == "settings") app.ShowSettings();
+ else if (arg.StartsWith("settings")) { app.ShowSettings(); if (arg.Length > 9) app.SettingsPage(arg[9..]); }
else if (arg == "flyout") app.ShowFlyout();
else if (arg == "menu") app.ShowMenu();
else if (arg.StartsWith("onboarding")) { var o = new Onboarding(app); if (int.TryParse(arg[10..].Trim(), out var n)) o.At(n); o.Show(); }
@@ -649,6 +701,8 @@ static class DebugServer
break;
case "endkeep": app.KeepRecording(); break;
case "quit": _ = app.Quit(); break;
+ case "updatefeed": app.Updates.Feed = arg; _ = app.CheckForUpdates(); break;
+ case "checkupdate": _ = app.CheckForUpdates(); break;
case "state": break;
default: return new JsonObject { ["error"] = $"unknown command {parts[0]}" };
}
diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.cs
index 2b4c91b..17f5e6c 100644
--- a/windows/src/Cicada/SettingsWindow.cs
+++ b/windows/src/Cicada/SettingsWindow.cs
@@ -65,8 +65,10 @@ sealed class SettingsWindow : Window
Card(Icons.List, L("说话人识别"), L("按声音标出说话人 1、2…,只在这台电脑上处理"), Ui.Switch(app.Settings.SpeakerVoices, v => { app.Settings.SpeakerVoices = v; Save(); }, L("说话人识别"))),
Card(Icons.Power, L("开机时启动知了"), null, Ui.Switch(AutoStart.Enabled, v => AutoStart.Enabled = v, L("开机时启动知了"))),
Card(Icons.Folder, L("会议记录存放位置"), $"{Paths.Sessions} · {L("和 Mac 版格式相同")}", Ui.Button(L("打开文件夹"), () => OpenFolder(Paths.Sessions), height: 32))));
- var version = typeof(SettingsWindow).Assembly.GetName().Version?.ToString(3) ?? "";
- Section(page, "about", L("关于"), Group(Card(null, LF("知了 %@", version), L("说话人识别用 WeSpeaker 的声纹模型(CC BY 4.0)"), Ui.LinkText(L("打开日志"), () => OpenFolder(Path.GetDirectoryName(Paths.Log)!)), AppIcon.Small(24))));
+ Section(page, "about", L("关于"), Group(
+ Card(null, LF("知了 %@", Controller.Version), UpdateDetail(), UpdateControl(), AppIcon.Small(24)),
+ Card(null, L("日志"), null, Ui.LinkText(L("打开日志"), () => OpenFolder(Path.GetDirectoryName(Paths.Log)!)))),
+ Credit());
scroll.Content = page;
scroll.ScrollToVerticalOffset(shownPage == current ? offset : 0);
shownPage = current;
@@ -75,6 +77,33 @@ sealed class SettingsWindow : Window
string? shownPage;
+ static FrameworkElement Credit() { var t = Ui.Helper(L("说话人识别用 WeSpeaker 的声纹模型(CC BY 4.0)")); t.Margin = new Thickness(6, 0, 0, 0); return t; }
+
+ /// Opens one category's page (the debug pipe's `show settings about`).
+ public void Show(string id) { current = id; Render(); }
+
+ /// An update was found or a check finished: only 关于 shows it.
+ public void UpdatesChanged() { if (current == "about") Render(); }
+
+ // The Mac's AppRows version row: what the last check found, and 检查更新 or 下载.
+ string? UpdateDetail()
+ {
+ if (app.Updates.Available is { } u) return LF("有新版本 %@", u.Version) + " · " + L("下载后解压,替换旧的知了");
+ if (app.UpdateCheck is { } c) return c;
+ if (app.Updates.LastChecked is not { } d) return null;
+ var local = d.ToLocalTime();
+ return LF("上次检查 %@", local.ToString(local.Date == DateTime.Today ? "HH:mm" : L("M月d日 HH:mm"), Strings.Culture));
+ }
+
+ FrameworkElement UpdateControl()
+ {
+ if (app.Updates.Available is not null)
+ return Ui.Row(12, Ui.LinkText(L("更新说明"), app.OpenReleaseNotes), Ui.Button(L("下载"), app.DownloadUpdate, Ui.Kind.Primary, height: 32));
+ var check = Ui.Button(L("检查更新"), () => _ = app.CheckForUpdates(), height: 32);
+ check.IsEnabled = app.UpdateCheck != L("正在检查…");
+ return check;
+ }
+
void Nav()
{
nav.Children.Clear();
diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.strings
index 9b0ad33..58d89d7 100644
--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings
@@ -173,3 +173,6 @@
"去设置" = "Settings";
"听电脑里的声音" = "Hear this PC's audio";
"让知了听到电脑里的声音" = "Let Cicada hear your PC";
+"日志" = "Log";
+"下载后解压,替换旧的知了" = "Unzip it and replace the old Cicada";
+"下载" = "Download";
diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
index 569cbbb..49dbca8 100644
--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings
@@ -173,3 +173,6 @@
"去设置" = "設定へ";
"听电脑里的声音" = "PC の音声を聞く";
"让知了听到电脑里的声音" = "Cicada に PC の音を聞かせる";
+"日志" = "ログ";
+"下载后解压,替换旧的知了" = "展開して古い Cicada と置き換えてください";
+"下载" = "ダウンロード";
diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
index 0be98ba..0433873 100644
--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings
+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings
@@ -173,3 +173,6 @@
"去设置" = "설정으로";
"听电脑里的声音" = "PC 소리 듣기";
"让知了听到电脑里的声音" = "Cicada가 PC 소리를 듣게 하세요";
+"日志" = "로그";
+"下载后解压,替换旧的知了" = "압축을 풀어 이전 Cicada를 교체하세요";
+"下载" = "다운로드";
diff --git a/windows/src/Cicada/TrayFlyout.cs b/windows/src/Cicada/TrayFlyout.cs
index 0eb5b2d..e491f91 100644
--- a/windows/src/Cicada/TrayFlyout.cs
+++ b/windows/src/Cicada/TrayFlyout.cs
@@ -37,6 +37,7 @@ sealed class TrayFlyout : Window
{
if (IsVisible) { Hide(); return; }
if ((DateTime.UtcNow - hiddenAt).TotalMilliseconds < 300) return;
+ app.PanelOpened();
Refresh();
Show();
Anchor();
@@ -75,6 +76,25 @@ sealed class TrayFlyout : Window
var head = Ui.Spread(title, Ui.IconButton(Icons.Gear, L("打开设置"), () => Do(app.ShowSettings), Palette.Body, 36, 18));
stack.Children.Add(head);
+ // A newer release (the Mac's UpdateBanner): the browser downloads this PC's zip.
+ if (app.Updates.Available is { } update)
+ {
+ var size = update.Size > 0 ? $"{update.Size / 1_048_576.0:0} MB · " : "";
+ var text = Ui.Stack(2, Ui.Text(LF("新版本 %@", update.Version), 13, Palette.Ink, Palette.Strong, wrap: false),
+ Ui.Text(size + L("下载后解压,替换旧的知了"), 11, Palette.Secondary),
+ Ui.LinkText(L("更新说明"), () => Do(app.OpenReleaseNotes), 11));
+ var download = Ui.Button(L("下载"), () => Do(app.DownloadUpdate), Ui.Kind.Standard, height: 30);
+ var dock = new DockPanel();
+ DockPanel.SetDock(download, Dock.Right);
+ download.VerticalAlignment = VerticalAlignment.Center; download.Margin = new Thickness(10, 0, 0, 0);
+ var dot = Ui.Dot(Palette.Live, 7);
+ dot.Margin = new Thickness(0, 5, 8, 0); dot.VerticalAlignment = VerticalAlignment.Top;
+ DockPanel.SetDock(dot, Dock.Left);
+ dock.Children.Add(download); dock.Children.Add(dot); dock.Children.Add(text);
+ var strip = new Border { Background = Palette.AccentPale, CornerRadius = new CornerRadius(9), Padding = new Thickness(10), Margin = new Thickness(0, 14, 0, 0), Child = dock };
+ stack.Children.Add(strip);
+ }
+
// The one thing to do
var main = new StackPanel { Margin = new Thickness(0, 18, 0, 0) };
if (listen.Listening && app.Ending is { } p)
diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.cs
index c8398bf..36b78fa 100644
--- a/windows/tests/Cicada.Tests/Program.cs
+++ b/windows/tests/Cicada.Tests/Program.cs
@@ -835,4 +835,68 @@ static class Tests
}
finally { LingClient.Spacing = old; }
}
+
+ // MARK: Updates (the Mac's UpdateCheckerTests)
+
+ static string Rel(string tag, params string[] assets) =>
+ $$"""{"tag_name":"{{tag}}","html_url":"https://example.com/{{tag}}","assets":[{{string.Join(",", assets.Select(a => $$"""{"name":"{{a}}","browser_download_url":"https://example.com/{{a}}","size":1048576}"""))}}]}""";
+
+ public static void UpdateVersionsCompareByNumber()
+ {
+ Check(UpdateChecker.IsNewer("2.10.0", "2.9.1"), "2.10 > 2.9");
+ Check(UpdateChecker.IsNewer("1.4.1", "1.4"), "1.4.1 > 1.4");
+ Check(!UpdateChecker.IsNewer("1.4.0", "1.4"), "1.4.0 = 1.4");
+ Check(!UpdateChecker.IsNewer("1.3.9", "1.4.0"), "older");
+ }
+
+ public static void UpdateSkipsReleasesWithoutAWindowsZip()
+ {
+ var list = UpdateChecker.Decode($"[{Rel("v1.6.0", "Cicada-1.6.0-macOS-AppleSilicon.zip")},{Rel("v1.5.0", "Cicada-1.5.0-Windows-x64.zip", "Cicada-1.5.0-Windows-ARM64.zip")}]")!;
+ var u = UpdateChecker.NewestWindows(list, "x64")!;
+ Equal("1.5.0", u.Version, "newest with a Windows zip");
+ Equal("https://example.com/Cicada-1.5.0-Windows-x64.zip", u.Zip, "this PC's zip");
+ Equal(1048576L, u.Size, "size");
+ Equal("https://example.com/Cicada-1.5.0-Windows-ARM64.zip", UpdateChecker.NewestWindows(list, "ARM64")!.Zip, "ARM zip");
+ }
+
+ public static void UpdateOnArmFallsBackToX64AndSkipsDrafts()
+ {
+ var draft = Rel("v2.0.0", "Cicada-2.0.0-Windows-x64.zip").Replace("\"tag_name\"", "\"draft\":true,\"tag_name\"");
+ var list = UpdateChecker.Decode($"[{draft},{Rel("v1.5.0", "Cicada-1.5.0-Windows-x64.zip")}]")!;
+ var u = UpdateChecker.NewestWindows(list, "ARM64")!;
+ Equal("1.5.0", u.Version, "draft skipped");
+ Equal("https://example.com/Cicada-1.5.0-Windows-x64.zip", u.Zip, "x64 on ARM");
+ Equal(1, UpdateChecker.Decode(Rel("v1.5.0"))!.Count, "a single release");
+ Equal(null, UpdateChecker.Decode("{\"message\":\"Not Found\"}"), "GitHub's 404");
+ Equal(null, UpdateChecker.Decode("<html>"), "not JSON");
+ }
+
+ public static void UpdateDueAfterTheAge()
+ {
+ var now = DateTimeOffset.FromUnixTimeSeconds(1_000_000);
+ Check(UpdateChecker.Due(null, now, UpdateChecker.Every), "never checked");
+ Check(!UpdateChecker.Due(now.AddHours(-1), now, UpdateChecker.Every), "an hour ago");
+ Check(UpdateChecker.Due(now.AddHours(-4), now, UpdateChecker.Every), "4 hours ago");
+ Check(UpdateChecker.Due(now.AddHours(2), now, UpdateChecker.Every), "clock set back");
+ }
+
+ public static async Task UpdateCheckReadsAFeedFile()
+ {
+ var file = Path.Combine(Path.GetTempPath(), $"cicada-feed-{Environment.ProcessId}.json");
+ File.WriteAllText(file, $"[{Rel("v9.0.0", "Cicada-9.0.0-Windows-x64.zip", "Cicada-9.0.0-Windows-ARM64.zip")}]");
+ DateTimeOffset? saved = null;
+ var c = new UpdateChecker(null, at => saved = at) { Feed = file, Current = "1.0.0" };
+ try
+ {
+ Check(await c.Check(), "reached");
+ Equal("9.0.0", c.Available?.Version, "found");
+ Check(saved is not null && c.LastChecked == saved, "remembered");
+ c.Current = "9.0.0";
+ await c.Check();
+ Equal(null, c.Available, "up to date");
+ c.Feed = file + ".missing";
+ Check(!await c.Check(), "unreachable");
+ }
+ finally { File.Delete(file); }
+ }
}