diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a3d7e9f8b..6fb2081c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -154,16 +154,6 @@ jobs: wait "$pid" || status=1 done exit "$status" - # The Android build is the real thing: the program as a shared library with - # the NDK's compiler, the host's Java, and an APK around them with the SDK's - # tools, all of which the runner's image has. It is not run here; the - # runner has no device. - - name: Android build - run: | - export ANDROID_HOME="${ANDROID_HOME:-/usr/local/lib/android/sdk}" - export ANDROID_NDK_HOME="${ANDROID_NDK_HOME:-$(ls -d "$ANDROID_HOME"/ndk/* | sort -V | tail -1)}" - go run ./cmd/viva build --target android ./examples/guides/hello - go run ./cmd/viva build --target android --arch amd64 ./examples/guides/hello - name: Native Linux text rasterization run: | sudo apt-get install -y libpangocairo-1.0-0 fonts-noto-color-emoji || @@ -184,7 +174,7 @@ jobs: run: | sudo apt-get install -y xvfb libxcb-shape0 libgtk-3-0 || { sudo apt-get update && sudo apt-get install -y xvfb libxcb-shape0 libgtk-3-0; } - xvfb-run -a go test ./internal/platform/linux -run '^Test(PreviewNativeX11Contract|NotificationNativeX11)$' -count=1 -v + xvfb-run -a -s '-screen 0 1280x1024x24 -noreset' go test ./internal/platform/linux -run '^Test(PreviewNativeX11Contract|NotificationNativeX11|TrayWindowQueuedRedrawBeforeInput|TrayWindowRepaintsLaterExposure)$' -count=1 -v GDK_BACKEND=x11 VIVA_TEST_GTK_NOTIFICATION=1 xvfb-run -a go test -tags vivagtk ./internal/platform/linux -run '^TestGTKNotificationFocusHints$' -count=1 -v - name: Native X11 global shortcut env: @@ -193,6 +183,16 @@ jobs: sudo apt-get install -y xvfb xdotool libx11-xcb1 || { sudo apt-get update && sudo apt-get install -y xvfb xdotool libx11-xcb1; } xvfb-run -a go test ./internal/platform/linux -run '^TestNativeX11(GlobalShortcut|WindowIconPropertyUpdates)$' -count=1 -v + - name: Native X11 clipboard formats and ownership + run: | + sudo apt-get install -y xclip python3-gi gir1.2-gtk-3.0 || + { sudo apt-get update && sudo apt-get install -y xclip python3-gi gir1.2-gtk-3.0; } + env -u WAYLAND_DISPLAY GDK_BACKEND=x11 VIVA_LINUX_XCB_SMOKE=1 \ + xvfb-run -a -s '-screen 0 1280x1024x24 -noreset' \ + go test ./internal/platform/linux -run '^TestClipboardImage(FromX11Owner|AfterExternalOwnerReplacesCachedText|StreamedWithINCR)$|^TestX11ClipboardChangeLifecycle$' -count=1 -timeout=60s -v + env -u WAYLAND_DISPLAY GDK_BACKEND=x11 VIVA_TEST_GTK_CLIPBOARD_WATCH=x11 \ + xvfb-run -a -s '-screen 0 1280x1024x24 -noreset' \ + go test -tags vivagtk ./internal/platform/linux -run '^TestGTKClipboardChangeNative$' -count=1 -timeout=60s -v # The browser target is a release target: it compiles every package, runs the # shared tests under GOOS=js, and builds the browser entry points and a guide. @@ -350,11 +350,6 @@ jobs: VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1' run: go test ./internal/platform/darwin -run '^TestNativeCarbonGlobalShortcut$' -count=1 -v - # The iOS build compiles the Metal and UIKit bridge against the simulator - # SDK; it is not run here, since the runner cannot show a simulator. - - name: iOS simulator build - run: go run ./cmd/viva build --target ios-sim ./examples/guides/hello - windows-materials: diff --git a/.gitignore b/.gitignore index 391c7ffdf..151c58ecf 100644 --- a/.gitignore +++ b/.gitignore @@ -27,4 +27,3 @@ # A signing key written by viva update-keygen in the project root. /update.key -tools/android/local.sh diff --git a/README.md b/README.md index 13d83512d..74dbca185 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,9 @@ WebView and no bundled rendering runtime. - `app/proxy.SystemProxy` reports the proxy the desktop selects for an HTTP URL: CFNetwork on macOS, WinHTTP's automatic proxy on Windows (PAC, WPAD and the static settings), and the environment on Linux. A policy the platform cannot - evaluate is an error, never a silent direct connection. + evaluate is an error, never a silent direct connection. `SystemProxyContext` + lets a request cancel macOS PAC downloads and evaluation; both entry points + bound PAC work to ten seconds. - `gfx.MonoFamily` draws fixed-pitch text in any installed family and `app.MonospaceFamilies` lists them. - `Config.OnFileDrop` receives files dragged from the file manager, with the hit diff --git a/app/app.go b/app/app.go index fb2efc5a5..41571c992 100644 --- a/app/app.go +++ b/app/app.go @@ -44,7 +44,9 @@ const ( // WindowNotification opens a desktop popup that accepts pointer input and // stays open when focus changes. On Windows, macOS and X11 it requests the // bottom-right of the pointer monitor's work area without taking keyboard - // focus. On native Wayland, the compositor decides placement, stacking and + // focus. Mark the parts the user may drag with gfx.Canvas.MoveRegion or + // ui.Box.MovesWindow and save Frame's X and Y for Config.Origin. + // On native Wayland, the compositor decides placement, stacking and // keyboard focus. Use SendNotification for a system-managed notification. WindowNotification WindowMode = WindowMode(platform.WindowNotification) ) @@ -78,7 +80,10 @@ type Config struct { // system. It is a request: on Windows and macOS the content area lands there // (kept on a screen); an X11 window manager places the window's frame there, // so the content area sits below the title bar. Window.Frame reports where it - // really is. + // really is. WindowNotification restores to the nearest available monitor + // and clamps to its work area. On Windows a notification's origin is in + // physical desktop pixels, matching Frame's X and Y across mixed-DPI + // displays. A Wayland compositor may ignore the requested position. Origin *gfx.Point // Maximized asks the window manager to open the window maximized on Windows // and Linux, while keeping Width, Height and Origin as its restored floating @@ -226,12 +231,12 @@ 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) - // OnLifecycle runs on the window thread when the system moves a phone application - // between the foreground and the background, or asks it for memory. A desktop window - // never gets one. A phone may end a backgrounded application without further notice, so - // Background is when to save what the user would miss; a MemoryWarning is when to drop - // caches that can be rebuilt. - OnLifecycle func(LifecycleEvent) + // 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 + // hit under them. Handled keeps the pinch from doing anything else (nothing does by + // default), and Repaint asks for a frame. + OnPinch func(event gfx.PinchEvent) gfx.EventResult // OnActivate runs on the window thread when the top-level window becomes // the active window, including when the user switches back from another // application. Moving focus between editors inside the window does not @@ -360,16 +365,3 @@ func (config Config) originPoint() gfx.Point { } return *config.Origin } - -// LifecycleEvent is a change the system makes to the state of a phone application (see -// Config.OnLifecycle). -type LifecycleEvent uint8 - -const ( - // LifecycleBackground says the application went behind another. - LifecycleBackground LifecycleEvent = iota + 1 - // LifecycleForeground says it came back to the front. - LifecycleForeground - // LifecycleMemoryWarning says the system wants memory back. - LifecycleMemoryWarning -) diff --git a/app/application.go b/app/application.go index e1b5a177b..1594eb75a 100644 --- a/app/application.go +++ b/app/application.go @@ -140,6 +140,8 @@ func (window *Window) Show() { // application's windows finds it by comparing its pointer with their frames. The // result is false for a closed window. On displays of different scale the // coordinates of windows on different displays are only approximately comparable. +// On Windows a WindowNotification reports X and Y in physical desktop pixels, +// suitable for saving and restoring with Config.Origin. Its size is still logical. // It may be called from any goroutine. func (window *Window) Frame() (gfx.Rect, bool) { if window == nil || window.control == nil || window.closed.Load() { diff --git a/app/backend_android.go b/app/backend_android.go deleted file mode 100644 index 79a40cb14..000000000 --- a/app/backend_android.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build android - -package app - -import ( - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/platform/android" -) - -func runNative(config platform.Config) error { return android.Run(config) } -func runNativeApplication(start platform.ApplicationStart) error { - return android.RunApplication(start) -} diff --git a/app/backend_ios.go b/app/backend_ios.go deleted file mode 100644 index 968839fbe..000000000 --- a/app/backend_ios.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build ios - -package app - -import ( - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/platform/darwin" -) - -func runNative(config platform.Config) error { return darwin.Run(config) } -func runNativeApplication(start platform.ApplicationStart) error { - return darwin.RunApplication(start) -} diff --git a/app/driver.go b/app/driver.go index 841640c0e..0d03a9953 100644 --- a/app/driver.go +++ b/app/driver.go @@ -293,25 +293,6 @@ func (driver *Driver) Resize(width, height int) error { return err } -// Lifecycle tells the application the system did something to it, as a phone does when it -// moves the application to the background or asks it for memory. -func (driver *Driver) Lifecycle(event LifecycleEvent) { - if driver.config.OnLifecycle != nil { - driver.config.OnLifecycle(event) - } -} - -// SetSafeArea says the system covers the window's edges by insets, as a phone's status bar, -// sensor housing and home indicator do, and lets the page lay out again inside what is left. -func (driver *Driver) SetSafeArea(insets gfx.Insets) error { - if err := driver.Pump(); err != nil { - return err - } - size := driver.painter.size - _, err := driver.painter.resize(platform.Size{Width: size.Width, Height: size.Height, Scale: driver.painter.scale, SafeArea: insets}) - return err -} - func (driver *Driver) pointer(kind platform.PointerEventKind, x, y float32, button gfx.PointerButton, clicks int) error { if err := driver.Pump(); err != nil { return err diff --git a/app/ios_unsupported.go b/app/ios_unsupported.go deleted file mode 100644 index 6356e3dd1..000000000 --- a/app/ios_unsupported.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build ios - -package app - -// What a phone has no use for, and Android answers with its common fallbacks: -// an iPhone has no file icons for the application to ask for, and no reopening. - -func nativeFileIcon(string, int) ([]byte, error) { return nil, ErrUnsupported } -func setReopenHandler(*Config, *Window) {} diff --git a/app/mobile_unsupported.go b/app/mobile_unsupported.go deleted file mode 100644 index 7f77ae94a..000000000 --- a/app/mobile_unsupported.go +++ /dev/null @@ -1,62 +0,0 @@ -//go:build ios || android - -package app - -import ( - "fmt" - - "github.com/vivaui/viva/gfx" -) - -// Until the iOS and Android backends provide them (ADR 0095), the platforms' native -// hooks report that the system does not offer them: what a window and a host give, -// such as the clipboard, the cursor, dialogs and notifications, is added one by -// one, and each moves out of this file into the platform's own as it lands. - -func currentPlatform() Platform { return PlatformUnknown } - -func nativeHasClipboardImage() bool { return false } -func nativeClipboardImagePNG() ([]byte, error) { return nil, ErrUnsupported } -func nativeSetClipboardImage([]byte) error { return ErrUnsupported } -func nativeClipboardFiles() ([]string, error) { return nil, ErrUnsupported } -func nativeSetClipboardFiles([]string) error { return ErrUnsupported } -func nativeSetClipboardHTML(html, alt string) error { return ErrUnsupported } -func nativeOnClipboardChange(func()) error { return ErrUnsupported } -func nativeSetCursor(Cursor) error { return ErrUnsupported } -func nativeSetCursorImage(*gfx.CursorImage) error { return ErrUnsupported } -func nativeOpenFiles(OpenFileOptions) ([]string, error) { return nil, ErrUnsupported } -func nativeOpenDirectory(OpenDirectoryOptions) (string, error) { return "", ErrUnsupported } -func nativeSaveFile(SaveFileOptions) (string, error) { return "", ErrUnsupported } -func nativeSaveFileWithCheckbox(SaveFileOptions, SaveFileCheckbox) (SaveFileSelection, error) { - return SaveFileSelection{}, ErrUnsupported -} -func nativeRevealPath(string) error { return ErrUnsupported } -func nativePlaySystemSound(SystemSound) error { return ErrUnsupported } -func nativeSendNotification(Notification) error { return ErrUnsupported } -func nativeStoreSecret(string, string, []byte) error { return ErrSecretStoreUnavailable } -func nativeLoadSecret(string, string) ([]byte, error) { return nil, ErrSecretStoreUnavailable } -func nativeDeleteSecret(string, string) error { return ErrSecretStoreUnavailable } - -func nativeEnableCrashDumps(string) (string, error) { return "", ErrUnsupported } -func nativeShowFatalError(string, string) {} - -func nativeMonospaceFamilies() []string { return nil } -func nativeFontFamilies() []string { return nil } -func nativeFontWeights(string) []int { return nil } - -func nativeSetAppearance(Appearance) {} - -func nativeStartFileDrag([]string, FileDragEffect) (FileDragEffect, error) { - return FileDragNone, ErrUnsupported -} - -func nativeRegisterGlobalShortcut(GlobalShortcut, func()) (func(), error) { return nil, ErrUnsupported } -func nativePreventSleep(string) (func(), error) { return nil, ErrSleepPreventionUnavailable } -func nativeSchemeHandlerAvailable(string) (bool, error) { return false, ErrUnsupported } -func nativeOpenInBrowser(string) error { return fmt.Errorf("%w: OpenPathInBrowser", ErrUnsupported) } -func nativeOpenWith(_, _ string) error { return fmt.Errorf("%w: OpenWith", ErrUnsupported) } - -// No window buttons: the system owns the window. -const controlsDrawnByViva = false - -func platformTitlebarInsets() (leading, trailing float32) { return 0, 0 } diff --git a/app/painter.go b/app/painter.go index 39cfd77a6..ef6b5e41a 100644 --- a/app/painter.go +++ b/app/painter.go @@ -22,8 +22,6 @@ import ( // native label list, so an unchanged repaint performs no renderer work. type painter struct { fullscreen bool - // safeArea is how far the system covers the window's edges, as the platform last said. - safeArea gfx.Insets // touch reads a finger's presses, pans and flings (touch.go). touch touchState // customTitlebar says the page draws the window's titlebar strip itself @@ -38,6 +36,7 @@ type painter struct { onShortcut func(gfx.KeyEvent) gfx.EventResult captureMenuKeys func() bool onScroll func(gfx.ScrollEvent) gfx.EventResult + onPinch func(gfx.PinchEvent) gfx.EventResult // onModifierTap and tap recognize a modifier pressed and released on its own. onModifierTap func(gfx.ModifierTapEvent) gfx.EventResult // onFocusLost hears that the window lost the keyboard (Config.OnFocusLost). @@ -164,6 +163,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D onShortcut: config.OnShortcut, captureMenuKeys: config.CaptureMenuKeys, onScroll: config.OnScroll, + onPinch: config.OnPinch, onModifierTap: config.OnModifierTap, onFocusLost: config.OnFocusLost, onFileDrop: config.OnFileDrop, @@ -213,7 +213,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D func (painter *painter) resize(size platform.Size) (platform.Frame, error) { next := gfx.Size{Width: size.Width, Height: size.Height} changed := next != painter.size - painter.size, painter.scale, painter.safeArea = next, size.Scale, size.SafeArea + painter.size, painter.scale = next, size.Scale if changed && painter.onResize != nil { painter.onResize(next) } @@ -855,6 +855,23 @@ func (painter *painter) scroll(event platform.ScrollEvent) (platform.Frame, erro // applyScroll gives a scroll to the application, or scrolls the page itself when // the application leaves it, and reports whether anything changed that needs a // repaint. +// applyPinch gives the application a pinch and reports whether the page is to be painted +// again. A pinch nobody listens to changes nothing. +func (painter *painter) applyPinch(phase gfx.PinchPhase, x, y, scale, delta float32, modifiers input.Modifiers) bool { + if painter.onPinch == nil { + return false + } + target := gfx.ID{} + if hit, ok := painter.focus.Router().HitTest(x, y); ok { + target = hit + } + response := painter.onPinch(gfx.PinchEvent{ + Phase: phase, Modifiers: gfx.Modifiers(modifiers), X: x, Y: y, Scale: scale, Delta: delta, + Viewport: painter.size, Target: target, + }) + return painter.applyEventResult(response) || response.Repaint +} + func (painter *painter) applyScroll(event platform.ScrollEvent) bool { if event.DeltaY == 0 && event.DeltaX == 0 && event.Phase != gfx.ScrollPhaseEnd { return false @@ -1060,7 +1077,6 @@ func (painter *painter) paintCanvas() { painter.canvas.SetHoveredRole(painter.pointer.HoveredRole()) painter.canvas.SetPointerOnSurface(painter.onSurface) painter.canvas.SetTitlebarInsets(painter.titlebarInsets()) - painter.canvas.SetSafeArea(painter.safeArea) painter.canvas.SetScroll(painter.scrollX, painter.scrollY) painter.canvas.BeginFrame() painter.paint(painter.canvas, painter.size) diff --git a/app/proxy/native_darwin.go b/app/proxy/native_darwin.go index 9ddc908a3..67219d81a 100644 --- a/app/proxy/native_darwin.go +++ b/app/proxy/native_darwin.go @@ -3,6 +3,7 @@ package proxy import ( + "context" "errors" "fmt" "net/url" @@ -10,8 +11,8 @@ import ( darwinplatform "github.com/vivaui/viva/internal/platform/darwin" ) -func nativeSystemProxy(target *url.URL) (*url.URL, error) { - proxy, err := darwinplatform.SystemProxy(target.String()) +func nativeSystemProxy(ctx context.Context, target *url.URL) (*url.URL, error) { + proxy, err := darwinplatform.SystemProxyContext(ctx, target.String()) if errors.Is(err, darwinplatform.ErrProxyUnavailable) { return nil, fmt.Errorf("%w: %v", errSystemProxyUnavailable, err) } diff --git a/app/proxy/native_js.go b/app/proxy/native_js.go index 3b5c6f503..64b77e075 100644 --- a/app/proxy/native_js.go +++ b/app/proxy/native_js.go @@ -2,6 +2,9 @@ package proxy -import "net/url" +import ( + "context" + "net/url" +) -func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrUnavailable } +func nativeSystemProxy(context.Context, *url.URL) (*url.URL, error) { return nil, ErrUnavailable } diff --git a/app/proxy/native_linux.go b/app/proxy/native_linux.go index 6aef80d23..1b1813ce2 100644 --- a/app/proxy/native_linux.go +++ b/app/proxy/native_linux.go @@ -2,10 +2,13 @@ package proxy -import "net/url" +import ( + "context" + "net/url" +) // nativeSystemProxy is the environment, which SystemProxy has already read: // Linux desktops that keep a proxy in GSettings do not export it, and asking // them would mean starting a session-bus or GIO connection for a setting most // programs do not read. A system proxy configured there is not reported. -func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, nil } +func nativeSystemProxy(context.Context, *url.URL) (*url.URL, error) { return nil, nil } diff --git a/app/proxy/native_unsupported.go b/app/proxy/native_unsupported.go index 52c3320db..4a8805407 100644 --- a/app/proxy/native_unsupported.go +++ b/app/proxy/native_unsupported.go @@ -2,6 +2,9 @@ package proxy -import "net/url" +import ( + "context" + "net/url" +) -func nativeSystemProxy(*url.URL) (*url.URL, error) { return nil, ErrUnavailable } +func nativeSystemProxy(context.Context, *url.URL) (*url.URL, error) { return nil, ErrUnavailable } diff --git a/app/proxy/native_windows.go b/app/proxy/native_windows.go index ead6795bc..64b85b66e 100644 --- a/app/proxy/native_windows.go +++ b/app/proxy/native_windows.go @@ -3,6 +3,7 @@ package proxy import ( + "context" "errors" "fmt" "net/url" @@ -10,7 +11,7 @@ import ( windowsplatform "github.com/vivaui/viva/internal/platform/windows" ) -func nativeSystemProxy(target *url.URL) (*url.URL, error) { +func nativeSystemProxy(_ context.Context, target *url.URL) (*url.URL, error) { proxy, err := windowsplatform.SystemProxy(target.String()) if errors.Is(err, windowsplatform.ErrProxyUnavailable) { return nil, fmt.Errorf("%w: %v", errSystemProxyUnavailable, err) diff --git a/app/proxy/proxy.go b/app/proxy/proxy.go index 6cef6ffcc..7f524687e 100644 --- a/app/proxy/proxy.go +++ b/app/proxy/proxy.go @@ -1,10 +1,11 @@ // Package proxy reads the desktop's proxy settings. It is a package of its own // rather than part of app so that an application which never asks for a proxy -// does not link net/http and its TLS stack: SystemProxy is the only entry, and +// does not link net/http and its TLS stack: proxy lookup is the only entry, and // the environment answer is net/http's own. package proxy import ( + "context" "errors" "fmt" "net/http" @@ -13,8 +14,8 @@ import ( ) // ErrUnavailable reports that the desktop's proxy settings could not -// be read: a macOS system that routes through a PAC script, or a Windows -// WinHTTP session that refused the request. An application that gets it either +// be read: a PAC script that could not be evaluated, or a Windows WinHTTP +// session that refused the request. An application that gets it either // goes direct or keeps its own resolver; Viva never reports a proxy it did not // read. var ErrUnavailable = errors.New("app: the system proxy settings cannot be read") @@ -30,21 +31,36 @@ var ErrUnavailable = errors.New("app: the system proxy settings cannot be read") // desktops that keep their proxy in GSettings do not export it, and this // package does not start a D-Bus or GIO session to find it. // -// A macOS system whose policy is a PAC script returns -// ErrUnavailable: evaluating the script is asynchronous and needs a -// run loop, and silently going direct would bypass the user's policy. +// On macOS, PAC URLs and inline scripts are evaluated by CFNetwork, with a +// ten-second limit. A failed script returns ErrUnavailable rather than silently +// bypassing the policy. SystemProxyContext also cancels a pending PAC evaluation +// when its context ends. // // The call may block while the system evaluates its policy. It starts no -// goroutine and keeps nothing after it returns. +// goroutine. Use SystemProxyContext for a request with a cancellation context. func SystemProxy(target *url.URL) (*url.URL, error) { + return SystemProxyContext(context.Background(), target) +} + +// SystemProxyContext is SystemProxy with a request's context. An already-ended +// context is returned before reading settings; on macOS it also stops pending +// PAC downloads and script evaluation. Other native settings readers may finish +// their synchronous OS call before returning the context's error. +func SystemProxyContext(ctx context.Context, target *url.URL) (*url.URL, error) { if target == nil || (target.Scheme != "http" && target.Scheme != "https") { return nil, errors.New("app: SystemProxy needs an http or https URL") } + if err := ctx.Err(); err != nil { + return nil, err + } if environmentProxyConfigured() { request := &http.Request{URL: target} return http.ProxyFromEnvironment(request) } - proxy, err := nativeSystemProxy(target) + proxy, err := nativeSystemProxy(ctx, target) + if ctx.Err() != nil { + return nil, ctx.Err() + } if errors.Is(err, errSystemProxyUnavailable) { return nil, fmt.Errorf("%w: %v", ErrUnavailable, err) } diff --git a/app/proxy/proxy_test.go b/app/proxy/proxy_test.go index 5d37a1cdf..c1b981afa 100644 --- a/app/proxy/proxy_test.go +++ b/app/proxy/proxy_test.go @@ -1,14 +1,34 @@ package proxy import ( + "context" + "errors" "net/url" "os" "os/exec" "runtime" "strings" "testing" + "time" ) +func TestSystemProxyContextReturnsCancellation(t *testing.T) { + target, err := url.Parse("https://example.com/") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if proxy, err := SystemProxyContext(ctx, target); proxy != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("canceled lookup = %v, %v", proxy, err) + } + ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + if proxy, err := SystemProxyContext(ctx, target); proxy != nil || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expired lookup = %v, %v", proxy, err) + } +} + func TestSystemProxyNeedsAnHTTPURL(t *testing.T) { for _, raw := range []string{"ftp://example.com", "file:///tmp/x", "example.com"} { target, err := url.Parse(raw) diff --git a/app/run_canvas.go b/app/run_canvas.go index b6ad48468..9c77d7200 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -181,39 +181,37 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, Red: normalized.ClearColor.Red, Green: normalized.ClearColor.Green, Blue: normalized.ClearColor.Blue, Alpha: normalized.ClearColor.Alpha, }, - Web: normalized.Web.bind(), - NativeViews: slices.Clone(painter.lastViews), - Rectangles: painter.frame.Rectangles(), - TextLabels: painter.frame.Labels(), - Accessibility: painter.accessibility, - OnResize: resizeHandler, - OnFrameChange: frameChangeHandler(normalized.OnFrameChange), - OnMinimize: minimizeHandler(normalized.OnMinimize), - OnVisibility: gate.handler(), - OnLifecycle: lifecycleHandler(normalized.OnLifecycle), - OnMaximize: maximizeHandler(normalized.OnMaximize), - OnFullscreen: painter.fullscreenHandler(normalized.OnFullscreen), - OnReopen: normalized.onReopen, - OnPointer: pointerHandler, - PressAt: painter.pressAt, - OnKey: keyHandler, - ModifierTaps: normalized.OnModifierTap != nil, - OnShortcut: painter.shortcutHandler(normalized), - CaptureMenuKeys: normalized.CaptureMenuKeys, - OnAccessibility: painter.accessibilityHandler(normalized), - AccessibilityTree: func() []platform.AccessibilityNode { return painter.accessibility }, - OnFocusLost: painter.focusLostHandler(), - OnActivate: normalized.OnActivate, - OnDeactivate: painter.deactivateHandler(), - OnScroll: scrollHandler, - OnFileDrop: dropHandler, - OnRedraw: redrawHandler, - SetFrameInterval: setFrameInterval, - FramePresented: framePresented, - Waker: waker, - OnCloseRequest: closeHandler, - OnClosed: normalized.OnClosed, - DynamicTextInput: normalized.TextInput != nil, + Web: normalized.Web.bind(), + NativeViews: slices.Clone(painter.lastViews), + Rectangles: painter.frame.Rectangles(), + TextLabels: painter.frame.Labels(), + Accessibility: painter.accessibility, + OnResize: resizeHandler, + OnFrameChange: frameChangeHandler(normalized.OnFrameChange), + OnMinimize: minimizeHandler(normalized.OnMinimize), + OnVisibility: gate.handler(), + OnMaximize: maximizeHandler(normalized.OnMaximize), + OnFullscreen: painter.fullscreenHandler(normalized.OnFullscreen), + OnReopen: normalized.onReopen, + OnPointer: pointerHandler, + PressAt: painter.pressAt, + OnKey: keyHandler, + ModifierTaps: normalized.OnModifierTap != nil, + OnShortcut: painter.shortcutHandler(normalized), + CaptureMenuKeys: normalized.CaptureMenuKeys, + OnAccessibility: painter.accessibilityHandler(normalized), + OnFocusLost: painter.focusLostHandler(), + OnActivate: normalized.OnActivate, + OnDeactivate: painter.deactivateHandler(), + OnScroll: scrollHandler, + OnFileDrop: dropHandler, + OnRedraw: redrawHandler, + SetFrameInterval: setFrameInterval, + FramePresented: framePresented, + Waker: waker, + OnCloseRequest: closeHandler, + OnClosed: normalized.OnClosed, + DynamicTextInput: normalized.TextInput != nil, } if normalized.TextInput != nil { config.ReadOnlyTextFocused = func() bool { @@ -268,11 +266,3 @@ func prepareNativeWindow(config Config, canvas *gfx.Canvas) (platform.Config, *p stopWatchingDesktop := watchDesktopSettings(canvas, native.Waker) return native, painter, func() { stopWatchingDesktop(); cleanup() }, nil } - -// lifecycleHandler is the application's OnLifecycle as the platform's, or nil without one. -func lifecycleHandler(handler func(LifecycleEvent)) func(platform.Lifecycle) { - if handler == nil { - return nil - } - return func(event platform.Lifecycle) { handler(LifecycleEvent(event)) } -} diff --git a/app/system.go b/app/system.go index 68b72c2a6..52c287e3d 100644 --- a/app/system.go +++ b/app/system.go @@ -126,10 +126,13 @@ func ClipboardText() (string, error) { // clipboard belongs in the work it schedules. // // Nothing runs until the first call: no timer, no thread. It may be made before -// the first window opens, and watching then starts with the window. One -// registration serves the process and the last wins; OnClipboardChange(nil) +// the first window opens, except with the GTK backend: GTK requires an +// initialized display, so register after opening the first window. XCB listens +// as soon as it registers with XFixes, and stops when RunApplication returns, +// so a registration made before the application runs, or kept across a second +// run, needs to be made again. One registration serves the process and the last wins; OnClipboardChange(nil) // stops watching. An error wrapping ErrUnsupported means this target cannot -// watch the clipboard (the Linux and web targets today): the clipboard keeps +// watch the clipboard (for example, GTK on Wayland and web): the clipboard keeps // working, only the news is missing, and a caller may fall back to reading it // when the user acts. macOS has no change notification, so while a // registration is held it polls the pasteboard's change count on a 250 ms diff --git a/app/system_android.go b/app/system_android.go deleted file mode 100644 index 43daea339..000000000 --- a/app/system_android.go +++ /dev/null @@ -1,60 +0,0 @@ -//go:build android - -package app - -import ( - "os" - - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/platform/android" -) - -// What the system gives an Android application grows here as its backend lands; the -// rest is answered in mobile_unsupported.go. - -func nativeTextEngine() gfx.TextEngine { return android.TextEngine() } - -func nativeClipboardText() (string, error) { - text, ok := android.ClipboardText() - if !ok { - return "", nil - } - return text, nil -} - -func nativeSetClipboardText(text string) error { - if !android.SetClipboardText(text) { - return ErrUnsupported - } - return nil -} - -func nativeOpenURL(url string) error { - if !android.OpenURL(url) { - return ErrUnsupported - } - return nil -} - -func nativePreferredLanguages() []string { - if languages := android.PreferredLanguages(); len(languages) > 0 { - return languages - } - return languagesFromEnvironment(os.Getenv) -} - -func nativeReduceMotion() bool { return android.AnimationsOff() } - -func nativeAppearance() Appearance { - switch android.DarkTheme() { - case 1: - return AppearanceDark - case 0: - return AppearanceLight - } - return AppearanceUnknown -} - -// The host tells the application when the theme changes (Activity.onConfigurationChanged), -// whether or not anyone watches. -func nativeWatchAppearance() {} diff --git a/app/system_ios.go b/app/system_ios.go deleted file mode 100644 index a5279d562..000000000 --- a/app/system_ios.go +++ /dev/null @@ -1,55 +0,0 @@ -//go:build ios - -package app - -import ( - "os" - - "github.com/vivaui/viva/gfx" - darwinplatform "github.com/vivaui/viva/internal/platform/darwin" -) - -// What the system gives an iPhone application grows here as its backend lands; the -// rest is answered in mobile_unsupported.go. - -func nativeTextEngine() gfx.TextEngine { return darwinplatform.SharedTextEngine() } - -func nativeClipboardText() (string, error) { - text, _ := darwinplatform.ClipboardText() - return text, nil -} - -func nativeSetClipboardText(text string) error { - darwinplatform.SetClipboardText(text) - return nil -} - -func nativeOpenURL(url string) error { - if !darwinplatform.OpenURL(url) { - return ErrUnsupported - } - return nil -} - -func nativePreferredLanguages() []string { - if languages := darwinplatform.PreferredLanguages(); len(languages) > 0 { - return languages - } - return languagesFromEnvironment(os.Getenv) -} - -func nativeReduceMotion() bool { return darwinplatform.ReduceMotion() } - -func nativeAppearance() Appearance { - switch darwinplatform.DarkTheme() { - case 1: - return AppearanceDark - case 0: - return AppearanceLight - } - return AppearanceUnknown -} - -// The view controller tells the application when the look changes, whether or not -// anyone watches. -func nativeWatchAppearance() {} diff --git a/app/text_geometry.go b/app/text_geometry.go index 763bb16fd..72f06da6d 100644 --- a/app/text_geometry.go +++ b/app/text_geometry.go @@ -9,9 +9,8 @@ import ( // textGeometry is where the text of the focused field is on the window: the character // boundary nearest a point, the caret at a boundary and the rectangles a range covers. The -// framework draws the text, so it is the one that can say; a phone's text interaction (the -// caret a tap places, the word a long press selects, the handles and the magnifier) is -// built on it. Indexes are runes of the field's value, as in TextState. +// framework draws the text, so it is the one that can say; a finger's text interaction +// (the caret a tap places, the word a long press selects) is built on it. Indexes are runes of the field's value, as in TextState. // // A field that lays its rows out itself answers through its gfx.TextPlacement. Any other // is one line, measured the way the components paint it: from the line's origin in the @@ -73,7 +72,7 @@ func (geometry textGeometry) IndexAt(x, y float32) (int, bool) { // CaretRect is the caret at a boundary, as tall as the line. func (geometry textGeometry) CaretRect(index int) (gfx.Rect, bool) { if geometry.placement != nil { - return geometry.placement.CaretBounds() + return gfx.Rect{}, false // it paints one caret, wherever the caret is } offset := byteOffsetOfRune(geometry.shown, index) x := geometry.origin() + geometry.canvas.TextCaretStyle(geometry.shown, geometry.style, offset) diff --git a/app/touch.go b/app/touch.go index 6fce58577..20fa2e06a 100644 --- a/app/touch.go +++ b/app/touch.go @@ -132,6 +132,12 @@ func (painter *painter) carryTouch(step interaction.TouchStep) (platform.Frame, frame, err = painter.repaintAfterInput() } } + if step.Pinch != interaction.PinchNone { + phase := gfx.PinchPhase(step.Pinch) + if painter.applyPinch(phase, step.PinchX, step.PinchY, step.PinchScale, step.PinchDelta, t.modifiers) && !t.advancing { + frame, err = painter.repaintAfterInput() + } + } if step.Wake && painter.scheduleFrame != nil { painter.scheduleFrame(step.WakeAfter) } diff --git a/app/touch_test.go b/app/touch_test.go index c2f6e28b0..54ba01014 100644 --- a/app/touch_test.go +++ b/app/touch_test.go @@ -234,3 +234,52 @@ func TestAFlingStepDoesNotAllocate(t *testing.T) { t.Fatalf("a fling frame allocated %v times", allocations) } } + +// Two fingers are a pinch the application hears from begin to end, and the first finger's +// press does not click or scroll. +func TestTwoFingersPinchAndNeverPressOrScroll(t *testing.T) { + var events []gfx.PinchEvent + f := newTouchFixture(t) + f.driver.painter.onPinch = func(event gfx.PinchEvent) gfx.EventResult { + events = append(events, event) + return gfx.EventResult{Handled: true} + } + f.must(t, f.driver.TouchDown(1, 100, 300)) + f.must(t, f.driver.TouchDown(2, 200, 300)) + f.must(t, f.driver.TouchMove(2, 300, 300)) + f.must(t, f.driver.TouchMove(1, 50, 300)) + f.must(t, f.driver.TouchUp(2, 300, 300)) + f.must(t, f.driver.TouchUp(1, 50, 300)) + if len(events) != 4 || events[0].Phase != gfx.PinchBegin || events[len(events)-1].Phase != gfx.PinchEnd { + t.Fatalf("events = %+v, want begin, two changes and end", events) + } + last := events[len(events)-2] + if last.Scale < 2.4 || last.Scale > 2.6 || last.X != 175 { + t.Fatalf("the last change = %+v, want scale 2.5 about x 175", last) + } + if f.clicks != 0 || f.presses != 0 || f.scrolls != 0 { + t.Fatalf("a pinch clicked %d, pressed %d and scrolled %d times", f.clicks, f.presses, f.scrolls) + } +} + +// A page that does not listen to pinches is not bothered by them. +func TestAPinchNobodyListensToDoesNothing(t *testing.T) { + f := newTouchFixture(t) + f.must(t, f.driver.TouchDown(1, 100, 300)) + f.must(t, f.driver.TouchDown(2, 200, 300)) + f.must(t, f.driver.TouchMove(2, 300, 300)) + f.must(t, f.driver.TouchUp(2, 300, 300)) + f.must(t, f.driver.TouchUp(1, 100, 300)) +} + +// The public pinch phases are the state machine's, converted by number. +func TestPinchPhasesConvertByNumber(t *testing.T) { + for _, c := range []struct { + inner interaction.PinchPhase + public gfx.PinchPhase + }{{interaction.PinchBegin, gfx.PinchBegin}, {interaction.PinchChange, gfx.PinchChange}, {interaction.PinchEnd, gfx.PinchEnd}} { + if gfx.PinchPhase(c.inner) != c.public { + t.Fatalf("phase %d converts to %d, want %d", c.inner, gfx.PinchPhase(c.inner), c.public) + } + } +} diff --git a/base/attrcheck_dev.go b/base/attrcheck_dev.go index 7c2fb8df4..f7bee8810 100644 --- a/base/attrcheck_dev.go +++ b/base/attrcheck_dev.go @@ -190,6 +190,16 @@ func (f *Frame) checkTextAttributes(n *Node, name string, mono, face, line, alig if !mono && n.Flags&flagMono != 0 { f.badAttribute(n, name, "Mono", "Mono styles a Text or a single-line text field; this element paints no monospace text") } + // A text field shapes its own value in the painter that reads Mono; no element + // that reaches this check reads Italic, so setting it is reported, not ignored. + if n.TextDecor&textItalic != 0 { + f.badAttribute(n, name, "Italic", "Italic styles a Text; this element shapes no italic text") + } + // Strike is drawn by the Text painter, so an element that paints no text of its + // own never draws it: report it rather than drop it. + if n.TextDecor&textStrike != 0 { + f.badAttribute(n, name, "Strike", "Strike styles a Text; this element draws no struck-through text") + } if !face && n.Face != 0 { f.badAttribute(n, name, "MonoFace", "MonoFace styles a Text or a single-line text field; this element paints no monospace text") } diff --git a/base/attrcheck_italic_dev_test.go b/base/attrcheck_italic_dev_test.go new file mode 100644 index 000000000..6366cd805 --- /dev/null +++ b/base/attrcheck_italic_dev_test.go @@ -0,0 +1,26 @@ +//go:build dev || vivadev + +package base + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// Italic is the Text's own type. An element that shapes no italic text reports it +// in the dev build instead of dropping it, as it reports Mono on an element that +// paints no monospace text. +func TestItalicOnAnElementThatShapesNoTextIsReported(t *testing.T) { + drawBase(func(f *Frame) { + f.Column().Children(func() { + f.Text("emphasis").Italic() + }) + }) + expectAttributePanic(t, func(f *Frame) { + f.Column().Italic() + }, "Column", "Italic") + expectAttributePanic(t, func(f *Frame) { + f.Button(gfx.Item(9), "Save").Italic() + }, "Button", "Italic") +} diff --git a/base/attrcheck_strike_dev_test.go b/base/attrcheck_strike_dev_test.go new file mode 100644 index 000000000..5ee1a1439 --- /dev/null +++ b/base/attrcheck_strike_dev_test.go @@ -0,0 +1,25 @@ +//go:build dev || vivadev + +package base + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// Strike is the Text's own type, as Italic and Mono are. An element that draws no +// struck text of its own reports it in the dev build instead of dropping it. +func TestStrikeOnAnElementThatDrawsNoTextIsReported(t *testing.T) { + drawBase(func(f *Frame) { + f.Column().Children(func() { + f.Text("paid").Strike() + }) + }) + expectAttributePanic(t, func(f *Frame) { + f.Column().Strike() + }, "Column", "Strike") + expectAttributePanic(t, func(f *Frame) { + f.Button(gfx.Item(9), "Save").Strike() + }, "Button", "Strike") +} diff --git a/base/box.go b/base/box.go index faeea0961..5e9c7cb29 100644 --- a/base/box.go +++ b/base/box.go @@ -94,10 +94,9 @@ func (b Box) Hit(ID gfx.ID, Label string) Box { return b } -// MovesWindow makes the element's rectangle a place a custom-titlebar window is -// moved from: pressing and dragging it moves the window, and a double click zooms -// it (see gfx.Canvas.MoveRegion). Controls declared inside the element take their -// own presses. Declare it on the row that is the window's top bar. +// MovesWindow makes the element a drag region of a custom-titlebar or +// notification window. Double-clicking zooms a custom-titlebar window. +// Controls inside the element take their own presses (see gfx.Canvas.MoveRegion). func (b Box) MovesWindow() Box { b.N() b.f.Extra(b.i).moves = true @@ -351,9 +350,9 @@ func (b Box) Shadow(level gfx.ShadowLevel) Box { // Clip keeps what is drawn inside the element to its rectangle. func (b Box) Clip() Box { b.N().Flags |= flagClip; return b } -// Text: FontSize, Bold, Weight, Color, Muted and Mono style a Text; TextCenter -// centers it in its rectangle. On a control, FontSize is the size of its text in -// place of the theme's body size. +// Text: FontSize, Bold, Weight, Italic, Strike, Color, Muted and Mono style a +// Text; TextCenter centers it in its rectangle. On a control, FontSize is the +// size of its text in place of the theme's body size. func (b Box) FontSize(v float32) Box { n := b.N() n.FontSize, n.FontSet = v, v > 0 @@ -384,6 +383,22 @@ func (b Box) Muted() Box { } func (b Box) Mono() Box { b.N().Flags |= flagMono; return b } +// Italic draws a Text in the italic face of its font: the face +// gfx.StyledTextEngine shapes for a gfx.TextStyle whose Italic is set, which the +// width its lines are laid out by is measured in too (Canvas.TextWidthStyle). A +// text is never slanted by a synthetic transform, so a font whose family has no +// italic face and whose engine shapes none stays upright rather than sheared. +func (b Box) Italic() Box { b.N().TextDecor |= textItalic; return b } + +// Strike draws a Text with a line through it: one pixel, in the text's color, +// across the middle of each line's box, from the first glyph to the last. It is +// the line components.MarkdownView has drawn for ~~struck~~ text since it learned +// inline styles: a Text keeps its own width and wrapping, so nothing about the +// layout moves when a text is struck. A strike covers the text, not the box the +// text was laid out in, so a Text stretched by its container is struck across its +// glyphs only. +func (b Box) Strike() Box { b.N().TextDecor |= textStrike; return b } + // IconTransform draws the icon scaled, turned and moved from the box it was laid // out in, without moving the layout or the hit region: a row keeps its size and // its target while the glyph moves inside it. Components use it to play the diff --git a/base/elements.go b/base/elements.go index 756aff57a..12e335f63 100644 --- a/base/elements.go +++ b/base/elements.go @@ -14,21 +14,6 @@ func Row(c C) Box { return c.page.container(c.f.Row()) } func Column(c C) Box { return c.page.container(c.f.Column()) } func Stack(c C) Box { return c.page.container(c.f.Stack()) } -// SafeArea is a column that fills its container and keeps what it holds inside what the -// system draws over the window's edges: the status bar and the sensor housing, the home -// indicator or navigation bar, a cutout. A phone's window runs under them, so the page's -// background reaches the screen's edges while its content stays readable and tappable. It is -// padded by the window's SafeArea as the last layout left it, and not at all on a desktop -// window. Put it once at the root of a page; the padding is its own, so give the content -// inside it a column of its own for any other. -func SafeArea(c C) Box { - var inset gfx.Insets - if c.f.Surface != nil { - inset = c.f.Surface.SafeArea() - } - return Column(c).Fill().PadSides(inset.Top, inset.Right, inset.Bottom, inset.Left) -} - // Scroll is a scroll area whose offset is kept by the area's own name. func Scroll(c C) Box { p := c.page diff --git a/base/flags.go b/base/flags.go index 7dec72925..7476d5c48 100644 --- a/base/flags.go +++ b/base/flags.go @@ -35,6 +35,16 @@ const ( FlagInvalid // a control whose value failed validation: the destructive border and ring ) +// A Text's own faces, beyond its size, weight and color: the italic face of its +// font and the line struck through it. They are not bits of the element state word +// — its 32 are all taken, the last of them by the required marker below — and a +// face describes the text rather than the element, so they have a byte of their own +// (Node.TextDecor). +const ( + textItalic uint8 = 1 << iota // Italic: the face gfx.StyledTextEngine shapes + textStrike // Strike: one line through the middle of each line +) + // flagRequired marks a page Label that appends the field title's required // marker. It is internal: only the page Label reads it. const flagRequired uint32 = 1 << 31 diff --git a/base/frame.go b/base/frame.go index 96681f28b..2aa636fb2 100644 --- a/base/frame.go +++ b/base/frame.go @@ -151,9 +151,13 @@ type Node struct { // styling, including the valid zero value of regular weight. FontSet, WeightSet bool Frozen bool - Rect Rect - Band uint16 // the compositing band the subtree paints on (Overlay); zero is the page's - FocusScope gfx.ID // the focus scope the subtree paints in, when it is not the page's + // TextDecor is the faces a Text is drawn in. It sits in the padding after + // Frozen so that Node keeps its size; a byte at the end of the struct would + // have grown every Node by eight. + TextDecor uint8 + Rect Rect + Band uint16 // the compositing band the subtree paints on (Overlay); zero is the page's + FocusScope gfx.ID // the focus scope the subtree paints in, when it is not the page's } // placement says where a Popup goes. diff --git a/base/layout.go b/base/layout.go index 379e9d018..c72dabee5 100644 --- a/base/layout.go +++ b/base/layout.go @@ -143,6 +143,10 @@ func (f *Frame) measureLeafIn(n *Node) { // mark none, as the canvas measures and draws it. _, ch := f.Surface.MonoCellSize(n.FontSize, n.Face) n.Pref = [2]float32{f.Surface.TextWidthStyle(n.Text, n.textStyle()), ch} + } else if n.TextDecor&textItalic != 0 { + // An Italic text is as wide as the italic face the canvas draws it in, so the + // box it is given and the glyphs in it agree. + n.Pref = [2]float32{f.Surface.TextWidthStyle(n.Text, n.textStyle()), n.leading()} } else { n.Pref = [2]float32{f.Surface.TextWidthWeight(n.Text, n.FontSize, n.Weight), n.leading()} } diff --git a/base/paint.go b/base/paint.go index 0f11fb72b..a11b6a9e8 100644 --- a/base/paint.go +++ b/base/paint.go @@ -339,7 +339,10 @@ func (f *Frame) paintText(n *Node) { left, right := n.Inset(AxisX) top, bottom := n.Inset(AxisY) r := Rect{X: n.Rect.X + left, Y: n.Rect.Y + top, Width: max(n.Rect.Width-left-right, 0), Height: max(n.Rect.Height-top-bottom, 0)} - style := gfx.TextStyle{Size: n.FontSize, Weight: n.Weight, Color: n.Color, Mono: n.Flags&flagMono != 0, MonoFace: n.Face, Direction: n.TextDirection} + style := gfx.TextStyle{ + Size: n.FontSize, Weight: n.Weight, Color: n.Color, Italic: n.TextDecor&textItalic != 0, + Mono: n.Flags&flagMono != 0, MonoFace: n.Face, Direction: n.TextDirection, + } alignment := gfx.AlignStart switch { case n.Flags&flagTextCenter != 0: @@ -356,7 +359,11 @@ func (f *Frame) paintText(n *Node) { lh := n.leading() for k := int32(0); k < n.LineCount; k++ { bounds := Rect{X: r.X, Y: r.Y + float32(k)*lh, Width: r.Width, Height: lh} - f.paintLabel(n, f.Lines[n.LineFirst+k], bounds, style, alignment) + line := f.Lines[n.LineFirst+k] + f.paintLabel(n, line, bounds, style, alignment) + if n.TextDecor&textStrike != 0 { + f.paintStrike(line, bounds, style, alignment) + } } return } @@ -367,6 +374,9 @@ func (f *Frame) paintText(n *Node) { f.Surface.Clip(r) } f.paintLabel(n, n.Text, bounds, style, alignment) + if n.TextDecor&textStrike != 0 { + f.paintStrike(n.Text, bounds, style, alignment) + } if clipped { f.Surface.Unclip() } @@ -379,3 +389,18 @@ func (f *Frame) paintLabel(n *Node, value string, bounds Rect, style gfx.TextSty } f.Surface.LabelAligned(value, bounds, style, alignment) } + +// paintStrike draws the line a struck-through Text crosses: the one +// components.MarkdownView has drawn for ~~struck~~ text, one pixel high, in the +// text's color, across the middle of the line box. It runs from the left end the +// line is drawn at (Canvas.LabelOrigin, so a centered or right-aligned text is +// struck where its glyphs are) for the width the line is measured at +// (Canvas.TextWidthStyle, so a Mono line is struck across its cells), which is the +// text and not the box the text was given. +func (f *Frame) paintStrike(value string, bounds Rect, style gfx.TextStyle, alignment gfx.Alignment) { + if value == "" { + return + } + x := f.Surface.LabelOrigin(value, bounds, style, alignment) + f.Surface.Fill(Rect{X: x, Y: bounds.Y + bounds.Height/2, Width: f.Surface.TextWidthStyle(value, style), Height: 1}, style.Color) +} diff --git a/base/scroll.go b/base/scroll.go index 6ea13bc49..357fb7e5e 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -504,7 +504,7 @@ func (f *Frame) wheelArea(panel int32, event gfx.ScrollEvent) (result gfx.EventR break } n := &f.Nodes[i] - if n.Ext == 0 || f.Exts[n.Ext].scrollState == nil || f.Exts[n.Ext].scrollManual { + if n.Ext == 0 || f.Exts[n.Ext].scrollState == nil || f.Exts[n.Ext].scrollManual || !f.within(int32(i), panel) { continue } if !f.within(int32(i), panel) { diff --git a/base/text_decor_baseline_test.go b/base/text_decor_baseline_test.go new file mode 100644 index 000000000..72a5f9e66 --- /dev/null +++ b/base/text_decor_baseline_test.go @@ -0,0 +1,89 @@ +package base + +import ( + "fmt" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// plainPageProse is long enough that the paragraph in the reference page breaks. +const plainPageProse = "a paragraph of plain text that its container does not stretch, so it asks for its widest line" + +// plainPage draws a page of Texts and nothing of its own that Italic or Strike +// touches, and returns every primitive it painted. It is the page the guide's +// text attributes describe: sizes, weights, colors, alignment, Mono, LineHeight, +// wrapping, right-to-left text, background, border and radius. +func plainPage(canvas *gfx.Canvas) string { + var view View + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 500}) + f.Column().Pad(8).Gap(4).Background(gfx.Color{Blue: 0.1, Alpha: 1}).Radius(4).Border(1, gfx.Color{Alpha: 0.25}).Children(func() { + f.Text("plain text").FontSize(12) + f.Text("weighted").FontSize(14).Weight(gfx.WeightSemibold) + f.Text("muted").FontSize(12).Muted() + f.Text("centered").FontSize(12).TextCenter() + f.Text("ended").FontSize(12).TextEnd() + f.Text("mono").FontSize(12).Mono() + f.Text("tall").FontSize(12).LineHeight(30) + f.Wrap(plainPageProse).FontSize(12).MaxLines(3) + f.Text("שלום עולם").FontSize(12) + f.Row().Border(1, gfx.Color{Alpha: 0.5}).Children(func() { + f.Text("in a row").FontSize(12) + f.Text("stretched").FontSize(12).Grow(1) + }) + }) + f.End() + return dumpPrimitives(canvas) +} + +// dumpPrimitives writes every primitive a paint pass left on the canvas, in paint +// order. The primitives are what a renderer rasterizes, so two frames whose +// primitives are equal are two frames that are the same pixels. +func dumpPrimitives(canvas *gfx.Canvas) string { + var out strings.Builder + for _, rectangle := range canvas.Rectangles() { + fmt.Fprintf(&out, "rect %+v\n", rectangle) + } + for _, text := range canvas.Texts() { + fmt.Fprintf(&out, "text %+v\n", text) + } + for _, triangle := range canvas.Triangles() { + fmt.Fprintf(&out, "triangle %+v\n", triangle) + } + for _, shadow := range canvas.Shadows() { + fmt.Fprintf(&out, "shadow %+v\n", shadow) + } + fmt.Fprintf(&out, "images %d\n", len(canvas.Images())) + return out.String() +} + +// A page that sets neither Italic nor Strike paints no italic run and no strike +// fill. That is the invariant this change must keep, and it holds whatever else +// moves in the layout or in gfx.Text: a page that never asks for a face cannot +// get one. +// +// An earlier version of this test pinned a dump of every primitive; it failed on +// any unrelated layout change, so it now asserts the property instead. +func TestAPageWithoutItalicOrStrikePaintsNeitherFace(t *testing.T) { + canvas := runeCanvas() + plainPage(canvas) + + texts := canvas.Texts() + if len(texts) == 0 { + t.Fatal("the reference page painted no text") + } + for _, text := range texts { + if text.Style.Italic { + t.Fatalf("a page that sets no Italic painted an italic run: %q", text.Value) + } + } + + // Strike is a one-pixel fill through the middle of each line. The reference + // page draws no rule of its own, so any one-pixel rectangle is a strike. + for _, rectangle := range canvas.Rectangles() { + if rectangle.Bounds.Height == 1 { + t.Fatalf("a page that sets no Strike painted a strike fill: %+v", rectangle.Bounds) + } + } +} diff --git a/base/text_italic_test.go b/base/text_italic_test.go new file mode 100644 index 000000000..b866ee74d --- /dev/null +++ b/base/text_italic_test.go @@ -0,0 +1,199 @@ +package base + +import ( + "testing" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" +) + +// italicProse is long enough to break at the widths these tests give it. +const italicProse = "the emphasis in this paragraph is drawn in the italic face" + +// paintedText is one line the page painted: its value and its slant. +type paintedText struct { + value string + italic bool +} + +// paintedTexts is every label the page painted, in paint order. +func paintedTexts(canvas *gfx.Canvas) []paintedText { + texts := canvas.Texts() + out := make([]paintedText, 0, len(texts)) + for _, painted := range texts { + out = append(out, paintedText{value: painted.Value, italic: painted.Style.Italic}) + } + return out +} + +// Italic draws a Text in the italic face of its font and leaves every other Text +// upright: it is the element's own type, like Mono, so it travels to the label the +// canvas draws and no farther. +func TestItalicTextIsPaintedInTheItalicFace(t *testing.T) { + var view View + canvas := testCanvas() + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 200}) + f.Column().Children(func() { + f.Text("upright").FontSize(10) + f.Text("slanted").FontSize(10).Italic() + }) + f.End() + painted := paintedTexts(canvas) + if len(painted) != 2 { + t.Fatalf("painted %d labels, want the two Texts: %+v", len(painted), painted) + } + if painted[0].value != "upright" || painted[0].italic { + t.Fatalf("first label = %+v, want the upright Text drawn upright", painted[0]) + } + if painted[1].value != "slanted" || !painted[1].italic { + t.Fatalf("second label = %+v, want the Italic Text drawn in the italic face", painted[1]) + } +} + +// Every line of a wrapped Italic paragraph is drawn in the italic face: the lines +// are measured and painted through one style, so a slant on the paragraph cannot +// reach some of them and not the rest. +func TestEveryWrappedLineOfAnItalicTextIsItalic(t *testing.T) { + var view View + canvas := runeCanvas() + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 100, Height: 400}) + f.Column().Children(func() { + f.Wrap(italicProse).FontSize(10).Italic() + }) + f.End() + painted := paintedTexts(canvas) + if len(painted) < 2 { + t.Fatalf("painted %d labels, want the paragraph broken into lines: %+v", len(painted), painted) + } + for index, line := range painted { + if !line.italic { + t.Fatalf("line %d %q is upright; every line of an Italic paragraph is drawn in the italic face", index, line.value) + } + } +} + +// italicWiderEngine measures a line at its upright width and twice that in the +// italic face, so a line wrapped in one face and drawn in the other does not fit +// the box, and the lines of a paragraph say which face they were measured in. +type italicWiderEngine struct{} + +func (engine *italicWiderEngine) lineWidth(value string, size float32) float32 { + return float32(utf8.RuneCountInString(value)) * size +} + +func (engine *italicWiderEngine) Width(value string, size, weight float32) float32 { + return engine.lineWidth(value, size) +} + +func (engine *italicWiderEngine) Caret(value string, size, weight float32, offset int) float32 { + return float32(offset) * size +} + +func (engine *italicWiderEngine) Selection(dst []gfx.TextSpan, value string, size, weight float32, start, end int) []gfx.TextSpan { + return append(dst, gfx.TextSpan{X: float32(start) * size, Width: float32(end-start) * size}) +} + +func (engine *italicWiderEngine) OffsetAt(value string, size, weight, x float32) int { + return min(max(int(x/size+0.5), 0), len(value)) +} + +func (engine *italicWiderEngine) WidthStyle(value string, size, weight float32, italic bool) float32 { + if italic { + return 2 * engine.lineWidth(value, size) + } + return engine.lineWidth(value, size) +} + +func (engine *italicWiderEngine) CaretStyle(value string, size, weight float32, italic bool, offset int) float32 { + return engine.Caret(value, size, weight, offset) +} + +func (engine *italicWiderEngine) SelectionStyle(dst []gfx.TextSpan, value string, size, weight float32, italic bool, start, end int) []gfx.TextSpan { + return engine.Selection(dst, value, size, weight, start, end) +} + +func (engine *italicWiderEngine) OffsetAtStyle(value string, size, weight float32, italic bool, x float32) int { + return engine.OffsetAt(value, size, weight, x) +} + +// A wrapped Italic paragraph is wrapped at the widths of the italic face, and the +// lines it is given are drawn in that face: a Text that became italic on the next +// frame is wrapped again, not drawn in the upright lines it was measured in. The +// italic face here is twice as wide, so lines of the wrong face overflow the box. +func TestAWrappedItalicTextIsWrappedAndDrawnInTheItalicFace(t *testing.T) { + const width, size = 200, 10 // 20 characters of the upright face, 10 of the italic one + var view View + declare := func(italic bool) (*gfx.Canvas, []paintedText) { + canvas := &gfx.Canvas{} + canvas.SetTree(&tree) + canvas.SetTextEngine(&italicWiderEngine{}) + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: width, Height: 800}) + f.Column().Children(func() { + text := f.Wrap(italicProse).FontSize(size) + if italic { + text.Italic() + } + }) + f.End() + return canvas, paintedTexts(canvas) + } + _, upright := declare(false) + canvas, slanted := declare(true) + if len(slanted) <= len(upright) { + t.Fatalf("%d italic lines and %d upright ones: the paragraph was wrapped as if it were upright", len(slanted), len(upright)) + } + italic := gfx.TextStyle{Size: size, Italic: true} + for index, line := range slanted { + if !line.italic { + t.Fatalf("line %d %q is drawn upright; an Italic paragraph is drawn in the italic face", index, line.value) + } + if got := canvas.TextWidthStyle(line.value, italic); got > width { + t.Fatalf("line %d %q is %v wide in the italic face, wider than the %v box: it was wrapped in the upright face", index, line.value, got, width) + } + } +} + +// A single-line Italic Text takes the width the italic face measures it at, so the +// box it is given holds its glyphs: here the italic face is twice as wide, so an +// upright measurement would leave it half the room it needs. +func TestAnItalicTextTakesTheWidthOfItsItalicFace(t *testing.T) { + var view View + canvas := &gfx.Canvas{} + canvas.SetTree(&tree) + canvas.SetTextEngine(&italicWiderEngine{}) + var box Box + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 100}) + f.Row().Children(func() { + box = f.Text("ab").FontSize(10).Italic() + }) + f.End() + if got, want := box.Rect().Width, float32(40); got != want { + t.Fatalf("Italic Text is %v wide, want %v: twice the upright width of %q in the italic face", got, want, "ab") + } + painted := paintedTexts(canvas) + if len(painted) != 1 || painted[0].value != "ab" || !painted[0].italic { + t.Fatalf("painted %+v, want the one label of the Italic Text", painted) + } +} + +// An Italic Text is not a required field Label and a required Label is not +// italic: the required marker a form field's title appends and the face a Text is +// drawn in are two different properties. The state word's bits were all taken when +// Italic arrived, and 1<<31 is the required marker, so taking that bit for the +// slant made every Italic Label of a page report itself required (and every +// required Label italic). +func TestAnItalicTextIsNotARequiredLabel(t *testing.T) { + var view View + var box Box + f := view.Begin(testCanvas(), gfx.LightTheme(), gfx.Rect{Width: 400, Height: 100}) + f.Column().Children(func() { + box = f.Text("emphasis").Italic() + }) + f.End() + if box.N().Flags&flagRequired != 0 { + t.Fatal("an Italic Text carries the required marker's bit: Italic must not share a bit with a property it has nothing to do with") + } + if box.N().TextDecor&textItalic == 0 { + t.Fatal("the Text is not marked italic at all") + } +} diff --git a/base/text_strike_test.go b/base/text_strike_test.go new file mode 100644 index 000000000..1e05fcf2b --- /dev/null +++ b/base/text_strike_test.go @@ -0,0 +1,222 @@ +package base + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// strikeProse is long enough to break into several lines at the widths these +// tests give it. +const strikeProse = "the price of every item in this list was struck through before the sale began" + +// strikeInk is the color these tests give the struck texts, so the one fill a +// Strike paints can be told from anything else on the page. +var strikeInk = gfx.Color{Red: 1, Alpha: 1} + +// strikeFills are the lines a page painted: one per Strike, since a page of bare +// Texts paints no other rectangle. +func strikeFills(canvas *gfx.Canvas) []gfx.Rectangle { + return canvas.Rectangles() +} + +// labelNamed returns the label of the text value, or fails. +func labelNamed(t *testing.T, canvas *gfx.Canvas, value string) gfx.Text { + t.Helper() + for _, painted := range canvas.Texts() { + if painted.Value == value { + return painted + } + } + t.Fatalf("%q was not painted; the page painted %+v", value, canvas.Texts()) + return gfx.Text{} +} + +// The line a Strike draws: one pixel high, in the text's own color, across the +// middle of the line box the label was given, from the first glyph to the last. +// That is the line components.MarkdownView draws for struck text, and it is the +// text that is struck: the box the Text was laid out in is four hundred pixels +// wide, the strike is as wide as the word. +func TestStrikeDrawsOnePixelThroughTheMiddleOfTheText(t *testing.T) { + const size = 10 // the rune measurer makes every character ten pixels wide + var view View + canvas := runeCanvas() + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 200}) + f.Column().Children(func() { + f.Text("struck").FontSize(size).Color(strikeInk).Strike() + f.Text("plain").FontSize(size) + }) + f.End() + fills := strikeFills(canvas) + if len(fills) != 1 { + t.Fatalf("painted %d rectangles, want the one strike: %+v", len(fills), fills) + } + struck := labelNamed(t, canvas, "struck") + plain := labelNamed(t, canvas, "plain") + if struck.Style.Italic || plain.Style.Italic { + t.Fatalf("a page without Italic painted italics: %+v %+v", struck.Style, plain.Style) + } + if plain.Bounds.Y <= struck.Bounds.Y { + t.Fatalf("the two Texts are not stacked: %+v then %+v", struck.Bounds, plain.Bounds) + } + line := fills[0] + if line.Color != strikeInk { + t.Errorf("strike color = %v, want the text's color %v", line.Color, strikeInk) + } + if line.Bounds.Height != 1 { + t.Errorf("strike height = %v, want one pixel", line.Bounds.Height) + } + if want := struck.Bounds.Y + struck.Bounds.Height/2; line.Bounds.Y != want { + t.Errorf("strike top = %v, want %v: the middle of the line box %+v", line.Bounds.Y, want, struck.Bounds) + } + if line.Bounds.Y <= struck.Bounds.Y || line.Bounds.Y >= struck.Bounds.Y+struck.Bounds.Height { + t.Errorf("strike %+v is not inside the line box %+v: it would miss the glyphs", line.Bounds, struck.Bounds) + } + if line.Bounds.X != struck.Bounds.X { + t.Errorf("strike starts at %v, want the left end of the line %v", line.Bounds.X, struck.Bounds.X) + } + if want := canvas.TextWidthStyle("struck", struck.Style); line.Bounds.Width != want { + t.Errorf("strike width = %v, want the width of the word %v, not the %v box it was laid out in", line.Bounds.Width, want, struck.Bounds.Width) + } +} + +// A strike follows the text, not the box: a centered or end-aligned Text is +// struck where its glyphs are, so the line starts at the label's own left end. +func TestStrikeFollowsACenteredAndAnEndAlignedText(t *testing.T) { + const size = 10 + var view View + canvas := runeCanvas() + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 200}) + f.Column().Children(func() { + f.Text("mid").FontSize(size).Color(strikeInk).TextCenter().Strike() + f.Text("end").FontSize(size).Color(strikeInk).TextEnd().Strike() + }) + f.End() + fills := strikeFills(canvas) + if len(fills) != 2 { + t.Fatalf("painted %d rectangles, want one strike per Text: %+v", len(fills), fills) + } + for index, value := range []string{"mid", "end"} { + label := labelNamed(t, canvas, value) + line := fills[index] + if line.Bounds.X != label.Bounds.X { + t.Errorf("%q strike starts at %v, want %v: the left end of the drawn line", value, line.Bounds.X, label.Bounds.X) + } + if want := canvas.TextWidthStyle(value, label.Style); line.Bounds.Width != want { + t.Errorf("%q strike width = %v, want %v", value, line.Bounds.Width, want) + } + if label.Bounds.X == 0 { + t.Errorf("%q label was not moved off the left edge, so the test cannot tell the strike from a box-wide one", value) + } + } +} + +// Every line of a wrapped struck paragraph crosses its own line box, at its own +// width: the lines are painted one by one, so a strike cannot be one long line +// across the paragraph. +func TestEveryLineOfAStruckParagraphIsStruck(t *testing.T) { + const size, width = 10, 400 // forty characters to a line + var view View + canvas := runeCanvas() + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: width, Height: 600}) + f.Column().Children(func() { + f.Wrap(strikeProse).FontSize(size).Color(strikeInk).Strike() + }) + f.End() + lines := canvas.Texts() + fills := strikeFills(canvas) + if len(lines) < 2 { + t.Fatalf("painted %d lines, want the paragraph broken up: %+v", len(lines), lines) + } + if len(fills) != len(lines) { + t.Fatalf("painted %d strikes for %d lines, want one each", len(fills), len(lines)) + } + previous := float32(-1) + for index, line := range lines { + strike := fills[index] + if strike.Bounds.Height != 1 { + t.Errorf("line %d strike height = %v, want one pixel", index, strike.Bounds.Height) + } + if want := line.Bounds.Y + line.Bounds.Height/2; strike.Bounds.Y != want { + t.Errorf("line %d strike top = %v, want %v (line box %+v)", index, strike.Bounds.Y, want, line.Bounds) + } + if strike.Bounds.Y <= previous { + t.Errorf("line %d strike at %v is not below the previous one at %v", index, strike.Bounds.Y, previous) + } + previous = strike.Bounds.Y + if strike.Bounds.X != line.Bounds.X { + t.Errorf("line %d strike starts at %v, want %v", index, strike.Bounds.X, line.Bounds.X) + } + if want := canvas.TextWidthStyle(line.Value, line.Style); strike.Bounds.Width != want { + t.Errorf("line %d %q strike width = %v, want %v", index, line.Value, strike.Bounds.Width, want) + } + if strike.Bounds.Width > width { + t.Errorf("line %d %q strike is %v wide, wider than the %v box", index, line.Value, strike.Bounds.Width, width) + } + } +} + +// A Mono text is struck across its cells, as it is laid out on them. +func TestStrikeOfAMonoTextSpansItsCells(t *testing.T) { + const size = 10 + var view View + canvas := runeCanvas() + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 100}) + f.Column().Children(func() { + f.Text("mm").FontSize(size).Mono().Color(strikeInk).Strike() + }) + f.End() + fills := strikeFills(canvas) + if len(fills) != 1 { + t.Fatalf("painted %d rectangles, want the one strike: %+v", len(fills), fills) + } + label := labelNamed(t, canvas, "mm") + columns := canvas.TextWidthStyle("mm", label.Style) + if fills[0].Bounds.X != label.Bounds.X || fills[0].Bounds.Width != columns { + t.Errorf("strike %+v, want the cells %v..%v", fills[0].Bounds, label.Bounds.X, label.Bounds.X+columns) + } +} + +// A Strike changes no layout: a struck Text is measured, broken into the same lines +// and given the same box as the same Text without one. The face is read by the +// painter alone, never by the measurement, so a Text is as wide and as tall struck +// as upright. +func TestAStrikeChangesNoLayout(t *testing.T) { + const width, size = 400, 10 + draw := func(struck bool) (Box, Box, []string) { + var view View + canvas := runeCanvas() + var single, paragraph Box + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: width, Height: 400}) + f.Column().Children(func() { + f.Row().Children(func() { + single = f.Text("struck").FontSize(size) + if struck { + single = single.Strike() + } + }) + paragraph = f.Wrap(strikeProse).FontSize(size).Width(220) + if struck { + paragraph = paragraph.Strike() + } + }) + f.End() + var lines []string + for _, painted := range canvas.Texts() { + lines = append(lines, painted.Value) + } + return single, paragraph, lines + } + uprightText, uprightParagraph, uprightLines := draw(false) + struckText, struckParagraph, struckLines := draw(true) + if uprightText.Rect() != struckText.Rect() { + t.Errorf("a struck Text is %+v, want the upright one's %+v: a strike must not be measured", struckText.Rect(), uprightText.Rect()) + } + if uprightParagraph.Rect() != struckParagraph.Rect() { + t.Errorf("a struck paragraph is %+v, want the upright one's %+v", struckParagraph.Rect(), uprightParagraph.Rect()) + } + if strings.Join(uprightLines, "|") != strings.Join(struckLines, "|") { + t.Errorf("struck lines %q, want the upright lines %q", struckLines, uprightLines) + } +} diff --git a/base/text_wrap.go b/base/text_wrap.go index bcbd2b9fa..2637dd3a6 100644 --- a/base/text_wrap.go +++ b/base/text_wrap.go @@ -15,6 +15,7 @@ type wrapCache struct { Size float32 Weight float32 mono bool + italic bool Face gfx.MonoFace width float32 MaxLines int @@ -25,9 +26,10 @@ type wrapCache struct { // wrapText appends the lines of a wrapped Text, breaking them as gfx.Canvas.WrapLines // does (spaces, East Asian text with its line-start and line-end rules, separators // inside a long path or URL, and as a last resort between whole characters), each -// line measured as it is drawn: a Mono text on its cells. Both -// the full line set and the ellipsized last line are kept for the life of the view, -// so a page that does not change does no wrapping or string building. +// line measured as it is drawn: a Mono text on its cells, an Italic one in the +// italic face. Both the full line set and the ellipsized last line are kept for the +// life of the view, so a page that does not change does no wrapping or string +// building. func (f *Frame) wrapText(dst []string, n *Node) []string { if f.wrapCursor == len(f.Ellipses) { f.Ellipses = append(f.Ellipses, gfx.EllipsisCache{}) @@ -41,25 +43,29 @@ func (f *Frame) wrapText(dst []string, n *Node) []string { width := max(n.Rect.Width-n.PadX(), 1) maxLines := int(n.MaxLines) mono := n.Flags&flagMono != 0 + italic := n.TextDecor&textItalic != 0 face := gfx.MonoFace(0) if mono { face = n.Face } - if wrapped.filled && wrapped.Text == n.Text && wrapped.Size == n.FontSize && wrapped.Weight == n.Weight && wrapped.mono == mono && wrapped.Face == face && wrapped.width == width && wrapped.MaxLines == maxLines { + if wrapped.filled && wrapped.Text == n.Text && wrapped.Size == n.FontSize && wrapped.Weight == n.Weight && + wrapped.mono == mono && wrapped.italic == italic && wrapped.Face == face && + wrapped.width == width && wrapped.MaxLines == maxLines { return append(dst, wrapped.Lines...) } start := len(dst) dst = f.Surface.WrapLinesStyle(dst, n.Text, n.textStyle(), width, maxLines, cache) - wrapped.Text, wrapped.Size, wrapped.Weight, wrapped.mono, wrapped.Face, wrapped.width, wrapped.MaxLines = n.Text, n.FontSize, n.Weight, mono, face, width, maxLines + wrapped.Text, wrapped.Size, wrapped.Weight, wrapped.mono, wrapped.italic, wrapped.Face = n.Text, n.FontSize, n.Weight, mono, italic, face + wrapped.width, wrapped.MaxLines = width, maxLines wrapped.Lines = append(wrapped.Lines[:0], dst[start:]...) wrapped.filled = true return dst } -// textStyle is the style a Text's width depends on: its size, weight and, when it is -// Mono, its face. +// textStyle is the style a Text's width depends on: its size, weight, slant and, +// when it is Mono, its face. func (n *Node) textStyle() gfx.TextStyle { - return gfx.TextStyle{Size: n.FontSize, Weight: n.Weight, Mono: n.Flags&flagMono != 0, MonoFace: n.Face} + return gfx.TextStyle{Size: n.FontSize, Weight: n.Weight, Italic: n.TextDecor&textItalic != 0, Mono: n.Flags&flagMono != 0, MonoFace: n.Face} } // Wrap adds text that breaks into as many lines as the width it is given needs, diff --git a/benchmarks/size.sh b/benchmarks/size.sh index 3116efd16..030e8c01d 100755 --- a/benchmarks/size.sh +++ b/benchmarks/size.sh @@ -13,6 +13,7 @@ set -eu root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT +over_limit=0 check() { name=$1 @@ -26,7 +27,7 @@ check() { printf '%-28s %10d B (limit %d)\n' "$name" "$size" "$limit" if [ "$size" -gt "$limit" ]; then echo "size: $name is $size bytes, over the $limit-byte limit" >&2 - exit 1 + over_limit=1 fi } @@ -39,3 +40,5 @@ check "hello windows/amd64" windows amd64 ./examples/guides/hello "$hello_limit" check "hello linux/amd64" linux amd64 ./examples/guides/hello "$hello_limit" check "showcase darwin/arm64" darwin arm64 ./cmd/showcase "$gallery_limit" check "showcase windows/amd64" windows amd64 ./cmd/showcase "$gallery_windows_limit" + +exit "$over_limit" diff --git a/cmd/viva-conformance/main.go b/cmd/viva-conformance/main.go index a3b370b87..a0e7c8e9e 100644 --- a/cmd/viva-conformance/main.go +++ b/cmd/viva-conformance/main.go @@ -405,6 +405,24 @@ func (r *runner) scenarios(results *report) { return p.waitFor("the panel's OnClosed", p.isClosed) }) + check("a notification paints without pointer input and returns to idle", func() error { + p, err := r.open("notification", app.WindowNotification, false) + if err != nil { + return err + } + defer p.window.Close() + if err := p.waitFor("the notification's first paint", func() bool { return p.paints.Load() > 0 }); err != nil { + return err + } + time.Sleep(quiet) + paints := p.paints.Load() + time.Sleep(quiet) + if extra := p.paints.Load() - paints; extra != 0 { + return fmt.Errorf("an idle notification painted %d extra frames", extra) + } + return nil + }) + check("a status item can be added, changed and removed", func() error { var item *app.StatusItem var addErr, iconErr error diff --git a/cmd/viva/android.go b/cmd/viva/android.go deleted file mode 100644 index 475a1be1e..000000000 --- a/cmd/viva/android.go +++ /dev/null @@ -1,611 +0,0 @@ -package main - -import ( - "archive/zip" - "bytes" - "encoding/xml" - "errors" - "fmt" - "io" - "io/fs" - "os" - "os/exec" - "path" - "path/filepath" - "regexp" - "runtime" - "sort" - "strconv" - "strings" - "time" - - "github.com/vivaui/viva/internal/platform/android/hostsrc" - "github.com/vivaui/viva/tools/manifest" -) - -// An Android build is the program as a shared library (the Go toolchain with the -// NDK's C compiler, which purego and the JNI bridge need), the Java of the host -// (hostsrc) compiled with javac and d8, and an APK assembled from them with aapt2, -// zipalign and apksigner: the tools of the Android SDK and the JDK, with no Gradle. - -const ( - // androidMinSDK is the oldest Android an application runs on: 8.0, which has the - // Vulkan 1.1 and the text APIs the host uses. - androidMinSDK = 26 - // androidTargetSDK is the Android the application is built for. - androidTargetSDK = 35 - // androidActivity is the host's Activity, the launcher entry. - androidActivity = "dev.viva.host.VivaActivity" -) - -// isAndroid reports whether the plan builds an Android package. -func (plan buildPlan) isAndroid() bool { return plan.target == "android" } - -// androidABI is the name Android gives an architecture. -func androidABI(arch string) string { - if arch == "amd64" { - return "x86_64" - } - return "arm64-v8a" -} - -// androidSDK is where the Android tools are. -type androidSDK struct { - home string - ndk string - buildTools string - androidJar string - javac, java string - clangDir string - adb, emulator string -} - -// lookEnv is os.Getenv; tests replace it. -var lookEnv = os.Getenv - -// findAndroidSDK finds the SDK, the NDK and the JDK, and says what to install when -// one is missing. -func findAndroidSDK() (androidSDK, error) { - sdk := androidSDK{} - var candidates []string - for _, name := range []string{"ANDROID_HOME", "ANDROID_SDK_ROOT"} { - if value := lookEnv(name); value != "" { - candidates = append(candidates, value) - } - } - if home, err := os.UserHomeDir(); err == nil { - candidates = append(candidates, - filepath.Join(home, "Library", "Android", "sdk"), // macOS, Android Studio - filepath.Join(home, "Android", "Sdk"), // Linux, Android Studio - filepath.Join(home, "AppData", "Local", "Android", "Sdk")) - } - candidates = append(candidates, "/opt/homebrew/share/android-commandlinetools", "/usr/local/share/android-commandlinetools") - for _, candidate := range candidates { - if info, err := os.Stat(filepath.Join(candidate, "build-tools")); err == nil && info.IsDir() { - sdk.home = candidate - break - } - } - if sdk.home == "" { - return sdk, errors.New("the Android SDK was not found; install it with 'brew install --cask android-commandlinetools' " + - "(or Android Studio) and set ANDROID_HOME, then 'sdkmanager \"platform-tools\" \"platforms;android-35\" \"build-tools;35.0.0\" \"ndk;28.2.13676358\"'") - } - var err error - if sdk.buildTools, err = newestChild(filepath.Join(sdk.home, "build-tools"), func(name string) bool { - return fileExists(filepath.Join(sdk.home, "build-tools", name, executable("aapt2"))) - }); err != nil { - return sdk, fmt.Errorf("no Android build-tools in %s; run sdkmanager \"build-tools;35.0.0\"", sdk.home) - } - sdk.buildTools = filepath.Join(sdk.home, "build-tools", sdk.buildTools) - platform, err := newestPlatform(filepath.Join(sdk.home, "platforms")) - if err != nil { - return sdk, fmt.Errorf("no Android platform (android-%d or newer) in %s; run sdkmanager \"platforms;android-%d\"", androidMinSDK, sdk.home, androidTargetSDK) - } - sdk.androidJar = filepath.Join(sdk.home, "platforms", platform, "android.jar") - if ndk := lookEnv("ANDROID_NDK_HOME"); ndk != "" && fileExists(ndk) { - sdk.ndk = ndk - } else if name, err := newestChild(filepath.Join(sdk.home, "ndk"), func(string) bool { return true }); err == nil { - sdk.ndk = filepath.Join(sdk.home, "ndk", name) - } else { - return sdk, fmt.Errorf("no Android NDK in %s; run sdkmanager \"ndk;28.2.13676358\"", sdk.home) - } - prebuilt, err := fs.Glob(os.DirFS(sdk.ndk), "toolchains/llvm/prebuilt/*") - if err != nil || len(prebuilt) == 0 { - return sdk, fmt.Errorf("the NDK in %s has no LLVM toolchain", sdk.ndk) - } - sdk.clangDir = filepath.Join(sdk.ndk, filepath.FromSlash(prebuilt[0]), "bin") - if sdk.javac, err = findJava("javac"); err != nil { - return sdk, err - } - if sdk.java, err = findJava("java"); err != nil { - return sdk, err - } - sdk.adb = filepath.Join(sdk.home, "platform-tools", executable("adb")) - if !fileExists(sdk.adb) { - if found, err := exec.LookPath("adb"); err == nil { - sdk.adb = found - } - } - sdk.emulator = filepath.Join(sdk.home, "emulator", executable("emulator")) - return sdk, nil -} - -func executable(name string) string { - if runtime.GOOS == "windows" { - switch name { - case "aapt2", "adb", "emulator": - return name + ".exe" - case "zipalign": - return name + ".exe" - case "apksigner", "d8": - return name + ".bat" - } - } - return name -} - -func fileExists(name string) bool { - _, err := os.Stat(name) - return err == nil -} - -// newestChild is the child of dir with the highest version in its name that ok accepts. -func newestChild(dir string, ok func(string) bool) (string, error) { - entries, err := os.ReadDir(dir) - if err != nil { - return "", err - } - var names []string - for _, entry := range entries { - if entry.IsDir() && ok(entry.Name()) { - names = append(names, entry.Name()) - } - } - if len(names) == 0 { - return "", fmt.Errorf("nothing in %s", dir) - } - sort.Slice(names, func(i, j int) bool { return versionLess(versionNumbers(names[i]), versionNumbers(names[j])) }) - return names[len(names)-1], nil -} - -var digits = regexp.MustCompile(`\d+`) - -// versionNumbers are the numbers of a name such as 35.0.0 or android-35, in order. -func versionNumbers(name string) []int { - var numbers []int - for _, part := range digits.FindAllString(name, -1) { - number, _ := strconv.Atoi(part) - numbers = append(numbers, number) - } - return numbers -} - -// newestPlatform is the newest platforms/android-N with N at least the minimum SDK and -// an android.jar in it. -func newestPlatform(dir string) (string, error) { - return newestChild(dir, func(name string) bool { - numbers := versionNumbers(name) - return strings.HasPrefix(name, "android-") && len(numbers) > 0 && numbers[0] >= androidMinSDK && - fileExists(filepath.Join(dir, name, "android.jar")) - }) -} - -// findJava finds a JDK tool: under JAVA_HOME, else on the path. -func findJava(tool string) (string, error) { - if home := lookEnv("JAVA_HOME"); home != "" { - if candidate := filepath.Join(home, "bin", tool); fileExists(candidate) || fileExists(candidate+".exe") { - return candidate, nil - } - } - found, err := exec.LookPath(tool) - if err != nil { - return "", fmt.Errorf("%s was not found: install a JDK (17 or newer) and put it on the path or set JAVA_HOME", tool) - } - return found, nil -} - -// clang is the NDK's C compiler for an architecture and the minimum SDK. -func (sdk androidSDK) clang(arch string) string { - triple := "aarch64-linux-android" - if arch == "amd64" { - triple = "x86_64-linux-android" - } - name := fmt.Sprintf("%s%d-clang", triple, androidMinSDK) - if runtime.GOOS == "windows" { - name += ".cmd" - } - return filepath.Join(sdk.clangDir, name) -} - -// androidEnvironment is what go build needs for Android: cgo with the NDK's compiler. -func (plan buildPlan) androidEnvironment(environment []string) []string { - return append(environment, "CGO_ENABLED=1", "CC="+plan.sdk.clang(plan.arch)) -} - -// checkAndroid reports what a flag combination cannot build. -func checkAndroid(shared buildFlags) error { - if shared.cgo { - return errors.New("--cgo is for Linux and Windows; Android builds always use cgo") - } - return nil -} - -// androidPackageID is the application's identifier on a device. -func (plan buildPlan) androidPackageID() string { - if id := plan.manifest.App.ID; id != "" { - return id - } - return "dev.viva." + strings.ReplaceAll(manifest.Slug(plan.executable), "-", "_") -} - -// versionCode is the integer Android orders releases by: major, minor and patch in -// three digits each, so 1.2.3 is 1002003. A version it cannot read is 1. -func versionCode(version string) int { - numbers := versionNumbers(strings.SplitN(version, "-", 2)[0]) - if len(numbers) == 0 { - return 1 - } - code := 0 - for index := 0; index < 3; index++ { - part := 0 - if index < len(numbers) { - part = min(numbers[index], 999) - } - code = code*1000 + part - } - return max(code, 1) -} - -// androidManifest is AndroidManifest.xml: one activity, the host's, which the -// application's window is. -func androidManifest(id, name, version string) []byte { - var escaped bytes.Buffer - xml.EscapeText(&escaped, []byte(name)) - return []byte(` - - - - - - - - - - - - - - - -`) -} - -// addToAPK writes base (aapt2's package) to out with the dex file and the program's -// library added. The library is stored, not compressed, so the system maps it from the -// package, as zipalign -p then aligns it to a page. -func addToAPK(base, out string, dex []byte, library, abi string) error { - reader, err := zip.OpenReader(base) - if err != nil { - return err - } - defer reader.Close() - file, err := os.Create(out) - if err != nil { - return err - } - defer file.Close() - writer := zip.NewWriter(file) - for _, entry := range reader.File { - if err := writer.Copy(entry); err != nil { - return err - } - } - dexEntry, err := writer.Create("classes.dex") - if err != nil { - return err - } - if _, err := dexEntry.Write(dex); err != nil { - return err - } - libraryEntry, err := writer.CreateHeader(&zip.FileHeader{Name: path.Join("lib", abi, "libviva.so"), Method: zip.Store, Modified: time.Unix(0, 0)}) - if err != nil { - return err - } - source, err := os.Open(library) - if err != nil { - return err - } - defer source.Close() - if _, err := io.Copy(libraryEntry, source); err != nil { - return err - } - return writer.Close() -} - -// runCommand runs a tool and puts its output in the error when it fails. -func runCommand(dir string, name string, arguments ...string) error { - command := exec.Command(name, arguments...) - command.Dir = dir - var output bytes.Buffer - command.Stdout, command.Stderr = &output, &output - if err := command.Run(); err != nil { - return fmt.Errorf("%s: %w\n%s", filepath.Base(name), err, strings.TrimSpace(output.String())) - } - return nil -} - -// debugKeystore is the keystore a debug build is signed with: the one Android Studio -// makes, created when there is none. -func (sdk androidSDK) debugKeystore() (string, error) { - home, err := os.UserHomeDir() - if err != nil { - return "", err - } - keystore := filepath.Join(home, ".android", "debug.keystore") - if fileExists(keystore) { - return keystore, nil - } - if err := os.MkdirAll(filepath.Dir(keystore), 0o700); err != nil { - return "", err - } - keytool, err := findJava("keytool") - if err != nil { - return "", err - } - if err := runCommand("", keytool, "-genkeypair", "-keystore", keystore, "-storepass", "android", "-keypass", "android", - "-alias", "androiddebugkey", "-keyalg", "RSA", "-keysize", "2048", "-validity", "10000", - "-dname", "CN=Android Debug,O=Android,C=US"); err != nil { - return "", err - } - return keystore, nil -} - -// runAndroid builds the program into a library and the package around it. -func (plan buildPlan) runAndroid(errorOutput io.Writer) error { - sdk, err := findAndroidSDK() - if err != nil { - return err - } - plan.sdk = sdk - work, err := os.MkdirTemp("", "viva-android-") - if err != nil { - return err - } - defer os.RemoveAll(work) - abi := androidABI(plan.arch) - - library := filepath.Join(work, "lib", abi, "libviva.so") - if err := plan.buildLibrary(library, errorOutput); err != nil { - return err - } - - classes := filepath.Join(work, "classes") - sources, err := extractHost(work) - if err != nil { - return err - } - if err := os.MkdirAll(classes, 0o755); err != nil { - return err - } - arguments := append([]string{"-source", "8", "-target", "8", "-Xlint:-options", "-nowarn", "-classpath", sdk.androidJar, "-d", classes}, sources...) - if err := runCommand("", sdk.javac, arguments...); err != nil { - return err - } - var classFiles []string - filepath.WalkDir(classes, func(name string, entry fs.DirEntry, err error) error { - if err == nil && !entry.IsDir() && strings.HasSuffix(name, ".class") { - classFiles = append(classFiles, name) - } - return nil - }) - dexDir := filepath.Join(work, "dex") - if err := os.MkdirAll(dexDir, 0o755); err != nil { - return err - } - if err := runCommand("", filepath.Join(sdk.buildTools, executable("d8")), - append([]string{"--min-api", strconv.Itoa(androidMinSDK), "--lib", sdk.androidJar, "--output", dexDir}, classFiles...)...); err != nil { - return err - } - dex, err := os.ReadFile(filepath.Join(dexDir, "classes.dex")) - if err != nil { - return err - } - - name := plan.manifest.App.Name - if name == "" { - name = plan.executable - } - manifestFile := filepath.Join(work, "AndroidManifest.xml") - if err := os.WriteFile(manifestFile, androidManifest(plan.androidPackageID(), name, plan.manifest.App.Version), 0o644); err != nil { - return err - } - base := filepath.Join(work, "base.apk") - if err := runCommand("", filepath.Join(sdk.buildTools, executable("aapt2")), "link", "-o", base, "-I", sdk.androidJar, - "--manifest", manifestFile, "--min-sdk-version", strconv.Itoa(androidMinSDK), "--target-sdk-version", strconv.Itoa(androidTargetSDK)); err != nil { - return err - } - assembled := filepath.Join(work, "assembled.apk") - if err := addToAPK(base, assembled, dex, library, abi); err != nil { - return err - } - aligned := filepath.Join(work, "aligned.apk") - if err := runCommand("", filepath.Join(sdk.buildTools, executable("zipalign")), "-f", "-p", "4", assembled, aligned); err != nil { - return err - } - keystore, err := sdk.debugKeystore() - if err != nil { - return err - } - if err := os.MkdirAll(filepath.Dir(plan.out), 0o755); err != nil { - return err - } - os.Remove(plan.out) - return runCommand("", filepath.Join(sdk.buildTools, executable("apksigner")), "sign", "--ks", keystore, "--ks-pass", "pass:android", - "--key-pass", "pass:android", "--out", plan.out, aligned) -} - -// buildLibrary compiles the program as the library the host loads. -func (plan buildPlan) buildLibrary(output string, errorOutput io.Writer) error { - if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil { - return err - } - if err := requireGo(errorOutput); err != nil { - return err - } - arguments := []string{"build", "-trimpath", "-buildmode=c-shared", "-ldflags", plan.ldflags()} - if len(plan.tags) > 0 { - arguments = append(arguments, "-tags", strings.Join(plan.tags, ",")) - } - arguments = append(arguments, "-o", output, plan.pkg) - command := exec.Command("go", arguments...) - command.Dir = plan.manifest.Dir - command.Env = plan.environment(os.Environ()) - command.Stdout, command.Stderr = errorOutput, errorOutput - if err := command.Run(); err != nil { - if errors.Is(err, exec.ErrNotFound) { - return errors.New("the go tool was not found in PATH") - } - return fmt.Errorf("go build failed: %w", err) - } - return nil -} - -// extractHost writes the host's Java sources under dir and returns their paths. -func extractHost(dir string) ([]string, error) { - var sources []string - err := fs.WalkDir(hostsrc.Java, "java", func(name string, entry fs.DirEntry, err error) error { - if err != nil || entry.IsDir() { - return err - } - data, err := hostsrc.Java.ReadFile(name) - if err != nil { - return err - } - target := filepath.Join(dir, "host", filepath.FromSlash(strings.TrimPrefix(name, "java/"))) - if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { - return err - } - sources = append(sources, target) - return os.WriteFile(target, data, 0o644) - }) - return sources, err -} - -// adbDevice is one entry of 'adb devices'. -type adbDevice struct { - Serial string - State string -} - -// parseADBDevices reads the output of 'adb devices'. -func parseADBDevices(output string) []adbDevice { - var devices []adbDevice - for _, line := range strings.Split(output, "\n") { - fields := strings.Fields(line) - if len(fields) == 2 && fields[0] != "List" && !strings.HasPrefix(fields[0], "*") { - devices = append(devices, adbDevice{Serial: fields[0], State: fields[1]}) - } - } - return devices -} - -// chooseDevice picks the device to run on: the one asked for by serial; otherwise the -// only one that is ready, or a real one before an emulator. -func chooseDevice(devices []adbDevice, requested string) (adbDevice, error) { - var ready []adbDevice - for _, device := range devices { - if device.State != "device" { - continue - } - if requested != "" { - if device.Serial == requested { - return device, nil - } - continue - } - ready = append(ready, device) - } - if requested != "" { - return adbDevice{}, fmt.Errorf("no device %q is ready; 'adb devices' lists them", requested) - } - if len(ready) == 0 { - return adbDevice{}, errors.New("no Android device is ready: connect a phone with USB debugging on, or start an emulator") - } - sort.SliceStable(ready, func(i, j int) bool { - return !strings.HasPrefix(ready[i].Serial, "emulator-") && strings.HasPrefix(ready[j].Serial, "emulator-") - }) - return ready[0], nil -} - -// adb runs the Android debug bridge; tests replace it. -var adb = func(sdk androidSDK, serial string, arguments ...string) (string, error) { - if serial != "" { - arguments = append([]string{"-s", serial}, arguments...) - } - command := exec.Command(sdk.adb, arguments...) - var stdout, stderr bytes.Buffer - command.Stdout, command.Stderr = &stdout, &stderr - if err := command.Run(); err != nil { - return stdout.String(), fmt.Errorf("adb %s: %w: %s", strings.Join(arguments, " "), err, strings.TrimSpace(stderr.String())) - } - return stdout.String(), nil -} - -// runOnAndroid installs the built package on a device and starts it. -func runOnAndroid(plan buildPlan, requested string, output io.Writer) error { - sdk, err := findAndroidSDK() - if err != nil { - return err - } - if !fileExists(sdk.adb) && filepath.Base(sdk.adb) == executable("adb") { - return fmt.Errorf("adb was not found in %s; run sdkmanager \"platform-tools\"", sdk.home) - } - listing, err := adb(sdk, "", "devices") - if err != nil { - return err - } - device, err := chooseDevice(parseADBDevices(listing), requested) - if err != nil { - return err - } - if err := waitForPackageService(sdk, device.Serial, output); err != nil { - return err - } - if _, err := adb(sdk, device.Serial, "install", "-r", plan.out); err != nil { - return err - } - id := plan.androidPackageID() - if _, err := adb(sdk, device.Serial, "shell", "am", "start", "-n", id+"/"+androidActivity); err != nil { - return err - } - fmt.Fprintf(output, "started %s on %s\n", id, device.Serial) - return nil -} - -// bootWait bounds how long run waits for a device that has just started. -const ( - bootAttempts = 90 - bootPause = 2 * time.Second -) - -// pause waits between boot checks; tests replace it. -var pause = time.Sleep - -// waitForPackageService waits for the device to have its package service: an emulator -// that is still starting is a device adb already lists, and answers an install with -// "Can't find service: package". -func waitForPackageService(sdk androidSDK, serial string, output io.Writer) error { - for attempt := 0; attempt < bootAttempts; attempt++ { - if _, err := adb(sdk, serial, "shell", "pm", "path", "android"); err == nil { - return nil - } - if attempt == 0 { - fmt.Fprintf(output, "waiting for %s to finish starting\n", serial) - } - pause(bootPause) - } - return fmt.Errorf("%s did not finish starting in %v", serial, bootAttempts*bootPause) -} diff --git a/cmd/viva/android_test.go b/cmd/viva/android_test.go deleted file mode 100644 index 6e42913e6..000000000 --- a/cmd/viva/android_test.go +++ /dev/null @@ -1,268 +0,0 @@ -package main - -import ( - "archive/zip" - "encoding/xml" - "errors" - "io" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -// Releases are ordered by a number: a later version is never a smaller one, and a -// version the tool cannot read still installs. -func TestVersionCodeOrdersReleases(t *testing.T) { - order := []string{"0.0.1", "0.1.0", "0.9.9", "1.0.0", "1.0.1", "1.2.0", "1.10.0", "2.0.0"} - last := 0 - for _, version := range order { - code := versionCode(version) - if code <= last { - t.Errorf("%s has code %d, not above %d", version, code, last) - } - last = code - } - if code := versionCode("1.2.3-beta.4"); code != versionCode("1.2.3") { - t.Errorf("a pre-release of 1.2.3 has code %d, 1.2.3 has %d", code, versionCode("1.2.3")) - } - if versionCode("") < 1 || versionCode("preview") < 1 { - t.Error("an unreadable version has no valid code") - } -} - -func TestAndroidManifestNamesTheApplicationAndTheHost(t *testing.T) { - data := androidManifest("dev.example.notes", "Notes & ", "2.0.1") - var parsed struct { - Package string `xml:"package,attr"` - VersionName string `xml:"versionName,attr"` - Application struct { - Label string `xml:"label,attr"` - Activity struct { - Name string `xml:"name,attr"` - } `xml:"activity"` - } `xml:"application"` - } - if err := xml.Unmarshal(data, &parsed); err != nil { - t.Fatalf("the manifest is not XML: %v\n%s", err, data) - } - if parsed.Package != "dev.example.notes" || parsed.VersionName != "2.0.1" { - t.Errorf("package %q version %q", parsed.Package, parsed.VersionName) - } - if parsed.Application.Label != "Notes & " { - t.Errorf("label %q lost its characters", parsed.Application.Label) - } - if parsed.Application.Activity.Name != androidActivity { - t.Errorf("the launcher activity is %q, want the host's", parsed.Application.Activity.Name) - } - if !strings.Contains(string(data), "android.hardware.vulkan") { - t.Error("the manifest does not ask for Vulkan, which the program draws with") - } -} - -// fakeSDK lays out the parts of an SDK the finder looks at. -func fakeSDK(t *testing.T) string { - t.Helper() - home := t.TempDir() - touch := func(parts ...string) { - path := filepath.Join(append([]string{home}, parts...)...) - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, nil, 0o755); err != nil { - t.Fatal(err) - } - } - for _, version := range []string{"9.0.0", "34.0.0", "35.0.0"} { - touch("build-tools", version, executable("aapt2")) - } - for _, platform := range []string{"android-9", "android-34", "android-35"} { - touch("platforms", platform, "android.jar") - } - os.MkdirAll(filepath.Join(home, "platforms", "android-36"), 0o755) // no jar: not a platform - for _, ndk := range []string{"27.1.0", "28.2.0"} { - os.MkdirAll(filepath.Join(home, "ndk", ndk, "toolchains", "llvm", "prebuilt", "host", "bin"), 0o755) - } - touch("platform-tools", executable("adb")) - jdk := t.TempDir() - touch2 := filepath.Join(jdk, "bin") - os.MkdirAll(touch2, 0o755) - for _, tool := range []string{"javac", "java"} { - os.WriteFile(filepath.Join(touch2, tool), nil, 0o755) - } - t.Setenv("JAVA_HOME", jdk) - t.Setenv("ANDROID_HOME", home) - t.Setenv("ANDROID_SDK_ROOT", "") - t.Setenv("ANDROID_NDK_HOME", "") - return home -} - -// The newest of what is installed is used, by version and not by name ("9" sorts -// after "35"), and a platform too old to run on, or without its jar, is not one. -func TestFindAndroidSDKTakesTheNewestOfEachTool(t *testing.T) { - home := fakeSDK(t) - sdk, err := findAndroidSDK() - if err != nil { - t.Fatal(err) - } - if filepath.Base(sdk.buildTools) != "35.0.0" { - t.Errorf("build-tools %s, want 35.0.0", sdk.buildTools) - } - if filepath.Base(filepath.Dir(sdk.androidJar)) != "android-35" { - t.Errorf("platform %s, want android-35", sdk.androidJar) - } - if filepath.Base(sdk.ndk) != "28.2.0" { - t.Errorf("ndk %s, want 28.2.0", sdk.ndk) - } - if !strings.HasPrefix(sdk.clangDir, home) || filepath.Base(sdk.clangDir) != "bin" { - t.Errorf("the NDK's compiler directory is %s", sdk.clangDir) - } -} - -func TestFindAndroidSDKSaysWhatToInstall(t *testing.T) { - t.Setenv("ANDROID_HOME", t.TempDir()) - t.Setenv("ANDROID_SDK_ROOT", "") - t.Setenv("HOME", t.TempDir()) - t.Setenv("USERPROFILE", t.TempDir()) - if _, err := findAndroidSDK(); err == nil { - t.Skip("this machine has an Android SDK in a default place") - } else if !strings.Contains(err.Error(), "sdkmanager") { - t.Errorf("the error does not say how to install the SDK: %v", err) - } -} - -func TestAndroidEnvironmentUsesTheNDKCompilerOfTheArchitecture(t *testing.T) { - sdk := androidSDK{clangDir: filepath.Join("ndk", "bin")} - for _, test := range []struct{ arch, triple string }{{"arm64", "aarch64-linux-android"}, {"amd64", "x86_64-linux-android"}} { - plan := buildPlan{target: "android", arch: test.arch, sdk: sdk} - goos, goarch := plan.goTarget() - if goos != "android" || goarch != test.arch { - t.Errorf("%s builds for %s/%s", test.arch, goos, goarch) - } - environment := plan.environment(nil) - if lastEnvironment(environment, "CGO_ENABLED") != "1" { - t.Errorf("%s: cgo is off", test.arch) - } - compiler := filepath.Base(lastEnvironment(environment, "CC")) - if !strings.HasPrefix(compiler, test.triple) || !strings.Contains(compiler, "26-clang") { - t.Errorf("%s: compiler %q", test.arch, compiler) - } - } - if checkAndroid(buildFlags{target: "android", cgo: true}) == nil { - t.Error("--cgo was accepted for Android, which always uses cgo") - } -} - -func TestAndroidOutputIsAnAPKOfItsOwn(t *testing.T) { - dir := fixture(t, notesTOML) - plan := buildPlan{manifest: loadPlan(t, dir, buildFlags{target: "linux"}, "").manifest, target: "android", arch: "arm64", executable: "notes"} - if err := plan.outputPath(""); err != nil { - t.Fatal(err) - } - if !strings.HasSuffix(plan.out, "notes-android.apk") { - t.Errorf("output %s", plan.out) - } -} - -func TestChooseDevicePrefersAPhoneToAnEmulator(t *testing.T) { - listing := "List of devices attached\nemulator-5554\tdevice\nR58M123ABC\tdevice\nR58M999XYZ\tunauthorized\n\n" - devices := parseADBDevices(listing) - if len(devices) != 3 { - t.Fatalf("parsed %v", devices) - } - chosen, err := chooseDevice(devices, "") - if err != nil || chosen.Serial != "R58M123ABC" { - t.Fatalf("chose %+v, %v; want the phone that is ready", chosen, err) - } - if chosen, err := chooseDevice(devices, "emulator-5554"); err != nil || chosen.Serial != "emulator-5554" { - t.Fatalf("--device chose %+v, %v", chosen, err) - } - if _, err := chooseDevice(devices, "R58M999XYZ"); err == nil { - t.Error("a device that has not been authorized was chosen") - } - if _, err := chooseDevice(parseADBDevices("List of devices attached\n"), ""); err == nil { - t.Error("no devices, and one was chosen") - } -} - -// The package keeps what aapt2 made, adds the program's library stored and not -// compressed (the system maps it from the package), and the dex. -func TestAddToAPKStoresTheLibraryAndKeepsTheBase(t *testing.T) { - dir := t.TempDir() - base := filepath.Join(dir, "base.apk") - file, err := os.Create(base) - if err != nil { - t.Fatal(err) - } - writer := zip.NewWriter(file) - entry, _ := writer.Create("AndroidManifest.xml") - entry.Write([]byte("manifest")) - writer.Close() - file.Close() - library := filepath.Join(dir, "libviva.so") - if err := os.WriteFile(library, []byte("library bytes"), 0o644); err != nil { - t.Fatal(err) - } - out := filepath.Join(dir, "out.apk") - if err := addToAPK(base, out, []byte("dex bytes"), library, "arm64-v8a"); err != nil { - t.Fatal(err) - } - reader, err := zip.OpenReader(out) - if err != nil { - t.Fatal(err) - } - defer reader.Close() - contents := map[string]string{} - methods := map[string]uint16{} - for _, entry := range reader.File { - opened, err := entry.Open() - if err != nil { - t.Fatal(err) - } - data, _ := io.ReadAll(opened) - opened.Close() - contents[entry.Name], methods[entry.Name] = string(data), entry.Method - } - if contents["AndroidManifest.xml"] != "manifest" || contents["classes.dex"] != "dex bytes" { - t.Errorf("package holds %v", contents) - } - const name = "lib/arm64-v8a/libviva.so" - if contents[name] != "library bytes" || methods[name] != zip.Store { - t.Errorf("library entry %q method %d, want it stored", contents[name], methods[name]) - } -} - -// A device adb lists while it is still starting answers nothing yet: run waits for it -// and then installs, instead of failing on the first try. -func TestRunWaitsForADeviceThatIsStillStarting(t *testing.T) { - asked := 0 - previous, previousPause := adb, pause - t.Cleanup(func() { adb, pause = previous, previousPause }) - adb = func(sdk androidSDK, serial string, arguments ...string) (string, error) { - asked++ - if asked < 4 { - return "", errors.New("cmd: Can't find service: package") - } - return "package:/system/framework/framework-res.apk", nil - } - pauses := 0 - pause = func(time.Duration) { pauses++ } - var output strings.Builder - if err := waitForPackageService(androidSDK{}, "emulator-5554", &output); err != nil { - t.Fatal(err) - } - if asked != 4 || pauses != 3 || !strings.Contains(output.String(), "waiting") { - t.Fatalf("asked %d times, paused %d, said %q", asked, pauses, output.String()) - } -} - -func TestRunGivesUpOnADeviceThatNeverStarts(t *testing.T) { - previous, previousPause := adb, pause - t.Cleanup(func() { adb, pause = previous, previousPause }) - adb = func(androidSDK, string, ...string) (string, error) { return "", errors.New("no service") } - pause = func(time.Duration) {} - if err := waitForPackageService(androidSDK{}, "emulator-5554", io.Discard); err == nil { - t.Fatal("a device that never started was waited for forever") - } -} diff --git a/cmd/viva/build.go b/cmd/viva/build.go index 4d135f20e..9de3b919f 100644 --- a/cmd/viva/build.go +++ b/cmd/viva/build.go @@ -18,7 +18,7 @@ import ( const mebibyte = 1 << 20 var ( - buildTargets = []string{"darwin", "windows", "linux", "web", "ios-sim", "ios", "android"} + buildTargets = []string{"darwin", "windows", "linux", "web"} buildArches = []string{"arm64", "amd64"} ) @@ -36,34 +36,16 @@ type buildPlan struct { debug bool // cgo explicitly opts Linux and Windows applications into native dependencies. cgo bool - // toolchain is Xcode's compiler and SDK, found when an iOS build starts. - toolchain iosToolchain - // sdk is the Android SDK, found when an Android build starts. - sdk androidSDK } // goTarget is the GOOS/GOARCH pair for a target. func (plan buildPlan) goTarget() (goos, goarch string) { - switch plan.target { - case "web": + if plan.target == "web" { return "js", "wasm" - case "ios-sim", "ios": - return "ios", plan.arch - case "android": - return "android", plan.arch } return plan.target, plan.arch } -// programPath is the executable a build writes: the output itself, or for iOS -// the file inside the .app. -func (plan buildPlan) programPath() string { - if plan.isIOS() { - return filepath.Join(plan.out, plan.executable) - } - return plan.out -} - // ldflags are the linker flags: stripped unless debug, a fixed build ID so the // same sources give the same bytes, and on Windows the GUI subsystem for // release builds (a debug build keeps the console so output is visible). @@ -110,10 +92,6 @@ func (plan buildPlan) environment(base []string) []string { } environment = append(environment, name+"="+value) } - case "ios-sim", "ios": - return plan.iosEnvironment(environment, base) - case "android": - return plan.androidEnvironment(environment) case "linux", "windows": // These targets reach the system through purego and the standard // library's own system calls, not through cgo. Go turns cgo on by @@ -143,22 +121,8 @@ func lastEnvironment(environment []string, name string) string { return value } -// run builds into output; for an iOS target, the .app at plan.out. +// run builds into output. func (plan buildPlan) run(output string, errorOutput io.Writer) error { - if plan.isIOS() { - return plan.runIOS(errorOutput) - } - if plan.isAndroid() { - return plan.runAndroid(errorOutput) - } - if err := plan.build(output, errorOutput); err != nil { - return err - } - return plan.addWindowsResources(output, errorOutput) -} - -// build runs go build into the output file. -func (plan buildPlan) build(output string, errorOutput io.Writer) error { if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil { return err } @@ -175,7 +139,7 @@ func (plan buildPlan) build(output string, errorOutput io.Writer) error { } return fmt.Errorf("go build failed: %w", err) } - return nil + return plan.addWindowsResources(output, errorOutput) } // buildFlags holds the flags build and package share. @@ -192,7 +156,7 @@ type buildFlags struct { func (shared *buildFlags) register(flags *flag.FlagSet, defaultTarget string) { flags.StringVar(&shared.dir, "C", ".", "directory holding viva.toml and the Go module") flags.StringVar(&shared.dir, "dir", ".", "same as -C") - flags.StringVar(&shared.target, "target", defaultTarget, "darwin, windows, linux, web, ios-sim (the simulator), ios (devices) or android") + flags.StringVar(&shared.target, "target", defaultTarget, "darwin, windows, linux or web") flags.StringVar(&shared.arch, "arch", runtime.GOARCH, "arm64 or amd64 (not used by web)") flags.StringVar(&shared.tags, "tags", "", "comma-separated build tags, added to [build] tags") flags.BoolVar(&shared.debug, "debug", false, "keep symbols and debug information (not the release size)") @@ -204,16 +168,6 @@ func newPlan(shared buildFlags, packageArgument string) (buildPlan, error) { if !contains(buildTargets, shared.target) { return buildPlan{}, fmt.Errorf("unknown target %q; use one of: %s", shared.target, strings.Join(buildTargets, ", ")) } - if shared.target == "ios-sim" || shared.target == "ios" { - if err := checkIOS(shared); err != nil { - return buildPlan{}, err - } - } - if shared.target == "android" { - if err := checkAndroid(shared); err != nil { - return buildPlan{}, err - } - } if shared.target != "web" && !contains(buildArches, shared.arch) { return buildPlan{}, fmt.Errorf("unknown architecture %q; use one of: %s", shared.arch, strings.Join(buildArches, ", ")) } @@ -295,38 +249,6 @@ func (plan *buildPlan) outputPath(requested string) error { return err } plan.out = filepath.Join(plan.manifest.Path(plan.manifest.Build.Out), "web") - case plan.isAndroid(): - name += "-android" - if plan.arch != "arm64" { - name += "-" + plan.arch - } - name += ".apk" - if requested != "" { - absolute, err := filepath.Abs(requested) - if err != nil { - return err - } - if info, statErr := os.Stat(absolute); statErr == nil && info.IsDir() { - absolute = filepath.Join(absolute, name) - } - plan.out = absolute - } else { - plan.out = filepath.Join(plan.manifest.Path(plan.manifest.Build.Out), name) - } - case plan.isIOS(): - name += "-" + plan.target + ".app" - if requested != "" { - absolute, err := filepath.Abs(requested) - if err != nil { - return err - } - if info, statErr := os.Stat(absolute); statErr == nil && info.IsDir() && filepath.Ext(absolute) != ".app" { - absolute = filepath.Join(absolute, name) - } - plan.out = absolute - } else { - plan.out = filepath.Join(plan.manifest.Path(plan.manifest.Build.Out), name) - } default: if plan.target != runtime.GOOS || plan.arch != runtime.GOARCH { name += "-" + plan.target + "-" + plan.arch @@ -389,7 +311,7 @@ func runBuild(arguments []string, output, errorOutput io.Writer) error { if err := plan.run(plan.out, errorOutput); err != nil { return err } - info, err := os.Stat(plan.programPath()) + info, err := os.Stat(plan.out) if err != nil { return err } @@ -411,12 +333,6 @@ func displayPath(path string) string { func printBuildDetails(output io.Writer, plan buildPlan, size int64) { goos, goarch := plan.goTarget() target := goos + "/" + goarch - if plan.isIOS() { - target += " (iOS " + iosMinSystem + " or later)" - } - if plan.isAndroid() { - target += fmt.Sprintf(" (Android 8.0, API %d, or later)", androidMinSDK) - } if plan.target == "darwin" { target += " (macOS " + plan.manifest.Mac.MinSystem + " or later)" } diff --git a/cmd/viva/help.go b/cmd/viva/help.go index f29d513b8..0aef5441e 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -23,31 +23,17 @@ type command struct { func commands() []command { return []command{ {name: "build", usage: "build [flags] [package]", - summary: "Build a release program for macOS, Windows, Linux, iOS or the browser.", + summary: "Build a release program for macOS, Windows, Linux or the browser.", detail: "Builds with -trimpath and a stripped, reproducible link, and reports the size. Settings come from\n" + "viva.toml when there is one; the package argument overrides [app] package (or [web] package for\n" + "--target web, which also writes the loader and an index.html). macOS builds are compiled for\n" + "[mac] min_system, not for the macOS of the machine building them, and reach Cocoa through cgo;\n" + "Linux and Windows builds disable cgo by default. Use --cgo for application-owned native libraries;\n" + "provide the target C compiler and link flags, and check the resulting system dependencies.\n" + - "Windows release builds use the GUI subsystem; with --debug they keep the console. --target ios-sim writes\n" + - "an .app for the iOS simulator (macOS with Xcode; the Metal and UIKit bridge is built with cgo against\n" + - "the SDK); viva run builds, installs and starts it. --target android writes an .apk (the program as a\n" + - "shared library, built with the NDK's compiler, around the host's Activity, put together with the Android\n" + - "SDK's tools and the JDK, with no Gradle), signed with the debug key.", + "Windows release builds use the GUI subsystem; with --debug they keep the console.", run: func(arguments []string, output, errorOutput io.Writer) error { return runBuild(arguments, output, errorOutput) }}, - {name: "run", usage: "run [flags] [package]", - summary: "Build the application and start it in the iOS simulator or on an Android device.", - detail: "--target ios-sim builds an .app for the simulator, boots a simulator if none is running, installs the app and\n" + - "starts it. --device names the simulator or gives its identifier; without it, an iPhone already booted is used,\n" + - "else the newest iPhone the machine has. The Simulator window is shown unless -open=false. It needs macOS with\n" + - "Xcode. --target android builds an .apk, installs it with adb on the device that is ready (--device gives its\n" + - "serial; a phone before an emulator) and starts it. For the desktop, use viva dev.", - run: func(arguments []string, output, errorOutput io.Writer) error { - return runRun(arguments, output, errorOutput) - }}, {name: "sign", usage: "sign --target windows --program FILE", summary: "Sign a Windows program that was built elsewhere, in place.", detail: "Uses the same Windows signing options as package: a custom command with {file} " + diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 1d40492d1..2927b5d5d 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -222,11 +222,14 @@ func (m *model) page(c ui.C) { `ui/chart`, `ui/sidebar`. Its state type is named by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`. Use `cal`, `msg`, `pic` for locals; a model field may keep the noun (`m.calendar`) because a selector never shadows a package. -- Editors and visuals: `ui/textview`, `ui/codeeditor`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`. +- For read-only selectable output, keep a `textview.View` in the model and call + `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns the + lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. - Some packages expose `pkg.View(c, label, &state)` (`calendar.View`, `markdown.View`); others a method on the state (`avatar.New().View(c, label)`, `questionnaire.New().View(c, label)`). `go doc github.com/vivaui/viva/ui/` shows which. @@ -431,7 +434,7 @@ func (m *model) page(c ui.C) { ### Text and icons -- Text: `FontSize`, `Weight`, `Bold`, `Color`, `Highlight`, `Muted`, `Mono`, `MonoFace`, `TextCenter`, `TextEnd`, `TextDirection`, `LineHeight`; +- Text: `FontSize`, `Weight`, `Bold`, `Italic`, `Strike`, `Color`, `Highlight`, `Muted`, `Mono`, `MonoFace`, `TextCenter`, `TextEnd`, `TextDirection`, `LineHeight`; `Ellipsis()` keeps a Text to one line and ends it with … when it does not fit; `MaxLines(n)` lets a Text break into at most n lines (the last ends with …), `ui.Wrap(c, text)` into as many as the width needs. A paragraph its container does not stretch asks for its widest line, so a long URL or path runs out over the @@ -445,7 +448,11 @@ func (m *model) page(c ui.C) { overrides it. The height follows the width. Viva measures text with its own metrics, the same on every platform, and draws the platform's glyphs at that width: a button as wide as its label, a tab, a table column sized to content and every line break are the same on macOS, Windows and Linux, so do not size by a - platform's font (or special-case a platform) to make text fit. + platform's font (or special-case a platform) to make text fit. `Italic()` draws a Text in the italic face of its + font and wraps it at that face's widths; a text is never slanted by a transform, so a font whose family has no + italic face stays upright. `Strike()` draws a one-pixel line in the text's color through the middle of every line + it breaks into, from its first glyph to its last, as Markdown does for ~~struck~~ text: it changes no width, so a + struck Text keeps the layout it had upright. ### Buttons and controls diff --git a/cmd/viva/ios.go b/cmd/viva/ios.go deleted file mode 100644 index b41211aea..000000000 --- a/cmd/viva/ios.go +++ /dev/null @@ -1,319 +0,0 @@ -package main - -import ( - "bytes" - "encoding/json" - "errors" - "flag" - "fmt" - "io" - "os" - "os/exec" - "path/filepath" - "runtime" - "sort" - "strconv" - "strings" - - "github.com/vivaui/viva/tools/appbundle" - "github.com/vivaui/viva/tools/manifest" -) - -// iosMinSystem is the oldest iOS an application is built for. -const iosMinSystem = "16.0" - -// isIOS reports whether the plan builds an iOS application bundle, for the -// simulator or for devices. -func (plan buildPlan) isIOS() bool { return plan.target == "ios-sim" || plan.target == "ios" } - -// iosToolchain is where Xcode keeps what cgo needs to build for an iOS SDK. -type iosToolchain struct { - clang, sdk string -} - -// xcrun runs Xcode's tool locator and returns its trimmed output; tests replace it. -var xcrun = func(arguments ...string) (string, error) { - command := exec.Command("xcrun", arguments...) - var stderr bytes.Buffer - command.Stderr = &stderr - output, err := command.Output() - if err != nil { - return "", fmt.Errorf("xcrun %s: %w: %s", strings.Join(arguments, " "), err, strings.TrimSpace(stderr.String())) - } - return strings.TrimSpace(string(output)), nil -} - -// iosSDK is the Xcode SDK a target is built against. -func iosSDK(target string) string { - if target == "ios-sim" { - return "iphonesimulator" - } - return "iphoneos" -} - -// findIOSToolchain asks Xcode for the SDK and the C compiler of the target. -func findIOSToolchain(target string) (iosToolchain, error) { - sdk := iosSDK(target) - root, err := xcrun("--sdk", sdk, "--show-sdk-path") - if err != nil { - return iosToolchain{}, fmt.Errorf("the %s SDK was not found; install Xcode and run 'xcode-select -s /Applications/Xcode.app': %w", sdk, err) - } - clang, err := xcrun("--sdk", sdk, "-f", "clang") - if err != nil { - return iosToolchain{}, err - } - return iosToolchain{clang: clang, sdk: root}, nil -} - -// triple is the clang target of an iOS build. -func (plan buildPlan) iosTriple() string { - arch := plan.arch - if arch == "amd64" { - arch = "x86_64" - } - triple := arch + "-apple-ios" + iosMinSystem - if plan.target == "ios-sim" { - triple += "-simulator" - } - return triple -} - -// iosEnvironment is what go build needs for iOS: cgo, with Xcode's compiler -// pointed at the SDK and the deployment target. The Metal and UIKit bridge is -// Objective-C, so there is no building it without them. -func (plan buildPlan) iosEnvironment(environment, base []string) []string { - flags := "-isysroot " + plan.toolchain.sdk + " -target " + plan.iosTriple() - environment = append(environment, "CGO_ENABLED=1", "CC="+plan.toolchain.clang+" "+flags) - for _, name := range []string{"CGO_CFLAGS", "CGO_LDFLAGS"} { - value := flags - if existing := lastEnvironment(base, name); existing != "" { - value = existing + " " + flags - } - environment = append(environment, name+"="+value) - } - return environment -} - -// checkIOS reports what a machine or flag combination cannot build. -func checkIOS(shared buildFlags) error { - if runtime.GOOS != "darwin" { - return errors.New("building for iOS needs a macOS host with Xcode: the Metal and UIKit bridge is Objective-C") - } - if shared.target == "ios" && shared.arch != "arm64" { - return fmt.Errorf("iOS devices run arm64; got --arch %s", shared.arch) - } - if shared.cgo { - return errors.New("--cgo is for Linux and Windows; iOS builds always use cgo") - } - return nil -} - -// bundleID is the application's identifier on a device. -func (plan buildPlan) bundleID() string { - if id := plan.manifest.App.ID; id != "" { - return id - } - return "dev.viva." + manifest.Slug(plan.executable) -} - -// runIOS builds the program into the .app and writes the Info.plist beside it. -func (plan buildPlan) runIOS(errorOutput io.Writer) error { - toolchain, err := findIOSToolchain(plan.target) - if err != nil { - return err - } - plan.toolchain = toolchain - if err := os.RemoveAll(plan.out); err != nil { - return err - } - if err := os.MkdirAll(plan.out, 0o755); err != nil { - return err - } - if err := plan.build(plan.programPath(), errorOutput); err != nil { - return err - } - name := plan.manifest.App.Name - if name == "" { - name = plan.executable - } - plist, err := appbundle.IOSInfo{ - Name: name, ID: plan.bundleID(), Version: plan.manifest.App.Version, Executable: plan.executable, - MinSystem: iosMinSystem, Simulator: plan.target == "ios-sim", - }.Plist() - if err != nil { - return err - } - return os.WriteFile(filepath.Join(plan.out, "Info.plist"), plist, 0o644) -} - -// simulator is one device of the iOS simulator. -type simulator struct { - UDID string `json:"udid"` - Name string `json:"name"` - State string `json:"state"` - Runtime string `json:"-"` -} - -// listSimulators reads the available devices out of 'simctl list devices -j'. -func listSimulators(data []byte) ([]simulator, error) { - var listing struct { - Devices map[string][]simulator `json:"devices"` - } - if err := json.Unmarshal(data, &listing); err != nil { - return nil, fmt.Errorf("reading the simulator list: %w", err) - } - var devices []simulator - for runtimeName, list := range listing.Devices { - if !strings.Contains(runtimeName, ".iOS-") { - continue - } - for _, device := range list { - device.Runtime = runtimeName - devices = append(devices, device) - } - } - return devices, nil -} - -// runtimeVersion orders runtime names such as ...SimRuntime.iOS-18-5 by version. -func runtimeVersion(name string) []int { - _, version, _ := strings.Cut(name, ".iOS-") - var numbers []int - for _, part := range strings.Split(version, "-") { - number, _ := strconv.Atoi(part) - numbers = append(numbers, number) - } - return numbers -} - -func versionLess(a, b []int) bool { - for index := 0; index < len(a) && index < len(b); index++ { - if a[index] != b[index] { - return a[index] < b[index] - } - } - return len(a) < len(b) -} - -// chooseSimulator picks the device to run on: the one asked for by name or -// identifier; otherwise an iPhone already booted, or the first iPhone of the -// newest iOS the machine has. -func chooseSimulator(devices []simulator, requested string) (simulator, error) { - if requested != "" { - for _, device := range devices { - if device.UDID == requested || device.Name == requested { - return device, nil - } - } - return simulator{}, fmt.Errorf("no simulator named %q; 'xcrun simctl list devices available' lists them", requested) - } - var phones []simulator - for _, device := range devices { - if strings.HasPrefix(device.Name, "iPhone") { - phones = append(phones, device) - } - } - if len(phones) == 0 { - return simulator{}, errors.New("no iPhone simulator is installed; add one in Xcode's Devices and Simulators window") - } - sort.SliceStable(phones, func(i, j int) bool { - a, b := phones[i], phones[j] - if (a.State == "Booted") != (b.State == "Booted") { - return a.State == "Booted" - } - if a.Runtime != b.Runtime { - return versionLess(runtimeVersion(b.Runtime), runtimeVersion(a.Runtime)) - } - return a.Name < b.Name - }) - return phones[0], nil -} - -// simctl runs the simulator's control tool; tests replace it. -var simctl = func(output io.Writer, arguments ...string) ([]byte, error) { - command := exec.Command("xcrun", append([]string{"simctl"}, arguments...)...) - var stdout, stderr bytes.Buffer - command.Stdout, command.Stderr = &stdout, &stderr - if err := command.Run(); err != nil { - return stdout.Bytes(), fmt.Errorf("simctl %s: %w: %s", strings.Join(arguments, " "), err, strings.TrimSpace(stderr.String())) - } - return stdout.Bytes(), nil -} - -// openSimulatorApp shows the Simulator window; tests replace it. -var openSimulatorApp = func(udid string) error { - return exec.Command("open", "-a", "Simulator", "--args", "-CurrentDeviceUDID", udid).Run() -} - -func runRun(arguments []string, output, errorOutput io.Writer) error { - c, _ := findCommand("run") - flags := flag.NewFlagSet("run", flag.ContinueOnError) - var shared buildFlags - shared.register(flags, "") - var device string - open := true - flags.StringVar(&device, "device", "", "ios-sim: the simulator's name or identifier (default: a booted iPhone, else the newest one installed); android: the device's adb serial (default: the one that is ready)") - flags.BoolVar(&open, "open", true, "show the Simulator window") - positional, helped, err := parseFlags(c, flags, arguments, output) - if helped || err != nil { - return err - } - if shared.target != "ios-sim" && shared.target != "android" { - return fmt.Errorf("run starts an application on a phone: give --target ios-sim or --target android (got %q). Use viva dev for the desktop", shared.target) - } - if len(positional) > 1 { - return errors.New("run takes at most one package; run 'viva help run'") - } - argument := "" - if len(positional) == 1 { - argument = positional[0] - } - plan, err := newPlan(shared, argument) - if err != nil { - return err - } - if err := plan.outputPath(""); err != nil { - return err - } - if err := plan.run(plan.out, errorOutput); err != nil { - return err - } - if plan.isAndroid() { - return runOnAndroid(plan, device, output) - } - listing, err := simctl(errorOutput, "list", "devices", "available", "-j") - if err != nil { - return err - } - devices, err := listSimulators(listing) - if err != nil { - return err - } - chosen, err := chooseSimulator(devices, device) - if err != nil { - return err - } - if chosen.State != "Booted" { - if _, err := simctl(errorOutput, "boot", chosen.UDID); err != nil { - return err - } - } - if open { - if err := openSimulatorApp(chosen.UDID); err != nil { - return fmt.Errorf("showing the Simulator window: %w", err) - } - } - if _, err := simctl(errorOutput, "bootstatus", chosen.UDID, "-b"); err != nil { - return err - } - if _, err := simctl(errorOutput, "install", chosen.UDID, plan.out); err != nil { - return err - } - // Without --terminate-running-process a copy still running from the last - // run would be brought forward instead of started again. - if _, err := simctl(errorOutput, "launch", "--terminate-running-process", chosen.UDID, plan.bundleID()); err != nil { - return err - } - fmt.Fprintf(output, "started %s on %s (%s)\n", plan.bundleID(), chosen.Name, chosen.UDID) - return nil -} diff --git a/cmd/viva/ios_test.go b/cmd/viva/ios_test.go deleted file mode 100644 index 786809c5d..000000000 --- a/cmd/viva/ios_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package main - -import ( - "runtime" - "slices" - "strings" - "testing" -) - -const simulatorListing = `{"devices": { - "com.apple.CoreSimulator.SimRuntime.iOS-9-0": [ - {"udid": "OLD", "name": "iPhone 6", "state": "Shutdown"}], - "com.apple.CoreSimulator.SimRuntime.iOS-18-5": [ - {"udid": "PRO", "name": "iPhone 16 Pro", "state": "Shutdown"}, - {"udid": "PAD", "name": "iPad Pro", "state": "Booted"}, - {"udid": "SIX", "name": "iPhone 16", "state": "Shutdown"}], - "com.apple.CoreSimulator.SimRuntime.watchOS-11-0": [ - {"udid": "WATCH", "name": "Apple Watch", "state": "Booted"}] -}}` - -func simulators(t *testing.T) []simulator { - t.Helper() - devices, err := listSimulators([]byte(simulatorListing)) - if err != nil { - t.Fatal(err) - } - return devices -} - -// The newest iOS wins by version, not by the order of the names: 18-5 is newer -// than 9-0 though "9" sorts after "1". -func TestRunPicksAnIPhoneOfTheNewestRuntime(t *testing.T) { - devices := simulators(t) - chosen, err := chooseSimulator(devices, "") - if err != nil { - t.Fatal(err) - } - if !strings.Contains(chosen.Runtime, "iOS-18-5") || !strings.HasPrefix(chosen.Name, "iPhone") { - t.Fatalf("chose %+v, want an iPhone of iOS 18.5", chosen) - } -} - -// What is already running is used rather than booting a second device, and a -// watch or an iPad is not an iPhone to start on. -func TestRunPrefersABootedIPhone(t *testing.T) { - devices := simulators(t) - for index := range devices { - if devices[index].UDID == "OLD" { - devices[index].State = "Booted" - } - } - chosen, err := chooseSimulator(devices, "") - if err != nil { - t.Fatal(err) - } - if chosen.UDID != "OLD" { - t.Fatalf("chose %+v, want the booted iPhone", chosen) - } -} - -func TestRunTakesADeviceByNameOrIdentifier(t *testing.T) { - devices := simulators(t) - for _, requested := range []string{"SIX", "iPhone 16"} { - chosen, err := chooseSimulator(devices, requested) - if err != nil || chosen.UDID != "SIX" { - t.Fatalf("--device %s chose %+v, %v", requested, chosen, err) - } - } - if _, err := chooseSimulator(devices, "iPhone 99"); err == nil { - t.Fatal("an unknown device was accepted") - } -} - -func TestRunNeedsAnIPhoneSimulator(t *testing.T) { - devices, err := listSimulators([]byte(`{"devices": {"com.apple.CoreSimulator.SimRuntime.iOS-18-5": [{"udid": "PAD", "name": "iPad Pro", "state": "Shutdown"}]}}`)) - if err != nil { - t.Fatal(err) - } - if _, err := chooseSimulator(devices, ""); err == nil { - t.Fatal("no iPhone, and still a device was chosen") - } -} - -func TestIOSBuildChecks(t *testing.T) { - err := checkIOS(buildFlags{target: "ios-sim", arch: "arm64"}) - if runtime.GOOS != "darwin" { - // Only a Mac has Xcode: the check says so before anything else. - if err == nil { - t.Fatal("an iOS build was accepted on a host without Xcode") - } - return - } - if err != nil { - t.Fatalf("a simulator build was refused on a Mac: %v", err) - } - if checkIOS(buildFlags{target: "ios", arch: "amd64"}) == nil { - t.Error("an amd64 device build was accepted; devices run arm64") - } - if checkIOS(buildFlags{target: "ios-sim", arch: "arm64", cgo: true}) == nil { - t.Error("--cgo was accepted for iOS, which always uses cgo") - } -} - -// An iOS build compiles the Objective-C bridge against the SDK of its target: -// the environment must name the SDK, the architecture and, for the simulator -// only, the simulator. -func TestIOSEnvironmentPointsCgoAtTheSDK(t *testing.T) { - for _, test := range []struct { - target, arch, triple string - simulator bool - }{ - {"ios-sim", "arm64", "arm64-apple-ios" + iosMinSystem + "-simulator", true}, - {"ios-sim", "amd64", "x86_64-apple-ios" + iosMinSystem + "-simulator", true}, - {"ios", "arm64", "arm64-apple-ios" + iosMinSystem, false}, - } { - plan := buildPlan{target: test.target, arch: test.arch, toolchain: iosToolchain{clang: "/x/clang", sdk: "/x/SDK.sdk"}} - environment := plan.environment([]string{"CGO_CFLAGS=-O2"}) - for _, want := range []string{"GOOS=ios", "GOARCH=" + test.arch, "CGO_ENABLED=1"} { - if !slices.Contains(environment, want) { - t.Errorf("%s/%s: environment lacks %s", test.target, test.arch, want) - } - } - for _, name := range []string{"CC", "CGO_CFLAGS", "CGO_LDFLAGS"} { - value := lastEnvironment(environment, name) - if !strings.Contains(value, "-isysroot /x/SDK.sdk") || !strings.Contains(value, "-target "+test.triple) { - t.Errorf("%s/%s: %s = %q, want the SDK and target %s", test.target, test.arch, name, value, test.triple) - } - if strings.HasSuffix(test.triple, "-simulator") != test.simulator { - t.Errorf("test table disagrees with itself for %s", test.target) - } - } - if value := lastEnvironment(environment, "CGO_CFLAGS"); !strings.Contains(value, "-O2") { - t.Errorf("%s: the developer's CGO_CFLAGS were dropped: %q", test.target, value) - } - } -} - -// The simulator's app and the device's do not overwrite each other, and both -// are bundles, not files. -func TestIOSOutputsAreSeparateBundles(t *testing.T) { - dir := fixture(t, notesTOML) - var outputs []string - for _, target := range []string{"ios-sim", "ios"} { - plan := buildPlan{manifest: loadPlan(t, dir, buildFlags{target: runtime.GOOS}, "").manifest, target: target, arch: "arm64", executable: "notes"} - if err := plan.outputPath(""); err != nil { - t.Fatal(err) - } - if !strings.HasSuffix(plan.out, ".app") || !strings.HasSuffix(plan.programPath(), "/notes") { - t.Errorf("%s: output %q, program %q", target, plan.out, plan.programPath()) - } - outputs = append(outputs, plan.out) - } - if outputs[0] == outputs[1] { - t.Fatalf("both targets write to %s", outputs[0]) - } -} - -func TestPackagingRefusesIOS(t *testing.T) { - dir := fixture(t, notesTOML) - if err := run([]string{"package", "-C", dir, "--target", "ios-sim"}, new(strings.Builder)); err == nil { - t.Fatal("package accepted an iOS target") - } -} diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index a2dcd15b3..e0ec01fd9 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -155,6 +155,11 @@ type DropdownMenuOptions struct { // Submenu makes this the content of a submenu, which has a smaller minimum // width (96) than a menu opened by a trigger (128). Submenu bool + // RowHeight is the height of an item row; zero is the theme's control height, + // and a row with a description stays as tall as the description needs. It is + // ContextMenuOptions.RowHeight for a menu a trigger opens instead of a point: + // the same rows, sized the same way. + RowHeight float32 // Unpainted declares the menu's behavior, size and rows but paints none of // it: PaintPanel draws the surface and PaintItem draws each row, both inside // the menu's layer, clipping and focus scope. Hits, focus, the keyboard and @@ -163,6 +168,9 @@ type DropdownMenuOptions struct { Unpainted bool PaintPanel func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) PaintItem func(MenuItemPaint) + // MaxWidth caps the surface width, including its default minimum. Zero + // keeps the default minimum and leaves the width unbounded. + MaxWidth float32 } // DropdownMenuItem describes one stable menu action. @@ -216,6 +224,15 @@ func DropdownMenuItemHeight(theme gfx.Theme, item DropdownMenuItem) float32 { return menuItemHeight(theme, item.common(), 0) } +// DropdownMenuItemHeightFor is DropdownMenuItemHeight for a menu whose rows are +// rowHeight high — DropdownMenuOptions.RowHeight — instead of the theme's control +// height. Zero keeps the theme's, and a row with a description stays as tall as +// the description needs, exactly as AddItem reserves it, so a caller that lays a +// menu out from its rows measures them with this. +func DropdownMenuItemHeightFor(theme gfx.Theme, item DropdownMenuItem, rowHeight float32) float32 { + return menuItemHeight(theme, item.common(), rowHeight) +} + // The heights AddLabel and AddSeparator reserve, and the padding of the surface // around its rows: a menu's bounds are as tall as its rows and twice the padding. const ( @@ -232,16 +249,20 @@ type DropdownMenu struct { // BeginDropdownMenu paints an open menu using caller-owned layer, focus scope, // and Escape action identities. Bounds are normalized to Vega's 8rem minimum -// (6rem for a submenu). +// (6rem for a submenu), subject to MaxWidth. func BeginDropdownMenu(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, options DropdownMenuOptions) DropdownMenu { minWidth := float32(128) if options.Submenu { minWidth = 96 } + if options.MaxWidth > 0 { + minWidth = min(minWidth, options.MaxWidth) + bounds.Width = min(bounds.Width, options.MaxWidth) + } return DropdownMenu{surface: beginMenuSurface(canvas, theme, bounds, minWidth, menuSurfaceOptions{ layer: options.Layer, scope: options.Scope, dismissID: options.DismissID, viewport: options.Viewport, scroll: options.Scroll, key: overlayKey(options.ID, options.DismissID, options.Scope), side: options.Side, submenu: options.Submenu, - labelMuted: true, tabCloses: true, + labelMuted: true, tabCloses: true, rowHeight: options.RowHeight, unpainted: options.Unpainted, paintPanel: options.PaintPanel, paintItem: options.PaintItem, })} } diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index cbfbd441c..28d413eff 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -155,6 +155,11 @@ type DropdownMenuOptions struct { // Submenu makes this the content of a submenu, which has a smaller minimum // width (96) than a menu opened by a trigger (128). Submenu bool + // RowHeight is the height of an item row; zero is the theme's control height, + // and a row with a description stays as tall as the description needs. It is + // ContextMenuOptions.RowHeight for a menu a trigger opens instead of a point: + // the same rows, sized the same way. + RowHeight float32 // Unpainted declares the menu's behavior, size and rows but paints none of // it: PaintPanel draws the surface and PaintItem draws each row, both inside // the menu's layer, clipping and focus scope. Hits, focus, the keyboard and @@ -163,6 +168,9 @@ type DropdownMenuOptions struct { Unpainted bool PaintPanel func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) PaintItem func(MenuItemPaint) + // MaxWidth caps the surface width, including its default minimum. Zero + // keeps the default minimum and leaves the width unbounded. + MaxWidth float32 } // DropdownMenuItem describes one stable menu action. @@ -216,6 +224,15 @@ func DropdownMenuItemHeight(theme gfx.Theme, item DropdownMenuItem) float32 { return menuItemHeight(theme, item.common(), 0) } +// DropdownMenuItemHeightFor is DropdownMenuItemHeight for a menu whose rows are +// rowHeight high — DropdownMenuOptions.RowHeight — instead of the theme's control +// height. Zero keeps the theme's, and a row with a description stays as tall as +// the description needs, exactly as AddItem reserves it, so a caller that lays a +// menu out from its rows measures them with this. +func DropdownMenuItemHeightFor(theme gfx.Theme, item DropdownMenuItem, rowHeight float32) float32 { + return menuItemHeight(theme, item.common(), rowHeight) +} + // The heights AddLabel and AddSeparator reserve, and the padding of the surface // around its rows: a menu's bounds are as tall as its rows and twice the padding. const ( @@ -232,16 +249,20 @@ type DropdownMenu struct { // BeginDropdownMenu paints an open menu using caller-owned layer, focus scope, // and Escape action identities. Bounds are normalized to Vega's 8rem minimum -// (6rem for a submenu). +// (6rem for a submenu), subject to MaxWidth. func BeginDropdownMenu(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, options DropdownMenuOptions) DropdownMenu { minWidth := float32(128) if options.Submenu { minWidth = 96 } + if options.MaxWidth > 0 { + minWidth = min(minWidth, options.MaxWidth) + bounds.Width = min(bounds.Width, options.MaxWidth) + } return DropdownMenu{surface: beginMenuSurface(canvas, theme, bounds, minWidth, menuSurfaceOptions{ layer: options.Layer, scope: options.Scope, dismissID: options.DismissID, viewport: options.Viewport, scroll: options.Scroll, key: overlayKey(options.ID, options.DismissID, options.Scope), side: options.Side, submenu: options.Submenu, - labelMuted: true, tabCloses: true, + labelMuted: true, tabCloses: true, rowHeight: options.RowHeight, unpainted: options.Unpainted, paintPanel: options.PaintPanel, paintItem: options.PaintItem, })} } diff --git a/components/dropdown_menu_rowheight_test.go b/components/dropdown_menu_rowheight_test.go new file mode 100644 index 000000000..e7d6c9557 --- /dev/null +++ b/components/dropdown_menu_rowheight_test.go @@ -0,0 +1,56 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A dropdown menu sizes its rows by DropdownMenuOptions.RowHeight, the way a +// context menu sizes its own by ContextMenuOptions.RowHeight, and falls back to +// the theme's control height when it is zero. +func TestDropdownMenuRowsFollowTheRowHeightOption(t *testing.T) { + compact := gfx.LightTheme() + compact.Metrics = compact.Metrics.WithDensity(gfx.DensityCompact) + for _, test := range []struct { + name string + theme gfx.Theme + rowHeight float32 + want float32 + }{ + {"default density", gfx.LightTheme(), 0, 32}, + {"compact density", compact, 0, 26}, + {"RowHeight wins over the theme", compact, 24, 24}, + } { + t.Run(test.name, func(t *testing.T) { + var canvas gfx.Canvas + menu := BeginDropdownMenu(&canvas, test.theme, gfx.Rect{X: 10, Y: 20, Width: 160, Height: 400}, DropdownMenuOptions{ + Layer: 1, Scope: gfx.Item(2), DismissID: gfx.Item(3), RowHeight: test.rowHeight, + }) + first := menu.AddItem(DropdownMenuItem{ID: gfx.Item(11), Label: "One"}) + second := menu.AddItem(DropdownMenuItem{ID: gfx.Item(12), Label: "Two"}) + if first.Height != test.want || second.Height != test.want || menu.NextItemBounds().Height != test.want { + t.Fatalf("rows = %+v %+v next %+v, want %v high", first, second, menu.NextItemBounds(), test.want) + } + if got := DropdownMenuItemHeightFor(test.theme, DropdownMenuItem{Label: "One"}, test.rowHeight); got != test.want { + t.Fatalf("DropdownMenuItemHeightFor = %v, want %v: the helper a caller lays a menu out with must agree with AddItem", got, test.want) + } + }) + } +} + +// The option packs the rows the menu reserves, not just the ones it paints: a +// separator still takes its own height, and the next row starts right below it. +func TestDropdownMenuRowHeightOptionPacksItemsDenser(t *testing.T) { + var canvas gfx.Canvas + menu := BeginDropdownMenu(&canvas, gfx.LightTheme(), gfx.Rect{X: 10, Y: 20, Width: 160, Height: 4*24 + 9 + 8}, DropdownMenuOptions{ + Layer: 1, Scope: gfx.Item(2), DismissID: gfx.Item(3), RowHeight: 24, + }) + first := menu.AddItem(DropdownMenuItem{ID: gfx.Item(11), Label: "One"}) + menu.AddSeparator() + second := menu.AddItem(DropdownMenuItem{ID: gfx.Item(12), Label: "Two"}) + third := menu.AddItem(DropdownMenuItem{ID: gfx.Item(13), Label: "Three"}) + if first.Height != 24 || second.Y != first.Y+24+DropdownMenuSeparatorHeight || third.Y != second.Y+24 || menu.NextItemBounds().Height != 24 { + t.Fatalf("rows = %+v %+v %+v next %+v", first, second, third, menu.NextItemBounds()) + } +} diff --git a/docs/conformance.md b/docs/conformance.md index bf175450c..4317bb6fb 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -30,6 +30,7 @@ desktop session. | A hidden window stays open and still receives wakes | an application that hides to the status area updates its icon from a window nobody can see | | A hidden window runs `OnWake` but paints nothing until it is shown again | a window nobody can see (hidden, minimized, covered, on another space or desktop, as far as the platform reports it) must not lay out, rasterize and present frames; the frame it missed is painted when it shows again | | A panel opens, paints and closes from another goroutine | `WindowPanel` is a window kind of its own on each backend | +| A notification paints without pointer input and returns to idle | a notification may open while the pointer stays on another window | | A status item can be added, changed and removed (SKIP where the desktop has no status area) | `AddStatusItem` and its setters on three different APIs | | `Quit` ends the loop though windows refuse to close, even as the last-used window closes | the loop must end whatever the windows say | diff --git a/docs/images/textview/README.md b/docs/images/textview/README.md new file mode 100644 index 000000000..485ed5598 --- /dev/null +++ b/docs/images/textview/README.md @@ -0,0 +1,35 @@ +# Textview frames + +These are real Metal/CoreText screenshots of `ui/textview`, captured on macOS +27.3 / arm64 at 800 × 420 logical pixels, scale 2 (1600 × 840 PNGs). Both Viva +themes use the same English and Chinese content, with combining accents, emoji +sequences, a flag and an Indic conjunct in the Unicode scene. + +From the repository root, capture the current implementation with: + +```sh +VIVA_TEXTVIEW_SHOTS="$PWD/build/textview-review/after" \ + go test -tags vivahead ./ui/textview -run '^TestVisualCapture$' -count=1 -timeout=60s -v +``` + +`TestVisualCapture` opens no native window and closes every headless session. Its +Unicode scene has no selection. Its sibling scene double-clicks `Second` in the +second plain view, then right-clicks line 1 in the second scrollable view. It also +declares a button after the two views with context menus and checks strict control +identity before saving the frame. + +- `unicode-before-{light,dark}.png`: production sources from + `0e17e516264fdb0a102cca3d2fcc4d2a8807c5a7`, captured with the same Unicode scene. + For the comparison, those five source files were copied unchanged to the ignored + `build/textview-review/before` package and the capture test's import pointed there. +- `unicode-after-{light,dark}.png`: the implementation and capture test in this commit. +- `siblings-menu-{light,dark}.png`: the implementation and capture test in this commit. + The old implementation panics before this scene's first frame, so it has no + corresponding before image; `TestClosedMenusLeaveTheNextSiblingsIdentityAlone` + reproduces the panic on the old implementation. + +The comparison shows the retained accent, joined emoji and flag, and shaped Indic +conjunct. Cell advances still use the sum of Viva's `text.CellWidth` values, so an +emoji sequence can occupy more grid space than its visible glyph. This change does +not redefine Viva's fixed-pitch grid. These captures do not establish native +window, clipboard or accessibility integration on any desktop platform. diff --git a/docs/images/textview/siblings-menu-dark.png b/docs/images/textview/siblings-menu-dark.png new file mode 100644 index 000000000..409df2cd0 Binary files /dev/null and b/docs/images/textview/siblings-menu-dark.png differ diff --git a/docs/images/textview/siblings-menu-light.png b/docs/images/textview/siblings-menu-light.png new file mode 100644 index 000000000..3845dd4f1 Binary files /dev/null and b/docs/images/textview/siblings-menu-light.png differ diff --git a/docs/images/textview/unicode-after-dark.png b/docs/images/textview/unicode-after-dark.png new file mode 100644 index 000000000..d06960b25 Binary files /dev/null and b/docs/images/textview/unicode-after-dark.png differ diff --git a/docs/images/textview/unicode-after-light.png b/docs/images/textview/unicode-after-light.png new file mode 100644 index 000000000..7caabb6d0 Binary files /dev/null and b/docs/images/textview/unicode-after-light.png differ diff --git a/docs/images/textview/unicode-before-dark.png b/docs/images/textview/unicode-before-dark.png new file mode 100644 index 000000000..ad4a7dc1b Binary files /dev/null and b/docs/images/textview/unicode-before-dark.png differ diff --git a/docs/images/textview/unicode-before-light.png b/docs/images/textview/unicode-before-light.png new file mode 100644 index 000000000..570e70dca Binary files /dev/null and b/docs/images/textview/unicode-before-light.png differ diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index fce0089ca..ba5c82e52 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -44,7 +44,7 @@ There are two authoring paths, and they are not duplicates: may keep Begin are pure measurement, whole-canvas drawing, pixel-fixed slots and copied source. See `private/docs/decisions/0085-begin-stays-in-components.md`. -Opt-in page packages live under `ui/` (`ui/textview`, `ui/codeeditor`, `ui/chart`, +Opt-in page packages live under `ui/` (`ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/calendar`, `ui/carousel`, `ui/markdown`, `ui/columnresize`, `ui/avatareditor`, `ui/reordergrid`, `ui/avatar`, `ui/attachment`, `ui/message`, `ui/messagescroller`, `ui/command`, `ui/menubar`, @@ -60,6 +60,11 @@ imported by package `ui`; importing one is the explicit opt-in. Do not add a new directory at the repository root for a page widget. See `private/docs/decisions/0086-opt-in-page-views.md`. +`ui/textview` is the read-only selectable output control: keep a `textview.View` +in the model and call its `Declare(c, textview.Spec{Source: lines, ...})` method. +The caller owns the lines, spans and actions; the package owns selection, layout +and input, without a text editor or undo model. + ### Naming and types An opt-in package is named for the capability, never with a `view` suffix: diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index c52920b19..bb1928e7b 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -89,7 +89,8 @@ func (m *model) page(c ui.C) { ### Optional page packages and custom surfaces - A heavy or stateful page control lives in an opt-in package under `ui/`; import it only when the page uses it. -- Editors and visuals: `ui/textview`, `ui/codeeditor`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`. +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`. +- For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. - The package name is the capability, never a `view` suffix. Name its state type by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`, `hovercard.Card`. Keep locals out of the package name (`cal`, `msg`, `pic`); a model field may keep the domain noun (`m.calendar`). - Some packages expose `pkg.View(c, label, &state)` (`calendar.View`, `markdown.View`); others expose a method on the state (`avatar.New().View(c, label)`, `questionnaire.New().View(c, label)`). `go doc github.com/vivaui/viva/ui/` shows which. - A page control can sit inside a `ui.Slot` at the rectangle a component painted: keep the slot's size, declare the control with `.Absolute().Left(0).Top(0).Size(...).Hit(id, label)`, and bind a copy when the application's dispatcher owns the value. `ui/slot_parity_test.go` keeps this exact for Checkbox, Switch and FormField. diff --git a/docs/system-integrations.md b/docs/system-integrations.md index 3eaf4fb8b..e1b1ff528 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -36,7 +36,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | 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 | | 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`) | CFNetwork's settings for the URL: the static HTTP, HTTPS or SOCKS proxy with its bypass list. A PAC script is reported as `ErrSystemProxyUnavailable`, not silently bypassed | 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 | `ErrSystemProxyUnavailable` | +| 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` | | Window title (`SetTitle`) | `NSWindow.title`, the text the window list and Mission Control show | `SetWindowTextW`, applied on the window thread | `WM_NAME` and `_NET_WM_NAME` on X11; `gtk_window_set_title` on the GTK shell | `ErrUnsupported`: the page keeps its own title | | Page visibility (`OnMinimize`) | window minimized/restored | window minimized/restored | window minimized/restored | `visibilitychange`; a hidden tab counts as minimized | diff --git a/examples/touch/main.go b/examples/touch/main.go index e3871cd59..9dc141ecb 100644 --- a/examples/touch/main.go +++ b/examples/touch/main.go @@ -1,7 +1,9 @@ -// Touch is the page a phone is checked with: what a finger does to each kind of control. -// A long list scrolls under a finger and keeps going when it lifts; a tap presses; a -// finger held on a row opens its menu; a slider takes a moving finger as a drag; and a -// field brings the keyboard. The same page runs with a mouse on a desktop. +// Touch is the page a touch screen is checked with: what a finger does to each kind of +// control. A long list scrolls under a finger, keeps going when it lifts and gives at its +// ends; a tap presses; a finger held on a row opens its menu, and on a control with a +// tooltip shows it; a slider takes a moving finger as a drag; a tap in a field puts the +// caret there and a held finger selects a word; and two fingers pinch the zoom. The same +// page runs with a mouse. package main import ( @@ -9,6 +11,7 @@ import ( "log" "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -21,42 +24,43 @@ type model struct { name string list ui.ListState menu string - // lifecycle is what the system last did to the application: it went to the background, came - // back, or asked for memory. - lifecycle string - // invalidator asks for a new frame after a change the page was not told of. - invalidator *app.Invalidator + // zoom is set by pinching the page. + zoom float32 } func newModel() *model { - m := &model{volume: ui.SliderState{Value: 40}} + m := &model{volume: ui.SliderState{Value: 40}, zoom: 1} m.list.Label = func(i int) string { return fmt.Sprintf("Row %d", i+1) } return m } +// pinched is two fingers pinching the page: the zoom follows how far apart they go. +func (m *model) pinched(event gfx.PinchEvent) gfx.EventResult { + if event.Phase == gfx.PinchChange { + m.zoom = min(max(m.zoom*event.Delta, 0.5), 4) + } + return gfx.EventResult{Handled: true, Repaint: true} +} + func (m *model) page(c ui.C) { - ui.SafeArea(c).Children(func() { - ui.Column(c).Fill().Pad(16).Gap(12).Items(ui.Stretch).Children(func() { - ui.Row(c).Gap(12).Items(ui.Center).Children(func() { - if ui.Button(c, "Tap me").Tooltip("Counts your taps").Clicked() { - m.taps++ - } - ui.Text(c, fmt.Sprintf("Tapped %d times", m.taps)) - }) - ui.Row(c).Gap(12).Items(ui.Center).Children(func() { - ui.Text(c, fmt.Sprintf("Volume %.0f", m.volume.Value)) - ui.Slider(c, &m.volume).Width(220).Step(1) - }) - ui.Switch(c, &m.notify, "Notifications") - ui.TextField(c, &m.name, "Name", "Your name").Width(320) - if m.menu != "" { - ui.Text(c, m.menu).Muted() + ui.Column(c).Fill().Pad(16).Gap(12).Items(ui.Stretch).Children(func() { + ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + if ui.Button(c, "Tap me").Tooltip("Counts your taps").Clicked() { + m.taps++ } - if m.lifecycle != "" { - ui.Text(c, "System: "+m.lifecycle).Muted() - } - ui.List(c, &m.list, rows, m.row).Label("Rows").Grow(1) + ui.Text(c, fmt.Sprintf("Tapped %d times", m.taps)) + ui.Text(c, fmt.Sprintf("Zoom %.2f", m.zoom)).Muted() + }) + ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + ui.Text(c, fmt.Sprintf("Volume %.0f", m.volume.Value)) + ui.Slider(c, &m.volume).Width(220).Step(1) }) + ui.Switch(c, &m.notify, "Notifications") + ui.TextField(c, &m.name, "Name", "Your name").Width(320) + if m.menu != "" { + ui.Text(c, m.menu).Muted() + } + ui.List(c, &m.list, rows, m.row).Label("Rows").Grow(1) }) } @@ -79,24 +83,10 @@ func (m *model) row(r ui.ListRow) { }) } -// systemChanged notes what the system did; the next frame shows it. -func (m *model) systemChanged(event app.LifecycleEvent) { - switch event { - case app.LifecycleBackground: - m.lifecycle = "background" - case app.LifecycleForeground: - m.lifecycle = "foreground" - case app.LifecycleMemoryWarning: - m.lifecycle = "memory warning" - } - m.invalidator.Invalidate() -} - func main() { m := newModel() - m.invalidator = new(app.Invalidator) - config := app.Config{Title: "Touch", Width: 420, Height: 760, OnLifecycle: m.systemChanged} - if err := ui.Run(config, ui.PageConfig{View: m.page, Invalidator: m.invalidator}); err != nil { + config := app.Config{Title: "Touch", Width: 420, Height: 760, OnPinch: m.pinched} + if err := ui.Run(config, ui.PageConfig{View: m.page}); err != nil { log.Fatal(err) } } diff --git a/examples/touch/main_test.go b/examples/touch/main_test.go index b68e57b5f..78c667ae2 100644 --- a/examples/touch/main_test.go +++ b/examples/touch/main_test.go @@ -280,45 +280,6 @@ func TestAHeldFingerOnAControlWithAMenuShowsNoTooltip(t *testing.T) { } } -// A page keeps inside the bars a phone's system draws over its window, and the page's own -// background reaches the edges: the window being told the bars grow moves the content down. -func TestThePageKeepsInsideTheSafeArea(t *testing.T) { - m := newModel() - driver := open(t, m) - before := control(t, driver, "Tap me").Bounds - if err := driver.SetSafeArea(gfx.Insets{Top: 47, Bottom: 34, Left: 10, Right: 10}); err != nil { - t.Fatal(err) - } - after := control(t, driver, "Tap me").Bounds - if after.Y != before.Y+47 || after.X != before.X+10 { - t.Fatalf("the button moved from %v, %v to %v, %v, want 10 right and 47 down", before.X, before.Y, after.X, after.Y) - } - rows := driver.Snapshot().Hits - last := rows[len(rows)-1] - if bottom := last.Bounds.Y + last.Bounds.Height; bottom > 760-34+0.5 { - t.Fatalf("content reaches %v, into the 34 px the home indicator covers", bottom) - } -} - -// What the system does to the application shows on the page once the application says so. -func TestThePageShowsWhatTheSystemDid(t *testing.T) { - m := newModel() - m.invalidator = new(app.Invalidator) - page := ui.NewPage(ui.PageConfig{View: m.page, Invalidator: m.invalidator}) - driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 420, Height: 760, OnLifecycle: m.systemChanged}), nil) - if err != nil { - t.Fatal(err) - } - t.Cleanup(driver.Close) - driver.Lifecycle(app.LifecycleMemoryWarning) - if err := driver.Pump(); err != nil { - t.Fatal(err) - } - if !shown(driver, "System: memory warning") { - t.Fatal("the page does not show the memory warning") - } -} - // typeInName focuses the name field with a tap and types value into it. func typeInName(t *testing.T, driver *app.Driver, value string) gfx.Rect { t.Helper() @@ -351,7 +312,7 @@ func wordX(t *testing.T, driver *app.Driver, word string) float32 { return 0 } -// A finger lifted inside the text puts the caret there, as on a phone; typing goes in +// A finger lifted inside the text puts the caret there; typing goes in // at that point, not at the end. func TestATapPutsTheCaretWhereTheFingerLifts(t *testing.T) { skipWithoutTouchRuntime(t) @@ -398,3 +359,35 @@ func TestAHeldFingerSelectsTheWord(t *testing.T) { t.Fatalf("name = %q after holding on \"world\" and typing, want %q", m.name, "hello there") } } + +// Two fingers moving apart zoom the page, and the first finger's gesture does nothing else. +func TestPinchingZoomsThePage(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + page := ui.NewPage(ui.PageConfig{View: m.page}) + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 420, Height: 760, OnPinch: m.pinched}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + for _, step := range []func() error{ + func() error { return driver.TouchDown(1, 150, 500) }, + func() error { return driver.TouchDown(2, 250, 500) }, + func() error { return driver.TouchMove(2, 350, 500) }, + func() error { return driver.TouchUp(2, 350, 500) }, + func() error { return driver.TouchUp(1, 150, 500) }, + } { + if err := step(); err != nil { + t.Fatal(err) + } + } + if m.zoom < 1.9 || m.zoom > 2.1 { + t.Fatalf("zoom = %v after the fingers went from 100 to 200 apart, want about 2", m.zoom) + } + if !shown(driver, "Zoom 2.00") { + t.Fatal("the page does not show the zoom") + } + if m.taps != 0 || m.list.Selected() >= 0 { + t.Fatalf("a pinch tapped (%d) or chose a row (%d)", m.taps, m.list.Selected()) + } +} diff --git a/gfx/canvas.go b/gfx/canvas.go index b13d945e1..0f2c088eb 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -659,7 +659,7 @@ type Hit struct { IsLabel bool // Backdrop is HitOptions.Backdrop. Backdrop bool - // MovesWindow marks a region of a custom-titlebar window that moves the + // MovesWindow marks a region of a custom-titlebar or notification window that moves the // window when pressed (see Canvas.MoveRegion). It has no ID and no // accessibility node. MovesWindow bool @@ -767,8 +767,6 @@ type Canvas struct { onSurface bool // titlebarLeading and titlebarTrailing are the window's TitlebarInsets. titlebarLeading, titlebarTrailing float32 - // safeArea is the window's SafeArea. - safeArea Insets // touched is set once a finger has touched the window. touched bool // prevHovered is the hit the pointer was on at the end of the previous @@ -1808,8 +1806,8 @@ func (canvas *Canvas) BlockSurface(bounds Rect) { }) } -// MoveRegion declares a place a custom-titlebar window is moved from: pressing -// and dragging it moves the window, and a double click zooms it. It is inert as +// MoveRegion makes a custom-titlebar or notification window draggable there. +// Double-clicking zooms a custom-titlebar window. A move region is inert as // Block is, with no ID, hover, focus or accessibility node, and it lies where it // was declared in paint order: a control declared after it, such as a button of a // tab bar laid over it, takes its own presses, and so does the surface of a dialog @@ -2117,15 +2115,6 @@ func (canvas *Canvas) TitlebarInsets() (leading, trailing float32) { return canvas.titlebarLeading, canvas.titlebarTrailing } -// SafeArea is how far the system covers the edges of the window: the status bar and the -// sensor housing, the home indicator or navigation bar, a cutout or rounded corner. A page -// keeps its content inside of on a phone, where the window runs under the bars. Zero for -// a desktop window. -func (canvas *Canvas) SafeArea() Insets { return canvas.safeArea } - -// SetSafeArea records the window's SafeArea; the runtime calls it before each paint. -func (canvas *Canvas) SetSafeArea(insets Insets) { canvas.safeArea = insets } - // SetTitlebarInsets records the window's TitlebarInsets; the runtime calls it // before each paint. func (canvas *Canvas) SetTitlebarInsets(leading, trailing float32) { diff --git a/gfx/input.go b/gfx/input.go index 81170f49e..4f1125152 100644 --- a/gfx/input.go +++ b/gfx/input.go @@ -208,6 +208,35 @@ type ModifierTapEvent struct { Target ID } +// PinchPhase is where two fingers are in a pinch. +type PinchPhase uint8 + +const ( + // PinchBegin is the second finger touching: Scale is 1. + PinchBegin PinchPhase = iota + 1 + // PinchChange is a finger moving. + PinchChange + // PinchEnd is a finger lifting, or the system taking the pinch away: Scale is what it + // was at the last change. + PinchEnd +) + +// PinchEvent is two fingers held on the window, as they move toward or away from each +// other. X and Y are the midpoint in logical window pixels, which a zoom keeps under the +// fingers. Scale is how far apart the fingers are as a multiple of how far apart they began; +// Delta is the same since the last event, which is what a zoom that multiplies its own +// level takes. Target is the stable hit ID at X, Y. A pinch is no scroll and no press: +// what the first finger was doing ended when the second came. +type PinchEvent struct { + Phase PinchPhase + Modifiers Modifiers + X, Y float32 + Scale float32 + Delta float32 + Viewport Size + Target ID +} + // ScrollEvent is one normalized scroll gesture in logical window pixels. // Target is the stable hit ID at X,Y. Viewport is the current logical window // size, allowing coordinate-driven controls to derive their local geometry. diff --git a/internal/gallery/gallery.go b/internal/gallery/gallery.go index 39276b381..9727058b3 100644 --- a/internal/gallery/gallery.go +++ b/internal/gallery/gallery.go @@ -81,9 +81,7 @@ func Tree() *gfx.Tree { return tree } // the same value so their pixels and behavior originate from one implementation. type State struct { // page is 0 for the catalog and n for catalog[n-1]. - page int - // safe is how far the system covers the window's edges, as of the last paint. - safe gfx.Insets + page int lightMode bool density gfx.Density textEditing bool @@ -268,10 +266,8 @@ func (state *State) dragThumb(event gfx.PointerEvent) gfx.EventResult { // the full window width so the scrollbar sits on the window edge while the // page keeps its side insets. func (state *State) scrollArea(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) components.ScrollArea { - safe := state.safe - viewport := gfx.Rect{X: safe.Left, Y: toolbarHeight + safe.Top, Width: max(size.Width-safe.Left-safe.Right, 0), - Height: max(size.Height-toolbarHeight-safe.Top-safe.Bottom, 0)} - pageHeight := state.contentHeight(max(viewport.Width-pageInset*2, 0)) + viewport := gfx.Rect{Y: toolbarHeight, Width: size.Width, Height: max(size.Height-toolbarHeight, 0)} + pageHeight := state.contentHeight(max(size.Width-pageInset*2, 0)) return components.BeginScrollArea(canvas, theme, viewport, gfx.Size{Width: viewport.Width, Height: pageTopGap + pageHeight + pageBottomGap}). Offset(0, state.viewScroll). VerticalScrollbar(hitPageScrollbar, "Page position", "") @@ -293,7 +289,6 @@ func (state *State) contentHeight(width float32) float32 { func (state *State) Paint(canvas *gfx.Canvas, size gfx.Size) { canvas.SetTree(tree) theme := state.Theme() - state.safe = canvas.SafeArea() width, height := size.Width, size.Height canvas.Fill(gfx.Rect{Width: width, Height: height}, theme.Background) canvas.PushLayer(toolbarLayer) @@ -308,9 +303,9 @@ func (state *State) Paint(canvas *gfx.Canvas, size gfx.Size) { // Write the clamped offset back: a resize or a shorter page may have left // the stored one past the new end. state.viewScroll, state.scrollMax = geometry.OffsetY, geometry.MaxOffsetY - pageWidth := max(width-state.safe.Left-state.safe.Right-pageInset*2, 0) + pageWidth := max(width-pageInset*2, 0) content := gfx.Rect{ - X: state.safe.Left + pageInset, Y: geometry.Content.Y + pageTopGap, + X: pageInset, Y: geometry.Content.Y + pageTopGap, Width: pageWidth, Height: state.contentHeight(pageWidth), } if state.page == 0 { @@ -325,9 +320,8 @@ func (state *State) Paint(canvas *gfx.Canvas, size gfx.Size) { // open one, unless a click in this paint chose another. func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width float32) (page int) { page = state.page - safe := state.safe - canvas.Fill(gfx.Rect{Width: width, Height: toolbarHeight + safe.Top}, theme.Card) - canvas.Fill(gfx.Rect{Y: toolbarHeight + safe.Top - 1, Width: width, Height: 1}, theme.Border) + canvas.Fill(gfx.Rect{Width: width, Height: toolbarHeight}, theme.Card) + canvas.Fill(gfx.Rect{Y: toolbarHeight - 1, Width: width, Height: 1}, theme.Border) // Every element is centered on the bar's own centerline (the area above // its 1px border) at the active density's control height, rather than at @@ -335,23 +329,23 @@ func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width floa // Small size, whose height is exactly the control height; the default // button is four pixels taller and would sit below the centerline. control := theme.Metrics.ControlHeight - top := safe.Top + (toolbarHeight-1-control)/2 + top := (toolbarHeight - 1 - control) / 2 markSize := float32(20) - paintMark(canvas, theme, gfx.Rect{X: safe.Left + pageInset, Y: safe.Top + (toolbarHeight-1-markSize)/2, Width: markSize, Height: markSize}) + paintMark(canvas, theme, gfx.Rect{X: pageInset, Y: (toolbarHeight - 1 - markSize) / 2, Width: markSize, Height: markSize}) // Clicks are read where the control is painted, in the event pass of the // click (see gfx.Canvas.Clicked). - if paintIconButton(canvas, theme, hitPagePrevious, gfx.Rect{X: safe.Left + 72, Y: top, Width: 28, Height: control}, iconChevronLeft, "Previous page") { + if paintIconButton(canvas, theme, hitPagePrevious, gfx.Rect{X: 72, Y: top, Width: 28, Height: control}, iconChevronLeft, "Previous page") { page = (state.page + len(catalog)) % (len(catalog) + 1) } - if paintIconButton(canvas, theme, hitPageNext, gfx.Rect{X: safe.Left + 104, Y: top, Width: 28, Height: control}, iconChevronRight, "Next page") { + if paintIconButton(canvas, theme, hitPageNext, gfx.Rect{X: 104, Y: top, Width: 28, Height: control}, iconChevronRight, "Next page") { page = (state.page + 1) % (len(catalog) + 1) } - labelX := safe.Left + 148 + labelX := float32(148) title := "Components" // On a phone there is no room between the page arrows and the density and theme // buttons for a breadcrumb; the page's own heading already names where you are. - if titleWidth := width - safe.Right - labelX - 210; titleWidth >= 96 { + if titleWidth := width - labelX - 210; titleWidth >= 96 { if state.page != 0 { if components.BeginButton(canvas, theme, hitPageCatalog, gfx.Rect{X: labelX, Y: top, Width: 96}).Small().Ghost("Components").Clicked() { page = 0 @@ -360,11 +354,11 @@ func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width floa title = catalog[state.page-1].Title } canvas.Label(title, gfx.Rect{ - X: labelX, Y: top, Width: max(width-safe.Right-labelX-210, 0), Height: control, + X: labelX, Y: top, Width: max(width-labelX-210, 0), Height: control, }, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.MutedForeground}) } - densityBounds := gfx.Rect{X: width - safe.Right - 190, Y: top, Width: 88} + densityBounds := gfx.Rect{X: width - 190, Y: top, Width: 88} if components.BeginButton(canvas, theme, hitDensityCycle, densityBounds).Small().Ghost(state.densityName()).Clicked() { state.density = (state.density + 1) % 3 } @@ -373,7 +367,7 @@ func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width floa appearance = "Dark" } if components.BeginButton(canvas, theme, hitThemeToggle, gfx.Rect{ - X: width - safe.Right - 92, Y: top, Width: 76, + X: width - 92, Y: top, Width: 76, }).Small().Outline(appearance).Clicked() { state.lightMode = !state.lightMode } diff --git a/internal/interaction/touch.go b/internal/interaction/touch.go index 3febb530a..d14c60f55 100644 --- a/internal/interaction/touch.go +++ b/internal/interaction/touch.go @@ -34,6 +34,20 @@ const ( velocityWindow = 100 * time.Millisecond ) +// PinchPhase is where two fingers are in a pinch. +type PinchPhase uint8 + +const ( + PinchNone PinchPhase = iota + PinchBegin + PinchChange + PinchEnd +) + +// pinchMinDistance is the least the two fingers of a pinch may start apart, in logical +// pixels: closer, the ratio of their distances is noise. +const pinchMinDistance = 24 + type touchPhase uint8 const ( @@ -60,6 +74,13 @@ type TouchStep struct { ScrollX, ScrollY float32 ScrollAtX, ScrollAtY float32 Momentum bool + // Pinch is where two fingers are in a pinch: at its start, as it changes and at its + // end; zero when this step is no part of one. Scale is the distance between the fingers + // as a multiple of what it was at the start, Delta the same since the last step, and + // PinchX, PinchY the midpoint. + Pinch PinchPhase + PinchX, PinchY float32 + PinchScale, PinchDelta float32 // ScrollEnds says the finger that was scrolling lifted or was taken: what it held // past an end of the content is let go. ScrollEnds bool @@ -95,16 +116,35 @@ type Touch struct { flinging bool flingVX, flingVY float32 // the finger's velocity, logical pixels a second flingAt time.Duration + // A pinch is the first finger (id) and a second one (pinchID) held together. + pinching bool + pinchID int32 + pinchAX, pinchAY float32 // where the first finger is + pinchBX, pinchBY float32 // where the second is + pinchStart, pinchLast float32 // the distance between them when it began, and at the last step } // Active reports whether a finger is down or a fling moves. -func (t *Touch) Active() bool { return t.phase != touchIdle || t.flinging } +func (t *Touch) Active() bool { return t.phase != touchIdle || t.flinging || t.pinching } // Down is finger id touching at x, y. claimsDrag says what is under it takes a // moving finger as a drag (a slider, a divider): it presses at once. func (t *Touch) Down(id int32, x, y float32, now time.Duration, claimsDrag bool) TouchStep { + if t.pinching { + return TouchStep{} // a third finger is nothing + } if t.phase != touchIdle && id != t.id { - return t.Cancel() // a second finger is not a press: the first one's gesture ends + // A second finger is not a press: the first one's gesture ends, and the two are a pinch. + ax, ay := t.lastX, t.lastY + step := t.Cancel() + if distance := float32(math.Hypot(float64(x-ax), float64(y-ay))); distance >= pinchMinDistance { + t.pinching, t.pinchID = true, id + t.pinchAX, t.pinchAY, t.pinchBX, t.pinchBY = ax, ay, x, y + t.pinchStart, t.pinchLast = distance, distance + step.Pinch, step.PinchX, step.PinchY = PinchBegin, (ax+x)/2, (ay+y)/2 + step.PinchScale, step.PinchDelta = 1, 1 + } + return step } t.flinging = false t.phase, t.id, t.down = touchPending, id, now @@ -120,6 +160,9 @@ func (t *Touch) Down(id int32, x, y float32, now time.Duration, claimsDrag bool) // Move is finger id moving to x, y. func (t *Touch) Move(id int32, x, y float32, now time.Duration) TouchStep { + if t.pinching { + return t.pinchMove(id, x, y) + } if t.phase == touchIdle || id != t.id { return TouchStep{} } @@ -146,6 +189,13 @@ func (t *Touch) Move(id int32, x, y float32, now time.Duration) TouchStep { // Up is finger id lifting at x, y. func (t *Touch) Up(id int32, x, y float32, now time.Duration) TouchStep { + if t.pinching { + if id != t.id && id != t.pinchID { + return TouchStep{} + } + step := t.pinchMove(id, x, y) + return t.endPinch(step) + } if t.phase == touchIdle || id != t.id { return TouchStep{} } @@ -173,6 +223,9 @@ func (t *Touch) Up(id int32, x, y float32, now time.Duration) TouchStep { // Cancel ends what the finger was doing without a click: the platform took it, // or a second finger came. func (t *Touch) Cancel() TouchStep { + if t.pinching { + return t.endPinch(TouchStep{}) + } phase := t.phase t.phase, t.pressDue, t.longPressDue, t.flinging = touchIdle, false, false, false if phase == touchPanning { @@ -208,6 +261,42 @@ func (t *Touch) Advance(now time.Duration) TouchStep { // stops. func (t *Touch) FlingBlocked() { t.flinging = false } +// pinchMove follows one of the two fingers of a pinch and says how far apart they are now. +func (t *Touch) pinchMove(id int32, x, y float32) TouchStep { + switch id { + case t.id: + t.pinchAX, t.pinchAY = x, y + case t.pinchID: + t.pinchBX, t.pinchBY = x, y + default: + return TouchStep{} + } + distance := float32(math.Hypot(float64(t.pinchBX-t.pinchAX), float64(t.pinchBY-t.pinchAY))) + step := TouchStep{ + Pinch: PinchChange, PinchX: (t.pinchAX + t.pinchBX) / 2, PinchY: (t.pinchAY + t.pinchBY) / 2, + PinchScale: distance / t.pinchStart, PinchDelta: 1, + } + if t.pinchLast > 0 { + step.PinchDelta = distance / t.pinchLast + } + t.pinchLast = distance + return step +} + +// endPinch ends a pinch where the fingers last were: the finger that is left is no gesture. +func (t *Touch) endPinch(step TouchStep) TouchStep { + scale := float32(1) + if t.pinchStart > 0 { + scale = t.pinchLast / t.pinchStart + } + step.Pinch = PinchEnd + step.PinchX, step.PinchY = (t.pinchAX+t.pinchBX)/2, (t.pinchAY+t.pinchBY)/2 + step.PinchScale, step.PinchDelta = scale, 1 + t.pinching = false + t.phase = touchIdle + return step +} + func (t *Touch) press(now time.Duration) TouchStep { t.phase, t.pressDue = touchPressed, false step := TouchStep{Press: true, X: t.lastX, Y: t.lastY, Clicks: t.tapCount(t.lastX, t.lastY, now)} diff --git a/internal/interaction/touch_pinch_test.go b/internal/interaction/touch_pinch_test.go new file mode 100644 index 000000000..007aa73e6 --- /dev/null +++ b/internal/interaction/touch_pinch_test.go @@ -0,0 +1,105 @@ +package interaction + +import ( + "math" + "testing" + "time" +) + +func near(a, b float32) bool { return math.Abs(float64(a-b)) < 1e-4 } + +// Two fingers held together are a pinch: it begins where they are, follows how far apart +// they go as a multiple of the start and a factor since the last step, and ends where they +// were when one lifts. +func TestTwoFingersPinch(t *testing.T) { + var touch Touch + now := time.Duration(0) + touch.Down(1, 100, 200, now, false) + begin := touch.Down(2, 200, 200, now, false) + if begin.Pinch != PinchBegin || begin.PinchX != 150 || begin.PinchY != 200 || begin.PinchScale != 1 { + t.Fatalf("begin = %+v, want a pinch at 150, 200 with scale 1", begin) + } + if !touch.Active() { + t.Fatal("a pinch is a gesture in progress") + } + change := touch.Move(2, 300, 200, now) // 100 apart became 200 + if change.Pinch != PinchChange || !near(change.PinchScale, 2) || !near(change.PinchDelta, 2) || change.PinchX != 200 { + t.Fatalf("change = %+v, want scale 2 and delta 2 around x 200", change) + } + again := touch.Move(1, 50, 200, now) // 250 apart: 1.25 of the 200 + if !near(again.PinchScale, 2.5) || !near(again.PinchDelta, 1.25) { + t.Fatalf("again = %+v, want scale 2.5 and delta 1.25", again) + } + end := touch.Up(2, 300, 200, now) + if end.Pinch != PinchEnd || !near(end.PinchScale, 2.5) { + t.Fatalf("end = %+v, want the pinch to end at scale 2.5", end) + } + if touch.Active() { + t.Fatal("the pinch is over") + } +} + +// What is left after a pinch is no gesture: the finger that stays down neither presses nor +// scrolls, and the next touch starts fresh. +func TestTheFingerLeftAfterAPinchIsNoGesture(t *testing.T) { + var touch Touch + now := time.Duration(0) + touch.Down(1, 100, 200, now, false) + touch.Down(2, 200, 200, now, false) + touch.Up(2, 200, 200, now) + for _, step := range []TouchStep{touch.Move(1, 100, 400, now), touch.Up(1, 100, 400, now), touch.Advance(now + time.Second)} { + if step.Press || step.Release || step.Scrolls() || step.Pinch != PinchNone { + t.Fatalf("the finger left after a pinch did something: %+v", step) + } + } + if step := touch.Down(3, 10, 10, now+2*time.Second, false); !step.Wake { + t.Fatalf("a new touch after a pinch did not start a gesture: %+v", step) + } +} + +// The first finger's gesture ends when the second comes: a press is released without a click, +// and a pan stops. +func TestAPinchEndsWhatTheFirstFingerWasDoing(t *testing.T) { + var touch Touch + now := time.Duration(0) + touch.Down(1, 100, 100, now, true) // a slider: pressed at once + step := touch.Down(2, 300, 100, now, false) + if !step.Cancel || step.Release || step.Pinch != PinchBegin { + t.Fatalf("second finger on a pressed control: %+v, want the press cancelled, no click, and a pinch", step) + } + touch = Touch{} + touch.Down(1, 100, 100, now, false) + touch.Move(1, 100, 180, now) + step = touch.Down(2, 300, 180, now, false) + if !step.ScrollEnds || step.Pinch != PinchBegin { + t.Fatalf("second finger during a pan: %+v, want the pan ended and a pinch", step) + } +} + +// Two fingers that start too close have no ratio to speak of: they are not a pinch, and a +// third finger is nothing. +func TestFingersTooCloseAreNoPinchAndAThirdIsNothing(t *testing.T) { + var touch Touch + now := time.Duration(0) + touch.Down(1, 100, 100, now, false) + if step := touch.Down(2, 105, 100, now, false); step.Pinch != PinchNone { + t.Fatalf("fingers 5 px apart began a pinch: %+v", step) + } + touch = Touch{} + touch.Down(1, 100, 100, now, false) + touch.Down(2, 200, 100, now, false) + if step := touch.Down(3, 150, 150, now, false); step != (TouchStep{}) { + t.Fatalf("a third finger did something: %+v", step) + } +} + +func TestCancelEndsAPinch(t *testing.T) { + var touch Touch + now := time.Duration(0) + touch.Down(1, 100, 100, now, false) + touch.Down(2, 200, 100, now, false) + touch.Move(2, 250, 100, now) + if step := touch.Cancel(); step.Pinch != PinchEnd || touch.Active() { + t.Fatalf("cancel of a pinch: %+v active=%v", step, touch.Active()) + } +} diff --git a/internal/platform/android/accessibility_android.go b/internal/platform/android/accessibility_android.go deleted file mode 100644 index e9001b4e9..000000000 --- a/internal/platform/android/accessibility_android.go +++ /dev/null @@ -1,123 +0,0 @@ -//go:build android - -package android - -/* -#include "jni_android.h" -*/ -import "C" - -import ( - "unsafe" - - "github.com/vivaui/viva/internal/platform" -) - -// The flags of a node, as the host's Accessibility reads them. -const ( - a11yFocused = 1 << iota - a11yDisabled - a11yChecked - a11yMixed - a11ySelected - a11yExpanded - a11yMultiline - a11yReadOnly - a11yInvalid - a11ySecure - a11yFocusable - a11yExpandable - a11yHasRange -) - -func a11yFlags(node platform.AccessibilityNode) int32 { - var flags int32 - for _, flag := range []struct { - on bool - bit int32 - }{ - {node.Focused, a11yFocused}, {node.Disabled, a11yDisabled}, {node.Checked, a11yChecked}, {node.Mixed, a11yMixed}, - {node.Selected, a11ySelected}, {node.Expanded, a11yExpanded}, {node.Multiline, a11yMultiline}, {node.ReadOnly, a11yReadOnly}, - {node.Invalid, a11yInvalid}, {node.Secure, a11ySecure}, {node.Focusable, a11yFocusable}, {node.Expandable, a11yExpandable}, - {node.Range.Set, a11yHasRange}, - } { - if flag.on { - flags |= flag.bit - } - } - return flags -} - -// pushTree gives the host the accessibility tree a screen reader reads, in the window's -// pixels. The nodes are the application's to reuse after this returns, so what is kept is -// the place of each in the tree, which is what a request of the screen reader names. -func (win *window) pushTree(nodes []platform.AccessibilityNode) { - count := len(nodes) - win.treeIDs = win.treeIDs[:0] - bounds := make([]float32, 0, 4*count) - ints := make([]int32, 0, 5*count) - ranges := make([]float32, 0, 3*count) - offsets := make([]int32, 0, 4*count+1) - var chars []uint16 - scale := win.density - for _, node := range nodes { - win.treeIDs = append(win.treeIDs, node.ID) - bounds = append(bounds, node.X*scale, node.Y*scale, node.Width*scale, node.Height*scale) - ints = append(ints, int32(node.Role), a11yFlags(node), int32(node.Level), node.PosInSet, node.SetSize) - ranges = append(ranges, float32(node.Range.Min), float32(node.Range.Max), float32(node.Range.Now)) - for _, text := range [4]string{node.Label, node.Value, node.Hint, node.Description} { - offsets = append(offsets, int32(len(chars))) - chars = append(chars, utf16Units(text)...) - } - } - offsets = append(offsets, int32(len(chars))) - var boundsPointer, rangesPointer *C.float - var intsPointer *C.int32_t - var charsPointer *C.uint16_t - if count > 0 { - boundsPointer = (*C.float)(unsafe.Pointer(&bounds[0])) - intsPointer = (*C.int32_t)(unsafe.Pointer(&ints[0])) - rangesPointer = (*C.float)(unsafe.Pointer(&ranges[0])) - } - if len(chars) > 0 { - charsPointer = (*C.uint16_t)(unsafe.Pointer(&chars[0])) - } - C.viva_host_tree(C.int(count), boundsPointer, intsPointer, rangesPointer, charsPointer, C.int(len(chars)), (*C.int32_t)(unsafe.Pointer(&offsets[0]))) -} - -// accessibilityState follows a screen reader starting or stopping. Starting, the program -// asks the application for the tree it has, as frames carry it only when it changes. -func (application *application) accessibilityState(on bool) { - win := application.window - if win == nil || win.closed { - return - } - win.a11y = on - if on && win.config.AccessibilityTree != nil { - win.pushTree(win.config.AccessibilityTree()) - } -} - -// accessible carries out a screen reader's request of the node at index in the tree last -// sent, and shows what the application paints for it. -func (application *application) accessible(ev event) { - win := application.window - if win == nil || win.closed || win.config.OnAccessibility == nil || ev.index < 0 || int(ev.index) >= len(win.treeIDs) { - return - } - defer application.guard() - action := [...]platform.AccessibilityAction{ - 1: platform.AccessibilityPress, 2: platform.AccessibilityFocus, 3: platform.AccessibilityIncrement, - 4: platform.AccessibilityDecrement, 5: platform.AccessibilitySetNumber, 6: platform.AccessibilitySetText, - 7: platform.AccessibilitySetSelection, - } - if ev.action < 1 || int(ev.action) >= len(action) { - return - } - request := platform.AccessibilityRequest{ - Node: win.treeIDs[ev.index], Action: action[ev.action], Number: float64(ev.dx), Text: ev.text, Start: ev.start, End: ev.end, - } - if _, err := win.config.OnAccessibility(request, win.present); err != nil { - application.fail(err) - } -} diff --git a/internal/platform/android/android.go b/internal/platform/android/android.go deleted file mode 100644 index 50b718a07..000000000 --- a/internal/platform/android/android.go +++ /dev/null @@ -1,660 +0,0 @@ -//go:build android - -// Package android runs a Viva program in an Android process. The program is a shared -// library loaded by the host's Activity (hostsrc): the host owns the UI thread, the -// surface and the input method, and the program draws on the surface with Vulkan from -// a thread of its own. What happens on the UI thread reaches the program as events on -// a queue, and the program is idle, with no timer and no wake-up, until one comes. -package android - -/* -#include -#include "jni_android.h" -*/ -import "C" - -import ( - "errors" - "fmt" - "runtime" - "sync" - "sync/atomic" - "unsafe" - - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/platform/vulkan" -) - -// eventKind is what the host reports. -type eventKind uint8 - -const ( - eventSurface eventKind = iota + 1 // a surface, of a size, on a display of a density - eventSurfaceLost // the surface is going away: let go of it, then answer - eventTouch // a finger, a pen or a mouse - eventVisible // the activity is in front or behind - eventLowMemory // the system is short of memory - eventClose // the user asked to close the window - eventWake // something was posted - eventRedraw // the application asked for a frame - eventText // the input method edits the text input - eventKey // a key of a keyboard - eventHover // a mouse over the surface - eventHoverExit // the mouse left it - eventScroll // a wheel - eventAppearance // the theme, the language or the animation setting may have changed - eventAccessibility // a screen reader started or stopped - eventAccessible // a screen reader asks something of a node - eventInsets // the system bars, the cutout or the keyboard cover other edges - eventLifecycle // the activity went to the background or came back - eventRedrawNeeded // the system shows the surface once a frame is on it: draw one, then answer -) - -// event is one thing that happened, small enough to queue by value. -type event struct { - kind eventKind - surface *C.ANativeWindow - width int32 - height int32 - density float32 - // A touch: the Android action, the pointer's id, where, the tool, the buttons - // held, the modifier state and when. - action, pointer, tool, buttons, modifiers int32 - x, y float32 - time int64 - // ack is answered once the program no longer uses the surface it is told to let go of, - // or has applied the edit it was sent. - ack chan struct{} - // edit is eventText's operation. - edit edit - // A key: its Android code, the character it types and whether it repeats; the modifiers - // are modifiers above. A scroll's distances are dx and dy. - keyCode, unicode int32 - repeat bool - dx, dy float32 - // An accessibility request: the node (an index of the tree last sent), the action (above), the - // text and the span; the number is dx. - index int32 - text string - start, end int32 - // visible is eventVisible's state. - visible bool -} - -// queue is the events from the host, in order. Moves of a finger may be dropped when -// the program falls behind; nothing else is. -var queue = make(chan event, 1024) - -// send queues an event for the program. -func send(ev event) { queue <- ev } - -// sendMove queues a finger's move, unless the program is so far behind that there -// are no more places: the next move says where the finger is. -func sendMove(ev event) { - select { - case queue <- ev: - default: - } -} - -// Run enters the program's event loop with one window. -func Run(config platform.Config) error { - return RunApplication(func(application platform.Application) error { - _, err := application.OpenWindow(config) - return err - }) -} - -// RunApplication runs the event loop on the calling goroutine, which stays on one OS -// thread for as long as it does. It returns when the window is closed. -func RunApplication(start platform.ApplicationStart) error { - runtime.LockOSThread() - defer runtime.UnlockOSThread() - if C.viva_attach_thread() == 0 { - return errors.New("android: the process has no Java virtual machine; the program must run as the host's library") - } - app := &application{} - loopApplication.Store(app) - defer loopApplication.Store(nil) - if err := start(app); err != nil { - app.closeWindow() - return err - } - return app.loop() -} - -// loopApplication is the application whose loop runs, for what the host asks of it -// from other threads. -var loopApplication atomic.Pointer[application] - -// application is the one window a phone's application has. -type application struct { - window *window - done bool - err error - - postMu sync.Mutex - posts []func() - pending atomic.Bool // a wake is queued - redraw atomic.Bool // a redraw is queued -} - -var errOneWindow = errors.New("android: an Android application has one window; its surface is the Activity's") - -func (application *application) OpenWindow(config platform.Config) (platform.Window, error) { - if application.window != nil && !application.window.closed { - return nil, errOneWindow - } - win := &window{application: application, config: config, visible: true} - application.window = win - if config.Waker != nil && config.OnRedraw != nil { - config.Waker.Bind(application.wakeRedraw) - } - if config.Title != "" { - setTitle(config.Title) - } - // A surface the host made before the window was asked for waits for it. - if pending := takePendingSurface(); pending != nil { - application.surfaceChanged(*pending) - } - return win, nil -} - -func (application *application) AddStatusItem(platform.StatusItemConfig) (platform.StatusItem, error) { - return nil, platform.ErrStatusAreaUnavailable -} - -func (application *application) SetDockBadge(string) {} - -func (application *application) SetProgress(float32) {} - -// Quit closes the window and ends the loop. -func (application *application) Quit() { - application.Post(func() { application.closeWindow() }) -} - -// Post runs fn on the loop's thread. -func (application *application) Post(fn func()) { - application.postMu.Lock() - application.posts = append(application.posts, fn) - application.postMu.Unlock() - if !application.pending.Swap(true) { - send(event{kind: eventWake}) - } -} - -// wakeRedraw is what the application's waker calls from any goroutine. -func (application *application) wakeRedraw() { - if !application.redraw.Swap(true) { - send(event{kind: eventRedraw}) - } -} - -// loop waits for the host's events and handles them, until the window is closed. -func (application *application) loop() error { - for !application.done { - ev := <-queue - application.handle(ev) - } - return application.err -} - -func (application *application) handle(ev event) { - switch ev.kind { - case eventSurface: - application.surfaceChanged(ev) - case eventSurfaceLost: - application.surfaceLost(ev) - case eventTouch: - application.touch(ev) - case eventVisible: - application.visibility(ev.visible) - case eventClose: - application.closeRequested() - case eventWake: - application.runPosts() - case eventRedraw: - application.redrawNow() - case eventText: - application.textEdit(ev) - case eventKey: - application.keyEvent(ev) - case eventHover, eventHoverExit: - application.hover(ev) - case eventScroll: - application.scroll(ev) - case eventAppearance: - platform.NotifyAppearanceChanged() - case eventAccessibility: - application.accessibilityState(ev.visible) - case eventAccessible: - application.accessible(ev) - case eventLowMemory: - application.lifecycle(platform.LifecycleMemoryWarning) - case eventRedrawNeeded: - application.redrawNeeded(ev) - case eventLifecycle: - application.lifecycle(platform.Lifecycle(ev.action)) - case eventInsets: - application.insetsChanged(ev) - } -} - -// lifecycle tells the application the system moved it between the foreground and the -// background, or asked for memory. -func (application *application) lifecycle(event platform.Lifecycle) { - win := application.window - if win == nil || win.closed || win.config.OnLifecycle == nil { - return - } - defer application.guard() - win.config.OnLifecycle(event) -} - -// insetsChanged follows the system covering other edges of the window: the page lays out -// again inside what is left. The host gives them in device pixels; they are kept as the -// window's own, in logical pixels, and so are known when the first frame is painted. -func (application *application) insetsChanged(ev event) { - left, top, right, bottom := ev.x, ev.y, ev.dx, ev.dy - hostInsets.Lock() - hostInsets.left, hostInsets.top, hostInsets.right, hostInsets.bottom, hostInsets.known = left, top, right, bottom, true - hostInsets.Unlock() - win := application.window - if win == nil || win.closed || win.density <= 0 { - return - } - defer application.guard() - insets := insetsIn(win.density) - if insets == win.insets { - return - } - win.insets = insets - if err := win.resized(false); err != nil { - application.fail(err) - } -} - -// hostInsets are the insets the host last gave, in device pixels. They arrive before the -// window exists and again whenever they change; the window takes them with its density. -var hostInsets struct { - sync.Mutex - left, top, right, bottom float32 - known bool -} - -// insetsIn is the host's insets in logical pixels at a density. -func insetsIn(density float32) gfx.Insets { - hostInsets.Lock() - defer hostInsets.Unlock() - if !hostInsets.known || density <= 0 { - return gfx.Insets{} - } - return gfx.Insets{Top: hostInsets.top / density, Left: hostInsets.left / density, Bottom: hostInsets.bottom / density, Right: hostInsets.right / density} -} - -func (application *application) runPosts() { - application.postMu.Lock() - posts := application.posts - application.posts = nil - application.pending.Store(false) - application.postMu.Unlock() - for _, fn := range posts { - fn() - } -} - -// fail ends the window with err. -func (application *application) fail(err error) { - logf(logError, "the window ends: %v", err) - if application.err == nil { - application.err = err - } - application.closeWindow() -} - -// guard turns a panic in the application's handlers into the end of the window, as the -// other adapters do. -func (application *application) guard() { - if recovered := recover(); recovered != nil { - platform.ReportFault("android: event handler", recovered) - application.fail(fmt.Errorf("android: a handler panicked: %v", recovered)) - } -} - -// window is the Activity's surface and what draws on it. -type window struct { - application *application - config platform.Config - closed bool - visible bool - - native *C.ANativeWindow // the surface the host gave, nil when it has none - width uint32 // its size in device pixels - height uint32 - density float32 // device pixels per logical pixel - renderer *vulkan.Renderer - text *textInput // the application's focused text input, if it has one - insets gfx.Insets // how far the system covers each edge, in logical pixels - hovering bool // a mouse is over the surface - a11y bool // a screen reader reads the window - treeIDs []gfx.ID // the nodes of the tree last sent to the host, by place -} - -func (win *window) Close() { - win.application.Post(func() { win.application.closeWindow() }) -} - -func (win *window) Hide() {} -func (win *window) Show() {} - -// Frame is the content area: the whole surface, from the screen's corner. -func (win *window) Frame() (gfx.Rect, bool) { - density := win.density - if density <= 0 { - return gfx.Rect{}, false - } - return gfx.Rect{Width: float32(win.width) / density, Height: float32(win.height) / density}, true -} - -func (win *window) size() platform.Size { - density := win.density - return platform.Size{Width: float32(win.width) / density, Height: float32(win.height) / density, Scale: density, SafeArea: win.insets} -} - -// closeWindow ends the window and the loop. -func (application *application) closeWindow() { - win := application.window - if win == nil || win.closed { - application.done = true - return - } - win.closed = true - if win.config.Waker != nil && win.config.OnRedraw != nil { - win.config.Waker.Unbind() - } - if win.renderer != nil { - win.renderer.Close() - win.renderer = nil - } - win.setTextInput(platform.TextInputUpdate{Changed: true}) - win.releaseNative() - application.done = true - if win.config.OnClosed != nil { - win.config.OnClosed() - } -} - -func (win *window) releaseNative() { - if win.native != nil { - C.ANativeWindow_release(win.native) - win.native = nil - } -} - -// pendingSurface is a surface that came before the window was opened. -var pendingSurface struct { - sync.Mutex - event *event -} - -func takePendingSurface() *event { - pendingSurface.Lock() - defer pendingSurface.Unlock() - ev := pendingSurface.event - pendingSurface.event = nil - return ev -} - -// surfaceChanged takes the surface the host gave: the first makes the renderer, a later -// one for the same window is a resize, and a different window a surface to move to. -func (application *application) surfaceChanged(ev event) { - win := application.window - if win == nil || win.closed { - pendingSurface.Lock() - if old := pendingSurface.event; old != nil && old.surface != nil && old.surface != ev.surface { - C.ANativeWindow_release(old.surface) - } - kept := ev - pendingSurface.event = &kept - pendingSurface.Unlock() - return - } - defer application.guard() - if ev.width <= 0 || ev.height <= 0 || ev.density <= 0 { - return - } - density := ev.density - win.insets = insetsIn(density) - switch { - case win.renderer == nil: - win.native, win.width, win.height, win.density = ev.surface, uint32(ev.width), uint32(ev.height), density - source, err := win.surfaceSource() - if err == nil { - win.renderer, err = vulkan.New(vulkan.Config{ - Surface: source, Width: win.width, Height: win.height, Scale: density, Clear: win.config.ClearColor, - Rectangles: win.config.Rectangles, Labels: win.config.TextLabels, Rasterizer: newRasterizer, - }) - } - if err != nil { - application.fail(err) - return - } - if win.config.SetFrameInterval != nil { - // A FIFO present blocks until the display takes the frame, so the display - // paces the window; the runtime asks for the next frame as soon as the last - // one is shown. - win.config.SetFrameInterval(0) - } - if err := win.resized(false); err != nil { - application.fail(err) - } - case ev.surface != win.native: - // A new surface: the activity was recreated, or came back from behind another. - win.releaseNative() - win.native, win.width, win.height, win.density = ev.surface, uint32(ev.width), uint32(ev.height), density - if err := win.renderer.SetScale(density); err != nil { - application.fail(err) - return - } - if err := win.renderer.ReplaceSurface(win.width, win.height); err != nil { - application.fail(err) - return - } - if err := win.resized(true); err != nil { - application.fail(err) - } - default: - // The same surface at another size (a rotation, a split screen) or density. - C.ANativeWindow_release(ev.surface) // the host's reference to a window we already hold - changedDensity := density != win.density - win.width, win.height, win.density = uint32(ev.width), uint32(ev.height), density - if changedDensity { - if err := win.renderer.SetScale(density); err != nil { - application.fail(err) - return - } - } - if err := win.resized(true); err != nil { - application.fail(err) - } - } -} - -// resized shows the application at the surface's size: it paints for the size and the -// frame it answers with is drawn. A whole frame is what a surface that came back -// needs, and what the application's resize handler answers with. -func (win *window) resized(swapchain bool) error { - defer win.application.guard() - renderer := win.renderer - if renderer == nil || win.native == nil { - return nil - } - if win.config.OnResize != nil { - frame, err := win.config.OnResize(win.size()) - if err != nil { - return err - } - if swapchain { - if _, err := renderer.Stage(frame); err != nil { - return err - } - if err := renderer.Resize(win.width, win.height); err != nil { - return err - } - } else if _, err := renderer.Apply(frame); err != nil { - return err - } - win.setTextInput(frame.TextInput) - win.syncTree(frame) - } - if err := renderer.Present(); err != nil { - return err - } - if win.config.FramePresented != nil { - win.config.FramePresented() - } - return nil -} - -// surfaceLost lets go of the surface before the host takes it away. -func (application *application) surfaceLost(ev event) { - if win := application.window; win != nil && !win.closed { - if win.renderer != nil { - win.renderer.ReleaseSurface() - } - win.releaseNative() - } else { - pendingSurface.Lock() - if old := pendingSurface.event; old != nil && old.surface != nil { - C.ANativeWindow_release(old.surface) - } - pendingSurface.event = nil - pendingSurface.Unlock() - } - if ev.ack != nil { - close(ev.ack) - } -} - -// redrawNeeded draws the window on the surface the system is about to show, and answers -// once the frame is presented (SurfaceHolder.Callback2.surfaceRedrawNeeded): the system -// shows a new surface only after it, so the user never sees one without the window on it. -// The frame is presented even when nothing in it changed, as the surface may hold none. -func (application *application) redrawNeeded(ev event) { - defer close(ev.ack) - win := application.window - if win == nil || win.closed || win.renderer == nil || win.native == nil { - return - } - defer application.guard() - if win.config.OnRedraw != nil { - frame, err := win.config.OnRedraw() - if err == nil { - _, err = win.renderer.Apply(frame) - } - if err == nil { - win.setTextInput(frame.TextInput) - win.syncTree(frame) - } - if err != nil { - application.fail(err) - return - } - } - if err := win.renderer.Present(); err != nil { - application.fail(err) - return - } - if win.config.FramePresented != nil { - win.config.FramePresented() - } -} - -// present draws a frame the application answered with. -func (win *window) present(frame platform.Frame) error { - if win.renderer == nil || win.native == nil || !win.visible { - return nil - } - changed, err := win.renderer.Apply(frame) - if err == nil && changed { - err = win.renderer.Present() - } - if err == nil { - win.setTextInput(frame.TextInput) - win.syncTree(frame) - } - if err == nil && win.config.FramePresented != nil { - win.config.FramePresented() - } - return err -} - -// redrawNow answers the application's request for a frame. -func (application *application) redrawNow() { - application.redraw.Store(false) - win := application.window - if win == nil || win.closed || win.config.OnRedraw == nil || win.renderer == nil || win.native == nil || !win.visible { - return - } - defer application.guard() - frame, err := win.config.OnRedraw() - if err == nil { - err = win.present(frame) - } - if err != nil { - application.fail(err) - } -} - -// visibility follows the activity going behind another and coming back. -func (application *application) visibility(visible bool) { - win := application.window - if win == nil || win.closed { - return - } - defer application.guard() - was := win.visible - win.visible = visible - if win.config.OnVisibility != nil && visible != was { - win.config.OnVisibility(visible) - } - if visible && !was && win.renderer != nil && win.native != nil { - // What was drawn last may have gone with the surface: the application - // paints for the size again. - if err := win.resized(true); err != nil { - application.fail(err) - } - } -} - -// closeRequested is the user's back gesture at the root: the application may keep the -// window, as it may a window's close button. -func (application *application) closeRequested() { - win := application.window - if win == nil || win.closed { - return - } - defer application.guard() - if win.config.OnCloseRequest != nil { - win.config.OnCloseRequest(func() { application.Post(application.closeWindow) }) - return - } - application.closeWindow() -} - -// setTitle names the task in the system's list of recent apps. -func setTitle(title string) { - units := utf16Units(title) - if len(units) == 0 { - return - } - C.viva_host_set_title((*C.uint16_t)(unsafe.Pointer(&units[0])), C.int(len(units))) -} - -// syncTree gives the host the accessibility tree a frame carries, when a screen reader reads. -func (win *window) syncTree(frame platform.Frame) { - if win.a11y && frame.Accessibility != nil { - win.pushTree(frame.Accessibility) - } -} diff --git a/internal/platform/android/exports_android.go b/internal/platform/android/exports_android.go deleted file mode 100644 index 016da06d1..000000000 --- a/internal/platform/android/exports_android.go +++ /dev/null @@ -1,193 +0,0 @@ -//go:build android - -package android - -/* -#include -#include -#include -#include "jni_android.h" -*/ -import "C" - -import ( - "os" - "sync" - "unsafe" - _ "unsafe" // for go:linkname -) - -// The host's calls, made on the UI thread by dev.viva.host.Native. They queue what -// happened for the program's own thread, and return. - -//go:linkname applicationMain main.main -func applicationMain() - -var started sync.Once - -//export Java_dev_viva_host_Native_start -func Java_dev_viva_host_Native_start(env *C.JNIEnv, _ C.jclass, filesDir, cacheDir C.jstring) { - started.Do(func() { - if dir := goString(env, filesDir); dir != "" { - // What a program looks for under the home directory is the app's own. - os.Setenv("HOME", dir) - } - if dir := goString(env, cacheDir); dir != "" { - os.Setenv("TMPDIR", dir) - } - go func() { - applicationMain() - // The program's main returned: its window is gone, and so is the activity. - C.viva_host_finish() - }() - }) -} - -func goString(env *C.JNIEnv, value C.jstring) string { - chars := C.viva_string_chars(env, value) - if chars == nil { - return "" - } - defer C.free(unsafe.Pointer(chars)) - return C.GoString(chars) -} - -//export Java_dev_viva_host_Native_surfaceChanged -func Java_dev_viva_host_Native_surfaceChanged(env *C.JNIEnv, _ C.jclass, surface C.jobject, width, height C.jint, density C.jfloat) { - native := C.ANativeWindow_fromSurface(env, surface) - if native == nil { - return - } - send(event{kind: eventSurface, surface: native, width: int32(width), height: int32(height), density: float32(density)}) -} - -//export Java_dev_viva_host_Native_surfaceDestroyed -func Java_dev_viva_host_Native_surfaceDestroyed(env *C.JNIEnv, _ C.jclass) { - // The host takes the surface back when this returns, so the program must have let - // go of it by then. - ack := make(chan struct{}) - send(event{kind: eventSurfaceLost, ack: ack}) - <-ack -} - -//export Java_dev_viva_host_Native_redrawNeeded -func Java_dev_viva_host_Native_redrawNeeded(env *C.JNIEnv, _ C.jclass) { - // The system shows the surface when this returns, so the window must be on it by then. - ack := make(chan struct{}) - send(event{kind: eventRedrawNeeded, ack: ack}) - <-ack -} - -//export Java_dev_viva_host_Native_touch -func Java_dev_viva_host_Native_touch(env *C.JNIEnv, _ C.jclass, action, pointer C.jint, x, y C.jfloat, tool, buttons, modifiers C.jint, uptime C.jlong) { - ev := event{kind: eventTouch, action: int32(action), pointer: int32(pointer), x: float32(x), y: float32(y), - tool: int32(tool), buttons: int32(buttons), modifiers: int32(modifiers), time: int64(uptime)} - if ev.action == actionMove { - sendMove(ev) - return - } - send(ev) -} - -//export Java_dev_viva_host_Native_visible -func Java_dev_viva_host_Native_visible(env *C.JNIEnv, _ C.jclass, visible C.jboolean) { - send(event{kind: eventVisible, visible: visible != 0}) -} - -//export Java_dev_viva_host_Native_lifecycle -func Java_dev_viva_host_Native_lifecycle(env *C.JNIEnv, _ C.jclass, kind C.jint) { - send(event{kind: eventLifecycle, action: int32(kind)}) -} - -//export Java_dev_viva_host_Native_lowMemory -func Java_dev_viva_host_Native_lowMemory(env *C.JNIEnv, _ C.jclass) { - send(event{kind: eventLowMemory}) -} - -//export Java_dev_viva_host_Native_insets -func Java_dev_viva_host_Native_insets(env *C.JNIEnv, _ C.jclass, left, top, right, bottom C.jfloat) { - send(event{kind: eventInsets, x: float32(left), y: float32(top), dx: float32(right), dy: float32(bottom)}) -} - -//export Java_dev_viva_host_Native_closeRequested -func Java_dev_viva_host_Native_closeRequested(env *C.JNIEnv, _ C.jclass) { - send(event{kind: eventClose}) -} - -// edit queues an input method's edit and returns when the program has applied it: the -// input method asks what is around the cursor as soon as it has typed. -func queueEdit(operation textOperation, text string, first, last int32, codePoints bool) { - ack := make(chan struct{}) - send(event{kind: eventText, ack: ack, edit: edit{operation: operation, text: text, first: first, last: last, codePoints: codePoints}}) - <-ack -} - -//export Java_dev_viva_host_Native_commitText -func Java_dev_viva_host_Native_commitText(env *C.JNIEnv, _ C.jclass, text C.jstring, newCursor C.jint) { - queueEdit(opCommit, goString(env, text), int32(newCursor), 0, false) -} - -//export Java_dev_viva_host_Native_setComposingText -func Java_dev_viva_host_Native_setComposingText(env *C.JNIEnv, _ C.jclass, text C.jstring, newCursor C.jint) { - queueEdit(opSetComposing, goString(env, text), int32(newCursor), 0, false) -} - -//export Java_dev_viva_host_Native_finishComposing -func Java_dev_viva_host_Native_finishComposing(env *C.JNIEnv, _ C.jclass) { - queueEdit(opFinish, "", 0, 0, false) -} - -//export Java_dev_viva_host_Native_deleteSurrounding -func Java_dev_viva_host_Native_deleteSurrounding(env *C.JNIEnv, _ C.jclass, before, after C.jint, codePoints C.jboolean) { - queueEdit(opDeleteSurrounding, "", int32(before), int32(after), codePoints != 0) -} - -//export Java_dev_viva_host_Native_setSelection -func Java_dev_viva_host_Native_setSelection(env *C.JNIEnv, _ C.jclass, start, end C.jint) { - queueEdit(opSelect, "", int32(start), int32(end), false) -} - -//export Java_dev_viva_host_Native_setComposingRegion -func Java_dev_viva_host_Native_setComposingRegion(env *C.JNIEnv, _ C.jclass, start, end C.jint) { - queueEdit(opMarkRange, "", int32(start), int32(end), false) -} - -//export Java_dev_viva_host_Native_editorAction -func Java_dev_viva_host_Native_editorAction(env *C.JNIEnv, _ C.jclass, action C.jint) { - send(event{kind: eventText, edit: edit{operation: opAction, editorAction: int32(action)}}) -} - -//export Java_dev_viva_host_Native_key -func Java_dev_viva_host_Native_key(env *C.JNIEnv, _ C.jclass, keyCode, meta, unicode C.jint, repeat C.jboolean) { - send(event{kind: eventKey, keyCode: int32(keyCode), modifiers: int32(meta), unicode: int32(unicode), repeat: repeat != 0}) -} - -//export Java_dev_viva_host_Native_hover -func Java_dev_viva_host_Native_hover(env *C.JNIEnv, _ C.jclass, x, y C.jfloat, meta C.jint, uptime C.jlong) { - sendMove(event{kind: eventHover, x: float32(x), y: float32(y), modifiers: int32(meta), time: int64(uptime)}) -} - -//export Java_dev_viva_host_Native_hoverExit -func Java_dev_viva_host_Native_hoverExit(env *C.JNIEnv, _ C.jclass) { - send(event{kind: eventHoverExit}) -} - -//export Java_dev_viva_host_Native_scroll -func Java_dev_viva_host_Native_scroll(env *C.JNIEnv, _ C.jclass, x, y, dx, dy C.jfloat, meta C.jint) { - send(event{kind: eventScroll, x: float32(x), y: float32(y), dx: float32(dx), dy: float32(dy), modifiers: int32(meta)}) -} - -//export Java_dev_viva_host_Native_appearanceChanged -func Java_dev_viva_host_Native_appearanceChanged(env *C.JNIEnv, _ C.jclass) { - send(event{kind: eventAppearance}) -} - -//export Java_dev_viva_host_Native_accessibility -func Java_dev_viva_host_Native_accessibility(env *C.JNIEnv, _ C.jclass, on C.jboolean) { - send(event{kind: eventAccessibility, visible: on != 0}) -} - -//export Java_dev_viva_host_Native_accessible -func Java_dev_viva_host_Native_accessible(env *C.JNIEnv, _ C.jclass, node C.jint, action C.jint, number C.jfloat, text C.jstring, start, end C.jint) { - send(event{kind: eventAccessible, index: int32(node), action: int32(action), dx: float32(number), text: goString(env, text), start: int32(start), end: int32(end)}) -} diff --git a/internal/platform/android/hostsrc/embed.go b/internal/platform/android/hostsrc/embed.go deleted file mode 100644 index 0d578bb47..000000000 --- a/internal/platform/android/hostsrc/embed.go +++ /dev/null @@ -1,12 +0,0 @@ -// Package hostsrc holds the Java sources of the Android host: the Activity and the -// SurfaceView that give the Go program a window, and what it asks of the system's -// text drawing. viva build compiles them with the application, so the host needs -// no Gradle project. -package hostsrc - -import "embed" - -// Java is the host's source tree, rooted at java/. -// -//go:embed java -var Java embed.FS diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Accessibility.java b/internal/platform/android/hostsrc/java/dev/viva/host/Accessibility.java deleted file mode 100644 index 1bbcdb207..000000000 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Accessibility.java +++ /dev/null @@ -1,248 +0,0 @@ -package dev.viva.host; - -import android.graphics.Rect; -import android.os.Bundle; -import android.view.View; -import android.view.accessibility.AccessibilityEvent; -import android.view.accessibility.AccessibilityNodeInfo; -import android.view.accessibility.AccessibilityNodeProvider; - -import java.util.ArrayList; -import java.util.List; - -/** - * The program's accessibility tree, shown to TalkBack and the other services as virtual - * views of the surface. The program sends the tree whole whenever it changes (Host.tree), - * and a service's requests go back to it as what to do to which node (Native.accessible). - */ -final class Accessibility extends AccessibilityNodeProvider { - // The roles, in the program's numbering (platform.A11yRole*). - private static final int BUTTON = 3, TEXT = 4, TEXT_FIELD = 5, CHECKBOX = 6, SLIDER = 7, IMAGE = 8, LINK = 9, RADIO = 10, - TAB = 11, SWITCH = 14, LIST_BOX = 17, OPTION = 18, HEADING = 21, STATUS = 22, PROGRESS = 24; - // The flags of a node. - private static final int FOCUSED = 1, DISABLED = 2, CHECKED = 4, MIXED = 8, SELECTED = 16, EXPANDED = 32, MULTILINE = 64, - READ_ONLY = 128, INVALID = 256, SECURE = 512, FOCUSABLE = 1024, EXPANDABLE = 2048, HAS_RANGE = 4096; - // What a service asks of a node (platform.Accessibility*). - static final int PRESS = 1, FOCUS = 2, INCREMENT = 3, DECREMENT = 4, SET_NUMBER = 5, SET_TEXT = 6, SET_SELECTION = 7; - - private static final class Node { - int role, flags, level, position, size; - float x, y, width, height; - float min, max, value; - String label, text, hint, description; - } - - private final View view; - private volatile Node[] nodes = new Node[0]; - private volatile boolean enabled; - - Accessibility(View view) { - this.view = view; - } - - boolean enabled() { - return enabled; - } - - void setEnabled(boolean on) { - enabled = on; - } - - /** The tree the program has now. */ - void set(float[] bounds, int[] ints, float[] ranges, char[] chars, int[] offsets) { - int count = bounds.length / 4; - Node[] next = new Node[count]; - for (int i = 0; i < count; i++) { - Node node = new Node(); - node.x = bounds[4 * i]; - node.y = bounds[4 * i + 1]; - node.width = bounds[4 * i + 2]; - node.height = bounds[4 * i + 3]; - node.role = ints[5 * i]; - node.flags = ints[5 * i + 1]; - node.level = ints[5 * i + 2]; - node.position = ints[5 * i + 3]; - node.size = ints[5 * i + 4]; - node.min = ranges[3 * i]; - node.max = ranges[3 * i + 1]; - node.value = ranges[3 * i + 2]; - node.label = text(chars, offsets, 4 * i); - node.text = text(chars, offsets, 4 * i + 1); - node.hint = text(chars, offsets, 4 * i + 2); - node.description = text(chars, offsets, 4 * i + 3); - next[i] = node; - } - nodes = next; - view.post(() -> view.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED)); - } - - private static String text(char[] chars, int[] offsets, int index) { - return new String(chars, offsets[index], offsets[index + 1] - offsets[index]); - } - - private static String className(Node node) { - switch (node.role) { - case BUTTON: - case LINK: - return "android.widget.Button"; - case TEXT_FIELD: - return "android.widget.EditText"; - case CHECKBOX: - return "android.widget.CheckBox"; - case SWITCH: - return "android.widget.Switch"; - case RADIO: - return "android.widget.RadioButton"; - case SLIDER: - return "android.widget.SeekBar"; - case PROGRESS: - return "android.widget.ProgressBar"; - case IMAGE: - return "android.widget.ImageView"; - case LIST_BOX: - return "android.widget.ListView"; - case TEXT: - case HEADING: - case STATUS: - return "android.widget.TextView"; - default: - return "android.view.View"; - } - } - - @Override - public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { - Node[] tree = nodes; - if (virtualViewId == View.NO_ID) { - AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(view); - view.onInitializeAccessibilityNodeInfo(info); - for (int i = 0; i < tree.length; i++) { - info.addChild(view, i); - } - return info; - } - if (virtualViewId < 0 || virtualViewId >= tree.length) { - return null; - } - Node node = tree[virtualViewId]; - AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(view, virtualViewId); - info.setPackageName(view.getContext().getPackageName()); - info.setClassName(className(node)); - info.setParent(view); - info.setEnabled((node.flags & DISABLED) == 0); - info.setFocusable((node.flags & FOCUSABLE) != 0); - info.setVisibleToUser(true); - info.setContentDescription(node.label.isEmpty() ? null : node.label); - if (!node.text.isEmpty()) { - info.setText(node.text); - } else if (node.role == TEXT || node.role == HEADING || node.role == STATUS) { - info.setText(node.label); - } - if (!node.hint.isEmpty() && android.os.Build.VERSION.SDK_INT >= 26) { - info.setHintText(node.hint); - } - if (!node.description.isEmpty() && android.os.Build.VERSION.SDK_INT >= 30) { - info.setStateDescription(node.description); - } - if (node.role == HEADING) { - info.setHeading(true); - } - if (node.role == CHECKBOX || node.role == SWITCH || node.role == RADIO) { - info.setCheckable(true); - info.setChecked((node.flags & CHECKED) != 0); - } - if ((node.flags & SELECTED) != 0) { - info.setSelected(true); - } - if ((node.flags & INVALID) != 0) { - info.setContentInvalid(true); - } - if (node.role == TEXT_FIELD) { - info.setEditable((node.flags & READ_ONLY) == 0); - info.setMultiLine((node.flags & MULTILINE) != 0); - info.setPassword((node.flags & SECURE) != 0); - if ((node.flags & READ_ONLY) == 0) { - info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_TEXT); - } - } - if ((node.flags & HAS_RANGE) != 0) { - info.setRangeInfo(AccessibilityNodeInfo.RangeInfo.obtain(AccessibilityNodeInfo.RangeInfo.RANGE_TYPE_FLOAT, node.min, node.max, node.value)); - if (node.role == SLIDER) { - info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD); - info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD); - if (android.os.Build.VERSION.SDK_INT >= 24) { - info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_PROGRESS); - } - } - } - if (node.size > 0 && (node.role == TAB || node.role == OPTION || node.role == RADIO)) { - info.setCollectionItemInfo(AccessibilityNodeInfo.CollectionItemInfo.obtain(Math.max(node.position - 1, 0), 1, 0, 1, false, (node.flags & SELECTED) != 0)); - } - boolean operable = (node.flags & DISABLED) == 0; - if (operable && (node.role == BUTTON || node.role == LINK || node.role == CHECKBOX || node.role == SWITCH || node.role == RADIO - || node.role == TAB || node.role == OPTION || node.role == 12 || node.role == 20)) { - info.setClickable(true); - info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK); - } - if ((node.flags & EXPANDABLE) != 0 && operable) { - info.addAction((node.flags & EXPANDED) != 0 ? AccessibilityNodeInfo.AccessibilityAction.ACTION_COLLAPSE : AccessibilityNodeInfo.AccessibilityAction.ACTION_EXPAND); - } - if ((node.flags & FOCUSABLE) != 0) { - info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_FOCUS); - } - info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_ACCESSIBILITY_FOCUS); - int[] origin = new int[2]; - view.getLocationOnScreen(origin); - Rect screen = new Rect(origin[0] + Math.round(node.x), origin[1] + Math.round(node.y), - origin[0] + Math.round(node.x + node.width), origin[1] + Math.round(node.y + node.height)); - info.setBoundsInScreen(screen); - Rect parent = new Rect(Math.round(node.x), Math.round(node.y), Math.round(node.x + node.width), Math.round(node.y + node.height)); - info.setBoundsInParent(parent); - return info; - } - - @Override - public boolean performAction(int virtualViewId, int action, Bundle arguments) { - Node[] tree = nodes; - if (virtualViewId == View.NO_ID) { - return view.performAccessibilityAction(action, arguments); - } - if (virtualViewId < 0 || virtualViewId >= tree.length) { - return false; - } - Node node = tree[virtualViewId]; - switch (action) { - case AccessibilityNodeInfo.ACTION_CLICK: - case AccessibilityNodeInfo.ACTION_EXPAND: - case AccessibilityNodeInfo.ACTION_COLLAPSE: - Native.accessible(virtualViewId, PRESS, 0, null, 0, 0); - return true; - case AccessibilityNodeInfo.ACTION_FOCUS: - Native.accessible(virtualViewId, FOCUS, 0, null, 0, 0); - return true; - case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { - AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); - event.setSource(view, virtualViewId); - view.getParent().requestSendAccessibilityEvent(view, event); - return true; - } - case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: - Native.accessible(virtualViewId, INCREMENT, 0, null, 0, 0); - return true; - case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: - Native.accessible(virtualViewId, DECREMENT, 0, null, 0, 0); - return true; - case AccessibilityNodeInfo.ACTION_SET_TEXT: { - CharSequence text = arguments == null ? null : arguments.getCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE); - Native.accessible(virtualViewId, SET_TEXT, 0, text == null ? "" : text.toString(), 0, 0); - return true; - } - default: - if (android.os.Build.VERSION.SDK_INT >= 24 && action == android.R.id.accessibilityActionSetProgress && arguments != null) { - Native.accessible(virtualViewId, SET_NUMBER, arguments.getFloat(AccessibilityNodeInfo.ACTION_ARGUMENT_PROGRESS_VALUE), null, 0, 0); - return true; - } - return false; - } - } -} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Editor.java b/internal/platform/android/hostsrc/java/dev/viva/host/Editor.java deleted file mode 100644 index 2222bd5d3..000000000 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Editor.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.viva.host; - -/** - * The text input the program has focused, as the input method reads it: the text and - * where the selection and the composing text are, in UTF-16 units. The program is the - * owner of it and sends it whole after every change; the input method only reads. - */ -final class Editor { - private Editor() {} - - private static String text = ""; - private static int selectionStart; - private static int selectionEnd; - private static int compositionStart = -1; - private static int compositionEnd = -1; - - static synchronized void set(String value, int start, int end, int compStart, int compEnd) { - text = value; - selectionStart = start; - selectionEnd = end; - compositionStart = compStart; - compositionEnd = compEnd; - } - - static synchronized String text() { - return text; - } - - static synchronized int selectionStart() { - return Math.min(selectionStart, selectionEnd); - } - - static synchronized int selectionEnd() { - return Math.max(selectionStart, selectionEnd); - } - - static synchronized int compositionStart() { - return compositionStart; - } - - static synchronized int compositionEnd() { - return compositionEnd; - } - - static synchronized CharSequence before(int length) { - int end = selectionStart(); - return text.substring(Math.max(0, end - length), end); - } - - static synchronized CharSequence after(int length) { - int start = selectionEnd(); - return text.substring(start, Math.min(text.length(), start + length)); - } - - static synchronized CharSequence selected() { - int start = selectionStart(); - int end = selectionEnd(); - return start == end ? null : text.substring(start, end); - } -} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Host.java b/internal/platform/android/hostsrc/java/dev/viva/host/Host.java deleted file mode 100644 index f0f1025d0..000000000 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Host.java +++ /dev/null @@ -1,149 +0,0 @@ -package dev.viva.host; - -import android.app.Activity; -import android.content.ClipData; -import android.content.ClipboardManager; -import android.content.Context; -import android.content.Intent; -import android.content.res.Configuration; -import android.net.Uri; -import android.os.LocaleList; -import android.provider.Settings; -import android.view.Surface; - -/** What the Go program asks of the host, on any thread. */ -public final class Host { - private Host() {} - - private static volatile Activity activity; - private static volatile VivaView view; - - static void attach(Activity current, VivaView surface) { - activity = current; - view = surface; - } - - /** - * The program's focused text input has this text: the input method reads it from - * here, and is told when it changes under it. - */ - public static void editor(String text, int selectionStart, int selectionEnd, int compositionStart, int compositionEnd) { - Editor.set(text, selectionStart, selectionEnd, compositionStart, compositionEnd); - final VivaView current = view; - if (current != null) { - current.post(current::editorChanged); - } - } - - /** The program's accessibility tree, whole: its nodes and what a screen reader reads of them. */ - public static void tree(float[] bounds, int[] ints, float[] ranges, char[] chars, int[] offsets) { - VivaView current = view; - if (current != null) { - current.accessibility().set(bounds, ints, ranges, chars, offsets); - } - } - - /** Shows the keyboard for a text input, or takes it away when editing is false. */ - public static void keyboard(final boolean editing, final boolean multiline, final boolean secure) { - final VivaView current = view; - if (current != null) { - current.post(() -> current.configure(editing, multiline, secure)); - } - } - - /** Ends the activity; the program's window is gone with it. */ - public static void finish() { - final Activity current = activity; - if (current != null) { - current.runOnUiThread(current::finishAndRemoveTask); - } - } - - /** Names the task in the system's list of recent apps. */ - public static void setTitle(final String title) { - final Activity current = activity; - if (current != null) { - current.runOnUiThread(() -> current.setTitle(title)); - } - } - - /** Asks the display for the rate the program's frames take, the highest it has. */ - public static void preferHighRefresh(Surface surface) { - if (surface != null && surface.isValid() && android.os.Build.VERSION.SDK_INT >= 30) { - surface.setFrameRate(120f, Surface.FRAME_RATE_COMPATIBILITY_DEFAULT); - } - } - - /** The text on the clipboard, or null when there is none or the system will not say. */ - public static String clipboardText() { - Activity current = activity; - if (current == null) { - return null; - } - ClipboardManager clipboard = (ClipboardManager) current.getSystemService(Context.CLIPBOARD_SERVICE); - if (clipboard == null || !clipboard.hasPrimaryClip() || clipboard.getPrimaryClip().getItemCount() == 0) { - return null; - } - CharSequence text = clipboard.getPrimaryClip().getItemAt(0).coerceToText(current); - return text == null ? null : text.toString(); - } - - public static boolean setClipboardText(String text) { - Activity current = activity; - if (current == null) { - return false; - } - ClipboardManager clipboard = (ClipboardManager) current.getSystemService(Context.CLIPBOARD_SERVICE); - if (clipboard == null) { - return false; - } - clipboard.setPrimaryClip(ClipData.newPlainText(null, text)); - return true; - } - - /** Opens a link in the app that takes it. */ - public static boolean openURL(String url) { - Activity current = activity; - if (current == null) { - return false; - } - try { - current.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); - return true; - } catch (RuntimeException e) { - return false; - } - } - - /** The user's languages, most preferred first, as BCP 47 tags separated by newlines. */ - public static String languages() { - LocaleList list = LocaleList.getAdjustedDefault(); - StringBuilder tags = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { - if (i > 0) { - tags.append('\n'); - } - tags.append(list.get(i).toLanguageTag()); - } - return tags.toString(); - } - - /** 1 when the system shows the dark theme, 0 for the light one. */ - public static int darkTheme() { - Activity current = activity; - if (current == null) { - return -1; - } - int night = current.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; - return night == Configuration.UI_MODE_NIGHT_YES ? 1 : 0; - } - - /** True when the user turned animations off. */ - public static boolean animationsOff() { - Activity current = activity; - if (current == null) { - return false; - } - return Settings.Global.getFloat(current.getContentResolver(), Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f; - } -} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java deleted file mode 100644 index 3f040cb82..000000000 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.viva.host; - -import android.view.Surface; - -/** - * The calls the host makes into the Go program, which runs in this process as a - * shared library. They are made on the UI thread and only queue what happened: the - * program works on a thread of its own. - */ -public final class Native { - private Native() {} - - static { - System.loadLibrary("viva"); - } - - /** Starts the program once for the process; later calls change nothing. */ - public static native void start(String filesDir, String cacheDir); - - /** The surface of the window has a size (and the display a density), or a new one. */ - public static native void surfaceChanged(Surface surface, int width, int height, float density); - - /** - * The system shows the surface once it has a frame: the program draws the window on it - * and this returns when the frame is presented. - */ - public static native void redrawNeeded(); - - /** The surface is going away; the program must stop drawing to it before this returns. */ - public static native void surfaceDestroyed(); - - /** One finger or pen: its action, and where, in the surface's pixels. */ - public static native void touch(int action, int pointer, float x, float y, int toolType, int buttons, int modifiers, long uptimeMillis); - - /** The activity is in front (true) or has gone behind another (false). */ - public static native void visible(boolean visible); - - /** The theme, the language or the animation setting may have changed. */ - public static native void appearanceChanged(); - - /** The activity went behind another (1) or came back (2): the program's Background and Foreground. */ - public static native void lifecycle(int kind); - - /** The system is short of memory. */ - public static native void lowMemory(); - - /** - * How far the system covers each edge of the surface, in its pixels: the bars, the display - * cutout, and the navigation bar unless the keyboard is up. Sent before the surface is - * known and whenever it changes. - */ - public static native void insets(float left, float top, float right, float bottom); - - /** The user asked to close the window (the back gesture at the root). */ - public static native void closeRequested(); - - // The input method's edits of the program's focused text input, in UTF-16 units. Each - // returns when the program has applied it and sent the editor's state (Host.editor). - - public static native void commitText(String text, int newCursorPosition); - - public static native void setComposingText(String text, int newCursorPosition); - - public static native void finishComposing(); - - public static native void deleteSurrounding(int before, int after, boolean codePoints); - - public static native void setSelection(int start, int end); - - public static native void setComposingRegion(int start, int end); - - public static native void editorAction(int action); - - /** A key of a keyboard: its Android key code, the meta state and the character it types. */ - public static native void key(int keyCode, int meta, int unicode, boolean repeat); - - /** A screen reader is reading the window, or has stopped. */ - public static native void accessibility(boolean on); - - /** A screen reader's request of a node: its place in the tree last sent, what to do, and the value of it. */ - public static native void accessible(int node, int action, float number, String text, int start, int end); - - /** A mouse over the surface. */ - public static native void hover(float x, float y, int meta, long uptimeMillis); - - public static native void hoverExit(); - - /** A wheel, in pixels. */ - public static native void scroll(float x, float y, float dx, float dy, int meta); -} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Text.java b/internal/platform/android/hostsrc/java/dev/viva/host/Text.java deleted file mode 100644 index a70768274..000000000 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Text.java +++ /dev/null @@ -1,162 +0,0 @@ -package dev.viva.host; - -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Path; -import android.graphics.RectF; -import android.graphics.Typeface; -import android.os.Build; -import android.text.Layout; -import android.text.StaticLayout; -import android.text.TextPaint; - -import java.nio.ByteBuffer; - -/** - * What the Go program asks of the system's text drawing: the width of a line, the - * extent of each of its grapheme clusters, and its pixels. The system shapes with - * Minikin and HarfBuzz and draws with Skia, so what the program measures is what is - * drawn. The program asks on one thread and caches what it learns; none of this is - * called for a line it has seen. - */ -public final class Text { - private Text() {} - - private static final TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG); - private static final Path path = new Path(); - private static final RectF bounds = new RectF(); - private static final float[] advances = new float[256]; - - /** The family the interface's proportional text is shaped in; null for the system's. */ - private static volatile String family; - - /** Moves on every change after which the same line shapes differently. */ - public static void setFamily(String name) { - family = (name == null || name.isEmpty()) ? null : name; - } - - private static Typeface face(int weight, boolean italic, boolean mono) { - Typeface base = mono ? Typeface.MONOSPACE : null; - if (base == null) { - String name = family; - base = name == null ? Typeface.DEFAULT : Typeface.create(name, Typeface.NORMAL); - } - if (Build.VERSION.SDK_INT >= 28) { - return Typeface.create(base, weight, italic); - } - int style = (weight >= 600 ? Typeface.BOLD : Typeface.NORMAL) | (italic ? Typeface.ITALIC : 0); - return Typeface.create(base, style); - } - - private static TextPaint set(float size, int weight, boolean italic, boolean mono) { - paint.setTypeface(face(weight, italic, mono)); - paint.setTextSize(size); - return paint; - } - - /** The advance of the whole line. */ - public static float width(String value, float size, int weight, boolean italic, boolean mono) { - return set(size, weight, italic, mono).measureText(value); - } - - /** The ascent and descent of the font at size, and the gap it asks between lines, in out. */ - public static void metrics(float size, int weight, boolean italic, boolean mono, float[] out) { - Paint.FontMetrics fm = set(size, weight, italic, mono).getFontMetrics(); - out[0] = -fm.ascent; - out[1] = fm.descent; - out[2] = fm.leading; - } - - /** - * The horizontal extent, from the left end of the line, of each range - * [bounds[i], bounds[i+1]) of value, in UTF-16 units: left to right in lefts and - * rights. A line that is all left-to-right adds up the advances the font gives; - * one with right-to-left text asks the layout, which orders the runs. - */ - public static void rects(String value, float size, int weight, boolean italic, boolean mono, boolean rtl, - int[] boundaries, float[] lefts, float[] rights) { - TextPaint p = set(size, weight, italic, mono); - int n = value.length(); - int count = boundaries.length - 1; - if (!rtl && !hasRightToLeft(value)) { - char[] chars = value.toCharArray(); - float[] advance = n <= advances.length ? advances : new float[n]; - p.getTextRunAdvances(chars, 0, n, 0, n, false, advance, 0); - float x = 0; - int unit = 0; - for (int i = 0; i < count; i++) { - float start = x; - // Ligatures give the first unit the whole advance and the rest none, - // so summing the units of a cluster is the cluster's width. - for (; unit < boundaries[i + 1]; unit++) { - x += advance[unit]; - } - lefts[i] = start; - rights[i] = x; - } - return; - } - StaticLayout layout = StaticLayout.Builder.obtain(value, 0, n, p, 1 << 24) - .setIncludePad(false) - .setAlignment(Layout.Alignment.ALIGN_NORMAL) - .setTextDirection(rtl ? android.text.TextDirectionHeuristics.RTL : android.text.TextDirectionHeuristics.LTR) - .build(); - for (int i = 0; i < count; i++) { - path.rewind(); - layout.getSelectionPath(boundaries[i], boundaries[i + 1], path); - path.computeBounds(bounds, true); - lefts[i] = bounds.left; - rights[i] = bounds.right; - } - } - - private static boolean hasRightToLeft(String value) { - for (int i = 0; i < value.length(); i++) { - byte d = Character.getDirectionality(value.charAt(i)); - if (d == Character.DIRECTIONALITY_RIGHT_TO_LEFT || d == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC - || d == Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING || d == Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE - || d == Character.DIRECTIONALITY_ARABIC_NUMBER) { - return true; - } - } - return false; - } - - private static Bitmap bitmap; - private static Canvas canvas; - - /** Starts a transparent bitmap of width x height pixels that draw adds runs to. */ - public static void begin(int width, int height) { - if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { - if (bitmap != null) { - bitmap.recycle(); - } - bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - canvas = new Canvas(bitmap); - } - bitmap.eraseColor(Color.TRANSPARENT); - } - - /** Draws a run of text with its left end at x and its baseline at baseline, in pixels. */ - public static void draw(String value, float x, float baseline, float size, int weight, boolean italic, boolean mono, - int argb, boolean underline, boolean rtl) { - TextPaint p = set(size, weight, italic, mono); - p.setColor(argb); - p.setUnderlineText(underline); - if (rtl) { - // Draw from the right end: the run's own direction lays its glyphs out. - canvas.drawText(value, 0, value.length(), x, baseline, p); - } else { - canvas.drawText(value, 0, value.length(), x, baseline, p); - } - p.setUnderlineText(false); - } - - /** Copies the pixels, premultiplied, in the order of Bitmap's ARGB_8888 (RGBA bytes), to out. */ - public static void end(ByteBuffer out) { - out.clear(); - bitmap.copyPixelsToBuffer(out); - } -} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java deleted file mode 100644 index 2cb32eaa0..000000000 --- a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java +++ /dev/null @@ -1,213 +0,0 @@ -package dev.viva.host; - -import android.app.Activity; -import android.content.res.Configuration; -import android.os.Bundle; -import android.view.MotionEvent; -import android.view.SurfaceHolder; -import android.view.View; -import android.view.Window; -import android.view.WindowInsets; -import android.view.WindowInsetsController; -import android.view.WindowManager; -import android.graphics.Color; -import android.os.Build; -import android.widget.FrameLayout; - -/** - * The window of a Viva program: one SurfaceView that fills the screen, which the - * program draws on with Vulkan. Everything the user does reaches the program as - * what happened; nothing here lays anything out. - */ -public class VivaActivity extends Activity implements SurfaceHolder.Callback2 { - private VivaView view; - - @Override - protected void onCreate(Bundle state) { - super.onCreate(state); - requestWindowFeature(Window.FEATURE_NO_TITLE); - view = new VivaView(this); - Host.attach(this, view); - view.getHolder().addCallback(this); - view.setOnTouchListener(this::onTouch); - // The window runs under the system bars and the display cutout, as an Android 15 window - // must; the program is told how far they cover each edge and keeps what matters inside - // them. The keyboard still shrinks the surface from the bottom. - edgeToEdge(); - FrameLayout root = new FrameLayout(this); - root.addView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); - root.setOnApplyWindowInsetsListener(VivaActivity::applyInsets); - setContentView(root); - barIcons(); // needs the decor view, which setContentView installs - if (Build.VERSION.SDK_INT >= 31) { - // The window is drawn on the surface, which the system's reveal of the splash screen - // does not follow: left to it, the reveal stops part way and leaves the window faded - // until the next layout. The splash screen goes as soon as the window is drawn. - getSplashScreen().setOnExitAnimationListener(splash -> splash.remove()); - } - Native.start(getFilesDir().getAbsolutePath(), getCacheDir().getAbsolutePath()); - } - - private void edgeToEdge() { - Window window = getWindow(); - if (Build.VERSION.SDK_INT >= 30) { - window.setDecorFitsSystemWindows(false); - } else { - window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); - } - window.setStatusBarColor(Color.TRANSPARENT); - window.setNavigationBarColor(Color.TRANSPARENT); - if (Build.VERSION.SDK_INT >= 29) { - window.setNavigationBarContrastEnforced(false); - window.setStatusBarContrastEnforced(false); - } - if (Build.VERSION.SDK_INT >= 28) { - WindowManager.LayoutParams params = window.getAttributes(); - params.layoutInDisplayCutoutMode = Build.VERSION.SDK_INT >= 30 - ? WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS - : WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; - window.setAttributes(params); - } - } - - /** The bars' icons are dark on the light theme and light on the dark one, as the system's own are. */ - private void barIcons() { - Window window = getWindow(); - boolean night = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) - == Configuration.UI_MODE_NIGHT_YES; - if (Build.VERSION.SDK_INT >= 30) { - WindowInsetsController controller = window.getInsetsController(); - if (controller != null) { - int mask = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS - | WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; - controller.setSystemBarsAppearance(night ? 0 : mask, mask); - } - } else if (Build.VERSION.SDK_INT >= 23) { - View decor = window.getDecorView(); - int light = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR - | (Build.VERSION.SDK_INT >= 26 ? View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR : 0); - int flags = decor.getSystemUiVisibility(); - decor.setSystemUiVisibility(night ? flags & ~light : flags | light); - } - } - - private boolean stopped; - - @Override - protected void onStart() { - super.onStart(); - Native.visible(true); - if (stopped) { - Native.lifecycle(2); // Foreground: it came back, it is not the first start - } - } - - @Override - protected void onStop() { - Native.visible(false); - stopped = true; - Native.lifecycle(1); // Background: the time to save what the user would miss - super.onStop(); - } - - @Override - public void onTrimMemory(int level) { - super.onTrimMemory(level); - // From the point the system runs short (TRIM_MEMORY_RUNNING_LOW) on; the level that - // only says the user interface is hidden (TRIM_MEMORY_UI_HIDDEN) is Background's. - if (level >= TRIM_MEMORY_RUNNING_LOW && level != TRIM_MEMORY_UI_HIDDEN) { - Native.lowMemory(); - } - } - - @Override - public void onLowMemory() { - super.onLowMemory(); - Native.lowMemory(); - } - - @Override - public void onConfigurationChanged(Configuration config) { - super.onConfigurationChanged(config); - barIcons(); - Native.appearanceChanged(); - } - - @Override - public void onBackPressed() { - Native.closeRequested(); - } - - @Override - public void surfaceCreated(SurfaceHolder holder) {} - - @Override - public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - Host.preferHighRefresh(holder.getSurface()); - Native.surfaceChanged(holder.getSurface(), width, height, getResources().getDisplayMetrics().density); - } - - /** The system waits for this before it shows the surface, so the program draws on it first. */ - @Override - public void surfaceRedrawNeeded(SurfaceHolder holder) { - Native.redrawNeeded(); - } - - @Override - public void surfaceDestroyed(SurfaceHolder holder) { - Native.surfaceDestroyed(); - } - - /** - * The surface is the whole window, less the keyboard from the bottom; the program is told how - * far the bars and the cutout cover each edge (the bottom one is not covered with the - * keyboard up, which covers it instead). - */ - private static WindowInsets applyInsets(View root, WindowInsets insets) { - if (Build.VERSION.SDK_INT >= 30) { - android.graphics.Insets bars = insets.getInsets( - WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout()); - boolean keyboard = insets.isVisible(WindowInsets.Type.ime()); - root.setPadding(0, 0, 0, keyboard ? insets.getInsets(WindowInsets.Type.ime()).bottom : 0); - Native.insets(bars.left, bars.top, bars.right, keyboard ? 0 : bars.bottom); - return WindowInsets.CONSUMED; - } - int bottom = insets.getSystemWindowInsetBottom(); - boolean keyboard = bottom > insets.getStableInsetBottom(); - root.setPadding(0, 0, 0, keyboard ? bottom : 0); - Native.insets(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), - insets.getSystemWindowInsetRight(), keyboard ? 0 : insets.getStableInsetBottom()); - return insets.consumeSystemWindowInsets(); - } - - private boolean onTouch(View v, MotionEvent event) { - int action = event.getActionMasked(); - long time = event.getEventTime(); - int buttons = event.getButtonState(); - int modifiers = event.getMetaState(); - switch (action) { - case MotionEvent.ACTION_MOVE: - for (int i = 0; i < event.getPointerCount(); i++) { - Native.touch(action, event.getPointerId(i), event.getX(i), event.getY(i), event.getToolType(i), buttons, modifiers, time); - } - break; - case MotionEvent.ACTION_DOWN: - case MotionEvent.ACTION_POINTER_DOWN: - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_POINTER_UP: { - int i = event.getActionIndex(); - Native.touch(action, event.getPointerId(i), event.getX(i), event.getY(i), event.getToolType(i), buttons, modifiers, time); - break; - } - case MotionEvent.ACTION_CANCEL: - for (int i = 0; i < event.getPointerCount(); i++) { - Native.touch(action, event.getPointerId(i), event.getX(i), event.getY(i), event.getToolType(i), buttons, modifiers, time); - } - break; - default: - return false; - } - return true; - } -} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaInputConnection.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaInputConnection.java deleted file mode 100644 index efbd13184..000000000 --- a/internal/platform/android/hostsrc/java/dev/viva/host/VivaInputConnection.java +++ /dev/null @@ -1,121 +0,0 @@ -package dev.viva.host; - -import android.view.KeyEvent; -import android.view.View; -import android.view.inputmethod.BaseInputConnection; -import android.view.inputmethod.CompletionInfo; -import android.view.inputmethod.ExtractedText; -import android.view.inputmethod.ExtractedTextRequest; - -/** - * What an input method says to the program's focused text input. Each edit is sent to - * the program and answered when it has been applied, with the editor's state (Editor) - * as it is after, because a keyboard asks what is around the cursor as soon as it has - * typed. - */ -final class VivaInputConnection extends BaseInputConnection { - VivaInputConnection(View view) { - super(view, false); - } - - @Override - public boolean commitText(CharSequence text, int newCursorPosition) { - Native.commitText(text.toString(), newCursorPosition); - return true; - } - - @Override - public boolean setComposingText(CharSequence text, int newCursorPosition) { - Native.setComposingText(text.toString(), newCursorPosition); - return true; - } - - @Override - public boolean finishComposingText() { - Native.finishComposing(); - return true; - } - - @Override - public boolean deleteSurroundingText(int before, int after) { - Native.deleteSurrounding(before, after, false); - return true; - } - - @Override - public boolean deleteSurroundingTextInCodePoints(int before, int after) { - Native.deleteSurrounding(before, after, true); - return true; - } - - @Override - public boolean setSelection(int start, int end) { - Native.setSelection(start, end); - return true; - } - - @Override - public boolean setComposingRegion(int start, int end) { - Native.setComposingRegion(start, end); - return true; - } - - @Override - public boolean performEditorAction(int action) { - Native.editorAction(action); - return true; - } - - @Override - public boolean sendKeyEvent(KeyEvent event) { - // A soft keyboard's Delete and Enter come as keys. - if (event.getAction() == KeyEvent.ACTION_DOWN) { - Native.key(event.getKeyCode(), event.getMetaState(), event.getUnicodeChar(event.getMetaState()), event.getRepeatCount() > 0); - } - return true; - } - - @Override - public CharSequence getTextBeforeCursor(int length, int flags) { - return Editor.before(length); - } - - @Override - public CharSequence getTextAfterCursor(int length, int flags) { - return Editor.after(length); - } - - @Override - public CharSequence getSelectedText(int flags) { - return Editor.selected(); - } - - @Override - public int getCursorCapsMode(int reqModes) { - return 0; - } - - @Override - public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { - ExtractedText extracted = new ExtractedText(); - extracted.text = Editor.text(); - extracted.selectionStart = Editor.selectionStart(); - extracted.selectionEnd = Editor.selectionEnd(); - return extracted; - } - - @Override - public boolean commitCompletion(CompletionInfo text) { - return false; - } - - @Override - public boolean beginBatchEdit() { - return true; - } - - @Override - public boolean endBatchEdit() { - return true; - } -} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java deleted file mode 100644 index b71d00de0..000000000 --- a/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java +++ /dev/null @@ -1,140 +0,0 @@ -package dev.viva.host; - -import android.content.Context; -import android.text.InputType; -import android.view.KeyEvent; -import android.view.MotionEvent; -import android.view.SurfaceView; -import android.view.ViewConfiguration; -import android.view.accessibility.AccessibilityManager; -import android.view.accessibility.AccessibilityNodeProvider; -import android.view.inputmethod.EditorInfo; -import android.view.inputmethod.InputConnection; -import android.view.inputmethod.InputMethodManager; - -/** - * The surface the program draws on, which is also what the keyboard types into when - * the program has a text input focused. - */ -final class VivaView extends SurfaceView { - private boolean editing; - private boolean multiline; - private boolean secure; - - private final Accessibility accessibility = new Accessibility(this); - - VivaView(Context context) { - super(context); - setFocusable(true); - setFocusableInTouchMode(true); - setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); - } - - Accessibility accessibility() { - return accessibility; - } - - @Override - public AccessibilityNodeProvider getAccessibilityNodeProvider() { - return accessibility; - } - - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - AccessibilityManager manager = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); - if (manager != null) { - Native.accessibility(manager.isEnabled()); - manager.addAccessibilityStateChangeListener(Native::accessibility); - } - } - - /** Makes the view a text editor, or not, and restarts the input method on it. */ - void configure(boolean editing, boolean multiline, boolean secure) { - boolean restart = this.editing != editing || this.multiline != multiline || this.secure != secure; - this.editing = editing; - this.multiline = multiline; - this.secure = secure; - InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - if (imm == null) { - return; - } - if (!editing) { - imm.hideSoftInputFromWindow(getWindowToken(), 0); - if (restart) { - imm.restartInput(this); - } - return; - } - requestFocus(); - if (restart) { - imm.restartInput(this); - } - imm.showSoftInput(this, 0); - } - - /** The program changed the text under the input method. */ - void editorChanged() { - InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - if (imm != null && editing) { - imm.updateSelection(this, Editor.selectionStart(), Editor.selectionEnd(), Editor.compositionStart(), Editor.compositionEnd()); - } - } - - @Override - public boolean onCheckIsTextEditor() { - return editing; - } - - @Override - public InputConnection onCreateInputConnection(EditorInfo info) { - if (!editing) { - return null; - } - int type = InputType.TYPE_CLASS_TEXT; - if (multiline) { - type |= InputType.TYPE_TEXT_FLAG_MULTI_LINE; - } - if (secure) { - type |= InputType.TYPE_TEXT_VARIATION_PASSWORD; - } - info.inputType = type; - info.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_FLAG_NO_EXTRACT_UI - | (multiline ? EditorInfo.IME_ACTION_NONE : EditorInfo.IME_ACTION_DONE); - info.initialSelStart = Editor.selectionStart(); - info.initialSelEnd = Editor.selectionEnd(); - return new VivaInputConnection(this); - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if (keyCode == KeyEvent.KEYCODE_BACK) { - return super.onKeyDown(keyCode, event); - } - Native.key(keyCode, event.getMetaState(), event.getUnicodeChar(event.getMetaState()), event.getRepeatCount() > 0); - return true; - } - - @Override - public boolean onGenericMotionEvent(MotionEvent event) { - long time = event.getEventTime(); - switch (event.getActionMasked()) { - case MotionEvent.ACTION_HOVER_MOVE: - case MotionEvent.ACTION_HOVER_ENTER: - Native.hover(event.getX(), event.getY(), event.getMetaState(), time); - return true; - case MotionEvent.ACTION_HOVER_EXIT: - Native.hoverExit(); - return true; - case MotionEvent.ACTION_SCROLL: { - ViewConfiguration configuration = ViewConfiguration.get(getContext()); - float horizontal = event.getAxisValue(MotionEvent.AXIS_HSCROLL) * configuration.getScaledHorizontalScrollFactor(); - float vertical = event.getAxisValue(MotionEvent.AXIS_VSCROLL) * configuration.getScaledVerticalScrollFactor(); - Native.scroll(event.getX(), event.getY(), horizontal, vertical, event.getMetaState()); - return true; - } - default: - return super.onGenericMotionEvent(event); - } - } -} diff --git a/internal/platform/android/input_android.go b/internal/platform/android/input_android.go deleted file mode 100644 index 1ca1366e7..000000000 --- a/internal/platform/android/input_android.go +++ /dev/null @@ -1,254 +0,0 @@ -//go:build android - -package android - -/* -#include "jni_android.h" -*/ -import "C" - -import ( - "unsafe" - - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/input" - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/platform/imebridge" -) - -// Android's key codes of the keys that are not text, and its meta state. -const ( - keycodeBack = 4 - keycodeDpadUp = 19 - keycodeDpadDown = 20 - keycodeDpadLeft = 21 - keycodeDpadRight = 22 - keycodeTab = 61 - keycodeSpace = 62 - keycodeEnter = 66 - keycodeDelete = 67 // the key that deletes backward - keycodeEscape = 111 - keycodeForwardDel = 112 - keycodeMoveHome = 122 - keycodeMoveEnd = 123 - keycodeInsert = 124 - keycodePageUp = 92 - keycodePageDown = 93 - keycodeF1 = 131 - keycodeF12 = 142 - keycodeNumpadEnter = 160 -) - -// keyOfCode is the key an Android key code names, for the keys that are not text. -func keyOfCode(code int32) gfx.Key { - if code >= keycodeF1 && code <= keycodeF12 { - return gfx.KeyF1 + gfx.Key(code-keycodeF1) - } - switch code { - case keycodeDpadUp: - return gfx.KeyUp - case keycodeDpadDown: - return gfx.KeyDown - case keycodeDpadLeft: - return gfx.KeyLeft - case keycodeDpadRight: - return gfx.KeyRight - case keycodeTab: - return gfx.KeyTab - case keycodeSpace: - return gfx.KeySpace - case keycodeEnter, keycodeNumpadEnter: - return gfx.KeyEnter - case keycodeDelete: - return gfx.KeyBackspace - case keycodeEscape: - return gfx.KeyEscape - case keycodeForwardDel: - return gfx.KeyDelete - case keycodeMoveHome: - return gfx.KeyHome - case keycodeMoveEnd: - return gfx.KeyEnd - case keycodeInsert: - return gfx.KeyInsert - case keycodePageUp: - return gfx.KeyPageUp - case keycodePageDown: - return gfx.KeyPageDown - } - return gfx.KeyUnknown -} - -// textOperation is what the input method does to the text input. -type textOperation uint8 - -const ( - opCommit textOperation = iota + 1 - opSetComposing - opFinish - opDeleteSurrounding - opSelect - opMarkRange - opAction - opKey -) - -// textInput is the text input the application has focused. -type textInput struct { - session imebridge.Session - input *platform.TextInput -} - -// setTextInput follows the application's wish for its text input: another one, the -// same one with other text, or none (platform.TextInputUpdate). -func (win *window) setTextInput(update platform.TextInputUpdate) { - if !update.Changed { - return - } - if update.Input == nil { - if win.text != nil { - win.text = nil - C.viva_host_keyboard(0, 0, 0) - } - return - } - input := update.Input - restart := win.text == nil || win.text.input.Target != input.Target || win.text.input.Multiline != input.Multiline || win.text.input.Secure != input.Secure - win.text = &textInput{session: imebridge.Session{Handler: input.OnEvent, State: input.State}, input: input} - win.pushEditor() - if restart { - C.viva_host_keyboard(1, boolInt(input.Multiline), boolInt(input.Secure)) - } -} - -func boolInt(value bool) C.int { - if value { - return 1 - } - return 0 -} - -// pushEditor gives the host the text input's state, for the input method to read. -func (win *window) pushEditor() { - mirror := win.text.session.Mirror() - units := utf16Units(mirror.Text) - var data *C.uint16_t - if len(units) > 0 { - data = (*C.uint16_t)(unsafe.Pointer(&units[0])) - } - C.viva_host_editor(data, C.int(len(units)), C.int(mirror.SelStart), C.int(mirror.SelEnd), C.int(mirror.CompStart), C.int(mirror.CompEnd)) -} - -// edit is one edit of the input method. -type edit struct { - operation textOperation - text string - first, last int32 // newCursor, the range, or what to delete before and after - codePoints bool - editorAction int32 - action imebridge.KeyAction -} - -// textEdit applies an input method's edit to the application's text input, sends the state -// after it back, and shows what the application painted for it. -func (application *application) textEdit(ev event) { - if ev.ack != nil { - defer close(ev.ack) - } - win := application.window - if win == nil || win.closed || win.text == nil { - return - } - defer application.guard() - text, session := win.text, &win.text.session - var err error - switch ev.edit.operation { - case opCommit: - err = session.Commit(ev.edit.text, int(ev.edit.first)) - case opSetComposing: - err = session.SetComposing(ev.edit.text, int(ev.edit.first)) - case opFinish: - err = session.Finish() - case opDeleteSurrounding: - err = session.DeleteSurrounding(int(ev.edit.first), int(ev.edit.last), ev.edit.codePoints) - case opSelect: - err = session.Select(int(ev.edit.first), int(ev.edit.last)) - case opMarkRange: - err = session.MarkRange(int(ev.edit.first), int(ev.edit.last)) - case opKey: - err = ev.edit.action.Apply(session) - case opAction: - application.editorAction(ev.edit.editorAction) - return - } - if err != nil { - application.fail(err) - return - } - text.input.State = session.State - win.pushEditor() - if win.config.OnRedraw != nil { - frame, err := win.config.OnRedraw() - if err == nil { - err = win.present(frame) - } - if err != nil { - application.fail(err) - } - } -} - -// editorAction is the action key of a keyboard (Done, Go, Search): it is Enter. -func (application *application) editorAction(int32) { - application.keyEvent(event{keyCode: keycodeEnter}) -} - -// keyEvent gives the application a key of a keyboard. A key that is not text is a key -// event; a character, in a window with a text input, is typed into it; a chord with -// Control or Meta and a character is offered as a shortcut first. -func (application *application) keyEvent(ev event) { - win := application.window - if win == nil || win.closed || win.renderer == nil { - return - } - defer application.guard() - modifiers := modifiers(ev.modifiers) - key := keyOfCode(ev.keyCode) - character := "" - if ev.unicode > 0 { - character = string(rune(ev.unicode)) - } - chord := modifiers&(input.ModifierControl|input.ModifierMeta) != 0 && character != "" - if chord && win.config.OnShortcut != nil { - frame, handled, err := win.config.OnShortcut(platform.KeyEvent{Key: key, Modifiers: modifiers, Repeat: ev.repeat, Text: character}) - if err == nil { - err = win.present(frame) - } - if err != nil { - application.fail(err) - return - } - if handled { - return - } - } - if win.text != nil && !chord { - if action, ok := imebridge.KeyEdit(key, modifiers, character, win.text.input); ok { - application.textEdit(event{edit: edit{operation: opKey, action: action}}) - return - } - } - if key == gfx.KeyUnknown && !chord { - return - } - if win.config.OnKey == nil { - return - } - frame, err := win.config.OnKey(platform.KeyEvent{Key: key, Modifiers: modifiers, Repeat: ev.repeat, Text: character}) - if err == nil { - err = win.present(frame) - } - if err != nil { - application.fail(err) - } -} diff --git a/internal/platform/android/jni_android.c b/internal/platform/android/jni_android.c deleted file mode 100644 index c213dfa57..000000000 --- a/internal/platform/android/jni_android.c +++ /dev/null @@ -1,319 +0,0 @@ -#include "jni_android.h" - -#include -#include -#include -#include - -static JavaVM *vm; -static jclass hostClass, textClass; -static jmethodID hostFinish, hostSetTitle, hostEditor, hostKeyboard; -static jmethodID hostTree, hostClipboardText, hostSetClipboardText, hostOpenURL, hostLanguages, hostDarkTheme, hostAnimationsOff; -static jmethodID textWidth, textMetrics, textRects, textSetFamily, textBegin, textDraw, textEnd; - -/* A JNI_OnLoad finds the host's classes while the loader that holds them is the caller's. */ -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { - JNIEnv *env; - vm = jvm; - if ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) { - return JNI_ERR; - } - jclass host = (*env)->FindClass(env, "dev/viva/host/Host"); - jclass text = (*env)->FindClass(env, "dev/viva/host/Text"); - if (host == NULL || text == NULL) { - return JNI_ERR; - } - hostClass = (*env)->NewGlobalRef(env, host); - textClass = (*env)->NewGlobalRef(env, text); - hostFinish = (*env)->GetStaticMethodID(env, hostClass, "finish", "()V"); - hostSetTitle = (*env)->GetStaticMethodID(env, hostClass, "setTitle", "(Ljava/lang/String;)V"); - hostEditor = (*env)->GetStaticMethodID(env, hostClass, "editor", "(Ljava/lang/String;IIII)V"); - hostKeyboard = (*env)->GetStaticMethodID(env, hostClass, "keyboard", "(ZZZ)V"); - hostTree = (*env)->GetStaticMethodID(env, hostClass, "tree", "([F[I[F[C[I)V"); - hostClipboardText = (*env)->GetStaticMethodID(env, hostClass, "clipboardText", "()Ljava/lang/String;"); - hostSetClipboardText = (*env)->GetStaticMethodID(env, hostClass, "setClipboardText", "(Ljava/lang/String;)Z"); - hostOpenURL = (*env)->GetStaticMethodID(env, hostClass, "openURL", "(Ljava/lang/String;)Z"); - hostLanguages = (*env)->GetStaticMethodID(env, hostClass, "languages", "()Ljava/lang/String;"); - hostDarkTheme = (*env)->GetStaticMethodID(env, hostClass, "darkTheme", "()I"); - hostAnimationsOff = (*env)->GetStaticMethodID(env, hostClass, "animationsOff", "()Z"); - textWidth = (*env)->GetStaticMethodID(env, textClass, "width", "(Ljava/lang/String;FIZZ)F"); - textMetrics = (*env)->GetStaticMethodID(env, textClass, "metrics", "(FIZZ[F)V"); - textRects = (*env)->GetStaticMethodID(env, textClass, "rects", "(Ljava/lang/String;FIZZZ[I[F[F)V"); - textSetFamily = (*env)->GetStaticMethodID(env, textClass, "setFamily", "(Ljava/lang/String;)V"); - textBegin = (*env)->GetStaticMethodID(env, textClass, "begin", "(II)V"); - textDraw = (*env)->GetStaticMethodID(env, textClass, "draw", "(Ljava/lang/String;FFFIZZIZZ)V"); - textEnd = (*env)->GetStaticMethodID(env, textClass, "end", "(Ljava/nio/ByteBuffer;)V"); - return JNI_VERSION_1_6; -} - -/* A thread that attached itself must detach before it exits, or the runtime aborts: - * a key whose destructor does it as the thread ends. */ -static pthread_key_t detachKey; -static pthread_once_t detachOnce = PTHREAD_ONCE_INIT; - -static void detach(void *unused) { - if (vm != NULL) { - (*vm)->DetachCurrentThread(vm); - } -} - -static void makeDetachKey(void) { pthread_key_create(&detachKey, detach); } - -static JNIEnv *env(void) { - JNIEnv *e = NULL; - if (vm == NULL) { - return NULL; - } - if ((*vm)->GetEnv(vm, (void **)&e, JNI_VERSION_1_6) == JNI_EDETACHED) { - if ((*vm)->AttachCurrentThread(vm, &e, NULL) != JNI_OK) { - return NULL; - } - pthread_once(&detachOnce, makeDetachKey); - pthread_setspecific(detachKey, e); - } - return e; -} - -int viva_attach_thread(void) { return env() != NULL; } - -char *viva_string_chars(JNIEnv *e, jstring value) { - if (value == NULL) { - return NULL; - } - const char *chars = (*e)->GetStringUTFChars(e, value, NULL); - if (chars == NULL) { - return NULL; - } - char *copy = strdup(chars); - (*e)->ReleaseStringUTFChars(e, value, chars); - return copy; -} - -/* clear drops a pending Java exception: a call into the host must not leave one behind. */ -static int failed(JNIEnv *e) { - if ((*e)->ExceptionCheck(e)) { - (*e)->ExceptionClear(e); - return 1; - } - return 0; -} - -float viva_text_width(const uint16_t *value, int length, float size, int weight, int italic, int mono) { - JNIEnv *e = env(); - if (e == NULL) { - return -1; - } - jstring s = (*e)->NewString(e, (const jchar *)value, length); - jfloat width = (*e)->CallStaticFloatMethod(e, textClass, textWidth, s, size, weight, italic != 0, mono != 0); - (*e)->DeleteLocalRef(e, s); - return failed(e) ? -1 : width; -} - -void viva_text_metrics(float size, int weight, int italic, int mono, float *out) { - JNIEnv *e = env(); - out[0] = out[1] = out[2] = 0; - if (e == NULL) { - return; - } - jfloatArray array = (*e)->NewFloatArray(e, 3); - (*e)->CallStaticVoidMethod(e, textClass, textMetrics, size, weight, italic != 0, mono != 0, array); - if (!failed(e)) { - (*e)->GetFloatArrayRegion(e, array, 0, 3, out); - } - (*e)->DeleteLocalRef(e, array); -} - -int viva_text_rects(const uint16_t *value, int length, float size, int weight, int italic, int mono, int rtl, - const int32_t *bounds, int boundCount, float *lefts, float *rights) { - JNIEnv *e = env(); - if (e == NULL) { - return 0; - } - int count = boundCount - 1; - jstring s = (*e)->NewString(e, (const jchar *)value, length); - jintArray b = (*e)->NewIntArray(e, boundCount); - jfloatArray l = (*e)->NewFloatArray(e, count); - jfloatArray r = (*e)->NewFloatArray(e, count); - (*e)->SetIntArrayRegion(e, b, 0, boundCount, (const jint *)bounds); - (*e)->CallStaticVoidMethod(e, textClass, textRects, s, size, weight, italic != 0, mono != 0, rtl != 0, b, l, r); - int ok = !failed(e); - if (ok) { - (*e)->GetFloatArrayRegion(e, l, 0, count, lefts); - (*e)->GetFloatArrayRegion(e, r, 0, count, rights); - } - (*e)->DeleteLocalRef(e, s); - (*e)->DeleteLocalRef(e, b); - (*e)->DeleteLocalRef(e, l); - (*e)->DeleteLocalRef(e, r); - return ok; -} - -void viva_text_set_family(const uint16_t *name, int length) { - JNIEnv *e = env(); - if (e == NULL) { - return; - } - jstring s = length > 0 ? (*e)->NewString(e, (const jchar *)name, length) : NULL; - (*e)->CallStaticVoidMethod(e, textClass, textSetFamily, s); - failed(e); - if (s != NULL) { - (*e)->DeleteLocalRef(e, s); - } -} - -int viva_text_begin(int width, int height) { - JNIEnv *e = env(); - if (e == NULL) { - return 0; - } - (*e)->CallStaticVoidMethod(e, textClass, textBegin, width, height); - return !failed(e); -} - -void viva_text_draw(const uint16_t *value, int length, float x, float baseline, float size, int weight, int italic, - int mono, int argb, int underline, int rtl) { - JNIEnv *e = env(); - if (e == NULL) { - return; - } - jstring s = (*e)->NewString(e, (const jchar *)value, length); - (*e)->CallStaticVoidMethod(e, textClass, textDraw, s, x, baseline, size, weight, italic != 0, mono != 0, argb, - underline != 0, rtl != 0); - failed(e); - (*e)->DeleteLocalRef(e, s); -} - -int viva_text_end(void *out, int64_t capacity) { - JNIEnv *e = env(); - if (e == NULL) { - return 0; - } - jobject buffer = (*e)->NewDirectByteBuffer(e, out, capacity); - if (buffer == NULL) { - failed(e); - return 0; - } - (*e)->CallStaticVoidMethod(e, textClass, textEnd, buffer); - (*e)->DeleteLocalRef(e, buffer); - return !failed(e); -} - -void viva_host_finish(void) { - JNIEnv *e = env(); - if (e != NULL) { - (*e)->CallStaticVoidMethod(e, hostClass, hostFinish); - failed(e); - } -} - -void viva_host_set_title(const uint16_t *title, int length) { - JNIEnv *e = env(); - if (e == NULL) { - return; - } - jstring s = (*e)->NewString(e, (const jchar *)title, length); - (*e)->CallStaticVoidMethod(e, hostClass, hostSetTitle, s); - failed(e); - (*e)->DeleteLocalRef(e, s); -} - -void viva_log(int priority, const char *line) { __android_log_write(priority, "viva", line); } - -void viva_host_editor(const uint16_t *text, int length, int selectionStart, int selectionEnd, int compositionStart, int compositionEnd) { - JNIEnv *e = env(); - if (e == NULL) { - return; - } - jstring s = (*e)->NewString(e, (const jchar *)text, length); - (*e)->CallStaticVoidMethod(e, hostClass, hostEditor, s, selectionStart, selectionEnd, compositionStart, compositionEnd); - failed(e); - (*e)->DeleteLocalRef(e, s); -} - -void viva_host_keyboard(int editing, int multiline, int secure) { - JNIEnv *e = env(); - if (e != NULL) { - (*e)->CallStaticVoidMethod(e, hostClass, hostKeyboard, editing != 0, multiline != 0, secure != 0); - failed(e); - } -} - - -static char *host_string(jmethodID method) { - JNIEnv *e = env(); - if (e == NULL) { - return NULL; - } - jstring s = (jstring)(*e)->CallStaticObjectMethod(e, hostClass, method); - if (failed(e) || s == NULL) { - return NULL; - } - char *copy = viva_string_chars(e, s); - (*e)->DeleteLocalRef(e, s); - return copy; -} - -char *viva_host_clipboard_text(void) { return host_string(hostClipboardText); } - -char *viva_host_languages(void) { return host_string(hostLanguages); } - -static int host_text_call(jmethodID method, const uint16_t *text, int length) { - JNIEnv *e = env(); - if (e == NULL) { - return 0; - } - jstring s = (*e)->NewString(e, (const jchar *)text, length); - jboolean ok = (*e)->CallStaticBooleanMethod(e, hostClass, method, s); - (*e)->DeleteLocalRef(e, s); - return !failed(e) && ok; -} - -int viva_host_set_clipboard_text(const uint16_t *text, int length) { return host_text_call(hostSetClipboardText, text, length); } - -int viva_host_open_url(const uint16_t *url, int length) { return host_text_call(hostOpenURL, url, length); } - -int viva_host_dark_theme(void) { - JNIEnv *e = env(); - if (e == NULL) { - return -1; - } - jint theme = (*e)->CallStaticIntMethod(e, hostClass, hostDarkTheme); - return failed(e) ? -1 : theme; -} - -int viva_host_animations_off(void) { - JNIEnv *e = env(); - if (e == NULL) { - return 0; - } - jboolean off = (*e)->CallStaticBooleanMethod(e, hostClass, hostAnimationsOff); - return !failed(e) && off; -} - -void viva_host_tree(int count, const float *bounds, const int32_t *ints, const float *ranges, const uint16_t *chars, int charCount, const int32_t *offsets) { - JNIEnv *e = env(); - if (e == NULL) { - return; - } - jfloatArray b = (*e)->NewFloatArray(e, 4 * count); - jintArray i = (*e)->NewIntArray(e, 5 * count); - jfloatArray r = (*e)->NewFloatArray(e, 3 * count); - jcharArray c = (*e)->NewCharArray(e, charCount); - jintArray o = (*e)->NewIntArray(e, 4 * count + 1); - if (count > 0) { - (*e)->SetFloatArrayRegion(e, b, 0, 4 * count, bounds); - (*e)->SetIntArrayRegion(e, i, 0, 5 * count, (const jint *)ints); - (*e)->SetFloatArrayRegion(e, r, 0, 3 * count, ranges); - } - if (charCount > 0) { - (*e)->SetCharArrayRegion(e, c, 0, charCount, (const jchar *)chars); - } - (*e)->SetIntArrayRegion(e, o, 0, 4 * count + 1, (const jint *)offsets); - (*e)->CallStaticVoidMethod(e, hostClass, hostTree, b, i, r, c, o); - failed(e); - (*e)->DeleteLocalRef(e, b); - (*e)->DeleteLocalRef(e, i); - (*e)->DeleteLocalRef(e, r); - (*e)->DeleteLocalRef(e, c); - (*e)->DeleteLocalRef(e, o); -} diff --git a/internal/platform/android/jni_android.h b/internal/platform/android/jni_android.h deleted file mode 100644 index a107b53a6..000000000 --- a/internal/platform/android/jni_android.h +++ /dev/null @@ -1,41 +0,0 @@ -// The host's calls, from the Go program's threads. - -#include -#include - -/* log writes a line to the system log under the tag "viva". */ -void viva_log(int priority, const char *line); - -/* attach_thread makes the calling OS thread known to the JVM; it stays attached. */ -int viva_attach_thread(void); - -/* string_chars copies a Java string to malloc memory as modified UTF-8; free it. */ -char *viva_string_chars(JNIEnv *env, jstring value); - -/* The text helpers (dev.viva.host.Text), over UTF-16. */ -float viva_text_width(const uint16_t *value, int length, float size, int weight, int italic, int mono); -void viva_text_metrics(float size, int weight, int italic, int mono, float *out); -int viva_text_rects(const uint16_t *value, int length, float size, int weight, int italic, int mono, int rtl, - const int32_t *bounds, int boundCount, float *lefts, float *rights); -void viva_text_set_family(const uint16_t *name, int length); -int viva_text_begin(int width, int height); -void viva_text_draw(const uint16_t *value, int length, float x, float baseline, float size, int weight, int italic, - int mono, int argb, int underline, int rtl); -int viva_text_end(void *out, int64_t capacity); - -/* The host (dev.viva.host.Host). */ -void viva_host_editor(const uint16_t *text, int length, int selectionStart, int selectionEnd, int compositionStart, int compositionEnd); -void viva_host_keyboard(int editing, int multiline, int secure); -void viva_host_finish(void); -/* viva_host_tree gives the host the accessibility tree: per node four floats of bounds, five ints - * (role, flags, level, position, size) and three of range (min, max, now), and four strings - * (label, value, hint, description) in one UTF-16 buffer cut by offsets, four per node plus one. */ -void viva_host_tree(int count, const float *bounds, const int32_t *ints, const float *ranges, const uint16_t *chars, int charCount, const int32_t *offsets); -/* The strings the system answers with, malloc memory the caller frees; NULL for none. */ -char *viva_host_clipboard_text(void); -int viva_host_set_clipboard_text(const uint16_t *text, int length); -int viva_host_open_url(const uint16_t *url, int length); -char *viva_host_languages(void); -int viva_host_dark_theme(void); -int viva_host_animations_off(void); -void viva_host_set_title(const uint16_t *title, int length); diff --git a/internal/platform/android/link_android.s b/internal/platform/android/link_android.s deleted file mode 100644 index 9823b839c..000000000 --- a/internal/platform/android/link_android.s +++ /dev/null @@ -1,3 +0,0 @@ -//go:build android -// An empty assembly file lets applicationMain be declared without a body, which -// go:linkname to the program's main needs. diff --git a/internal/platform/android/log_android.go b/internal/platform/android/log_android.go deleted file mode 100644 index 805bbccdb..000000000 --- a/internal/platform/android/log_android.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build android - -package android - -/* -#cgo LDFLAGS: -llog -#include -#include "jni_android.h" -*/ -import "C" - -import ( - "fmt" - "unsafe" -) - -// Priorities of the system log. -const ( - logInfo = 4 - logError = 6 -) - -// logf writes a line to the system log (adb logcat -s viva). -func logf(priority int, format string, args ...any) { - line := C.CString(fmt.Sprintf(format, args...)) - defer C.free(unsafe.Pointer(line)) - C.viva_log(C.int(priority), line) -} diff --git a/internal/platform/android/surface_android.go b/internal/platform/android/surface_android.go deleted file mode 100644 index 3fa640d53..000000000 --- a/internal/platform/android/surface_android.go +++ /dev/null @@ -1,55 +0,0 @@ -//go:build android - -package android - -/* -#cgo LDFLAGS: -landroid -#include -*/ -import "C" - -import ( - "errors" - "unsafe" - - "github.com/vivaui/viva/internal/platform/vulkan" -) - -const ( - vkStructureAndroidSurfaceCreateInfo = 1000008000 -) - -type vkAndroidSurfaceCreateInfo struct { - SType uint32 - _ uint32 - Next uintptr - Flags uint32 - _ uint32 - Window uintptr -} - -// surfaceSource makes the Vulkan surface of the ANativeWindow the window holds now: -// the renderer asks again whenever it has to make its surface again, and the window -// then is the one the host last gave. -func (win *window) surfaceSource() (vulkan.SurfaceSource, error) { - var create func(uintptr, *vkAndroidSurfaceCreateInfo, unsafe.Pointer, *uintptr) int32 - if err := vulkan.Bind(&create, "vkCreateAndroidSurfaceKHR"); err != nil { - return vulkan.SurfaceSource{}, err - } - return vulkan.SurfaceSource{ - Extension: "VK_KHR_android_surface", - HostSize: true, - Create: func(instance uintptr) (uintptr, error) { - native := win.native - if native == nil { - return 0, errors.New("android: the window has no surface") - } - info := vkAndroidSurfaceCreateInfo{SType: vkStructureAndroidSurfaceCreateInfo, Window: uintptr(unsafe.Pointer(native))} - var surface uintptr - if err := vulkan.Check(create(instance, &info, nil, &surface), "create Android surface"); err != nil { - return 0, err - } - return surface, nil - }, - }, nil -} diff --git a/internal/platform/android/system_android.go b/internal/platform/android/system_android.go deleted file mode 100644 index 3189fe268..000000000 --- a/internal/platform/android/system_android.go +++ /dev/null @@ -1,64 +0,0 @@ -//go:build android - -package android - -/* -#include -#include "jni_android.h" -*/ -import "C" - -import ( - "strings" - "unsafe" -) - -// What the system answers an application with, from the host's calls into Android's -// services. They are safe from any goroutine. - -func hostString(chars *C.char) (string, bool) { - if chars == nil { - return "", false - } - defer C.free(unsafe.Pointer(chars)) - return C.GoString(chars), true -} - -// ClipboardText is the text on the clipboard, false when there is none or the system will -// not say (Android lets only the application in front read it). -func ClipboardText() (string, bool) { return hostString(C.viva_host_clipboard_text()) } - -// SetClipboardText puts text on the clipboard. -func SetClipboardText(text string) bool { - units := utf16Units(text) - var data *C.uint16_t - if len(units) > 0 { - data = (*C.uint16_t)(unsafe.Pointer(&units[0])) - } - return C.viva_host_set_clipboard_text(data, C.int(len(units))) != 0 -} - -// OpenURL opens a link in the app that takes it. -func OpenURL(url string) bool { - units := utf16Units(url) - if len(units) == 0 { - return false - } - return C.viva_host_open_url((*C.uint16_t)(unsafe.Pointer(&units[0])), C.int(len(units))) != 0 -} - -// PreferredLanguages are the user's languages, most preferred first, as BCP 47 tags. -func PreferredLanguages() []string { - tags, ok := hostString(C.viva_host_languages()) - if !ok || tags == "" { - return nil - } - return strings.Split(tags, "\n") -} - -// DarkTheme is 1 when the system shows the dark theme, 0 for the light one and -1 when it -// does not say. -func DarkTheme() int { return int(C.viva_host_dark_theme()) } - -// AnimationsOff reports whether the user turned animations off. -func AnimationsOff() bool { return C.viva_host_animations_off() != 0 } diff --git a/internal/platform/android/text_android.go b/internal/platform/android/text_android.go deleted file mode 100644 index 210fd09c1..000000000 --- a/internal/platform/android/text_android.go +++ /dev/null @@ -1,304 +0,0 @@ -//go:build android - -package android - -/* -#include -#include "jni_android.h" -*/ -import "C" - -import ( - "errors" - "math" - "sync" - "unicode/utf16" - "unsafe" - - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/bidi" - "github.com/vivaui/viva/internal/lineengine" - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/platform/vulkan" - "github.com/vivaui/viva/internal/textmetrics" -) - -// The Android text engine is the shared line engine over the system's own text -// drawing (dev.viva.host.Text): the width of a line and the extent of each of its -// grapheme clusters come from the font Android draws it with, shaped by Minikin, so -// what is measured is what is on screen. A line that has been measured is answered -// from the engine's tables and crosses into Java no more. - -// measurer is the line engine's view of the system's text drawing. The Java side -// keeps one Paint and one bitmap, so every call is made under mu. -type measurer struct { - mu sync.Mutex - units []uint16 - pixels unsafe.Pointer - capacity int - invalidate func() -} - -var _ lineengine.Measurer = (*measurer)(nil) -var _ lineengine.StyledMeasurer = (*measurer)(nil) -var _ lineengine.Rasterizer = (*measurer)(nil) - -// shared is the one measurer of the process: the engine and the Vulkan renderer's -// label drawing read the same fonts. -var shared = &measurer{} - -// encode puts value in UTF-16 in the measurer's scratch, which is valid until the -// next call. The caller holds mu. -func (m *measurer) encode(value string) (*C.uint16_t, C.int) { - m.units = m.units[:0] - for _, r := range value { - if r >= 0x10000 { - high, low := utf16.EncodeRune(r) - m.units = append(m.units, uint16(high), uint16(low)) - } else { - m.units = append(m.units, uint16(r)) - } - } - if len(m.units) == 0 { - return nil, 0 - } - return (*C.uint16_t)(unsafe.Pointer(&m.units[0])), C.int(len(m.units)) -} - -// weightClass is the CSS weight of a gfx weight: the steps the platforms' own -// engines take. -func weightClass(weight float32) int { - switch { - case weight >= 0.34: - return 700 - case weight >= 0.20: - return 600 - case weight >= 0.10: - return 500 - } - return 400 -} - -func cBool(value bool) C.int { - if value { - return 1 - } - return 0 -} - -func (m *measurer) SetInvalidate(invalidate func()) { m.invalidate = invalidate } - -func (m *measurer) Width(value string, size, weight float32, rtl bool) float32 { - return m.WidthStyle(value, size, weight, false, rtl) -} - -func (m *measurer) WidthStyle(value string, size, weight float32, italic, rtl bool) float32 { - if value == "" { - return 0 - } - m.mu.Lock() - defer m.mu.Unlock() - units, length := m.encode(value) - width := float32(C.viva_text_width(units, length, C.float(size), C.int(weightClass(weight)), cBool(italic), 0)) - if width < 0 { - return 0 - } - return width -} - -func (m *measurer) Rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) { - m.RectsStyle(value, size, weight, false, rtl, bounds, lefts, rights) -} - -func (m *measurer) RectsStyle(value string, size, weight float32, italic, rtl bool, bounds []int32, lefts, rights []float32) { - count := len(bounds) - 1 - if count <= 0 { - return - } - m.mu.Lock() - defer m.mu.Unlock() - units, length := m.encode(value) - if C.viva_text_rects(units, length, C.float(size), C.int(weightClass(weight)), cBool(italic), 0, cBool(rtl), - (*C.int32_t)(unsafe.Pointer(&bounds[0])), C.int(len(bounds)), (*C.float)(unsafe.Pointer(&lefts[0])), (*C.float)(unsafe.Pointer(&rights[0]))) == 0 { - // The host could not answer: the line is drawn with no extent rather than not at all. - clear(lefts[:count]) - clear(rights[:count]) - } -} - -// argb is a color as Android's Canvas takes it. -func argb(red, green, blue, alpha float64) C.int { - component := func(v float64) uint32 { return uint32(math.Round(min(max(v, 0), 1) * 255)) } - return C.int(int32(component(alpha)<<24 | component(red)<<16 | component(green)<<8 | component(blue))) -} - -// bitmap is the pixels of the Java bitmap, as BGRA premultiplied: Android's own -// order is RGBA, and the renderers' textures are BGRA. -func (m *measurer) bitmap(width, height int) ([]byte, error) { - size := width * height * 4 - if size > m.capacity { - if m.pixels != nil { - C.free(m.pixels) - } - m.pixels, m.capacity = C.malloc(C.size_t(size)), size - if m.pixels == nil { - m.capacity = 0 - return nil, errors.New("android: no memory for a text bitmap") - } - } - if C.viva_text_end(m.pixels, C.int64_t(size)) == 0 { - return nil, errors.New("android: the host could not copy the text bitmap") - } - rgba := unsafe.Slice((*byte)(m.pixels), size) - pixels := make([]byte, size) - for i := 0; i < size; i += 4 { - pixels[i], pixels[i+1], pixels[i+2], pixels[i+3] = rgba[i+2], rgba[i+1], rgba[i], rgba[i+3] - } - return pixels, nil -} - -// RasterizeText draws one proportional line, as a gfx.TextRasterizer. -func (m *measurer) RasterizeText(value string, style gfx.TextStyle, scale float32, width, height int) (gfx.Bitmap, error) { - if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 || scale <= 0 || !platform.ValidFontSize(style.Size) { - return gfx.Bitmap{}, errors.New("android: invalid text bitmap size or scale") - } - m.mu.Lock() - defer m.mu.Unlock() - if C.viva_text_begin(C.int(width), C.int(height)) == 0 { - return gfx.Bitmap{}, errors.New("android: the host could not start a text bitmap") - } - if value != "" { - units, length := m.encode(value) - baseline := float32(textmetrics.LabelBaseline(height, float64(style.Size*scale))) - color := style.Color - C.viva_text_draw(units, length, 0, C.float(baseline), C.float(style.Size*scale), C.int(weightClass(style.Weight)), cBool(style.Italic), - cBool(style.Mono), argb(float64(color.Red), float64(color.Green), float64(color.Blue), float64(color.Alpha)), 0, - cBool(bidi.BaseDirection(value) == bidi.RTL)) - } - pixels, err := m.bitmap(width, height) - if err != nil { - return gfx.Bitmap{}, err - } - return gfx.Bitmap{Pix: pixels, Width: width, Height: height, Stride: width * 4}, nil -} - -// Rasterize draws the glyphs of a label into the coverage of its texture, as the -// Vulkan renderer's text rasterizer: the device columns from skip to skip+width of the -// line. It is the grayscale text Android draws; LCD text is not offered. -func (m *measurer) Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) ([]byte, bool, error) { - if !platform.LabelTextureFits(width, height) || skip < 0 { - return nil, false, errors.New("android: label texture exceeds bounded size") - } - if !platform.ValidFontSize(label.FontSize) || scale <= 0 || math.IsNaN(float64(scale)) || math.IsInf(float64(scale), 0) { - return nil, false, errors.New("android: invalid label font size or scale") - } - pixels := make([]byte, width*height*4) - if label.Value == "" || (label.Color.Alpha <= 0 && len(label.Runs) == 0) { - return pixels, false, nil - } - m.mu.Lock() - defer m.mu.Unlock() - if C.viva_text_begin(C.int(width), C.int(height)) == 0 { - return nil, false, errors.New("android: the host could not start a text bitmap") - } - size := C.float(label.FontSize * scale) - baseline := C.float(platform.TextBaseline(label, height, scale)) - rtl := cBool(bidi.BaseDirection(label.Value) == bidi.RTL) - if len(label.Runs) == 0 { - units, length := m.encode(label.Value) - C.viva_text_draw(units, length, C.float(-skip), baseline, size, C.int(weightClass(label.Weight)), cBool(label.Italic), cBool(label.Mono), - argb(label.Color.Red, label.Color.Green, label.Color.Blue, label.Color.Alpha), 0, rtl) - } else { - pitch := float64(label.CellWidth * scale) - if pitch <= 0 || math.IsNaN(pitch) || math.IsInf(pitch, 0) { - return nil, false, errors.New("android: invalid fixed-pitch cell width") - } - offset := 0 - for _, run := range label.Runs { - end := min(offset+int(run.Bytes), len(label.Value)) - text := label.Value[offset:end] - offset = end - if text == "" { - continue - } - weight := run.Weight - if weight == 0 { - weight = label.Weight - } - x := float64(run.Column)*pitch - float64(skip) - units, length := m.encode(text) - C.viva_text_draw(units, length, C.float(x), baseline, size, C.int(weightClass(weight)), cBool(run.Italic || label.Italic), 1, - argb(float64(run.Color.Red), float64(run.Color.Green), float64(run.Color.Blue), float64(run.Color.Alpha)), cBool(run.Underline), 0) - } - } - drawn, err := m.bitmap(width, height) - if err != nil { - return nil, false, err - } - return drawn, false, nil -} - -func (m *measurer) Spans() []vulkan.ColorSpan { return nil } -func (m *measurer) Close() {} - -// newRasterizer makes what the Vulkan renderer draws label glyphs with. -func newRasterizer() (vulkan.TextRasterizer, error) { return shared, nil } - -// engine is the text engine the application measures with: the shared line engine -// over the system's text drawing, with the fixed-pitch cell of the system's own -// monospace font. -type engine struct { - *lineengine.Engine -} - -var _ gfx.TextEngine = engine{} -var _ gfx.StyledTextEngine = engine{} -var _ gfx.TextRasterizer = engine{} -var _ gfx.FontFamilyAware = engine{} -var _ gfx.MonoCellEngine = engine{} - -var sharedEngine = struct { - once sync.Once - engine engine -}{} - -// TextEngine is the gfx.TextEngine over the system's text, shared by every window. -func TextEngine() gfx.TextEngine { - sharedEngine.once.Do(func() { - sharedEngine.engine = engine{lineengine.New(shared)} - }) - return sharedEngine.engine -} - -// SetFontFamily names the family the interface's proportional text is shaped in. -func (e engine) SetFontFamily(family string) { - e.Engine.SetFontFamily(family) - shared.mu.Lock() - defer shared.mu.Unlock() - if family == "" { - C.viva_text_set_family(nil, 0) - return - } - units, length := shared.encode(family) - C.viva_text_set_family(units, length) -} - -// MonoCell is the cell of the system's monospace font at a logical size. -func (e engine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCellMetrics { - if !platform.ValidFontSize(size) { - return gfx.MonoCellMetrics{} - } - shared.mu.Lock() - defer shared.mu.Unlock() - var out [3]C.float - C.viva_text_metrics(C.float(size), 400, 0, 1, &out[0]) - units, length := shared.encode("0") - advance := float32(C.viva_text_width(units, length, C.float(size), 400, 0, 1)) - if advance <= 0 || out[0]+out[1] <= 0 { - return gfx.MonoCellMetrics{} - } - return gfx.MonoCellMetrics{Advance: advance, Ascent: float32(out[0]), Descent: float32(out[1]), LineGap: float32(out[2])} -} - -// utf16Units is value in UTF-16. -func utf16Units(value string) []uint16 { return utf16.Encode([]rune(value)) } diff --git a/internal/platform/android/touch_android.go b/internal/platform/android/touch_android.go deleted file mode 100644 index f2223642d..000000000 --- a/internal/platform/android/touch_android.go +++ /dev/null @@ -1,169 +0,0 @@ -//go:build android - -package android - -import ( - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/input" - "github.com/vivaui/viva/internal/platform" -) - -// MotionEvent's actions, tools, buttons and meta state, as the host sends them. -const ( - actionDown = 0 - actionUp = 1 - actionMove = 2 - actionCancel = 3 - actionPointerDown = 5 - actionPointerUp = 6 - - toolFinger = 1 - toolStylus = 2 - toolMouse = 3 - toolEraser = 4 - - buttonSecondary = 2 - buttonTertiary = 4 - - metaShift = 0x1 - metaAlt = 0x2 - metaCtrl = 0x1000 - metaMeta = 0x10000 -) - -// pointerKind is what an Android action is to the application, false for one the -// application has no use for. -func pointerKind(action int32) (platform.PointerEventKind, bool) { - switch action { - case actionDown, actionPointerDown: - return platform.PointerDown, true - case actionMove: - return platform.PointerMove, true - case actionUp, actionPointerUp: - return platform.PointerUp, true - case actionCancel: - return platform.PointerCancel, true - } - return 0, false -} - -func pointerDevice(tool int32) gfx.PointerDevice { - switch tool { - case toolMouse: - return gfx.PointerMouse - case toolStylus, toolEraser: - return gfx.PointerPen - } - return gfx.PointerTouch -} - -// pointerButton is the button a press of the tool is: a finger and a pen's tip press the -// primary one, a mouse the one it holds. -func pointerButton(tool, buttons int32) gfx.PointerButton { - if tool == toolMouse { - switch { - case buttons&buttonSecondary != 0: - return gfx.PointerButtonSecondary - case buttons&buttonTertiary != 0: - return gfx.PointerButtonMiddle - } - } - return gfx.PointerButtonPrimary -} - -func modifiers(meta int32) input.Modifiers { - var result input.Modifiers - if meta&metaShift != 0 { - result |= input.ModifierShift - } - if meta&metaCtrl != 0 { - result |= input.ModifierControl - } - if meta&metaAlt != 0 { - result |= input.ModifierAlt - } - if meta&metaMeta != 0 { - result |= input.ModifierMeta - } - return result -} - -// touch gives the application one finger's event, and shows what it answers with. -func (application *application) touch(ev event) { - win := application.window - if win == nil || win.closed || win.config.OnPointer == nil || win.renderer == nil || win.native == nil || win.density <= 0 { - return - } - kind, ok := pointerKind(ev.action) - if !ok { - return - } - defer application.guard() - // The surface fills the window and starts at the screen's corner: the surface's - // pixels over the density are the window's and the screen's logical ones. - x, y := ev.x/win.density, ev.y/win.density - event := platform.PointerEvent{ - Kind: kind, Modifiers: modifiers(ev.modifiers), X: x, Y: y, ScreenX: x, ScreenY: y, - Device: pointerDevice(ev.tool), PointerID: ev.pointer, - } - if kind == platform.PointerDown || kind == platform.PointerUp { - event.Button = pointerButton(ev.tool, ev.buttons) - event.ClickCount = 1 - } - frame, err := win.config.OnPointer(event) - if err == nil { - err = win.present(frame) - } - if err != nil { - application.fail(err) - } -} - -// hover gives the application a mouse over the surface, as a pointer that moves with no -// button, and its leaving. -func (application *application) hover(ev event) { - win := application.window - if win == nil || win.closed || win.config.OnPointer == nil || win.renderer == nil || win.native == nil || win.density <= 0 { - return - } - defer application.guard() - event := platform.PointerEvent{Kind: platform.PointerMove, Device: gfx.PointerMouse} - if ev.kind == eventHoverExit { - if !win.hovering { - return - } - win.hovering = false - event.Kind = platform.PointerExit - } else { - win.hovering = true - x, y := ev.x/win.density, ev.y/win.density - event.X, event.Y, event.ScreenX, event.ScreenY, event.Modifiers = x, y, x, y, modifiers(ev.modifiers) - } - frame, err := win.config.OnPointer(event) - if err == nil { - err = win.present(frame) - } - if err != nil { - application.fail(err) - } -} - -// scroll gives the application a wheel. Android reports a wheel up as positive; a scroll -// that moves the content up is a positive distance here, as on the other platforms. -func (application *application) scroll(ev event) { - win := application.window - if win == nil || win.closed || win.config.OnScroll == nil || win.renderer == nil || win.native == nil || win.density <= 0 { - return - } - defer application.guard() - x, y := ev.x/win.density, ev.y/win.density - frame, err := win.config.OnScroll(platform.ScrollEvent{ - Modifiers: modifiers(ev.modifiers), X: x, Y: y, DeltaX: ev.dx / win.density, DeltaY: -ev.dy / win.density, - }) - if err == nil { - err = win.present(frame) - } - if err != nil { - application.fail(err) - } -} diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 10e939ea6..69b51a04b 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -83,10 +83,6 @@ type Config struct { // as far as the platform says so. An adapter that cannot tell never calls it, // and the window counts as visible. OnVisibility VisibilityHandler - // OnLifecycle, when set, runs on the window thread when the system moves the - // application between the foreground and the background, or warns it of low memory. - // Only the phone adapters call it. - OnLifecycle func(Lifecycle) // OnMaximize, when set, runs on the window thread when the window is // maximized or restored. OnMaximize MaximizeHandler @@ -131,11 +127,7 @@ type Config struct { // node: press it, focus it, set its value. The adapter calls it on the // event-loop thread and presents the frames it hands back. OnAccessibility AccessibilityHandler - // AccessibilityTree, when set, answers with the tree the window has now, for an adapter - // whose assistive technology starts after the window opened: frames carry the tree only - // when it changes. The slice is the application's, read at once and not kept. - AccessibilityTree func() []AccessibilityNode - OnRedraw RedrawHandler + OnRedraw RedrawHandler // SetFrameInterval, when set, is called by the adapter on the window thread // once it knows how the window's frames are paced: the interval between // display frames, or zero when presenting a frame blocks until the display @@ -509,19 +501,6 @@ type PointerEvent struct { PointerID int32 } -// Lifecycle is a change the system makes to the state of a phone application. -type Lifecycle uint8 - -const ( - // LifecycleBackground is the application going behind another: the time to save what - // the user would miss, as the system may end it from there without a word. - LifecycleBackground Lifecycle = iota + 1 - // LifecycleForeground is the application coming back to the front. - LifecycleForeground - // LifecycleMemoryWarning is the system asking applications to give memory back. - LifecycleMemoryWarning -) - // Size is a window client size in logical pixels. type Size struct { Width float32 @@ -530,9 +509,6 @@ type Size struct { // (1.25 at 125%), or zero when the platform does not say. The application paints // what must land on whole device pixels for it. Scale float32 - // SafeArea is how far the system covers each edge of the window, in logical pixels - // (status bar, sensor housing, home indicator); zero where it covers nothing. - SafeArea gfx.Insets } // KeyEvent is one normalized keyboard event. Key identities mirror diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index 44bdcaa8d..54802a9ba 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -129,7 +129,7 @@ func vivaViewResized(handle C.uintptr_t, view unsafe.Pointer, width C.double, he } }() - frame, err := state.resizeHandler(Size{Width: float32(width), Height: float32(height), SafeArea: state.safeArea}) + frame, err := state.resizeHandler(Size{Width: float32(width), Height: float32(height)}) if err == nil { // The layer presents the frame in the same Core Animation transaction as // the new bounds (see -[VivaMetalView beginLiveResizeRelaxation]), so the diff --git a/internal/platform/darwin/ios_callback.go b/internal/platform/darwin/ios_callback.go deleted file mode 100644 index 3acf4907e..000000000 --- a/internal/platform/darwin/ios_callback.go +++ /dev/null @@ -1,49 +0,0 @@ -//go:build ios - -package darwin - -/* -#include "native.h" -*/ -import "C" - -import ( - "unsafe" - - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/platform" -) - -// vivaTouchEvent is a finger of the window's view: kind is a PointerEventKind, -// id tells the fingers touching at once apart, and the coordinates are logical -// pixels in the view and on the screen. -// -//export vivaTouchEvent -func vivaTouchEvent(handle C.uintptr_t, view unsafe.Pointer, kind C.int, id C.int, x, y, screenX, screenY C.double) { - state, ok := runStateFor(handle) - if !ok { - return - } - deliverPointer(state, view, PointerEvent{ - Kind: platform.PointerEventKind(kind), - Button: gfx.PointerButtonPrimary, - X: float32(x), - Y: float32(y), - ScreenX: float32(screenX), - ScreenY: float32(screenY), - Device: gfx.PointerTouch, - PointerID: int32(id), - }) -} - -// vivaIOSSafeArea is how far the system covers each edge of the window's view, in points. -// The resize that follows carries it to the application. -// -//export vivaIOSSafeArea -func vivaIOSSafeArea(handle C.uintptr_t, view unsafe.Pointer, top, left, bottom, right C.double) { - state, ok := runStateFor(handle) - if !ok { - return - } - state.safeArea = gfx.Insets{Top: float32(top), Left: float32(left), Bottom: float32(bottom), Right: float32(right)} -} diff --git a/internal/platform/darwin/ios_hooks.go b/internal/platform/darwin/ios_hooks.go deleted file mode 100644 index 262a7c9d9..000000000 --- a/internal/platform/darwin/ios_hooks.go +++ /dev/null @@ -1,46 +0,0 @@ -//go:build ios - -package darwin - -import ( - "errors" - "unsafe" - - "github.com/vivaui/viva/internal/platform" -) - -// What a macOS window or application has that an iOS one does not, or has not -// yet (ADR 0095): each is a plain stand-in here, and moves out of this file as -// the iOS backend gets its own. - -// webState is the pages of one window; iOS hosts none yet, so a window never -// makes one (newWebState answers nil) and these are never called. -type webState struct { - token unsafe.Pointer -} - -func newWebState(*runState, *platform.WebHost, []platform.NativeView) *webState { return nil } -func (*webState) frame(platform.Frame) {} -func (*webState) layout(bool) {} -func (*webState) closeAll() {} - -// AddStatusItem: iOS has no status area. -func (application *nativeApplication) AddStatusItem(platform.StatusItemConfig) (platform.StatusItem, error) { - return nil, errors.New("darwin: iOS has no status item") -} - -// setApplicationIcon: an iOS application's icon is its bundle's. -func setApplicationIcon(platform.WindowIcon) {} - -// Quit does nothing: an iOS application does not end itself; the system does. -func (application *nativeApplication) Quit() {} - -// SetDockBadge and SetProgress: there is no Dock; an icon badge needs a permission -// this backend does not ask for yet. -func (application *nativeApplication) SetDockBadge(string) {} -func (application *nativeApplication) SetProgress(float32) {} - -// SetMenuBar: iOS has no menu bar. -func (application *nativeApplication) SetMenuBar([]platform.MenuBarMenu) error { - return errors.New("darwin: iOS has no menu bar") -} diff --git a/internal/platform/darwin/ios_host.h b/internal/platform/darwin/ios_host.h deleted file mode 100644 index ec8d99b14..000000000 --- a/internal/platform/darwin/ios_host.h +++ /dev/null @@ -1,19 +0,0 @@ -//go:build ios - -#ifndef VIVA_IOS_HOST_H -#define VIVA_IOS_HOST_H - -/* Runs UIApplicationMain with Viva's application delegate. The Go side starts - * the application from vivaIOSLaunched, once UIKit has launched it, and this - * returns only if UIKit gives up. */ -int viva_ios_main(void); - -/* Ends the process, as an application that cannot go on must: iOS has no way to - * quit gracefully. */ -void viva_ios_terminate(int status); - -/* Nonzero when the program runs in the iOS simulator, which takes another build - * of the Metal library than a device. */ -int viva_ios_is_simulator(void); - -#endif diff --git a/internal/platform/darwin/ios_host.m b/internal/platform/darwin/ios_host.m deleted file mode 100644 index b23f6d6fc..000000000 --- a/internal/platform/darwin/ios_host.m +++ /dev/null @@ -1,1265 +0,0 @@ -//go:build ios - -// The iOS host: UIKit's application, window and view around the shared renderer. -// It answers the same C interface (native.h) the AppKit host does, so the Go side -// that runs a window is the same code; what a phone has no use for answers that -// the system does not offer it. Everything runs on the main thread, where UIKit -// calls it and where the Go callbacks are made. - -#import "core.h" -#import -#include "ios_host.h" - -/* The callbacks into Go. */ -extern void vivaIOSLaunched(void); -extern void vivaViewResized(uintptr_t callbackHandle, void *view, double width, double height); -extern void vivaWindowClosed(uintptr_t callbackHandle); -extern void vivaTouchEvent(uintptr_t callbackHandle, void *view, int kind, int identifier, - double x, double y, double screenX, double screenY); -extern int vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int modifiers, int repeat, - const unsigned char *utf8, size_t utf8Length); -extern void vivaIOSVisibility(uintptr_t callbackHandle, void *view, int visible); -extern void vivaIOSLifecycle(uintptr_t callbackHandle, void *view, int kind); -extern void vivaIOSAppearanceChanged(void); -extern void vivaIOSSafeArea(uintptr_t callbackHandle, void *view, double top, double left, double bottom, double right); -extern int vivaAccessibilityAction(uintptr_t callbackHandle, void *view, uint64_t node, int action, double number, - const unsigned char *utf8, size_t utf8Length, int start, int end); -extern void vivaIOSTextOp(uintptr_t callbackHandle, void *view, int operation, const unsigned char *utf8, size_t utf8Length, - int64_t first, int64_t last); -extern void vivaRedrawRequested(uintptr_t callbackHandle, void *view); - -/* The pointer kinds, as platform.PointerEventKind numbers them. */ -enum { - VIVA_IOS_POINTER_DOWN = 1, - VIVA_IOS_POINTER_MOVE = 2, - VIVA_IOS_POINTER_UP = 3, - VIVA_IOS_POINTER_CANCEL = 5, -}; - -/* What viva_application_open_window reports when it cannot make the window. */ -enum { - VIVA_IOS_STATUS_NO_APPLICATION = 8, - VIVA_IOS_STATUS_ONE_WINDOW = 9, - VIVA_IOS_STATUS_NO_VIEW = 7, -}; - -static int viva_application_status = 0; - -/* What the keyboard does to the text input, as vivaIOSTextOp takes it. */ -enum { - VIVA_IOS_TEXT_COMMIT = 1, - VIVA_IOS_TEXT_SET_MARKED = 2, - VIVA_IOS_TEXT_FINISH = 3, - VIVA_IOS_TEXT_REPLACE = 4, - VIVA_IOS_TEXT_SELECT = 5, - VIVA_IOS_TEXT_DELETE_BACKWARD = 6, - VIVA_IOS_TEXT_ENTER = 7, -}; - -@class VivaIOSView; - -/* A position in the text, as a number of UTF-16 units from its start. */ -@interface VivaIOSTextPosition : UITextPosition { -@public - NSInteger _offset; -} -+ (instancetype)positionAt:(NSInteger)offset; -@end - -@implementation VivaIOSTextPosition -+ (instancetype)positionAt:(NSInteger)offset { - VivaIOSTextPosition *position = [[VivaIOSTextPosition alloc] init]; - position->_offset = offset; - return [position autorelease]; -} -@end - -@interface VivaIOSTextRange : UITextRange { - VivaIOSTextPosition *_start; - VivaIOSTextPosition *_end; -} -+ (instancetype)rangeFrom:(NSInteger)start to:(NSInteger)end; -@end - -@implementation VivaIOSTextRange -+ (instancetype)rangeFrom:(NSInteger)start to:(NSInteger)end { - VivaIOSTextRange *range = [[VivaIOSTextRange alloc] init]; - range->_start = [[VivaIOSTextPosition positionAt:MIN(start, end)] retain]; - range->_end = [[VivaIOSTextPosition positionAt:MAX(start, end)] retain]; - return [range autorelease]; -} -- (void)dealloc { - [_start release]; - [_end release]; - [super dealloc]; -} -- (UITextPosition *)start { - return _start; -} -- (UITextPosition *)end { - return _end; -} -- (BOOL)isEmpty { - return _start->_offset == _end->_offset; -} -@end - -/* VivaIOSEditor is what the keyboard types into: an invisible view that holds a copy of - * the application's focused text input and passes what the keyboard does to it back, as - * ranges of UTF-16 units. The application owns the text; this is only read by UIKit. */ -@interface VivaIOSEditor : UIView { - NSMutableString *_text; - NSRange _selected; - NSRange _marked; - BOOL _hasMarked; - BOOL _enabled; - BOOL _multiline; - BOOL _secure; - uintptr_t _callbackHandle; - VivaIOSView *_surface; - CGRect _caret; - id _inputDelegate; - UITextInputStringTokenizer *_tokenizer; - UITextInputAssistantItem *_assistant; -} -@property(nonatomic, assign) VivaIOSView *surface; -@property(nonatomic, assign) uintptr_t callbackHandle; -@property(nonatomic, readonly) BOOL enabled; -- (void)setState:(const unsigned char *)utf8 length:(size_t)length selection:(NSRange)selection marked:(NSRange)marked hasMarked:(BOOL)hasMarked; -- (void)setEnabled:(BOOL)enabled multiline:(BOOL)multiline secure:(BOOL)secure; -- (void)setCaret:(CGRect)caret; -+ (BOOL)textSystemTakes:(UIKey *)key; -@end - - -/* The accessibility roles, in the numbering of platform.A11yRole*. */ -enum { - VIVA_A11Y_GROUP = 2, VIVA_A11Y_BUTTON = 3, VIVA_A11Y_TEXT = 4, VIVA_A11Y_TEXT_FIELD = 5, VIVA_A11Y_CHECKBOX = 6, - VIVA_A11Y_SLIDER = 7, VIVA_A11Y_IMAGE = 8, VIVA_A11Y_LINK = 9, VIVA_A11Y_RADIO = 10, VIVA_A11Y_TAB = 11, - VIVA_A11Y_MENU_ITEM = 12, VIVA_A11Y_SWITCH = 14, VIVA_A11Y_OPTION = 18, VIVA_A11Y_GRID_CELL = 20, - VIVA_A11Y_HEADING = 21, VIVA_A11Y_STATUS = 22, VIVA_A11Y_PROGRESS = 24, -}; - -/* One node of the program's accessibility tree, as VoiceOver reads it. It holds what the - * node said when it was last sent; VoiceOver's requests go back to the program by the - * node's identity. */ -@interface VivaIOSAccessibleElement : UIAccessibilityElement { - uint64_t _identity; - int _role; - BOOL _operable; - uintptr_t _callbackHandle; - void *_surface; - double _rangeNow; - double _rangeMin; - double _rangeMax; -} -- (instancetype)initWithNode:(const viva_accessibility_node *)node container:(UIView *)container handle:(uintptr_t)handle; -@end - -@implementation VivaIOSAccessibleElement - -static NSString *viva_string(const char *chars, size_t length) { - if (chars == NULL || length == 0) { - return nil; - } - return [[[NSString alloc] initWithBytes:chars length:length encoding:NSUTF8StringEncoding] autorelease]; -} - -- (instancetype)initWithNode:(const viva_accessibility_node *)node container:(UIView *)container handle:(uintptr_t)handle { - self = [super initWithAccessibilityContainer:container]; - if (self == nil) { - return nil; - } - _identity = node->id; - _role = node->role; - _callbackHandle = handle; - _surface = container; - _rangeNow = node->range_now; - _rangeMin = node->range_min; - _rangeMax = node->range_max; - _operable = !node->disabled; - self.accessibilityLabel = viva_string(node->label, node->label_length); - NSString *value = viva_string(node->value, node->value_length); - if (_role == VIVA_A11Y_CHECKBOX || _role == VIVA_A11Y_SWITCH || _role == VIVA_A11Y_RADIO) { - value = node->mixed ? @"2" : node->checked ? @"1" : @"0"; - } else if (node->range_set && value == nil) { - double span = node->range_max - node->range_min; - value = span > 0 ? [NSString stringWithFormat:@"%.0f%%", (node->range_now - node->range_min) / span * 100] : nil; - } - self.accessibilityValue = value; - NSString *hint = viva_string(node->hint, node->hint_length); - if (hint == nil) { - hint = viva_string(node->description, node->description_length); - } - self.accessibilityHint = hint; - self.accessibilityFrameInContainerSpace = CGRectMake(node->x, node->y, node->width, node->height); - UIAccessibilityTraits traits = UIAccessibilityTraitNone; - switch (_role) { - case VIVA_A11Y_BUTTON: - case VIVA_A11Y_MENU_ITEM: - case VIVA_A11Y_TAB: - case VIVA_A11Y_OPTION: - case VIVA_A11Y_RADIO: - case VIVA_A11Y_GRID_CELL: - case VIVA_A11Y_CHECKBOX: - case VIVA_A11Y_SWITCH: - traits |= UIAccessibilityTraitButton; - break; - case VIVA_A11Y_LINK: - traits |= UIAccessibilityTraitLink; - break; - case VIVA_A11Y_SLIDER: - traits |= UIAccessibilityTraitAdjustable; - break; - case VIVA_A11Y_HEADING: - traits |= UIAccessibilityTraitHeader | UIAccessibilityTraitStaticText; - break; - case VIVA_A11Y_TEXT: - case VIVA_A11Y_STATUS: - traits |= UIAccessibilityTraitStaticText; - break; - case VIVA_A11Y_IMAGE: - traits |= UIAccessibilityTraitImage; - break; - default: - break; - } - if (node->selected) { - traits |= UIAccessibilityTraitSelected; - } - if (node->disabled) { - traits |= UIAccessibilityTraitNotEnabled; - } - if (node->live != 0) { - traits |= UIAccessibilityTraitUpdatesFrequently; - } - self.accessibilityTraits = traits; - // A group only holds others; what it contains is what is read. - self.isAccessibilityElement = _role != 1 && _role != VIVA_A11Y_GROUP && (self.accessibilityLabel != nil || value != nil || traits != UIAccessibilityTraitNone); - return self; -} - -- (BOOL)accessibilityActivate { - if (!_operable) { - return NO; - } - return vivaAccessibilityAction(_callbackHandle, _surface, _identity, 1, 0, NULL, 0, 0, 0) != 0; -} - -- (void)accessibilityIncrement { - vivaAccessibilityAction(_callbackHandle, _surface, _identity, 3, 0, NULL, 0, 0, 0); -} - -- (void)accessibilityDecrement { - vivaAccessibilityAction(_callbackHandle, _surface, _identity, 4, 0, NULL, 0, 0, 0); -} - -@end - -@interface VivaIOSView : UIView { - NSMutableArray *_accessibleElements; - VivaIOSEditor *_editor; - VivaRenderer *_renderer; - uintptr_t _callbackHandle; - BOOL _resizeEventsEnabled; - BOOL _closed; - CGSize _lastReportedSize; - BOOL _reportedSize; - UIEdgeInsets _safeArea; - UIEdgeInsets _lastReportedSafeArea; -} -@property(nonatomic, readonly) uintptr_t callbackHandle; -/* How far the system covers each edge (status bar, sensor housing, home indicator), which - * the view controller sets; the next layout tells the application. */ -@property(nonatomic) UIEdgeInsets safeArea; -@property(nonatomic, readonly) BOOL closed; -@property(nonatomic, readonly) VivaIOSEditor *editor; -- (instancetype)initWithFrame:(CGRect)frame - device:(id)device - commandQueue:(id)commandQueue - rectanglePipeline:(id)rectanglePipeline - rectangleBuffer:(id)rectangleBuffer - textPipeline:(id)textPipeline - config:(const viva_window_config *)config; -- (void)render; -- (void)renderWaitingForSchedule:(BOOL)wait; -- (BOOL)recoverResources; -- (int)updateRectangles:(const viva_rectangle *)rectangles - clips:(const viva_clip *)clips - totalCount:(NSUInteger)totalCount - first:(NSUInteger)first - count:(NSUInteger)count - rebuild:(BOOL)rebuild - render:(BOOL)render; -- (int)updateLabels:(const viva_text_label *)labels count:(NSUInteger)count; -- (int)updateAccessibility:(const viva_accessibility_node *)nodes count:(NSUInteger)count; -- (void)closeWindow; -@end - -@implementation VivaIOSView - -@synthesize callbackHandle = _callbackHandle; -@synthesize closed = _closed; -@synthesize editor = _editor; -@synthesize safeArea = _safeArea; - -+ (Class)layerClass { - return [CAMetalLayer class]; -} - -- (instancetype)initWithFrame:(CGRect)frame - device:(id)device - commandQueue:(id)commandQueue - rectanglePipeline:(id)rectanglePipeline - rectangleBuffer:(id)rectangleBuffer - textPipeline:(id)textPipeline - config:(const viva_window_config *)config { - self = [super initWithFrame:frame]; - if (self == nil) { - return nil; - } - _callbackHandle = config->callback_handle; - _editor = [[VivaIOSEditor alloc] initWithFrame:CGRectMake(0, 0, 1, 1)]; - _editor.surface = self; - _editor.callbackHandle = _callbackHandle; - [self addSubview:_editor]; - _resizeEventsEnabled = config->resize_events_enabled != 0; - // Fingers are separate pointers: a second one ends what the first was doing. - self.multipleTouchEnabled = YES; - self.opaque = config->clear_alpha >= 1.0; - - CAMetalLayer *layer = (CAMetalLayer *)self.layer; - layer.device = device; - layer.pixelFormat = MTLPixelFormatBGRA8Unorm; - layer.framebufferOnly = YES; - layer.opaque = config->clear_alpha >= 1.0; - layer.maximumDrawableCount = 2; - layer.allowsNextDrawableTimeout = YES; - [self updateDrawableSize]; - - _renderer = [[VivaRenderer alloc] - initWithLayer:layer - commandQueue:commandQueue - rectanglePipeline:rectanglePipeline - rectangleBuffer:rectangleBuffer - rectangleCount:config->rectangle_count - rectangleClips:config->rectangle_clips - textPipeline:textPipeline - textLabels:config->text_labels - textLabelCount:config->text_label_count - clearColor:MTLClearColorMake(config->clear_red, config->clear_green, config->clear_blue, config->clear_alpha) - viewport:self.bounds.size]; - if (_renderer == nil) { - [self release]; - return nil; - } - return self; -} - -- (void)dealloc { - [_accessibleElements release]; - [_editor release]; - [_renderer release]; - [super dealloc]; -} - -// updateDrawableSize makes the layer as many pixels as the view has points times -// the screen's scale, so the picture is not stretched. -- (void)updateDrawableSize { - CGFloat scale = self.window.screen.scale ?: UIScreen.mainScreen.scale; - CAMetalLayer *layer = (CAMetalLayer *)self.layer; - CGSize size = self.bounds.size; - layer.contentsScale = scale; - layer.drawableSize = CGSizeMake(size.width * scale, size.height * scale); -} - -// layoutSubviews runs when the view gets its size, the first time and on every -// rotation: the application is told, and answers with the scene at that size. -- (void)layoutSubviews { - [super layoutSubviews]; - if (_closed) { - return; - } - [self updateDrawableSize]; - CGSize size = self.bounds.size; - if (_resizeEventsEnabled && (!_reportedSize || !CGSizeEqualToSize(size, _lastReportedSize) || - !UIEdgeInsetsEqualToEdgeInsets(_safeArea, _lastReportedSafeArea))) { - _reportedSize = YES; - _lastReportedSize = size; - _lastReportedSafeArea = _safeArea; - // The insets come first: the resize that follows lays the page out inside them. - vivaIOSSafeArea(_callbackHandle, self, _safeArea.top, _safeArea.left, _safeArea.bottom, _safeArea.right); - vivaViewResized(_callbackHandle, self, size.width, size.height); - } -} - -- (void)render { - [self renderWaitingForSchedule:NO]; -} - -- (void)renderWaitingForSchedule:(BOOL)wait { - // The system kills an application that submits GPU work from the background. - if (_closed || UIApplication.sharedApplication.applicationState == UIApplicationStateBackground) { - return; - } - @autoreleasepool { - CAMetalLayer *layer = (CAMetalLayer *)self.layer; - if (layer.drawableSize.width < 1 || layer.drawableSize.height < 1) { - return; - } - id drawable = [layer nextDrawable]; - if (drawable == nil) { - return; - } - id commandBuffer = [_renderer renderToDrawable:drawable - viewport:self.bounds.size - inputTexture:nil - inputFrame:CGRectZero - inputLayer:0]; - if (wait) { - [commandBuffer waitUntilScheduled]; - } - } -} - -- (BOOL)recoverResources { - @autoreleasepool { - [self updateDrawableSize]; - return [_renderer recoverWithViewport:self.bounds.size]; - } -} - -- (int)updateRectangles:(const viva_rectangle *)rectangles - clips:(const viva_clip *)clips - totalCount:(NSUInteger)totalCount - first:(NSUInteger)first - count:(NSUInteger)count - rebuild:(BOOL)rebuild - render:(BOOL)render { - int status = [_renderer updateRectangles:rectangles - clips:clips - totalCount:totalCount - first:first - count:count - rebuild:rebuild]; - if (status == 0 && render) { - [self render]; - } - return status; -} - -- (int)updateLabels:(const viva_text_label *)labels count:(NSUInteger)count { - return [_renderer updateLabels:labels count:count viewport:self.bounds.size]; -} - -// closeWindow ends the window for the application: iOS windows are not closed -// by the user, so this is the application's own doing, after a failure. -- (void)closeWindow { - if (_closed) { - return; - } - _closed = YES; - vivaWindowClosed(_callbackHandle); -} - -#pragma mark Accessibility - -// updateAccessibility makes the program's tree what VoiceOver reads. The surface is the -// container of the elements: it is not itself read. -- (int)updateAccessibility:(const viva_accessibility_node *)nodes count:(NSUInteger)count { - NSMutableArray *elements = [[NSMutableArray alloc] initWithCapacity:count]; - for (NSUInteger index = 0; index < count; index++) { - VivaIOSAccessibleElement *element = [[VivaIOSAccessibleElement alloc] initWithNode:&nodes[index] container:self handle:_callbackHandle]; - if (element != nil) { - [elements addObject:element]; - [element release]; - } - } - [_accessibleElements release]; - _accessibleElements = elements; - UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil); - return 0; -} - -- (BOOL)isAccessibilityElement { - return NO; -} - -- (NSArray *)accessibilityElements { - return _accessibleElements; -} - -#pragma mark Touches - -// emitTouches reports each finger of a phase. A finger is its UITouch for as long -// as it touches, so the object's address names it. -- (void)emitTouches:(NSSet *)touches kind:(int)kind { - if (_closed) { - return; - } - for (UITouch *touch in touches) { - CGPoint point = [touch locationInView:self]; - CGPoint onScreen = [touch locationInView:nil]; - int identifier = (int)(((uintptr_t)touch >> 4) & 0x7fffffff); - vivaTouchEvent(_callbackHandle, self, kind, identifier, point.x, point.y, onScreen.x, onScreen.y); - } -} - -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { - [self emitTouches:touches kind:VIVA_IOS_POINTER_DOWN]; -} - -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { - [self emitTouches:touches kind:VIVA_IOS_POINTER_MOVE]; -} - -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { - [self emitTouches:touches kind:VIVA_IOS_POINTER_UP]; -} - -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { - [self emitTouches:touches kind:VIVA_IOS_POINTER_CANCEL]; -} - -#pragma mark Hardware keyboard - -- (BOOL)canBecomeFirstResponder { - return YES; -} - -- (void)didMoveToWindow { - [super didMoveToWindow]; - if (self.window != nil) { - [self becomeFirstResponder]; - } -} - -// pressesBegan reports the keys of a connected keyboard. The keys that are not -// text arrive as key events and the chords with Control or Command as shortcut -// offers; what is typed is the text input's (see UITextInput). -- (void)pressesBegan:(NSSet *)presses withEvent:(UIPressesEvent *)event { - NSMutableSet *others = [NSMutableSet set]; - for (UIPress *press in presses) { - UIKey *key = press.key; - if (key == nil || _closed || (_editor.enabled && [VivaIOSEditor textSystemTakes:key])) { - [others addObject:press]; - continue; - } - const char *chars = key.charactersIgnoringModifiers.UTF8String; - size_t length = chars != NULL ? strlen(chars) : 0; - if (vivaIOSKeyEvent(_callbackHandle, self, (int)key.keyCode, (int)key.modifierFlags, 0, (const unsigned char *)chars, length) == 0) { - [others addObject:press]; - } - } - if (others.count > 0) { - [super pressesBegan:others withEvent:event]; - } -} - -@end - - -@implementation VivaIOSEditor - -@synthesize surface = _surface; -@synthesize callbackHandle = _callbackHandle; -@synthesize enabled = _enabled; -@synthesize markedTextStyle; -@synthesize inputDelegate = _inputDelegate; - -- (instancetype)initWithFrame:(CGRect)frame { - self = [super initWithFrame:frame]; - if (self != nil) { - _text = [[NSMutableString alloc] init]; - _selected = NSMakeRange(0, 0); - _marked = NSMakeRange(NSNotFound, 0); - self.alpha = 0; - } - return self; -} - -- (void)dealloc { - [_text release]; - [_tokenizer release]; - [markedTextStyle release]; - [super dealloc]; -} - -/* textSystemTakes says a hardware key is the text system's while a field is focused: it - * arrives as insertText, deleteBackward or a change of the selection, not as a key. */ -+ (BOOL)textSystemTakes:(UIKey *)key { - switch (key.keyCode) { - case UIKeyboardHIDUsageKeyboardReturnOrEnter: - case UIKeyboardHIDUsageKeyboardDeleteOrBackspace: - case UIKeyboardHIDUsageKeyboardDeleteForward: - case UIKeyboardHIDUsageKeyboardLeftArrow: - case UIKeyboardHIDUsageKeyboardRightArrow: - case UIKeyboardHIDUsageKeyboardHome: - case UIKeyboardHIDUsageKeyboardEnd: - case UIKeyboardHIDUsageKeyboardSpacebar: - return YES; - default: - return NO; - } -} - -- (BOOL)canBecomeFirstResponder { - return _enabled; -} - -/* The editor is not there to be touched: the surface under it is. */ -- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { - return NO; -} - -- (UIView *)textInputView { - return self; -} - - -- (void)setEnabled:(BOOL)enabled multiline:(BOOL)multiline secure:(BOOL)secure { - BOOL restart = _enabled != enabled || _multiline != multiline || _secure != secure; - _enabled = enabled; - _multiline = multiline; - _secure = secure; - if (!restart) { - return; - } - if (enabled) { - if (self.isFirstResponder) { - [self reloadInputViews]; - } else { - [self becomeFirstResponder]; - } - } else { - [self resignFirstResponder]; - // The keys of a connected keyboard go on to the surface. - [_surface becomeFirstResponder]; - } -} - -- (void)setState:(const unsigned char *)utf8 length:(size_t)length selection:(NSRange)selection marked:(NSRange)marked hasMarked:(BOOL)hasMarked { - NSString *value = length > 0 ? [[NSString alloc] initWithBytes:utf8 length:length encoding:NSUTF8StringEncoding] : [[NSString alloc] init]; - BOOL textChanged = ![_text isEqualToString:value]; - BOOL selectionChanged = !NSEqualRanges(_selected, selection) || _hasMarked != hasMarked || (hasMarked && !NSEqualRanges(_marked, marked)); - if (textChanged) { - [_inputDelegate textWillChange:self]; - } - if (selectionChanged) { - [_inputDelegate selectionWillChange:self]; - } - [_text setString:value]; - [value release]; - _selected = NSMakeRange(MIN(selection.location, _text.length), MIN(selection.length, _text.length - MIN(selection.location, _text.length))); - _hasMarked = hasMarked; - _marked = hasMarked ? NSMakeRange(MIN(marked.location, _text.length), MIN(marked.length, _text.length - MIN(marked.location, _text.length))) : NSMakeRange(NSNotFound, 0); - if (selectionChanged) { - [_inputDelegate selectionDidChange:self]; - } - if (textChanged) { - [_inputDelegate textDidChange:self]; - } -} - -- (void)setCaret:(CGRect)caret { - _caret = caret; -} - -- (void)sendOperation:(int)operation text:(NSString *)text first:(NSInteger)first last:(NSInteger)last { - NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding]; - vivaIOSTextOp(_callbackHandle, _surface, operation, data.bytes, data.length, first, last); -} - -#pragma mark UIKeyInput - -- (BOOL)hasText { - return _text.length > 0; -} - -- (void)insertText:(NSString *)text { - if ([text isEqualToString:@"\n"] && !_multiline) { - [self sendOperation:VIVA_IOS_TEXT_ENTER text:@"" first:0 last:0]; - return; - } - [self sendOperation:VIVA_IOS_TEXT_COMMIT text:text first:0 last:0]; -} - -- (void)deleteBackward { - [self sendOperation:VIVA_IOS_TEXT_DELETE_BACKWARD text:@"" first:0 last:0]; -} - -#pragma mark UITextInput: text - -- (NSString *)textInRange:(UITextRange *)range { - VivaIOSTextRange *r = (VivaIOSTextRange *)range; - NSInteger start = MIN(((VivaIOSTextPosition *)r.start)->_offset, (NSInteger)_text.length); - NSInteger end = MIN(((VivaIOSTextPosition *)r.end)->_offset, (NSInteger)_text.length); - return [_text substringWithRange:NSMakeRange(start, MAX(end - start, 0))]; -} - -- (void)replaceRange:(UITextRange *)range withText:(NSString *)text { - VivaIOSTextRange *r = (VivaIOSTextRange *)range; - [self sendOperation:VIVA_IOS_TEXT_REPLACE text:text first:((VivaIOSTextPosition *)r.start)->_offset last:((VivaIOSTextPosition *)r.end)->_offset]; -} - -- (UITextRange *)selectedTextRange { - return [VivaIOSTextRange rangeFrom:_selected.location to:_selected.location + _selected.length]; -} - -- (void)setSelectedTextRange:(UITextRange *)range { - VivaIOSTextRange *r = (VivaIOSTextRange *)range; - if (r == nil) { - return; - } - [self sendOperation:VIVA_IOS_TEXT_SELECT text:@"" first:((VivaIOSTextPosition *)r.start)->_offset last:((VivaIOSTextPosition *)r.end)->_offset]; -} - -- (UITextRange *)markedTextRange { - return _hasMarked ? [VivaIOSTextRange rangeFrom:_marked.location to:_marked.location + _marked.length] : nil; -} - -- (void)setMarkedText:(NSString *)markedText selectedRange:(NSRange)selectedRange { - NSInteger start = selectedRange.location == NSNotFound ? (NSInteger)markedText.length : (NSInteger)selectedRange.location; - [self sendOperation:VIVA_IOS_TEXT_SET_MARKED text:markedText ?: @"" first:start last:start + (NSInteger)selectedRange.length]; -} - -- (void)unmarkText { - [self sendOperation:VIVA_IOS_TEXT_FINISH text:@"" first:0 last:0]; -} - -#pragma mark UITextInput: positions - -- (UITextPosition *)beginningOfDocument { - return [VivaIOSTextPosition positionAt:0]; -} - -- (UITextPosition *)endOfDocument { - return [VivaIOSTextPosition positionAt:_text.length]; -} - -- (UITextRange *)textRangeFromPosition:(UITextPosition *)from toPosition:(UITextPosition *)to { - return [VivaIOSTextRange rangeFrom:((VivaIOSTextPosition *)from)->_offset to:((VivaIOSTextPosition *)to)->_offset]; -} - -- (UITextPosition *)positionFromPosition:(UITextPosition *)position offset:(NSInteger)offset { - NSInteger target = ((VivaIOSTextPosition *)position)->_offset + offset; - if (target < 0 || target > (NSInteger)_text.length) { - return nil; - } - return [VivaIOSTextPosition positionAt:target]; -} - -- (UITextPosition *)positionFromPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset { - NSInteger from = ((VivaIOSTextPosition *)position)->_offset; - NSInteger target = from; - switch (direction) { - case UITextLayoutDirectionLeft: - target = from - offset; - break; - case UITextLayoutDirectionRight: - target = from + offset; - break; - case UITextLayoutDirectionUp: - target = 0; - break; - case UITextLayoutDirectionDown: - target = _text.length; - break; - } - return [VivaIOSTextPosition positionAt:MIN(MAX(target, 0), (NSInteger)_text.length)]; -} - -- (NSComparisonResult)comparePosition:(UITextPosition *)position toPosition:(UITextPosition *)other { - NSInteger a = ((VivaIOSTextPosition *)position)->_offset; - NSInteger b = ((VivaIOSTextPosition *)other)->_offset; - return a < b ? NSOrderedAscending : a > b ? NSOrderedDescending : NSOrderedSame; -} - -- (NSInteger)offsetFromPosition:(UITextPosition *)from toPosition:(UITextPosition *)to { - return ((VivaIOSTextPosition *)to)->_offset - ((VivaIOSTextPosition *)from)->_offset; -} - -- (id)tokenizer { - if (_tokenizer == nil) { - _tokenizer = [[UITextInputStringTokenizer alloc] initWithTextInput:self]; - } - return _tokenizer; -} - -- (UITextPosition *)positionWithinRange:(UITextRange *)range farthestInDirection:(UITextLayoutDirection)direction { - BOOL end = direction == UITextLayoutDirectionRight || direction == UITextLayoutDirectionDown; - return end ? range.end : range.start; -} - -- (UITextRange *)characterRangeByExtendingPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction { - NSInteger offset = ((VivaIOSTextPosition *)position)->_offset; - BOOL forward = direction == UITextLayoutDirectionRight || direction == UITextLayoutDirectionDown; - return [VivaIOSTextRange rangeFrom:offset to:forward ? _text.length : 0]; -} - -- (NSWritingDirection)baseWritingDirectionForPosition:(UITextPosition *)position inDirection:(UITextStorageDirection)direction { - return NSWritingDirectionNatural; -} - -- (void)setBaseWritingDirection:(NSWritingDirection)direction forRange:(UITextRange *)range { -} - -#pragma mark UITextInput: geometry - -- (CGRect)firstRectForRange:(UITextRange *)range { - return [self convertRect:_caret fromView:_surface]; -} - -- (CGRect)caretRectForPosition:(UITextPosition *)position { - return [self convertRect:CGRectMake(CGRectGetMinX(_caret), CGRectGetMinY(_caret), 2, CGRectGetHeight(_caret)) fromView:_surface]; -} - -- (NSArray *)selectionRectsForRange:(UITextRange *)range { - return @[]; -} - -- (UITextPosition *)closestPositionToPoint:(CGPoint)point { - return [VivaIOSTextPosition positionAt:_selected.location + _selected.length]; -} - -- (UITextPosition *)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange *)range { - return range.end; -} - -- (UITextRange *)characterRangeAtPoint:(CGPoint)point { - return nil; -} - -#pragma mark UITextInputTraits - -- (UIKeyboardType)keyboardType { - return UIKeyboardTypeDefault; -} - -- (BOOL)isSecureTextEntry { - return _secure; -} - -- (UIReturnKeyType)returnKeyType { - return _multiline ? UIReturnKeyDefault : UIReturnKeyDone; -} - -- (UITextAutocorrectionType)autocorrectionType { - return _secure ? UITextAutocorrectionTypeNo : UITextAutocorrectionTypeDefault; -} - -- (UITextAutocapitalizationType)autocapitalizationType { - return UITextAutocapitalizationTypeNone; -} - -- (UITextSpellCheckingType)spellCheckingType { - return _secure ? UITextSpellCheckingTypeNo : UITextSpellCheckingTypeDefault; -} - -@end - - -@interface VivaIOSViewController : UIViewController { - VivaIOSView *_surface; -} -- (void)setSurface:(VivaIOSView *)surface; -@end - -@implementation VivaIOSViewController - -- (void)loadView { - UIView *root = [[UIView alloc] init]; - root.backgroundColor = UIColor.systemBackgroundColor; - self.view = root; - [root release]; -} - -- (void)setSurface:(VivaIOSView *)surface { - _surface = surface; - [self.view addSubview:surface]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(keyboardWillChange:) - name:UIKeyboardWillChangeFrameNotification - object:nil]; -} - -- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [super dealloc]; -} - -// keyboardWillChange moves the surface with the keyboard, in the keyboard's own -// animation. -- (void)keyboardWillChange:(NSNotification *)notification { - NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; - UIViewAnimationOptions curve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue] << 16; - [self.view setNeedsLayout]; - [UIView animateWithDuration:duration delay:0 options:curve animations:^{ - [self.view layoutIfNeeded]; - } completion:nil]; -} - -// viewDidLayoutSubviews makes the surface the whole window, as far as the keyboard -// allows, and tells it how far the system covers each edge: the status bar and the -// sensor housing, the home indicator. The application draws under them and keeps what -// matters inside them (ADR 0096). The keyboard shrinks the surface from the bottom, and -// with it up nothing covers the bottom edge but the keyboard itself. -- (void)viewDidLayoutSubviews { - [super viewDidLayoutSubviews]; - CGRect bounds = self.view.bounds; - UIEdgeInsets safe = self.view.safeAreaInsets; - CGFloat keyboardTop = CGRectGetMinY(self.view.keyboardLayoutGuide.layoutFrame); - // With no keyboard the guide's top is the safe area's bottom edge, the home indicator's - // line; the keyboard is up when it is higher than that. - if (keyboardTop < CGRectGetMaxY(bounds) - safe.bottom - 0.5) { - bounds.size.height = MAX(keyboardTop - bounds.origin.y, 0); - safe.bottom = 0; - } - _surface.safeArea = safe; - _surface.frame = bounds; - [_surface setNeedsLayout]; -} - -- (UIInterfaceOrientationMask)supportedInterfaceOrientations { - return UIInterfaceOrientationMaskAll; -} - -// traitCollectionDidChange tells the application when the system switches between -// its light and dark looks. -- (void)traitCollectionDidChange:(UITraitCollection *)previous { - [super traitCollectionDidChange:previous]; - if (previous != nil && previous.userInterfaceStyle != self.traitCollection.userInterfaceStyle) { - vivaIOSAppearanceChanged(); - } -} - -@end - -@interface VivaIOSAppDelegate : UIResponder { - BOOL _inBackground; -} -@end - -/* The one window an iPhone application shows (see viva_application_open_window). */ -static UIWindow *viva_ios_window; -static VivaIOSView *viva_ios_view; - -@implementation VivaIOSAppDelegate - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - vivaIOSLaunched(); - return YES; -} - -// The application goes behind another and comes back: it is told. The window is drawn -// again only once the application is active, as the system gives no GPU to one that -// has only begun to return; what the layer shows may not be what it should. -- (void)applicationDidEnterBackground:(UIApplication *)application { - if (viva_ios_view != nil && !viva_ios_view.closed) { - _inBackground = YES; - vivaIOSLifecycle(viva_ios_view.callbackHandle, viva_ios_view, 1); // Background - vivaIOSVisibility(viva_ios_view.callbackHandle, viva_ios_view, 0); - } -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - if (viva_ios_view != nil && !viva_ios_view.closed) { - vivaIOSLifecycle(viva_ios_view.callbackHandle, viva_ios_view, 2); // Foreground - } -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - if (_inBackground && viva_ios_view != nil && !viva_ios_view.closed) { - _inBackground = NO; - vivaIOSVisibility(viva_ios_view.callbackHandle, viva_ios_view, 1); - } -} - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - if (viva_ios_view != nil && !viva_ios_view.closed) { - vivaIOSLifecycle(viva_ios_view.callbackHandle, viva_ios_view, 3); // MemoryWarning - } -} - -@end - -int viva_ios_main(void) { - @autoreleasepool { - char *argv[] = {"viva", NULL}; - return UIApplicationMain(1, argv, nil, NSStringFromClass([VivaIOSAppDelegate class])); - } -} - -void viva_ios_terminate(int status) { - exit(status); -} - -int viva_ios_is_simulator(void) { -#if TARGET_OS_SIMULATOR - return 1; -#else - return 0; -#endif -} - -int viva_application_last_status(void) { - return viva_application_status; -} - -/* viva_application_open_window makes the application's window: one that fills the - * screen, as a phone's does. A second one is refused, since there is no screen to - * put it on; how an application shows a second surface there is a decision the - * framework has yet to make (ADR 0095). It must be called from the launch - * callback, on the main thread. */ -void *viva_application_open_window(viva_window_config config) { - @autoreleasepool { - if (viva_ios_view != nil) { - viva_application_status = VIVA_IOS_STATUS_ONE_WINDOW; - return NULL; - } - id device = nil; - id commandQueue = nil; - id rectanglePipeline = nil; - id textPipeline = nil; - id rectangleBuffer = nil; - int status = viva_make_scene_resources( - &config, &device, &commandQueue, &rectanglePipeline, &textPipeline, &rectangleBuffer); - if (status != 0) { - viva_application_status = status; - return NULL; - } - CGRect screen = UIScreen.mainScreen.bounds; - VivaIOSView *view = [[VivaIOSView alloc] initWithFrame:screen - device:device - commandQueue:commandQueue - rectanglePipeline:rectanglePipeline - rectangleBuffer:rectangleBuffer - textPipeline:textPipeline - config:&config]; - [rectangleBuffer release]; - [textPipeline release]; - [rectanglePipeline release]; - [commandQueue release]; - [device release]; - if (view == nil) { - viva_application_status = VIVA_IOS_STATUS_NO_VIEW; - return NULL; - } - if (config.accessibility_count > 0) { - [view updateAccessibility:config.accessibility count:config.accessibility_count]; - } - VivaIOSViewController *controller = [[VivaIOSViewController alloc] init]; - [controller loadViewIfNeeded]; - [controller setSurface:view]; - UIWindow *window = [[UIWindow alloc] initWithFrame:screen]; - window.rootViewController = controller; - [window makeKeyAndVisible]; - [controller release]; - viva_ios_window = window; - viva_ios_view = view; - return view; - } -} - -/* viva_request_redraw asks, from any thread, for the application to paint again. */ -void viva_request_redraw(uintptr_t callback_handle) { - dispatch_async(dispatch_get_main_queue(), ^{ - VivaIOSView *view = viva_ios_view; - if (view != nil && !view.closed && view.callbackHandle == callback_handle) { - vivaRedrawRequested(callback_handle, view); - } - }); -} - -/* The window always fills the screen: where it is and how big, in the points of - * the screen, and that it is full screen, are not the application's to change. */ -int viva_application_window_frame(void *window, double *out) { - VivaIOSView *view = (VivaIOSView *)window; - if (view == nil || view != viva_ios_view) { - return 0; - } - CGRect bounds = view.window.bounds; - out[0] = 0; - out[1] = 0; - out[2] = bounds.size.width; - out[3] = bounds.size.height; - return 1; -} - -void viva_application_move_window(void *window, double x, double y) {} -void viva_application_set_window_size(void *window, double width, double height) {} -int viva_application_set_fullscreen(void *window, int fullscreen) { return 0; } -int viva_application_fullscreen(void *window) { return 1; } -int viva_application_set_always_on_top(void *window, int enabled) { return 0; } -void viva_application_hide_window(void *window) {} -void viva_application_show_window(void *window) {} - -int viva_application_set_title(void *window, const char *title) { - VivaIOSView *view = (VivaIOSView *)window; - NSString *text = title != NULL ? [NSString stringWithUTF8String:title] : nil; - view.window.windowScene.title = text; - return 0; -} - -void viva_application_close_all(void) { - [viva_ios_view closeWindow]; -} - -void viva_application_close_window(void *window) { - [(VivaIOSView *)window closeWindow]; -} - -int viva_view_update_rectangles( - void *view, - const viva_rectangle *rectangles, - const viva_clip *clips, - size_t total_count, - size_t first, - size_t count, - int rebuild, - int render -) { - if (view == NULL) { - return 1; - } - @autoreleasepool { - return [(VivaIOSView *)view updateRectangles:rectangles - clips:clips - totalCount:total_count - first:first - count:count - rebuild:rebuild != 0 - render:render != 0]; - } -} - -int viva_view_update_labels(void *view, const viva_text_label *labels, size_t count) { - if (view == NULL) { - return 1; - } - @autoreleasepool { - return [(VivaIOSView *)view updateLabels:labels count:count]; - } -} - -int viva_view_recover(void *view) { - if (view == NULL) { - return 1; - } - return [(VivaIOSView *)view recoverResources] ? 0 : 1; -} - -void viva_view_render(void *view) { - [(VivaIOSView *)view render]; -} - -void viva_view_render_sync(void *view) { - [(VivaIOSView *)view renderWaitingForSchedule:YES]; -} - -void viva_view_close(void *view) { - [(VivaIOSView *)view closeWindow]; -} - -void viva_view_close_confirmed(void *view) { - [(VivaIOSView *)view closeWindow]; -} - -/* What an iOS view does not take yet (ADR 0095): the system keyboard, the - * accessibility tree and the web views come with their own work packages. They - * accept what the application sends and show nothing of it. */ -int viva_view_update_accessibility(void *view, const viva_accessibility_node *nodes, size_t count) { - if (view == NULL) { - return 1; - } - @autoreleasepool { - return [(VivaIOSView *)view updateAccessibility:nodes count:count]; - } -} - -int viva_view_update_text( - void *view, - const unsigned char *utf8, - size_t utf8_length, - size_t selected_start, - size_t selected_length, - size_t marked_start, - size_t marked_length, - int has_marked_text, - int tentative_composition, - int ends_composition, - int render -) { - VivaIOSView *surface = (VivaIOSView *)view; - if (surface == nil || surface.editor == nil) { - return 1; - } - [surface.editor setState:utf8 - length:utf8_length - selection:NSMakeRange(selected_start, selected_length) - marked:NSMakeRange(marked_start, marked_length) - hasMarked:has_marked_text != 0]; - return 0; -} - -/* viva_view_update_text_input follows the application's wish for its text input: another - * one, the same with other text, or none, which has the keyboard away. */ -static int viva_ios_text_input(void *view, viva_text_input_config text_input) { - VivaIOSView *surface = (VivaIOSView *)view; - if (surface == nil || surface.editor == nil) { - return 1; - } - if (text_input.enabled == 0) { - [surface.editor setEnabled:NO multiline:NO secure:NO]; - return 0; - } - [surface.editor setCaret:CGRectMake(text_input.x, text_input.y, text_input.width, text_input.height)]; - [surface.editor setEnabled:YES multiline:text_input.multiline != 0 secure:text_input.secure != 0]; - return viva_view_update_text(view, text_input.utf8, text_input.utf8_length, text_input.selected_start, text_input.selected_length, - text_input.marked_start, text_input.marked_length, text_input.has_marked_text, 0, 0, 0); -} - -int viva_view_update_text_input(void *view, viva_text_input_config text_input) { - return viva_ios_text_input(view, text_input); -} - -int viva_view_update_text_input_keeping_composition(void *view, viva_text_input_config text_input) { - return viva_ios_text_input(view, text_input); -} - -int viva_view_move_text_input(void *view, float x, float y, float width, float height) { - VivaIOSView *surface = (VivaIOSView *)view; - if (surface == nil || surface.editor == nil) { - return 1; - } - [surface.editor setCaret:CGRectMake(x, y, width, height)]; - return 0; -} - -void viva_web_ready_later(uintptr_t callback_handle) {} - -/* The AppKit text input's key routing is a Mac keyboard's: an iOS one comes - * through UIKit's own text input, so nothing here asks for raw keys. */ -int viva_text_input_row_key_is_raw(int placed, int composing, int key, int command) { return 0; } -int viva_text_input_navigation_key_is_raw(int navigation_keys, int composing, int key) { return 0; } -int viva_text_input_should_interpret_key(int enabled, int multiline, int composing, int key) { return 0; } -int viva_text_input_caret_should_blink( - int enabled, - size_t selected_length, - int composing, - int terminal, - int hide_native_overlays -) { - return 0; -} -int viva_terminal_key_routes_raw( - int composing, - int named_key, - int control, - int command, - int alt, - int alt_sends_escape -) { - return 0; -} -int viva_terminal_key_code(unsigned short character) { return 0; } diff --git a/internal/platform/darwin/ios_keys.go b/internal/platform/darwin/ios_keys.go deleted file mode 100644 index 63e810b13..000000000 --- a/internal/platform/darwin/ios_keys.go +++ /dev/null @@ -1,150 +0,0 @@ -//go:build ios - -package darwin - -/* -#include "native.h" -*/ -import "C" - -import ( - "fmt" - "unsafe" - - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/input" - "github.com/vivaui/viva/internal/platform" -) - -// UIKeyModifierFlags, as UIKey reports them. -const ( - uiKeyModifierShift = 1 << 17 - uiKeyModifierControl = 1 << 18 - uiKeyModifierAlt = 1 << 19 - uiKeyModifierCommand = 1 << 20 -) - -// keyOfUsage is the key a USB HID usage of the keyboard page names, for the keys that -// are not text: what a connected keyboard reports in UIKey.keyCode. -func keyOfUsage(usage int) gfx.Key { - switch { - case usage >= 0x3A && usage <= 0x45: // F1 to F12 - return gfx.KeyF1 + gfx.Key(usage-0x3A) - } - switch usage { - case 0x28, 0x58: // Return, keypad Enter - return gfx.KeyEnter - case 0x29: - return gfx.KeyEscape - case 0x2A: - return gfx.KeyBackspace - case 0x2B: - return gfx.KeyTab - case 0x2C: - return gfx.KeySpace - case 0x49: - return gfx.KeyInsert - case 0x4A: - return gfx.KeyHome - case 0x4B: - return gfx.KeyPageUp - case 0x4C: - return gfx.KeyDelete - case 0x4D: - return gfx.KeyEnd - case 0x4E: - return gfx.KeyPageDown - case 0x4F: - return gfx.KeyRight - case 0x50: - return gfx.KeyLeft - case 0x51: - return gfx.KeyDown - case 0x52: - return gfx.KeyUp - } - return gfx.KeyUnknown -} - -func keyModifiers(flags int) input.Modifiers { - var modifiers input.Modifiers - if flags&uiKeyModifierShift != 0 { - modifiers |= input.ModifierShift - } - if flags&uiKeyModifierControl != 0 { - modifiers |= input.ModifierControl - } - if flags&uiKeyModifierAlt != 0 { - modifiers |= input.ModifierAlt - } - if flags&uiKeyModifierCommand != 0 { - modifiers |= input.ModifierMeta - } - return modifiers -} - -// vivaIOSKeyEvent is a key of a connected keyboard, answering whether it was taken. A key that is not text is a key -// event; a chord with Control or Command and a character is offered as a shortcut, -// and is a key event only if nothing took it. What a key types is the text input's. -// -//export vivaIOSKeyEvent -func vivaIOSKeyEvent(handle C.uintptr_t, view unsafe.Pointer, usage C.int, flags C.int, repeat C.int, utf8 *C.uchar, utf8Length C.size_t) C.int { - state, ok := runStateFor(handle) - if !ok || state.closed { - return 0 - } - modifiers := keyModifiers(int(flags)) - key := keyOfUsage(int(usage)) - chord := modifiers&(input.ModifierControl|input.ModifierMeta) != 0 && utf8Length > 0 - if chord && vivaShortcutEvent(handle, view, C.int(key), C.int(modifiers), repeat, utf8, utf8Length) != 0 { - return 1 - } - if key == gfx.KeyUnknown && !chord { - // What the key types is the text system's. - return 0 - } - deliverKey(handle, view, KeyEvent{Key: key, Modifiers: modifiers, Repeat: repeat != 0}, utf8, utf8Length) - return 1 -} - -// vivaIOSVisibility follows the application going behind another and coming back. -// Coming back, the window is drawn again: what the layer holds may not be the scene. -// -//export vivaIOSVisibility -func vivaIOSVisibility(handle C.uintptr_t, view unsafe.Pointer, visible C.int) { - state, ok := runStateFor(handle) - if !ok || state.closed { - return - } - vivaWindowOccluded(handle, view, visible) - if visible == 0 || state.redrawHandler == nil { - return - } - frame, err := state.redrawHandler() - if err == nil { - err = presentFrame(state, view, frame, false) - } - if err != nil { - state.err = fmt.Errorf("darwin: drawing after the application returned: %w", err) - C.viva_view_close(view) - } -} - -// vivaIOSLifecycle is the system moving the application to the background or back, or -// warning it of low memory: the application's OnLifecycle is told, on the main thread. -// -//export vivaIOSLifecycle -func vivaIOSLifecycle(handle C.uintptr_t, view unsafe.Pointer, kind C.int) { - state, ok := runStateFor(handle) - if !ok || state.closed || state.lifecycleHandler == nil { - return - } - defer func() { - if recovered := recover(); recovered != nil { - platform.ReportFault("darwin: lifecycle handler", recovered) - state.err = fmt.Errorf("darwin: lifecycle handler panicked: %v", recovered) - C.viva_view_close(view) - } - }() - state.lifecycleHandler(platform.Lifecycle(kind)) -} diff --git a/internal/platform/darwin/ios_run.go b/internal/platform/darwin/ios_run.go deleted file mode 100644 index 459b95236..000000000 --- a/internal/platform/darwin/ios_run.go +++ /dev/null @@ -1,52 +0,0 @@ -//go:build ios - -package darwin - -/* -#include "native.h" -#include "ios_host.h" -*/ -import "C" - -import ( - "fmt" - "os" - "runtime" - - "github.com/vivaui/viva/internal/platform" -) - -// iosLaunch is what the application started with. UIKit owns the process from -// UIApplicationMain on, and has the application launched before anything of ours -// may make a window, so start runs from the launch callback, not before. -var iosLaunch struct { - start platform.ApplicationStart -} - -// Run enters the UIKit event loop with one window. -func Run(config Config) error { - return RunApplication(func(application platform.Application) error { - _, err := application.OpenWindow(config) - return err - }) -} - -// RunApplication enters the UIKit event loop; start opens the windows once the -// application has launched. It returns only if UIKit fails to start: an iOS -// application is ended by the system. -func RunApplication(start platform.ApplicationStart) error { - runtime.LockOSThread() - iosLaunch.start = start - return nativeStatusError(C.viva_ios_main()) -} - -// vivaIOSLaunched runs on the main thread, in application:didFinishLaunching. -// -//export vivaIOSLaunched -func vivaIOSLaunched() { - if err := iosLaunch.start(&nativeApplication{}); err != nil { - // There is no caller to return to: UIKit runs the process. - fmt.Fprintf(os.Stderr, "viva: %v\n", err) - C.viva_ios_terminate(1) - } -} diff --git a/internal/platform/darwin/ios_system.go b/internal/platform/darwin/ios_system.go deleted file mode 100644 index 4e5ef9d29..000000000 --- a/internal/platform/darwin/ios_system.go +++ /dev/null @@ -1,61 +0,0 @@ -//go:build ios - -package darwin - -/* -#include -#include "ios_system.h" -*/ -import "C" - -import ( - "strings" - "unsafe" - - "github.com/vivaui/viva/internal/platform" -) - -// fromC copies and frees a string the native side allocated; false for NULL. -func fromC(value *C.char) (string, bool) { - if value == nil { - return "", false - } - defer C.free(unsafe.Pointer(value)) - return C.GoString(value), true -} - -// ClipboardText is the text on the pasteboard, false when there is none. -func ClipboardText() (string, bool) { return fromC(C.viva_ios_clipboard_text()) } - -// SetClipboardText puts text on the pasteboard. -func SetClipboardText(text string) { - native := C.CString(text) - defer C.free(unsafe.Pointer(native)) - C.viva_ios_set_clipboard_text(native) -} - -// OpenURL opens a link in the application that takes it, false when none does. -func OpenURL(url string) bool { - native := C.CString(url) - defer C.free(unsafe.Pointer(native)) - return C.viva_ios_open_url(native) != 0 -} - -// PreferredLanguages are the user's languages, most preferred first, as BCP 47 tags. -func PreferredLanguages() []string { - joined, ok := fromC(C.viva_ios_preferred_languages()) - if !ok || joined == "" { - return nil - } - return strings.Split(joined, "\n") -} - -// ReduceMotion reports whether the user asked for less motion. -func ReduceMotion() bool { return C.viva_ios_reduce_motion() != 0 } - -// DarkTheme is 1 when the system shows the dark look, 0 for the light one and -1 when -// it does not say. -func DarkTheme() int { return int(C.viva_ios_dark_theme()) } - -//export vivaIOSAppearanceChanged -func vivaIOSAppearanceChanged() { platform.NotifyAppearanceChanged() } diff --git a/internal/platform/darwin/ios_system.h b/internal/platform/darwin/ios_system.h deleted file mode 100644 index 26f6c96bd..000000000 --- a/internal/platform/darwin/ios_system.h +++ /dev/null @@ -1,25 +0,0 @@ -//go:build ios - -#ifndef VIVA_IOS_SYSTEM_H -#define VIVA_IOS_SYSTEM_H - -/* What the system gives an application, answered on the main thread whichever - * thread asks. Strings are UTF-8, malloc'ed and freed by the caller. */ - -/* The text on the pasteboard, NULL when there is none. */ -char *viva_ios_clipboard_text(void); -void viva_ios_set_clipboard_text(const char *text); - -/* Opens a link in the application that takes it; nonzero when one was found. */ -int viva_ios_open_url(const char *url); - -/* The user's languages, most preferred first, joined by newlines. */ -char *viva_ios_preferred_languages(void); - -/* Nonzero when the user asked for less motion. */ -int viva_ios_reduce_motion(void); - -/* 1 for the dark look, 0 for the light one, -1 when unknown. */ -int viva_ios_dark_theme(void); - -#endif diff --git a/internal/platform/darwin/ios_system.m b/internal/platform/darwin/ios_system.m deleted file mode 100644 index 0e6347923..000000000 --- a/internal/platform/darwin/ios_system.m +++ /dev/null @@ -1,86 +0,0 @@ -//go:build ios - -// What the system gives an iPhone application: the pasteboard, links, the user's -// languages and the look they chose. - -#import -#include -#include - -#include "ios_system.h" - -// onMain runs work on the main thread, where UIKit may be used, and waits for it. -static void viva_on_main(dispatch_block_t work) { - if ([NSThread isMainThread]) { - work(); - } else { - dispatch_sync(dispatch_get_main_queue(), work); - } -} - -static char *viva_copy(NSString *value) { - const char *utf8 = value.UTF8String; - return utf8 == NULL ? NULL : strdup(utf8); -} - -char *viva_ios_clipboard_text(void) { - __block char *result = NULL; - viva_on_main(^{ - // hasStrings does not read the contents, so asking is free of the paste prompt. - if (UIPasteboard.generalPasteboard.hasStrings) { - result = viva_copy(UIPasteboard.generalPasteboard.string); - } - }); - return result; -} - -void viva_ios_set_clipboard_text(const char *text) { - NSString *value = [NSString stringWithUTF8String:text]; - viva_on_main(^{ - UIPasteboard.generalPasteboard.string = value; - }); -} - -int viva_ios_open_url(const char *text) { - NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:text]]; - if (url == nil) { - return 0; - } - __block int opened = 0; - viva_on_main(^{ - if ([UIApplication.sharedApplication canOpenURL:url] || [url.scheme hasPrefix:@"http"]) { - [UIApplication.sharedApplication openURL:url options:@{} completionHandler:nil]; - opened = 1; - } - }); - return opened; -} - -char *viva_ios_preferred_languages(void) { - return viva_copy([[NSLocale preferredLanguages] componentsJoinedByString:@"\n"]); -} - -int viva_ios_reduce_motion(void) { - __block int reduced = 0; - viva_on_main(^{ - reduced = UIAccessibilityIsReduceMotionEnabled() ? 1 : 0; - }); - return reduced; -} - -int viva_ios_dark_theme(void) { - __block int dark = -1; - viva_on_main(^{ - switch (UIScreen.mainScreen.traitCollection.userInterfaceStyle) { - case UIUserInterfaceStyleDark: - dark = 1; - break; - case UIUserInterfaceStyleLight: - dark = 0; - break; - default: - break; - } - }); - return dark; -} diff --git a/internal/platform/darwin/ios_text.go b/internal/platform/darwin/ios_text.go deleted file mode 100644 index f6d167718..000000000 --- a/internal/platform/darwin/ios_text.go +++ /dev/null @@ -1,68 +0,0 @@ -//go:build ios - -package darwin - -/* -#include "native.h" -*/ -import "C" - -import ( - "unsafe" - - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/platform/imebridge" -) - -// What the keyboard does to the text input, as ios_host.m sends it. -const ( - iosTextCommit = iota + 1 - iosTextSetMarked - iosTextFinish - iosTextReplace - iosTextSelect - iosTextDeleteBackward - iosTextEnter -) - -// vivaIOSTextOp is one thing the keyboard does to the focused text input. The ranges are -// UTF-16 units of the text the keyboard sees, which is the application's: each operation -// is read against the editor's state as it stands, and delivered as the text events the -// other platforms' text services make (deliverTextInputEvent), so the editor, the -// composition and the repaint are the same on every platform. -// -//export vivaIOSTextOp -func vivaIOSTextOp(handle C.uintptr_t, view unsafe.Pointer, operation C.int, utf8 *C.uchar, utf8Length C.size_t, first, last C.int64_t) { - state, ok := runStateFor(handle) - if !ok || state.closed || state.textHandler == nil { - return - } - value := "" - if utf8Length > 0 { - value = C.GoStringN((*C.char)(unsafe.Pointer(utf8)), C.int(utf8Length)) - } - session := &imebridge.Session{ - State: state.textState, - Handler: func(event platform.TextEvent) (platform.TextState, error) { - err := deliverTextInputEvent(state, view, event, true, false) - return state.textState, err - }, - } - switch operation { - case iosTextCommit: - session.Commit(value, 1) - case iosTextSetMarked: - session.SetMarked(value, int(first), int(last)) - case iosTextFinish: - session.Finish() - case iosTextReplace: - session.Replace(int(first), int(last), value) - case iosTextSelect: - session.Select(int(first), int(last)) - case iosTextDeleteBackward: - session.Command(platform.TextDeleteBackward) - case iosTextEnter: - // Enter in a field of one line is the application's, as a key. - _ = vivaIOSKeyEvent(handle, view, 0x28, 0, 0, nil, 0) - } -} diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 61bb88eb9..189909c27 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -1589,13 +1589,13 @@ - (void)mouseDown:(NSEvent *)event { } int press = VIVA_PRESS_CLIENT; if ((self.window.styleMask & NSWindowStyleMaskFullScreen) == 0 && - (_windowMode == VIVA_WINDOW_CUSTOM_TITLEBAR || _windowMode == VIVA_WINDOW_FRAMELESS) && _callbackHandle != 0) { + (_windowMode == VIVA_WINDOW_CUSTOM_TITLEBAR || _windowMode == VIVA_WINDOW_FRAMELESS || _windowMode == VIVA_WINDOW_NOTIFICATION) && _callbackHandle != 0) { // The application declares where the window moves from (a move region). NSPoint local = [self convertPoint:event.locationInWindow fromView:nil]; press = vivaPressAt(_callbackHandle, local.x, self.bounds.size.height - local.y); } if (press == VIVA_PRESS_MOVE) { - if (event.clickCount >= 2) { + if (event.clickCount >= 2 && _windowMode != VIVA_WINDOW_NOTIFICATION) { // Standard titlebar behavior: double-click zooms the window. [[self window] performZoom:event]; return; @@ -4056,6 +4056,29 @@ - (void)placeAtOrigin { return; } NSScreen *screen = nil; + if (_windowMode == VIVA_WINDOW_NOTIFICATION) { + NSPoint topLeft = NSMakePoint(NSMinX(frame), NSMaxY(frame)); + CGFloat nearestDistance = CGFLOAT_MAX; + for (NSScreen *candidate in NSScreen.screens) { + NSRect bounds = candidate.frame; + CGFloat dx = topLeft.x - MIN(MAX(topLeft.x, NSMinX(bounds)), NSMaxX(bounds)); + CGFloat dy = topLeft.y - MIN(MAX(topLeft.y, NSMinY(bounds)), NSMaxY(bounds)); + CGFloat distance = dx * dx + dy * dy; + if (distance < nearestDistance) { + nearestDistance = distance; + screen = candidate; + } + } + if (screen != nil) { + NSRect area = screen.visibleFrame; + frame.size.width = MIN(frame.size.width, area.size.width); + frame.size.height = MIN(frame.size.height, area.size.height); + frame.origin.x = MIN(MAX(NSMinX(area), frame.origin.x), NSMaxX(area) - frame.size.width); + frame.origin.y = MIN(MAX(NSMinY(area), frame.origin.y), NSMaxY(area) - frame.size.height); + } + [_window setFrame:frame display:NO]; + return; + } NSPoint middle = NSMakePoint(NSMidX(frame), NSMidY(frame)); for (NSScreen *candidate in NSScreen.screens) { if (NSPointInRect(middle, candidate.frame)) { @@ -4128,6 +4151,10 @@ - (BOOL)contentFrame:(double *)out { * screen the anchor is on. Without an anchor it is centered on the screen. */ - (void)placePanel { if (_windowMode == VIVA_WINDOW_NOTIFICATION) { + if (_hasOrigin) { + [self placeAtOrigin]; + return; + } NSPoint point = NSEvent.mouseLocation; NSScreen *screen = NSScreen.mainScreen ?: NSScreen.screens.firstObject; for (NSScreen *candidate in NSScreen.screens) { diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index e276e4ab9..1a1dc623b 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -148,8 +148,6 @@ func (window *nativeWindow) SetAlwaysOnTop(enabled bool) error { } type runState struct { - // safeArea is how far the system covers the window's edges, as the iOS host last said. - safeArea gfx.Insets application *nativeApplication callbackHandle cgo.Handle onClosed func() @@ -161,7 +159,6 @@ type runState struct { frameHandler platform.FrameChangeHandler minimizeHandler platform.MinimizeHandler visibilityHandler platform.VisibilityHandler - lifecycleHandler func(platform.Lifecycle) fullscreenHandler func(bool) onReopen func() onActivate func() @@ -368,7 +365,7 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window } state := &runState{application: application, onClosed: config.OnClosed, waker: config.Waker, closeHandler: config.OnCloseRequest, pressAt: config.PressAt, - frameHandler: config.OnFrameChange, minimizeHandler: config.OnMinimize, visibilityHandler: config.OnVisibility, lifecycleHandler: config.OnLifecycle, fullscreenHandler: config.OnFullscreen, onReopen: config.OnReopen, onActivate: config.OnActivate} + frameHandler: config.OnFrameChange, minimizeHandler: config.OnMinimize, visibilityHandler: config.OnVisibility, fullscreenHandler: config.OnFullscreen, onReopen: config.OnReopen, onActivate: config.OnActivate} state.pointerHandler = config.OnPointer state.resizeHandler = config.OnResize state.keyHandler = config.OnKey diff --git a/internal/platform/darwin/proxy_darwin.go b/internal/platform/darwin/proxy_darwin.go index 9b2d287d3..f455e2eef 100644 --- a/internal/platform/darwin/proxy_darwin.go +++ b/internal/platform/darwin/proxy_darwin.go @@ -11,39 +11,97 @@ package darwin import "C" import ( + "context" "errors" "fmt" "net/url" + "time" "unsafe" ) // ErrProxyUnavailable reports that the system's proxy policy could not be -// evaluated: it is a PAC script, or CFNetwork failed. +// evaluated: CFNetwork failed, or a PAC script failed or timed out. var ErrProxyUnavailable = errors.New("darwin: the system proxy settings cannot be read") // SystemProxy asks CFNetwork which proxy the system selects for target. func SystemProxy(target string) (*url.URL, error) { + return SystemProxyContext(context.Background(), target) +} + +// SystemProxyContext also stops a pending PAC download or evaluation when ctx +// ends. Native PAC work has a ten-second ceiling even without a deadline. +func SystemProxyContext(ctx context.Context, target string) (*url.URL, error) { + if err := ctx.Err(); err != nil { + return nil, err + } cTarget := C.CString(target) defer C.free(unsafe.Pointer(cTarget)) var value, nativeError *C.char status := C.viva_system_proxy(cTarget, &value, &nativeError) + if status == 2 || status == 3 { + defer C.viva_system_free(unsafe.Pointer(value)) + return proxyFromPAC(ctx, target, C.GoString(value), status == 2, 10*time.Second) + } + return proxyResult(status, value, nativeError) +} + +func proxyFromPAC(ctx context.Context, target, configuration string, fromURL bool, timeout time.Duration) (*url.URL, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + request := C.viva_proxy_request_create() + if request == nil { + return nil, fmt.Errorf("%w: the PAC request could not be allocated", ErrProxyUnavailable) + } + // Cancellation only writes the C request's atomic flag. Wait for an already + // running AfterFunc before dropping our reference to its C allocation. + cancelled := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { + C.viva_proxy_request_cancel(request) + close(cancelled) + }) + defer func() { + if !stop() { + <-cancelled + } + C.viva_proxy_request_release(request) + }() + cTarget, cConfiguration := C.CString(target), C.CString(configuration) + defer C.free(unsafe.Pointer(cTarget)) + defer C.free(unsafe.Pointer(cConfiguration)) + var value, nativeError *C.char + urlMode := C.int(0) + if fromURL { + urlMode = 1 + } + status := C.viva_proxy_execute_pac(request, cTarget, cConfiguration, urlMode, C.double(timeout.Seconds()), &value, &nativeError) + proxy, err := proxyResult(status, value, nativeError) + if ctx.Err() != nil { + return nil, ctx.Err() + } + return proxy, err +} + +func proxyResult(status C.int, value, nativeError *C.char) (*url.URL, error) { + if value != nil { + defer C.viva_system_free(unsafe.Pointer(value)) + } + if nativeError != nil { + defer C.viva_system_free(unsafe.Pointer(nativeError)) + } switch status { case 0: return nil, nil case 1: - defer C.viva_system_free(unsafe.Pointer(value)) proxy, err := url.Parse(C.GoString(value)) if err != nil { return nil, fmt.Errorf("%w: %v", ErrProxyUnavailable, err) } return proxy, nil - case 2: - return nil, fmt.Errorf("%w: the system uses a proxy auto-configuration script", ErrProxyUnavailable) default: message := "the system proxy settings could not be read" if nativeError != nil { message = C.GoString(nativeError) - C.viva_system_free(unsafe.Pointer(nativeError)) } return nil, fmt.Errorf("%w: %s", ErrProxyUnavailable, message) } diff --git a/internal/platform/darwin/proxy_darwin.h b/internal/platform/darwin/proxy_darwin.h index 6a8342222..f866ab193 100644 --- a/internal/platform/darwin/proxy_darwin.h +++ b/internal/platform/darwin/proxy_darwin.h @@ -3,10 +3,25 @@ #ifndef VIVA_PROXY_DARWIN_H #define VIVA_PROXY_DARWIN_H +#include + // viva_system_proxy asks CFNetwork which proxy the system's settings select for // target (an absolute URL). Status: 0 direct (no proxy), 1 proxy in *value -// (free with viva_system_free), 2 the policy is a PAC script, which this -// function does not evaluate, -1 failure with *error_message. +// (free with viva_system_free), 2 PAC URL in *value, 3 PAC JavaScript in *value, +// -1 failure with *error_message. int viva_system_proxy(const char *target, char **value, char **error_message); +// Select the first entry: a failed first choice must not silently become DIRECT. +int viva_proxy_select(CFArrayRef proxies, char **value, char **error_message); + +typedef struct viva_proxy_request viva_proxy_request; +viva_proxy_request *viva_proxy_request_create(void); +void viva_proxy_request_cancel(viva_proxy_request *request); +void viva_proxy_request_release(viva_proxy_request *request); +// Evaluate a PAC URL or inline script on this thread's private run-loop mode. +// The source is invalidated on every exit, including cancellation and timeout. +int viva_proxy_execute_pac(viva_proxy_request *request, const char *target, + const char *configuration, int from_url, double timeout, + char **value, char **error_message); + #endif diff --git a/internal/platform/darwin/proxy_darwin.m b/internal/platform/darwin/proxy_darwin.m index 052e189d9..3d77a2cbb 100644 --- a/internal/platform/darwin/proxy_darwin.m +++ b/internal/platform/darwin/proxy_darwin.m @@ -44,52 +44,83 @@ int viva_system_proxy(const char *target, char **value, char **error_message) { return -1; } CFDictionaryRef settings = CFNetworkCopySystemProxySettings(); + if (settings == NULL) { + CFRelease(url); + viva_proxy_set_error(error_message, "the system proxy settings are unavailable"); + return -1; + } CFArrayRef proxies = CFNetworkCopyProxiesForURL(url, settings); CFRelease(url); - if (settings != NULL) { - CFRelease(settings); + CFRelease(settings); + if (proxies == NULL) { + viva_proxy_set_error(error_message, "the system returned no proxy decision"); + return -1; } + int status = viva_proxy_select(proxies, value, error_message); + CFRelease(proxies); + return status; +} + +int viva_proxy_select(CFArrayRef proxies, char **value, char **error_message) { if (proxies == NULL || CFArrayGetCount(proxies) == 0) { - if (proxies != NULL) { - CFRelease(proxies); - } - return 0; + viva_proxy_set_error(error_message, "the policy returned no proxy decision"); + return -1; } CFDictionaryRef proxy = (CFDictionaryRef)CFArrayGetValueAtIndex(proxies, 0); CFStringRef type = (CFStringRef)CFDictionaryGetValue(proxy, kCFProxyTypeKey); - int status = 0; - if (type != NULL && CFStringCompare(type, kCFProxyTypeNone, 0) != kCFCompareEqualTo) { - if (CFStringCompare(type, kCFProxyTypeAutoConfigurationURL, 0) == 0 || - CFStringCompare(type, kCFProxyTypeAutoConfigurationJavaScript, 0) == 0) { - status = 2; - } else { - CFStringRef host = (CFStringRef)CFDictionaryGetValue(proxy, kCFProxyHostNameKey); - CFNumberRef port = (CFNumberRef)CFDictionaryGetValue(proxy, kCFProxyPortNumberKey); - char *host_text = viva_proxy_copy_utf8(host); - int port_value = 0; - if (port != NULL) { - CFNumberGetValue(port, kCFNumberIntType, &port_value); - } - if (host_text == NULL) { - viva_proxy_set_error(error_message, "the selected proxy has no host"); - status = -1; - } else { - const char *scheme = CFStringCompare(type, kCFProxyTypeSOCKS, 0) == 0 ? "socks5" : "http"; - char buffer[1024]; - if (port_value > 0) { - snprintf(buffer, sizeof buffer, "%s://%s:%d", scheme, host_text, port_value); - } else { - snprintf(buffer, sizeof buffer, "%s://%s", scheme, host_text); - } - *value = strdup(buffer); - free(host_text); - status = *value == NULL ? -1 : 1; - if (status < 0) { - viva_proxy_set_error(error_message, "the proxy URL could not be allocated"); - } + if (type == NULL) { + viva_proxy_set_error(error_message, "the selected proxy has no type"); + return -1; + } + if (CFEqual(type, kCFProxyTypeNone)) { + return 0; + } + if (CFEqual(type, kCFProxyTypeAutoConfigurationURL) || + CFEqual(type, kCFProxyTypeAutoConfigurationJavaScript)) { + int from_url = CFEqual(type, kCFProxyTypeAutoConfigurationURL); + CFStringRef configuration = NULL; + if (from_url) { + CFURLRef pac_url = (CFURLRef)CFDictionaryGetValue(proxy, kCFProxyAutoConfigurationURLKey); + if (pac_url != NULL) { + configuration = CFURLGetString(pac_url); } + } else { + configuration = (CFStringRef)CFDictionaryGetValue(proxy, kCFProxyAutoConfigurationJavaScriptKey); + } + *value = viva_proxy_copy_utf8(configuration); + if (*value == NULL) { + viva_proxy_set_error(error_message, "the PAC configuration is missing"); + return -1; } + return from_url ? 2 : 3; } - CFRelease(proxies); - return status; + CFStringRef host = (CFStringRef)CFDictionaryGetValue(proxy, kCFProxyHostNameKey); + CFNumberRef port = (CFNumberRef)CFDictionaryGetValue(proxy, kCFProxyPortNumberKey); + char *host_text = viva_proxy_copy_utf8(host); + int port_value = 0; + if (port != NULL) { + CFNumberGetValue(port, kCFNumberIntType, &port_value); + } + if (host_text == NULL) { + viva_proxy_set_error(error_message, "the selected proxy has no host"); + return -1; + } + const char *scheme = CFEqual(type, kCFProxyTypeSOCKS) ? "socks5" : "http"; + char buffer[1024]; + if (port_value > 0) { + if (strchr(host_text, ':') != NULL && host_text[0] != '[') { + snprintf(buffer, sizeof buffer, "%s://[%s]:%d", scheme, host_text, port_value); + } else { + snprintf(buffer, sizeof buffer, "%s://%s:%d", scheme, host_text, port_value); + } + } else { + snprintf(buffer, sizeof buffer, "%s://%s", scheme, host_text); + } + *value = strdup(buffer); + free(host_text); + if (*value == NULL) { + viva_proxy_set_error(error_message, "the proxy URL could not be allocated"); + return -1; + } + return 1; } diff --git a/internal/platform/darwin/proxy_darwin_test.go b/internal/platform/darwin/proxy_darwin_test.go index 415818d59..cbec758c2 100644 --- a/internal/platform/darwin/proxy_darwin_test.go +++ b/internal/platform/darwin/proxy_darwin_test.go @@ -2,7 +2,173 @@ package darwin -import "testing" +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +const targetPAC = `function FindProxyForURL(url, host) { + if (host === "direct.example") return "DIRECT"; + if (host === "socks.example") return "SOCKS 127.0.0.1:1080"; + return "PROXY 127.0.0.1:7890; DIRECT"; +}` + +func TestProxyFromPACScript(t *testing.T) { + for _, test := range []struct{ target, want string }{ + {"http://dl.motty.page/latest.json", "http://127.0.0.1:7890"}, + {"https://api.github.com/repos/carapace-sh/carapace-bin/releases/latest", "http://127.0.0.1:7890"}, + {"https://direct.example/", ""}, + {"https://socks.example/", "socks5://127.0.0.1:1080"}, + } { + t.Run(test.target, func(t *testing.T) { + proxy, err := proxyFromPAC(context.Background(), test.target, targetPAC, false, 10*time.Second) + if err != nil { + t.Fatal(err) + } + got := "" + if proxy != nil { + got = proxy.String() + } + if got != test.want { + t.Fatalf("PAC proxy = %q, want %q", got, test.want) + } + }) + } +} + +func TestProxyFromPACURL(t *testing.T) { + requested := make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case requested <- struct{}{}: + default: + } + w.Header().Set("Content-Type", "application/x-ns-proxy-autoconfig") + fmt.Fprint(w, targetPAC) + })) + defer server.Close() + proxy, err := proxyFromPAC(context.Background(), "https://dl.motty.page/latest.json", server.URL+"/proxy.pac", true, 10*time.Second) + if err != nil || proxy == nil || proxy.String() != "http://127.0.0.1:7890" { + t.Fatalf("downloaded PAC proxy = %v, %v", proxy, err) + } + select { + case <-requested: + default: + t.Fatal("the PAC URL was never downloaded") + } +} + +func TestPACScriptFailureDoesNotGoDirect(t *testing.T) { + for _, script := range []string{ + `function FindProxyForURL( {`, + `function FindProxyForURL(url, host) { throw new Error("broken PAC"); }`, + } { + proxy, err := proxyFromPAC(context.Background(), "https://example.com/", script, false, 10*time.Second) + if proxy != nil || !errors.Is(err, ErrProxyUnavailable) { + t.Fatalf("broken PAC returned %v, %v; want an error instead of DIRECT", proxy, err) + } + } +} + +func stalledPAC(t *testing.T) (string, <-chan struct{}) { + t.Helper() + started, release := make(chan struct{}, 1), make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case started <- struct{}{}: + default: + } + select { + case <-release: + case <-r.Context().Done(): + } + })) + t.Cleanup(server.Close) + t.Cleanup(func() { close(release) }) + return server.URL + "/proxy.pac", started +} + +func TestPACDownloadHonorsCancellation(t *testing.T) { + address, started := stalledPAC(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + result := make(chan error, 1) + go func() { + _, err := proxyFromPAC(ctx, "https://example.com/", address, true, 10*time.Second) + result <- err + }() + select { + case <-started: + case err := <-result: + t.Fatalf("PAC lookup ended before the download: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("PAC download did not start") + } + cancel() + select { + case err := <-result: + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled PAC lookup returned %v", err) + } + case <-time.After(3 * time.Second): + t.Fatal("cancellation did not interrupt the PAC download") + } +} + +func TestPACDownloadHonorsDeadline(t *testing.T) { + address, _ := stalledPAC(t) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + proxy, err := proxyFromPAC(ctx, "https://example.com/", address, true, 10*time.Second) + if proxy != nil || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expired PAC lookup returned %v, %v", proxy, err) + } +} + +func TestPACDownloadTimeoutDoesNotGoDirect(t *testing.T) { + address, _ := stalledPAC(t) + start := time.Now() + proxy, err := proxyFromPAC(context.Background(), "https://example.com/", address, true, 200*time.Millisecond) + if proxy != nil || !errors.Is(err, ErrProxyUnavailable) || !strings.Contains(err.Error(), "timed out") { + t.Fatalf("stalled PAC returned %v, %v", proxy, err) + } + if time.Since(start) > 3*time.Second { + t.Fatal("PAC download exceeded its timeout") + } + // A terminated source must leave the worker's run loop usable. + proxy, err = proxyFromPAC(context.Background(), "https://direct.example/", targetPAC, false, 10*time.Second) + if proxy != nil || err != nil { + t.Fatalf("PAC lookup after timeout returned %v, %v", proxy, err) + } +} + +func TestPACConcurrentLookups(t *testing.T) { + results := make(chan error, 8) + for i := range 8 { + go func() { + target := "https://dl.motty.page/" + if i%2 == 0 { + target = "https://direct.example/" + } + proxy, err := proxyFromPAC(context.Background(), target, targetPAC, false, 10*time.Second) + if err == nil && (proxy == nil) != (i%2 == 0) { + err = fmt.Errorf("lookup %d: proxy = %v", i, proxy) + } + results <- err + }() + } + for range 8 { + if err := <-results; err != nil { + t.Error(err) + } + } +} // The machine this runs on may or may not have a proxy; what must hold is that // CFNetwork answers, and that an answer is a URL or a policy this package names. diff --git a/internal/platform/darwin/proxy_pac_darwin.m b/internal/platform/darwin/proxy_pac_darwin.m new file mode 100644 index 000000000..9aaa87e68 --- /dev/null +++ b/internal/platform/darwin/proxy_pac_darwin.m @@ -0,0 +1,195 @@ +//go:build !ios + +#import + +#include +#include +#include +#include + +#include "proxy_darwin.h" + +// lock guards cancelled, waiting and wake. Cancellation signals the wake source +// and wakes waiting's run loop, so a stalled PAC evaluation returns at once +// instead of on the next poll. +struct viva_proxy_request { + int references; + int cancelled; + int done; + CFArrayRef proxies; + CFErrorRef error; + pthread_mutex_t lock; + CFRunLoopRef waiting; + CFRunLoopSourceRef wake; +}; + +viva_proxy_request *viva_proxy_request_create(void) { + viva_proxy_request *request = calloc(1, sizeof *request); + if (request != NULL) { + request->references = 1; + pthread_mutex_init(&request->lock, NULL); + } + return request; +} + +static void *viva_proxy_request_retain(void *info) { + viva_proxy_request *request = info; + __atomic_fetch_add(&request->references, 1, __ATOMIC_RELAXED); + return request; +} + +void viva_proxy_request_release(viva_proxy_request *request) { + if (request != NULL && __atomic_fetch_sub(&request->references, 1, __ATOMIC_ACQ_REL) == 1) { + if (request->proxies != NULL) { + CFRelease(request->proxies); + } + if (request->error != NULL) { + CFRelease(request->error); + } + pthread_mutex_destroy(&request->lock); + free(request); + } +} + +static void viva_proxy_context_release(void *info) { + viva_proxy_request_release(info); +} + +// viva_proxy_wake only exists so that signalling the wake source makes the run +// loop return from CFRunLoopRunInMode; there is no work to do in it. +static void viva_proxy_wake(void *info) { + (void)info; +} + +void viva_proxy_request_cancel(viva_proxy_request *request) { + pthread_mutex_lock(&request->lock); + request->cancelled = 1; + if (request->waiting != NULL) { + CFRunLoopSourceSignal(request->wake); + CFRunLoopWakeUp(request->waiting); + } + pthread_mutex_unlock(&request->lock); +} + +static void viva_proxy_pac_result(void *info, CFArrayRef proxies, CFErrorRef error) { + viva_proxy_request *request = info; + // CFNetwork invokes this on the run loop that scheduled its source. Only + // cancellation touches the request from another thread, through its atomic. + if (!request->done) { + request->proxies = proxies == NULL ? NULL : (CFArrayRef)CFRetain(proxies); + request->error = error == NULL ? NULL : (CFErrorRef)CFRetain(error); + request->done = 1; + } +} + +static int viva_proxy_pac_error(char **error_message, const char *message) { + *error_message = strdup(message); + return -1; +} + +static double viva_proxy_monotonic_seconds(void) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + return (double)now.tv_sec + (double)now.tv_nsec / 1000000000.0; +} + +int viva_proxy_execute_pac(viva_proxy_request *request, const char *target, + const char *configuration, int from_url, double timeout, + char **value, char **error_message) { + *value = NULL; + CFURLRef url = CFURLCreateWithBytes(kCFAllocatorDefault, (const UInt8 *)target, + (CFIndex)strlen(target), kCFStringEncodingUTF8, NULL); + CFStringRef script = CFStringCreateWithCString(kCFAllocatorDefault, configuration, kCFStringEncodingUTF8); + if (url == NULL || script == NULL) { + if (url != NULL) CFRelease(url); + if (script != NULL) CFRelease(script); + return viva_proxy_pac_error(error_message, "the PAC configuration or target is not UTF-8"); + } + CFStreamClientContext context = {0, request, viva_proxy_request_retain, viva_proxy_context_release, NULL}; + CFRunLoopSourceRef source = NULL; + if (from_url) { + CFURLRef pac_url = CFURLCreateWithString(kCFAllocatorDefault, script, NULL); + if (pac_url != NULL) { + source = CFNetworkExecuteProxyAutoConfigurationURL(pac_url, url, viva_proxy_pac_result, &context); + CFRelease(pac_url); + } + } else { + source = CFNetworkExecuteProxyAutoConfigurationScript(script, url, viva_proxy_pac_result, &context); + } + CFRelease(script); + CFRelease(url); + if (source == NULL) { + return viva_proxy_pac_error(error_message, "the PAC evaluation could not be started"); + } + + CFRunLoopRef loop = CFRunLoopGetCurrent(); + CFStringRef mode = CFSTR("dev.vivaui.proxy.PAC"); + CFRunLoopSourceContext wake_context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, viva_proxy_wake}; + CFRunLoopSourceRef wake = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &wake_context); + int scheduled = 0; + pthread_mutex_lock(&request->lock); + if (!request->cancelled && wake != NULL) { + request->waiting = loop; + request->wake = wake; + CFRunLoopAddSource(loop, source, mode); + CFRunLoopAddSource(loop, wake, mode); + scheduled = 1; + } + pthread_mutex_unlock(&request->lock); + + double deadline = viva_proxy_monotonic_seconds() + timeout; + while (scheduled && !request->done) { + pthread_mutex_lock(&request->lock); + int cancelled = request->cancelled; + pthread_mutex_unlock(&request->lock); + double remaining = deadline - viva_proxy_monotonic_seconds(); + if (cancelled || remaining <= 0) { + break; + } + // Blocks until the PAC work finishes, the wake source is signalled by + // cancellation, or the remaining time runs out. A private mode does not + // dispatch the application's UI. + SInt32 result = CFRunLoopRunInMode(mode, remaining, true); + if (result == kCFRunLoopRunFinished || result == kCFRunLoopRunStopped) { + break; + } + } + + // Stop cancellation from touching the wake source before it is released. + pthread_mutex_lock(&request->lock); + request->waiting = NULL; + request->wake = NULL; + int was_cancelled = request->cancelled; + pthread_mutex_unlock(&request->lock); + if (scheduled) { + CFRunLoopRemoveSource(loop, wake, mode); + } + if (wake != NULL) { + CFRunLoopSourceInvalidate(wake); + CFRelease(wake); + } + // Apple requires invalidating this source to terminate unfinished work. + // The source retains the heap context until CFNetwork is finished with it. + CFRunLoopSourceInvalidate(source); + CFRelease(source); + if (was_cancelled) { + return viva_proxy_pac_error(error_message, "the PAC evaluation was canceled"); + } + if (!request->done) { + return viva_proxy_pac_error(error_message, "the PAC evaluation timed out"); + } + if (request->error != NULL) { + CFStringRef description = CFErrorCopyDescription(request->error); + char message[1024]; + int copied = description != NULL && CFStringGetCString(description, message, sizeof message, kCFStringEncodingUTF8); + if (description != NULL) CFRelease(description); + return viva_proxy_pac_error(error_message, copied ? message : "the PAC evaluation failed"); + } + int status = viva_proxy_select(request->proxies, value, error_message); + if (status == 2 || status == 3) { + free(*value); + *value = NULL; + return viva_proxy_pac_error(error_message, "the PAC evaluation returned another PAC configuration"); + } + return status; +} diff --git a/internal/platform/darwin/shader_ios.go b/internal/platform/darwin/shader_ios.go deleted file mode 100644 index 29ae48abe..000000000 --- a/internal/platform/darwin/shader_ios.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build ios - -package darwin - -/* -#include "ios_host.h" -*/ -import "C" - -import _ "embed" - -// A Metal library records the platform it was built for, and the simulator's is -// not the device's, so both are shipped and the one the build runs on is chosen. -// tools/generate_darwin_shaders.sh makes them. -var ( - //go:embed shaders/scene_ios.metallib - sceneShaderLibraryDevice []byte - //go:embed shaders/scene_ios_simulator.metallib - sceneShaderLibrarySimulator []byte -) - -// sceneShaderLibrary is the library of the platform the program runs on. -var sceneShaderLibrary = func() []byte { - if C.viva_ios_is_simulator() != 0 { - return sceneShaderLibrarySimulator - } - return sceneShaderLibraryDevice -}() diff --git a/internal/platform/darwin/shaders/scene_ios.metallib b/internal/platform/darwin/shaders/scene_ios.metallib deleted file mode 100644 index 4d92d4052..000000000 Binary files a/internal/platform/darwin/shaders/scene_ios.metallib and /dev/null differ diff --git a/internal/platform/darwin/shaders/scene_ios_simulator.metallib b/internal/platform/darwin/shaders/scene_ios_simulator.metallib deleted file mode 100644 index 7add350bc..000000000 Binary files a/internal/platform/darwin/shaders/scene_ios_simulator.metallib and /dev/null differ diff --git a/internal/platform/darwin/testdata/window_notification.m b/internal/platform/darwin/testdata/window_notification.m index 10a22c1ae..ee49a879d 100644 --- a/internal/platform/darwin/testdata/window_notification.m +++ b/internal/platform/darwin/testdata/window_notification.m @@ -79,6 +79,21 @@ int main(void) { assert(window.isVisible && NSApp.keyWindow == key); assert(NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier == foreground); [popup hideWindow]; + if (NSScreen.screens.count == 1) { + NSRect area = NSScreen.screens.firstObject.visibleFrame; + CGFloat height = NSScreen.screens.firstObject.frame.size.height; + [popup setValue:[NSValue valueWithPoint:NSMakePoint(NSMinX(area) + 20, height - NSMaxY(area) + 20)] + forKey:@"origin"]; + [popup placeAtOrigin]; + assert(NSMinX(window.frame) == NSMinX(area) + 20 && NSMaxY(window.frame) == NSMaxY(area) - 20); + [popup setValue:[NSValue valueWithPoint:NSMakePoint(NSMaxX(area) - 1, height - NSMinY(area) - 1)] + forKey:@"origin"]; + [popup placeAtOrigin]; + assert(NSMaxX(window.frame) == NSMaxX(area) && NSMinY(window.frame) == NSMinY(area)); + [popup setValue:[NSValue valueWithPoint:NSMakePoint(-100000, -100000)] forKey:@"origin"]; + [popup placeAtOrigin]; + assert(NSMinX(window.frame) == NSMinX(area) && NSMaxY(window.frame) == NSMaxY(area)); + } [owner orderOut:nil]; [popup release]; [queue release]; diff --git a/internal/platform/darwin/web_darwin.go b/internal/platform/darwin/web_darwin.go index 1bfe7f33f..a3bad7cf4 100644 --- a/internal/platform/darwin/web_darwin.go +++ b/internal/platform/darwin/web_darwin.go @@ -10,6 +10,8 @@ package darwin import "C" import ( + "crypto/sha1" + "encoding/hex" "encoding/json" "fmt" "os" @@ -23,6 +25,15 @@ import ( "github.com/vivaui/viva/internal/render" ) +// partitionIdentifier gives WebKit the same persistent store for a partition name on every launch. +func partitionIdentifier(name string) string { + sum := sha1.Sum([]byte("viva-storage-partition:" + name)) + sum[6] = sum[6]&0x0f | 0x50 // version 5 + sum[8] = sum[8]&0x3f | 0x80 // RFC 4122 variant + text := hex.EncodeToString(sum[:16]) + return strings.ToUpper(text[0:8] + "-" + text[8:12] + "-" + text[12:16] + "-" + text[16:20] + "-" + text[20:32]) +} + // Web pages inside the window (ADR 0064): WKWebView, one per page, subviews of the window's Metal // view and above its layer. A page gives way where Viva draws over it (platform.NativeCuts): those // parts are masked off, so Viva's picture shows, and refuse the pointer, so Viva gets it. The @@ -134,7 +145,7 @@ func (w *webState) open(config platform.WebViewConfig) (platform.WebView, error) if C.viva_web_partition_supported() == 0 { return nil, fmt.Errorf("darwin: a named storage partition needs macOS 14 or newer: %w", platform.ErrWebViewUnsupported) } - partition = C.CString(platform.PartitionIdentifier(config.Partition)) + partition = C.CString(partitionIdentifier(config.Partition)) defer C.free(unsafe.Pointer(partition)) } var failure *C.char diff --git a/internal/platform/web_host_test.go b/internal/platform/darwin/web_partition_darwin_test.go similarity index 71% rename from internal/platform/web_host_test.go rename to internal/platform/darwin/web_partition_darwin_test.go index 360c440c8..1dcf6474c 100644 --- a/internal/platform/web_host_test.go +++ b/internal/platform/darwin/web_partition_darwin_test.go @@ -1,4 +1,6 @@ -package platform +//go:build darwin && !ios + +package darwin import ( "strings" @@ -8,17 +10,17 @@ import ( // A storage partition's name is the same store in every run, so the identifier it is named by on the // platform that wants one has to be the same too. func TestAPartitionIdentifierIsTheSameForEveryNameEveryTime(t *testing.T) { - first, second := PartitionIdentifier("workspace-1"), PartitionIdentifier("workspace-1") + first, second := partitionIdentifier("workspace-1"), partitionIdentifier("workspace-1") if first != second { t.Fatalf("%q and %q name the same partition", first, second) } - if other := PartitionIdentifier("workspace-2"); other == first { + if other := partitionIdentifier("workspace-2"); other == first { t.Fatalf("two partitions share the identifier %q", other) } } func TestAPartitionIdentifierIsAUUID(t *testing.T) { - identifier := PartitionIdentifier("workspace-1") + identifier := partitionIdentifier("workspace-1") if len(identifier) != 36 { t.Fatalf("identifier %q is %d characters, want 36", identifier, len(identifier)) } @@ -40,3 +42,10 @@ func TestAPartitionIdentifierIsAUUID(t *testing.T) { t.Fatalf("identifier %q is not a version 5 UUID with an RFC 4122 variant", identifier) } } + +func TestWebKitKeepsTheExistingPartitionIdentifier(t *testing.T) { + const want = "26F5E273-A7C6-5A8C-B0C9-829B7CE44701" + if got := partitionIdentifier("workspace-1"); got != want { + t.Fatalf("identifier = %q, want %q so existing WebKit data remains accessible", got, want) + } +} diff --git a/internal/platform/imebridge/imebridge.go b/internal/platform/imebridge/imebridge.go deleted file mode 100644 index 5ed555e43..000000000 --- a/internal/platform/imebridge/imebridge.go +++ /dev/null @@ -1,259 +0,0 @@ -// Package imebridge turns what a phone's input method does into the text events -// the application's editor takes. Android's InputConnection and iOS's UITextInput -// both speak in UTF-16 ranges of a copy of the text, and commit, mark, replace and -// select in ways that differ from a desktop's; the bridge reads each operation -// against the editor's state as it stands, so an operation that follows another sees -// what the first did. It has no system call in it and is tested on the host. -package imebridge - -import ( - "unicode/utf16" - - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/input" - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/text" -) - -// Session is one focused editor as the input method edits it: the state the -// application last gave, and the handler that applies an event and answers with the -// state after it. -type Session struct { - Handler platform.TextHandler - State platform.TextState -} - -// Mirror is the text and the ranges an input method reads, in UTF-16 units. -type Mirror struct { - Text string - SelStart, SelEnd int - CompStart, CompEnd int - Composing bool - SelectionEndIsCaret bool - TentativeComposition bool -} - -// Mirror is the state as the input method counts it. -func (session *Session) Mirror() Mirror { return MirrorOf(session.State) } - -// MirrorOf is state counted in UTF-16 units. -func MirrorOf(state platform.TextState) Mirror { - mirror := Mirror{ - Text: state.Value, - SelStart: text.UTF16Offset(state.Value, state.Selection.Start), - SelEnd: text.UTF16Offset(state.Value, state.Selection.End), - SelectionEndIsCaret: !state.SelectionReversed, - Composing: state.Composing, - } - if state.Composing { - mirror.CompStart = text.UTF16Offset(state.Value, state.Composition.Start) - mirror.CompEnd = text.UTF16Offset(state.Value, state.Composition.End) - } else { - mirror.CompStart, mirror.CompEnd = -1, -1 - } - return mirror -} - -// apply sends one event and takes the state after it. -func (session *Session) apply(event platform.TextEvent) error { - next, err := session.Handler(event) - if err != nil { - return err - } - session.State = next - return nil -} - -// units is the number of UTF-16 units of value. -func units(value string) int { return len(utf16.Encode([]rune(value))) } - -// runeRange is the rune range of the UTF-16 range [start, end) of value, clamped to the -// text and ordered. -func runeRange(value string, start, end int) text.Range { - length := units(value) - start, end = min(max(start, 0), length), min(max(end, 0), length) - if end < start { - start, end = end, start - } - return text.Range{Start: text.RuneIndexAtUTF16(value, start), End: text.RuneIndexAtUTF16(value, end)} -} - -// Commit puts value in place of the composing text, or of the selection when nothing is -// composing, and ends the composition: InputConnection.commitText and UIKeyInput's -// insertText. newCursor places the caret as commitText does: above zero, after the text -// counted from its end (1 is just after); zero or below, before it counted from its start. -func (session *Session) Commit(value string, newCursor int) error { - event := platform.TextEvent{Kind: platform.TextInsert, Text: value} - if session.State.Composing { - event.Replacement, event.HasReplacement = session.State.Composition, true - } - if err := session.apply(event); err != nil { - return err - } - if newCursor == 1 { - return nil - } - after := MirrorOf(session.State) - end := after.SelEnd - target := end + newCursor - 1 - if newCursor <= 0 { - target = end - units(value) + newCursor - } - target = min(max(target, 0), units(after.Text)) - if target == end { - return nil - } - return session.apply(platform.TextEvent{Kind: platform.TextSetSelection, Selection: runeRange(after.Text, target, target)}) -} - -// SetComposing replaces the composing text, or the selection when nothing is composing, -// with value, which stays composing: InputConnection.setComposingText. The caret is -// placed inside it as commitText's newCursor does. -func (session *Session) SetComposing(value string, newCursor int) error { - length := units(value) - caret := newCursor - if newCursor > 0 { - caret = length + newCursor - 1 - } - return session.SetMarked(value, caret, caret) -} - -// SetMarked replaces the composing text, or the selection, with value, composing, and -// selects [start, end) of it in UTF-16 units: UITextInput's setMarkedText. -func (session *Session) SetMarked(value string, start, end int) error { - event := platform.TextEvent{Kind: platform.TextSetMarked, Text: value, MarkedSelection: runeRange(value, start, end)} - if session.State.Composing { - event.Replacement, event.HasReplacement = session.State.Composition, true - } - return session.apply(event) -} - -// Finish ends the composition, keeping what is composed: finishComposingText and -// unmarkText. -func (session *Session) Finish() error { - if !session.State.Composing { - return nil - } - return session.apply(platform.TextEvent{Kind: platform.TextUnmark}) -} - -// DeleteSurrounding deletes before units before the selection and after units after it, -// counting UTF-16 units, or code points when codePoints says so. -func (session *Session) DeleteSurrounding(before, after int, codePoints bool) error { - mirror := MirrorOf(session.State) - start, end := mirror.SelStart, mirror.SelEnd - if start > end { - start, end = end, start - } - if codePoints { - runes := []rune(mirror.Text) - first := text.RuneIndexAtUTF16(mirror.Text, start) - last := text.RuneIndexAtUTF16(mirror.Text, end) - first = max(first-before, 0) - last = min(last+after, len(runes)) - return session.replace(text.Range{Start: first, End: last}, "") - } - return session.replace(runeRange(mirror.Text, start-before, end+after), "") -} - -// Replace puts value in place of the UTF-16 range [start, end): UITextInput's -// replaceRange, an autocorrection or a suggestion taken. -func (session *Session) Replace(start, end int, value string) error { - return session.replace(runeRange(session.State.Value, start, end), value) -} - -func (session *Session) replace(replacement text.Range, value string) error { - if replacement.Start == replacement.End && value == "" { - return nil - } - return session.apply(platform.TextEvent{Kind: platform.TextInsert, Text: value, Replacement: replacement, HasReplacement: true}) -} - -// Select selects [start, end) in UTF-16 units: setSelection and selectedTextRange. -func (session *Session) Select(start, end int) error { - return session.apply(platform.TextEvent{Kind: platform.TextSetSelection, Selection: runeRange(session.State.Value, start, end)}) -} - -// MarkRange makes text that is already there the composing text: setComposingRegion, -// which a keyboard uses to reopen a word it is about to correct. -func (session *Session) MarkRange(start, end int) error { - value := session.State.Value - rng := runeRange(value, start, end) - if rng.Start == rng.End { - return nil - } - marked := string([]rune(value)[rng.Start:rng.End]) - size := rng.End - rng.Start - return session.apply(platform.TextEvent{ - Kind: platform.TextSetMarked, Text: marked, MarkedSelection: text.Range{Start: size, End: size}, - Replacement: rng, HasReplacement: true, - }) -} - -// Command applies an editing command: deleteBackward of a hardware or software key. -func (session *Session) Command(command platform.TextCommand) error { - return session.apply(platform.TextEvent{Kind: platform.TextCommandEvent, Command: command}) -} - -// KeyEdit is what a key of a hardware keyboard does in a focused text input: type its -// character, or edit as the key says, which is how the desktops' native text services -// take the keys of a text field. A key it does not answer for, such as Enter in a field of -// one line, is for the application, and so are all the keys of a terminal. -func KeyEdit(key gfx.Key, modifiers input.Modifiers, character string, field *platform.TextInput) (KeyAction, bool) { - if field.Terminal { - return KeyAction{}, false - } - word := modifiers&(input.ModifierControl|input.ModifierAlt) != 0 - shift := modifiers&input.ModifierShift != 0 - choose := func(plain, selecting, byWord, selectingByWord platform.TextCommand) (KeyAction, bool) { - command := plain - switch { - case shift && word: - command = selectingByWord - case word: - command = byWord - case shift: - command = selecting - } - return KeyAction{Command: command}, command != 0 - } - switch key { - case gfx.KeyBackspace: - return choose(platform.TextDeleteBackward, platform.TextDeleteBackward, platform.TextDeleteWordBackward, platform.TextDeleteWordBackward) - case gfx.KeyDelete: - return choose(platform.TextDeleteForward, platform.TextDeleteForward, platform.TextDeleteWordForward, platform.TextDeleteWordForward) - case gfx.KeyLeft: - return choose(platform.TextMoveLeft, platform.TextMoveLeftAndModifySelection, platform.TextMoveWordLeft, platform.TextMoveWordLeftAndModifySelection) - case gfx.KeyRight: - return choose(platform.TextMoveRight, platform.TextMoveRightAndModifySelection, platform.TextMoveWordRight, platform.TextMoveWordRightAndModifySelection) - case gfx.KeyHome: - return choose(platform.TextMoveLineStart, platform.TextMoveLineStartAndModifySelection, platform.TextMoveLineStart, platform.TextMoveLineStartAndModifySelection) - case gfx.KeyEnd: - return choose(platform.TextMoveLineEnd, platform.TextMoveLineEndAndModifySelection, platform.TextMoveLineEnd, platform.TextMoveLineEndAndModifySelection) - case gfx.KeyEnter: - if field.Multiline { - return KeyAction{Command: platform.TextInsertNewline}, true - } - case gfx.KeySpace: - return KeyAction{Text: " "}, true - case gfx.KeyUnknown: - if character != "" { - return KeyAction{Text: character}, true - } - } - return KeyAction{}, false -} - -// KeyAction is what KeyEdit decided: a command to apply, or text to commit. -type KeyAction struct { - Command platform.TextCommand - Text string -} - -// Apply does the action to the session. -func (action KeyAction) Apply(session *Session) error { - if action.Command != 0 { - return session.Command(action.Command) - } - return session.Commit(action.Text, 1) -} diff --git a/internal/platform/imebridge/imebridge_test.go b/internal/platform/imebridge/imebridge_test.go deleted file mode 100644 index 5bf37cb75..000000000 --- a/internal/platform/imebridge/imebridge_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package imebridge - -import ( - "testing" - - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/input" - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/text" -) - -// newSession is an editor holding initial, with the caret at its end, behind a session. -func newSession(initial string) (*Session, *text.Editor) { - editor := text.NewEditor(initial) - editor.SetSelection(text.Range{Start: editor.RuneCount(), End: editor.RuneCount()}) - session := &Session{ - Handler: func(event platform.TextEvent) (platform.TextState, error) { - event.Apply(editor) - return platform.EditorState(editor), nil - }, - State: platform.EditorState(editor), - } - return session, editor -} - -func must(t *testing.T, err error) { - t.Helper() - if err != nil { - t.Fatal(err) - } -} - -func TestCommitTypesAtTheCaretAndLeavesItAfter(t *testing.T) { - session, editor := newSession("ab") - must(t, session.Commit("cd", 1)) - if editor.String() != "abcd" || editor.Caret() != 4 { - t.Fatalf("text %q caret %d", editor.String(), editor.Caret()) - } -} - -// A keyboard that commits with a cursor before the text, or past it, moves the caret -// as commitText says. -func TestCommitPlacesTheCaretByItsNewCursorPosition(t *testing.T) { - for _, test := range []struct{ newCursor, caret int }{{1, 7}, {0, 4}, {-1, 3}, {2, 7}, {-9, 0}, {9, 7}} { - session, editor := newSession("abcd") - must(t, session.Commit("xyz", test.newCursor)) - if editor.String() != "abcdxyz" || editor.Caret() != test.caret { - t.Errorf("newCursor %d: text %q caret %d, want caret %d", test.newCursor, editor.String(), editor.Caret(), test.caret) - } - } -} - -// Composing, as a pinyin keyboard does: the letters are marked, replaced by the -// candidate, and committed over the composition, which ends it. -func TestAComposedWordIsMarkedReplacedAndCommitted(t *testing.T) { - session, editor := newSession("") - must(t, session.SetComposing("ni", 1)) - if composition, composing := editor.Composition(); !composing || editor.String() != "ni" || composition != (text.Range{Start: 0, End: 2}) { - t.Fatalf("after the first letters: %q composing=%v %v", editor.String(), composing, composition) - } - must(t, session.SetComposing("你", 1)) - if composition, composing := editor.Composition(); !composing || editor.String() != "你" || composition != (text.Range{Start: 0, End: 1}) { - t.Fatalf("after the candidate: %q composing=%v %v", editor.String(), composing, composition) - } - must(t, session.Commit("你好", 1)) - if _, composing := editor.Composition(); composing || editor.String() != "你好" || editor.Caret() != 2 { - t.Fatalf("after the commit: %q composing=%v caret %d", editor.String(), composing, editor.Caret()) - } -} - -func TestFinishKeepsWhatIsComposed(t *testing.T) { - session, editor := newSession("a") - must(t, session.SetComposing("bc", 1)) - must(t, session.Finish()) - if _, composing := editor.Composition(); composing || editor.String() != "abc" { - t.Fatalf("text %q composing=%v", editor.String(), composing) - } - must(t, session.Finish()) // nothing composing: nothing happens -} - -// Ranges count UTF-16 units, so an emoji is two, and a range may not end in the middle -// of a character. -func TestRangesCountUTF16UnitsOverSurrogatePairs(t *testing.T) { - session, editor := newSession("a😀b") - mirror := session.Mirror() - if mirror.Text != "a😀b" || mirror.SelStart != 4 || mirror.SelEnd != 4 { - t.Fatalf("mirror %+v", mirror) - } - must(t, session.Select(1, 3)) // the emoji - if selection := editor.Selection(); selection != (text.Range{Start: 1, End: 2}) { - t.Fatalf("selection %v", selection) - } - must(t, session.Replace(1, 3, "x")) - if editor.String() != "axb" { - t.Fatalf("text %q", editor.String()) - } -} - -func TestDeleteSurroundingCountsUnitsOrCodePoints(t *testing.T) { - session, editor := newSession("a😀b") - must(t, session.Select(3, 3)) - must(t, session.DeleteSurrounding(2, 0, false)) // the emoji is two units - if editor.String() != "ab" { - t.Fatalf("by units: %q", editor.String()) - } - session, editor = newSession("a😀b") - must(t, session.Select(3, 3)) - must(t, session.DeleteSurrounding(1, 1, true)) // one code point either side - if editor.String() != "a" { - t.Fatalf("by code points: %q", editor.String()) - } - must(t, session.DeleteSurrounding(0, 0, false)) // nothing to delete -} - -func TestMarkRangeReopensAWordForCorrection(t *testing.T) { - session, editor := newSession("hello wrld") - must(t, session.MarkRange(6, 10)) - composition, composing := editor.Composition() - if !composing || composition != (text.Range{Start: 6, End: 10}) { - t.Fatalf("composition %v %v", composition, composing) - } - must(t, session.SetComposing("world", 1)) - must(t, session.Commit("world", 1)) - if editor.String() != "hello world" { - t.Fatalf("text %q", editor.String()) - } -} - -func TestSetMarkedSelectsInsideTheMarkedText(t *testing.T) { - session, editor := newSession("") - must(t, session.SetMarked("abc", 1, 1)) - if editor.Caret() != 1 { - t.Fatalf("caret %d, want it inside the marked text", editor.Caret()) - } -} - -func TestMirrorOfAComposingEditorNamesItsComposition(t *testing.T) { - session, _ := newSession("") - must(t, session.SetComposing("😀a", 1)) - mirror := session.Mirror() - if !mirror.Composing || mirror.CompStart != 0 || mirror.CompEnd != 3 { - t.Fatalf("mirror %+v", mirror) - } - must(t, session.Finish()) - if mirror := session.Mirror(); mirror.Composing || mirror.CompStart != -1 || mirror.CompEnd != -1 { - t.Fatalf("mirror %+v after finishing", mirror) - } -} - -func keyInto(t *testing.T, session *Session, key gfx.Key, modifiers input.Modifiers, character string, field *platform.TextInput) bool { - t.Helper() - action, ok := KeyEdit(key, modifiers, character, field) - if !ok { - return false - } - must(t, action.Apply(session)) - return true -} - -// A hardware keyboard types into a field and edits it as a desktop's does: characters and -// the space are typed, Backspace deletes, the arrows move, and a word's worth with Control. -func TestKeysTypeAndEditAFocusedField(t *testing.T) { - session, editor := newSession("") - field := &platform.TextInput{} - for _, step := range []struct { - key gfx.Key - modifiers input.Modifiers - character string - }{ - {gfx.KeyUnknown, 0, "h"}, {gfx.KeyUnknown, 0, "i"}, {gfx.KeySpace, 0, " "}, {gfx.KeyUnknown, 0, "x"}, {gfx.KeyBackspace, 0, ""}, - } { - if !keyInto(t, session, step.key, step.modifiers, step.character, field) { - t.Fatalf("key %v was not taken", step.key) - } - } - if editor.String() != "hi " { - t.Fatalf("text %q", editor.String()) - } - keyInto(t, session, gfx.KeyLeft, 0, "", field) - if editor.Caret() != 2 { - t.Fatalf("caret %d after Left", editor.Caret()) - } - keyInto(t, session, gfx.KeyLeft, input.ModifierShift, "", field) - if selection := editor.Selection(); selection.End-selection.Start != 1 { - t.Fatalf("selection %v after Shift+Left", selection) - } - keyInto(t, session, gfx.KeyBackspace, input.ModifierControl, "", field) - if editor.String() != "h " { - t.Fatalf("text %q after deleting the selection", editor.String()) - } -} - -// Enter is a newline in a field of several lines and the application's in one of a line; -// a terminal's keys are all the application's. -func TestEnterAndTerminalKeysBelongToTheApplicationWhereTheyShould(t *testing.T) { - if _, ok := KeyEdit(gfx.KeyEnter, 0, "", &platform.TextInput{}); ok { - t.Error("Enter in a one-line field was taken") - } - if action, ok := KeyEdit(gfx.KeyEnter, 0, "", &platform.TextInput{Multiline: true}); !ok || action.Command != platform.TextInsertNewline { - t.Errorf("Enter in a multiline field: %+v %v", action, ok) - } - for _, key := range []gfx.Key{gfx.KeyBackspace, gfx.KeyLeft, gfx.KeySpace, gfx.KeyUnknown} { - if _, ok := KeyEdit(key, 0, "x", &platform.TextInput{Terminal: true}); ok { - t.Errorf("key %v of a terminal was taken", key) - } - } - if _, ok := KeyEdit(gfx.KeyUp, 0, "", &platform.TextInput{}); ok { - t.Error("Up was taken: moving between rows is the application's") - } -} diff --git a/internal/platform/linux/api_linux_test.go b/internal/platform/linux/api_linux_test.go index 46e938bed..f72e90ecb 100644 --- a/internal/platform/linux/api_linux_test.go +++ b/internal/platform/linux/api_linux_test.go @@ -201,6 +201,12 @@ func TestNextEventCoalescesConfigureNotifyAndInterleavedSyncAndExpose(t *testing } win.api.free(first) + exposure := state.nextEvent() + if exposure == nil || (*xcbGenericEvent)(exposure).ResponseType&0x7f != xcbExpose { + t.Fatal("configure coalescing lost the server's exposure request") + } + win.api.free(exposure) + second := state.nextEvent() if second == nil { t.Fatal("second nextEvent returned nil, want held Sync(202)") diff --git a/internal/platform/linux/atspi_bridge.go b/internal/platform/linux/atspi_bridge.go index 7024fd5a2..eaa09f090 100644 --- a/internal/platform/linux/atspi_bridge.go +++ b/internal/platform/linux/atspi_bridge.go @@ -367,6 +367,9 @@ func (bridge *atspiBridge) update(window *atspiWindow, nodes []platform.Accessib events++ bridge.emit(bridge.parentPath(window, index), atspiEventObject, "ChildrenChanged", "add", int32(window.indexInParent(index)), 0, bridge.ref(path)) } + if node.Focused { + bridge.emit(path, atspiEventObject, "StateChanged", "focused", 1, 0, nil) + } continue } bridge.announceChanges(window, path, old[previous], node) diff --git a/internal/platform/linux/atspi_bridge_test.go b/internal/platform/linux/atspi_bridge_test.go index d76063054..98d3beafb 100644 --- a/internal/platform/linux/atspi_bridge_test.go +++ b/internal/platform/linux/atspi_bridge_test.go @@ -326,6 +326,40 @@ func TestAtspiEventsNameWhatChanged(t *testing.T) { } } +func TestAtspiAnnouncesFocusWhenAddingAControl(t *testing.T) { + nodes := demoNodes() + nodes[4].Focused = true + test := newTestBridge(nodes) + test.signals = nil + changed := demoNodes() + changed = append(changed, + platform.AccessibilityNode{ID: gfx.Item(7), Role: platform.A11yRoleButton, Label: "Close", Focusable: true}, + platform.AccessibilityNode{ID: gfx.Item(8), Role: platform.A11yRoleTextField, Label: "Find", Focusable: true, Focused: true}, + ) + test.update(test.window, changed) + var events []string + for _, signal := range test.signals { + switch { + case signal.member == "ChildrenChanged" && signal.detail == "add" && signal.detail1 == int32(test.window.indexInParent(7)): + events = append(events, "find added") + case signal.member == "StateChanged" && signal.detail == "focused" && signal.detail1 == 1: + if signal.path != test.path(7) { + t.Fatalf("unexpected focus recipient: %+v", signal) + } + events = append(events, "find focused") + } + } + if got := strings.Join(events, ", "); got != "find added, find focused" { + t.Fatalf("new control events = %q, want add then focus", got) + } + + test.signals = nil + test.update(test.window, changed) + if len(test.signals) != 0 { + t.Fatalf("unchanged focused tree announced %v", test.signals) + } +} + func TestAtspiLiveRegionAnnounces(t *testing.T) { test := newTestBridge([]platform.AccessibilityNode{{Role: platform.A11yRoleStatus, Label: "Saved", X: 0, Y: 0, Width: 10, Height: 10, Live: gfx.LivePolite}}) test.signals = nil diff --git a/internal/platform/linux/clipboard_image_linux_test.go b/internal/platform/linux/clipboard_image_linux_test.go index d45939b50..b7b308e2d 100644 --- a/internal/platform/linux/clipboard_image_linux_test.go +++ b/internal/platform/linux/clipboard_image_linux_test.go @@ -13,6 +13,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "testing" "time" @@ -69,6 +70,19 @@ func TestClipboardImageFromX11Owner(t *testing.T) { } own("-t", "image/png", "-i", imagePath) + if value, err := ClipboardText(); err != nil || value != "" { + t.Fatalf("image-only copy returned %d text bytes: %v", len(value), err) + } + editor := text.NewEditor("draft") + editor.SetSelection(text.Range{Start: 0, End: 5}) + event, changed, err := platform.TextClipboardEvent(platform.EditorState(editor), false, 'v', ClipboardText, nil) + if err != nil || !changed || event.Kind != platform.TextPasteNoText { + t.Fatalf("image paste = %+v, changed=%v, error=%v", event, changed, err) + } + event.Apply(editor) + if editor.String() != "draft" || editor.CanUndo() { + t.Fatal("image paste changed the draft or undo history") + } if has, err := clipboardOffersImage(); !has { t.Fatalf("clipboard offers no image with a PNG on it (error: %v)", err) } @@ -85,12 +99,70 @@ func TestClipboardImageFromX11Owner(t *testing.T) { t.Fatal(err) } own("-i", textPath) + if value, err := ClipboardText(); err != nil || value != "plain text" { + t.Fatalf("text after image = %q, %v", value, err) + } if HasClipboardImage() { t.Fatal("HasClipboardImage = true with text on the clipboard") } if _, err := ClipboardImagePNG(); !errors.Is(err, platform.ErrNoClipboardImage) { t.Fatalf("error = %v, want ErrNoClipboardImage", err) } + if err := os.WriteFile(textPath, []byte("caf\xe9"), 0o600); err != nil { + t.Fatal(err) + } + own("-t", "STRING", "-i", textPath) + if value, err := ClipboardText(); err != nil || value != "café" { + t.Fatalf("legacy Latin-1 = %q, %v", value, err) + } +} + +// A background copy can replace our clipboard before the window loop handles +// SelectionClear. Reads must follow the server's owner, not the stale cache. +func TestClipboardImageAfterExternalOwnerReplacesCachedText(t *testing.T) { + win := liveSelectionWindow(t) + if err := SetClipboardText("old draft"); err != nil { + t.Fatal(err) + } + picture := picturePNG(t) + command := exec.Command("xclip", "-selection", "clipboard", "-t", "image/png", "-i") + command.Stdin = bytes.NewReader(picture) + if err := command.Run(); err != nil { + t.Fatal(err) + } + // Do not pump the window's pending SelectionClear event. + if owner, err := selectionOwner(win.api, win.connection, win.clipboardAtom); err != nil || owner == win.id { + t.Fatalf("external owner did not claim the clipboard: %d, %v", owner, err) + } + got, err := ClipboardImagePNG() + if err != nil || !bytes.Equal(got, picture) { + t.Fatalf("external picture after cached text: %d bytes, %v", len(got), err) + } + if value, err := ClipboardText(); err != nil || value != "" { + t.Fatalf("stale text after external picture: %q, %v", value, err) + } +} + +func BenchmarkClipboardTextFromX11Owner(b *testing.B) { + if os.Getenv("VIVA_LINUX_XCB_SMOKE") == "" { + b.Skip("set VIVA_LINUX_XCB_SMOKE=1 with a private X11 display and xclip") + } + value := strings.Repeat("clipboard 文本 ", 10) + command := exec.Command("xclip", "-selection", "clipboard", "-i") + command.Stdin = strings.NewReader(value) + if err := command.Run(); err != nil { + b.Fatal(err) + } + if got, err := ClipboardText(); err != nil || got != value { + b.Fatalf("clipboard not ready: %q, %v", got, err) + } + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if got, err := ClipboardText(); err != nil || got != value { + b.Fatalf("clipboard text: %q, %v", got, err) + } + } } // TestClipboardImageStreamedWithINCR reads a large image from a GTK owner. GTK diff --git a/internal/platform/linux/clipboard_watch_live_linux_test.go b/internal/platform/linux/clipboard_watch_live_linux_test.go new file mode 100644 index 000000000..0a9e838a6 --- /dev/null +++ b/internal/platform/linux/clipboard_watch_live_linux_test.go @@ -0,0 +1,120 @@ +//go:build linux && !vivagtk + +package linux + +import ( + "errors" + "os" + "testing" + "time" +) + +func TestX11ClipboardChangeWithoutExtension(t *testing.T) { + if os.Getenv("VIVA_LINUX_XCB_NO_XFIXES") != "1" { + t.Skip("requires a private X server started with -extension XFIXES") + } + api, conn, _, err := openSystemConnection() + if err != nil { + t.Fatal(err) + } + api.disconnect(conn) + defer OnClipboardChange(nil) + if err := OnClipboardChange(func() {}); !errors.Is(err, ErrUnsupported) { + t.Fatalf("clipboard watch without XFixes = %v, want ErrUnsupported", err) + } +} + +func TestX11ClipboardChangeLifecycle(t *testing.T) { + if testing.Short() || os.Getenv("VIVA_LINUX_XCB_SMOKE") != "1" { + t.Skip("set VIVA_LINUX_XCB_SMOKE=1 with a private X11 display and XFixes") + } + first, second := make(chan struct{}, 8), make(chan struct{}, 8) + register := func(events chan struct{}) { + t.Helper() + if err := OnClipboardChange(func() { events <- struct{}{} }); err != nil { + t.Fatal(err) + } + } + wait := func(events chan struct{}) { + t.Helper() + select { + case <-events: + case <-time.After(2 * time.Second): + t.Fatal("clipboard notification did not arrive") + } + } + quiet := func(events chan struct{}) { + t.Helper() + select { + case <-events: + t.Fatal("unexpected clipboard notification") + case <-time.After(40 * time.Millisecond): + } + } + t.Cleanup(func() { + if err := OnClipboardChange(nil); err != nil { + t.Error(err) + } + }) + register(first) // Registration does not require an application window. + quiet(first) + + api, conn, screen, err := openSystemConnection() + if err != nil { + t.Fatal(err) + } + defer func() { + if conn != 0 { + api.disconnect(conn) + } + }() + owner := api.generateID(conn) + api.createWindow(conn, xcbCopyFromParent, owner, screen.Root, 0, 0, 1, 1, 0, xcbWindowClassInput, 0, 0, nil) + clipboard, err := api.atom(conn, "CLIPBOARD") + if err != nil { + t.Fatal(err) + } + primary, err := api.atom(conn, "PRIMARY") + if err != nil { + t.Fatal(err) + } + claim := func(selection uint32) { + t.Helper() + api.setSelectionOwner(conn, owner, selection, 0) + if got, err := selectionOwner(api, conn, selection); err != nil || got != owner { + t.Fatalf("selection owner = %d, %v; want %d", got, err, owner) + } + } + claim(primary) + quiet(first) + claim(clipboard) + claim(clipboard) + wait(first) + wait(first) + quiet(first) + + register(second) + claim(clipboard) + wait(second) + quiet(first) + if err := OnClipboardChange(nil); err != nil { + t.Fatal(err) + } + claim(clipboard) + quiet(second) + + stopped := make(chan error, 1) + if err := OnClipboardChange(func() { stopped <- OnClipboardChange(nil) }); err != nil { + t.Fatal(err) + } + api.disconnect(conn) + conn = 0 + select { + case err := <-stopped: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("owner exit notification did not arrive or could not unregister") + } +} diff --git a/internal/platform/linux/clipboard_watch_xcb_linux.go b/internal/platform/linux/clipboard_watch_xcb_linux.go new file mode 100644 index 000000000..8bd9144a6 --- /dev/null +++ b/internal/platform/linux/clipboard_watch_xcb_linux.go @@ -0,0 +1,187 @@ +//go:build linux && !vivagtk + +package linux + +import ( + "errors" + "fmt" + "sync" + "unsafe" + + "github.com/ebitengine/purego" + "golang.org/x/sys/unix" +) + +var clipboardWatch struct { + sync.Mutex + current *x11ClipboardWatch +} + +type x11ClipboardWatch struct { + api *xcbAPI + connection, library uintptr + root, clipboard uint32 + event uint8 + wake [2]int + notify func() // guarded by clipboardWatch +} + +type xfixesVersionReply struct { + Header [8]byte + Major uint32 +} + +// OnClipboardChange watches CLIPBOARD on a separate connection so selection +// reads and the window loop cannot consume these events. The callback must only +// hand the notification on, as on the other backends. +func OnClipboardChange(notify func()) error { + if notify == nil { + stopClipboardWatch() + return nil + } + clipboardWatch.Lock() + defer clipboardWatch.Unlock() + if current := clipboardWatch.current; current != nil { + current.notify = notify + return nil + } + watch, err := newX11ClipboardWatch(notify) + if err != nil { + return err + } + clipboardWatch.current = watch + go watch.run() + return nil +} + +func stopClipboardWatch() { + clipboardWatch.Lock() + defer clipboardWatch.Unlock() + if current := clipboardWatch.current; current != nil { + clipboardWatch.current = nil + // EOF wakes the worker even when the server has no events. The + // worker closes the X connection and the read end of the pipe. + _ = unix.Close(current.wake[1]) + } +} + +func newX11ClipboardWatch(notify func()) (*x11ClipboardWatch, error) { + api, conn, screen, err := openSystemConnection() + if err != nil { + return nil, unsupported("clipboard change events need a usable X11 display") + } + w := &x11ClipboardWatch{api: api, connection: conn, root: screen.Root, notify: notify} + if err := w.subscribe(); err != nil { + w.closeX11() + return nil, err + } + if err := unix.Pipe2(w.wake[:], unix.O_CLOEXEC); err != nil { + w.closeX11() + return nil, fmt.Errorf("linux: create clipboard watch wake pipe: %w", err) + } + return w, nil +} + +func (w *x11ClipboardWatch) subscribe() error { + library, err := purego.Dlopen("libxcb-xfixes.so.0", purego.RTLD_NOW|purego.RTLD_LOCAL) + if err != nil { + return unsupported("clipboard change events need libxcb-xfixes") + } + w.library = library + identity, err := purego.Dlsym(library, "xcb_xfixes_id") + if err != nil { + return unsupported("clipboard change events need XFixes") + } + var extensionData func(uintptr, uintptr) *xcbExtensionReply + purego.RegisterLibFunc(&extensionData, w.api.library, "xcb_get_extension_data") + extension := extensionData(w.connection, identity) + if extension == nil || extension.Present == 0 { + return unsupported("the X server does not provide XFixes") + } + w.event = extension.FirstEvent // XFixesSelectionNotify is extension event 0. + var queryVersion func(uintptr, uint32, uint32) xcbVoidCookie + var versionReply func(uintptr, xcbVoidCookie, *unsafe.Pointer) *xfixesVersionReply + purego.RegisterLibFunc(&queryVersion, library, "xcb_xfixes_query_version") + purego.RegisterLibFunc(&versionReply, library, "xcb_xfixes_query_version_reply") + var nativeError unsafe.Pointer + version := versionReply(w.connection, queryVersion(w.connection, 2, 0), &nativeError) + if nativeError != nil { + w.api.free(nativeError) + } + if version == nil { + return unsupported("clipboard change events could not negotiate XFixes") + } + major := version.Major + w.api.free(unsafe.Pointer(version)) + if major < 2 { + return unsupported("clipboard change events need XFixes 2.0") + } + if w.clipboard, err = w.api.atom(w.connection, "CLIPBOARD"); err != nil { + return err + } + var selectInput func(uintptr, uint32, uint32, uint32) xcbVoidCookie + purego.RegisterLibFunc(&selectInput, library, "xcb_xfixes_select_selection_input_checked") + const setOwner, windowDestroy, clientClose = 1, 2, 4 + if failure := w.api.requestCheck(w.connection, selectInput(w.connection, w.root, w.clipboard, setOwner|windowDestroy|clientClose)); failure != nil { + code := failure.ErrorCode + w.api.free(unsafe.Pointer(failure)) + return fmt.Errorf("linux: subscribe to clipboard change events: X11 error %d", code) + } + return nil +} + +func (w *x11ClipboardWatch) closeX11() { + w.api.disconnect(w.connection) + if w.library != 0 { + _ = purego.Dlclose(w.library) + } +} + +func (w *x11ClipboardWatch) callback() func() { + clipboardWatch.Lock() + defer clipboardWatch.Unlock() + if clipboardWatch.current != w { + return nil + } + return w.notify +} + +func (w *x11ClipboardWatch) run() { + defer func() { + clipboardWatch.Lock() + if clipboardWatch.current == w { + clipboardWatch.current = nil + _ = unix.Close(w.wake[1]) + } + clipboardWatch.Unlock() + _ = unix.Close(w.wake[0]) + w.closeX11() + }() + fds := []unix.PollFd{{Fd: w.api.fileDescriptor(w.connection), Events: unix.POLLIN}, {Fd: int32(w.wake[0]), Events: unix.POLLIN}} + for w.callback() != nil { + for raw := w.api.pollForEvent(w.connection); raw != nil; raw = w.api.pollForEvent(w.connection) { + event := (*xcbGenericEvent)(raw) + // XFixes selection event: window, owner, selection. Ignore events + // marked SendEvent and every other selection or extension event. + changed := event.ResponseType == w.event && event.Data[0] == w.root && event.Data[2] == w.clipboard + w.api.free(raw) + callback := w.callback() + if callback == nil { + return + } + if changed { + callback() + } + } + if w.api.connectionHasError(w.connection) != 0 { + return + } + _, err := unix.Poll(fds, -1) + if errors.Is(err, unix.EINTR) { + continue + } + if err != nil || fds[1].Revents != 0 || fds[0].Revents&(unix.POLLERR|unix.POLLHUP|unix.POLLNVAL) != 0 { + return + } + } +} diff --git a/internal/platform/linux/display_scale.go b/internal/platform/linux/display_scale.go index 0700ff52f..14af05d89 100644 --- a/internal/platform/linux/display_scale.go +++ b/internal/platform/linux/display_scale.go @@ -200,6 +200,26 @@ func monitorAt(monitors []monitorGeometry, x, y int) (monitorGeometry, bool) { return fallback, have } +// notificationMonitorAt picks the nearest screen when an old position is +// outside all current monitors. +func notificationMonitorAt(monitors []monitorGeometry, x, y int) (monitorGeometry, bool) { + var closest monitorGeometry + var closestDistance int64 + found := false + for _, monitor := range monitors { + if monitor.Width <= 0 || monitor.Height <= 0 { + continue + } + dx := int64(x - min(max(x, monitor.X), monitor.X+monitor.Width-1)) + dy := int64(y - min(max(y, monitor.Y), monitor.Y+monitor.Height-1)) + distance := dx*dx + dy*dy + if !found || distance < closestDistance || (distance == closestDistance && monitor.Primary) { + closest, closestDistance, found = monitor, distance, true + } + } + return closest, found +} + // xsettings holds the settings of the XSETTINGS manager that a scale is derived // from. type xsettings struct { diff --git a/internal/platform/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go index fa9d7f713..ce1d68313 100644 --- a/internal/platform/linux/gtk_app_linux.go +++ b/internal/platform/linux/gtk_app_linux.go @@ -61,6 +61,7 @@ type gtkApplication struct { clipboardGet, clipboardClear uintptr clipboardBytes map[uintptr][]byte clipboardGeneration uintptr + clipboardWatch gtkClipboardWatch } // gtkTasks are the functions other goroutines asked the loop to run. @@ -111,6 +112,7 @@ func RunGTKApplication(start platform.ApplicationStart) error { application.mainThread = syscall.Gettid() application.installHooks() defer application.removeHooks() + defer application.clipboardWatch.stop(g) // Whoever starts to watch the desktop's settings, from any goroutine, wakes the loop to open the // connection that hears them. platform.SetWatchHook(func() { diff --git a/internal/platform/linux/gtk_clipboard_watch_linux.go b/internal/platform/linux/gtk_clipboard_watch_linux.go new file mode 100644 index 000000000..a048c14cd --- /dev/null +++ b/internal/platform/linux/gtk_clipboard_watch_linux.go @@ -0,0 +1,88 @@ +//go:build linux && vivagtk + +package linux + +import ( + "sync" + + "github.com/ebitengine/purego" +) + +type gtkClipboardWatch struct { + object uintptr + signal uint64 + notify func() +} + +var gtkClipboardWatchCallback = sync.OnceValue(func() uintptr { + return purego.NewCallback(func(object, _ uintptr, _ uintptr) { + if a := gtkRunning.Load(); a != nil && a.clipboardWatch.object == object { + if notify := a.clipboardWatch.notify; notify != nil { + notify() + } + } + }) +}) + +func OnClipboardChange(notify func()) error { + a := gtkRunning.Load() + if a == nil { + if notify == nil { + return nil + } + return unsupported("clipboard change events need an initialized GTK display") + } + var err error + if e := a.onMain(func() { err = a.setClipboardWatch(notify) }); e != nil { + return e + } + return err +} + +func (a *gtkApplication) setClipboardWatch(notify func()) error { + w := &a.clipboardWatch + if notify == nil { + w.stop(a.g) + return nil + } + if !a.started || a.stopping { + return unsupported("clipboard change events need an initialized GTK display") + } + if a.wayland { + // GTK's Wayland selection offers are focus-scoped; owner-change + // cannot report copies that happen while another client is focused. + return unsupported("clipboard change events are not available on GTK Wayland") + } + if w.signal != 0 { + w.notify = notify + return nil + } + var supportsSelectionNotification func(uintptr) int32 + if !a.g.lookup(&supportsSelectionNotification, "gdk_display_supports_selection_notification") || + supportsSelectionNotification(a.g.gdkDisplayDefault()) == 0 { + return unsupported("the GTK display does not support clipboard change notifications") + } + clipboard, err := a.clipboardAPI() + if err != nil { + return err + } + if clipboard.clipboard == 0 { + return unsupported("the GTK display does not have a clipboard") + } + signal := a.g.connect(clipboard.clipboard, "owner-change", gtkClipboardWatchCallback(), 0) + if signal == 0 { + return unsupported("could not register the GTK clipboard owner-change signal") + } + *w = gtkClipboardWatch{object: clipboard.clipboard, signal: signal, notify: notify} + return nil +} + +func (w *gtkClipboardWatch) stop(g *gtkLibrary) { + if w.signal != 0 { + g.signalDisc(w.object, w.signal) + } + *w = gtkClipboardWatch{} +} + +// The direct XCB application has no watch to stop in a GTK build. +func stopClipboardWatch() {} diff --git a/internal/platform/linux/gtk_clipboard_watch_native_linux_test.go b/internal/platform/linux/gtk_clipboard_watch_native_linux_test.go new file mode 100644 index 000000000..34429f0ee --- /dev/null +++ b/internal/platform/linux/gtk_clipboard_watch_native_linux_test.go @@ -0,0 +1,118 @@ +//go:build linux && vivagtk + +package linux + +import ( + "errors" + "fmt" + "os" + "testing" + "time" + + "github.com/vivaui/viva/internal/platform" +) + +func TestGTKClipboardChangeNative(t *testing.T) { + backend := os.Getenv("VIVA_TEST_GTK_CLIPBOARD_WATCH") + if backend != "x11" && backend != "wayland" { + t.Skip("requires a private GTK display") + } + first, second := make(chan struct{}, 8), make(chan struct{}, 8) + result := make(chan error, 1) + err := RunGTKApplication(func(app platform.Application) error { + if _, err := app.OpenWindow(platform.Config{Title: "Clipboard watch test", Width: 160, Height: 100}); err != nil { + return err + } + if gtkRunning.Load().wayland != (backend == "wayland") { + return fmt.Errorf("GTK did not select the %s display", backend) + } + err := OnClipboardChange(func() { first <- struct{}{} }) + if backend == "wayland" { + if !errors.Is(err, ErrUnsupported) { + return fmt.Errorf("Wayland registration = %v, want ErrUnsupported", err) + } + app.Quit() + return nil + } + if err != nil { + return err + } + go func() { + result <- exerciseGTKClipboardChange(first, second) + app.Quit() + }() + return nil + }) + if err != nil { + t.Fatal(err) + } + if backend == "x11" { + if err := <-result; err != nil { + t.Fatal(err) + } + } +} + +func exerciseGTKClipboardChange(first, second chan struct{}) error { + wait := func(ch chan struct{}) error { + select { + case <-ch: + return nil + case <-time.After(2 * time.Second): + return errors.New("clipboard notification did not arrive") + } + } + quiet := func(ch chan struct{}) error { + select { + case <-ch: + return errors.New("unexpected clipboard notification") + case <-time.After(40 * time.Millisecond): + return nil + } + } + api, conn, screen, err := openSystemConnection() + if err != nil { + return err + } + defer func() { + if conn != 0 { + api.disconnect(conn) + } + }() + owner := api.generateID(conn) + api.createWindow(conn, xcbCopyFromParent, owner, screen.Root, 0, 0, 1, 1, 0, xcbWindowClassInput, 0, 0, nil) + claim := func(name string) error { + atom, err := api.atom(conn, name) + if err != nil { + return err + } + api.setSelectionOwner(conn, owner, atom, 0) + if got, err := selectionOwner(api, conn, atom); err != nil || got != owner { + return fmt.Errorf("selection owner = %d, %v; want %d", got, err, owner) + } + return nil + } + for _, step := range []func() error{ + func() error { return claim("PRIMARY") }, + func() error { return quiet(first) }, + func() error { return claim("CLIPBOARD") }, + func() error { return wait(first) }, + func() error { return claim("CLIPBOARD") }, + func() error { return wait(first) }, + func() error { return OnClipboardChange(func() { second <- struct{}{} }) }, + func() error { return claim("CLIPBOARD") }, + func() error { return wait(second) }, + func() error { return quiet(first) }, + func() error { return OnClipboardChange(nil) }, + func() error { return claim("CLIPBOARD") }, + func() error { return quiet(second) }, + func() error { return OnClipboardChange(func() { second <- struct{}{} }) }, + } { + if err := step(); err != nil { + return err + } + } + api.disconnect(conn) + conn = 0 + return wait(second) +} diff --git a/internal/platform/linux/gtk_input_linux.go b/internal/platform/linux/gtk_input_linux.go index 193c87a80..1ca769e58 100644 --- a/internal/platform/linux/gtk_input_linux.go +++ b/internal/platform/linux/gtk_input_linux.go @@ -302,14 +302,15 @@ func (w *gtkWindow) frameDrag(e *gdkEventButton, x, y float32) bool { if w.fullscreen.Load() { return false } - if w.config.WindowMode != platform.WindowCustomTitlebar { + notification := w.config.WindowMode == platform.WindowNotification + if w.config.WindowMode != platform.WindowCustomTitlebar && !notification { return false } press := platform.PressClient if w.config.PressAt != nil { press = w.config.PressAt(x, y) } - if !w.maximized { + if !notification && !w.maximized { // The top edge yields to a control, so the buttons work up to the top. if edge := platform.EdgeAt(x, y, w.width, w.height, press == platform.PressControl); edge != platform.EdgeNone { w.g.windowBeginResize(w.toplevel, gdkEdge(edge), 1, int32(e.XRoot), int32(e.YRoot), e.Time) @@ -325,7 +326,7 @@ func (w *gtkWindow) frameDrag(e *gdkEventButton, x, y float32) bool { return false } w.pointer.clicks.Press(time.Duration(e.Time)*time.Millisecond, uint8(e.Button), x, y) - if w.pointer.clicks.Current() == 2 { + if !notification && w.pointer.clicks.Current() == 2 { w.actionToggleMaximize() return true } diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index 10a8d69fc..99c5ac2a3 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -155,7 +155,11 @@ func (a *gtkApplication) OpenWindow(config platform.Config) (platform.Window, er var rect [4]int32 g.gdkMonitorWorkarea(monitor, &rect) area := platform.ScreenRect{X: float32(rect[0]), Y: float32(rect[1]), Width: float32(rect[2]), Height: float32(rect[3])} - x, y := platform.PlaceNotification(float32(config.Width)*w.ratio, float32(config.Height)*w.ratio, 12*w.ratio, area) + width, height := float32(config.Width)*w.ratio, float32(config.Height)*w.ratio + x, y := platform.PlaceNotification(width, height, 12*w.ratio, area) + if config.HasOrigin { + x, y = platform.RestoreNotification(config.Origin.X*w.ratio, config.Origin.Y*w.ratio, width, height, area) + } g.windowMove(w.toplevel, int32(x), int32(y)) } case platform.WindowPanel: @@ -276,6 +280,12 @@ func (w *gtkWindow) notificationMonitor(display uintptr) uintptr { return 0 } g := w.g + if w.config.HasOrigin { + at := w.config.Origin + if monitor := g.gdkMonitorAtPoint(display, int32(at.X*w.ratio), int32(at.Y*w.ratio)); monitor != 0 { + return monitor + } + } if seat := g.gdkDisplaySeat(display); seat != 0 { if pointer := g.gdkSeatPointer(seat); pointer != 0 { var x, y int32 diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 34f46c295..c750b27a7 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -92,7 +92,12 @@ func (win *window) panelOrigin(config platform.Config) (x, y int16) { } else if pointerX, pointerY, ok := win.pointerPosition(); ok { focusX, focusY = pointerX, pointerY } - if monitor, ok := monitorAt(monitors, focusX, focusY); ok && monitor.Width > 0 && monitor.Height > 0 { + monitor, ok := monitorAt(monitors, focusX, focusY) + if config.WindowMode == platform.WindowNotification && config.HasOrigin { + scale := win.displayScale() + monitor, ok = notificationMonitorAt(monitors, int(config.Origin.X*scale), int(config.Origin.Y*scale)) + } + if ok && monitor.Width > 0 && monitor.Height > 0 { work, haveWork := win.workArea() usable := usableArea(monitorRect(monitor), work, haveWork) area = platform.ScreenRect{X: float32(usable.x), Y: float32(usable.y), Width: float32(usable.width), Height: float32(usable.height)} @@ -100,6 +105,10 @@ func (win *window) panelOrigin(config platform.Config) (x, y int16) { var fx, fy float32 if config.WindowMode == platform.WindowNotification { fx, fy = platform.PlaceNotification(width, height, 12*win.displayScale(), area) + if config.HasOrigin { + scale := win.displayScale() + fx, fy = platform.RestoreNotification(config.Origin.X*scale, config.Origin.Y*scale, width, height, area) + } } else if config.HasAnchor { fx, fy = platform.PlacePanel(config.Anchor, width, height, area) } else { diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index e4795ca9e..3d608b441 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -54,7 +54,7 @@ func ClipboardText() (string, error) { } if win := activeWindow.Load(); win != nil { win.mu.Lock() - if activeWindow.Load() == win && win.connection != 0 && win.ownsClipboard { + if activeWindow.Load() == win && win.clipboardOwnedLocked() { value := win.clipboard win.mu.Unlock() return value, nil @@ -81,18 +81,66 @@ func readSelectionTextX11(name string) (string, error) { if err != nil { return "", err } - utf8, err := api.atom(connection, "UTF8_STRING") + utf8Atom, err := api.atom(connection, "UTF8_STRING") if err != nil { return "", err } - value, accepted, err := readSelection(api, connection, requestor, selection, utf8, property) + // Some owners (including xclip) answer unadvertised text requests with + // their binary payload. Ask TARGETS first, just as the image reader does, + // so an image-only copy reaches TextPasteNoText rather than the editor. + targets, err := api.atom(connection, "TARGETS") if err != nil { return "", err } - if accepted { - return value, nil + data, kind, accepted, err := readSelectionBytes(api, connection, requestor, selection, targets, property, 1<<16) + if err != nil { + return "", err + } + textTarget := utf8Atom + wantUTF8, wantLatin1 := true, true + if accepted && kind == xcbAtomAtom && len(data)%4 == 0 { + mimeUTF8, mimeErr := api.atom(connection, "text/plain;charset=utf-8") + if mimeErr != nil { + return "", mimeErr + } + wantUTF8, wantLatin1 = false, false + for offset := 0; offset < len(data); offset += 4 { + switch binary.NativeEndian.Uint32(data[offset:]) { + case utf8Atom: + wantUTF8, textTarget = true, utf8Atom + case xcbAtomString: + wantLatin1 = true + case mimeUTF8: + // Owners that only offer the MIME spelling of UTF-8 text. + if !wantUTF8 { + wantUTF8, textTarget = true, mimeUTF8 + } + } + } + } + // Old owners without TARGETS still get the legacy text requests. + if wantUTF8 { + // A target the owner advertised may answer typed as UTF8_STRING; only the + // unadvertised legacy request needs the type check. + read := readSelection + if textTarget == utf8Atom { + read = readTypedSelection + } + value, accepted, err := read(api, connection, requestor, selection, textTarget, property) + if err != nil { + return "", err + } + if accepted { + if !utf8.ValidString(value) { + return "", fmt.Errorf("linux: clipboard text is not valid UTF-8") + } + return value, nil + } + } + if wantLatin1 { + return readLegacySelection(api, connection, requestor, selection, property) } - return readLegacySelection(api, connection, requestor, selection, property) + return "", nil } // HasClipboardImage reports whether the X11 CLIPBOARD owner offers image/png. @@ -287,7 +335,27 @@ func ownsClipboardText() bool { } win.mu.Lock() defer win.mu.Unlock() - return activeWindow.Load() == win && win.connection != 0 && win.ownsClipboard + return activeWindow.Load() == win && win.clipboardOwnedLocked() +} + +// SelectionClear can still be queued when a background owner finishes a copy. +// Check ownership when reading the cache, never on a timer, so an immediate +// paste cannot return stale text or incorrectly report that no image exists. +// win.mu is held by the caller. +func (win *window) clipboardOwnedLocked() bool { + if win.connection == 0 || !win.ownsClipboard { + return false + } + owner, err := selectionOwner(win.api, win.connection, win.clipboardAtom) + if err != nil { + return false + } + if owner == win.id { + return true + } + win.clipboard, win.clipboardHTML, win.clipboardFiles, win.clipboardImage = "", "", nil, nil + win.ownsClipboard = false + return false } // ownedClipboardImage is the picture this window's clipboard holds, and whether @@ -299,7 +367,7 @@ func ownedClipboardImage() ([]byte, bool) { } win.mu.Lock() defer win.mu.Unlock() - if activeWindow.Load() != win || win.connection == 0 || !win.ownsClipboard || len(win.clipboardImage) == 0 { + if activeWindow.Load() != win || !win.clipboardOwnedLocked() || len(win.clipboardImage) == 0 { return nil, false } return append([]byte(nil), win.clipboardImage...), true @@ -314,7 +382,7 @@ func ownedClipboardFiles() ([]string, bool) { } win.mu.Lock() defer win.mu.Unlock() - if activeWindow.Load() != win || win.connection == 0 || !win.ownsClipboard { + if activeWindow.Load() != win || !win.clipboardOwnedLocked() { return nil, false } return append([]string(nil), win.clipboardFiles...), true @@ -1055,7 +1123,7 @@ func selectionOwner(api *xcbAPI, connection uintptr, selection uint32) (uint32, } func readLegacySelection(api *xcbAPI, connection uintptr, requestor, selection, property uint32) (string, error) { - value, accepted, err := readSelection(api, connection, requestor, selection, xcbAtomString, property) + value, accepted, err := readTypedSelection(api, connection, requestor, selection, xcbAtomString, property) if err != nil || !accepted { return "", err } @@ -1065,13 +1133,33 @@ func readLegacySelection(api *xcbAPI, connection uintptr, requestor, selection, // readSelection asks the owner for target as text. A text bigger than one property comes in // pieces (INCR), as readSelectionBytes collects them. func readSelection(api *xcbAPI, connection uintptr, requestor, selection, target, property uint32) (string, bool, error) { - data, _, accepted, err := readSelectionBytes(api, connection, requestor, selection, target, property, maxClipboardBytes) + return readSelectionText(api, connection, requestor, selection, target, property, false) +} + +// readTypedSelection is readSelection for the clipboard text readers: an owner that answers +// with another type than the one asked for (a binary payload from an unadvertised request) +// is treated as having no text. +func readTypedSelection(api *xcbAPI, connection uintptr, requestor, selection, target, property uint32) (string, bool, error) { + return readSelectionText(api, connection, requestor, selection, target, property, true) +} + +func readSelectionText(api *xcbAPI, connection uintptr, requestor, selection, target, property uint32, typed bool) (string, bool, error) { + data, kind, accepted, err := readSelectionBytes(api, connection, requestor, selection, target, property, maxClipboardBytes) if errors.Is(err, platform.ErrClipboardImageTooLarge) { return "", false, fmt.Errorf("linux: clipboard text exceeds 64 MiB") } if err != nil || !accepted { return "", false, err } + if typed && kind != target { + incr, atomErr := api.atom(connection, "INCR") + if atomErr != nil { + return "", false, atomErr + } + if kind != incr { + return "", false, nil + } + } return string(data), true, nil } @@ -1200,15 +1288,3 @@ func (win *window) clearPixmap(pixmap uint32) error { win.api.freeGC(win.connection, gc) return err } - -// OnClipboardChange reports that this target cannot watch the clipboard. X11 announces a change of -// selection owner through the XFixes extension and the GTK shell through its own clipboard -// signal, and neither is wired up yet; the alternative, asking who owns the selection on a timer, -// would run for as long as the process lives and miss a new copy by the same owner, which is the -// common case. The clipboard itself keeps working. -func OnClipboardChange(notify func()) error { - if notify == nil { - return nil - } - return unsupported("clipboard change events are not available on this display server") -} diff --git a/internal/platform/linux/system_linux_test.go b/internal/platform/linux/system_linux_test.go index 5c181aadd..5d1696fd1 100644 --- a/internal/platform/linux/system_linux_test.go +++ b/internal/platform/linux/system_linux_test.go @@ -451,7 +451,8 @@ func TestDarkAppearanceAnswersOnThisMachine(t *testing.T) { // X11 and the GTK shell cannot report clipboard changes yet. The caller is told so, with the error a // caller checks for, instead of being promised news that never comes; stopping needs nothing. -func TestOnClipboardChangeSaysThisTargetCannotWatch(t *testing.T) { +func TestOnClipboardChangeWithoutDisplayReportsUnsupported(t *testing.T) { + t.Setenv("DISPLAY", "") if err := OnClipboardChange(func() {}); !errors.Is(err, ErrUnsupported) { t.Fatalf("OnClipboardChange = %v, want ErrUnsupported", err) } diff --git a/internal/platform/linux/text_engine_linux.go b/internal/platform/linux/text_engine_linux.go index f3aa88b38..dd30015f9 100644 --- a/internal/platform/linux/text_engine_linux.go +++ b/internal/platform/linux/text_engine_linux.go @@ -39,11 +39,18 @@ type shapedLine struct { hasTables bool // offsets are the byte offsets of the grapheme cluster boundaries, from 0 to len(value); // carets the x of the caret at each (the strong cursor: where a character of the - // paragraph's direction is typed). extents holds, for the cluster that starts at - // offsets[i], its left and right edge on the screen at extents[2*i] and extents[2*i+1]. + // paragraph's direction is typed). edges holds the logical start and end on + // screen for the cluster beginning at offsets[i]. offsets []int32 carets []float32 - extents []float32 + edges []clusterEdges + hasRTL bool +} + +type clusterEdges struct{ leading, trailing float32 } + +func (edge clusterEdges) bounds() (left, right float32) { + return min(edge.leading, edge.trailing), max(edge.leading, edge.trailing) } // textEngine is the gfx.TextEngine over Pango. It is safe for concurrent use: the Pango @@ -255,7 +262,8 @@ func (engine *textEngine) tablesLocked(line *shapedLine, value string) { } clusters := len(line.offsets) - 1 line.carets = line.carets[:0] - line.extents = line.extents[:0] + line.edges = line.edges[:0] + line.hasRTL = false for index, offset := range line.offsets { engine.strong = pangoRectangle{} engine.weak = pangoRectangle{} @@ -266,11 +274,11 @@ func (engine *textEngine) tablesLocked(line *shapedLine, value string) { } engine.cell = pangoRectangle{} services.layoutIndexToPos(line.layout, offset, &engine.cell) - left, right := engine.cell.X, engine.cell.X+engine.cell.Width - if right < left { - left, right = right, left - } - line.extents = append(line.extents, float32(left)/pangoScale, float32(right)/pangoScale) + line.hasRTL = line.hasRTL || engine.cell.Width < 0 + line.edges = append(line.edges, clusterEdges{ + leading: float32(engine.cell.X) / pangoScale, + trailing: float32(engine.cell.X+engine.cell.Width) / pangoScale, + }) } line.hasTables = true } @@ -366,7 +374,7 @@ func (engine *textEngine) SelectionStyle(dst []gfx.TextSpan, value string, size, } base := len(dst) for cluster := first; cluster < last; cluster++ { - left, right := line.extents[2*cluster], line.extents[2*cluster+1] + left, right := line.edges[cluster].bounds() joined := false for index := base; index < len(dst); index++ { span := &dst[index] @@ -421,6 +429,9 @@ func (engine *textEngine) OffsetAtStyle(value string, size, weight float32, ital if line == nil { return engine.reference.OffsetAt(value, size, weight, x) } + if line.hasRTL { + return line.hitDirectionalCluster(x) + } best, bestDistance := 0, float32(-1) for index, caret := range line.carets { distance := caret - x @@ -433,3 +444,29 @@ func (engine *textEngine) OffsetAtStyle(value string, size, weight float32, ital } return int(line.offsets[best]) } + +func (line *shapedLine) hitDirectionalCluster(x float32) int { + best, distance := 0, float32(-1) + for i, edge := range line.edges { + left, right := edge.bounds() + if left == right { + continue + } + // Two logical boundaries can share one position. The cluster under the + // pointer determines which one owns this side of that position. + gap := max(left-x, x-right, 0) + if distance >= 0 && gap >= distance { + continue + } + at := i + if x-left < right-x && edge.leading > edge.trailing || + x-left > right-x && edge.leading < edge.trailing { + at++ + } + best, distance = at, gap + if gap == 0 { + break + } + } + return int(line.offsets[best]) +} diff --git a/internal/platform/linux/text_engine_linux_test.go b/internal/platform/linux/text_engine_linux_test.go index 251acca81..86b9b15a6 100644 --- a/internal/platform/linux/text_engine_linux_test.go +++ b/internal/platform/linux/text_engine_linux_test.go @@ -40,6 +40,41 @@ func TestEnginePassesTheTextEngineContract(t *testing.T) { textenginetest.Run(t, newTestEngine(t)) } +func TestMixedDirectionHitUsesTheClickedClusterEdge(t *testing.T) { + engine := newTestEngine(t) + const prefix, first, second, tail = "ab ", "\u05d0\u05b7", "\u05d1", " cd" + const value = prefix + first + second + tail + const start, middle, end = len(prefix), len(prefix + first), len(prefix + first + second) + const size = 20 + span := func(from, to int) gfx.TextSpan { + t.Helper() + spans := engine.Selection(nil, value, size, 0, from, to) + if len(spans) != 1 || spans[0].Width <= 0 { + t.Fatalf("selection [%d,%d) spans = %+v", from, to, spans) + } + return spans[0] + } + leftLatin := span(start-1, start) + leftRTL := span(middle, end) + rightRTL := span(start, middle) + rightLatin := span(end, end+1) + for _, check := range []struct { + name string + x float32 + want int + }{ + {"Latin before RTL", leftLatin.X + 0.9*leftLatin.Width, start}, + {"RTL at left boundary", leftRTL.X + 0.1*leftRTL.Width, end}, + {"RTL at right boundary", rightRTL.X + 0.9*rightRTL.Width, start}, + {"Latin after RTL", rightLatin.X + 0.1*rightLatin.Width, end}, + {"RTL between graphemes", rightRTL.X + 0.1*rightRTL.Width, middle}, + } { + if got := engine.OffsetAt(value, size, 0, check.x); got != check.want { + t.Errorf("%s: hit at %.2f returned byte %d, want %d", check.name, check.x, got, check.want) + } + } +} + func TestTextEngineRasterizesProportionalText(t *testing.T) { engine := newTestEngine(t) textenginetest.TransparentColorGlyphs(t, engine) diff --git a/internal/platform/linux/window_controls_linux.go b/internal/platform/linux/window_controls_linux.go index 9f19a6b85..b593ad9e5 100644 --- a/internal/platform/linux/window_controls_linux.go +++ b/internal/platform/linux/window_controls_linux.go @@ -298,7 +298,8 @@ func (win *window) beginWindowMove(config platform.Config, event *xcbInputEvent) if win.fullscreen.Load() { return false } - if config.WindowMode != platform.WindowCustomTitlebar || event.Detail != xcbButtonLeft { + notification := config.WindowMode == platform.WindowNotification + if (config.WindowMode != platform.WindowCustomTitlebar && !notification) || event.Detail != xcbButtonLeft { return false } // The application's coordinates are logical; the event's are device pixels. @@ -309,7 +310,7 @@ func (win *window) beginWindowMove(config platform.Config, event *xcbInputEvent) press = config.PressAt(x, y) } direction, ok := uint32(moveResizeMove), false - if !win.frame.maximized { + if !notification && !win.frame.maximized { // The top edge yields to a control, so the buttons work up to the top. edge := platform.EdgeAt(x, y, float32(windowframe.ContentSize(win.width, win.margin))/scale, float32(windowframe.ContentSize(win.height, win.margin))/scale, press == platform.PressControl) if ok = edge != platform.EdgeNone; ok { @@ -325,7 +326,7 @@ func (win *window) beginWindowMove(config platform.Config, event *xcbInputEvent) win.frame.pendingRootX, win.frame.pendingRootY = event.RootX, event.RootY return false } - if win.doubleClick(event) { + if !notification && win.doubleClick(event) { win.toggleMaximize() return true } diff --git a/internal/platform/linux/window_exposure_linux_test.go b/internal/platform/linux/window_exposure_linux_test.go new file mode 100644 index 000000000..b2e7ac886 --- /dev/null +++ b/internal/platform/linux/window_exposure_linux_test.go @@ -0,0 +1,87 @@ +//go:build !android + +package linux + +import ( + "os" + "testing" + "time" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// Mapping/reparenting or uncovering can invalidate pixels again after the +// first Expose. Recover from the server's damage request without pointer input +// or changes to the application's retained scene. +func TestTrayWindowRepaintsLaterExposure(t *testing.T) { + if os.Getenv("VIVA_TEST_NOTIFICATION_XVFB") != "1" { + t.Skip("requires a private Xvfb server") + } + t.Setenv("VIVA_SOFTWARE_RENDERING", "1") + a := &linuxApplication{} + control, err := a.OpenWindow(platform.Config{ + Title: "Viva tray exposure", Width: 180, Height: 66, WindowMode: platform.WindowPanel, + Rectangles: []render.Rectangle{{Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 180, Height: 66}, Color: scene.Color{Red: 1, Alpha: 1}}}, + }) + if err != nil { + t.Fatal(err) + } + defer a.closeAll() + s := control.(*nativeWindow).state + drain := func() { + deadline := time.Now().Add(100 * time.Millisecond) + for time.Now().Before(deadline) { + e := s.nextEvent() + if e == nil { + time.Sleep(time.Millisecond) + continue + } + closed, err := s.handleEvent(e) + s.win.api.free(e) + if err != nil || closed { + t.Fatalf("dispatch: closed=%v err=%v", closed, err) + } + } + } + drain() + if !s.exposed { + t.Fatal("window never mapped") + } + var clearArea func(uintptr, uint8, uint32, int16, int16, uint16, uint16) xcbVoidCookie + purego.RegisterLibFunc(&clearArea, s.win.api.library, "xcb_clear_area") + for range 2 { + clearArea(s.win.connection, 1, s.win.id, 0, 0, 180, 66) + s.win.api.flush(s.win.connection) + drain() + pixel := readWindowPixels(t, s.win, 20, 20, 1, 1) + if pixel[0] != 0 || pixel[1] != 0 || pixel[2] != 255 { + t.Fatalf("exposed tray remains blank without pointer input: %v", pixel[:4]) + } + } + presents := s.renderer.stats().presents + drain() + if got := s.renderer.stats().presents; got != presents { + t.Fatalf("idle tray keeps repainting: %d -> %d", presents, got) + } +} + +func TestExposureDoesNotPaintHiddenOrForeignWindow(t *testing.T) { + r := &fakeWindowRenderer{} + s := &linuxWindowState{win: &window{id: 9}, renderer: r, hidden: true} + e := xcbExposeEvent{ResponseType: xcbExpose, Window: 9} + if _, err := s.handleEvent(unsafe.Pointer(&e)); err != nil { + t.Fatal(err) + } + s.hidden = false + e.Window = 10 + if _, err := s.handleEvent(unsafe.Pointer(&e)); err != nil { + t.Fatal(err) + } + if len(r.calls) != 0 { + t.Fatal("painted a hidden or unrelated window", r.calls) + } +} diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 8ac4d03d7..ce2fb02cc 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -167,7 +167,8 @@ type linuxWindowState struct { // margin before its matching ConfigureNotify supplied the final dimensions. frameGeometryDirty bool // hidden records the application's request, independently of the asynchronous - // MapNotify/UnmapNotify events. The first Expose after a map paints in full. + // MapNotify/UnmapNotify events. exposed records that a mapped frame was shown; + // it must not suppress later server requests to restore lost pixels. hidden bool exposed bool // visible is the last visibility reported to OnVisibility; a window starts as visible. @@ -243,6 +244,7 @@ func RunApplication(start platform.ApplicationStart) error { runtime.LockOSThread() defer runtime.UnlockOSThread() application := &linuxApplication{} + defer stopClipboardWatch() defer application.closeStatus() defer application.atspiClose() defer application.closeDesktop() @@ -266,7 +268,16 @@ func RunApplication(start platform.ApplicationStart) error { if len(fds) == 0 { break } - if result := application.windows[0].win.api.poll(&fds[0], uintptr(len(fds)), application.pollTimeout()); result < 0 { + timeout := application.pollTimeout() + // A synchronous XCB reply (including renderer setup) can move events + // out of the socket into libxcb's queue. poll cannot see those bytes. + // Dispatch them before sleeping, without polling an idle application. + for _, state := range states { + if state != nil && state.bufferedEvent() { + timeout = 0 + } + } + if result := application.windows[0].win.api.poll(&fds[0], uintptr(len(fds)), timeout); result < 0 { // A signal that reaches the thread while it sleeps ends the wait // early without anything being wrong: wait again. if errno := *application.windows[0].win.api.errnoLocation(); errno == errnoINTR { @@ -281,10 +292,13 @@ func RunApplication(start platform.ApplicationStart) error { application.checkInputMethod() } for index, descriptor := range fds { - if descriptor.REvents == 0 { + state := states[index] + if state != nil && !application.contains(state) { + continue + } + if descriptor.REvents == 0 && (state == nil || !state.bufferedEvent()) { continue } - state := states[index] if state == nil { switch { case application.inputMethod != nil && int(descriptor.FD) == application.inputMethod.FD(): @@ -507,6 +521,18 @@ func (application *linuxApplication) pollTimeout() int32 { return timeout } +// bufferedEvent peeks only at events already read from the socket. Preserve +// their order with any input held by motion/configure coalescing. +func (state *linuxWindowState) bufferedEvent() bool { + if state.held != nil { + return true + } + if poll := state.win.api.pollForQueuedEvent; poll != nil { + state.held = poll(state.win.connection) + } + return state.held != nil +} + // takeHeld returns the event read ahead, once. func (state *linuxWindowState) takeHeld() unsafe.Pointer { if state.held == nil { @@ -628,13 +654,14 @@ func (state *linuxWindowState) coalesceMotions(event unsafe.Pointer) unsafe.Poin func (state *linuxWindowState) coalesceConfigures(event unsafe.Pointer) unsafe.Pointer { configure := (*xcbConfigureEvent)(event) var heldSync unsafe.Pointer + var heldExpose unsafe.Pointer var heldPointers []unsafe.Pointer finish := func(boundary unsafe.Pointer) unsafe.Pointer { if len(heldPointers) == 0 { - state.holdEvents(heldSync, boundary) + state.holdEvents(heldExpose, heldSync, boundary) } else { - replay := make([]unsafe.Pointer, 0, len(heldPointers)+2) - replay = append(replay, heldSync) + replay := make([]unsafe.Pointer, 0, len(heldPointers)+3) + replay = append(replay, heldExpose, heldSync) replay = append(replay, heldPointers...) replay = append(replay, boundary) state.holdEvents(replay...) @@ -674,8 +701,17 @@ func (state *linuxWindowState) coalesceConfigures(event unsafe.Pointer) unsafe.P state.win.api.free(next) case xcbExpose: expose := (*xcbExposeEvent)(next) - if expose.Window == state.win.id && (state.hidden || state.exposed) { - state.win.api.free(next) + if expose.Window == state.win.id { + if state.hidden { + state.win.api.free(next) + } else { + // A position-only Configure does not repaint. Preserve one + // exposure after the final geometry instead of losing damage. + if heldExpose != nil { + state.win.api.free(heldExpose) + } + heldExpose = next + } continue } return finish(next) @@ -1225,7 +1261,7 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { return true, nil } case xcbExpose: - if !state.hidden && !state.exposed && (*xcbExposeEvent)(event).Count == 0 { + if expose := (*xcbExposeEvent)(event); !state.hidden && expose.Window == win.id && expose.Count == 0 { state.exposed = true return false, renderer.presentFull() } diff --git a/internal/platform/linux/window_notification_linux_test.go b/internal/platform/linux/window_notification_linux_test.go index 6d7b821e8..c0a94a72f 100644 --- a/internal/platform/linux/window_notification_linux_test.go +++ b/internal/platform/linux/window_notification_linux_test.go @@ -9,6 +9,7 @@ import ( "unsafe" "github.com/ebitengine/purego" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" ) @@ -51,6 +52,27 @@ func TestNotificationNativeX11(t *testing.T) { if x != int32(wantX) || y != int32(wantY) { t.Fatalf("origin %d,%d want %d,%d", x, y, wantX, wantY) } + // The initial position is inside the monitor. A stale top-left far outside + // the private display falls back to the edge of the available work area. + scale := win.displayScale() + for _, test := range []struct { + origin gfx.Point + wantX, wantY int32 + }{ + {gfx.Point{X: float32(x) / scale, Y: float32(y) / scale}, x, y}, + {gfx.Point{X: -10000, Y: -10000}, 0, 0}, + } { + config.HasOrigin, config.Origin = true, test.origin + restored, err := openWindow(config) + if err != nil { + t.Fatal(err) + } + rx, ry := restored.rootOrigin() + restored.close() + if rx != test.wantX || ry != test.wantY { + t.Errorf("restoring %+v produced %d,%d want %d,%d", test.origin, rx, ry, test.wantX, test.wantY) + } + } getProperty := func(name string, kind uint32) uint32 { t.Helper() atom, err := win.api.atom(win.connection, name) diff --git a/internal/platform/linux/window_queued_wake_linux_test.go b/internal/platform/linux/window_queued_wake_linux_test.go new file mode 100644 index 000000000..442826410 --- /dev/null +++ b/internal/platform/linux/window_queued_wake_linux_test.go @@ -0,0 +1,55 @@ +//go:build !android + +package linux + +import ( + "os" + "sync/atomic" + "testing" + "time" + + "github.com/vivaui/viva/internal/platform" +) + +// A round trip made after opening a tray window can consume the socket bytes +// into libxcb's private queue. No mouse or keyboard event should be needed to +// dispatch the redraw already waiting in that queue. +func TestTrayWindowQueuedRedrawBeforeInput(t *testing.T) { + if os.Getenv("VIVA_TEST_NOTIFICATION_XVFB") != "1" { + t.Skip("requires a private Xvfb server") + } + t.Setenv("VIVA_SOFTWARE_RENDERING", "1") + var redraws atomic.Int32 + var observed atomic.Int32 + err := RunApplication(func(app platform.Application) error { + owner, err := app.OpenWindow(platform.Config{Width: 80, Height: 60}) + if err != nil { + return err + } + owner.Hide() + app.Post(func() { + panel, err := app.OpenWindow(platform.Config{Width: 180, Height: 66, WindowMode: platform.WindowNotification, + Waker: &platform.Waker{}, + OnRedraw: func() (platform.Frame, error) { redraws.Add(1); return platform.Frame{}, nil }, + }) + if err != nil { + t.Error(err) + app.Quit() + return + } + win := panel.(*nativeWindow).state.win + win.postRedraw() + if _, err := win.api.atom(win.connection, "_VIVA_TEST_AFTER_TRAY_OPEN"); err != nil { + t.Error(err) + } + time.AfterFunc(time.Second, func() { observed.Store(redraws.Load()); app.Quit() }) + }) + return nil + }) + if err != nil { + t.Fatal(err) + } + if observed.Load() == 0 { + t.Fatal("tray redraw stayed buffered until another input event") + } +} diff --git a/internal/platform/linux/xcb_linux.go b/internal/platform/linux/xcb_linux.go index aadafebac..d7d7b2a39 100644 --- a/internal/platform/linux/xcb_linux.go +++ b/internal/platform/linux/xcb_linux.go @@ -349,6 +349,7 @@ type xcbAPI struct { flush func(uintptr) int32 waitForEvent func(uintptr) unsafe.Pointer pollForEvent func(uintptr) unsafe.Pointer + pollForQueuedEvent func(uintptr) unsafe.Pointer fileDescriptor func(uintptr) int32 internAtom func(uintptr, uint8, uint16, *byte) xcbAtomCookie internAtomReply func(uintptr, xcbAtomCookie, *unsafe.Pointer) *xcbAtomReply @@ -440,6 +441,7 @@ func openXCB() (*xcbAPI, error) { purego.RegisterLibFunc(&api.flush, library, "xcb_flush") purego.RegisterLibFunc(&api.waitForEvent, library, "xcb_wait_for_event") purego.RegisterLibFunc(&api.pollForEvent, library, "xcb_poll_for_event") + purego.RegisterLibFunc(&api.pollForQueuedEvent, library, "xcb_poll_for_queued_event") purego.RegisterLibFunc(&api.fileDescriptor, library, "xcb_get_file_descriptor") purego.RegisterLibFunc(&api.internAtom, library, "xcb_intern_atom") purego.RegisterLibFunc(&api.internAtomReply, library, "xcb_intern_atom_reply") diff --git a/internal/platform/status_item.go b/internal/platform/status_item.go index a68d4010b..4a09c20d4 100644 --- a/internal/platform/status_item.go +++ b/internal/platform/status_item.go @@ -39,6 +39,12 @@ func PlaceNotification(width, height, margin float32, area ScreenRect) (float32, return max(area.X, area.X+area.Width-width-margin), max(area.Y, area.Y+area.Height-height-margin) } +// RestoreNotification fits a remembered top-left into the selected work area. +func RestoreNotification(x, y, width, height float32, area ScreenRect) (float32, float32) { + return min(max(x, area.X), area.X+max(0, area.Width-width)), + min(max(y, area.Y), area.Y+max(0, area.Height-height)) +} + // Scaled returns the icon at size x size pixels, each result pixel the average // of the source pixels it covers, weighted by their alpha so that a transparent // edge does not bleed its hidden color into the shape. Platforms that draw a diff --git a/internal/platform/status_item_test.go b/internal/platform/status_item_test.go index 2df69bc71..9b8b5332d 100644 --- a/internal/platform/status_item_test.go +++ b/internal/platform/status_item_test.go @@ -12,6 +12,25 @@ func TestNotificationPlacementRespectsWorkAreaAndNegativeScreenOrigins(t *testin } } +func TestRestoreNotificationClampsRememberedOrigin(t *testing.T) { + area := ScreenRect{X: -1920, Y: 30, Width: 1920, Height: 1040} + for _, test := range []struct { + name string + x, y, wantX, wantY float32 + }{ + {"inside", -1200, 60, -1200, 60}, + {"partly outside", -100, 1040, -320, 942}, + {"screen gone", -8000, -4000, -1920, 30}, + } { + t.Run(test.name, func(t *testing.T) { + x, y := RestoreNotification(test.x, test.y, 320, 128, area) + if x != test.wantX || y != test.wantY { + t.Errorf("restored %g,%g, want %g,%g", x, y, test.wantX, test.wantY) + } + }) + } +} + func TestPlacePanelOpensTowardTheMiddleOfTheScreen(t *testing.T) { work := ScreenRect{Width: 1920, Height: 1040} // a 40 pixel taskbar at the bottom // An icon in the bottom-right corner of a bottom taskbar: the panel is above diff --git a/internal/platform/vulkan/driver_android.go b/internal/platform/vulkan/driver_android.go deleted file mode 100644 index c0208f5ce..000000000 --- a/internal/platform/vulkan/driver_android.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build android - -package vulkan - -// Android ships the loader as libvulkan.so, with the drivers of the device behind -// it, and has no manifests to look for: whether a driver works is found when the -// instance is made. -const vulkanLibraryName = "libvulkan.so" - -func vulkanDriverConfigured() bool { return true } diff --git a/internal/platform/vulkan/rasterizer.go b/internal/platform/vulkan/rasterizer.go index bbbda56f7..ea50c2fc1 100644 --- a/internal/platform/vulkan/rasterizer.go +++ b/internal/platform/vulkan/rasterizer.go @@ -13,8 +13,8 @@ type ColorSpan struct { // TextRasterizer draws the glyphs of a text label into the coverage bitmap of its // texture. The renderer owns the texture, its upload and its placement; what draws -// the glyphs is the platform's text engine (Pango on a Linux desktop, the system's -// Paint on Android), which the platform gives the renderer as a factory. +// the glyphs is the platform's text engine (Pango on a Linux desktop), which the platform +// gives the renderer as a factory. type TextRasterizer interface { // Rasterize draws the device columns from skip to skip+width of the label, height // rows tall, at scale. With allowLCD the result may be the coverage of each diff --git a/internal/platform/vulkan/surface_lifecycle_linux.go b/internal/platform/vulkan/surface_lifecycle_linux.go deleted file mode 100644 index 4c66ab23c..000000000 --- a/internal/platform/vulkan/surface_lifecycle_linux.go +++ /dev/null @@ -1,57 +0,0 @@ -package vulkan - -import "fmt" - -// A window system can take a surface back while the application lives on: Android -// destroys the surface of a window that goes behind another and gives it a new one -// when it returns. ReleaseSurface and ReplaceSurface keep the device, the scene and -// the label textures through that; only what hangs on the surface is made again. - -// ReleaseSurface lets go of the swapchain and the surface, and everything made for -// the swapchain's images, before the window system takes the surface away. The device -// is kept, so is what the renderer would draw. Nothing is drawn until ReplaceSurface. -func (renderer *Renderer) ReleaseSurface() { - if renderer == nil || renderer.api == nil || renderer.device == 0 { - return - } - renderer.api.deviceWaitIdle(renderer.device) - renderer.destroySwapchain() - if renderer.surface != 0 && renderer.instance != 0 { - renderer.api.destroySurface(renderer.instance, renderer.surface, nil) - } - renderer.surface = 0 - renderer.hasSurfaceFormat = false - renderer.hasPresentMode = false - renderer.hasPendingCapabilities = false - renderer.recorded = nil -} - -// ReplaceSurface makes the surface again from the window system's current one, which -// is width x height device pixels, and a swapchain on it. The scene and the label -// textures the renderer kept are drawn on it; the application should apply a whole -// frame next, as the one it applied last may have been before the surface went. -func (renderer *Renderer) ReplaceSurface(width, height uint32) error { - for losses := 0; ; losses++ { - retry, err := renderer.recoverFrom(renderer.replaceSurfaceOnce(width, height), losses) - if !retry { - return err - } - } -} - -func (renderer *Renderer) replaceSurfaceOnce(width, height uint32) error { - if renderer.source.Create == nil || renderer.shared == nil { - return fmt.Errorf("vulkan: only a window renderer has a surface to replace") - } - renderer.ReleaseSurface() - surface, err := renderer.source.Create(renderer.instance) - if err != nil { - return err - } - renderer.surface = surface - if err := renderer.shared.attach(surface); err != nil { - return err - } - renderer.width, renderer.height = width, height - return renderer.createSwapchain() -} diff --git a/internal/platform/vulkan/vulkan_linux.go b/internal/platform/vulkan/vulkan_linux.go index 7c5828ff2..3b8d23db8 100644 --- a/internal/platform/vulkan/vulkan_linux.go +++ b/internal/platform/vulkan/vulkan_linux.go @@ -549,16 +549,11 @@ func openVulkan() (*vulkanAPI, error) { // to: the instance extension that makes a VkSurfaceKHR, and the call that makes it. type SurfaceSource struct { // Extension is the name of the instance extension the surface needs: - // VK_KHR_xcb_surface, VK_KHR_android_surface. + // VK_KHR_xcb_surface. Extension string // Create makes the surface on instance. The renderer calls it again after the // device or the surface was lost. Create func(instance uintptr) (surface uintptr, err error) - // HostSize says the window system gives the surface's size with its events, which is - // truer than what the surface reports while it changes: Android learns the new size - // of a surface a frame after it told the program. The swapchain is then made at the - // size the renderer was given, and the compositor fits it to the window. - HostSize bool } // Config is what a window's renderer is made from. @@ -698,7 +693,7 @@ func (renderer *Renderer) createSwapchain() (err error) { renderer.hasSurfaceFormat = true } extent := capabilities.Current - if extent.Width == math.MaxUint32 || renderer.source.HostSize { + if extent.Width == math.MaxUint32 { extent.Width = clamp(renderer.width, capabilities.Minimum.Width, capabilities.Maximum.Width) extent.Height = clamp(renderer.height, capabilities.Minimum.Height, capabilities.Maximum.Height) } diff --git a/internal/platform/web_host.go b/internal/platform/web_host.go index 4d12ad861..93a8c997c 100644 --- a/internal/platform/web_host.go +++ b/internal/platform/web_host.go @@ -1,10 +1,7 @@ package platform import ( - "crypto/sha1" - "encoding/hex" "errors" - "strings" "github.com/vivaui/viva/gfx" ) @@ -21,18 +18,6 @@ var ErrWebViewUnsupported = errors.New("platform: this window cannot host web pa // WebProxyDirect explicitly bypasses system proxies for one page's network context. const WebProxyDirect = "direct" -// PartitionIdentifier is the identifier a platform that names a store by an identifier gives a storage -// partition: a UUID made from the name, the same for a name in every run of the application, so a name -// is one store. macOS's WKWebsiteDataStore names its persistent stores this way; WebView2 names a -// profile by the partition's name itself, and WebKitGTK by the directory it keeps, one of the name. -func PartitionIdentifier(name string) string { - sum := sha1.Sum([]byte("viva-storage-partition:" + name)) - sum[6] = sum[6]&0x0f | 0x50 // a name-based UUID, version 5 - sum[8] = sum[8]&0x3f | 0x80 // the variant a UUID carries - text := hex.EncodeToString(sum[:]) - return strings.ToUpper(text[0:8] + "-" + text[8:12] + "-" + text[12:16] + "-" + text[16:20] + "-" + text[20:32]) -} - // NativeView is a place in the window that a native view fills. type NativeView struct { // ID is the WebView it belongs to (WebViewConfig.ID). diff --git a/internal/platform/windows/status_item_windows.go b/internal/platform/windows/status_item_windows.go index 9b1b506bf..6b1460cff 100644 --- a/internal/platform/windows/status_item_windows.go +++ b/internal/platform/windows/status_item_windows.go @@ -481,18 +481,16 @@ func (state *windowState) placePanel() { getWindowRect.Call(state.window, uintptr(unsafe.Pointer(&bounds))) width, height := float32(bounds.Right-bounds.Left), float32(bounds.Bottom-bounds.Top) config := state.config - if !config.HasAnchor || config.WindowMode == platform.WindowNotification { + if !config.HasAnchor { // Centered on the monitor the cursor is on. var info monitorInfo info.Size = uint32(unsafe.Sizeof(info)) monitor := cursorMonitor() - getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))) + if ok, _, _ := getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))); ok == 0 { + return + } x := float32(info.Work.Left) + (float32(info.Work.Right-info.Work.Left)-width)/2 y := float32(info.Work.Top) + (float32(info.Work.Bottom-info.Work.Top)-height)/2 - if config.WindowMode == platform.WindowNotification { - area := platform.ScreenRect{X: float32(info.Work.Left), Y: float32(info.Work.Top), Width: float32(info.Work.Right - info.Work.Left), Height: float32(info.Work.Bottom - info.Work.Top)} - x, y = platform.PlaceNotification(width, height, 12*state.scale, area) - } setWindowPosition.Call(state.window, hwndTopmost, uintptr(int32(x)), uintptr(int32(y)), 0, 0, 0x11) // NOSIZE | NOACTIVATE return } @@ -566,8 +564,8 @@ func (state *windowState) placeAtOrigin(origin gfx.Point) { setWindowPosition.Call(state.window, 0, uintptr(x), uintptr(y), uintptr(width), uintptr(height), 0x14) } -// Frame is the content area in screen coordinates, in the logical pixels of the -// window's own display. It reads the system's state, so any goroutine may call it. +// Frame reads the system's state, so any goroutine may call it. Notification +// origins stay in physical desktop pixels across monitor DPI changes. func (window *nativeWindow) Frame() (gfx.Rect, bool) { if window == nil || window.closed.Load() || window.state == nil || window.state.window == 0 { return gfx.Rect{}, false @@ -587,8 +585,12 @@ func (window *nativeWindow) Frame() (gfx.Rect, bool) { scale = float32(dpi) / 96 } } + x, y := float32(origin.X), float32(origin.Y) + if window.state.config.WindowMode != platform.WindowNotification { + x, y = x/scale, y/scale + } return gfx.Rect{ - X: float32(origin.X) / scale, Y: float32(origin.Y) / scale, + X: x, Y: y, Width: float32(client.Right-client.Left) / scale, Height: float32(client.Bottom-client.Top) / scale, }, true } diff --git a/internal/platform/windows/window_notification_windows.go b/internal/platform/windows/window_notification_windows.go new file mode 100644 index 000000000..61ca928ce --- /dev/null +++ b/internal/platform/windows/window_notification_windows.go @@ -0,0 +1,47 @@ +package windows + +import ( + "syscall" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +var monitorEffectiveDPI = syscall.NewLazyDLL("shcore.dll").NewProc("GetDpiForMonitor") + +func (state *windowState) placeNotification() { + config := state.config + monitor := cursorMonitor() + if config.HasOrigin { + x, y := int32(config.Origin.X), int32(config.Origin.Y) + monitor, _, _ = monitorFromPoint.Call(uintptr(uint32(x))|uintptr(uint32(y))<<32, monitorNearest) + } + var info monitorInfo + info.Size = uint32(unsafe.Sizeof(info)) + if ok, _, _ := getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))); ok == 0 { + return + } + scale := state.scale + if !state.scaleFixed && monitorEffectiveDPI.Find() == nil { + var dpiX, dpiY uint32 + hr, _, _ := monitorEffectiveDPI.Call(monitor, 0, uintptr(unsafe.Pointer(&dpiX)), uintptr(unsafe.Pointer(&dpiY))) + if int32(hr) == 0 && dpiX != 0 { + scale = float32(dpiX) / 96 + } + } + area := platform.ScreenRect{ + X: float32(info.Work.Left), Y: float32(info.Work.Top), + Width: float32(info.Work.Right - info.Work.Left), Height: float32(info.Work.Bottom - info.Work.Top), + } + width := min(float32(int32(float32(config.Width)*scale)), area.Width) + height := min(float32(int32(float32(config.Height)*scale)), area.Height) + x, y := platform.PlaceNotification(width, height, 12*scale, area) + if config.HasOrigin { + x, y = platform.RestoreNotification(config.Origin.X, config.Origin.Y, width, height, area) + } + // The selected monitor's DPI is already included. A synchronous + // WM_DPICHANGED still updates the scale but must not move the window again. + state.placingNotification = true + setWindowPosition.Call(state.window, hwndTopmost, uintptr(int32(x)), uintptr(int32(y)), uintptr(int32(width)), uintptr(int32(height)), 0x10) + state.placingNotification = false +} diff --git a/internal/platform/windows/window_notification_windows_test.go b/internal/platform/windows/window_notification_windows_test.go index b9f8197c3..7ba52ad03 100644 --- a/internal/platform/windows/window_notification_windows_test.go +++ b/internal/platform/windows/window_notification_windows_test.go @@ -8,6 +8,7 @@ import ( "testing" "unsafe" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" ) @@ -51,7 +52,12 @@ func TestNotificationNativeWindows(t *testing.T) { t.Fatalf("expected original keyboard focus %x, got %x", handle, before) } clicks := 0 - popup, err := app.OpenWindow(platform.Config{Title: "Incoming", Width: 336, Height: 136, WindowMode: platform.WindowNotification, OnPointer: func(e platform.PointerEvent) (platform.Frame, error) { + popup, err := app.OpenWindow(platform.Config{Title: "Incoming", Width: 336, Height: 136, WindowMode: platform.WindowNotification, PressAt: func(x, _ float32) platform.PressKind { + if x < 100 { + return platform.PressMove + } + return platform.PressControl + }, OnPointer: func(e platform.PointerEvent) (platform.Frame, error) { if e.Kind == platform.PointerDown { clicks++ } @@ -62,6 +68,18 @@ func TestNotificationNativeWindows(t *testing.T) { } defer popup.Close() hwnd := popup.(*nativeWindow).state.window + var native rect + getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&native))) + hit := func(x, y int32) uintptr { + result, _, _ := send.Call(hwnd, wmNCHitTest, 0, uintptr(uint16(x))|uintptr(uint16(y))<<16) + return result + } + if got := hit(native.Left+15, native.Top+15); got != htCaption { + t.Fatalf("notification drag surface hit code = %d", got) + } + if got := hit(native.Right-15, native.Top+15); got != htClient { + t.Fatalf("notification button hit code = %d", got) + } if after, _, _ := focus.Call(); after != handle { t.Fatal("opening the popup stole focus") } @@ -76,6 +94,34 @@ func TestNotificationNativeWindows(t *testing.T) { if after, _, _ := focus.Call(); after != handle { t.Fatal("interacting with notification stole focus") } + + var work monitorInfo + work.Size = uint32(unsafe.Sizeof(work)) + monitor, _, _ := monitorFromWindow.Call(hwnd, monitorNearest) + if ok, _, _ := getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&work))); ok == 0 { + t.Fatal("missing monitor work area") + } + width, height := native.Right-native.Left, native.Bottom-native.Top + for _, test := range []struct { + name string + origin, want point + }{ + {"restore", point{native.Left, native.Top}, point{native.Left, native.Top}}, + {"edge", point{work.Work.Right - 1, work.Work.Bottom - 1}, point{work.Work.Right - width, work.Work.Bottom - height}}, + } { + window, err := app.OpenWindow(platform.Config{ + Width: 336, Height: 136, WindowMode: platform.WindowNotification, HasOrigin: true, + Origin: gfx.Point{X: float32(test.origin.X), Y: float32(test.origin.Y)}, + }) + if err != nil { + return err + } + frame, ok := window.Frame() + window.Close() + if !ok || frame.X != float32(test.want.X) || frame.Y != float32(test.want.Y) { + t.Errorf("%s notification frame = %+v (ok=%v), want origin %+v", test.name, frame, ok, test.want) + } + } return nil }) if err != nil { diff --git a/internal/platform/windows/window_preview_windows.go b/internal/platform/windows/window_preview_windows.go index fd977731d..bc8ca46fb 100644 --- a/internal/platform/windows/window_preview_windows.go +++ b/internal/platform/windows/window_preview_windows.go @@ -24,6 +24,9 @@ func (window *nativeWindow) MoveTo(origin gfx.Point) { if scale <= 0 { scale = 1 } + if state.config.WindowMode == platform.WindowNotification { + scale = 1 + } x := int32(origin.X * scale) y := int32(origin.Y * scale) setWindowPosition.Call(state.window, 0, uintptr(x), uintptr(y), 0, 0, 0x15) // nosize, nozorder, noactivate diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index dba732464..fd3868d32 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -103,6 +103,7 @@ type windowState struct { maximized bool lastFrame gfx.Rect scale float32 + placingNotification bool scaleFixed bool // VIVA_SCALE set it: the display's own scale is ignored err error pointerEvents, resizeEvents, keyEvents uint64 @@ -437,7 +438,7 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf postMessage.Call(state.window, wmRedraw, 0, 0) } if config.WindowMode == platform.WindowNotification { - state.placePanel() + state.placeNotification() showWindow.Call(state.window, swShowNoActivate) } else if config.WindowMode == platform.WindowPanel { state.placePanel() @@ -867,7 +868,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { resizes := state.resizeEvents if state.fullscreen.Load() { state.fitFullscreenMonitor() - } else { + } else if !state.placingNotification { setWindowPosition.Call(window, 0, uintptr(bounds.Left), uintptr(bounds.Top), uintptr(bounds.Right-bounds.Left), uintptr(bounds.Bottom-bounds.Top), 0x14) } if state.sizingMove || state.sizing { @@ -1065,6 +1066,14 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { if state.fullscreen.Load() { return htClient } + if state.config.WindowMode == platform.WindowNotification { + point := point{X: int32(int16(second)), Y: int32(int16(second >> 16))} + screenToClient.Call(window, uintptr(unsafe.Pointer(&point))) + if state.pressAt(float32(point.X)/state.scale, float32(point.Y)/state.scale) == platform.PressMove { + return htCaption + } + return htClient + } if state.customFrame() { if code := state.hitTest(int32(int16(second)), int32(int16(second>>16))); code != 0 { return code diff --git a/tools/android/env.sh b/tools/android/env.sh deleted file mode 100644 index 5655ea359..000000000 --- a/tools/android/env.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -# Source this: the Android SDK, NDK and emulator Viva's mobile work uses. -# Paths of this machine go in tools/android/local.sh (git-ignored); the defaults -# are where Homebrew's android-commandlinetools puts them. -here=$(cd "$(dirname "$0")" && pwd) -[ -f "$here/local.sh" ] && . "$here/local.sh" -: "${ANDROID_HOME:=/opt/homebrew/share/android-commandlinetools}" -export ANDROID_HOME ANDROID_SDK_ROOT=$ANDROID_HOME -: "${ANDROID_NDK_HOME:=$(ls -d "$ANDROID_HOME"/ndk/* 2>/dev/null | sort | tail -1)}" -export ANDROID_NDK_HOME -export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$ANDROID_HOME/cmdline-tools/latest/bin:$PATH" -# The virtual device viva run --target android-emu starts. -: "${VIVA_ANDROID_AVD:=viva-api35}" -export VIVA_ANDROID_AVD diff --git a/tools/appbundle/ios_plist.go b/tools/appbundle/ios_plist.go deleted file mode 100644 index 30b685727..000000000 --- a/tools/appbundle/ios_plist.go +++ /dev/null @@ -1,75 +0,0 @@ -package appbundle - -import ( - "bytes" - "encoding/xml" - "fmt" -) - -// IOSInfo is what an iOS application's Info.plist records. An iOS bundle is -// flat: the executable and Info.plist sit side by side in the .app. -type IOSInfo struct { - // Name is the display name (CFBundleName and CFBundleDisplayName). - Name string - // ID is the bundle identifier. - ID string - // Version is both the short version and the build version. - Version string - // Executable is the file name inside the bundle. - Executable string - // MinSystem is MinimumOSVersion. - MinSystem string - // Simulator marks a bundle for the simulator rather than for devices. - Simulator bool -} - -// Plist renders Info.plist as XML, keys in a fixed order so the same IOSInfo -// always gives the same bytes. The application fills the screen, in any -// orientation, on iPhone and iPad. -func (info IOSInfo) Plist() ([]byte, error) { - if info.Name == "" || info.ID == "" || info.Version == "" || info.Executable == "" || info.MinSystem == "" { - return nil, fmt.Errorf("appbundle: name, identifier, version, executable and minimum system are required") - } - platform := "iPhoneOS" - if info.Simulator { - platform = "iPhoneSimulator" - } - var buffer bytes.Buffer - buffer.WriteString(`` + "\n") - buffer.WriteString(`` + "\n") - buffer.WriteString(`` + "\n\n") - text := func(key, value string) { - buffer.WriteString("\t" + key + "\n\t") - xml.EscapeText(&buffer, []byte(value)) - buffer.WriteString("\n") - } - list := func(key string, values ...string) { - buffer.WriteString("\t" + key + "\n\t\n") - for _, value := range values { - buffer.WriteString("\t\t") - xml.EscapeText(&buffer, []byte(value)) - buffer.WriteString("\n") - } - buffer.WriteString("\t\n") - } - text("CFBundleDevelopmentRegion", "en") - text("CFBundleDisplayName", info.Name) - text("CFBundleExecutable", info.Executable) - text("CFBundleIdentifier", info.ID) - text("CFBundleInfoDictionaryVersion", "6.0") - text("CFBundleName", info.Name) - text("CFBundlePackageType", "APPL") - list("CFBundleSupportedPlatforms", platform) - text("CFBundleShortVersionString", info.Version) - text("CFBundleVersion", info.Version) - text("MinimumOSVersion", info.MinSystem) - buffer.WriteString("\tUIDeviceFamily\n\t\n\t\t1\n\t\t2\n\t\n") - buffer.WriteString("\tUILaunchScreen\n\t\n") - list("UISupportedInterfaceOrientations", - "UIInterfaceOrientationPortrait", "UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight") - list("UISupportedInterfaceOrientations~ipad", - "UIInterfaceOrientationPortrait", "UIInterfaceOrientationPortraitUpsideDown", - "UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight") - buffer.WriteString("\n\n") - return buffer.Bytes(), nil -} diff --git a/tools/appbundle/ios_plist_test.go b/tools/appbundle/ios_plist_test.go deleted file mode 100644 index 029a1e473..000000000 --- a/tools/appbundle/ios_plist_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package appbundle - -import ( - "strings" - "testing" -) - -func TestIOSPlistNamesTheApplicationAndItsPlatform(t *testing.T) { - info := IOSInfo{Name: "Notes & Co", ID: "dev.example.notes", Version: "2.0.1", Executable: "notes", MinSystem: "16.0", Simulator: true} - data, err := info.Plist() - if err != nil { - t.Fatal(err) - } - text := string(data) - for _, want := range []string{"dev.example.notes", "2.0.1", "notes", "16.0", "iPhoneSimulator", "Notes & Co"} { - if !strings.Contains(text, want) { - t.Errorf("Info.plist lacks %q", want) - } - } - info.Simulator = false - data, err = info.Plist() - if err != nil { - t.Fatal(err) - } - if text := string(data); !strings.Contains(text, "iPhoneOS") || strings.Contains(text, "iPhoneSimulator") { - t.Error("a device bundle names the simulator platform") - } -} - -func TestIOSPlistIsReproducibleAndNeedsItsFields(t *testing.T) { - info := IOSInfo{Name: "N", ID: "a.b", Version: "1", Executable: "n", MinSystem: "16.0"} - first, _ := info.Plist() - second, _ := info.Plist() - if string(first) != string(second) { - t.Fatal("the same bundle gave different bytes") - } - info.ID = "" - if _, err := info.Plist(); err == nil { - t.Fatal("a bundle with no identifier was accepted") - } -} diff --git a/tools/generate_darwin_shaders.sh b/tools/generate_darwin_shaders.sh index dde64d275..b97d88cd3 100755 --- a/tools/generate_darwin_shaders.sh +++ b/tools/generate_darwin_shaders.sh @@ -24,25 +24,3 @@ xcrun --sdk macosx metallib \ -o "$shader_dir/scene.metallib" unlink "$air" - -# iOS has two: a Metal library records the platform it was built for, and the -# simulator's is not the device's (shader_ios.go picks the one it runs on). -minimum_ios=16.0 - -xcrun --sdk iphoneos metal \ - -mios-version-min="$minimum_ios" \ - -c "$shader_dir/scene.metal" \ - -o "$air" -xcrun --sdk iphoneos metallib \ - "$air" \ - -o "$shader_dir/scene_ios.metallib" -unlink "$air" - -xcrun --sdk iphonesimulator metal \ - -mios-simulator-version-min="$minimum_ios" \ - -c "$shader_dir/scene.metal" \ - -o "$air" -xcrun --sdk iphonesimulator metallib \ - "$air" \ - -o "$shader_dir/scene_ios_simulator.metallib" -unlink "$air" diff --git a/ui/facade.go b/ui/facade.go index 3f4088520..c0d5d57a6 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -107,8 +107,6 @@ func Column(c C) Box { return base.Column(c) } func Stack(c C) Box { return base.Stack(c) } -func SafeArea(c C) Box { return base.SafeArea(c) } - func Divider(c C) Box { return base.Divider(c) } func Spacer(c C) Box { return base.Spacer(c) } diff --git a/ui/menu_paint.go b/ui/menu_paint.go index 9293490e9..da02c8643 100644 --- a/ui/menu_paint.go +++ b/ui/menu_paint.go @@ -42,10 +42,12 @@ func rowExtent(m *MenuItems, i int) float32 { case MenuRowContent, MenuRowPageContent: return row.GetHeight() } + // Both branches size a row by GetRowSize, which RowHeight sets: a dropdown of + // the application's own is asked for the same rows the context menu gets. if m.GetContext() { return components.ContextMenuItemHeight(m.GetF().Palette, contextItem(menuItemRow(m, i)), m.GetRowSize()) } - return components.DropdownMenuItemHeight(m.GetF().Palette, menuItemRow(m, i)) + return components.DropdownMenuItemHeightFor(m.GetF().Palette, menuItemRow(m, i), m.GetRowSize()) } // paintContent calls a content row's painter over its row, inside the menu's clip. @@ -119,8 +121,9 @@ func paintAt(m *MenuItems, Surface *gfx.Canvas, Palette *Theme, bounds Rect, lay } menu := components.BeginDropdownMenu(Surface, *Palette, bounds, components.DropdownMenuOptions{ Layer: layer, Scope: focus, DismissID: dismiss, Viewport: f.GetBounds(), ID: id, - Scroll: &m.Scroll, Side: side, Submenu: m.Parent != nil, + Scroll: &m.Scroll, Side: side, Submenu: m.Parent != nil, RowHeight: m.GetRowSize(), Unpainted: m.GetUnpainted(), PaintPanel: m.GetPanelPainter(), PaintItem: m.GetItemPainter(), + MaxWidth: m.GetWidthMax(), }) for i := range m.Items { switch row := &m.Items[i]; row.Kind { diff --git a/ui/menu_rowheight_gap_test.go b/ui/menu_rowheight_gap_test.go new file mode 100644 index 000000000..941fcb295 --- /dev/null +++ b/ui/menu_rowheight_gap_test.go @@ -0,0 +1,43 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +// A menu opened by a trigger is a dropdown, not a context menu, and its rows stay +// the theme's control height whatever RowHeight asks for. +// +// Two halves of the same gap: +// +// - ui/menu_paint.go's rowExtent reads GetRowSize() only inside `if m.GetContext()` +// (the context menu), and its dropdown branch calls +// components.DropdownMenuItemHeight, which has no row height at all. +// - the dropdown branch of the painter never hands a row height to +// components.DropdownMenuOptions, which has no field to carry one — even though +// the menuSurfaceOptions underneath it has read `rowHeight` all along +// (components/dropdown_menu.go: itemHeight / menuItemHeight). +// +// This is the same request TestContextMenuRowHeightOptionPacksItemsDenser makes of +// a context menu, one menu kind over, which is why it is a fair thing to ask for. +func TestDropdownMenuTakesTheRowHeight(t *testing.T) { + open := true + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + more := ui.Button(c, "More") + ui.Menu(c, more, &open, func(Items *ui.MenuItems) { + Items.RowHeight(24) + Items.Item("One") + Items.Item("Two") + }) + }) + }) + one, two := d.hit("One").Bounds, d.hit("Two").Bounds + if one.Height != 24 { + t.Fatalf("row is %v high, want the 24 RowHeight asked for (a dropdown row keeps the theme's height)", one.Height) + } + if got := two.Y - one.Y; got != 24 { + t.Fatalf("rows are %v apart, want 24", got) + } +} diff --git a/ui/menu_test.go b/ui/menu_test.go index 76bc083a5..44a2465ba 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -480,6 +480,28 @@ func TestMenuWidthRange(t *testing.T) { t.Fatalf("the surface is %v wide, want at most the 160 it was given", got) } }) + t.Run("greatest below default", func(t *testing.T) { + m := &menuOptionsModel{greatest: 112, Label: "A model name that is far too long for a narrow menu"} + d := openPage(t, m.page) + d.click("More") + if got := d.hit(m.Label).Bounds.Width; got > m.greatest { + t.Fatalf("item width = %v, exceeds the menu maximum of %v", got, m.greatest) + } + var menuWidth float32 + for _, hit := range d.driver.Snapshot().Hits { + if hit.Role == gfx.RoleMenu { + menuWidth = hit.Bounds.Width + break + } + } + if menuWidth != m.greatest { + t.Fatalf("menu surface width = %v, want %v", menuWidth, m.greatest) + } + d.click(m.Label) + if m.picked != 1 || m.open { + t.Fatalf("picked=%d open=%v", m.picked, m.open) + } + }) } // Beside opens the menu right of its anchor, its first row level with the anchor @@ -607,12 +629,14 @@ func TestContextMenuAtNamedByAZeroSizeSlotTakesTheArrows(t *testing.T) { // A Content row takes room in the menu and is painted by the caller; the arrows pass over it. func TestMenuContentRow(t *testing.T) { + const maxWidth = 112 m := &menuModel{open: true} painted := gfx.Rect{} d := openPage(t, func(c ui.C) { ui.Column(c).Pad(16).Children(func() { more := ui.Button(c, "More") ui.Menu(c, more, &m.open, func(menu *ui.MenuItems) { + menu.WidthRange(0, maxWidth) menu.Item("One") menu.Content(40, func(Surface *gfx.Canvas, bounds gfx.Rect, Palette gfx.Theme) { painted = bounds @@ -625,6 +649,9 @@ func TestMenuContentRow(t *testing.T) { }) }) one, two := d.hit("One").Bounds, d.hit("Two").Bounds + if painted.Width <= 0 || painted.Width > maxWidth { + t.Fatalf("content width = %v, want a positive width within the menu maximum of %v", painted.Width, maxWidth) + } if painted.Height != 40 || two.Y-one.Y < 40 { t.Fatalf("content %v, rows %v and %v: the row took no room", painted, one, two) } diff --git a/ui/textview/cells.go b/ui/textview/cells.go index 5e6883cf5..f259b9265 100644 --- a/ui/textview/cells.go +++ b/ui/textview/cells.go @@ -1,10 +1,6 @@ package textview -import ( - "unicode/utf8" - - "github.com/vivaui/viva/text" -) +import "github.com/vivaui/viva/text" // tabSize is how many columns a tab stop is apart. const tabSize = 4 @@ -39,17 +35,20 @@ func cellsOf(text string, at int) int { func byteAt(text string, column float32, nearest bool) int { cells := 0 for i := 0; i < len(text); { - r, size := utf8.DecodeRuneInString(text[i:]) - width := runeCells(r, cells) + endByte := nextGrapheme(text, i) + width := cellsOf(text[i:endByte], cells) end := float32(cells + width) if column < end { if nearest && width > 0 && column >= float32(cells)+float32(width)/2 { - return i + size + return endByte } return i } cells += width - i += size + i = endByte } return len(text) } + +// nextGrapheme uses the same boundaries for painting, wrapping and hit testing. +func nextGrapheme(value string, at int) int { return text.NextGraphemeBoundary(value, at) } diff --git a/ui/textview/paint.go b/ui/textview/paint.go index c32cf52e3..456ff3fb6 100644 --- a/ui/textview/paint.go +++ b/ui/textview/paint.go @@ -24,14 +24,18 @@ type painter struct { left float32 y float32 line int + // parts names the links and Button trails, each a part of the view's control, and + // part is how many this paint has named. + parts gfx.Scope + part int // fit is how many cells of the row are drawn before the ellipsis of a line cut short, // and -1 when the row is drawn whole. fit int } // paint draws the rows on screen: the selection behind them, then each row on the -// fixed-pitch grid in its spans' colors. It declares the view's hit again with the text -// cursor, and the links with the hand. +// fixed-pitch grid in its spans' colors. Its links and Button trails are declared as +// parts of the view (see ui.Handlers.Parts), with the hand cursor. func (v *View) paint(dc *ui.DrawContext) { canvas := dc.Canvas src := v.spec.Source @@ -48,10 +52,9 @@ func (v *View) paint(dc *ui.DrawContext) { if v.pressed && v.moved { v.extendTo(v.pointer) } - canvas.HitWithOptions(v.id, v.clip, dc.Label, gfx.HitOptions{Role: gfx.RoleGroup, Cursor: gfx.PointerCursorText}) from, to := v.rowRange() selFrom, selTo, selected := v.Selection.Range(src) - p := &painter{v: v, canvas: canvas, style: v.spec.Font, left: v.rect.X + v.spec.PadX} + p := &painter{v: v, canvas: canvas, style: v.spec.Font, left: v.rect.X + v.spec.PadX, parts: v.input.Parts()} p.style.Mono = true limit := max(int(labelWidth/v.cellW), 1) cols := max(int(math.Ceil(float64((v.clip.X+v.clip.Width-p.left)/v.cellW))), 0) @@ -126,7 +129,7 @@ func (p *painter) trail(n int, t Trail) { p.canvas.Label(t.Text, rect, t.Style) if t.Button { hit := gfx.Rect{X: rect.X, Y: p.y, Width: rect.Width, Height: v.lineH} - p.canvas.HitWithOptions(v.id, hit, t.Text, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand}) + p.canvas.HitWithOptions(p.nextPart(), hit, t.Text, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, SkipTab: true}) v.trails = append(v.trails, trailHit{line: n, rect: hit}) } } @@ -182,7 +185,8 @@ func (v *View) paintSelection(canvas *gfx.Canvas, text string, line, start, end, // row draws the bytes start to end of a line, the columns before cols of it, as labels // of at most limit columns: each character on its cells, in the color of the span it is -// in. A tab or a control character leaves its cells empty; a combining mark is not drawn. +// in. Each non-ASCII grapheme is shaped as one run, including all its marks. A tab or a +// control character leaves its cells empty. func (p *painter) row(text string, start, end, cols, limit int) int { v := p.v span := 0 @@ -192,13 +196,8 @@ func (p *painter) row(text string, start, end, cols, limit int) int { for i := start; i < end; { at := i r, size := utf8.DecodeRuneInString(text[i:]) - i += size - width := runeCells(r, cells) - if width == 0 { - p.flush(text[labelAt:labelTo], label, labelEnd) - label = -1 - continue - } + i = nextGrapheme(text, i) + width := cellsOf(text[at:i], cells) if cells >= cols || p.fit >= 0 && cells+width > cols { p.flush(text[labelAt:labelTo], label, labelEnd) return at @@ -230,13 +229,13 @@ func (p *painter) row(text string, start, end, cols, limit int) int { } } italic := styled && style.Italic - ascii := r < 0x80 + ascii := r < 0x80 && i-at == 1 if ascii && runASCII && run >= 0 && p.runs[run].Color == color && p.runs[run].Weight == weight && p.runs[run].Italic == italic && p.runs[run].Underline == style.Underline && p.runs[run].Strike == style.Strike { - p.runs[run].Bytes += int32(size) + p.runs[run].Bytes += int32(i - at) p.runs[run].Cells += int32(width) } else { - bytes := size + bytes := i - at if invalid { bytes = len(replacementChar) } @@ -258,8 +257,8 @@ func (p *painter) row(text string, start, end, cols, limit int) int { } // decorate fills the backgrounds of a row's spans and declares the hits of its links with -// the hand cursor, named by their text, under the view's own identity so a press on a link -// still selects. +// the hand cursor, named by their text. Each is a part of the view, so a press on a link +// still reaches the view's Pointer and selects. func (p *painter) decorate(text string, start, end int) { v := p.v for _, span := range v.spans { @@ -286,11 +285,19 @@ func (p *painter) decorate(text string, start, end int) { if label == "" { label = text[a:b] } - p.canvas.HitWithOptions(v.id, rect, label, gfx.HitOptions{Role: gfx.RoleLink, Cursor: gfx.PointerCursorHand}) + p.canvas.HitWithOptions(p.nextPart(), rect, label, gfx.HitOptions{Role: gfx.RoleLink, Cursor: gfx.PointerCursorHand, SkipTab: true}) } } } +// nextPart names the next link or Button trail of the paint. They are out of the Tab +// order, so the view is one tab stop however many links it shows, as a console is. +func (p *painter) nextPart() gfx.ID { + id := p.parts.At(p.part) + p.part++ + return id +} + // flush draws the runs gathered for a label from column start to column end and empties // them for the next label. func (p *painter) flush(value string, start, end int) { diff --git a/ui/textview/rows.go b/ui/textview/rows.go index d1d27e174..083266525 100644 --- a/ui/textview/rows.go +++ b/ui/textview/rows.go @@ -57,8 +57,9 @@ func (v *View) trailCells(n int) int { func wrapLine(rows []row, n int, text string, cols int) []row { start, cells, space := 0, 0, -1 for i := 0; i < len(text); { - r, size := utf8.DecodeRuneInString(text[i:]) - width := runeCells(r, cells) + r, _ := utf8.DecodeRuneInString(text[i:]) + endByte := nextGrapheme(text, i) + width := cellsOf(text[i:endByte], cells) if cells+width > cols && cells > 0 { end := i if space > start { @@ -70,7 +71,7 @@ func wrapLine(rows []row, n int, text string, cols int) []row { continue } cells += width - i += size + i = endByte if r == ' ' || r == '\t' { space = i } diff --git a/ui/textview/selection.go b/ui/textview/selection.go index e1aca7f99..86e48e896 100644 --- a/ui/textview/selection.go +++ b/ui/textview/selection.go @@ -11,10 +11,13 @@ import ( "strings" "unicode" "unicode/utf8" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" ) // Point is a place in the text: the number of a line, as the Source numbers it, and a -// byte offset into the line. +// byte offset into the line. Selection points snap to whole grapheme boundaries. type Point struct { Line, Byte int } @@ -199,43 +202,41 @@ func clamp(src Source, p Point) Point { return Point{p.Line, boundary(src.Line(p.Line), p.Byte)} } -// boundary moves at into text and back to the start of the character it is inside. +// boundary keeps a base and its marks, an emoji sequence or a conjunct together. func boundary(text string, at int) int { - at = min(max(at, 0), len(text)) - for at > 0 && at < len(text) && !utf8.RuneStart(text[at]) { - at-- - } - return at + return gfx.GraphemeStart(text, at) } // wordAt is the word, the run of spaces or the run of punctuation under the character // at at, as a double click in a code editor selects it. At the end of the text // it is the one before. -func wordAt(text string, at int) (int, int) { - if text == "" { +func wordAt(value string, at int) (int, int) { + if value == "" { return 0, 0 } - if at >= len(text) { - _, size := utf8.DecodeLastRuneInString(text) - at = len(text) - size + if at >= len(value) { + at = text.PreviousGraphemeBoundary(value, len(value)) + } else { + at = boundary(value, at) } - r, _ := utf8.DecodeRuneInString(text[at:]) + r, _ := utf8.DecodeRuneInString(value[at:]) class := charClass(r) from := at for from > 0 { - r, size := utf8.DecodeLastRuneInString(text[:from]) + previous := text.PreviousGraphemeBoundary(value, from) + r, _ := utf8.DecodeRuneInString(value[previous:]) if charClass(r) != class { break } - from -= size + from = previous } to := at - for to < len(text) { - r, size := utf8.DecodeRuneInString(text[to:]) + for to < len(value) { + r, _ := utf8.DecodeRuneInString(value[to:]) if charClass(r) != class { break } - to += size + to = nextGrapheme(value, to) } return from, to } diff --git a/ui/textview/selection_test.go b/ui/textview/selection_test.go index b58878da2..a43d207ba 100644 --- a/ui/textview/selection_test.go +++ b/ui/textview/selection_test.go @@ -175,3 +175,36 @@ func TestWrapLineBreaksAfterASpaceOrAtTheLimit(t *testing.T) { t.Fatalf("an empty line has rows %+v, want one empty row", rows) } } + +func TestGraphemesStayWholeInSelectionAndWrapping(t *testing.T) { + for _, cluster := range []string{"e\u0301", "👩‍💻", "🇨🇳", "क्ष"} { + t.Run(cluster, func(t *testing.T) { + for at := 1; at < len(cluster); at++ { + if got := boundary(cluster, at); got != 0 { + t.Errorf("boundary at byte %d splits %q at %d", at, cluster, got) + } + } + width := float32(cellsOf(cluster, 0)) + if got := byteAt(cluster, width*0.75, true); got != len(cluster) { + t.Errorf("nearest boundary is byte %d, want the end %d of %q", got, len(cluster), cluster) + } + if got := byteAt(cluster, width*0.75, false); got != 0 { + t.Errorf("the character under the pointer starts at byte %d, want 0", got) + } + line := "x" + cluster + "z" + rows := wrapLine(nil, 0, line, 1) + if len(rows) != 3 || line[rows[0].from:rows[0].to] != "x" || + line[rows[1].from:rows[1].to] != cluster || line[rows[2].from:rows[2].to] != "z" { + t.Errorf("wrapping %q into one-cell rows split its character: %+v", line, rows) + } + }) + } + for _, word := range []string{"cafe\u0301", "👩‍💻", "क्ष"} { + line := word + " next" + var selection Selection + selection.Begin(Point{0, len(word) - 1}, line, 2) + if got := selection.Text(Strings{line}); got != word { + t.Errorf("double clicking %q selected %q", word, got) + } + } +} diff --git a/ui/textview/view.go b/ui/textview/view.go index 44d494dbb..8b4469025 100644 --- a/ui/textview/view.go +++ b/ui/textview/view.go @@ -95,7 +95,8 @@ type View struct { spec Spec input ui.Handlers draw func(*ui.DrawContext) - id gfx.ID + // id names the control the text is drawn in; its links and trails are its parts. + id gfx.ID // rect is the control as the last paint placed it and clip the part of it on screen; // cellW and lineH are the grid it was drawn on, width the text width it wrapped at, @@ -223,7 +224,7 @@ func (v *View) PointOf(p Point) (gfx.Point, bool) { } _, from, _ := v.rowBytes(index) text := src.Line(p.Line) - at := min(max(p.Byte, from), len(text)) + at := boundary(text, min(max(p.Byte, from), len(text))) x := v.rect.X + v.spec.PadX + (float32(cellsOf(text[from:at], 0))+0.25)*v.cellW y := v.rect.Y + v.spec.PadY + (float32(index)+0.5)*v.lineH if y < v.clip.Y || y >= v.clip.Y+v.clip.Height { @@ -243,8 +244,8 @@ func (v *View) Visible() (int, int) { return v.rowLine(from), v.rowLine(max(to-1, from)) + 1 } -// Declare declares the view with spec and returns its outermost box: the scrolling area, -// or the text itself. +// Declare declares the view with spec and returns its outermost box: the scrolling area +// or the container sized to its text. func (v *View) Declare(c ui.C, spec Spec) ui.Box { v.spec = spec if v.draw == nil { @@ -278,21 +279,21 @@ func (v *View) Declare(c ui.C, spec Spec) ui.Box { } height = max(height, state.Viewport) outer.Children(func() { - v.id = ui.ID(c.Part("text")) - control = ui.Control(c.Part("text"), spec.Label, &v.input).FillWidth().Height(height).Draw(v.draw) + control = v.control(c, spec.Label).FillWidth().Height(height) }) } else if spec.Wrap { // The rows depend on the width, which the page knows only once it lays the view // out: the layout wraps the lines there, before it asks for the height. v.wrap.v = v outer = ui.CustomLayout(c, &v.wrap).FillWidth().Children(func() { - v.id = ui.ID(c.Part("text")) - control = ui.Control(c.Part("text"), spec.Label, &v.input).Draw(v.draw) + control = v.control(c, spec.Label) }) } else { - v.id = ui.ID(c.Part("text")) - control = ui.Control(c.Part("text"), spec.Label, &v.input).FillWidth().Height(height).Draw(v.draw) - outer = control + // Parts belong to one instance, including when the view has no scroll or wrap + // container. This also consumes a Key the caller gave this view. + outer = ui.Column(c).FillWidth().Height(height).Children(func() { + control = v.control(c, spec.Label).Fill() + }) } if control.Shortcut(ui.Primary, "c") && v.Has() { text, copy := v.Text(), spec.Copy @@ -308,11 +309,19 @@ func (v *View) Declare(c ui.C, spec Spec) ui.Box { v.SelectAll() } if spec.Menu != nil { - ui.ContextMenuAt(c.Key("menu"), control, &v.menuOpen, v.menuAt, spec.Menu) + ui.ContextMenuAt(c, control, &v.menuOpen, v.menuAt, spec.Menu) } return outer } +// control declares the control the text is drawn in, with the text cursor over it. +func (v *View) control(c ui.C, label string) ui.Box { + v.id = ui.ID(c.Part("text")) + return ui.Control(c.Part("text"), label, &v.input). + HitWith(v.id, label, gfx.HitOptions{Role: gfx.RoleGroup, Cursor: gfx.PointerCursorText}). + Draw(v.draw) +} + // wrapLayout lays out a view that wraps: the text takes the width it is given and is as // tall as its rows at that width. type wrapLayout struct{ v *View } @@ -382,6 +391,9 @@ func (v *View) onPointer(event gfx.PointerEvent) gfx.EventResult { at := gfx.Point{X: event.X, Y: event.Y} switch event.Kind { case gfx.PointerDown: + // The press focuses what it lands on, a link or a trail too; the keyboard + // goes back to the view, where the selection's keys are. + took := gfx.EventResult{Handled: true, Repaint: true, Focus: v.id} if event.Button == gfx.PointerButtonSecondary { if v.spec.Menu == nil { return gfx.EventResult{} @@ -391,7 +403,7 @@ func (v *View) onPointer(event gfx.PointerEvent) gfx.EventResult { v.menuLine, v.menuSet = p.Line, true } v.menuOpen, v.menuAt = true, at - return gfx.EventResult{Handled: true, Repaint: true} + return took } if event.Button != gfx.PointerButtonPrimary { return gfx.EventResult{} @@ -399,13 +411,13 @@ func (v *View) onPointer(event gfx.PointerEvent) gfx.EventResult { if n, ok := v.trailAt(at); ok { // A press on a button after a line presses it, and leaves the selection be. v.trailHeld, v.trailLine = true, n - return gfx.EventResult{Handled: true} + return gfx.EventResult{Handled: true, Focus: v.id} } v.pressed, v.moved, v.press, v.pointer, v.clicks = true, false, at, at, max(event.ClickCount, 1) p, ok := v.pointAt(at, v.clicks == 1) if !ok { v.Selection.Clear() - return gfx.EventResult{Handled: true, Repaint: true} + return took } if event.Modifiers&gfx.ModifierShift != 0 && v.clicks == 1 { v.Selection.Extend(p, src.Line(p.Line)) @@ -413,7 +425,7 @@ func (v *View) onPointer(event gfx.PointerEvent) gfx.EventResult { } else { v.Selection.Begin(p, src.Line(p.Line), v.clicks) } - return gfx.EventResult{Handled: true, Repaint: true} + return took case gfx.PointerMove: if !v.pressed { return gfx.EventResult{Handled: v.trailHeld, Repaint: v.hoverAt(at)} diff --git a/ui/textview/view_test.go b/ui/textview/view_test.go index 9df71e453..7fb44f735 100644 --- a/ui/textview/view_test.go +++ b/ui/textview/view_test.go @@ -194,6 +194,73 @@ func TestALinkOpensOnAClickAndSelectsOnADrag(t *testing.T) { } } +// Each link and each Button trail is a node of its own for assistive technology, a part +// of the view's control: no two nodes share an identity, and a press on a part still +// reaches the view. The text shows the text cursor, a link the hand. +func TestLinksAndTrailsAreNodesOfTheirOwn(t *testing.T) { + o := openOutput(t, "\tat demo.Main.run(Main.java:12)", "\tat demo.Main.main(Main.java:12)", "done") + o.link = "Main.java:12" + o.trail = 2 + o.must(o.driver.Paint()) + seen := map[gfx.ID]string{} + var view gfx.ID + roles := map[gfx.Role]int{} + for _, node := range o.driver.Accessibility() { + if node.ID.IsZero() { + continue + } + if other, ok := seen[node.ID]; ok { + t.Fatalf("%q and %q share the identity %v", other, node.Label, node.ID) + } + seen[node.ID] = node.Label + roles[node.Role]++ + if node.Role == gfx.RoleGroup && node.Label == "Output" { + view = node.ID + } + } + if roles[gfx.RoleLink] != 2 || roles[gfx.RoleButton] != 1 || view.IsZero() { + t.Fatalf("the nodes are %v, want the view, two links and a button", seen) + } + x, y := o.at(1, strings.Index(o.lines[1], o.link)+2) + part, ok := o.driver.HitTest(x, y) + if !ok || part == view { + t.Fatalf("the link is hit as %v, want a part of the view %v", part, view) + } + o.must(o.driver.Move(x, y)) + if got := o.driver.Snapshot().Cursor; got != app.CursorHand { + t.Fatalf("over the link the cursor is %v, want the hand", got) + } + x, y = o.at(2, 1) + o.must(o.driver.Move(x, y)) + if got := o.driver.Snapshot().Cursor; got != app.CursorText { + t.Fatalf("over the text the cursor is %v, want the text cursor", got) + } +} + +// A press on a link focuses the view, not the link, so the keys of the selection work +// after it: Primary+C copies what a drag from the link selected, Escape clears it and +// Primary+A selects everything. +func TestTheKeysStayWithTheViewAfterAPressOnALink(t *testing.T) { + o := openOutput(t, "\tat demo.Main.run(Main.java:12)", "done") + o.link = "Main.java:12" + o.must(o.driver.Paint()) + from := strings.Index(o.lines[0], o.link) + o.drag(0, from+2, 0, from+len("Main.java")) + if got, want := o.copyShortcut(), "in.java"; got != want { + t.Fatalf("after a drag from the link Primary+C copied %q, want %q", got, want) + } + o.must(o.driver.Key(gfx.KeyEscape, 0)) + if o.view.Has() { + t.Fatalf("after a press on the link Escape kept %q selected", o.view.Text()) + } + x, y := o.at(0, from+2) + o.must(o.driver.Click(x, y)) + o.chord('a') + if got, want := o.copyShortcut(), "\tat demo.Main.run(Main.java:12)\ndone"; got != want { + t.Fatalf("after a click on the link Primary+A then Primary+C copied %q, want %q", got, want) + } +} + // A Button trail is pressed by a click, and is never part of what is selected or copied. func TestATrailIsPressedButNeverCopied(t *testing.T) { o := openOutput(t, "Receiving objects", "done") @@ -226,6 +293,149 @@ func TestCopyGoesThroughTheSpecHook(t *testing.T) { } } +func TestSiblingViewsKeepTheirInputSeparate(t *testing.T) { + var views [2]textview.View + lines := [2]string{"first output", "second output"} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Children(func() { + for i := range views { + views[i].Declare(c, textview.Spec{ + Label: lines[i], Source: textview.Strings{lines[i]}, + Font: gfx.TextStyle{Size: 13}, LineHeight: 18, + }) + } + }) + }}) + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 640, Height: 320}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + must(driver.Paint()) + for _, i := range []int{1, 0} { + at, ok := views[i].PointOf(textview.Point{Line: 0, Byte: 2}) + if !ok { + t.Fatalf("view %d is not on screen", i) + } + must(driver.DoubleClick(at.X, at.Y)) + if got, want := views[i].Text(), strings.Fields(lines[i])[0]; got != want { + t.Fatalf("double clicking view %d selected %q, want %q", i, got, want) + } + _, err := driver.ShortcutChord(keymap.Primary, 'a') + must(err) + _, err = driver.ShortcutChord(keymap.Primary, 'c') + must(err) + must(driver.Paint()) + if got := driver.Clipboard(); got != lines[i] { + t.Fatalf("copy in view %d got %q, want %q", i, got, lines[i]) + } + must(driver.Key(gfx.KeyEscape, 0)) + if views[0].Has() || views[1].Has() { + t.Fatal("input in one view left a selection in its sibling") + } + } + seen := map[gfx.ID]string{} + for _, node := range driver.Accessibility() { + if node.ID.IsZero() { + continue + } + if other, ok := seen[node.ID]; ok { + t.Fatalf("%q and %q share the identity %v", other, node.Label, node.ID) + } + seen[node.ID] = node.Label + } +} + +func TestClosedMenusLeaveTheNextSiblingsIdentityAlone(t *testing.T) { + var views [2]textview.View + pressed := -1 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Children(func() { + for i := range views { + views[i].Declare(c, textview.Spec{ + Label: "Output", Source: textview.Strings{"first", "second"}, Scroll: true, + Font: gfx.TextStyle{Size: 13}, LineHeight: 18, + Menu: func(menu *ui.MenuItems) { + if menu.Item("Copy line").Clicked() { + pressed = i + } + }, + }).Height(80) + } + ui.Button(c, "After the views") + }) + }}) + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 640, Height: 320}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + must(driver.Paint()) + for i := range views { + at, ok := views[i].PointOf(textview.Point{Line: 1}) + if !ok { + t.Fatalf("view %d is not on screen", i) + } + must(driver.ClickButton(at.X, at.Y, gfx.PointerButtonSecondary)) + if line, ok := views[i].MenuLine(); !ok || line != 1 { + t.Fatalf("view %d opened the menu on line %d (%v), want 1", i, line, ok) + } + hit := trailHit(t, driver, "Copy line") + must(driver.Click(hit.Bounds.X+hit.Bounds.Width/2, hit.Bounds.Y+hit.Bounds.Height/2)) + if pressed != i { + t.Fatalf("view %d's menu pressed view %d", i, pressed) + } + must(driver.Paint()) + } +} + +func TestPaintAndCopyKeepGraphemesWhole(t *testing.T) { + for _, test := range []struct{ line, word string }{ + {"cafe\u0301", "cafe\u0301"}, {"a👩‍💻b", "👩‍💻"}, {"a🇨🇳b", "🇨🇳"}, {"क्ष", "क्ष"}, {"\u0301x", ""}, + } { + line := test.line + t.Run(line, func(t *testing.T) { + o := openOutput(t, line) + var drawn strings.Builder + for _, label := range o.driver.Snapshot().Labels { + drawn.WriteString(label.Value) + end := 0 + for _, run := range label.Runs { + end += int(run.Bytes) + if gfx.GraphemeStart(label.Value, end) != end { + t.Fatalf("run ending at %d splits a grapheme of %q", end, label.Value) + } + } + if end != len(label.Value) { + t.Fatalf("runs hold %d bytes of %q", end, label.Value) + } + } + if got := drawn.String(); got != line { + t.Fatalf("paint drew %q, want the complete text %q", got, line) + } + if test.word != "" { + x, y := o.at(0, 1) + o.must(o.driver.DoubleClick(x, y)) + if got := o.copyShortcut(); got != test.word { + t.Fatalf("double clicking %q copied %q, want %q", line, got, test.word) + } + } + }) + } +} + func trailHit(t *testing.T, driver *app.Driver, label string) gfx.Hit { t.Helper() for _, hit := range driver.Snapshot().Hits { diff --git a/ui/textview/visual_test.go b/ui/textview/visual_test.go new file mode 100644 index 000000000..c7144b029 --- /dev/null +++ b/ui/textview/visual_test.go @@ -0,0 +1,114 @@ +//go:build vivahead && (darwin || windows || linux) + +package textview_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/textview" +) + +// TestVisualCapture is an opt-in frame for reviewing the same textview states in +// both themes. VIVA_TEXTVIEW_SHOTS names the output directory. +func TestVisualCapture(t *testing.T) { + dir := os.Getenv("VIVA_TEXTVIEW_SHOTS") + if dir == "" { + t.Skip("set VIVA_TEXTVIEW_SHOTS to capture textview frames") + } + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + for _, dark := range []bool{false, true} { + name, theme := "light", ui.LightTheme() + if dark { + name, theme = "dark", ui.DarkTheme() + } + for _, siblings := range []bool{false, true} { + scene := "unicode" + if siblings { + scene = "siblings-menu" + } + t.Run(name+"/"+scene, func(t *testing.T) { + var views [4]textview.View + page := ui.NewPage(ui.PageConfig{Theme: &theme, View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + if !siblings { + ui.Text(c, "Selectable text / 可选择文本").Bold() + views[0].Declare(c, textview.Spec{ + Label: "Unicode output", Source: textview.Strings{ + "Combining accent: cafe\u0301", + "Emoji sequence: a👩‍💻b", + "Flag: a🇨🇳b", + "Indic conjunct: क्ष", + "中文输出:选择并复制完整字符。", + }, + Font: gfx.TextStyle{Size: 22, Color: theme.Foreground}, + LineHeight: 46, Selection: theme.Selection, + }) + return + } + ui.Text(c, "Sibling views / 同级视图").Bold() + for i, line := range []string{"First plain output / 第一段", "Second plain output / 第二段"} { + views[i].Declare(c, textview.Spec{ + Label: line, Source: textview.Strings{line}, + Font: gfx.TextStyle{Size: 17, Color: theme.Foreground}, + LineHeight: 32, Selection: theme.Selection, + }) + } + for i := 2; i < len(views); i++ { + views[i].Declare(c, textview.Spec{ + Label: []string{"First scroll output", "Second scroll output"}[i-2], + Source: textview.Strings{"Process output / 程序输出", "Context menu target / 菜单目标"}, + Font: gfx.TextStyle{Size: 17, Color: theme.Foreground}, + LineHeight: 30, Scroll: true, Selection: theme.Selection, + Menu: func(menu *ui.MenuItems) { menu.Item("Copy line / 复制行") }, + }).Height(68) + } + ui.Button(c, "After the views / 后续按钮") + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{ + Title: "Textview", Width: 800, Height: 420, WindowMode: app.WindowFrameless, + }), nil, headless.Options{Scale: 2, Strict: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + if siblings { + at, ok := views[1].PointOf(textview.Point{Byte: 2}) + if !ok { + t.Fatal("second plain view is not on screen") + } + if err := session.DoubleClick(at.X, at.Y); err != nil { + t.Fatal(err) + } + if got := views[1].Text(); got != "Second" { + t.Fatalf("second view selected %q, want Second", got) + } + at, ok = views[3].PointOf(textview.Point{Line: 1, Byte: 2}) + if !ok { + t.Fatal("second scroll view is not on screen") + } + if err := session.RightClick(at.X, at.Y); err != nil { + t.Fatal(err) + } + if line, ok := views[3].MenuLine(); !ok || line != 1 { + t.Fatalf("menu targets line %d (%v), want 1", line, ok) + } + } + if err := session.CheckStrict(); err != nil { + t.Fatal(err) + } + if err := session.Screenshot(filepath.Join(dir, scene+"-"+name+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index 8a824e527..db6f605dd 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -25,10 +25,12 @@ A theme is a value, `gfx.LightTheme()` or `gfx.DarkTheme()`. Switching appearanc A page control for a heavy or stateful component lives in its own package under `ui/`. Import it only when the page uses it; the package is the pay-for-use boundary. -- Editors and visuals: `ui/textview`, `ui/codeeditor`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid` +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid` - Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard` - Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup` +`ui/textview` displays read-only text that the user can select and copy, such as logs and process output. Keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`; `textview.Strings` adapts a string slice. The caller owns the lines, styles and actions. The view owns selection and drawing without an editing or undo model. + The package name is the capability, never a `view` suffix, and its state type is named by role: `calendar.State`, `message.Row`, `attachment.Card`. Keep locals out of the package name (`cal`, `msg`, `pic`); a model field may keep the noun (`m.calendar`) because a selector never shadows a package. Some packages expose `pkg.View(c, label, &state)` (`calendar.View`, `markdown.View`); others expose a method on the state (`avatar.New().View(c, label)`, `questionnaire.New().View(c, label)`). `go doc github.com/vivaui/viva/ui/` shows which. diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index 617782031..c544bac8e 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -25,10 +25,12 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") 重功能或有状态的页面控件放在 `ui/<能力名>` 的独立包里。用到才 import;包本身就是按需付费的边界。 -- 编辑器与可视化:`ui/textview`, `ui/codeeditor`、`ui/chart`、`ui/markdown`、`ui/image`、`ui/calendar`、`ui/carousel`、`ui/columnresize`、`ui/reordergrid` +- 编辑器与可视化:`ui/codeeditor`、`ui/textview`、`ui/chart`、`ui/markdown`、`ui/image`、`ui/calendar`、`ui/carousel`、`ui/columnresize`、`ui/reordergrid` - 导航与浮层:`ui/command`、`ui/menubar`、`ui/navigationmenu`、`ui/sidebar`、`ui/hovercard` - 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup` +`ui/textview` 用来显示可选择、可复制的只读文本,例如日志和进程输出。在 model 中保留 `textview.View`,调用 `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`;`textview.Strings` 可以把字符串切片适配成数据源。调用方拥有文本、样式和动作,视图负责选择与绘制,不带编辑或撤销模型。 + 包名是能力名,没有 `view` 后缀;状态类型按角色命名,不重复包名:`calendar.State`、`message.Row`、`attachment.Card`。局部变量避让包名(`cal`、`msg`、`pic`);model 字段可以保留领域名词(`m.calendar`),因为选择器不会遮蔽包。 有些包暴露 `pkg.View(c, label, &state)`(`calendar.View`、`markdown.View`),有些则是状态上的方法(`avatar.New().View(c, label)`、`questionnaire.New().View(c, label)`)。用 `go doc github.com/vivaui/viva/ui/` 查看具体形式。