-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
253 lines (206 loc) · 5.36 KB
/
module.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package cy
import (
"context"
"fmt"
"os"
"sync/atomic"
"time"
"github.com/cfoust/cy/pkg/bind"
"github.com/cfoust/cy/pkg/events"
"github.com/cfoust/cy/pkg/geom"
"github.com/cfoust/cy/pkg/janet"
"github.com/cfoust/cy/pkg/mux/screen"
"github.com/cfoust/cy/pkg/mux/screen/replay"
"github.com/cfoust/cy/pkg/mux/screen/server"
"github.com/cfoust/cy/pkg/mux/screen/toasts"
"github.com/cfoust/cy/pkg/mux/screen/tree"
"github.com/cfoust/cy/pkg/mux/stream"
"github.com/cfoust/cy/pkg/params"
"github.com/cfoust/cy/pkg/util"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/sasha-s/go-deadlock"
)
type Options struct {
// The initial Janet script, typically ~/.cyrc.janet.
Config string
// The default directory in which to store data (e.g. recorded sessions).
DataDir string
// The default shell
Shell string
// Whether to show the splash screen on client join
HideSplash bool
}
type historyEvent struct {
Stamp time.Time
Client ClientID
Node tree.NodeID
}
type Cy struct {
util.Lifetime
deadlock.RWMutex
*janet.VM
nextClientID atomic.Int32
muxServer *server.Server
// The top-level fallback for all parameter queries. This is distinct
// from the *Parameters at the root node of the tree, which the user
// can actually change.
defaults *params.Parameters
// The tree of groups and panes
tree *tree.Tree
// Replay mode has its own isolated binding scope
replayBinds *bind.BindScope
clients []*Client
log zerolog.Logger
configPath string
showSplash bool
toast *ToastLogger
queuedToasts []toasts.Toast
// Every time a client writes to or visits a node, we make a note of it
// so we can infer who last used it
// (tmux does the same thing)
lastWrite, lastVisit map[tree.NodeID]historyEvent
writes, visits chan historyEvent
}
func (c *Cy) loadUserConfig(ctx context.Context) {
err := c.ExecuteFile(ctx, c.configPath)
if err != nil {
c.log.Error().Err(err).Msg("failed to execute config")
message := fmt.Sprintf("an error occurred while loading %s: %s", c.configPath, err.Error())
c.toast.Error(message)
}
}
// Get the first pane that another client is attached to or return nil if there
// are no other clients.
func (c *Cy) getFirstClientPane(except *Client) tree.Node {
c.RLock()
defer c.RUnlock()
clients := c.clients
if len(clients) == 0 {
return nil
}
for _, client := range clients {
if client == except {
continue
}
node := client.Node()
if node != nil {
return node
}
}
return nil
}
func (c *Cy) Shutdown() error {
c.RLock()
defer c.RUnlock()
for _, client := range c.clients {
err := client.Detach("server went away")
if err != nil {
return err
}
}
c.Cancel()
return nil
}
func (c *Cy) pollInteractions(ctx context.Context, journal map[tree.NodeID]historyEvent, channel chan historyEvent) {
for {
select {
case <-ctx.Done():
return
case event := <-channel:
c.Lock()
journal[event.Node] = event
c.Unlock()
}
}
}
func (c *Cy) getClient(id ClientID) (client *Client, found bool) {
c.RLock()
defer c.RUnlock()
for _, otherClient := range c.clients {
if otherClient.id == id {
client = otherClient
found = true
return
}
}
return
}
func (c *Cy) inferClient(node tree.NodeID) (client *Client, found bool) {
c.RLock()
write, haveWrite := c.lastWrite[node]
visit, haveVisit := c.lastVisit[node]
c.RUnlock()
if !haveVisit {
return
}
if !haveWrite || write.Stamp.Before(visit.Stamp) {
return c.getClient(visit.Client)
}
return c.getClient(write.Client)
}
func (c *Cy) pollNodeEvents(ctx context.Context, events <-chan events.Msg) {
for {
select {
case <-ctx.Done():
return
case event := <-events:
nodeEvent, ok := event.(tree.NodeEvent)
if !ok {
continue
}
client, ok := c.inferClient(nodeEvent.Id)
if !ok {
continue
}
switch event := nodeEvent.Event.(type) {
case replay.CopyEvent:
client.buffer = event.Text
case bind.BindEvent:
go client.runAction(event)
}
}
}
}
func Start(ctx context.Context, options Options) (*Cy, error) {
replayBinds := bind.NewBindScope(nil)
defaults := params.New()
t := tree.NewTree(tree.WithParams(defaults.NewChild()))
cy := Cy{
Lifetime: util.NewLifetime(ctx),
tree: t,
muxServer: server.New(),
replayBinds: replayBinds,
defaults: defaults,
showSplash: !options.HideSplash,
lastVisit: make(map[tree.NodeID]historyEvent),
lastWrite: make(map[tree.NodeID]historyEvent),
writes: make(chan historyEvent),
visits: make(chan historyEvent),
}
cy.toast = NewToastLogger(cy.sendToast)
err := cy.setDefaults(options)
if err != nil {
return nil, err
}
subscriber := t.Subscribe(cy.Ctx())
go cy.pollNodeEvents(cy.Ctx(), subscriber.Recv())
go cy.pollInteractions(cy.Ctx(), cy.lastWrite, cy.writes)
go cy.pollInteractions(cy.Ctx(), cy.lastVisit, cy.visits)
logs := stream.NewReader()
terminal := screen.NewTerminal(cy.Ctx(), logs, geom.DEFAULT_SIZE)
logPane := t.Root().NewPane(cy.Ctx(), terminal)
logPane.SetName("logs")
consoleWriter := zerolog.ConsoleWriter{Out: logs.Writer(), TimeFormat: time.RFC3339}
cy.log = log.Output(zerolog.MultiLevelWriter(consoleWriter, os.Stdout))
vm, err := cy.initJanet(ctx)
if err != nil {
return nil, fmt.Errorf("error initializing Janet: %s", err.Error())
}
cy.VM = vm
if len(options.Config) != 0 {
cy.configPath = options.Config
cy.loadUserConfig(ctx)
}
return &cy, nil
}