-
Notifications
You must be signed in to change notification settings - Fork 2
/
wsys.go
142 lines (130 loc) · 2.43 KB
/
wsys.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package shrew
import (
"image"
"log"
"sync"
"time"
)
func (w *Wsys) merge(C ...<-chan Msg) <-chan Msg {
var wg sync.WaitGroup
out := make(chan Msg)
output := func(c <-chan Msg) {
for n := range c {
out <- n
}
wg.Done()
}
wg.Add(len(C))
for _, c := range C {
go output(c)
}
// Start a goroutine to close out once all the output goroutines are
// done. This must start after the wg.Add call.
go func() {
wg.Wait()
close(out)
}()
return out
}
type Wsys struct {
// The window system has several independently executing clients, each of which has the same external
// specification. It multiplexes a screen, mouse, and keyboard for its clients and therefore has a type reminiscent
// of the clients themselves:
W Screen
M <-chan Mouse
K <-chan Kbd
C <-chan Msg
N chan *Options
Env []*Env
Nametab map[string]*Env
}
func NewWsys() *Wsys {
w := &Wsys{
N: make(chan *Options),
Nametab: make(map[string]*Env),
}
w.W = ShinyClient()
w.M, w.K = w.W.Mouse(), w.W.Kbd()
go w.prog()
return w
}
func (w *Wsys) newWindow(opt *Options) *Env {
if !opt.Bounds.In(w.W.Bounds()) {
println("bad bounds requested by client")
close(opt.reply)
return nil
}
bmp := w.W.AllocImage(opt.Bounds)
e := &Env{
Sp: opt.Bounds.Min,
W: bmp,
M: make(chan Mouse),
K: make(chan Kbd),
C: make(chan Msg),
}
w.Nametab[opt.Name] = e
w.Env = append(w.Env, e)
return e
}
func (w *Wsys) prog() {
for {
select {
case Msg := <-w.C:
if Msg.Kind == "move" {
w := w.Nametab[Msg.Name]
type Mover interface {
Move(sp image.Point)
}
Msg.Sp = Msg.Sp.Add(w.Sp)
w.W.(Mover).Move(Msg.Sp)
w.Sp = Msg.Sp
}
case opt := <-w.N:
e := w.newWindow(opt)
if e == nil {
continue
}
w.C = w.merge(w.C, e.C)
opt.reply <- e
case k := <-w.K:
for _, c := range w.Env {
c.K <- k
}
case m := <-w.M:
for i, c := range w.Env {
m := m
m.Point = m.Point.Sub(c.Sp)
select {
case c.M <- m:
case <-time.After(time.Second / 4):
log.Printf("client %d is slow\n", i)
}
}
}
}
}
type Options struct {
Name string
Bounds image.Rectangle
reply chan *Env
}
func (w *Wsys) NewClient(opt *Options) *Client {
if opt == nil {
opt = &Options{
Name: "unnamed",
Bounds: image.Rect(0, 0, 1, 1),
}
}
opt.reply = make(chan *Env)
w.N <- opt
e := <-opt.reply
if e == nil {
return nil
}
return &Client{
W: e.W,
M: e.M,
K: e.K,
C: e.C,
}
}