commit 0bc7b23
Duc Nguyen
·
2021-09-24 14:57:12 +0000 UTC
parent a532aae
Restore last buffer on start review emersion review taiite review taiite Use os.WriteFile instead of os.Create
2 files changed,
+50,
-3
M
app.go
+13,
-1
1@@ -79,13 +79,15 @@ type App struct {
2
3 lastQuery string
4 messageBounds map[string]bound
5+ lastBuffer string
6 }
7
8-func NewApp(cfg Config) (app *App, err error) {
9+func NewApp(cfg Config, lastBuffer string) (app *App, err error) {
10 app = &App{
11 cfg: cfg,
12 events: make(chan event, eventChanSize),
13 messageBounds: map[string]bound{},
14+ lastBuffer: lastBuffer,
15 }
16
17 if cfg.Highlights != nil {
18@@ -136,6 +138,10 @@ func (app *App) Run() {
19 app.eventLoop()
20 }
21
22+func (app *App) CurrentBuffer() string {
23+ return app.win.CurrentBuffer()
24+}
25+
26 // eventLoop retrieves events (in batches) from the event channel and handle
27 // them, then draws the interface after each batch is handled.
28 func (app *App) eventLoop() {
29@@ -590,6 +596,12 @@ func (app *App) handleIRCEvent(ev interface{}) {
30 if ev.Topic != "" {
31 app.printTopic(ev.Channel)
32 }
33+
34+ // Restore last buffer
35+ lastBuffer := app.lastBuffer
36+ if ev.Channel == lastBuffer {
37+ app.win.JumpBuffer(lastBuffer)
38+ }
39 case irc.UserJoinEvent:
40 var body ui.StyledStringBuilder
41 body.Grow(len(ev.User) + 1)
+37,
-2
1@@ -3,9 +3,11 @@ package main
2 import (
3 "flag"
4 "fmt"
5+ "io/ioutil"
6 "math/rand"
7 "os"
8 "path"
9+ "strings"
10 "time"
11
12 "git.sr.ht/~taiite/senpai"
13@@ -41,11 +43,44 @@ func main() {
14
15 cfg.Debug = cfg.Debug || debug
16
17- app, err := senpai.NewApp(cfg)
18+ lastBuffer := getLastBuffer()
19+
20+ app, err := senpai.NewApp(cfg, lastBuffer)
21 if err != nil {
22 panic(err)
23 }
24- defer app.Close()
25
26 app.Run()
27+ app.Close()
28+
29+ // Write last buffer on close
30+ lastBufferPath := getLastBufferPath()
31+ err = os.WriteFile(lastBufferPath, []byte(app.CurrentBuffer()), 0666)
32+ if err != nil {
33+ fmt.Fprintf(os.Stderr, "failed to write last buffer at %q: %s\n", lastBufferPath, err)
34+ }
35+}
36+
37+func getLastBufferPath() string {
38+ cacheDir, err := os.UserCacheDir()
39+ if err != nil {
40+ panic(err)
41+ }
42+ cachePath := path.Join(cacheDir, "senpai")
43+ err = os.MkdirAll(cachePath, 0755)
44+ if err != nil {
45+ panic(err)
46+ }
47+
48+ lastBufferPath := path.Join(cachePath, "lastbuffer.txt")
49+ return lastBufferPath
50+}
51+
52+func getLastBuffer() string {
53+ buf, err := ioutil.ReadFile(getLastBufferPath())
54+ if err != nil {
55+ return ""
56+ }
57+
58+ return strings.TrimSpace(string(buf))
59 }