From a57f0bd54a7ef3f970bc9677d5df0d7169cfb451 Mon Sep 17 00:00:00 2001 From: omartelo Date: Thu, 3 Dec 2026 17:43:59 -0300 Subject: [PATCH 1/2] Screens that change by a click, while a journey is tried A field's error had to be a second screen, which lost what was typed in the first. A screen declares its state, set changes it on a click, and When has its children only while the state is the one it names. A change is a step of the path; render_screen draws a screen in any state. --- CHANGELOG.md | 6 ++ DESIGN.md | 4 ++ app.gockup | 4 +- board.go | 3 + builtins.go | 8 +++ docs/AUTHORING.md | 3 + docs/GUIDE.md | 18 +++++ docs/ceilings.md | 3 + dsl/dsl.go | 15 +++- dsl/fragment.go | 6 +- dsl/state.go | 65 ++++++++++++++++++ dsl/state_test.go | 37 ++++++++++ gockup.go | 171 ++++++++++++++++++++++++++++++++++++++++------ mcp.go | 55 ++++++++++----- state_test.go | 155 +++++++++++++++++++++++++++++++++++++++++ systems_test.go | 2 +- trial.go | 64 +++++++++++++---- trial_test.go | 6 +- 18 files changed, 567 insertions(+), 58 deletions(-) create mode 100644 dsl/state.go create mode 100644 dsl/state_test.go create mode 100644 state_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b19a7d..76ce257 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Screens that change by a click**: while a journey is tried, a click can show a field's error, open a menu or go to a + form's next step on the same screen, with what was typed still there. A screen declares its `state`, `set` changes it + and `When` shows what goes with it; your model writes them, and `render_screen` draws a screen in any state. + ## [0.4.0] - 2026-12-03 ### Added diff --git a/DESIGN.md b/DESIGN.md index 0d22f93..442ef53 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -144,6 +144,10 @@ Present shows screens; trying a journey is using the app, to find where it fails stays as it was left. There is no next: only the app's own links lead on. - What is typed stays on the way back; starting over clears it. A step back undoes the step, the app's own back (`goto=back`) is one more. +- A click that changes the screen's state (`set`) is a step too, on the same screen: "With error=yes: you are here", and + the state beside the screen's name in the bottom pill. Only what is not as the screen starts is told. The state lasts + from a screen to the next; a step back undoes it and starting over clears it. The board and Present show every screen + as it starts. - At the end, the journey's `to` or a screen nothing leads out of, once through its `via`, the path says "Got to Welcome in 4 steps" and **what it showed**: the clicks that did nothing, in yellow, and the screens of its pages no click opens, in blue. Three names at most, then "and 2 more"; with neither, one green line says so. diff --git a/app.gockup b/app.gockup index cedcd11..bea2cb4 100644 --- a/app.gockup +++ b/app.gockup @@ -1025,11 +1025,11 @@ fragment TrialFinding text="" where="" color="#ffcf4a" { } // under the app being tried: a step back, where it is, start over, the path shown or not -fragment TrialBar name="" back="#dccfc7" path="#ff9a80" pathBg="#3a2019" { +fragment TrialBar name="" state="" back="#dccfc7" path="#ff9a80" pathBg="#3a2019" { Pill top=4 bottom=4 left=4 right=4 { Flex axis=horizontal align=center spacing=4 { Tip text="Step back" key="" { Box radius=999 goto="try-back" { Inset all=6 { Image src="back.svg" width=16 color=$back } } } - Inset left=4 right=4 { Text text=$name bold=true } + Inset left=4 right=4 { Flex axis=horizontal align=center spacing=6 { Text text=$name bold=true Text text=$state size=12 color="#9c8d84" } } Tip text="Start over" key="" { Box radius=999 goto="try-restart" { Inset all=6 { Image src="restart.svg" width=16 color="#dccfc7" } } } Tip text="Path" key="" { Box color=$pathBg radius=999 goto="try-path" { Inset all=6 { Image src="route.svg" width=16 color=$path } } } } diff --git a/board.go b/board.go index 939d8a1..48df4f0 100644 --- a/board.go +++ b/board.go @@ -218,6 +218,9 @@ func contentPrint(reg *Registry, sc *dsl.Screen, assets map[string][]byte) uint6 maphash.WriteComparable(&h, reg) maphash.WriteComparable(&h, image.Pt(sc.Width, sc.Height)) maphash.WriteComparable(&h, sc.Theme) + for _, p := range sc.State { + maphash.WriteComparable(&h, [2]string{p.Name, p.Value.Plain()}) + } var walk func(n *dsl.Node) walk = func(n *dsl.Node) { maphash.WriteComparable(&h, n.Type) diff --git a/builtins.go b/builtins.go index be0e0e4..a9b0b9c 100644 --- a/builtins.go +++ b/builtins.go @@ -11,6 +11,8 @@ import ( "gioui.org/text" "gioui.org/unit" "gioui.org/widget/material" + + "github.com/lichdotdev/gockup/dsl" ) func registerBuiltins(r *Registry) { @@ -156,6 +158,12 @@ func registerBuiltins(r *Registry) { return stacked(c.Children())(gtx) }, }) + r.Register(dsl.WhenNode, Component{ + Doc: "its children, laid out by its parent as if written there, only while the screen's states have these values: " + + "When error=yes { … }, with state error=no at the screen's start", + Children: true, + Layout: func(c *Ctx) layout.Dimensions { return stacked(c.Children())(c.Gtx) }, + }) r.Register("Spacer", Component{ Doc: "empty space", Props: []Prop{ diff --git a/docs/AUTHORING.md b/docs/AUTHORING.md index e9947eb..5573ec5 100644 --- a/docs/AUTHORING.md +++ b/docs/AUTHORING.md @@ -9,6 +9,9 @@ What a mockup of more than one screen needs, learned building lich's screens wit - A screen per **state** of a flow (Session → Menu → Confirm); `goto="Screen"` on the node you would click links them, so the app walks the flow; `goto=back` on a back arrow or a Cancel opens, while a journey is tried, wherever the user came from. +- A state the user should see on the board, or that looks like another screen, is a screen of its own. One that keeps + what was typed (a field's error, an open menu, a step of a form) is a `state` with `When` and `set` in the same screen: + going to another screen starts its fields empty. - A **journey** per thing the user came to do (`journey "Create account" from="Login" to="Welcome"`). The board shows the shortest way there: `via="Register"` takes it through a screen that one skips. Trying it tells the clicks that did nothing and the screens no click opens: link every step, the ways out too. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 241097a..ca73c75 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -36,6 +36,24 @@ were working (there, `goto=back` opens the screen the user came from), `note "Wh leaves context on the board for whoever reads the project next, the model included, `theme=` on a screen picks a look. [AUTHORING.md](AUTHORING.md) is the guide for mockups of many screens. +A screen can also change in place while a journey is tried. `state` declares what can change and how it starts, `set` +changes it on a click, and `When` has its children only while the states have the values it lists: + +``` +screen "Register" { + state error=no + Flex axis=vertical spacing=16 { + Editor hint="E-mail" + When error=yes { Caption text="That is not an e-mail yet" } + When error=no { Button text="Create account" set="error=yes" } + When error=yes { Button text="Create account" goto="Welcome" } + } +} +``` + +There are no expressions and nothing reads what is typed: a journey is played, not programmed. The board shows the screen +as it starts; `render_screen` takes the state to draw it in. + ## Projects A project holds screens and fragments (its reusable components) and draws with one design system, the one diff --git a/docs/ceilings.md b/docs/ceilings.md index d003728..b080bac 100644 --- a/docs/ceilings.md +++ b/docs/ceilings.md @@ -47,6 +47,9 @@ file is the trap alone. - **Where a goto is on its screen comes from Gio's semantic tree** (`Session.gotoAreas`): Gio tells no widget its place, so the screen is laid out once more, each goto labelled. It is as the screen opens, so on a live frame scrolled by hand the ring stays where the goto was. + A goto in a `When` not shown as the screen starts has no place: its arrow leaves from the frame's edge, with no ring. +- **A `When` is never laid out**: `Ctx.Children` gives its parent what is in it, in its place, or nothing. So it takes no + `weight`, `goto` or `set`, cannot be a screen's root, and picking one in the layers outlines nothing. - **A click that did nothing is told by the state its node keeps** (`Session.answers`): a leaf that keeps only a `widget.Clickable`, or nothing, did nothing without a goto. An adapter with a click type of its own passes for one that answers, so its dead buttons are not told; a bare `Box` or `Spacer` never is. diff --git a/dsl/dsl.go b/dsl/dsl.go index c6e321d..9c3daec 100644 --- a/dsl/dsl.go +++ b/dsl/dsl.go @@ -99,6 +99,8 @@ type Screen struct { Width, Height int // Theme names one of the registry's themes; "" is its default look. Theme string + // State are the names the screen's Whens look at, with what each starts as. + State []Prop Root *Node Line int // Source is the declaration's text, the comments above it included. @@ -474,7 +476,13 @@ func (p *parser) screen() (*Screen, error) { return nil, &Error{pr.Line, fmt.Sprintf("unknown screen property %q", pr.Name)} } } - children, err := p.block() + if _, err := p.expect(tLBrace, "{"); err != nil { + return nil, err + } + if s.State, err = p.state(); err != nil { + return nil, err + } + children, err := p.nodes() if err != nil { return nil, err } @@ -489,6 +497,11 @@ func (p *parser) block() ([]*Node, error) { if _, err := p.expect(tLBrace, "{"); err != nil { return nil, err } + return p.nodes() +} + +// nodes reads the rest of a block, its closing brace included. +func (p *parser) nodes() ([]*Node, error) { var nodes []*Node for p.peek().kind != tRBrace { n, err := p.node() diff --git a/dsl/fragment.go b/dsl/fragment.go index 68998ec..e28b6bb 100644 --- a/dsl/fragment.go +++ b/dsl/fragment.go @@ -21,7 +21,9 @@ const Back = "back" func IsBack(v Value) bool { return v.Kind == Ident && v.Str == Back } // IsUniversal reports whether every node takes the prop, whatever its type. -func IsUniversal(name string) bool { return name == WeightProp || name == GotoProp } +func IsUniversal(name string) bool { + return name == WeightProp || name == GotoProp || name == SetProp +} // SlotNode marks where a fragment places the children of the call. const SlotNode = "Slot" @@ -42,7 +44,7 @@ type scope struct { func expandFile(f *File) error { e := &expander{frags: map[string]*Fragment{}} for _, fr := range f.Fragments { - if fr.Name == SlotNode || fr.Name == "screen" || fr.Name == "fragment" { + if fr.Name == SlotNode || fr.Name == WhenNode || fr.Name == "screen" || fr.Name == "fragment" { return &Error{fr.Line, fmt.Sprintf("%q is reserved and cannot name a fragment", fr.Name)} } if prev, dup := e.frags[fr.Name]; dup { diff --git a/dsl/state.go b/dsl/state.go new file mode 100644 index 0000000..81c35df --- /dev/null +++ b/dsl/state.go @@ -0,0 +1,65 @@ +package dsl + +import ( + "fmt" + "strings" +) + +// SetProp is accepted on any node: a click on it, while a journey is tried, +// gives one of the screen's states a value, set="error=yes". +const SetProp = "set" + +// WhenNode has its children only while the screen's states have the values +// it is written with, When error=yes { … }. +const WhenNode = "When" + +// Plain is the value as text, the way states compare. +func (v Value) Plain() string { + if v.Kind == Number { + return v.String() + } + return v.Str +} + +// ParseSet reads a set's value, the state's name and what it becomes. +func ParseSet(s string) (name, value string, ok bool) { + name, value, ok = strings.Cut(s, "=") + return name, value, ok && name != "" +} + +// StateOf is what the screen's state name starts as. +func (s *Screen) StateOf(name string) (value string, ok bool) { + for _, p := range s.State { + if p.Name == name { + return p.Value.Plain(), true + } + } + return "", false +} + +// state reads the states a screen's body starts with, state error=no step=1. +func (p *parser) state() ([]Prop, error) { + var all []Prop + for p.peek().kind == tIdent && p.peek().text == "state" { + kw := p.next() + props, err := p.props() + if err != nil { + return nil, err + } + if len(props) == 0 { + return nil, &Error{kw.line, "state needs a name and the value it starts with: state error=no"} + } + for _, pr := range props { + if pr.Value.Kind == Param { + return nil, &Error{pr.Line, fmt.Sprintf("state %s must start with a value, got %s", pr.Name, pr.Value)} + } + for _, had := range all { + if had.Name == pr.Name { + return nil, &Error{pr.Line, fmt.Sprintf("duplicate state %q", pr.Name)} + } + } + all = append(all, pr) + } + } + return all, nil +} diff --git a/dsl/state_test.go b/dsl/state_test.go new file mode 100644 index 0000000..31220d3 --- /dev/null +++ b/dsl/state_test.go @@ -0,0 +1,37 @@ +package dsl + +import ( + "strings" + "testing" +) + +func TestState(t *testing.T) { + f, err := Parse(`screen "A" { state error=no step=1 +state plan="Pro plan" +Flex { When error=yes step=2 { Box set="error=no" } } }`) + if err != nil { + t.Fatal(err) + } + sc := f.Screens[0] + for name, want := range map[string]string{"error": "no", "step": "1", "plan": "Pro plan"} { + if got, ok := sc.StateOf(name); !ok || got != want { + t.Errorf("state %s = %q, %v; want %q", name, got, ok, want) + } + } + if sc.Root.Type != "Flex" || sc.Root.Children[0].Type != WhenNode { + t.Errorf("root = %+v", sc.Root) + } + for src, want := range map[string]string{ + `screen "A" { state Box }`: "state needs a name", + `screen "A" { state a=1 a=2 Box }`: `duplicate property "a"`, + `screen "A" { state a=1 state a=2 Box }`: `duplicate state "a"`, + `screen "A" { state a=$b Box }`: "must start with a value", + `screen "A" { state a=1 }`: "exactly one root node", + `fragment When { Box } screen "A" { Box }`: "reserved", + `fragment F set="" { Box } screen "A" { Box }`: "reserved", + } { + if _, err := Parse(src); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%s: err = %v, want %q", src, err, want) + } + } +} diff --git a/gockup.go b/gockup.go index 8ec953e..1483a22 100644 --- a/gockup.go +++ b/gockup.go @@ -7,6 +7,7 @@ import ( "image" "image/color" "reflect" + "slices" "sort" "strconv" "strings" @@ -214,8 +215,16 @@ func Errors(probs []Problem) []Problem { func (r *Registry) Validate(f *dsl.File) []Problem { var probs []Problem + var on *dsl.Screen var walk func(n *dsl.Node) walk = func(n *dsl.Node) { + if n.Type == dsl.WhenNode { + probs = append(probs, checkWhen(on, n)...) + for _, ch := range n.Children { + walk(ch) + } + return + } c, ok := r.comps[n.Type] if !ok { probs = append(probs, Problem{Line: n.Line, Msg: fmt.Sprintf("unknown component %q", n.Type), File: n.File}) @@ -234,6 +243,12 @@ func (r *Registry) Validate(f *dsl.File) []Problem { } continue } + if p.Name == dsl.SetProp { + if msg := checkSet(on, p.Value); msg != "" { + probs = append(probs, Problem{Line: p.Line, Msg: msg, File: p.File}) + } + continue + } if !ok { continue } @@ -269,6 +284,10 @@ func (r *Registry) Validate(f *dsl.File) []Problem { } } for _, s := range f.Screens { + on = s + if s.Root.Type == dsl.WhenNode { + probs = append(probs, Problem{Line: s.Root.Line, Msg: fmt.Sprintf("screen %q cannot be a When: put it inside a layout", s.Name), File: s.Root.File}) + } walk(s.Root) } for _, n := range f.Notes { @@ -288,6 +307,39 @@ func (r *Registry) Validate(f *dsl.File) []Problem { return probs } +func checkWhen(on *dsl.Screen, n *dsl.Node) []Problem { + var probs []Problem + if len(n.Props) == 0 { + probs = append(probs, Problem{Line: n.Line, Msg: "When needs a state and its value: When error=yes", File: n.File}) + } + for _, p := range n.Props { + if dsl.IsUniversal(p.Name) { + probs = append(probs, Problem{Line: p.Line, Msg: p.Name + " goes on what is inside a When, not on it", File: p.File}) + } else if _, ok := on.StateOf(p.Name); !ok { + probs = append(probs, Problem{Line: p.Line, Msg: noState(on, p.Name), File: p.File}) + } + } + return probs +} + +func checkSet(on *dsl.Screen, v dsl.Value) string { + if v.Kind == dsl.String && v.Str == "" { + return "" // the default of a fragment's optional one + } + name, _, ok := dsl.ParseSet(v.Str) + if v.Kind != dsl.String || !ok { + return fmt.Sprintf("set must be a state and its value, \"error=yes\", got %s", v) + } + if _, ok := on.StateOf(name); !ok { + return noState(on, name) + } + return "" +} + +func noState(on *dsl.Screen, name string) string { + return fmt.Sprintf("screen %q has no state %q: declare it first in its body, state %s=no", on.Name, name, name) +} + func checkValue(spec *Prop, v dsl.Value) string { switch spec.Type { case String: @@ -351,11 +403,22 @@ type Session struct { back func() // idle, when set, is called with what a click landed on and did nothing. idle func(n *dsl.Node) - // clicked is the node whose goto runs; went tells one already ran this frame, and + // changed, when set, makes the nodes with a set change the screen's states, + // and is called after a click that did and opened no screen. + changed func() + // vars are the states changed, by screen; the others are as declared. + vars map[string]map[string]string + // screen is the one being laid out, and hidden the paths of its Whens not shown. + screen *dsl.Screen + hidden []string + // clicked is the node whose goto or set runs. This frame, acted tells one + // did, wrote that a set changed a state, went that a goto already ran, and // hit is the leaf a click landed on, with its path. clicked *dsl.Node // measured are the gotos gotoAreas is after, by node. measured map[*dsl.Node]int + acted bool + wrote bool went bool hit *dsl.Node hitPath string @@ -405,16 +468,20 @@ func (s *Session) Layout(gtx layout.Context, sc *dsl.Screen) layout.Dimensions { bg, env = th.Background, &envEntry{key: ThemeKey{}, val: th.Value} } paint.FillShape(gtx.Ops, bg, clip.Rect{Max: gtx.Constraints.Max}.Op()) - s.went, s.hit = false, nil + s.screen, s.hidden = sc, s.hidden[:0] + s.acted, s.wrote, s.went, s.hit = false, false, false, nil dims := s.layoutNode(gtx, sc.Root, sc.Root.Type, env) - if s.hit != nil && !s.went && !s.answers(s.hitPath) { + if s.hit != nil && !s.acted && !s.answers(s.hitPath) { s.idle(s.hit) } + if s.wrote && !s.went { + s.changed() + } // shortcut: state not requested this frame is dropped, so an adapter that // skips laying out a child loses its state; track liveness per subtree if - // conditional or virtualized layouts appear. + // virtualized layouts appear. A When's comes back with what was typed in it. for k, e := range s.cur { - if e.frame != s.frame { + if e.frame != s.frame && !slices.ContainsFunc(s.hidden, func(p string) bool { return strings.HasPrefix(k, p) }) { delete(s.cur, k) } } @@ -427,13 +494,12 @@ func (s *Session) layoutNode(gtx layout.Context, n *dsl.Node, path string, env * return errorBox(gtx, fmt.Sprintf("unknown component %q", n.Type)) } ctx := &Ctx{Gtx: gtx, node: n, comp: c, path: path, sess: s, env: env} - lay := c.Layout - if v, ok := n.Prop(GotoProp); ok && v.Kind == dsl.String && v.Str != "" && s.Goto != nil { - lay = func(c *Ctx) layout.Dimensions { return s.layoutGoto(c, func() { s.Goto(v.Str) }) } - } else if dsl.IsBack(v) && s.back != nil { - lay = func(c *Ctx) layout.Dimensions { return s.layoutGoto(c, s.back) } + var dims layout.Dimensions + if click := s.clickOf(n); click != nil { + dims = s.layoutClick(ctx, click) + } else { + dims = c.Layout(ctx) } - dims := lay(ctx) if i, ok := s.measured[n]; ok { markArea(gtx.Ops, i, dims.Size) } @@ -460,6 +526,58 @@ var highlightColor = color.NRGBA{R: 0xff, G: 0x5f, B: 0x3d, A: 0xff} type gotoClick struct{ pressed bool } +// clickOf is what a click on n does, its set before its goto; nil for nothing. +func (s *Session) clickOf(n *dsl.Node) func() { + var open func() + if v, ok := n.Prop(GotoProp); ok && v.Kind == dsl.String && v.Str != "" && s.Goto != nil { + open = func() { s.Goto(v.Str) } + } else if dsl.IsBack(v) && s.back != nil { + open = s.back + } + set, _ := n.Prop(dsl.SetProp) + name, value, ok := dsl.ParseSet(set.Str) + if !ok || s.changed == nil { + if open == nil { + return nil + } + return func() { open(); s.went = true } + } + return func() { + s.setState(name, value) + if open != nil { + open() + s.went = true + } + } +} + +func (s *Session) setState(name, value string) { + if s.stateNow(s.screen, name) == value { + return + } + if s.vars == nil { + s.vars = map[string]map[string]string{} + } + if s.vars[s.screen.Name] == nil { + s.vars[s.screen.Name] = map[string]string{} + } + s.vars[s.screen.Name][name] = value + s.wrote = true +} + +func (s *Session) stateNow(sc *dsl.Screen, name string) string { + if v, ok := s.vars[sc.Name][name]; ok { + return v + } + v, _ := sc.StateOf(name) + return v +} + +// shows reports whether a When's states have its values. +func (s *Session) shows(when *dsl.Node) bool { + return !slices.ContainsFunc(when.Props, func(p dsl.Prop) bool { return s.stateNow(s.screen, p.Name) != p.Value.Plain() }) +} + // watchClick tells the clicks on a leaf, which its own handlers get too. type watchClick struct{ pressed bool } @@ -507,9 +625,9 @@ func (s *Session) answers(path string) bool { return false } -// layoutGoto lays the node out and lays a click area over it that lets the +// layoutClick lays the node out and lays a click area over it that lets the // node's own pointer handlers see the same events. -func (s *Session) layoutGoto(c *Ctx, open func()) layout.Dimensions { +func (s *Session) layoutClick(c *Ctx, do func()) layout.Dimensions { click := State[gotoClick](c, nil) for { ev, ok := c.Gtx.Event(pointer.Filter{Target: click, Kinds: pointer.Press | pointer.Release | pointer.Cancel}) @@ -522,9 +640,8 @@ func (s *Session) layoutGoto(c *Ctx, open func()) layout.Dimensions { click.pressed = e.Source != pointer.Mouse || e.Buttons.Contain(pointer.ButtonPrimary) case pointer.Release: if click.pressed { - s.clicked = c.node - open() - s.went = true + s.clicked, s.acted = c.node, true + do() } click.pressed = false case pointer.Cancel: @@ -659,18 +776,30 @@ type Child struct { } func (c *Ctx) Children() []Child { - kids := make([]Child, len(c.node.Children)) + return c.childrenOf(make([]Child, 0, len(c.node.Children)), c.node, c.path) +} + +// childrenOf appends n's children, those of a When shown in its place. +func (c *Ctx) childrenOf(kids []Child, parent *dsl.Node, at string) []Child { env := c.env - for i, n := range c.node.Children { - path := fmt.Sprintf("%s/%d:%s", c.path, i, n.Type) + for i, n := range parent.Children { + path := fmt.Sprintf("%s/%d:%s", at, i, n.Type) + if n.Type == dsl.WhenNode { + if c.sess.shows(n) { + kids = c.childrenOf(kids, n, path) + } else { + c.sess.hidden = append(c.sess.hidden, path+"/") + } + continue + } var w float32 if v, ok := n.Prop(WeightProp); ok && v.Kind == dsl.Number { w = float32(v.Num) } - kids[i] = Child{ + kids = append(kids, Child{ Widget: func(gtx layout.Context) layout.Dimensions { return c.sess.layoutNode(gtx, n, path, env) }, Weight: w, - } + }) } return kids } diff --git a/mcp.go b/mcp.go index f862ffa..5119d8c 100644 --- a/mcp.go +++ b/mcp.go @@ -59,6 +59,19 @@ screen "Name" width=360 height=640 theme=dark { // size in dp, defaults 360x64 alone keeps its aspect, color="#rrggbb" repaints a one-color icon. - goto="Screen" on any node makes it open that screen when clicked in the app or preview, to walk a flow. goto=back, an identifier, opens the screen the user came from while a journey is tried. +- A screen can change by a click while a journey is tried, with no second screen for the state it goes to: + screen "Register" { + state error=no + Flex axis=vertical spacing=16 { + Editor hint="E-mail" + When error=yes { Caption text="That is not an e-mail yet" } + When error=no { Button text="Create account" set="error=yes" } + When error=yes { Button text="Create account" goto="Welcome" } + } + } + state, first in the screen's body, declares the names and what each starts as. set="name=value" on any node gives one + a value; When has its children only while the names it lists have those values. Nothing else: no expressions, and + what is typed is not read. The board, and render_screen without state, show the screen as it starts. - Journeys are the ways through the app the user tries as if it were working, one item each: journey "Create account" from="Login" via="Register" to="Welcome" from is where it starts, to the screen it is meant to get to (left out, one nothing leads out of). The board shows @@ -342,6 +355,7 @@ var ( "project": projectArg, "screen": map[string]any{"type": "string", "description": "screen name; all screens when omitted"}, "scale": map[string]any{"type": "number", "description": "pixels per dp, default 2"}, + "state": map[string]any{"type": "object", "additionalProperties": map[string]any{"type": "string"}, "description": "the screen's states to draw it in, {\"error\": \"yes\"}; the others are as it starts. Needs screen."}, }, "project")}, {"name": "render_overview", "description": "Render every screen of a project side by side on one PNG, to check a whole flow at once.", "inputSchema": schema(map[string]any{ @@ -353,20 +367,21 @@ var ( func (s *mcpServer) call(name string, raw json.RawMessage) (toolResult, error) { var args struct { - Project string `json:"project"` - Kind dsl.DeclKind `json:"kind"` - Name string `json:"name"` - Source string `json:"source"` - Screen string `json:"screen"` - Scale float32 `json:"scale"` - Old string `json:"old"` - New string `json:"new"` - All bool `json:"all"` - Position int `json:"position"` - Path string `json:"path"` - Group *string `json:"group"` - SVG string `json:"svg"` - DesignSystem string `json:"design_system"` + Project string `json:"project"` + Kind dsl.DeclKind `json:"kind"` + Name string `json:"name"` + Source string `json:"source"` + Screen string `json:"screen"` + Scale float32 `json:"scale"` + State map[string]string `json:"state"` + Old string `json:"old"` + New string `json:"new"` + All bool `json:"all"` + Position int `json:"position"` + Path string `json:"path"` + Group *string `json:"group"` + SVG string `json:"svg"` + DesignSystem string `json:"design_system"` Places map[string]struct { X float32 `json:"x"` Y float32 `json:"y"` @@ -498,7 +513,7 @@ func (s *mcpServer) call(name string, raw json.RawMessage) (toolResult, error) { case "delete_item": return s.deleteItem(args.Project, args.Kind, args.Name) case "render_screen": - return s.renderScreen(args.Project, args.Screen, args.Scale) + return s.renderScreen(args.Project, args.Screen, args.Scale, args.State) case "render_overview": return s.renderOverview(args.Project, args.Scale) } @@ -793,7 +808,7 @@ func (s *mcpServer) load(project string) (*dsl.File, []Problem, *Session, error) return f, probs, sess, err } -func (s *mcpServer) renderScreen(project, screen string, scale float32) (toolResult, error) { +func (s *mcpServer) renderScreen(project, screen string, scale float32, state map[string]string) (toolResult, error) { f, probs, sess, err := s.load(project) if err != nil { return toolResult{}, err @@ -807,7 +822,15 @@ func (s *mcpServer) renderScreen(project, screen string, scale float32) (toolRes if sc == nil { return toolResult{}, fmt.Errorf("no screen %q in %s", screen, project) } + for name := range state { + if _, ok := sc.StateOf(name); !ok { + return toolResult{}, errors.New(noState(sc, name)) + } + } + sess.vars = map[string]map[string]string{sc.Name: state} screens = []*dsl.Screen{sc} + } else if len(state) > 0 { + return toolResult{}, errors.New("state is a screen's: name the screen too") } if len(screens) == 0 { return toolResult{}, fmt.Errorf("%s has no screens yet", project) diff --git a/state_test.go b/state_test.go new file mode 100644 index 0000000..ac8bf79 --- /dev/null +++ b/state_test.go @@ -0,0 +1,155 @@ +package gockup + +import ( + "image" + "reflect" + "strings" + "testing" + + "gioui.org/layout" + "gioui.org/widget" + + "github.com/lichdotdev/gockup/dsl" +) + +func TestStateValidation(t *testing.T) { + for src, want := range map[string]string{ + `screen "A" { state error=no Flex { When error=yes { Box set="error=no" } } }`: "", + `screen "A" { Flex { When error=yes { Box } } }`: `has no state "error"`, + `screen "A" { state a=1 Flex { Box set="b=1" } }`: `has no state "b"`, + `screen "A" { state a=1 Flex { Box set="a" } }`: `set must be a state and its value`, + `screen "A" { state a=1 Flex { Box set=a } }`: `set must be a state and its value`, + `screen "A" { state a=1 Flex { When { Box } } }`: "When needs a state", + `screen "A" { state a=1 Flex { When a=1 weight=1 { Box } } }`: "weight goes on what is inside", + `screen "A" { state a=1 When a=1 { Box } }`: "cannot be a When", + `screen "A" { state a=1 Flex { When a=1 { Nope } } }`: `unknown component "Nope"`, + `fragment F then="" { Box set=$then } screen "A" { Flex { F } }`: "", + } { + _, probs, err := NewRegistry().LoadSource(src, "") + if err != nil { + t.Fatalf("%s: %v", src, err) + } + got := joinProblems(probs) + if want == "" && got != "" || !strings.Contains(got, want) { + t.Errorf("%s:\n%q, want %q", src, got, want) + } + } +} + +// stateDecls is a register screen that turns to its error in place. +func stateDecls() []dsl.Decl { + return []dsl.Decl{ + {Kind: dsl.ScreenDecl, Name: "Login", Text: `screen "Login" width=360 height=640 { Text text="Sign up" goto="Register" }`}, + {Kind: dsl.ScreenDecl, Name: "Register", Text: `screen "Register" width=360 height=640 { state error=no + Flex axis=vertical { + When error=yes { Text text="Not an e-mail" } + When error=no { Text text="Create" set="error=yes" } + When error=yes { Text text="Create again" goto="Welcome" } + When error=no { Toggle } + Text text="Fix it" set="error=no" + Text text="Cancel" goto=back + } }`}, + {Kind: dsl.ScreenDecl, Name: "Welcome", Text: `screen "Welcome" width=360 height=640 { Text text="Hello" }`}, + {Kind: dsl.JourneyDecl, Name: "Create account", Text: `journey "Create account" from="Login" to="Welcome"`}, + } +} + +func TestWhenTakesNoRoomOfItsOwn(t *testing.T) { + r := NewRegistry() + r.Register("Cell", Component{Layout: func(c *Ctx) layout.Dimensions { return layout.Dimensions{Size: image.Pt(40, 20)} }}) + f, probs, err := r.LoadSource(`screen "A" width=200 height=100 { state on=no Flex axis=horizontal spacing=6 { + Cell When on=yes { Cell } When on=no { Cell goto="A" Cell goto="A" } } }`, "") + if err != nil || len(probs) > 0 { + t.Fatal(err, probs) + } + got := NewSession(r).gotoAreas(f.Screens[0], 1) + if got[0] != image.Rect(46, 0, 86, 20) || got[1] != image.Rect(92, 0, 132, 20) { + t.Errorf("areas = %v", got) + } +} + +func TestTryingChangesAScreensState(t *testing.T) { + s := newJourneyStudioOf(t, stateDecls()) + s.act("try:Create account") + toggle := func() *widget.Bool { + for _, e := range s.a.trial.sess.state["Register"] { + if b, ok := e.v.(*widget.Bool); ok { + return b + } + } + return nil + } + s.clickApp(20, 20) + s.clickApp(20, 120) // the toggle + s.clickApp(20, 20) // Create, which turns to the error + last := s.a.trial.steps[len(s.a.trial.steps)-1] + if got := s.walked(); got != "Login/Sign up Register/Create Register/" || last.state != "error=yes" { + t.Fatalf("walked %q, state %q", got, last.state) + } + if b := toggle(); b == nil || !b.Value { + t.Error("what was done in a When is lost while it is hidden") + } + if src := s.a.trialScreen(); !strings.Contains(src, `did="With error=yes: you are here"`) || !strings.Contains(src, `TrialBar name="Register" state="error=yes"`) { + t.Error("the path does not tell the state") + } + s.act("try-back") + if s.a.stateText("Register") != "" { + t.Error("a step back leaves the state") + } + s.clickApp(20, 20) + s.clickApp(20, 320) // Cancel, back to Login and not to Register before the error + if s.a.trial.screen() != "Login" { + t.Errorf("back from the error: %q", s.a.trial.screen()) + } + s.clickApp(20, 20) + if s.a.trial.steps[len(s.a.trial.steps)-1].state != "error=yes" { + t.Error("the screen's state is lost on the way back to it") + } + s.clickApp(20, 120) + if !s.a.arrived() || len(s.a.trial.idle) != 0 { + t.Errorf("at the end: on %q, idle %v", s.a.trial.screen(), s.a.trial.idle) + } + s.act("try-restart") + if s.a.stateText("Register") != "" { + t.Error("starting over leaves the state") + } +} + +func TestASetThatChangesNothingIsNoStepNorIdle(t *testing.T) { + s := newJourneyStudioOf(t, stateDecls()) + s.act("try:Create account") + s.clickApp(20, 20) + s.clickApp(20, 220) // Fix it, with nothing to fix + if got := s.walked(); got != "Login/Sign up Register/" || len(s.a.trial.idle) != 0 { + t.Errorf("walked %q, idle %v", got, s.a.trial.idle) + } +} + +func TestMCPRendersAState(t *testing.T) { + src := `screen "A" width=40 height=40 { state on=no Overlay { When on=yes { Box color="#ff0000" fill=true { Spacer } } } }` + args := func(more map[string]any) map[string]any { + more["project"] = "P" + return more + } + resps := mcpCall(t, NewRegistry(), testDB(t), + call("create_project", args(map[string]any{})), + call("write_item", args(map[string]any{"source": src})), + call("render_screen", args(map[string]any{"screen": "A"})), + call("render_screen", args(map[string]any{"screen": "A", "state": map[string]any{"on": "yes"}})), + call("render_screen", args(map[string]any{"screen": "A", "state": map[string]any{"off": "yes"}})), + call("render_screen", args(map[string]any{"state": map[string]any{"on": "yes"}})), + ) + for i, want := range map[int]string{4: `has no state "off"`, 5: "name the screen too"} { + if txt, isErr := toolText(t, resps[i]); !isErr || !strings.Contains(txt, want) { + t.Errorf("call %d: %q, want %q", i, txt, want) + } + } + for _, i := range []int{1, 2, 3} { + if txt, isErr := toolText(t, resps[i]); isErr { + t.Fatalf("call %d: %s", i, txt) + } + } + if reflect.DeepEqual(resps[2]["result"], resps[3]["result"]) { + t.Error("the state draws the same as the screen's start") + } +} diff --git a/systems_test.go b/systems_test.go index add1d56..b4c0a7c 100644 --- a/systems_test.go +++ b/systems_test.go @@ -327,7 +327,7 @@ func TestMCPRendersWaitForTheWindowsLayout(t *testing.T) { s := &mcpServer{sys: sys, db: db} window.Lock() done := make(chan error) - go func() { _, err := s.renderScreen("P", "S", 1); done <- err }() + go func() { _, err := s.renderScreen("P", "S", 1, nil); done <- err }() select { case <-done: t.Fatal("the render laid out while the window was laying out") diff --git a/trial.go b/trial.go index 8ad661b..635cb67 100644 --- a/trial.go +++ b/trial.go @@ -3,8 +3,8 @@ package gockup import ( "fmt" "image" + "maps" "slices" - "strconv" "strings" "unicode/utf8" @@ -41,6 +41,10 @@ type trialStep struct { screen string // did is what was clicked on the screen to leave it, "" on the last. did string + // vars are the states as the step began, by screen, and state those of + // this one that are not as it starts, "error=yes". + vars map[string]map[string]string + state string // from are the screens goto=back goes back through, the last first left. from []string } @@ -84,6 +88,9 @@ func (a *studio) restartTrial() { a.walk(from[n-1], from[:n-1]) } } + t.sess.changed = func() { + a.walk(t.screen(), t.steps[len(t.steps)-1].from) + } t.sess.idle = func(n *dsl.Node) { if c := (idleClick{nodeText(n), t.screen()}); !slices.Contains(t.idle, c) { t.idle = append(t.idle, c) @@ -97,7 +104,7 @@ func (a *studio) restartTrial() { // click runs both, the outer first, and is one step. func (a *studio) innermost() { if a.trial.sess.went { - a.trialBack() + a.trial.dropStep() } } @@ -105,7 +112,7 @@ func (a *studio) innermost() { func (a *studio) walk(screen string, from []string) { t := &a.trial t.steps[len(t.steps)-1].did = nodeText(t.sess.clicked) - t.steps = append(t.steps, trialStep{screen: screen, from: from}) + t.steps = append(t.steps, trialStep{screen: screen, from: from, vars: cloneVars(t.sess.vars), state: a.stateText(screen)}) a.regen() a.invalidate() } @@ -113,12 +120,41 @@ func (a *studio) walk(screen string, from []string) { // trialBack takes the last step back, as if it was not walked. func (a *studio) trialBack() { t := &a.trial - if n := len(t.steps); n > 1 { - t.steps = t.steps[:n-1] - t.steps[n-2].did = "" + if len(t.steps) > 1 { + t.dropStep() + t.sess.vars = cloneVars(t.steps[len(t.steps)-1].vars) } } +func (t *trial) dropStep() { + n := len(t.steps) + t.steps = t.steps[:n-1] + t.steps[n-2].did = "" +} + +func cloneVars(vars map[string]map[string]string) map[string]map[string]string { + out := make(map[string]map[string]string, len(vars)) + for screen, v := range vars { + out[screen] = maps.Clone(v) + } + return out +} + +// stateText tells the states of screen that are not as it starts. +func (a *studio) stateText(screen string) string { + sc := a.file.Screen(screen) + if sc == nil { + return "" + } + var out []string + for _, p := range sc.State { + if now := a.trial.sess.stateNow(sc, p.Name); now != p.Value.Plain() { + out = append(out, p.Name+"="+now) + } + } + return strings.Join(out, ", ") +} + func (a *studio) trialExit() { if !a.trial.on() { return @@ -235,8 +271,8 @@ func (a *studio) trialScreen() string { } else { a.trialPath(&b) } - fmt.Fprintf(&b, "Inset left=%d bottom=16 { Flex axis=vertical { Spacer weight=1\nFlex axis=horizontal { Spacer weight=1\nTrialBar name=%q back=%q path=%q pathBg=%q\nSpacer weight=1 } } }\n", - left, t.screen(), back, path, pathBg) + fmt.Fprintf(&b, "Inset left=%d bottom=16 { Flex axis=vertical { Spacer weight=1\nFlex axis=horizontal { Spacer weight=1\nTrialBar name=%q state=%q back=%q path=%q pathBg=%q\nSpacer weight=1 } } }\n", + left, t.screen(), t.steps[len(t.steps)-1].state, back, path, pathBg) b.WriteString("} }\n") return b.String() } @@ -256,15 +292,17 @@ func (a *studio) trialPath(b *strings.Builder) { } for i := first; i < len(t.steps); i++ { s := t.steps[i] - n := strconv.Itoa(i + 1) + row, did := "TrialHere", "You are here" switch { case i < len(t.steps)-1: - fmt.Fprintf(b, "TrialStep n=%q name=%q did=%q\n", n, s.screen, "Clicked "+s.did) + row, did = "TrialStep", "Clicked "+s.did case arrived: - fmt.Fprintf(b, "TrialHere n=%q name=%q did=\"The end\"\n", n, s.screen) - default: - fmt.Fprintf(b, "TrialHere n=%q name=%q did=\"You are here\"\n", n, s.screen) + did = "The end" + } + if s.state != "" { + did = "With " + s.state + ": " + strings.ToLower(did[:1]) + did[1:] } + fmt.Fprintf(b, "%s n=\"%d\" name=%q did=%q\n", row, i+1, s.screen, did) } if arrived { a.trialFindings(b) diff --git a/trial_test.go b/trial_test.go index 02287c9..454870d 100644 --- a/trial_test.go +++ b/trial_test.go @@ -35,7 +35,9 @@ func journeyDecls() []dsl.Decl { // newJourneyStudio is the app on the journey's project, its Text a box of its // own size and its Toggle a switch. -func newJourneyStudio(t *testing.T) *noteStudio { +func newJourneyStudio(t *testing.T) *noteStudio { return newJourneyStudioOf(t, journeyDecls()) } + +func newJourneyStudioOf(t *testing.T, decls []dsl.Decl) *noteStudio { reg := NewRegistry() box := func(layout.Context) layout.Dimensions { return layout.Dimensions{Size: image.Pt(360, 100)} } reg.Register("Text", Component{ @@ -45,7 +47,7 @@ func newJourneyStudio(t *testing.T) *noteStudio { reg.Register("Toggle", Component{Layout: func(c *Ctx) layout.Dimensions { return State[widget.Bool](c, nil).Layout(c.Gtx, box) }}) - return newStudioDrawing(t, reg, journeyDecls()...) + return newStudioDrawing(t, reg, decls...) } // newTrial tries the journey, its screen drawn at 1:1 right of the path. From 69cc2060603fcab7ffe629d0a0e22fbeba010f73 Mon Sep 17 00:00:00 2001 From: omartelo Date: Thu, 3 Dec 2026 17:54:59 -0300 Subject: [PATCH 2/2] =?UTF-8?q?Settings=20=E2=80=BA=20Updates:=20gockup=20?= =?UTF-8?q?tells=20of=20a=20new=20version=20and=20updates=20itself?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nothing told of a release. gockup asks GitHub once a day, when it opens, and a click downloads the new one, checks it against the release's checksums, sees that it starts, puts it in this one's place and restarts where the user was. One a package manager installed is left to it, with the command to copy. --- CHANGELOG.md | 3 + DESIGN.md | 14 +- app.go | 14 +- app.gockup | 46 +++++ docs/ceilings.md | 12 ++ install.go | 2 + restart_unix.go | 3 + restart_windows.go | 11 ++ theme.go | 17 +- update.go | 428 +++++++++++++++++++++++++++++++++++++++++++++ update_test.go | 369 ++++++++++++++++++++++++++++++++++++++ update_ui.go | 322 ++++++++++++++++++++++++++++++++++ 12 files changed, 1234 insertions(+), 7 deletions(-) create mode 100644 update.go create mode 100644 update_test.go create mode 100644 update_ui.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 76ce257..aa9a17a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Screens that change by a click**: while a journey is tried, a click can show a field's error, open a menu or go to a form's next step on the same screen, with what was typed still there. A screen declares its `state`, `set` changes it and `When` shows what goes with it; your model writes them, and `render_screen` draws a screen in any state. +- **Settings › Updates**: gockup tells when there is a new version, what is in it, and updates itself in a click, opening + again where you were. Installed from the AUR or Homebrew, it gives the command instead. It looks once a day, when it + opens, and you can turn that off. ## [0.4.0] - 2026-12-03 diff --git a/DESIGN.md b/DESIGN.md index 442ef53..6032ca5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -161,10 +161,22 @@ Present shows screens; trying a journey is using the app, to find where it fails - Laid out as a project: the sections are rows in the floating sidebar, under "← Settings"; the open one fills the rest of the window as a card titled level with the sidebar's title. The ground is the plain one of the pages: the dots are the board's alone. -- The sections are Appearance and MCP. A part of a section is its name at 15 over a line at 12, then what it holds. +- The sections are Appearance, MCP and Updates. A part of a section is its name at 15 over a line at 12, then what it holds. - Theme is a selector of the app in miniature in each theme (ground, sidebar, top bar, a frame), System showing both, overlapped; each preview keeps its own theme's colors whatever theme shows it. +## Updates + +- Settings › Updates is a card with the version in use, a green check and when gockup last looked, "Look now" at its + right. With a newer one out it is that one, in coral: what is new, six changes at most from the release's notes, and + "Update and restart". The section's row has a coral dot till then. +- Updating shows the megabytes and a bar, and can be cancelled. gockup then restarts where the user was. One that fails + says why under the card and leaves gockup as it was. +- **gockup replaces only what it installed.** From the AUR or Homebrew the card gives the command to copy, in the button's + place; where it cannot write, "Download" opens the release; built from source, it only says so. +- The projects page tells of a new version once, over the projects: "Not now" closes it till the next one. +- It looks once a day, when it opens. The switch at the foot of the page turns that off; "Look now" still works. + ## Agents gockup sets up its own MCP server: nothing else does, the install script included. diff --git a/app.go b/app.go index 7b1ea8c..c87e56c 100644 --- a/app.go +++ b/app.go @@ -258,9 +258,11 @@ type studio struct { settings bool // systemsTab is the home showing the design systems, not the projects. systemsTab bool - // section is the settings' open section: "" is Appearance, or mcpSettings. + // section is the settings' open section: "" is Appearance, or mcpSettings + // or updateSettings. section string agents agentsUI + updates updatesUI // clip is text for the clipboard, written by the next frame; copied is // what the last action copied, "" for one that did not. clip, copied string @@ -329,10 +331,11 @@ func (sys *systems) app(db *store.DB, serve func() string) error { a.checkAgents() a.askAboutAgents() }() + go a.lookByItself() if r.src != nil { go r.src.run(func(bin string) { a.mu.Lock() - env := append(os.Environ(), appStateEnv+"="+a.savedState()) + env := append(os.Environ(), appStateEnv+"="+a.savedState(), baseBinEnv+"="+baseBin) a.mu.Unlock() err := execSelf(bin, env) r.src.setStatus("Restart into the new build failed: " + err.Error()) @@ -360,6 +363,8 @@ func newStudio(sys *systems, db *store.DB, invalidate func()) *studio { a.uiSess.SetAssets(appIcons()) // both are called while a frame is laid out, with a.mu already held a.uiSess.Goto = a.act + a.updates = updatesUI{from: gitHub, bin: baseBin, version: version(), install: installation{kind: installSource}, restart: restartInto} + a.loadUpdates() var st appState if err := json.Unmarshal([]byte(os.Getenv(appStateEnv)), &st); err == nil { a.project, a.selKind, a.selName = st.Project, st.Kind, st.Name @@ -825,6 +830,10 @@ func (a *studio) act(action string) { clear(a.agents.failed) go a.checkAgents() } + case "update-look", "update-start", "update-cancel", "update-close", "update-page", "update-auto": + err = a.updateAct(strings.TrimPrefix(verb, "update-")) + case "update-open": + a.settings, a.section, a.menu, a.dialog = true, updateSettings, "", "" case "settings-close": a.settings = false case "folder": @@ -1393,6 +1402,7 @@ func (a *studio) homeScreen() string { var b strings.Builder b.WriteString(`screen "home" { Page {` + "\n") a.homeHead(&b) + a.updateNotice(&b) a.agentNotices(&b) ps, err := a.db.Projects() if err != nil { diff --git a/app.gockup b/app.gockup index bea2cb4..f4129d4 100644 --- a/app.gockup +++ b/app.gockup @@ -1035,3 +1035,49 @@ fragment TrialBar name="" state="" back="#dccfc7" path="#ff9a80" pathBg="#3a2019 } } } + +// a version of gockup: the one in use, or the one out, and at the right (the Slot) what can be done +fragment UpdateHead title="" text="" icon="check.svg" color="#34e08f" tint="#34e08f26" { + Inset all=14 { + Flex axis=horizontal align=center spacing=12 { + Sized width=36 height=36 { Overlay { Box color=$tint radius=10 fill=true { Spacer } Image src=$icon width=18 color=$color } } + Flex axis=vertical spacing=2 weight=1 { + Text text=$title size=15 + Text text=$text size=12 color="#9c8d84" + } + Slot + } + } +} + +fragment UpdateProgress done=0.5 left=0.5 { + Inset left=14 right=14 bottom=14 { + Box color="#302824" radius=2 { + Sized height=4 { + Flex axis=horizontal { + Box color="#ff5f3d" radius=2 fill=true weight=$done { Spacer } + Spacer weight=$left + } + } + } + } +} + +fragment UpdateNews { + Flex axis=horizontal spacing=10 { + Inset top=7 { Box color="#ff5f3d" radius=3 { Sized width=5 height=5 { Spacer } } } + Flex axis=vertical spacing=1 weight=1 { Slot } + } +} + +fragment SwitchOn open="" { + Box color="#ff5f3d" radius=11 goto=$open { + Sized width=38 height=22 { Inset all=3 { Flex axis=horizontal { Spacer weight=1 Box color="#ffffff" radius=8 { Sized width=16 height=16 { Spacer } } } } } + } +} + +fragment SwitchOff open="" { + Box color="#3a302b" radius=11 goto=$open { + Sized width=38 height=22 { Inset all=3 { Flex axis=horizontal { Box color="#9c8d84" radius=8 { Sized width=16 height=16 { Spacer } } Spacer weight=1 } } } + } +} diff --git a/docs/ceilings.md b/docs/ceilings.md index b080bac..78c1c43 100644 --- a/docs/ceilings.md +++ b/docs/ceilings.md @@ -138,3 +138,15 @@ file is the trap alone. only after `task install`. - **The light mockups are copies** (`Light…` fragments, "… – light" screens), made with the same color map as the window's theme: a change to a dark fragment does not reach its light twin; change both. + +## Updates + +- **The checksum is the release's own** (`checksums.txt`, from the same place): it tells a broken download, not a release + published by someone else. Nothing is signed. The new gockup must also start and tell the version it is for. +- **The gockup updated is the one the user installed** (`baseBin`), which the environment carries to the build of design + systems that runs in its place. That build is made again for the new version when it opens, with no window till it is + done. +- **Windows keeps the replaced binary** as `gockup.exe.old` until the next start, and its list of installed programs keeps + the version of the installer. On macOS the whole `gockup.app` is replaced, for its signature. +- **Only Linux's launcher stays as installed**: an update brings the binary, not the `.desktop` file nor its icon. +- **GitHub answers 60 questions an hour to an address** with no account: many windows behind one can be told 403. diff --git a/install.go b/install.go index c6fe33b..a7679c6 100644 --- a/install.go +++ b/install.go @@ -513,6 +513,8 @@ func (sys *systems) useInstalled(w *sourceWatch) { return } self, _ := os.Executable() + os.Setenv(baseBinEnv, baseBin) + defer os.Unsetenv(baseBinEnv) b, err := newDSBuild(list) inBuild := b != nil && sameFile(self, b.bin()) sys.added = map[string]string{} diff --git a/restart_unix.go b/restart_unix.go index 1ce6c37..be0e9a5 100644 --- a/restart_unix.go +++ b/restart_unix.go @@ -18,6 +18,9 @@ func execSelf(bin string, env []string) error { return syscall.Exec(bin, os.Args, env) } +// restartInto replaces the process with the gockup an update put at bin. +func restartInto(bin string, env []string) error { return execSelf(bin, env) } + // handOver replaces the process with bin, run with the same arguments. func handOver(bin string) error { return execSelf(bin, os.Environ()) } diff --git a/restart_windows.go b/restart_windows.go index 6b7c7f2..0da640e 100644 --- a/restart_windows.go +++ b/restart_windows.go @@ -13,6 +13,17 @@ const canRestart = false func execSelf(string, []string) error { return errors.ErrUnsupported } +// restartInto opens the gockup an update put at bin, and ends this one. +func restartInto(bin string, env []string) error { + cmd := exec.Command(bin, os.Args[1:]...) + cmd.Env = env + if err := cmd.Start(); err != nil { + return err + } + os.Exit(0) + return nil +} + // handOver runs bin with the same arguments and stdio and exits with it. func handOver(bin string) error { cmd := exec.Command(bin, os.Args[1:]...) diff --git a/theme.go b/theme.go index 8b93c4f..e2b23b1 100644 --- a/theme.go +++ b/theme.go @@ -182,23 +182,32 @@ func (a *studio) settingsScreen() string { fmt.Fprintf(&b, "Sidebar width=%d {\nSettingsHead\n", a.sideWidth) title := "Appearance" row := func(name, icon, section string) { - iconColor, bg, color := "#9c8d84", "#00000000", "#bbaca3" + iconColor, bg, color, dot := "#9c8d84", "#00000000", "#bbaca3", "#00000000" + if section == updateSettings && a.updateOut() { + dot = "#ff5f3d" + } if a.section == section { title, iconColor, bg, color = name, "#ff5f3d", pickedFill, pickedText } - fmt.Fprintf(&b, "Row name=%q icon=%q iconColor=%q bg=%q color=%q open=%q\n", name, icon, iconColor, bg, color, "settings-section:"+section) + fmt.Fprintf(&b, "Row name=%q icon=%q iconColor=%q bg=%q color=%q dot=%q open=%q\n", name, icon, iconColor, bg, color, dot, "settings-section:"+section) } row("Appearance", "sun.svg", "") row("MCP", "code.svg", mcpSettings) + row("Updates", "restart.svg", updateSettings) b.WriteString("}\n") fmt.Fprintf(&b, "Inset left=%d top=10 right=10 bottom=10 { Surface { Box color=\"#1a1614\" radius=16 border=1 borderColor=\"#302824\" fill=true {\n", a.sidebarSpan()) b.WriteString("Inset top=14 left=24 right=24 bottom=24 { Flex axis=vertical spacing=20 align=stretch {\n") fmt.Fprintf(&b, "Flex axis=vertical spacing=14 align=stretch {\nText text=%q size=20 bold=true\nHLine\n}\n", title) - if a.section == mcpSettings { + switch a.section { + case mcpSettings: b.WriteString("Scroll axis=vertical spacing=20 weight=1 {\n") a.mcpSection(&b) b.WriteString("}\n") - } else { + case updateSettings: + b.WriteString("Scroll axis=vertical spacing=20 weight=1 {\n") + a.updateSection(&b) + b.WriteString("}\n") + default: a.appearanceSection(&b) } b.WriteString("} } } } }\n} }\n") diff --git a/update.go b/update.go new file mode 100644 index 0000000..15cd0ca --- /dev/null +++ b/update.go @@ -0,0 +1,428 @@ +package gockup + +import ( + "archive/tar" + "archive/zip" + "cmp" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "os/exec" + "path" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "time" +) + +const ( + repoURL = "https://github.com/lichdotdev/gockup" + // lookTimeout bounds the question for the latest release. + lookTimeout = 20 * time.Second + // maxAnswer bounds what is read of GitHub's answer and of the checksums. + maxAnswer = 1 << 20 +) + +// baseBinEnv carries the gockup the user installed to the build of design +// systems it hands over to, which runs from the cache: it is the one to update. +const baseBinEnv = "GOCKUP_BASE" + +// baseBin is the gockup the user installed, its links followed. +var baseBin = func() string { + bin := os.Getenv(baseBinEnv) + os.Unsetenv(baseBinEnv) + if bin == "" { + bin, _ = os.Executable() + } + if real, err := filepath.EvalSymlinks(bin); err == nil { + bin = real + } + return bin +}() + +// release is a version published on GitHub. +type release struct { + Version string // v0.5.0 + Notes string +} + +func (r release) page() string { return repoURL + "/releases/tag/" + r.Version } + +// releaseVersion is the form of the versions gockup offers: no prereleases. +var releaseVersion = regexp.MustCompile(`^v(\d+)\.(\d+)\.(\d+)(-.+)?$`) + +// newer reports whether version a, of a release, comes after b; a prerelease +// comes before its release. +func newer(a, b string) bool { + x, y := releaseVersion.FindStringSubmatch(a), releaseVersion.FindStringSubmatch(b) + if x == nil || y == nil { + return false + } + for i := 1; i <= 3; i++ { + m, _ := strconv.Atoi(x[i]) + n, _ := strconv.Atoi(y[i]) + if m != n { + return m > n + } + } + return x[4] == "" && y[4] != "" +} + +// installKind is how gockup got where it is, which says who updates it. +type installKind int + +const ( + // installOwn is a release's binary in a place gockup can write to. + installOwn installKind = iota + // installPackaged is a package manager's, whose command updates it. + installPackaged + // installFixed is one gockup cannot write over. + installFixed + // installSource is a build from a checkout. + installSource +) + +type installation struct { + kind installKind + // by is the package manager and command what updates gockup with it. + by, command string +} + +// howInstalled finds how bin, the base gockup, was installed. +func howInstalled(bin string) installation { + if dir, _, err := gockupSource(); err != nil || dir != "" || !releaseVersion.MatchString(version()) { + return installation{kind: installSource} + } + switch runtime.GOOS { + case "linux": + if _, err := exec.LookPath("pacman"); err == nil { + if owner, err := exec.Command("pacman", "-Qqo", bin).Output(); err == nil { + helper := "yay" + if _, err := exec.LookPath(helper); err != nil { + if _, err := exec.LookPath("paru"); err == nil { + helper = "paru" + } + } + return installation{installPackaged, "the AUR", helper + " -S " + strings.TrimSpace(string(owner))} + } + } + case "darwin": + for _, prefix := range []string{"/opt/homebrew", "/usr/local"} { + if _, err := os.Stat(prefix + "/Caskroom/gockup"); err == nil && !strings.HasPrefix(bin, os.Getenv("HOME")+"/") { + return installation{installPackaged, "Homebrew", "brew upgrade --cask gockup"} + } + } + } + target, err := updateTarget(bin, runtime.GOOS) + if err != nil || !writable(filepath.Dir(target)) { + return installation{kind: installFixed} + } + return installation{kind: installOwn} +} + +func writable(dir string) bool { + f, err := os.CreateTemp(dir, ".gockup-") + if err != nil { + return false + } + f.Close() + return os.Remove(f.Name()) == nil +} + +// updateTarget is what an update replaces: the binary, or on macOS the bundle +// around it, whose signature seals every file in it. +func updateTarget(bin, goos string) (string, error) { + if goos != "darwin" { + return bin, nil + } + app := filepath.Dir(filepath.Dir(filepath.Dir(bin))) + if filepath.Ext(app) != ".app" { + return "", fmt.Errorf("%s is not in gockup.app", bin) + } + return app, nil +} + +// updater gets releases from GitHub, for a system. +type updater struct { + api, files string // the latest release's address, and where the files of each are + goos, goarch string +} + +var gitHub = updater{ + api: "https://api.github.com/repos/lichdotdev/gockup/releases/latest", + files: repoURL + "/releases/download", + goos: runtime.GOOS, goarch: runtime.GOARCH, +} + +func get(ctx context.Context, url string) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "gockup") + res, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + if res.StatusCode != http.StatusOK { + res.Body.Close() + return nil, fmt.Errorf("GitHub answered %s", res.Status) + } + return res, nil +} + +func (u updater) latest(ctx context.Context) (release, error) { + ctx, cancel := context.WithTimeout(ctx, lookTimeout) + defer cancel() + res, err := get(ctx, u.api) + if err != nil { + return release{}, err + } + defer res.Body.Close() + var got struct { + Tag string `json:"tag_name"` + Body string `json:"body"` + } + if err := json.NewDecoder(io.LimitReader(res.Body, maxAnswer)).Decode(&got); err != nil { + return release{}, fmt.Errorf("reading GitHub's answer: %w", err) + } + if !releaseVersion.MatchString(got.Tag) { + return release{}, fmt.Errorf("the latest release, %q, is not a version", got.Tag) + } + return release{got.Tag, got.Body}, nil +} + +// update replaces the gockup at bin with version: nothing is touched until +// the new one is here, is the one the release has, and starts. progress is +// told how much of the download has come, in bytes. +func (u updater) update(ctx context.Context, bin, version string, progress func(done, total int64)) error { + target, err := updateTarget(bin, u.goos) + if err != nil { + return err + } + // beside the target, for the last step to be a rename + dir, err := os.MkdirTemp(filepath.Dir(target), ".gockup-update-") + if err != nil { + return err + } + defer os.RemoveAll(dir) + name := fmt.Sprintf("gockup_%s_%s.tar.gz", u.goos, u.goarch) + if u.goos == "windows" { + name = fmt.Sprintf("gockup_%s_%s.zip", u.goos, u.goarch) + } + from := u.files + "/" + version + "/" + want, err := checksum(ctx, from+"checksums.txt", name) + if err != nil { + return err + } + archive := filepath.Join(dir, name) + got, err := download(ctx, from+name, archive, progress) + if err != nil { + return err + } + if got != want { + return fmt.Errorf("%s is not the file the release has: its checksum differs", name) + } + fresh := filepath.Join(dir, "new") + if err := unpack(archive, fresh); err != nil { + return fmt.Errorf("unpacking %s: %w", name, err) + } + fresh, run := filepath.Join(fresh, "gockup"), "" + switch u.goos { + case "windows": + fresh += ".exe" + case "darwin": + fresh += ".app" + run = filepath.Join(fresh, "Contents", "MacOS", "gockup") + } + check := exec.CommandContext(ctx, cmp.Or(run, fresh), "version") + quiet(check) + out, err := check.Output() + if err != nil { + return fmt.Errorf("gockup %s does not start here: %w", version, err) + } + if told := strings.TrimSpace(string(out)); told != version { + return fmt.Errorf("the file for %s is gockup %s", version, told) + } + if err := ctx.Err(); err != nil { + return err + } + return swap(fresh, target) +} + +func checksum(ctx context.Context, url, name string) (string, error) { + res, err := get(ctx, url) + if err != nil { + return "", fmt.Errorf("the release's checksums: %w", err) + } + defer res.Body.Close() + data, err := io.ReadAll(io.LimitReader(res.Body, maxAnswer)) + if err != nil { + return "", fmt.Errorf("the release's checksums: %w", err) + } + for line := range strings.Lines(string(data)) { + if f := strings.Fields(line); len(f) == 2 && f[1] == name { + return f[0], nil + } + } + return "", fmt.Errorf("the release has no %s", name) +} + +// countingWriter tells how much went through it. +type countingWriter struct { + done, total int64 + tell func(done, total int64) +} + +func (w *countingWriter) Write(p []byte) (int, error) { + w.done += int64(len(p)) + w.tell(w.done, w.total) + return len(p), nil +} + +// download saves url at file and returns its SHA-256. +func download(ctx context.Context, url, file string, progress func(done, total int64)) (string, error) { + res, err := get(ctx, url) + if err != nil { + return "", fmt.Errorf("downloading: %w", err) + } + defer res.Body.Close() + f, err := os.Create(file) + if err != nil { + return "", err + } + defer f.Close() + sum := sha256.New() + if _, err := io.Copy(io.MultiWriter(f, sum, &countingWriter{total: res.ContentLength, tell: progress}), res.Body); err != nil { + return "", fmt.Errorf("downloading: %w", err) + } + return hex.EncodeToString(sum.Sum(nil)), f.Close() +} + +// unpack writes the files of a release's archive in dir. +func unpack(archive, dir string) error { + write := func(name string, mode fs.FileMode, r io.Reader) error { + name = path.Clean(name) + if !filepath.IsLocal(filepath.FromSlash(name)) { + return fmt.Errorf("it has a file out of it, %q", name) + } + to := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(to), 0o755); err != nil { + return err + } + f, err := os.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode.Perm()) + if err != nil { + return err + } + defer f.Close() + if _, err := io.Copy(f, r); err != nil { + return err + } + return f.Close() + } + if strings.HasSuffix(archive, ".zip") { + z, err := zip.OpenReader(archive) + if err != nil { + return err + } + defer z.Close() + for _, f := range z.File { + if f.FileInfo().IsDir() { + continue + } + r, err := f.Open() + if err != nil { + return err + } + err = write(f.Name, f.Mode()|0o600, r) + r.Close() + if err != nil { + return err + } + } + return nil + } + f, err := os.Open(archive) + if err != nil { + return err + } + defer f.Close() + gz, err := gzip.NewReader(f) + if err != nil { + return err + } + for t := tar.NewReader(gz); ; { + h, err := t.Next() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + switch h.Typeflag { + case tar.TypeDir: + case tar.TypeReg: + if err := write(h.Name, h.FileInfo().Mode(), t); err != nil { + return err + } + default: + return fmt.Errorf("it has %q, not a file", h.Name) + } + } +} + +// replacedSuffix names what an update replaced, till it can be deleted: +// Windows keeps the file of a program that runs. +const replacedSuffix = ".old" + +// swap puts fresh in target's place, or leaves target as it was. +func swap(fresh, target string) error { + if runtime.GOOS != "windows" && isFile(target) { + return os.Rename(fresh, target) + } + old := target + replacedSuffix + if err := os.RemoveAll(old); err != nil { + return err + } + if err := os.Rename(target, old); err != nil { + return err + } + if err := os.Rename(fresh, target); err != nil { + return errors.Join(err, os.Rename(old, target)) + } + os.RemoveAll(old) + return nil +} + +// dropReplaced deletes what the last update could not. +func dropReplaced(bin string) { + if target, err := updateTarget(bin, runtime.GOOS); err == nil { + os.RemoveAll(target + replacedSuffix) + } +} + +// openPage opens an address in the user's browser. +func openPage(url string) error { + cmd := exec.Command("xdg-open", url) + switch runtime.GOOS { + case "darwin": + cmd = exec.Command("open", url) + case "windows": + cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url) + } + if err := cmd.Start(); err != nil { + return err + } + go cmd.Wait() + return nil +} diff --git a/update_test.go b/update_test.go new file mode 100644 index 0000000..e3fec9c --- /dev/null +++ b/update_test.go @@ -0,0 +1,369 @@ +package gockup + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + "time" +) + +func TestNewer(t *testing.T) { + for _, c := range []struct { + a, b string + want bool + }{ + {"v0.5.0", "v0.4.0", true}, {"v0.10.0", "v0.9.9", true}, {"v1.0.0", "v0.99.0", true}, {"v0.4.1", "v0.4.0", true}, + {"v0.4.0", "v0.4.0", false}, {"v0.4.0", "v0.5.0", false}, + {"v0.5.0", "v0.5.0-rc.1", true}, {"v0.5.0-rc.1", "v0.5.0", false}, + {"", "v0.4.0", false}, {"v0.5.0", "(devel)", false}, {"latest", "v0.4.0", false}, + } { + if got := newer(c.a, c.b); got != c.want { + t.Errorf("newer(%q, %q) = %v", c.a, c.b, got) + } + } +} + +func TestNewsOf(t *testing.T) { + got := newsOf("\n### Added\n\n- **Journeys**: name a way\n through your `mockup`.\n- **Find it.** It is there.\n- `goto=back`, for **Cancel**.\n\nNot a change.\n") + want := []news{{"Journeys", "Name a way through your mockup."}, {"Find it", "It is there."}, {"", "goto=back, for Cancel."}} + if !slices.Equal(got, want) { + t.Errorf("news = %q", got) + } +} + +// gockupThatSays is a program that answers version as a gockup would. +func gockupThatSays(version string) string { return "#!/bin/sh\necho " + version + "\n" } + +func tarOf(t *testing.T, files map[string]string) []byte { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + w := tar.NewWriter(gz) + for name, body := range files { + if err := w.WriteHeader(&tar.Header{Name: name, Mode: 0o755, Size: int64(len(body)), Typeflag: tar.TypeReg}); err != nil { + t.Fatal(err) + } + w.Write([]byte(body)) + } + if err := errors.Join(w.Close(), gz.Close()); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func zipOf(t *testing.T, files map[string]string) []byte { + t.Helper() + var buf bytes.Buffer + w := zip.NewWriter(&buf) + for name, body := range files { + h := &zip.FileHeader{Name: name} + h.SetMode(0o755) + f, err := w.CreateHeader(h) + if err != nil { + t.Fatal(err) + } + f.Write([]byte(body)) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +// releasing is GitHub with v0.5.0 out, its file for goos being archive. +func releasing(t *testing.T, goos string, archive []byte) updater { + t.Helper() + name := "gockup_" + goos + "_amd64.tar.gz" + if goos == "windows" { + name = "gockup_" + goos + "_amd64.zip" + } + mux := http.NewServeMux() + mux.HandleFunc("/latest", func(w http.ResponseWriter, _ *http.Request) { + fmt.Fprint(w, `{"tag_name": "v0.5.0", "body": "- **Updates**: it updates itself."}`) + }) + mux.HandleFunc("/files/v0.5.0/checksums.txt", func(w http.ResponseWriter, _ *http.Request) { + fmt.Fprintf(w, "0000 other.zip\n%x %s\n", sha256.Sum256(archive), name) + }) + mux.HandleFunc("/files/v0.5.0/"+name, func(w http.ResponseWriter, _ *http.Request) { w.Write(archive) }) + s := httptest.NewServer(mux) + t.Cleanup(s.Close) + return updater{api: s.URL + "/latest", files: s.URL + "/files", goos: goos, goarch: "amd64"} +} + +func needsShell(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the gockup of these tests is a shell script") + } +} + +func writeProgram(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o755); err != nil { + t.Fatal(err) + } +} + +func TestUpdateReplacesTheBinary(t *testing.T) { + needsShell(t) + for _, c := range []struct { + goos, bin string + archive []byte + }{ + {"linux", "gockup", tarOf(t, map[string]string{"./gockup": gockupThatSays("v0.5.0"), "./README.md": "read me"})}, + {"windows", "gockup.exe", zipOf(t, map[string]string{"gockup.exe": gockupThatSays("v0.5.0"), "LICENSE": "MIT"})}, + {"darwin", "gockup.app/Contents/MacOS/gockup", tarOf(t, map[string]string{"./gockup.app/Contents/MacOS/gockup": gockupThatSays("v0.5.0"), "./gockup.app/Contents/Info.plist": "0.5.0"})}, + } { + t.Run(c.goos, func(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, filepath.FromSlash(c.bin)) + writeProgram(t, bin, gockupThatSays("v0.4.0")) + var done, total int64 + if err := releasing(t, c.goos, c.archive).update(context.Background(), bin, "v0.5.0", func(d, n int64) { done, total = d, n }); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(bin); string(got) != gockupThatSays("v0.5.0") { + t.Errorf("the binary is %q", got) + } + if done != int64(len(c.archive)) || total != done { + t.Errorf("progress ended at %d of %d, the file has %d", done, total, len(c.archive)) + } + if left, _ := os.ReadDir(dir); len(left) != 1 { + t.Errorf("left beside it: %v", left) + } + }) + } +} + +func TestAnUpdateThatFailsLeavesTheBinary(t *testing.T) { + needsShell(t) + good := tarOf(t, map[string]string{"gockup": gockupThatSays("v0.5.0")}) + cancelled, cancel := context.WithCancel(context.Background()) + cancel() + for name, c := range map[string]struct { + ctx context.Context + archive []byte + change func(u *updater) + want string + }{ + "another version": {archive: tarOf(t, map[string]string{"gockup": gockupThatSays("v0.3.0")}), want: "is gockup v0.3.0"}, + "does not start": {archive: tarOf(t, map[string]string{"gockup": "#!/bin/sh\nexit 1\n"}), want: "does not start here"}, + "a file out of it": {archive: tarOf(t, map[string]string{"../gockup": "x"}), want: "a file out of it"}, + "no file": {archive: good, change: func(u *updater) { u.goarch = "riscv64" }, want: "the release has no gockup_linux_riscv64"}, + "no release": {archive: good, change: func(u *updater) { u.files += "/none" }, want: "404"}, + "cancelled": {ctx: cancelled, archive: good, want: "canceled"}, + } { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "gockup") + writeProgram(t, bin, gockupThatSays("v0.4.0")) + u := releasing(t, "linux", c.archive) + if c.change != nil { + c.change(&u) + } + ctx := c.ctx + if ctx == nil { + ctx = context.Background() + } + err := u.update(ctx, bin, "v0.5.0", func(int64, int64) {}) + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("err = %v, want %q", err, c.want) + } + if got, _ := os.ReadFile(bin); string(got) != gockupThatSays("v0.4.0") { + t.Errorf("the binary is %q", got) + } + if left, _ := os.ReadDir(dir); len(left) != 1 { + t.Errorf("left beside it: %v", left) + } + }) + } +} + +func TestAnUpdateWithAnotherChecksumIsRefused(t *testing.T) { + needsShell(t) + archive := tarOf(t, map[string]string{"gockup": gockupThatSays("v0.5.0")}) + real := releasing(t, "linux", archive) + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "checksums.txt") { + fmt.Fprintf(w, "%x gockup_linux_amd64.tar.gz\n", sha256.Sum256([]byte("another"))) + return + } + w.Write(archive) + })) + defer s.Close() + real.files = s.URL + bin := filepath.Join(t.TempDir(), "gockup") + writeProgram(t, bin, gockupThatSays("v0.4.0")) + if err := real.update(context.Background(), bin, "v0.5.0", func(int64, int64) {}); err == nil || !strings.Contains(err.Error(), "checksum differs") { + t.Errorf("err = %v", err) + } + if got, _ := os.ReadFile(bin); string(got) != gockupThatSays("v0.4.0") { + t.Errorf("the binary is %q", got) + } +} + +func updateStudio(t *testing.T, kind installKind) *studio { + a := newStudio(single(NewRegistry()), testDB(t), func() {}) + a.updates.version = "v0.4.0" + a.updates.install = installation{kind: kind} + return a +} + +// until waits for what runs off the window's turn. +func until(t *testing.T, a *studio, what string, ok func() bool) { + t.Helper() + for end := time.Now().Add(10 * time.Second); time.Now().Before(end); time.Sleep(5 * time.Millisecond) { + a.mu.Lock() + done := ok() + a.mu.Unlock() + if done { + return + } + } + t.Fatalf("not in 10s: %s", what) +} + +func TestLookingForAnUpdate(t *testing.T) { + a := updateStudio(t, installOwn) + a.updates.from = releasing(t, "linux", nil) + a.look() + a.mu.Lock() + defer a.mu.Unlock() + if !a.updateOut() || a.updates.failed != "" { + t.Fatalf("latest %q, failed %q", a.updates.latest.Version, a.updates.failed) + } + if src := a.homeScreen(); !strings.Contains(src, "gockup 0.5.0 is out") || !strings.Contains(src, "Update and restart") { + t.Error("the projects page does not tell") + } + a.act("update-close") + if strings.Contains(a.homeScreen(), "0.5.0") { + t.Error("the notice stays after Not now") + } + a.act("update-open") + if src := a.settingsScreen(); !strings.Contains(src, "gockup 0.5.0 is out") || !strings.Contains(src, "It updates itself.") { + t.Error("the page does not tell, or not what is new") + } + // the next window knows without asking again + b := newStudio(a.sys, a.db, func() {}) + if b.updates.latest != a.updates.latest || b.updates.looked.IsZero() { + t.Errorf("kept %+v, looked %v", b.updates.latest, b.updates.looked) + } +} + +func TestALookThatFailsSaysSo(t *testing.T) { + a := updateStudio(t, installOwn) + a.updates.from.api = releasing(t, "linux", nil).files + "/none" + a.look() + a.mu.Lock() + defer a.mu.Unlock() + a.act("update-open") + if !strings.Contains(a.updates.failed, "404") || !strings.Contains(a.settingsScreen(), "Could not look") { + t.Errorf("failed = %q", a.updates.failed) + } +} + +func TestTheLookByItselfCanBeTurnedOff(t *testing.T) { + a := updateStudio(t, installOwn) + a.act("update-open") + if !strings.Contains(a.settingsScreen(), "SwitchOn") { + t.Error("off before it was turned off") + } + a.act("update-auto") + if v, _ := a.db.Setting(updateLookSetting); v != "off" || !strings.Contains(a.settingsScreen(), "SwitchOff") { + t.Errorf("setting %q", v) + } + a.act("update-auto") + if !strings.Contains(a.settingsScreen(), "SwitchOn") { + t.Error("does not turn back on") + } +} + +func TestUpdatingFromTheWindow(t *testing.T) { + needsShell(t) + a := updateStudio(t, installOwn) + a.updates.from = releasing(t, "linux", tarOf(t, map[string]string{"gockup": gockupThatSays("v0.5.0")})) + a.updates.bin = filepath.Join(t.TempDir(), "gockup") + writeProgram(t, a.updates.bin, gockupThatSays("v0.4.0")) + restarted := make(chan []string, 1) + a.updates.restart = func(bin string, env []string) error { + restarted <- append(env, bin) + return nil + } + a.look() + a.mu.Lock() + a.act("update-start") + a.act("update-start") + a.mu.Unlock() + select { + case env := <-restarted: + if env[len(env)-1] != a.updates.bin || !slices.ContainsFunc(env, func(e string) bool { return strings.HasPrefix(e, appStateEnv+"=") }) { + t.Error("restarted into another binary, or without where the window was") + } + case <-time.After(10 * time.Second): + t.Fatal("not restarted in 10s") + } + if got, _ := os.ReadFile(a.updates.bin); string(got) != gockupThatSays("v0.5.0") { + t.Errorf("the binary is %q", got) + } +} + +func TestAnUpdateThatFailsSaysSoAndCanBeTriedAgain(t *testing.T) { + needsShell(t) + a := updateStudio(t, installOwn) + a.updates.from = releasing(t, "linux", tarOf(t, map[string]string{"gockup": gockupThatSays("v0.3.0")})) + a.updates.bin = filepath.Join(t.TempDir(), "gockup") + writeProgram(t, a.updates.bin, gockupThatSays("v0.4.0")) + a.updates.restart = func(string, []string) error { t.Error("restarted"); return nil } + a.look() + a.mu.Lock() + a.act("update-start") + a.mu.Unlock() + until(t, a, "the update failing", func() bool { return a.updates.failed != "" }) + a.mu.Lock() + defer a.mu.Unlock() + if src := a.settingsScreen(); !strings.Contains(src, "Not updated") || !strings.Contains(src, "Update and restart") { + t.Errorf("failed %q; the page does not say it, or offers no other try", a.updates.failed) + } +} + +func TestAPackagedGockupIsUpdatedByItsPackageManager(t *testing.T) { + a := updateStudio(t, installPackaged) + a.updates.install.by, a.updates.install.command = "the AUR", "yay -S gockup-bin" + a.updates.latest = release{"v0.5.0", ""} + a.updates.restart = func(string, []string) error { t.Error("restarted"); return nil } + a.act("update-start") + if a.updates.cancel != nil { + t.Error("it began to update itself") + } + a.act("update-open") + if src := a.settingsScreen(); !strings.Contains(src, "yay -S gockup-bin") || strings.Contains(src, "Update and restart") { + t.Error("the page does not give the command, or offers to update") + } +} + +func TestABuildFromSourceIsNotUpdated(t *testing.T) { + a := updateStudio(t, installSource) + a.updates.latest = release{"v0.5.0", ""} + if strings.Contains(a.homeScreen(), "0.5.0") { + t.Error("the projects page tells of a release") + } + a.act("update-open") + if !strings.Contains(a.settingsScreen(), "Built from source") { + t.Error("the page does not say it is built from source") + } +} diff --git a/update_ui.go b/update_ui.go new file mode 100644 index 0000000..d0e27c3 --- /dev/null +++ b/update_ui.go @@ -0,0 +1,322 @@ +package gockup + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +// updateSettings is the settings section of gockup's own version. +const updateSettings = "updates" + +const ( + // the settings keys of the updates: "off" when gockup is not to look by + // itself, when it last looked, what it found, and the version whose + // notice the user closed + updateLookSetting = "update-look" + updateLookedSetting = "update-looked" + updateLatestSetting = "update-latest" + updateClosedSetting = "update-closed" + + // lookEvery is how often gockup looks by itself, when it opens. + lookEvery = 24 * time.Hour + // newsShown is how many of a release's changes the page lists. + newsShown = 6 + megabyte = 1 << 20 +) + +// updatesUI is what the window knows of gockup's versions. +type updatesUI struct { + from updater + bin string + version string + install installation + + latest release + looked time.Time + looking bool + failed string + // cancel stops the update under way; nil when there is none. + cancel context.CancelFunc + done, total int64 + // restart opens the gockup an update put in bin. + restart func(bin string, env []string) error +} + +// loadUpdates reads what the last look found. a.mu must be held. +func (a *studio) loadUpdates() { + u := &a.updates + if kept, _ := a.db.Setting(updateLatestSetting); kept != "" { + json.Unmarshal([]byte(kept), &u.latest) + } + if at, _ := a.db.Setting(updateLookedSetting); at != "" { + u.looked, _ = time.Parse(time.RFC3339, at) + } +} + +// lookByItself looks for a new version unless the user said not to, a look +// was made in the last day, or there is none to have. +func (a *studio) lookByItself() { + in := howInstalled(baseBin) + if in.kind == installOwn { + dropReplaced(baseBin) + } + a.mu.Lock() + a.updates.install = in + choice, _ := a.db.Setting(updateLookSetting) + due := in.kind != installSource && choice != "off" && time.Since(a.updates.looked) > lookEvery + a.regen() + a.mu.Unlock() + a.invalidate() + if due { + a.look() + } +} + +// look asks GitHub for the latest version, off the window's turn. +func (a *studio) look() { + a.mu.Lock() + u := &a.updates + if u.looking || u.cancel != nil { + a.mu.Unlock() + return + } + u.looking, u.failed = true, "" + a.regen() + from := u.from + a.mu.Unlock() + a.invalidate() + + got, err := from.latest(context.Background()) + + a.mu.Lock() + defer a.mu.Unlock() + u.looking = false + if err != nil { + u.failed = "Could not look for a new version: " + err.Error() + } else { + u.latest, u.looked = got, time.Now() + kept, _ := json.Marshal(got) + err = errors.Join(a.db.SetSetting(updateLatestSetting, string(kept)), a.db.SetSetting(updateLookedSetting, u.looked.Format(time.RFC3339))) + if err != nil { + u.failed = err.Error() + } + } + a.regen() + a.invalidate() +} + +// updateOut reports whether there is a newer version for this gockup; one +// built from source is not the releases' to update. +func (a *studio) updateOut() bool { + return a.updates.install.kind != installSource && newer(a.updates.latest.Version, a.updates.version) +} + +// startUpdate gets the latest version, puts it in this one's place and +// restarts into it. a.mu must be held. +func (a *studio) startUpdate() { + u := &a.updates + if u.cancel != nil || !a.updateOut() || u.install.kind != installOwn { + return + } + ctx, cancel := context.WithCancel(context.Background()) + u.cancel, u.failed, u.done, u.total = cancel, "", 0, 0 + a.settings, a.section, a.dialog = true, updateSettings, "" + from, bin, version := u.from, u.bin, u.latest.Version + go func() { + defer cancel() + err := from.update(ctx, bin, version, func(done, total int64) { + a.mu.Lock() + // told by the megabyte: each is a frame + tell := done/megabyte != u.done/megabyte + u.done, u.total = done, total + if tell { + a.regen() + } + a.mu.Unlock() + if tell { + a.invalidate() + } + }) + a.mu.Lock() + if err == nil { + env := append(os.Environ(), appStateEnv+"="+a.savedState()) + a.mu.Unlock() + if err = u.restart(bin, env); err == nil { + return + } + err = fmt.Errorf("%s is installed, and opens the next time you open gockup: %w", version[1:], err) + a.mu.Lock() + } + u.cancel = nil + if !errors.Is(err, context.Canceled) { + u.failed = "Not updated: " + err.Error() + } + a.regen() + a.mu.Unlock() + a.invalidate() + }() +} + +// updateAct does the updates' actions, named after "update-". +func (a *studio) updateAct(verb string) error { + u := &a.updates + switch verb { + case "look": + go a.look() + case "start": + a.startUpdate() + case "cancel": + if u.cancel != nil { + u.cancel() + } + case "close": + return a.db.SetSetting(updateClosedSetting, u.latest.Version) + case "page": + return openPage(u.latest.page()) + case "auto": + choice, err := a.db.Setting(updateLookSetting) + if err != nil { + return err + } + if choice == "off" { + return a.db.SetSetting(updateLookSetting, "") + } + return a.db.SetSetting(updateLookSetting, "off") + } + return nil +} + +// news is one change of a release: its name, when the notes give it one, and +// what it is. +type news struct{ name, text string } + +// newsOf reads a release's notes, a list with each change's name in bold. +func newsOf(notes string) []news { + var items []string + open := false + for line := range strings.Lines(notes) { + line = strings.TrimRight(line, "\r\n") + text := strings.TrimSpace(line) + switch { + case strings.HasPrefix(line, "- "): + items, open = append(items, text[2:]), true + case text == "" || !strings.HasPrefix(line, " "): + open = false + case open: + items[len(items)-1] += " " + text + } + } + out := make([]news, 0, len(items)) + for _, item := range items { + n := news{text: item} + if rest, ok := strings.CutPrefix(item, "**"); ok { + if name, text, ok := strings.Cut(rest, "**"); ok { + n = news{strings.TrimSuffix(name, "."), strings.TrimLeft(text, ":. ")} + } + } + n.text = strings.NewReplacer("**", "", "`", "").Replace(n.text) + if n.name != "" && n.text != "" { + r, size := utf8.DecodeRuneInString(n.text) + n.text = string(unicode.ToUpper(r)) + n.text[size:] + } + out = append(out, n) + } + return out +} + +// updateHead writes the version out, or how getting it goes, with what is to +// be done about it at its right. +func (a *studio) updateHead(b *strings.Builder, text, right string) { + fmt.Fprintf(b, "UpdateHead title=%q text=%q icon=\"down.svg\" color=\"#ff5f3d\" tint=\"#ff5f3d26\" {\n%s\n}\n", + "gockup "+a.updates.latest.Version[1:]+" is out", text, right) +} + +// updateNotice tells, over the projects, of a version the user has not been +// told of. +func (a *studio) updateNotice(b *strings.Builder) { + closed, _ := a.db.Setting(updateClosedSetting) + if !a.updateOut() || closed == a.updates.latest.Version { + return + } + right := `Inset right=6 { Text text="Not now" size=12 color="#9c8d84" goto="update-close" }` + "\n" + if a.updates.install.kind == installOwn { + right += `Inset right=6 { Text text="What is new" size=12 color="#dccfc7" goto="update-open" }` + "\n" + `AgentsMain text="Update and restart" open="update-start"` + } else { + right += `AgentsMain text="See how to update" open="update-open"` + } + b.WriteString("AgentList {\n") + a.updateHead(b, "You have "+strings.TrimPrefix(a.updates.version, "v")+".", right) + b.WriteString("}\n") +} + +// updateSection writes the settings' Updates section. +func (a *studio) updateSection(b *strings.Builder) { + u := &a.updates + have := strings.TrimPrefix(u.version, "v") + if u.install.kind == installSource { + fmt.Fprintf(b, "AgentList {\nUpdateHead title=%q text=\"Built from source: update the checkout and build it again.\" icon=\"code.svg\" color=\"#9c8d84\" tint=\"#9c8d8426\"\n}\n", "gockup "+have) + return + } + b.WriteString("AgentList {\n") + switch { + case u.cancel != nil: + text := "Starting the download." + if u.total > 0 { + text = fmt.Sprintf("%d of %d MB. gockup restarts where you are when it is done.", u.done/megabyte, (u.total+megabyte-1)/megabyte) + } + fmt.Fprintf(b, "UpdateHead title=%q text=%q icon=\"down.svg\" color=\"#ff5f3d\" tint=\"#ff5f3d26\" { AgentButton text=\"Cancel\" open=\"update-cancel\" }\n", "Updating to "+u.latest.Version[1:], text) + part := float64(u.done) / float64(max(u.total, 1)) + // a weight of 0 takes its own size: neither part is left with none + fmt.Fprintf(b, "UpdateProgress done=%.3f left=%.3f\n", max(part, 0.001), max(1-part, 0.001)) + case a.updateOut(): + text, right := "You have "+have+".", `AgentsMain text="Update and restart" open="update-start"` + switch u.install.kind { + case installPackaged: + text, right = "You have "+have+", installed from "+u.install.by+": update it there, then open gockup again.", "" + case installFixed: + text, right = "You have "+have+", where gockup cannot write: download the new one and put it in its place.", `AgentsMain text="Download" open="update-page"` + } + a.updateHead(b, text, right) + if u.install.command != "" { + b.WriteString("Inset left=14 right=14 bottom=14 {\n") + a.copyBox(b, u.install.command) + b.WriteString("}\n") + } + b.WriteString("HLine\nInset all=14 { Flex axis=vertical spacing=12 align=stretch {\nText text=\"WHAT IS NEW\" size=11 bold=true color=\"#80726a\"\n") + all := newsOf(u.latest.Notes) + for _, n := range all[:min(len(all), newsShown)] { + if n.name == "" { + fmt.Fprintf(b, "UpdateNews { Text text=%q color=\"#dccfc7\" }\n", n.text) + continue + } + fmt.Fprintf(b, "UpdateNews { Text text=%q color=\"#dccfc7\" Text text=%q size=12 color=\"#9c8d84\" }\n", n.name, n.text) + } + b.WriteString("Flex axis=horizontal { Text text=\"All of it on GitHub\" size=12 color=\"#ff9a80\" goto=\"update-page\" }\n} }\n") + default: + text, right := "Not looked for a newer one yet.", `AgentButton text="Look now" open="update-look"` + if !u.looked.IsZero() { + text = "The latest version. Looked for " + ago(u.looked, time.Now()) + "." + } + if u.looking { + text, right = "Looking for a newer one…", "" + } + fmt.Fprintf(b, "UpdateHead title=%q text=%q { %s }\n", "gockup "+have, text, right) + } + b.WriteString("}\n") + if u.failed != "" { + fmt.Fprintf(b, "Notice text=%q color=%q textColor=%q\n", u.failed, "#2e131b", errColor) + } + toggle := "SwitchOn" + if choice, _ := a.db.Setting(updateLookSetting); choice == "off" { + toggle = "SwitchOff" + } + fmt.Fprintf(b, "Flex axis=horizontal align=center spacing=12 {\nInset weight=1 { SettingsTitle title=\"Look for updates by itself\" text=%q }\n%s open=\"update-auto\"\n}\n", + "Once a day, when gockup opens. It asks GitHub for the latest release and sends nothing about you.", toggle) +}