~dricottone/nspotify

ref: 8475ba6f72670f2b684c04aa95ffb09cbb3257ab nspotify/listing.go -rw-r--r-- 1.9 KiB
8475ba6fDominic Ricottone Initial commit 7 months ago
                                                                                
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
package main

// Manager for the track listing.

import (
	"context"
	"time"

	log "github.com/sirupsen/logrus"
	"github.com/zmb3/spotify/v2"
	"github.com/rivo/tview"
)

// Actually append tracks to the listing.
//
// NOTE: `ch` is for receiving tracks from the `FetchingManager`.
//       `quit` is for receiving a termination signal from the `ListingManager`.
//       `done` is for the reverse, sending a termination signal to the `ListingManager`.
func listingWorker(listing *tview.Table, ch <-chan *spotify.FullTrack, quit <-chan bool, done chan<- bool) {
	for {
		select {

		// Terminate loader.
		case <-quit:
			break

		default:
			cursor, _ := listing.GetSelection()
			length := listing.GetRowCount()

			if (length - cursor) < loadLookahead {
				track, ok := <- ch

				// Channel is closed; terminate now.
				if !ok {
					log.Trace("no more tracks to load")
					break
				}

				log.Tracef("loading %s...", track.Name)
				for col, cell := range IntoCells(track) {
					listing.SetCell(length, col, cell)
				}

				continue
			}

			// Wait before retrying
			time.Sleep(loadTimeout * time.Second)
		}
	}

	done <- true
}

// Manager for appending tracks to the listing.
func ListingManager(ctx context.Context, listing *tview.Table, ch <-chan *spotify.FullTrack) {
	// Load first N tracks eagerly.
	log.Tracef("loading %d tracks...", loadEager)
	for i := 0; i < loadEager; i++ {
		track := <- ch
		for col, cell := range IntoCells(track) {
			listing.SetCell(i, col, cell)
		}
	}
	log.Tracef("loaded %d tracks", loadEager)

	// Load more tracks lazily.
	quit := make(chan bool)
	done := make(chan bool)
	go listingWorker(listing, ch, quit, done)

	for {
		select {

		// Somehow track loader is terminating faster than this loop.
		case <-done:
			log.Trace("track renderer stopped running")
			break

		// Context is cancelled; terminate track loader.
		case <-ctx.Done():
			break

		}
	}

	quit <- true
}