From 1fd5e0b1d673e8141249ca7b34fdb25ba64d7dd4 Mon Sep 17 00:00:00 2001 From: zhangkun Date: Wed, 2 Dec 2026 13:47:56 +0800 Subject: [PATCH 1/2] feat(wayland): add Go client and protocol scanner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Add a pure Go Wayland client with core bindings and opt-in protocol tracing. 2. Generate Go client bindings from protocol XML and replace output files atomically. 3. Add standalone CMake generation and cover wire interoperability and object lifecycle. Log: Add the Go Wayland client runtime and protocol scanner. Influence: Go clients can connect to Wayland compositors. feat(wayland): 新增 Go 客户端和协议生成器 1. 新增纯 Go Wayland 客户端,提供核心协议绑定和可选的协议日志。 2. 从协议 XML 生成 Go 客户端绑定,并原子替换输出文件。 3. 提供独立的 CMake 生成入口,覆盖协议互通和对象生命周期测试。 Log: 新增 Go Wayland 客户端运行时和协议生成器。 PMS: BUG-377251 Influence: Go 客户端可连接 Wayland 合成器。 --- .reuse/dep5 | 6 + LICENSES/MIT.txt | 21 + Makefile | 8 +- cmd/go-wayland-scanner/main.go | 442 +++++++++++++++++ cmd/go-wayland-scanner/main_test.go | 67 +++ debian/copyright | 25 + wayland/CMakeLists.txt | 40 ++ wayland/conn_linux.go | 334 +++++++++++++ wayland/conn_linux_test.go | 213 ++++++++ wayland/core/client.go | 57 +++ wayland/core/wayland-client-protocol.go | 625 ++++++++++++++++++++++++ wayland/debug_linux.go | 96 ++++ wayland/testdata/interop/client.go | 148 ++++++ wayland/testdata/interop/probe.xml | 49 ++ wayland/testdata/interop/run.sh | 59 +++ wayland/testdata/interop/server.c | 146 ++++++ wayland/wire_linux.go | 223 +++++++++ 17 files changed, 2557 insertions(+), 2 deletions(-) create mode 100644 LICENSES/MIT.txt create mode 100644 cmd/go-wayland-scanner/main.go create mode 100644 cmd/go-wayland-scanner/main_test.go create mode 100644 wayland/CMakeLists.txt create mode 100644 wayland/conn_linux.go create mode 100644 wayland/conn_linux_test.go create mode 100644 wayland/core/client.go create mode 100644 wayland/core/wayland-client-protocol.go create mode 100644 wayland/debug_linux.go create mode 100644 wayland/testdata/interop/client.go create mode 100644 wayland/testdata/interop/probe.xml create mode 100755 wayland/testdata/interop/run.sh create mode 100644 wayland/testdata/interop/server.c create mode 100644 wayland/wire_linux.go diff --git a/.reuse/dep5 b/.reuse/dep5 index 08f22cfa..c02199d4 100644 --- a/.reuse/dep5 +++ b/.reuse/dep5 @@ -68,6 +68,12 @@ Files: *_methods_auto.go *_dbusutil.go *_gen.go grub_theme/themetxt/grub_theme.p Copyright: UnionTech Software Technology Co., Ltd. License: GPL-3.0-or-later +Files: wayland/core/wayland-client-protocol.go +Copyright: 2008-2011 Kristian Høgsberg + 2010-2011 Intel Corporation + 2012-2013 Collabora, Ltd. +License: MIT + # go vendor dir Files: vendor/* Copyright: UnionTech Software Technology Co., Ltd. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 00000000..242da623 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile index c147573a..5035538d 100644 --- a/Makefile +++ b/Makefile @@ -38,7 +38,10 @@ TESTS = \ ${GOPKG_PREFIX}/sound-theme-player \ ${GOPKG_PREFIX}/soundutils \ ${GOPKG_PREFIX}/userenv \ - ${GOPKG_PREFIX}/validator + ${GOPKG_PREFIX}/validator \ + ${GOPKG_PREFIX}/cmd/go-wayland-scanner \ + ${GOPKG_PREFIX}/wayland \ + ${GOPKG_PREFIX}/wayland/core LIBRARIES = \ dxinput \ @@ -52,6 +55,7 @@ LIBRARIES = \ inhibit_hint \ powersupply \ polkit \ + wayland \ ININSTALLS = \ ${LIBRARIES} \ @@ -130,7 +134,7 @@ endif cp -R misc/icons/* ${DESTDIR}${PREFIX}/share/icons/hicolor build-dev: prepare - ${GOBUILD} $(addprefix ${GOPKG_PREFIX}/, ${LIBRARIES}) + ${GOBUILD} $(addprefix ${GOPKG_PREFIX}/, ${LIBRARIES}) ${GOPKG_PREFIX}/wayland/core install/lib/%: mkdir -pv ${DESTDIR}${GOSITE_DIR}/src/${GOPKG_PREFIX} diff --git a/cmd/go-wayland-scanner/main.go b/cmd/go-wayland-scanner/main.go new file mode 100644 index 00000000..3d9c8fd2 --- /dev/null +++ b/cmd/go-wayland-scanner/main.go @@ -0,0 +1,442 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "bytes" + "encoding/xml" + "flag" + "fmt" + "go/format" + "go/token" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "unicode" +) + +type protocol struct { + XMLName xml.Name `xml:"protocol"` + Copyright string `xml:"copyright"` + Interfaces []iface `xml:"interface"` +} + +type iface struct { + Name string `xml:"name,attr"` + Version uint32 `xml:"version,attr"` + Requests []message `xml:"request"` + Events []message `xml:"event"` + Enums []enum `xml:"enum"` +} + +type message struct { + Name string `xml:"name,attr"` + Since uint32 `xml:"since,attr"` + Type string `xml:"type,attr"` + Args []arg `xml:"arg"` +} + +type arg struct { + Name string `xml:"name,attr"` + Type string `xml:"type,attr"` + Interface string `xml:"interface,attr"` + Nullable bool `xml:"allow-null,attr"` +} + +type enum struct { + Name string `xml:"name,attr"` + Entries []struct { + Name string `xml:"name,attr"` + Value string `xml:"value,attr"` + } `xml:"entry"` +} + +func exported(s string) string { + var b strings.Builder + for _, part := range strings.FieldsFunc(s, func(r rune) bool { return r == '_' || r == '-' }) { + for i, r := range part { + if i == 0 { + r = unicode.ToUpper(r) + } + b.WriteRune(r) + } + } + return b.String() +} + +func (a arg) goType() string { + switch a.Type { + case "uint": + return "uint32" + case "int": + return "int32" + case "fixed": + return "wl.Fixed" + case "fd": + return "int" + case "array": + return "[]byte" + case "object", "new_id": + return "*wl.Object" + case "string": + if a.Nullable { + return "*string" + } + return "string" + } + return "" +} + +func (a arg) codec() string { + if a.Type == "string" && a.Nullable { + return "NullableString" + } + if a.Type == "fd" { + return "FD" + } + if a.Type == "new_id" { + return "NewID" + } + return exported(a.Type) +} + +func (a arg) extra() string { + switch a.Type { + case "object": + return fmt.Sprintf("%q, %t", a.Interface, a.Nullable) + case "new_id": + return fmt.Sprintf("%q", a.Interface) + } + return "" +} + +func (m message) since() uint32 { + if m.Since == 0 { + return 1 + } + return m.Since +} + +func readProtocol(path string) (protocol, error) { + f, err := os.Open(path) + if err != nil { + return protocol{}, err + } + defer f.Close() + var p protocol + d := xml.NewDecoder(f) + if err := d.Decode(&p); err != nil { + return protocol{}, err + } + for { + tok, err := d.Token() + if err == io.EOF { + return p, nil + } + if err != nil { + return protocol{}, err + } + switch v := tok.(type) { + case xml.Comment, xml.ProcInst: + continue + case xml.CharData: + if len(bytes.TrimSpace(v)) == 0 { + continue + } + } + return protocol{}, fmt.Errorf("unexpected content after ") + } +} + +func claimName(names map[string]string, name, source string) error { + if !token.IsIdentifier(name) { + return fmt.Errorf("%s generates invalid Go name %q", source, name) + } + if other, ok := names[name]; ok { + return fmt.Errorf("Go name %q conflicts between %s and %s", name, other, source) + } + names[name] = source + return nil +} + +func generate(out io.Writer, pkg string, files []string, only map[string]bool) error { + if !token.IsIdentifier(pkg) || pkg == "_" || len(files) == 0 { + return fmt.Errorf("a Go package name and at least one protocol XML are required") + } + var interfaces []iface + var copyrights []string + names := map[string]string{"Register": "protocol registration function", "wl": "runtime import"} + selected := make(map[string]bool) + for _, file := range files { + p, err := readProtocol(file) + if err != nil { + return fmt.Errorf("%s: %w", file, err) + } + if text := strings.TrimSpace(p.Copyright); text != "" { + copyrights = append(copyrights, text) + } + for _, i := range p.Interfaces { + if len(only) != 0 && !only[i.Name] { + continue + } + name := exported(i.Name) + if i.Version == 0 { + return fmt.Errorf("%s: interface %q has no version", file, i.Name) + } + for _, symbol := range []string{name, name + "Interface"} { + if err := claimName(names, symbol, "interface "+i.Name); err != nil { + return fmt.Errorf("%s: %w", file, err) + } + } + selected[i.Name] = true + interfaces = append(interfaces, i) + } + } + for name := range only { + if !selected[name] { + return fmt.Errorf("interface %q not found", name) + } + } + if len(interfaces) == 0 { + return fmt.Errorf("no interfaces found") + } + + var b bytes.Buffer + fmt.Fprintln(&b, "// Code generated by go-wayland-scanner; DO NOT EDIT.") + for _, text := range copyrights { + fmt.Fprintln(&b, "//") + for _, line := range strings.Split(text, "\n") { + fmt.Fprintln(&b, "// "+strings.TrimSpace(line)) + } + } + fmt.Fprintf(&b, "\npackage %s\n\nimport wl \"github.com/linuxdeepin/dde-api/wayland\"\n\n", pkg) + fmt.Fprintln(&b, "func Register(c *wl.Conn) { c.Register(") + for _, i := range interfaces { + fmt.Fprintf(&b, "&%sInterface,\n", exported(i.Name)) + } + fmt.Fprintln(&b, ") }") + for _, i := range interfaces { + if err := emitInterface(&b, i, names); err != nil { + return fmt.Errorf("%s: %w", i.Name, err) + } + } + formatted, err := format.Source(b.Bytes()) + if err != nil { + return fmt.Errorf("format generated Go: %w", err) + } + _, err = out.Write(formatted) + return err +} + +func emitInterface(b *bytes.Buffer, i iface, names map[string]string) error { + name := exported(i.Name) + fmt.Fprintf(b, "\ntype %s struct { *wl.Object }\n", name) + for _, e := range i.Enums { + for _, v := range e.Entries { + constant := name + exported(e.Name) + exported(v.Name) + if err := claimName(names, constant, "enum "+i.Name+"."+e.Name+"."+v.Name); err != nil { + return err + } + if _, err := strconv.ParseInt(v.Value, 0, 64); err != nil { + return fmt.Errorf("invalid enum value %q", v.Value) + } + fmt.Fprintf(b, "const %s = %s\n", constant, v.Value) + } + } + methods := make(map[string]string) + for _, name := range []string{"Object", "Version", "On", "Handler", "Request"} { + methods[name] = "embedded Wayland object" + } + for op, m := range i.Requests { + if err := validate(m, i.Version, false); err != nil { + return err + } + if err := claimName(methods, exported(m.Name), "request "+m.Name); err != nil { + return err + } + emitRequest(b, name, op, m) + } + fmt.Fprintf(b, "\nvar %sInterface = wl.Interface{Name: %q, Version: %d, Requests: []wl.Message{\n", name, i.Name, i.Version) + for _, m := range i.Requests { + fmt.Fprintf(b, "%s,\n", debugMessage(m)) + } + fmt.Fprintln(b, "}, Events: []wl.Event{") + var listeners bytes.Buffer + for op, m := range i.Events { + if err := validate(m, i.Version, true); err != nil { + return err + } + if err := claimName(methods, "On"+exported(m.Name), "event "+m.Name); err != nil { + return err + } + emitEvent(b, &listeners, name, op, m) + } + fmt.Fprintln(b, "}}") + b.Write(listeners.Bytes()) + return nil +} + +func validate(m message, version uint32, event bool) error { + if !token.IsIdentifier(exported(m.Name)) || m.since() > version || (m.Type != "" && m.Type != "destructor") { + return fmt.Errorf("invalid message %q", m.Name) + } + newIDs := 0 + for _, a := range m.Args { + if a.goType() == "" || (a.Nullable && a.Type != "object" && a.Type != "string") { + return fmt.Errorf("%s: unsupported %s argument %q", m.Name, a.Type, a.Name) + } + if a.Type == "new_id" { + newIDs++ + if newIDs > 1 || (event && a.Interface == "") { + return fmt.Errorf("%s: invalid new_id", m.Name) + } + } + } + return nil +} + +func emitRequest(b *bytes.Buffer, name string, op int, m message) { + var params, enc []string + result, binding, version := "error", `""`, "0" + for j, a := range m.Args { + v := fmt.Sprintf("arg%d", j) + if a.Type == "new_id" { + result = "(*wl.Object, error)" + if a.Interface == "" { + params = append(params, "interfaceName string", "version uint32") + binding, version = "interfaceName", "version" + enc = append(enc, "e.String(interfaceName)", "e.Uint(version)") + } else { + binding = fmt.Sprintf("%q", a.Interface) + } + enc = append(enc, "e.Uint(id)") + continue + } + params = append(params, v+" "+a.goType()) + if extra := a.extra(); extra != "" { + v += ", " + extra + } + enc = append(enc, fmt.Sprintf("e.%s(%s)", a.codec(), v)) + } + fmt.Fprintf(b, "func (p %s) %s(%s) %s {\n", name, exported(m.Name), strings.Join(params, ", "), result) + if binding == "interfaceName" { + fmt.Fprintln(b, `if interfaceName == "" || version == 0 { return nil, wl.ErrInvalidBinding }`) + } + if result == "error" { + fmt.Fprint(b, "_, err := ") + } else { + fmt.Fprint(b, "return ") + } + fmt.Fprintf(b, "p.Object.Request(%d, %d, %t, %s, %s, ", op, m.since(), m.Type == "destructor", binding, version) + if len(enc) == 0 { + fmt.Fprint(b, "nil") + } else { + fmt.Fprintln(b, "func(e *wl.Encoder, id uint32) {") + for _, line := range enc { + fmt.Fprintln(b, line) + } + fmt.Fprint(b, "}") + } + fmt.Fprintln(b, ")") + if result == "error" { + fmt.Fprintln(b, "return err") + } + fmt.Fprintln(b, "}") +} + +func debugMessage(m message) string { + var b strings.Builder + fmt.Fprintf(&b, "{Name: %q", m.Name) + if len(m.Args) != 0 { + b.WriteString(", Args: []wl.Argument{") + for _, a := range m.Args { + if a.Type == "new_id" && a.Interface == "" { + b.WriteString(`{Name: "interface", Type: "string"}, {Name: "version", Type: "uint"}, `) + } + fmt.Fprintf(&b, "{Name: %q, Type: %q", a.Name, a.Type) + if a.Interface != "" { + fmt.Fprintf(&b, ", Interface: %q", a.Interface) + } + b.WriteString("}, ") + } + b.WriteString("}") + } + b.WriteString("}") + return b.String() +} + +func emitEvent(b, listeners *bytes.Buffer, name string, op int, m message) { + var types, values []string + fds := 0 + for _, a := range m.Args { + if a.Type == "fd" { + fds++ + } + } + fmt.Fprintf(b, "{Message: wl.Message%s, Since: %d, Destructor: %t, FDs: %d, Decode: func(o *wl.Object, d *wl.Decoder) error {\n", debugMessage(m), m.since(), m.Type == "destructor", fds) + for j, a := range m.Args { + v := fmt.Sprintf("arg%d", j) + fmt.Fprintf(b, "%s := d.%s(%s)\n", v, a.codec(), a.extra()) + values = append(values, v) + types = append(types, a.goType()) + } + sig := "func(" + strings.Join(types, ", ") + ")" + fmt.Fprintf(b, "h, _ := o.Handler(%d).(%s)\n", op, sig) + fmt.Fprintln(b, "if err := d.Finish(h != nil); err != nil { return err }") + fmt.Fprintf(b, "if h != nil { h(%s) }; return nil\n}},\n", strings.Join(values, ", ")) + fmt.Fprintf(listeners, "func (p %s) On%s(h %s) { p.Object.On(%d, h) }\n", name, exported(m.Name), sig, op) +} + +func writeOutput(path string, data []byte) error { + f, err := os.CreateTemp(filepath.Dir(path), ".wayland-*.tmp") + if err != nil { + return err + } + defer os.Remove(f.Name()) + if _, err := f.Write(data); err != nil { + _ = f.Close() + return err + } + if err := f.Chmod(0644); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(f.Name(), path) +} + +func main() { + pkg := flag.String("package", "", "Go package of the generated bindings") + output := flag.String("o", "", "output Go file (stdout if omitted)") + filter := flag.String("interfaces", "", "comma-separated list of interfaces to emit (default: all)") + flag.Usage = func() { + fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s -package NAME [-o FILE] [options] PROTOCOL.xml ...\n", os.Args[0]) + flag.PrintDefaults() + } + flag.Parse() + only := make(map[string]bool) + if *filter != "" { + for _, name := range strings.Split(*filter, ",") { + only[strings.TrimSpace(name)] = true + } + } + var b bytes.Buffer + err := generate(&b, *pkg, flag.Args(), only) + if err == nil { + if *output == "" { + _, err = b.WriteTo(os.Stdout) + } else { + err = writeOutput(*output, b.Bytes()) + } + } + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/cmd/go-wayland-scanner/main_test.go b/cmd/go-wayland-scanner/main_test.go new file mode 100644 index 00000000..57b9f04d --- /dev/null +++ b/cmd/go-wayland-scanner/main_test.go @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "bytes" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestGenerateRejectsInvalidInput(t *testing.T) { + for _, tc := range []struct { + name, xml, want string + }{ + {"second root", ``, "unexpected content after "}, + {"trailing syntax error", `<`, "XML syntax error"}, + {"descriptor collision", ``, `Go name "DemoInterface" conflicts`}, + {"method collision", ``, `Go name "OnDone" conflicts`}, + {"runtime method collision", ``, `Go name "Version" conflicts`}, + {"constant collision", ``, `Go name "DemoAbCD" conflicts`}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "demo.xml") + if err := os.WriteFile(path, []byte(``+tc.xml), 0600); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + err := generate(&out, "demo", []string{path}, nil) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("generate error = %v, want %q", err, tc.want) + } + if out.Len() != 0 { + t.Fatalf("generated %d bytes despite invalid input", out.Len()) + } + }) + } +} + +func TestWriteOutputReplacesFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "bindings.go") + old := []byte("package old\n") + if err := os.WriteFile(path, old, 0644); err != nil { + t.Fatal(err) + } + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + next := []byte("package fresh\n") + if err := writeOutput(path, next); err != nil { + t.Fatal(err) + } + previous, err := io.ReadAll(f) + if err != nil || !bytes.Equal(previous, old) { + t.Fatalf("existing reader sees %q, want %q: %v", previous, old, err) + } + current, err := os.ReadFile(path) + if err != nil || !bytes.Equal(current, next) { + t.Fatalf("new reader sees %q, want %q: %v", current, next, err) + } +} diff --git a/debian/copyright b/debian/copyright index 68e3a5be..ea5f0e3e 100644 --- a/debian/copyright +++ b/debian/copyright @@ -19,3 +19,28 @@ License: GPL-3+ . On Debian systems, the complete text of the GNU General Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". + +Files: wayland/core/wayland-client-protocol.go +Copyright: 2008-2011 Kristian Høgsberg + 2010-2011 Intel Corporation + 2012-2013 Collabora, Ltd. +License: Expat + +License: Expat + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + . + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + . + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. diff --git a/wayland/CMakeLists.txt b/wayland/CMakeLists.txt new file mode 100644 index 00000000..6e59943c --- /dev/null +++ b/wayland/CMakeLists.txt @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +# +# SPDX-License-Identifier: GPL-3.0-or-later + +cmake_minimum_required(VERSION 3.17) +project(DDEGoWayland LANGUAGES NONE) + +find_program(GO_EXECUTABLE go REQUIRED) +set(WAYLAND_CORE_XML "/usr/share/wayland/wayland.xml" CACHE FILEPATH "Wayland core protocol XML") +set(WAYLAND_PROTOCOL_XML "" CACHE FILEPATH "Optional extension protocol XML") +set(WAYLAND_PROTOCOL_PACKAGE inputmanager CACHE STRING "Go package for the extension bindings") + +function(dde_generate_wayland_client output package xml) + get_filename_component(output_dir "${output}" DIRECTORY) + set(scanner "${CMAKE_CURRENT_SOURCE_DIR}/../cmd/go-wayland-scanner/main.go") + file(GENERATE OUTPUT "${output}.settings" CONTENT "${package}\n${xml}\n${ARGN}\n") + add_custom_command(OUTPUT "${output}" + COMMAND "${CMAKE_COMMAND}" -E make_directory "${output_dir}" + COMMAND "${CMAKE_COMMAND}" -E env --unset=GOOS --unset=GOARCH --unset=GOFLAGS + GOENV=off GO111MODULE=off CGO_ENABLED=0 "${GO_EXECUTABLE}" run "${scanner}" + -package "${package}" -o "${output}" ${ARGN} "${xml}" + DEPENDS "${scanner}" "${xml}" "${output}.settings" + VERBATIM) +endfunction() + +set(core "${CMAKE_CURRENT_BINARY_DIR}/core/wayland-client-protocol.go") +dde_generate_wayland_client("${core}" core "${WAYLAND_CORE_XML}" + -interfaces wl_display,wl_registry,wl_callback,wl_seat,wl_pointer,wl_keyboard,wl_touch) +set(bindings "${core}") +if(WAYLAND_PROTOCOL_XML) + get_filename_component(protocol_name "${WAYLAND_PROTOCOL_XML}" NAME_WE) + set(extension "${CMAKE_CURRENT_BINARY_DIR}/${WAYLAND_PROTOCOL_PACKAGE}/wayland-${protocol_name}-client-protocol.go") + dde_generate_wayland_client("${extension}" "${WAYLAND_PROTOCOL_PACKAGE}" "${WAYLAND_PROTOCOL_XML}") + list(APPEND bindings "${extension}") +endif() +add_custom_target(wayland-client-bindings ALL DEPENDS ${bindings}) + +enable_testing() +add_test(NAME wayland-client-interop COMMAND sh "${CMAKE_CURRENT_SOURCE_DIR}/testdata/interop/run.sh") +set_tests_properties(wayland-client-interop PROPERTIES TIMEOUT 60) diff --git a/wayland/conn_linux.go b/wayland/conn_linux.go new file mode 100644 index 00000000..ac3d7049 --- /dev/null +++ b/wayland/conn_linux.go @@ -0,0 +1,334 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package wayland is the transport for generated Go Wayland clients. +package wayland + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "syscall" + "time" + "unsafe" +) + +var order binary.ByteOrder = binary.LittleEndian + +func init() { + x := uint16(1) + if *(*byte)(unsafe.Pointer(&x)) == 0 { + order = binary.BigEndian + } +} + +const serverID = 0xff000000 + +var ErrInvalidBinding = errors.New("Wayland bind requires an interface name and nonzero version") + +// Interface describes a generated protocol object's requests and events. +type Interface struct { + Name string + Version uint32 + Requests []Message + Events []Event +} + +type Event struct { + Message Message + Since uint32 + FDs int + Destructor bool + Decode func(*Object, *Decoder) error +} + +type Object struct { + conn *Conn + id, version uint32 + spec *Interface + dead bool + handlers map[uint16]any +} + +func (o *Object) Version() uint32 { return o.version } + +func (o *Object) On(opcode uint16, handler any) { + if o.handlers == nil { + o.handlers = make(map[uint16]any) + } + o.handlers[opcode] = handler +} + +func (o *Object) Handler(opcode uint16) any { + if o.dead { + return nil + } + return o.handlers[opcode] +} + +// Conn is owned by one goroutine. Handlers may send requests but must not +// dispatch recursively. Close releases file descriptors not yet delivered. +type Conn struct { + sock *net.UnixConn + objects map[uint32]*Object + interfaces map[string]*Interface + next uint32 + free []uint32 + in []byte + readAt int + fds []int + out []byte + sendFDs []int + debug bool + oob [2048]byte +} + +func Dial(ctx context.Context, display *Interface) (*Conn, *Object, error) { + name := os.Getenv("WAYLAND_DISPLAY") + if name == "" { + name = "wayland-0" + } + if !filepath.IsAbs(name) { + dir := os.Getenv("XDG_RUNTIME_DIR") + if dir == "" { + return nil, nil, fmt.Errorf("XDG_RUNTIME_DIR is unset") + } + name = filepath.Join(dir, name) + } + var dialer net.Dialer + sock, err := dialer.DialContext(ctx, "unix", name) + if err != nil { + return nil, nil, err + } + c, root := NewConn(sock.(*net.UnixConn), display) + return c, root, nil +} + +// NewConn takes ownership of an already connected socket. +func NewConn(sock *net.UnixConn, display *Interface) (*Conn, *Object) { + c := &Conn{sock: sock, objects: make(map[uint32]*Object), interfaces: make(map[string]*Interface), next: 2} + c.debug = clientDebugEnabled(os.Getenv("WAYLAND_DEBUG")) + root := c.add(1, display, 1) + return c, root +} + +func (c *Conn) SetDeadline(t time.Time) error { return c.sock.SetDeadline(t) } + +func (c *Conn) Close() error { + for _, fd := range c.fds { + _ = syscall.Close(fd) + } + c.fds = nil + return c.sock.Close() +} + +func (c *Conn) Register(specs ...*Interface) { + for _, spec := range specs { + c.interfaces[spec.Name] = spec + } +} + +func (c *Conn) add(id uint32, spec *Interface, version uint32) *Object { + o := &Object{conn: c, id: id, version: version, spec: spec} + c.objects[id] = o + return o +} + +// DeleteID handles wl_display.delete_id. An ID cannot be reused until the +// server has acknowledged its destruction. +func (c *Conn) DeleteID(id uint32) { + if o := c.objects[id]; id > 1 && id < serverID && o != nil { + o.destroy() + delete(c.objects, id) + c.free = append(c.free, id) + } +} + +func (o *Object) destroy() { + o.dead = true + o.handlers = nil + if o.id >= serverID { + delete(o.conn.objects, o.id) + } +} + +// Request is used by generated bindings. A non-empty childName describes an +// XML new_id; version zero inherits the parent's version, capped by the child. +func (o *Object) Request(opcode uint16, since uint32, destructor bool, childName string, version uint32, encode func(*Encoder, uint32)) (*Object, error) { + if o.dead || o.version < since { + return nil, fmt.Errorf("%s request %d unavailable on object version %d", o.spec.Name, opcode, o.version) + } + c := o.conn + var id uint32 + var spec *Interface + if childName != "" { + spec = c.interfaces[childName] + if spec == nil { + return nil, fmt.Errorf("unregistered Wayland interface %q", childName) + } + if version == 0 { + version = childVersion(o.version, spec.Version) + } else if version > spec.Version { + return nil, fmt.Errorf("unsupported %s version %d", childName, version) + } + if n := len(c.free); n != 0 { + id = c.free[n-1] + } else if c.next < serverID { + id = c.next + } else { + return nil, fmt.Errorf("Wayland object IDs exhausted") + } + } + e := Encoder{conn: c, data: append(c.out[:0], 0, 0, 0, 0, 0, 0, 0, 0), fds: c.sendFDs[:0]} + if encode != nil { + encode(&e, id) + } + c.out, c.sendFDs = e.data, e.fds + if e.err != nil { + return nil, e.err + } + order.PutUint32(e.data, o.id) + order.PutUint32(e.data[4:], uint32(len(e.data))<<16|uint32(opcode)) + var n int + var err error + if len(e.fds) != 0 { + var on int + oob := syscall.UnixRights(e.fds...) + n, on, err = c.sock.WriteMsgUnix(e.data, oob, nil) + if err == nil && on != len(oob) { + err = io.ErrShortWrite + } + if err == nil && n < len(e.data) { + var rest int + rest, err = c.sock.Write(e.data[n:]) + n += rest + } + } else { + n, err = c.sock.Write(e.data) + } + if err != nil || n != len(e.data) { + _ = c.Close() + if err == nil { + err = io.ErrShortWrite + } + return nil, err + } + if c.debug && int(opcode) < len(o.spec.Requests) { + o.trace("->", &o.spec.Requests[opcode], e.data[8:], e.fds, childName) + } + if destructor { + o.destroy() + } + if spec == nil { + return nil, nil + } + if n := len(c.free); n != 0 { + c.free = c.free[:n-1] + } else { + c.next++ + } + return c.add(id, spec, version), nil +} + +func childVersion(parent, max uint32) uint32 { + if parent < max { + return parent + } + return max +} + +func (c *Conn) receive() error { + if c.readAt > 0 && cap(c.in)-len(c.in) < maxMessage { + c.in = append(c.in[:0], c.in[c.readAt:]...) + c.readAt = 0 + } + if cap(c.in) == 0 { + c.in = make([]byte, 0, 2*maxMessage) + } + if len(c.in) == cap(c.in) { + return fmt.Errorf("Wayland message or descriptors out of sequence") + } + n, on, flags, _, err := c.sock.ReadMsgUnix(c.in[len(c.in):cap(c.in)], c.oob[:]) + if err != nil { + return err + } + if on != 0 { + msgs, err := syscall.ParseSocketControlMessage(c.oob[:on]) + if err != nil { + return err + } + for _, msg := range msgs { + if msg.Header.Level == syscall.SOL_SOCKET && msg.Header.Type == syscall.SCM_RIGHTS { + fds, err := syscall.ParseUnixRights(&msg) + if err != nil { + return err + } + c.fds = append(c.fds, fds...) + } + } + } + if len(c.fds) > 256 { + return fmt.Errorf("too many pending Wayland file descriptors") + } + if flags&syscall.MSG_CTRUNC != 0 { + return fmt.Errorf("truncated Wayland ancillary data") + } + if n == 0 { + return io.EOF + } + c.in = c.in[:len(c.in)+n] + return nil +} + +// Dispatch processes one event. A read or decode error closes the connection. +func (c *Conn) Dispatch() error { + err := c.dispatch() + if err != nil { + _ = c.Close() + } + return err +} + +func (c *Conn) dispatch() error { + for len(c.in)-c.readAt < 8 { + if err := c.receive(); err != nil { + return err + } + } + id, word := order.Uint32(c.in[c.readAt:]), order.Uint32(c.in[c.readAt+4:]) + size, opcode := int(word>>16), uint16(word) + if size < 8 || size > maxMessage || size%4 != 0 { + return fmt.Errorf("invalid Wayland message size %d", size) + } + o := c.objects[id] + if o == nil || int(opcode) >= len(o.spec.Events) || o.spec.Events[opcode].Since > o.version { + return fmt.Errorf("invalid Wayland event %d on object %d", opcode, id) + } + event := &o.spec.Events[opcode] + for len(c.in)-c.readAt < size || len(c.fds) < event.FDs { + if err := c.receive(); err != nil { + return err + } + } + d := Decoder{object: o, data: c.in[c.readAt+8 : c.readAt+size], discard: o.dead, destructor: event.Destructor} + if c.debug { + d.traceMessage = &event.Message + d.traceData = d.data + } + if err := event.Decode(o, &d); err != nil { + d.closeFDs() + return fmt.Errorf("%s event %d: %w", o.spec.Name, opcode, err) + } + c.readAt += size + if c.readAt == len(c.in) { + c.in = c.in[:0] + c.readAt = 0 + } + return nil +} diff --git a/wayland/conn_linux_test.go b/wayland/conn_linux_test.go new file mode 100644 index 00000000..bf5de91d --- /dev/null +++ b/wayland/conn_linux_test.go @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package wayland + +import ( + "bytes" + "fmt" + "io" + "net" + "os" + "strings" + "syscall" + "testing" + "time" +) + +func testSockets(t *testing.T) [2]*net.UnixConn { + t.Helper() + pair, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0) + if err != nil { + t.Fatal(err) + } + var sockets [2]*net.UnixConn + for i, fd := range pair { + f := os.NewFile(uintptr(fd), "wayland-socket") + sock, err := net.FileConn(f) + _ = f.Close() + if err != nil { + t.Fatal(err) + } + sockets[i] = sock.(*net.UnixConn) + t.Cleanup(func() { _ = sock.Close() }) + if err := sock.SetDeadline(time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + } + return sockets +} + +func TestDispatchQueuedFD(t *testing.T) { + sockets := testSockets(t) + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + if _, err := w.WriteString("keymap"); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + var data [16]byte + for i := 0; i < 2; i++ { + order.PutUint32(data[8*i:], 1) + order.PutUint32(data[8*i+4:], 8<<16|uint32(i)) + } + if _, _, err := sockets[1].WriteMsgUnix(data[:1], syscall.UnixRights(int(r.Fd())), nil); err != nil { + t.Fatal(err) + } + if _, err := sockets[1].Write(data[1:]); err != nil { + t.Fatal(err) + } + var payload string + c, _ := NewConn(sockets[0], &Interface{Name: "test_display", Version: 1, Events: []Event{ + {Since: 1, Decode: func(_ *Object, d *Decoder) error { return d.Finish(false) }}, + {Since: 1, FDs: 1, Decode: func(_ *Object, d *Decoder) error { + fd := d.FD() + if err := d.Finish(true); err != nil { + return err + } + file := os.NewFile(uintptr(fd), "keymap") + defer file.Close() + flags, _, errno := syscall.Syscall(syscall.SYS_FCNTL, uintptr(fd), syscall.F_GETFD, 0) + if errno != 0 || flags&syscall.FD_CLOEXEC == 0 { + return fmt.Errorf("received descriptor is not close-on-exec: flags=%d errno=%v", flags, errno) + } + b, err := io.ReadAll(file) + payload = string(b) + return err + }}, + }}) + defer c.Close() + for i := 0; i < 2; i++ { + if err := c.Dispatch(); err != nil { + t.Fatal(err) + } + } + if payload != "keymap" { + t.Fatalf("received fd contains %q, want keymap", payload) + } +} + +func sendEvent(t *testing.T, socket *net.UnixConn, id uint32, opcode uint16, encode func(*Encoder)) { + t.Helper() + e := Encoder{data: make([]byte, 8)} + if encode != nil { + encode(&e) + } + if e.err != nil { + t.Fatal(e.err) + } + order.PutUint32(e.data, id) + order.PutUint32(e.data[4:], uint32(len(e.data))<<16|uint32(opcode)) + if _, err := socket.Write(e.data); err != nil { + t.Fatal(err) + } +} + +func TestEventArraySurvivesNextReceive(t *testing.T) { + sockets := testSockets(t) + var got [][]byte + c, _ := NewConn(sockets[0], &Interface{Name: "test_display", Version: 1, Events: []Event{ + {Since: 1, Decode: func(_ *Object, d *Decoder) error { + v := d.Array() + if err := d.Finish(true); err != nil { + return err + } + got = append(got, v) + return nil + }}, + }}) + defer c.Close() + for _, value := range [][]byte{{1, 2, 3}, {4, 5, 6}} { + sendEvent(t, sockets[1], 1, 0, func(e *Encoder) { e.Array(value) }) + if err := c.Dispatch(); err != nil { + t.Fatal(err) + } + } + if !bytes.Equal(got[0], []byte{1, 2, 3}) || !bytes.Equal(got[1], []byte{4, 5, 6}) { + t.Fatalf("retained arrays changed after next receive: %v", got) + } +} + +func TestDestroyedObjectRejectsRequests(t *testing.T) { + sockets := testSockets(t) + spec := &Interface{Name: "test_object", Version: 1, Events: []Event{ + {Since: 1, Destructor: true, Decode: func(o *Object, d *Decoder) error { + h := o.Handler(0).(func()) + if err := d.Finish(true); err != nil { + return err + } + h() + return nil + }}, + }} + c, root := NewConn(sockets[0], &Interface{Name: "test_display", Version: 1, Events: []Event{ + {Since: 1, Decode: func(_ *Object, d *Decoder) error { + id := d.Uint() + if err := d.Finish(true); err != nil { + return err + } + c := d.object.conn + c.DeleteID(id) + return nil + }}, + }}) + defer c.Close() + c.Register(spec) + makeObject := func() *Object { + o, err := root.Request(0, 1, false, spec.Name, 0, func(e *Encoder, id uint32) { e.Uint(id) }) + if err != nil { + t.Fatal(err) + } + return o + } + ended := makeObject() + called := false + ended.On(0, func() { + called = true + if _, err := ended.Request(0, 1, false, "", 0, nil); err == nil { + t.Error("destructor callback was able to send a request on its destroyed object") + } + }) + sendEvent(t, sockets[1], ended.id, 0, nil) + if err := c.Dispatch(); err != nil { + t.Fatal(err) + } + if !called { + t.Fatal("destructor callback not delivered") + } + live := makeObject() + for _, id := range []uint32{ended.id, live.id, live.id} { + sendEvent(t, sockets[1], 1, 0, func(e *Encoder) { e.Uint(id) }) + if err := c.Dispatch(); err != nil { + t.Fatal(err) + } + } + if _, err := live.Request(0, 1, false, "", 0, nil); err == nil { + t.Fatal("server-deleted object was able to send a request") + } + if a, b := makeObject(), makeObject(); a.id != live.id || b.id != ended.id { + t.Fatalf("deleted IDs were not recycled exactly once: %d, %d", a.id, b.id) + } +} + +func TestUnhandledConstructorEventFailsDispatch(t *testing.T) { + sockets := testSockets(t) + c, _ := NewConn(sockets[0], &Interface{Name: "test_display", Version: 1, Events: []Event{ + {Since: 1, Decode: func(_ *Object, d *Decoder) error { + d.NewID("test_child") + return d.Finish(false) + }}, + }}) + defer c.Close() + c.Register(&Interface{Name: "test_child", Version: 1}) + sendEvent(t, sockets[1], 1, 0, func(e *Encoder) { e.Uint(serverID) }) + if err := c.Dispatch(); err == nil || !strings.Contains(err.Error(), "unhandled Wayland event creating an object") { + t.Fatalf("dispatch with no constructor listener: %v", err) + } +} diff --git a/wayland/core/client.go b/wayland/core/client.go new file mode 100644 index 00000000..bd0fdff5 --- /dev/null +++ b/wayland/core/client.go @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package core + +import ( + "context" + "fmt" + + "github.com/linuxdeepin/dde-api/wayland" +) + +type Display struct { + WlDisplay + *wayland.Conn + protocolError error +} + +func Connect(ctx context.Context) (*Display, error) { + conn, root, err := wayland.Dial(ctx, &WlDisplayInterface) + if err != nil { + return nil, err + } + Register(conn) + d := &Display{WlDisplay: WlDisplay{root}, Conn: conn} + d.OnError(func(_ *wayland.Object, code uint32, message string) { + d.protocolError = fmt.Errorf("Wayland protocol error %d: %s", code, message) + }) + d.OnDeleteId(conn.DeleteID) + return d, nil +} + +func (d *Display) Dispatch() error { + if d.protocolError != nil { + return d.protocolError + } + if err := d.Conn.Dispatch(); err != nil { + return err + } + return d.protocolError +} + +func (d *Display) Roundtrip() error { + obj, err := d.Sync() + if err != nil { + return err + } + done := false + WlCallback{obj}.OnDone(func(uint32) { done = true }) + for !done { + if err := d.Dispatch(); err != nil { + return err + } + } + return nil +} diff --git a/wayland/core/wayland-client-protocol.go b/wayland/core/wayland-client-protocol.go new file mode 100644 index 00000000..85462666 --- /dev/null +++ b/wayland/core/wayland-client-protocol.go @@ -0,0 +1,625 @@ +// Code generated by go-wayland-scanner; DO NOT EDIT. +// +// Copyright © 2008-2011 Kristian Høgsberg +// Copyright © 2010-2011 Intel Corporation +// Copyright © 2012-2013 Collabora, Ltd. +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation files +// (the "Software"), to deal in the Software without restriction, +// including without limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of the Software, +// and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice (including the +// next paragraph) shall be included in all copies or substantial +// portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package core + +import wl "github.com/linuxdeepin/dde-api/wayland" + +func Register(c *wl.Conn) { + c.Register( + &WlDisplayInterface, + &WlRegistryInterface, + &WlCallbackInterface, + &WlSeatInterface, + &WlPointerInterface, + &WlKeyboardInterface, + &WlTouchInterface, + ) +} + +type WlDisplay struct{ *wl.Object } + +const WlDisplayErrorInvalidObject = 0 +const WlDisplayErrorInvalidMethod = 1 +const WlDisplayErrorNoMemory = 2 +const WlDisplayErrorImplementation = 3 + +func (p WlDisplay) Sync() (*wl.Object, error) { + return p.Object.Request(0, 1, false, "wl_callback", 0, func(e *wl.Encoder, id uint32) { + e.Uint(id) + }) +} +func (p WlDisplay) GetRegistry() (*wl.Object, error) { + return p.Object.Request(1, 1, false, "wl_registry", 0, func(e *wl.Encoder, id uint32) { + e.Uint(id) + }) +} + +var WlDisplayInterface = wl.Interface{Name: "wl_display", Version: 1, Requests: []wl.Message{ + {Name: "sync", Args: []wl.Argument{{Name: "callback", Type: "new_id", Interface: "wl_callback"}}}, + {Name: "get_registry", Args: []wl.Argument{{Name: "registry", Type: "new_id", Interface: "wl_registry"}}}, +}, Events: []wl.Event{ + {Message: wl.Message{Name: "error", Args: []wl.Argument{{Name: "object_id", Type: "object"}, {Name: "code", Type: "uint"}, {Name: "message", Type: "string"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Object("", false) + arg1 := d.Uint() + arg2 := d.String() + h, _ := o.Handler(0).(func(*wl.Object, uint32, string)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2) + } + return nil + }}, + {Message: wl.Message{Name: "delete_id", Args: []wl.Argument{{Name: "id", Type: "uint"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + h, _ := o.Handler(1).(func(uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0) + } + return nil + }}, +}} + +func (p WlDisplay) OnError(h func(*wl.Object, uint32, string)) { p.Object.On(0, h) } +func (p WlDisplay) OnDeleteId(h func(uint32)) { p.Object.On(1, h) } + +type WlRegistry struct{ *wl.Object } + +func (p WlRegistry) Bind(arg0 uint32, interfaceName string, version uint32) (*wl.Object, error) { + if interfaceName == "" || version == 0 { + return nil, wl.ErrInvalidBinding + } + return p.Object.Request(0, 1, false, interfaceName, version, func(e *wl.Encoder, id uint32) { + e.Uint(arg0) + e.String(interfaceName) + e.Uint(version) + e.Uint(id) + }) +} + +var WlRegistryInterface = wl.Interface{Name: "wl_registry", Version: 1, Requests: []wl.Message{ + {Name: "bind", Args: []wl.Argument{{Name: "name", Type: "uint"}, {Name: "interface", Type: "string"}, {Name: "version", Type: "uint"}, {Name: "id", Type: "new_id"}}}, +}, Events: []wl.Event{ + {Message: wl.Message{Name: "global", Args: []wl.Argument{{Name: "name", Type: "uint"}, {Name: "interface", Type: "string"}, {Name: "version", Type: "uint"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.String() + arg2 := d.Uint() + h, _ := o.Handler(0).(func(uint32, string, uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2) + } + return nil + }}, + {Message: wl.Message{Name: "global_remove", Args: []wl.Argument{{Name: "name", Type: "uint"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + h, _ := o.Handler(1).(func(uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0) + } + return nil + }}, +}} + +func (p WlRegistry) OnGlobal(h func(uint32, string, uint32)) { p.Object.On(0, h) } +func (p WlRegistry) OnGlobalRemove(h func(uint32)) { p.Object.On(1, h) } + +type WlCallback struct{ *wl.Object } + +var WlCallbackInterface = wl.Interface{Name: "wl_callback", Version: 1, Requests: []wl.Message{}, Events: []wl.Event{ + {Message: wl.Message{Name: "done", Args: []wl.Argument{{Name: "callback_data", Type: "uint"}}}, Since: 1, Destructor: true, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + h, _ := o.Handler(0).(func(uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0) + } + return nil + }}, +}} + +func (p WlCallback) OnDone(h func(uint32)) { p.Object.On(0, h) } + +type WlSeat struct{ *wl.Object } + +const WlSeatCapabilityPointer = 1 +const WlSeatCapabilityKeyboard = 2 +const WlSeatCapabilityTouch = 4 +const WlSeatErrorMissingCapability = 0 + +func (p WlSeat) GetPointer() (*wl.Object, error) { + return p.Object.Request(0, 1, false, "wl_pointer", 0, func(e *wl.Encoder, id uint32) { + e.Uint(id) + }) +} +func (p WlSeat) GetKeyboard() (*wl.Object, error) { + return p.Object.Request(1, 1, false, "wl_keyboard", 0, func(e *wl.Encoder, id uint32) { + e.Uint(id) + }) +} +func (p WlSeat) GetTouch() (*wl.Object, error) { + return p.Object.Request(2, 1, false, "wl_touch", 0, func(e *wl.Encoder, id uint32) { + e.Uint(id) + }) +} +func (p WlSeat) Release() error { + _, err := p.Object.Request(3, 5, true, "", 0, nil) + return err +} + +var WlSeatInterface = wl.Interface{Name: "wl_seat", Version: 11, Requests: []wl.Message{ + {Name: "get_pointer", Args: []wl.Argument{{Name: "id", Type: "new_id", Interface: "wl_pointer"}}}, + {Name: "get_keyboard", Args: []wl.Argument{{Name: "id", Type: "new_id", Interface: "wl_keyboard"}}}, + {Name: "get_touch", Args: []wl.Argument{{Name: "id", Type: "new_id", Interface: "wl_touch"}}}, + {Name: "release"}, +}, Events: []wl.Event{ + {Message: wl.Message{Name: "capabilities", Args: []wl.Argument{{Name: "capabilities", Type: "uint"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + h, _ := o.Handler(0).(func(uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0) + } + return nil + }}, + {Message: wl.Message{Name: "name", Args: []wl.Argument{{Name: "name", Type: "string"}}}, Since: 2, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.String() + h, _ := o.Handler(1).(func(string)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0) + } + return nil + }}, +}} + +func (p WlSeat) OnCapabilities(h func(uint32)) { p.Object.On(0, h) } +func (p WlSeat) OnName(h func(string)) { p.Object.On(1, h) } + +type WlPointer struct{ *wl.Object } + +const WlPointerErrorRole = 0 +const WlPointerButtonStateReleased = 0 +const WlPointerButtonStatePressed = 1 +const WlPointerAxisVerticalScroll = 0 +const WlPointerAxisHorizontalScroll = 1 +const WlPointerAxisSourceWheel = 0 +const WlPointerAxisSourceFinger = 1 +const WlPointerAxisSourceContinuous = 2 +const WlPointerAxisSourceWheelTilt = 3 +const WlPointerAxisRelativeDirectionIdentical = 0 +const WlPointerAxisRelativeDirectionInverted = 1 + +func (p WlPointer) SetCursor(arg0 uint32, arg1 *wl.Object, arg2 int32, arg3 int32) error { + _, err := p.Object.Request(0, 1, false, "", 0, func(e *wl.Encoder, id uint32) { + e.Uint(arg0) + e.Object(arg1, "wl_surface", true) + e.Int(arg2) + e.Int(arg3) + }) + return err +} +func (p WlPointer) Release() error { + _, err := p.Object.Request(1, 3, true, "", 0, nil) + return err +} + +var WlPointerInterface = wl.Interface{Name: "wl_pointer", Version: 11, Requests: []wl.Message{ + {Name: "set_cursor", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "surface", Type: "object", Interface: "wl_surface"}, {Name: "hotspot_x", Type: "int"}, {Name: "hotspot_y", Type: "int"}}}, + {Name: "release"}, +}, Events: []wl.Event{ + {Message: wl.Message{Name: "enter", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "surface", Type: "object", Interface: "wl_surface"}, {Name: "surface_x", Type: "fixed"}, {Name: "surface_y", Type: "fixed"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Object("wl_surface", false) + arg2 := d.Fixed() + arg3 := d.Fixed() + h, _ := o.Handler(0).(func(uint32, *wl.Object, wl.Fixed, wl.Fixed)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2, arg3) + } + return nil + }}, + {Message: wl.Message{Name: "leave", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "surface", Type: "object", Interface: "wl_surface"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Object("wl_surface", false) + h, _ := o.Handler(1).(func(uint32, *wl.Object)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, + {Message: wl.Message{Name: "motion", Args: []wl.Argument{{Name: "time", Type: "uint"}, {Name: "surface_x", Type: "fixed"}, {Name: "surface_y", Type: "fixed"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Fixed() + arg2 := d.Fixed() + h, _ := o.Handler(2).(func(uint32, wl.Fixed, wl.Fixed)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2) + } + return nil + }}, + {Message: wl.Message{Name: "button", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "time", Type: "uint"}, {Name: "button", Type: "uint"}, {Name: "state", Type: "uint"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Uint() + arg2 := d.Uint() + arg3 := d.Uint() + h, _ := o.Handler(3).(func(uint32, uint32, uint32, uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2, arg3) + } + return nil + }}, + {Message: wl.Message{Name: "axis", Args: []wl.Argument{{Name: "time", Type: "uint"}, {Name: "axis", Type: "uint"}, {Name: "value", Type: "fixed"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Uint() + arg2 := d.Fixed() + h, _ := o.Handler(4).(func(uint32, uint32, wl.Fixed)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2) + } + return nil + }}, + {Message: wl.Message{Name: "frame"}, Since: 5, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + h, _ := o.Handler(5).(func()) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h() + } + return nil + }}, + {Message: wl.Message{Name: "axis_source", Args: []wl.Argument{{Name: "axis_source", Type: "uint"}}}, Since: 5, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + h, _ := o.Handler(6).(func(uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0) + } + return nil + }}, + {Message: wl.Message{Name: "axis_stop", Args: []wl.Argument{{Name: "time", Type: "uint"}, {Name: "axis", Type: "uint"}}}, Since: 5, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Uint() + h, _ := o.Handler(7).(func(uint32, uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, + {Message: wl.Message{Name: "axis_discrete", Args: []wl.Argument{{Name: "axis", Type: "uint"}, {Name: "discrete", Type: "int"}}}, Since: 5, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Int() + h, _ := o.Handler(8).(func(uint32, int32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, + {Message: wl.Message{Name: "axis_value120", Args: []wl.Argument{{Name: "axis", Type: "uint"}, {Name: "value120", Type: "int"}}}, Since: 8, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Int() + h, _ := o.Handler(9).(func(uint32, int32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, + {Message: wl.Message{Name: "axis_relative_direction", Args: []wl.Argument{{Name: "axis", Type: "uint"}, {Name: "direction", Type: "uint"}}}, Since: 9, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Uint() + h, _ := o.Handler(10).(func(uint32, uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, + {Message: wl.Message{Name: "warp", Args: []wl.Argument{{Name: "surface_x", Type: "fixed"}, {Name: "surface_y", Type: "fixed"}}}, Since: 11, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Fixed() + arg1 := d.Fixed() + h, _ := o.Handler(11).(func(wl.Fixed, wl.Fixed)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, +}} + +func (p WlPointer) OnEnter(h func(uint32, *wl.Object, wl.Fixed, wl.Fixed)) { p.Object.On(0, h) } +func (p WlPointer) OnLeave(h func(uint32, *wl.Object)) { p.Object.On(1, h) } +func (p WlPointer) OnMotion(h func(uint32, wl.Fixed, wl.Fixed)) { p.Object.On(2, h) } +func (p WlPointer) OnButton(h func(uint32, uint32, uint32, uint32)) { p.Object.On(3, h) } +func (p WlPointer) OnAxis(h func(uint32, uint32, wl.Fixed)) { p.Object.On(4, h) } +func (p WlPointer) OnFrame(h func()) { p.Object.On(5, h) } +func (p WlPointer) OnAxisSource(h func(uint32)) { p.Object.On(6, h) } +func (p WlPointer) OnAxisStop(h func(uint32, uint32)) { p.Object.On(7, h) } +func (p WlPointer) OnAxisDiscrete(h func(uint32, int32)) { p.Object.On(8, h) } +func (p WlPointer) OnAxisValue120(h func(uint32, int32)) { p.Object.On(9, h) } +func (p WlPointer) OnAxisRelativeDirection(h func(uint32, uint32)) { p.Object.On(10, h) } +func (p WlPointer) OnWarp(h func(wl.Fixed, wl.Fixed)) { p.Object.On(11, h) } + +type WlKeyboard struct{ *wl.Object } + +const WlKeyboardKeymapFormatNoKeymap = 0 +const WlKeyboardKeymapFormatXkbV1 = 1 +const WlKeyboardKeyStateReleased = 0 +const WlKeyboardKeyStatePressed = 1 +const WlKeyboardKeyStateRepeated = 2 + +func (p WlKeyboard) Release() error { + _, err := p.Object.Request(0, 3, true, "", 0, nil) + return err +} + +var WlKeyboardInterface = wl.Interface{Name: "wl_keyboard", Version: 11, Requests: []wl.Message{ + {Name: "release"}, +}, Events: []wl.Event{ + {Message: wl.Message{Name: "keymap", Args: []wl.Argument{{Name: "format", Type: "uint"}, {Name: "fd", Type: "fd"}, {Name: "size", Type: "uint"}}}, Since: 1, Destructor: false, FDs: 1, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.FD() + arg2 := d.Uint() + h, _ := o.Handler(0).(func(uint32, int, uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2) + } + return nil + }}, + {Message: wl.Message{Name: "enter", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "surface", Type: "object", Interface: "wl_surface"}, {Name: "keys", Type: "array"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Object("wl_surface", false) + arg2 := d.Array() + h, _ := o.Handler(1).(func(uint32, *wl.Object, []byte)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2) + } + return nil + }}, + {Message: wl.Message{Name: "leave", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "surface", Type: "object", Interface: "wl_surface"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Object("wl_surface", false) + h, _ := o.Handler(2).(func(uint32, *wl.Object)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, + {Message: wl.Message{Name: "key", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "time", Type: "uint"}, {Name: "key", Type: "uint"}, {Name: "state", Type: "uint"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Uint() + arg2 := d.Uint() + arg3 := d.Uint() + h, _ := o.Handler(3).(func(uint32, uint32, uint32, uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2, arg3) + } + return nil + }}, + {Message: wl.Message{Name: "modifiers", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "mods_depressed", Type: "uint"}, {Name: "mods_latched", Type: "uint"}, {Name: "mods_locked", Type: "uint"}, {Name: "group", Type: "uint"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Uint() + arg2 := d.Uint() + arg3 := d.Uint() + arg4 := d.Uint() + h, _ := o.Handler(4).(func(uint32, uint32, uint32, uint32, uint32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2, arg3, arg4) + } + return nil + }}, + {Message: wl.Message{Name: "repeat_info", Args: []wl.Argument{{Name: "rate", Type: "int"}, {Name: "delay", Type: "int"}}}, Since: 4, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Int() + arg1 := d.Int() + h, _ := o.Handler(5).(func(int32, int32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, +}} + +func (p WlKeyboard) OnKeymap(h func(uint32, int, uint32)) { p.Object.On(0, h) } +func (p WlKeyboard) OnEnter(h func(uint32, *wl.Object, []byte)) { p.Object.On(1, h) } +func (p WlKeyboard) OnLeave(h func(uint32, *wl.Object)) { p.Object.On(2, h) } +func (p WlKeyboard) OnKey(h func(uint32, uint32, uint32, uint32)) { p.Object.On(3, h) } +func (p WlKeyboard) OnModifiers(h func(uint32, uint32, uint32, uint32, uint32)) { p.Object.On(4, h) } +func (p WlKeyboard) OnRepeatInfo(h func(int32, int32)) { p.Object.On(5, h) } + +type WlTouch struct{ *wl.Object } + +func (p WlTouch) Release() error { + _, err := p.Object.Request(0, 3, true, "", 0, nil) + return err +} + +var WlTouchInterface = wl.Interface{Name: "wl_touch", Version: 11, Requests: []wl.Message{ + {Name: "release"}, +}, Events: []wl.Event{ + {Message: wl.Message{Name: "down", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "time", Type: "uint"}, {Name: "surface", Type: "object", Interface: "wl_surface"}, {Name: "id", Type: "int"}, {Name: "x", Type: "fixed"}, {Name: "y", Type: "fixed"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Uint() + arg2 := d.Object("wl_surface", false) + arg3 := d.Int() + arg4 := d.Fixed() + arg5 := d.Fixed() + h, _ := o.Handler(0).(func(uint32, uint32, *wl.Object, int32, wl.Fixed, wl.Fixed)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2, arg3, arg4, arg5) + } + return nil + }}, + {Message: wl.Message{Name: "up", Args: []wl.Argument{{Name: "serial", Type: "uint"}, {Name: "time", Type: "uint"}, {Name: "id", Type: "int"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Uint() + arg2 := d.Int() + h, _ := o.Handler(1).(func(uint32, uint32, int32)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2) + } + return nil + }}, + {Message: wl.Message{Name: "motion", Args: []wl.Argument{{Name: "time", Type: "uint"}, {Name: "id", Type: "int"}, {Name: "x", Type: "fixed"}, {Name: "y", Type: "fixed"}}}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Uint() + arg1 := d.Int() + arg2 := d.Fixed() + arg3 := d.Fixed() + h, _ := o.Handler(2).(func(uint32, int32, wl.Fixed, wl.Fixed)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2, arg3) + } + return nil + }}, + {Message: wl.Message{Name: "frame"}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + h, _ := o.Handler(3).(func()) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h() + } + return nil + }}, + {Message: wl.Message{Name: "cancel"}, Since: 1, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + h, _ := o.Handler(4).(func()) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h() + } + return nil + }}, + {Message: wl.Message{Name: "shape", Args: []wl.Argument{{Name: "id", Type: "int"}, {Name: "major", Type: "fixed"}, {Name: "minor", Type: "fixed"}}}, Since: 6, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Int() + arg1 := d.Fixed() + arg2 := d.Fixed() + h, _ := o.Handler(5).(func(int32, wl.Fixed, wl.Fixed)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1, arg2) + } + return nil + }}, + {Message: wl.Message{Name: "orientation", Args: []wl.Argument{{Name: "id", Type: "int"}, {Name: "orientation", Type: "fixed"}}}, Since: 6, Destructor: false, FDs: 0, Decode: func(o *wl.Object, d *wl.Decoder) error { + arg0 := d.Int() + arg1 := d.Fixed() + h, _ := o.Handler(6).(func(int32, wl.Fixed)) + if err := d.Finish(h != nil); err != nil { + return err + } + if h != nil { + h(arg0, arg1) + } + return nil + }}, +}} + +func (p WlTouch) OnDown(h func(uint32, uint32, *wl.Object, int32, wl.Fixed, wl.Fixed)) { + p.Object.On(0, h) +} +func (p WlTouch) OnUp(h func(uint32, uint32, int32)) { p.Object.On(1, h) } +func (p WlTouch) OnMotion(h func(uint32, int32, wl.Fixed, wl.Fixed)) { p.Object.On(2, h) } +func (p WlTouch) OnFrame(h func()) { p.Object.On(3, h) } +func (p WlTouch) OnCancel(h func()) { p.Object.On(4, h) } +func (p WlTouch) OnShape(h func(int32, wl.Fixed, wl.Fixed)) { p.Object.On(5, h) } +func (p WlTouch) OnOrientation(h func(int32, wl.Fixed)) { p.Object.On(6, h) } diff --git a/wayland/debug_linux.go b/wayland/debug_linux.go new file mode 100644 index 00000000..f5ea527f --- /dev/null +++ b/wayland/debug_linux.go @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package wayland + +import ( + "fmt" + "os" + "strconv" + "strings" +) + +// Message holds debug metadata in wire argument order. +type Message struct { + Name string + Args []Argument +} + +// Argument uses the type names from the Wayland XML schema. +type Argument struct { + Name string + Type string + Interface string +} + +func clientDebugEnabled(value string) bool { + for _, token := range strings.Split(value, ",") { + if token == "1" || token == "client" { + return true + } + } + return false +} + +func (o *Object) trace(direction string, msg *Message, data []byte, fds []int, childInterface string) { + if msg.Name == "" { + return + } + var b strings.Builder + fmt.Fprintf(&b, "[wayland] %s %s@%d.%s(", direction, o.spec.Name, o.id, msg.Name) + d := Decoder{data: data} + for i, arg := range msg.Args { + if i != 0 { + b.WriteString(", ") + } + fmt.Fprintf(&b, "%s=", arg.Name) + switch arg.Type { + case "int": + fmt.Fprint(&b, d.Int()) + case "uint": + fmt.Fprint(&b, d.Uint()) + case "fixed": + fmt.Fprint(&b, d.Fixed().Float64()) + case "string": + n := d.Uint() + if n == 0 { + b.WriteString("null") + } else { + b.WriteString(strconv.Quote(d.text(n))) + } + case "array": + n := d.Uint() + d.take(n) + fmt.Fprintf(&b, "array[%d]", n) + case "object", "new_id": + id := d.Uint() + iface := arg.Interface + if arg.Type == "new_id" { + b.WriteString("new ") + if iface == "" { + iface = childInterface + } + } else if found := o.conn.objects[id]; found != nil { + iface = found.spec.Name + } + if id == 0 { + b.WriteString("null") + } else { + fmt.Fprintf(&b, "%s@%d", iface, id) + } + case "fd": + if len(fds) == 0 { + return + } + fmt.Fprintf(&b, "fd %d", fds[0]) + fds = fds[1:] + default: + return + } + } + if d.err == nil && len(d.data) == 0 && len(fds) == 0 { + b.WriteString(")\n") + _, _ = os.Stderr.WriteString(b.String()) + } +} diff --git a/wayland/testdata/interop/client.go b/wayland/testdata/interop/client.go new file mode 100644 index 00000000..ee15134c --- /dev/null +++ b/wayland/testdata/interop/client.go @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "bytes" + "context" + "fmt" + "io" + "log" + "os" + "time" + + wl "github.com/linuxdeepin/dde-api/wayland" + "github.com/linuxdeepin/dde-api/wayland/core" +) + +func check(err error) { + if err != nil { + log.Fatal(err) + } +} + +func expect(ok bool, what string) { + if !ok { + log.Fatalf("unexpected %s", what) + } +} + +func sendFD(send func(int) error) { + r, w, err := os.Pipe() + check(err) + _, err = w.WriteString("from-go") + check(err) + check(w.Close()) + check(send(int(r.Fd()))) + check(r.Close()) +} + +func expectFD(fd int) { + file := os.NewFile(uintptr(fd), "reply") + data, err := io.ReadAll(file) + check(err) + check(file.Close()) + expect(string(data) == "from-c", "descriptor contents") +} + +func main() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + d, err := core.Connect(ctx) + check(err) + defer d.Close() + deadline, _ := ctx.Deadline() + check(d.SetDeadline(deadline)) + Register(d.Conn) + obj, err := d.GetRegistry() + check(err) + registry := core.WlRegistry{Object: obj} + var name, seatName uint32 + registry.OnGlobal(func(n uint32, iface string, version uint32) { + if iface == DdeGoProbeInterface.Name && version == 2 { + name = n + } + if iface == core.WlSeatInterface.Name && version >= 5 { + seatName = n + } + }) + check(d.Roundtrip()) + expect(name != 0, "registry global event") + expect(seatName != 0, "seat global event") + obj, err = registry.Bind(seatName, core.WlSeatInterface.Name, 5) + check(err) + seat := core.WlSeat{Object: obj} + _, err = seat.GetPointer() + check(err) + keyboard, err := seat.GetKeyboard() + check(err) + _, err = seat.GetTouch() + check(err) + var repeat bool + core.WlKeyboard{Object: keyboard}.OnRepeatInfo(func(rate, delay int32) { + repeat = rate == 25 && delay == 300 + }) + check(d.Roundtrip()) + expect(repeat, "keyboard repeat_info event") + + obj, err = registry.Bind(name, DdeGoProbeInterface.Name, 2) + check(err) + probe := DdeGoProbe{Object: obj} + child, err := probe.MakeChild() + check(err) + expect(child.Version() == 1, "typed request new_id version") + empty := "" + flags := uint32(DdeGoProbeFlagsFirst | DdeGoProbeFlagsLast) + pattern := []byte{0, 7, 255} + legacyObj, err := registry.Bind(name, DdeGoProbeInterface.Name, 1) + check(err) + legacy := DdeGoProbe{Object: legacyObj} + sendFD(func(fd int) error { + expect(legacy.SendValues(-123, flags, -320, "布局!", nil, pattern, child, nil, fd) != nil, "v2 request accepted by v1 proxy") + return nil + }) + check(legacy.Destroy()) + var values, serverEvents int + var arrays [][]byte + var serverChild DdeGoProbeChild + probe.OnValues(func(signed int32, mask uint32, fixed wl.Fixed, text string, optional *string, + data []byte, required, maybe *wl.Object, fd int) { + expectFD(fd) + expect(signed == -456 && mask == flags && fixed.Float64() == 1.5 && text == "应答!", "event scalar values") + expect(required == child && bytes.Equal(data, pattern), "event object or array") + if values == 0 { + expect(optional == nil && maybe == nil, "null event parameters") + data[0] = 9 + } else { + expect(optional != nil && *optional == "" && maybe == child, "present but empty string or object") + } + arrays = append(arrays, data) + values++ + }) + probe.OnChildCreated(func(obj *wl.Object) { + expect(obj != nil && obj.Version() == 1, "server-created new_id") + serverChild = DdeGoProbeChild{Object: obj} + serverChild.OnChildFile(func(fd int) { + expectFD(fd) + serverEvents++ + }) + }) + sendFD(func(fd int) error { + return probe.SendValues(-123, flags, -320, "布局!", nil, pattern, child, nil, fd) + }) + sendFD(func(fd int) error { + return probe.SendValues(-123, flags, -320, "布局!", &empty, pattern, child, child, fd) + }) + check(d.Roundtrip()) + expect(values == 2 && serverEvents == 1 && arrays[0][0] == 9, "ordered callbacks or array ownership") + sendFD(serverChild.ExchangeFd) + check(d.Roundtrip()) + expect(serverEvents == 2, "FD-only request or event") + check(serverChild.Destroy()) + check(DdeGoProbeChild{Object: child}.Destroy()) + expect(DdeGoProbeChild{Object: child}.Destroy() != nil, "second destructor accepted") + check(probe.Destroy()) + check(d.Roundtrip()) + fmt.Println("libwayland interop: requests, events, all wire argument types, v1/v2 and destruction passed") +} diff --git a/wayland/testdata/interop/probe.xml b/wayland/testdata/interop/probe.xml new file mode 100644 index 00000000..a017af1e --- /dev/null +++ b/wayland/testdata/interop/probe.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/wayland/testdata/interop/run.sh b/wayland/testdata/interop/run.sh new file mode 100755 index 00000000..971a1cd3 --- /dev/null +++ b/wayland/testdata/interop/run.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: GPL-3.0-or-later +set -eu + +fixtures=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH='' cd -- "$fixtures/../../.." && pwd) +work=$(mktemp -d /tmp/dde-wayland.XXXXXXXX) +server= +cleanup() { + if [ -n "$server" ]; then + kill "$server" 2>/dev/null || true + wait "$server" 2>/dev/null || true + fi + rm -rf -- "$work" +} +trap cleanup EXIT +trap 'exit 1' HUP INT TERM + +mkdir -p "$work/src/github.com/linuxdeepin" "$work/client" "$work/runtime" +chmod 700 "$work/runtime" +ln -s "$root" "$work/src/github.com/linuxdeepin/dde-api" +export GO111MODULE=off GOPATH="$work" CGO_ENABLED=0 + +wayland-scanner server-header "$fixtures/probe.xml" "$work/probe-server.h" +wayland-scanner private-code "$fixtures/probe.xml" "$work/probe.c" +# pkg-config intentionally expands to separate compiler flags. +${CC:-cc} -Wall -Wextra -Werror -I"$work" "$fixtures/server.c" "$work/probe.c" \ + $(pkg-config --cflags --libs wayland-server) -o "$work/server" +go run "$root/cmd/go-wayland-scanner/main.go" -package main \ + -o "$work/client/probe_gen.go" "$fixtures/probe.xml" +cp "$fixtures/client.go" "$work/client/" +(cd "$work/client" && go build -o "$work/probe-client" .) + +export XDG_RUNTIME_DIR="$work/runtime" WAYLAND_DISPLAY=dde-go-test +"$work/server" "$WAYLAND_DISPLAY" & +server=$! +for attempt in $(seq 100); do + [ ! -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ] || break + kill -0 "$server" || exit 1 + sleep 0.02 +done +for mode in '' server client 1; do + if ! WAYLAND_DEBUG="$mode" "$work/probe-client" 2>"$work/trace"; then + cat "$work/trace" >&2 + exit 1 + fi + case "$mode" in + ''|server) test ! -s "$work/trace" ;; + client|1) + grep -E '^\[wayland\] -> wl_registry@[0-9]+\.bind\(name=[0-9]+, interface="dde_go_probe", version=2, id=new dde_go_probe@[0-9]+\)$' "$work/trace" + grep -E '^\[wayland\] -> dde_go_probe@[0-9]+\.send_values\(signed_value=-123, flags=2147483649, fraction=-1\.25, text="布局!", optional=null, data=array\[3\], child=dde_go_probe_child@[0-9]+, maybe_child=null, file=fd [0-9]+\)$' "$work/trace" + grep -E '^\[wayland\] <- dde_go_probe@[0-9]+\.values\(signed_value=-456, flags=2147483649, fraction=1\.5, text="应答!", optional="", data=array\[3\], child=dde_go_probe_child@[0-9]+, maybe_child=dde_go_probe_child@[0-9]+, file=fd [0-9]+\)$' "$work/trace" + grep -E '^\[wayland\] <- dde_go_probe@[0-9]+\.child_created\(id=new dde_go_probe_child@[0-9]+\)$' "$work/trace" + grep -E '^\[wayland\] <- dde_go_probe_child@[0-9]+\.child_file\(file=fd [0-9]+\)$' "$work/trace" + grep -E '^\[wayland\] -> dde_go_probe@[0-9]+\.destroy\(\)$' "$work/trace" + ;; + esac +done diff --git a/wayland/testdata/interop/server.c b/wayland/testdata/interop/server.c new file mode 100644 index 00000000..71d92a35 --- /dev/null +++ b/wayland/testdata/interop/server.c @@ -0,0 +1,146 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later + +#include +#include +#include +#include +#include + +#include "probe-server.h" + +static void destroy(struct wl_client *client, struct wl_resource *resource) +{ + (void)client; + wl_resource_destroy(resource); +} + +static void receive_fd(int fd) +{ + char buf[8]; + assert(read(fd, buf, sizeof(buf)) == 7 && memcmp(buf, "from-go", 7) == 0); + close(fd); +} + +static int reply_fd(void) +{ + int fds[2]; + assert(pipe(fds) == 0); + assert(write(fds[1], "from-c", 6) == 6); + close(fds[1]); + return fds[0]; +} + +static void child_exchange_fd(struct wl_client *client, struct wl_resource *resource, int32_t fd) +{ + (void)client; + receive_fd(fd); + fd = reply_fd(); + dde_go_probe_child_send_child_file(resource, fd); + close(fd); +} + +static const struct dde_go_probe_child_interface child_impl = { + .destroy = destroy, + .exchange_fd = child_exchange_fd, +}; + +static struct wl_resource *make_child(struct wl_client *client, uint32_t id) +{ + struct wl_resource *child = wl_resource_create(client, &dde_go_probe_child_interface, 1, id); + assert(child); + wl_resource_set_implementation(child, &child_impl, NULL, NULL); + return child; +} + +static void create_child(struct wl_client *client, struct wl_resource *resource, uint32_t id) +{ + (void)resource; + make_child(client, id); +} + +static void send_values(struct wl_client *client, struct wl_resource *resource, int32_t signed_value, + uint32_t flags, wl_fixed_t fraction, const char *text, const char *optional, + struct wl_array *data, struct wl_resource *child, + struct wl_resource *maybe_child, int32_t fd) +{ + const char pattern[] = {0, 7, -1}; + assert(signed_value == -123 && flags == 0x80000001 && fraction == -320); + assert(strcmp(text, "布局!") == 0); + assert(data->size == sizeof(pattern) && memcmp(data->data, pattern, data->size) == 0); + assert(child && wl_resource_instance_of(child, &dde_go_probe_child_interface, &child_impl)); + assert(optional ? *optional == '\0' && maybe_child == child : !maybe_child); + receive_fd(fd); + fd = reply_fd(); + dde_go_probe_send_values(resource, -456, flags, 384, "应答!", optional, data, child, maybe_child, fd); + close(fd); + if (!optional) { + struct wl_resource *server_child = make_child(client, 0); + dde_go_probe_send_child_created(resource, server_child); + fd = reply_fd(); + dde_go_probe_child_send_child_file(server_child, fd); + close(fd); + } +} + +static const struct dde_go_probe_interface probe_impl = { + .destroy = destroy, + .make_child = create_child, + .send_values = send_values, +}; + +static void bind_probe(struct wl_client *client, void *data, uint32_t version, uint32_t id) +{ + (void)data; + struct wl_resource *resource = wl_resource_create(client, &dde_go_probe_interface, version, id); + assert(resource); + wl_resource_set_implementation(resource, &probe_impl, NULL, NULL); +} + +static void get_pointer(struct wl_client *client, struct wl_resource *seat, uint32_t id) +{ + assert(wl_resource_create(client, &wl_pointer_interface, wl_resource_get_version(seat), id)); +} + +static void get_keyboard(struct wl_client *client, struct wl_resource *seat, uint32_t id) +{ + struct wl_resource *keyboard = wl_resource_create(client, &wl_keyboard_interface, wl_resource_get_version(seat), id); + assert(keyboard); + wl_keyboard_send_repeat_info(keyboard, 25, 300); +} + +static void get_touch(struct wl_client *client, struct wl_resource *seat, uint32_t id) +{ + assert(wl_resource_create(client, &wl_touch_interface, wl_resource_get_version(seat), id)); +} + +static const struct wl_seat_interface seat_impl = { + .get_pointer = get_pointer, + .get_keyboard = get_keyboard, + .get_touch = get_touch, + .release = destroy, +}; + +static void bind_seat(struct wl_client *client, void *data, uint32_t version, uint32_t id) +{ + (void)data; + struct wl_resource *seat = wl_resource_create(client, &wl_seat_interface, version, id); + assert(seat); + wl_resource_set_implementation(seat, &seat_impl, NULL, NULL); + wl_seat_send_capabilities(seat, WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD | WL_SEAT_CAPABILITY_TOUCH); +} + +int main(int argc, char **argv) +{ + assert(argc == 2); + struct wl_display *display = wl_display_create(); + assert(display); + assert(wl_global_create(display, &dde_go_probe_interface, 2, NULL, bind_probe)); + assert(wl_global_create(display, &wl_seat_interface, 5, NULL, bind_seat)); + assert(wl_display_add_socket(display, argv[1]) == 0); + puts("ready"); + fflush(stdout); + wl_display_run(display); + wl_display_destroy(display); + return 0; +} diff --git a/wayland/wire_linux.go b/wayland/wire_linux.go new file mode 100644 index 00000000..63bee15b --- /dev/null +++ b/wayland/wire_linux.go @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package wayland + +import ( + "fmt" + "strings" + "syscall" + "unicode/utf8" +) + +// Fixed is a signed 24.8 Wayland fixed-point number. +type Fixed int32 + +func (f Fixed) Float64() float64 { return float64(f) / 256 } + +const maxMessage = 4096 + +var padding [3]byte + +type Encoder struct { + conn *Conn + data []byte + fds []int + err error +} + +func (e *Encoder) Uint(v uint32) { + if len(e.data)+4 > maxMessage { + e.err = fmt.Errorf("Wayland message exceeds %d bytes", maxMessage) + return + } + start := len(e.data) + e.data = append(e.data, 0, 0, 0, 0) + order.PutUint32(e.data[start:], v) +} + +func (e *Encoder) Int(v int32) { e.Uint(uint32(v)) } +func (e *Encoder) Fixed(v Fixed) { e.Int(int32(v)) } + +func (e *Encoder) String(v string) { + if len(v) >= maxMessage || !utf8.ValidString(v) || strings.IndexByte(v, 0) >= 0 { + e.err = fmt.Errorf("invalid Wayland string") + return + } + n := len(v) + 1 + padded := (n + 3) &^ 3 + if len(e.data)+4+padded > maxMessage { + e.err = fmt.Errorf("Wayland string exceeds message limit") + return + } + e.Uint(uint32(n)) + e.data = append(e.data, v...) + e.data = append(e.data, 0) + e.data = append(e.data, padding[:padded-n]...) +} + +func (e *Encoder) NullableString(v *string) { + if v == nil { + e.Uint(0) + return + } + e.String(*v) +} + +func (e *Encoder) Array(v []byte) { + if len(v) > maxMessage || len(e.data)+4+((len(v)+3)&^3) > maxMessage { + e.err = fmt.Errorf("Wayland array exceeds message limit") + return + } + e.Uint(uint32(len(v))) + e.data = append(e.data, v...) + e.data = append(e.data, padding[:(-len(v))&3]...) +} + +func (e *Encoder) Object(v *Object, iface string, nullable bool) { + if v != nil && !v.dead && v.conn == e.conn && (iface == "" || v.spec.Name == iface) { + e.Uint(v.id) + } else if v == nil && nullable { + e.Uint(0) + } else { + e.err = fmt.Errorf("invalid Wayland object argument (%s)", iface) + } +} + +func (e *Encoder) FD(fd int) { + if fd < 0 { + e.err = fmt.Errorf("invalid Wayland file descriptor") + return + } + e.fds = append(e.fds, fd) +} + +type Decoder struct { + object *Object + data []byte + fds []int + discard bool + destructor bool + created bool + err error + traceMessage *Message + traceData []byte +} + +func (d *Decoder) take(n uint32) []byte { + if n > uint32(len(d.data)) || (n+3)&^3 > uint32(len(d.data)) { + d.err = fmt.Errorf("truncated Wayland argument") + return nil + } + v := d.data[:n] + d.data = d.data[(n+3)&^3:] + return v +} + +func (d *Decoder) Uint() uint32 { + v := d.take(4) + if v == nil { + return 0 + } + return order.Uint32(v) +} + +func (d *Decoder) Int() int32 { return int32(d.Uint()) } +func (d *Decoder) Fixed() Fixed { return Fixed(d.Int()) } + +func (d *Decoder) text(n uint32) string { + v := d.take(n) + if len(v) == 0 || v[len(v)-1] != 0 || !utf8.Valid(v[:len(v)-1]) { + d.err = fmt.Errorf("invalid Wayland string") + return "" + } + s := string(v[:len(v)-1]) + if strings.IndexByte(s, 0) >= 0 { + d.err = fmt.Errorf("embedded NUL in Wayland string") + } + return s +} + +func (d *Decoder) String() string { return d.text(d.Uint()) } + +func (d *Decoder) NullableString() *string { + n := d.Uint() + if n == 0 { + return nil + } + s := d.text(n) + return &s +} + +func (d *Decoder) Array() []byte { return append([]byte(nil), d.take(d.Uint())...) } + +func (d *Decoder) Object(iface string, nullable bool) *Object { + id := d.Uint() + if id == 0 && nullable { + return nil + } + o := d.object.conn.objects[id] + if o == nil || (iface != "" && o.spec.Name != iface) { + d.err = fmt.Errorf("unknown Wayland object %d (%s)", id, iface) + return nil + } + if o.dead { + return nil + } + return o +} + +func (d *Decoder) NewID(iface string) *Object { + id := d.Uint() + c := d.object.conn + spec := c.interfaces[iface] + if o := c.objects[id]; id < serverID || spec == nil || (o != nil && !o.dead) { + d.err = fmt.Errorf("invalid server-created Wayland object %d (%s)", id, iface) + return nil + } + d.created = true + return c.add(id, spec, childVersion(d.object.version, spec.Version)) +} + +// FD transfers ownership of a received descriptor to the event handler. +func (d *Decoder) FD() int { + c := d.object.conn + if len(c.fds) == 0 { + d.err = fmt.Errorf("missing Wayland file descriptor") + return -1 + } + fd := c.fds[0] + c.fds = c.fds[1:] + d.fds = append(d.fds, fd) + return fd +} + +func (d *Decoder) closeFDs() { + for _, fd := range d.fds { + _ = syscall.Close(fd) + } + d.fds = nil +} + +// Finish validates the message before a listener may consume its arguments. +func (d *Decoder) Finish(hasListener bool) error { + if d.err == nil && len(d.data) != 0 { + d.err = fmt.Errorf("trailing bytes in Wayland event") + } + if d.err == nil && d.created && (!hasListener || d.discard) { + // A server-created object may send more events immediately; dropping its ID is unsafe. + d.err = fmt.Errorf("unhandled Wayland event creating an object") + } + if d.err == nil && d.traceMessage != nil { + d.object.trace("<-", d.traceMessage, d.traceData, d.fds, "") + } + if !hasListener || d.discard || d.err != nil { + d.closeFDs() + } + d.fds = nil + if d.err == nil && d.destructor { + d.object.destroy() + } + return d.err +} From 590681aca56ecaa2e6b5e4f4de711770e0526406 Mon Sep 17 00:00:00 2001 From: zhangkun Date: Wed, 2 Dec 2026 15:31:19 +0800 Subject: [PATCH 2/2] fix(wayland): preserve display bookkeeping MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Keep protocol error reporting and object ID recycling when registering listeners. 2. Test that user listeners still run and bookkeeping is preserved. Log: Preserve internal display event handling when clients register listeners. Influence: Listeners retain error and ID handling. fix(wayland): 保留显示对象的内部事件处理 1. 注册监听器时保留协议错误上报与对象 ID 回收。 2. 验证用户回调和内部处理都能执行。 Log: 注册监听器时保留显示对象的内部事件处理。 PMS: BUG-377251 Influence: 监听器不会覆盖错误上报和 ID 回收。 --- wayland/core/client.go | 24 +++++++- wayland/core/client_test.go | 107 ++++++++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 3 deletions(-) create mode 100644 wayland/core/client_test.go diff --git a/wayland/core/client.go b/wayland/core/client.go index bd0fdff5..8141556e 100644 --- a/wayland/core/client.go +++ b/wayland/core/client.go @@ -24,11 +24,29 @@ func Connect(ctx context.Context) (*Display, error) { } Register(conn) d := &Display{WlDisplay: WlDisplay{root}, Conn: conn} - d.OnError(func(_ *wayland.Object, code uint32, message string) { + d.OnError(nil) + d.OnDeleteId(nil) + return d, nil +} + +// OnError sets the user listener without replacing protocol error reporting. +func (d *Display) OnError(h func(*wayland.Object, uint32, string)) { + d.WlDisplay.OnError(func(obj *wayland.Object, code uint32, message string) { d.protocolError = fmt.Errorf("Wayland protocol error %d: %s", code, message) + if h != nil { + h(obj, code, message) + } + }) +} + +// OnDeleteId sets the user listener without replacing object ID recycling. +func (d *Display) OnDeleteId(h func(uint32)) { + d.WlDisplay.OnDeleteId(func(id uint32) { + d.Conn.DeleteID(id) + if h != nil { + h(id) + } }) - d.OnDeleteId(conn.DeleteID) - return d, nil } func (d *Display) Dispatch() error { diff --git a/wayland/core/client_test.go b/wayland/core/client_test.go new file mode 100644 index 00000000..cd802197 --- /dev/null +++ b/wayland/core/client_test.go @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +package core + +import ( + "context" + "encoding/binary" + "io" + "net" + "path/filepath" + "testing" + "time" + "unsafe" + + "github.com/linuxdeepin/dde-api/wayland" +) + +func TestDisplayListenersPreserveBookkeeping(t *testing.T) { + path := filepath.Join(t.TempDir(), "socket") + listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) + if err != nil { + t.Fatal(err) + } + defer listener.Close() + t.Setenv("WAYLAND_DISPLAY", path) + + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + d, err := Connect(ctx) + if err != nil { + t.Fatal(err) + } + defer d.Close() + deadline, _ := ctx.Deadline() + if err := d.SetDeadline(deadline); err != nil { + t.Fatal(err) + } + if err := listener.SetDeadline(deadline); err != nil { + t.Fatal(err) + } + peer, err := listener.AcceptUnix() + if err != nil { + t.Fatal(err) + } + defer peer.Close() + if err := peer.SetDeadline(deadline); err != nil { + t.Fatal(err) + } + + var order binary.ByteOrder = binary.LittleEndian + one := uint16(1) + if *(*byte)(unsafe.Pointer(&one)) == 0 { + order = binary.BigEndian + } + sendEvent := func(id uint32, opcode uint16, args ...uint32) { + t.Helper() + msg := make([]byte, 8+4*len(args)) + order.PutUint32(msg, id) + order.PutUint32(msg[4:], uint32(len(msg))<<16|uint32(opcode)) + for i, arg := range args { + order.PutUint32(msg[8+4*i:], arg) + } + if _, err := peer.Write(msg); err != nil { + t.Fatal(err) + } + } + syncID := func() uint32 { + t.Helper() + if _, err := d.Sync(); err != nil { + t.Fatal(err) + } + var msg [12]byte + if _, err := io.ReadFull(peer, msg[:]); err != nil { + t.Fatal(err) + } + return order.Uint32(msg[8:]) + } + + var deleted uint32 + d.OnDeleteId(func(id uint32) { deleted = id }) + id := syncID() + sendEvent(id, 0, 0) // wl_callback.done + sendEvent(1, 1, id) // wl_display.delete_id + for i := 0; i < 2; i++ { + if err := d.Dispatch(); err != nil { + t.Fatal(err) + } + } + if deleted != id || syncID() != id { + t.Fatal("delete_id must reach the listener and recycle the ID") + } + + var callbackCode uint32 + var callbackMessage string + d.OnError(func(_ *wayland.Object, code uint32, message string) { + callbackCode, callbackMessage = code, message + }) + sendEvent(1, 0, id, 1, 4, order.Uint32([]byte{'b', 'a', 'd', 0})) // wl_display.error + if err := d.Dispatch(); err == nil || err.Error() != "Wayland protocol error 1: bad" { + t.Fatalf("Dispatch() = %v, want server protocol error", err) + } + if callbackCode != 1 || callbackMessage != "bad" { + t.Fatalf("error listener received %d %q", callbackCode, callbackMessage) + } +}