diff options
Diffstat (limited to 'gui')
| -rw-r--r-- | gui/LICENSE | 21 | ||||
| -rw-r--r-- | gui/README.md | 342 | ||||
| -rw-r--r-- | gui/env.go | 33 | ||||
| -rw-r--r-- | gui/event.go | 70 | ||||
| -rw-r--r-- | gui/mux.go | 134 | ||||
| -rw-r--r-- | gui/win/events.go | 93 | ||||
| -rw-r--r-- | gui/win/win.go | 362 |
7 files changed, 1055 insertions, 0 deletions
diff --git a/gui/LICENSE b/gui/LICENSE new file mode 100644 index 0000000..b497e83 --- /dev/null +++ b/gui/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Michal Štrba + +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/gui/README.md b/gui/README.md new file mode 100644 index 0000000..7e83229 --- /dev/null +++ b/gui/README.md @@ -0,0 +1,342 @@ +# faiface/gui [](https://godoc.org/github.com/faiface/gui) [](https://discord.gg/T5YAAT2) + +Super minimal, rock-solid foundation for concurrent GUI in Go. + +## Installation + +``` +go get -u github.com/faiface/gui +``` + +Currently uses [GLFW](https://www.glfw.org/) under the hood, so have [these dependencies](https://github.com/go-gl/glfw#installation). + +## Why concurrent GUI? + +GUI is concurrent by nature. Elements like buttons, text fields, or canvases are conceptually independent. Conventional GUI frameworks solve this by implementing huge architectures: the event +loop, call-backs, tickers, you name it. + +In a concurrent GUI, the story is different. Each element is actually handled by its own goroutine, +or event multiple ones. Elements communicate with each other via channels. + +This has several advantages: + +- Make a new element at any time just by spawning a goroutine. +- Implement animations using simple for-loops. +- An intenstive computation in one element won't block the whole app. +- Enables decentralized design - since elements communicate via channels, multiple communications + may be going on at once, without any central entity. + +## Examples + +| [Image Viewer](examples/imageviewer) | [Paint](examples/paint) | [Pexeso](examples/pexeso) | +| --- | --- | --- | +|  |  |  | + +## What needs getting done? + +This package is solid, but not complete. Here are some of the things that I'd love to get done with your help: + +- Get rid of the C dependencies. +- Support multiple windows. +- Mobile support. +- A widgets/layout package. + +Contributions are highly welcome! + +## Overview + +The idea of concurrent GUI pre-dates Go and is found in another language by Rob Pike called Newsqueak. He explains it quite nicely in [this talk](https://www.youtube.com/watch?v=hB05UFqOtFA&t=2408s). Newsqueak was similar to Go, mostly in that it had channels. + +Why the hell has no one made a concurrent GUI in Go yet? I have no idea. Go is a perfect language for such a thing. Let's change that! + +**This package is a minimal foundation for a concurrent GUI in Go.** It doesn't include widgets, layout systems, or anything like that. The main reason is that I am not yet sure how to do them most correctly. So, instead of providing a half-assed, "fully-featured" library, I decided to make a small, rock-solid package, where everything is right. + +**So, how does this work?** + +The main idea is that different components of the GUI (buttons, text fields, ...) run concurrently and communicate using channels. Furthermore, they receive events from an object called _environment_ and can draw by sending draw commands to it. + +Here's [`Env`](https://godoc.org/github.com/faiface/gui#Env0), short for environment: + +```go +type Env interface { + Events() <-chan Event + Draw() chan<- func(draw.Image) image.Rectangle +} +``` + +It's something that produces events (such as mouse clicks and key presses) and accepts draw commands. + +Closing the `Draw()` channel destroys the environment. When destroyed (either by closing the `Draw()` channel or by any other reason), the environment will always close the `Events()` channel. + +As you can see, a draw command is a function that draws something onto a [`draw.Image`](https://golang.org/pkg/image/draw/#Image) and returns a rectangle telling which part got changed. + +If you're not familiar with the `"image"` and the `"image/draw"` packages, go read [this short entry in the Go blog](https://blog.golang.org/go-imagedraw-package). + + + +Yes, `faiface/gui` uses CPU for drawing. You won't make AAA games with it, but the performance is enough for most GUI apps. The benefits are outstanding, though: + +1. Drawing is as simple as changing pixels. +2. No FPS (frames per second), results are immediately on the screen. +3. No need to organize the API around a GPU library, like OpenGL. +4. Use all the good packages, like [`"image"`](https://golang.org/pkg/image/), [`"image/draw"`](https://golang.org/pkg/image/draw/), [`"golang.org/x/image/font"`](https://godoc.org/golang.org/x/image/font) for fonts, or [`"github.com/fogleman/gg"`](https://godoc.org/github.com/fogleman/gg) for shapes. + +What is an [`Event`](https://godoc.org/github.com/faiface/gui#Event)? It's an interface: + +```go +type Event interface { + String() string +} +``` + +This purpose of this interface is to hold different kinds of events and be able to discriminate among them using a type switch. + +Examples of concrete `Event` types are: [`gui.Resize`](https://godoc.org/github.com/faiface/gui#Resize), [`win.WiClose`](https://godoc.org/github.com/faiface/gui/win#WiClose), [`win.MoDown`](https://godoc.org/github.com/faiface/gui/win#MoDown), [`win.KbType`](https://godoc.org/github.com/faiface/gui/win#KbType) (where `Wi`, `Mo`, and `Kb` stand for _window_, _mouse_, and _keyboard_, respectively). When we have an `Event`, we can type switch on it like this: + +```go +switch event := event.(type) { +case gui.Resize: + // environment resized to event.Rectangle +case win.WiClose: + // window closed +case win.MoMove: + // mouse moved to event.Point +case win.MoDown: + // mouse button event.Button pressed on event.Point +case win.MoUp: + // mouse button event.Button released on event.Point +case win.MoScroll: + // mouse scrolled by event.Point +case win.KbType: + // rune event.Rune typed on the keyboard +case win.KbDown: + // keyboard key event.Key pressed on the keyboard +case win.KbUp: + // keyboard key event.Key released on the keyboard +case win.KbRepeat: + // keyboard key event.Key repeated on the keyboard (happens when held) +} +``` + +This shows all the possible events that a window can produce. + +The [`gui.Resize`](https://godoc.org/github.com/faiface/gui#Resize) event is not from the package [`win`](https://godoc.org/github.com/faiface/gui/win) because it's not window specific. In fact, every `Env` guarantees to produce `gui.Resize` as its first event. + +How do we create a window? With the [`"github.com/faiface/gui/win"`](https://godoc.org/github.com/faiface/gui/win) package: + +```go +// import "github.com/faiface/gui/win" +w, err := win.New(win.Title("faiface/win"), win.Size(800, 600), win.Resizable()) +``` + +The [`win.New`](https://godoc.org/github.com/faiface/gui/win#New) constructor uses the [functional options pattern](https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis) by Dave Cheney. Unsurprisingly, the returned [`*win.Win`](https://godoc.org/github.com/faiface/gui/win#Win) is an `Env`. + +Due to stupid limitations imposed by operating systems, the internal code that fetches events from the OS must run on the main thread of the program. To ensure this, we need to call [`mainthread.Run`](https://godoc.org/github.com/faiface/mainthread#Run) in the `main` function: + +```go +import "github.com/faiface/mainthread" + +func run() { + // do everything here, this becomes the new main function +} + +func main() { + mainthread.Run(run) +} +``` + +How does it all look together? Here's a simple program that displays a nice, big rectangle in the middle of the window: + +```go +package main + +import ( + "image" + "image/draw" + + "github.com/faiface/gui/win" + "github.com/faiface/mainthread" +) + +func run() { + w, err := win.New(win.Title("faiface/gui"), win.Size(800, 600)) + if err != nil { + panic(err) + } + + w.Draw() <- func(drw draw.Image) image.Rectangle { + r := image.Rect(200, 200, 600, 400) + draw.Draw(drw, r, image.White, image.ZP, draw.Src) + return r + } + + for event := range w.Events() { + switch event.(type) { + case win.WiClose: + close(w.Draw()) + } + } +} + +func main() { + mainthread.Run(run) +} +``` + +### Muxing + +When you receive an event from the `Events()` channel, it gets removed from the channel and no one else can receive it. But what if you have a button, a text field, four switches, and a bunch of other things that all want to receive the same events? + +That's where multiplexing, or muxing comes in. + + + +A [`Mux`](https://godoc.org/github.com/faiface/gui#Mux) basically lets you split a single `Env` into multiple ones. + +When the original `Env` produces an event, `Mux` sends it to each one of the multiple `Env`s. + +When any one of the multiple `Env`s receives a draw function, `Mux` sends it to the original `Env`. + +To mux an `Env`, use [`gui.NewMux`](https://godoc.org/github.com/faiface/gui#NewMux): + +```go +mux, env := gui.NewMux(w) +``` + +Here we muxed the window `Env` stored in the `w` variable. + +What's that second return value? That's the _master `Env`_. It's the first environment that the mux creates for us. It has a special role: if you close its `Draw()` channel, you close the `Mux`, all other `Env`s created by the `Mux`, and the original `Env`. But other than that, it's just like any other `Env` created by the `Mux`. + +Don't use the original `Env` after muxing it. The `Mux` is using it and you'll steal its events at best. + +To create more `Env`s, we can use [`mux.MakeEnv()`](https://godoc.org/github.com/faiface/gui#Mux.MakeEnv): + +For example, here's a simple program that shows four white rectangles on the screen. Whenever the user clicks on any of them, the rectangle blinks (switches between white and black) 3 times. We use `Mux` to send events to all of the rectangles independently: + +```go +package main + +import ( + "image" + "image/draw" + "time" + + "github.com/faiface/gui" + "github.com/faiface/gui/win" + "github.com/faiface/mainthread" +) + +func Blinker(env gui.Env, r image.Rectangle) { + // redraw takes a bool and produces a draw command + redraw := func(visible bool) func(draw.Image) image.Rectangle { + return func(drw draw.Image) image.Rectangle { + if visible { + draw.Draw(drw, r, image.White, image.ZP, draw.Src) + } else { + draw.Draw(drw, r, image.Black, image.ZP, draw.Src) + } + return r + } + } + + // first we draw a white rectangle + env.Draw() <- redraw(true) + + for event := range env.Events() { + switch event := event.(type) { + case win.MoDown: + if event.Point.In(r) { + // user clicked on the rectangle + // we blink 3 times + for i := 0; i < 3; i++ { + env.Draw() <- redraw(false) + time.Sleep(time.Second / 3) + env.Draw() <- redraw(true) + time.Sleep(time.Second / 3) + } + } + } + } + + close(env.Draw()) +} + +func run() { + w, err := win.New(win.Title("faiface/gui"), win.Size(800, 600)) + if err != nil { + panic(err) + } + + mux, env := gui.NewMux(w) + + // we create four blinkers, each with its own Env from the mux + go Blinker(mux.MakeEnv(), image.Rect(100, 100, 350, 250)) + go Blinker(mux.MakeEnv(), image.Rect(450, 100, 700, 250)) + go Blinker(mux.MakeEnv(), image.Rect(100, 350, 350, 500)) + go Blinker(mux.MakeEnv(), image.Rect(450, 350, 700, 500)) + + // we use the master env now, w is used by the mux + for event := range env.Events() { + switch event.(type) { + case win.WiClose: + close(env.Draw()) + } + } +} + +func main() { + mainthread.Run(run) +} +``` + +Just for the info, closing the `Draw()` channel on an `Env` created by `mux.MakeEnv()` removes the `Env` from the `Mux`. + +What if one of the `Env`s hangs and stops consuming events, or if it simply takes longer to consume them? Will all the other `Env`s hang as well? + +They won't, because the channels of events have unlimited capacity and never block. This is implemented using an intermediate goroutine that handles the queueing. + + + +And that's basically all you need to know about `faiface/gui`! Happy hacking! + +## A note on race conditions + +There is no guarantee when a function sent to the `Draw()` channel will be executed, or if at all. Look at this code: + +```go +pressed := false + +env.Draw() <- func(drw draw.Image) image.Rectangle { + // use pressed somehow +} + +// change pressed somewhere here +``` + +The code above has a danger of a race condition. The code that changes the `pressed` variable and the code that uses it may run concurrently. + +**My advice is to never enclose a shared variable in a drawing function.** + +Instead, you can do this: + +```go +redraw := func(pressed bool) func(draw.Image) image.Rectangle { + return func(drw draw.Image) image.Rectangle { + // use the pressed argument + } +} + +pressed := false + +env.Draw() <- redraw(pressed) + +// changing pressed here doesn't cause race conditions +``` + +## Credit + +The cutest ever pictures are all drawn by Tori Bane! You can see more of her drawings and follow her on [Instagram here](https://www.instagram.com/teplomilka/). + +## Licence + +[MIT](LICENCE) diff --git a/gui/env.go b/gui/env.go new file mode 100644 index 0000000..2515417 --- /dev/null +++ b/gui/env.go @@ -0,0 +1,33 @@ +package gui + +import ( + "image" + "image/draw" +) + +// Env is the most important thing in this package. It is an interactive graphical +// environment, such as a window. +// +// It has two channels: Events() and Draw(). +// +// The Events() channel produces events, like mouse and keyboard presses, while the +// Draw() channel receives drawing functions. A drawing function draws onto the +// supplied draw.Image, which is the drawing area of the Env and returns a rectangle +// covering the whole part of the image that got changed. +// +// An Env guarantees to produce a "resize/<x0>/<y0>/<x1>/<y1>" event as its first event. +// +// The Events() channel must be unlimited in capacity. Use MakeEventsChan() to create +// a channel of events with an unlimited capacity. +// +// The Draw() channel may be synchronous. +// +// Drawing functions sent to the Draw() channel are not guaranteed to be executed. +// +// Closing the Draw() channel results in closing the Env. The Env will subsequently +// close the Events() channel. On the other hand, when the Events() channel gets closed +// the user of the Env should subsequently close the Draw() channel. +type Env interface { + Events() <-chan Event + Draw() chan<- func(draw.Image) image.Rectangle +} diff --git a/gui/event.go b/gui/event.go new file mode 100644 index 0000000..533317e --- /dev/null +++ b/gui/event.go @@ -0,0 +1,70 @@ +package gui + +import ( + "fmt" + "image" +) + +// Event is something that can happen in an environment. +// +// This package defines only one kind of event: Resize. Other packages implementing environments +// may implement more kinds of events. For example, the win package implements all kinds of +// events for mouse and keyboard. +type Event interface { + String() string +} + +// Resize is an event that happens when the environment changes the size of its drawing area. +type Resize struct { + image.Rectangle +} + +func (r Resize) String() string { + return fmt.Sprintf("resize/%d/%d/%d/%d", r.Min.X, r.Min.Y, r.Max.X, r.Max.Y) +} + +// MakeEventsChan implements a channel of events with an unlimited capacity. It does so +// by creating a goroutine that queues incoming events. Sending to this channel never blocks +// and no events get lost. +// +// The unlimited capacity channel is very suitable for delivering events because the consumer +// may be unavailable for some time (doing a heavy computation), but will get to the events +// later. +// +// An unlimited capacity channel has its dangers in general, but is completely fine for +// the purpose of delivering events. This is because the production of events is fairly +// infrequent and should never out-run their consumption in the long term. +func MakeEventsChan() (<-chan Event, chan<- Event) { + out, in := make(chan Event), make(chan Event) + + go func() { + var queue []Event + + for { + x, ok := <-in + if !ok { + close(out) + return + } + queue = append(queue, x) + + for len(queue) > 0 { + select { + case out <- queue[0]: + queue = queue[1:] + case x, ok := <-in: + if !ok { + for _, x := range queue { + out <- x + } + close(out) + return + } + queue = append(queue, x) + } + } + } + }() + + return out, in +} diff --git a/gui/mux.go b/gui/mux.go new file mode 100644 index 0000000..4198d61 --- /dev/null +++ b/gui/mux.go @@ -0,0 +1,134 @@ +package gui + +import ( + "image" + "image/draw" + "sync" +) + +// Mux can be used to multiplex an Env, let's call it a root Env. Mux implements a way to +// create multiple virtual Envs that all interact with the root Env. They receive the same +// events and their draw functions get redirected to the root Env. +type Mux struct { + mu sync.Mutex + lastResize Event + eventsIns []chan<- Event + draw chan<- func(draw.Image) image.Rectangle +} + +// NewMux creates a new Mux that multiplexes the given Env. It returns the Mux along with +// a master Env. The master Env is just like any other Env created by the Mux, except that +// closing the Draw() channel on the master Env closes the whole Mux and all other Envs +// created by the Mux. +func NewMux(env Env) (mux *Mux, master Env) { + drawChan := make(chan func(draw.Image) image.Rectangle) + mux = &Mux{draw: drawChan} + master = mux.makeEnv(true) + + go func() { + for d := range drawChan { + env.Draw() <- d + } + close(env.Draw()) + }() + + go func() { + for e := range env.Events() { + mux.mu.Lock() + if resize, ok := e.(Resize); ok { + mux.lastResize = resize + } + for _, eventsIn := range mux.eventsIns { + eventsIn <- e + } + mux.mu.Unlock() + } + mux.mu.Lock() + for _, eventsIn := range mux.eventsIns { + close(eventsIn) + } + mux.mu.Unlock() + }() + + return mux, master +} + +// MakeEnv creates a new virtual Env that interacts with the root Env of the Mux. Closing +// the Draw() channel of the Env will not close the Mux, or any other Env created by the Mux +// but will delete the Env from the Mux. +func (mux *Mux) MakeEnv() Env { + return mux.makeEnv(false) +} + +type muxEnv struct { + events <-chan Event + draw chan<- func(draw.Image) image.Rectangle +} + +func (m *muxEnv) Events() <-chan Event { return m.events } +func (m *muxEnv) Draw() chan<- func(draw.Image) image.Rectangle { return m.draw } + +func (mux *Mux) makeEnv(master bool) Env { + eventsOut, eventsIn := MakeEventsChan() + drawChan := make(chan func(draw.Image) image.Rectangle) + env := &muxEnv{eventsOut, drawChan} + + mux.mu.Lock() + mux.eventsIns = append(mux.eventsIns, eventsIn) + // make sure to always send a resize event to a new Env if we got the size already + // that means it missed the resize event by the root Env + if mux.lastResize != nil { + eventsIn <- mux.lastResize + } + mux.mu.Unlock() + + go func() { + func() { + // When the master Env gets its Draw() channel closed, it closes all the Events() + // channels of all the children Envs, and it also closes the internal draw channel + // of the Mux. Otherwise, closing the Draw() channel of the master Env wouldn't + // close the Env the Mux is muxing. However, some child Envs of the Mux may still + // send some drawing commmands before they realize that their Events() channel got + // closed. + // + // That is perfectly fine if their drawing commands simply get ignored. This down here + // is a little hacky, but (I hope) perfectly fine solution to the problem. + // + // When the internal draw channel of the Mux gets closed, the line marked with ! will + // cause panic. We recover this panic, then we receive, but ignore all furhter draw + // commands, correctly draining the Env until it closes itself. + defer func() { + if recover() != nil { + for range drawChan { + } + } + }() + for d := range drawChan { + mux.draw <- d // ! + } + }() + if master { + mux.mu.Lock() + for _, eventsIn := range mux.eventsIns { + close(eventsIn) + } + mux.eventsIns = nil + close(mux.draw) + mux.mu.Unlock() + } else { + mux.mu.Lock() + i := -1 + for i = range mux.eventsIns { + if mux.eventsIns[i] == eventsIn { + break + } + } + if i != -1 { + mux.eventsIns = append(mux.eventsIns[:i], mux.eventsIns[i+1:]...) + } + mux.mu.Unlock() + } + }() + + return env +} diff --git a/gui/win/events.go b/gui/win/events.go new file mode 100644 index 0000000..bae8017 --- /dev/null +++ b/gui/win/events.go @@ -0,0 +1,93 @@ +package win + +import ( + "fmt" + "image" +) + +// Button indicates a mouse button in an event. +type Button string + +// List of all mouse buttons. +const ( + ButtonLeft Button = "left" + ButtonRight Button = "right" + ButtonMiddle Button = "middle" +) + +// Key indicates a keyboard key in an event. +type Key string + +// List of all keyboard keys. +const ( + KeyLeft Key = "left" + KeyRight Key = "right" + KeyUp Key = "up" + KeyDown Key = "down" + KeyEscape Key = "escape" + KeySpace Key = "space" + KeyBackspace Key = "backspace" + KeyDelete Key = "delete" + KeyEnter Key = "enter" + KeyTab Key = "tab" + KeyHome Key = "home" + KeyEnd Key = "end" + KeyPageUp Key = "pageup" + KeyPageDown Key = "pagedown" + KeyShift Key = "shift" + KeyCtrl Key = "ctrl" + KeyAlt Key = "alt" +) + +type ( + // WiClose is an event that happens when the user presses the close button on the window. + WiClose struct{} + + // WiFocus is an event that happens when the window gains or loses focus. + WiFocus struct{ Focused bool } + + // MoMove is an event that happens when the mouse gets moved across the window. + MoMove struct{ image.Point } + + // MoDown is an event that happens when a mouse button gets pressed. + MoDown struct { + image.Point + Button Button + } + + // MoUp is an event that happens when a mouse button gets released. + MoUp struct { + image.Point + Button Button + } + + // MoScroll is an event that happens on scrolling the mouse. + // + // The Point field tells the amount scrolled in each direction. + MoScroll struct{ image.Point } + + // KbType is an event that happens when a Unicode character gets typed on the keyboard. + KbType struct{ Rune rune } + + // KbDown is an event that happens when a key on the keyboard gets pressed. + KbDown struct{ Key Key } + + // KbUp is an event that happens when a key on the keyboard gets released. + KbUp struct{ Key Key } + + // KbRepeat is an event that happens when a key on the keyboard gets repeated. + // + // This happens when its held down for some time. + KbRepeat struct{ Key Key } +) + +func (wc WiClose) String() string { return "wi/close" } +func (wf WiFocus) String() string { return "wi/focus" } +func (mm MoMove) String() string { return fmt.Sprintf("mo/move/%d/%d", mm.X, mm.Y) } +func (md MoDown) String() string { return fmt.Sprintf("mo/down/%d/%d/%s", md.X, md.Y, md.Button) } +func (mu MoUp) String() string { return fmt.Sprintf("mo/up/%d/%d/%s", mu.X, mu.Y, mu.Button) } +func (ms MoScroll) String() string { return fmt.Sprintf("mo/scroll/%d/%d", ms.X, ms.Y) } +func (kt KbType) String() string { return fmt.Sprintf("kb/type/%d", kt.Rune) } +func (kd KbDown) String() string { return fmt.Sprintf("kb/down/%s", kd.Key) } +func (ku KbUp) String() string { return fmt.Sprintf("kb/up/%s", ku.Key) } +func (kr KbRepeat) String() string { return fmt.Sprintf("kb/repeat/%s", kr.Key) } diff --git a/gui/win/win.go b/gui/win/win.go new file mode 100644 index 0000000..2b45868 --- /dev/null +++ b/gui/win/win.go @@ -0,0 +1,362 @@ +package win + +import ( + "image" + "image/draw" + "runtime" + "time" + "unsafe" + + "github.com/faiface/mainthread" + "github.com/go-gl/gl/v2.1/gl" + "github.com/go-gl/glfw/v3.2/glfw" + "volute/gui" +) + +// Option is a functional option to the window constructor New. +type Option func(*options) + +type options struct { + title string + width, height int + resizable bool + borderless bool + maximized bool +} + +// Title option sets the title (caption) of the window. +func Title(title string) Option { + return func(o *options) { + o.title = title + } +} + +// Size option sets the width and height of the window. +func Size(width, height int) Option { + return func(o *options) { + o.width = width + o.height = height + } +} + +// Resizable option makes the window resizable by the user. +func Resizable() Option { + return func(o *options) { + o.resizable = true + } +} + +// Borderless option makes the window borderless. +func Borderless() Option { + return func(o *options) { + o.borderless = true + } +} + +// Maximized option makes the window start maximized. +func Maximized() Option { + return func(o *options) { + o.maximized = true + } +} + +// New creates a new window with all the supplied options. +// +// The default title is empty and the default size is 640x480. +func New(opts ...Option) (*Win, error) { + o := options{ + title: "", + width: 640, + height: 480, + resizable: false, + borderless: false, + maximized: false, + } + for _, opt := range opts { + opt(&o) + } + + eventsOut, eventsIn := gui.MakeEventsChan() + + w := &Win{ + eventsOut: eventsOut, + eventsIn: eventsIn, + draw: make(chan func(draw.Image) image.Rectangle), + newSize: make(chan image.Rectangle), + finish: make(chan struct{}), + } + + var err error + mainthread.Call(func() { + w.w, err = makeGLFWWin(&o) + }) + if err != nil { + return nil, err + } + + mainthread.Call(func() { + // hiDPI hack + width, _ := w.w.GetFramebufferSize() + w.ratio = width / o.width + if w.ratio < 1 { + w.ratio = 1 + } + if w.ratio != 1 { + o.width /= w.ratio + o.height /= w.ratio + } + w.w.Destroy() + w.w, err = makeGLFWWin(&o) + }) + if err != nil { + return nil, err + } + + bounds := image.Rect(0, 0, o.width*w.ratio, o.height*w.ratio) + w.img = image.NewRGBA(bounds) + + go func() { + runtime.LockOSThread() + w.openGLThread() + }() + + mainthread.CallNonBlock(w.eventThread) + + return w, nil +} + +func makeGLFWWin(o *options) (*glfw.Window, error) { + err := glfw.Init() + if err != nil { + return nil, err + } + glfw.WindowHint(glfw.DoubleBuffer, glfw.False) + if o.resizable { + glfw.WindowHint(glfw.Resizable, glfw.True) + } else { + glfw.WindowHint(glfw.Resizable, glfw.False) + } + if o.borderless { + glfw.WindowHint(glfw.Decorated, glfw.False) + } + if o.maximized { + glfw.WindowHint(glfw.Maximized, glfw.True) + } + w, err := glfw.CreateWindow(o.width, o.height, o.title, nil, nil) + if err != nil { + return nil, err + } + if o.maximized { + o.width, o.height = w.GetFramebufferSize() // set o.width and o.height to the window size due to the window being maximized + } + return w, nil +} + +// Win is an Env that handles an actual graphical window. +// +// It receives its events from the OS and it draws to the surface of the window. +// +// Warning: only one window can be open at a time. This will be fixed. +type Win struct { + eventsOut <-chan gui.Event + eventsIn chan<- gui.Event + draw chan func(draw.Image) image.Rectangle + + newSize chan image.Rectangle + finish chan struct{} + + w *glfw.Window + img *image.RGBA + ratio int +} + +// Events returns the events channel of the window. +func (w *Win) Events() <-chan gui.Event { return w.eventsOut } + +// Draw returns the draw channel of the window. +func (w *Win) Draw() chan<- func(draw.Image) image.Rectangle { return w.draw } + +var buttons = map[glfw.MouseButton]Button{ + glfw.MouseButtonLeft: ButtonLeft, + glfw.MouseButtonRight: ButtonRight, + glfw.MouseButtonMiddle: ButtonMiddle, +} + +var keys = map[glfw.Key]Key{ + glfw.KeyLeft: KeyLeft, + glfw.KeyRight: KeyRight, + glfw.KeyUp: KeyUp, + glfw.KeyDown: KeyDown, + glfw.KeyEscape: KeyEscape, + glfw.KeySpace: KeySpace, + glfw.KeyBackspace: KeyBackspace, + glfw.KeyDelete: KeyDelete, + glfw.KeyEnter: KeyEnter, + glfw.KeyTab: KeyTab, + glfw.KeyHome: KeyHome, + glfw.KeyEnd: KeyEnd, + glfw.KeyPageUp: KeyPageUp, + glfw.KeyPageDown: KeyPageDown, + glfw.KeyLeftShift: KeyShift, + glfw.KeyRightShift: KeyShift, + glfw.KeyLeftControl: KeyCtrl, + glfw.KeyRightControl: KeyCtrl, + glfw.KeyLeftAlt: KeyAlt, + glfw.KeyRightAlt: KeyAlt, +} + +func (w *Win) eventThread() { + var moX, moY int + + w.w.SetCursorPosCallback(func(_ *glfw.Window, x, y float64) { + moX, moY = int(x), int(y) + w.eventsIn <- MoMove{image.Pt(moX*w.ratio, moY*w.ratio)} + }) + + w.w.SetMouseButtonCallback(func(_ *glfw.Window, button glfw.MouseButton, action glfw.Action, mod glfw.ModifierKey) { + b, ok := buttons[button] + if !ok { + return + } + switch action { + case glfw.Press: + w.eventsIn <- MoDown{image.Pt(moX*w.ratio, moY*w.ratio), b} + case glfw.Release: + w.eventsIn <- MoUp{image.Pt(moX*w.ratio, moY*w.ratio), b} + } + }) + + w.w.SetScrollCallback(func(_ *glfw.Window, xoff, yoff float64) { + w.eventsIn <- MoScroll{image.Pt(int(xoff), int(yoff))} + }) + + w.w.SetCharCallback(func(_ *glfw.Window, r rune) { + w.eventsIn <- KbType{r} + }) + + w.w.SetKeyCallback(func(_ *glfw.Window, key glfw.Key, _ int, action glfw.Action, _ glfw.ModifierKey) { + k, ok := keys[key] + if !ok { + return + } + switch action { + case glfw.Press: + w.eventsIn <- KbDown{k} + case glfw.Release: + w.eventsIn <- KbUp{k} + case glfw.Repeat: + w.eventsIn <- KbRepeat{k} + } + }) + + w.w.SetFramebufferSizeCallback(func(_ *glfw.Window, width, height int) { + r := image.Rect(0, 0, width, height) + w.newSize <- r + w.eventsIn <- gui.Resize{Rectangle: r} + }) + + w.w.SetCloseCallback(func(_ *glfw.Window) { + w.eventsIn <- WiClose{} + }) + + w.w.SetFocusCallback(func(_ *glfw.Window, focused bool) { + w.eventsIn <- WiFocus{focused} + }) + + r := w.img.Bounds() + w.eventsIn <- gui.Resize{Rectangle: r} + + for { + select { + case <-w.finish: + close(w.eventsIn) + w.w.Destroy() + return + default: + glfw.WaitEventsTimeout(1.0 / 30) + } + } +} + +func (w *Win) openGLThread() { + w.w.MakeContextCurrent() + gl.Init() + + w.openGLFlush(w.img.Bounds()) + +loop: + for { + var totalR image.Rectangle + + select { + case r := <-w.newSize: + img := image.NewRGBA(r) + draw.Draw(img, w.img.Bounds(), w.img, w.img.Bounds().Min, draw.Src) + w.img = img + totalR = totalR.Union(r) + + case d, ok := <-w.draw: + if !ok { + close(w.finish) + return + } + r := d(w.img) + totalR = totalR.Union(r) + } + + for { + select { + case <-time.After(time.Second / 960): + w.openGLFlush(totalR) + totalR = image.ZR + continue loop + + case r := <-w.newSize: + img := image.NewRGBA(r) + draw.Draw(img, w.img.Bounds(), w.img, w.img.Bounds().Min, draw.Src) + w.img = img + totalR = totalR.Union(r) + + case d, ok := <-w.draw: + if !ok { + close(w.finish) + return + } + r := d(w.img) + totalR = totalR.Union(r) + } + } + } +} + +func (w *Win) openGLFlush(r image.Rectangle) { + bounds := w.img.Bounds() + r = r.Intersect(bounds) + if r.Empty() { + return + } + + tmp := image.NewRGBA(r) + draw.Draw(tmp, r, w.img, r.Min, draw.Src) + + gl.DrawBuffer(gl.FRONT) + gl.Viewport( + int32(bounds.Min.X), + int32(bounds.Min.Y), + int32(bounds.Dx()), + int32(bounds.Dy()), + ) + gl.RasterPos2d( + -1+2*float64(r.Min.X)/float64(bounds.Dx()), + +1-2*float64(r.Min.Y)/float64(bounds.Dy()), + ) + gl.PixelZoom(1, -1) + gl.DrawPixels( + int32(r.Dx()), + int32(r.Dy()), + gl.RGBA, + gl.UNSIGNED_BYTE, + unsafe.Pointer(&tmp.Pix[0]), + ) + gl.Flush() +} |