Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/)。

Expand Down
85 changes: 85 additions & 0 deletions app/drag_files.go
Original file line number Diff line number Diff line change
@@ -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
}
64 changes: 64 additions & 0 deletions app/drag_files_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
29 changes: 29 additions & 0 deletions app/driver_system.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions app/driver_system_unsupported.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

package app

import "github.com/vivaui/viva/internal/platform"

func markNonNativeSystemUsed() {}

func driverClipboardText() (string, error, bool) { return "", nil, false }
Expand All @@ -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 }
Expand Down
3 changes: 2 additions & 1 deletion app/launch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions app/system_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions app/system_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down
5 changes: 5 additions & 0 deletions app/system_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions app/system_unsupported.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
4 changes: 4 additions & 0 deletions app/system_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions base/accessors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down
9 changes: 7 additions & 2 deletions base/color.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions base/paint.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions base/scroll.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
Loading
Loading