feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
# updater
The update window of [MyGo](https://github.com/egoist/mygo) apps, in the
manner of Sparkle: it checks for updates in the background, shows the
release notes of a new version and offers to install it, skip it or remind
the user later, downloads it with a progress bar and relaunches the app into
it. It is all Go, with no npm package.
```go
import "github.com/egoist/mygo/plugins/updater"
mygo.Use(updater.Plugin) // or updater.New(updater.Options{Interval: ..., Icon: ...})
```
and "Check for Updates…" in the app's menu:
```go
{Label: "My App", Submenu: []*mygo.MenuItem{
{Role: mygo.RoleAbout},
updater.MenuItem(),
mygo.Separator(),
{Role: mygo.RoleQuit},
}},
```
Apps whose windows all show native UI use `native.Plugin` (package
`github.com/egoist/mygo/plugins/updater/native`) instead: the same window
drawn in native UI, with no webview.
It speaks the user's language (English, Chinese, Dutch, French, German,
Italian, Japanese, Korean, Polish, Portuguese, Russian, Spanish, Turkish,
Ukrainian), and `Options.Strings` changes its texts or adds languages.
The app must be built with updates: see
[auto-updates](https://github.com/egoist/mygo/blob/main/docs/updates.md).
[The plugin's documentation](https://github.com/egoist/mygo/blob/main/docs/plugins/updater.md)
lists the options, the languages and the preferences
(`SetAutomaticChecks`, `SetAutomaticDownloads`, and `OnChange` to hear
them change) apps can offer.
+98
View File
@@ -0,0 +1,98 @@
package updater
import (
"context"
"errors"
"testing"
"time"
)
func activateAvailabilityHarness(t *testing.T) *harness {
t.Helper()
h := newHarness(t, Options{})
active.Store(h.u)
t.Cleanup(func() { active.Store(nil) })
return h
}
func TestAvailableVersionChangesNotify(t *testing.T) {
h := activateAvailabilityHarness(t)
if AvailableVersion() != "" {
t.Fatal("a new updater already has an available version")
}
originalNow := now
now = func() time.Time { return time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC) }
t.Cleanup(func() { now = originalNow })
changes := make(chan string, 8)
off := OnChange(func() { changes <- AvailableVersion() })
defer off()
wantChange := func(want string) {
t.Helper()
select {
case got := <-changes:
if got != want {
t.Fatalf("available version = %q, want %q", got, want)
}
case <-time.After(5 * time.Second):
t.Fatal("availability change was not reported")
}
}
h.u.checked(nil, "2.0.0", false)
wantChange("2.0.0")
h.u.checked(errors.New("offline"), "", false)
wantChange("")
h.u.checked(nil, "2.0.0", false)
wantChange("2.0.0") // LastCheck is unchanged; availability must still notify.
h.u.checked(nil, "", false)
wantChange("")
}
func TestAvailableVersionFollowsSkipAndLater(t *testing.T) {
h := activateAvailabilityHarness(t)
h.result = func(context.Context) (*release, error) { return newRelease("2.0.0", nil), nil }
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "A new version of")
if AvailableVersion() != "2.0.0" {
t.Fatal("a detected update did not expose its version")
}
s.Respond(v.Prompt, actionSkip, false)
waitDone(t, done)
if AvailableVersion() != "" {
t.Fatal("a skipped update remains available")
}
waitDone(t, h.begin(false))
h.noWindow()
if AvailableVersion() != "" {
t.Fatal("the automatic check exposed a skipped update")
}
h.result = func(context.Context) (*release, error) { return newRelease("3.0.0", nil), nil }
done = h.begin(false)
s = h.shown()
v = waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
if AvailableVersion() != "3.0.0" {
t.Fatal("reminding later lost the detected version")
}
h.result = func(context.Context) (*release, error) { return nil, nil }
waitDone(t, h.begin(false))
if AvailableVersion() != "" {
t.Fatal("an up-to-date result retained the previous version")
}
}
func TestAvailableVersionRetainedAfterInstallation(t *testing.T) {
h := activateAvailabilityHarness(t)
h.result = func(context.Context) (*release, error) { return newRelease("2.0.0", nil), nil }
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionInstall, false)
v = waitView(t, s, "Ready to Relaunch")
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
if AvailableVersion() != "2.0.0" {
t.Fatal("the installed update needs to remain discoverable until relaunch")
}
}
@@ -0,0 +1,212 @@
// Package frontend is what the updater shares with the windows that show
// its sessions: package updater shows them in a web page, package native
// in native UI.
package frontend
import (
"runtime"
"sync"
"github.com/egoist/mygo"
"github.com/egoist/mygo/plugins/updater/internal/markdown"
)
// Session is a check for updates and what follows it, as its window sees
// it.
type Session interface {
// NewWindow creates the session's window, hidden, showing content, or
// a web page when content is nil. The session resizes it for its
// views and closes it when it ends.
NewWindow(content mygo.Content) *mygo.Window
// Current returns the view to show and a channel closed when it
// changes.
Current() (View, <-chan struct{})
// Done is closed when the session ends or its window closes.
Done() <-chan struct{}
// Respond answers the prompt of a view with a button, and tells
// whether updates may be installed automatically from now on. Only
// the first response to a prompt counts.
Respond(prompt int, a Action, automaticDownloads bool)
// Fit gives the window the width its buttons need, when they need
// more than the usual width, and a status view the height of its
// content, in DIPs.
Fit(width, height int)
// Texts returns the texts of the window that views leave out.
Texts() Texts
// Icon returns the PNG image of the window, or nil.
Icon() []byte
// User reports whether the user asked for the check: the window shows
// in front.
User() bool
}
// Open creates the window of a session and shows it, at once or once it
// is ready to.
type Open func(s Session)
// Plugin returns the updater plugin with opts, an updater.Options, whose
// windows open creates. Package updater sets it.
var Plugin func(opts any, open Open) mygo.Plugin
// Show shows win as Sparkle shows its update alert: in front, with the
// keyboard, when the user asked for the check or the app is active. A check
// in the background takes the keyboard from no other app: on macOS win
// waits until the app becomes active, unless the app has no Dock icon and
// so may never be, which comes to the front; elsewhere it shows without
// the keyboard.
func Show(win *mygo.Window, user bool) { show(win, user) }
// The app as Show sees it, which tests swap.
var (
goos = runtime.GOOS
appActive = mygo.App.IsActive
activationPolicy = mygo.App.ActivationPolicy
focusApp = mygo.App.Focus
onAppActive = mygo.App.OnDidBecomeActive
)
// window is what Show does with a *mygo.Window.
type window interface {
Show()
ShowInactive()
Focus()
IsVisible() bool
OnClosed(fn func()) (off func())
}
func show(win window, user bool) {
switch {
case user || appActive():
case goos != "darwin":
win.ShowInactive()
return
case activationPolicy() != mygo.ActivationPolicyRegular:
focusApp()
default:
showWhenActive(win)
return
}
win.Show()
win.Focus()
}
// showWhenActive shows win in front once the app becomes active, unless
// it closed first or the user had it shown already.
func showWhenActive(win window) {
var mu sync.Mutex
var offs []func()
done := false
// end stops waiting, and shows win when front is set. Only its first
// call counts.
end := func(front bool) {
mu.Lock()
if done {
mu.Unlock()
return
}
done = true
for _, off := range offs {
off()
}
mu.Unlock()
if front && !win.IsVisible() {
win.Show()
win.Focus()
}
}
mu.Lock()
offs = append(offs, onAppActive(func() { end(true) }), win.OnClosed(func() { end(false) }))
mu.Unlock()
// The app may have become active before it was watched.
if appActive() {
end(true)
}
}
// Action is a button of the update window.
type Action string
const (
OK Action = "ok"
Cancel Action = "cancel"
Skip Action = "skip"
Later Action = "later"
Install Action = "install"
Relaunch Action = "relaunch"
// Close is the window closing, not a button.
Close Action = "close"
)
// View is what the update window shows.
type View struct {
// Prompt changes with the buttons: responses name the prompt they
// answer, so that none answers a later one.
Prompt int `json:"prompt"`
// Release views show release notes, in a larger window.
Release bool `json:"release,omitzero"`
Title string `json:"title"`
Message string `json:"message,omitzero"`
// Detail is the error of a failure.
Detail string `json:"detail,omitzero"`
// Notes are the release notes.
Notes []markdown.Block `json:"-"`
// Bar shows a progress bar with Progress, between 0 and 1, or -1 when
// the progress is unknown.
Bar bool `json:"bar,omitzero"`
Progress float64 `json:"progress,omitzero"`
// Checkbox offers to download and install updates automatically,
// Checked or not.
Checkbox bool `json:"checkbox,omitzero"`
Checked bool `json:"checked,omitzero"`
Buttons []Button `json:"buttons"`
}
// Button is a button of a view.
type Button struct {
Action Action `json:"action"`
Label string `json:"label"`
// Default is the button of Enter, Cancel the one of Escape.
Default bool `json:"default,omitzero"`
Cancel bool `json:"cancel,omitzero"`
// Aside sets the button apart, on the left.
Aside bool `json:"aside,omitzero"`
Disabled bool `json:"disabled,omitzero"`
}
// Texts are the texts of the window around its views, in the language of
// the window.
type Texts struct {
// Title is the title of the window, ReleaseNotes the heading of the
// notes and AutomaticDownloads the label of the checkbox.
Title, ReleaseNotes, AutomaticDownloads string
// Lang is the language, such as "zh-Hans", and RTL is set for those
// written from right to left.
Lang string
RTL bool
}
// The size of the update window's content, for status views and for views
// with release notes.
const (
StatusWidth, StatusHeight = 480, 148
ReleaseWidth, ReleaseHeight = 620, 440
)
// Size returns the size of the window's content for a status view or a
// release view.
func Size(release bool) (width, height int) {
if release {
return ReleaseWidth, ReleaseHeight
}
return StatusWidth, StatusHeight
}
// Background returns the light and dark colors of the update window: the
// gray of dialogs on macOS, and white elsewhere, where the title bar above
// it is light.
func Background() (light, dark string) {
if runtime.GOOS == "darwin" {
return "#ececec", "#1e1e1e"
}
return "#fff", "#1e1e1e"
}
@@ -0,0 +1,126 @@
package frontend
import (
"testing"
"github.com/egoist/mygo"
)
type fakeWindow struct {
visible, focused, inactive bool
closed []func()
}
func (w *fakeWindow) Show() { w.visible = true }
func (w *fakeWindow) ShowInactive() { w.visible, w.inactive = true, true }
func (w *fakeWindow) Focus() { w.focused = true }
func (w *fakeWindow) IsVisible() bool { return w.visible }
func (w *fakeWindow) OnClosed(fn func()) func() {
w.closed = append(w.closed, fn)
return func() { w.closed = nil }
}
// fakeApp is the app as Show sees it, on GOOS os, until the test ends.
type fakeApp struct {
active, focused bool
policy mygo.ActivationPolicy
listeners []func()
}
func useApp(t *testing.T, os string) *fakeApp {
a := &fakeApp{policy: mygo.ActivationPolicyRegular}
prev := [...]any{goos, appActive, activationPolicy, focusApp, onAppActive}
goos = os
appActive = func() bool { return a.active }
activationPolicy = func() mygo.ActivationPolicy { return a.policy }
focusApp = func() { a.focused = true }
onAppActive = func(fn func()) func() {
a.listeners = append(a.listeners, fn)
return func() { a.listeners = nil }
}
t.Cleanup(func() {
goos = prev[0].(string)
appActive = prev[1].(func() bool)
activationPolicy = prev[2].(func() mygo.ActivationPolicy)
focusApp = prev[3].(func())
onAppActive = prev[4].(func(func()) func())
})
return a
}
func (a *fakeApp) activate() {
a.active = true
for _, fn := range a.listeners {
fn()
}
}
// A background check while the app is active shows the window in front, with
// the keyboard, as Sparkle does; it used to show it behind the app's window.
func TestShowActiveApp(t *testing.T) {
for _, os := range []string{"darwin", "windows", "linux"} {
a := useApp(t, os)
a.active = true
w := &fakeWindow{}
show(w, false)
if !w.visible || !w.focused {
t.Errorf("%s: visible %v, focused %v; want the window in front", os, w.visible, w.focused)
}
}
}
// On macOS a background check while another app is in front waits for the
// app to become active, then shows the window in front, once.
func TestShowWaitsForActivation(t *testing.T) {
a := useApp(t, "darwin")
w := &fakeWindow{}
show(w, false)
if w.visible {
t.Fatal("the window showed while the app was in the background")
}
a.activate()
if !w.visible || !w.focused || w.inactive {
t.Fatalf("visible %v, focused %v, inactive %v once active; want it in front", w.visible, w.focused, w.inactive)
}
if len(a.listeners) != 0 || len(w.closed) != 0 {
t.Error("still watching the app after showing the window")
}
}
// A window closed while it waits for the app, as when its session ends,
// never shows.
func TestShowClosedWhileWaiting(t *testing.T) {
a := useApp(t, "darwin")
w := &fakeWindow{}
show(w, false)
for _, fn := range w.closed {
fn()
}
a.activate()
if w.visible {
t.Error("a closed window showed when the app became active")
}
}
// An app without a Dock icon may never become active by itself, so a
// background check brings it to the front with the window, as Sparkle does.
func TestShowAccessoryApp(t *testing.T) {
a := useApp(t, "darwin")
a.policy = mygo.ActivationPolicyAccessory
w := &fakeWindow{}
show(w, false)
if !a.focused || !w.visible || !w.focused {
t.Errorf("app focused %v, window visible %v, focused %v; want both in front", a.focused, w.visible, w.focused)
}
}
// Elsewhere a background check while another app is in front shows the
// window without the keyboard.
func TestShowInactiveElsewhere(t *testing.T) {
useApp(t, "windows")
w := &fakeWindow{}
show(w, false)
if !w.visible || w.focused {
t.Errorf("visible %v, focused %v; want it shown without the keyboard", w.visible, w.focused)
}
}
@@ -0,0 +1,534 @@
// Package markdown parses the release notes of the update window. It
// knows what changelogs use: headings, paragraphs, nested lists, block
// quotes, fenced code, rules, emphasis, code spans and links. Everything
// else is text: raw HTML stays text, and links only go to http, https and
// mailto URLs, so notes cannot run code in the window.
package markdown
import (
"html"
"strconv"
"strings"
"unicode/utf8"
)
// BlockKind is what a Block is.
type BlockKind uint8
const (
Paragraph BlockKind = iota
Heading
List
Quote
Code
Rule
)
// Block is a block of release notes.
type Block struct {
Kind BlockKind
// Level is the level of a heading, from 1 to 6.
Level int
// Inlines are the text of a paragraph or heading.
Inlines []Inline
// Text is the text of fenced code.
Text string
// Ordered is set for a numbered list, whose Items hold the blocks of
// each item; Blocks are those of a quote.
Ordered bool
Items [][]Block
Blocks []Block
}
// InlineKind is what an Inline is.
type InlineKind uint8
const (
Text InlineKind = iota
CodeSpan
Emphasis
Strong
Link
)
// Inline is a run of text in a paragraph or heading.
type Inline struct {
Kind InlineKind
// Text is the text of a Text or CodeSpan.
Text string
// Children are the text of an Emphasis, Strong or Link.
Children []Inline
// URL is where a Link goes: an http, https or mailto URL.
URL string
}
// Parse parses release notes.
func Parse(src string) []Block {
src = strings.ReplaceAll(src, "\r\n", "\n")
src = strings.ReplaceAll(src, "\t", " ")
return parseBlocks(strings.Split(src, "\n"))
}
// parseBlocks parses lines as blocks.
func parseBlocks(lines []string) []Block {
var blocks []Block
var para []string
flush := func() {
if len(para) > 0 {
blocks = append(blocks, Block{Kind: Paragraph, Inlines: parseInline(strings.Join(para, "\n"))})
para = nil
}
}
for i := 0; i < len(lines); {
line := lines[i]
trimmed := strings.TrimSpace(line)
switch {
case trimmed == "":
flush()
i++
case isFence(trimmed):
flush()
fence := trimmed[:3]
var code []string
for i++; i < len(lines) && !strings.HasPrefix(strings.TrimSpace(lines[i]), fence); i++ {
code = append(code, lines[i])
}
i++
blocks = append(blocks, Block{Kind: Code, Text: strings.Join(code, "\n")})
case heading(trimmed) > 0:
flush()
n := heading(trimmed)
text := strings.TrimRight(strings.TrimSpace(trimmed[n:]), "#")
blocks = append(blocks, Block{Kind: Heading, Level: n, Inlines: parseInline(strings.TrimSpace(text))})
i++
case isRule(trimmed):
flush()
blocks = append(blocks, Block{Kind: Rule})
i++
case strings.HasPrefix(trimmed, ">"):
flush()
var quote []string
for ; i < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i]), ">"); i++ {
q := strings.TrimPrefix(strings.TrimSpace(lines[i]), ">")
quote = append(quote, strings.TrimPrefix(q, " "))
}
blocks = append(blocks, Block{Kind: Quote, Blocks: parseBlocks(quote)})
default:
if _, _, ok := listMarker(line); ok && (len(para) == 0 || startsList(line)) {
flush()
var list Block
list, i = parseList(lines, i)
blocks = append(blocks, list)
continue
}
para = append(para, trimmed)
i++
}
}
flush()
return blocks
}
// parseList parses the list starting at lines[i] and returns it with the
// index of the line after it.
func parseList(lines []string, i int) (Block, int) {
indent, ordered, _ := listMarker(lines[i])
list := Block{Kind: List, Ordered: ordered}
for i < len(lines) {
ind, ord, ok := listMarker(lines[i])
if !ok || ind != indent || ord != ordered {
break
}
// The item holds the rest of its first line, the lines indented to
// its content, lists nested less deep than that, and the lines
// that continue its paragraph.
width := markerWidth(lines[i])
item := []string{lines[i][width:]}
blank := false
lines:
for i++; i < len(lines); i++ {
line := lines[i]
if strings.TrimSpace(line) == "" {
blank = true
item = append(item, "")
continue
}
ind := leadingSpaces(line)
_, _, marker := listMarker(line)
switch {
case ind >= width:
item = append(item, line[width:])
case ind > indent && marker:
item = append(item, line[ind:])
case !blank && !marker && !isBlockStart(line):
item = append(item, strings.TrimSpace(line))
default:
break lines
}
blank = false
}
for len(item) > 0 && item[len(item)-1] == "" {
item = item[:len(item)-1]
}
list.Items = append(list.Items, parseBlocks(item))
}
return list, i
}
// listMarker reports whether line starts a list item, with the indentation
// of its marker and whether the list is ordered.
func listMarker(line string) (indent int, ordered, ok bool) {
indent = leadingSpaces(line)
rest := line[indent:]
if len(rest) >= 2 && strings.ContainsRune("-*+", rune(rest[0])) && rest[1] == ' ' {
return indent, false, !isRule(strings.TrimSpace(rest))
}
n := 0
for n < len(rest) && n < 9 && rest[n] >= '0' && rest[n] <= '9' {
n++
}
if n > 0 && len(rest) > n+1 && (rest[n] == '.' || rest[n] == ')') && rest[n+1] == ' ' {
return indent, true, true
}
return 0, false, false
}
// markerWidth returns the column where the content of the list item that
// line starts begins: after its marker and the space after it.
func markerWidth(line string) int {
w := leadingSpaces(line)
for w < len(line) && line[w] != ' ' {
w++
}
start := w
for w < len(line) && line[w] == ' ' && w-start < 4 {
w++
}
return w
}
// startsList reports whether line starts a list item that may interrupt a
// paragraph: a bullet, or an ordered item numbered 1.
func startsList(line string) bool {
_, ordered, ok := listMarker(line)
if !ok {
return false
}
return !ordered || strings.HasPrefix(strings.TrimSpace(line), "1")
}
func isBlockStart(line string) bool {
t := strings.TrimSpace(line)
return heading(t) > 0 || isFence(t) || isRule(t) || strings.HasPrefix(t, ">")
}
func leadingSpaces(s string) int {
n := 0
for n < len(s) && s[n] == ' ' {
n++
}
return n
}
func heading(t string) int {
n := 0
for n < len(t) && n < 7 && t[n] == '#' {
n++
}
if n == 0 || n > 6 || (len(t) > n && t[n] != ' ') {
return 0
}
return n
}
func isFence(t string) bool { return strings.HasPrefix(t, "```") || strings.HasPrefix(t, "~~~") }
func isRule(t string) bool {
if len(t) < 3 || !strings.ContainsRune("-*_", rune(t[0])) {
return false
}
n := 0
for _, c := range t {
switch {
case c == rune(t[0]):
n++
case c != ' ':
return false
}
}
return n >= 3
}
// inlines collects the inlines of a text, merging runs of text.
type inlines []Inline
func (in *inlines) text(s string) {
if n := len(*in); n > 0 && (*in)[n-1].Kind == Text {
(*in)[n-1].Text += s
return
}
*in = append(*in, Inline{Kind: Text, Text: s})
}
// link adds children linked to href, or the children alone when the URL is
// not one the window opens.
func (in *inlines) link(href string, children []Inline) {
if !SafeURL(href) {
for _, c := range children {
if c.Kind == Text {
in.text(c.Text)
} else {
*in = append(*in, c)
}
}
return
}
*in = append(*in, Inline{Kind: Link, URL: href, Children: children})
}
// parseInline parses the text of a paragraph or heading.
func parseInline(s string) []Inline {
var in inlines
for i := 0; i < len(s); {
c := s[i]
switch {
case c == '\\' && i+1 < len(s) && isPunct(s[i+1]):
in.text(s[i+1 : i+2])
i += 2
continue
case c == '\n':
in.text(" ")
i++
continue
case c == '`':
n := run(s[i:], '`')
if end := strings.Index(s[i+n:], s[i:i+n]); end >= 0 {
code := strings.TrimSpace(strings.ReplaceAll(s[i+n:i+n+end], "\n", " "))
in = append(in, Inline{Kind: CodeSpan, Text: code})
i += n + end + n
continue
}
in.text(s[i : i+n])
i += n
continue
case c == '[' || c == '!' && strings.HasPrefix(s[i:], "!["):
image := c == '!'
start := i
if image {
start++
}
if text, href, n, ok := parseLink(s[start:]); ok {
var children []Inline
if image {
children = []Inline{{Kind: Text, Text: text}}
} else {
children = parseInline(text)
}
in.link(href, children)
i = start + n
continue
}
case c == '<':
if end := strings.IndexByte(s[i:], '>'); end > 0 {
if u := s[i+1 : i+end]; !strings.ContainsAny(u, " <") && SafeURL(u) {
in.link(u, []Inline{{Kind: Text, Text: u}})
i += end + 1
continue
}
}
case c == '*' || c == '_':
n := min(run(s[i:], c), 2)
if c == '_' && i > 0 && isWord(s[i-1]) {
break
}
delim := s[i : i+n]
rest := s[i+n:]
if rest != "" && rest[0] != ' ' && rest[0] != '\n' {
if end := closing(rest, delim); end > 0 {
kind := Emphasis
if n == 2 {
kind = Strong
}
in = append(in, Inline{Kind: kind, Children: parseInline(rest[:end])})
i += n + end + n
continue
}
}
in.text(delim)
i += n
continue
case c == 'h' && (i == 0 || !isWord(s[i-1])) && (strings.HasPrefix(s[i:], "https://") || strings.HasPrefix(s[i:], "http://")):
end := i
for end < len(s) && s[end] > ' ' && s[end] != '<' {
end++
}
u := strings.TrimRight(s[i:end], ".,:;!?\"')")
if strings.Count(u, "(") > strings.Count(u, ")") && end > i+len(u) && s[i+len(u)] == ')' {
u += ")"
}
in.link(u, []Inline{{Kind: Text, Text: u}})
i += len(u)
continue
}
_, size := utf8.DecodeRuneInString(s[i:])
in.text(s[i : i+size])
i += size
}
return in
}
// parseLink parses "[text](url)" or `[text](url "title")` at the start of
// s, returning the text, the URL and the length of the link.
func parseLink(s string) (text, href string, n int, ok bool) {
depth := 0
end := -1
for i := 0; i < len(s) && end < 0; i++ {
switch s[i] {
case '\\':
i++
case '[':
depth++
case ']':
if depth--; depth == 0 {
end = i
}
}
}
if end < 0 || !strings.HasPrefix(s[end+1:], "(") {
return "", "", 0, false
}
close := strings.IndexByte(s[end+2:], ')')
if close < 0 {
return "", "", 0, false
}
dest := strings.TrimSpace(s[end+2 : end+2+close])
if sp := strings.IndexAny(dest, " \n"); sp >= 0 {
dest = dest[:sp] // drop the title
}
dest = strings.TrimSuffix(strings.TrimPrefix(dest, "<"), ">")
return s[1:end], dest, end + 2 + close + 1, true
}
// SafeURL reports whether u is a URL the window opens: http, https or
// mailto.
func SafeURL(u string) bool {
l := strings.ToLower(u)
return strings.HasPrefix(l, "https://") || strings.HasPrefix(l, "http://") || strings.HasPrefix(l, "mailto:")
}
// closing returns the index of the delimiter closing an emphasis in s.
func closing(s, delim string) int {
for i := 1; i+len(delim) <= len(s); i++ {
switch {
case s[i] == '`':
// Code spans take precedence.
n := run(s[i:], '`')
if end := strings.Index(s[i+n:], s[i:i+n]); end >= 0 {
i += n + end + n - 1
}
case s[i] == '\\':
i++
case strings.HasPrefix(s[i:], delim) && s[i-1] != ' ' && s[i-1] != '\n':
if len(delim) == 1 && i+1 < len(s) && s[i+1] == delim[0] {
i++ // part of a strong delimiter
continue
}
if delim[0] == '_' && i+len(delim) < len(s) && isWord(s[i+len(delim)]) {
continue
}
return i
}
}
return -1
}
func run(s string, c byte) int {
n := 0
for n < len(s) && s[n] == c {
n++
}
return n
}
func isPunct(c byte) bool { return strings.IndexByte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", c) >= 0 }
func isWord(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c >= 0x80
}
// HTML renders blocks as HTML, escaping all their text.
func HTML(blocks []Block) string {
var b strings.Builder
writeBlocks(&b, blocks, false)
return b.String()
}
// writeBlocks renders blocks. tight renders paragraphs without <p>, apart
// by <br>, as in the items of a list.
func writeBlocks(b *strings.Builder, blocks []Block, tight bool) {
paras := 0
for _, bl := range blocks {
switch bl.Kind {
case Paragraph:
if !tight {
b.WriteString("<p>")
writeInlines(b, bl.Inlines)
b.WriteString("</p>")
} else {
if paras > 0 {
b.WriteString("<br>")
}
writeInlines(b, bl.Inlines)
}
paras++
case Heading:
tag := "h" + strconv.Itoa(bl.Level)
b.WriteString("<" + tag + ">")
writeInlines(b, bl.Inlines)
b.WriteString("</" + tag + ">")
case List:
tag := "ul"
if bl.Ordered {
tag = "ol"
}
b.WriteString("<" + tag + ">")
for _, item := range bl.Items {
b.WriteString("<li>")
writeBlocks(b, item, true)
b.WriteString("</li>")
}
b.WriteString("</" + tag + ">")
case Quote:
b.WriteString("<blockquote>")
writeBlocks(b, bl.Blocks, false)
b.WriteString("</blockquote>")
case Code:
b.WriteString("<pre><code>" + html.EscapeString(bl.Text) + "</code></pre>")
case Rule:
b.WriteString("<hr>")
}
}
}
func writeInlines(b *strings.Builder, inlines []Inline) {
for _, in := range inlines {
switch in.Kind {
case Text:
b.WriteString(html.EscapeString(in.Text))
case CodeSpan:
b.WriteString("<code>" + html.EscapeString(in.Text) + "</code>")
case Emphasis, Strong:
tag := "em"
if in.Kind == Strong {
tag = "strong"
}
b.WriteString("<" + tag + ">")
writeInlines(b, in.Children)
b.WriteString("</" + tag + ">")
case Link:
b.WriteString(`<a href="` + html.EscapeString(in.URL) + `">`)
writeInlines(b, in.Children)
b.WriteString("</a>")
}
}
}
@@ -0,0 +1,79 @@
package markdown
import (
"reflect"
"testing"
)
func TestHTML(t *testing.T) {
for _, tc := range []struct{ in, want string }{
{"", ""},
{"Hello\nworld", "<p>Hello world</p>"},
{"One\n\nTwo", "<p>One</p><p>Two</p>"},
{"### Added\n\n- One\n- Two", "<h3>Added</h3><ul><li>One</li><li>Two</li></ul>"},
{"## 1.2.0 ##", "<h2>1.2.0</h2>"},
{"#hashtag", "<p>#hashtag</p>"},
{"Fixes:\n- one\n- two", "<p>Fixes:</p><ul><li>one</li><li>two</li></ul>"},
{"1. one\n2. two", "<ol><li>one</li><li>two</li></ol>"},
{"We shipped\n2. things", "<p>We shipped 2. things</p>"},
{"- a\n - b\n - c\n- d", "<ul><li>a<ul><li>b</li><li>c</li></ul></li><li>d</li></ul>"},
{"1. a\n - b", "<ol><li>a<ul><li>b</li></ul></li></ol>"},
{"- a long\nitem\n- b", "<ul><li>a long item</li><li>b</li></ul>"},
{"- a\n\n more\n- b", "<ul><li>a<br>more</li><li>b</li></ul>"},
{"- a\n\nAfter", "<ul><li>a</li></ul><p>After</p>"},
{"- a\n* b", "<ul><li>a</li><li>b</li></ul>"},
{"- a\n1. b", "<ul><li>a</li></ul><ol><li>b</li></ol>"},
{"> quoted\n> text", "<blockquote><p>quoted text</p></blockquote>"},
{"---", "<hr>"},
{"- - -", "<hr>"},
{"```\n<b>code</b>\n\n x\n```\nafter", "<pre><code>&lt;b&gt;code&lt;/b&gt;\n\n x</code></pre><p>after</p>"},
{"**bold** and *em* and _em_ and __bold__", "<p><strong>bold</strong> and <em>em</em> and <em>em</em> and <strong>bold</strong></p>"},
{"snake_case_name and 2 * 3 * 4", "<p>snake_case_name and 2 * 3 * 4</p>"},
{"**bold *em* bold**", "<p><strong>bold <em>em</em> bold</strong></p>"},
{"`a *b* <c>` and ``x ` y``", "<p><code>a *b* &lt;c&gt;</code> and <code>x ` y</code></p>"},
{`\*not em\*`, "<p>*not em*</p>"},
{"[docs](https://example.com/a?b=1&c=2 \"Title\")", `<p><a href="https://example.com/a?b=1&amp;c=2">docs</a></p>`},
{"[**bold** link](https://example.com)", `<p><a href="https://example.com"><strong>bold</strong> link</a></p>`},
{"[bad](javascript:alert(1))", "<p>bad)</p>"},
{"[rel](/path)", "<p>rel</p>"},
{"![logo](https://example.com/logo.png)", `<p><a href="https://example.com/logo.png">logo</a></p>`},
{"<https://example.com> <b>hi</b>", `<p><a href="https://example.com">https://example.com</a> &lt;b&gt;hi&lt;/b&gt;</p>`},
{"See https://example.com/x_(y). Or (https://example.com).", `<p>See <a href="https://example.com/x_(y)">https://example.com/x_(y)</a>. Or (<a href="https://example.com">https://example.com</a>).</p>`},
{"<script>alert(1)</script>", "<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>"},
{`<img src=x onerror="alert(1)">`, "<p>&lt;img src=x onerror=&#34;alert(1)&#34;&gt;</p>"},
{"[x](https://a\"onmouseover=\"alert(1))", `<p><a href="https://a&#34;onmouseover=&#34;alert(1">x</a>)</p>`},
{"Café — ünïcode", "<p>Café — ünïcode</p>"},
{"a\r\nb", "<p>a b</p>"},
{"**unclosed", "<p>**unclosed</p>"},
{"[unclosed](https://x", "<p>[unclosed](<a href=\"https://x\">https://x</a></p>"},
} {
if got := HTML(Parse(tc.in)); got != tc.want {
t.Errorf("HTML(Parse(%q))\n got %s\nwant %s", tc.in, got, tc.want)
}
}
}
func TestParse(t *testing.T) {
got := Parse("## Fixed\n\n- A **bold [link](https://example.com)** fix\n 1. nested\n\n> `code`")
want := []Block{
{Kind: Heading, Level: 2, Inlines: []Inline{{Kind: Text, Text: "Fixed"}}},
{Kind: List, Items: [][]Block{{
{Kind: Paragraph, Inlines: []Inline{
{Kind: Text, Text: "A "},
{Kind: Strong, Children: []Inline{
{Kind: Text, Text: "bold "},
{Kind: Link, URL: "https://example.com", Children: []Inline{{Kind: Text, Text: "link"}}},
}},
{Kind: Text, Text: " fix"},
}},
{Kind: List, Ordered: true, Items: [][]Block{{{Kind: Paragraph, Inlines: []Inline{{Kind: Text, Text: "nested"}}}}}},
}}},
{Kind: Quote, Blocks: []Block{{Kind: Paragraph, Inlines: []Inline{{Kind: CodeSpan, Text: "code"}}}}},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Parse\n got %+v\nwant %+v", got, want)
}
if blocks := Parse(" \n\n"); len(blocks) != 0 {
t.Errorf("Parse of blank notes = %+v, want none", blocks)
}
}
+24
View File
@@ -0,0 +1,24 @@
// Package native is the update window of package updater drawn in native
// UI (package ui) instead of a web page, for apps whose windows all show
// native UI: it needs no webview, so neither WebKitGTK on Linux nor the
// WebView2 Runtime on Windows. Use it in place of updater.Plugin:
//
// mygo.Use(native.Plugin) // or native.New(updater.Options{Interval: ..., Icon: ...})
//
// The rest is package updater's: updater.MenuItem and
// updater.CheckForUpdates check from the app's menu, and the preferences
// (updater.SetAutomaticChecks, updater.OnChange, …) work the same.
package native
import (
"github.com/egoist/mygo"
"github.com/egoist/mygo/plugins/updater"
"github.com/egoist/mygo/plugins/updater/internal/frontend"
)
// Plugin is the plugin with the default options.
var Plugin = New(updater.Options{})
// New returns the plugin with options. Use one of them only, and neither
// updater.Plugin nor updater.New.
func New(opts updater.Options) mygo.Plugin { return frontend.Plugin(opts, open) }
+169
View File
@@ -0,0 +1,169 @@
package native
import (
"strconv"
"unicode"
"github.com/egoist/mygo/plugins/updater/internal/markdown"
"github.com/egoist/mygo/ui"
)
// notes builds release notes, in the manner of the page of package
// updater. Their text is selectable, and links open in the browser.
func notes(c *ui.Context, t *ui.Theme, blocks []markdown.Block) {
n := &notesStyle{t: t, rtl: rightToLeft(blocks)}
ui.Column(c).Children(func() { n.blocks(c, blocks, false, 0) })
}
// notesStyle is how release notes look. Like the page's notes, whose dir
// is auto, they are laid out from the right when the language they are
// written in is written from right to left, whatever the window's.
type notesStyle struct {
t *ui.Theme
rtl bool
}
// rightToLeft reports whether the first strongly directional letter of
// blocks is of a script written from right to left, as text does.
func rightToLeft(blocks []markdown.Block) bool {
var rtl, found bool
var inlines func([]markdown.Inline)
text := func(s string) {
for _, r := range s {
if found {
return
}
switch {
case unicode.In(r, unicode.Hebrew, unicode.Arabic, unicode.Syriac, unicode.Thaana, unicode.Nko, unicode.Samaritan, unicode.Mandaic, unicode.Adlam):
rtl, found = true, true
case unicode.IsLetter(r):
found = true
}
}
}
inlines = func(ins []markdown.Inline) {
for _, in := range ins {
text(in.Text)
inlines(in.Children)
}
}
var walk func([]markdown.Block)
walk = func(bs []markdown.Block) {
for _, b := range bs {
inlines(b.Inlines)
text(b.Text)
for _, item := range b.Items {
walk(item)
}
walk(b.Blocks)
}
}
walk(blocks)
return rtl
}
// blocks builds blocks, apart by the room between paragraphs, or by none
// in the items of a list (tight). depth counts the lists around them.
func (n *notesStyle) blocks(c *ui.Context, blocks []markdown.Block, tight bool, depth int) {
for i, b := range blocks {
var gap float32
switch {
case i == 0 || tight:
case b.Kind == markdown.Heading:
gap = 12
case blocks[i-1].Kind == markdown.Heading:
gap = 4
default:
gap = 8
}
n.block(c, b, depth).Margin(gap, 0, 0, 0)
}
}
// headingSizes are the sizes of headings of levels 1, 2 and the others,
// relative to the text.
var headingSizes = [...]float32{16.0 / 13, 14.0 / 13, 1}
func (n *notesStyle) block(c *ui.Context, b markdown.Block, depth int) ui.Element {
t := n.t
switch b.Kind {
case markdown.Heading:
size := headingSizes[min(b.Level, len(headingSizes))-1]
return paragraph(c, t, b.Inlines).FontSize(t.Rem(size)).Bold()
case markdown.List:
return ui.Column(c).Children(func() {
for i, item := range b.Items {
row := ui.Row(c).AlignItems(ui.Start)
if n.rtl {
row.Reverse()
}
row.Children(func() {
marker := bullet(depth)
if b.Ordered {
marker = strconv.Itoa(i+1) + "."
}
// The marker ends next to the item.
m := ui.Text(c, marker).Width(20).Shrink(0)
if n.rtl {
m.Padding(0, 0, 0, 6)
} else {
m.TextAlign(ui.End).Padding(0, 6, 0, 0)
}
ui.Column(c).Grow(1).Children(func() { n.blocks(c, item, true, depth+1) })
})
}
})
case markdown.Quote:
quote := ui.Column(c).BorderColor(t.Border).TextColor(t.TextMuted)
if n.rtl {
quote.BorderWidth(0, 3, 0, 0).Padding(0, 10, 0, 0)
} else {
quote.BorderWidth(0, 0, 0, 3).Padding(0, 0, 0, 10)
}
return quote.Children(func() { n.blocks(c, b.Blocks, false, depth) })
case markdown.Code:
return ui.ScrollHorizontal(c).Background(track(t)).Radius(3).Children(func() {
ui.Text(c, b.Text).Font("monospace").FontSize(t.Rem(12.0/13)).NoWrap().Padding(6, 8).Selectable()
})
case markdown.Rule:
return ui.Divider(c)
}
return paragraph(c, t, b.Inlines)
}
// paragraph builds the text of a paragraph or heading, which the user may
// select.
func paragraph(c *ui.Context, t *ui.Theme, inlines []markdown.Inline) ui.Element {
return ui.RichText(c).Children(func() { buildInlines(c, t, inlines) }).Selectable()
}
// bullet returns the marker of the items of a list in depth lists, as
// browsers draw them.
func bullet(depth int) string {
switch depth {
case 0:
return "•"
case 1:
return "◦"
}
return "▪"
}
// buildInlines builds the text of a paragraph inside it: links open in the
// browser.
func buildInlines(c *ui.Context, t *ui.Theme, inlines []markdown.Inline) {
for _, in := range inlines {
switch in.Kind {
case markdown.Text:
ui.Text(c, in.Text)
case markdown.CodeSpan:
ui.Text(c, in.Text).Font("monospace").FontSize(t.Rem(12.0 / 13)).TextBackground(track(t))
case markdown.Emphasis:
ui.RichText(c).Italic().Children(func() { buildInlines(c, t, in.Children) })
case markdown.Strong:
ui.RichText(c).Bold().Children(func() { buildInlines(c, t, in.Children) })
case markdown.Link:
ui.Link(c, "", in.URL).Children(func() { buildInlines(c, t, in.Children) })
}
}
}
+267
View File
@@ -0,0 +1,267 @@
package native
import (
"math"
"github.com/egoist/mygo/plugins/updater/internal/frontend"
"github.com/egoist/mygo/ui"
)
// window is the update window of a session.
type window struct {
s frontend.Session
texts frontend.Texts
icon *ui.Bitmap // nil without an icon
// What the view keeps from frame to frame, on the main thread: the
// prompt of the view it shows, the prompt the user answered, and the
// checkbox, which each prompt resets.
prompt int
answered int
checked bool
// built is what the last frame laid out, and fitted the size last
// asked of the window for it.
built layout
fitted [2]int
}
// layout is what the size of the window's content depends on.
type layout struct {
prompt int
title, message, detail string
bar, checkbox, release bool
windowWidth, windowHeight float32
}
// open creates the window of s, which shows at once.
func open(s frontend.Session) {
w := newWindow(s)
// Changes made while the window is being created redraw it too.
_, changed := s.Current()
win := s.NewWindow(ui.View(w.view))
go func() {
for {
select {
case <-changed:
_, changed = s.Current()
win.Invalidate()
case <-s.Done():
return
}
}
}()
frontend.Show(win, s.User())
}
func newWindow(s frontend.Session) *window {
w := &window{s: s, texts: s.Texts(), prompt: -1, answered: -1}
if png := s.Icon(); png != nil {
w.icon, _ = ui.DecodeBitmap(png) // no icon when it is not an image
}
return w
}
// The room around the window's content and between its parts, in DIPs, as
// in the page of package updater.
const (
padTop, padSide, padBottom = 18, 20, 20
iconSize, iconGap = 64, 18
footGap = 12
asideGap = 40
)
// view builds the update window.
func (w *window) view(c *ui.Context) {
v, _ := w.s.Current()
if v.Prompt != w.prompt {
w.prompt, w.checked = v.Prompt, v.Checked
}
t := theme(c.Theme())
c.SetTheme(t)
w.keys(c, v)
var body, aside, buttons ui.Element
ui.Column(c).Fill().Padding(padTop, padSide, padBottom).Gap(footGap).Children(func() {
top := w.row(c).Grow(1).Gap(iconGap).AlignItems(ui.Start)
if v.Release {
top.AlignItems(ui.Stretch)
}
top.Children(func() {
if w.icon != nil {
ui.Image(c, w.icon).Size(iconSize, iconSize).Shrink(0).AlignSelf(ui.Start)
}
body = ui.Column(c).Grow(1).Children(func() { w.body(c, t, v) })
})
w.row(c).Gap(10).Shrink(0).Children(func() {
aside = w.row(c).Gap(10).Shrink(0).Children(func() { w.buttons(c, t, v, true) })
ui.Spacer(c)
buttons = w.row(c).Gap(10).Shrink(0).Children(func() { w.buttons(c, t, v, false) })
})
})
w.fit(c, v, body, aside, buttons)
}
// row creates a row, laid out from the right in a window of a language
// written from right to left.
func (w *window) row(c *ui.Context) ui.Element {
r := ui.Row(c)
if w.texts.RTL {
r.Reverse()
}
return r
}
// body builds the texts, progress bar, release notes and checkbox of the
// view. Texts start on the side their own language starts, as the
// page's unicode-bidi: plaintext does, since they may fall back to
// English or be errors.
func (w *window) body(c *ui.Context, t *ui.Theme, v frontend.View) {
small := t.Rem(11.0 / 13)
ui.Text(c.Key("title"), v.Title).Bold().Margin(0, 0, 4, 0)
if v.Message != "" {
ui.Text(c.Key("message"), v.Message).Margin(0, 0, 6, 0)
}
if v.Bar {
bar := ui.Progress(c.Key("bar"), v.Progress).Margin(6, 0, 4, 0)
if w.texts.RTL {
bar.Reverse()
}
}
if v.Detail != "" {
// All of it, however long: the window grows to fit it, and a
// tooltip would cover the title.
ui.Text(c.Key("detail"), v.Detail).FontSize(small).TextColor(t.TextMuted).Selectable()
}
if len(v.Notes) > 0 {
ui.Column(c.Key("notes")).Grow(1).Margin(6, 0, 0, 0).Children(func() {
ui.Text(c, w.texts.ReleaseNotes).FontSize(small).Bold().Margin(0, 0, 4, 0)
ui.Scroll(c).Grow(1).Background(panel(t)).Border(1, t.Border).Padding(8, 12).Children(func() {
notes(c, t, v.Notes)
})
})
}
if v.Checkbox {
w.row(c).Key("checkbox").Margin(10, 0, 0, 0).Children(func() {
box := ui.Checkbox(c, &w.checked, w.texts.AutomaticDownloads)
if w.texts.RTL {
box.Reverse()
}
})
}
}
// buttons builds the buttons of the view set aside, or the others.
func (w *window) buttons(c *ui.Context, t *ui.Theme, v frontend.View, aside bool) {
height := float32(math.Round(float64(t.Rem(24.0 / 13))))
for _, b := range v.Buttons {
if b.Aside != aside {
continue
}
// Keyed by action, so that the focus leaves with the button.
var e ui.Element
if b.Default {
e = ui.PrimaryButton(c.Key(string(b.Action)), "")
} else {
e = ui.Button(c.Key(string(b.Action)), "").Shadow(0, 1, 1, 0, ui.RGBA(0, 0, 0, 0.08))
}
e.Padding(0, 14).Height(height).MinWidth(84).Disabled(w.off(v, b)).Children(func() {
ui.Text(c, b.Label).SingleLine()
})
if e.Clicked() {
w.respond(v, b)
}
}
}
// keys answers with the button of Escape, and that of Enter when no
// button has the focus.
func (w *window) keys(c *ui.Context, v frontend.View) {
for _, b := range v.Buttons {
if b.Cancel && c.Shortcut(0, ui.KeyEscape) || b.Default && c.Shortcut(0, ui.KeyEnter) {
w.respond(v, b)
}
}
}
// off reports whether a button is disabled: by the view, or because the
// user answered its prompt, until the next view.
func (w *window) off(v frontend.View, b frontend.Button) bool {
return b.Disabled || w.answered == v.Prompt
}
func (w *window) respond(v frontend.View, b frontend.Button) {
if w.off(v, b) {
return
}
w.answered = v.Prompt
w.s.Respond(v.Prompt, b.Action, w.checked)
}
// fit asks for the size the content needs, as measured in the last frame
// when it laid out the same view at the same size: the width of the
// buttons, and for status views the height of the text.
func (w *window) fit(c *ui.Context, v frontend.View, body, aside, buttons ui.Element) {
ww, wh := c.Size()
l := layout{v.Prompt, v.Title, v.Message, v.Detail, v.Bar, v.Checkbox, v.Release, ww, wh}
if l != w.built {
// Measure the layout of this frame in the next.
w.built = l
c.Invalidate()
return
}
b, a, f := body.Bounds(), aside.Bounds(), buttons.Bounds()
width := padSide + a.W + f.W + padSide
if a.W > 0 {
width += asideGap
}
height := padTop + b.H + footGap + max(a.H, f.H) + padBottom
if w.icon != nil {
height = max(height, padTop+iconSize+footGap+max(a.H, f.H)+padBottom)
}
size := [2]int{int(math.Ceil(float64(width))), int(math.Ceil(float64(height)))}
if size != w.fitted {
w.fitted = size
go w.s.Fit(size[0], size[1])
}
}
// theme returns the look of the update window, that of the page of
// package updater, over base.
func theme(base *ui.Theme) *ui.Theme {
t := *base
light, dark := frontend.Background()
if t.Dark {
t.Background = ui.Hex(dark)
t.Surface = ui.Hex("#5b5b5f")
t.Border = ui.RGBA(255, 255, 255, 0.15)
t.Text, t.TextMuted = ui.Hex("#f5f5f7"), ui.Hex("#98989d")
t.Accent = ui.Hex("#0a84ff")
} else {
t.Background = ui.Hex(light)
t.Surface = ui.Hex("#ffffff")
t.Border = ui.RGBA(0, 0, 0, 0.15)
t.Text, t.TextMuted = ui.Hex("#1d1d1f"), ui.Hex("#6e6e73")
t.Accent = ui.Hex("#007aff")
}
black := ui.RGB(0, 0, 0)
t.SurfaceHover, t.SurfacePressed = t.Surface.Mix(black, 0.05), t.Surface.Mix(black, 0.1)
t.AccentHover, t.AccentPressed = t.Accent.Mix(black, 0.08), t.Accent.Mix(black, 0.16)
t.Selection, t.Focus = t.Accent.Alpha(0.25), t.Accent.Alpha(0.55)
return &t
}
// panel returns the background of the release notes.
func panel(t *ui.Theme) ui.Color {
if t.Dark {
return ui.Hex("#141414")
}
return ui.Hex("#ffffff")
}
// track returns the background of code.
func track(t *ui.Theme) ui.Color {
if t.Dark {
return ui.RGBA(255, 255, 255, 0.12)
}
return ui.RGBA(0, 0, 0, 0.1)
}
+331
View File
@@ -0,0 +1,331 @@
package native
import (
"bytes"
"image"
"image/png"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/plugins/updater/internal/frontend"
"github.com/egoist/mygo/plugins/updater/internal/markdown"
"github.com/egoist/mygo/ui"
)
// session is a frontend.Session that records what the window does.
type session struct {
texts frontend.Texts
icon []byte
mu sync.Mutex
view frontend.View
changed chan struct{}
responses []response
fits chan [2]int
}
type response struct {
prompt int
action frontend.Action
automatic bool
}
func newSession(v frontend.View) *session {
return &session{
texts: frontend.Texts{
Title: "Software Update", ReleaseNotes: "Release Notes:",
AutomaticDownloads: "Automatically download and install updates in the future", Lang: "en",
},
view: v, changed: make(chan struct{}), fits: make(chan [2]int, 100),
}
}
func (s *session) NewWindow(mygo.Content) *mygo.Window { panic("no windows in tests") }
func (s *session) Done() <-chan struct{} { return nil }
func (s *session) Texts() frontend.Texts { return s.texts }
func (s *session) Icon() []byte { return s.icon }
func (s *session) User() bool { return true }
func (s *session) Fit(width, height int) { s.fits <- [2]int{width, height} }
func (s *session) Current() (frontend.View, <-chan struct{}) {
s.mu.Lock()
defer s.mu.Unlock()
return s.view, s.changed
}
func (s *session) set(v frontend.View) {
s.mu.Lock()
defer s.mu.Unlock()
s.view = v
close(s.changed)
s.changed = make(chan struct{})
}
func (s *session) Respond(prompt int, a frontend.Action, automatic bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.responses = append(s.responses, response{prompt, a, automatic})
}
func (s *session) answers() []response {
s.mu.Lock()
defer s.mu.Unlock()
return slices.Clone(s.responses)
}
// fit returns the last size the window asked for.
func (s *session) fit(t *testing.T) [2]int {
t.Helper()
var size [2]int
select {
case size = <-s.fits:
case <-time.After(wait.Guard):
t.Fatal("the window did not ask for a size")
}
for {
select {
case size = <-s.fits:
case <-time.After(50 * time.Millisecond):
return size
}
}
}
func available(prompt int, notes string) frontend.View {
return frontend.View{
Prompt: prompt,
Release: true,
Title: "A new version of App is available!",
Message: "App 2.0 is now available—you have 1.0. Would you like to install it now?",
Notes: markdown.Parse(notes),
Checkbox: true,
Buttons: []frontend.Button{
{Action: frontend.Skip, Label: "Skip This Version", Aside: true},
{Action: frontend.Later, Label: "Remind Me Later", Cancel: true},
{Action: frontend.Install, Label: "Install Update", Default: true},
},
}
}
func status(prompt int, title, message string) frontend.View {
return frontend.View{Prompt: prompt, Title: title, Message: message, Buttons: []frontend.Button{
{Action: frontend.OK, Label: "OK", Default: true, Cancel: true},
}}
}
func TestAvailable(t *testing.T) {
s := newSession(available(1, "### Fixed\n\n- [The editor](https://example.com/editor) lost a **bug**\n - nested\n\n```\ncode\n```"))
w := newWindow(s)
tt := ui.NewTester(w.view, frontend.ReleaseWidth, frontend.ReleaseHeight)
for _, want := range []string{"A new version of App is available!", "Release Notes:", "Fixed", "The editor lost a bug", "nested", "code", "•", "◦", s.texts.AutomaticDownloads} {
if !tt.HasText(want) {
t.Errorf("the window lacks %q: %q", want, tt.Texts())
}
}
// The link of the notes opens in the browser.
r, _ := tt.Find("The editor lost a bug")
tt.ClickAt(r.X+10, r.Y+r.H/2)
if got := tt.OpenedURLs(); !slices.Equal(got, []string{"https://example.com/editor"}) {
t.Errorf("opened %v", got)
}
// The keyboard reaches it, and Enter opens it rather than installing.
tt.Key(0, ui.KeyTab)
if !tt.Focused(s.texts.AutomaticDownloads) {
t.Fatal("Tab does not go from the link to the checkbox")
}
tt.Key(ui.Shift, ui.KeyTab)
if !tt.Focused("The editor") {
t.Fatal("Shift+Tab does not go back to the link of the notes")
}
tt.Key(0, ui.KeyEnter)
if got := tt.OpenedURLs(); len(got) != 2 || len(s.answers()) != 0 {
t.Fatalf("Enter on the link opened %v and answered %v", got, s.answers())
}
if err := tt.Click(s.texts.AutomaticDownloads); err != nil {
t.Fatal(err)
}
if err := tt.Click("Install Update"); err != nil {
t.Fatal(err)
}
// The answer disables the buttons until the next prompt.
tt.Click("Remind Me Later")
tt.Key(0, ui.KeyEscape)
if got := s.answers(); !slices.Equal(got, []response{{1, frontend.Install, true}}) {
t.Fatalf("responses %v", got)
}
// A new prompt resets the checkbox, and takes an answer again.
s.set(available(2, "Notes"))
tt.Frame()
tt.Key(0, ui.KeyEscape)
if got := s.answers(); !slices.Equal(got[1:], []response{{2, frontend.Later, false}}) {
t.Fatalf("responses %v", got)
}
}
func TestKeys(t *testing.T) {
s := newSession(available(1, ""))
tt := ui.NewTester(newWindow(s).view, frontend.StatusWidth, 200)
tt.Key(0, ui.KeyEnter)
if got := s.answers(); !slices.Equal(got, []response{{1, frontend.Install, false}}) {
t.Fatalf("Enter answered %v", got)
}
s.set(available(2, ""))
tt.Frame()
tt.Key(0, ui.KeyEscape)
if got := s.answers()[1:]; !slices.Equal(got, []response{{2, frontend.Later, false}}) {
t.Fatalf("Escape answered %v", got)
}
// Disabled buttons do not answer.
v := status(3, "Installing update…", "")
v.Buttons = []frontend.Button{{Action: frontend.Cancel, Label: "Cancel", Cancel: true, Disabled: true}}
s.set(v)
tt.Frame()
tt.Key(0, ui.KeyEscape)
tt.Click("Cancel")
if got := s.answers(); len(got) != 2 {
t.Fatalf("a disabled button answered %v", got[2:])
}
}
func TestProgress(t *testing.T) {
s := newSession(frontend.View{
Prompt: 1, Title: "Downloading update…", Message: "5.0 MB of 20.0 MB", Bar: true, Progress: 0.25,
Buttons: []frontend.Button{{Action: frontend.Cancel, Label: "Cancel", Cancel: true}},
})
tt := ui.NewTester(newWindow(s).view, frontend.StatusWidth, frontend.StatusHeight)
if !tt.HasText("5.0 MB of 20.0 MB") {
t.Errorf("texts %q", tt.Texts())
}
if err := tt.Click("Cancel"); err != nil {
t.Fatal(err)
}
if got := s.answers(); !slices.Equal(got, []response{{1, frontend.Cancel, false}}) {
t.Fatalf("responses %v", got)
}
}
func TestFit(t *testing.T) {
s := newSession(status(1, "You’re up to date!", "App 1.0 is currently the newest version available."))
tt := ui.NewTester(newWindow(s).view, frontend.StatusWidth, frontend.StatusHeight)
short := s.fit(t)
if short[0] > frontend.StatusWidth || short[1] < 60 || short[1] > frontend.StatusHeight+40 {
t.Errorf("a short status asks for %v", short)
}
// A longer text asks for more height, at the window's width.
v := status(2, "Update Error!", "An error occurred while checking for updates. Please try again later.")
v.Detail = strings.Repeat("dial tcp: lookup updates.example.com: no such host ", 4)
s.set(v)
tt.Frame()
long := s.fit(t)
if long[1] <= short[1] {
t.Errorf("an error asks for %v, a short status for %v", long, short)
}
// The session widens the window to the usual width at least.
tt.SetSize(max(long[0], frontend.StatusWidth), long[1])
select {
case got := <-s.fits:
t.Errorf("the window asks for %v once it has the size it asked for, %v", got, long)
case <-time.After(100 * time.Millisecond):
}
// Long labels widen the window.
v = available(3, "Notes")
for i := range v.Buttons {
v.Buttons[i].Label = strings.Repeat(v.Buttons[i].Label+" ", 3)
}
s.set(v)
tt.SetSize(frontend.ReleaseWidth, frontend.ReleaseHeight)
if wide := s.fit(t); wide[0] <= frontend.ReleaseWidth {
t.Errorf("long labels ask for %v", wide)
}
}
// A long error shows in full, in a window that grows to fit it, and no
// tooltip covers the title.
func TestLongDetail(t *testing.T) {
var icon bytes.Buffer
png.Encode(&icon, image.NewRGBA(image.Rect(0, 0, 128, 128)))
v := status(1, "Update Error!", "An error occurred while checking for updates. Please try again later.")
v.Detail = "i/o timeout"
s := newSession(v)
s.icon = icon.Bytes()
tt := ui.NewTester(newWindow(s).view, frontend.StatusWidth, frontend.StatusHeight)
line, _ := tt.Find(v.Detail)
// Three lines at the window's width.
v.Detail = `mygo: checking for updates: Get "https://example.com/releases/latest/download/update-darwin-arm64.json": dial tcp 20.205.243.166:443: i/o timeout`
s.set(v)
tt.Frame()
size := s.fit(t)
tt.SetSize(max(size[0], frontend.StatusWidth), size[1])
r, ok := tt.Find(v.Detail)
if !ok || r.H < 2.5*line.H {
t.Fatalf("the detail takes %v, a line of it %v", r, line)
}
if r.Y+r.H > float32(size[1]) {
t.Errorf("the detail ends at %v in a window %v high", r.Y+r.H, size[1])
}
tt.Move(r.X+r.W/2, r.Y+r.H/2)
tt.Advance(2 * time.Second)
tt.Frame()
if n := len(slices.DeleteFunc(tt.Texts(), func(s string) bool { return s != v.Detail })); n != 1 {
t.Errorf("hovering the detail shows it %d times: %q", n, tt.Texts())
}
}
func TestLayout(t *testing.T) {
var icon bytes.Buffer
png.Encode(&icon, image.NewRGBA(image.Rect(0, 0, 128, 128)))
for _, rtl := range []bool{false, true} {
s := newSession(available(1, "- An English item"))
s.icon, s.texts.RTL = icon.Bytes(), rtl
tt := ui.NewTester(newWindow(s).view, frontend.ReleaseWidth, frontend.ReleaseHeight)
find := func(text string) ui.Rect {
t.Helper()
r, ok := tt.Find(text)
if !ok {
t.Fatalf("no %q", text)
}
return r
}
// The title, stretched across the column of texts, which the
// icon leaves.
body := find("A new version of App is available!")
skip, later, install := find("Skip This Version"), find("Remind Me Later"), find("Install Update")
// The checkbox's box sits between its label and the edge of the
// texts' column where they start.
label := find(s.texts.AutomaticDownloads)
left, right := label.X-body.X, body.X+body.W-(label.X+label.W)
bullet, item := find("•"), find("An English item")
if !rtl {
if body.X < padSide+iconSize+iconGap || skip.X > later.X || later.X > install.X {
t.Errorf("left to right: texts at %v, Skip at %v, Later at %v, Install at %v", body, skip, later, install)
}
if left < 4 || left > right {
t.Errorf("left to right: the checkbox's label at %v in %v", label, body)
}
} else {
if body.X+body.W > frontend.ReleaseWidth-padSide-iconSize-iconGap+1 || skip.X < later.X || later.X < install.X {
t.Errorf("right to left: texts at %v, Skip at %v, Later at %v, Install at %v", body, skip, later, install)
}
if right < 4 || right > left {
t.Errorf("right to left: the checkbox's label at %v in %v", label, body)
}
}
// Notes take the direction of their language, not the window's.
if bullet.X > item.X {
t.Errorf("rtl %v: the bullet of English notes at %v, the item at %v", rtl, bullet, item)
}
s.set(available(2, "- פריט בעברית"))
tt.Frame()
if bullet, item := find("•"), find("פריט בעברית"); bullet.X < item.X {
t.Errorf("rtl %v: the bullet of Hebrew notes at %v, the item at %v", rtl, bullet, item)
}
}
}
+244
View File
@@ -0,0 +1,244 @@
<!doctype html>
<html lang="{{lang}}" dir="{{dir}}">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'nonce-{{nonce}}'">
<title>{{title}}</title>
<style>
:root {
color-scheme: light dark;
--bg: {{background}};
--fg: #1d1d1f;
--muted: #6e6e73;
--panel: #fff;
--border: rgb(0 0 0 / 0.15);
--button: #fff;
--button-fg: #1d1d1f;
--accent: #007aff;
--track: rgb(0 0 0 / 0.1);
}
@media (prefers-color-scheme: dark) {
:root {
--bg: {{darkBackground}};
--fg: #f5f5f7;
--muted: #98989d;
--panel: #141414;
--border: rgb(255 255 255 / 0.15);
--button: #5b5b5f;
--button-fg: #f5f5f7;
--accent: #0a84ff;
--track: rgb(255 255 255 / 0.12);
}
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body {
background: var(--bg);
color: var(--fg);
font: 13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI Variable Text", "Segoe UI", Cantarell, Ubuntu, system-ui, sans-serif;
-webkit-user-select: none;
user-select: none;
cursor: default;
overflow: hidden;
}
main {
height: 100%;
display: grid;
grid-template: "icon body" 1fr "foot foot" auto / 64px 1fr;
gap: 12px 18px;
padding: 18px 20px 20px;
}
main.noicon { grid-template-columns: 0 1fr; column-gap: 0; }
#icon { grid-area: icon; width: 64px; height: 64px; }
main.noicon #icon { display: none; }
#body { grid-area: body; display: flex; flex-direction: column; min-height: 0; }
main:not(.release) #body { align-self: start; }
h1 { font-size: 13px; font-weight: 700; margin: 0 0 4px; }
/* Texts that may fall back to English, and errors, take the direction of
their own words; release notes are in the language of the changelog. */
h1, p, label { unicode-bidi: plaintext; }
p { margin: 0; }
#message { margin-bottom: 6px; }
#detail {
color: var(--muted);
font-size: 11px;
overflow-wrap: anywhere;
-webkit-user-select: text;
user-select: text;
cursor: text;
}
#bar { height: 6px; border-radius: 3px; background: var(--track); overflow: hidden; margin: 6px 0 4px; }
#fill { height: 100%; width: 0; border-radius: 3px; background: var(--accent); transition: width 0.1s linear; }
#bar.indeterminate #fill { width: 30%; transition: none; animation: slide 1.4s ease-in-out infinite; }
@keyframes slide { from { transform: translateX(-100%); } to { transform: translateX(333%); } }
#notes-box { flex: 1; display: flex; flex-direction: column; min-height: 0; margin-top: 6px; }
h2 { font-size: 11px; font-weight: 700; margin: 0 0 4px; }
#notes {
flex: 1;
overflow: auto;
background: var(--panel);
border: 1px solid var(--border);
padding: 8px 12px;
-webkit-user-select: text;
user-select: text;
cursor: auto;
}
#notes > :first-child { margin-top: 0; }
#notes > :last-child { margin-bottom: 0; }
#notes h1, #notes h2, #notes h3, #notes h4, #notes h5, #notes h6 { font-size: 13px; font-weight: 700; margin: 12px 0 4px; }
#notes h1 { font-size: 16px; }
#notes h2 { font-size: 14px; }
#notes p, #notes ul, #notes ol, #notes pre, #notes blockquote { margin: 0 0 8px; }
#notes ul, #notes ol { padding-inline-start: 20px; }
#notes li > ul, #notes li > ol { margin: 0; }
#notes code { font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; background: var(--track); border-radius: 3px; padding: 0 3px; }
#notes pre { overflow: auto; }
#notes pre code { display: block; padding: 6px 8px; }
#notes blockquote { border-inline-start: 3px solid var(--border); padding-inline-start: 10px; color: var(--muted); margin-inline-start: 0; }
#notes hr { border: 0; border-top: 1px solid var(--border); }
#notes a { color: var(--accent); cursor: pointer; }
label { display: flex; align-items: center; gap: 6px; margin-top: 10px; }
input { margin: 0; accent-color: var(--accent); }
footer { grid-area: foot; display: flex; gap: 10px; align-items: center; }
footer div { display: flex; flex: none; gap: 10px; }
footer .spacer { flex: 1; }
button {
font: inherit;
white-space: nowrap;
min-width: 84px;
height: 24px;
padding: 0 14px;
border-radius: 6px;
border: 1px solid var(--border);
background: var(--button);
color: var(--button-fg);
box-shadow: 0 1px 1px rgb(0 0 0 / 0.08);
}
button.default { background: var(--accent); border-color: transparent; color: #fff; }
button:active:not(:disabled) { filter: brightness(0.9); }
button:disabled { opacity: 0.5; }
button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
[hidden] { display: none !important; }
</style>
</head>
<body>
<main id="main">
<img id="icon" src="{{icon}}" alt="">
<section id="body">
<h1 id="title"></h1>
<p id="message"></p>
<div id="bar" role="progressbar"><div id="fill"></div></div>
<p id="detail"></p>
<div id="notes-box">
<h2>{{releaseNotes}}</h2>
<div id="notes" dir="auto"></div>
</div>
<label id="auto-box"><input type="checkbox" id="auto"> {{automaticDownloads}}</label>
</section>
<footer id="foot"><div id="aside"></div><span class="spacer"></span><div id="buttons"></div></footer>
</main>
<script nonce="{{nonce}}">
const $ = (id) => document.getElementById(id);
if (!$("icon").getAttribute("src")) $("main").classList.add("noicon");
let view = null;
let notes = null;
const text = (el, s) => {
el.textContent = s || "";
el.hidden = !s;
};
function render(v) {
const prompt = !view || view.prompt !== v.prompt;
view = v;
$("main").classList.toggle("release", !!v.release);
$("title").textContent = v.title;
text($("message"), v.message);
text($("detail"), v.detail);
$("bar").hidden = !v.bar;
const known = v.progress >= 0;
$("bar").classList.toggle("indeterminate", !known);
$("fill").style.width = known ? v.progress * 100 + "%" : "";
if (known) $("bar").setAttribute("aria-valuenow", Math.round(v.progress * 100));
else $("bar").removeAttribute("aria-valuenow");
$("notes-box").hidden = !v.notes;
if (v.notes !== notes) {
notes = v.notes;
$("notes").innerHTML = notes || ""; // rendered and escaped by Go
}
$("auto-box").hidden = !v.checkbox;
if (prompt) {
$("auto").checked = !!v.checked;
renderButtons(v.buttons);
}
fit();
}
// The window takes the width of the buttons, and status views the height
// of their text, which depend on the language and the platform's fonts.
let fitted = "";
function fit() {
const main = getComputedStyle($("main"));
const aside = $("aside").offsetWidth;
const width = Math.ceil(
parseFloat(main.paddingLeft) + aside + (aside ? 40 : 0) + $("buttons").offsetWidth +
parseFloat(main.paddingRight),
);
const height = Math.ceil(
parseFloat(main.paddingTop) + Math.max($("icon").offsetHeight, $("body").offsetHeight) +
parseFloat(main.rowGap) + $("foot").offsetHeight + parseFloat(main.paddingBottom),
);
const key = [view.release, width, view.release ? 0 : height].join();
if (key !== fitted) {
fitted = key;
mygo.call("plugin:updater.Fit", width, height).catch(() => {});
}
}
addEventListener("resize", () => view && fit());
function renderButtons(buttons) {
$("aside").replaceChildren();
$("buttons").replaceChildren();
for (const b of buttons) {
const el = document.createElement("button");
el.textContent = b.label;
el.disabled = !!b.disabled;
if (b.default) el.className = "default";
el.addEventListener("click", () => respond(b.action));
$(b.aside ? "aside" : "buttons").append(el);
}
}
// Only the first response to a prompt counts: the buttons wait for the
// next view.
let answered = null;
function respond(action) {
if (answered === view.prompt) return;
answered = view.prompt;
for (const el of document.querySelectorAll("footer button")) el.disabled = true;
mygo.call("plugin:updater.Respond", view.prompt, action, $("auto").checked).catch(() => {});
}
addEventListener("keydown", (e) => {
if (!view || e.isComposing) return;
const pick = (want) => {
const b = view.buttons.find((b) => want(b) && !b.disabled);
if (b) {
e.preventDefault();
respond(b.action);
}
};
if (e.key === "Escape") pick((b) => b.cancel);
else if (e.key === "Enter" && !(document.activeElement instanceof HTMLButtonElement)) pick((b) => b.default);
});
addEventListener("contextmenu", (e) => {
if (!e.target.closest("#notes, #detail")) e.preventDefault();
});
render({{view}});
mygo.call("plugin:updater.Watch", mygo.channel(render)).catch(() => {});
</script>
</body>
</html>
+390
View File
@@ -0,0 +1,390 @@
package updater
import (
"context"
"fmt"
"os"
"path/filepath"
"slices"
"sync"
"github.com/egoist/mygo"
"github.com/egoist/mygo/plugins/updater/internal/frontend"
"github.com/egoist/mygo/plugins/updater/internal/markdown"
)
// session is a check for updates and what follows it: the update window,
// the download, the offer to relaunch. The window shows the session's
// current view, which the session keeps up to date even while the window
// is not shown, so that it can show at any point. It is the
// frontend.Session of the window, which the updater's open function
// creates.
type session struct {
u *updater
// t are the texts of the window, in the language the app showed when
// the check began: a window keeps its language while it is open.
t *text
// ctx is canceled when the session ends, the user cancels or the
// window closes.
ctx context.Context
cancel context.CancelFunc
responses chan response
// rechecks asks the session to check again while it offers an
// update (offering).
rechecks chan struct{}
// showMu is held while the window is being created.
showMu sync.Mutex
mu sync.Mutex
// user is set when the user asked for the check: the window shows
// from the start and reports that the app is up to date.
user bool
shown bool
ended bool
view view
changed chan struct{} // closed when the view changes
win *mygo.Window
release bool // the window has the size of a release view
// offering is set while the window offers an update and waits for the
// user's answer.
offering bool
}
func newSession(u *updater, t *text, user bool) *session {
ctx, cancel := context.WithCancel(context.Background())
return &session{
u: u, t: t, user: user, ctx: ctx, cancel: cancel,
responses: make(chan response, 1),
rechecks: make(chan struct{}, 1),
changed: make(chan struct{}),
}
}
// User reports whether the user asked for the check.
func (s *session) User() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.user
}
func (s *session) isShown() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.shown
}
// Current returns the view and a channel closed when it changes.
func (s *session) Current() (view, <-chan struct{}) {
s.mu.Lock()
defer s.mu.Unlock()
return s.view, s.changed
}
// Done is closed when the session ends or its window closes.
func (s *session) Done() <-chan struct{} { return s.ctx.Done() }
// set changes the view, and the window's size when the view needs another.
func (s *session) set(v view) {
s.mu.Lock()
v.Prompt = s.view.Prompt
if !slices.Equal(v.Buttons, s.view.Buttons) {
v.Prompt++
}
s.view = v
close(s.changed)
s.changed = make(chan struct{})
win := s.win
resize := win != nil && s.release != v.Release
if resize {
s.release = v.Release
}
s.mu.Unlock()
if resize {
fit(win, v.Release)
}
}
// NewWindow creates the window of the session, hidden, showing content or,
// when it is nil, a web page.
func (s *session) NewWindow(content mygo.Content) *mygo.Window {
v, _ := s.Current()
width, height := frontend.Size(v.Release)
light, dark := frontend.Background()
win := mygo.NewWindow(mygo.WindowOptions{
Title: s.t.Title,
Width: width,
Height: height,
UseContentSize: true,
Hidden: true,
DisableResize: true,
DisableMaximize: true,
DisableFullScreen: true,
BackgroundColor: "light-dark(" + light + ", " + dark + ")",
Content: content,
})
// A menu of its own, empty, rather than the app's menu bar (Linux,
// Windows).
win.SetMenu(mygo.NewMenu(nil))
s.mu.Lock()
s.win = win
s.release = s.view.Release // the view may have changed since
resize := s.release != v.Release
release := s.release
s.mu.Unlock()
if resize {
fit(win, release)
}
win.OnClosed(s.cancel)
return win
}
// fit gives the window the size of a status or release view.
func fit(win *mygo.Window, release bool) {
win.SetContentSize(frontend.Size(release))
win.Center()
}
// Fit gives the window the width its buttons need, when they need more
// than the usual width, and a status view the height of its content.
func (s *session) Fit(width, height int) {
s.mu.Lock()
win, release := s.win, s.release
s.mu.Unlock()
if win == nil {
return
}
w, h := frontend.Size(release)
w = max(w, min(width, 1000))
if !release {
h = min(max(height, 80), 600)
}
win.SetContentSize(w, h)
}
// Texts returns the texts of the window around its views.
func (s *session) Texts() frontend.Texts { return s.t.texts() }
// Icon returns the icon of the window, or nil.
func (s *session) Icon() []byte { return s.u.icon() }
// icon returns the PNG image of the update window: Options.Icon, else
// icon.png among the app's resources, or nil.
func (u *updater) icon() []byte {
if u.opts.Icon != nil {
return u.opts.Icon
}
dir, err := resourcesDir()
if err != nil {
return nil
}
png, err := os.ReadFile(filepath.Join(dir, "icon.png"))
if err != nil {
return nil
}
return png
}
// show shows the window, bringing it to the front when the user asked for
// the check.
func (s *session) show() {
s.showMu.Lock()
defer s.showMu.Unlock()
s.mu.Lock()
win, user, ended, shown := s.win, s.user, s.ended, s.shown
s.shown = shown || !ended
s.mu.Unlock()
switch {
case ended:
case !shown:
s.u.open(s)
case user && win != nil:
win.Show()
win.Focus()
}
}
// promote makes a check running in the background one the user asked for.
func (s *session) promote() {
s.mu.Lock()
s.user = true
s.mu.Unlock()
s.show()
}
// recheck asks the session to check again and then bring its window to
// the front, when the window offers an update. It reports whether it does.
func (s *session) recheck() bool {
s.mu.Lock()
defer s.mu.Unlock()
if !s.offering {
return false
}
select {
case s.rechecks <- struct{}{}:
default: // already asked
}
return true
}
// setOffering sets whether the window offers an update. When the offer
// ends with a re-check still asked for, the window comes to the front, as
// the user asked, unless it closed.
func (s *session) setOffering(on bool) {
s.mu.Lock()
s.offering = on
s.mu.Unlock()
if on {
return
}
select {
case <-s.rechecks:
if s.ctx.Err() == nil {
s.promote()
}
default:
}
}
// wait waits for the user to respond to the view, or the window to close.
func (s *session) wait() response {
select {
case r := <-s.responses:
return r
case <-s.ctx.Done():
return response{action: actionClose}
}
}
// Respond takes the user's response to the prompt of a view. Only one
// response to a prompt counts, and only with one of its buttons.
func (s *session) Respond(prompt int, a action, automaticDownloads bool) {
s.mu.Lock()
ok := prompt == s.view.Prompt && slices.ContainsFunc(s.view.Buttons, func(b button) bool {
return b.Action == a && !b.Disabled
})
if ok {
s.view.Prompt++
}
s.mu.Unlock()
switch {
case !ok:
case a == actionCancel:
s.cancel()
default:
select {
case s.responses <- response{a, automaticDownloads}:
default: // the session ended
}
}
}
// close ends the session and closes its window.
func (s *session) close() {
s.cancel()
s.showMu.Lock()
s.mu.Lock()
s.ended = true
win := s.win
s.mu.Unlock()
s.showMu.Unlock()
if win != nil {
win.Close()
}
}
// The views of the update window and their buttons, as frontend has them.
type (
view = frontend.View
button = frontend.Button
action = frontend.Action
)
const (
actionOK = frontend.OK
actionCancel = frontend.Cancel
actionSkip = frontend.Skip
actionLater = frontend.Later
actionInstall = frontend.Install
actionRelaunch = frontend.Relaunch
actionClose = frontend.Close
)
type response struct {
action action
automaticDownloads bool
}
func (t *text) ok() []button {
return []button{{Action: actionOK, Label: t.OK, Default: true, Cancel: true}}
}
func (t *text) cancel(disabled bool) []button {
return []button{{Action: actionCancel, Label: t.Cancel, Cancel: true, Disabled: disabled}}
}
func (t *text) checkingView() view {
return view{Title: t.Checking, Bar: true, Progress: -1, Buttons: t.cancel(false)}
}
func (t *text) upToDateView() view {
return view{
Title: t.UpToDate,
Message: fmt.Sprintf(t.UpToDateMessage, mygo.App.Name(), appVersion()),
Buttons: t.ok(),
}
}
func (t *text) unavailableView() view {
msg := fmt.Sprintf(t.UnavailableMessage, mygo.App.Name())
if mygo.IsDev() {
msg = t.DevelopmentBuild
}
return view{Title: t.Unavailable, Message: msg, Buttons: t.ok()}
}
func (t *text) errorView(msg string, err error) view {
return view{Title: t.Error, Message: msg, Detail: err.Error(), Buttons: t.ok()}
}
func (t *text) availableView(r *release, automaticDownloads bool) view {
name := mygo.App.Name()
notes := markdown.Parse(r.notes)
return view{
Release: len(notes) > 0,
Title: fmt.Sprintf(t.Available, name),
Message: fmt.Sprintf(t.AvailableMessage, name, r.version, appVersion()),
Notes: notes,
Checkbox: true,
Checked: automaticDownloads,
Buttons: []button{
{Action: actionSkip, Label: t.Skip, Aside: true},
{Action: actionLater, Label: t.RemindLater, Cancel: true},
{Action: actionInstall, Label: t.Install, Default: true},
},
}
}
func (t *text) downloadingView(downloaded, total int64) view {
v := view{Title: t.Downloading, Bar: true, Progress: -1, Buttons: t.cancel(false)}
if total > 0 {
v.Progress = float64(downloaded) / float64(total)
v.Message = fmt.Sprintf(t.Progress, t.megabytes(downloaded), t.megabytes(total))
}
return v
}
func (t *text) installingView() view {
return view{Title: t.Installing, Bar: true, Progress: -1, Buttons: t.cancel(true)}
}
func (t *text) readyView(r *release) view {
return view{
Title: t.Ready,
Message: fmt.Sprintf(t.ReadyMessage, mygo.App.Name(), r.version),
Buttons: []button{
{Action: actionLater, Label: t.Later, Cancel: true},
{Action: actionRelaunch, Label: t.Relaunch, Default: true},
},
}
}
+244
View File
@@ -0,0 +1,244 @@
package updater
import (
"errors"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"github.com/egoist/mygo/plugins/updater/internal/frontend"
)
// Strings are the texts of the update window in one language. The plugin
// has them in English, Chinese (zh-Hans, zh-Hant), Dutch, French, German,
// Italian, Japanese, Korean, Polish, Portuguese (pt-BR), Russian, Spanish,
// Turkish and Ukrainian, and Options.Strings changes them or adds
// languages.
//
// Some are formats, whose arguments are listed: indexed verbs such as
// %[2]s let a language order them as it needs.
type Strings struct {
// Title of the window: "Software Update".
Title string
// MenuItem is the label of MenuItem: "Check for Updates…".
MenuItem string
Checking string // "Checking for updates…"
Cancel string
OK string
UpToDate string // "You’re up to date!"
// UpToDateMessage: the app's name and version.
UpToDateMessage string
Unavailable string // "Updates Unavailable"
// UnavailableMessage explains that the app cannot write where it is
// installed: the app's name.
UnavailableMessage string
// DevelopmentBuild explains that development builds do not update.
DevelopmentBuild string
Error string // "Update Error!"
CheckError string // "An error occurred while checking for updates…"
InstallError string // "An error occurred while installing the update…"
// Available: the app's name.
Available string
// AvailableMessage: the app's name, the new version and the running
// one.
AvailableMessage string
ReleaseNotes string // "Release Notes:"
AutomaticDownloads string // the checkbox
Skip string // "Skip This Version"
RemindLater string // "Remind Me Later"
Install string // "Install Update"
Downloading string // "Downloading update…"
// Progress: the size downloaded and the whole size, as Megabytes.
Progress string
// Megabytes: a number, such as 12.3, with the decimal mark of the
// language.
Megabytes string
Installing string // "Installing update…"
Ready string // "Ready to Relaunch"
// ReadyMessage: the app's name and the new version.
ReadyMessage string
Later string
Relaunch string // "Relaunch Now"
}
// formats lists the Strings that are formats, with the number of their
// arguments.
var formats = map[string]int{
"UpToDateMessage": 2,
"UnavailableMessage": 1,
"Available": 1,
"AvailableMessage": 3,
"Progress": 2,
"Megabytes": 1,
"ReadyMessage": 2,
}
// check reports the first format of s, among those that are set, that fmt
// cannot fill with its arguments.
func (s *Strings) check() error {
v := reflect.ValueOf(s).Elem()
for i := range v.NumField() {
name, text := v.Type().Field(i).Name, v.Field(i).String()
n, ok := formats[name]
if text == "" || !ok {
continue
}
args := make([]any, n)
for j := range args {
args[j] = "\x00" + strconv.Itoa(j)
}
if out := fmt.Sprintf(text, args...); strings.Contains(out, "%!") {
return fmt.Errorf("%s %q is not a format of %d strings", name, text, n)
}
}
return nil
}
// merge fills the empty fields of s from fallback.
func (s *Strings) merge(fallback *Strings) {
v, f := reflect.ValueOf(s).Elem(), reflect.ValueOf(fallback).Elem()
for i := range v.NumField() {
if v.Field(i).String() == "" {
v.Field(i).Set(f.Field(i))
}
}
}
// text is the language the window shows, resolved once.
type text struct {
Strings
// lang is the language, such as "zh-Hans".
lang string
// comma is set for languages whose decimal mark is a comma, rtl for
// those written from right to left.
comma, rtl bool
}
// texts returns the texts of the window around its views.
func (t *text) texts() frontend.Texts {
return frontend.Texts{
Title: t.Title,
ReleaseNotes: t.ReleaseNotes,
AutomaticDownloads: t.AutomaticDownloads,
Lang: t.lang,
RTL: t.rtl,
}
}
// newText returns the strings of the language the plugin has, or the app
// gives, that best matches locale, completed with the plugin's own and
// English.
func newText(locale string, extra map[string]Strings) *text {
var available []string
for l := range translations {
available = append(available, l)
}
for l := range extra {
available = append(available, l)
}
slices.Sort(available)
lang := matchLanguage(locale, available)
t := &text{lang: lang, comma: decimalComma[lang], rtl: rightToLeft[baseLanguage(lang)]}
for l, s := range extra {
if strings.EqualFold(l, lang) {
t.Strings = s
}
}
if s, ok := translations[lang]; ok {
t.Strings.merge(&s)
}
t.Strings.merge(&english)
return t
}
// checkStrings reports translations of the app that are not valid.
func checkStrings(extra map[string]Strings) error {
var errs []error
for l, s := range extra {
if err := s.check(); err != nil {
errs = append(errs, fmt.Errorf("strings of %q: %w", l, err))
}
}
return errors.Join(errs...)
}
// matchLanguage returns the language among available, which are language
// tags such as "de" or "zh-Hant", that best matches locale, a language tag
// or a POSIX locale such as "zh_TW.UTF-8": the same language, script and
// region, else the same language and script, else the same language. It
// returns "en" without a match.
func matchLanguage(locale string, available []string) string {
locale, _, _ = strings.Cut(locale, ".") // zh_TW.UTF-8
locale, _, _ = strings.Cut(locale, "@") // sr_RS@latin
parts := strings.FieldsFunc(locale, func(r rune) bool { return r == '-' || r == '_' })
if len(parts) == 0 {
return "en"
}
lang := strings.ToLower(parts[0])
var script, region string
for _, p := range parts[1:] {
switch {
case len(p) == 4:
script = strings.ToUpper(p[:1]) + strings.ToLower(p[1:])
case len(p) == 2 || len(p) == 3 && p[0] >= '0' && p[0] <= '9':
region = strings.ToUpper(p)
}
}
if lang == "zh" && script == "" {
script = "Hans"
switch region {
case "TW", "HK", "MO":
script = "Hant"
}
}
var candidates []string
if script != "" {
candidates = append(candidates, lang+"-"+script+"-"+region, lang+"-"+script)
}
candidates = append(candidates, lang+"-"+region, lang)
for _, c := range candidates {
for _, a := range available {
if strings.EqualFold(a, c) {
return a
}
}
}
// Another variant of the language: pt-PT gets pt-BR. Chinese scripts
// are not variants of each other.
if lang != "zh" {
for _, a := range available {
if baseLanguage(a) == lang {
return a
}
}
}
return "en"
}
func baseLanguage(tag string) string {
l, _, _ := strings.Cut(tag, "-")
return strings.ToLower(l)
}
// rightToLeft lists the languages written from right to left, for which
// the window is laid out from the right. The plugin has none of them, but
// apps may add them.
var rightToLeft = map[string]bool{"ar": true, "fa": true, "he": true, "ps": true, "ur": true, "yi": true}
// megabytes formats a size in decimal megabytes, as Finder does.
func (t *text) megabytes(n int64) string {
s := strconv.FormatFloat(float64(n)/1e6, 'f', 1, 64)
if t.comma {
s = strings.Replace(s, ".", ",", 1)
}
return fmt.Sprintf(t.Megabytes, s)
}
+119
View File
@@ -0,0 +1,119 @@
package updater
import (
"fmt"
"reflect"
"strconv"
"strings"
"testing"
)
func TestMatchLanguage(t *testing.T) {
available := []string{"de", "en", "pt-BR", "sv", "zh-Hans", "zh-Hant"}
for locale, want := range map[string]string{
"de-DE": "de",
"de_AT.UTF-8": "de",
"en-GB": "en",
"pt-BR": "pt-BR",
"pt-PT": "pt-BR",
"zh-Hans-CN": "zh-Hans",
"zh-CN": "zh-Hans",
"zh_SG": "zh-Hans",
"zh": "zh-Hans",
"zh-Hant-HK": "zh-Hant",
"zh-TW": "zh-Hant",
"zh_HK.UTF-8": "zh-Hant",
"zh-MO": "zh-Hant",
"SV_se": "sv",
"es-419": "en",
"sr-Latn-RS": "en",
"": "en",
"C": "en",
} {
if got := matchLanguage(locale, available); got != want {
t.Errorf("matchLanguage(%q) = %q, want %q", locale, got, want)
}
}
if got := matchLanguage("zh-TW", []string{"en", "zh-Hans"}); got != "en" {
t.Errorf("zh-TW got %q: one script of Chinese is no fallback for the other", got)
}
}
// The plugin's translations have every text, and their formats use every
// argument.
func TestTranslations(t *testing.T) {
all := map[string]Strings{"en": english}
for l, s := range translations {
all[l] = s
}
for lang, s := range all {
if err := s.check(); err != nil {
t.Errorf("%s: %v", lang, err)
}
v := reflect.ValueOf(s)
for i := range v.NumField() {
name, text := v.Type().Field(i).Name, v.Field(i).String()
n, format := formats[name]
switch {
case text == "":
t.Errorf("%s: no %s", lang, name)
case !format && strings.Contains(text, "%"):
t.Errorf("%s: %s is not a format: %q", lang, name, text)
case format:
args := make([]any, n)
for j := range args {
args[j] = "<" + strconv.Itoa(j) + ">"
}
out := fmt.Sprintf(text, args...)
for _, a := range args {
if !strings.Contains(out, a.(string)) {
t.Errorf("%s: %s %q leaves out argument %s", lang, name, text, a)
}
}
}
}
}
}
func TestText(t *testing.T) {
de := newText("de-AT", nil)
if de.lang != "de" || de.Install != "Update installieren" || de.megabytes(12_345_678) != "12,3 MB" {
t.Errorf("de: %q, %q, %q", de.lang, de.Install, de.megabytes(12_345_678))
}
if fr := newText("fr-CA", nil); fr.megabytes(1_500_000) != "1,5 Mo" {
t.Errorf("fr: %q", fr.megabytes(1_500_000))
}
if ja := newText("ja-JP", nil); ja.megabytes(1_500_000) != "1.5 MB" {
t.Errorf("ja: %q", ja.megabytes(1_500_000))
}
extra := map[string]Strings{
"EN": {Install: "Update Now"},
"ar": {Title: "تحديث البرامج"},
"sv": {Install: "Installera uppdatering"},
}
en := newText("en-US", extra)
if en.Install != "Update Now" || en.Skip != "Skip This Version" {
t.Errorf("en: %q, %q", en.Install, en.Skip)
}
sv := newText("sv-SE", extra)
if sv.lang != "sv" || sv.Install != "Installera uppdatering" || sv.Skip != "Skip This Version" {
t.Errorf("sv: %q, %q, %q", sv.lang, sv.Install, sv.Skip)
}
if ar := newText("ar-EG", extra); !ar.rtl || ar.Title != "تحديث البرامج" {
t.Errorf("ar: rtl %v, %q", ar.rtl, ar.Title)
}
if de := newText("de", extra); de.Install != "Update installieren" {
t.Errorf("another language's strings leaked into de: %q", de.Install)
}
}
func TestInvalidStrings(t *testing.T) {
p := New(Options{Strings: map[string]Strings{"en": {Available: "A new version of %d"}}})
if err := p.Setup(); err == nil || !strings.Contains(err.Error(), "Available") {
t.Errorf("Setup: %v", err)
}
if active.Load() != nil {
t.Error("an invalid plugin became the active one")
}
}
+463
View File
@@ -0,0 +1,463 @@
package updater
var english = Strings{
Title: "Software Update",
MenuItem: "Check for Updates…",
Checking: "Checking for updates…",
Cancel: "Cancel",
OK: "OK",
UpToDate: "You’re up to date!",
UpToDateMessage: "%[1]s %[2]s is currently the newest version available.",
Unavailable: "Updates Unavailable",
UnavailableMessage: "%[1]s cannot update itself where it is installed. If a package manager installed it, update it there.",
DevelopmentBuild: "Development builds do not update themselves.",
Error: "Update Error!",
CheckError: "An error occurred while checking for updates. Please try again later.",
InstallError: "An error occurred while installing the update. Please try again later.",
Available: "A new version of %[1]s is available!",
AvailableMessage: "%[1]s %[2]s is now available—you have %[3]s. Would you like to install it now?",
ReleaseNotes: "Release Notes:",
AutomaticDownloads: "Automatically download and install updates in the future",
Skip: "Skip This Version",
RemindLater: "Remind Me Later",
Install: "Install Update",
Downloading: "Downloading update…",
Progress: "%[1]s of %[2]s",
Megabytes: "%s MB",
Installing: "Installing update…",
Ready: "Ready to Relaunch",
ReadyMessage: "%[1]s %[2]s is installed and starts the next time you open %[1]s. Relaunch now to start using it.",
Later: "Later",
Relaunch: "Relaunch Now",
}
// decimalComma lists the translations whose decimal mark is a comma.
var decimalComma = map[string]bool{
"de": true, "es": true, "fr": true, "it": true, "nl": true, "pl": true,
"pt-BR": true, "ru": true, "tr": true, "uk": true,
}
// translations are the languages of the plugin besides English, by
// language tag.
var translations = map[string]Strings{
"de": {
Title: "Softwareaktualisierung",
MenuItem: "Nach Updates suchen …",
Checking: "Suche nach Updates …",
Cancel: "Abbrechen",
OK: "OK",
UpToDate: "Sie sind auf dem neuesten Stand!",
UpToDateMessage: "%[1]s %[2]s ist derzeit die neueste verfügbare Version.",
Unavailable: "Updates nicht verfügbar",
UnavailableMessage: "%[1]s kann sich an seinem Installationsort nicht selbst aktualisieren. Wurde es mit einer Paketverwaltung installiert, aktualisieren Sie es dort.",
DevelopmentBuild: "Entwicklungs-Builds aktualisieren sich nicht selbst.",
Error: "Fehler beim Update!",
CheckError: "Beim Suchen nach Updates ist ein Fehler aufgetreten. Bitte versuchen Sie es später erneut.",
InstallError: "Beim Installieren des Updates ist ein Fehler aufgetreten. Bitte versuchen Sie es später erneut.",
Available: "Eine neue Version von %[1]s ist verfügbar!",
AvailableMessage: "%[1]s %[2]s ist jetzt verfügbar – Sie haben %[3]s. Möchten Sie es jetzt installieren?",
ReleaseNotes: "Versionshinweise:",
AutomaticDownloads: "Updates künftig automatisch laden und installieren",
Skip: "Diese Version überspringen",
RemindLater: "Später erinnern",
Install: "Update installieren",
Downloading: "Update wird geladen …",
Progress: "%[1]s von %[2]s",
Megabytes: "%s MB",
Installing: "Update wird installiert …",
Ready: "Bereit zum Neustart",
ReadyMessage: "%[1]s %[2]s ist installiert und startet, wenn Sie %[1]s das nächste Mal öffnen. Starten Sie jetzt neu, um es zu verwenden.",
Later: "Später",
Relaunch: "Jetzt neu starten",
},
"es": {
Title: "Actualización de software",
MenuItem: "Buscar actualizaciones…",
Checking: "Buscando actualizaciones…",
Cancel: "Cancelar",
OK: "Aceptar",
UpToDate: "¡Ya tiene la versión más reciente!",
UpToDateMessage: "%[1]s %[2]s es la versión más reciente disponible.",
Unavailable: "Actualizaciones no disponibles",
UnavailableMessage: "%[1]s no puede actualizarse en la ubicación donde está instalado. Si lo instaló un gestor de paquetes, actualícelo desde allí.",
DevelopmentBuild: "Las versiones de desarrollo no se actualizan solas.",
Error: "¡Error de actualización!",
CheckError: "Se ha producido un error al buscar actualizaciones. Vuelva a intentarlo más tarde.",
InstallError: "Se ha producido un error al instalar la actualización. Vuelva a intentarlo más tarde.",
Available: "¡Hay una nueva versión de %[1]s disponible!",
AvailableMessage: "%[1]s %[2]s ya está disponible (tiene la versión %[3]s). ¿Desea instalarla ahora?",
ReleaseNotes: "Notas de la versión:",
AutomaticDownloads: "Descargar e instalar actualizaciones automáticamente en el futuro",
Skip: "Omitir esta versión",
RemindLater: "Recordármelo más tarde",
Install: "Instalar actualización",
Downloading: "Descargando actualización…",
Progress: "%[1]s de %[2]s",
Megabytes: "%s MB",
Installing: "Instalando actualización…",
Ready: "Listo para reiniciar",
ReadyMessage: "%[1]s %[2]s está instalado y se abrirá la próxima vez que inicie %[1]s. Reinicie ahora para empezar a usarlo.",
Later: "Más tarde",
Relaunch: "Reiniciar ahora",
},
"fr": {
Title: "Mise à jour de logiciels",
MenuItem: "Rechercher les mises à jour…",
Checking: "Recherche de mises à jour…",
Cancel: "Annuler",
OK: "OK",
UpToDate: "Vous êtes à jour !",
UpToDateMessage: "%[1]s %[2]s est actuellement la version la plus récente.",
Unavailable: "Mises à jour indisponibles",
UnavailableMessage: "%[1]s ne peut pas se mettre à jour à l’emplacement où il est installé. S’il a été installé par un gestionnaire de paquets, mettez-le à jour depuis celui-ci.",
DevelopmentBuild: "Les versions de développement ne se mettent pas à jour.",
Error: "Erreur de mise à jour !",
CheckError: "Une erreur est survenue lors de la recherche de mises à jour. Veuillez réessayer plus tard.",
InstallError: "Une erreur est survenue lors de l’installation de la mise à jour. Veuillez réessayer plus tard.",
Available: "Une nouvelle version de %[1]s est disponible !",
AvailableMessage: "%[1]s %[2]s est maintenant disponible (vous avez la version %[3]s). Voulez-vous l’installer maintenant ?",
ReleaseNotes: "Notes de version :",
AutomaticDownloads: "Télécharger et installer automatiquement les mises à jour à l’avenir",
Skip: "Ignorer cette version",
RemindLater: "Me le rappeler plus tard",
Install: "Installer la mise à jour",
Downloading: "Téléchargement de la mise à jour…",
Progress: "%[1]s sur %[2]s",
Megabytes: "%s Mo",
Installing: "Installation de la mise à jour…",
Ready: "Prêt à relancer",
ReadyMessage: "%[1]s %[2]s est installé et démarrera la prochaine fois que vous ouvrirez %[1]s. Relancez maintenant pour l’utiliser.",
Later: "Plus tard",
Relaunch: "Relancer maintenant",
},
"it": {
Title: "Aggiornamento software",
MenuItem: "Controlla aggiornamenti…",
Checking: "Ricerca di aggiornamenti…",
Cancel: "Annulla",
OK: "OK",
UpToDate: "Hai già l’ultima versione!",
UpToDateMessage: "%[1]s %[2]s è attualmente la versione più recente disponibile.",
Unavailable: "Aggiornamenti non disponibili",
UnavailableMessage: "%[1]s non può aggiornarsi nella posizione in cui è installato. Se è stato installato con un gestore di pacchetti, aggiornalo da lì.",
DevelopmentBuild: "Le build di sviluppo non si aggiornano da sole.",
Error: "Errore di aggiornamento!",
CheckError: "Si è verificato un errore durante la ricerca di aggiornamenti. Riprova più tardi.",
InstallError: "Si è verificato un errore durante l’installazione dell’aggiornamento. Riprova più tardi.",
Available: "È disponibile una nuova versione di %[1]s!",
AvailableMessage: "%[1]s %[2]s è ora disponibile (hai la versione %[3]s). Vuoi installarla adesso?",
ReleaseNotes: "Note di rilascio:",
AutomaticDownloads: "Scarica e installa automaticamente gli aggiornamenti in futuro",
Skip: "Salta questa versione",
RemindLater: "Ricordamelo più tardi",
Install: "Installa aggiornamento",
Downloading: "Download dell’aggiornamento…",
Progress: "%[1]s di %[2]s",
Megabytes: "%s MB",
Installing: "Installazione dell’aggiornamento…",
Ready: "Pronto per il riavvio",
ReadyMessage: "%[1]s %[2]s è installato e si avvierà la prossima volta che apri %[1]s. Riavvia ora per iniziare a usarlo.",
Later: "Più tardi",
Relaunch: "Riavvia ora",
},
"ja": {
Title: "ソフトウェア・アップデート",
MenuItem: "アップデートを確認…",
Checking: "アップデートを確認中…",
Cancel: "キャンセル",
OK: "OK",
UpToDate: "最新の状態です",
UpToDateMessage: "%[1]s %[2]s は現在入手できる最新バージョンです。",
Unavailable: "アップデートを利用できません",
UnavailableMessage: "%[1]s はインストールされている場所では自動でアップデートできません。パッケージマネージャでインストールした場合は、そちらでアップデートしてください。",
DevelopmentBuild: "開発用ビルドは自動でアップデートされません。",
Error: "アップデートエラー",
CheckError: "アップデートの確認中にエラーが起きました。後でもう一度お試しください。",
InstallError: "アップデートのインストール中にエラーが起きました。後でもう一度お試しください。",
Available: "%[1]s の新しいバージョンがあります",
AvailableMessage: "%[1]s %[2]s が利用可能です(現在のバージョンは %[3]s)。今すぐインストールしますか?",
ReleaseNotes: "リリースノート:",
AutomaticDownloads: "今後はアップデートを自動的にダウンロードしてインストール",
Skip: "このバージョンをスキップ",
RemindLater: "後で通知",
Install: "アップデートをインストール",
Downloading: "アップデートをダウンロード中…",
Progress: "%[1]s / %[2]s",
Megabytes: "%s MB",
Installing: "アップデートをインストール中…",
Ready: "再起動の準備ができました",
ReadyMessage: "%[1]s %[2]s がインストールされました。次回 %[1]s を開いたときに起動します。今すぐ再起動すると使い始められます。",
Later: "後で",
Relaunch: "今すぐ再起動",
},
"ko": {
Title: "소프트웨어 업데이트",
MenuItem: "업데이트 확인…",
Checking: "업데이트 확인 중…",
Cancel: "취소",
OK: "확인",
UpToDate: "최신 버전입니다!",
UpToDateMessage: "%[1]s %[2]s이(가) 현재 사용 가능한 최신 버전입니다.",
Unavailable: "업데이트를 사용할 수 없음",
UnavailableMessage: "%[1]s은(는) 설치된 위치에서 스스로 업데이트할 수 없습니다. 패키지 관리자로 설치했다면 해당 관리자에서 업데이트하십시오.",
DevelopmentBuild: "개발용 빌드는 스스로 업데이트하지 않습니다.",
Error: "업데이트 오류!",
CheckError: "업데이트를 확인하는 중 오류가 발생했습니다. 나중에 다시 시도하십시오.",
InstallError: "업데이트를 설치하는 중 오류가 발생했습니다. 나중에 다시 시도하십시오.",
Available: "%[1]s의 새 버전을 사용할 수 있습니다!",
AvailableMessage: "%[1]s %[2]s을(를) 사용할 수 있습니다(현재 버전: %[3]s). 지금 설치하시겠습니까?",
ReleaseNotes: "릴리즈 노트:",
AutomaticDownloads: "앞으로 업데이트를 자동으로 다운로드하고 설치",
Skip: "이 버전 건너뛰기",
RemindLater: "나중에 알림",
Install: "업데이트 설치",
Downloading: "업데이트 다운로드 중…",
Progress: "%[1]s / %[2]s",
Megabytes: "%s MB",
Installing: "업데이트 설치 중…",
Ready: "다시 실행 준비 완료",
ReadyMessage: "%[1]s %[2]s이(가) 설치되었으며 다음에 %[1]s을(를) 열 때 실행됩니다. 지금 다시 실행하여 사용을 시작하십시오.",
Later: "나중에",
Relaunch: "지금 다시 실행",
},
"nl": {
Title: "Software-update",
MenuItem: "Zoek naar updates…",
Checking: "Zoeken naar updates…",
Cancel: "Annuleer",
OK: "OK",
UpToDate: "Je bent up-to-date!",
UpToDateMessage: "%[1]s %[2]s is momenteel de nieuwste beschikbare versie.",
Unavailable: "Updates niet beschikbaar",
UnavailableMessage: "%[1]s kan zichzelf niet bijwerken op de plek waar het is geïnstalleerd. Als een pakketbeheerder het heeft geïnstalleerd, werk het daar bij.",
DevelopmentBuild: "Ontwikkelversies werken zichzelf niet bij.",
Error: "Fout bij update!",
CheckError: "Er is een fout opgetreden bij het zoeken naar updates. Probeer het later opnieuw.",
InstallError: "Er is een fout opgetreden bij het installeren van de update. Probeer het later opnieuw.",
Available: "Er is een nieuwe versie van %[1]s beschikbaar!",
AvailableMessage: "%[1]s %[2]s is nu beschikbaar (je hebt %[3]s). Wil je deze nu installeren?",
ReleaseNotes: "Release-opmerkingen:",
AutomaticDownloads: "Updates voortaan automatisch downloaden en installeren",
Skip: "Sla deze versie over",
RemindLater: "Herinner me later",
Install: "Installeer update",
Downloading: "Update downloaden…",
Progress: "%[1]s van %[2]s",
Megabytes: "%s MB",
Installing: "Update installeren…",
Ready: "Klaar om opnieuw te starten",
ReadyMessage: "%[1]s %[2]s is geïnstalleerd en start de volgende keer dat je %[1]s opent. Start nu opnieuw om het te gebruiken.",
Later: "Later",
Relaunch: "Start nu opnieuw",
},
"pl": {
Title: "Aktualizacja oprogramowania",
MenuItem: "Sprawdź aktualizacje…",
Checking: "Sprawdzanie aktualizacji…",
Cancel: "Anuluj",
OK: "OK",
UpToDate: "Masz najnowszą wersję!",
UpToDateMessage: "Wersja %[2]s aplikacji %[1]s jest obecnie najnowszą dostępną wersją.",
Unavailable: "Aktualizacje niedostępne",
UnavailableMessage: "Aplikacja %[1]s nie może zaktualizować się w miejscu, w którym jest zainstalowana. Jeśli zainstalował ją menedżer pakietów, zaktualizuj ją tam.",
DevelopmentBuild: "Wersje deweloperskie nie aktualizują się same.",
Error: "Błąd aktualizacji!",
CheckError: "Wystąpił błąd podczas sprawdzania aktualizacji. Spróbuj ponownie później.",
InstallError: "Wystąpił błąd podczas instalowania aktualizacji. Spróbuj ponownie później.",
Available: "Dostępna jest nowa wersja aplikacji %[1]s!",
AvailableMessage: "Wersja %[2]s aplikacji %[1]s jest już dostępna (masz wersję %[3]s). Czy chcesz ją teraz zainstalować?",
ReleaseNotes: "Informacje o wersji:",
AutomaticDownloads: "W przyszłości automatycznie pobieraj i instaluj aktualizacje",
Skip: "Pomiń tę wersję",
RemindLater: "Przypomnij później",
Install: "Zainstaluj aktualizację",
Downloading: "Pobieranie aktualizacji…",
Progress: "%[1]s z %[2]s",
Megabytes: "%s MB",
Installing: "Instalowanie aktualizacji…",
Ready: "Gotowe do ponownego uruchomienia",
ReadyMessage: "Wersja %[2]s aplikacji %[1]s jest zainstalowana i uruchomi się przy następnym otwarciu aplikacji %[1]s. Uruchom ją ponownie teraz, aby zacząć z niej korzystać.",
Later: "Później",
Relaunch: "Uruchom ponownie",
},
"pt-BR": {
Title: "Atualização de Software",
MenuItem: "Verificar atualizações…",
Checking: "Verificando atualizações…",
Cancel: "Cancelar",
OK: "OK",
UpToDate: "Você já tem a versão mais recente!",
UpToDateMessage: "%[1]s %[2]s é a versão mais recente disponível.",
Unavailable: "Atualizações indisponíveis",
UnavailableMessage: "%[1]s não pode se atualizar no local onde está instalado. Se ele foi instalado por um gerenciador de pacotes, atualize-o por lá.",
DevelopmentBuild: "Versões de desenvolvimento não se atualizam sozinhas.",
Error: "Erro de atualização!",
CheckError: "Ocorreu um erro ao verificar atualizações. Tente novamente mais tarde.",
InstallError: "Ocorreu um erro ao instalar a atualização. Tente novamente mais tarde.",
Available: "Uma nova versão de %[1]s está disponível!",
AvailableMessage: "%[1]s %[2]s já está disponível (você tem a versão %[3]s). Deseja instalá-la agora?",
ReleaseNotes: "Notas da versão:",
AutomaticDownloads: "Baixar e instalar atualizações automaticamente no futuro",
Skip: "Ignorar esta versão",
RemindLater: "Lembrar mais tarde",
Install: "Instalar atualização",
Downloading: "Baixando atualização…",
Progress: "%[1]s de %[2]s",
Megabytes: "%s MB",
Installing: "Instalando atualização…",
Ready: "Pronto para reabrir",
ReadyMessage: "%[1]s %[2]s está instalado e será iniciado na próxima vez que você abrir %[1]s. Reabra agora para começar a usá-lo.",
Later: "Mais tarde",
Relaunch: "Reabrir agora",
},
"ru": {
Title: "Обновление ПО",
MenuItem: "Проверить обновления…",
Checking: "Проверка обновлений…",
Cancel: "Отмена",
OK: "ОК",
UpToDate: "У вас последняя версия!",
UpToDateMessage: "%[1]s %[2]s — самая новая из доступных версий.",
Unavailable: "Обновления недоступны",
UnavailableMessage: "Приложение %[1]s не может обновить себя в месте установки. Если оно установлено менеджером пакетов, обновите его там.",
DevelopmentBuild: "Сборки для разработки не обновляются сами.",
Error: "Ошибка обновления!",
CheckError: "При проверке обновлений произошла ошибка. Повторите попытку позже.",
InstallError: "При установке обновления произошла ошибка. Повторите попытку позже.",
Available: "Доступна новая версия %[1]s!",
AvailableMessage: "Доступна версия %[1]s %[2]s (у вас %[3]s). Установить её сейчас?",
ReleaseNotes: "Что нового:",
AutomaticDownloads: "Автоматически загружать и устанавливать обновления в будущем",
Skip: "Пропустить эту версию",
RemindLater: "Напомнить позже",
Install: "Установить обновление",
Downloading: "Загрузка обновления…",
Progress: "%[1]s из %[2]s",
Megabytes: "%s МБ",
Installing: "Установка обновления…",
Ready: "Готово к перезапуску",
ReadyMessage: "%[1]s %[2]s установлено и запустится при следующем открытии %[1]s. Перезапустите сейчас, чтобы начать пользоваться новой версией.",
Later: "Позже",
Relaunch: "Перезапустить",
},
"tr": {
Title: "Yazılım Güncelleme",
MenuItem: "Güncellemeleri Denetle…",
Checking: "Güncellemeler denetleniyor…",
Cancel: "Vazgeç",
OK: "Tamam",
UpToDate: "En son sürümü kullanıyorsunuz!",
UpToDateMessage: "%[1]s %[2]s şu anda mevcut en yeni sürüm.",
Unavailable: "Güncellemeler Kullanılamıyor",
UnavailableMessage: "%[1]s yüklü olduğu konumda kendini güncelleyemiyor. Bir paket yöneticisiyle yüklendiyse oradan güncelleyin.",
DevelopmentBuild: "Geliştirme sürümleri kendilerini güncellemez.",
Error: "Güncelleme Hatası!",
CheckError: "Güncellemeler denetlenirken bir hata oluştu. Lütfen daha sonra yeniden deneyin.",
InstallError: "Güncelleme yüklenirken bir hata oluştu. Lütfen daha sonra yeniden deneyin.",
Available: "%[1]s için yeni bir sürüm var!",
AvailableMessage: "%[1]s %[2]s artık kullanılabilir (sizdeki sürüm %[3]s). Şimdi yüklemek ister misiniz?",
ReleaseNotes: "Sürüm Notları:",
AutomaticDownloads: "Gelecekte güncellemeleri otomatik olarak indir ve yükle",
Skip: "Bu Sürümü Atla",
RemindLater: "Daha Sonra Hatırlat",
Install: "Güncellemeyi Yükle",
Downloading: "Güncelleme indiriliyor…",
Progress: "%[1]s / %[2]s",
Megabytes: "%s MB",
Installing: "Güncelleme yükleniyor…",
Ready: "Yeniden Başlatmaya Hazır",
ReadyMessage: "%[1]s %[2]s yüklendi ve %[1]s bir sonraki açılışında başlayacak. Kullanmaya başlamak için şimdi yeniden başlatın.",
Later: "Daha Sonra",
Relaunch: "Şimdi Yeniden Başlat",
},
"uk": {
Title: "Оновлення ПЗ",
MenuItem: "Перевірити оновлення…",
Checking: "Перевірка оновлень…",
Cancel: "Скасувати",
OK: "OK",
UpToDate: "У вас остання версія!",
UpToDateMessage: "%[1]s %[2]s — найновіша доступна версія.",
Unavailable: "Оновлення недоступні",
UnavailableMessage: "Застосунок %[1]s не може оновити себе в місці встановлення. Якщо його встановив менеджер пакетів, оновіть його там.",
DevelopmentBuild: "Збірки для розробки не оновлюються самі.",
Error: "Помилка оновлення!",
CheckError: "Під час перевірки оновлень сталася помилка. Спробуйте пізніше.",
InstallError: "Під час встановлення оновлення сталася помилка. Спробуйте пізніше.",
Available: "Доступна нова версія %[1]s!",
AvailableMessage: "Доступна версія %[1]s %[2]s (у вас %[3]s). Встановити її зараз?",
ReleaseNotes: "Що нового:",
AutomaticDownloads: "Автоматично завантажувати та встановлювати оновлення надалі",
Skip: "Пропустити цю версію",
RemindLater: "Нагадати пізніше",
Install: "Встановити оновлення",
Downloading: "Завантаження оновлення…",
Progress: "%[1]s з %[2]s",
Megabytes: "%s МБ",
Installing: "Встановлення оновлення…",
Ready: "Готово до перезапуску",
ReadyMessage: "%[1]s %[2]s встановлено, і ця версія запуститься під час наступного відкриття %[1]s. Перезапустіть зараз, щоб почати нею користуватися.",
Later: "Пізніше",
Relaunch: "Перезапустити",
},
"zh-Hans": {
Title: "软件更新",
MenuItem: "检查更新…",
Checking: "正在检查更新…",
Cancel: "取消",
OK: "好",
UpToDate: "已是最新版本!",
UpToDateMessage: "%[1]s %[2]s 是目前可用的最新版本。",
Unavailable: "无法更新",
UnavailableMessage: "%[1]s 无法在当前安装位置自行更新。如果它是通过软件包管理器安装的,请在那里更新。",
DevelopmentBuild: "开发版本不会自行更新。",
Error: "更新出错!",
CheckError: "检查更新时出错,请稍后再试。",
InstallError: "安装更新时出错,请稍后再试。",
Available: "%[1]s 有新版本可用!",
AvailableMessage: "%[1]s %[2]s 现已推出,你当前的版本是 %[3]s。要现在安装吗?",
ReleaseNotes: "更新说明:",
AutomaticDownloads: "以后自动下载并安装更新",
Skip: "跳过这个版本",
RemindLater: "稍后提醒我",
Install: "安装更新",
Downloading: "正在下载更新…",
Progress: "%[1]s / %[2]s",
Megabytes: "%s MB",
Installing: "正在安装更新…",
Ready: "可以重新启动了",
ReadyMessage: "%[1]s %[2]s 已安装,将在下次打开 %[1]s 时启动。立即重新启动即可开始使用。",
Later: "稍后",
Relaunch: "立即重新启动",
},
"zh-Hant": {
Title: "軟體更新",
MenuItem: "檢查更新項目…",
Checking: "正在檢查更新項目…",
Cancel: "取消",
OK: "好",
UpToDate: "已是最新版本!",
UpToDateMessage: "%[1]s %[2]s 是目前可用的最新版本。",
Unavailable: "無法更新",
UnavailableMessage: "%[1]s 無法在目前的安裝位置自行更新。如果它是透過套件管理工具安裝的,請在那裡更新。",
DevelopmentBuild: "開發版本不會自行更新。",
Error: "更新發生錯誤!",
CheckError: "檢查更新項目時發生錯誤,請稍後再試。",
InstallError: "安裝更新項目時發生錯誤,請稍後再試。",
Available: "%[1]s 有新版本可用!",
AvailableMessage: "%[1]s %[2]s 現已推出,你目前的版本是 %[3]s。要立即安裝嗎?",
ReleaseNotes: "版本說明:",
AutomaticDownloads: "日後自動下載並安裝更新項目",
Skip: "略過此版本",
RemindLater: "稍後提醒我",
Install: "安裝更新項目",
Downloading: "正在下載更新項目…",
Progress: "%[1]s / %[2]s",
Megabytes: "%s MB",
Installing: "正在安裝更新項目…",
Ready: "準備重新啟動",
ReadyMessage: "%[1]s %[2]s 已安裝,會在下次打開 %[1]s 時啟動。立即重新啟動即可開始使用。",
Later: "稍後",
Relaunch: "立即重新啟動",
},
}
+676
View File
@@ -0,0 +1,676 @@
// Package updater is the update window of MyGo apps, in the manner of
// Sparkle on macOS. It checks for updates in the background, once a day by
// default, and when a new version is out it shows its release notes and
// offers to install it, skip it or remind the user later. The first check
// is soon after launch, so a version that came out since the app last ran
// shows when it opens again. Installing downloads the update with a
// progress bar, then offers to relaunch the app into it.
//
// mygo.Use(updater.Plugin)
//
// Add "Check for Updates…" to the app's menu, after About on macOS:
//
// {Label: "My App", Submenu: []*mygo.MenuItem{
// {Role: mygo.RoleAbout},
// updater.MenuItem(),
// ...
// }},
//
// It is built on mygo.Updater, so the app must be built with updates (see
// the updates guide). Builds that cannot update themselves, such as
// development builds and apps installed by a package manager, never check
// in the background, and say why when the user checks.
//
// The window speaks the user's language when the plugin has it, and
// Options.Strings changes its texts or adds languages (see Strings).
//
// The user's choices are kept in updater.json in the app's user data
// directory: whether to check automatically (AutomaticChecks), whether to
// install updates without asking (AutomaticDownloads, the checkbox of the
// update window), the version they skipped and when the app last checked.
// OnChange tells the app when they changed, for a preferences page.
package updater
import (
"context"
"encoding/json/v2"
"errors"
"os"
"path/filepath"
"slices"
"sync"
"sync/atomic"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/update"
"github.com/egoist/mygo/plugins/updater/internal/frontend"
)
// Options configure the plugin.
type Options struct {
// Interval between automatic checks. Zero means a day.
Interval time.Duration
// DisableAutomaticChecks turns automatic checks off until
// SetAutomaticChecks turns them on, for apps that ask the user first or
// only check from the menu.
DisableAutomaticChecks bool
// Icon is the PNG image shown in the update window. Nil means icon.png
// among the app's resources, the default icon of `mygo build`, when
// there is one.
Icon []byte
// Language of the window, a language tag such as "fr" or "zh-Hant".
// Empty means the user's (App.Locale): the plugin shows the language
// that matches it best among its own and those of Strings, else
// English.
Language string
// Strings change the texts of the window by language tag, or add
// languages. Their empty fields keep the plugin's texts, else the
// English ones:
//
// Strings: map[string]updater.Strings{
// "en": {Install: "Update Now"},
// "sv": {Title: "Programuppdatering", ...},
// }
Strings map[string]Strings
}
// Plugin is the plugin with the default options.
var Plugin = New(Options{})
// New returns the plugin with options. Use one of them only.
func New(opts Options) mygo.Plugin { return newPlugin(opts, openWindow) }
func init() {
// Package native shows the window in native UI.
frontend.Plugin = func(opts any, open frontend.Open) mygo.Plugin {
return newPlugin(opts.(Options), func(s *session) { open(s) })
}
}
// newPlugin returns the plugin whose windows open creates.
func newPlugin(opts Options, open func(*session)) mygo.Plugin {
u := newUpdater(opts, open)
return mygo.Plugin{
Name: "updater",
Service: &service{u},
Setup: func() error {
if err := checkStrings(opts.Strings); err != nil {
return err
}
if !active.CompareAndSwap(nil, u) {
return errors.New("another updater plugin is used")
}
mygo.App.WhenReady(func() { go u.start() })
return nil
},
}
}
// CheckForUpdates checks for updates as the user asked, from a menu item
// or a button: the update window shows right away, says when the app is up
// to date or the check failed, and shows updates the user skipped. It
// returns at once; while a check is under way it brings its window to the
// front, and while the window offers an update it checks again first, so
// that it offers a newer version that came out since.
func CheckForUpdates() {
u := used()
go u.begin(true)
}
// MenuItem returns a "Check for Updates…" item that calls CheckForUpdates.
func MenuItem() *mygo.MenuItem {
return &mygo.MenuItem{
Label: used().text().MenuItem,
Click: func(*mygo.MenuItem, *mygo.Window) { CheckForUpdates() },
}
}
// AutomaticChecks reports whether the app checks for updates in the
// background.
func AutomaticChecks() bool {
u := used()
u.load()
u.mu.Lock()
defer u.mu.Unlock()
return u.automaticChecks()
}
// SetAutomaticChecks turns checking for updates in the background on or
// off, for a preference of the app.
func SetAutomaticChecks(on bool) {
u := used()
u.update(func(s *state) { s.AutomaticChecks = &on })
u.schedule()
}
// AutomaticDownloads reports whether updates found in the background are
// installed without asking: they run the next time the app starts. The
// update window offers to turn it on.
func AutomaticDownloads() bool {
u := used()
u.load()
u.mu.Lock()
defer u.mu.Unlock()
return u.state.AutomaticDownloads
}
// SetAutomaticDownloads turns installing updates found in the background
// without asking on or off.
func SetAutomaticDownloads(on bool) {
used().update(func(s *state) { s.AutomaticDownloads = on })
}
// LastCheck returns when the app last checked for updates successfully, or
// the zero time.
func LastCheck() time.Time {
u := used()
u.load()
u.mu.Lock()
defer u.mu.Unlock()
return u.state.LastCheck
}
// AvailableVersion reports the newer version found by the last check, or "".
// It is empty before checking, after a failed check, and for a skipped version.
// A downloaded update keeps its version until the app relaunches.
func AvailableVersion() string {
u := used()
u.mu.Lock()
defer u.mu.Unlock()
return u.available
}
// OnChange calls fn on the main thread after the choices of the user or the
// time of the last check or AvailableVersion changed: a check succeeded, the user answered the
// update window (its checkbox, Skip This Version), or the app called
// SetAutomaticChecks or SetAutomaticDownloads. A preferences page that shows
// AutomaticChecks, AutomaticDownloads or LastCheck reads them again. It
// returns a function that removes fn.
func OnChange(fn func()) (off func()) {
u := used()
return u.add(&u.changes, fn)
}
// OnInstalled calls fn on the main thread once an update is installed,
// whether the user installed it or it was installed in the background
// (AutomaticDownloads), before the app relaunches into it. On Windows and
// Linux the app's executable is then the new version's; on macOS the new
// version is staged until the app quits. It returns a function that
// removes fn.
func OnInstalled(fn func()) (off func()) {
u := used()
return u.add(&u.installs, fn)
}
// active is the plugin that was used.
var active atomic.Pointer[updater]
func used() *updater {
u := active.Load()
if u == nil {
panic("updater: the plugin is not used: call mygo.Use(updater.Plugin) before App.Run")
}
return u
}
// Replaced by tests.
var (
enabled = mygo.Updater.Enabled
check = checkRelease
relaunch = mygo.App.Relaunch
appVersion = mygo.App.Version
locale = mygo.App.Locale
now = time.Now
stateDir = func() (string, error) { return mygo.App.Path(mygo.PathUserData) }
resourcesDir = func() (string, error) { return mygo.App.Path(mygo.PathResources) }
runOnMain = mygo.RunOnMain
firstCheckWait = 10 * time.Second
)
// release is an update that a check found.
type release struct {
version string
notes string
install func(ctx context.Context, progress func(downloaded, total int64)) error
}
func checkRelease(ctx context.Context) (*release, error) {
up, err := mygo.Updater.Check(ctx)
if err != nil || up == nil {
return nil, err
}
return &release{version: up.Version, notes: up.Notes, install: up.Install}, nil
}
// state is what updater.json keeps.
type state struct {
// AutomaticChecks is nil until the app or the user chose.
AutomaticChecks *bool `json:"automaticChecks,omitempty"`
AutomaticDownloads bool `json:"automaticDownloads,omitzero"`
SkippedVersion string `json:"skippedVersion,omitzero"`
LastCheck time.Time `json:"lastCheck,omitzero"`
}
// same reports whether s keeps what o keeps.
func (s state) same(o state) bool {
if (s.AutomaticChecks == nil) != (o.AutomaticChecks == nil) ||
s.AutomaticChecks != nil && *s.AutomaticChecks != *o.AutomaticChecks {
return false
}
return s.AutomaticDownloads == o.AutomaticDownloads &&
s.SkippedVersion == o.SkippedVersion &&
s.LastCheck.Equal(o.LastCheck)
}
const stateFile = "updater.json"
type updater struct {
opts Options
// open creates the window of a session and shows it.
open func(*session)
// txt are the texts of the language txtLang, the last one asked for.
textMu sync.Mutex
txt *text
txtLang string
loadOnce sync.Once
mu sync.Mutex
file string // "" when the state cannot be saved
state state
// changes are the functions of OnChange, and installs those of
// OnInstalled, in the order they were added.
changes []*func()
installs []*func()
// running is set once the app is ready and can update itself: only
// then are checks scheduled.
running bool
timer *time.Timer
// failed is when the last automatic check failed, which retries sooner
// than the interval.
failed time.Time
// launchChecked is set once a check began since launch: until then the
// next one is soon, however recent the last check of an earlier launch.
launchChecked bool
// session is the check in progress; installed the update installed
// while the app runs, which runs at the next launch.
session *session
installed *release
available string
}
func newUpdater(opts Options, open func(*session)) *updater {
if opts.Interval <= 0 {
opts.Interval = 24 * time.Hour
}
return &updater{opts: opts, open: open}
}
// text returns the texts of the window in the language the app shows now
// (Options.Language, else App.Locale): after App.SetLocale, or a change of
// the user's languages, the next window and menu item take the new one.
func (u *updater) text() *text {
lang := u.opts.Language
if lang == "" {
lang = locale()
}
u.textMu.Lock()
defer u.textMu.Unlock()
if u.txt == nil || lang != u.txtLang {
u.txt, u.txtLang = newText(lang, u.opts.Strings), lang
}
return u.txt
}
// start schedules the automatic checks, once the app is ready.
func (u *updater) start() {
if !enabled() {
return
}
u.load()
u.mu.Lock()
u.running = true
u.mu.Unlock()
// Timers stop while the computer sleeps: check what is due on waking.
mygo.Power.OnResume(func() { go u.schedule() })
u.schedule()
}
// load reads the state file, once.
func (u *updater) load() {
u.loadOnce.Do(func() {
dir, err := stateDir()
if err != nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.file = filepath.Join(dir, stateFile)
if data, err := os.ReadFile(u.file); err == nil {
_ = json.Unmarshal(data, &u.state) // a damaged file is ignored
}
})
}
// update changes the state, saves it, and calls the functions of OnChange
// when it changed.
func (u *updater) update(fn func(*state)) {
u.load()
u.mu.Lock()
before := u.state
beforeAvailable := u.available
fn(&u.state)
u.save()
var changes []*func()
if !u.state.same(before) || u.available != beforeAvailable {
changes = slices.Clone(u.changes)
}
u.mu.Unlock()
call(changes)
}
// call calls fns on the main thread, from a goroutine of its own: no
// caller waits for the main thread.
func call(fns []*func()) {
if len(fns) == 0 {
return
}
go runOnMain(func() {
for _, fn := range fns {
(*fn)()
}
})
}
// save writes the state file. u.mu is held.
func (u *updater) save() {
if u.file == "" {
return
}
data, err := json.Marshal(u.state, json.Deterministic(true))
if err != nil {
return
}
if err := os.WriteFile(u.file+".tmp", data, 0o644); err == nil {
_ = os.Rename(u.file+".tmp", u.file)
}
}
// add adds fn to the functions fns, which u.mu guards, and returns a
// function that removes it.
func (u *updater) add(fns *[]*func(), fn func()) (off func()) {
p := &fn
u.mu.Lock()
*fns = append(*fns, p)
u.mu.Unlock()
return func() {
u.mu.Lock()
defer u.mu.Unlock()
*fns = slices.DeleteFunc(*fns, func(q *func()) bool { return q == p })
}
}
func (u *updater) automaticChecks() bool {
if u.state.AutomaticChecks != nil {
return *u.state.AutomaticChecks
}
return !u.opts.DisableAutomaticChecks
}
// schedule arms the timer of the next automatic check.
func (u *updater) schedule() {
u.mu.Lock()
defer u.mu.Unlock()
if u.timer != nil {
u.timer.Stop()
u.timer = nil
}
if !u.running || u.session != nil || u.installed != nil || !u.automaticChecks() {
return
}
wait := firstCheckWait
if u.launchChecked {
wait = max(nextCheck(u.state.LastCheck, u.failed, u.opts.Interval, now()).Sub(now()), firstCheckWait)
}
u.timer = time.AfterFunc(wait, func() { u.begin(false) })
}
// nextCheck returns when the next automatic check is due: an interval
// after the last successful one, and when a check failed since, an hour
// after that at most.
func nextCheck(last, failed time.Time, interval time.Duration, now time.Time) time.Time {
if last.After(now) { // the clock was set back
last = now
}
due := last.Add(interval)
if retry := failed.Add(min(interval, time.Hour)); !failed.IsZero() && retry.After(due) {
due = retry
}
return due
}
// checked records the outcome of a check.
func (u *updater) checked(err error, version string, user bool) {
u.mu.Lock()
if err != nil {
u.failed = now()
u.mu.Unlock()
u.update(func(*state) { u.available = "" })
return
}
u.failed = time.Time{}
u.mu.Unlock()
t := now()
u.update(func(s *state) {
s.LastCheck = t
u.available = version
if !user && s.SkippedVersion == version {
u.available = ""
}
})
}
// begin starts a check, or makes the one under way show its window when
// the user asked for it.
func (u *updater) begin(user bool) {
u.load()
// Its window speaks the app's language when the check begins. Out of
// u.mu: the first App.Locale asks the main thread.
t := u.text()
u.mu.Lock()
if s := u.session; s != nil {
u.mu.Unlock()
if user && !s.recheck() {
s.promote()
}
return
}
if !user && u.installed != nil {
u.mu.Unlock()
return
}
s := newSession(u, t, user)
u.session = s
u.launchChecked = true
if u.timer != nil {
u.timer.Stop()
u.timer = nil
}
u.mu.Unlock()
u.run(s)
}
// end closes the window of a session and schedules the next check.
func (u *updater) end(s *session) {
u.mu.Lock()
if u.session == s {
u.session = nil
}
u.mu.Unlock()
s.close()
u.schedule()
}
// run checks for updates and drives the update window.
func (u *updater) run(s *session) {
defer u.end(s)
t := s.t
if !enabled() {
u.update(func(*state) { u.available = "" })
s.set(t.unavailableView())
s.show()
s.wait()
return
}
u.mu.Lock()
installed := u.installed
u.mu.Unlock()
if installed != nil {
u.offerRelaunch(s, installed)
return
}
s.set(t.checkingView())
if s.User() {
s.show()
}
r, err := check(s.ctx)
if s.ctx.Err() != nil {
return // canceled
}
version := ""
if err == nil && r != nil {
version = r.version
}
u.checked(err, version, s.User())
switch {
case err != nil:
if s.User() {
s.set(t.errorView(t.CheckError, err))
s.wait()
}
return
case r == nil:
if s.User() {
s.set(t.upToDateView())
s.wait()
}
return
}
u.mu.Lock()
skipped := u.state.SkippedVersion == r.version
automatic := u.state.AutomaticDownloads
u.mu.Unlock()
if !s.User() {
if skipped {
return
}
if automatic {
u.install(s, r)
return
}
}
r, resp := u.offer(s, r, automatic)
if resp.action == actionClose {
return
}
u.update(func(st *state) {
st.AutomaticDownloads = resp.automaticDownloads
if resp.action == actionSkip {
st.SkippedVersion = r.version
u.available = ""
}
})
if resp.action == actionInstall {
// A newer version may have come out while the window was open.
s.set(t.checkingView())
r = u.recheck(s, r)
if s.ctx.Err() != nil {
return // canceled
}
u.install(s, r)
}
}
// offer shows the window offering r and waits for the user's response.
// CheckForUpdates meanwhile checks again, and a newer version found takes
// the place of r. It returns the release offered last.
func (u *updater) offer(s *session, r *release, automatic bool) (*release, response) {
t := s.t
s.set(t.availableView(r, automatic))
s.show()
s.setOffering(true)
defer s.setOffering(false)
for {
select {
case resp := <-s.responses:
return r, resp
case <-s.rechecks:
if newer := u.recheck(s, r); newer != r {
r = newer
s.set(t.availableView(r, automatic))
}
s.promote()
case <-s.ctx.Done():
return r, response{action: actionClose}
}
}
}
// recheck checks for updates again while the window offers r, and returns
// the newer release it finds, else r: when the check fails, finds nothing
// newer or is canceled, r stays.
func (u *updater) recheck(s *session, r *release) *release {
found, err := check(s.ctx)
if err != nil || found == nil || s.ctx.Err() != nil {
return r
}
if update.Compare(found.version, r.version) > 0 {
r = found
}
u.checked(nil, r.version, true)
return r
}
// install downloads and installs r, showing its progress when the window
// shows, then offers to relaunch.
func (u *updater) install(s *session, r *release) {
t := s.t
s.set(t.downloadingView(0, 0))
err := r.install(s.ctx, func(downloaded, total int64) {
if downloaded < total {
s.set(t.downloadingView(downloaded, total))
} else {
s.set(t.installingView())
}
})
if s.ctx.Err() != nil {
return // canceled
}
if err != nil {
if s.User() || s.isShown() {
s.set(t.errorView(t.InstallError, err))
s.show()
s.wait()
}
return
}
u.mu.Lock()
u.installed = r
installs := slices.Clone(u.installs)
u.mu.Unlock()
call(installs)
if s.User() || s.isShown() {
u.offerRelaunch(s, r)
}
}
func (u *updater) offerRelaunch(s *session, r *release) {
s.set(s.t.readyView(r))
s.show()
if s.wait().action == actionRelaunch {
relaunch()
}
}
+775
View File
@@ -0,0 +1,775 @@
package updater
import (
"context"
"encoding/json/v2"
"errors"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/plugins/updater/internal/markdown"
)
// harness runs the updater without windows: its open function records the sessions
// that would show one.
type harness struct {
t *testing.T
u *updater
dir string
presented chan *session
relaunches atomic.Int32
checks atomic.Int32
// result is what checks find.
result func(ctx context.Context) (*release, error)
}
func newHarness(t *testing.T, opts Options) *harness {
h := &harness{t: t, dir: t.TempDir(), presented: make(chan *session, 10)}
saved := []func(){
func(e func() bool) func() { return func() { enabled = e } }(enabled),
func(c func(context.Context) (*release, error)) func() { return func() { check = c } }(check),
func(r func(...string)) func() { return func() { relaunch = r } }(relaunch),
func(v func() string) func() { return func() { appVersion = v } }(appVersion),
func(l func() string) func() { return func() { locale = l } }(locale),
func(d func() (string, error)) func() { return func() { stateDir = d } }(stateDir),
func(r func(func())) func() { return func() { runOnMain = r } }(runOnMain),
}
t.Cleanup(func() {
for _, restore := range saved {
restore()
}
})
enabled = func() bool { return true }
h.result = func(context.Context) (*release, error) { return nil, nil }
check = func(ctx context.Context) (*release, error) {
h.checks.Add(1)
return h.result(ctx)
}
relaunch = func(...string) { h.relaunches.Add(1) }
appVersion = func() string { return "1.0.0" }
locale = func() string { return "en-US" }
stateDir = func() (string, error) { return h.dir, nil }
runOnMain = func(fn func()) { fn() }
h.u = newUpdater(opts, func(s *session) { h.presented <- s })
return h
}
// begin starts a check and returns a channel closed when it ends.
func (h *harness) begin(user bool) chan struct{} {
done := make(chan struct{})
go func() {
h.u.begin(user)
close(done)
}()
return done
}
// shown returns the session that shows a window.
func (h *harness) shown() *session {
h.t.Helper()
select {
case s := <-h.presented:
return s
case <-time.After(wait.Guard):
h.t.Fatal("no window was shown")
return nil
}
}
func (h *harness) noWindow() {
h.t.Helper()
select {
case s := <-h.presented:
v, _ := s.Current()
h.t.Fatalf("a window was shown: %q", v.Title)
default:
}
}
// waitView waits for s to show a view whose title starts with title.
func waitView(t *testing.T, s *session, title string) view {
t.Helper()
deadline := time.After(wait.Guard)
for {
v, changed := s.Current()
if strings.HasPrefix(v.Title, title) {
return v
}
select {
case <-changed:
case <-deadline:
t.Fatalf("view %q, want %q", v.Title, title)
}
}
}
func waitDone(t *testing.T, done chan struct{}) {
t.Helper()
select {
case <-done:
case <-time.After(wait.Guard):
t.Fatal("the check did not end")
}
}
func (h *harness) saved() state {
h.t.Helper()
var st state
data, err := os.ReadFile(filepath.Join(h.dir, stateFile))
if err != nil {
h.t.Fatal(err)
}
if err := json.Unmarshal(data, &st); err != nil {
h.t.Fatal(err)
}
return st
}
func newRelease(version string, install func(ctx context.Context, progress func(downloaded, total int64)) error) *release {
if install == nil {
install = func(context.Context, func(int64, int64)) error { return nil }
}
return &release{version: version, notes: "### Fixed\n\n- A **bug**", install: install}
}
func TestUpToDate(t *testing.T) {
checked := time.Date(2026, 10, 16, 9, 30, 0, 0, time.UTC)
t.Cleanup(func(n func() time.Time) func() { return func() { now = n } }(now))
now = func() time.Time { return checked }
h := newHarness(t, Options{})
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "You’re up to date!")
if !strings.Contains(v.Message, "1.0.0 is currently the newest version") {
t.Errorf("message %q", v.Message)
}
s.Respond(v.Prompt, actionOK, false)
waitDone(t, done)
if h.u.session != nil {
t.Error("the session was not cleared")
}
if st := h.saved(); !st.LastCheck.Equal(checked) {
t.Errorf("last check %v, want %v", st.LastCheck, checked)
}
}
func TestInstallAndRelaunch(t *testing.T) {
h := newHarness(t, Options{})
proceed := make(chan struct{})
h.result = func(context.Context) (*release, error) {
return newRelease("2.0.0", func(ctx context.Context, progress func(int64, int64)) error {
progress(5e6, 20e6)
<-proceed
progress(20e6, 20e6)
return nil
}), nil
}
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "A new version of")
if !v.Release || !v.Checkbox || v.Checked || !strings.Contains(markdown.HTML(v.Notes), "<li>A <strong>bug</strong></li>") {
t.Errorf("available view: %+v", v)
}
if !strings.Contains(v.Message, "2.0.0 is now available—you have 1.0.0") {
t.Errorf("message %q", v.Message)
}
if len(v.Buttons) != 3 || v.Buttons[0].Action != actionSkip || !v.Buttons[0].Aside || !v.Buttons[2].Default {
t.Errorf("buttons %+v", v.Buttons)
}
s.Respond(v.Prompt, actionInstall, true)
v = waitView(t, s, "Downloading update…")
for v.Progress != 0.25 {
_, changed := s.Current()
<-changed
v, _ = s.Current()
}
if v.Message != "5.0 MB of 20.0 MB" || !v.Bar || v.Release {
t.Errorf("downloading view: %+v", v)
}
close(proceed)
v = waitView(t, s, "Ready to Relaunch")
if !strings.Contains(v.Message, "2.0.0 is installed") {
t.Errorf("message %q", v.Message)
}
s.Respond(v.Prompt, actionRelaunch, false)
waitDone(t, done)
if h.relaunches.Load() != 1 {
t.Error("the app did not relaunch")
}
if !h.saved().AutomaticDownloads {
t.Error("the checkbox was not saved")
}
// The update runs at the next launch: checks do not offer it again.
checks := h.checks.Load()
waitDone(t, h.begin(false))
h.noWindow()
done = h.begin(true)
s = h.shown()
v = waitView(t, s, "Ready to Relaunch")
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
if h.checks.Load() != checks {
t.Error("checked again after installing")
}
if h.relaunches.Load() != 1 {
t.Error("Later relaunched")
}
}
// releaseInstalls returns a release whose install sends its version to
// installed.
func releaseInstalls(version string, installed chan<- string) *release {
return newRelease(version, func(context.Context, func(int64, int64)) error {
installed <- version
return nil
})
}
// A release that came out while the window offered an older one is the
// one Install installs.
func TestInstallNewerRelease(t *testing.T) {
h := newHarness(t, Options{})
installed := make(chan string, 2)
h.result = func(context.Context) (*release, error) { return releaseInstalls("2.0.0", installed), nil }
done := h.begin(false)
s := h.shown()
v := waitView(t, s, "A new version of")
h.result = func(context.Context) (*release, error) { return releaseInstalls("2.1.0", installed), nil }
s.Respond(v.Prompt, actionInstall, false)
v = waitView(t, s, "Ready to Relaunch")
if !strings.Contains(v.Message, "2.1.0 is installed") {
t.Errorf("message %q", v.Message)
}
if got := wait.For(t, "the install", installed); got != "2.1.0" {
t.Errorf("installed %s, want 2.1.0", got)
}
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
if h.u.available != "2.1.0" || h.u.installed == nil || h.u.installed.version != "2.1.0" {
t.Errorf("available %q, installed %+v", h.u.available, h.u.installed)
}
if n := h.checks.Load(); n != 2 {
t.Errorf("%d checks, want 2", n)
}
}
// When checking again before installing fails, Install installs the
// release the window shows.
func TestInstallRecheckFails(t *testing.T) {
h := newHarness(t, Options{})
installed := make(chan string, 2)
h.result = func(context.Context) (*release, error) { return releaseInstalls("2.0.0", installed), nil }
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "A new version of")
h.result = func(context.Context) (*release, error) { return nil, errors.New("offline") }
s.Respond(v.Prompt, actionInstall, false)
v = waitView(t, s, "Ready to Relaunch")
if !strings.Contains(v.Message, "2.0.0 is installed") {
t.Errorf("message %q", v.Message)
}
if got := wait.For(t, "the install", installed); got != "2.0.0" {
t.Errorf("installed %s, want 2.0.0", got)
}
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
if h.u.available != "2.0.0" {
t.Errorf("available %q", h.u.available)
}
if n := h.checks.Load(); n != 2 {
t.Errorf("%d checks, want 2", n)
}
}
// CheckForUpdates while the window offers an update checks again, and the
// window then offers the newer version that came out.
func TestCheckWhileOffering(t *testing.T) {
h := activateAvailabilityHarness(t)
installed := make(chan string, 2)
h.result = func(context.Context) (*release, error) { return releaseInstalls("2.0.0", installed), nil }
done := h.begin(false)
s := h.shown()
waitView(t, s, "A new version of")
if AvailableVersion() != "2.0.0" {
t.Fatalf("available %q", AvailableVersion())
}
h.result = func(context.Context) (*release, error) {
r := releaseInstalls("2.1.0", installed)
r.notes = "- Newer"
return r, nil
}
waitDone(t, h.begin(true)) // returns at once
wait.Until(t, "the window offers 2.1.0", func() bool {
v, _ := s.Current()
return strings.Contains(v.Message, "2.1.0 is now available")
})
v, _ := s.Current()
if !strings.Contains(markdown.HTML(v.Notes), "Newer") {
t.Errorf("notes %q", markdown.HTML(v.Notes))
}
if AvailableVersion() != "2.1.0" {
t.Errorf("available %q", AvailableVersion())
}
wait.Until(t, "the window promoted", s.User)
h.noWindow() // the same window, not another one
s.Respond(v.Prompt, actionInstall, false)
v = waitView(t, s, "Ready to Relaunch")
if got := wait.For(t, "the install", installed); got != "2.1.0" {
t.Errorf("installed %s, want 2.1.0", got)
}
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
}
// A window keeps the language it opened in; after the app's language
// changes, the next window and the menu item take the new one.
func TestLanguageChange(t *testing.T) {
h := newHarness(t, Options{})
proceed := make(chan struct{})
h.result = func(context.Context) (*release, error) {
return newRelease("2.0.0", func(ctx context.Context, progress func(int64, int64)) error {
<-proceed
return nil
}), nil
}
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionInstall, false)
waitView(t, s, "Downloading update…")
locale = func() string { return "zh-Hans" }
close(proceed)
v = waitView(t, s, "Ready to Relaunch")
if got := s.Texts(); got.Title != "Software Update" {
t.Errorf("texts of the open window: %+v", got)
}
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
done = h.begin(true)
s = h.shown()
v = waitView(t, s, "可以重新启动了")
if got := s.Texts(); got.Title != "软件更新" {
t.Errorf("texts of the next window: %+v", got)
}
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
if got := h.u.text().MenuItem; got != "检查更新…" {
t.Errorf("menu item %q", got)
}
}
func TestSkipVersion(t *testing.T) {
h := newHarness(t, Options{})
h.result = func(context.Context) (*release, error) { return newRelease("2.0.0", nil), nil }
done := h.begin(false)
s := h.shown()
if s.User() {
t.Error("a background check counts as the user's")
}
v := waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionSkip, false)
waitDone(t, done)
if got := h.saved().SkippedVersion; got != "2.0.0" {
t.Fatalf("skipped %q", got)
}
// Background checks leave it alone,
waitDone(t, h.begin(false))
h.noWindow()
// the user still sees it,
done = h.begin(true)
s = h.shown()
v = waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionLater, false)
waitDone(t, done)
// and a newer version is offered again.
h.result = func(context.Context) (*release, error) { return newRelease("2.0.1", nil), nil }
done = h.begin(false)
s = h.shown()
waitView(t, s, "A new version of")
s.close()
waitDone(t, done)
}
func TestAutomaticDownloads(t *testing.T) {
h := newHarness(t, Options{})
h.u.update(func(s *state) { s.AutomaticDownloads = true })
installed := make(chan struct{})
h.result = func(context.Context) (*release, error) {
return newRelease("2.0.0", func(context.Context, func(int64, int64)) error {
close(installed)
return nil
}), nil
}
waitDone(t, h.begin(false))
<-installed
h.noWindow()
if h.u.installed == nil {
t.Fatal("not installed")
}
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "Ready to Relaunch")
s.Respond(v.Prompt, actionRelaunch, false)
waitDone(t, done)
if h.relaunches.Load() != 1 || h.checks.Load() != 1 {
t.Errorf("relaunches %d, checks %d", h.relaunches.Load(), h.checks.Load())
}
}
func TestCancelDownload(t *testing.T) {
h := newHarness(t, Options{})
canceled := make(chan error, 1)
h.result = func(context.Context) (*release, error) {
return newRelease("2.0.0", func(ctx context.Context, progress func(int64, int64)) error {
progress(1, 10)
<-ctx.Done()
canceled <- ctx.Err()
return ctx.Err()
}), nil
}
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionInstall, false)
v = waitView(t, s, "Downloading update…")
s.Respond(v.Prompt, actionCancel, false)
waitDone(t, done)
if err := <-canceled; !errors.Is(err, context.Canceled) {
t.Errorf("install ended with %v", err)
}
if h.u.installed != nil {
t.Error("a canceled update counts as installed")
}
}
func TestCheckErrors(t *testing.T) {
h := newHarness(t, Options{})
h.result = func(context.Context) (*release, error) { return nil, errors.New("offline") }
waitDone(t, h.begin(false))
h.noWindow()
if h.u.failed.IsZero() {
t.Error("the failure was not recorded")
}
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "Update Error!")
if v.Detail != "offline" {
t.Errorf("detail %q", v.Detail)
}
s.Respond(v.Prompt, actionOK, false)
waitDone(t, done)
h.result = func(context.Context) (*release, error) {
return newRelease("2.0.0", func(context.Context, func(int64, int64)) error {
return errors.New("bad signature")
}), nil
}
done = h.begin(true)
s = h.shown()
v = waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionInstall, false)
v = waitView(t, s, "Update Error!")
if v.Detail != "bad signature" || !strings.Contains(v.Message, "installing") {
t.Errorf("error view %+v", v)
}
s.Respond(v.Prompt, actionOK, false)
waitDone(t, done)
}
func TestUnavailable(t *testing.T) {
h := newHarness(t, Options{})
enabled = func() bool { return false }
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "Updates Unavailable")
s.Respond(v.Prompt, actionOK, false)
waitDone(t, done)
if h.checks.Load() != 0 {
t.Error("checked for updates")
}
}
func TestResponses(t *testing.T) {
h := newHarness(t, Options{})
h.result = func(context.Context) (*release, error) { return newRelease("2.0.0", nil), nil }
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "A new version of")
s.Respond(v.Prompt-1, actionSkip, false) // an earlier prompt
s.Respond(v.Prompt, actionRelaunch, false) // no such button
s.Respond(v.Prompt, actionLater, false) // counts
s.Respond(v.Prompt, actionSkip, false) // a second response
waitDone(t, done)
if st := h.saved(); st.SkippedVersion != "" {
t.Errorf("skipped %q", st.SkippedVersion)
}
}
func TestPromote(t *testing.T) {
h := newHarness(t, Options{})
proceed := make(chan struct{})
h.result = func(context.Context) (*release, error) {
<-proceed
return nil, nil
}
done := h.begin(false)
for h.checks.Load() == 0 {
time.Sleep(time.Millisecond)
}
h.noWindow()
waitDone(t, h.begin(true)) // returns at once
s := h.shown()
waitView(t, s, "Checking for updates…")
close(proceed)
v := waitView(t, s, "You’re up to date!")
s.Respond(v.Prompt, actionOK, false)
waitDone(t, done)
if h.checks.Load() != 1 {
t.Errorf("%d checks", h.checks.Load())
}
}
func TestCancelCheck(t *testing.T) {
h := newHarness(t, Options{})
h.result = func(ctx context.Context) (*release, error) {
<-ctx.Done()
return nil, ctx.Err()
}
done := h.begin(true)
s := h.shown()
v := waitView(t, s, "Checking for updates…")
s.Respond(v.Prompt, actionCancel, false)
waitDone(t, done)
if !h.u.failed.IsZero() {
t.Error("canceling counts as a failure")
}
}
func TestPreferences(t *testing.T) {
h := newHarness(t, Options{DisableAutomaticChecks: true})
active.Store(h.u)
t.Cleanup(func() { active.Store(nil) })
if AutomaticChecks() || AutomaticDownloads() || !LastCheck().IsZero() {
t.Fatal("wrong defaults")
}
SetAutomaticChecks(true)
SetAutomaticDownloads(true)
if !AutomaticChecks() || !AutomaticDownloads() {
t.Fatal("not set")
}
// Another run reads them back.
u := newUpdater(Options{DisableAutomaticChecks: true}, nil)
u.load()
if !u.automaticChecks() || !u.state.AutomaticDownloads {
t.Errorf("state %+v", u.state)
}
if u := newUpdater(Options{}, nil); u.opts.Interval != 24*time.Hour {
t.Errorf("interval %v", u.opts.Interval)
}
}
func TestOnChange(t *testing.T) {
h := newHarness(t, Options{})
active.Store(h.u)
t.Cleanup(func() { active.Store(nil) })
changes := make(chan struct{}, 10)
off := OnChange(func() { changes <- struct{}{} })
told := func(want bool, what string) {
t.Helper()
wait := 50 * time.Millisecond
if want {
wait = 5 * time.Second
}
select {
case <-changes:
if !want {
t.Errorf("%s: told of a change", what)
}
case <-time.After(wait):
if want {
t.Errorf("%s: not told", what)
}
}
}
SetAutomaticDownloads(true)
told(true, "SetAutomaticDownloads")
SetAutomaticDownloads(true)
told(false, "the same value")
waitDone(t, h.begin(false))
told(true, "a check")
h.result = func(context.Context) (*release, error) { return nil, errors.New("offline") }
waitDone(t, h.begin(false))
told(false, "a failed check")
h.result = func(context.Context) (*release, error) { return newRelease("2.0.0", nil), nil }
done := h.begin(true)
s := h.shown()
told(true, "the user's check")
v := waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionSkip, true)
waitDone(t, done)
told(true, "Skip This Version")
off()
SetAutomaticDownloads(false)
told(false, "a function removed")
}
func TestOnInstalled(t *testing.T) {
h := newHarness(t, Options{})
active.Store(h.u)
t.Cleanup(func() { active.Store(nil) })
installs := make(chan struct{}, 10)
off := OnInstalled(func() { installs <- struct{}{} })
told := func(want int, what string) {
t.Helper()
for range want {
select {
case <-installs:
case <-time.After(wait.Guard):
t.Fatalf("%s: not told", what)
}
}
// The calls run in a goroutine of their own: a call that should
// not happen may come later, and then the next count sees it.
if len(installs) > 0 {
t.Errorf("%s: told %d more times", what, len(installs))
}
}
// A failed install does not count.
h.result = func(context.Context) (*release, error) {
return newRelease("2.0.0", func(context.Context, func(int64, int64)) error { return errors.New("disk full") }), nil
}
done := h.begin(true)
s := h.shown()
s.Respond(waitView(t, s, "A new version of").Prompt, actionInstall, false)
s.Respond(waitView(t, s, "Update Error").Prompt, actionOK, false)
waitDone(t, done)
told(0, "a failed install")
// Installed in the background.
h.result = func(context.Context) (*release, error) { return newRelease("2.0.0", nil), nil }
h.u.update(func(s *state) { s.AutomaticDownloads = true })
waitDone(t, h.begin(false))
told(1, "an automatic install")
// Only once: the update installed runs at the next launch.
done = h.begin(true)
s = h.shown()
s.Respond(waitView(t, s, "Ready to Relaunch").Prompt, actionLater, false)
waitDone(t, done)
told(0, "Ready to Relaunch again")
// Installed by the user, after a function was removed.
h.u.installed = nil
off2 := OnInstalled(func() { installs <- struct{}{} })
off()
done = h.begin(true)
s = h.shown()
s.Respond(waitView(t, s, "A new version of").Prompt, actionInstall, false)
s.Respond(waitView(t, s, "Ready to Relaunch").Prompt, actionLater, false)
waitDone(t, done)
told(1, "the user's install")
off2()
}
func TestSchedule(t *testing.T) {
h := newHarness(t, Options{})
h.u.running = true
h.u.schedule()
if h.u.timer == nil {
t.Fatal("no check scheduled")
}
h.u.update(func(s *state) { f := false; s.AutomaticChecks = &f })
h.u.schedule()
if h.u.timer != nil {
t.Error("scheduled with automatic checks off")
}
}
func TestCheckAtLaunch(t *testing.T) {
h := newHarness(t, Options{})
defer func(w time.Duration) { firstCheckWait = w }(firstCheckWait)
firstCheckWait = time.Millisecond
// The last launch checked an hour ago; a version came out since.
h.u.update(func(s *state) { s.LastCheck = now().Add(-time.Hour) })
h.result = func(context.Context) (*release, error) { return newRelease("2.0.0", nil), nil }
h.u.running = true
h.u.schedule()
s := h.shown()
v := waitView(t, s, "A new version of")
s.Respond(v.Prompt, actionLater, false)
wait.Until(t, "the next check scheduled", func() bool {
h.u.mu.Lock()
defer h.u.mu.Unlock()
return h.u.session == nil && h.u.timer != nil
})
// Then an interval after it, not at once again.
time.Sleep(20 * time.Millisecond)
if n := h.checks.Load(); n != 1 {
t.Errorf("%d checks, want 1", n)
}
}
func TestNextCheck(t *testing.T) {
now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
day := 24 * time.Hour
for _, tc := range []struct {
name string
last, failed time.Time
interval time.Duration
want time.Time
}{
{"never checked", time.Time{}, time.Time{}, day, time.Time{}.Add(day)},
{"checked an hour ago", now.Add(-time.Hour), time.Time{}, day, now.Add(23 * time.Hour)},
{"due check failed", now.Add(-2 * day), now.Add(-time.Minute), day, now.Add(59 * time.Minute)},
{"a check of the user failed", now.Add(-time.Hour), now.Add(-time.Minute), day, now.Add(23 * time.Hour)},
{"short interval", now.Add(-time.Hour), now, 10 * time.Minute, now.Add(10 * time.Minute)},
{"clock set back", now.Add(time.Hour), time.Time{}, day, now.Add(day)},
} {
if got := nextCheck(tc.last, tc.failed, tc.interval, now); !got.Equal(tc.want) {
t.Errorf("%s: %v, want %v", tc.name, got, tc.want)
}
}
}
func TestPage(t *testing.T) {
fr := newText("fr-FR", map[string]Strings{"fr": {ReleaseNotes: "<b>Notes</b>"}})
v := view{Title: "</script><script>alert(1)</script>", Notes: markdown.Parse("A **bug**"), Buttons: fr.ok()}
p := page(fr.texts(), "data:image/png;base64,AAAA", v)
if strings.Contains(p, "{{") {
t.Error("a placeholder was left")
}
if strings.Contains(p, "</script><script>alert") {
t.Error("the view is not escaped")
}
i := strings.Index(p, "'nonce-")
nonce := p[i+7 : i+7+strings.IndexByte(p[i+7:], '\'')]
if len(nonce) < 20 || !strings.Contains(p, `<script nonce="`+nonce+`">`) {
t.Errorf("nonce %q", nonce)
}
if !strings.Contains(p, `src="data:image/png;base64,AAAA"`) {
t.Error("no icon")
}
for _, want := range []string{
`<html lang="fr" dir="ltr">`, "<title>Mise à jour de logiciels</title>", "&lt;b&gt;Notes&lt;/b&gt;",
`"notes":"\u003cp\u003eA \u003cstrong\u003ebug\u003c/strong\u003e\u003c/p\u003e"`, // the notes in HTML, escaped
} {
if !strings.Contains(p, want) {
t.Errorf("the page lacks %s", want)
}
}
}
+143
View File
@@ -0,0 +1,143 @@
package updater
import (
"context"
"crypto/rand"
_ "embed"
"encoding/base64"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"html"
"strings"
"github.com/egoist/mygo"
"github.com/egoist/mygo/plugins/updater/internal/frontend"
"github.com/egoist/mygo/plugins/updater/internal/markdown"
)
//go:embed page.html
var pageHTML string
// openWindow creates the update window of s as a web page. It shows once
// its page is ready, in front when the user asked for the check.
func openWindow(s *session) {
win := s.NewWindow(nil)
win.Page().OnWillNavigate(func(e *mygo.NavigateEvent) {
// Links of the release notes open in the browser.
e.PreventDefault()
if e.UserInitiated && markdown.SafeURL(e.URL) {
go mygo.Shell.OpenExternal(e.URL)
}
})
user := s.User()
win.OnReadyToShow(func() { frontend.Show(win, user) })
v, _ := s.Current()
win.Page().LoadHTML(page(s.Texts(), s.u.iconURL(), v), "")
}
// pageView is a view as the page gets it, with the notes in HTML.
type pageView struct {
view
Notes string `json:"notes,omitzero"`
}
func newPageView(v view) pageView { return pageView{v, markdown.HTML(v.Notes)} }
// page returns the page of the update window with the texts t, showing v
// until the page watches the session.
func page(t frontend.Texts, icon string, v view) string {
nonce := make([]byte, 16)
rand.Read(nonce)
initial, _ := json.Marshal(newPageView(v), jsontext.EscapeForHTML(true), jsontext.EscapeForJS(true))
dir := "ltr"
if t.RTL {
dir = "rtl"
}
light, dark := frontend.Background()
return strings.NewReplacer(
"{{lang}}", html.EscapeString(t.Lang),
"{{dir}}", dir,
"{{background}}", light,
"{{darkBackground}}", dark,
"{{title}}", html.EscapeString(t.Title),
"{{releaseNotes}}", html.EscapeString(t.ReleaseNotes),
"{{automaticDownloads}}", html.EscapeString(t.AutomaticDownloads),
"{{nonce}}", base64.StdEncoding.EncodeToString(nonce),
"{{icon}}", icon,
"{{view}}", string(initial),
).Replace(pageHTML)
}
// iconURL returns the icon of the update window as a data URL, or "".
func (u *updater) iconURL() string {
png := u.icon()
if png == nil {
return ""
}
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(png)
}
// service is what the update window's page calls.
type service struct{ u *updater }
var errNotUpdateWindow = errors.New("only the update window may call the updater")
// session returns the session whose window made the call.
func (sv *service) session(ctx context.Context) (*session, error) {
win := mygo.CallerWindow(ctx)
sv.u.mu.Lock()
s := sv.u.session
sv.u.mu.Unlock()
if s == nil || win == nil {
return nil, errNotUpdateWindow
}
s.mu.Lock()
defer s.mu.Unlock()
if s.win != win {
return nil, errNotUpdateWindow
}
return s, nil
}
// Watch streams the views of the session to the update window.
func (sv *service) Watch(ctx context.Context, views *mygo.Channel[pageView]) error {
s, err := sv.session(ctx)
if err != nil {
return err
}
for {
v, changed := s.Current()
if err := views.Send(newPageView(v)); err != nil {
return nil // the page went away
}
select {
case <-changed:
case <-ctx.Done():
return nil
}
}
}
// Fit gives the window the width its buttons need, when they need more
// than the usual width, and a status view the height of its text, which
// both depend on the language and the platform's fonts.
func (sv *service) Fit(ctx context.Context, width, height int) error {
s, err := sv.session(ctx)
if err != nil {
return err
}
s.Fit(width, height)
return nil
}
// Respond answers the prompt of a view with a button, and tells whether
// updates may be installed automatically from now on.
func (sv *service) Respond(ctx context.Context, prompt int, a action, automaticDownloads bool) error {
s, err := sv.session(ctx)
if err != nil {
return err
}
s.Respond(prompt, a, automaticDownloads)
return nil
}