forked from GeertJohan/gomatrix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
321 lines (274 loc) · 8.7 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package main
import (
"fmt"
"log"
"math/rand"
"os"
"os/signal"
"runtime/pprof"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gdamore/tcell"
"github.com/jessevdk/go-flags"
)
var screen tcell.Screen
// command line flags variable
var opts struct {
// display ascii only instead of ascii+kana's
Ascii bool `short:"a" long:"ascii" description:"Use ascii/alphanumeric characters only instead of a mixture with japanese kana's."`
// display kana's instead of ascii+kana's
Kana bool `short:"k" long:"kana" description:"Use japanese kana's only instead of a mix of ascii/alphanumeric and 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',
'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',
}
// everything together, for that authentic feel
var allTheCharacters = append(halfWidthKana, alphaNumerics...)
// characters to be used, can be set to alphaNumerics or halfWidthKana depending on flags
// defaults to allTheCharacters
var characters []rune
// streamDisplays by column number
var streamDisplaysByColumn = make(map[int]*StreamDisplay)
// current sizes
var curSizes sizes
// channel used to notify StreamDisplayManager
var sizesUpdateCh = make(chan sizes)
// struct sizes contains terminal sizes (in amount of characters)
type sizes struct {
width int
height int
curStreamsPerStreamDisplay int // current amount of streams per display allowed
}
// set the sizes and notify StreamDisplayManager
func (s *sizes) setSizes(width int, height int) {
s.width = width
s.height = height
s.curStreamsPerStreamDisplay = 1 + height/10
}
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)
}
err = pprof.StartCPUProfile(f)
if err != nil {
fmt.Printf("Error start profiling : %s\n", err)
os.Exit(1)
}
}
// Use 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.")
if opts.Ascii {
characters = alphaNumerics
} else if opts.Kana {
characters = halfWidthKana
} else {
characters = allTheCharacters
}
// 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
curSizes.setSizes(screen.Size())
sizesUpdateCh <- curSizes
// flusher flushes the termbox every x milliseconds
curFPS := opts.FPS
fpsSleepTime := time.Duration(1000000/curFPS) * time.Microsecond
fmt.Printf("fps sleep time: %s\n", fpsSleepTime.String())
go func() {
for {
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, os.Kill)
// handle tcell events and unix signals
EVENTS:
for {
// 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:
break EVENTS
case tcell.KeyCtrlL:
screen.Sync()
case tcell.KeyRune:
switch ev.Rune() {
case 'q':
break EVENTS
case 'c':
screen.Clear()
case 'k':
characters = halfWidthKana
case 'b': // "both"
characters = allTheCharacters
case '+': // speed it up
if curFPS < 60 {
curFPS++
fpsSleepTime = time.Duration(1000000/curFPS) * time.Microsecond
}
case '-': // slow it down
if curFPS > 1 {
curFPS--
fpsSleepTime = time.Duration(1000000/curFPS) * time.Microsecond
}
case '=': // set the speed back to where it started
curFPS = opts.FPS
fpsSleepTime = time.Duration(1000000/curFPS) * time.Microsecond
}
//++ TODO: add more fun keys (slowmo? freeze? rampage?)
}
case *tcell.EventResize: // set sizes
w, h := ev.Size()
curSizes.setSizes(w, h)
sizesUpdateCh <- curSizes
case *tcell.EventError: // quit
log.Fatalf("Quitting because of tcell error: %v", ev.Error())
}
case signal := <-sigChan:
log.Printf("Have signal: \n%s", spew.Sdump(signal))
break EVENTS
}
}
// 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()
}
}