-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.go
607 lines (563 loc) · 15.8 KB
/
application.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
package main
import (
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/dpinela/charseg"
"github.com/mattn/go-runewidth"
"github.com/dpinela/mflg/internal/buffer"
"github.com/dpinela/mflg/internal/config"
"github.com/dpinela/mflg/internal/highlight"
"github.com/dpinela/mflg/internal/pathwatch"
"github.com/dpinela/mflg/internal/termdraw"
"github.com/dpinela/mflg/internal/termesc"
"golang.org/x/crypto/ssh/terminal"
)
type application struct {
searchRE *regexp.Regexp // The regexp used in the last navigation command, if any
navStack []location
filename string
mainWindow, promptWindow *window
cursorVisible bool
screen *termdraw.Screen
promptHandler func(string) // What to do with the prompt input when the user hits Enter
note string
noteClearTimer timer
saveDelay time.Duration
saveTimer timer
taskQueue chan func() // Used by asynchronous tasks to run code on the main event loop
fsWatcher *pathwatch.Watcher
fileChangeCh chan struct{}
configChangeCh chan struct{}
// These fields are used when receiving a bracketed paste
pasteBuffer []byte
inBracketedPaste bool
titleNeedsRedraw bool
config *config.Config
}
// A wrapper for time.Timer that can be safely reset.
// The zero value is an inactive, usable timer.
// After receiving on the timer t's channel, the receiver must set t.pending to false.
type timer struct {
timer *time.Timer
pending bool
}
func (t *timer) reset(dt time.Duration) {
if t.timer == nil {
t.timer = time.NewTimer(dt)
t.pending = true
return
}
t.stop()
t.timer.Reset(dt)
t.pending = true
}
func (t *timer) stop() {
if t.timer != nil && !t.timer.Stop() && t.pending {
<-t.timer.C
}
t.pending = false
}
func (t *timer) channel() <-chan time.Time {
if t.timer == nil {
return nil
}
return t.timer.C
}
type location struct {
filename string
pos point
}
func newApplication(outdev io.Writer, size termdraw.Point) *application {
return &application{
cursorVisible: true,
saveDelay: 1 * time.Second,
screen: termdraw.NewScreen(outdev, size),
taskQueue: make(chan func(), 32),
fileChangeCh: make(chan struct{}, 32),
configChangeCh: make(chan struct{}, 32),
fsWatcher: pathwatch.NewWatcher(),
}
}
func (app *application) loadConfig() {
c, err := config.Load()
if err != nil && !os.IsNotExist(err) {
app.setNotification(err.Error())
return
}
app.config = c
if ext := filepath.Ext(app.filename); ext != "" && app.mainWindow != nil {
app.mainWindow.langConfig = app.config.ConfigForExt(ext[1:])
}
}
func (app *application) navigateTo(where string) error {
// If this isn't the very first navigation command, save the current location and add it to the
// navigation stack once the command completes successfully.
oldLocation := location{filename: app.filename, pos: point{-1, -1}}
if app.filename != "" {
oldLocation.pos = app.mainWindow.windowCoordsToTextCoords(app.mainWindow.cursorPos)
}
line := 1
regex := (*regexp.Regexp)(nil)
filename := where
err := error(nil)
if i := strings.IndexByte(where, ':'); i != -1 {
filename = where[:i]
if rest := where[i+1:]; allASCIIDigits(rest) {
line, err = strconv.Atoi(rest)
} else {
regex, err = regexp.Compile(rest)
}
if err != nil {
return err
}
}
switch filename {
case "-c":
filename, err = config.Path()
if err != nil {
return err
}
case "":
default:
filename = expandPath(filename)
// Interpret relative paths relative to the directory containing the current file, if any.
// When starting up, interpret them relative to the working directory.
if !filepath.IsAbs(filename) {
if app.filename != "" {
filename = filepath.Join(filepath.Dir(app.filename), filename)
} else {
if filename, err = filepath.Abs(filename); err != nil {
return err
}
}
}
}
if err := app.gotoFile(filename); err != nil {
return err
}
switch {
case regex != nil:
app.mainWindow.searchRegexp(regex, 0)
case line > 0:
app.mainWindow.gotoLine(line - 1)
}
if oldLocation.pos.Y >= 0 {
app.navStack = append(app.navStack, oldLocation)
}
app.searchRE = regex
return nil
}
// expandPath expands references to environment variables in path, of the form $VAR or ${VAR}.
// It also expands ~/ at the start of a path to the user's home directory.
func expandPath(path string) string {
path = os.ExpandEnv(path)
if p := strings.TrimPrefix(path, "~"+string(filepath.Separator)); len(p) != len(path) {
// In the unlikely event that the lookup fails, leave the tilde unexpanded; it will be easier
// to detect the problem that way.
if h, err := homeDir(); err == nil {
path = filepath.Join(h, p)
}
}
return path
}
// This is a variable so that it can be mocked for tests.
var homeDir = os.UserHomeDir
// gotoFile loads the file at filename into the editor, if it isn't the currently open file already.
func (app *application) gotoFile(filename string) error {
if filename != "" && filename != app.filename {
buf := buffer.New()
if f, err := os.Open(filename); err == nil {
_, err = buf.ReadFrom(f)
f.Close()
if err != nil {
return err
}
// Allow the user to edit a file that doesn't exist yet
} else if !os.IsNotExist(err) {
return err
}
if app.fileChangeCh == nil {
app.fileChangeCh = make(chan struct{}, 32)
}
app.fsWatcher.Remove(app.filename, app.fileChangeCh)
app.finishFormatNow()
app.saveNow()
app.fsWatcher.Add(filename, app.fileChangeCh)
size := app.screen.Size()
app.mainWindow = newWindow(app, size.X, size.Y, buf)
app.mainWindow.onChange = app.resetSaveTimer
if ext := filepath.Ext(filename); ext != "" {
app.mainWindow.langConfig = app.config.ConfigForExt(ext[1:])
app.mainWindow.highlighter = highlight.Language(ext[1:], app.mainWindow)
} else {
app.mainWindow.highlighter = highlight.Language(ext, app.mainWindow)
}
app.filename = filename
app.titleNeedsRedraw = true
}
return nil
}
func (app *application) reloadFile() error {
buf := buffer.New()
if f, err := os.Open(app.filename); err == nil {
_, err = buf.ReadFrom(f)
f.Close()
if err != nil {
return err
}
} else if !os.IsNotExist(err) {
return err
}
app.mainWindow.buf = buf
app.mainWindow.wrappedBuf.Reset(buf)
app.mainWindow.highlighter.Invalidate(0)
app.mainWindow.roundCursorPos()
app.mainWindow.needsRedraw = true
if app.promptWindow != nil {
app.promptWindow.needsRedraw = true
}
return nil
}
func (app *application) gotoNextMatch() {
if app.searchRE != nil {
tp := app.mainWindow.windowCoordsToTextCoords(app.mainWindow.cursorPos)
app.navStack = append(app.navStack, location{filename: app.filename, pos: tp})
app.mainWindow.searchRegexp(app.searchRE, tp.Y+1)
}
}
func (app *application) back() error {
if len(app.navStack) == 0 {
return nil
}
s := app.navStack
loc := s[len(s)-1]
if err := app.gotoFile(loc.filename); err != nil {
return err
}
app.mainWindow.gotoTextPos(loc.pos)
app.navStack = s[:len(s)-1]
return nil
}
func (app *application) currentFile() string { return app.filename }
func (app *application) resetSaveTimer() { app.saveTimer.reset(app.saveDelay) }
func (app *application) saveNow() {
if app.saveTimer.pending {
if !app.saveTimer.timer.Stop() {
<-app.saveTimer.timer.C
}
saveBuffer(app.filename, app.mainWindow.buf)
app.saveTimer.pending = false
}
}
func (app *application) finishFormatNow() {
for app.mainWindow != nil && app.mainWindow.formatPending {
(<-app.taskQueue)()
}
}
func (app *application) run(in io.Reader, resizeSignal <-chan os.Signal) error {
cp, err := config.Path()
if err != nil {
return err
}
app.fsWatcher.Add(cp, app.configChangeCh)
inputCh := make(chan string, 32)
go func() {
con := termesc.NewConsoleReader(in)
for {
if s, err := con.ReadToken(); err != nil {
close(inputCh)
return
} else {
inputCh <- s
}
}
}()
for {
app.redraw()
if err := app.screen.Flip(); err != nil {
return err
}
aw := app.activeWindow()
select {
case c, ok := <-inputCh:
if !ok {
return nil
}
if app.inBracketedPaste {
if c == termesc.PastedTextEnd {
aw.insertText(app.pasteBuffer)
app.inBracketedPaste = false
} else {
if c == "\r" {
c = "\n"
}
app.pasteBuffer = append(app.pasteBuffer, c...)
}
continue
}
switch c {
case termesc.UpKey:
aw.repeatMove(aw.moveCursorUp)
case termesc.DownKey:
aw.repeatMove(aw.moveCursorDown)
case termesc.LeftKey:
aw.moveCursorLeft()
case termesc.RightKey:
aw.moveCursorRight()
case termesc.PastedTextBegin:
app.inBracketedPaste = true
app.pasteBuffer = app.pasteBuffer[:0]
case "\x11":
app.finishFormatNow()
if app.saveTimer.pending {
saveBuffer(app.filename, app.mainWindow.buf)
}
return nil
case "\x7f", "\b":
aw.backspace()
case "\x0c":
app.openPrompt("Go to:", func(response string) {
if err := app.navigateTo(response); err != nil {
app.setNotification(err.Error())
}
})
case "\x07":
app.gotoNextMatch()
case "\x02":
if err := app.back(); err != nil {
app.setNotification(err.Error())
}
case "\x06":
aw.formatBuffer()
case "\x12":
app.openPrompt("Replace:", func(searchRE string) {
re, err := regexp.Compile(searchRE)
if err != nil {
app.setNotification(err.Error())
return
}
app.openPrompt("With:", func(replacement string) {
app.mainWindow.replaceRegexp(re, replacement)
})
})
case "\x01":
if !aw.inMouseSelection() {
aw.markSelectionBound()
}
case "\x18":
aw.cutSelection()
case "\x03":
aw.copySelection()
case "\x16":
aw.paste()
case "\x1a":
aw.undo()
case "\x15":
if len(aw.undoStack) > 0 && app.promptWindow == nil {
app.openPrompt("Discard changes [y/Esc]?", func(resp string) {
if len(resp) != 0 && (resp[0] == 'Y' || resp[0] == 'y') {
aw.undoAll()
}
})
} else {
aw.undoAll()
}
case "\x1b":
switch {
case aw.selection.Set || aw.selectionAnchor.Set || aw.mouseSelectionAnchor.Set:
aw.resetSelectionState()
case app.promptWindow != nil:
app.cancelPrompt()
}
default:
if ev, err := termesc.ParseMouseEvent(c); err == nil {
app.handleMouseEvent(ev)
} else if c >= " " || c == "\r" || c == "\t" {
if app.promptWindow != nil && c == "\r" {
app.finishPrompt()
} else {
aw.typeText(c)
}
} else if termesc.IsAltRightKey(c) {
aw.moveCursorRightWord()
} else if termesc.IsAltLeftKey(c) {
aw.moveCursorLeftWord()
}
}
case <-resizeSignal:
// This can only fail if our terminal turns into a non-terminal
// during execution, which is highly unlikely.
if w, h, err := terminal.GetSize(0); err != nil {
return err
} else {
app.resize(h, w)
}
case <-app.saveTimer.channel():
app.saveTimer.pending = false
if err := saveBuffer(app.filename, app.mainWindow.buf); err != nil {
app.setNotification(err.Error())
}
case <-app.noteClearTimer.channel():
app.noteClearTimer.pending = false
app.note = ""
app.mainWindow.needsRedraw = true
case <-app.fileChangeCh:
app.reloadFile()
case <-app.configChangeCh:
app.loadConfig()
case err := <-app.fsWatcher.Errors():
app.setNotification(err.Error())
case f := <-app.taskQueue:
f()
}
}
}
// do schedules f to run on the main event loop.
// It is safe to call it concurrently only from outside the goroutine running app.run.
// Calling it from that goroutine may deadlock.
func (app *application) do(f func()) {
app.taskQueue <- f
}
func (app *application) resize(height, width int) {
app.screen.Resize(termdraw.Point{X: width, Y: height})
app.mainWindow.resize(height, width)
if app.promptWindow != nil {
app.promptWindow.resize(1, width)
}
}
// openPrompt opens a prompt window at the bottom of the viewport.
// When the user hits Enter, whenDone is called with the entered text.
func (app *application) openPrompt(prompt string, whenDone func(string)) {
app.promptWindow = newWindow(app, app.screen.Size().X, 1, buffer.New())
app.promptWindow.setGutterText(prompt)
app.promptWindow.highlighter = highlight.Language("", app.promptWindow)
app.promptHandler = whenDone
app.note = ""
}
func (app *application) cancelPrompt() {
app.mainWindow.needsRedraw = true
app.promptWindow = nil
app.promptHandler = nil
}
func (app *application) finishPrompt() {
// Do things in this order so that the prompt handler can safely call openPrompt.
response := app.promptWindow.buf.Line(0)
handler := app.promptHandler
app.cancelPrompt()
handler(response)
}
// setNotification displays a string at the bottom line of the viewport until the next
// call to this or openPrompt.
func (app *application) setNotification(note string) {
app.note = note
app.noteClearTimer.reset(5 * time.Second)
}
func (app *application) activeWindow() *window {
if app.promptWindow != nil {
return app.promptWindow
}
return app.mainWindow
}
func (app *application) promptYOffset() int {
if app.promptWindow != nil {
return app.screen.Size().Y - 1
}
return app.screen.Size().Y
}
func (app *application) redraw() {
app.screen.Clear()
app.screen.SetTitle(app.filename)
app.mainWindow.redraw(app.screen)
// When displaying the prompt or a message, clear out the bottom row first so the existing text doesn't show.
switch {
case app.promptWindow != nil:
clearBottomRow(app.screen)
app.promptWindow.redrawAtYOffset(app.screen, app.promptYOffset())
case app.note != "":
clearBottomRow(app.screen)
ellipsify2(app.screen, app.note, termdraw.Style{Bold: true})
}
app.screen.SetCursorVisible(app.activeWindow().cursorInViewport())
p := app.cursorPos()
app.screen.SetCursorPos(termdraw.Point{X: p.X + app.activeWindow().gutterWidth(), Y: p.Y})
}
func clearBottomRow(scr *termdraw.Screen) {
s := scr.Size()
for p := (termdraw.Point{X: 0, Y: s.Y - 1}); p.X < s.X; p.X++ {
scr.Put(p, termdraw.Cell{})
}
}
func ellipsify2(console *termdraw.Screen, text string, style termdraw.Style) {
if i := strings.IndexByte(text, '\n'); i != -1 {
text = text[:i]
}
text = strings.Replace(text, "\t", " ", -1)
size := console.Size()
wp := termdraw.Point{X: 0, Y: size.Y - 1}
for i := 0; i < len(text); {
c := charseg.FirstGraphemeCluster(text[i:])
w := runewidth.StringWidth(c)
if wp.X+w > size.X {
for x := size.X - min(3, size.X); x < size.X; x++ {
console.Put(termdraw.Point{X: x, Y: wp.Y}, termdraw.Cell{Content: ".", Style: style})
}
return
}
console.Put(wp, termdraw.Cell{Content: c, Style: style})
wp.X += w
i += len(c)
}
}
var ellipses = [...]string{"", ".", "..", "..."}
// ellipsify truncates text to fit within width columns, adding an ellipsis at the end if it
// must be truncated.
func ellipsify(text string, width int) string {
if i := strings.IndexByte(text, '\n'); i != -1 {
text = text[:i]
}
text = strings.Replace(text, "\t", " ", -1)
if n := runewidth.StringWidth(text); n <= width {
return text
}
n := 0
prefix := ""
prefixSet := false
for i := 0; i < len(text); {
c := charseg.FirstGraphemeCluster(text[i:])
w := runewidth.StringWidth(c)
// Record the part of the string that fits without counting the ellipsis.
if n+w > width-3 && !prefixSet {
prefix = text[:i]
prefixSet = true
}
if n+w > width {
return prefix + ellipses[min(3, width)]
}
n += w
i += len(c)
}
return text
}
func (app *application) cursorPos() point {
if app.promptWindow != nil {
p := app.promptWindow.viewportCursorPos()
return point{p.X, p.Y + app.promptYOffset()}
}
return app.mainWindow.viewportCursorPos()
}
func (app *application) handleMouseEvent(ev termesc.MouseEvent) {
if py := app.promptYOffset(); ev.Y >= py && app.promptWindow != nil {
ev.Y -= py
app.promptWindow.handleMouseEvent(ev)
return
}
if app.promptWindow != nil && !ev.Move {
app.cancelPrompt()
}
app.mainWindow.handleMouseEvent(ev)
}