filepicker.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. package dialog
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "path/filepath"
  7. "sort"
  8. "strings"
  9. "time"
  10. "github.com/charmbracelet/bubbles/key"
  11. "github.com/charmbracelet/bubbles/textinput"
  12. "github.com/charmbracelet/bubbles/viewport"
  13. tea "github.com/charmbracelet/bubbletea"
  14. "github.com/charmbracelet/lipgloss"
  15. "github.com/sst/opencode/internal/app"
  16. "github.com/sst/opencode/internal/config"
  17. "github.com/sst/opencode/internal/message"
  18. "github.com/sst/opencode/internal/status"
  19. "github.com/sst/opencode/internal/tui/image"
  20. "github.com/sst/opencode/internal/tui/styles"
  21. "github.com/sst/opencode/internal/tui/theme"
  22. "github.com/sst/opencode/internal/tui/util"
  23. "log/slog"
  24. )
  25. const (
  26. maxAttachmentSize = int64(5 * 1024 * 1024) // 5MB
  27. downArrow = "down"
  28. upArrow = "up"
  29. )
  30. type FilePrickerKeyMap struct {
  31. Enter key.Binding
  32. Down key.Binding
  33. Up key.Binding
  34. Forward key.Binding
  35. Backward key.Binding
  36. OpenFilePicker key.Binding
  37. Esc key.Binding
  38. InsertCWD key.Binding
  39. }
  40. var filePickerKeyMap = FilePrickerKeyMap{
  41. Enter: key.NewBinding(
  42. key.WithKeys("enter"),
  43. key.WithHelp("enter", "select file/enter directory"),
  44. ),
  45. Down: key.NewBinding(
  46. key.WithKeys("j", downArrow),
  47. key.WithHelp("↓/j", "down"),
  48. ),
  49. Up: key.NewBinding(
  50. key.WithKeys("k", upArrow),
  51. key.WithHelp("↑/k", "up"),
  52. ),
  53. Forward: key.NewBinding(
  54. key.WithKeys("l"),
  55. key.WithHelp("l", "enter directory"),
  56. ),
  57. Backward: key.NewBinding(
  58. key.WithKeys("h", "backspace"),
  59. key.WithHelp("h/backspace", "go back"),
  60. ),
  61. OpenFilePicker: key.NewBinding(
  62. key.WithKeys("ctrl+f"),
  63. key.WithHelp("ctrl+f", "open file picker"),
  64. ),
  65. Esc: key.NewBinding(
  66. key.WithKeys("esc"),
  67. key.WithHelp("esc", "close/exit"),
  68. ),
  69. InsertCWD: key.NewBinding(
  70. key.WithKeys("i"),
  71. key.WithHelp("i", "manual path input"),
  72. ),
  73. }
  74. type filepickerCmp struct {
  75. basePath string
  76. width int
  77. height int
  78. cursor int
  79. err error
  80. cursorChain stack
  81. viewport viewport.Model
  82. dirs []os.DirEntry
  83. cwdDetails *DirNode
  84. selectedFile string
  85. cwd textinput.Model
  86. ShowFilePicker bool
  87. app *app.App
  88. }
  89. type DirNode struct {
  90. parent *DirNode
  91. child *DirNode
  92. directory string
  93. }
  94. type stack []int
  95. func (s stack) Push(v int) stack {
  96. return append(s, v)
  97. }
  98. func (s stack) Pop() (stack, int) {
  99. l := len(s)
  100. return s[:l-1], s[l-1]
  101. }
  102. type AttachmentAddedMsg struct {
  103. Attachment message.Attachment
  104. }
  105. func (f *filepickerCmp) Init() tea.Cmd {
  106. return nil
  107. }
  108. func (f *filepickerCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  109. var cmd tea.Cmd
  110. switch msg := msg.(type) {
  111. case tea.WindowSizeMsg:
  112. f.width = 60
  113. f.height = 20
  114. f.viewport.Width = 80
  115. f.viewport.Height = 22
  116. f.cursor = 0
  117. f.getCurrentFileBelowCursor()
  118. case tea.KeyMsg:
  119. if f.cwd.Focused() {
  120. f.cwd, cmd = f.cwd.Update(msg)
  121. }
  122. switch {
  123. case key.Matches(msg, filePickerKeyMap.InsertCWD):
  124. f.cwd.Focus()
  125. return f, cmd
  126. case key.Matches(msg, filePickerKeyMap.Esc):
  127. if f.cwd.Focused() {
  128. f.cwd.Blur()
  129. }
  130. case key.Matches(msg, filePickerKeyMap.Down):
  131. if !f.cwd.Focused() || msg.String() == downArrow {
  132. if f.cursor < len(f.dirs)-1 {
  133. f.cursor++
  134. f.getCurrentFileBelowCursor()
  135. }
  136. }
  137. case key.Matches(msg, filePickerKeyMap.Up):
  138. if !f.cwd.Focused() || msg.String() == upArrow {
  139. if f.cursor > 0 {
  140. f.cursor--
  141. f.getCurrentFileBelowCursor()
  142. }
  143. }
  144. case key.Matches(msg, filePickerKeyMap.Enter):
  145. var path string
  146. var isPathDir bool
  147. if f.cwd.Focused() {
  148. path = f.cwd.Value()
  149. fileInfo, err := os.Stat(path)
  150. if err != nil {
  151. status.Error("Invalid path")
  152. return f, cmd
  153. }
  154. isPathDir = fileInfo.IsDir()
  155. } else {
  156. path = filepath.Join(f.cwdDetails.directory, "/", f.dirs[f.cursor].Name())
  157. isPathDir = f.dirs[f.cursor].IsDir()
  158. }
  159. if isPathDir {
  160. newWorkingDir := DirNode{parent: f.cwdDetails, directory: path}
  161. f.cwdDetails.child = &newWorkingDir
  162. f.cwdDetails = f.cwdDetails.child
  163. f.cursorChain = f.cursorChain.Push(f.cursor)
  164. f.dirs = readDir(f.cwdDetails.directory, false)
  165. f.cursor = 0
  166. f.cwd.SetValue(f.cwdDetails.directory)
  167. f.getCurrentFileBelowCursor()
  168. } else {
  169. f.selectedFile = path
  170. return f.addAttachmentToMessage()
  171. }
  172. case key.Matches(msg, filePickerKeyMap.Esc):
  173. if !f.cwd.Focused() {
  174. f.cursorChain = make(stack, 0)
  175. f.cursor = 0
  176. } else {
  177. f.cwd.Blur()
  178. }
  179. case key.Matches(msg, filePickerKeyMap.Forward):
  180. if !f.cwd.Focused() {
  181. if f.dirs[f.cursor].IsDir() {
  182. path := filepath.Join(f.cwdDetails.directory, "/", f.dirs[f.cursor].Name())
  183. newWorkingDir := DirNode{parent: f.cwdDetails, directory: path}
  184. f.cwdDetails.child = &newWorkingDir
  185. f.cwdDetails = f.cwdDetails.child
  186. f.cursorChain = f.cursorChain.Push(f.cursor)
  187. f.dirs = readDir(f.cwdDetails.directory, false)
  188. f.cursor = 0
  189. f.cwd.SetValue(f.cwdDetails.directory)
  190. f.getCurrentFileBelowCursor()
  191. }
  192. }
  193. case key.Matches(msg, filePickerKeyMap.Backward):
  194. if !f.cwd.Focused() {
  195. if len(f.cursorChain) != 0 && f.cwdDetails.parent != nil {
  196. f.cursorChain, f.cursor = f.cursorChain.Pop()
  197. f.cwdDetails = f.cwdDetails.parent
  198. f.cwdDetails.child = nil
  199. f.dirs = readDir(f.cwdDetails.directory, false)
  200. f.cwd.SetValue(f.cwdDetails.directory)
  201. f.getCurrentFileBelowCursor()
  202. }
  203. }
  204. case key.Matches(msg, filePickerKeyMap.OpenFilePicker):
  205. f.dirs = readDir(f.cwdDetails.directory, false)
  206. f.cursor = 0
  207. f.getCurrentFileBelowCursor()
  208. }
  209. }
  210. return f, cmd
  211. }
  212. func (f *filepickerCmp) addAttachmentToMessage() (tea.Model, tea.Cmd) {
  213. modeInfo := GetSelectedModel(config.Get())
  214. if !modeInfo.SupportsAttachments {
  215. status.Error(fmt.Sprintf("Model %s doesn't support attachments", modeInfo.Name))
  216. return f, nil
  217. }
  218. selectedFilePath := f.selectedFile
  219. if !isExtSupported(selectedFilePath) {
  220. status.Error("Unsupported file")
  221. return f, nil
  222. }
  223. isFileLarge, err := image.ValidateFileSize(selectedFilePath, maxAttachmentSize)
  224. if err != nil {
  225. status.Error("unable to read the image")
  226. return f, nil
  227. }
  228. if isFileLarge {
  229. status.Error("file too large, max 5MB")
  230. return f, nil
  231. }
  232. content, err := os.ReadFile(selectedFilePath)
  233. if err != nil {
  234. status.Error("Unable read selected file")
  235. return f, nil
  236. }
  237. mimeBufferSize := min(512, len(content))
  238. mimeType := http.DetectContentType(content[:mimeBufferSize])
  239. fileName := filepath.Base(selectedFilePath)
  240. attachment := message.Attachment{FilePath: selectedFilePath, FileName: fileName, MimeType: mimeType, Content: content}
  241. f.selectedFile = ""
  242. return f, util.CmdHandler(AttachmentAddedMsg{attachment})
  243. }
  244. func (f *filepickerCmp) View() string {
  245. t := theme.CurrentTheme()
  246. const maxVisibleDirs = 20
  247. const maxWidth = 80
  248. adjustedWidth := maxWidth
  249. for _, file := range f.dirs {
  250. if len(file.Name()) > adjustedWidth-4 { // Account for padding
  251. adjustedWidth = len(file.Name()) + 4
  252. }
  253. }
  254. adjustedWidth = max(30, min(adjustedWidth, f.width-15)) + 1
  255. files := make([]string, 0, maxVisibleDirs)
  256. startIdx := 0
  257. if len(f.dirs) > maxVisibleDirs {
  258. halfVisible := maxVisibleDirs / 2
  259. if f.cursor >= halfVisible && f.cursor < len(f.dirs)-halfVisible {
  260. startIdx = f.cursor - halfVisible
  261. } else if f.cursor >= len(f.dirs)-halfVisible {
  262. startIdx = len(f.dirs) - maxVisibleDirs
  263. }
  264. }
  265. endIdx := min(startIdx+maxVisibleDirs, len(f.dirs))
  266. for i := startIdx; i < endIdx; i++ {
  267. file := f.dirs[i]
  268. itemStyle := styles.BaseStyle().Width(adjustedWidth)
  269. if i == f.cursor {
  270. itemStyle = itemStyle.
  271. Background(t.Primary()).
  272. Foreground(t.Background()).
  273. Bold(true)
  274. }
  275. filename := file.Name()
  276. if len(filename) > adjustedWidth-4 {
  277. filename = filename[:adjustedWidth-7] + "..."
  278. }
  279. if file.IsDir() {
  280. filename = filename + "/"
  281. } else if isExtSupported(file.Name()) {
  282. filename = filename
  283. } else {
  284. filename = filename
  285. }
  286. files = append(files, itemStyle.Padding(0, 1).Render(filename))
  287. }
  288. // Pad to always show exactly 21 lines
  289. for len(files) < maxVisibleDirs {
  290. files = append(files, styles.BaseStyle().Width(adjustedWidth).Render(""))
  291. }
  292. currentPath := styles.BaseStyle().
  293. Height(1).
  294. Width(adjustedWidth).
  295. Render(f.cwd.View())
  296. viewportstyle := lipgloss.NewStyle().
  297. Width(f.viewport.Width).
  298. Background(t.Background()).
  299. Border(lipgloss.RoundedBorder()).
  300. BorderForeground(t.TextMuted()).
  301. BorderBackground(t.Background()).
  302. Padding(2).
  303. Render(f.viewport.View())
  304. var insertExitText string
  305. if f.IsCWDFocused() {
  306. insertExitText = "Press esc to exit typing path"
  307. } else {
  308. insertExitText = "Press i to start typing path"
  309. }
  310. content := lipgloss.JoinVertical(
  311. lipgloss.Left,
  312. currentPath,
  313. styles.BaseStyle().Width(adjustedWidth).Render(""),
  314. styles.BaseStyle().Width(adjustedWidth).Render(lipgloss.JoinVertical(lipgloss.Left, files...)),
  315. styles.BaseStyle().Width(adjustedWidth).Render(""),
  316. styles.BaseStyle().Foreground(t.TextMuted()).Width(adjustedWidth).Render(insertExitText),
  317. )
  318. f.cwd.SetValue(f.cwd.Value())
  319. contentStyle := styles.BaseStyle().Padding(1, 2).
  320. Border(lipgloss.RoundedBorder()).
  321. BorderBackground(t.Background()).
  322. BorderForeground(t.TextMuted()).
  323. Width(lipgloss.Width(content) + 4)
  324. return lipgloss.JoinHorizontal(lipgloss.Center, contentStyle.Render(content), viewportstyle)
  325. }
  326. type FilepickerCmp interface {
  327. tea.Model
  328. ToggleFilepicker(showFilepicker bool)
  329. IsCWDFocused() bool
  330. }
  331. func (f *filepickerCmp) ToggleFilepicker(showFilepicker bool) {
  332. f.ShowFilePicker = showFilepicker
  333. }
  334. func (f *filepickerCmp) IsCWDFocused() bool {
  335. return f.cwd.Focused()
  336. }
  337. func NewFilepickerCmp(app *app.App) FilepickerCmp {
  338. homepath, err := os.UserHomeDir()
  339. if err != nil {
  340. slog.Error("error loading user files")
  341. return nil
  342. }
  343. baseDir := DirNode{parent: nil, directory: homepath}
  344. dirs := readDir(homepath, false)
  345. viewport := viewport.New(0, 0)
  346. currentDirectory := textinput.New()
  347. currentDirectory.CharLimit = 200
  348. currentDirectory.Width = 44
  349. currentDirectory.Cursor.Blink = true
  350. currentDirectory.SetValue(baseDir.directory)
  351. return &filepickerCmp{cwdDetails: &baseDir, dirs: dirs, cursorChain: make(stack, 0), viewport: viewport, cwd: currentDirectory, app: app}
  352. }
  353. func (f *filepickerCmp) getCurrentFileBelowCursor() {
  354. if len(f.dirs) == 0 || f.cursor < 0 || f.cursor >= len(f.dirs) {
  355. slog.Error(fmt.Sprintf("Invalid cursor position. Dirs length: %d, Cursor: %d", len(f.dirs), f.cursor))
  356. f.viewport.SetContent("Preview unavailable")
  357. return
  358. }
  359. dir := f.dirs[f.cursor]
  360. filename := dir.Name()
  361. if !dir.IsDir() && isExtSupported(filename) {
  362. fullPath := f.cwdDetails.directory + "/" + dir.Name()
  363. go func() {
  364. imageString, err := image.ImagePreview(f.viewport.Width-4, fullPath)
  365. if err != nil {
  366. slog.Error(err.Error())
  367. f.viewport.SetContent("Preview unavailable")
  368. return
  369. }
  370. f.viewport.SetContent(imageString)
  371. }()
  372. } else {
  373. f.viewport.SetContent("Preview unavailable")
  374. }
  375. }
  376. func readDir(path string, showHidden bool) []os.DirEntry {
  377. slog.Info(fmt.Sprintf("Reading directory: %s", path))
  378. entriesChan := make(chan []os.DirEntry, 1)
  379. errChan := make(chan error, 1)
  380. go func() {
  381. dirEntries, err := os.ReadDir(path)
  382. if err != nil {
  383. status.Error(err.Error())
  384. errChan <- err
  385. return
  386. }
  387. entriesChan <- dirEntries
  388. }()
  389. select {
  390. case dirEntries := <-entriesChan:
  391. sort.Slice(dirEntries, func(i, j int) bool {
  392. if dirEntries[i].IsDir() == dirEntries[j].IsDir() {
  393. return dirEntries[i].Name() < dirEntries[j].Name()
  394. }
  395. return dirEntries[i].IsDir()
  396. })
  397. if showHidden {
  398. return dirEntries
  399. }
  400. var sanitizedDirEntries []os.DirEntry
  401. for _, dirEntry := range dirEntries {
  402. isHidden, _ := IsHidden(dirEntry.Name())
  403. if !isHidden {
  404. if dirEntry.IsDir() || isExtSupported(dirEntry.Name()) {
  405. sanitizedDirEntries = append(sanitizedDirEntries, dirEntry)
  406. }
  407. }
  408. }
  409. return sanitizedDirEntries
  410. case <-errChan:
  411. status.Error(fmt.Sprintf("Error reading directory %s", path))
  412. return []os.DirEntry{}
  413. case <-time.After(5 * time.Second):
  414. status.Error(fmt.Sprintf("Timeout reading directory %s", path))
  415. return []os.DirEntry{}
  416. }
  417. }
  418. func IsHidden(file string) (bool, error) {
  419. return strings.HasPrefix(file, "."), nil
  420. }
  421. func isExtSupported(path string) bool {
  422. ext := strings.ToLower(filepath.Ext(path))
  423. return (ext == ".jpg" || ext == ".jpeg" || ext == ".webp" || ext == ".png")
  424. }