diff --git a/app/app.go b/app/app.go index a27424b32..1e363c2b4 100644 --- a/app/app.go +++ b/app/app.go @@ -252,6 +252,15 @@ type Config struct { // application stop work nobody can see, such as a remote desktop stream. // Hide is the application's own request and is not reported here. OnMinimize func(minimized bool) + // OnShow runs when Window.Show puts back a window that Hide took off the + // screen, a macOS Dock reopen included. It runs inside Show, before the + // window is back on screen, so what it changes is in the first frame the + // user sees; an application that sets it calls Show on the window thread, + // where menus, status-item clicks and reopen requests already run. Showing + // a window that is on screen, or one restored from minimized, does not call + // it. It lets an application put back what a window should hold whenever it + // is shown, such as the document a window that hides on close reopens with. + OnShow func() // OnPinch receives two fingers pinching the window: its begin, each change and its end. // Only a touch screen and a touchpad that can pinch send them; the event says where the // fingers are, how far apart they are against the start and since the last event, and the diff --git a/app/application.go b/app/application.go index 0c4af0d9f..024bea73f 100644 --- a/app/application.go +++ b/app/application.go @@ -117,6 +117,8 @@ type Window struct { control WindowControl closed atomic.Bool hidden atomic.Bool + // onShow is Config.OnShow, run when Show brings back a hidden window. + onShow func() // minimized mirrors what the platform last reported through OnMinimize. minimized atomic.Bool // maximized mirrors what the platform last reported through OnMaximize. @@ -161,12 +163,15 @@ func (window *Window) Hide() { } // Show puts the window back on the screen in front of the others and brings -// the application forward. Showing a window already on screen raises it. +// the application forward. Showing a window already on screen raises it. A +// window that Hide took off the screen runs Config.OnShow first. func (window *Window) Show() { if window == nil || window.closed.Load() { return } - window.hidden.Store(false) + if window.hidden.Swap(false) && window.onShow != nil { + window.onShow() + } window.control.Show() } @@ -262,7 +267,7 @@ func (application *Application) OpenWindow(config Config, canvas *gfx.Canvas) (* if application == nil || application.host == nil { return nil, errors.New("app: application is not running") } - window := &Window{} + window := &Window{onShow: config.OnShow} config.attachPosts() application.mu.Lock() if application.windows == nil { diff --git a/app/application_test.go b/app/application_test.go index e86cfbc33..7461ad1ff 100644 --- a/app/application_test.go +++ b/app/application_test.go @@ -278,6 +278,50 @@ func TestHiddenWindowStaysOpenAndShowBringsItBack(t *testing.T) { } } +// A window that hides on close puts back what it holds when it is shown again, +// before it is on screen; a raise or a restore from minimized is not a return. +func TestOnShowRunsWhenAHiddenWindowComesBack(t *testing.T) { + host := &fakeHost{} + useHost(t, host) + var window *Window + var shown []int // the native shows already made when OnShow ran + if err := RunApplication(func(application *Application) error { + var err error + window, err = application.OpenWindow(Config{Title: "main", OnShow: func() { + shown = append(shown, host.windows[0].shows) + }}, nil) + return err + }); err != nil { + t.Fatal(err) + } + window.Show() + host.windows[0].config.OnMinimize(true) + window.Show() + if len(shown) != 0 { + t.Fatalf("OnShow ran for a window that was on screen: %v", shown) + } + window.Hide() + window.Show() + window.Show() + if len(shown) != 1 || shown[0] != host.windows[0].shows-2 { + t.Fatalf("OnShow calls = %v with native shows %d, want one before the hidden window's show", shown, host.windows[0].shows) + } + if runtime.GOOS == "darwin" { + window.Hide() + host.windows[0].config.onReopen() + if len(shown) != 2 { + t.Fatalf("a Dock reopen of the hidden window did not run OnShow: %v", shown) + } + } + calls := len(shown) + window.Hide() + window.Close() + window.Show() + if len(shown) != calls { + t.Fatalf("a closed window ran OnShow: %v", shown) + } +} + func TestDockReopenThenHideReachesNativeWindow(t *testing.T) { if runtime.GOOS != "darwin" { t.Skip("Dock reopen is macOS-specific") diff --git a/app/capabilities.go b/app/capabilities.go index cae63c14e..bf708181b 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -69,6 +69,10 @@ const ( // CapabilityWindowWatermark means native text patterns can cover canvas and // embedded native views without receiving input. CapabilityWindowWatermark + // CapabilityElevatedLaunch means StartElevated can start a copy of the + // program with administrator rights after the system's consent prompt. + // Only Windows has one. + CapabilityElevatedLaunch ) // Capabilities is a set of platform integrations. diff --git a/app/capabilities_native.go b/app/capabilities_native.go index 9e88abdd5..b6987e5ab 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -42,6 +42,6 @@ func nativeCapabilities() Capabilities { } else { capabilities |= CapabilityWindowMaximize } - capabilities |= capabilityTransparentWindow | capabilityNotificationActivation | capabilityWindowWatermark + capabilities |= capabilityTransparentWindow | capabilityNotificationActivation | capabilityWindowWatermark | capabilityElevatedLaunch return Capabilities(capabilities) } diff --git a/app/capability_elevated_native.go b/app/capability_elevated_native.go new file mode 100644 index 000000000..89a81e863 --- /dev/null +++ b/app/capability_elevated_native.go @@ -0,0 +1,7 @@ +//go:build windows + +package app + +// capabilityElevatedLaunch reports that StartElevated can ask the system's +// consent prompt for administrator rights: Windows' User Account Control. +const capabilityElevatedLaunch = CapabilityElevatedLaunch diff --git a/app/capability_elevated_other.go b/app/capability_elevated_other.go new file mode 100644 index 000000000..ccf9eb8bc --- /dev/null +++ b/app/capability_elevated_other.go @@ -0,0 +1,7 @@ +//go:build !windows + +package app + +// capabilityElevatedLaunch is absent where no consent prompt raises a copy of +// the program; see capability_elevated_native.go. +const capabilityElevatedLaunch Capability = 0 diff --git a/app/driver_system.go b/app/driver_system.go index ddb776eae..85b8d8bd4 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -38,6 +38,11 @@ type driverSystem struct { schemes []string // the URL schemes SetSchemeHandlers declared as registered sleepMu sync.Mutex sleep map[string]int // sleep-prevention reasons this run holds, with their counts + // elevatedStarts are the command lines the application asked StartElevated + // to start, and elevatedResult is what the next requests answer. + elevatedMu sync.Mutex + elevatedStarts [][]string + elevatedResult error // dragFiles and dragAllowed are what the application last asked to drag out // of a driver-backed window, and dragTaken is the effect the driver's target // took from them; see driverStartFileDrag. dragPromises is the same for a @@ -306,6 +311,41 @@ func driverPreventSleep(reason string) (func(), error, bool) { }, nil, true } +// driverStartElevated answers StartElevated in a driver-backed run: it records +// the request instead of asking the system for administrator rights, so a +// headless test neither shows a consent prompt nor starts a second program. +func driverStartElevated(args []string) (bool, error) { + system := activeDriverSystem.Load() + if system == nil { + return false, nil + } + system.elevatedMu.Lock() + defer system.elevatedMu.Unlock() + system.elevatedStarts = append(system.elevatedStarts, append([]string(nil), args...)) + return true, system.elevatedResult +} + +// ElevatedStarts returns the command lines the application asked StartElevated +// to start in this driver-backed run, in order. +func (driver *Driver) ElevatedStarts() [][]string { + driver.system.elevatedMu.Lock() + defer driver.system.elevatedMu.Unlock() + starts := make([][]string, len(driver.system.elevatedStarts)) + for index, args := range driver.system.elevatedStarts { + starts[index] = append([]string(nil), args...) + } + return starts +} + +// SetElevatedStartResult makes StartElevated answer err from now on (nil, the +// default, is a started program; ErrElevationDeclined is a refused prompt), so +// a test can see how the application treats a refusal. +func (driver *Driver) SetElevatedStartResult(err error) { + driver.system.elevatedMu.Lock() + driver.system.elevatedResult = err + driver.system.elevatedMu.Unlock() +} + // AwakeReasons returns the sleep-prevention reasons a driver-backed run holds, // sorted, so a test can see what the application asked to keep awake. func (driver *Driver) AwakeReasons() []string { diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index 812d859f5..7ea42e214 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -67,3 +67,5 @@ func driverLoadSecret(string, string) ([]byte, error, bool) { return nil, nil, f func driverDeleteSecret(string, string) (error, bool) { return nil, false } func driverPreventSleep(string) (func(), error, bool) { return nil, nil, false } + +func driverStartElevated([]string) (bool, error) { return false, nil } diff --git a/app/elevate.go b/app/elevate.go new file mode 100644 index 000000000..a87af8af6 --- /dev/null +++ b/app/elevate.go @@ -0,0 +1,67 @@ +package app + +import ( + "errors" + "fmt" + "os" + "strings" + "unicode/utf8" +) + +// ErrElevationDeclined reports that StartElevated did not start the program +// because the user refused the system's consent prompt for administrator +// rights. It is a choice, not a failure: report nothing. +var ErrElevationDeclined = errors.New("app: elevation was declined") + +// maxElevatedArguments and maxElevatedArgumentLength bound what a request to +// start an elevated copy carries: the arguments are shown to nobody before the +// prompt, so they stay small and plain. +const ( + maxElevatedArguments = 64 + maxElevatedArgumentLength = 4096 +) + +// Elevated reports whether this process runs with an administrator's elevated +// token, as one started through StartElevated does. It is false on a platform +// without such a token (macOS and Linux have no consent prompt that raises a +// running user's own processes; a program there is started under sudo instead). +// Where Windows has User Account Control off, an administrator's every process +// reports true. Supports(CapabilityElevatedLaunch) tells whether StartElevated +// can work at all. +func Elevated() bool { return nativeElevated() } + +// StartElevated starts another copy of this program with administrator rights, +// after the system's consent prompt, and returns once the system has started it +// or the user has refused. It does not raise this process: a process keeps the +// rights it began with, and the elevated copy is a separate process with its own +// windows, which an ordinary-rights process cannot type into. That separation is +// the point of the call; an application that wants its elevated copy to share +// state with this one must say how, since the two must not write the same files +// at once. +// +// args are the command line of the new copy, without the program name. They are +// plain data: at most 64 of them, each valid UTF-8 without NUL bytes and at most +// 4096 bytes, and the new copy must treat them as a request from a process of +// lower rights, since any process of the user's can start it the same way. +// +// The refusal of the prompt is ErrElevationDeclined. A target without the +// capability returns an error wrapping ErrUnsupported. The call waits for the +// system, never starts a goroutine or timer, and is safe from any goroutine. +func StartElevated(args ...string) error { + if len(args) > maxElevatedArguments { + return fmt.Errorf("app: an elevated start takes at most %d arguments", maxElevatedArguments) + } + for _, argument := range args { + if !utf8.ValidString(argument) || strings.IndexByte(argument, 0) >= 0 || len(argument) > maxElevatedArgumentLength { + return errors.New("app: an elevated start argument must be valid UTF-8 without NUL bytes and at most 4096 bytes") + } + } + if handled, err := driverStartElevated(args); handled { + return err + } + executable, err := os.Executable() + if err != nil { + return err + } + return nativeStartElevated(executable, args) +} diff --git a/app/elevate_driver_test.go b/app/elevate_driver_test.go new file mode 100644 index 000000000..d82380f8f --- /dev/null +++ b/app/elevate_driver_test.go @@ -0,0 +1,45 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "slices" + "testing" +) + +func TestDriverRecordsElevatedStartsWithoutAskingTheSystem(t *testing.T) { + driver, err := NewDriver(Config{}, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + + if err := StartElevated("--shell=C:\\Windows\\System32\\cmd.exe", "two words"); err != nil { + t.Fatalf("a driver run refused an elevated start: %v", err) + } + starts := driver.ElevatedStarts() + if len(starts) != 1 || !slices.Equal(starts[0], []string{"--shell=C:\\Windows\\System32\\cmd.exe", "two words"}) { + t.Fatalf("ElevatedStarts = %q", starts) + } + starts[0][0] = "changed" + if driver.ElevatedStarts()[0][0] == "changed" { + t.Fatal("ElevatedStarts hands out the driver's own slice") + } +} + +func TestDriverAnswersAnElevatedStartWithTheQueuedResult(t *testing.T) { + driver, err := NewDriver(Config{}, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + + driver.SetElevatedStartResult(ErrElevationDeclined) + if err := StartElevated("x"); !errors.Is(err, ErrElevationDeclined) { + t.Fatalf("StartElevated = %v, want the declined prompt", err) + } + if len(driver.ElevatedStarts()) != 1 { + t.Fatal("a declined request is still a request the application made") + } +} diff --git a/app/elevate_other.go b/app/elevate_other.go new file mode 100644 index 000000000..65c87e3d0 --- /dev/null +++ b/app/elevate_other.go @@ -0,0 +1,11 @@ +//go:build !windows + +package app + +import "fmt" + +func nativeElevated() bool { return false } + +func nativeStartElevated(string, []string) error { + return fmt.Errorf("%w: elevated start", ErrUnsupported) +} diff --git a/app/elevate_test.go b/app/elevate_test.go new file mode 100644 index 000000000..353de5446 --- /dev/null +++ b/app/elevate_test.go @@ -0,0 +1,26 @@ +package app + +import ( + "strings" + "testing" +) + +func TestStartElevatedRejectsArgumentsAProgramCannotReceive(t *testing.T) { + tooMany := make([]string, maxElevatedArguments+1) + for _, args := range [][]string{ + {"a\x00b"}, + {"\xff\xfe"}, + {strings.Repeat("x", maxElevatedArgumentLength+1)}, + tooMany, + } { + if err := StartElevated(args...); err == nil { + t.Fatalf("StartElevated accepted %d arguments, first %.20q", len(args), strings.Join(args, " ")) + } + } +} + +func TestElevatedIsFalseWhereNoConsentPromptExists(t *testing.T) { + if !Supports(CapabilityElevatedLaunch) && Elevated() { + t.Fatal("a target without elevated launches reports an elevated process") + } +} diff --git a/app/elevate_windows.go b/app/elevate_windows.go new file mode 100644 index 000000000..21bfe178e --- /dev/null +++ b/app/elevate_windows.go @@ -0,0 +1,20 @@ +//go:build windows + +package app + +import ( + "errors" + "fmt" + + windowsplatform "github.com/vivaui/viva/internal/platform/windows" +) + +func nativeElevated() bool { return windowsplatform.Elevated() } + +func nativeStartElevated(executable string, args []string) error { + err := windowsplatform.StartElevated(executable, args) + if errors.Is(err, windowsplatform.ErrElevationDeclined) { + return fmt.Errorf("%w", ErrElevationDeclined) + } + return err +} diff --git a/base/elements.go b/base/elements.go index 964f6a37d..e2db6f99a 100644 --- a/base/elements.go +++ b/base/elements.go @@ -329,9 +329,12 @@ func textFieldOf[T TextValue](c C, Value T, Label, placeholder string, Base bool func TextArea[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { p := c.page field, id := namedFieldOf(p, pkArea, Value, namedBy("TextArea", opts)) - maxRunes, _ := limitsOf(opts) + maxRunes, count := limitsOf(opts) field.limit(maxRunes) b := c.f.FieldArea(field, id, Label, placeholder) + if count { + WidgetsOf(c.f).textareas[b.N().Aux].Count = field.countText() + } c.f.bindField(b, field) if p.areaKey == nil { p.keyRoute, p.areaKey = (*Page).RouteKey, (*Field).Key // Up and Down by row diff --git a/base/frame.go b/base/frame.go index 3b2001f83..3ec709704 100644 --- a/base/frame.go +++ b/base/frame.go @@ -199,6 +199,8 @@ type Extra struct { glide gfx.Motion // Glide: how the element slides to a place the layout moves it to glided bool glideScroll gfx.Point + glideHold float32 // how much of a list row that has come in shows while the rows below it slide down to make room + glideHeld bool // glideHold applies presence gfx.Presence // Presence: how the element enters and leaves presenced bool pose gfx.Pose // Pose: where the element sits relative to its place @@ -445,10 +447,14 @@ func (f *Frame) End() { } f.shiftedX = false } + // Sticky elements are held before the popups are placed, so a popup that hangs + // off one opens where it is seen. + f.placeSticky(false) for _, index := range f.Floats { f.placePopup(&f.Nodes[index], AxisY) f.solve(index, AxisY) } + f.placeSticky(true) f.reportScrolls() f.Scrolls.sweep() f.reportSplitters() @@ -461,6 +467,9 @@ func (f *Frame) End() { f.ellipsis = ellipsisState{} f.setEllipsis(ellipsisState{on: f.page.config.EllipsisTooltips}) } + if f.page != nil { + f.page.holdGlidedRows() + } f.PaintChild(0) f.raiseOverNativeViews() if f.popupLayer != 0 { @@ -525,6 +534,8 @@ func (f *Frame) trim() { f.Wraps = trimFlexCapacity(f.Wraps) trimControls(f) f.scratch.abs = trimFlexCapacity(f.scratch.abs) + f.scratch.sticky = trimFlexCapacity(f.scratch.sticky) + f.scratch.stuck = trimFlexCapacity(f.scratch.stuck) f.scratch.rows = trimFlexCapacity(f.scratch.rows) f.scratch.rowAt = trimFlexCapacity(f.scratch.rowAt) f.scratch.cells = trimFlexCapacity(f.scratch.cells) diff --git a/base/layout_custom.go b/base/layout_custom.go index 4299c026e..c355de75c 100644 --- a/base/layout_custom.go +++ b/base/layout_custom.go @@ -192,6 +192,12 @@ func (f *Frame) shiftSubtreeX(i int32, delta float32) { if delta == 0 { return } + f.shiftSubtree(i, AxisX, delta) + f.shiftedX = true +} + +// shiftSubtree moves the descendants of element i by delta on an axis. +func (f *Frame) shiftSubtree(i int32, axis int, delta float32) { start := int(i) + 1 end := start for end < len(f.Nodes) { @@ -208,7 +214,6 @@ func (f *Frame) shiftSubtreeX(i int32, delta float32) { end++ } for j := start; j < end; j++ { - f.Nodes[j].Rect.X += delta + *origin(&f.Nodes[j].Rect, axis) += delta } - f.shiftedX = true } diff --git a/base/list.go b/base/list.go index f27fea8fe..e27287e1d 100644 --- a/base/list.go +++ b/base/list.go @@ -24,7 +24,9 @@ type ListState struct { // Glide, when it has a duration, slides a row to the place the list gives it // after rows were added, removed or moved above or among them, instead of // letting it jump: rows must have a Key to keep their identity, and a scroll is - // not a move. The zero Motion keeps the rows where the list puts them. + // not a move. A row that comes in is revealed as the rows below it slide down to + // make room, so it never runs over them. The zero Motion keeps the rows where the + // list puts them. Glide gfx.Motion // Label is the text of row i: typing the first letters of a row's text while // the list has the keyboard focus chooses it. It is also the row's name for @@ -1382,3 +1384,47 @@ func (p *Page) ListType(event gfx.KeyEvent) (gfx.EventResult, bool) { } return gfx.EventResult{}, false } + +// holdGlidedRows works out, before the page paints, how much of each row of a +// list that glides may show. A row that came in is placed where the layout +// puts it at once, while the rows below it are still sliding down from where they +// were: it would be painted over them. It shows down to the top of the highest of +// those rows, which grows to the full row as they arrive, so the rows open like a +// folder rather than land on the ones below. A row that is itself sliding is left +// alone: two rows that change places pass each other, and both are seen to. It runs +// in the layout's frame, after the rows are placed and before they are painted, on +// the places the canvas shows, and costs a lookup of each visible row in the +// canvas's glides. +func (p *Page) holdGlidedRows() { + f := p.ctx.f + canvas := f.Surface + if canvas == nil { + return + } + for _, list := range p.lists { + if list.state.Glide.Duration <= 0 { + continue + } + below := float32(math.MaxFloat32) // the top of the highest row after this one that is shown above where it will be + rows := p.listRows[list.rows:list.until] + for k := len(rows) - 1; k >= 0; k-- { + n := &f.Nodes[rows[k]] + extra := &f.Exts[n.Ext] + if !extra.glided { + continue + } + layout := n.Rect.Y + extra.glideScroll.Y + shown, known := layout, false + if id := extra.glideIdentity(n); !id.IsZero() { + if at, ok := canvas.GlideShown(id); ok { + shown, known = at.Y, true + } + } + resting := !known || shown-layout < 0.01 && layout-shown < 0.01 + if resting && below < layout+n.Rect.Height-0.01 { + extra.glideHold, extra.glideHeld = max(below-shown, 0), true + } + below = min(below, shown) + } + } +} diff --git a/base/list_glide_test.go b/base/list_glide_test.go index b9ccb0bb5..f2d3b2de6 100644 --- a/base/list_glide_test.go +++ b/base/list_glide_test.go @@ -66,3 +66,153 @@ func TestListGlideSlidesRowsAfterOneIsRemoved(t *testing.T) { t.Fatalf("arrived = %v animating=%v", got, canvas.Animating()) } } + +// glideRig is a vertical list of 40 pixel rows that glides, painted at a clock the +// test moves. rows are the keys shown top to bottom. +type glideRig struct { + page *Page + canvas *gfx.Canvas + list ListState + keys []int + now time.Duration + ids map[int]gfx.ID +} + +func newGlideRig(keys ...int) *glideRig { + theme := gfx.LightTheme() + rig := &glideRig{page: NewPage(PageConfig{Theme: &theme}), canvas: testCanvas(), keys: keys, ids: map[int]gfx.ID{}} + rig.canvas.SetClock(func() time.Duration { return rig.now }) + rig.list.Key = func(i int) int { return rig.keys[i] } + rig.list.Glide = gfx.Motion{Duration: 100 * time.Millisecond, Easing: gfx.EaseLinear} + return rig +} + +// frame paints at time at and returns, for each key, the pixels of that row's +// background that are painted: the top and the bottom edge the eye sees. +func (rig *glideRig) frame(at time.Duration) map[int][2]float32 { + rig.now = at + rig.canvas.Reset() + rig.canvas.BeginFrame() + rig.page.Draw(rig.canvas, gfx.Rect{Width: 200, Height: 400}, func(c C) { + Column(c).Fill().Children(func() { + List(c, &rig.list, len(rig.keys), func(row ListRow) { + row.Element.Height(40).Background(gfx.Color{Red: float32(row.Key) / 10, Alpha: 1}) + rig.ids[row.Key] = row.ID + }).Grow(1).MinHeight(0) + }) + }) + rig.canvas.EndFrame() + // What the eye sees of a row is its background as painted, cut by the clip it + // was painted under. Each row has its own colour, which names it. + shown := map[int][2]float32{} + for _, rectangle := range rig.canvas.Rectangles() { + key := int(rectangle.Color.Red*10 + 0.5) + if _, ours := rig.ids[key]; !ours || rectangle.Bounds.Height != 40 { + continue + } + top, bottom := rectangle.Bounds.Y, rectangle.Bounds.Y+rectangle.Bounds.Height + if rectangle.HasClip { + top, bottom = max(top, rectangle.ClipOf.Y), min(bottom, rectangle.ClipOf.Y+rectangle.ClipOf.Height) + } + if bottom <= top { + continue // cut away entirely: nothing of it is seen + } + shown[key] = [2]float32{top, bottom} + } + return shown +} + +// A row that comes in above rows that are still sliding down must not be painted +// over them: it shows down to where the next row is, and grows as that row moves. +// This is a group opening in a list of groups and hosts. +func TestListGlideRevealsARowThatComesInInsteadOfRunningOverTheRowsBelow(t *testing.T) { + rig := newGlideRig(1, 9) + rig.frame(0) + rig.frame(10 * time.Millisecond) + // Rows 2 and 3 come in between: row 9 is laid out 80 below where it is seen. + rig.keys = []int{1, 2, 3, 9} + first := rig.frame(time.Second) + if first[9][0] != 40 { + t.Fatalf("row 9 starts at %v, want the old place 40", first[9][0]) + } + for _, key := range []int{2, 3} { + if seen, ok := first[key]; ok { + t.Fatalf("row %d shows %v before anything has moved, want none of it", key, seen) + } + } + // Half way through, row 9 is 40 down and has opened room for row 2 only. + middle := rig.frame(time.Second + 50*time.Millisecond) + if !rig.canvas.Animating() { + t.Fatal("the slide is not animating") + } + if got := middle[2][1] - middle[2][0]; got <= 1 || got > 40.5 { + t.Fatalf("row 2 shows %v pixels half way, want some of 40", got) + } + if _, ok := middle[3]; ok { + t.Fatalf("row 3 shows %v before the room for it has opened", middle[3]) + } + for _, key := range []int{2, 3} { + if seen, ok := middle[key]; ok && seen[1] > middle[9][0]+0.5 { + t.Fatalf("row %d reaches %v, over row 9 at %v", key, seen[1], middle[9][0]) + } + } + end := rig.frame(2 * time.Second) + if rig.canvas.Animating() { + t.Fatal("the slide did not end") + } + for key, want := range map[int][2]float32{1: {0, 40}, 2: {40, 80}, 3: {80, 120}, 9: {120, 160}} { + if end[key] != want { + t.Fatalf("row %d ends at %v, want %v", key, end[key], want) + } + } +} + +// Rows that were already there slide with the rows around them and keep all of +// themselves: only a row that came in is held to the room that has opened. +func TestListGlideKeepsWholeTheRowsThatWereAlreadyThere(t *testing.T) { + rig := newGlideRig(1, 2, 3) + rig.frame(0) + rig.frame(10 * time.Millisecond) + rig.keys = []int{1, 3, 2} // 2 and 3 change places + rig.frame(time.Second) + middle := rig.frame(time.Second + 50*time.Millisecond) + for _, key := range []int{2, 3} { + if got := middle[key][1] - middle[key][0]; got != 40 { + t.Fatalf("row %d shows %v pixels while it slides past its neighbour, want all 40", key, got) + } + } +} + +// A list at rest, and one whose canvas has no clock, are not held to anything. +func TestListGlideHoldsNothingAtRestOrWithoutAClock(t *testing.T) { + rig := newGlideRig(1, 2, 3) + rig.frame(0) + rest := rig.frame(time.Second) + for key, want := range map[int][2]float32{1: {0, 40}, 2: {40, 80}, 3: {80, 120}} { + if rest[key] != want { + t.Fatalf("row %d at rest is %v, want %v", key, rest[key], want) + } + } + rig.canvas.SetReduceMotion(true) + rig.keys = []int{1, 5, 2, 3} + jumped := rig.frame(2 * time.Second) + if jumped[5] != [2]float32{40, 80} || jumped[3] != [2]float32{120, 160} { + t.Fatalf("under reduced motion rows are %v and %v, want them where the layout puts them", jumped[5], jumped[3]) + } +} + +// Folding a group is the other way: the rows below slide up under rows that are +// leaving, and the rows that stay are not cut. +func TestListGlideKeepsTheRowsThatStayWhenRowsAboveThemGoAway(t *testing.T) { + rig := newGlideRig(1, 2, 3, 9) + rig.frame(0) + rig.frame(10 * time.Millisecond) + rig.keys = []int{1, 9} + rig.frame(time.Second) + middle := rig.frame(time.Second + 50*time.Millisecond) + for _, key := range []int{1, 9} { + if got := middle[key][1] - middle[key][0]; got != 40 { + t.Fatalf("row %d shows %v pixels while rows fold away, want all 40", key, got) + } + } +} diff --git a/base/option.go b/base/option.go index c28e1a289..c243725f0 100644 --- a/base/option.go +++ b/base/option.go @@ -47,8 +47,8 @@ func groupsOf(opts []Option) []SelectGroup { func MaxLength(n int) Option { return Option{maxRunes: n} } // ShowCount shows how many runes a TextField or TextArea holds, and of how many -// when MaxLength caps it ("12/32"), at the end of the field. It takes the place of -// an Action. +// when MaxLength caps it ("12/32"): at the end of a TextField, in the place of an +// Action, and at the end of a row of its own under a TextArea's text. // // ui.TextField(c, &m.title, "Title", "", ui.MaxLength(80), ui.ShowCount()) func ShowCount() Option { return Option{count: true} } diff --git a/base/paint.go b/base/paint.go index 2a6787566..1d8238250 100644 --- a/base/paint.go +++ b/base/paint.go @@ -84,6 +84,10 @@ func (f *Frame) paintElement(i int32) { if extra := &f.Exts[n.Ext]; extra.glided && f.Surface != nil && !extra.glideIdentity(n).IsZero() { f.Surface.BeginGlide(extra.glideIdentity(n), 0, gfx.Point{X: n.Rect.X + extra.glideScroll.X, Y: n.Rect.Y + extra.glideScroll.Y}, extra.glide) defer f.Surface.EndPose() + if extra.glideHeld { + f.Surface.Clip(Rect{X: n.Rect.X, Y: n.Rect.Y, Width: n.Rect.Width, Height: extra.glideHold}) + defer f.Surface.Unclip() + } } if memo := f.Exts[n.Ext].memo; memo != 0 && f.memoFn != nil && f.area == nil { if f.memoFn(f, i, true) { @@ -247,6 +251,7 @@ func (f *Frame) paintElement(i int32) { if hooks.under != nil { f.runDraw(n, hooks.under) } + clipsBelow := 0 for c := n.First; c >= 0; c = f.Nodes[c].Next { // PaintChild written out: it does not inline, and this loop paints // nearly every element. @@ -255,6 +260,18 @@ func (f *Frame) paintElement(i int32) { } else { f.paintElement(c) } + if n.OutOfFlow&stickyChildren != 0 && canvas != nil { + // What follows a held sticky child is cut off below it, in paint and in + // hits, so the child covers its group without changing the paint order + // Tab and reading follow. + if below, held := f.stuckBelow(n, c); held { + canvas.Clip(below) + clipsBelow++ + } + } + } + for ; clipsBelow > 0; clipsBelow-- { + canvas.Unclip() } if n.OutOfFlow&absChildren != 0 { f.paintAbsolute(i) diff --git a/base/scratch.go b/base/scratch.go index d6da402bb..fa959b093 100644 --- a/base/scratch.go +++ b/base/scratch.go @@ -5,14 +5,16 @@ import "unsafe" // scratch is the memory the layout borrows beyond the node tree, reused from frame to // frame so a warm page allocates nothing. type scratch struct { - theme Theme // the theme of the element a recipe is applied to - abs []int32 // the absolute elements, in the order declared - rows []float32 // the height of each row of the Grid being laid out - rowAt []float32 // the offset of each of its rows - cells []bool // which cells of a Grid row-spanning elements have taken + theme Theme // the theme of the element a recipe is applied to + abs []int32 // the absolute elements, in the order declared + sticky []int32 // the sticky elements + stuck []int32 // the sticky elements held away from their place in the flow + rows []float32 // the height of each row of the Grid being laid out + rowAt []float32 // the offset of each of its rows + cells []bool // which cells of a Grid row-spanning elements have taken } -func (s *scratch) reset() { s.abs = s.abs[:0] } +func (s *scratch) reset() { s.abs, s.sticky, s.stuck = s.abs[:0], s.sticky[:0], s.stuck[:0] } // frameTails is the length each pointer-holding slice of a Frame had when the // last frame ended. diff --git a/base/sticky.go b/base/sticky.go new file mode 100644 index 000000000..e62d91f7e --- /dev/null +++ b/base/sticky.go @@ -0,0 +1,107 @@ +package base + +import "github.com/vivaui/viva/gfx" + +// Sticky positioning keeps an element in its container's flow, where it takes its +// room as usual, but once the nearest enclosing Scroll has scrolled that place above +// the top of its viewport, holds the element at the top instead, the way CSS +// position: sticky with top: 0 does: +// +// f.Scroll(offset).Children(func() { +// for _, group := range groups { +// f.Column().Children(func() { +// f.Row().Sticky().Background(theme.Card).Children(header) +// rows(group) +// }) +// } +// }) +// +// The element goes no further than the end of its container, so the next group's +// header pushes the one before it away. Its whole subtree moves with it: what it +// paints, its hits and focus ring, and the popups that hang off it. It is painted in +// its place in the tree, so Tab, reading order and accessibility are unchanged; while +// it is held, what its container paints after it is clipped below it, so nothing of +// the group shows or takes a press behind it. Give it a background of its own. +// +// An element with no Scroll around it stays where the flow put it. A Popup, the root +// and an Absolute element cannot be sticky. + +// Bits of node.OutOfFlow, after the absolute ones. +const ( + stickySelf uint8 = 1 << 6 // the element is sticky + stickyChildren uint8 = 1 << 7 // the container has sticky children +) + +// Sticky holds the element at the top of the nearest enclosing Scroll's viewport +// while its place in the flow is scrolled above it, no further than the end of its +// container. See the package's notes on sticky positioning above. +func (b Box) Sticky() Box { + f, n := b.f, b.N() + if n.OutOfFlow&(stickySelf|absSelf) != 0 || n.Parent < 0 { + return b + } + n.OutOfFlow |= stickySelf + f.Nodes[n.Parent].OutOfFlow |= stickyChildren + f.scratch.sticky = append(f.scratch.sticky, b.i) + return b +} + +// placeSticky moves the sticky elements of the page, or of its popups, from where +// the flow put them to where they are held, once both axes are laid out. Elements +// are taken in the order of the tree, so a sticky element inside another moves with +// it first and is then held against its own Scroll. +func (f *Frame) placeSticky(popups bool) { + list := f.scratch.sticky + for k := 1; k < len(list); k++ { + for j := k; j > 0 && list[j] < list[j-1]; j-- { + list[j], list[j-1] = list[j-1], list[j] + } + } + for _, i := range list { + if (f.rootOf(i) != 0) != popups { + continue + } + n := &f.Nodes[i] + if n.OutOfFlow&absSelf != 0 { + continue + } + scroll := n.Parent + for scroll >= 0 && f.Nodes[scroll].Flags&flagScroll == 0 { + scroll = f.Nodes[scroll].Parent + } + if scroll < 0 { + continue + } + area := &f.Nodes[scroll] + held := area.Rect.Y + if area.Flags&flagOutline == 0 { + held += area.BorderWidth + } + if n.Parent != scroll { + // The container's content ends above its bottom padding and border, and + // the element keeps its own bottom margin inside it. + parent := &f.Nodes[n.Parent] + _, end := parent.Inset(AxisY) + held = min(held, parent.Rect.Y+parent.Rect.Height-end-n.Margin[2]-n.Rect.Height) + } + if delta := snapScroll(held - n.Rect.Y); delta > 0 { + n.Rect.Y += delta + f.shiftSubtree(i, AxisY, delta) + f.scratch.stuck = append(f.scratch.stuck, i) + } + } +} + +// stuckBelow is the clip for what container n paints after its sticky child c: the +// container below c's bottom edge, while c is held away from its place in the flow. +func (f *Frame) stuckBelow(n *Node, c int32) (gfx.Rect, bool) { + for _, i := range f.scratch.stuck { + if i != c { + continue + } + child := &f.Nodes[c] + bottom := child.Rect.Y + child.Rect.Height + child.Margin[2] + return gfx.Rect{X: n.Rect.X, Y: bottom, Width: n.Rect.Width, Height: max(n.Rect.Y+n.Rect.Height-bottom, 0)}, true + } + return gfx.Rect{}, false +} diff --git a/base/sticky_test.go b/base/sticky_test.go new file mode 100644 index 000000000..4dcc1af75 --- /dev/null +++ b/base/sticky_test.go @@ -0,0 +1,170 @@ +package base + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// stickyPage is a Scroll of two groups, each a sticky header holding a toggle +// over three rows that each hold a button. +type stickyPage struct { + scroll Box + groups [2]Box + headers [2]Box + toggles [2]Box + rows [2][3]Box + headerH, rowH float32 + viewport float32 + plain bool // the headers are ordinary rows, for comparison +} + +func paintStickyPage(view *View, canvas *gfx.Canvas, offset float32) *stickyPage { + page := &stickyPage{} + page.paint(view, canvas, offset) + return page +} + +func (page *stickyPage) paint(view *View, canvas *gfx.Canvas, offset float32) { + page.headerH, page.rowH, page.viewport = 24, 40, 100 + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 200, Height: 300}) + page.scroll = f.Scroll(offset).Height(page.viewport).Children(func() { + for g := range page.groups { + page.groups[g] = f.Column().FillWidth().Children(func() { + header := f.Row() + if !page.plain { + header = header.Sticky() + } + page.headers[g] = header.FillWidth().Height(page.headerH).Background(gfx.RGB(1, 2, 3)).Children(func() { + page.toggles[g] = f.Slot().Size(20, 20).Hit(gfx.Item(100+g), "Collapse") + }) + for r := range page.rows[g] { + page.rows[g][r] = f.Slot().FillWidth().Height(page.rowH).Hit(gfx.Item(200+10*g+r), "Row") + } + }) + } + }) + f.End() +} + +func TestStickyHeaderHoldsAtTheTopAndIsPushedByTheNextGroup(t *testing.T) { + var view View + canvas := testCanvas() + top := float32(0) + for _, offset := range []float32{0, 30, 60, 100, 130, 200} { + canvas.Reset() + page := paintStickyPage(&view, canvas, offset) + for g, header := range page.headers { + group := page.groups[g].Rect() + natural := group.Y // the header is the group's first child + got := header.Rect() + want := max(natural, min(top, group.Y+group.Height-page.headerH)) + if got.Y != want { + t.Fatalf("offset %v: group %d header at %v, want %v (natural %v, group ends %v)", + offset, g, got.Y, want, natural, group.Y+group.Height) + } + if got.Y < natural || got.Y+got.Height > group.Y+group.Height { + t.Fatalf("offset %v: group %d header %+v leaves its group %+v", offset, g, got, group) + } + toggle := page.toggles[g].Rect() + if toggle.Y < got.Y || toggle.Y+toggle.Height > got.Y+got.Height { + t.Fatalf("offset %v: the toggle %+v did not move with its header %+v", offset, toggle, got) + } + } + if a, b := page.headers[0].Rect(), page.headers[1].Rect(); a.Y+a.Height > b.Y { + t.Fatalf("offset %v: the first header %+v overlaps the second %+v", offset, a, b) + } + if got := page.scroll.Content(); got != 2*(page.headerH+3*page.rowH) { + t.Fatalf("offset %v: the Scroll's content is %v; holding a header must not change it", offset, got) + } + } +} + +// A press on the band a held header covers reaches the header's control, not the +// row scrolled under it, and Tab still visits the header before its rows. +func TestStickyHeaderCoversItsGroupWithoutReorderingTab(t *testing.T) { + var view View + canvas := testCanvas() + page := paintStickyPage(&view, canvas, 30) + header, toggle := page.headers[0].Rect(), page.toggles[0].Rect() + if header.Y != 0 { + t.Fatalf("header at %v, want it held at the top", header.Y) + } + under := page.rows[0][0].Rect() // y -6..34: partly under the header + if under.Y >= header.Y+header.Height || under.Y+under.Height <= header.Y { + t.Fatalf("the first row %+v is not under the held header %+v", under, header) + } + x, y := toggle.X+toggle.Width/2, toggle.Y+toggle.Height/2 + if got := topHit(canvas, x, y); got != gfx.Item(100) { + t.Fatalf("a press on the held header's toggle reaches %v", got) + } + if got := topHit(canvas, header.X+header.Width-2, header.Y+header.Height-2); got == gfx.Item(200) { + t.Fatal("a press on the held header reaches the row scrolled under it") + } + if got := topHit(canvas, under.X+4, header.Y+header.Height+2); got != gfx.Item(200) { + t.Fatalf("below the header the row is still pressable, got %v", got) + } + order := map[gfx.ID]int{} + for index, hit := range canvas.Hits() { + if _, seen := order[hit.ID]; !seen { + order[hit.ID] = index + } + } + if order[gfx.Item(100)] > order[gfx.Item(200)] { + t.Fatal("the held header's toggle comes after its rows in paint order, which Tab follows") + } +} + +func TestStickyElementWithoutAScrollStaysInTheFlow(t *testing.T) { + var view View + var header, first Box + f := view.Begin(testCanvas(), gfx.LightTheme(), gfx.Rect{Width: 200, Height: 300}) + f.Column().Children(func() { + first = f.Slot().Height(30) + header = f.Row().Sticky().Height(20) + }) + f.End() + if got := header.Rect().Y; got != first.Rect().Y+first.Rect().Height { + t.Fatalf("a sticky row with no Scroll around it is at %v, want its place in the flow", got) + } +} + +func TestPopupHangsOffAHeldStickyHeader(t *testing.T) { + var view View + var header, popup Box + f := view.Begin(testCanvas(), gfx.LightTheme(), gfx.Rect{Width: 200, Height: 300}) + f.Scroll(60).Height(100).Children(func() { + f.Column().FillWidth().Children(func() { + header = f.Row().Sticky().FillWidth().Height(20) + f.Slot().Height(400) + }) + }) + popup = f.Popup().Size(80, 40).BelowBox(header, 4, Start) + f.End() + if got, want := popup.Rect().Y, header.Rect().Y+header.Rect().Height+4; got != want { + t.Fatalf("the popup opens at %v, want under the held header at %v", got, want) + } +} + +// Holding headers costs a warm page no allocation beyond what the same page with +// ordinary rows costs. +func TestStickyAddsNoAllocationToAWarmPaint(t *testing.T) { + allocs := func(plain bool) float64 { + var view View + canvas := testCanvas() + page := stickyPage{plain: plain} + offset := float32(0) + paint := func() { + canvas.Reset() + offset = 130 - offset // held, pushed and back + page.paint(&view, canvas, offset) + } + for range 3 { + paint() + } + return testing.AllocsPerRun(50, paint) + } + if sticky, plain := allocs(false), allocs(true); sticky > plain { + t.Fatalf("a warm sticky page allocates %v times a paint, %v with ordinary rows", sticky, plain) + } +} diff --git a/base/text_selection.go b/base/text_selection.go index 6a7fa3dae..b4d0c6afb 100644 --- a/base/text_selection.go +++ b/base/text_selection.go @@ -3,8 +3,19 @@ package base import ( "math" "strings" + "unicode/utf8" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// selectUnit is what a press selects and a drag extends by. +type selectUnit uint8 + +const ( + unitChar selectUnit = iota + unitWord + unitLine ) // TextPoint is a place in a run of painted texts that a selection can cross: @@ -33,9 +44,14 @@ func (point TextPoint) before(other TextPoint) bool { // schedules no work: the caller repaints when a result says the selection // changed. type TextSelection struct { - Anchor TextPoint - Focus TextPoint - dragging bool + Anchor TextPoint + Focus TextPoint + + dragging bool + unit selectUnit + origin [2]TextPoint + anchorAt TextPoint + hasAnchor bool } // TextRange is the selected part of one text, in byte offsets: of a Text in a @@ -134,7 +150,8 @@ func (selection *TextSelection) SelectAll(surfaces int, length func(surface int) // Pointer follows one pointer event. A primary press begins a selection at the // point at() reports for it; a held move extends it; the release ends the drag // and drops a selection that covers nothing; the pointer leaving the window -// ends the drag and keeps what was selected. +// ends the drag and keeps what was selected. It selects by character: for words, +// lines and Shift extension see PointerWithText. // // at maps a window point to a place in the surfaces: the surface the point is // over, or the nearest, and the offset in it. It reports false for a point that @@ -143,6 +160,31 @@ func (selection *TextSelection) SelectAll(surfaces int, length func(surface int) // go on. A press that should not start a selection, such as one on a link or a // button painted over the text, is the caller's to keep from reaching Pointer. func (selection *TextSelection) Pointer(event gfx.PointerEvent, at func(gfx.Point) (TextPoint, bool)) TextSelectionResult { + return selection.pointer(event, at, nil, false) +} + +// PointerWithText follows one pointer event like Pointer, adding click-count +// granularity and Shift+click extension using each surface's text: two clicks +// select a word and drag by words, three or more select a logical line and drag +// by lines, and a single press with Shift extends from the last press or anchor. +// +// textOf returns the full plain text of a surface without copying it (for +// example MarkdownView.PlainText). It is only read during the call and need +// not be retained; if nil, PointerWithText falls back to character granularity. +func (selection *TextSelection) PointerWithText( + event gfx.PointerEvent, + at func(gfx.Point) (TextPoint, bool), + textOf func(surface int) string, +) TextSelectionResult { + return selection.pointer(event, at, textOf, true) +} + +func (selection *TextSelection) pointer( + event gfx.PointerEvent, + at func(gfx.Point) (TextPoint, bool), + textOf func(surface int) string, + clickAware bool, +) TextSelectionResult { point := gfx.Point{X: event.X, Y: event.Y} switch event.Kind { case gfx.PointerDown: @@ -153,29 +195,38 @@ func (selection *TextSelection) Pointer(event gfx.PointerEvent, at func(gfx.Poin if !ok { return TextSelectionResult{} } - *selection = TextSelection{Anchor: place, Focus: place, dragging: true} + if !clickAware { + *selection = TextSelection{Anchor: place, Focus: place, dragging: true} + return TextSelectionResult{Handled: true, Changed: true} + } + clicks := max(event.ClickCount, 1) + if textOf == nil { + clicks = 1 + } + shift := event.Modifiers&gfx.ModifierShift != 0 + value := "" + if textOf != nil && (clicks > 1 || shift) { + value = textOf(place.Surface) + } + selection.press(place, clicks, shift, value) return TextSelectionResult{Handled: true, Changed: true} case gfx.PointerMove: if !selection.dragging || !event.Captured { return TextSelectionResult{} } place, ok := at(point) - if !ok || place == selection.Focus { + if !ok { return TextSelectionResult{Handled: true} } - selection.Focus = place - return TextSelectionResult{Handled: true, Changed: true} + return TextSelectionResult{Handled: true, Changed: selection.extend(place, selection.unitText(place, textOf))} case gfx.PointerUp: if !selection.dragging { return TextSelectionResult{} } if place, ok := at(point); ok { - selection.Focus = place - } - selection.dragging = false - if selection.Empty() { - selection.Clear() + selection.extend(place, selection.unitText(place, textOf)) } + selection.release() return TextSelectionResult{Handled: true, Changed: true} case gfx.PointerExit: // A held press keeps the pointer outside the window, and Exit reaches the @@ -190,6 +241,127 @@ func (selection *TextSelection) Pointer(event gfx.PointerEvent, at func(gfx.Poin return TextSelectionResult{} } +func selectUnitForClicks(clicks int) selectUnit { + switch { + case clicks >= 3: + return unitLine + case clicks == 2: + return unitWord + default: + return unitChar + } +} + +// press begins a selection at a place for a primary press of clicks clicks: +// a character for one, the word around it for two, the logical line for more. +// value is the text of the place's surface, read only for two clicks or more. +// A single press with shift extends the selection instead of beginning a new +// one: by the unit the selection was picked by, keeping that word or line +// whole, as double and triple presses do in other text, or by character from +// the last press if that selected nothing. value is also read for such a press. +func (selection *TextSelection) press(place TextPoint, clicks int, shift bool, value string) { + if shift && clicks == 1 && selection.unit != unitChar && !selection.Empty() { + selection.dragging = true + selection.extend(place, value) + return + } + if shift && clicks == 1 && (selection.hasAnchor || !selection.Empty()) { + anchor := selection.Anchor + if selection.Empty() { + anchor = selection.anchorAt + } + *selection = TextSelection{Anchor: anchor, Focus: place, dragging: true, anchorAt: anchor, hasAnchor: true} + return + } + unit := selectUnitForClicks(clicks) + from, to := selectionUnitSpan(unit, place, value) + *selection = TextSelection{ + Anchor: from, + Focus: to, + dragging: true, + unit: unit, + origin: [2]TextPoint{from, to}, + anchorAt: place, + hasAnchor: true, + } +} + +// unitText is the text extend reads for a place: the text of its surface when +// the press picked words or lines, and nothing for characters. +func (selection *TextSelection) unitText(place TextPoint, textOf func(surface int) string) string { + if selection.unit == unitChar || textOf == nil { + return "" + } + return textOf(place.Surface) +} + +// extend moves the selection to a place by the unit of its press, keeping the +// unit the press picked whole, and reports whether the selection changed. value +// is the text of the place's surface, read only for words and lines. +func (selection *TextSelection) extend(place TextPoint, value string) bool { + if selection.unit == unitChar { + changed := selection.Focus != place + selection.Focus = place + return changed + } + from, to := selectionUnitSpan(selection.unit, place, value) + anchor, focus := selection.origin[0], to + if from.before(selection.origin[0]) { + anchor, focus = selection.origin[1], from + } + changed := selection.Anchor != anchor || selection.Focus != focus + selection.Anchor, selection.Focus = anchor, focus + return changed +} + +// release ends the drag of a press, and drops a selection that covers nothing +// while keeping where the press began for a later Shift press. +func (selection *TextSelection) release() { + selection.dragging = false + if selection.Empty() { + selection.dropEmpty() + } +} + +// dropEmpty clears an empty selection, keeping where the last press began. +func (selection *TextSelection) dropEmpty() { + if !selection.hasAnchor { + selection.Clear() + return + } + *selection = TextSelection{anchorAt: selection.anchorAt, hasAnchor: true} +} + +// selectionUnitSpan returns the word or logical-line bounds around point inside +// value, or (point, point) for character granularity or empty text. +func selectionUnitSpan(unit selectUnit, point TextPoint, value string) (TextPoint, TextPoint) { + if unit == unitChar || value == "" { + return point, point + } + offset := min(max(point.Offset, 0), len(value)) + // Snapping to the end of a non-empty line lands on its trailing newline (or + // past it at the end of a surface); step onto the last character on that line + // so a double-click there picks the trailing word instead of the line break. + if unit == unitWord { + end := offset + if end == len(value) && end > 0 && (value[end-1] == '\n' || value[end-1] == '\r') { + end-- + } + if end < len(value) && (value[end] == '\n' || value[end] == '\r') && end > 0 { + if prev, size := utf8.DecodeLastRuneInString(value[:end]); prev != '\n' && prev != '\r' { + offset = end - size + } + } + } + var from, to int + if unit == unitWord { + from, to = text.WordSpan(value, offset) + } else { + from, to = text.LineSpan(value, offset) + } + return TextPoint{Surface: point.Surface, Offset: from}, TextPoint{Surface: point.Surface, Offset: to} +} + // In is the part of one surface's text the selection covers, to paint // highlighted and to copy: the zero value for a surface outside it, the whole // text for one it passes through completely, and in the surface where the @@ -269,7 +441,14 @@ func (selection *TextSelection) Clamp(surfaces int, length func(surface int) int return TextPoint{Surface: point.Surface, Offset: min(max(point.Offset, 0), length(point.Surface))} } selection.Anchor, selection.Focus = clampPoint(selection.Anchor), clampPoint(selection.Focus) + if selection.hasAnchor { + selection.anchorAt = clampPoint(selection.anchorAt) + } + if selection.unit != unitChar { + selection.origin[0] = clampPoint(selection.origin[0]) + selection.origin[1] = clampPoint(selection.origin[1]) + } if selection.Empty() && !selection.dragging { - selection.Clear() + selection.dropEmpty() } } diff --git a/base/text_selection_area.go b/base/text_selection_area.go index 2f4c69844..03987224e 100644 --- a/base/text_selection_area.go +++ b/base/text_selection_area.go @@ -4,7 +4,6 @@ import ( "math" "strings" "time" - "unicode/utf8" "unsafe" "github.com/vivaui/viva/gfx" @@ -42,13 +41,6 @@ type TextSelectionState struct { // down, moved whether it has left that spot, and pointer where it is now. pressed, moved bool press, pointer gfx.Point - unit selectUnit - // span is the word or line the press picked, which a drag by words or lines - // keeps whole. anchor is where the last press began, which Shift with a press - // extends from even when that press selected nothing. - span [2]TextPoint - anchor TextPoint - hasAnchor bool focused bool // the area had the keyboard focus in the last paint, or lost it to nothing page *Page @@ -64,15 +56,6 @@ type TextSelectionState struct { stepAt time.Duration } -// selectUnit is what a press selects and a drag extends by. -type selectUnit uint8 - -const ( - unitChar selectUnit = iota - unitWord - unitLine -) - // selectableText is one text of an area as a paint drew it. type selectableText struct { text string @@ -230,7 +213,7 @@ func (s *TextSelectionState) Text() string { // Clear drops the selection. func (s *TextSelectionState) Clear() { s.Selection.Clear() - s.pressed, s.hasAnchor = false, false + s.pressed = false } // SelectAll selects every text the area held in its last paint. @@ -379,25 +362,7 @@ func (s *TextSelectionState) onPointer(event gfx.PointerEvent) gfx.EventResult { s.Clear() return gfx.EventResult{Handled: true, Repaint: had, Focus: s.id} } - clicks := max(event.ClickCount, 1) - if event.Modifiers&gfx.ModifierShift != 0 && clicks == 1 && (s.hasAnchor || !s.Selection.Empty()) { - s.unit = unitChar - if s.Selection.Empty() { - s.Selection.Anchor = s.anchor - } - s.Selection.Focus = point - } else { - s.unit = unitChar - switch { - case clicks >= 3: - s.unit = unitLine - case clicks == 2: - s.unit = unitWord - } - s.span[0], s.span[1] = s.unitSpan(point) - s.Selection.Select(s.span[0], s.span[1]) - s.anchor, s.hasAnchor = point, true - } + s.Selection.press(point, max(event.ClickCount, 1), event.Modifiers&gfx.ModifierShift != 0, s.textOf(point.Surface)) s.pressed, s.moved, s.press, s.pointer = true, false, at, at return gfx.EventResult{Handled: true, Repaint: true, Focus: s.id} case gfx.PointerMove: @@ -418,9 +383,7 @@ func (s *TextSelectionState) onPointer(event gfx.PointerEvent) gfx.EventResult { if s.moved { s.extendTo(at) } - if s.Selection.Empty() { - s.Selection.Clear() - } + s.Selection.release() s.publish() return gfx.EventResult{Handled: true, Repaint: true} case gfx.PointerExit: @@ -428,6 +391,7 @@ func (s *TextSelectionState) onPointer(event gfx.PointerEvent) gfx.EventResult { // the button came up outside the window. if s.pressed { s.pressed = false + s.Selection.EndDrag() s.publish() return gfx.EventResult{Handled: true, Repaint: true} } @@ -442,48 +406,16 @@ func (s *TextSelectionState) extendTo(at gfx.Point) bool { if !ok { return false } - was := s.Selection - if s.unit == unitChar { - s.Selection.Focus = point - } else { - from, to := s.unitSpan(point) - if from.before(s.span[0]) { - s.Selection.Anchor, s.Selection.Focus = s.span[1], from - } else { - s.Selection.Anchor, s.Selection.Focus = s.span[0], to - } - } - return s.Selection != was + return s.Selection.extend(point, s.textOf(point.Surface)) } -// unitSpan is the unit of the press around a point: the point itself for -// characters, the word or the line of its text around it. -func (s *TextSelectionState) unitSpan(point TextPoint) (TextPoint, TextPoint) { - if s.unit == unitChar || point.Surface >= len(s.texts) { - return point, point - } - value := s.texts[point.Surface].text - index := utf8.RuneCountInString(value[:min(point.Offset, len(value))]) - var picked text.Range - if s.unit == unitWord { - picked = text.WordRange(value, index) - } else { - picked = text.LineRange(value, index) - } - from, to := byteOfRune(value, picked.Start), byteOfRune(value, picked.End) - return TextPoint{point.Surface, from}, TextPoint{point.Surface, to} -} - -// byteOfRune is the byte offset of rune index i in value, its length past the end. -func byteOfRune(value string, i int) int { - n := 0 - for offset := range value { - if n == i { - return offset - } - n++ +// textOf is the text of surface i as the last paint drew it, or nothing for a +// surface the area does not hold. +func (s *TextSelectionState) textOf(i int) string { + if i < 0 || i >= len(s.texts) { + return "" } - return len(value) + return s.texts[i].text } func (s *TextSelectionState) onKey(event gfx.KeyEvent) gfx.EventResult { @@ -648,10 +580,8 @@ func (f *Frame) beginTextArea(s *TextSelectionState) { // drag the paint scrolled the texts under. func (f *Frame) endTextArea(s *TextSelectionState) { // A press that has not moved yet holds an empty selection, which is the start of - // a drag and not one to drop. - s.Selection.dragging = s.pressed + // a drag and not one to drop: the selection is dragging while the press is held. s.Selection.Clamp(len(s.texts), s.length) - s.Selection.dragging = false if s.pressed && s.moved { s.extendTo(s.pointer) } diff --git a/base/text_selection_test.go b/base/text_selection_test.go index 46f3b69db..475898418 100644 --- a/base/text_selection_test.go +++ b/base/text_selection_test.go @@ -1,6 +1,7 @@ package base import ( + "strings" "testing" "github.com/vivaui/viva/gfx" @@ -208,3 +209,248 @@ func TestTextSelectionEndDragKeepsTheSelection(t *testing.T) { t.Fatalf("a move after EndDrag = %+v focus=%+v", result, selection.Focus) } } + +var unitSelectionTexts = []string{ + "alpha beta_two 中文测试\ngamma delta", + "second surface line\nthird line", + "", + "omega", +} + +func unitSelectionAt(point gfx.Point) (TextPoint, bool) { + surface := int(point.Y / 10) + if point.Y < 0 || surface >= len(unitSelectionTexts) { + return TextPoint{}, false + } + return TextPoint{Surface: surface, Offset: min(max(int(point.X), 0), len(unitSelectionTexts[surface]))}, true +} + +func unitSurfaceText(surface int) string { + if surface < 0 || surface >= len(unitSelectionTexts) { + return "" + } + return unitSelectionTexts[surface] +} + +func unitSelectedText(surface int, part TextRange) string { + text := unitSurfaceText(surface) + start, end := part.rangeIn(text) + return text[start:end] +} + +func unitPress(x, y float32, clicks int, mods gfx.Modifiers) gfx.PointerEvent { + return gfx.PointerEvent{ + Kind: gfx.PointerDown, + Button: gfx.PointerButtonPrimary, + ClickCount: clicks, + Modifiers: mods, + X: x, + Y: y, + } +} + +func TestTextSelectionPointerWithTextWordSelectionAndDrag(t *testing.T) { + var selection TextSelection + betaOffset := strings.Index(unitSelectionTexts[0], "beta_two") + 3 + if result := selection.PointerWithText(unitPress(float32(betaOffset), 1, 2, 0), unitSelectionAt, unitSurfaceText); !result.Handled || !result.Changed || !selection.Dragging() { + t.Fatalf("double press = %+v dragging=%v", result, selection.Dragging()) + } + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != "beta_two" { + t.Fatalf("double press copied %q, want %q", got, "beta_two") + } + + // Dragging backward keeps the original word included. + selection.PointerWithText(selectDrag(2, 1), unitSelectionAt, unitSurfaceText) + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != "alpha beta_two" { + t.Fatalf("backward word drag copied %q, want %q", got, "alpha beta_two") + } + + // Dragging forward across CJK and into the next surface extends whole words. + secondWord := strings.Index(unitSelectionTexts[1], "surface") + 2 + selection.PointerWithText(selectDrag(float32(secondWord), 11), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(float32(secondWord), 11), unitSelectionAt, unitSurfaceText) + if selection.Dragging() { + t.Fatal("release left drag active") + } + want := "beta_two 中文测试\ngamma delta\nsecond surface" + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != want { + t.Fatalf("forward cross-surface word drag copied %q, want %q", got, want) + } + + // Double-clicking on a line-ending newline selects the trailing word of that line, + // whereas double-clicking an empty line stays on the newline. + newlineAt := strings.IndexByte(unitSelectionTexts[0], '\n') + selection.PointerWithText(unitPress(float32(newlineAt), 1, 2, 0), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(float32(newlineAt), 1), unitSelectionAt, unitSurfaceText) + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != "中文测试" { + t.Fatalf("line-end double-click copied %q, want %q", got, "中文测试") + } +} + +func TestTextSelectionPointerWithTextLineSelectionAndDrag(t *testing.T) { + var selection TextSelection + secondLine := strings.Index(unitSelectionTexts[0], "gamma") + 2 + selection.PointerWithText(unitPress(float32(secondLine), 1, 3, 0), unitSelectionAt, unitSurfaceText) + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != "gamma delta" { + t.Fatalf("triple press copied %q, want %q", got, "gamma delta") + } + + // Extending backward to the first line keeps the second line selected. + selection.PointerWithText(selectDrag(2, 1), unitSelectionAt, unitSurfaceText) + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != "alpha beta_two 中文测试\ngamma delta" { + t.Fatalf("backward line drag copied %q", got) + } + + // Quadruple-click also selects at line granularity and extends across an empty surface. + selection.PointerWithText(unitPress(2, 1, 4, 0), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectDrag(0, 21), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectDrag(2, 31), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(2, 31), unitSelectionAt, unitSurfaceText) + want := "alpha beta_two 中文测试\ngamma delta\nsecond surface line\nthird line\nomega" + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != want { + t.Fatalf("cross-surface line drag copied %q, want %q", got, want) + } +} + +func TestTextSelectionPointerWithTextShiftClickExtendsFromClickOrSelection(t *testing.T) { + var selection TextSelection + // A plain click selects nothing, but leaves its anchor for Shift+click. + selection.PointerWithText(unitPress(6, 1, 1, 0), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(6, 1), unitSelectionAt, unitSurfaceText) + if !selection.Empty() || selection.Dragging() { + t.Fatalf("click left %+v", selection) + } + + selection.PointerWithText(unitPress(14, 1, 1, gfx.ModifierShift), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(14, 1), unitSelectionAt, unitSurfaceText) + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != "beta_two" { + t.Fatalf("first shift-click copied %q, want %q", got, "beta_two") + } + + // Shift+click before the original anchor extends backward from offset 6. + selection.PointerWithText(unitPress(0, 1, 1, gfx.ModifierShift), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(0, 1), unitSelectionAt, unitSurfaceText) + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != "alpha " { + t.Fatalf("backward shift-click copied %q, want %q", got, "alpha ") + } + + // Clamp preserves an active Shift anchor when surfaces remain, while Clear drops it. + selection.PointerWithText(unitPress(2, 1, 1, 0), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(2, 1), unitSelectionAt, unitSurfaceText) + selection.Clamp(len(unitSelectionTexts), func(surface int) int { return len(unitSelectionTexts[surface]) }) + selection.PointerWithText(unitPress(5, 1, 1, gfx.ModifierShift), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(5, 1), unitSelectionAt, unitSurfaceText) + if got := selection.Text(len(unitSelectionTexts), "\n", unitSelectedText); got != "pha" { + t.Fatalf("shift-click after Clamp copied %q, want %q", got, "pha") + } + + selection.Clear() + selection.PointerWithText(unitPress(5, 1, 1, gfx.ModifierShift), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(5, 1), unitSelectionAt, unitSurfaceText) + if !selection.Empty() { + t.Fatalf("shift-click after Clear left %+v", selection) + } +} + +var longSelectionSurface = strings.Repeat("alpha beta_two gamma delta\n", 256) + +func longSelectionAt(point gfx.Point) (TextPoint, bool) { + if point.Y < 0 || point.Y >= 10 { + return TextPoint{}, false + } + return TextPoint{Surface: 0, Offset: min(max(int(point.X), 0), len(longSelectionSurface))}, true +} + +func longSelectionText(int) string { return longSelectionSurface } + +func TestTextSelectionPointerWithTextDoesNotAllocate(t *testing.T) { + var selection TextSelection + allocs := testing.AllocsPerRun(100, func() { + selection.PointerWithText(unitPress(6, 1, 1, 0), longSelectionAt, longSelectionText) + selection.PointerWithText(selectRelease(6, 1), longSelectionAt, longSelectionText) + selection.PointerWithText(unitPress(28, 1, 1, gfx.ModifierShift), longSelectionAt, longSelectionText) + selection.PointerWithText(selectRelease(28, 1), longSelectionAt, longSelectionText) + + selection.PointerWithText(unitPress(8, 1, 2, 0), longSelectionAt, longSelectionText) + selection.PointerWithText(selectDrag(400, 1), longSelectionAt, longSelectionText) + selection.PointerWithText(selectDrag(2, 1), longSelectionAt, longSelectionText) + selection.PointerWithText(selectRelease(2, 1), longSelectionAt, longSelectionText) + + selection.PointerWithText(unitPress(8, 1, 3, 0), longSelectionAt, longSelectionText) + selection.PointerWithText(selectDrag(120, 1), longSelectionAt, longSelectionText) + selection.PointerWithText(selectRelease(120, 1), longSelectionAt, longSelectionText) + _ = selection.In(0) + }) + if allocs != 0 { + t.Fatalf("PointerWithText allocates %v times", allocs) + } +} + +func BenchmarkTextSelectionPointerWithTextWordDrag(b *testing.B) { + var selection TextSelection + selection.PointerWithText(unitPress(64, 1, 2, 0), longSelectionAt, longSelectionText) + b.ReportAllocs() + for b.Loop() { + selection.PointerWithText(selectDrag(float32(len(longSelectionSurface)-8), 1), longSelectionAt, longSelectionText) + selection.PointerWithText(selectDrag(8, 1), longSelectionAt, longSelectionText) + } +} + +func BenchmarkTextSelectionPointerWithTextLineDrag(b *testing.B) { + var selection TextSelection + selection.PointerWithText(unitPress(64, 1, 3, 0), longSelectionAt, longSelectionText) + b.ReportAllocs() + for b.Loop() { + selection.PointerWithText(selectDrag(float32(len(longSelectionSurface)-8), 1), longSelectionAt, longSelectionText) + selection.PointerWithText(selectDrag(8, 1), longSelectionAt, longSelectionText) + } +} + +// Pointer selects by character whatever the press says: a double press or one +// with Shift is for PointerWithText, so existing callers keep their behavior. +func TestTextSelectionPointerStaysByCharacter(t *testing.T) { + var selection TextSelection + selection.Pointer(unitPress(2, 1, 2, 0), unitSelectionAt) + selection.Pointer(selectRelease(2, 1), unitSelectionAt) + if selection != (TextSelection{}) { + t.Fatalf("a double press selected %+v", selection) + } + selection.Pointer(unitPress(2, 1, 1, 0), unitSelectionAt) + selection.Pointer(selectRelease(2, 1), unitSelectionAt) + selection.Pointer(unitPress(9, 1, 1, gfx.ModifierShift), unitSelectionAt) + selection.Pointer(selectRelease(9, 1), unitSelectionAt) + if selection != (TextSelection{}) { + t.Fatalf("a Shift press extended %+v", selection) + } +} + +// Shift with a press after a double or triple press extends by words or lines and +// keeps the picked one whole, on either side of it. +func TestTextSelectionPointerWithTextShiftPressExtendsByTheUnitPicked(t *testing.T) { + var selection TextSelection + copied := func() string { return selection.Text(len(unitSelectionTexts), "\n", unitSelectedText) } + beta := strings.Index(unitSelectionTexts[0], "beta_two") + 3 + selection.PointerWithText(unitPress(float32(beta), 1, 2, 0), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(float32(beta), 1), unitSelectionAt, unitSurfaceText) + + gamma := strings.Index(unitSelectionTexts[0], "gamma") + 2 + selection.PointerWithText(unitPress(float32(gamma), 1, 1, gfx.ModifierShift), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(float32(gamma), 1), unitSelectionAt, unitSurfaceText) + if got := copied(); got != "beta_two 中文测试\ngamma" { + t.Fatalf("shift press after the word copied %q", got) + } + + selection.PointerWithText(unitPress(2, 1, 1, gfx.ModifierShift), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(2, 1), unitSelectionAt, unitSurfaceText) + if got := copied(); got != "alpha beta_two" { + t.Fatalf("shift press before the word copied %q", got) + } + + selection.PointerWithText(unitPress(float32(gamma), 1, 3, 0), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(float32(gamma), 1), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(unitPress(3, 11, 1, gfx.ModifierShift), unitSelectionAt, unitSurfaceText) + selection.PointerWithText(selectRelease(3, 11), unitSelectionAt, unitSurfaceText) + if got := copied(); got != "gamma delta\nsecond surface line\n" { + t.Fatalf("shift press after the line copied %q", got) + } +} diff --git a/base/textarea.go b/base/textarea.go index b8d02edde..c669e24a3 100644 --- a/base/textarea.go +++ b/base/textarea.go @@ -87,6 +87,10 @@ type TextareaSnapshot struct { InsetBottom float32 // InsetRight reserves room for caller-owned controls such as a scrollbar. InsetRight float32 + // Count is text shown at the end of a row of its own under the rows, above + // InsetBottom, such as the "12/80" a page's TextArea shows for ShowCount. The + // rows scroll above it as they do above InsetBottom. + Count string // Layout makes the rows the application's to move through: it keeps them from // one frame to the next (so a steady paint allocates nothing), scrolls to the // caret and, held by the application's key and pointer handlers, moves the @@ -108,6 +112,19 @@ type TextareaSnapshot struct { CompositionEnd int } +// BottomInset is the room the rows keep free at the bottom of the box: InsetBottom, +// and the row Count is shown on. +func (snapshot TextareaSnapshot) BottomInset(theme Theme) float32 { + inset := max(snapshot.InsetBottom, 0) + if snapshot.Count != "" { + inset += TextareaCountRow(theme) + } + return inset +} + +// TextareaCountRow is the height of the row a textarea shows its Count on. +func TextareaCountRow(theme Theme) float32 { return theme.Metrics.FontSizeM + 7 } + // TextareaMovement is a way of moving the caret of a wrapping Textarea that // depends on how its text is laid out in rows. type TextareaMovement uint8 diff --git a/cmd/viva/templates/code_diff.go.txt b/cmd/viva/templates/code_diff.go.txt index 243d3d1d2..f680c7dee 100644 --- a/cmd/viva/templates/code_diff.go.txt +++ b/cmd/viva/templates/code_diff.go.txt @@ -612,6 +612,39 @@ func (diff *CodeDiff) GutterAt(point gfx.Point) (row, line int, left, ok bool) { return row, line, left, true } +// RowOfOffset is the aligned row that holds the line of the editable text at a +// byte offset, as last painted. Navigation such as NextHunk starts there when +// it follows the caret. +func (diff *CodeDiff) RowOfOffset(offset int) (int, bool) { + if !diff.valueSet || len(diff.lines) == 0 { + return 0, false + } + line, _ := codeDiffLineAt(diff.lineStarts, diff.lines, offset) + for row, aligned := range diff.snapshot.Result.Rows { + if aligned.RightLine == line { + return row, true + } + } + return 0, false +} + +// RowOffset is the byte offset in the editable text, as last painted, where an +// aligned row's line starts. A row with no editable line gives the start of the +// next one, or the end of the text, which is where a caret moved to the row +// belongs. +func (diff *CodeDiff) RowOffset(row int) (int, bool) { + rows := diff.snapshot.Result.Rows + if !diff.valueSet || row < 0 || row >= len(rows) { + return 0, false + } + for _, aligned := range rows[row:] { + if aligned.RightLine >= 0 && aligned.RightLine < len(diff.lineStarts) { + return diff.lineStarts[aligned.RightLine], true + } + } + return len(diff.value), true +} + // RevealRow scrolls an aligned row into the shared viewport without changing // the horizontal position. It is suitable for navigating to a hunk's Start. func (diff *CodeDiff) RevealRow(row int) { diff --git a/cmd/viva/templates/code_merge.go.txt b/cmd/viva/templates/code_merge.go.txt index 8ea6dea02..96be597f5 100644 --- a/cmd/viva/templates/code_merge.go.txt +++ b/cmd/viva/templates/code_merge.go.txt @@ -10,6 +10,16 @@ type CodeMergeRow struct { CurrentChanged, IncomingChanged bool } +// CodeMergeConflict is a caller-owned conflict over the aligned rows from Start +// up to End, which is exclusive. Resolved records that the user settled it, by +// accepting a side or by editing the result; the component paints an unresolved +// conflict as one and skips resolved ones when navigating. The caller decides +// what a conflict is and when it is resolved. +type CodeMergeConflict struct { + Start, End int + Resolved bool +} + // CodeMergeAction is a caller-owned action on an aligned row of either source. type CodeMergeAction struct { Row int @@ -23,15 +33,49 @@ type CodeMergeAction struct { // Editor.Result is ignored. Current and Incoming are the caller's split source // lines. Action IDs are optional gutter regions; the caller maps their pointer // coordinates to an aligned row with ActionAt and decides what accepting means. +// Conflicts are sorted by Start and do not overlap. type CodeMergeSnapshot struct { Current, Incoming []string Rows []CodeMergeRow + Conflicts []CodeMergeConflict Editor CodeDiffSnapshot CurrentActionID gfx.ID IncomingActionID gfx.ID Actions []CodeMergeAction } +// Unresolved counts the conflicts the user has not resolved yet. +func (snapshot CodeMergeSnapshot) Unresolved() int { + count := 0 + for _, conflict := range snapshot.Conflicts { + if !conflict.Resolved { + count++ + } + } + return count +} + +// NextConflict finds the index of the next or previous unresolved conflict +// whose Start lies strictly past or before row, as NextHunk does for a diff. It +// does not wrap and does not allocate. RowOfOffset gives the row of the +// result's caret to start from. +func (snapshot CodeMergeSnapshot) NextConflict(row int, forward bool) (int, bool) { + if forward { + for index, conflict := range snapshot.Conflicts { + if !conflict.Resolved && conflict.Start > row { + return index, true + } + } + return 0, false + } + for index := len(snapshot.Conflicts) - 1; index >= 0; index-- { + if conflict := snapshot.Conflicts[index]; !conflict.Resolved && conflict.Start < row { + return index, true + } + } + return 0, false +} + // CodeMerge shares CodeDiff's grid rendering, native text placement, selection, // keyboard movement and scrolling, but owns an independent three-pane layout. // Its center pane is the only editable surface. @@ -162,7 +206,9 @@ func (merge *CodeMerge) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Re merge.currentAction = gfx.Rect{X: currentPane.X, Y: viewport.Y, Width: min(diff.gutter, currentPane.Width), Height: viewport.Height} merge.incomingAction = gfx.Rect{X: incomingPane.X, Y: viewport.Y, Width: min(diff.gutter, incomingPane.Width), Height: viewport.Height} currentShown := diff.leftShown + resultColor := diff.snapshot.AddedColor first := max(int(diff.scrollY/diff.rowHeight), 0) + conflict := 0 for rowIndex := first; rowIndex < len(snapshot.Rows); rowIndex++ { y := viewport.Y + float32(rowIndex)*diff.rowHeight - diff.scrollY if y >= viewport.Y+viewport.Height { @@ -179,8 +225,15 @@ func (merge *CodeMerge) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Re if row.CurrentChanged || row.IncomingChanged { kind = CodeDiffChanged } + for conflict < len(snapshot.Conflicts) && snapshot.Conflicts[conflict].End <= rowIndex { + conflict++ + } + if conflict < len(snapshot.Conflicts) && snapshot.Conflicts[conflict].Start <= rowIndex && !snapshot.Conflicts[conflict].Resolved { + kind, diff.snapshot.AddedColor = CodeDiffChanged, theme.WarningColor() + } diff.paintRowSide(canvas, gfx.Rect{X: resultPane.X, Y: y, Width: resultPane.Width, Height: diff.rowHeight}, resultPane, kind, row.ResultLine, false, rowIndex) + diff.snapshot.AddedColor = resultColor kind = CodeDiffUnchanged if row.IncomingChanged { kind = CodeDiffChanged diff --git a/cmd/viva/templates/color_picker.go.txt b/cmd/viva/templates/color_picker.go.txt index 568afdc3f..7816b2a76 100644 --- a/cmd/viva/templates/color_picker.go.txt +++ b/cmd/viva/templates/color_picker.go.txt @@ -163,6 +163,9 @@ func (picker ColorPicker) Paint() ColorPickerLayout { if picker.triggerOnly || !o.Open || o.Disabled || o.Viewport.Width <= 0 || o.Viewport.Height <= 0 { return l } + // 弹层使用窗口裁切范围,避免继承表单滚动区域的裁切。 + c.PushOverlayClip(o.Viewport) + defer c.PopOverlayClip() gap, control := theme.Metrics.GapItem, theme.Metrics.ControlHeight errorHeight := float32(0) if o.Error != "" { diff --git a/cmd/viva/templates/markdown.go.txt b/cmd/viva/templates/markdown.go.txt index 1b08a477c..30df2290a 100644 --- a/cmd/viva/templates/markdown.go.txt +++ b/cmd/viva/templates/markdown.go.txt @@ -180,6 +180,14 @@ func (v *MarkdownView) Height() float32 { return v.height } // TextLen is the length in bytes of the rendered text that can be selected. func (v *MarkdownView) TextLen() int { return len(v.plain) } +// PlainText returns a read-only view of the rendered text, matching TextLen +// and SelectedText, without copying it. The returned string aliases the view's +// backing slice until the next Layout call, so callers must read it rather than +// retain it across layouts. +func (v *MarkdownView) PlainText() string { + return unsafe.String(unsafe.SliceData(v.plain), len(v.plain)) +} + // SelectedText returns the rendered text of sel: what a copy of the selection // puts on the clipboard. Offsets are clamped to the laid-out text, so an empty // view or a selection outside it returns "". diff --git a/cmd/viva/templates/textarea.go.txt b/cmd/viva/templates/textarea.go.txt index f1d61f8c3..cfee8cc46 100644 --- a/cmd/viva/templates/textarea.go.txt +++ b/cmd/viva/templates/textarea.go.txt @@ -62,7 +62,7 @@ func paintTextareaContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, area gfx. return } top := min(max(snapshot.InsetTop, 0), max(area.Height, 0)) - content := gfx.Rect{X: area.X, Y: area.Y + top, Width: textareaMax(0, area.Width-snapshot.InsetRight), Height: textareaMax(0, area.Height-top-snapshot.InsetBottom)} + content := gfx.Rect{X: area.X, Y: area.Y + top, Width: textareaMax(0, area.Width-snapshot.InsetRight), Height: textareaMax(0, area.Height-top-snapshot.BottomInset(theme))} // A Secure box shows what its Value is, as bullets: DisplayValue is not its. display := snapshot.DisplayValue if display == "" || snapshot.Secure { @@ -75,6 +75,16 @@ func paintTextareaContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, area gfx. if !snapshot.NativeEditing { textareaPaintRows(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) } + if snapshot.Count != "" { + // The count of a single-line field is its end addon's text; this is the + // same words in the same style, on the row kept for it under the text. + color := theme.MutedForeground + if snapshot.Disabled { + color.Alpha *= 0.50 + } + row := gfx.Rect{X: content.X, Y: content.Y + content.Height, Width: content.Width, Height: base.TextareaCountRow(theme)} + canvas.LabelAligned(snapshot.Count, row, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: color}, gfx.AlignEnd) + } if !snapshot.ID.IsZero() { options := gfx.HitOptions{ Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, diff --git a/components/code_diff.go b/components/code_diff.go index 512ccffc9..761c86293 100644 --- a/components/code_diff.go +++ b/components/code_diff.go @@ -612,6 +612,39 @@ func (diff *CodeDiff) GutterAt(point gfx.Point) (row, line int, left, ok bool) { return row, line, left, true } +// RowOfOffset is the aligned row that holds the line of the editable text at a +// byte offset, as last painted. Navigation such as NextHunk starts there when +// it follows the caret. +func (diff *CodeDiff) RowOfOffset(offset int) (int, bool) { + if !diff.valueSet || len(diff.lines) == 0 { + return 0, false + } + line, _ := codeDiffLineAt(diff.lineStarts, diff.lines, offset) + for row, aligned := range diff.snapshot.Result.Rows { + if aligned.RightLine == line { + return row, true + } + } + return 0, false +} + +// RowOffset is the byte offset in the editable text, as last painted, where an +// aligned row's line starts. A row with no editable line gives the start of the +// next one, or the end of the text, which is where a caret moved to the row +// belongs. +func (diff *CodeDiff) RowOffset(row int) (int, bool) { + rows := diff.snapshot.Result.Rows + if !diff.valueSet || row < 0 || row >= len(rows) { + return 0, false + } + for _, aligned := range rows[row:] { + if aligned.RightLine >= 0 && aligned.RightLine < len(diff.lineStarts) { + return diff.lineStarts[aligned.RightLine], true + } + } + return len(diff.value), true +} + // RevealRow scrolls an aligned row into the shared viewport without changing // the horizontal position. It is suitable for navigating to a hunk's Start. func (diff *CodeDiff) RevealRow(row int) { diff --git a/components/code_merge.go b/components/code_merge.go index 83028dc95..a376d43ab 100644 --- a/components/code_merge.go +++ b/components/code_merge.go @@ -10,6 +10,16 @@ type CodeMergeRow struct { CurrentChanged, IncomingChanged bool } +// CodeMergeConflict is a caller-owned conflict over the aligned rows from Start +// up to End, which is exclusive. Resolved records that the user settled it, by +// accepting a side or by editing the result; the component paints an unresolved +// conflict as one and skips resolved ones when navigating. The caller decides +// what a conflict is and when it is resolved. +type CodeMergeConflict struct { + Start, End int + Resolved bool +} + // CodeMergeAction is a caller-owned action on an aligned row of either source. type CodeMergeAction struct { Row int @@ -23,15 +33,49 @@ type CodeMergeAction struct { // Editor.Result is ignored. Current and Incoming are the caller's split source // lines. Action IDs are optional gutter regions; the caller maps their pointer // coordinates to an aligned row with ActionAt and decides what accepting means. +// Conflicts are sorted by Start and do not overlap. type CodeMergeSnapshot struct { Current, Incoming []string Rows []CodeMergeRow + Conflicts []CodeMergeConflict Editor CodeDiffSnapshot CurrentActionID gfx.ID IncomingActionID gfx.ID Actions []CodeMergeAction } +// Unresolved counts the conflicts the user has not resolved yet. +func (snapshot CodeMergeSnapshot) Unresolved() int { + count := 0 + for _, conflict := range snapshot.Conflicts { + if !conflict.Resolved { + count++ + } + } + return count +} + +// NextConflict finds the index of the next or previous unresolved conflict +// whose Start lies strictly past or before row, as NextHunk does for a diff. It +// does not wrap and does not allocate. RowOfOffset gives the row of the +// result's caret to start from. +func (snapshot CodeMergeSnapshot) NextConflict(row int, forward bool) (int, bool) { + if forward { + for index, conflict := range snapshot.Conflicts { + if !conflict.Resolved && conflict.Start > row { + return index, true + } + } + return 0, false + } + for index := len(snapshot.Conflicts) - 1; index >= 0; index-- { + if conflict := snapshot.Conflicts[index]; !conflict.Resolved && conflict.Start < row { + return index, true + } + } + return 0, false +} + // CodeMerge shares CodeDiff's grid rendering, native text placement, selection, // keyboard movement and scrolling, but owns an independent three-pane layout. // Its center pane is the only editable surface. @@ -162,7 +206,9 @@ func (merge *CodeMerge) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Re merge.currentAction = gfx.Rect{X: currentPane.X, Y: viewport.Y, Width: min(diff.gutter, currentPane.Width), Height: viewport.Height} merge.incomingAction = gfx.Rect{X: incomingPane.X, Y: viewport.Y, Width: min(diff.gutter, incomingPane.Width), Height: viewport.Height} currentShown := diff.leftShown + resultColor := diff.snapshot.AddedColor first := max(int(diff.scrollY/diff.rowHeight), 0) + conflict := 0 for rowIndex := first; rowIndex < len(snapshot.Rows); rowIndex++ { y := viewport.Y + float32(rowIndex)*diff.rowHeight - diff.scrollY if y >= viewport.Y+viewport.Height { @@ -179,8 +225,15 @@ func (merge *CodeMerge) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Re if row.CurrentChanged || row.IncomingChanged { kind = CodeDiffChanged } + for conflict < len(snapshot.Conflicts) && snapshot.Conflicts[conflict].End <= rowIndex { + conflict++ + } + if conflict < len(snapshot.Conflicts) && snapshot.Conflicts[conflict].Start <= rowIndex && !snapshot.Conflicts[conflict].Resolved { + kind, diff.snapshot.AddedColor = CodeDiffChanged, theme.WarningColor() + } diff.paintRowSide(canvas, gfx.Rect{X: resultPane.X, Y: y, Width: resultPane.Width, Height: diff.rowHeight}, resultPane, kind, row.ResultLine, false, rowIndex) + diff.snapshot.AddedColor = resultColor kind = CodeDiffUnchanged if row.IncomingChanged { kind = CodeDiffChanged diff --git a/components/code_merge_headless_test.go b/components/code_merge_headless_test.go index 436d25dd5..cf2025463 100644 --- a/components/code_merge_headless_test.go +++ b/components/code_merge_headless_test.go @@ -89,3 +89,135 @@ func TestCodeMergeHeadlessAcceptButtonAndNativeResultInput(t *testing.T) { } } } + +// A caller resolves two conflicts through the merge's public API: accepting a +// side, navigating from the native caret to the next unresolved conflict, and +// editing it by typing. The remaining count closes at zero. +func TestCodeMergeHeadlessResolvesConflictsByAcceptingNavigatingAndTyping(t *testing.T) { + var tree gfx.Tree + scope := tree.Feature("merge-conflicts") + resultID := tree.ID(scope, "result") + acceptID := tree.ID(scope, "accept-incoming") + current := strings.Split("head\nlocal one\nmiddle\nlocal two\ntail", "\n") + incoming := strings.Split("head\nremote one\nmiddle\nremote two\ntail", "\n") + var editor text.Editor + editor.Insert(strings.Join(current, "\n")) + editor.MoveTo(0, false) + var merge components.CodeMerge + conflicts := []components.CodeMergeConflict{{Start: 1, End: 2}, {Start: 3, End: 4}} + accepted := [2]bool{} + rows := make([]components.CodeMergeRow, len(current)) + for line := range rows { + changed := line == 1 || line == 3 + rows[line] = components.CodeMergeRow{CurrentLine: line, ResultLine: line, IncomingLine: line, CurrentChanged: changed, IncomingChanged: changed} + } + var snapshot components.CodeMergeSnapshot + remaining := -1 + navigate := false + config := app.Config{ + Title: "Merge conflicts", Width: 900, Height: 260, + Paint: func(canvas *gfx.Canvas, size gfx.Size) { + canvas.SetTree(&tree) + value := editor.String() + lines := strings.Split(value, "\n") + // The caller's policy: a conflict is resolved once a side is accepted + // or its result line no longer matches what the merge started with. + for index := range conflicts { + line := conflicts[index].Start + conflicts[index].Resolved = accepted[index] || line >= len(lines) || lines[line] != current[line] + } + var actions []components.CodeMergeAction + if !conflicts[0].Resolved { + actions = append(actions, components.CodeMergeAction{Row: conflicts[0].Start, Incoming: true, ID: acceptID, Label: "Accept"}) + } + snapshot = components.CodeMergeSnapshot{ + Current: current, Incoming: incoming, Rows: rows, Conflicts: conflicts, + Editor: components.CodeDiffSnapshot{ID: resultID, Label: "Result", Value: value, + Caret: editor.ByteOffset(editor.Caret()), Focused: canvas.Focused() == resultID, ShowCaret: true}, + Actions: actions, + } + remaining = snapshot.Unresolved() + merge.Paint(canvas, gfx.DarkTheme(), gfx.Rect{Width: size.Width, Height: size.Height - 30}, snapshot) + if canvas.Clicked(acceptID) { + line := conflicts[0].Start + start := editor.RuneIndex(strings.Index(value, current[line])) + editor.ReplaceRange(text.Range{Start: start, End: start + len([]rune(current[line]))}, incoming[line]) + accepted[0] = true + } + if navigate { + navigate = false + from := -1 + if row, ok := merge.RowOfOffset(editor.ByteOffset(editor.Caret())); ok { + from = row + } + if index, ok := snapshot.NextConflict(from, true); ok { + merge.RevealRow(conflicts[index].Start) + if offset, ok := merge.RowOffset(conflicts[index].Start); ok { + editor.MoveTo(editor.RuneIndex(offset), false) + } + } + } + }, + // F7 goes to the next conflict, as in mature diff and merge tools. + OnKey: func(event gfx.KeyEvent) gfx.EventResult { + if event.Key != gfx.KeyF7 { + return gfx.EventResult{} + } + navigate = true + return gfx.EventResult{Handled: true, Repaint: true} + }, + TextInput: func(context app.TextInputContext) *app.TextInput { + if context.ID != resultID { + return nil + } + return &app.TextInput{Editor: &editor} + }, + } + session, err := headless.Open(config, nil, headless.Options{Scale: 1.25}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + if remaining != 2 { + t.Fatalf("a fresh merge reports %d unresolved conflicts, want 2", remaining) + } + clickHit := func(id gfx.ID) { + t.Helper() + for _, hit := range session.Snapshot().Hits { + if hit.ID == id { + if err := session.Click(hit.Bounds.X+hit.Bounds.Width/2, hit.Bounds.Y+hit.Bounds.Height/2); err != nil { + t.Fatal(err) + } + return + } + } + t.Fatalf("no hit region for %v", id) + } + clickHit(acceptID) + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if !strings.Contains(editor.String(), "remote one") || remaining != 1 { + t.Fatalf("accepting the incoming side left %q with %d unresolved", editor.String(), remaining) + } + clickHit(resultID) + editor.MoveTo(0, false) + if err := session.Driver().Key(gfx.KeyF7, 0); err != nil { + t.Fatal(err) + } + if got := editor.ByteOffset(editor.Caret()); got != strings.Index(editor.String(), "local two") { + t.Fatalf("next conflict put the caret at %d in %q, want the start of the second conflict", got, editor.String()) + } + if err := session.Type("edited "); err != nil { + t.Fatal(err) + } + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if !strings.Contains(editor.String(), "edited local two") || remaining != 0 { + t.Fatalf("typing in the second conflict left %q with %d unresolved", editor.String(), remaining) + } + if _, ok := snapshot.NextConflict(-1, true); ok { + t.Fatal("a resolved merge still offers a conflict to navigate to") + } +} diff --git a/components/code_merge_test.go b/components/code_merge_test.go index 5271f9f0a..83086c39a 100644 --- a/components/code_merge_test.go +++ b/components/code_merge_test.go @@ -160,3 +160,80 @@ func BenchmarkCodeMergePaint(b *testing.B) { merge.Paint(&canvas, theme, bounds, snapshot) } } + +func TestCodeMergeConflictNavigationSkipsResolvedConflicts(t *testing.T) { + snapshot := CodeMergeSnapshot{Conflicts: []CodeMergeConflict{ + {Start: 1, End: 2}, {Start: 3, End: 4, Resolved: true}, {Start: 5, End: 7}, + }} + if got := snapshot.Unresolved(); got != 2 { + t.Fatalf("Unresolved() = %d, want 2", got) + } + for _, step := range []struct { + row int + forward bool + want int + wantFound bool + }{ + {row: -1, forward: true, want: 0, wantFound: true}, + {row: 1, forward: true, want: 2, wantFound: true}, + {row: 5, forward: true, wantFound: false}, + {row: 5, forward: false, want: 0, wantFound: true}, + {row: 1, forward: false, wantFound: false}, + } { + got, found := snapshot.NextConflict(step.row, step.forward) + if found != step.wantFound || found && got != step.want { + t.Fatalf("NextConflict(%d, %t) = %d, %t; want %d, %t", step.row, step.forward, got, found, step.want, step.wantFound) + } + } + snapshot.Conflicts[0].Resolved, snapshot.Conflicts[2].Resolved = true, true + if _, found := snapshot.NextConflict(-1, true); found || snapshot.Unresolved() != 0 { + t.Fatal("a fully resolved merge still offers a conflict") + } +} + +// The result can gain a line no source has; mapping the caret to its aligned +// row and a row back to the result must agree with the caller's alignment. +func TestCodeMergeMapsResultOffsetsToAlignedRows(t *testing.T) { + var canvas gfx.Canvas + var merge CodeMerge + current := strings.Split("head\nlocal\ntail", "\n") + result := "head\nlocal\nadded\ntail" + snapshot := CodeMergeSnapshot{ + Current: current, Incoming: current, + Rows: []CodeMergeRow{ + {CurrentLine: 0, ResultLine: 0, IncomingLine: 0}, + {CurrentLine: -1, ResultLine: -1, IncomingLine: -1, IncomingChanged: true}, + {CurrentLine: 1, ResultLine: 1, IncomingLine: 1}, + {CurrentLine: -1, ResultLine: 2, IncomingLine: -1, CurrentChanged: true}, + {CurrentLine: 2, ResultLine: 3, IncomingLine: 2}, + }, + Editor: CodeDiffSnapshot{ID: gfx.Item(30), Value: result}, + } + merge.Paint(&canvas, gfx.DarkTheme(), gfx.Rect{Width: 900, Height: 200}, snapshot) + lines := strings.Split(result, "\n") + start := 0 + for line, value := range lines { + row := -1 + for index, aligned := range snapshot.Rows { + if aligned.ResultLine == line { + row = index + } + } + for _, offset := range []int{start, start + len(value)} { + if got, ok := merge.RowOfOffset(offset); !ok || got != row { + t.Fatalf("RowOfOffset(%d) = %d, %t; want row %d", offset, got, ok, row) + } + } + if got, ok := merge.RowOffset(row); !ok || got != start { + t.Fatalf("RowOffset(%d) = %d, %t; want %d", row, got, ok, start) + } + start += len(value) + 1 + } + // A row the result has no line on puts the caret where the next line starts. + if got, ok := merge.RowOffset(1); !ok || got != len("head\n") { + t.Fatalf("RowOffset of a row without a result line = %d, %t", got, ok) + } + if _, ok := merge.RowOffset(len(snapshot.Rows)); ok { + t.Fatal("RowOffset accepted a row past the alignment") + } +} diff --git a/components/color_picker.go b/components/color_picker.go index 05aed8a86..0b96202db 100644 --- a/components/color_picker.go +++ b/components/color_picker.go @@ -163,6 +163,9 @@ func (picker ColorPicker) Paint() ColorPickerLayout { if picker.triggerOnly || !o.Open || o.Disabled || o.Viewport.Width <= 0 || o.Viewport.Height <= 0 { return l } + // 弹层使用窗口裁切范围,避免继承表单滚动区域的裁切。 + c.PushOverlayClip(o.Viewport) + defer c.PopOverlayClip() gap, control := theme.Metrics.GapItem, theme.Metrics.ControlHeight errorHeight := float32(0) if o.Error != "" { diff --git a/components/doc.go b/components/doc.go index f17601d23..3e66df071 100644 --- a/components/doc.go +++ b/components/doc.go @@ -169,7 +169,8 @@ // gutter hit regions and row navigation. `DiffCodeLines` produces bounded // line alignment with `CodeDiffInline` grapheme changes. `CodeMerge` uses // the same editor and grid for three caller-aligned sources and an editable -// center result. +// center result, marks the caller's unresolved conflicts, counts them and +// finds the next or previous one. // - Image preview: `PaintImageView` clips an immutable bitmap with fit, zoom // and pan; actual size maps one bitmap pixel to one device pixel at any DPI. // - One-time code: `PaintInputOTP` paints segmented code entry; diff --git a/components/markdown.go b/components/markdown.go index 1ee0613d0..6146529d0 100644 --- a/components/markdown.go +++ b/components/markdown.go @@ -180,6 +180,14 @@ func (v *MarkdownView) Height() float32 { return v.height } // TextLen is the length in bytes of the rendered text that can be selected. func (v *MarkdownView) TextLen() int { return len(v.plain) } +// PlainText returns a read-only view of the rendered text, matching TextLen +// and SelectedText, without copying it. The returned string aliases the view's +// backing slice until the next Layout call, so callers must read it rather than +// retain it across layouts. +func (v *MarkdownView) PlainText() string { + return unsafe.String(unsafe.SliceData(v.plain), len(v.plain)) +} + // SelectedText returns the rendered text of sel: what a copy of the selection // puts on the clipboard. Offsets are clamped to the laid-out text, so an empty // view or a selection outside it returns "". diff --git a/components/markdown_test.go b/components/markdown_test.go index c475f67c7..6d7021fc0 100644 --- a/components/markdown_test.go +++ b/components/markdown_test.go @@ -1973,3 +1973,24 @@ func TestMarkdownImageWithNoDestinationIsOnlyItsAltText(t *testing.T) { t.Errorf("an empty destination laid out %+v and %q", view.images, view.words()) } } + +func TestMarkdownViewPlainTextMatchesSelectedTextWithoutAllocating(t *testing.T) { + src := "# Heading\n\nalpha beta_two 中文测试\n\n```\nline one\nline two\n```\n" + view, _ := layoutMarkdown(t, src, 240, MarkdownStyle{Size: 12}) + want := view.SelectedText(base.TextRange{Focus: view.TextLen()}) + if got := view.PlainText(); got != want || len(got) != view.TextLen() { + t.Fatalf("PlainText() = %q (len %d), want %q (len %d)", got, len(got), want, view.TextLen()) + } + allocs := testing.AllocsPerRun(100, func() { + if view.PlainText() == "" { + t.Fatal("empty view text") + } + }) + if allocs != 0 { + t.Fatalf("MarkdownView.PlainText allocates %v times", allocs) + } + var empty MarkdownView + if empty.PlainText() != "" { + t.Fatalf("empty view PlainText() = %q", empty.PlainText()) + } +} diff --git a/components/textarea.go b/components/textarea.go index 00891bf61..75c14d209 100644 --- a/components/textarea.go +++ b/components/textarea.go @@ -62,7 +62,7 @@ func paintTextareaContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, area gfx. return } top := min(max(snapshot.InsetTop, 0), max(area.Height, 0)) - content := gfx.Rect{X: area.X, Y: area.Y + top, Width: textareaMax(0, area.Width-snapshot.InsetRight), Height: textareaMax(0, area.Height-top-snapshot.InsetBottom)} + content := gfx.Rect{X: area.X, Y: area.Y + top, Width: textareaMax(0, area.Width-snapshot.InsetRight), Height: textareaMax(0, area.Height-top-snapshot.BottomInset(theme))} // A Secure box shows what its Value is, as bullets: DisplayValue is not its. display := snapshot.DisplayValue if display == "" || snapshot.Secure { @@ -75,6 +75,16 @@ func paintTextareaContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, area gfx. if !snapshot.NativeEditing { textareaPaintRows(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) } + if snapshot.Count != "" { + // The count of a single-line field is its end addon's text; this is the + // same words in the same style, on the row kept for it under the text. + color := theme.MutedForeground + if snapshot.Disabled { + color.Alpha *= 0.50 + } + row := gfx.Rect{X: content.X, Y: content.Y + content.Height, Width: content.Width, Height: base.TextareaCountRow(theme)} + canvas.LabelAligned(snapshot.Count, row, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: color}, gfx.AlignEnd) + } if !snapshot.ID.IsZero() { options := gfx.HitOptions{ Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, diff --git a/docs/system-integrations.md b/docs/system-integrations.md index f0f6642eb..9c093e47a 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -36,6 +36,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Native look (`SetNativeAppearance`) | `NSApplication.appearance`: window buttons, menus, file dialogs and native text editing follow it | nothing to do: Viva draws the window buttons | nothing to do: Viva draws the window buttons | nothing to do | | Reduced motion (`ReduceMotion`, returns `bool`) | `NSWorkspace.accessibilityDisplayShouldReduceMotion` | `SPI_GETCLIENTAREAANIMATION` | the settings portal's `reduced-motion` or `enable-animations`, else XSETTINGS `Gtk/EnableAnimations`, else KDE's `AnimationDurationFactor` of 0; a change is applied to a running canvas | `prefers-reduced-motion`, read at mount and watched with `matchMedia` | | Keep awake (`PreventSleep`) | an `IOPMAssertion` of type `PreventUserIdleSystemSleep`, named by the reason; `pmset -g assertions` lists it | a power request of type `SystemRequired`, created with the reason; `powercfg /requests` lists it | logind's `Manager.Inhibit("idle")` on the system bus, held by the returned descriptor; `systemd-inhibit --list` shows it. `ErrSleepPreventionUnavailable` without logind | `ErrSleepPreventionUnavailable`: a page cannot keep the machine awake | +| Elevated copy (`StartElevated`, `Elevated`) | `ErrUnsupported`: a user's processes are raised with `sudo` in a terminal, not by a prompt of the desktop | `ShellExecuteExW` with the `runas` verb: the consent prompt of User Account Control, then a separate process of the program with an elevated token. A refused prompt is `ErrElevationDeclined`. `Elevated` reads the token's elevation, so it is also true for every process of an administrator when User Account Control is off | `ErrUnsupported` | `ErrUnsupported` | | Application menu bar (`Application.SetMenuBar`) | the NSMenu bar's application and Window menus stay; the application's own menus sit between them, with their key equivalents, enablement, check marks, submenus and actions whose event results the runtime carries out on the active window. A character chord first reaches the application's shortcut handler with the focused control, and a named-key chord its key handler, as the system offers a key to the content before the menu; the entry's action runs only when that handler declines it | `ErrUnsupported`: a window's own menu bar is `components.Menubar` | `ErrUnsupported`: `components.Menubar` | `ErrUnsupported`: `components.Menubar` | | System proxy (`app/proxy.SystemProxy`, `SystemProxyContext`) | CFNetwork's settings for the URL: static HTTP, HTTPS or SOCKS and PAC URLs or inline scripts, with bypass rules. PAC work has a ten-second ceiling and follows the context's cancellation; failed policies return `proxy.ErrUnavailable` rather than silently going direct | WinHTTP's automatic proxy: auto-detection (WPAD), the PAC script, or the static per-user settings | the environment only (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`); a proxy kept in GSettings is not read | `proxy.ErrUnavailable` | | Fullscreen (`RequestFullscreen`, `OnFullscreen`) | `NSWindow.toggleFullScreen:` | `SetWindowPos` / window style | window-manager fullscreen | `requestFullscreen` / `exitFullscreen`, reported by `fullscreenchange` | @@ -78,6 +79,8 @@ single running copy should pass those arguments through - `ErrUserGestureRequired` means a browser rejected an operation outside an accepted direct-input gesture. - `ErrPermissionDenied` means the user or system denied the capability. +- `ErrElevationDeclined` means the user refused the consent prompt of + `StartElevated`; it is a choice, not a failure to report. Callers should use `errors.Is` rather than matching error strings. diff --git a/gfx/pose.go b/gfx/pose.go index 23e23ea3d..d40d7730e 100644 --- a/gfx/pose.go +++ b/gfx/pose.go @@ -238,3 +238,31 @@ func (canvas *Canvas) GlideFrom(id ID, slot uint8, from Point) { entry.origin = Point{X: from.X - entry.channels[0].value(now), Y: from.Y - entry.channels[1].value(now)} entry.placed = true } + +// GlideShown reports where the canvas shows the element BeginGlide placed under +// id (slot 0), as of this frame's time: the place its last frame painted, carried +// on by the slide in flight, in the coordinates BeginGlide's place is measured in. +// Called before the frame places the element, it is what the eye sees now; a slide +// that this frame's layout begins starts from exactly this point. It reports false +// for an element the canvas has not seen painted, for ID zero, outside a frame with +// a clock and under reduced motion, where an element is only at its place. It +// allocates nothing. +func (canvas *Canvas) GlideShown(id ID) (Point, bool) { + state := &canvas.motion + if !state.active || state.reduce || id.IsZero() { + return Point{}, false + } + index := -1 + for candidate := range state.poses { + if state.poses[candidate].id == id && state.poses[candidate].slot == 0 { + index = candidate + break + } + } + if index < 0 || !state.poses[index].placed { + return Point{}, false + } + entry := &state.poses[index] + now := state.frameTime() + return Point{X: entry.origin.X + entry.channels[0].value(now), Y: entry.origin.Y + entry.channels[1].value(now)}, true +} diff --git a/headless/control.go b/headless/control.go index 95587473f..b1235c25c 100644 --- a/headless/control.go +++ b/headless/control.go @@ -98,6 +98,8 @@ import ( // openedurl report the last public OpenURL request // openedpath report the last OpenPath request // revealedpath report the last RevealPath request +// elevatedstarts report the StartElevated requests so far, as quoted command lines (none: ok none) +// elevatedresult [declined] make StartElevated answer a refused consent prompt (no argument: a started program) // schemehandlers [SCHEME...] declare which custom URL schemes have a registered application (none: clear) // openfiles PATH...|cancel queue the next native open-dialog result // opendirectory PATH|cancel queue the next native directory-dialog result @@ -185,6 +187,29 @@ func execute(session *Session, line string) (reply string, quit bool) { case "schemehandlers": session.driver.SetSchemeHandlers(strings.Fields(rest)...) return finish(nil, "") + case "elevatedstarts": + if rest != "" { + return finish(fmt.Errorf("elevatedstarts takes no arguments"), "") + } + starts := session.driver.ElevatedStarts() + if len(starts) == 0 { + return finish(nil, " none") + } + var lines []string + for _, args := range starts { + lines = append(lines, strconv.Quote(strings.Join(args, " "))) + } + return finish(nil, " "+strings.Join(lines, " ")) + case "elevatedresult": + switch rest { + case "": + session.driver.SetElevatedStartResult(nil) + case "declined": + session.driver.SetElevatedStartResult(app.ErrElevationDeclined) + default: + return finish(fmt.Errorf("elevatedresult takes declined or nothing"), "") + } + return finish(nil, "") case "openedurl": if rest != "" { return finish(fmt.Errorf("openedurl takes no arguments"), "") diff --git a/headless/control_system_test.go b/headless/control_system_test.go index 54c04ada8..eefa6e5a3 100644 --- a/headless/control_system_test.go +++ b/headless/control_system_test.go @@ -4,6 +4,7 @@ package headless import ( "bytes" + "errors" "image" "image/png" "os" @@ -228,3 +229,36 @@ func TestControlClipfilesFeedsTheAppsClipboardFileReads(t *testing.T) { t.Fatalf("copying text leaves the files: %v", err) } } + +func TestControlReportsAndAnswersElevatedStarts(t *testing.T) { + session, err := Open(app.Config{}, nil, Options{}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + + if reply, _ := execute(session, "elevatedstarts"); reply != "ok none\n" { + t.Fatalf("elevatedstarts before any start = %q", reply) + } + if err := app.StartElevated("--local-terminal", "pwsh"); err != nil { + t.Fatal(err) + } + if reply, _ := execute(session, "elevatedstarts"); reply != "ok \"--local-terminal pwsh\"\n" { + t.Fatalf("elevatedstarts = %q", reply) + } + if reply, _ := execute(session, "elevatedresult declined"); reply != "ok\n" { + t.Fatalf("elevatedresult reply = %q", reply) + } + if err := app.StartElevated("x"); !errors.Is(err, app.ErrElevationDeclined) { + t.Fatalf("StartElevated after a declined result = %v", err) + } + if reply, _ := execute(session, "elevatedresult"); reply != "ok\n" { + t.Fatalf("elevatedresult reset reply = %q", reply) + } + if err := app.StartElevated("y"); err != nil { + t.Fatalf("StartElevated after the reset = %v", err) + } + if reply, _ := execute(session, "elevatedresult maybe"); !strings.HasPrefix(reply, "error") { + t.Fatalf("elevatedresult with an unknown answer = %q", reply) + } +} diff --git a/internal/componentdemo/code_merge.go b/internal/componentdemo/code_merge.go index 1e55c6c5f..2c11eef4b 100644 --- a/internal/componentdemo/code_merge.go +++ b/internal/componentdemo/code_merge.go @@ -19,7 +19,8 @@ var ( const ( codeMergeCurrent = "head\nlocal\ntail" codeMergeIncoming = "head\nremote\ntail" - codeMergeResult = "head\nchoice\ntail" + codeMergeResult = codeMergeCurrent + codeMergeAccepted = codeMergeIncoming ) type codeMergeDemoState struct { @@ -28,13 +29,14 @@ type codeMergeDemoState struct { current []string incoming []string actions [1]components.CodeMergeAction + conflicts [1]components.CodeMergeConflict value string accepted bool } var codeMergeComponent = Component{ ID: "code-merge", Title: "Code Merge", Category: "Forms", - Summary: "并排查看 Current、可编辑的 Result 与 Incoming,操作含义由应用决定。", + Summary: "并排查看 Current、可编辑的 Result 与 Incoming,标出未解决的冲突,操作含义由应用决定。", initialize: func(state *State) { state.codeMerge = &codeMergeDemoState{ current: strings.Split(codeMergeCurrent, "\n"), incoming: strings.Split(codeMergeIncoming, "\n"), @@ -54,17 +56,18 @@ var codeMergeComponent = Component{ return text.NewEditor(codeMergeResult) }, Examples: []Example{{ - ID: "default", Title: "三方对齐", Description: "中栏可编辑;点击 Incoming 操作由调用方接收并决定如何更新结果。", + ID: "default", Title: "三方对齐", Description: "中栏可编辑;接受 Incoming 或改写冲突行后,由调用方把冲突记为已解决。", Height: 310, Snippet: `merge.Paint(canvas, theme, bounds, components.CodeMergeSnapshot{ Current: currentLines, Incoming: incomingLines, Rows: alignedRows, + Conflicts: []components.CodeMergeConflict{{Start: 1, End: 2, Resolved: accepted}}, Editor: components.CodeDiffSnapshot{ID: resultID, Value: result}, Actions: []components.CodeMergeAction{{Row: 1, Incoming: true, ID: acceptID, Label: "Accept"}}, })`, PageSnippet: `current := []string{"head", "local", "tail"} incoming := []string{"head", "remote", "tail"} -result := "head\nchoice\ntail" +result := "head\nlocal\ntail" type mergeRow struct { CurrentLine, ResultLine, IncomingLine int CurrentChanged, IncomingChanged bool @@ -83,14 +86,24 @@ type mergeAction struct { m.merge.Snapshot.Current = current m.merge.Snapshot.Incoming = incoming m.merge.Snapshot.Rows = rows +type mergeConflict struct { + Start, End int + Resolved bool +} +m.merge.Snapshot.Conflicts = []mergeConflict{{Start: 1, End: 2, Resolved: m.accepted}} m.merge.Snapshot.Editor.Value = result m.merge.Snapshot.Editor.VerticalScrollbarID = codeeditor.Shown // m.acceptID is the caller's stable hit ID for the Accept action. m.merge.Snapshot.Actions = []mergeAction{{Row: 1, Incoming: true, ID: m.acceptID, Label: "Accept"}} -codeeditor.MergeView(c, "Merge result", &m.merge).Fill()`, +codeeditor.MergeView(c, "Merge result", &m.merge).Fill() +// Next and previous: from the caret's row to an unresolved conflict. +row, _ := m.merge.Code.RowOfOffset(m.caret) +if index, ok := m.merge.Snapshot.NextConflict(row, true); ok { + m.merge.Code.RevealRow(m.merge.Snapshot.Conflicts[index].Start) +}`, PageSnippetZh: `current := []string{"head", "local", "tail"} incoming := []string{"head", "remote", "tail"} -result := "head\nchoice\ntail" +result := "head\nlocal\ntail" type mergeRow struct { CurrentLine, ResultLine, IncomingLine int CurrentChanged, IncomingChanged bool @@ -109,17 +122,30 @@ type mergeAction struct { m.merge.Snapshot.Current = current m.merge.Snapshot.Incoming = incoming m.merge.Snapshot.Rows = rows +type mergeConflict struct { + Start, End int + Resolved bool +} +m.merge.Snapshot.Conflicts = []mergeConflict{{Start: 1, End: 2, Resolved: m.accepted}} m.merge.Snapshot.Editor.Value = result m.merge.Snapshot.Editor.VerticalScrollbarID = codeeditor.Shown // m.acceptID 是调用方为“接受”操作分配的稳定命中 ID。 m.merge.Snapshot.Actions = []mergeAction{{Row: 1, Incoming: true, ID: m.acceptID, Label: "接受"}} -codeeditor.MergeView(c, "合并结果", &m.merge).Fill()`, +codeeditor.MergeView(c, "合并结果", &m.merge).Fill() +// 上一个/下一个:从光标所在行找未解决的冲突。 +row, _ := m.merge.Code.RowOfOffset(m.caret) +if index, ok := m.merge.Snapshot.NextConflict(row, true); ok { + m.merge.Code.RevealRow(m.merge.Snapshot.Conflicts[index].Start) +}`, }}, } func (state *State) paintCodeMerge(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { demo := state.codeMerge value := state.fieldValue(codeMergeResult) + if !state.editing && demo.accepted { + value = codeMergeAccepted + } if demo.value != value { alignment := components.DiffCodeLines(codeMergeCurrent, value) demo.rows = demo.rows[:0] @@ -150,24 +176,59 @@ func (state *State) paintCodeMerge(canvas *gfx.Canvas, theme gfx.Theme, size gfx snapshot.CompositionEnd = byteOffsetOfRune(value, marked.End) } } - var stage ui.Box - state.drawPage(canvas, theme, size, 750, state.Text("Code Merge · 三方对比", "Code Merge · Three-way comparison"), func(c ui.C) { - stage = ui.Slot(c).FillWidth().Height(min(float32(230), max(size.Height-105, 120))) - ui.Wrap(c, state.Text("三栏同步滚动,冲突检测和接受策略由调用方负责。", "The three panes scroll together; conflict detection and acceptance remain caller-owned.")). - FontSize(theme.Metrics.FontSizeS).Muted() - }) + // The demo's one conflict is the row of the second line; it is resolved once + // Incoming is accepted or the result no longer holds Current's line there. + var conflicts []components.CodeMergeConflict var actions []components.CodeMergeAction for rowIndex, row := range demo.rows { - if row.IncomingLine == 1 && !demo.accepted { + if row.CurrentLine != 1 && row.IncomingLine != 1 { + continue + } + resolved := demo.accepted || row.ResultLine < 0 || state.editing && !codeMergeLineIs(value, row.ResultLine, demo.current[1]) + demo.conflicts[0] = components.CodeMergeConflict{Start: rowIndex, End: rowIndex + 1, Resolved: resolved} + conflicts = demo.conflicts[:] + if !resolved { demo.actions[0] = components.CodeMergeAction{Row: rowIndex, Incoming: true, ID: codeMergeAccept, Label: state.Text("接受", "Accept")} actions = demo.actions[:] - break } + break + } + merge := components.CodeMergeSnapshot{ + Current: demo.current, Incoming: demo.incoming, Rows: demo.rows, Conflicts: conflicts, Editor: snapshot, Actions: actions, + } + remaining := state.Text("冲突已全部解决", "All conflicts resolved") + if merge.Unresolved() > 0 { + remaining = state.Text("剩余 1 个冲突", "1 conflict remaining") } - demo.component.Paint(canvas, theme, stage.Rect(), components.CodeMergeSnapshot{ - Current: demo.current, Incoming: demo.incoming, Rows: demo.rows, Editor: snapshot, Actions: actions, + var stage ui.Box + state.drawPage(canvas, theme, size, 750, state.Text("Code Merge · 三方对比", "Code Merge · Three-way comparison"), func(c ui.C) { + ui.Text(c, remaining).FontSize(theme.Metrics.FontSizeS).Muted() + stage = ui.Slot(c).FillWidth().Height(min(float32(230), max(size.Height-105, 120))) }) + demo.component.Paint(canvas, theme, stage.Rect(), merge) if canvas.Clicked(codeMergeAccept) { + if state.editing { + if offset, ok := demo.component.RowOffset(demo.conflicts[0].Start); ok { + start := state.editor.RuneIndex(offset) + state.editor.ReplaceRange(text.Range{Start: start, End: start + len([]rune(demo.current[1]))}, demo.incoming[1]) + } + } demo.accepted = true } } + +// codeMergeLineIs reports whether line index of value is want, without +// splitting the value. +func codeMergeLineIs(value string, index int, want string) bool { + for ; index > 0; index-- { + newline := strings.IndexByte(value, '\n') + if newline < 0 { + return false + } + value = value[newline+1:] + } + if newline := strings.IndexByte(value, '\n'); newline >= 0 { + value = value[:newline] + } + return value == want +} diff --git a/internal/platform/windows/direct_windows.go b/internal/platform/windows/direct_windows.go index 081068ee1..420b1ec92 100644 --- a/internal/platform/windows/direct_windows.go +++ b/internal/platform/windows/direct_windows.go @@ -41,6 +41,10 @@ const ( writeSetCharacterSpacing = 69 writeSetUnderline = 36 writeSetStrikethrough = 37 + writeSetTypography = 40 + + writeFactoryCreateTypography = 16 // IDWriteFactory + writeTypographyAddFontFeature = 3 // IDWriteTypography ) // D2D1_TEXT_ANTIALIAS_MODE, D2D1_ALPHA_MODE and D2D1_DRAW_TEXT_OPTIONS. @@ -193,6 +197,7 @@ type directRasterizer struct { inkCache map[inkKey]platform.GridInk formats map[gridFormatKey]uintptr shaped map[gridLayoutKey]*gridLayout + typography uintptr // IDWriteTypography of one glyph per cell; see cellTypography gdi *gdiGridRasterizer // the GDI face of fixed-pitch runs, made on first use directOnly bool // draw fixed-pitch runs with DirectWrite alone; tests compare the two } diff --git a/internal/platform/windows/elevate_windows.go b/internal/platform/windows/elevate_windows.go new file mode 100644 index 000000000..218f5ec94 --- /dev/null +++ b/internal/platform/windows/elevate_windows.go @@ -0,0 +1,93 @@ +//go:build windows + +package windows + +import ( + "errors" + "fmt" + "syscall" + "unsafe" +) + +// ErrElevationDeclined reports that the user dismissed the consent prompt, or +// that the system refused the request without one. +var ErrElevationDeclined = errors.New("windows: elevation was declined") + +const ( + // seeMaskNoAsync makes ShellExecuteEx finish the launch before it returns, + // so a caller's thread may end right after without losing the request. + seeMaskNoAsync = 0x00000100 + swShowNormal = 1 + errorCancelled = syscall.Errno(1223) +) + +var shellExecuteEx = shell.NewProc("ShellExecuteExW") + +// shellExecuteInfo is SHELLEXECUTEINFOW. Its fields keep the Win32 order and +// types, so the same Go layout is right on 32- and 64-bit targets. +type shellExecuteInfo struct { + size uint32 + mask uint32 + window uintptr + verb *uint16 + file *uint16 + parameters *uint16 + directory *uint16 + show int32 + instance uintptr + idList uintptr + class *uint16 + keyClass uintptr + hotKey uint32 + icon uintptr + process uintptr +} + +// Elevated reports whether this process runs with an administrator's elevated +// token. Where User Account Control is off, an administrator's every process +// does. +func Elevated() bool { return elevated() } + +// StartElevated starts executable with arguments under the consent prompt that +// asks for administrator rights, and returns once the system has either started +// it or refused. The new process is not a child of this one: it keeps its own +// integrity level, which is why nothing of this process's input reaches it. +func StartElevated(executable string, arguments []string) error { + verb, _ := syscall.UTF16PtrFromString("runas") + file, err := syscall.UTF16PtrFromString(executable) + if err != nil { + return err + } + var parameters *uint16 + if line := ComposeCommandLine(arguments); line != "" { + if parameters, err = syscall.UTF16PtrFromString(line); err != nil { + return err + } + } + info := shellExecuteInfo{ + mask: seeMaskNoAsync, window: dialogOwner(), + verb: verb, file: file, parameters: parameters, show: swShowNormal, + } + info.size = uint32(unsafe.Sizeof(info)) + started, _, callErr := shellExecuteEx.Call(uintptr(unsafe.Pointer(&info))) + if started == 0 { + if errors.Is(callErr, errorCancelled) { + return ErrElevationDeclined + } + return windowsCallError(fmt.Sprintf("start %s elevated", executable), callErr) + } + return nil +} + +// ComposeCommandLine joins arguments into the one string Windows hands a +// program, quoted so that the program's own parser reads back exactly them. +func ComposeCommandLine(arguments []string) string { + var line []byte + for index, argument := range arguments { + if index > 0 { + line = append(line, ' ') + } + line = append(line, syscall.EscapeArg(argument)...) + } + return string(line) +} diff --git a/internal/platform/windows/elevate_windows_test.go b/internal/platform/windows/elevate_windows_test.go new file mode 100644 index 000000000..506a60e38 --- /dev/null +++ b/internal/platform/windows/elevate_windows_test.go @@ -0,0 +1,43 @@ +//go:build windows + +package windows + +import ( + "slices" + "syscall" + "testing" + "unsafe" +) + +// The command line must read back as the very arguments it was made from, by +// the parser Windows itself offers. +func TestComposeCommandLineRoundTripsThroughTheWindowsParser(t *testing.T) { + for _, arguments := range [][]string{ + {"--local-terminal=C:\\Program Files\\PowerShell\\7\\pwsh.exe"}, + {"two words", `quote"inside`, `trailing backslash\`, ""}, + {`C:\dir with space\`, `a\\"b`}, + } { + // The first word of a command line is the program's own name. + line, err := syscall.UTF16PtrFromString("program.exe " + ComposeCommandLine(arguments)) + if err != nil { + t.Fatal(err) + } + var count int32 + argv, err := syscall.CommandLineToArgv(line, &count) + if err != nil { + t.Fatal(err) + } + got := make([]string, 0, count) + for index := int32(1); index < count; index++ { + got = append(got, syscall.UTF16ToString(argv[index][:])) + } + syscall.LocalFree(syscall.Handle(uintptr(unsafe.Pointer(argv)))) + if !slices.Equal(got, arguments) { + t.Fatalf("arguments %q came back as %q", arguments, got) + } + } +} + +func TestElevatedReportsWithoutFailing(t *testing.T) { + t.Logf("this process is elevated: %v", Elevated()) +} diff --git a/internal/platform/windows/grid_cache_windows.go b/internal/platform/windows/grid_cache_windows.go index 506cfc646..f32e201f9 100644 --- a/internal/platform/windows/grid_cache_windows.go +++ b/internal/platform/windows/grid_cache_windows.go @@ -108,6 +108,21 @@ func (rasterizer *directRasterizer) gridShaped(format gridFormatKey, handle uint release(&layout) } }() + all := uint64(shaped.chars) << 32 + cells := !run.Ligatures && pitch > 0 && printableASCII(piece) + if cells { + // One glyph per cell (gfx.TextRun.Ligatures): DirectWrite applies a font's + // contextual alternates and ligatures by default, which would join + // characters such as Maple Mono's ]# however the advances are spaced. + // Before the metrics, which a substitution changes. + typography, err := rasterizer.cellTypography() + if err != nil { + return nil, err + } + if err := hresult(comCall2(layout, writeSetTypography, typography, uintptr(all))); err != nil { + return nil, fmt.Errorf("windows: set grid typography: %w", err) + } + } if err := hresult(comCall1(layout, writeGetMetrics, uintptr(unsafe.Pointer(&shaped.metrics)))); err != nil { return nil, err } @@ -115,14 +130,13 @@ func (rasterizer *directRasterizer) gridShaped(format gridFormatKey, handle uint if err := hresult(comCall3(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&shaped.line)), 1, uintptr(unsafe.Pointer(&lines)))); err != nil && lines == 0 { return nil, err } - all := uint64(shaped.chars) << 32 if run.Underline { comCall2(layout, writeSetUnderline, 1, uintptr(all)) } if run.Strike { comCall2(layout, writeSetStrikethrough, 1, uintptr(all)) } - if !run.Ligatures && pitch > 0 && printableASCII(piece) { + if cells { // Every character stands on its cell, whatever the advance of the font. advance := shaped.metrics.WidthTrailing / float32(shaped.chars) if reduction := advance - pitch; reduction != 0 { @@ -140,6 +154,34 @@ func (rasterizer *directRasterizer) gridShaped(format gridFormatKey, handle uint return shaped, nil } +// cellTypography returns the typography that turns off the font features that +// would put anything but one glyph on each cell of a run: ligatures (standard +// and contextual), contextual alternates, and kerning. It is made once and owned +// by the rasterizer: callers must not release it. +func (rasterizer *directRasterizer) cellTypography() (uintptr, error) { + if rasterizer.typography != 0 { + return rasterizer.typography, nil + } + var typography uintptr + if err := hresult(comCall1(rasterizer.services.write, writeFactoryCreateTypography, uintptr(unsafe.Pointer(&typography)))); err != nil { + return 0, fmt.Errorf("windows: create grid typography: %w", err) + } + for _, tag := range [...]uint32{openTypeTag("liga"), openTypeTag("clig"), openTypeTag("calt"), openTypeTag("kern")} { + // DWRITE_FONT_FEATURE{nameTag, parameter 0} fits in one register. + if err := hresult(comCall1(typography, writeTypographyAddFontFeature, uintptr(tag))); err != nil { + release(&typography) + return 0, fmt.Errorf("windows: turn off a grid font feature: %w", err) + } + } + rasterizer.typography = typography + return typography, nil +} + +// openTypeTag is DWRITE_MAKE_OPENTYPE_TAG. +func openTypeTag(name string) uint32 { + return uint32(name[0]) | uint32(name[1])<<8 | uint32(name[2])<<16 | uint32(name[3])<<24 +} + // setCharacterSpacing gives a layout direct-write's per-range character spacing. func (rasterizer *directRasterizer) setCharacterSpacing(layout uintptr, trailing float32, span uint64) { var extended uintptr @@ -161,5 +203,6 @@ func (rasterizer *directRasterizer) releaseGridCache() { for _, shaped := range rasterizer.shaped { release(&shaped.layout) } + release(&rasterizer.typography) rasterizer.formats, rasterizer.shaped = nil, nil } diff --git a/internal/platform/windows/ligature_windows_test.go b/internal/platform/windows/ligature_windows_test.go index 9bc70b7cb..f2e770c67 100644 --- a/internal/platform/windows/ligature_windows_test.go +++ b/internal/platform/windows/ligature_windows_test.go @@ -2,6 +2,7 @@ package windows import ( "bytes" + _ "embed" "fmt" "image" "runtime" @@ -81,3 +82,55 @@ func TestFixedPitchLigatureRunShapesTheFont(t *testing.T) { t.Fatal("the fixed-pitch renderer drew no ligature for Consolas") } } + +// testLigatureFont is testdata/VivaTestLigature-Regular.ttf (see ligature_font.py): +// a fixed-pitch font of 600 units whose contextual alternates join "]#" into one +// glyph two cells wide, as Maple Mono does in a root prompt. +// +//go:embed testdata/VivaTestLigature-Regular.ttf +var testLigatureFont []byte + +// A run that does not ask for ligatures has one glyph on each cell even when the +// font's default features would join its characters (t8y2/motty#1820): it draws +// what the same characters draw as runs of their own. +func TestFixedPitchRunWithoutLigaturesKeepsEveryCharacter(t *testing.T) { + engine, err := theTextEngine() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + family, unregister, err := engine.RegisterFont(testLigatureFont) + if err != nil { + t.Fatalf("register the test font: %v", err) + } + t.Cleanup(unregister) + rasterizer := newTestRasterizer(t) + rasterizer.directOnly = true // GDI shapes nothing; the DirectWrite path is the one that can join + const size, cell, width, height = 20, 12, 48, 28 + white := gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1} + // Grayscale is how a window over a translucent backdrop draws its text; + // ClearType is how an opaque one does. + for _, lcd := range []bool{false, true} { + render := func(runs ...gfx.TextRun) []byte { + t.Helper() + label := platform.TextLabel{ + Value: "]#", Width: width, Height: height, FontSize: size, CellWidth: cell, + Mono: true, MonoFace: gfx.MonoFamily(family), Runs: runs, + } + pixels, _, err := rasterizer.rasterize(label, 1, width, height, lcd, 0) + if err != nil { + t.Fatal(err) + } + return bytes.Clone(pixels) + } + apart := render( + gfx.TextRun{Column: 0, Bytes: 1, Cells: 1, Color: white}, + gfx.TextRun{Column: 1, Bytes: 1, Cells: 1, Color: white}, + ) + if bytes.Equal(render(gfx.TextRun{Bytes: 2, Cells: 2, Color: white, Ligatures: true}), apart) { + t.Fatalf("ClearType %v: the test font's ]# ligature was not shaped; the test cannot tell a joined run", lcd) + } + if !bytes.Equal(render(gfx.TextRun{Bytes: 2, Cells: 2, Color: white}), apart) { + t.Errorf("ClearType %v: a run without ligatures joined ]# into the font's ligature", lcd) + } + } +} diff --git a/internal/platform/windows/menu_keyboard_windows_test.go b/internal/platform/windows/menu_keyboard_windows_test.go index 0a6374c98..21caf7398 100644 --- a/internal/platform/windows/menu_keyboard_windows_test.go +++ b/internal/platform/windows/menu_keyboard_windows_test.go @@ -26,7 +26,8 @@ func TestQueuedMenuKeysLeaveTerminalCompositionWithItsOwner(t *testing.T) { {"E during composition", 'E', 'E', true, false}, {"IME-processed C", 'C', vkProcessKey, true, false}, {"IME-processed E", 'E', vkProcessKey, true, false}, - {"keyboard hook", 'E', 'E', true, true}, + {"C keyboard hook", 'C', 'C', false, true}, + {"E keyboard hook", 'E', 'E', true, true}, } { t.Run(tc.name, func(t *testing.T) { runtime.LockOSThread() @@ -82,6 +83,9 @@ func TestQueuedMenuKeysLeaveTerminalCompositionWithItsOwner(t *testing.T) { return platform.Frame{}, nil }, OnShortcut: func(event platform.KeyEvent) (platform.Frame, bool, error) { + if event.Repeat { + t.Error("a repeat reached the shortcut instead of the initial press") + } shortcuts = append(shortcuts, event.Text) if menuOpen { checkOwner("shortcut") @@ -111,15 +115,18 @@ func TestQueuedMenuKeysLeaveTerminalCompositionWithItsOwner(t *testing.T) { if tc.fromHook { // Exercise the installed hook's key route and private message without // sending hardware input to the user's foreground application. - if !state.shortcutsHeld || shortcutHook.handle == 0 || - !state.takePhysicalMenuKey(wmKeyDown, &kbdLLHook{VkCode: uint32(tc.sent), ScanCode: uint32(scan)}) { + key := kbdLLHook{VkCode: uint32(tc.sent), ScanCode: uint32(scan)} + if !state.shortcutsHeld || shortcutHook.handle == 0 || !state.takePhysicalMenuKey(wmKeyDown, &key) { t.Error("the installed hook did not consume the menu press") } + if !state.takePhysicalMenuKey(wmKeyUp, &key) { + t.Error("the installed hook did not consume the menu release") + } } else { postMessage.Call(state.window, wmKeyDown, tc.sent, flags) + postMessage.Call(state.window, wmKeyDown, tc.sent, flags|1<<30) + postMessage.Call(state.window, wmKeyUp, tc.sent, flags|1<<30|1<<31) } - postMessage.Call(state.window, wmKeyDown, tc.sent, flags|1<<30) - postMessage.Call(state.window, wmKeyUp, tc.sent, flags|1<<30|1<<31) application.Post(func() { checkOwner("after key up") if state.shortcutsHeld || shortcutHook.handle != 0 { diff --git a/internal/platform/windows/menu_keys_windows.go b/internal/platform/windows/menu_keys_windows.go index c2f6de680..2d0348219 100644 --- a/internal/platform/windows/menu_keys_windows.go +++ b/internal/platform/windows/menu_keys_windows.go @@ -5,7 +5,7 @@ import ( "github.com/vivaui/viva/internal/platform" ) -const wmMenuKey = wmUpdateIcon + 1 +const wmMenuKey = 0x8058 // after wmSetWatermark var imeVirtualKey = imm.NewProc("ImmGetVirtualKey") diff --git a/internal/platform/windows/open_with_windows.go b/internal/platform/windows/open_with_windows.go index e87edc6b5..c0dd6db0e 100644 --- a/internal/platform/windows/open_with_windows.go +++ b/internal/platform/windows/open_with_windows.go @@ -13,12 +13,13 @@ import ( const openWithCreateNoWindow = 0x08000000 +// openWithCommand gives a console program no console window. It must not set +// HideWindow: that puts SW_HIDE in STARTUPINFO, which Windows applies to the +// first ShowWindow of a GUI program, so the editor would start with its main +// window hidden. func openWithCommand(executable, path string) *exec.Cmd { command := exec.Command(executable, path) - command.SysProcAttr = &syscall.SysProcAttr{ - HideWindow: true, - CreationFlags: openWithCreateNoWindow, - } + command.SysProcAttr = &syscall.SysProcAttr{CreationFlags: openWithCreateNoWindow} return command } diff --git a/internal/platform/windows/open_with_windows_test.go b/internal/platform/windows/open_with_windows_test.go index f49f5bcf2..8a78efc6b 100644 --- a/internal/platform/windows/open_with_windows_test.go +++ b/internal/platform/windows/open_with_windows_test.go @@ -7,13 +7,16 @@ import ( "testing" ) -func TestOpenWithCommandPassesOnePathAndHidesItsConsole(t *testing.T) { +func TestOpenWithCommandPassesOnePathAndShowsTheEditor(t *testing.T) { command := openWithCommand(`C:\Program Files\Editor\Editor.exe`, `C:\Notes\server config.yml`) if want := []string{`C:\Program Files\Editor\Editor.exe`, `C:\Notes\server config.yml`}; !reflect.DeepEqual(command.Args, want) { t.Fatalf("command args = %q, want %q", command.Args, want) } - if command.SysProcAttr == nil || !command.SysProcAttr.HideWindow || - command.SysProcAttr.CreationFlags&openWithCreateNoWindow == 0 { + if command.SysProcAttr == nil || command.SysProcAttr.CreationFlags&openWithCreateNoWindow == 0 { t.Fatal("the custom editor command does not hide its console window") } + // HideWindow would hide a GUI editor's main window as well. + if command.SysProcAttr.HideWindow { + t.Fatal("the custom editor command starts the editor's window hidden") + } } diff --git a/internal/platform/windows/testdata/VivaTestLigature-Regular.ttf b/internal/platform/windows/testdata/VivaTestLigature-Regular.ttf new file mode 100644 index 000000000..8fb4cad65 Binary files /dev/null and b/internal/platform/windows/testdata/VivaTestLigature-Regular.ttf differ diff --git a/internal/platform/windows/testdata/ligature_font.py b/internal/platform/windows/testdata/ligature_font.py new file mode 100644 index 000000000..784c6b0b2 --- /dev/null +++ b/internal/platform/windows/testdata/ligature_font.py @@ -0,0 +1,63 @@ +# Generates VivaTestLigature-Regular.ttf: a fixed-pitch font of 600 units whose +# contextual alternates (calt) replace "]#" with one glyph two cells wide, as +# Maple Mono does. "]" is a bar at the left of its cell, "#" a bar at the right +# of its own, and the ligature a horizontal bar across both, so the pixels tell +# which was drawn. +# +# python3 ligature_font.py VivaTestLigature-Regular.ttf +import sys + +from fontTools.feaLib.builder import addOpenTypeFeaturesFromString +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.ttGlyphPen import TTGlyphPen +from fontTools.ttLib.tables.O_S_2f_2 import Panose + + +def box(left, bottom, right, top): + pen = TTGlyphPen(None) + pen.moveTo((left, bottom)) + pen.lineTo((left, top)) + pen.lineTo((right, top)) + pen.lineTo((right, bottom)) + pen.closePath() + return pen.glyph() + + +def empty(): + return TTGlyphPen(None).glyph() + + +order = [".notdef", "space", "bracketright", "numbersign", "bracketright_numbersign.liga"] +builder = FontBuilder(1000, isTTF=True) +builder.setupGlyphOrder(order) +builder.setupCharacterMap({0x20: "space", 0x23: "numbersign", 0x5D: "bracketright"}) +builder.setupGlyf({ + ".notdef": box(50, 0, 550, 700), + "space": empty(), + "bracketright": box(80, 0, 200, 700), + "numbersign": box(400, 0, 520, 700), + "bracketright_numbersign.liga": box(0, 300, 1200, 420), +}) +# Advance and left side bearing (the xMin of each outline). +metrics = { + ".notdef": (600, 50), + "space": (600, 0), + "bracketright": (600, 80), + "numbersign": (600, 400), + "bracketright_numbersign.liga": (1200, 0), +} +builder.setupHorizontalMetrics(metrics) +builder.setupHorizontalHeader(ascent=800, descent=-200) +builder.setupNameTable({"familyName": "Viva Test Ligature", "styleName": "Regular"}) +# A monospaced panose (bProportion 9), so the font is listed as fixed-pitch. +panose = Panose() +panose.bFamilyType, panose.bProportion = 2, 9 +builder.setupOS2(sTypoAscender=800, sTypoDescender=-200, usWinAscent=800, usWinDescent=200, + panose=panose) +builder.setupPost(isFixedPitch=1) +addOpenTypeFeaturesFromString(builder.font, """ +languagesystem DFLT dflt; +languagesystem latn dflt; +feature calt { sub bracketright numbersign by bracketright_numbersign.liga; } calt; +""") +builder.save(sys.argv[1]) diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 721e30f12..880280ace 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -548,6 +548,11 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmChangeDecoration: state.applyDecoration() return 0 + case wmMenuKey: + if state.ready { + state.deliverMenuMessage(first, second) + return 0 + } case wmSetTitle: state.applyTitle() return 0 @@ -1056,9 +1061,6 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { return 0 } state.modifierTap(first, second, true, modifiers()) - case wmMenuKey: - state.deliverMenuMessage(first, second) - return 0 case wmKeyDown, wmSysKeyDown: if state.textEnabled && state.imeComposing { break // IME candidate keys must not submit or dismiss the surrounding form. diff --git a/text/editing.go b/text/editing.go index 6328aca88..f72262405 100644 --- a/text/editing.go +++ b/text/editing.go @@ -94,20 +94,58 @@ func (editor *Editor) MoveWord(forward, extend bool) { // WordRange returns the run around a pointer position, on grapheme boundaries. // It reads value in place: what it walks is the word, and the rune index is found // by counting, so a drag that extends a selection by words through a long text -// allocates nothing. +// allocates nothing. WordSpan is the same run in byte offsets, without the count. func WordRange(value string, index int) Range { at, index, ok := lastRuneAt(value, index) if !ok { return Range{} } - start := at + start, end := wordSpanAt(value, at) + return Range{ + Start: index - utf8.RuneCountInString(value[start:at]), + End: index + utf8.RuneCountInString(value[at:end]), + } +} + +// LineRange returns the logical line around a pointer position, including its +// trailing newline when it has one. It is the selection a triple click takes. +// LineSpan is the same run in byte offsets, without the count. +func LineRange(value string, index int) Range { + at, index, ok := lastRuneAt(value, index) + if !ok { + return Range{} + } + start, end := lineSpanAt(value, at) + return Range{ + Start: index - utf8.RuneCountInString(value[start:at]), + End: index + utf8.RuneCountInString(value[at:end]), + } +} + +// WordSpan is the run around the byte offset at in value, on grapheme boundaries, +// as byte offsets: the same run WordRange finds for the rune at that offset. An +// offset inside a rune counts as the rune's start, and one at or past the end as +// the last rune; an empty value has an empty run. It reads only the word and what +// borders it, so its cost does not depend on the length of value. +func WordSpan(value string, at int) (start, end int) { + at, ok := runeStart(value, at) + if !ok { + return 0, 0 + } + return wordSpanAt(value, at) +} + +// wordSpanAt is WordSpan for an at that is already the start of a rune, as +// ranging over value gives it. +func wordSpanAt(value string, at int) (start, end int) { + start = at for start > 0 && !grapheme.Boundary(value, start) { _, size := utf8.DecodeLastRuneInString(value[:start]) start -= size } first, _ := utf8.DecodeRuneInString(value[start:]) kind := wordClass(first) - end := grapheme.Next(value, start) + end = grapheme.Next(value, start) for start > 0 { previous := grapheme.Prev(value, start) if r, _ := utf8.DecodeRuneInString(value[previous:]); wordClass(r) != kind { @@ -121,28 +159,49 @@ func WordRange(value string, index int) Range { } end = grapheme.Next(value, end) } - return Range{ - Start: index - utf8.RuneCountInString(value[start:at]), - End: index + utf8.RuneCountInString(value[at:end]), - } + return start, end } -// LineRange returns the logical line around a pointer position, including its -// trailing newline when it has one. It is the selection a triple click takes. -func LineRange(value string, index int) Range { - at, index, ok := lastRuneAt(value, index) +// LineSpan is the logical line around the byte offset at in value, with its +// trailing newline when it has one, as byte offsets: the same run LineRange finds +// for the rune at that offset, clamped as WordSpan clamps it. +func LineSpan(value string, at int) (start, end int) { + at, ok := runeStart(value, at) if !ok { - return Range{} + return 0, 0 } - start := strings.LastIndexByte(value[:at], '\n') + 1 - end := len(value) + return lineSpanAt(value, at) +} + +// lineSpanAt is LineSpan for an at that is already the start of a rune. +func lineSpanAt(value string, at int) (start, end int) { + start = strings.LastIndexByte(value[:at], '\n') + 1 + end = len(value) if newline := strings.IndexByte(value[at:], '\n'); newline >= 0 { end = at + newline + 1 // the newline belongs to the line it ends } - return Range{ - Start: index - utf8.RuneCountInString(value[start:at]), - End: index + utf8.RuneCountInString(value[at:end]), + return start, end +} + +// runeStart is the start of the rune holding the byte offset at in value: the +// last rune for an offset at or past the end, and not ok for an empty value. +func runeStart(value string, at int) (int, bool) { + if value == "" { + return 0, false + } + at = min(max(at, 0), len(value)-1) + // A byte inside a rune belongs to the rune that starts at most UTFMax-1 bytes + // before it; a byte no rune holds is a rune of its own, as ranging over value + // reads it. + for back := 1; back < utf8.UTFMax && back <= at; back++ { + if candidate := at - back; utf8.RuneStart(value[candidate]) { + if _, size := utf8.DecodeRuneInString(value[candidate:]); candidate+size > at { + return candidate, true + } + break + } } + return at, true } // lastRuneAt is the byte offset of the rune at index in value, index clamped to diff --git a/text/span_test.go b/text/span_test.go new file mode 100644 index 000000000..ff2124eea --- /dev/null +++ b/text/span_test.go @@ -0,0 +1,86 @@ +package text + +import ( + "strings" + "testing" + "unicode/utf8" +) + +var spanValues = []string{ + "", "a", "alpha beta_two 中文测试\ngamma delta", "é 👩‍💻 🇨🇳🇺🇸", "host.example.com:22\n\n\nx", + "tail\n", "\n", "ab\xff\xfecd", "\x80x", "a\r\nb", +} + +// checkSpans compares the byte spans at every rune start of value with the +// rune ranges, which count from the start of the text. +func checkSpans(t testing.TB, value string) { + t.Helper() + index := 0 + for at := range value { + for _, tc := range []struct { + name string + span func(string, int) (int, int) + rng func(string, int) Range + label string + }{{"WordSpan", WordSpan, WordRange, "word"}, {"LineSpan", LineSpan, LineRange, "line"}} { + start, end := tc.span(value, at) + want := tc.rng(value, index) + gotStart, gotEnd := utf8.RuneCountInString(value[:start]), utf8.RuneCountInString(value[:end]) + if utf8.ValidString(value) && (gotStart != want.Start || gotEnd != want.End) { + t.Fatalf("%s(%q, %d) = [%d,%d) in runes, %s range is %+v", tc.name, value, at, gotStart, gotEnd, tc.label, want) + } + if start > at || end <= at && at < len(value) || end > len(value) { + t.Fatalf("%s(%q, %d) = [%d,%d) does not hold the offset", tc.name, value, at, start, end) + } + } + index++ + } +} + +func TestSpansAgreeWithRanges(t *testing.T) { + for _, value := range spanValues { + checkSpans(t, value) + } +} + +func TestSpansClampTheOffset(t *testing.T) { + value := "héllo wörld" + last := strings.LastIndex(value, "d") + for _, at := range []int{-5, len(value), len(value) + 9} { + start, end := WordSpan(value, at) + if want := strings.Index(value, "wörld"); at < 0 && start != 0 || at >= len(value) && (start != want || end != len(value)) { + t.Fatalf("WordSpan(%q, %d) = [%d,%d), last rune at %d", value, at, start, end, last) + } + } + // An offset inside a rune is the rune's start. + inside := strings.Index(value, "é") + 1 + if a, b := WordSpan(value, inside); a != 0 || b != len("héllo") { + t.Fatalf("WordSpan inside a rune = [%d,%d)", a, b) + } + if a, b := WordSpan("", 3); a != 0 || b != 0 { + t.Fatalf("WordSpan of nothing = [%d,%d)", a, b) + } +} + +func FuzzSpansAgreeWithRanges(f *testing.F) { + for _, value := range spanValues { + f.Add(value) + } + f.Fuzz(func(t *testing.T, value string) { + if len(value) > 256 { + return + } + checkSpans(t, value) + }) +} + +// A span costs what the word costs, not what the text does. +func BenchmarkWordSpanLongText(b *testing.B) { + value := strings.Repeat("alpha beta_two gamma delta\n", 4096) + at := len(value) - 8 + b.ReportAllocs() + for b.Loop() { + WordSpan(value, at) + LineSpan(value, at) + } +} diff --git a/text/testdata/fuzz/FuzzSpansAgreeWithRanges/0207b12045ecfa8f b/text/testdata/fuzz/FuzzSpansAgreeWithRanges/0207b12045ecfa8f new file mode 100644 index 000000000..f735eff4d --- /dev/null +++ b/text/testdata/fuzz/FuzzSpansAgreeWithRanges/0207b12045ecfa8f @@ -0,0 +1,2 @@ +go test fuzz v1 +string("00\xb8") diff --git a/tools/docs/content.go b/tools/docs/content.go index 157a25c54..e8eda63d4 100644 --- a/tools/docs/content.go +++ b/tools/docs/content.go @@ -36,7 +36,7 @@ func documentation() map[string]Page { {ID: "keyboard", Title: "Editing and scrolling", Text: "The right pane preserves byte-based selection, composition and caret placement while the aligned rows remain read-only on the left.", Items: []string{"Mouse wheel and scrollbar drags update the shared offsets.", "Read-only previews do not expose a platform editor.", "Applications should debounce expensive recomputation and discard stale results after newer text arrives."}}, }}, "code-merge": {Sections: []Section{ - {ID: "usage", Title: "Three caller-aligned sources", Text: "CodeMerge displays Current and Incoming beside an editable Result on a shared line grid.", Items: []string{"Supply the three split sources and aligned row indices; update alignment after editing the result.", "Source gutter actions expose stable IDs and row coordinates; the caller decides what accepting a change means.", "Conflict detection, remaining counts and resolution policy are not part of the view."}}, + {ID: "usage", Title: "Three caller-aligned sources", Text: "CodeMerge displays Current and Incoming beside an editable Result on a shared line grid.", Items: []string{"Supply the three split sources and aligned row indices; update alignment after editing the result.", "Source gutter actions expose stable IDs and row coordinates; the caller decides what accepting a change means.", "Conflicts are caller-owned row ranges with a Resolved flag; the view marks unresolved ones, Unresolved counts them and NextConflict finds the next or previous one from RowOfOffset of the caret.", "Detecting conflicts, deciding what accepting a side writes and when an edit resolves a conflict stay with the caller."}}, {ID: "keyboard", Title: "Editing and scrolling", Text: "Result uses the same native text input, selection and composition bridge as CodeDiff.", Items: []string{"All three panes share vertical scrolling.", "The preview action records a click; it does not silently merge file contents."}}, }}, "split-button": {Sections: []Section{ diff --git a/ui/color_test.go b/ui/color_test.go index 058c255e7..1550dd77b 100644 --- a/ui/color_test.go +++ b/ui/color_test.go @@ -291,3 +291,23 @@ func TestColorPickerPanelStandsAboveItsDialog(t *testing.T) { t.Fatalf("open=%v color=%v, want the panel's Apply to reach the picker", state.Open(), color) } } + +func TestColorPickerPanelEscapesScrollClip(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(10, 20, 30) + d := openPage(t, func(c ui.C) { + ui.Scroll(c).Width(360).Height(400).MarginLeft(100).Children(func() { + ui.Column(c).Pad(16).Children(func() { + ui.ColorPicker(c, &state, &color, "Accent") + }) + }) + }) + d.click("Accent") + if !state.Open() { + t.Fatal("picker did not open") + } + plane := state.GetLayout().Saturation + if hit := d.hit("Saturation and brightness"); hit.Bounds != plane { + t.Fatalf("picker plane is clipped: hit=%v want=%v", hit.Bounds, plane) + } +} diff --git a/ui/controls_paint.go b/ui/controls_paint.go index 539e29ce8..8438279a9 100644 --- a/ui/controls_paint.go +++ b/ui/controls_paint.go @@ -331,7 +331,7 @@ func measureTextareaNode(f *Frame, n *Node) { line = n.LineH } n.Pref = [2]float32{n.PadX(), line + n.PadY()} - insets := snapshot.InsetTop + snapshot.InsetBottom + insets := snapshot.InsetTop + snapshot.BottomInset(f.Palette) if n.Flags&FlagThemed != 0 { n.Pref = [2]float32{0, max(64, line+n.PadY()+insets)} if n.MaxLines == 0 { diff --git a/ui/doc.go b/ui/doc.go index 87b9561cb..7d8928b0d 100644 --- a/ui/doc.go +++ b/ui/doc.go @@ -49,10 +49,13 @@ // A Grid child may span columns and rows (ColSpan, RowSpan); any child may be taken out // of the flow and placed by its edges inside its container (Absolute, Top, Right, // Bottom, Left, Inset), painted above the in-flow children and winning pointer hits -// over them; and a Popup is placed on a side of an anchor, flipped to the side with -// more room when the requested one is too small, kept inside the frame (or Within a -// rectangle) on both axes, and limited to the frame's size: see popup.go, grid.go and -// absolute.go for the exact rules. +// over them; a child of a Scroll's content may be Sticky, held at the top of the +// nearest Scroll while its place is scrolled away and pushed off by the end of its +// container, so a group's header stays in view until the next group's takes over; +// and a Popup is placed on a side of an anchor, flipped to the side with more room +// when the requested one is too small, kept inside the frame (or Within a rectangle) +// on both axes, and limited to the frame's size: see popup.go, grid.go, absolute.go +// and sticky.go in package base for the exact rules. // // The declaration runs once a frame, then the tree is laid out in one pass and // painted in order; pointer and keyboard state are read where a control is diff --git a/ui/field_limit_test.go b/ui/field_limit_test.go index 1478d4218..159a6d0f7 100644 --- a/ui/field_limit_test.go +++ b/ui/field_limit_test.go @@ -1,8 +1,11 @@ package ui_test import ( + "strconv" "testing" + "unicode/utf8" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -69,3 +72,75 @@ func TestCountedFieldRepaintsWithoutAllocating(t *testing.T) { t.Fatalf("%v allocations a repaint", allocs) } } + +// A TextArea shows its count under its text, as a TextField shows it at its end: +// inside the box, clear of every row, also when the rows scroll, and updated as +// the user types. +func TestTextAreaShowCountSitsUnderItsRows(t *testing.T) { + notes := "" + for line := 1; line <= 12; line++ { + if line > 1 { + notes += "\n" + } + notes += "line " + strconv.Itoa(line) + } + d := openPage(t, func(c ui.C) { + ui.TextArea(c, ¬es, "Notes", "", ui.MaxLength(200), ui.ShowCount()).Height(120) + }) + // count is the row the count is painted on, and rows the box the text rows are + // laid out and clipped in, which the platform's editor is also given. + geometry := func() (count, box, rows gfx.Rect) { + t.Helper() + snapshot := d.driver.Snapshot() + want := strconv.Itoa(utf8.RuneCountInString(notes)) + "/200" + found := false + for index, text := range snapshot.Texts { + if text.Value == want && index < len(snapshot.TextWidths) { + // A line is recorded from where it starts, with the box it was + // placed in; what is drawn is its measured width from there. + count, found = text.Bounds, true + count.Width = snapshot.TextWidths[index] + } + } + if !found { + t.Fatalf("the text area does not show its count %s", want) + } + for index, hit := range snapshot.Hits { + if hit.Label == "Notes" { + box = hit.Bounds + if text, ok := snapshot.HitTextAt(index); ok { + rows = text.Bounds + } + } + } + return count, box, rows + } + check := func(when string) { + t.Helper() + count, box, rows := geometry() + if count.X < box.X || count.Y < box.Y || count.X+count.Width > box.X+box.Width || count.Y+count.Height > box.Y+box.Height { + t.Fatalf("%s: the count %+v is outside the text area %+v", when, count, box) + } + if rows.Height <= 0 || rows.Y+rows.Height > count.Y { + t.Fatalf("%s: the rows %+v reach into the count's row %+v", when, rows, count) + } + } + check("before typing") + d.click("Notes") + d.typeText("!") + d.repaint() + check("after typing") +} + +// A counting TextArea repaints without allocating, as a counting TextField does. +func TestCountedTextAreaRepaintsWithoutAllocating(t *testing.T) { + notes := "abc" + d := openPage(t, func(c ui.C) { + ui.TextArea(c, ¬es, "Notes", "", ui.MaxLength(10), ui.ShowCount()) + }) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} diff --git a/ui/inputnumber/inputnumber.go b/ui/inputnumber/inputnumber.go index 96457cba8..60053e0af 100644 --- a/ui/inputnumber/inputnumber.go +++ b/ui/inputnumber/inputnumber.go @@ -50,15 +50,16 @@ type InputNumber struct { field ui.Field keyFn func(gfx.KeyEvent) gfx.EventResult - min, max float64 - step float64 - precision int // decimals; negative follows step - hint string - readOnly bool - decrease string - increase string - fieldID gfx.ID - fieldOpt [1]ui.Option + min, max float64 + step float64 + stepPlaces int // decimals step has, worked out when it is set + precision int // decimals; negative follows step + hint string + readOnly bool + decrease string + increase string + fieldID gfx.ID + fieldOpt [1]ui.Option value *float64 shown float64 // the number the field's text was made from @@ -91,7 +92,7 @@ func (n *InputNumber) Max(max float64) *InputNumber { // default. It must be above zero. func (n *InputNumber) Step(step float64) *InputNumber { if step > 0 { - n.step = step + n.step, n.stepPlaces = step, places(step) } return n } @@ -149,7 +150,12 @@ func (n *InputNumber) decimals() int { if n.precision >= 0 { return n.precision } - text := strconv.FormatFloat(n.step, 'f', -1, 64) + return n.stepPlaces +} + +// places is how many decimals x has written in its shortest exact form. +func places(x float64) int { + text := strconv.FormatFloat(x, 'f', -1, 64) if dot := strings.IndexByte(text, '.'); dot >= 0 { return len(text) - dot - 1 } diff --git a/ui/markdown/markdown.go b/ui/markdown/markdown.go index bfad88664..a70e965fe 100644 --- a/ui/markdown/markdown.go +++ b/ui/markdown/markdown.go @@ -165,6 +165,9 @@ func (m *State) Height() float32 { return m.View.Height() } // TextLen is the length in bytes of the rendered text that can be selected. func (m *State) TextLen() int { return m.View.TextLen() } +// PlainText returns a read-only view of the rendered text without copying it. +func (m *State) PlainText() string { return m.View.PlainText() } + // SelectedText is what a copy of Selection puts on the clipboard. func (m *State) SelectedText() string { return m.View.SelectedText(m.Selection) } diff --git a/ui/sticky_test.go b/ui/sticky_test.go new file mode 100644 index 000000000..e90cb2ea9 --- /dev/null +++ b/ui/sticky_test.go @@ -0,0 +1,112 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A grouped list in a ScrollArea keeps the current group's header, with its +// collapse button, at the top while the wheel scrolls through the group. The +// button works while held, a press on the header does not reach the row under it, +// and Tab still reaches the header before the group's rows. +func TestStickyGroupHeaderWorksWhileHeldInAScrollArea(t *testing.T) { + collapsed := [3]bool{} + labels := [3]string{"Group A", "Group B", "Group C"} + rowPressed := "" + view := func(c ui.C) { + ui.Scroll(c).Fill().Children(func() { + for g := range labels { + ui.Column(c).FillWidth().Children(func() { + ui.Row(c).Sticky().FillWidth().Background(pageTheme.Card).Pad(4).Children(func() { + ui.Text(c, labels[g]).Grow(1) + if ui.Button(c, "Collapse "+labels[g]).Clicked() { + collapsed[g] = !collapsed[g] + } + }) + if collapsed[g] { + return + } + for r := range 8 { + if ui.Button(c, labels[g]+" row "+string(rune('1'+r))).FillWidth().Clicked() { + rowPressed = labels[g] + } + } + }) + } + }) + } + page := ui.NewPage(ui.PageConfig{View: view, Theme: &pageTheme}) + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 360, Height: 240}), nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + hit := func(label string) gfx.Hit { + t.Helper() + for _, hit := range driver.Snapshot().Hits { + if hit.Label == label { + return hit + } + } + t.Fatalf("no %q on the page", label) + return gfx.Hit{} + } + top := hit("Collapse Group A").Bounds.Y + if err := driver.Scroll(gfx.ScrollEvent{X: 100, Y: 120, DeltaY: 120, Precise: true}); err != nil { + t.Fatal(err) + } + held := hit("Collapse Group A").Bounds + if held.Y != top { + t.Fatalf("after scrolling into group A its header button is at %v, want held at %v", held.Y, top) + } + // The press lands on the header; the row scrolled under it stays untouched. + if err := driver.Click(held.X+held.Width/2, held.Y+held.Height/2); err != nil { + t.Fatal(err) + } + if !collapsed[0] || rowPressed != "" { + t.Fatalf("a click on the held header collapsed=%t and pressed a row of %q", collapsed[0], rowPressed) + } + // Collapsing the group shortens it to its header, which scrolls away with it, + // and the next group's header takes the top: no stale position survives. + for _, hit := range driver.Snapshot().Hits { + if hit.Label == "Collapse Group A" && hit.Bounds.Height > 0 { + t.Fatalf("group A's collapsed header is still shown at %+v", hit.Bounds) + } + } + if b := hit("Collapse Group B").Bounds; b.Y != top { + t.Fatalf("after collapsing group A, group B's header button is at %v, want held at %v", b.Y, top) + } + if err := driver.Scroll(gfx.ScrollEvent{X: 100, Y: 120, DeltaY: -1000, Precise: true}); err != nil { + t.Fatal(err) + } + collapsed[0] = false + if err := driver.Paint(); err != nil { + t.Fatal(err) + } + if err := driver.Scroll(gfx.ScrollEvent{X: 100, Y: 120, DeltaY: 120, Precise: true}); err != nil { + t.Fatal(err) + } + if got := hit("Collapse Group A").Bounds.Y; got != top { + t.Fatalf("group A's header is at %v before Tab, want it held at %v", got, top) + } + first := hit("Collapse Group A").ID + if err := driver.Key(gfx.KeyTab, 0); err != nil { + t.Fatal(err) + } + if got := driver.Snapshot().Focused; got != first { + t.Fatalf("the first Tab focused %v, want group A's header button %v", got, first) + } + if err := driver.Key(gfx.KeyTab, 0); err != nil { + t.Fatal(err) + } + focused := driver.Snapshot().Focused + for _, hit := range driver.Snapshot().Hits { + if hit.ID == focused && len(hit.Label) > len("Group A row") && hit.Label[:len("Group A row")] == "Group A row" { + return + } + } + t.Fatalf("the second Tab focused %v, want a row of group A after its held header", focused) +} diff --git a/ui/text_selection_test.go b/ui/text_selection_test.go index 65163dd6f..a95539b40 100644 --- a/ui/text_selection_test.go +++ b/ui/text_selection_test.go @@ -502,3 +502,40 @@ func TestTextSelectionAreaDragFromTheBlankBeside(t *testing.T) { t.Fatalf("copied %q", got) } } + +// A double press past the end of a line that has a next one picks the line's last +// word, not the line break after it. +func TestTextSelectionAreaDoublePressAtALineEndPicksItsLastWord(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "first line\nsecond line") + }) + whole := "first line\nsecond line" + r := s.text(whole) + s.must(s.driver.ClickCount(r.X+s.width(whole, "first line")+2, r.Y+4, 2)) + s.must(s.driver.Paint()) + if got := s.copied(); got != "line" { + t.Fatalf("a double press past a line's end copied %q", got) + } +} + +// Shift with a press after a double press extends by words, keeping the first one whole. +func TestTextSelectionAreaShiftPressAfterAWordExtendsByWords(t *testing.T) { + line := "connection refused by peer" + s := openSelectable(t, func(c ui.C) { ui.Text(c, line) }) + r := s.text(line) + y := r.Y + r.Height/2 + inside := func(word string) float32 { + from := strings.Index(line, word) + before, through := s.width(line, line[:from]), s.width(line, line[:from+len(word)]) + return r.X + before + (through-before)/2 + } + s.must(s.driver.ClickCount(inside("refused"), y, 2)) + s.must(s.driver.Paint()) + s.must(s.driver.KeyDown(gfx.KeyShiftLeft, "")) + s.must(s.driver.Click(inside("peer"), y)) + s.must(s.driver.KeyUp(gfx.KeyShiftLeft, "")) + s.must(s.driver.Paint()) + if got := s.copied(); got != "refused by peer" { + t.Fatalf("a Shift press after a double press copied %q", got) + } +} diff --git a/ui/tree_test.go b/ui/tree_test.go index c64bd3f0c..f21041e93 100644 --- a/ui/tree_test.go +++ b/ui/tree_test.go @@ -649,3 +649,124 @@ func TestTreeCompressedIndentKeepsTheHierarchyForKeys(t *testing.T) { t.Fatalf("Left focused %q, want the parent", got) } } + +// glideTree is a Tree whose rows glide, painted at a clock the test moves. +type glideTree struct { + *treeModel + canvas *gfx.Canvas + page *ui.Page + now time.Duration +} + +func newGlideTree(folders []folder) *glideTree { + g := &glideTree{treeModel: newTreeModel(folders), canvas: benchCanvas(), page: ui.NewPage(ui.PageConfig{Theme: &pageTheme})} + g.state.Glide = gfx.Motion{Duration: 100 * time.Millisecond, Easing: gfx.EaseLinear} + g.canvas.SetClock(func() time.Duration { return g.now }) + return g +} + +func (g *glideTree) draw(at time.Duration) { + g.now = at + drawPage(g.page, g.canvas, g.treeModel.page) +} + +// seen is the part of each row's text that is painted, by the text of the row, as +// its top and bottom: what the eye sees, with the clips the rows were painted +// under taken into account. +func (g *glideTree) seen(names ...string) map[string][2]float32 { + out := map[string][2]float32{} + for _, text := range g.canvas.Texts() { + for _, name := range names { + if text.Value != name { + continue + } + top, bottom := text.Bounds.Y, text.Bounds.Y+text.Bounds.Height + if text.HasClip { + top, bottom = max(top, text.ClipOf.Y), min(bottom, text.ClipOf.Y+text.ClipOf.Height) + } + if bottom > top { + out[name] = [2]float32{top, bottom} + } + } + } + return out +} + +// Opening a folder puts its files in at once under it, and the folders below it +// slide down to make room. The files must not be painted over the folders that +// have not got out of the way yet: they show as the room opens. +func TestTreeOpeningAFolderRevealsItsFilesInsteadOfPaintingThemOverTheFoldersBelow(t *testing.T) { + g := newGlideTree([]folder{ + {Name: "alpha", files: []string{"one", "two", "three"}}, + {Name: "zeta", files: []string{"last"}}, + }) + g.draw(0) + g.draw(10 * time.Millisecond) + g.folders[0].open = true + g.flatten() + g.draw(time.Second) + names := []string{"alpha", "one", "two", "three", "zeta"} + first := g.seen(names...) + if _, ok := first["one"]; ok { + t.Fatalf("a file shows %v before the folder below it has moved", first["one"]) + } + if _, ok := first["zeta"]; !ok { + t.Fatal("the folder below the one that opened is not painted") + } + g.draw(time.Second + 50*time.Millisecond) + if !g.canvas.Animating() { + t.Fatal("opening a folder does not animate") + } + middle := g.seen(names...) + zeta := middle["zeta"][0] + for _, name := range []string{"one", "two", "three"} { + if seen, ok := middle[name]; ok && seen[1] > zeta+0.5 { + t.Fatalf("%s is painted down to %v, over zeta which starts at %v", name, seen[1], zeta) + } + } + g.draw(3 * time.Second) + if g.canvas.Animating() { + t.Fatal("the rows did not arrive") + } + end := g.seen(names...) + for _, name := range names { + if _, ok := end[name]; !ok { + t.Fatalf("%s is not shown once the rows have arrived", name) + } + } +} + +// A Tree whose rows glide costs nothing to repaint when nothing moves, and the row +// hold adds no allocation to the frames in which rows slide. +func TestTreeGlideRepaintAllocates(t *testing.T) { + g := newGlideTree([]folder{{Name: "etc", files: []string{"hosts", "passwd"}}, {Name: "var", files: []string{"log"}}}) + g.draw(0) + g.draw(time.Second) + at := 2 * time.Second + if allocs := testing.AllocsPerRun(100, func() { at += time.Second; g.draw(at) }); allocs != 0 { + t.Fatalf("%v allocations a repaint at rest", allocs) + } + g.folders[0].open = true + g.flatten() + at += time.Second + g.draw(at) // the frame that adds the rows allocates what a new row needs + at += 10 * time.Millisecond + if allocs := testing.AllocsPerRun(1, func() { g.draw(at) }); allocs > 4 { + t.Fatalf("%v allocations in a frame where rows slide", allocs) + } +} + +func BenchmarkTreeGlide(b *testing.B) { + folders := make([]folder, 500) + for i := range folders { + folders[i] = folder{Name: fmt.Sprintf("f%04d", i), open: i%2 == 0, files: []string{"a", "b"}} + } + g := newGlideTree(folders) + g.draw(0) + b.ReportAllocs() + at := time.Second + for b.Loop() { + at += time.Second + g.draw(at) + } +} diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md index 5d893c329..27663fcdd 100644 --- a/website/content/guides/en/system-integration.md +++ b/website/content/guides/en/system-integration.md @@ -324,6 +324,7 @@ func main() { ## Boundaries worth knowing +- `app.StartElevated` starts another copy of the program with administrator rights after the system's consent prompt (Windows' User Account Control; `Supports(CapabilityElevatedLaunch)`). It never raises the running process: the elevated copy is a separate process that an ordinary-rights process cannot type into, which is the boundary a terminal for administrators needs. Two copies of one program must not write the same files, so decide what the elevated copy may read and write before offering it. Its arguments are a request from a process of lower rights, since any process of the user's can start the program the same way; validate them as such. `app.Elevated` tells a copy that it already has the rights. - Linux file dialogs and notifications use the desktop's portal and notification service over D-Bus, and start an installed desktop utility only on a desktop without them; URL dispatch always does. Viva does not bundle GTK or Qt. - In the browser, the clipboard and file pickers return `ErrAsyncRequired` by design. Returning early would lie about success, and waiting would deadlock the WebAssembly event loop. - To follow the system's light or dark look, read `app.SystemAppearance` while painting and call `app.WatchSystemAppearance` once with a function that requests a redraw. It is called on the event-loop thread, only when the look really changed. Linux listens to the desktop portal's signal while something watches, falls back to the XSETTINGS manager, `GTK_THEME` and the GTK and KDE configuration files, and answers `AppearanceUnknown` when none gives a preference; a headless `Driver` answers `AppearanceUnknown` until `SetSystemAppearance` says otherwise. diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md index 625b59520..f69432e8c 100644 --- a/website/content/guides/zh/system-integration.md +++ b/website/content/guides/zh/system-integration.md @@ -314,6 +314,7 @@ func main() { ## 值得了解的边界 +- `app.StartElevated` 在系统的同意提示(Windows 的用户账户控制,见 `Supports(CapabilityElevatedLaunch)`)之后,以管理员权限再启动一个本程序的副本。它从不提升正在运行的进程:提升后的副本是另一个进程,普通权限的进程无法向它输入,这正是管理员终端所需要的边界。同一程序的两个副本不能同时写同一批文件,所以提供提升副本之前,先决定它可以读写什么。它的参数应当按来自低权限进程的请求来校验,因为用户的任何进程都能用同样的方式启动本程序。`app.Elevated` 告诉副本自己是否已经有了这些权限。 - Linux 上的文件对话框、URL 分发和通知,会在用户请求时启动已安装的桌面工具。Viva 不捆绑 GTK、Qt 或 D-Bus 栈。 - 在浏览器里,剪贴板和文件选择器按设计返回 `ErrAsyncRequired`。提前返回会谎报成功,而等待会让 WebAssembly 事件循环死锁。 - 要跟随系统的浅色或深色外观,就在绘制时读取 `app.SystemAppearance`,并只调用一次 `app.WatchSystemAppearance`,传入一个请求重绘的函数。它在事件循环线程上调用,且只在外观真的变了时调用。Linux 不监听桌面门户,而是在窗口获得焦点时重新读取一次,桌面没有给出偏好时返回 `AppearanceUnknown`;无窗口的 `Driver` 在调用 `SetSystemAppearance` 之前也返回 `AppearanceUnknown`。