github.com/as/shiny@v0.8.2/driver/x11driver/x11driver.go (about)

     1  // Copyright 2015 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.
     4  
     5  // Package x11driver provides the X11 driver for accessing a screen.
     6  package x11driver // import "github.com/as/shiny/driver/x11driver"
     7  
     8  // TODO: figure out what to say about the responsibility for users of this
     9  // package to check any implicit dependencies' LICENSEs. For example, the
    10  // driver might use third party software outside of golang.org/x, like an X11
    11  // or OpenGL library.
    12  
    13  import (
    14  	"fmt"
    15  
    16  	"github.com/BurntSushi/xgb"
    17  	"github.com/BurntSushi/xgb/render"
    18  	"github.com/BurntSushi/xgb/shm"
    19  
    20  	"github.com/as/shiny/driver/internal/errscreen"
    21  	"github.com/as/shiny/screen"
    22  )
    23  
    24  // Main is called by the program's main function to run the graphical
    25  // application.
    26  //
    27  // It calls f on the Screen, possibly in a separate goroutine, as some OS-
    28  // specific libraries require being on 'the main thread'. It returns when f
    29  // returns.
    30  func Main(f func(screen.Screen)) {
    31  	if err := main(f); err != nil {
    32  		f(errscreen.Stub(err))
    33  	}
    34  }
    35  
    36  func main(f func(screen.Screen)) (retErr error) {
    37  	xc, err := xgb.NewConn()
    38  	if err != nil {
    39  		return fmt.Errorf("x11driver: xgb.NewConn failed: %v", err)
    40  	}
    41  	defer func() {
    42  		if retErr != nil {
    43  			xc.Close()
    44  		}
    45  	}()
    46  
    47  	if err := render.Init(xc); err != nil {
    48  		return fmt.Errorf("x11driver: render.Init failed: %v", err)
    49  	}
    50  	if err := shm.Init(xc); err != nil {
    51  		return fmt.Errorf("x11driver: shm.Init failed: %v", err)
    52  	}
    53  
    54  	s, err := newScreenImpl(xc)
    55  	if err != nil {
    56  		return err
    57  	}
    58  	f(s)
    59  	// TODO: tear down the s.run goroutine? It's probably not worth the
    60  	// complexity of doing it cleanly, if the app is about to exit anyway.
    61  	return nil
    62  }