Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 8 additions & 3 deletions app/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()
}

Expand Down Expand Up @@ -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 {
Expand Down
44 changes: 44 additions & 0 deletions app/application_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
4 changes: 4 additions & 0 deletions app/capabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion app/capabilities_native.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ func nativeCapabilities() Capabilities {
} else {
capabilities |= CapabilityWindowMaximize
}
capabilities |= capabilityTransparentWindow | capabilityNotificationActivation | capabilityWindowWatermark
capabilities |= capabilityTransparentWindow | capabilityNotificationActivation | capabilityWindowWatermark | capabilityElevatedLaunch
return Capabilities(capabilities)
}
7 changes: 7 additions & 0 deletions app/capability_elevated_native.go
Original file line number Diff line number Diff line change
@@ -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
7 changes: 7 additions & 0 deletions app/capability_elevated_other.go
Original file line number Diff line number Diff line change
@@ -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
40 changes: 40 additions & 0 deletions app/driver_system.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions app/driver_system_unsupported.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
67 changes: 67 additions & 0 deletions app/elevate.go
Original file line number Diff line number Diff line change
@@ -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)
}
45 changes: 45 additions & 0 deletions app/elevate_driver_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
11 changes: 11 additions & 0 deletions app/elevate_other.go
Original file line number Diff line number Diff line change
@@ -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)
}
26 changes: 26 additions & 0 deletions app/elevate_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
20 changes: 20 additions & 0 deletions app/elevate_windows.go
Original file line number Diff line number Diff line change
@@ -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
}
5 changes: 4 additions & 1 deletion base/elements.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading