1package filepicker
  2
  3import (
  4	"fmt"
  5	"io/fs"
  6	"net/http"
  7	"os"
  8	"path/filepath"
  9	"strings"
 10
 11	"github.com/charmbracelet/bubbles/v2/filepicker"
 12	"github.com/charmbracelet/bubbles/v2/help"
 13	"github.com/charmbracelet/bubbles/v2/key"
 14	tea "github.com/charmbracelet/bubbletea/v2"
 15	"github.com/charmbracelet/crush/internal/home"
 16	"github.com/charmbracelet/crush/internal/message"
 17	"github.com/charmbracelet/crush/internal/tui/components/core"
 18	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 19	"github.com/charmbracelet/crush/internal/tui/components/image"
 20	"github.com/charmbracelet/crush/internal/tui/styles"
 21	"github.com/charmbracelet/crush/internal/tui/util"
 22	"github.com/charmbracelet/lipgloss/v2"
 23)
 24
 25const (
 26	MaxAttachmentSize   = int64(5 * 1024 * 1024) // 5MB
 27	FilePickerID        = "filepicker"
 28	fileSelectionHeight = 10
 29	previewHeight       = 20
 30)
 31
 32type FilePickedMsg struct {
 33	Attachment message.Attachment
 34}
 35
 36type FilePicker interface {
 37	dialogs.DialogModel
 38}
 39
 40type model struct {
 41	wWidth          int
 42	wHeight         int
 43	width           int
 44	filePicker      filepicker.Model
 45	highlightedFile string
 46	image           image.Model
 47	keyMap          KeyMap
 48	help            help.Model
 49}
 50
 51var AllowedTypes = []string{".jpg", ".jpeg", ".png"}
 52
 53func NewFilePickerCmp(workingDir string) FilePicker {
 54	t := styles.CurrentTheme()
 55	fp := filepicker.New()
 56	fp.AllowedTypes = AllowedTypes
 57
 58	if workingDir != "" {
 59		fp.CurrentDirectory = workingDir
 60	} else {
 61		// Fallback to current working directory, then home directory
 62		if cwd, err := os.Getwd(); err == nil {
 63			fp.CurrentDirectory = cwd
 64		} else {
 65			fp.CurrentDirectory = home.Dir()
 66		}
 67	}
 68
 69	fp.ShowPermissions = false
 70	fp.ShowSize = false
 71	fp.AutoHeight = false
 72	fp.Styles = t.S().FilePicker
 73	fp.Cursor = ""
 74	fp.SetHeight(fileSelectionHeight)
 75
 76	image := image.New(1, 1, "")
 77
 78	help := help.New()
 79	help.Styles = t.S().Help
 80	return &model{
 81		filePicker: fp,
 82		image:      image,
 83		keyMap:     DefaultKeyMap(),
 84		help:       help,
 85	}
 86}
 87
 88func (m *model) Init() tea.Cmd {
 89	return m.filePicker.Init()
 90}
 91
 92func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 93	switch msg := msg.(type) {
 94	case tea.WindowSizeMsg:
 95		m.wWidth = msg.Width
 96		m.wHeight = msg.Height
 97		m.width = min(70, m.wWidth)
 98		styles := m.filePicker.Styles
 99		styles.Directory = styles.Directory.Width(m.width - 4)
100		styles.Selected = styles.Selected.PaddingLeft(1).Width(m.width - 4)
101		styles.DisabledSelected = styles.DisabledSelected.PaddingLeft(1).Width(m.width - 4)
102		styles.File = styles.File.Width(m.width)
103		m.filePicker.Styles = styles
104		return m, nil
105	case tea.KeyPressMsg:
106		if key.Matches(msg, m.keyMap.Close) {
107			return m, util.CmdHandler(dialogs.CloseDialogMsg{})
108		}
109		if key.Matches(msg, m.filePicker.KeyMap.Back) {
110			// make sure we don't go back if we are at the home directory
111			if m.filePicker.CurrentDirectory == home.Dir() {
112				return m, nil
113			}
114		}
115	}
116
117	var cmd tea.Cmd
118	var cmds []tea.Cmd
119	m.filePicker, cmd = m.filePicker.Update(msg)
120	cmds = append(cmds, cmd)
121	if m.highlightedFile != m.currentImage() && m.currentImage() != "" {
122		w, h := m.imagePreviewSize()
123		cmd = m.image.Redraw(uint(w-2), uint(h-2), m.currentImage())
124		cmds = append(cmds, cmd)
125	}
126	m.highlightedFile = m.currentImage()
127
128	// Did the user select a file?
129	if didSelect, path := m.filePicker.DidSelectFile(msg); didSelect {
130		// Get the path of the selected file.
131		return m, tea.Sequence(
132			util.CmdHandler(dialogs.CloseDialogMsg{}),
133			func() tea.Msg {
134				isFileLarge, err := IsFileTooBig(path, MaxAttachmentSize)
135				if err != nil {
136					return util.ReportError(fmt.Errorf("unable to read the image: %w", err))
137				}
138				if isFileLarge {
139					return util.ReportError(fmt.Errorf("file too large, max 5MB"))
140				}
141
142				content, err := os.ReadFile(path)
143				if err != nil {
144					return util.ReportError(fmt.Errorf("unable to read the image: %w", err))
145				}
146
147				mimeBufferSize := min(512, len(content))
148				mimeType := http.DetectContentType(content[:mimeBufferSize])
149				fileName := filepath.Base(path)
150				attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
151				return FilePickedMsg{
152					Attachment: attachment,
153				}
154			},
155		)
156	}
157	m.image, cmd = m.image.Update(msg)
158	cmds = append(cmds, cmd)
159	return m, tea.Batch(cmds...)
160}
161
162func (m *model) View() string {
163	t := styles.CurrentTheme()
164
165	strs := []string{
166		t.S().Base.Padding(0, 1, 1, 1).Render(core.Title("Add Image", m.width-4)),
167	}
168
169	// hide image preview if the terminal is too small
170	if x, y := m.imagePreviewSize(); x > 0 && y > 0 {
171		strs = append(strs, m.imagePreview())
172	}
173
174	strs = append(
175		strs,
176		m.filePicker.View(),
177		t.S().Base.Width(m.width-2).PaddingLeft(1).AlignHorizontal(lipgloss.Left).Render(m.help.View(m.keyMap)),
178	)
179
180	content := lipgloss.JoinVertical(
181		lipgloss.Left,
182		strs...,
183	)
184	return m.style().Render(content)
185}
186
187func (m *model) currentImage() string {
188	for _, ext := range m.filePicker.AllowedTypes {
189		if strings.HasSuffix(m.filePicker.HighlightedPath(), ext) {
190			return m.filePicker.HighlightedPath()
191		}
192	}
193	return ""
194}
195
196func (m *model) imagePreview() string {
197	const padding = 2
198
199	t := styles.CurrentTheme()
200	w, h := m.imagePreviewSize()
201
202	if m.currentImage() == "" {
203		imgPreview := t.S().Base.
204			Width(w - padding).
205			Height(h - padding).
206			Background(t.BgOverlay)
207
208		return m.imagePreviewStyle().Render(imgPreview.Render())
209	}
210
211	return m.imagePreviewStyle().Width(w).Height(h).Render(m.image.View())
212}
213
214func (m *model) imagePreviewStyle() lipgloss.Style {
215	t := styles.CurrentTheme()
216	return t.S().Base.Padding(1, 1, 1, 1)
217}
218
219func (m *model) imagePreviewSize() (int, int) {
220	if m.wHeight-fileSelectionHeight-8 > previewHeight {
221		return m.width - 4, previewHeight
222	}
223	return 0, 0
224}
225
226func (m *model) style() lipgloss.Style {
227	t := styles.CurrentTheme()
228	return t.S().Base.
229		Width(m.width).
230		Border(lipgloss.RoundedBorder()).
231		BorderForeground(t.BorderFocus)
232}
233
234// ID implements FilePicker.
235func (m *model) ID() dialogs.DialogID {
236	return FilePickerID
237}
238
239// Position implements FilePicker.
240func (m *model) Position() (int, int) {
241	_, imageHeight := m.imagePreviewSize()
242	dialogHeight := fileSelectionHeight + imageHeight + 4
243	row := (m.wHeight - dialogHeight) / 2
244
245	col := m.wWidth / 2
246	col -= m.width / 2
247	return row, col
248}
249
250func IsFileTooBigWithFS(fsys fs.FS, filePath string, sizeLimit int64) (bool, error) {
251	return isFileTooBigFS(fsys, filePath, sizeLimit)
252}
253
254func IsFileTooBig(filePath string, sizeLimit int64) (bool, error) {
255	return isFileTooBigFS(os.DirFS("."), filePath, sizeLimit)
256}
257
258func isFileTooBigFS(fsys fs.FS, filePath string, sizeLimit int64) (bool, error) {
259	fileInfo, err := fs.Stat(fsys, filePath)
260	if err != nil {
261		return false, fmt.Errorf("error getting file info: %w", err)
262	}
263
264	if fileInfo.Size() > sizeLimit {
265		return true, nil
266	}
267
268	return false, nil
269}