diff --git a/README.md b/README.md index 5d3be502..94826fbe 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,8 @@ platform's own bundle. Requirements: Go 1.26 or newer (viva fetches it when missing). On macOS the Xcode command-line tools, because Viva reaches Cocoa and Metal through cgo; on Linux, X11 with the system XCB, -Pango and Cairo libraries, and a Vulkan loader and driver for GPU acceleration +Pango and Cairo libraries (the opt-in GTK 3 shell, `-tags vivagtk`, is a native +Wayland client and needs the system's GTK 3), and a Vulkan loader and driver for GPU acceleration (a machine without them draws on the CPU); on Windows, Win32 with Direct3D 11 and DirectWrite. Viva loads the system libraries at runtime and bundles none of them. diff --git a/README.zh-CN.md b/README.zh-CN.md index 12e0b871..81204f69 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -32,7 +32,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st `viva init` 会写一个可直接运行的项目:一个窗口、一个不用打开窗口就能驱动它的测试、`viva.toml`,以及一份描述编程模型的 `AGENTS.md`。`viva build` 把发布程序写到 `build/`,`viva package` 写出平台自己的包。 -环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal;Linux 上需要带系统 XCB、Pango 和 Cairo 库的 X11,Vulkan 加载库和驱动用于 GPU 加速,缺失时窗口用 CPU 渲染;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 +环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal;Linux 上需要带系统 XCB、Pango 和 Cairo 库的 X11(可选的 GTK 3 外壳用 `-tags vivagtk` 构建,是原生 Wayland 客户端,需要系统的 GTK 3),Vulkan 加载库和驱动用于 GPU 加速,缺失时窗口用 CPU 渲染;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 当前版本是 `v0.6.6`;要固定版本就写明(`@v0.6.6`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 diff --git a/app/drag_files.go b/app/drag_files.go new file mode 100644 index 00000000..06342f77 --- /dev/null +++ b/app/drag_files.go @@ -0,0 +1,85 @@ +package app + +import ( + "errors" + "fmt" + "path/filepath" + "strings" + + "github.com/vivaui/viva/internal/platform" +) + +// FileDragEffect is what letting go of dragged files does to them where they +// land: a copy leaves them where they were, a move hands them to the target, and +// a link leaves a reference to them behind. The values are the OLE DROPEFFECT +// flags Windows reports and asks for, so one value is also the mask of the +// effects a drag offers. +type FileDragEffect = platform.DragEffect + +const ( + // FileDragNone is what a drag that ended nowhere, or that the user + // cancelled, reports. + FileDragNone FileDragEffect = platform.DragEffectNone + // FileDragCopy copies the files; the ones dragged out stay where they are. + FileDragCopy FileDragEffect = platform.DragEffectCopy + // FileDragMove moves the files to where they land. + FileDragMove FileDragEffect = platform.DragEffectMove + // FileDragLink puts a link to the files where they land. + FileDragLink FileDragEffect = platform.DragEffectLink +) + +// MaxDragFiles is the most paths one drag takes; a longer list is an error +// rather than a silent cut. It is the bound a clipboard read uses too, and for +// the same reason: it limits what a huge selection can make an application hold. +const MaxDragFiles = platform.MaxClipboardFiles + +// StartFileDrag takes paths out of the application's window, as dragging a file +// from a file manager to another window does. The drag lasts until the pointer +// is released or the user presses Escape, and the effect the target took is +// returned — FileDragNone when it took nothing, which is also what a cancelled +// drag reports. An error wrapping ErrUnsupported means this target cannot drag +// files out of a window at all, and the application should offer them some other +// way (SetClipboardFiles tells the user something else, a copy). +// +// allowed is the mask of effects the application offers: a target takes at most +// one of them, and only those. Windows reports the effect the drop performed, +// and a target that claims one the application never offered counts as taking +// nothing. +// +// The files are not read here, and nothing is copied when the drag starts: a +// target that takes a copy or a move reads the paths while the drop happens, so +// the files must still be where they are when the user lets go. The paths must be +// absolute and free of NUL, and at most MaxDragFiles are accepted. +// +// Windows starts an OLE drag (IDropSource and IDataObject, DoDragDrop), so it is +// called on the event-loop thread, from the handler of the pointer event that +// starts the drag, and does not return until the drag has ended; the drag's own +// message loop dispatches the messages that arrive meanwhile, so a handler can +// be reentered by one. macOS needs an NSDraggingSession and Linux the XDND +// protocol as a source, and neither adapter binds them yet; the Web target has +// no DOM DataTransfer behind a canvas. Those three return an error wrapping +// ErrUnsupported. +func StartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { + if len(paths) == 0 { + return FileDragNone, fmt.Errorf("app: no files to drag out of the window") + } + if len(paths) > MaxDragFiles { + return FileDragNone, fmt.Errorf("app: a drag takes at most %d files", MaxDragFiles) + } + if allowed == FileDragNone || !platform.DragEffectKnown(allowed) { + return FileDragNone, fmt.Errorf("app: a drag of files offers FileDragCopy, FileDragMove or FileDragLink") + } + for index, path := range paths { + if path == "" || strings.IndexByte(path, 0) >= 0 || !filepath.IsAbs(path) { + return FileDragNone, fmt.Errorf("app: dragged file %d is not an absolute path: %q", index, path) + } + } + if effect, err, handled := driverStartFileDrag(paths, allowed); handled { + return effect, err + } + effect, err := nativeStartFileDrag(paths, allowed) + if errors.Is(err, platform.ErrDragUnsupported) { + return FileDragNone, fmt.Errorf("%w: %v", ErrUnsupported, err) + } + return effect, err +} diff --git a/app/drag_files_test.go b/app/drag_files_test.go new file mode 100644 index 00000000..660660a0 --- /dev/null +++ b/app/drag_files_test.go @@ -0,0 +1,64 @@ +//go:build darwin || windows || linux + +package app + +import ( + "path/filepath" + "slices" + "testing" +) + +func TestStartFileDragOfADriverRun(t *testing.T) { + driver := newFilesDriver(t) + want := []string{filepath.Join(t.TempDir(), "report.pdf"), filepath.Join(t.TempDir(), "文件夹")} + effect, err := StartFileDrag(want, FileDragCopy|FileDragMove) + if err != nil { + t.Fatal(err) + } + // A folder window that may copy takes the copy, as DropEffect prefers, and + // the driver's target does the same. + if effect != FileDragCopy { + t.Fatalf("the drag took effect %d, want a copy", effect) + } + got, taken := driver.DraggedFiles() + if !slices.Equal(got, want) || taken != FileDragCopy { + t.Fatalf("the driver's drag = %q taking %d, want %q taking a copy", got, taken, want) + } + want[0] = "changed" + if again, _ := driver.DraggedFiles(); again[0] != got[0] { + t.Fatal("a caller changed the driver's drag through the slice it was given") + } + + // An application that offers no copy is taken at its word. + if effect, err := StartFileDrag(got, FileDragMove|FileDragLink); err != nil || effect != FileDragLink { + t.Fatalf("a drag offering a link and a move took %d, %v", effect, err) + } + if effect, err := StartFileDrag(got, FileDragMove); err != nil || effect != FileDragMove { + t.Fatalf("a drag offering only a move took %d, %v", effect, err) + } +} + +func TestStartFileDragRefusesWhatItCannotDrag(t *testing.T) { + newFilesDriver(t) + if _, err := StartFileDrag(nil, FileDragCopy); err == nil { + t.Fatal("a drag of no files was accepted") + } + if _, err := StartFileDrag([]string{"relative.txt"}, FileDragCopy); err == nil { + t.Fatal("a relative path was accepted") + } + // A drag that offers no effect cannot end anywhere. + if _, err := StartFileDrag([]string{filepath.Join(t.TempDir(), "one.txt")}, FileDragNone); err == nil { + t.Fatal("a drag offering no effect was accepted") + } + if _, err := StartFileDrag([]string{filepath.Join(t.TempDir(), "one.txt")}, FileDragEffect(8)); err == nil { + t.Fatal("a drag offering an effect this platform does not name was accepted") + } + dir := t.TempDir() + paths := make([]string, MaxDragFiles+1) + for index := range paths { + paths[index] = filepath.Join(dir, "f") + } + if _, err := StartFileDrag(paths, FileDragCopy); err == nil { + t.Fatal("a drag of more files than it takes was accepted") + } +} diff --git a/app/driver_system.go b/app/driver_system.go index 640cf64d..ad9d8f90 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -33,6 +33,12 @@ type driverSystem struct { schemes []string // the URL schemes SetSchemeHandlers declared as registered sleepMu sync.Mutex sleep map[string]int // sleep-prevention reasons this run holds, with their counts + // dragFiles and dragAllowed are what the application last asked to drag out + // of a driver-backed window, and dragTaken is the effect the driver's target + // took from them; see driverStartFileDrag. + dragFiles []string + dragAllowed platform.DragEffect + dragTaken platform.DragEffect } type driverSaveFileResponse struct { @@ -130,6 +136,29 @@ func driverSetClipboardFiles(paths []string) (error, bool) { return nil, true } +// driverStartFileDrag answers a drag of files out of a driver-backed run: the +// driver records what the application asked and takes the effect a folder window +// takes, with no native drag and no pointer to move. +func driverStartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error, bool) { + system := activeDriverSystem.Load() + if system == nil { + return platform.DragEffectNone, nil, false + } + taken := platform.DragEffectOf(allowed, platform.DragEffect(platform.DropEffect(true, uint32(allowed)))) + system.dragFiles, system.dragAllowed, system.dragTaken = append([]string(nil), paths...), allowed, taken + return taken, nil, true +} + +// DraggedFiles is the files the application last asked to drag out of the +// driver's window, and the effect the driver's target took from them. That +// target behaves like a folder window: it takes a copy when the application +// offers one, then a link, then a move, and takes nothing when the application +// offers nothing or the drag ends without a drop. The slice is the driver's own; +// do not modify it. +func (driver *Driver) DraggedFiles() ([]string, FileDragEffect) { + return driver.system.dragFiles, driver.system.dragTaken +} + // driverSetClipboardHTML answers the rich copy of a driver-backed run: the // driver's private clipboard holds html beside alt as its text, the shape the // native paste paths already read, and anything else copied clears both. diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index 6ea68a8f..9b693860 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -2,6 +2,8 @@ package app +import "github.com/vivaui/viva/internal/platform" + func markNonNativeSystemUsed() {} func driverClipboardText() (string, error, bool) { return "", nil, false } @@ -22,6 +24,10 @@ func driverClipboardFiles() (paths []string, err error, handled bool) { return n func driverSetClipboardFiles([]string) (error, bool) { return nil, false } +func driverStartFileDrag([]string, platform.DragEffect) (platform.DragEffect, error, bool) { + return platform.DragEffectNone, nil, false +} + func driverSetClipboardHTML(string, string) (error, bool) { return nil, false } func driverSendNotification(Notification) (error, bool) { return nil, false } diff --git a/app/launch.go b/app/launch.go index 7c6644de..f2622881 100644 --- a/app/launch.go +++ b/app/launch.go @@ -72,7 +72,8 @@ func (application *Application) OnOpenURL(handler func(url string)) { // on the event-loop thread, also for documents that arrived while the // application was starting. Call it from the startup callback. // -// macOS delivers documents to the running program. Windows and Linux start the +// macOS delivers documents to the running program, as a path even when the +// system handed the document over as a file URL. Windows and Linux start the // program with the path as an argument instead; package app/singleinstance // carries it to the running copy, and the program reads it from its arguments // at launch. Where the system delivers nothing, the handler is never called. diff --git a/app/system_darwin.go b/app/system_darwin.go index af9f33c3..120ed41c 100644 --- a/app/system_darwin.go +++ b/app/system_darwin.go @@ -20,6 +20,10 @@ func nativeClipboardFiles() ([]string, error) { return darwinplatform.ClipboardF func nativeSetClipboardFiles(paths []string) error { return darwinplatform.SetClipboardFiles(paths) } +func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { + return darwinplatform.StartFileDrag(paths, allowed) +} + func nativeReduceMotion() bool { return darwinplatform.ReduceMotion() } // nativeTextEngine is the platform's text engine; nil keeps the reference metrics. diff --git a/app/system_js.go b/app/system_js.go index 212a75e8..ca4b2ff8 100644 --- a/app/system_js.go +++ b/app/system_js.go @@ -39,6 +39,10 @@ func nativeClipboardFiles() ([]string, error) { return nil, ErrUnsupported } func nativeSetClipboardFiles([]string) error { return ErrUnsupported } +func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { + return webplatform.StartFileDrag(paths, allowed) +} + func nativeClipboardImagePNG() ([]byte, error) { return nil, webSystemError("read clipboard image", webplatform.ClipboardImagePNG()) } diff --git a/app/system_linux.go b/app/system_linux.go index 76012fcd..ac1f0a51 100644 --- a/app/system_linux.go +++ b/app/system_linux.go @@ -44,6 +44,11 @@ func nativeSetClipboardFiles(paths []string) error { return linuxSystemError(linuxplatform.SetClipboardFiles(paths)) } +func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { + effect, err := linuxplatform.StartFileDrag(paths, allowed) + return effect, linuxSystemError(err) +} + func nativeClipboardImagePNG() ([]byte, error) { png, err := linuxplatform.ClipboardImagePNG() return png, linuxSystemError(err) diff --git a/app/system_unsupported.go b/app/system_unsupported.go index 28bfb0bc..a1cde86a 100644 --- a/app/system_unsupported.go +++ b/app/system_unsupported.go @@ -47,3 +47,10 @@ func nativeAppearance() Appearance { return AppearanceUnknown } func nativeWatchAppearance() {} func nativeSetAppearance(Appearance) {} + +// nativeStartFileDrag is the Web-independent fallback: a target with neither a +// window the platform can drag from nor the Web's own drag has no way to take +// files out of one. +func nativeStartFileDrag([]string, FileDragEffect) (FileDragEffect, error) { + return FileDragNone, ErrUnsupported +} diff --git a/app/system_windows.go b/app/system_windows.go index ccfb273e..92f4bfba 100644 --- a/app/system_windows.go +++ b/app/system_windows.go @@ -17,6 +17,10 @@ func nativeClipboardFiles() ([]string, error) { return windowsplatform.Clipboard func nativeSetClipboardFiles(paths []string) error { return windowsplatform.SetClipboardFiles(paths) } +func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { + return windowsplatform.StartFileDrag(paths, allowed) +} + func nativeReduceMotion() bool { return windowsplatform.ReduceMotion() } // nativeTextEngine is the platform's text engine; nil keeps the reference metrics. diff --git a/base/accessors.go b/base/accessors.go index a966ad8a..3b911882 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -57,6 +57,9 @@ func (x *ColorPickerState) GetHexEditor() text.Editor { return x.hexEditor } // GetInvalid reads the invalid of ColorPickerState for the styled painting layer. func (x *ColorPickerState) GetInvalid() bool { return x.invalid } +// GetLayer reads the layer of ColorPickerState for the styled painting layer. +func (x *ColorPickerState) GetLayer() uint16 { return x.layer } + // GetLayout reads the layout of ColorPickerState for the styled painting layer. func (x *ColorPickerState) GetLayout() ColorPickerLayout { return x.layout } diff --git a/base/color.go b/base/color.go index b77f9399..ab19c51e 100644 --- a/base/color.go +++ b/base/color.go @@ -67,8 +67,12 @@ type ColorPickerState struct { invalid bool handlers Handlers layout ColorPickerLayout - target *Color - Bound bool + // layer is where the panel paints: the layer the picker was declared on, plus + // two, captured then so a picker inside a Dialog's body keeps its panel over + // the dialog rather than under the page the dialog covers. + layer uint16 + target *Color + Bound bool } // Open reports whether the picker's panel is open. @@ -134,6 +138,7 @@ func colorPicker(c C, ID gfx.ID, s *ColorPickerState, Color *Color, Label string ID = p.ControlID(pkControl) } s.target = Color + s.layer = c.f.WidgetLayer() + 2 if !s.Bound { s.hex.Bind(&s.hexEditor) s.handlers.Key, s.handlers.Pointer = s.key, s.pointer diff --git a/base/paint.go b/base/paint.go index e289abbb..77767984 100644 --- a/base/paint.go +++ b/base/paint.go @@ -44,6 +44,9 @@ func (f *Frame) PaintChild(i int32) { r := n.Rect canvas := f.Surface extra := &f.Exts[n.Ext] + if s := extra.scrollState; s != nil && canvas != nil { + s.scope = canvas.FocusScope() + } style := f.resolve(n, extra) // What the element is drawn with fades with it and with what it is inside; the // controls inside it are painted with a theme faded the same way. diff --git a/base/scroll.go b/base/scroll.go index 09e062a4..35e72113 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -29,6 +29,9 @@ import ( // ViewportWidth are its horizontal Offset, Content and Viewport, MaxX and ScrollToX its // Max and ScrollTo. In any other area OffsetX is 0 and ContentWidth is ViewportWidth. type ScrollState struct { + // scope is the focus scope the area was last painted in. While a focus trap + // is up, a wheel reaches only the areas in that scope, as a press does. + scope gfx.ID Offset float32 Content float32 // the height of everything inside, as of the last layout Viewport float32 // the height of the area itself, less its padding @@ -320,12 +323,21 @@ func (View *View) Wheel(event gfx.ScrollEvent) gfx.EventResult { } func (f *Frame) wheelArea(panel int32, event gfx.ScrollEvent) (result gfx.EventResult, manual bool) { + // A focus trap covers the areas painted outside its scope: the pointer does not + // reach them, so neither does the wheel, however they lie under the pointer. + trap := gfx.ID{} + if f.Surface != nil { + trap = f.Surface.TrappedFocusScope() + } first := int(max(panel, 0)) // what a panel holds is declared after its root for i := len(f.Nodes) - 1; i >= first; i-- { n := &f.Nodes[i] if n.Ext == 0 || f.Exts[n.Ext].scrollState == nil { continue } + if !trap.IsZero() && f.Exts[n.Ext].scrollState.scope != trap { + continue + } if !f.ContainsPoint(i, event.X, event.Y) || !f.within(int32(i), panel) { continue } diff --git a/components/select.go b/components/select.go index 7ea6f3b2..3c19a791 100644 --- a/components/select.go +++ b/components/select.go @@ -92,6 +92,10 @@ const ( selectIconGap = 8 ) +// SelectIconSpan is the room an icon takes before a select's value or an +// option's label: the icon and the gap after it. +const SelectIconSpan = selectIconSize + selectIconGap + // selectTriggerSize is the height of a trigger and the type step of its value. // Only the extra-small step changes the type, as in Button: a compact control // keeps the body size and just gets shorter. @@ -301,8 +305,8 @@ func (selectControl Select) paintTrigger() { inset := selectControl.theme.Metrics.TextInsetX() textX, textWidth := bounds.X+inset, bounds.Width-inset-chevronSpan-6 if paintSelectIcon(canvas, options.Icon, options.IconImage, options.IconText, gfx.Rect{X: textX, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, foreground, selectControl.textSize) { - textX += selectIconSize + selectIconGap - textWidth -= selectIconSize + selectIconGap + textX += SelectIconSpan + textWidth -= SelectIconSpan } canvas.Label(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.textSize, Weight: gfx.WeightRegular, Color: foreground, @@ -331,8 +335,8 @@ func (selectControl *Select) paintItem(bounds gfx.Rect, item SelectItem) { foreground := look.Foreground textX, textWidth := bounds.X+8, bounds.Width-40 if paintSelectIcon(selectControl.canvas, item.Icon, item.IconImage, item.IconText, gfx.Rect{X: textX, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, foreground, selectControl.theme.Metrics.FontSizeM) { - textX += selectIconSize + selectIconGap - textWidth -= selectIconSize + selectIconGap + textX += SelectIconSpan + textWidth -= SelectIconSpan } selectControl.canvas.Label(item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, diff --git a/docs/conformance.md b/docs/conformance.md index dcfe5588..b97b6982 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -93,7 +93,7 @@ mistakes an absence for an oversight. Items marked *measured* were tried or size | Gap | Platform | Reason | | --- | --- | --- | -| Native Wayland | Linux | Only XCB is spoken; a Wayland session runs through XWayland. A second window system, input stack and frame is a project of its own. | +| Native Wayland in the default build | Linux | Only XCB is spoken, so a Wayland session runs through XWayland; speaking Wayland directly — a window system, input stack and frame of Viva's own — is a project of its own. The opt-in GTK 3 shell (`-tags vivagtk`, see [Platforms](../website/content/guides/en/platforms.md)) is a native Wayland client instead: GTK owns the window, the seat and the input method, and Viva draws into a subsurface. | | Smooth scrolling (`Precise`) | Linux | It needs XInput2 valuators, and a window that selects XI2 events stops receiving the core pointer events, so the whole pointer path would move. The test machine's Xvnc has no scroll valuator, so the code could not be verified; none was added. | | Text Services Framework | Windows | IMM32 is used (candidate placement, reconversion, clause styling). TSF means implementing `ITextStoreACP`; not done. | | Toast notifications | Windows | They need a Start-menu shortcut carrying an AppUserModelID, and NSIS cannot write that property without a plugin. A balloon is shown instead. The process AppUserModelID is set only when the application sets `Config.Class`, so a pinned shortcut and its window group together. | @@ -115,6 +115,11 @@ X11 with software Vulkan. macOS is arm64; Intel Macs, their GPUs, IME and text rasterization are not part of that matrix. The Linux machine's software renderer is evidence for behavior, not for GPU performance. +The scenarios run against the default XCB build. The GTK 3 shell is vetted and +tested with `-tags vivagtk`: its contracts and the GTK input-method path run under +X11 in CI, and its Wayland-only paths — the subsurface, the seat and the input +regions — run in the text-input workflow against a nested weston compositor. + ## Machines without a GPU A window needs a graphics driver, not a GPU. Windows falls back to WARP, Direct3D's diff --git a/docs/system-integrations.md b/docs/system-integrations.md index b790a7f9..259d9583 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -13,6 +13,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Column-selection clipboard (`SetRectangularClipboardText`, `ClipboardTextWithFormat`; `TextInput.CopyRectangular`, `TextEvent.Rectangular`) | no platform format; reads report `false` | Unicode text beside `MSDEVColumnSelect` (presence) and `Borland IDE Block Type` (one byte, `0x02`); an advertised marker whose data cannot be read is pasted as stream text | reads report `false` | reads report `false` | | Rich copy (`SetClipboardHTML`, html + plain alt) | `NSPasteboard`: `public.html` beside `public.utf8-plain-text` | registered `HTML Format` (CF_HTML, with its header of byte offsets) beside `CF_UNICODETEXT` | X11 `CLIPBOARD`: `text/html` target beside `UTF8_STRING`; the GTK shell serves the same pair through `gtk_clipboard_set_with_data` | synchronous calls return `ErrAsyncRequired`; `SetClipboardHTMLAsync` writes one `ClipboardItem` with both MIME flavours and needs a user gesture | | Copied files (`ClipboardFiles`, returns `[]string`) | the pasteboard's file URLs, file reference URLs resolved to paths; promised files have no path and are not listed | the `CF_HDROP` list (UTF-16 form) | X11 `CLIPBOARD`: `x-special/gnome-copied-files` (Nautilus, Nemo, Caja, Thunar) or `text/uri-list` (Dolphin, most toolkits); the GTK shell asks GTK for `text/uri-list` | `ErrUnsupported` | +| Dragging files out (`StartFileDrag`, returns `FileDragEffect`) | `ErrUnsupported`: needs an `NSDraggingSession`, which the adapter does not bind yet | an OLE drag: an `IDataObject` offering the paths as `CF_HDROP` and an `IDropSource` that ends the drag when the pointer is released and cancels it on Escape, run by `DoDragDrop` on the window's event-loop thread. `SetClipboardFiles` is the copy a paste makes, not this | `ErrUnsupported`: needs XDND as a source, which the adapter does not speak yet | `ErrUnsupported`: a canvas has no DOM `DataTransfer` | | Primary selection (`SetPrimarySelection`, `PrimarySelection`) | `ErrUnsupported` | `ErrUnsupported` | X11 `PRIMARY`: selected text, pasted with a middle click | `ErrUnsupported` | | Cursor shape | AppKit cursor; wait unsupported, diagonal resize requires macOS 15 | Win32 system cursors; running window required | XCB cursor font; running window required | CSS cursor on `documentElement` | | Open files | `NSOpenPanel` | `IFileOpenDialog` | the desktop portal's `FileChooser` over D-Bus; installed `zenity` or `kdialog` without one | synchronous call returns `ErrAsyncRequired`; `OpenFilesAsync` returns `FileRef` values, using File System Access or an `` fallback | diff --git a/gfx/canvas.go b/gfx/canvas.go index 64f79a6e..5e9ee044 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -1843,6 +1843,10 @@ func (canvas *Canvas) TrapFocus(scope ID) { } } +// FocusScope returns the focus scope the next paint primitive is declared in, or +// zero outside any scope. +func (canvas *Canvas) FocusScope() ID { return canvas.currentFocusScope() } + // TrappedFocusScope returns the top-most active focus trap. func (canvas *Canvas) TrappedFocusScope() ID { return canvas.trappedScope diff --git a/gfx/path.go b/gfx/path.go index f96dfc8b..655d5672 100644 --- a/gfx/path.go +++ b/gfx/path.go @@ -434,7 +434,7 @@ func (canvas *Canvas) strokeContourOverlapping(points []Point, closed bool, half intoFirst := direction(points[1], first) outLast := direction(points[count-2], last) canvas.appendCapGeometry(first, intoFirst, half, cap, color) - canvas.appendCapGeometry(last, negate(outLast), half, cap, color) + canvas.appendCapGeometry(last, outLast, half, cap, color) } } diff --git a/gfx/square_cap_test.go b/gfx/square_cap_test.go new file mode 100644 index 00000000..3e8effeb --- /dev/null +++ b/gfx/square_cap_test.go @@ -0,0 +1,84 @@ +package gfx + +import ( + "math" + "testing" +) + +// pathInkBounds returns the box that the triangles of an open path cover. +func pathInkBounds(t *testing.T, path Path, style PathStyle) Rect { + t.Helper() + var canvas Canvas + canvas.DrawPath(path, Rect{Width: 32, Height: 32}, style) + triangles := canvas.Triangles() + if len(triangles) == 0 { + t.Fatal("the path painted no geometry") + } + minX, minY := float32(math.Inf(1)), float32(math.Inf(1)) + maxX, maxY := float32(math.Inf(-1)), float32(math.Inf(-1)) + for _, triangle := range triangles { + for _, p := range triangle.Points { + minX = min(minX, p.X) + minY = min(minY, p.Y) + maxX = max(maxX, p.X) + maxY = max(maxY, p.Y) + } + } + return Rect{X: minX, Y: minY, Width: maxX - minX, Height: maxY - minY} +} + +// A square cap extends the stroke by half its width past the endpoint, at both +// ends of an open contour. Only the first end used to grow: the second end was +// given the negated outward direction, which put its square inside the stroke +// instead of past it. A round cap hid that, because a disc does not care which +// way it faces. +func TestSquareCapGrowsPastBothEndpoints(t *testing.T) { + const ( + width = float32(4) + half = width / 2 + x0 = float32(8) + x1 = float32(24) + middle = float32(16) + ) + path := NewPath(32, 32, + PathCommand{Kind: PathCommandMove, Point: Point{X: x0, Y: middle}}, + PathCommand{Kind: PathCommandLine, Point: Point{X: x1, Y: middle}}, + ) + bounds := pathInkBounds(t, path, PathStyle{ + Stroke: Color{Alpha: 1}, + StrokeWidth: width, + Cap: CapSquare, + }) + if got, want := bounds.X, x0-half; math.Abs(float64(got-want)) > 1e-3 { + t.Errorf("the square cap does not extend past the start: ink starts at %v, want %v", got, want) + } + if got, want := bounds.X+bounds.Width, x1+half; math.Abs(float64(got-want)) > 1e-3 { + t.Errorf("the square cap does not extend past the end: ink ends at %v, want %v", got, want) + } +} + +// The same contour with a butt cap ends exactly at the endpoints, which pins the +// measurement above: the difference is the cap, not the stroke width. +func TestButtCapEndsAtBothEndpoints(t *testing.T) { + const ( + width = float32(4) + x0 = float32(8) + x1 = float32(24) + middle = float32(16) + ) + path := NewPath(32, 32, + PathCommand{Kind: PathCommandMove, Point: Point{X: x0, Y: middle}}, + PathCommand{Kind: PathCommandLine, Point: Point{X: x1, Y: middle}}, + ) + bounds := pathInkBounds(t, path, PathStyle{ + Stroke: Color{Alpha: 1}, + StrokeWidth: width, + Cap: CapButt, + }) + if got, want := bounds.X, x0; math.Abs(float64(got-want)) > 1e-3 { + t.Errorf("the butt cap should start at the endpoint: ink starts at %v, want %v", got, want) + } + if got, want := bounds.X+bounds.Width, x1; math.Abs(float64(got-want)) > 1e-3 { + t.Errorf("the butt cap should end at the endpoint: ink ends at %v, want %v", got, want) + } +} diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index de788876..a2f0836e 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -1281,7 +1281,9 @@ func rectangleUpdateError(status int) error { //export vivaOpenURL func vivaOpenURL(url *C.char) { - deliverOpenURL(C.GoString(url)) + if url != nil { + routeOpenURL(C.GoString(url)) + } } //export vivaApplicationQuitRequested diff --git a/internal/platform/darwin/drag_darwin.go b/internal/platform/darwin/drag_darwin.go new file mode 100644 index 00000000..2b8f77bb --- /dev/null +++ b/internal/platform/darwin/drag_darwin.go @@ -0,0 +1,20 @@ +//go:build darwin + +package darwin + +import ( + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +// StartFileDrag cannot offer files from a window on macOS yet. A drag out of a +// window is a dragging session: the view under the pointer starts an +// NSDraggingSession whose pasteboard items are file URLs, and the session's +// dragging source reports where it ended and with which operation. This adapter +// binds the view and the general pasteboard, but neither NSDraggingSession nor +// NSDraggingSource is bound, so the window can offer its files only by copying +// them (see SetClipboardFiles), which is a different promise to the user. +func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error) { + return platform.DragEffectNone, fmt.Errorf("%w: macOS drags files out with an NSDraggingSession, which this adapter does not bind", platform.ErrDragUnsupported) +} diff --git a/internal/platform/darwin/label_invalid_utf8_vivahead_test.go b/internal/platform/darwin/label_invalid_utf8_vivahead_test.go new file mode 100644 index 00000000..a71256d9 --- /dev/null +++ b/internal/platform/darwin/label_invalid_utf8_vivahead_test.go @@ -0,0 +1,22 @@ +//go:build darwin && vivahead + +package darwin + +import "testing" + +// A label whose name is not valid UTF-8 (a remote Linux file name, Latin-1 é here) must not +// fail the offscreen update: the window keeps drawing, the label shows the replacement. +func TestLabelWithInvalidUTF8NameUpdates(t *testing.T) { + offscreen, err := NewOffscreen(160, 32, 1, Color{Alpha: 1}) + if err != nil { + t.Skipf("no Metal device: %v", err) + } + defer offscreen.Close() + label := TextLabel{Value: "caf\xe9.txt", X: 0, Y: 0, Width: 160, Height: 16, FontSize: 12} + if err := offscreen.Set(nil, []TextLabel{label}, nil); err != nil { + t.Fatalf("Set with invalid UTF-8 label: %v", err) + } + if _, _, _, err := offscreen.Render(); err != nil { + t.Fatalf("Render after invalid UTF-8 label: %v", err) + } +} diff --git a/internal/platform/darwin/native_label_text_darwin_test.go b/internal/platform/darwin/native_label_text_darwin_test.go new file mode 100644 index 00000000..13eb8a25 --- /dev/null +++ b/internal/platform/darwin/native_label_text_darwin_test.go @@ -0,0 +1,72 @@ +//go:build darwin + +package darwin + +import ( + "reflect" + "testing" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" +) + +// A remote file name in another encoding is not UTF-8; the native layer must still get text +// it can decode, and the run byte counts must follow the replacement. +func TestNativeLabelTextReplacesInvalidUTF8(t *testing.T) { + for _, test := range []struct { + name string + value string + runs []gfx.TextRun + want string + count []int32 + }{ + { + name: "no runs", + value: "caf\xe9.txt", + want: "caf\uFFFD.txt", + }, + { + name: "runs follow the replaced byte", + value: "caf\xe9.txt", + runs: []gfx.TextRun{{Bytes: 4}, {Bytes: 4}}, + want: "caf\uFFFD.txt", + count: []int32{6, 4}, + }, + { + name: "runs past the end are clamped", + value: "a\xffb", + runs: []gfx.TextRun{{Bytes: 2}, {Bytes: 100}}, + want: "a\uFFFDb", + count: []int32{4, 1}, + }, + } { + t.Run(test.name, func(t *testing.T) { + got, counts := nativeLabelText(test.value, test.runs) + if got != test.want { + t.Fatalf("text = %q, want %q", got, test.want) + } + if !utf8.ValidString(got) { + t.Fatalf("text %q is not valid UTF-8", got) + } + if len(counts) != len(test.count) || len(counts) > 0 && !reflect.DeepEqual(counts, test.count) { + t.Fatalf("run counts = %v, want %v", counts, test.count) + } + }) + } +} + +// Valid text is the common case on every redraw of every label: it must pass through +// unchanged and without allocating. +func TestNativeLabelTextKeepsValidTextWithoutAllocating(t *testing.T) { + value := "Viva 原生界面 👩‍💻" + runs := []gfx.TextRun{{Bytes: 4}} + allocs := testing.AllocsPerRun(100, func() { + got, counts := nativeLabelText(value, runs) + if got != value || counts != nil { + t.Fatalf("valid text changed: %q, counts %v", got, counts) + } + }) + if allocs != 0 { + t.Fatalf("valid text allocated %v times per call, want 0", allocs) + } +} diff --git a/internal/platform/darwin/open_url_darwin.go b/internal/platform/darwin/open_url_darwin.go index 078a49cb..052eb6ac 100644 --- a/internal/platform/darwin/open_url_darwin.go +++ b/internal/platform/darwin/open_url_darwin.go @@ -2,7 +2,11 @@ package darwin -import "sync" +import ( + "net/url" + "strings" + "sync" +) // Links the system opens the application with arrive on the event-loop thread, // possibly before the application has said what to do with them (a launch by @@ -29,6 +33,35 @@ func deliverOpenURL(url string) { handler(url) } +// routeOpenURL sends what the system handed over as a URL to the handler that +// owns it. AppKit delivers a document the application was opened with through +// the URL callback as a file URL, so file URLs become the paths the open-file +// handler expects; only other schemes reach the link handler. +func routeOpenURL(text string) { + if path, ok := fileURLPath(text); ok { + deliverOpenFile(path) + return + } + deliverOpenURL(text) +} + +// fileURLPath is the filesystem path a file URL names. A URL with a host other +// than localhost names a file on another machine, which this system cannot open +// by path. +func fileURLPath(text string) (string, bool) { + parsed, err := url.Parse(text) + if err != nil || !strings.EqualFold(parsed.Scheme, "file") || parsed.Opaque != "" { + return "", false + } + if parsed.Host != "" && !strings.EqualFold(parsed.Host, "localhost") { + return "", false + } + if parsed.Path == "" || parsed.Path == "/" { + return "", false + } + return parsed.Path, true +} + // SetOpenURLHandler sets who receives the links the system opens this // application with, and delivers any that arrived first. It runs on the // event-loop thread. diff --git a/internal/platform/darwin/open_url_darwin_test.go b/internal/platform/darwin/open_url_darwin_test.go index 4cd0fbf1..af35e53d 100644 --- a/internal/platform/darwin/open_url_darwin_test.go +++ b/internal/platform/darwin/open_url_darwin_test.go @@ -21,3 +21,55 @@ func TestLinksThatArriveBeforeTheHandlerAreDeliveredWhenItIsSet(t *testing.T) { } application.SetOpenURLHandler(nil) } + +// The system hands a document the application was opened with to the URL +// callback as a file URL; it has to reach the document handler as a path, while +// a registered scheme still goes to the link handler. +func TestFileURLsReachTheDocumentHandler(t *testing.T) { + openFiles.Lock() + openFiles.handler, openFiles.pending = nil, nil + openFiles.Unlock() + openURLs.Lock() + openURLs.handler, openURLs.pending = nil, nil + openURLs.Unlock() + application := &nativeApplication{} + var files, links []string + application.SetOpenFileHandler(func(path string) { files = append(files, path) }) + application.SetOpenURLHandler(func(url string) { links = append(links, url) }) + t.Cleanup(func() { + application.SetOpenFileHandler(nil) + application.SetOpenURLHandler(nil) + }) + + routeOpenURL("file:///Users/me/My%20Notes.md") + routeOpenURL("ssh://root@example.com:2222") + routeOpenURL("file://localhost/Users/me/runbook.markdown") + + if want := []string{"/Users/me/My Notes.md", "/Users/me/runbook.markdown"}; !reflect.DeepEqual(files, want) { + t.Fatalf("documents = %q, want %q", files, want) + } + if want := []string{"ssh://root@example.com:2222"}; !reflect.DeepEqual(links, want) { + t.Fatalf("links = %q, want %q", links, want) + } +} + +func TestFileURLPathNeedsALocalFile(t *testing.T) { + for _, test := range []struct { + url string + path string + ok bool + }{ + {"file:///tmp/notes.md", "/tmp/notes.md", true}, + {"file://localhost/tmp/notes.md", "/tmp/notes.md", true}, + {"file:///tmp/with%20space.md", "/tmp/with space.md", true}, + {"file://server/share/notes.md", "", false}, + {"file:///", "", false}, + {"ssh://host", "", false}, + {"notes.md", "", false}, + } { + path, ok := fileURLPath(test.url) + if path != test.path || ok != test.ok { + t.Fatalf("fileURLPath(%q) = %q, %v; want %q, %v", test.url, path, ok, test.path, test.ok) + } + } +} diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 88470ea0..a0fa9fc7 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -15,6 +15,7 @@ import ( "fmt" "runtime/cgo" "sync/atomic" + "unicode/utf8" "unsafe" "github.com/vivaui/viva/gfx" @@ -676,7 +677,8 @@ func makeNativeTextLabels(labels []TextLabel) (unsafe.Pointer, []unsafe.Pointer, if label.Width <= 0 || label.Height <= 0 || !bitmap && label.FontSize <= 0 { continue } - value := textBytes(label.Value) + content, runBytes := nativeLabelText(label.Value, label.Runs) + value := textBytes(content) if value != nil { strings = append(strings, value) } @@ -692,9 +694,13 @@ func makeNativeTextLabels(labels []TextLabel) (unsafe.Pointer, []unsafe.Pointer, strings = append(strings, runMemory) packed := unsafe.Slice((*C.viva_text_run)(runMemory), len(label.Runs)) for at, run := range label.Runs { + bytes := run.Bytes + if runBytes != nil { + bytes = runBytes[at] + } packed[at] = C.viva_text_run{ column: C.uint32_t(max(run.Column, 0)), - bytes: C.uint32_t(max(run.Bytes, 0)), + bytes: C.uint32_t(max(bytes, 0)), cells: C.uint32_t(max(run.Cells, 0)), flags: C.uint32_t(textRunFlags(run)), weight: C.float(run.Weight), @@ -736,7 +742,7 @@ func makeNativeTextLabels(labels []TextLabel) (unsafe.Pointer, []unsafe.Pointer, } native[validCount] = C.viva_text_label{ utf8: (*C.uchar)(value), - utf8_length: C.size_t(len(label.Value)), + utf8_length: C.size_t(len(content)), x: C.float(label.X), y: C.float(label.Y), width: C.float(label.Width), @@ -915,6 +921,55 @@ func textBytes(value string) unsafe.Pointer { return C.CBytes([]byte(value)) } +// nativeLabelText returns the text a label gives the native layer, which decodes +// it as UTF-8 and fails the whole label update on a byte it cannot decode. A +// file name stored in another encoding on a remote host is such text. Each +// invalid byte becomes U+FFFD, as the platform text system substitutes it, so +// the label still draws and the rest of the window keeps updating. +// +// runBytes is the byte count of each run in the returned text, because a +// replacement changes the length of the bytes it stands for. It is nil when +// the text was already valid, and then the runs keep their own counts. +func nativeLabelText(value string, runs []gfx.TextRun) (string, []int32) { + if utf8.ValidString(value) { + return value, nil + } + // bounds holds the end of each run in value, clamped to its length, so the + // runs cover value in order and never past it. + bounds := make([]int, len(runs)) + end := 0 + for index, run := range runs { + end = min(end+int(max(run.Bytes, 0)), len(value)) + bounds[index] = end + } + ends := make([]int, len(runs)) + out := make([]byte, 0, len(value)+len(runs)) + next := 0 + for position := 0; position < len(value); { + for next < len(runs) && bounds[next] <= position { + ends[next] = len(out) + next++ + } + decoded, size := utf8.DecodeRuneInString(value[position:]) + if decoded == utf8.RuneError && size == 1 { + out = utf8.AppendRune(out, utf8.RuneError) + } else { + out = append(out, value[position:position+size]...) + } + position += size + } + for ; next < len(runs); next++ { + ends[next] = len(out) + } + counts := make([]int32, len(runs)) + previous := 0 + for index, at := range ends { + counts[index] = int32(at - previous) + previous = at + } + return string(out), counts +} + func boolInt(value bool) int { if value { return 1 diff --git a/internal/platform/drag.go b/internal/platform/drag.go new file mode 100644 index 00000000..5774af78 --- /dev/null +++ b/internal/platform/drag.go @@ -0,0 +1,37 @@ +package platform + +import "errors" + +// ErrDragUnsupported reports that this target has no way to take files out of a +// window by dragging them: the application can still offer the files, but only +// by copying them (see SetClipboardFiles), which tells the user something else. +// The Web target has no drag of its own to start, macOS needs a dragging session +// and Linux a drag-and-drop protocol, and neither is bound yet. +var ErrDragUnsupported = errors.New("dragging files out of a window is unsupported") + +// DragEffect is what letting go of dragged files does to them where they land: a +// copy leaves them where they were, a move hands them to the target, and a link +// leaves a reference behind. The values are the OLE DROPEFFECT flags Windows +// reports and asks for, so one value is also the mask of the effects an +// operation allows. +type DragEffect uint32 + +const ( + // DragEffectNone is what a drag that ended nowhere, or that the user + // cancelled with Escape, reports. + DragEffectNone DragEffect = 0 + // DragEffectCopy copies the files; the ones dragged out stay where they are. + DragEffectCopy DragEffect = 1 + // DragEffectMove moves the files to where they land. + DragEffectMove DragEffect = 2 + // DragEffectLink puts a link to the files where they land. + DragEffectLink DragEffect = 4 + + // dragEffects is every effect named here. + dragEffects = DragEffectCopy | DragEffectMove | DragEffectLink +) + +// DragEffectKnown reports whether every effect in a mask is one this package +// names, so that an operation asking for an effect no platform understands is +// refused instead of having the bits silently dropped. +func DragEffectKnown(mask DragEffect) bool { return mask&^dragEffects == 0 } diff --git a/internal/platform/linux/drag_linux.go b/internal/platform/linux/drag_linux.go new file mode 100644 index 00000000..5c77760f --- /dev/null +++ b/internal/platform/linux/drag_linux.go @@ -0,0 +1,20 @@ +//go:build linux + +package linux + +import ( + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +// StartFileDrag cannot offer files from a window on Linux yet. Dragging out is +// the XDND protocol from the source's side: the window becomes the source, +// offers the paths as text/uri-list on the XdndSelection, answers the target's +// XdndStatus and the conversion requests while the drag lasts, and finishes it +// when the pointer is released. This adapter speaks XDND as a target only (see +// drop_linux.go), so the window can offer its files only by copying them (see +// SetClipboardFiles), which is a different promise to the user. +func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error) { + return platform.DragEffectNone, fmt.Errorf("%w: the X11 adapter takes XDND drops but does not offer them", platform.ErrDragUnsupported) +} diff --git a/internal/platform/web/drag_js.go b/internal/platform/web/drag_js.go new file mode 100644 index 00000000..678b0e08 --- /dev/null +++ b/internal/platform/web/drag_js.go @@ -0,0 +1,19 @@ +//go:build js && wasm + +package web + +import ( + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +// StartFileDrag cannot offer files from the page. A browser drags files out of a +// dragstart handler that puts them on the event's DataTransfer, which is a DOM +// object the page's own script builds and the browser takes over; the canvas this +// adapter paints into has no DataTransfer, and a canvas drag reaches the browser +// as a drag of pixels, not of files. So the page can offer its files only by +// copying them (see SetClipboardFiles), which is a different promise to the user. +func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error) { + return platform.DragEffectNone, fmt.Errorf("%w: a browser drags files from a DOM DataTransfer a canvas does not have", platform.ErrDragUnsupported) +} diff --git a/internal/platform/win32_drag.go b/internal/platform/win32_drag.go new file mode 100644 index 00000000..7c982494 --- /dev/null +++ b/internal/platform/win32_drag.go @@ -0,0 +1,22 @@ +package platform + +// DragEffectOf is what a drag of files reports once it has ended: the effect the +// target took, when the source allowed that one, and none otherwise. Files that +// went nowhere are none, as are files a target claimed to take by an effect the +// source never offered. +// +// Windows documents one effect for a drop, but a target that answers with more +// is taken as taking the first of them the source allows, in the order +// DropEffect prefers: a copy, then a link, then a move. +func DragEffectOf(allowed, reported DragEffect) DragEffect { + taken := reported & allowed + switch { + case taken&DragEffectCopy != 0: + return DragEffectCopy + case taken&DragEffectLink != 0: + return DragEffectLink + case taken&DragEffectMove != 0: + return DragEffectMove + } + return DragEffectNone +} diff --git a/internal/platform/win32_drag_test.go b/internal/platform/win32_drag_test.go new file mode 100644 index 00000000..7afef2ac --- /dev/null +++ b/internal/platform/win32_drag_test.go @@ -0,0 +1,41 @@ +package platform + +import "testing" + +func TestDragEffectOfReportsOnlyTheEffectsTheSourceOffered(t *testing.T) { + for _, test := range []struct { + allowed DragEffect + reported DragEffect + want DragEffect + }{ + {DragEffectCopy | DragEffectMove, DragEffectCopy, DragEffectCopy}, + {DragEffectCopy | DragEffectMove, DragEffectMove, DragEffectMove}, + {DragEffectCopy, DragEffectMove, DragEffectNone}, // a target cannot take what was not offered + {DragEffectCopy | DragEffectMove, DragEffectNone, DragEffectNone}, // the drag ended nowhere + {DragEffectNone, DragEffectCopy, DragEffectNone}, + {DragEffectCopy | DragEffectLink, DragEffectCopy | DragEffectLink, DragEffectCopy}, + {DragEffectMove | DragEffectLink, DragEffectCopy | DragEffectMove | DragEffectLink, DragEffectLink}, + {DragEffectCopy | DragEffectMove, DragEffectCopy | DragEffectMove, DragEffectCopy}, + } { + if got := DragEffectOf(test.allowed, test.reported); got != test.want { + t.Errorf("DragEffectOf(%d, %d) = %d, want %d", test.allowed, test.reported, got, test.want) + } + } +} + +func TestADragOffersAtLeastOneKnownEffect(t *testing.T) { + for _, test := range []struct { + mask DragEffect + known bool + }{ + {DragEffectCopy, true}, + {DragEffectCopy | DragEffectMove | DragEffectLink, true}, + {DragEffectNone, true}, + {8, false}, // a bit no platform understands + {1 | 16, false}, + } { + if got := DragEffectKnown(test.mask); got != test.known { + t.Errorf("DragEffectKnown(%d) = %v, want %v", test.mask, got, test.known) + } + } +} diff --git a/internal/platform/windows/drag_windows.go b/internal/platform/windows/drag_windows.go new file mode 100644 index 00000000..f68b6c9c --- /dev/null +++ b/internal/platform/windows/drag_windows.go @@ -0,0 +1,451 @@ +//go:build windows + +package windows + +import ( + "fmt" + "runtime" + "sync" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// Dragging files out of a window is the other half of drop_windows.go: there the +// shell owns a drag and asks the window, here the window owns one and asks the +// shell. Windows has one call for it, DoDragDrop, and it needs two COM objects +// from the application: an IDataObject that hands out the files, and an IDropSource +// that says what ends the drag and which cursors it shows. Both are built here of +// the callbacks a COM object always is, as dropTarget is. +// +// DoDragDrop runs the drag itself: it takes the mouse capture, pumps the messages +// the drag generates, and returns when the pointer is released or Escape is +// pressed, with the effect the target took. It is therefore called on the +// event-loop thread, from the handler the press reached, and this package's event +// loop is inside it until it returns rather than beside it. A message arriving +// meanwhile — a repaint, a timer, another window's input — is dispatched by that +// drag loop into the same window procedure, so the handler the drag started from +// can be reentered; a window move's modal loop already does the same, and the +// window's state machine takes it the same way. +// +// The files are offered as CF_HDROP, the list a copied selection puts on the +// clipboard (platform.DropFilesBytes), because that is what Explorer, a folder +// window and every other file target read. Nothing is copied when the drag +// starts: a target that takes a copy or a move reads the paths while the drop +// happens, so the files must still be where they were until the user lets go. +// A target in another process reads them through OLE's standard IDataObject +// marshaling, which asks EnumFormatEtc and GetData for a list in shared memory +// rather than for the object, so those two are what makes a drop out of the +// process work; a link needs a shell link the object does not offer, so a target +// told it may link leaves it to the modifiers or copies. + +const ( + // The answers an IDropSource gives: end with a drop, end with a cancel, and + // keep the drag going. S_OK says the drag has not ended. + dragdropSDrop = 0x00040100 + dragdropSCancel = 0x00040101 + dragdropSUseDefaultCursors = 0x00040102 + // DV_E_FORMATETC: the object does not offer that format. + dvEFormatEtc = 0x80040064 + // OLE_E_ADVISENOTSUPPORTED: the object takes no advice. + oleEAdviseNotSupported = 0x80040003 + // E_NOTIMPL: the object does not do that at all. + eNotImpl = 0x80004001 + // S_FALSE: an enumerator had less to give than it was asked for. + sFalse = 1 + // DATADIR_GET enumerates the formats GetData reads. + dataDirGet = 1 + lindexNone = -1 + // wmDragEnded is posted to the window once a file drag's loop has ended. The + // press that started the drag is then cancelled after the handler that started + // it returns. Its number is the next free one after wmSetTitle (0x8053). + wmDragEnded = 0x8054 +) + +var doDragDrop = ole.NewProc("DoDragDrop") + +var ( + iidDataObject = guid{0x0000010e, 0x0000, 0x0000, [8]byte{0xc0, 0, 0, 0, 0, 0, 0, 0x46}} + iidDropSource = guid{0x00000121, 0x0000, 0x0000, [8]byte{0xc0, 0, 0, 0, 0, 0, 0, 0x46}} + iidEnumFORMATETC = guid{0x00000103, 0x0000, 0x0000, [8]byte{0xc0, 0, 0, 0, 0, 0, 0, 0x46}} +) + +// fileDataObject is the IDataObject of a drag of files: a pointer to the method +// table first, as every COM object begins, then the paths it hands out. The +// drag owns it, so the garbage collector keeps it for as long as the shell may +// call it. +type fileDataObject struct { + table *[12]uintptr + refs int32 + paths []string + // enums are the enumerators given away. The shell holds them by a pointer + // the garbage collector cannot see, so the object keeps them for as long as + // the drag it belongs to lives. Only the drag's own thread appends. + enums []*fileFormatEnum +} + +// fileDropSource is the IDropSource of the same drag: what ends it and which +// cursors it shows. +type fileDropSource struct { + table *[5]uintptr + refs int32 +} + +// fileFormatEnum is the IEnumFORMATETC that lists what the data object offers: +// one format, the list of files. +type fileFormatEnum struct { + table *[7]uintptr + refs int32 + at uint32 // how many formats it has given + // owner is the data object whose drag keeps this enumerator alive, and every + // clone of it: the shell holds them by pointers the collector cannot follow. + owner *fileDataObject +} + +var ( + dataTableOnce sync.Once + dataTable [12]uintptr + sourceTableOnce sync.Once + sourceTable [5]uintptr + enumTableOnce sync.Once + enumTable [7]uintptr +) + +func newFileDataTable() { + dataTable = [12]uintptr{ + guarded3("drag and drop: QueryInterface", dataQueryInterface), + guarded1("drag and drop: AddRef", dataAddRef), + guarded1("drag and drop: Release", dataRelease), + guarded3("drag and drop: GetData", dataGetData), + guarded3("drag and drop: GetDataHere", dataGetDataHere), + guarded2("drag and drop: QueryGetData", dataQueryGetData), + guarded3("drag and drop: GetCanonicalFormatEtc", dataGetCanonicalFormatEtc), + guarded4("drag and drop: SetData", dataSetData), + guarded3("drag and drop: EnumFormatEtc", dataEnumFormatEtc), + guarded5("drag and drop: DAdvise", dataDAdvise), + guarded2("drag and drop: DUnadvise", dataDUnadvise), + guarded2("drag and drop: EnumDAdvise", dataEnumDAdvise), + } +} + +func newFileSourceTable() { + sourceTable = [5]uintptr{ + guarded3("drag and drop: QueryInterface", sourceQueryInterface), + guarded1("drag and drop: AddRef", sourceAddRef), + guarded1("drag and drop: Release", sourceRelease), + guarded3("drag and drop: QueryContinueDrag", sourceQueryContinueDrag), + guarded2("drag and drop: GiveFeedback", sourceGiveFeedback), + } +} + +func newFileEnumTable() { + enumTable = [7]uintptr{ + guarded3("drag and drop: QueryInterface", enumQueryInterface), + guarded1("drag and drop: AddRef", enumAddRef), + guarded1("drag and drop: Release", enumRelease), + guarded4("drag and drop: Next", enumNext), + guarded2("drag and drop: Skip", enumSkip), + guarded1("drag and drop: Reset", enumReset), + guarded2("drag and drop: Clone", enumClone), + } +} + +func dataOf(this uintptr) *fileDataObject { return (*fileDataObject)(pointer(this)) } +func sourceOf(this uintptr) *fileDropSource { return (*fileDropSource)(pointer(this)) } +func enumOf(this uintptr) *fileFormatEnum { return (*fileFormatEnum)(pointer(this)) } + +// fileFormat is the one FORMATETC the data object offers: a list of files in +// memory the system owns, its index meaning "the whole list". +func fileFormat() formatEtc { + return formatEtc{Format: cfHDrop, Aspect: dvAspectContent, Index: lindexNone, Medium: tymedHGlobal} +} + +// takesFileFormat reports whether a FORMATETC asks for that list. +func takesFileFormat(asked formatEtc) bool { + offered := fileFormat() + return asked.Format == offered.Format && + asked.Aspect&dvAspectContent != 0 && + (asked.Index == lindexNone || asked.Index == 0) && + asked.Medium&tymedHGlobal != 0 +} + +// answerInterface is every COM object's QueryInterface: the object answers a +// request for one of its own interfaces or for IUnknown, and refuses the rest. +// refs is the object's own count, which a granted request adds to. +func answerInterface(this, riid, object uintptr, refs *int32, known ...guid) uintptr { + requested := *(*guid)(pointer(riid)) + matched := requested == iidUnknown + for _, iid := range known { + if requested == iid { + matched = true + break + } + } + if !matched { + *(*uintptr)(pointer(object)) = 0 + return eNoInterface + } + *(*uintptr)(pointer(object)) = this + *refs++ + return sOK +} + +// dropListHandle copies the files into the shared memory a drop target reads +// them from. The caller owns the memory and hands it to the target through the +// storage medium, or frees it. +func dropListHandle(paths []string) (uintptr, error) { + data := platform.DropFilesBytes(paths) + handle, _, callErr := globalAlloc.Call(globalMoveable|globalZeroInit, uintptr(len(data))) + if handle == 0 { + return 0, windowsCallError("allocate dragged files", callErr) + } + memory, _, callErr := globalLock.Call(handle) + if memory == 0 { + globalFree.Call(handle) + return 0, windowsCallError("lock dragged files", callErr) + } + copy(unsafe.Slice((*byte)(pointer(memory)), len(data)), data) + globalUnlock.Call(handle) + return handle, nil +} + +func dataQueryInterface(this, riid, object uintptr) uintptr { + return answerInterface(this, riid, object, &dataOf(this).refs, iidDataObject) +} + +func dataAddRef(this uintptr) uintptr { + data := dataOf(this) + data.refs++ + return uintptr(data.refs) +} + +func dataRelease(this uintptr) uintptr { + data := dataOf(this) + if data.refs > 0 { + data.refs-- + } + return uintptr(data.refs) +} + +// dataGetData hands the target a fresh copy of the list: OLE gives the memory to +// the target, and the next question asks for another. +func dataGetData(this, format, medium uintptr) uintptr { + if !takesFileFormat(*(*formatEtc)(pointer(format))) { + return dvEFormatEtc + } + handle, err := dropListHandle(dataOf(this).paths) + if err != nil { + return eFail + } + *(*storageMedium)(pointer(medium)) = storageMedium{Medium: tymedHGlobal, Handle: handle} + return sOK +} + +func dataGetDataHere(this, format, medium uintptr) uintptr { return eNotImpl } + +func dataQueryGetData(this, format uintptr) uintptr { + if !takesFileFormat(*(*formatEtc)(pointer(format))) { + return dvEFormatEtc + } + return sOK +} + +func dataGetCanonicalFormatEtc(this, format, canonical uintptr) uintptr { return eNotImpl } + +func dataSetData(this, format, medium, release uintptr) uintptr { return eNotImpl } + +// dataEnumFormatEtc lends the target an enumerator over the formats it may ask +// for, which is what OLE's standard marshaling reads to learn what the object +// has: one format, the list of files. +func dataEnumFormatEtc(this, direction, out uintptr) uintptr { + if uint32(direction) != dataDirGet { + if out != 0 { + *(*uintptr)(pointer(out)) = 0 + } + return eNotImpl + } + enumTableOnce.Do(newFileEnumTable) + data := dataOf(this) + enum := &fileFormatEnum{table: &enumTable, refs: 1, owner: data} + data.enums = append(data.enums, enum) + *(*uintptr)(pointer(out)) = uintptr(unsafe.Pointer(enum)) + return sOK +} + +func dataDAdvise(this, format, flags, advise, out uintptr) uintptr { + return oleEAdviseNotSupported +} + +func dataDUnadvise(this, connection uintptr) uintptr { return oleEAdviseNotSupported } + +func dataEnumDAdvise(this, out uintptr) uintptr { + if out != 0 { + *(*uintptr)(pointer(out)) = 0 + } + return oleEAdviseNotSupported +} + +func sourceQueryInterface(this, riid, object uintptr) uintptr { + return answerInterface(this, riid, object, &sourceOf(this).refs, iidDropSource) +} + +func sourceAddRef(this uintptr) uintptr { + source := sourceOf(this) + source.refs++ + return uintptr(source.refs) +} + +func sourceRelease(this uintptr) uintptr { + source := sourceOf(this) + if source.refs > 0 { + source.refs-- + } + return uintptr(source.refs) +} + +// sourceQueryContinueDrag answers whether the drag goes on. Escape cancels it as +// every Windows application does, and letting go of the last mouse button ends +// it with a drop; the target still decides whether it takes anything. The +// modifier keys are left to the target, which is what the default cursors show. +func sourceQueryContinueDrag(this, escape, keys uintptr) uintptr { + if escape != 0 { + return dragdropSCancel + } + if keys&mkAnyButton == 0 { + return dragdropSDrop + } + return sOK +} + +// sourceGiveFeedback asks for the shell's own cursors, the copy, move and no-drop +// arrows the user knows, rather than one drawn here. +func sourceGiveFeedback(this, effect uintptr) uintptr { return dragdropSUseDefaultCursors } + +func enumQueryInterface(this, riid, object uintptr) uintptr { + return answerInterface(this, riid, object, &enumOf(this).refs, iidEnumFORMATETC) +} + +func enumAddRef(this uintptr) uintptr { + enum := enumOf(this) + enum.refs++ + return uintptr(enum.refs) +} + +func enumRelease(this uintptr) uintptr { + enum := enumOf(this) + if enum.refs > 0 { + enum.refs-- + } + return uintptr(enum.refs) +} + +func enumNext(this, count, formats, fetched uintptr) uintptr { + enum := enumOf(this) + given := uint32(0) + if asked := uint32(count); asked > 0 && enum.at == 0 { + *(*formatEtc)(pointer(formats)) = fileFormat() + enum.at = 1 + given = 1 + } + if fetched != 0 { + *(*uint32)(pointer(fetched)) = given + } + if given != uint32(count) { + return sFalse + } + return sOK +} + +func enumSkip(this, count uintptr) uintptr { + enum := enumOf(this) + if uint32(count) == 0 { + return sOK + } + // Skipping past the end moves to the end and reports S_FALSE, as the + // enumerator contract asks, when fewer formats remain than were asked for. + left := 1 - enum.at + enum.at = 1 + if uint32(count) > left { + return sFalse + } + return sOK +} + +func enumReset(this uintptr) uintptr { + enumOf(this).at = 0 + return sOK +} + +func enumClone(this, out uintptr) uintptr { + enum := enumOf(this) + clone := &fileFormatEnum{table: &enumTable, refs: 1, at: enum.at, owner: enum.owner} + if owner := clone.owner; owner != nil { + owner.enums = append(owner.enums, clone) + } + *(*uintptr)(pointer(out)) = uintptr(unsafe.Pointer(clone)) + return sOK +} + +// StartFileDrag takes files out of the application's active window, as a file +// manager does when the user drags a selection to another window: the drag lasts +// until the pointer is released or Escape is pressed, and the effect the target +// took is returned, DragEffectNone when it took nothing. +// +// allowed is the mask of effects the application offers; a target that takes one +// of them reports it. It is called on the event-loop thread, from the handler of +// the pointer event that starts the drag, and does not return until the drag has +// ended. The files are read while the drop happens, so they must still exist +// where they were when the user lets go. +func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error) { + state := active.Load() + if state == nil || state.window == 0 { + return platform.DragEffectNone, fmt.Errorf("windows: no window to drag files out of") + } + thread, _, _ := getCurrentThread.Call() + if uint32(thread) != state.application.thread { + return platform.DragEffectNone, fmt.Errorf("windows: files are dragged out on the event-loop thread that owns the window") + } + if len(paths) == 0 { + return platform.DragEffectNone, fmt.Errorf("windows: no files to drag out of the window") + } + // DoDragDrop needs OLE, which CoInitializeEx does not set up: the drag-and-drop + // services answer CO_E_NOTINITIALIZED until OleInitialize has run on the + // thread. A window that takes drops asks the same way (registerDropTarget), + // and closeOLE gives it back once. + if !state.application.oleReady { + if status, _, _ := oleInitialize.Call(0); int32(uint32(status)) < 0 { + return platform.DragEffectNone, hresult(status) + } + state.application.oleReady = true + } + dataTableOnce.Do(newFileDataTable) + sourceTableOnce.Do(newFileSourceTable) + data := &fileDataObject{table: &dataTable, refs: 1, paths: paths} + source := &fileDropSource{table: &sourceTable, refs: 1} + var effect uint32 + // DoDragDrop takes no window: it finds the drag's source from the capture the + // press took, which is why it is the window the user pressed in that owns the + // drag. The parameters are the data object, the drop source, the effects the + // application offers, and where the effect the target took is written. + status, _, _ := doDragDrop.Call( + uintptr(unsafe.Pointer(data)), + uintptr(unsafe.Pointer(source)), + uintptr(allowed), + uintptr(unsafe.Pointer(&effect)), + ) + // The objects outlive the drag: the shell held them by pointers the garbage + // collector cannot follow until DoDragDrop let them go. + runtime.KeepAlive(data) + runtime.KeepAlive(source) + // A drop or a cancel means the drag loop ran, and that loop took the button's + // release, so the window never sees it and the application's press stays open. + // The message is posted, not sent: the handler that started the drag is still + // on the stack, and the application must not be called back from inside it. + if uint32(status) == dragdropSDrop || uint32(status) == dragdropSCancel { + postMessage.Call(state.window, wmDragEnded, 0, 0) + } + if err := hresult(status); err != nil { + return platform.DragEffectNone, err + } + return platform.DragEffectOf(allowed, platform.DragEffect(effect)), nil +} diff --git a/internal/platform/windows/drag_windows_test.go b/internal/platform/windows/drag_windows_test.go new file mode 100644 index 00000000..29f73655 --- /dev/null +++ b/internal/platform/windows/drag_windows_test.go @@ -0,0 +1,226 @@ +//go:build windows + +package windows + +import ( + "bytes" + "runtime" + "slices" + "strings" + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// newDragObject is a data object for paths, as a drag of them builds it. The +// caller keeps it alive for as long as it drives it, as StartFileDrag does: the +// shell between them holds it by a pointer the collector cannot follow. +func newDragObject(paths []string) (*fileDataObject, uintptr) { + dataTableOnce.Do(newFileDataTable) + data := &fileDataObject{table: &dataTable, refs: 1, paths: paths} + return data, uintptr(unsafe.Pointer(data)) +} + +func newDragSource() (*fileDropSource, uintptr) { + sourceTableOnce.Do(newFileSourceTable) + source := &fileDropSource{table: &sourceTable, refs: 1} + return source, uintptr(unsafe.Pointer(source)) +} + +// TestTheDataObjectHandsOutTheFilesAsADropList asks the object for the files the +// way a target does and reads them back as a list of paths, which is all a drag +// of files ever carries. +func TestTheDataObjectHandsOutTheFilesAsADropList(t *testing.T) { + paths := []string{`C:\Temp\one.txt`, `C:\Temp\文件夹`, `D:\x`} + data, object := newDragObject(paths) + defer runtime.KeepAlive(data) + format := fileFormat() + if status := uint32(comCall(object, 5, uintptr(unsafe.Pointer(&format)))); status != sOK { + t.Fatalf("QueryGetData = %#x, want S_OK", status) + } + var medium storageMedium + if status := uint32(comCall(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&medium)))); status != sOK { + t.Fatalf("GetData = %#x, want S_OK", status) + } + defer releaseStgMedium.Call(uintptr(unsafe.Pointer(&medium))) + if medium.Medium != tymedHGlobal || medium.Handle == 0 { + t.Fatalf("the medium is %+v, want memory the target owns", medium) + } + want := platform.DropFilesBytes(paths) + memory, _, _ := globalLock.Call(medium.Handle) + if memory == 0 { + t.Fatal("the memory the object handed over cannot be locked") + } + block := unsafe.Slice((*byte)(pointer(memory)), len(want)) + if !bytes.Equal(block, want) { + t.Errorf("the block is %q, want %q", block, want) + } + globalUnlock.Call(medium.Handle) + if back := platform.FilesFromDropFiles(append([]byte(nil), block...)); !slices.Equal(back, paths) { + t.Errorf("the list reads back as %q, want %q", back, paths) + } + + // Every answer is the target's own memory: a second question cannot be given + // the block the first one took. + var again storageMedium + if status := uint32(comCall(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&again)))); status != sOK { + t.Fatalf("the second GetData = %#x, want S_OK", status) + } + defer releaseStgMedium.Call(uintptr(unsafe.Pointer(&again))) + if again.Handle == medium.Handle { + t.Error("both answers are the same memory, so the target would free it twice") + } +} + +// TestTheDataObjectRefusesWhatItDoesNotOffer keeps the formats a target asks for +// that a drag of files cannot answer from being taken as an empty answer. +func TestTheDataObjectRefusesWhatItDoesNotOffer(t *testing.T) { + data, object := newDragObject([]string{`C:\Temp\one.txt`}) + defer runtime.KeepAlive(data) + text := formatEtc{Format: 13 /* CF_UNICODETEXT */, Aspect: dvAspectContent, Index: lindexNone, Medium: tymedHGlobal} + if status := uint32(comCall(object, 5, uintptr(unsafe.Pointer(&text)))); status != dvEFormatEtc { + t.Errorf("QueryGetData of text = %#x, want DV_E_FORMATETC", status) + } + var medium storageMedium + if status := uint32(comCall(object, 3, uintptr(unsafe.Pointer(&text)), uintptr(unsafe.Pointer(&medium)))); status != dvEFormatEtc { + t.Errorf("GetData of text = %#x, want DV_E_FORMATETC", status) + } + thumbnail := fileFormat() + thumbnail.Aspect = 2 // DVASPECT_THUMBNAIL + if status := uint32(comCall(object, 5, uintptr(unsafe.Pointer(&thumbnail)))); status != dvEFormatEtc { + t.Errorf("QueryGetData of a thumbnail = %#x, want DV_E_FORMATETC", status) + } + stream := fileFormat() + stream.Medium = 4 // TYMED_ISTREAM + if status := uint32(comCall(object, 5, uintptr(unsafe.Pointer(&stream)))); status != dvEFormatEtc { + t.Errorf("QueryGetData of a stream = %#x, want DV_E_FORMATETC", status) + } + if status := uint32(comCall(object, 4, uintptr(unsafe.Pointer(&stream)), uintptr(unsafe.Pointer(&medium)))); status != eNotImpl { + t.Errorf("GetDataHere = %#x, want E_NOTIMPL", status) + } + if status := uint32(comCall(object, 9, uintptr(unsafe.Pointer(&stream)), 0, 0, 0)); status != oleEAdviseNotSupported { + t.Errorf("DAdvise = %#x, want OLE_E_ADVISENOTSUPPORTED", status) + } + if status := uint32(comCall(object, 10, 1)); status != oleEAdviseNotSupported { + t.Errorf("DUnadvise = %#x, want OLE_E_ADVISENOTSUPPORTED", status) + } +} + +// TestTheFormatEnumeratorListsTheDropList walks the enumerator OLE's standard +// marshaling reads: one format, the list of files, then nothing more. +func TestTheFormatEnumeratorListsTheDropList(t *testing.T) { + data, object := newDragObject([]string{`C:\Temp\one.txt`}) + defer runtime.KeepAlive(data) + var enum uintptr + if status := uint32(comCall(object, 8, dataDirGet, uintptr(unsafe.Pointer(&enum)))); status != sOK { + t.Fatalf("EnumFormatEtc = %#x, want S_OK", status) + } + if enum == 0 { + t.Fatal("EnumFormatEtc handed out no enumerator") + } + var offered formatEtc + var fetched uint32 + if status := uint32(comCall(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sOK || fetched != 1 { + t.Fatalf("Next(1) = %#x with %d formats, want S_OK with 1", status, fetched) + } + if offered.Format != cfHDrop || offered.Aspect != dvAspectContent || offered.Index != lindexNone || offered.Medium != tymedHGlobal { + t.Errorf("the format is %+v, want the list of files", offered) + } + if status := uint32(comCall(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 0 { + t.Errorf("Next after the end = %#x with %d formats, want S_FALSE with 0", status, fetched) + } + comCall(enum, 5) // Reset + if status := uint32(comCall(enum, 3, 2, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 1 { + t.Errorf("Next(2) = %#x with %d formats, want S_FALSE with 1", status, fetched) + } + comCall(enum, 5) + comCall(enum, 4, 1) // Skip + if status := uint32(comCall(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 0 { + t.Errorf("Next after Skip = %#x with %d formats, want S_FALSE with 0", status, fetched) + } + comCall(enum, 5) + if status := uint32(comCall(enum, 4, 2)); status != sFalse { + t.Errorf("Skip(2) with one format = %#x, want S_FALSE", status) + } + comCall(enum, 5) + var clone uintptr + if status := uint32(comCall(enum, 6, uintptr(unsafe.Pointer(&clone)))); status != sOK || clone == 0 { + t.Fatalf("Clone = %#x, want S_OK with an enumerator", status) + } + if status := uint32(comCall(clone, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sOK || fetched != 1 { + t.Errorf("the clone's Next = %#x with %d formats, want S_OK with 1", status, fetched) + } +} + +// TestTheDropSourceEndsTheDragWhereWindowsDoes checks the three answers a drag +// gives: Escape cancels, letting go of the mouse drops, and a drag that still +// holds a button goes on. +func TestTheDropSourceEndsTheDragWhereWindowsDoes(t *testing.T) { + source, object := newDragSource() + defer runtime.KeepAlive(source) + for _, test := range []struct { + escape uintptr + keys uintptr + want uintptr + }{ + {1, mkLButton, dragdropSCancel}, + {1, 0, dragdropSCancel}, + {0, 0, dragdropSDrop}, + {0, mkLButton, sOK}, + {0, 2, sOK}, // MK_RBUTTON + {0, 0x10 | 8, sOK}, // MK_MBUTTON with MK_CONTROL beside it + {0, 8, dragdropSDrop}, // no button, only a modifier + } { + if got := uint32(comCall(object, 3, test.escape, test.keys)); got != uint32(test.want) { + t.Errorf("QueryContinueDrag(escape=%d, keys=%#x) = %#x, want %#x", test.escape, test.keys, got, uint32(test.want)) + } + } + if got := uint32(comCall(object, 4, uintptr(platform.DragEffectCopy))); got != dragdropSUseDefaultCursors { + t.Errorf("GiveFeedback = %#x, want DRAGDROP_S_USEDEFAULTCURSORS", got) + } +} + +// TestTheObjectsAnswerForTheirOwnInterfaces is what OLE asks before it hands an +// object to another process, and a wrong answer there fails the drop with +// nothing said. +func TestTheObjectsAnswerForTheirOwnInterfaces(t *testing.T) { + data, object := newDragObject([]string{`C:\Temp\one.txt`}) + defer runtime.KeepAlive(data) + var asked uintptr + if status := uint32(comCall(object, 0, uintptr(unsafe.Pointer(&iidDataObject)), uintptr(unsafe.Pointer(&asked)))); status != sOK || asked != object { + t.Errorf("the data object answered IDataObject with %#x and %#x, want S_OK and itself", status, asked) + } + if data.refs != 2 { + t.Errorf("the data object counts %d references after one grant, want 2", data.refs) + } + asked = 1 + if status := uint32(comCall(object, 0, uintptr(unsafe.Pointer(&iidDropSource)), uintptr(unsafe.Pointer(&asked)))); status != eNoInterface || asked != 0 { + t.Errorf("the data object answered IDropSource with %#x and %#x, want E_NOINTERFACE and no object", status, asked) + } + source, sourceObject := newDragSource() + defer runtime.KeepAlive(source) + if status := uint32(comCall(sourceObject, 0, uintptr(unsafe.Pointer(&iidDropSource)), uintptr(unsafe.Pointer(&asked)))); status != sOK { + t.Errorf("the drop source refused IDropSource with %#x", status) + } + if status := uint32(comCall(sourceObject, 0, uintptr(unsafe.Pointer(&iidDataObject)), uintptr(unsafe.Pointer(&asked)))); status != eNoInterface { + t.Errorf("the drop source answered IDataObject with %#x, want E_NOINTERFACE", status) + } +} + +// TestAFileDragIsRefusedOffTheEventLoopThread keeps a drag from being started on +// a goroutine without the window's message loop, where DoDragDrop would wait for +// a pointer that never reaches it. +func TestAFileDragIsRefusedOffTheEventLoopThread(t *testing.T) { + events := make(chan platform.FileDropEvent, 4) + state, closeWindow := openDropWindow(t, true, events) + defer closeWindow() + if state.application.thread == 0 { + t.Fatal("the window's application has no event-loop thread") + } + if _, err := StartFileDrag([]string{`C:\Temp\one.txt`}, platform.DragEffectCopy); err == nil { + t.Fatal("a drag started from another goroutine") + } else if !strings.Contains(err.Error(), "event-loop thread") { + t.Fatalf("the refusal says %q, want the event-loop thread", err) + } +} diff --git a/internal/platform/windows/post_windows.go b/internal/platform/windows/post_windows.go index f4e9c2ed..f677ae0b 100644 --- a/internal/platform/windows/post_windows.go +++ b/internal/platform/windows/post_windows.go @@ -2,6 +2,98 @@ package windows +import ( + "fmt" + "sync" + "sync/atomic" + "syscall" + "unsafe" +) + +// Posted work is woken through a message-only window, not a thread message. +// A modal Win32 loop — a native menu, a dialog — retrieves messages and hands +// each one to DispatchMessage, but a thread message has no window to reach, so +// the modal loop consumes it and the event loop never sees the wake. The +// coalescing flag then stayed set and every later Post was accepted and never +// run: work waiting on the loop hung until restart while requests that never +// need the loop, such as a protocol handshake or a catalog listing, kept +// answering. A window message is dispatched to its window procedure even +// inside a modal loop, so the work runs there instead. +const ( + // hwndMessage is HWND_MESSAGE: the window is message-only and has no + // presence on any desktop. + hwndMessage = ^uintptr(2) + // wakeClassName names the message-only window Post wakes. + wakeClassName = "VivaNativeWake" +) + +var ( + wakeClassOnce sync.Once + wakeClassNamePtr *uint16 + wakeClassErr error + wakeCallbackOnce sync.Once + wakeCallback uintptr + // wakeOwner is the application whose loop drains the posted work. There is + // one native application per process. + wakeOwner atomic.Pointer[windowsApplication] +) + +// wakeProc runs posted work for the wake window. A modal loop dispatches the +// wake here just as the application's own loop does. +func wakeProc(window, kind, first, second uintptr) (result uintptr) { + if kind == wmPost { + if application := wakeOwner.Load(); application != nil { + application.drainPosts() + } + return 0 + } + result, _, _ = defaultWindowProc.Call(window, kind, first, second) + return +} + +// ensureWakeClass registers the wake window class once per process. A class +// registered here lives as long as the process; only the window is per loop. +func ensureWakeClass(instance uintptr) error { + wakeClassOnce.Do(func() { + wakeCallbackOnce.Do(func() { wakeCallback = syscall.NewCallback(wakeProc) }) + wakeClassNamePtr, _ = syscall.UTF16PtrFromString(wakeClassName) + class := windowClass{ + Size: uint32(unsafe.Sizeof(windowClass{})), + Procedure: wakeCallback, + Instance: instance, + Name: wakeClassNamePtr, + } + if registered, _, err := registerClass.Call(uintptr(unsafe.Pointer(&class))); registered == 0 { + wakeClassErr = fmt.Errorf("windows: register the wake class: %w", err) + } + }) + return wakeClassErr +} + +// openWakeWindow creates the message-only window Post wakes. It must run on +// the event-loop thread. +func (application *windowsApplication) openWakeWindow() error { + instance, _, _ := getModule.Call(0) + if err := ensureWakeClass(instance); err != nil { + return err + } + window, _, err := createWindow.Call(0, uintptr(unsafe.Pointer(wakeClassNamePtr)), 0, 0, 0, 0, 0, 0, hwndMessage, 0, instance, 0) + if window == 0 { + return fmt.Errorf("windows: create the wake window: %w", err) + } + application.wakeWindow.Store(window) + wakeOwner.Store(application) + return nil +} + +// closeWakeWindow drops the wake window; no posted work runs after it. +func (application *windowsApplication) closeWakeWindow() { + if window := application.wakeWindow.Swap(0); window != 0 { + destroyWindow.Call(window) + } + wakeOwner.CompareAndSwap(application, nil) +} + // Post runs fn on the event-loop thread; it is safe from any goroutine. func (application *windowsApplication) Post(fn func()) { if fn == nil { @@ -10,9 +102,23 @@ func (application *windowsApplication) Post(fn func()) { application.postMu.Lock() application.posts = append(application.posts, fn) application.postMu.Unlock() - if application.postWake.CompareAndSwap(false, true) { - postThreadMessage.Call(uintptr(application.thread), wmPost, 0, 0) + if application.postWake.CompareAndSwap(false, true) && !application.wake() { + // No wake reached the loop. Clear the flag so the next Post posts one + // instead of leaving the work queued forever. + application.postWake.Store(false) + } +} + +// wake asks the loop to drain the work Post accepted. The window message is +// the reliable form: a modal loop dispatches it to wakeProc. The thread +// message is only a fallback for a Post before the window exists. +func (application *windowsApplication) wake() bool { + if window := application.wakeWindow.Load(); window != 0 { + posted, _, _ := postMessage.Call(window, wmPost, 0, 0) + return posted != 0 } + posted, _, _ := postThreadMessage.Call(uintptr(application.thread), wmPost, 0, 0) + return posted != 0 } // drainPosts runs the functions accepted since the last drain, in order. A diff --git a/internal/platform/windows/post_windows_test.go b/internal/platform/windows/post_windows_test.go index 311f8bb9..94c5bcc0 100644 --- a/internal/platform/windows/post_windows_test.go +++ b/internal/platform/windows/post_windows_test.go @@ -2,7 +2,15 @@ package windows -import "testing" +import ( + "runtime" + "sync/atomic" + "testing" + "time" + "unsafe" +) + +var peekWakeMessage = user.NewProc("PeekMessageW") func TestDrainPostsRunsWorkInOrder(t *testing.T) { application := &windowsApplication{} @@ -27,3 +35,49 @@ func TestADrainPicksUpWorkPostedWhileItRuns(t *testing.T) { t.Fatalf("seen = %v, want [1 2]", seen) } } + +// modalPump retrieves messages the way a modal Win32 loop (a native menu, a +// dialog) does: a window message reaches its window procedure, a thread +// message is dispatched to nothing and disappears. +func modalPump(d time.Duration, done func() bool) bool { + deadline := time.Now().Add(d) + for { + if done() { + return true + } + if time.Now().After(deadline) { + return false + } + var event message + if received, _, _ := peekWakeMessage.Call(uintptr(unsafe.Pointer(&event)), 0, 0, 0, 1); received != 0 { + if event.Window != 0 { + dispatchMessage.Call(uintptr(unsafe.Pointer(&event))) + } + continue + } + time.Sleep(time.Millisecond) + } +} + +// Posted work must run while the loop is inside a modal message loop, and a +// later Post must still find a wake after one could not be delivered. +func TestPostedWorkRunsUnderAModalLoopAndRecoversALostWake(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + application := &windowsApplication{} + + // No wake window yet: the first wake cannot reach a loop (thread 0). The + // work stays queued and the next Post must post a fresh wake rather than + // leave it behind a latch. + var first, second atomic.Bool + application.Post(func() { first.Store(true) }) + if err := application.openWakeWindow(); err != nil { + t.Fatalf("open wake window: %v", err) + } + defer application.closeWakeWindow() + application.Post(func() { second.Store(true) }) + + if !modalPump(2*time.Second, func() bool { return first.Load() && second.Load() }) { + t.Fatalf("posted work did not run under a modal loop: first=%v second=%v", first.Load(), second.Load()) + } +} diff --git a/internal/platform/windows/window_controls_windows.go b/internal/platform/windows/window_controls_windows.go index 4b94e1f4..aa79e671 100644 --- a/internal/platform/windows/window_controls_windows.go +++ b/internal/platform/windows/window_controls_windows.go @@ -344,12 +344,18 @@ func (state *windowState) beginsCaptionPress(x, y int32) bool { // window move. The application is told the pointer left, which cancels its // press, because the system's loop swallows the button release. func (state *windowState) dragCaption(x, y int32) { - if state.config.OnPointer != nil { - frame, err := state.config.OnPointer(platform.PointerEvent{Kind: platform.PointerExit}) - state.frame(frame, err) - } + state.cancelPress() releaseCapture.Call() screen := point{X: x, Y: y} clientToScreen.Call(state.window, uintptr(unsafe.Pointer(&screen))) sendMessage.Call(state.window, wmNCLButtonDown, htCaption, uintptr(uint16(screen.X))|uintptr(uint16(screen.Y))<<16) } + +// cancelPress tells the application its press is over. The application is told +// the pointer left, the same event a window sees when the pointer leaves it. +func (state *windowState) cancelPress() { + if state.config.OnPointer != nil { + frame, err := state.config.OnPointer(platform.PointerEvent{Kind: platform.PointerExit}) + state.frame(frame, err) + } +} diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index e2f6fdac..a0b6e587 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -193,10 +193,12 @@ type windowsApplication struct { taskbar uintptr taskbarTried bool // posts are the functions other goroutines handed to Post; they are drained - // on the event-loop thread. postWake coalesces the messages that wake it. - postMu sync.Mutex - posts []func() - postWake atomic.Bool + // on the event-loop thread. postWake coalesces the messages that wake it, + // and wakeWindow is the message-only window that carries the wake. + postMu sync.Mutex + posts []func() + postWake atomic.Bool + wakeWindow atomic.Uintptr } type nativeWindow struct { @@ -265,6 +267,12 @@ func RunApplication(start platform.ApplicationStart) error { application := &windowsApplication{className: name, instance: instance} thread, _, _ := getCurrentThread.Call() application.thread = uint32(thread) + // The wake window exists before start, so work posted from the start + // callback has somewhere to wake the loop even while a modal loop runs. + if err := application.openWakeWindow(); err != nil { + return err + } + defer application.closeWakeWindow() defer application.closeStatus() defer application.closeOLE() if err := start(application); err != nil { @@ -538,6 +546,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmApplyAppearance: state.settingsChanged() return 0 + case wmDragEnded: + state.cancelPress() + return 0 case wmClipboardUpdate: notifyClipboardChange() return 0 diff --git a/ui/color_paint.go b/ui/color_paint.go index 186a473e..e92c92a5 100644 --- a/ui/color_paint.go +++ b/ui/color_paint.go @@ -57,7 +57,7 @@ func paintColorPickerPanel(s *ColorPickerState, d *DrawContext, c C, ID gfx.ID, options := components.ColorPickerOptions{ IDs: ids, Labels: labels, Value: value, Open: s.GetOpen(), Empty: empty, ShowAlpha: s.ShowsAlpha(), RoundTrigger: look.GetRound(), TriggerIcon: look.GetIcon(), SaturationText: s.Summary, - Viewport: Rect{Width: c.Bounds().Width, Height: c.Bounds().Height}, Layer: c.GetF().WidgetLayer() + 2, + Viewport: Rect{Width: c.Bounds().Width, Height: c.Bounds().Height}, Layer: s.GetLayer(), } if s.GetOpen() { options.Scope = s.GetHandlers().GetParts().At(8) diff --git a/ui/color_test.go b/ui/color_test.go index aea187d6..b4351996 100644 --- a/ui/color_test.go +++ b/ui/color_test.go @@ -226,3 +226,33 @@ func TestColorSwatchTakesTheApplicationsIDWithHit(t *testing.T) { t.Fatalf("the swatch declares %d hits under its id, want 1", n) } } + +// A picker declared inside a Dialog keeps its panel over the dialog: the panel +// is on the layer the picker was declared on, not on the page's layer that the +// dialog's scrim covers, so its controls stay clickable while it is open. +func TestColorPickerPanelStandsAboveItsDialog(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(10, 20, 30) + const dialogLayer = 600 + d := openPage(t, func(c ui.C) { + dialog := ui.Dialog(c, ui.DialogSpec{Title: "Pick a color", Width: 480, Layer: dialogLayer}) + dialog.Body(func() { + ui.Column(c).Pad(16).Children(func() { + ui.ColorPicker(c, &state, &color, "Accent") + }) + }) + }) + d.click("Accent") + if !state.Open() { + t.Fatal("the trigger did not open the panel") + } + if panel := d.hit("OK"); panel.Layer <= dialogLayer { + t.Fatalf("the panel's controls paint at layer %d, over the dialog's %d", panel.Layer, dialogLayer) + } + d.click("Hex color") + state.SetHexText("#FF0000") + d.click("OK") + if state.Open() || color != gfx.RGB(255, 0, 0) { + t.Fatalf("open=%v color=%v, want the panel's Apply to reach the picker", state.Open(), color) + } +} diff --git a/ui/page_test.go b/ui/page_test.go index 35d91ae4..bb699764 100644 --- a/ui/page_test.go +++ b/ui/page_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -592,6 +593,28 @@ func TestSelectIconsChooseAnOption(t *testing.T) { } } +// A Select with icons is measured wide enough for them: the component paints an +// icon before the value, so the trigger must not squeeze the label into it. +func TestSelectWithIconsMeasuresTheIconSpan(t *testing.T) { + labels := []string{"One", "Two"} + chosen := "One" + icon := gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{gfx.MoveTo(4, 4), gfx.LineTo(20, 20)}} + measure := func(icons []gfx.Icon) float32 { + d := openPage(t, func(c ui.C) { + ui.Row(c).Pad(16).Children(func() { + ui.Select(c, &chosen, labels, func(label string) string { return label }). + Placeholder("Language").Icons(icons) + }) + }) + return d.hit("Language").Bounds.Width + } + bare, withIcon := measure(nil), measure([]gfx.Icon{icon, icon}) + if withIcon-bare != components.SelectIconSpan { + t.Fatalf("a select with icons measured %g, without %g; want %d wider", withIcon, bare, components.SelectIconSpan) + } +} + // A TextAreaID is addressed by the identity the application gave it, and edits its // Field in rows like a TextArea. func TestPageTextAreaID(t *testing.T) { diff --git a/ui/page_wheel_trap_test.go b/ui/page_wheel_trap_test.go new file mode 100644 index 00000000..551055d0 --- /dev/null +++ b/ui/page_wheel_trap_test.go @@ -0,0 +1,68 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A focus trap owns the wheel as it owns the pointer: while a dialog is open, a +// scroll area painted outside its scope takes no wheel, wherever it lies under +// the pointer, and the dialog's own area still scrolls. Once the dialog is gone +// the page's areas scroll again. +func TestWheelOverAnAreaBehindATrappedDialogGoesNowhere(t *testing.T) { + var tree gfx.Tree + root := tree.Feature("wheel-trap") + scope := tree.Sub(root, tree.Name("scope")) + var behind, inside ui.Box + open := true + view := func(c ui.C) { + ui.Column(c).Fill().Children(func() { + behind = ui.Scroll(c).Grow(1).Children(func() { + ui.Slot(c).Height(2000).Shrink(0) + }) + }) + if !open { + return + } + dialog := ui.Dialog(c, ui.DialogSpec{Title: "Trap", Scope: scope.ID(tree.Name("scope")), Width: 320, Height: 300}) + dialog.Body(func() { + inside = ui.Scroll(c).Height(80).Shrink(0).Children(func() { + ui.Slot(c).Height(1000).Shrink(0) + }) + }) + } + page := ui.NewPage(ui.PageConfig{Tree: &tree, Root: "wheel-trap", View: view}) + canvas := benchCanvas() + drawPage(page, canvas, view) + + offset := func(b ui.Box) float32 { return b.ScrollState().Offset } + at := func(b ui.Box) gfx.ScrollEvent { + r := b.Rect() + return gfx.ScrollEvent{X: r.X + 10, Y: r.Y + 10, DeltaY: 60, Precise: true} + } + + // The page's area is under the pointer at its top-left, away from the centred + // dialog surface. + drawPage(page, canvas, view) + page.Wheel(at(behind)) + drawPage(page, canvas, view) + if offset(behind) != 0 { + t.Fatalf("a wheel over the page's area behind an open dialog scrolled it to %v", offset(behind)) + } + + page.Wheel(at(inside)) + drawPage(page, canvas, view) + if offset(inside) == 0 { + t.Fatal("the dialog's own area did not take the wheel") + } + + open = false + drawPage(page, canvas, view) + page.Wheel(at(behind)) + drawPage(page, canvas, view) + if offset(behind) == 0 { + t.Fatal("the page's area did not scroll again once the dialog closed") + } +} diff --git a/ui/select_paint.go b/ui/select_paint.go index 8e1b4dc0..c0576164 100644 --- a/ui/select_paint.go +++ b/ui/select_paint.go @@ -8,6 +8,9 @@ import ( func measureSelect(f *Frame, n *Node) { d := &base.WidgetsOf(f).GetSelects()[n.Aux] widest := d.GetState().WidestOption(f.Surface, d.GetLabels(), f.Palette.Metrics.FontSizeM) + if len(d.GetIcons()) > 0 { + widest += components.SelectIconSpan + } height := f.Palette.Metrics.ControlHeight switch { case n.ButtonSize == components.ButtonSizeXSmall: diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md index 7e1b6d1a..6b5d9385 100644 --- a/website/content/guides/en/getting-started.md +++ b/website/content/guides/en/getting-started.md @@ -9,7 +9,7 @@ group: start - **Go 1.26 or newer.** If you use the `viva` command and have none, it downloads one for you; see [Build and package](/en/docs/build-and-package/). - **macOS:** the Xcode command-line tools. Viva reaches Cocoa and Metal through cgo. -- **Linux:** X11 with the system XCB, Pango and Cairo libraries. A Vulkan loader and driver are recommended for GPU acceleration; without them Viva draws on the CPU. +- **Linux:** X11 with the system XCB, Pango and Cairo libraries, or native Wayland with the opt-in GTK 3 shell (`-tags vivagtk`, with GTK 3 installed). A Vulkan loader and driver are recommended for GPU acceleration; without them Viva draws on the CPU. - **Windows:** Win32 with the system Direct3D 11 and DirectWrite libraries. ## Add Viva to a project diff --git a/website/content/guides/en/platforms.md b/website/content/guides/en/platforms.md index 8b891b55..82e40a00 100644 --- a/website/content/guides/en/platforms.md +++ b/website/content/guides/en/platforms.md @@ -26,9 +26,10 @@ Win32 events, Direct3D 11 with embedded precompiled shaders, DirectWrite for mea ## Linux -X11 through dynamically loaded system XCB, Pango and Cairo, and Vulkan when a GPU driver is available, with a blocking event loop that does no idle redraw. +X11 through dynamically loaded system XCB, Pango and Cairo, and Vulkan when a GPU driver is available, with a blocking event loop that does no idle redraw. The default build is an X11 client, so a Wayland session runs it through XWayland; an opt-in GTK 3 shell is a native Wayland client instead. - X11 with the system's XCB, Pango and Cairo libraries; a Vulkan loader and driver add GPU acceleration, and the CPU renderer covers a machine without them. +- `-tags vivagtk` builds the GTK 3 shell: on a Wayland session it is a native client drawn at the compositor's fractional scale, and on X11 it runs through GTK. GTK owns the window, the pointer, the keyboard and the input method; Viva draws the content with the CPU rasterizer, so this build does not use Vulkan. The system's GTK 3 must be installed at run time, and the public API is the same. - Pango and Cairo for text. - Packaging to a `tar.gz` with an install script, or a `.deb`. - File dialogs, URL opening and notifications use installed desktop utilities; see [System integration](/en/docs/system-integration/). diff --git a/website/content/guides/zh/getting-started.md b/website/content/guides/zh/getting-started.md index 47155f28..c5fde4f7 100644 --- a/website/content/guides/zh/getting-started.md +++ b/website/content/guides/zh/getting-started.md @@ -9,7 +9,7 @@ group: start - **Go 1.26 或更新版本。** 使用 `viva` 命令时如果机器上没有,它会替你下载;见[构建与打包](/zh/docs/build-and-package/)。 - **macOS:** Xcode 命令行工具。Viva 通过 cgo 调用 Cocoa 和 Metal。 -- **Linux:** X11,以及系统自带的 XCB、Pango 和 Cairo 库。Vulkan 加载库和驱动建议安装以获得 GPU 加速;没有时 Viva 用 CPU 渲染。 +- **Linux:** X11,以及系统自带的 XCB、Pango 和 Cairo 库;要原生 Wayland 就用可选的 GTK 3 外壳(`-tags vivagtk`,需安装系统的 GTK 3)。Vulkan 加载库和驱动建议安装以获得 GPU 加速;没有时 Viva 用 CPU 渲染。 - **Windows:** Win32,以及系统自带的 Direct3D 11 和 DirectWrite 库。 ## 把 Viva 加入项目 diff --git a/website/content/guides/zh/platforms.md b/website/content/guides/zh/platforms.md index eb8dbfde..1676e320 100644 --- a/website/content/guides/zh/platforms.md +++ b/website/content/guides/zh/platforms.md @@ -26,9 +26,10 @@ Win32 事件、带预编译着色器的 Direct3D 11、用于测量的 DirectWrit ## Linux -通过动态加载的系统 XCB、Pango 和 Cairo 使用 X11,有 GPU 驱动时再用 Vulkan;事件循环是阻塞式的,空闲时不重绘。 +通过动态加载的系统 XCB、Pango 和 Cairo 使用 X11,有 GPU 驱动时再用 Vulkan;事件循环是阻塞式的,空闲时不重绘。默认构建是 X11 客户端,在 Wayland 会话里经由 XWayland 运行;可选的 GTK 3 外壳则是原生 Wayland 客户端。 - X11,使用系统自带的 XCB、Pango 和 Cairo 库;Vulkan 加载库和驱动提供 GPU 加速,缺失时用 CPU 渲染。 +- `-tags vivagtk` 构建 GTK 3 外壳:在 Wayland 会话里是原生客户端,按合成器要求的分数缩放绘制;在 X11 下经由 GTK 运行。窗口、指针、键盘和输入法交给 GTK,内容由 Viva 的 CPU 光栅器绘制,所以这个构建不用 Vulkan。运行环境需要安装系统的 GTK 3,公开 API 与默认构建相同。 - Pango 与 Cairo 负责文字。 - 可打包为带安装脚本的 `tar.gz` 或 `.deb`。 - 文件对话框、打开 URL 和通知使用已安装的桌面工具,见[系统集成](/zh/docs/system-integration/)。