forked from GeertJohan/gomatrix
/
main.go
300 lines (252 loc) · 7.72 KB
/
main.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package main
import (
"fmt"
"log"
"math/rand"
"os"
"os/signal"
"runtime/pprof"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/jessevdk/go-flags"
"github.com/gdamore/tcell"
)
var screen tcell.Screen
// command line flags variable
var opts struct {
// display ascii instead of kana's
Ascii bool `short:"a" long:"ascii" description:"Use ascii/alphanumeric characters instead of japanese kana's."`
// enable logging
Logging bool `short:"l" long:"log" description:"Enable logging debug messages to ~/.gomatrix-log."`
// enable profiling
Profile string `short:"p" long:"profile" description:"Write profile to given file path"`
// FPS
FPS int `long:"fps" description:"required FPS, must be somewhere between 1 and 60" default:"25"`
}
// array with half width kanas as Go runes
// source: http://en.wikipedia.org/wiki/Half-width_kana
var halfWidthKana = []rune{
'。', '「', '」', '、', '・', 'ヲ', 'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ャ', 'ュ', 'ョ', 'ッ',
'ー', 'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク', 'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ',
'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'マ',
'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ン', '゙', '゚',
}
// just basic alphanumeric characters
var alphaNumerics = []rune{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
}
// characters to be used, is being set to alphaNumerics or halfWidthKana depending on flags
var characters []rune
// streamDisplays by column number
var streamDisplaysByColumn = make(map[int]*StreamDisplay)
// struct sizes contains terminal sizes (in amount of characters)
type sizes struct {
width int
height int
}
var curSizes sizes // current sizes
var curStreamsPerStreamDisplay = 0 // curent amount of streams per display allowed
var sizesUpdateCh = make(chan sizes) //channel used to notify StreamDisplayManager
// set the sizes and notify StreamDisplayManager
func setSizes(width int, height int) {
s := sizes{
width: width,
height: height,
}
curSizes = s
curStreamsPerStreamDisplay = 1 + height/10
sizesUpdateCh <- s
}
func main() {
// parse flags
args, err := flags.Parse(&opts)
if err != nil {
flagError := err.(*flags.Error)
if flagError.Type == flags.ErrHelp {
return
}
if flagError.Type == flags.ErrUnknownFlag {
fmt.Println("Use --help to view all available options.")
return
}
fmt.Printf("Error parsing flags: %s\n", err)
return
}
if len(args) > 0 {
// we don't accept too much arguments..
fmt.Printf("Unknown argument '%s'.\n", args[0])
return
}
if opts.FPS < 1 || opts.FPS > 60 {
fmt.Println("Error: option --fps not within range 1-60")
os.Exit(1)
}
// Start profiling (if required)
if len(opts.Profile) > 0 {
f, err := os.Create(opts.Profile)
if err != nil {
fmt.Printf("Error opening profiling file: %s\n", err)
os.Exit(1)
}
pprof.StartCPUProfile(f)
}
// Juse a println for fun..
fmt.Println("Opening connection to The Matrix.. Please stand by..")
// setup logging with logfile /dev/null or ~/.gomatrix-log
filename := os.DevNull
if opts.Logging {
filename = os.Getenv("HOME") + "/.gomatrix-log"
}
logfile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("Could not open logfile. %s\n", err)
os.Exit(1)
}
defer logfile.Close()
log.SetOutput(logfile)
log.Println("-------------")
log.Println("Starting gomatrix. This logfile is for development/debug purposes.")
characters = halfWidthKana
if opts.Ascii {
characters = alphaNumerics
}
// seed the rand package with time
rand.Seed(time.Now().UnixNano())
// initialize tcell
if screen, err = tcell.NewScreen(); err != nil {
fmt.Println("Could not start tcell for gomatrix. View ~/.gomatrix-log for error messages.")
log.Printf("Cannot alloc screen, tcell.NewScreen() gave an error:\n%s", err)
os.Exit(1)
}
err = screen.Init()
if err != nil {
fmt.Println("Could not start tcell for gomatrix. View ~/.gomatrix-log for error messages.")
log.Printf("Cannot start gomatrix, screen.Init() gave an error:\n%s", err)
os.Exit(1)
}
screen.HideCursor()
screen.SetStyle(tcell.StyleDefault.
Background(tcell.ColorBlack).
Foreground(tcell.ColorBlack))
screen.Clear()
// StreamDisplay manager
go func() {
var lastWidth int
for newSizes := range sizesUpdateCh {
log.Printf("New width: %d\n", newSizes.width)
diffWidth := newSizes.width - lastWidth
if diffWidth == 0 {
// same column size, wait for new information
log.Println("Got resize over channel, but diffWidth = 0")
continue
}
if diffWidth > 0 {
log.Printf("Starting %d new SD's\n", diffWidth)
for newColumn := lastWidth; newColumn < newSizes.width; newColumn++ {
// create stream display
sd := &StreamDisplay{
column: newColumn,
stopCh: make(chan bool, 1),
streams: make(map[*Stream]bool),
newStream: make(chan bool, 1), // will only be filled at start and when a spawning stream has it's tail released
}
streamDisplaysByColumn[newColumn] = sd
// start StreamDisplay in goroutine
go sd.run()
// create first new stream
sd.newStream <- true
}
lastWidth = newSizes.width
}
if diffWidth < 0 {
log.Printf("Closing %d SD's\n", diffWidth)
for closeColumn := lastWidth - 1; closeColumn > newSizes.width; closeColumn-- {
// get sd
sd := streamDisplaysByColumn[closeColumn]
// delete from map
delete(streamDisplaysByColumn, closeColumn)
// inform sd that it's being closed
sd.stopCh <- true
}
lastWidth = newSizes.width
}
}
}()
// set initial sizes
setSizes(screen.Size())
// flusher flushes the tcell every x miliseconds
fpsSleepTime := time.Duration(1000000/opts.FPS) * time.Microsecond
go func() {
for {
// <-time.After(40 * time.Millisecond) //++ TODO: find out wether .After() or .Sleep() is better performance-wise
time.Sleep(fpsSleepTime)
screen.Show()
}
}()
// make chan for tembox events and run poller to send events on chan
eventChan := make(chan tcell.Event)
go func() {
for {
event := screen.PollEvent()
eventChan <- event
}
}()
// register signals to channel
sigChan := make(chan os.Signal)
signal.Notify(sigChan, os.Interrupt)
signal.Notify(sigChan, os.Kill)
// handle tcell events and unix signals
done := false
for !done {
// select for either event or signal
select {
case event := <-eventChan:
log.Printf("Have event: \n%s", spew.Sdump(event))
// switch on event type
switch ev := event.(type) {
case *tcell.EventKey:
switch ev.Key() {
case tcell.KeyCtrlZ, tcell.KeyCtrlC:
done = true
continue
//++ TODO: add more fun keys (slowmo? freeze? rampage?)
case tcell.KeyCtrlL:
screen.Sync()
case tcell.KeyRune:
switch ev.Rune() {
case 'q':
done = true
continue
case 'c':
screen.Clear()
case 'a':
characters = alphaNumerics
case 'k':
characters = halfWidthKana
}
}
case *tcell.EventResize: // set sizes
w, h := ev.Size()
setSizes(w, h)
case *tcell.EventError: // quit
log.Fatalf("Quitting because of tcell error: %v", ev.Error())
done = true
continue
}
case signal := <-sigChan:
log.Printf("Have signal: \n%s", spew.Sdump(signal))
done = true
continue
}
}
// close down
screen.Fini()
log.Println("stopping gomatrix")
fmt.Println("Thank you for connecting with Morpheus' Matrix API v4.2. Have a nice day!")
// stop profiling (if required)
if len(opts.Profile) > 0 {
pprof.StopCPUProfile()
}
}