Repository navigation
Expand file tree
/
Copy patheditor.go
More file actions
814 lines (717 loc) · 22.1 KB
/
Copy patheditor.go
File metadata and controls
814 lines (717 loc) · 22.1 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
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
tea "github.com/charmbracelet/bubbletea"
)
// hasAnyExt reports whether path (compared case-insensitively) ends with any of
// the provided extensions (e.g. ".png", ".jpg").
func hasAnyExt(path string, exts []string) bool {
lower := strings.ToLower(path)
for _, e := range exts {
if strings.HasSuffix(lower, e) {
return true
}
}
return false
}
// editorAvailable checks if an editor command is available
func editorAvailable(cmd string) bool {
_, err := exec.LookPath(cmd)
return err == nil
}
// getAvailableEditor returns the first available editor
func getAvailableEditor() string {
editors := []string{"micro", "nano", "vim", "vi"}
for _, editor := range editors {
if editorAvailable(editor) {
return editor
}
}
return ""
}
// getTUIClassicsPath returns the path to TUIClassics launcher if found
// Checks multiple common installation locations in order:
// 1. In PATH (globally installed)
// 2. ~/TUIClassics/bin/classics
// 3. ~/projects/TUIClassics/bin/classics
// 4. ~/go/src/github.com/GGPrompts/TUIClassics/bin/classics
func getTUIClassicsPath() string {
// First check if it's in PATH (user may have installed globally)
if path, err := exec.LookPath("classics"); err == nil {
return path
}
// Then check common installation directories
homeDir, err := os.UserHomeDir()
if err != nil {
return ""
}
commonPaths := []string{
filepath.Join(homeDir, "TUIClassics", "bin", "classics"),
filepath.Join(homeDir, "projects", "TUIClassics", "bin", "classics"),
filepath.Join(homeDir, "go", "src", "github.com", "GGPrompts", "TUIClassics", "bin", "classics"),
}
for _, path := range commonPaths {
if _, err := os.Stat(path); err == nil {
return path
}
}
return ""
}
// openEditor opens a file in an external editor
func openEditor(editor, path string) tea.Cmd {
// SECURITY: Validate filename to prevent argument injection
// Filenames starting with '-' could be interpreted as editor flags
cleanPath := filepath.Clean(path)
filename := filepath.Base(cleanPath)
if strings.HasPrefix(filename, "-") {
return func() tea.Msg {
return editorFinishedMsg{
err: fmt.Errorf("invalid filename: cannot open files starting with '-' (potential argument injection)"),
}
}
}
// Use absolute path to avoid ambiguity
absPath, err := filepath.Abs(cleanPath)
if err != nil {
return func() tea.Msg {
return editorFinishedMsg{err: err}
}
}
c := exec.Command(editor, absPath)
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// openTUITool opens a TUI application in the specified directory
func openTUITool(tool, dir string) tea.Cmd {
c := exec.Command(tool)
c.Dir = dir // Set working directory
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// launchTmuxQuad exits TFE and launches tmux with 4 equal panes in the specified directory
// Session name is derived from directory name for easy reattachment
func launchTmuxQuad(dir string) tea.Cmd {
// Derive session name from directory (sanitize for tmux)
sessionName := filepath.Base(dir)
// Replace characters that tmux doesn't like in session names
sessionName = strings.ReplaceAll(sessionName, ".", "_")
sessionName = strings.ReplaceAll(sessionName, ":", "_")
// Shell-quote values before interpolating into the script so paths/names
// containing quotes or other shell metacharacters can't break out
qDir := shellQuote(dir)
qSession := shellQuote(sessionName)
// Create script that launches tmux with quad split after TFE exits
tmuxScript := fmt.Sprintf(`#!/bin/bash
# Wait for TFE to exit and terminal to settle
sleep 0.3
# Reset terminal to sane state
stty sane 2>/dev/null || true
clear
# Change to target directory first so pane 0 inherits it
cd %[1]s
# Check if session already exists
if tmux has-session -t %[2]s 2>/dev/null; then
echo "Attaching to existing tmux session:" %[2]s
sleep 0.5
tmux attach-session -t %[2]s
else
echo "Creating tmux quad session:" %[2]s
echo "Directory:" %[1]s
sleep 0.5
# Create new session with quad layout (2x2 grid)
# Pane layout:
# +-------+-------+
# | 0 | 1 |
# +-------+-------+
# | 2 | 3 |
# +-------+-------+
tmux new-session -d -s %[2]s -c %[1]s \; \
split-window -h -c %[1]s \; \
split-window -v -c %[1]s \; \
select-pane -t 0 \; \
split-window -v -c %[1]s \; \
select-pane -t 0 \; \
attach-session
fi
# Clean up temp script
rm -f "$0"
`, qDir, qSession)
// Write script to temp file
tmpScript := filepath.Join(os.TempDir(), fmt.Sprintf("tfe-tmux-%d.sh", os.Getpid()))
if err := os.WriteFile(tmpScript, []byte(tmuxScript), 0755); err != nil {
// If we can't write the script, just return without doing anything
return nil
}
// Launch script detached - use platform-appropriate method
var cmd *exec.Cmd
if editorAvailable("setsid") {
// Linux: Use setsid to fully detach the process
cmd = exec.Command("setsid", "-f", "bash", tmpScript)
} else {
// macOS/Termux: Use nohup with background execution
// The script runs in background (&) and nohup ensures it survives TFE exit
cmd = exec.Command("bash", "-c", fmt.Sprintf("nohup bash %s &", shellQuote(tmpScript)))
}
cmd.Stdin = nil
cmd.Stdout = nil
cmd.Stderr = nil
if err := cmd.Start(); err != nil {
os.Remove(tmpScript)
return nil
}
// Exit TFE so tmux can take over the terminal
return tea.Quit
}
// copyToClipboard copies text to the system clipboard
func copyToClipboard(text string) error {
var cmd *exec.Cmd
// Try different clipboard commands based on platform
if editorAvailable("termux-clipboard-set") {
// Termux (Android) - use shell wrapper because termux-clipboard-set
// fails with exit status 2 when using StdinPipe directly
cmd = exec.Command("bash", "-c", fmt.Sprintf("termux-clipboard-set <<'CLIPBOARD_EOF'\n%s\nCLIPBOARD_EOF", text))
return cmd.Run()
} else if editorAvailable("wl-copy") {
// Wayland - wl-copy reads from stdin
cmd = exec.Command("wl-copy")
} else if editorAvailable("xclip") {
cmd = exec.Command("xclip", "-selection", "clipboard")
} else if editorAvailable("xsel") {
cmd = exec.Command("xsel", "--clipboard", "--input")
} else if editorAvailable("pbcopy") {
// macOS
cmd = exec.Command("pbcopy")
} else if editorAvailable("clip.exe") {
// Windows/WSL
cmd = exec.Command("clip.exe")
} else {
return fmt.Errorf("no clipboard utility found (install wl-copy, xclip, xsel, or use WSL)")
}
// For non-Termux platforms, use the standard StdinPipe approach
pipe, err := cmd.StdinPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
if _, err := pipe.Write([]byte(text)); err != nil {
return err
}
if err := pipe.Close(); err != nil {
return err
}
return cmd.Wait()
}
// isImageFile checks if a file is an image based on extension (case-insensitive)
func isImageFile(path string) bool {
return hasAnyExt(path, []string{".png", ".jpg", ".jpeg", ".gif", ".bmp", ".svg", ".webp", ".ico", ".tiff", ".tif"})
}
// isHTMLFile checks if a file is an HTML file based on extension (case-insensitive)
func isHTMLFile(path string) bool {
return hasAnyExt(path, []string{".html", ".htm"})
}
// isBrowserFile checks if a file should be opened in a browser
func isBrowserFile(path string) bool {
return isImageFile(path) || isHTMLFile(path) || isPDFFile(path)
}
// isCSVFile checks if a file is a CSV/TSV file based on extension (case-insensitive)
func isCSVFile(path string) bool {
return hasAnyExt(path, []string{".csv", ".tsv"})
}
// isPDFFile checks if a file is a PDF based on extension (case-insensitive)
func isPDFFile(path string) bool {
return hasAnyExt(path, []string{".pdf"})
}
// isVideoFile checks if a file is a video based on extension (case-insensitive)
func isVideoFile(path string) bool {
return hasAnyExt(path, []string{".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".wmv", ".m4v"})
}
// isAudioFile checks if a file is an audio file based on extension (case-insensitive)
func isAudioFile(path string) bool {
return hasAnyExt(path, []string{".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".wma", ".opus", ".ape"})
}
// isDatabaseFile checks if a file is a database file based on extension (case-insensitive)
func isDatabaseFile(path string) bool {
return hasAnyExt(path, []string{".db", ".sqlite", ".sqlite3"})
}
// isArchiveFile checks if a file is an archive based on extension (case-insensitive)
func isArchiveFile(path string) bool {
return hasAnyExt(path, []string{".zip", ".tar", ".gz", ".7z", ".rar", ".bz2", ".xz", ".tar.gz", ".tgz"})
}
// isWSL checks if we're running in Windows Subsystem for Linux
func isWSL() bool {
// Check for WSL-specific indicators
if _, err := os.Stat("/proc/version"); err == nil {
data, err := os.ReadFile("/proc/version")
if err == nil {
version := string(data)
return strings.Contains(strings.ToLower(version), "microsoft") ||
strings.Contains(strings.ToLower(version), "wsl")
}
}
return false
}
// getAvailableBrowser returns the command to open files in the default browser
func getAvailableBrowser() string {
// WSL - try wslview first (from wslu package), then use Windows commands
if editorAvailable("wslview") {
return "wslview"
}
// Windows via WSL
if editorAvailable("cmd.exe") {
return "cmd.exe"
}
// Linux - xdg-open is the standard
if editorAvailable("xdg-open") {
return "xdg-open"
}
// macOS
if editorAvailable("open") {
return "open"
}
return ""
}
// browserOpenedMsg is returned when a file is opened in browser
type browserOpenedMsg struct {
success bool
err error
}
// openInBrowser opens a file in the default browser
func openInBrowser(path string) tea.Cmd {
browser := getAvailableBrowser()
if browser == "" {
return func() tea.Msg {
return browserOpenedMsg{
success: false,
err: fmt.Errorf("no browser command found (install xdg-open, wslview, or open)"),
}
}
}
return func() tea.Msg {
var c *exec.Cmd
browserPath := path
// In WSL, convert Linux paths to Windows paths for better compatibility
if isWSL() && browser != "wslview" {
// Use wslpath to convert WSL path to Windows path
cmd := exec.Command("wslpath", "-w", path)
output, err := cmd.Output()
if err != nil {
// wslpath failed - can't open with Windows browser
return browserOpenedMsg{
success: false,
err: fmt.Errorf("failed to convert path for Windows browser: %w", err),
}
}
browserPath = strings.TrimSpace(string(output))
// Validate it looks like a Windows path (e.g., C:\path or \\wsl.localhost\...)
if len(browserPath) < 3 {
return browserOpenedMsg{
success: false,
err: fmt.Errorf("wslpath produced invalid Windows path: %q", browserPath),
}
}
// Check for drive letter (C:\) or UNC path (\\)
hasDriveLetter := len(browserPath) >= 3 && browserPath[1] == ':' && (browserPath[2] == '\\' || browserPath[2] == '/')
hasUNCPath := len(browserPath) >= 2 && browserPath[0] == '\\' && browserPath[1] == '\\'
if !hasDriveLetter && !hasUNCPath {
return browserOpenedMsg{
success: false,
err: fmt.Errorf("wslpath produced invalid Windows path (expected drive letter or UNC): %q", browserPath),
}
}
}
if browser == "cmd.exe" {
// Windows via WSL - use powershell.exe Start-Process (handles UNC paths)
// cmd.exe /c start doesn't support UNC paths (\\wsl.localhost\...)
c = exec.Command("powershell.exe", "-Command", "Start-Process", "'"+browserPath+"'")
} else {
// Linux/macOS/wslview
c = exec.Command(browser, browserPath)
}
// Start the browser without blocking (browsers run in background)
err := c.Start()
if err != nil {
return browserOpenedMsg{
success: false,
err: err,
}
}
// Success
return browserOpenedMsg{
success: true,
err: nil,
}
}
}
// getAvailableImageViewer returns the first available image viewer
func getAvailableImageViewer() string {
viewers := []string{"viu", "timg", "chafa"}
for _, viewer := range viewers {
if editorAvailable(viewer) {
return viewer
}
}
return ""
}
// viewerPauseScript builds a bash script that runs viewerCmd on the given path
// (shell-quoted to survive apostrophes and other metacharacters in filenames)
// and pauses for a keypress before returning to TFE.
func viewerPauseScript(viewerCmd, path, prompt string) string {
return fmt.Sprintf(`%s %s
echo ""
echo "%s"
read -n 1 -s -r`, viewerCmd, shellQuote(path), prompt)
}
// openImageViewer opens an image in a TUI viewer
func openImageViewer(path string) tea.Cmd {
viewer := getAvailableImageViewer()
if viewer == "" {
return func() tea.Msg {
return editorFinishedMsg{fmt.Errorf("no image viewer found (install viu, timg, or chafa)")}
}
}
var c *exec.Cmd
if viewer == "viu" {
// viu with transparent background and size to terminal
// Wrap in shell to pause after displaying image (same as command prompt)
script := viewerPauseScript("viu -t", path, "Press any key to continue...")
c = exec.Command("bash", "-c", script)
} else if viewer == "timg" {
// timg with grid view support
script := viewerPauseScript("timg", path, "Press any key to continue...")
c = exec.Command("bash", "-c", script)
} else {
// chafa or other
script := viewerPauseScript(viewer, path, "Press any key to continue...")
c = exec.Command("bash", "-c", script)
}
// Set up stdin/stdout/stderr for interaction (same as command execution)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// getAvailableCSVViewer returns the first available CSV/spreadsheet viewer
func getAvailableCSVViewer() string {
viewers := []string{"visidata", "sc-im"}
for _, viewer := range viewers {
if editorAvailable(viewer) {
return viewer
}
}
return ""
}
// openCSVViewer opens a CSV file in a spreadsheet viewer
func openCSVViewer(path string) tea.Cmd {
viewer := getAvailableCSVViewer()
if viewer == "" {
// Fallback to text editor
editor := getAvailableEditor()
if editor == "" {
return func() tea.Msg {
return editorFinishedMsg{fmt.Errorf("no CSV viewer or text editor found")}
}
}
return openEditor(editor, path)
}
c := exec.Command(viewer, path)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// getAvailableVideoPlayer returns the first available video player
func getAvailableVideoPlayer() string {
players := []string{"mpv", "vlc", "mplayer"}
for _, player := range players {
if editorAvailable(player) {
return player
}
}
return ""
}
// openVideoPlayer opens a video file in a media player
func openVideoPlayer(path string) tea.Cmd {
player := getAvailableVideoPlayer()
if player == "" {
return func() tea.Msg {
return editorFinishedMsg{fmt.Errorf("no video player found (install mpv)")}
}
}
// mpv with terminal output
c := exec.Command(player, path)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// getAvailableAudioPlayer returns the first available audio player
func getAvailableAudioPlayer() string {
players := []string{"mpv", "cmus", "moc"}
for _, player := range players {
if editorAvailable(player) {
return player
}
}
return ""
}
// openAudioPlayer opens an audio file in a media player
func openAudioPlayer(path string) tea.Cmd {
player := getAvailableAudioPlayer()
if player == "" {
return func() tea.Msg {
return editorFinishedMsg{fmt.Errorf("no audio player found (install mpv)")}
}
}
// mpv with audio-only mode
c := exec.Command(player, path)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// getAvailableHexViewer returns the first available hex viewer
func getAvailableHexViewer() string {
viewers := []string{"hexyl", "hexpatch", "hexabyte", "xxd"}
for _, viewer := range viewers {
if editorAvailable(viewer) {
return viewer
}
}
return ""
}
// openHexViewer opens a binary file in a hex viewer
func openHexViewer(path string) tea.Cmd {
viewer := getAvailableHexViewer()
if viewer == "" {
return func() tea.Msg {
return editorFinishedMsg{fmt.Errorf("no hex viewer found (install hexyl)")}
}
}
var c *exec.Cmd
if viewer == "hexyl" {
// hexyl displays directly with built-in paging on terminals
// Add a pause wrapper to return to TFE cleanly
script := viewerPauseScript("hexyl", path, "Press any key to return to TFE...")
c = exec.Command("bash", "-c", script)
} else {
// Other hex viewers
c = exec.Command(viewer, path)
}
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// getAvailableDatabaseViewer returns the first available database viewer
func getAvailableDatabaseViewer() string {
viewers := []string{"harlequin", "litecli", "sqlite3"}
for _, viewer := range viewers {
if editorAvailable(viewer) {
return viewer
}
}
return ""
}
// openDatabaseViewer opens a database file in a viewer
func openDatabaseViewer(path string) tea.Cmd {
viewer := getAvailableDatabaseViewer()
if viewer == "" {
return func() tea.Msg {
return editorFinishedMsg{fmt.Errorf("no database viewer found (install harlequin)")}
}
}
c := exec.Command(viewer, path)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// getAvailablePDFViewer returns the first available PDF viewer
func getAvailablePDFViewer() string {
viewers := []string{"timg", "termpdf.py"}
for _, viewer := range viewers {
if editorAvailable(viewer) {
return viewer
}
}
return ""
}
// openPDFViewer opens a PDF file in a terminal viewer
func openPDFViewer(path string) tea.Cmd {
viewer := getAvailablePDFViewer()
if viewer == "" {
// Fallback to browser
return openInBrowser(path)
}
var c *exec.Cmd
if viewer == "timg" {
script := viewerPauseScript("timg", path, "Press any key to continue...")
c = exec.Command("bash", "-c", script)
} else {
c = exec.Command(viewer, path)
}
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// getAvailableImageEditor returns the first available image editor
func getAvailableImageEditor() string {
editors := []string{"textual-paint", "durdraw"}
for _, editor := range editors {
if editorAvailable(editor) {
return editor
}
}
return ""
}
// openImageEditor opens an image in a TUI editor
func openImageEditor(path string) tea.Cmd {
editor := getAvailableImageEditor()
if editor == "" {
return func() tea.Msg {
return editorFinishedMsg{fmt.Errorf("no image editor found (install textual-paint)")}
}
}
c := exec.Command(editor, path)
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// openImageEditorNew launches an image editor with a blank canvas (no file required)
func openImageEditorNew(currentDir string) tea.Cmd {
editor := getAvailableImageEditor()
if editor == "" {
return func() tea.Msg {
return editorFinishedMsg{fmt.Errorf("no image editor found (install textual-paint)")}
}
}
// Launch textual-paint without a file argument - it will start with a blank canvas
// Set the working directory so when user saves, it defaults to current directory
c := exec.Command(editor)
c.Dir = currentDir
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
}),
)
}
// fileExplorerOpenedMsg is returned when a folder is opened in file explorer
type fileExplorerOpenedMsg struct {
success bool
err error
}
// openInFileExplorer opens the current directory in the system file explorer
func openInFileExplorer(path string) tea.Cmd {
return func() tea.Msg {
var c *exec.Cmd
if isWSL() {
// WSL: Use explorer.exe to open Windows Explorer
// Convert Linux path to Windows path for better compatibility
cmd := exec.Command("wslpath", "-w", path)
output, err := cmd.Output()
if err != nil {
// wslpath failed - can't open with Windows Explorer
return fileExplorerOpenedMsg{
success: false,
err: fmt.Errorf("failed to convert path for Windows Explorer: %w", err),
}
}
winPath := strings.TrimSpace(string(output))
// Validate it looks like a Windows path (e.g., C:\path or \\wsl.localhost\...)
if len(winPath) < 3 {
return fileExplorerOpenedMsg{
success: false,
err: fmt.Errorf("wslpath produced invalid Windows path: %q", winPath),
}
}
// Check for drive letter (C:\) or UNC path (\\)
hasDriveLetter := len(winPath) >= 3 && winPath[1] == ':' && (winPath[2] == '\\' || winPath[2] == '/')
hasUNCPath := len(winPath) >= 2 && winPath[0] == '\\' && winPath[1] == '\\'
if !hasDriveLetter && !hasUNCPath {
return fileExplorerOpenedMsg{
success: false,
err: fmt.Errorf("wslpath produced invalid Windows path (expected drive letter or UNC): %q", winPath),
}
}
c = exec.Command("explorer.exe", winPath)
} else if editorAvailable("xdg-open") {
// Linux: Use xdg-open to open default file manager
c = exec.Command("xdg-open", path)
} else if editorAvailable("open") {
// macOS: Use open to open Finder
c = exec.Command("open", path)
} else {
return fileExplorerOpenedMsg{
success: false,
err: fmt.Errorf("no file explorer command found"),
}
}
// Start the file explorer without blocking
err := c.Start()
if err != nil {
return fileExplorerOpenedMsg{
success: false,
err: err,
}
}
// Success
return fileExplorerOpenedMsg{
success: true,
err: nil,
}
}
}