-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
645 lines (576 loc) · 15.4 KB
/
Copy pathhandlers.go
File metadata and controls
645 lines (576 loc) · 15.4 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
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"unicode/utf8"
"github.com/charmbracelet/bubbles/key"
tea "github.com/charmbracelet/bubbletea"
)
func (a *App) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
// Use filtered files count for cursor bounds
fileCount := len(a.filteredFiles())
// Handle gg (double-key: press g twice to go to top)
if msg.String() == "g" {
if a.pendingG {
a.pendingG = false
a.cursor = 0
a.message = ""
a.previewScroll = 0
a.showDiff = false
if a.showPreview {
return a, a.triggerPreview()
}
return a, nil
}
a.pendingG = true
return a, nil
}
a.pendingG = false // any other key cancels pending g
switch {
case key.Matches(msg, a.keys.Quit):
// Save config before quitting
a.config.ShowHidden = a.showHidden
a.config.PreviewEnabled = a.showPreview
if err := SaveConfig(a.config); err != nil {
// Can't show error since we're quitting, but don't silently ignore
fmt.Fprintf(os.Stderr, "Warning: failed to save config: %v\n", err)
}
return a, tea.Quit
case key.Matches(msg, a.keys.Help):
a.showHelp = true
return a, nil
case key.Matches(msg, a.keys.Up):
if a.cursor > 0 {
a.cursor--
a.previewScroll = 0
a.showDiff = false
}
case key.Matches(msg, a.keys.Down):
if a.cursor < fileCount-1 {
a.cursor++
a.previewScroll = 0
a.showDiff = false
}
case key.Matches(msg, a.keys.Bottom):
a.cursor = max(0, fileCount-1)
a.previewScroll = 0
a.showDiff = false
// Preview scrolling with K/J (uppercase)
case msg.String() == "K" && a.showPreview:
a.previewScroll = max(0, a.previewScroll-5)
case msg.String() == "J" && a.showPreview:
maxScroll := max(0, a.previewLines-(a.height-4))
a.previewScroll = min(maxScroll, a.previewScroll+5)
case key.Matches(msg, a.keys.PageUp):
a.cursor = max(0, a.cursor-10)
case key.Matches(msg, a.keys.PageDown):
a.cursor = min(fileCount-1, a.cursor+10)
case key.Matches(msg, a.keys.Left):
return a.goUp()
case key.Matches(msg, a.keys.Right):
return a.goDown()
case key.Matches(msg, a.keys.Select):
if fileCount > 0 {
if a.selected[a.cursor] {
delete(a.selected, a.cursor)
} else {
a.selected[a.cursor] = true
}
// Move cursor down
if a.cursor < fileCount-1 {
a.cursor++
}
}
case key.Matches(msg, a.keys.SelectAll):
files := a.filteredFiles()
if len(a.selected) == len(files) {
// Deselect all
a.selected = make(map[int]bool)
} else {
// Select all
for i := range files {
a.selected[i] = true
}
}
case key.Matches(msg, a.keys.TogglePreview):
a.showPreview = !a.showPreview
case key.Matches(msg, a.keys.ToggleHidden):
a.showHidden = !a.showHidden
a.config.ShowHidden = a.showHidden
return a, a.loadDir()
case key.Matches(msg, a.keys.Copy):
return a.copyFiles(false)
case key.Matches(msg, a.keys.Cut):
return a.copyFiles(true)
case key.Matches(msg, a.keys.Paste):
return a.pasteFiles()
case key.Matches(msg, a.keys.Delete):
return a.deleteFiles()
case key.Matches(msg, a.keys.Rename):
return a.startRename()
case key.Matches(msg, a.keys.Stage):
return a.gitStage()
case key.Matches(msg, a.keys.Unstage):
return a.gitUnstage()
case key.Matches(msg, a.keys.Diff):
return a.gitDiff()
case key.Matches(msg, a.keys.Filter):
a.filterMode = true
a.filterQuery = ""
a.cursor = 0
return a, nil
case key.Matches(msg, a.keys.Shell):
return a.openShell()
case key.Matches(msg, a.keys.SortMode):
return a.cycleSortMode()
case key.Matches(msg, a.keys.CreateFile):
return a.startCreateFile()
case key.Matches(msg, a.keys.CreateDir):
return a.startCreateDir()
case key.Matches(msg, a.keys.BookmarkAdd):
return a.addBookmark()
case key.Matches(msg, a.keys.BookmarkShow):
return a.showBookmarks()
case key.Matches(msg, a.keys.BookmarkRemove):
return a.removeBookmark()
case key.Matches(msg, a.keys.CommandPalette):
return a.showCommandPalette()
case key.Matches(msg, a.keys.Refresh):
return a, tea.Batch(a.loadDir(), a.loadGitStatus())
case key.Matches(msg, a.keys.Undo):
return a.undoLastOperation()
}
// Trigger async preview if preview is shown and not diff mode
if a.showPreview && !a.showDiff {
return a, a.triggerPreview()
}
return a, nil
}
func (a *App) handleConfirmKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "y", "Y":
action := a.confirmAction
a.confirmAction = ""
a.confirmTarget = ""
switch action {
case "delete":
files := a.getSelectedFiles()
return a, func() tea.Msg {
if err := ensureUndoDir(); err != nil {
return DeleteResultMsg{err: err}
}
var lastErr error
var backups, origPaths []string
deleted := 0
for _, f := range files {
// Stat before moving to detect directories
info, _ := os.Stat(f)
// Generate unique backup name
backupName := fmt.Sprintf("%d_%s", time.Now().UnixNano(), filepath.Base(f))
backupPath := filepath.Join(undoDir(), backupName)
// Move to undo directory with cross-device fallback
if err := moveFile(f, backupPath); err != nil {
lastErr = err
continue
}
backups = append(backups, backupPath)
origPaths = append(origPaths, f)
_ = info // available if needed for future logic
deleted++
}
var ops []Operation
if len(backups) > 0 {
ops = append(ops, Operation{
Type: "delete",
Backups: backups,
Paths: origPaths,
})
}
if lastErr != nil {
return DeleteResultMsg{count: deleted, err: lastErr, operations: ops}
}
return DeleteResultMsg{count: deleted, operations: ops}
}
case "paste-overwrite":
return a.doPaste()
case "create-overwrite":
name := a.confirmTarget
path := filepath.Join(a.cwd, name)
return a, func() tea.Msg {
f, err := os.Create(path)
if err != nil {
return CreateResultMsg{err: err}
}
f.Close()
return CreateResultMsg{name: name}
}
case "rename-overwrite":
oldPath := a.pendingRenameOld
newName := a.pendingRenameNew
newPath := filepath.Join(a.cwd, newName)
a.pendingRenameOld = ""
a.pendingRenameNew = ""
return a, func() tea.Msg {
if err := os.Rename(oldPath, newPath); err != nil {
return RenameResultMsg{err: err}
}
op := &Operation{
Type: "rename",
Path: newPath,
OldPath: oldPath,
}
return RenameResultMsg{newName: newName, op: op}
}
default:
return a, nil
}
case "n", "N", "esc":
a.message = "Cancelled"
a.messageIsError = false
a.confirmAction = ""
a.confirmTarget = ""
a.pendingRenameOld = ""
a.pendingRenameNew = ""
return a, nil
}
return a, nil
}
func (a *App) handlePromptKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "enter":
a.promptActive = false
// Handle the prompt result based on label
switch a.promptLabel {
case "Rename to:":
if a.promptValue != "" {
return a.doRename(a.promptValue)
}
case "New file:":
if a.promptValue != "" {
return a.doCreateFile(a.promptValue)
}
case "New directory:":
if a.promptValue != "" {
return a.doCreateDir(a.promptValue)
}
}
return a, nil
case "esc":
a.promptActive = false
a.promptValue = ""
a.promptCursor = 0
return a, nil
case "backspace":
// Unicode-safe backspace: remove rune before cursor
runes := []rune(a.promptValue)
if len(runes) > 0 && a.promptCursor > 0 {
a.promptValue = string(runes[:a.promptCursor-1]) + string(runes[a.promptCursor:])
a.promptCursor--
}
case "left":
if a.promptCursor > 0 {
a.promptCursor--
}
case "right":
runes := []rune(a.promptValue)
if a.promptCursor < len(runes) {
a.promptCursor++
}
case "home":
a.promptCursor = 0
case "end":
a.promptCursor = utf8.RuneCountInString(a.promptValue)
case "ctrl+u":
// Delete from cursor to beginning
runes := []rune(a.promptValue)
if a.promptCursor > 0 {
a.promptValue = string(runes[a.promptCursor:])
a.promptCursor = 0
}
case "ctrl+k":
// Delete from cursor to end
runes := []rune(a.promptValue)
if a.promptCursor < len(runes) {
a.promptValue = string(runes[:a.promptCursor])
}
default:
s := msg.String()
if utf8.RuneCountInString(s) == 1 {
// Insert character at cursor position
runes := []rune(a.promptValue)
a.promptValue = string(runes[:a.promptCursor]) + s + string(runes[a.promptCursor:])
a.promptCursor++
}
}
return a, nil
}
func (a *App) handleFilterKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "esc":
a.filterMode = false
a.filterQuery = ""
a.cursor = 0
a.selected = make(map[int]bool)
return a, nil
case "ctrl+c":
// Cancel filter and restore full list (not quit)
a.filterMode = false
a.filterQuery = ""
a.cursor = 0
a.selected = make(map[int]bool)
return a, nil
case "backspace":
// Unicode-safe backspace: remove last rune, not last byte
runes := []rune(a.filterQuery)
if len(runes) > 0 {
a.filterQuery = string(runes[:len(runes)-1])
a.cursor = 0
a.selected = make(map[int]bool)
}
if a.filterQuery == "" {
a.filterMode = false
}
return a, nil
case "enter":
// Exit filter mode but keep the filtered results
a.filterMode = false
return a, nil
default:
s := msg.String()
if utf8.RuneCountInString(s) == 1 && s >= " " {
a.filterQuery += s
a.cursor = 0
a.selected = make(map[int]bool)
}
return a, nil
}
}
func (a *App) goUp() (tea.Model, tea.Cmd) {
parent := filepath.Dir(a.cwd)
if parent == a.cwd {
return a, nil
}
a.cwd = parent
// Reuse GitService if still in the same repo
a.gitSvc = a.reuseOrNewGitService()
a.resetPreview()
return a, tea.Batch(a.loadDir(), a.loadGitStatus())
}
// resetPreview clears filter and preview state when navigating to a new directory.
func (a *App) resetPreview() {
a.filterQuery = ""
a.filterMode = false
a.previewScroll = 0
a.showDiff = false
a.previewReady = false
a.previewLoading = false
a.previewPath = ""
a.previewContent = ""
}
func (a *App) goDown() (tea.Model, tea.Cmd) {
item, ok := a.currentFile()
if !ok {
return a, nil
}
if !item.IsDir {
// Open file in editor or system default
return a, a.openFile(item.Path)
}
a.cwd = item.Path
// Reuse GitService if still in the same repo
a.gitSvc = a.reuseOrNewGitService()
a.resetPreview()
return a, tea.Batch(a.loadDir(), a.loadGitStatus())
}
// openFile launches the file in $EDITOR or the system default application.
func (a *App) openFile(path string) tea.Cmd {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
// Use rundll32 for robust path handling (handles &, %, spaces)
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", path)
} else {
// Use $EDITOR, fallback to $VISUAL, then xdg-open
editor := os.Getenv("EDITOR")
if editor == "" {
editor = os.Getenv("VISUAL")
}
if editor == "" {
if runtime.GOOS == "darwin" {
editor = "open"
} else {
editor = "xdg-open"
}
}
cmd = exec.Command(editor, path)
}
return tea.ExecProcess(cmd, func(err error) tea.Msg {
return OpenFileResultMsg{path: path, err: err}
})
}
// cycleSortMode cycles through sort modes: name -> size -> time -> type -> name.
func (a *App) cycleSortMode() (tea.Model, tea.Cmd) {
switch a.sortMode {
case SortByName:
a.sortMode = SortBySize
case SortBySize:
a.sortMode = SortByModified
case SortByModified:
a.sortMode = SortByType
case SortByType:
a.sortMode = SortByName
}
a.config.SortBy = a.sortMode.String()
return a, a.loadDir()
}
// triggerPreview starts async preview generation for the current file.
func (a *App) triggerPreview() tea.Cmd {
item, ok := a.currentFile()
if !ok {
a.previewContent = ""
a.previewPath = ""
a.previewReady = true
a.previewLoading = false
return nil
}
// For directories, show directory listing
if item.IsDir {
if a.previewPath == item.Path && a.previewReady {
return nil
}
a.previewPath = item.Path
a.previewReady = false
a.previewLoading = true
a.previewContent = ""
showHidden := a.config.ShowHidden
return func() tea.Msg {
entries, err := os.ReadDir(item.Path)
if err != nil {
return PreviewResultMsg{path: item.Path, content: fmt.Sprintf("[Error: %v]", err)}
}
// Filter hidden files if not showing them
if !showHidden {
filtered := make([]os.DirEntry, 0, len(entries))
for _, e := range entries {
if !strings.HasPrefix(e.Name(), ".") {
filtered = append(filtered, e)
}
}
entries = filtered
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Directory: %s\n", item.Name))
sb.WriteString(fmt.Sprintf("Items: %d\n\n", len(entries)))
for _, e := range entries {
if e.IsDir() {
sb.WriteString(fmt.Sprintf(" 📁 %s/\n", e.Name()))
} else {
sb.WriteString(fmt.Sprintf(" 📄 %s\n", e.Name()))
}
}
return PreviewResultMsg{path: item.Path, content: sb.String()}
}
}
// Skip if already showing preview for this file
if a.previewPath == item.Path && a.previewReady {
return nil
}
a.previewPath = item.Path
a.previewReady = false
a.previewLoading = true
a.previewContent = ""
// Width must match renderPreview: (a.width - sidebarWidth - 1) - 2 for border
previewWidth := a.width - a.width/3 - 3
if previewWidth < 10 {
previewWidth = 10
}
return a.previewSvc.GenerateAsync(item.Path, previewWidth)
}
// reuseOrNewGitService reuses the existing GitService if the current directory
// is still within the same git repository. This avoids redundant git rev-parse calls.
func (a *App) reuseOrNewGitService() *GitService {
if a.gitSvc != nil && a.gitSvc.IsRepo() {
root := a.gitSvc.Root()
// Check if a.cwd is under the same repo root
rel, err := filepath.Rel(root, a.cwd)
if err == nil && !strings.HasPrefix(rel, "..") {
// Same repo, create new service but it will reuse the cached root
svc := NewGitService(a.cwd)
svc.root = root
svc.rootSet = true
return svc
}
}
return NewGitService(a.cwd)
}
// handleMouse handles mouse events.
func (a *App) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
// Only handle mouse events in the main view (not in confirm/prompt/help)
if a.confirmAction != "" || a.promptActive || a.showHelp || a.filterMode {
return a, nil
}
files := a.filteredFiles()
if len(files) == 0 {
return a, nil
}
// Calculate sidebar dimensions
sidebarWidth := a.width
if a.showPreview {
sidebarWidth = a.width / 3
}
switch msg.Type {
case tea.MouseLeft:
// Click in sidebar to select file
if msg.X < sidebarWidth {
// Calculate which file was clicked
// Header takes 1 line, border takes 1 line, so content starts at Y=2
clickedRow := msg.Y - 2
if clickedRow >= 0 {
// Calculate the offset for scrolling
visibleHeight := a.height - 4
if visibleHeight < 1 {
visibleHeight = 1
}
offset := 0
if a.cursor >= visibleHeight {
offset = a.cursor - visibleHeight + 1
}
newCursor := offset + clickedRow
if newCursor >= 0 && newCursor < len(files) {
a.cursor = newCursor
a.previewScroll = 0
a.showDiff = false
// Trigger preview for the selected file
if a.showPreview {
return a, a.triggerPreview()
}
}
}
}
case tea.MouseWheelUp:
// Scroll up
if a.cursor > 0 {
a.cursor--
a.previewScroll = 0
a.showDiff = false
if a.showPreview {
return a, a.triggerPreview()
}
}
case tea.MouseWheelDown:
// Scroll down
if a.cursor < len(files)-1 {
a.cursor++
a.previewScroll = 0
a.showDiff = false
if a.showPreview {
return a, a.triggerPreview()
}
}
}
return a, nil
}