// Package primary owns the Wayland primary selection: the text selected // last, which a middle click pastes. Gio's Wayland backend implements only // the clipboard, so this package keeps a Wayland connection of its own and // uses the ext-data-control-v1 protocol, which needs neither a surface nor // an input serial, as clipboard managers and wl-copy do. // // It speaks the Wayland wire protocol directly: a few dozen bytes per // message over the compositor's socket, with file descriptors passed // alongside, which is how selection data moves. package primary import ( "bytes" "context" "encoding/binary" "errors" "fmt" "io" "net" "os" "path/filepath" "strings" "sync" "syscall" "time" ) // The protocol's interfaces and versions this package binds. const ( seatInterface = "wl_seat" managerInterface = "ext_data_control_manager_v1" ) // Opcodes. Requests and events are numbered separately, in protocol order. const ( // wl_display displaySync = 0 displayGetRegistry = 1 displayError = 0 // event displayDeleteID = 1 // event // wl_registry registryBind = 0 registryGlobal = 0 // event // wl_callback callbackDone = 0 // event // ext_data_control_manager_v1 managerCreateSource = 0 managerGetDevice = 1 // ext_data_control_device_v1 deviceSetPrimary = 2 deviceDataOffer = 0 // event deviceSelection = 1 // event deviceFinished = 2 // event devicePrimary = 3 // event // ext_data_control_source_v1 sourceOffer = 0 sourceDestroy = 1 sourceSend = 0 // event sourceCancelled = 1 // event // ext_data_control_offer_v1 offerReceive = 0 offerDestroy = 1 offerOffer = 0 // event ) // textTypes are the MIME types text goes by, preferred first. var textTypes = []string{"text/plain;charset=utf-8", "UTF8_STRING", "text/plain", "TEXT", "STRING"} // ErrUnsupported means the compositor offers no ext-data-control, or this // isn't a Wayland session. var ErrUnsupported = errors.New("primary: the compositor offers no ext-data-control") // Selection is a connection that owns, and reads, the primary selection. // Its methods are safe for concurrent use. type Selection struct { conn *net.UnixConn wmu sync.Mutex // serializes writes mu sync.Mutex // Objects this client made, and what each one is. nextID uint32 kinds map[uint32]kind device uint32 offers map[uint32][]string // offers the compositor introduced, and their types primary uint32 // the offer that is the primary selection, or 0 sources map[uint32]string // this client's sources, and their text err error // why the connection ended done chan struct{} // Used while connecting, by the reading goroutine. globals map[string]global synced map[uint32]chan struct{} fds []int // received with the message being read } type kind int const ( kindRegistry kind = iota + 1 kindCallback kindSeat kindManager kindDevice kindSource kindOffer ) type global struct { name uint32 version uint32 } // Open connects to the Wayland compositor named by WAYLAND_DISPLAY and // takes part in its primary selection. It returns ErrUnsupported if the // compositor can't share it. func Open() (*Selection, error) { path := os.Getenv("WAYLAND_DISPLAY") if path == "" { return nil, ErrUnsupported } if !filepath.IsAbs(path) { path = filepath.Join(os.Getenv("XDG_RUNTIME_DIR"), path) } c, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { return nil, fmt.Errorf("primary: connect to %s: %w", path, err) } s := &Selection{ conn: c, nextID: 2, // 1 is wl_display kinds: make(map[uint32]kind), offers: make(map[uint32][]string), sources: make(map[uint32]string), globals: make(map[string]global), synced: make(map[uint32]chan struct{}), done: make(chan struct{}), } go s.readLoop() registry := s.newID(kindRegistry) if err := s.send(1, displayGetRegistry, u32(registry)); err != nil { s.Close() return nil, err } if err := s.roundtrip(); err != nil { s.Close() return nil, err } s.mu.Lock() seat, hasSeat := s.globals[seatInterface] manager, hasManager := s.globals[managerInterface] s.mu.Unlock() if !hasSeat || !hasManager { s.Close() return nil, ErrUnsupported } seatID := s.newID(kindSeat) managerID := s.newID(kindManager) device := s.newID(kindDevice) s.mu.Lock() s.device = device s.mu.Unlock() for _, err := range []error{ s.send(registry, registryBind, u32(seat.name), str(seatInterface), u32(1), u32(seatID)), s.send(registry, registryBind, u32(manager.name), str(managerInterface), u32(1), u32(managerID)), s.send(managerID, managerGetDevice, u32(device), u32(seatID)), } { if err != nil { s.Close() return nil, err } } // The device announces the current selections right away; wait for // them, so that Get works at once. if err := s.roundtrip(); err != nil { s.Close() return nil, err } return s, nil } // Close ends the connection. A primary selection this client owns goes // with it. func (s *Selection) Close() error { err := s.conn.Close() <-s.done return err } // Set makes text the primary selection. The compositor asks this client for // it whenever another client pastes, until something else is selected. func (s *Selection) Set(text string) error { s.mu.Lock() device, err := s.device, s.err s.mu.Unlock() if err != nil { return err } source := s.newID(kindSource) s.mu.Lock() s.sources[source] = text var manager uint32 for id, k := range s.kinds { if k == kindManager { manager = id } } s.mu.Unlock() if err := s.send(manager, managerCreateSource, u32(source)); err != nil { return err } for _, t := range textTypes { if err := s.send(source, sourceOffer, str(t)); err != nil { return err } } return s.send(device, deviceSetPrimary, u32(source)) } // Get returns the primary selection's text, or "" if there is none. func (s *Selection) Get(ctx context.Context) (string, error) { s.mu.Lock() offer, types, err := s.primary, s.offers[s.primary], s.err s.mu.Unlock() if err != nil { return "", err } if offer == 0 { return "", nil } mime := "" for _, t := range textTypes { for _, have := range types { if have == t && mime == "" { mime = t } } } if mime == "" { return "", nil // not text } var p [2]int if err := syscall.Pipe2(p[:], syscall.O_CLOEXEC); err != nil { return "", err } r := os.NewFile(uintptr(p[0]), "primary") defer r.Close() err = s.sendFD(offer, offerReceive, p[1], str(mime)) syscall.Close(p[1]) // the compositor has its own copy now if err != nil { return "", err } // The selection's owner writes it and closes its end. if deadline, ok := ctx.Deadline(); ok { r.SetReadDeadline(deadline) } else { r.SetReadDeadline(time.Now().Add(5 * time.Second)) } data, err := io.ReadAll(io.LimitReader(r, 16<<20)) if err != nil && !errors.Is(err, os.ErrDeadlineExceeded) { return "", err } return string(data), nil } func (s *Selection) newID(k kind) uint32 { s.mu.Lock() defer s.mu.Unlock() id := s.nextID s.nextID++ s.kinds[id] = k return id } // roundtrip waits until the compositor has handled every request sent so // far, and sent every event they caused. func (s *Selection) roundtrip() error { cb := s.newID(kindCallback) ch := make(chan struct{}) s.mu.Lock() s.synced[cb] = ch s.mu.Unlock() if err := s.send(1, displaySync, u32(cb)); err != nil { return err } select { case <-ch: return nil case <-s.done: s.mu.Lock() defer s.mu.Unlock() return s.err case <-time.After(5 * time.Second): return errors.New("primary: the compositor didn't answer") } } // arg is one encoded argument. type arg []byte func u32(v uint32) arg { return binary.LittleEndian.AppendUint32(nil, v) } // str encodes a string: its length with the terminating NUL, then the // bytes, padded to a multiple of 4. func str(v string) arg { b := binary.LittleEndian.AppendUint32(nil, uint32(len(v)+1)) b = append(b, v...) b = append(b, 0) for len(b)%4 != 0 { b = append(b, 0) } return b } // encode makes a message: the object, then the size and opcode, then the // arguments. func encode(object uint32, opcode uint16, args ...arg) []byte { size := 8 for _, a := range args { size += len(a) } b := make([]byte, 0, size) b = binary.LittleEndian.AppendUint32(b, object) b = binary.LittleEndian.AppendUint32(b, uint32(size)<<16|uint32(opcode)) for _, a := range args { b = append(b, a...) } return b } func (s *Selection) send(object uint32, opcode uint16, args ...arg) error { s.wmu.Lock() defer s.wmu.Unlock() _, err := s.conn.Write(encode(object, opcode, args...)) return err } // sendFD sends a message with a file descriptor alongside. func (s *Selection) sendFD(object uint32, opcode uint16, fd int, args ...arg) error { s.wmu.Lock() defer s.wmu.Unlock() _, _, err := s.conn.WriteMsgUnix(encode(object, opcode, args...), syscall.UnixRights(fd), nil) return err } func (s *Selection) readLoop() { err := s.read() s.mu.Lock() if s.err == nil { s.err = err if s.err == nil { s.err = errors.New("primary: connection closed") } } s.mu.Unlock() close(s.done) } func (s *Selection) read() error { buf := make([]byte, 0, 4096) chunk := make([]byte, 4096) oob := make([]byte, syscall.CmsgSpace(4*28)) for { n, oobn, _, _, err := s.conn.ReadMsgUnix(chunk, oob) if oobn > 0 { msgs, perr := syscall.ParseSocketControlMessage(oob[:oobn]) if perr == nil { for _, m := range msgs { if fds, err := syscall.ParseUnixRights(&m); err == nil { s.fds = append(s.fds, fds...) } } } } if err != nil { return err } buf = append(buf, chunk[:n]...) for len(buf) >= 8 { object := binary.LittleEndian.Uint32(buf) word := binary.LittleEndian.Uint32(buf[4:]) size, opcode := int(word>>16), uint16(word) if size < 8 { return fmt.Errorf("primary: bad message size %d", size) } if len(buf) < size { break } if err := s.handle(object, opcode, buf[8:size]); err != nil { return err } buf = buf[size:] } buf = append(buf[:0:0], buf...) } } // reader decodes event arguments. type reader struct { b []byte err error } func (r *reader) u32() uint32 { if len(r.b) < 4 { r.err = errors.New("primary: short message") return 0 } v := binary.LittleEndian.Uint32(r.b) r.b = r.b[4:] return v } func (r *reader) str() string { n := int(r.u32()) padded := (n + 3) &^ 3 if r.err != nil || len(r.b) < padded { r.err = errors.New("primary: short string") return "" } s := string(bytes.TrimRight(r.b[:n], "\x00")) r.b = r.b[padded:] return s } // takeFD returns the next file descriptor that came with the messages. func (s *Selection) takeFD() int { if len(s.fds) == 0 { return -1 } fd := s.fds[0] s.fds = s.fds[1:] return fd } func (s *Selection) handle(object uint32, opcode uint16, body []byte) error { r := &reader{b: body} if object == 1 { switch opcode { case displayError: obj, code, msg := r.u32(), r.u32(), r.str() return fmt.Errorf("primary: compositor error on object %d (code %d): %s", obj, code, msg) case displayDeleteID: id := r.u32() s.mu.Lock() delete(s.kinds, id) s.mu.Unlock() } return r.err } s.mu.Lock() k, known := s.kinds[object] if !known { if _, isOffer := s.offers[object]; isOffer { k, known = kindOffer, true } } s.mu.Unlock() if !known { return nil // an object already destroyed } switch k { case kindRegistry: if opcode == registryGlobal { name, iface, version := r.u32(), r.str(), r.u32() s.mu.Lock() if _, ok := s.globals[iface]; !ok { s.globals[iface] = global{name, version} } s.mu.Unlock() } case kindCallback: if opcode == callbackDone { s.mu.Lock() if ch, ok := s.synced[object]; ok { close(ch) delete(s.synced, object) } delete(s.kinds, object) s.mu.Unlock() } case kindDevice: switch opcode { case deviceDataOffer: id := r.u32() s.mu.Lock() s.offers[id] = nil s.mu.Unlock() case deviceSelection: // The clipboard: Gio handles it. Let its offer go. if id := r.u32(); id != 0 { s.dropOffer(id) } case devicePrimary: id := r.u32() s.mu.Lock() old := s.primary s.primary = id s.mu.Unlock() if old != 0 && old != id { s.dropOffer(old) } case deviceFinished: return errors.New("primary: the compositor ended the data device") } case kindOffer: if opcode == offerOffer { t := r.str() s.mu.Lock() if types, ok := s.offers[object]; ok { s.offers[object] = append(types, t) } s.mu.Unlock() } case kindSource: switch opcode { case sourceSend: _ = r.str() // every type offered is the same text fd := s.takeFD() s.mu.Lock() text := s.sources[object] s.mu.Unlock() if fd >= 0 { // Write in the background: the reader may be this // process, waiting on a pipe this goroutine must not // block. go func() { f := os.NewFile(uintptr(fd), "primary-send") _, _ = io.Copy(f, strings.NewReader(text)) f.Close() }() } case sourceCancelled: // Something else is the primary selection now. s.mu.Lock() delete(s.sources, object) s.mu.Unlock() _ = s.send(object, sourceDestroy) } } return r.err } // dropOffer destroys an offer the client has no use for. func (s *Selection) dropOffer(id uint32) { s.mu.Lock() delete(s.offers, id) s.mu.Unlock() _ = s.send(id, offerDestroy) }