Documentation
¶
Overview ¶
Code generated by xtgen; DO NOT EDIT.
Example ¶
package main
import (
"errors"
"log"
"golang.org/x/sys/unix"
"bnema.dev/xturbo"
"bnema.dev/xturbo/xproto"
)
// Replies registered with Expect carry this kind (16 and above are free).
const kindGeometry uint16 = 16
func main() {
c, err := xturbo.Dial("") // "" means $DISPLAY
if err != nil {
log.Fatal(err)
}
defer c.Close()
// Startup: blocking calls, bounded by a 5 s deadline.
var atoms [1]uint32
if err := c.InternAtoms([]string{"WM_DELETE_WINDOW"}, false, atoms[:]); err != nil {
log.Fatal(err)
}
// Queue requests; they return a Seq (0 on failure, see c.Buf().Err()).
b := c.Buf()
win, err := c.NewXID()
if err != nil {
log.Fatal(err)
}
var v xproto.CreateWindowValues
v.SetEventMask(xproto.EventMaskExposure | xproto.EventMaskStructureNotify)
xproto.CreateWindow(b, 0, xproto.Window(win), xproto.Window(c.Root()),
0, 0, 640, 480, 0, xproto.WindowClassInputOutput, 0, &v)
xproto.MapWindow(b, xproto.Window(win))
if seq := xproto.GetGeometry(b, xproto.Drawable(win)); seq != 0 {
if err := c.Expect(seq, kindGeometry, win, 0, 0, 0); err != nil {
log.Fatal(err)
}
}
// Callbacks run inside Dispatch. Events, replies and errors are borrowed:
// copy what you keep.
h := &xturbo.Handler{
OnEvent: func(ev *xturbo.Event) {
switch ev.Kind {
case xproto.KindExpose:
e := xproto.ExposeOf(ev)
log.Printf("expose %dx%d", e.Width(), e.Height())
}
},
OnReply: func(r *xturbo.Reply) {
if r.Kind == kindGeometry {
if g, ok := xproto.ParseGetGeometryReply(r.Raw); ok {
log.Printf("window %#x is %dx%d", r.Args[0], g.Width(), g.Height())
}
}
},
OnError: func(e *xturbo.XError) { log.Print(e) },
}
for {
// Flush never blocks. On ErrWouldBlock, also wait for POLLOUT.
events := int16(unix.POLLIN)
if err := c.Flush(); errors.Is(err, xturbo.ErrWouldBlock) {
events |= unix.POLLOUT
} else if err != nil {
log.Fatal(err)
}
fds := []unix.PollFd{{Fd: int32(c.Fd()), Events: events}}
if _, err := unix.Poll(fds, -1); err != nil && err != unix.EINTR {
log.Fatal(err)
}
if err := c.Dispatch(h); err != nil { // io.EOF: server closed
log.Fatal(err)
}
// Keep the XID pool topped up without blocking later.
if c.XIDsLow() {
_ = c.PrefetchXIDs()
}
}
}
Output:
Index ¶
- Constants
- Variables
- type Buf
- type Conn
- func (c *Conn) Buf() *Buf
- func (c *Conn) Close() error
- func (c *Conn) Dispatch(h *Handler) error
- func (c *Conn) Expect(seq Seq, kind uint16, a0, a1, a2, a3 uint32) error
- func (c *Conn) Ext() *ExtTable
- func (c *Conn) Fd() int
- func (c *Conn) Flush() error
- func (c *Conn) FreeXID(id uint32)
- func (c *Conn) InternAtoms(names []string, onlyIfExists bool, dst []uint32) error
- func (c *Conn) NewXID() (uint32, error)
- func (c *Conn) PrefetchXIDs() error
- func (c *Conn) Root() uint32
- func (c *Conn) SetupBytes() []byte
- func (c *Conn) Stats() Stats
- func (c *Conn) Sync(h *Handler) error
- func (c *Conn) XIDsLow() bool
- type Event
- type EventKind
- type ExtID
- type ExtInfo
- type ExtTable
- func (t *ExtTable) ByError(code uint8) (id ExtID, rel uint8, ok bool)
- func (t *ExtTable) ByEvent(code uint8) (id ExtID, rel uint8, ok bool)
- func (t *ExtTable) ByMajor(major uint8) (id ExtID, ok bool)
- func (t *ExtTable) Info(id ExtID) ExtInfo
- func (t *ExtTable) Major(id ExtID) uint8
- func (t *ExtTable) Set(id ExtID, major, firstEvent, firstError uint8)
- type Handler
- type Reply
- type Seq
- type SetupError
- type Stats
- type XError
Examples ¶
Constants ¶
const MaxPacket = 16 << 20
MaxPacket bounds one server packet (a reply or an XGE event) in bytes. The read ring grows up to this size; a larger packet fails Dispatch with ErrPacketTooLarge and the connection is dead.
Variables ¶
var ( ErrWouldBlock = errors.New("xturbo: write would block") ErrClosed = errors.New("xturbo: connection closed") ErrRequestTooLarge = errors.New("xturbo: request too large") ErrExtMissing = errors.New("xturbo: extension missing") ErrBadLength = errors.New("xturbo: bad length") ErrSeqOverflow = errors.New("xturbo: sequence overflow") )
var ( // ErrMalformed reports bytes from the server or a local file that do not // follow the wire format (truncated, impossible lengths). ErrMalformed = errors.New("xturbo: malformed data") // ErrSetupFailed is wrapped by SetupError when the server refuses the // connection. ErrSetupFailed = errors.New("xturbo: connection setup failed") )
ErrPacketTooLarge reports a server packet longer than MaxPacket.
ErrRingFull reports more than ringSize registered requests outstanding: the Expect slot of seq still belongs to an earlier request that has not completed. Treat it as a bug: Sync, then retry.
var ExtXName = [extCount]string{"", "BIG-REQUESTS", "Generic Event Extension", "XC-MISC", "Composite", "XFIXES", "X-Resource", "RENDER", "SHAPE"}
Functions ¶
This section is empty.
Types ¶
type Buf ¶
type Buf struct {
Ext *ExtTable
// contains filtered or unexported fields
}
Buf is the caller-owned request encoder. Conn owns flushing and acknowledgment. It is not safe for concurrent use.
func NewBuf ¶
NewBuf returns an encoder with size bytes preallocated; size <= 0 means 64 KiB.
func (*Buf) Fail ¶
Fail records err as the sticky error; the first error wins.
func (*Buf) Next ¶
Next returns the sequence number the next Request will get.
func (*Buf) Request ¶
Request reserves a zeroed body of body bytes after the wire header and returns it with the request's sequence number. body must be a multiple of 4. Requests longer than 0xFFFF units get the BIG-REQUESTS 8-byte header. On failure it records a sticky error and returns (nil, 0). The body is valid only until the next Request, flush or Reset on b.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a client connection to an X server over a stream socket. It is not safe for concurrent use: one goroutine owns it.
func Dial ¶
Dial connects to a local X server named by a DISPLAY string (":N", ":N.S", "unix:N"; empty means $DISPLAY). It tries the abstract socket "@/tmp/.X11-unix/XN" first, then the filesystem socket, and authenticates with MIT-MAGIC-COOKIE-1 from $XAUTHORITY or ~/.Xauthority when a matching entry exists. Meant for tests and tools; the XWM uses NewConn.
func NewConn ¶
NewConn takes ownership of fd, a connected stream socket to an X server, and runs the connection setup without authorization (e.g. the -wm fd of an XWayland the caller spawned). It blocks for the handshake, then one round trip negotiates every known extension (QueryExtension each, BIG-REQUESTS Enable when present) into Ext() and the Buf request limit. fd is left O_NONBLOCK. The whole call gives up after 10 s with an error wrapping os.ErrDeadlineExceeded (an alive but silent server). On failure fd is closed.
func (*Conn) Buf ¶
Buf returns the request encoder bound to this connection.
func (*Conn) Close ¶
Close closes the socket. Later calls, and Flush after Close, return ErrClosed.
func (*Conn) Dispatch ¶
Dispatch reads what the server has sent without blocking and calls h for every complete packet, in wire order. It returns nil once the socket would block or after a bounded amount of input (about one read ring, so a flooding server cannot starve the caller's event loop): call it again while the fd is still readable, and Flush requests queued by callbacks in between. It returns io.EOF when the server closed the connection and ErrPacketTooLarge on a packet beyond MaxPacket. Read errors are sticky and also fail the Buf. Dispatch never flushes. A nil h drops every packet; a non-nil h is remembered for the packets Sync(nil), InternAtoms and NewXID read while they block. Errors on the requests root issues itself (reserved kinds) are handled internally and never reach OnError.
func (*Conn) Expect ¶
Expect registers the request seq so its reply, or its error, is delivered with kind and args a0..a3 (Reply.Kind/Args, XError.Kind/Args). Call it before the next Dispatch. kind must be 16 or more; lower kinds are reserved. A reply without a registration is dropped (Stats.DroppedReplies); a registered request that completes without reply or error frees its slot silently once a later sequence number arrives. seq 0 (a failed request) and requests already completed are ignored. A seq that was never sent (at or beyond Buf.Next) is a caller bug and fails. ErrRingFull: more than 1024 registered requests outstanding.
func (*Conn) Fd ¶
Fd returns the socket, for the caller's poll loop; -1 after Close.
func (*Conn) Flush ¶
Flush writes queued requests without blocking. It returns ErrWouldBlock when the socket is full (arm writable interest and call again) and the sticky Buf error once the connection is unusable. With resyncAt or more requests unacknowledged it first appends a GetInputFocus whose reply is discarded (Stats.Resyncs), at most one in flight.
func (*Conn) FreeXID ¶
FreeXID gives back id for reuse by a later NewXID. id must come from NewXID on this Conn and be freed once, after the caller destroyed its resource (the destroy request may still be queued, it precedes any reuse on the wire). IDs outside this client's range, 0, and IDs beyond the free list capacity are ignored; freeing an ID twice hands it out twice.
func (*Conn) InternAtoms ¶
InternAtoms interns every name in one pipelined batch and blocks for one round trip (Sync), writing the atom of names[i] into dst[i] (0 for a name that does not exist when onlyIfExists is set). len(dst) must equal len(names) and every name be at most 65535 bytes (ErrBadLength, nothing sent, the connection unaffected). The first X error on one of these requests is returned as *XError, its Args[0] the index of the name; the other atoms are still filled. Packets read meanwhile go to the last Handler given to Dispatch. Like Sync it gives up after 5 s (os.ErrDeadlineExceeded). Meant for startup; it must not be called from a Handler callback.
func (*Conn) NewXID ¶
NewXID returns a fresh resource ID for this client. IDs released with FreeXID are reused first, then the current range, then a range fetched ahead by PrefetchXIDs. When all are empty, outside a Handler callback, one blocking XC-MISC GetXIDRange round trip (bounded like Sync) refills it; packets read meanwhile go to the last Handler given to Dispatch. Inside a callback that refill is impossible and NewXID fails instead, so an event loop allocating from callbacks calls PrefetchXIDs whenever XIDsLow reports true (the XWM does it once per loop iteration). It also fails when XC-MISC is absent or the server has no IDs left.
func (*Conn) PrefetchXIDs ¶
PrefetchXIDs queues an XC-MISC GetXIDRange without waiting; its reply, read by a later Dispatch, becomes the range NewXID switches to when the current one runs out. Callers flush as usual. It does nothing while a prefetched range is unused or a prefetch is in flight, and may be called from a Handler callback. It fails with ErrExtMissing without XC-MISC, ErrRingFull when the next request's Expect slot is taken, and with the Buf's sticky error.
func (*Conn) SetupBytes ¶
SetupBytes returns the full setup reply. It is retained for the life of the Conn; parse it with the xproto Setup view. Do not modify it.
func (*Conn) Sync ¶
Sync flushes every queued request and blocks until the server has processed them and every request registered with Expect has completed. It appends a GetInputFocus as a fence, so even with nothing registered it is a full round trip: errors of earlier requests have been delivered when it returns. Packets read meanwhile go to h as with Dispatch (nil h: the last Handler given to Dispatch, or none). An error on a request root issued itself is returned as *XError. Sync gives up after 5 s with an error wrapping os.ErrDeadlineExceeded (a hung server); the connection is then still usable but its state unknown, treat it as dead. Meant for startup; called from a Handler callback it returns an error at once.
func (*Conn) XIDsLow ¶
XIDsLow reports that fewer than 4096 IDs remain in the current range with an empty free list, and that PrefetchXIDs would help: XC-MISC is present, no prefetched range is waiting, no prefetch is in flight and the last one did not report the server out of IDs (after that only NewXID's blocking refill retries).
type Event ¶
type Event struct {
Kind EventKind
SendEvent bool
Ext ExtID
Seq Seq // wire sequence; Conn widens it. 0 for KeymapNotify.
Raw [32]byte
Tail []byte
}
Event is a decoded event value. Raw is a copy and survives Dispatch; Tail borrows the read buffer (XGE bytes beyond 32) and is valid only until the Handler callback returns. Copy what you keep.
func DecodeEvent ¶
DecodeEvent decodes one event packet at the start of raw. n is the number of bytes consumed (32, or 32+4*length for XGE). ok is false for error and reply packets and for short input. Unknown codes decode with Kind == KindUnknown and ok == true. A nil ext decodes core events only. The returned Seq is the 16-bit wire value; Conn widens it.
type EventKind ¶
type EventKind uint16
EventKind identifies a decoded event: uint16(ExtID)<<8 | code. Core events use the wire code (2..34); extension events the code relative to the extension's first event; XGE events 0x80|evtype.
const KindUnknown EventKind = 0xFFFF
KindUnknown marks an event whose code or XGE extension is not known.
type ExtInfo ¶
ExtInfo is a negotiated extension's wire opcode and event/error bases.
type ExtTable ¶
type ExtTable struct {
// contains filtered or unexported fields
}
ExtTable is populated during setup. Fixed arrays avoid lookup allocations. Reverse maps store ExtID+1 so the zero value means "none".
func (*ExtTable) ByError ¶
ByError maps a wire error code to its extension and relative error code.
func (*ExtTable) ByEvent ¶
ByEvent maps an event code (raw[0]&0x7f) to its extension and the code relative to the extension's first event.
func (*ExtTable) ByMajor ¶
ByMajor maps a major opcode to its extension.
type Handler ¶
Handler receives decoded packets from Dispatch, in wire order, on the goroutine calling Dispatch. OnReply sees only replies registered with Expect; OnError sees every error (Kind 0 when unregistered). A nil field drops that packet class (nil OnError counts Stats.UnhandledErrors). Fill it once at init; the pointers passed to callbacks are owned by the Conn and are reused for the next packet, so callbacks must not retain them, nor the views they hold (Reply.Raw, Event.Tail). Callbacks may queue requests and call Expect but must not call Dispatch, Sync, InternAtoms, nor NewXID when it needs a refill: those return an error there and change nothing.
type Reply ¶
Reply is one reply packet to a request registered with Expect. Seq is widened; Kind and Args are the registration's. Raw is the whole reply, 32+4*length bytes, valid only until the callback returns.
type SetupError ¶
SetupError is the server's refusal of the connection setup: Status 0 (Failed) or 2 (Authenticate), with the server's reason. It wraps ErrSetupFailed.
func (*SetupError) Error ¶
func (e *SetupError) Error() string
func (*SetupError) Unwrap ¶
func (e *SetupError) Unwrap() error
type Stats ¶
type Stats struct {
DroppedReplies uint64 // replies with no Expect slot
UnhandledErrors uint64 // errors dispatched with a nil Handler.OnError
UnknownEvents uint64 // events decoded as KindUnknown
Resyncs uint64 // GetInputFocus appended by Flush to re-sync sequences
MaxRingUse int // most Expect slots outstanding at once
}
Stats are connection counters, for diagnostics.
type XError ¶
type XError struct {
Seq Seq
Code uint8 // wire error code
Ext ExtID // ExtCore for codes < 128 or unknown
Rel uint8 // Code - FirstError of Ext
Bad uint32 // bad resource/value
Minor uint16
Major uint8
Kind uint16 // ring slot kind, 0 when the request was not registered
Args [4]uint32
Raw [32]byte
}
XError is an X protocol error, passed by value (no interface on the hot path).
Source Files
¶
- atoms.go
- buf.go
- conn.go
- dial.go
- dispatch.go
- errors.go
- event.go
- ext.go
- ext_generated.go
- generate.go
- poison_off.go
- ring.go
- setup.go
- sync.go
- xerror.go
- xid.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |
|
cmd
|
|
|
xtgen
command
Command xtgen generates bindings from the pinned xcb-proto XML.
|
Command xtgen generates bindings from the pinned xcb-proto XML. |
|
xtsync
command
Command xtsync vendors the pinned xcb-proto sources.
|
Command xtsync vendors the pinned xcb-proto sources. |
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |
|
internal
|
|
|
xtest
Package xtest provides wire fixtures shared by binding tests.
|
Package xtest provides wire fixtures shared by binding tests. |
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |
|
Code generated by xtgen; DO NOT EDIT.
|
Code generated by xtgen; DO NOT EDIT. |