// License: GPLv3 Copyright: 2026, FWS package file_manager import ( "errors" "fmt" "os" "os/exec" "path/filepath" "sort" "strings" "time" "github.com/kovidgoyal/kitty/tools/cli" "github.com/kovidgoyal/kitty/tools/config" "github.com/kovidgoyal/kitty/tools/fzf" "github.com/kovidgoyal/kitty/tools/tui" "github.com/kovidgoyal/kitty/tools/tui/loop" "github.com/kovidgoyal/kitty/tools/wcswidth" ) var _ = fmt.Print // Entry is a single item of the listing. ModTime is kept as a unix timestamp // so that sorting by date does not require stat()ing every entry again. type Entry struct { Name string IsDir bool ModTime int64 Size int64 } type input_purpose int const ( input_none input_purpose = iota input_create_file input_create_dir input_rename input_search ) // Pure helpers, kept free of terminal state so that they can be unit tested // without a tty. func is_hidden_name(name string) bool { return strings.HasPrefix(name, ".") } func sort_entries(entries []Entry, sort_by string) { sort.SliceStable(entries, func(i, j int) bool { a, b := entries[i], entries[j] if a.IsDir != b.IsDir { return a.IsDir } switch sort_by { case "mtime": if a.ModTime != b.ModTime { return a.ModTime > b.ModTime } case "size": if a.Size != b.Size { return a.Size > b.Size } } return strings.ToLower(a.Name) < strings.ToLower(b.Name) }) } func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) { items, err := os.ReadDir(dir) if err != nil { return nil, err } entries := make([]Entry, 0, len(items)) for _, item := range items { name := item.Name() if !show_hidden && is_hidden_name(name) { continue } e := Entry{Name: name, IsDir: item.IsDir()} if info, ierr := item.Info(); ierr == nil { e.ModTime = info.ModTime().Unix() e.Size = info.Size() } entries = append(entries, e) } sort_entries(entries, sort_by) return entries, nil } func entry_path(dir, name string) string { return filepath.Join(dir, name) } func parent_of(dir string) string { return filepath.Dir(dir) } func validate_entry_name(name string) error { if name == "" || name == "." || name == ".." { return fmt.Errorf("A file name is required") } if strings.ContainsRune(name, '/') || strings.ContainsRune(name, 0) || strings.ContainsRune(name, os.PathSeparator) { return fmt.Errorf("%#v is not a valid file name as it contains a path separator", name) } return nil } func create_file(dir, name string) (string, error) { if err := validate_entry_name(name); err != nil { return "", err } path := entry_path(dir, name) f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) if err != nil { return "", err } if err = f.Close(); err != nil { return "", err } return path, nil } func create_subdir(dir, name string) (string, error) { if err := validate_entry_name(name); err != nil { return "", err } path := entry_path(dir, name) if err := os.Mkdir(path, 0o755); err != nil { return "", err } return path, nil } func rename_entry(dir, old_name, new_name string) (string, error) { if err := validate_entry_name(new_name); err != nil { return "", err } if old_name == new_name { return entry_path(dir, old_name), nil } dest := entry_path(dir, new_name) if _, err := os.Lstat(dest); err == nil { return "", fmt.Errorf("%#v already exists", new_name) } if err := os.Rename(entry_path(dir, old_name), dest); err != nil { return "", err } return dest, nil } // delete_entry removes a file, a symlink or an empty directory. Recursive // deletion is deliberately not done here so that a misplaced keypress cannot // wipe out a tree of files. func delete_entry(dir, name string) error { if name == "" || name == "." || name == ".." { return fmt.Errorf("Cannot delete %#v", name) } return os.Remove(entry_path(dir, name)) } func resolve_start_dir(candidate string) (string, error) { if candidate == "" { cwd, err := os.Getwd() if err != nil { return "", err } candidate = cwd } abs, err := filepath.Abs(candidate) if err != nil { return "", err } info, err := os.Stat(abs) if err != nil { return "", err } if !info.IsDir() { abs = filepath.Dir(abs) } return abs, nil } func truncate_to_width(s string, max_width int) string { if max_width <= 0 { return "" } if wcswidth.Stringwidth(s) <= max_width { return s } runes := []rune(s) for len(runes) > 0 && wcswidth.Stringwidth(string(runes))+1 > max_width { runes = runes[:len(runes)-1] } return string(runes) + "\u2026" } type Handler struct { lp *loop.Loop screen_size loop.ScreenSize conf *Config cwd string all_entries []Entry entries []Entry selected int scroll int show_hidden bool search_query string input_purpose input_purpose text_buffer string rename_source string confirm_name string palette_open bool palette_query string palette []action_info palette_selected int message string result_action string result_path string shortcut_tracker config.ShortcutTracker keyboard_shortcuts []*config.KeyAction } func (h *Handler) initialize() (string, error) { sz, err := h.lp.ScreenSize() if err != nil { return "", err } h.screen_size = sz h.lp.SetCursorVisible(false) h.lp.AllowLineWrapping(false) h.lp.SetWindowTitle("File manager") if err = h.load(h.cwd); err != nil { return "", err } h.draw_screen() h.lp.SendOverlayReady() return "", nil } // load reads dir and adopts it as the current directory. Selection is clamped // rather than reset so that reloading a directory after an action keeps the // cursor near where it was. func (h *Handler) load(dir string) error { entries, err := read_dir(dir, h.show_hidden, h.conf.Sort_by) if err != nil { return err } h.cwd = dir h.all_entries = entries h.entries = entries if h.search_query != "" { if err = h.apply_search(); err != nil { return err } } if h.selected >= len(h.entries) { h.selected = max(0, len(h.entries)-1) } if h.scroll > h.selected { h.scroll = h.selected } return nil } func (h *Handler) select_name(name string) { if name == "" { return } for i, e := range h.entries { if e.Name == name { h.selected = i return } } } func (h *Handler) selected_entry() (Entry, bool) { if h.selected < 0 || h.selected >= len(h.entries) { return Entry{}, false } return h.entries[h.selected], true } func (h *Handler) reload() { name := "" if e, ok := h.selected_entry(); ok { name = e.Name } if err := h.load(h.cwd); err != nil { h.message = err.Error() h.draw_screen() return } h.select_name(name) h.message = "" h.draw_screen() } func (h *Handler) change_dir(dir string) { // A filter belongs to the directory it was typed in, not to the next one. h.search_query, h.text_buffer, h.input_purpose = "", "", input_none if err := h.load(dir); err != nil { h.message = err.Error() h.draw_screen() return } h.selected, h.scroll, h.message = 0, 0, "" h.draw_screen() } func (h *Handler) move_selection(delta int) { if len(h.entries) == 0 { return } h.selected += delta h.selected = max(0, h.selected) h.selected = min(h.selected, len(h.entries)-1) h.draw_screen() } func (h *Handler) cancel_input() { h.input_purpose = input_none h.text_buffer = "" h.rename_source = "" h.message = "" h.draw_screen() } func (h *Handler) start_input(purpose input_purpose) { h.input_purpose = purpose h.text_buffer = "" h.message = "" h.draw_screen() } func (h *Handler) start_rename() { e, ok := h.selected_entry() if !ok { h.lp.Beep() return } h.input_purpose = input_rename h.rename_source = e.Name h.text_buffer = e.Name h.message = "" h.draw_screen() } // commit_input applies the pending create/rename operation. The name is // trimmed because a trailing space is almost never intended in a file name. func (h *Handler) commit_input() { name := strings.TrimSpace(h.text_buffer) purpose := h.input_purpose source := h.rename_source h.input_purpose = input_none h.text_buffer = "" h.rename_source = "" var err error var created string switch purpose { case input_create_file: created, err = create_file(h.cwd, name) case input_create_dir: created, err = create_subdir(h.cwd, name) case input_rename: created, err = rename_entry(h.cwd, source, name) } if err != nil { h.message = err.Error() h.draw_screen() return } if err = h.load(h.cwd); err != nil { h.message = err.Error() h.draw_screen() return } h.select_name(filepath.Base(created)) h.message = "" h.draw_screen() } func (h *Handler) start_delete() { e, ok := h.selected_entry() if !ok { h.lp.Beep() return } h.confirm_name = e.Name h.message = "" h.draw_screen() } func (h *Handler) perform_delete() { name := h.confirm_name h.confirm_name = "" if err := delete_entry(h.cwd, name); err != nil { h.message = err.Error() h.draw_screen() return } if err := h.load(h.cwd); err != nil { h.message = err.Error() } h.select_name(name) h.message = fmt.Sprintf("Deleted %s", name) h.draw_screen() } func (h *Handler) copy_selected_path() { path := h.cwd if e, ok := h.selected_entry(); ok { path = entry_path(h.cwd, e.Name) } h.lp.CopyTextToClipboard(path) h.message = fmt.Sprintf("Copied %s", path) h.draw_screen() } // activate implements the primary action: the selected directory is opened in // the panel, the selected file is opened in the editor. Enter used to quit the // panel and cd the shell, which did nothing when the panel was docked. func (h *Handler) activate() { if h.input_purpose == input_search { h.stop_search() } e, ok := h.selected_entry() if !ok { h.lp.Beep() return } if e.IsDir { h.enter_dir() return } h.open_file(entry_path(h.cwd, e.Name)) } // edit_args_in is the client side of kitty's edit protocol. The terminal opens // the editor in a new tab or OS window, which gives the file a whole window even // when the panel is docked. The window closes when the editor exits and the // panel is redrawn in place, instead of handing the command to the shell and // disappearing. func edit_args_in(path, window_type string) []string { return []string{"edit-in-kitty", "--type=" + window_type, path} } func edit_args(path string) []string { return edit_args_in(path, "tab") } func (h *Handler) open_file(path string) { h.open_file_in(path, "tab") } func (h *Handler) open_file_in(path, window_type string) { exe, err := os.Executable() if err != nil { h.message = err.Error() h.draw_screen() return } // The loop must give up the tty while edit-in-kitty talks to the terminal, // otherwise both processes compete for input and escape code responses. err = h.lp.SuspendAndRun(func() error { cmd := exec.Command(exe, edit_args_in(path, window_type)...) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr return cmd.Run() }) var ee *exec.ExitError if err != nil && !errors.As(err, &ee) { h.message = err.Error() } // The editor may have changed or removed the file, so refresh the listing. if lerr := h.load(h.cwd); lerr != nil { h.message = lerr.Error() } else { h.select_name(filepath.Base(path)) } h.draw_screen() } // enter_dir browses into the selected directory inside the panel, leaving the // working directory of the shell untouched. func (h *Handler) enter_dir() { e, ok := h.selected_entry() if !ok || !e.IsDir { h.lp.Beep() return } h.change_dir(entry_path(h.cwd, e.Name)) } func (h *Handler) change_shell_dir_to(path string) { h.result_action, h.result_path = "cd", path h.lp.Quit(0) } // change_shell_dir ends the kitten with a request to change the directory of // the shell that hosted it, to the selected directory, or to the one being // browsed when a file is selected. func (h *Handler) change_shell_dir() { path := h.cwd if e, ok := h.selected_entry(); ok && e.IsDir { path = entry_path(h.cwd, e.Name) } h.change_shell_dir_to(path) } type action_info struct { Name string Description string } // action_catalog is the single source of truth shared by the in-panel palette // and the documentation: every action accepted by perform_action has exactly // one description here, and test_action_catalog enforces that. var action_catalog = []action_info{ {"quit", "Close the panel without changing the shell directory"}, {"move_up", "Select the previous entry"}, {"move_down", "Select the next entry"}, {"page_up", "Move the selection up by one page"}, {"page_down", "Move the selection down by one page"}, {"home", "Select the first entry"}, {"end", "Select the last entry"}, {"activate", "Change the shell directory or open the selected file"}, {"enter_dir", "Browse into the selected directory"}, {"parent_dir", "Browse into the parent directory"}, {"cd_here", "Move the shell to the directory shown in the panel"}, {"toggle_hidden", "Show or hide entries whose name starts with a dot"}, {"create_file", "Create a file in the current directory"}, {"create_dir", "Create a directory in the current directory"}, {"rename", "Rename the selected entry"}, {"delete", "Delete the selected entry after confirmation"}, {"copy_path", "Copy the path of the selection to the clipboard"}, {"refresh", "Reload the current directory"}, {"search", "Filter the listing with a fuzzy query"}, {"palette", "List and run the actions of the panel"}, {"open_tab", "Open the selected file in a new tab"}, {"open_window", "Open the selected file in a new OS window"}, } // Actions that need the panel state are plain functions of the handler, so the // palette and the configurable shortcuts go through the same code path. var action_handlers = map[string]func(*Handler){ "quit": func(h *Handler) { h.lp.Quit(0) }, "move_up": func(h *Handler) { h.move_selection(-1) }, "move_down": func(h *Handler) { h.move_selection(1) }, "page_up": func(h *Handler) { h.move_selection(-max(1, int(h.screen_size.HeightCells)-3)) }, "page_down": func(h *Handler) { h.move_selection(max(1, int(h.screen_size.HeightCells)-3)) }, "home": func(h *Handler) { h.selected = 0 h.draw_screen() }, "end": func(h *Handler) { if len(h.entries) > 0 { h.selected = len(h.entries) - 1 } h.draw_screen() }, "parent_dir": func(h *Handler) { h.change_dir(parent_of(h.cwd)) }, "activate": func(h *Handler) { h.activate() }, "enter_dir": func(h *Handler) { h.enter_dir() }, "cd_here": func(h *Handler) { h.change_shell_dir() }, "toggle_hidden": func(h *Handler) { h.show_hidden = !h.show_hidden; h.reload() }, "create_file": func(h *Handler) { h.start_input(input_create_file) }, "create_dir": func(h *Handler) { h.start_input(input_create_dir) }, "rename": func(h *Handler) { h.start_rename() }, "delete": func(h *Handler) { h.start_delete() }, "copy_path": func(h *Handler) { h.copy_selected_path() }, "refresh": func(h *Handler) { h.reload() }, "search": func(h *Handler) { h.start_search() }, "palette": func(h *Handler) { h.open_palette() }, "open_tab": func(h *Handler) { h.open_selected("tab") }, "open_window": func(h *Handler) { h.open_selected("window") }, } func (h *Handler) perform_action(name string) { if fn, ok := action_handlers[name]; ok { fn(h) } } // filter_entries keeps the entries matching query, using the same fuzzy matcher // as the command palette so that scoring stays consistent across kittens. An // empty query keeps the listing untouched. func filter_entries(entries []Entry, query string) ([]Entry, error) { if query == "" { return entries, nil } names := make([]string, len(entries)) for i, e := range entries { names[i] = e.Name if e.IsDir { // Matching the trailing slash lets a query such as "src/" only // select directories. names[i] += "/" } } m := fzf.NewFuzzyMatcher(fzf.PATH_SCHEME) results, err := m.Score(names, query) if err != nil { return nil, err } type scored_entry struct { entry Entry score uint } matches := make([]scored_entry, 0, len(entries)) for i, r := range results { if r.Score > 0 { matches = append(matches, scored_entry{entries[i], r.Score}) } } sort.SliceStable(matches, func(i, j int) bool { if matches[i].score != matches[j].score { return matches[i].score > matches[j].score } return strings.ToLower(matches[i].entry.Name) < strings.ToLower(matches[j].entry.Name) }) ans := make([]Entry, len(matches)) for i, m := range matches { ans[i] = m.entry } return ans, nil } // filter_actions keeps the actions whose name or description matches query, most // relevant first. An empty query lists the whole catalog. func filter_actions(query string) ([]action_info, error) { if query == "" { return action_catalog, nil } texts := make([]string, len(action_catalog)) for i, a := range action_catalog { texts[i] = a.Name + " " + a.Description } m := fzf.NewFuzzyMatcher(fzf.DEFAULT_SCHEME) results, err := m.Score(texts, query) if err != nil { return nil, err } type scored_action struct { action action_info score uint } matches := make([]scored_action, 0, len(action_catalog)) for i, r := range results { if r.Score > 0 { matches = append(matches, scored_action{action_catalog[i], r.Score}) } } sort.SliceStable(matches, func(i, j int) bool { if matches[i].score != matches[j].score { return matches[i].score > matches[j].score } return matches[i].action.Name < matches[j].action.Name }) ans := make([]action_info, len(matches)) for i, m := range matches { ans[i] = m.action } return ans, nil } func (h *Handler) start_search() { h.input_purpose = input_search h.text_buffer, h.search_query = "", "" h.entries = h.all_entries h.selected, h.scroll, h.message = 0, 0, "" h.draw_screen() } // apply_search filters the listing without redrawing, so that it can also be // used from load() while the panel is being rebuilt. func (h *Handler) apply_search() error { entries, err := filter_entries(h.all_entries, h.search_query) if err != nil { return err } h.entries = entries h.selected = max(0, min(h.selected, len(h.entries)-1)) h.scroll = 0 return nil } // stop_search clears the filter and restores the full listing, keeping the // selection on the entry the user was looking at when it still exists. func (h *Handler) stop_search() { name := "" if e, ok := h.selected_entry(); ok { name = e.Name } h.input_purpose, h.text_buffer, h.search_query = input_none, "", "" h.entries = h.all_entries h.selected, h.scroll = 0, 0 h.select_name(name) if h.selected >= len(h.entries) { h.selected = max(0, len(h.entries)-1) } } func (h *Handler) handle_search_key(ev *loop.KeyEvent) error { switch { case ev.MatchesPressOrRepeat("escape"): ev.Handled = true h.stop_search() h.draw_screen() case ev.MatchesPressOrRepeat("enter"): ev.Handled = true h.activate() case ev.MatchesPressOrRepeat("up"): ev.Handled = true h.move_selection(-1) case ev.MatchesPressOrRepeat("down"): ev.Handled = true h.move_selection(1) case ev.MatchesPressOrRepeat("backspace"): ev.Handled = true if h.text_buffer != "" { g := wcswidth.SplitIntoGraphemes(h.text_buffer) h.text_buffer = strings.Join(g[:len(g)-1], "") } h.search_query = h.text_buffer if err := h.apply_search(); err != nil { h.message = err.Error() } h.draw_screen() case ev.MatchesPressOrRepeat("tab"), ev.MatchesPressOrRepeat("shift+tab"): // Tabs cannot be part of a query here, they move the selection. ev.Handled = true } return nil } func (h *Handler) open_palette() { h.palette_open = true h.palette_query = "" h.palette = action_catalog h.palette_selected = 0 h.message = "" h.draw_screen() } func (h *Handler) close_palette() { h.palette_open = false h.palette_query = "" h.palette = nil h.palette_selected = 0 h.draw_screen() } func (h *Handler) update_palette() { actions, err := filter_actions(h.palette_query) if err != nil { h.message = err.Error() return } h.palette = actions h.palette_selected = max(0, min(h.palette_selected, len(h.palette)-1)) } func (h *Handler) run_palette_action() { if h.palette_selected < 0 || h.palette_selected >= len(h.palette) { h.close_palette() return } name := h.palette[h.palette_selected].Name h.palette_open, h.palette_query, h.palette = false, "", nil h.palette_selected = 0 h.perform_action(name) } func (h *Handler) handle_palette_key(ev *loop.KeyEvent) error { switch { case ev.MatchesPressOrRepeat("escape"): ev.Handled = true h.close_palette() case ev.MatchesPressOrRepeat("enter"): ev.Handled = true h.run_palette_action() case ev.MatchesPressOrRepeat("up"): ev.Handled = true h.palette_selected = max(0, h.palette_selected-1) h.draw_screen() case ev.MatchesPressOrRepeat("down"): ev.Handled = true h.palette_selected = min(max(0, len(h.palette)-1), h.palette_selected+1) h.draw_screen() case ev.MatchesPressOrRepeat("backspace"): ev.Handled = true if h.palette_query != "" { g := wcswidth.SplitIntoGraphemes(h.palette_query) h.palette_query = strings.Join(g[:len(g)-1], "") h.update_palette() h.draw_screen() } } return nil } // open_selected opens the selected file in the requested window type. The // window type is a launch type, so "tab" and "window" both work. func (h *Handler) open_selected(window_type string) { e, ok := h.selected_entry() if !ok { h.lp.Beep() return } if e.IsDir { h.enter_dir() return } h.open_file_in(entry_path(h.cwd, e.Name), window_type) } func (h *Handler) draw_palette_list(width, list_start, list_height int) { if len(h.palette) == 0 { return } offset := 0 if h.palette_selected >= list_height { offset = h.palette_selected - list_height + 1 } for row := 0; row < list_height; row++ { idx := offset + row if idx >= len(h.palette) { break } a := h.palette[idx] text := truncate_to_width(fmt.Sprintf("%-18s %s", a.Name, a.Description), width-2) h.lp.MoveCursorTo(1, list_start+row) if idx == h.palette_selected { text += strings.Repeat(" ", max(0, width-wcswidth.Stringwidth(text))) h.lp.QueueWriteString(h.lp.SprintStyled("reverse", text)) } else { h.lp.QueueWriteString(" " + text) } } } func (h *Handler) handle_input_key(ev *loop.KeyEvent) error { if h.input_purpose == input_search { return h.handle_search_key(ev) } switch { case ev.MatchesPressOrRepeat("escape"): ev.Handled = true h.cancel_input() case ev.MatchesPressOrRepeat("enter"): ev.Handled = true h.commit_input() case ev.MatchesPressOrRepeat("backspace"): ev.Handled = true if h.text_buffer != "" { g := wcswidth.SplitIntoGraphemes(h.text_buffer) h.text_buffer = strings.Join(g[:len(g)-1], "") } h.draw_screen() case ev.MatchesPressOrRepeat("tab"), ev.MatchesPressOrRepeat("shift+tab"): // Tabs are not valid in file names, keep them out of the text buffer. ev.Handled = true } return nil } func (h *Handler) handle_confirm_key(ev *loop.KeyEvent) error { switch { case ev.MatchesPressOrRepeat("escape"): ev.Handled = true h.confirm_name = "" h.draw_screen() case ev.MatchesPressOrRepeat("enter"): ev.Handled = true h.perform_delete() } return nil } func (h *Handler) on_key_event(ev *loop.KeyEvent) error { if h.input_purpose != input_none { return h.handle_input_key(ev) } if h.palette_open { return h.handle_palette_key(ev) } if h.confirm_name != "" { return h.handle_confirm_key(ev) } if ac := h.shortcut_tracker.Match(ev, h.keyboard_shortcuts); ac != nil { ev.Handled = true h.perform_action(ac.Name) return nil } // Fallbacks so the panel stays usable when the user has replaced the // default shortcuts wholesale. switch { case ev.MatchesPressOrRepeat("escape"): ev.Handled = true h.perform_action("quit") case ev.MatchesPressOrRepeat("enter"): ev.Handled = true h.perform_action("activate") case ev.MatchesPressOrRepeat("up"): ev.Handled = true h.perform_action("move_up") case ev.MatchesPressOrRepeat("down"): ev.Handled = true h.perform_action("move_down") case ev.MatchesPressOrRepeat("backspace"): ev.Handled = true h.perform_action("parent_dir") case ev.MatchesPressOrRepeat("right"): ev.Handled = true h.perform_action("enter_dir") case ev.MatchesPressOrRepeat("left"): ev.Handled = true h.perform_action("parent_dir") case ev.MatchesPressOrRepeat("page_up"): ev.Handled = true h.perform_action("page_up") case ev.MatchesPressOrRepeat("page_down"): ev.Handled = true h.perform_action("page_down") } return nil } func (h *Handler) on_text(text string, from_key_event bool, in_bracketed_paste bool) error { if h.confirm_name != "" { switch strings.ToLower(strings.TrimSpace(text)) { case "y": h.perform_delete() case "n": h.confirm_name = "" h.draw_screen() } return nil } if h.palette_open { h.palette_query += text h.update_palette() h.draw_screen() return nil } if h.input_purpose != input_none { h.text_buffer += text if h.input_purpose == input_search { h.search_query = h.text_buffer if err := h.apply_search(); err != nil { h.message = err.Error() } } h.draw_screen() } return nil } func (h *Handler) on_resize(old, new_size loop.ScreenSize) error { h.screen_size = new_size h.draw_screen() return nil } func (h *Handler) row_to_entry(cell_y int) int { screen_row := cell_y + 1 list_start := 2 list_height := int(h.screen_size.HeightCells) - 1 - list_start if screen_row < list_start || screen_row >= list_start+list_height { return -1 } idx := h.scroll + (screen_row - list_start) if idx < 0 || idx >= len(h.entries) { return -1 } return idx } func (h *Handler) on_mouse_event(ev *loop.MouseEvent) error { switch ev.Event_type { case loop.MOUSE_CLICK: if ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 { if idx := h.row_to_entry(ev.Cell.Y); idx >= 0 { h.selected = idx h.draw_screen() } } case loop.MOUSE_MOVE: h.lp.ClearPointerShapes() if h.row_to_entry(ev.Cell.Y) >= 0 { h.lp.PushPointerShape(loop.POINTER_POINTER) } } return nil } func (h *Handler) entry_text(e Entry, width int) string { name := e.Name if e.IsDir { name += "/" } return " " + truncate_to_width(name, width-2) } func (h *Handler) padded_entry_text(e Entry, width int) string { text := h.entry_text(e, width) if pad := width - wcswidth.Stringwidth(text); pad > 0 { text += strings.Repeat(" ", pad) } return text } func (h *Handler) input_prompt() string { switch h.input_purpose { case input_create_file: return "New file:" case input_create_dir: return "New directory:" case input_rename: return fmt.Sprintf("Rename %s to:", h.rename_source) case input_search: return "Search:" } return "" } func (h *Handler) status_text() string { if h.message != "" { return " " + truncate_to_width(h.message, max(1, int(h.screen_size.WidthCells)-1)) } if h.search_query != "" { return fmt.Sprintf(" /%s %d matches", h.search_query, len(h.entries)) } if len(h.entries) == 0 { return " Empty directory" } e, ok := h.selected_entry() if !ok { return " Empty directory" } kind := "file" if e.IsDir { kind = "directory" } return fmt.Sprintf(" %d/%d - %s - modified %s", h.selected+1, len(h.entries), kind, time.Unix(e.ModTime, 0).Format("2006-01-02 15:04")) } func (h *Handler) draw_screen() { h.lp.StartAtomicUpdate() defer h.lp.EndAtomicUpdate() h.lp.ClearScreen() width := int(h.screen_size.WidthCells) height := int(h.screen_size.HeightCells) if width < 10 || height < 4 { return } h.lp.MoveCursorTo(1, 1) h.lp.QueueWriteString(h.lp.SprintStyled("bold fg=bright-green", truncate_to_width(h.cwd, width))) list_start := 2 status_y := height - 1 list_height := status_y - list_start if list_height < 1 { list_height = 1 } if len(h.entries) > 0 { h.selected = max(0, min(h.selected, len(h.entries)-1)) } else { h.selected, h.scroll = 0, 0 } if h.selected < h.scroll { h.scroll = h.selected } if h.selected >= h.scroll+list_height { h.scroll = h.selected - list_height + 1 } h.scroll = max(0, min(h.scroll, max(0, len(h.entries)-list_height))) if h.palette_open { h.draw_palette_list(width, list_start, list_height) } else { for row := 0; row < list_height; row++ { idx := h.scroll + row if idx >= len(h.entries) { break } e := h.entries[idx] h.lp.MoveCursorTo(1, list_start+row) switch { case idx == h.selected: h.lp.QueueWriteString(h.lp.SprintStyled("reverse", h.padded_entry_text(e, width))) case e.IsDir: h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-blue", h.entry_text(e, width))) default: h.lp.QueueWriteString(h.entry_text(e, width)) } } } h.lp.MoveCursorTo(1, status_y) h.lp.QueueWriteString(h.lp.SprintStyled("dim", h.status_text())) h.lp.MoveCursorTo(1, height) switch { case h.palette_open: prompt := "Actions: " h.lp.SetCursorVisible(true) h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt)) h.lp.QueueWriteString(h.palette_query) h.lp.MoveCursorTo(1+wcswidth.Stringwidth(prompt+h.palette_query), height) case h.input_purpose != input_none: prompt := h.input_prompt() + " " h.lp.QueueWriteString(h.lp.SprintStyled("fg=bright-yellow", prompt)) h.lp.QueueWriteString(h.text_buffer) h.lp.SetCursorVisible(true) h.lp.MoveCursorTo(1+wcswidth.Stringwidth(prompt+h.text_buffer), height) case h.confirm_name != "": h.lp.SetCursorVisible(false) h.lp.QueueWriteString(h.lp.SprintStyled("bold fg=bright-red", fmt.Sprintf("Delete %s? [y/N] ", h.confirm_name))) default: h.lp.SetCursorVisible(false) hints := "Enter: open /: search :: actions ->: enter Ctrl+Enter: cd here <-: up .: hidden n: new file r: rename d: delete y: copy q: quit" h.lp.QueueWriteString(h.lp.SprintStyled("dim", truncate_to_width(hints, width))) } } // result_payload is the JSON data handed over to the Python result handler. func (h *Handler) result_payload() map[string]string { return map[string]string{"action": h.result_action, "path": h.result_path} } func load_config(opts *Options) (*Config, error) { ans := NewConfig() p := config.ConfigParser{LineHandler: ans.Parse} if err := p.LoadConfig("file-manager.conf", opts.Config, opts.Override); err != nil { return nil, err } return ans, nil } func main(_ *cli.Command, opts *Options, args []string) (rc int, err error) { conf, err := load_config(opts) if err != nil { return 1, err } candidate := opts.StartDir if len(args) > 0 { candidate = args[0] } start_dir, err := resolve_start_dir(candidate) if err != nil { return 1, err } lp, err := loop.New() if err != nil { return 1, err } h := &Handler{lp: lp, conf: conf, cwd: start_dir, show_hidden: opts.ShowHidden || conf.Show_hidden} h.keyboard_shortcuts = config.ResolveShortcuts(conf.KeyboardShortcuts) lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING) lp.OnInitialize = func() (string, error) { return h.initialize() } lp.OnFinalize = func() string { return "" } lp.OnKeyEvent = h.on_key_event lp.OnText = h.on_text lp.OnResize = h.on_resize lp.OnMouseEvent = h.on_mouse_event if err = lp.Run(); err != nil { return 1, err } if ds := lp.DeathSignalName(); ds != "" { fmt.Println("Killed by signal:", ds) lp.KillIfSignalled() return } rc = lp.ExitCode() if h.result_action != "" { output := tui.KittenOutputSerializer() if s, serr := output(h.result_payload()); serr == nil { fmt.Println(s) } } return } func EntryPoint(parent *cli.Command) { create_cmd(parent, main) }