summaryrefslogtreecommitdiff
path: root/internal/termprint/columns.go
blob: b4d30bcf760bd1efcf4863fd4b1de60432be41c1 (plain)
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
package termprint

import (
	"io"
	"os"
	"strings"
	"sync"

	"github.com/mattn/go-runewidth"
	"golang.org/x/term"
)

// ColumnPrinter streams provider output in side-by-side columns.
type ColumnPrinter struct {
	mu        sync.Mutex
	stdout    io.Writer
	columns   int
	colWidth  int
	partial   []string
	providers []string
	models    []string
}

type columnWriter struct {
	printer *ColumnPrinter
	index   int
}

// NewColumnPrinter builds a multi-column printer for the provider/model pairs.
func NewColumnPrinter(stdout io.Writer, providers []string, models []string) *ColumnPrinter {
	cols := len(providers)
	if len(models) > cols {
		cols = len(models)
	}
	if cols == 0 {
		return nil
	}

	width := detectTerminalWidth(stdout)
	if width <= 0 {
		width = 100
	}
	sepWidth := (cols - 1) * 3
	colWidth := (width - sepWidth) / cols
	if colWidth < 20 {
		colWidth = 20
	}

	providerCols := make([]string, cols)
	copy(providerCols, providers)
	modelCols := make([]string, cols)
	copy(modelCols, models)

	return &ColumnPrinter{
		stdout:    stdout,
		columns:   cols,
		colWidth:  colWidth,
		partial:   make([]string, cols),
		providers: providerCols,
		models:    modelCols,
	}
}

func detectTerminalWidth(w io.Writer) int {
	type fder interface{ Fd() uintptr }
	if f, ok := w.(*os.File); ok {
		if width, _, err := term.GetSize(int(f.Fd())); err == nil {
			return width
		}
	}
	if f, ok := w.(fder); ok {
		if width, _, err := term.GetSize(int(f.Fd())); err == nil {
			return width
		}
	}
	return 0
}

// Writer returns an io.Writer that routes chunks to a single column index.
func (cp *ColumnPrinter) Writer(idx int) io.Writer {
	return columnWriter{printer: cp, index: idx}
}

// PrintHeader writes provider/model headers and a divider row.
func (cp *ColumnPrinter) PrintHeader() {
	cp.mu.Lock()
	defer cp.mu.Unlock()
	combo := make([]string, cp.columns)
	for i := 0; i < cp.columns; i++ {
		provider := strings.TrimSpace(cp.providers[i])
		model := strings.TrimSpace(cp.models[i])
		switch {
		case provider != "" && model != "":
			combo[i] = provider + ":" + model
		case provider != "":
			combo[i] = provider
		case model != "":
			combo[i] = model
		default:
			combo[i] = ""
		}
	}
	cp.writeLine(combo)
	divider := make([]string, cp.columns)
	line := strings.Repeat("─", cp.colWidth)
	for i := range divider {
		divider[i] = line
	}
	cp.writeLine(divider)
}

// Flush emits any buffered partial line for a column.
func (cp *ColumnPrinter) Flush(idx int) {
	cp.mu.Lock()
	defer cp.mu.Unlock()
	if idx < 0 || idx >= len(cp.partial) {
		return
	}
	if cp.partial[idx] == "" {
		return
	}
	cp.emitJobLine(idx, cp.partial[idx])
	cp.partial[idx] = ""
}

func (w columnWriter) Write(p []byte) (int, error) {
	return w.printer.write(w.index, string(p))
}

func (cp *ColumnPrinter) write(idx int, data string) (int, error) {
	cp.mu.Lock()
	defer cp.mu.Unlock()
	if idx < 0 || idx >= len(cp.partial) {
		return len(data), nil
	}
	data = strings.ReplaceAll(data, "\r", "")
	cp.partial[idx] += data
	for strings.Contains(cp.partial[idx], "\n") {
		line, rest, _ := strings.Cut(cp.partial[idx], "\n")
		cp.partial[idx] = rest
		cp.emitJobLine(idx, line)
	}
	return len(data), nil
}

func (cp *ColumnPrinter) emitJobLine(idx int, line string) {
	segments := cp.wrap(line)
	for _, seg := range segments {
		cells := make([]string, cp.columns)
		if idx >= 0 && idx < len(cells) {
			cells[idx] = seg
		}
		cp.writeLine(cells)
	}
}

func (cp *ColumnPrinter) wrap(text string) []string {
	text = strings.ReplaceAll(text, "\t", "    ")
	if runewidth.StringWidth(text) <= cp.colWidth {
		return []string{text}
	}
	var lines []string
	var current strings.Builder
	width := 0
	for _, r := range text {
		rw := runewidth.RuneWidth(r)
		if width+rw > cp.colWidth && current.Len() > 0 {
			lines = append(lines, current.String())
			current.Reset()
			width = 0
		}
		current.WriteRune(r)
		width += rw
	}
	if current.Len() > 0 {
		lines = append(lines, current.String())
	}
	if len(lines) == 0 {
		lines = append(lines, "")
	}
	return lines
}

func (cp *ColumnPrinter) writeLine(cells []string) {
	if len(cells) < cp.columns {
		extra := make([]string, cp.columns-len(cells))
		cells = append(cells, extra...)
	}
	var builder strings.Builder
	for i := 0; i < cp.columns; i++ {
		cell := cells[i]
		width := runewidth.StringWidth(cell)
		if width > cp.colWidth {
			cell = runewidth.Truncate(cell, cp.colWidth, "…")
			width = runewidth.StringWidth(cell)
		}
		builder.WriteString(cell)
		if pad := cp.colWidth - width; pad > 0 {
			builder.WriteString(strings.Repeat(" ", pad))
		}
		if i != cp.columns-1 {
			builder.WriteString(" │ ")
		}
	}
	builder.WriteByte('\n')
	_, _ = cp.stdout.Write([]byte(builder.String()))
}