1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package x11 implements an X11 backend for the exp/gui package.
7 // The X protocol specification is at ftp://ftp.x.org/pub/X11R7.0/doc/PDF/proto.pdf.
8 // A summary of the wire format can be found in XCB's xproto.xml.
25 type resID uint32 // X resource IDs.
27 // TODO(nigeltao): Handle window resizes.
43 gc, window, root, visual resID
46 eventc chan interface{}
47 mouseState gui.MouseEvent
49 buf [256]byte // General purpose scratch buffer.
53 flushBuf1 [4 * 1024]byte
56 // writeSocket runs in its own goroutine, serving both FlushImage calls
57 // directly from the exp/gui client and indirectly from X expose events.
58 // It paints c.img to the X server via PutImage requests.
59 func (c *conn) writeSocket() {
61 for _ = range c.flush {
66 // Each X request has a 16-bit length (in terms of 4-byte units). To avoid going over
67 // this limit, we send PutImage for each row of the image, rather than trying to paint
68 // the entire image in one X request. This approach could easily be optimized (or the
69 // X protocol may have an escape sequence to delimit very large requests).
70 // TODO(nigeltao): See what XCB's xcb_put_image does in this situation.
72 if units > 0xffff || b.Dy() > 0xffff {
73 log.Print("x11: window is too large for PutImage")
77 c.flushBuf0[0] = 0x48 // PutImage opcode.
78 c.flushBuf0[1] = 0x02 // XCB_IMAGE_FORMAT_Z_PIXMAP.
79 c.flushBuf0[2] = uint8(units)
80 c.flushBuf0[3] = uint8(units >> 8)
81 setU32LE(c.flushBuf0[4:8], uint32(c.window))
82 setU32LE(c.flushBuf0[8:12], uint32(c.gc))
83 setU32LE(c.flushBuf0[12:16], 1<<16|uint32(b.Dx()))
84 c.flushBuf0[21] = 0x18 // depth = 24 bits.
86 for y := b.Min.Y; y < b.Max.Y; y++ {
87 setU32LE(c.flushBuf0[16:20], uint32(y<<16))
88 if _, err := c.w.Write(c.flushBuf0[:24]); err != nil {
90 log.Println("x11:", err)
94 p := c.img.Pix[(y-b.Min.Y)*c.img.Stride:]
95 for x, dx := 0, 4*b.Dx(); x < dx; {
97 if nx > len(c.flushBuf1) {
98 nx = len(c.flushBuf1) &^ 3
100 for i := 0; i < nx; i += 4 {
101 // X11's order is BGRX, not RGBA.
102 c.flushBuf1[i+0] = p[x+i+2]
103 c.flushBuf1[i+1] = p[x+i+1]
104 c.flushBuf1[i+2] = p[x+i+0]
107 if _, err := c.w.Write(c.flushBuf1[:nx]); err != nil {
109 log.Println("x11:", err)
115 if err := c.w.Flush(); err != nil {
117 log.Println("x11:", err)
124 func (c *conn) Screen() draw.Image { return c.img }
126 func (c *conn) FlushImage() {
128 case c.flush <- false:
129 // Flush notification sent.
132 // Flush notification must be pending already.
136 func (c *conn) Close() os.Error {
137 // Shut down the writeSocket goroutine. This will close the socket to the
138 // X11 server, which will cause c.eventc to close.
140 for _ = range c.eventc {
141 // Drain the channel to allow the readSocket goroutine to shut down.
146 func (c *conn) EventChan() <-chan interface{} { return c.eventc }
148 // readSocket runs in its own goroutine, reading X events and sending gui
149 // events on c's EventChan.
150 func (c *conn) readSocket() {
153 keysymsPerKeycode int
155 defer close(c.eventc)
157 // X events are always 32 bytes long.
158 if _, err := io.ReadFull(c.r, c.buf[:32]); err != nil {
160 c.eventc <- gui.ErrEvent{err}
165 case 0x01: // Reply from a request (e.g. GetKeyboardMapping).
166 cookie := int(c.buf[3])<<8 | int(c.buf[2])
168 // We issued only one request (GetKeyboardMapping) with a cookie of 1,
169 // so we shouldn't get any other reply from the X server.
170 c.eventc <- gui.ErrEvent{os.NewError("x11: unexpected cookie")}
173 keysymsPerKeycode = int(c.buf[1])
174 b := make([]int, 256*keysymsPerKeycode)
175 for i := range keymap {
176 keymap[i] = b[i*keysymsPerKeycode : (i+1)*keysymsPerKeycode]
178 for i := keymapLo; i <= keymapHi; i++ {
181 u, err := readU32LE(c.r, c.buf[:4])
184 c.eventc <- gui.ErrEvent{err}
191 case 0x02, 0x03: // Key press, key release.
192 // X Keyboard Encoding is documented at http://tronche.com/gui/x/xlib/input/keyboard-encoding.html
193 // TODO(nigeltao): Do we need to implement the "MODE SWITCH / group modifier" feature
194 // or is that some no-longer-used X construct?
195 if keysymsPerKeycode < 2 {
196 // Either we haven't yet received the GetKeyboardMapping reply or
197 // the X server has sent one that's too short.
200 keycode := int(c.buf[1])
201 shift := int(c.buf[28]) & 0x01
202 keysym := keymap[keycode][shift]
204 keysym = keymap[keycode][0]
206 // TODO(nigeltao): Should we send KeyEvents for Shift/Ctrl/Alt? Should Shift-A send
207 // the same int down the channel as the sent on just the A key?
208 // TODO(nigeltao): How should IME events (e.g. key presses that should generate CJK text) work? Or
209 // is that outside the scope of the gui.Window interface?
210 if c.buf[0] == 0x03 {
213 c.eventc <- gui.KeyEvent{keysym}
214 case 0x04, 0x05: // Button press, button release.
215 mask := 1 << (c.buf[1] - 1)
216 if c.buf[0] == 0x04 {
217 c.mouseState.Buttons |= mask
219 c.mouseState.Buttons &^= mask
221 c.mouseState.Nsec = time.Nanoseconds()
222 c.eventc <- c.mouseState
223 case 0x06: // Motion notify.
224 c.mouseState.Loc.X = int(int16(c.buf[25])<<8 | int16(c.buf[24]))
225 c.mouseState.Loc.Y = int(int16(c.buf[27])<<8 | int16(c.buf[26]))
226 c.mouseState.Nsec = time.Nanoseconds()
227 c.eventc <- c.mouseState
228 case 0x0c: // Expose.
229 // A single user action could trigger multiple expose events (e.g. if moving another
230 // window with XShape'd rounded corners over our window). In that case, the X server will
231 // send a uint16 count (in bytes 16-17) of the number of additional expose events coming.
232 // We could parse each event for the (x, y, width, height) and maintain a minimal dirty
233 // rectangle, but for now, the simplest approach is to paint the entire window, when
234 // receiving the final event in the series.
235 if c.buf[17] == 0 && c.buf[16] == 0 {
236 // TODO(nigeltao): Should we ignore the very first expose event? A freshly mapped window
237 // will trigger expose, but until the first c.FlushImage call, there's probably nothing to
238 // paint but black. For an 800x600 window, at 4 bytes per pixel, each repaint writes about
239 // 2MB over the socket.
242 // TODO(nigeltao): Should we listen to DestroyNotify (0x11) and ResizeRequest (0x19) events?
243 // What about EnterNotify (0x07) and LeaveNotify (0x08)?
248 // connect connects to the X server given by the full X11 display name (e.g.
249 // ":12.0") and returns the connection as well as the portion of the full name
250 // that is the display number (e.g. "12").
252 // connect(":1") // calls net.Dial("unix", "", "/tmp/.X11-unix/X1"), displayStr="1"
253 // connect("/tmp/launch-123/:0") // calls net.Dial("unix", "", "/tmp/launch-123/:0"), displayStr="0"
254 // connect("hostname:2.1") // calls net.Dial("tcp", "", "hostname:6002"), displayStr="2"
255 // connect("tcp/hostname:1.0") // calls net.Dial("tcp", "", "hostname:6001"), displayStr="1"
256 func connect(display string) (conn net.Conn, displayStr string, err os.Error) {
257 colonIdx := strings.LastIndex(display, ":")
259 return nil, "", os.NewError("bad display: " + display)
261 // Parse the section before the colon.
262 var protocol, host, socket string
263 if display[0] == '/' {
264 socket = display[:colonIdx]
266 if i := strings.LastIndex(display, "/"); i < 0 {
267 // The default protocol is TCP.
269 host = display[:colonIdx]
271 protocol = display[:i]
272 host = display[i+1 : colonIdx]
275 // Parse the section after the colon.
276 after := display[colonIdx+1:]
278 return nil, "", os.NewError("bad display: " + display)
280 if i := strings.LastIndex(after, "."); i < 0 {
283 displayStr = after[:i]
285 displayInt, err := strconv.Atoi(displayStr)
286 if err != nil || displayInt < 0 {
287 return nil, "", os.NewError("bad display: " + display)
289 // Make the connection.
291 conn, err = net.Dial("unix", socket+":"+displayStr)
292 } else if host != "" {
293 conn, err = net.Dial(protocol, host+":"+strconv.Itoa(6000+displayInt))
295 conn, err = net.Dial("unix", "/tmp/.X11-unix/X"+displayStr)
298 return nil, "", os.NewError("cannot connect to " + display + ": " + err.String())
303 // authenticate authenticates ourselves with the X server.
304 // displayStr is the "12" out of ":12.0".
305 func authenticate(w *bufio.Writer, displayStr string) os.Error {
306 key, value, err := readAuth(displayStr)
310 // Assume that the authentication protocol is "MIT-MAGIC-COOKIE-1".
311 if len(key) != 18 || len(value) != 16 {
312 return os.NewError("unsupported Xauth")
314 // 0x006c means little-endian. 0x000b, 0x0000 means X major version 11, minor version 0.
315 // 0x0012 and 0x0010 means the auth key and value have lengths 18 and 16.
316 // The final 0x0000 is padding, so that the string length is a multiple of 4.
317 _, err = io.WriteString(w, "\x6c\x00\x0b\x00\x00\x00\x12\x00\x10\x00\x00\x00")
321 _, err = io.WriteString(w, key)
325 // Again, the 0x0000 is padding.
326 _, err = io.WriteString(w, "\x00\x00")
330 _, err = io.WriteString(w, value)
341 // readU8 reads a uint8 from r, using b as a scratch buffer.
342 func readU8(r io.Reader, b []byte) (uint8, os.Error) {
343 _, err := io.ReadFull(r, b[:1])
347 return uint8(b[0]), nil
350 // readU16LE reads a little-endian uint16 from r, using b as a scratch buffer.
351 func readU16LE(r io.Reader, b []byte) (uint16, os.Error) {
352 _, err := io.ReadFull(r, b[:2])
356 return uint16(b[0]) | uint16(b[1])<<8, nil
359 // readU32LE reads a little-endian uint32 from r, using b as a scratch buffer.
360 func readU32LE(r io.Reader, b []byte) (uint32, os.Error) {
361 _, err := io.ReadFull(r, b[:4])
365 return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24, nil
368 // setU32LE sets b[:4] to be the little-endian representation of u.
369 func setU32LE(b []byte, u uint32) {
370 b[0] = byte((u >> 0) & 0xff)
371 b[1] = byte((u >> 8) & 0xff)
372 b[2] = byte((u >> 16) & 0xff)
373 b[3] = byte((u >> 24) & 0xff)
376 // checkPixmapFormats checks that we have an agreeable X pixmap Format.
377 func checkPixmapFormats(r io.Reader, b []byte, n int) (agree bool, err os.Error) {
378 for i := 0; i < n; i++ {
379 _, err = io.ReadFull(r, b[:8])
383 // Byte 0 is depth, byte 1 is bits-per-pixel, byte 2 is scanline-pad, the rest (5) is padding.
384 if b[0] == 24 && b[1] == 32 {
391 // checkDepths checks that we have an agreeable X Depth (i.e. one that has an agreeable X VisualType).
392 func checkDepths(r io.Reader, b []byte, n int, visual uint32) (agree bool, err os.Error) {
393 for i := 0; i < n; i++ {
394 var depth, visualsLen uint16
395 depth, err = readU16LE(r, b)
400 visualsLen, err = readU16LE(r, b)
404 // Ignore 4 bytes of padding.
405 _, err = io.ReadFull(r, b[:4])
409 for j := 0; j < int(visualsLen); j++ {
410 // Read 24 bytes: visual(4), class(1), bits per rgb value(1), colormap entries(2),
411 // red mask(4), green mask(4), blue mask(4), padding(4).
412 v, _ := readU32LE(r, b)
413 _, _ = readU32LE(r, b)
414 rm, _ := readU32LE(r, b)
415 gm, _ := readU32LE(r, b)
416 bm, _ := readU32LE(r, b)
417 _, err = readU32LE(r, b)
421 if v == visual && rm == 0xff0000 && gm == 0xff00 && bm == 0xff && depth == 24 {
429 // checkScreens checks that we have an agreeable X Screen.
430 func checkScreens(r io.Reader, b []byte, n int) (root, visual uint32, err os.Error) {
431 for i := 0; i < n; i++ {
432 var root0, visual0, x uint32
433 root0, err = readU32LE(r, b)
437 // Ignore the next 7x4 bytes, which is: colormap, whitepixel, blackpixel, current input masks,
438 // width and height (pixels), width and height (mm), min and max installed maps.
439 _, err = io.ReadFull(r, b[:28])
443 visual0, err = readU32LE(r, b)
447 // Next 4 bytes: backing stores, save unders, root depth, allowed depths length.
448 x, err = readU32LE(r, b)
452 nDepths := int(x >> 24)
454 agree, err = checkDepths(r, b, nDepths, visual0)
458 if agree && root == 0 {
466 // handshake performs the protocol handshake with the X server, and ensures
467 // that the server provides a compatible Screen, Depth, etc.
468 func (c *conn) handshake() os.Error {
469 _, err := io.ReadFull(c.r, c.buf[:8])
473 // Byte 0 should be 1 (success), bytes 2:6 should be 0xb0000000 (major/minor version 11.0).
474 if c.buf[0] != 1 || c.buf[2] != 11 || c.buf[3] != 0 || c.buf[4] != 0 || c.buf[5] != 0 {
475 return os.NewError("unsupported X version")
477 // Ignore the release number.
478 _, err = io.ReadFull(c.r, c.buf[:4])
482 // Read the resource ID base.
483 resourceIdBase, err := readU32LE(c.r, c.buf[:4])
487 // Read the resource ID mask.
488 resourceIdMask, err := readU32LE(c.r, c.buf[:4])
492 if resourceIdMask < 256 {
493 return os.NewError("X resource ID mask is too small")
495 // Ignore the motion buffer size.
496 _, err = io.ReadFull(c.r, c.buf[:4])
500 // Read the vendor length and round it up to a multiple of 4,
501 // for X11 protocol alignment reasons.
502 vendorLen, err := readU16LE(c.r, c.buf[:2])
506 vendorLen = (vendorLen + 3) &^ 3
507 // Read the maximum request length.
508 maxReqLen, err := readU16LE(c.r, c.buf[:2])
512 if maxReqLen != 0xffff {
513 return os.NewError("unsupported X maximum request length")
515 // Read the roots length.
516 rootsLen, err := readU8(c.r, c.buf[:1])
520 // Read the pixmap formats length.
521 pixmapFormatsLen, err := readU8(c.r, c.buf[:1])
525 // Ignore some things that we don't care about (totaling 10 + vendorLen bytes):
526 // imageByteOrder(1), bitmapFormatBitOrder(1), bitmapFormatScanlineUnit(1) bitmapFormatScanlinePad(1),
527 // minKeycode(1), maxKeycode(1), padding(4), vendor (vendorLen).
528 if 10+int(vendorLen) > cap(c.buf) {
529 return os.NewError("unsupported X vendor")
531 _, err = io.ReadFull(c.r, c.buf[:10+int(vendorLen)])
535 // Check that we have an agreeable pixmap format.
536 agree, err := checkPixmapFormats(c.r, c.buf[:8], int(pixmapFormatsLen))
541 return os.NewError("unsupported X pixmap formats")
543 // Check that we have an agreeable screen.
544 root, visual, err := checkScreens(c.r, c.buf[:24], int(rootsLen))
548 if root == 0 || visual == 0 {
549 return os.NewError("unsupported X screen")
551 c.gc = resID(resourceIdBase)
552 c.window = resID(resourceIdBase + 1)
554 c.visual = resID(visual)
558 // NewWindow calls NewWindowDisplay with $DISPLAY.
559 func NewWindow() (gui.Window, os.Error) {
560 display := os.Getenv("DISPLAY")
561 if len(display) == 0 {
562 return nil, os.NewError("$DISPLAY not set")
564 return NewWindowDisplay(display)
567 // NewWindowDisplay returns a new gui.Window, backed by a newly created and
568 // mapped X11 window. The X server to connect to is specified by the display
569 // string, such as ":1".
570 func NewWindowDisplay(display string) (gui.Window, os.Error) {
571 socket, displayStr, err := connect(display)
577 c.r = bufio.NewReader(socket)
578 c.w = bufio.NewWriter(socket)
579 err = authenticate(c.w, displayStr)
588 // Now that we're connected, show a window, via three X protocol messages.
589 // First, issue a GetKeyboardMapping request. This is the first request, and
590 // will be associated with a cookie of 1.
591 setU32LE(c.buf[0:4], 0x00020065) // 0x65 is the GetKeyboardMapping opcode, and the message is 2 x 4 bytes long.
592 setU32LE(c.buf[4:8], uint32((keymapHi-keymapLo+1)<<8|keymapLo))
593 // Second, create a graphics context (GC).
594 setU32LE(c.buf[8:12], 0x00060037) // 0x37 is the CreateGC opcode, and the message is 6 x 4 bytes long.
595 setU32LE(c.buf[12:16], uint32(c.gc))
596 setU32LE(c.buf[16:20], uint32(c.root))
597 setU32LE(c.buf[20:24], 0x00010004) // Bit 2 is XCB_GC_FOREGROUND, bit 16 is XCB_GC_GRAPHICS_EXPOSURES.
598 setU32LE(c.buf[24:28], 0x00000000) // The Foreground is black.
599 setU32LE(c.buf[28:32], 0x00000000) // GraphicsExposures' value is unused.
600 // Third, create the window.
601 setU32LE(c.buf[32:36], 0x000a0001) // 0x01 is the CreateWindow opcode, and the message is 10 x 4 bytes long.
602 setU32LE(c.buf[36:40], uint32(c.window))
603 setU32LE(c.buf[40:44], uint32(c.root))
604 setU32LE(c.buf[44:48], 0x00000000) // Initial (x, y) is (0, 0).
605 setU32LE(c.buf[48:52], windowHeight<<16|windowWidth)
606 setU32LE(c.buf[52:56], 0x00010000) // Border width is 0, XCB_WINDOW_CLASS_INPUT_OUTPUT is 1.
607 setU32LE(c.buf[56:60], uint32(c.visual))
608 setU32LE(c.buf[60:64], 0x00000802) // Bit 1 is XCB_CW_BACK_PIXEL, bit 11 is XCB_CW_EVENT_MASK.
609 setU32LE(c.buf[64:68], 0x00000000) // The Back-Pixel is black.
610 setU32LE(c.buf[68:72], 0x0000804f) // Key/button press and release, pointer motion, and expose event masks.
611 // Fourth, map the window.
612 setU32LE(c.buf[72:76], 0x00020008) // 0x08 is the MapWindow opcode, and the message is 2 x 4 bytes long.
613 setU32LE(c.buf[76:80], uint32(c.window))
615 _, err = c.w.Write(c.buf[:80])
624 c.img = image.NewRGBA(image.Rect(0, 0, windowWidth, windowHeight))
625 c.eventc = make(chan interface{}, 16)
626 c.flush = make(chan bool, 1)