-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterm_misc.go
More file actions
419 lines (351 loc) · 11.3 KB
/
term_misc.go
File metadata and controls
419 lines (351 loc) · 11.3 KB
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
package main
import (
"bytes"
"errors"
"fmt"
"image"
_ "image/jpeg"
"image/png"
_ "image/png"
"io"
"net/http"
"os"
"regexp"
"strings"
"github.com/disintegration/imaging"
)
var (
ESC_ERASE_DISPLAY = "\x1b[2J\x1b[0;0H"
E_NON_TTY = errors.New("NON TTY")
E_TIMED_OUT = errors.New("TERM RESPONSE TIMED OUT")
)
func ExtractFileID(url string) (string, error) {
// Handle gdrive: format (new standardized format)
if strings.HasPrefix(url, "gdrive:") {
id := strings.TrimPrefix(url, "gdrive:")
if isValidGoogleDriveID(id) {
return id, nil
}
return "", errors.New("invalid gdrive: format")
}
// Handle full URL format (existing - backward compatible)
// A regular expression to find the file ID.
// It looks for a string of letters, numbers, hyphens, and underscores
// that is between "/d/" and the next "/".
re := regexp.MustCompile(`/d/([a-zA-Z0-9_-]+)`)
// Find the submatches in the URL string.
matches := re.FindStringSubmatch(url)
// The result of FindStringSubmatch is a slice where:
// - matches[0] is the full text that matched the expression (e.g., "/d/1Fj-...")
// - matches[1] is the text captured by the first group `(...)` (the file ID)
if len(matches) > 1 {
return matches[1], nil
}
return "", errors.New("google drive file ID not found in URL")
}
// isValidGoogleDriveID validates that a string looks like a valid Google Drive file ID
// Google Drive IDs are typically 28-33 characters, alphanumeric with - and _
func isValidGoogleDriveID(id string) bool {
match, _ := regexp.MatchString(`^[a-zA-Z0-9_-]{20,50}$`, id)
return match
}
// decodeImageWithOrientation decodes an image and applies EXIF orientation correction.
// Uses the imaging library's AutoOrientation feature to handle phone camera images
// that store orientation in EXIF metadata. Falls back gracefully if no EXIF present.
// Now supports HEIC format when CGO is available.
func decodeImageWithOrientation(r io.Reader) (image.Image, string, error) {
// Buffer the input so we can read it multiple times
data, err := io.ReadAll(r)
if err != nil {
return nil, "", err
}
// Check for HEIC format first (before standard library detection)
if IsHEICData(data) {
if IsHEICAvailable() {
img, err := GetHEICDecoder().Decode(bytes.NewReader(data))
if err != nil {
return nil, "", fmt.Errorf("HEIC decode failed: %v", err)
}
// HEIC images decoded by pillow-heif should already have orientation applied
// Return as "heic" format - will be converted to PNG for caching
return img, "heic", nil
}
// HEIC not available - return meaningful error
return nil, "", fmt.Errorf("HEIC format detected but not supported (requires .venv with pillow-heif)")
}
// Detect format using standard library for non-HEIC formats
_, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, "", err
}
// Decode with EXIF orientation using imaging library
img, err := imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true))
if err != nil {
return nil, "", err
}
return img, format, nil
}
// ErrGoogleDriveNotConfigured is returned when trying to load a Google Drive image
// but Google Drive credentials haven't been set up
var ErrGoogleDriveNotConfigured = errors.New("Google Drive not configured - see README.md for setup instructions")
func loadGoogleImage(path string, maxWidth, maxHeight int) (img image.Image, imgFmt string, err error) {
// Check if Google Drive service is available
if app.Session.googleDrive == nil {
err = ErrGoogleDriveNotConfigured
return
}
fileID, err := ExtractFileID(path)
if err != nil {
return
}
resp, err := app.Session.googleDrive.Files.Get(fileID).Download()
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = errors.New("Received non-OK response code")
//return fmt.Errorf("received non-OK response status: %s", resp.Status)
return
}
img, imgFmt, err = decodeImageWithOrientation(resp.Body)
// Downsize large images for cache efficiency - configurable via preferences.json
// Use Resize with height=0 to preserve aspect ratio while constraining width
if err == nil && img != nil && img.Bounds().Dx() > app.imageCacheMaxWidth {
img = imaging.Resize(img, app.imageCacheMaxWidth, 0, imaging.Lanczos)
}
return
}
func loadImage(path string, maxWidth, maxHeight int) (img image.Image, imgFmt string, err error) {
//fmt.Printf("loadImage: path=%s, maxWidth=%d, maxHeight=%d\n", path, maxWidth, maxHeight)
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
img, imgFmt, err = decodeImageWithOrientation(f)
if err != nil {
return
}
if img.Bounds().Max.X > maxWidth || img.Bounds().Max.Y > maxHeight {
//img = imaging.Resize(img, maxWidth, 0, imaging.Lanczos)
img = imaging.Fit(img, maxWidth, maxHeight, imaging.Lanczos)
}
//sess.showOrgMessage("bounds = %v", img.Bounds())
return
}
func loadWebImage(URL string) (img image.Image, imgFmt string, err error) {
//Get the response bytes from the url
response, err := http.Get(URL)
if err != nil {
return
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
err = errors.New("Received non 200 response code")
return
}
img, imgFmt, err = decodeImageWithOrientation(response.Body)
if err != nil {
return
}
if img.Bounds().Max.Y > app.Session.imgSizeY {
img = imaging.Resize(img, 0, app.Session.imgSizeY, imaging.Lanczos)
}
return
}
func displayImage(img image.Image) {
buf := new(bytes.Buffer)
err := png.Encode(buf, img)
if err != nil {
app.Organizer.ShowMessage(BL, "Error encoding image: %v", err)
return
}
err = KittyCopyPNGInline(os.Stdout, buf, int64(buf.Len()))
if err != nil {
app.Organizer.ShowMessage(BL, "Error in KittyCopyPNG...: %v", err)
}
}
// transforms given open/close terminal escapes to pass through tmux to parent terminal
func TmuxOscOpenClose(opn, cls string) (string, string) {
opn = "\x1bPtmux;" + strings.ReplaceAll(opn, "\x1b", "\x1b\x1b")
cls = strings.ReplaceAll(cls, "\x1b", "\x1b\x1b") + "\x1b\\"
return opn, cls
}
func IsTmuxScreen() bool {
TERM := strings.ToLower(strings.TrimSpace(os.Getenv("TERM")))
return strings.HasPrefix(TERM, "screen")
}
/*
Handles request/response terminal control sequences like <ESC>[0c
STDIN & STDOUT are parameterized for special cases.
os.Stdin & os.Stdout are usually sufficient.
`sRq` should be the request control sequence to the terminal.
NOTE: only captures up to 1KB of response
NOTE: when println debugging the response, probably want to go-escape
it, like:
fmt.Printf("%#v\n", sRsp)
since most responses begin with <ESC>, which the terminal treats as
another control sequence rather than text to output.
func TermRequestResponse(fileIN, fileOUT *os.File, sRq string) (sRsp []byte, E error) {
// defer func() {
// if E != nil {
// if _, file, line, ok := runtime.Caller(1); ok {
// E = fmt.Errorf("%s:%d - %s", file, line, E.Error())
// }
// }
// }()
fdIN := int(fileIN.Fd())
// NOTE: raw mode tip came from https://play.golang.org/p/kcMLTiDRZY
if !term.IsTerminal(fdIN) {
return nil, E_NON_TTY
}
// STDIN "RAW MODE" TO CAPTURE TERMINAL RESPONSE
// NOTE: without this, response bypasses stdin,
// and is written directly to the console
var oldState *term.State
if oldState, E = term.MakeRaw(fdIN); E != nil {
return
}
defer func() {
// CAPTURE RESTORE ERROR (IF ANY) IF THERE HASN'T ALREADY BEEN AN ERROR
if e2 := term.Restore(fdIN, oldState); E == nil {
E = e2
}
}()
// SEND REQUEST
if _, E = fileOUT.Write([]byte(sRq)); E != nil {
return
}
TMP := make([]byte, 1024)
// WAIT 1/16 SECOND FOR TERM RESPONSE. IF TIMER EXPIRES,
// TRIGGER BYTES TO STDIN SO .Read() CAN FINISH
tmr := time.NewTimer(time.Second >> 4)
cDone := make(chan bool)
WG := sync.WaitGroup{}
WG.Add(1)
go func() {
select {
case <-tmr.C:
// "Report Cursor Position (CPR) [row; column]
// JUST TO GET SOME BYTES TO STDIN
// NOTE: seems to work for everything except mlterm
fileOUT.Write([]byte("\x1b\x1b[" + "6n"))
break
case <-cDone:
break
}
WG.Done()
}()
// CAPTURE RESPONSE
nBytes, E := fileIN.Read(TMP)
// ENSURE GOROUTINE TERMINATION
if tmr.Stop() {
cDone <- true
} else {
// fmt.Fprintf(os.Stderr, "%#v\n", string(TMP[1:nBytes]))
E = E_TIMED_OUT
}
WG.Wait()
if (nBytes > 0) && (E != E_TIMED_OUT) {
return TMP[:nBytes], nil
}
return nil, E
}
/*
NOTE: the calling program MUST be connected to an actual terminal for this to work
Requests terminal attributes per:
https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h4-Functions-using-CSI-_-ordered-by-the-final-character-lparen-s-rparen:CSI-Ps-c.1CA3
CSI Ps c Send Device Attributes (Primary DA).
Ps = 0 or omitted ⇒ request attributes from terminal. The
response depends on the decTerminalID resource setting.
⇒ CSI ? 1 ; 2 c ("VT100 with Advanced Video Option")
⇒ CSI ? 1 ; 0 c ("VT101 with No Options")
⇒ CSI ? 4 ; 6 c ("VT132 with Advanced Video and Graphics")
⇒ CSI ? 6 c ("VT102")
⇒ CSI ? 7 c ("VT131")
⇒ CSI ? 1 2 ; Ps c ("VT125")
⇒ CSI ? 6 2 ; Ps c ("VT220")
⇒ CSI ? 6 3 ; Ps c ("VT320")
⇒ CSI ? 6 4 ; Ps c ("VT420")
The VT100-style response parameters do not mean anything by
themselves. VT220 (and higher) parameters do, telling the
host what features the terminal supports:
Ps = 1 ⇒ 132-columns.
Ps = 2 ⇒ Printer.
Ps = 3 ⇒ ReGIS graphics.
Ps = 4 ⇒ Sixel graphics.
Ps = 6 ⇒ Selective erase.
Ps = 8 ⇒ User-defined keys.
Ps = 9 ⇒ National Replacement Character sets.
Ps = 1 5 ⇒ Technical characters.
Ps = 1 6 ⇒ Locator port.
Ps = 1 7 ⇒ Terminal state interrogation.
Ps = 1 8 ⇒ User windows.
Ps = 2 1 ⇒ Horizontal scrolling.
Ps = 2 2 ⇒ ANSI color, e.g., VT525.
Ps = 2 8 ⇒ Rectangular editing.
Ps = 2 9 ⇒ ANSI text locator (i.e., DEC Locator mode).
*/
/*
func RequestTermAttributes() (sAttrs []int, E error) {
text, E := TermRequestResponse(os.Stdin, os.Stdout, "\x1b[0c")
if E != nil {
return
}
// EXTRACT CODES
t2 := rxNumber.FindAll(text, -1)
sAttrs = make([]int, len(t2))
for ix, sN := range t2 {
iN, _ := strconv.Atoi(string(sN))
sAttrs[ix] = iN
}
return
}
var rxNumber = regexp.MustCompile(`\d+`)
*/
func lcaseEnv(k string) string {
return strings.ToLower(strings.TrimSpace(os.Getenv(k)))
}
func GetEnvIdentifiers() map[string]string {
KEYS := []string{"TERM", "TERM_PROGRAM", "LC_TERMINAL"}
V := make(map[string]string)
for _, K := range KEYS {
V[K] = lcaseEnv(K)
}
return V
}
// IsTermKitty checks if the terminal supports the kitty graphics protocol.
// This includes Kitty terminal, Ghostty, and other compatible terminals.
// NOTE: $TERM may be overwritten by tmux
func IsTermKitty() bool {
V := GetEnvIdentifiers()
// Kitty terminal
if V["TERM"] == "xterm-kitty" {
return true
}
// Ghostty terminal - check TERM, TERM_PROGRAM, or ghostty-specific env var
if strings.Contains(V["TERM"], "ghostty") {
return true
}
if strings.Contains(V["TERM_PROGRAM"], "ghostty") {
return true
}
if os.Getenv("GHOSTTY_RESOURCES_DIR") != "" {
return true
}
return false
}
/*
// displayPNGFromFile - not in use
func readPNGIntoBuffer(path string) (err error) {
f, err := os.Open(path)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
reader := bufio.NewReader(f)
return KittyCopyPNGInline(os.Stdout, reader, int64(reader.Size()))
}
*/