diff --git a/README.md b/README.md index d6f0780..b094473 100644 --- a/README.md +++ b/README.md @@ -121,14 +121,16 @@ Run `tg` with no arguments. | `↑` `↓` `j` `k` | Move in the chat list | | `enter` | Open the chat, or send the message | | `/` | Filter chats by name | -| `tab` `esc` | Switch between chat list and composer | +| `tab` | Switch between chat list and composer, `esc` goes back to the list | | `pgup` `pgdn` | Scroll the conversation, older messages load as you go | -| `ctrl+↑` `ctrl+↓` | Pick the message to reply to (`alt` works too) | +| `ctrl+↑` `ctrl+↓` | Pick the message to reply to (`alt` works too, use it on a Mac) | | `↑` | In an empty composer, edit your last message | | `esc` | Cancel the reply or the edit | -| `ctrl+v` | Attach the image in the clipboard, the message becomes its caption | +| `ctrl+v` (`cmd+v` on a Mac) | Attach the image in the clipboard, the message becomes its caption | | `backspace` | Remove the attachment, when the message is empty | -| `q` `ctrl+c` | Quit | +| `ctrl+c` | Clear the composer or cancel the edit, quit when it is empty | +| `esc` | In the chat list, open the settings: theme, spacing, how shortcuts are written | +| `q` | Quit, from the chat list | The mouse works too: click a chat, scroll either pane, right click a message to reply, edit, copy its text or copy its ID. Copying uses OSC 52, so it also works over SSH; inside tmux it needs `set -g set-clipboard on`. Edits are sent as plain text, so bold and links made in another app are lost, and messages the composer cannot hold as they are (several lines, special characters) are edited elsewhere. New messages arrive live. What you type and leave unsent stays with its chat, shown in the list as a `[draft]`. @@ -144,6 +146,10 @@ To send a picture, copy it and paste it into the composer, or press `ctrl+v`, or `tg config spacing on` sets messages apart in the conversation: a blank line before a new sender, a pause of more than five minutes, or a new day. Off, the default, packs them together. It is stored as `"spaced_messages"` in `config.json`. +Both can also be changed in the settings, with `esc` from the chat list. There "Shortcuts" picks how keys are written: `⌘V` and `⌥↑↓` on a Mac, `ctrl+v` and `ctrl+↑↓` elsewhere. It follows the system tg runs on, so over SSH from a Mac set it once. It is stored as `"keys"` in `config.json`. + +Bots' inline buttons are drawn under their messages. Click one to press it, the bot's answer shows at the bottom. A link button copies its link. Buttons that need Telegram's own apps, like games and payments, say so. + ### Pictures Profile pictures, photos, stickers and video previews are drawn in terminals that implement the Kitty graphics protocol with Unicode placeholders: [Kitty](https://sw.kovidgoyal.net/kitty/) and [Ghostty](https://ghostty.org). Animated stickers play in a loop, and with [ffmpeg](https://ffmpeg.org) installed so do video stickers, GIFs and videos up to 6 seconds, muted. Round video messages show their first frame. The terminal animates them on the GPU, and ffmpeg decodes videos on the GPU when it can. A chat without a photo gets a square badge with its initials. Elsewhere the badge is drawn with text, and media shows as `[photo]`, `[sticker 😄]` and so on. Inside tmux, pictures need `set -g allow-passthrough on`. Force them on or off with `TG_IMAGES=1` or `TG_IMAGES=0`. diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 4e3dad4..b922695 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -200,7 +200,20 @@ func (a *app) dispatch(ctx context.Context, args []string) error { if len(cfg.Accounts) > 1 { label = name } - return tui.Run(ctx, be, a.version, label, tui.Look{Theme: cfg.Theme, Spaced: cfg.SpacedMessages}) + look := func(f *config.File) tui.Look { + return tui.Look{Theme: f.Theme, Spaced: f.SpacedMessages, Keys: f.Keys} + } + // The settings menu saves one change at a time, over config.json + // as it is then. + save := func(change func(*tui.Look)) error { + return config.Update(func(f *config.File) error { + l := look(f) + change(&l) + f.Theme, f.SpacedMessages, f.Keys = l.Theme, l.Spaced, l.Keys + return nil + }) + } + return tui.Run(ctx, be, a.version, label, look(cfg), save) }) } diff --git a/internal/config/config.go b/internal/config/config.go index 633b484..2239131 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -83,8 +83,12 @@ type File struct { Theme string `json:"theme,omitempty"` // SpacedMessages sets messages apart in the TUI's conversation, see // `tg config spacing`. Off packs them together. - SpacedMessages bool `json:"spaced_messages,omitempty"` - Accounts map[string]*Account `json:"accounts,omitempty"` + SpacedMessages bool `json:"spaced_messages,omitempty"` + // Keys is how the TUI writes shortcuts: "mac" with ⌥ and ⌘, "pc" with + // alt+ and ctrl+. Empty follows the system tg runs on. The TUI's + // settings menu (esc) sets it. + Keys string `json:"keys,omitempty"` + Accounts map[string]*Account `json:"accounts,omitempty"` } // Account is one logged in Telegram account and its guardrails. Both diff --git a/internal/core/core.go b/internal/core/core.go index 34ade43..e0da985 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -58,6 +58,37 @@ type Message struct { // PictureSize is the media's size in pixels, zero when unknown. The TUI // sets room aside for the picture with it, so nothing moves when it loads. PictureSize image.Point `json:"-"` + // Buttons are a bot's inline keyboard, row by row. + Buttons [][]Button `json:"-"` +} + +// ButtonKind tells what pressing a button of a bot's keyboard does. +type ButtonKind uint8 + +const ( + // ButtonOther only works in Telegram's own apps, like a game or a payment. + ButtonOther ButtonKind = iota + // ButtonCallback sends its Value to the bot, see Backend.Press. + ButtonCallback + // ButtonURL opens the link in its Value. + ButtonURL + // ButtonCopy copies its Value. + ButtonCopy +) + +// Button is one button of a bot's inline keyboard. +type Button struct { + Text string + Kind ButtonKind + Value string +} + +// BotAnswer is what a bot replies to a pressed button: a notice to show and +// a link to open. Either can be empty, a bot often answers by editing its +// message instead. +type BotAnswer struct { + Text string + URL string } // MediaPhoto is the Media of a message that carries a photo. @@ -172,6 +203,8 @@ type Backend interface { // posts: front ends offer it only for messages the account sent. Edit(ctx context.Context, chatID int64, msgID int, text string) error MarkRead(ctx context.Context, chatID int64, maxID int) error + // Press presses a ButtonCallback of message msgID, data being its Value. + Press(ctx context.Context, chatID int64, msgID int, data string) (BotAnswer, error) // CreateGroup makes a new group with only the account in it. CreateGroup(ctx context.Context, title string) (Chat, error) Search(ctx context.Context, q SearchQuery) ([]Message, error) diff --git a/internal/core/guard.go b/internal/core/guard.go index 1d114d4..3c9deee 100644 --- a/internal/core/guard.go +++ b/internal/core/guard.go @@ -78,6 +78,14 @@ func (g *guarded) Edit(ctx context.Context, chatID int64, msgID int, text string return g.Backend.Edit(ctx, chatID, msgID, text) } +// Press is checked like sending: the bot acts on it as on a message. +func (g *guarded) Press(ctx context.Context, chatID int64, msgID int, data string) (BotAnswer, error) { + if err := g.check("pressing buttons", chatID); err != nil { + return BotAnswer{}, err + } + return g.Backend.Press(ctx, chatID, msgID, data) +} + func (g *guarded) MarkRead(ctx context.Context, chatID int64, maxID int) error { if err := g.check("marking as read", chatID); err != nil { return err diff --git a/internal/core/guard_test.go b/internal/core/guard_test.go index 2f8851c..af53b38 100644 --- a/internal/core/guard_test.go +++ b/internal/core/guard_test.go @@ -18,13 +18,18 @@ func (w *writes) Send(context.Context, int64, SendRequest) (Message, error) { } func (w *writes) Edit(context.Context, int64, int, string) error { w.n++; return nil } func (w *writes) MarkRead(context.Context, int64, int) error { w.n++; return nil } +func (w *writes) Press(context.Context, int64, int, string) (BotAnswer, error) { + w.n++ + return BotAnswer{}, nil +} func (w *writes) CreateGroup(context.Context, string) (Chat, error) { w.n++ return Chat{}, nil } // attempt tries every kind of write on chatID and reports which were refused. -// Editing follows the same rules as sending, so it is reported with it. +// Editing and pressing buttons follow the same rules as sending, so they are +// reported with it. func attempt(t *testing.T, policy Policy, chatID int64) (send, read, group bool, reached int) { t.Helper() backend := &writes{} @@ -43,6 +48,9 @@ func attempt(t *testing.T, policy Policy, chatID int64) (send, read, group bool, if edit := refused(g.Edit(context.Background(), chatID, 1, "x")); edit != send { t.Errorf("chat %d: editing refused=%v, sending refused=%v", chatID, edit, send) } + if _, err := g.Press(context.Background(), chatID, 1, "x"); refused(err) != send { + t.Errorf("chat %d: pressing refused=%v, sending refused=%v", chatID, refused(err), send) + } read = refused(g.MarkRead(context.Background(), chatID, 1)) _, err = g.CreateGroup(context.Background(), "g") group = refused(err) @@ -69,7 +77,7 @@ func TestGuard(t *testing.T) { t.Errorf("%s: refused send=%v read=%v group=%v", c.name, send, read, group) } allowed := 0 - for _, refused := range []bool{c.send, c.send, c.read, c.group} { // send twice: edit too + for _, refused := range []bool{c.send, c.send, c.send, c.read, c.group} { // edit and press follow send if !refused { allowed++ } diff --git a/internal/demo/demo.go b/internal/demo/demo.go index c283f55..67e3e81 100644 --- a/internal/demo/demo.go +++ b/internal/demo/demo.go @@ -51,6 +51,14 @@ type fixture struct { lines []string // "||" } +// keyboards are the inline keyboards of the last message of bot chats. +var keyboards = map[int64][][]core.Button{ + 104: { + {{Text: "@weather_demo_bot", Kind: core.ButtonCallback, Value: "edit:1"}, {Text: "@build_demo_bot", Kind: core.ButtonCallback, Value: "edit:2"}}, + {{Text: "Bot API docs", Kind: core.ButtonURL, Value: "https://core.telegram.org/bots/api"}}, + }, +} + var fixtures = []fixture{ {core.Chat{ID: 101, Kind: core.KindUser, Title: "Alice Rossi", Username: "alice", Unread: 2, Pinned: true, PhotoID: 1}, []string{ "190|Alice Rossi|hey, are we still on for tomorrow?", @@ -97,8 +105,8 @@ var fixtures = []fixture{ "340|Papà|[photo]", }}, {core.Chat{ID: 104, Kind: core.KindBot, Title: "BotFather", Username: "BotFather", PhotoID: 6}, []string{ - "8000||/newbot", - "7999|BotFather|Alright, a new bot. How are we going to call it?", + "8000||/mybots", + "7999|BotFather|Choose a bot from the list below:", }}, {core.Chat{ID: 1000, Kind: core.KindUser, Title: "Saved Messages"}, []string{ "9000||wifi guest password: correct horse battery staple", @@ -143,6 +151,7 @@ func New() *Backend { } chat := f.chat msgs := b.messages[chat.ID] + msgs[len(msgs)-1].Buttons = keyboards[chat.ID] chat.Last = &msgs[len(msgs)-1] b.chats = append(b.chats, chat) } @@ -269,6 +278,24 @@ func (b *Backend) Edit(_ context.Context, chatID int64, msgID int, text string) return nil } +// Press answers with the label of the button, as a bot would with a notice. +func (b *Backend) Press(_ context.Context, chatID int64, msgID int, data string) (core.BotAnswer, error) { + b.mu.Lock() + defer b.mu.Unlock() + i := slices.IndexFunc(b.messages[chatID], func(m core.Message) bool { return m.ID == msgID }) + if i < 0 { + return core.BotAnswer{}, fmt.Errorf("no message %d in chat %d", msgID, chatID) + } + for _, row := range b.messages[chatID][i].Buttons { + for _, button := range row { + if button.Kind == core.ButtonCallback && button.Value == data { + return core.BotAnswer{Text: "Editing " + button.Text}, nil + } + } + } + return core.BotAnswer{}, fmt.Errorf("message %d has no such button", msgID) +} + func (b *Backend) MarkRead(_ context.Context, chatID int64, _ int) error { b.mu.Lock() defer b.mu.Unlock() diff --git a/internal/mtp/backend.go b/internal/mtp/backend.go index 6be5481..e3ef49f 100644 --- a/internal/mtp/backend.go +++ b/internal/mtp/backend.go @@ -20,6 +20,7 @@ import ( "github.com/gotd/td/telegram/updates" "github.com/gotd/td/telegram/uploader" "github.com/gotd/td/tg" + "github.com/gotd/td/tgerr" "github.com/RealDoc06/tg-cli/internal/config" "github.com/RealDoc06/tg-cli/internal/core" @@ -296,6 +297,23 @@ func (b *backend) Edit(ctx context.Context, chatID int64, msgID int, text string return err } +func (b *backend) Press(ctx context.Context, chatID int64, msgID int, data string) (core.BotAnswer, error) { + peer, err := b.peers.input(chatID) + if err != nil { + return core.BotAnswer{}, err + } + res, err := b.api.MessagesGetBotCallbackAnswer(ctx, &tg.MessagesGetBotCallbackAnswerRequest{ + Peer: peer, MsgID: msgID, Data: []byte(data), + }) + if tgerr.Is(err, "BOT_RESPONSE_TIMEOUT") { + return core.BotAnswer{}, nil // the bot got it, and may answer by editing its message + } + if err != nil { + return core.BotAnswer{}, err + } + return core.BotAnswer{Text: res.Message, URL: res.URL}, nil +} + func (b *backend) MarkRead(ctx context.Context, chatID int64, maxID int) error { peer, err := b.peers.input(chatID) if err != nil { diff --git a/internal/mtp/convert.go b/internal/mtp/convert.go index ce0d65a..fc02455 100644 --- a/internal/mtp/convert.go +++ b/internal/mtp/convert.go @@ -20,6 +20,15 @@ func (b *backend) message(raw tg.MessageClass, e tg.Entities) (core.Message, boo Edited: m.EditDate != 0 && !m.EditHide, } out.Media, out.Picture, out.PictureSize = mediaSummary(m.Media) + if markup, ok := m.ReplyMarkup.(*tg.ReplyInlineMarkup); ok { + for _, row := range markup.Rows { + buttons := make([]core.Button, len(row.Buttons)) + for i, button := range row.Buttons { + buttons[i] = buttonOf(button) + } + out.Buttons = append(out.Buttons, buttons) + } + } if reply, ok := m.ReplyTo.(*tg.MessageReplyHeader); ok && !reply.ForumTopic { out.ReplyTo = reply.ReplyToMsgID } @@ -38,6 +47,23 @@ func (b *backend) message(raw tg.MessageClass, e tg.Entities) (core.Message, boo return core.Message{}, false } +// buttonOf converts a button of an inline keyboard. A callback button that +// asks for the account's password is left to Telegram's own apps. +func buttonOf(button tg.KeyboardInlineButton) core.Button { + out := core.Button{Text: button.Text} + switch t := button.Type.(type) { + case *tg.InlineButtonTypeCallback: + if !t.RequiresPassword { + out.Kind, out.Value = core.ButtonCallback, string(t.Data) + } + case *tg.InlineButtonTypeURL: + out.Kind, out.Value = core.ButtonURL, t.URL + case *tg.InlineButtonTypeCopy: + out.Kind, out.Value = core.ButtonCopy, t.CopyText + } + return out +} + // author works out who wrote a message. Private chats and channel posts omit // the sender, which is then implied by the chat and the direction. func (b *backend) author(from, chat tg.PeerClass, out bool, e tg.Entities) (int64, string) { diff --git a/internal/tui/settings.go b/internal/tui/settings.go new file mode 100644 index 0000000..21e65bd --- /dev/null +++ b/internal/tui/settings.go @@ -0,0 +1,108 @@ +package tui + +import ( + "runtime" + "slices" + "strings" + + tea "charm.land/bubbletea/v2" +) + +// The settings menu opens with esc from the chat list, as in btop. A change +// shows at once and is saved to config.json. + +// settingsMenu is the open settings menu, sel the highlighted setting. +type settingsMenu struct{ sel int } + +// setting is one line of the settings menu. +type setting struct { + name string + value func(Look) string + // next returns the change that moves the setting from its value in l to + // the next (1) or previous (-1) one. It sets the value outright, so + // saving it over config.json leaves the other settings as they are there. + next func(l Look, delta int) func(*Look) +} + +var settingsItems = []setting{ + {"Theme", func(l Look) string { t, _ := FindTheme(l.Theme); return t.Name }, func(l Look, delta int) func(*Look) { + t, _ := FindTheme(l.Theme) + i := slices.IndexFunc(Themes, func(o Theme) bool { return o.Name == t.Name }) + name := Themes[(i+delta+len(Themes))%len(Themes)].Name + return func(l *Look) { l.Theme = name } + }}, + {"Spacing", func(l Look) string { return map[bool]string{true: "on", false: "off"}[l.Spaced] }, func(l Look, _ int) func(*Look) { + on := !l.Spaced + return func(l *Look) { l.Spaced = on } + }}, + {"Shortcuts", func(l Look) string { return map[bool]string{true: "macOS", false: "PC"}[l.mac()] }, func(l Look, _ int) func(*Look) { + keys := map[bool]string{true: "pc", false: "mac"}[l.mac()] + return func(l *Look) { l.Keys = keys } + }}, +} + +// mac reports whether shortcuts are written the way Mac keyboards label them. +// Over SSH tg runs on another system than the keyboard, so it can be set. +func (l Look) mac() bool { return l.Keys == "mac" || l.Keys == "" && runtime.GOOS == "darwin" } + +// changeSetting moves the highlighted setting by delta, shows it and saves it. +func (m *model) changeSetting(delta int) tea.Cmd { + change := settingsItems[m.settings.sel].next(m.look, delta) + change(&m.look) + t, _ := FindTheme(m.look.Theme) + if t.Name != m.st.theme.Name { + m.st = newStyles(t) + m.paint(&m.input) + m.paint(&m.filter) + // Initials badges are pictures, drawn in the old colors. + for key := range m.images { + if c := m.chat(key.chat); key.msg == 0 && (c == nil || c.PhotoID == 0) { + m.drop(key) + } + } + } + if m.save != nil { + if err := m.save(change); err != nil { + m.status = "the setting is not saved: " + err.Error() + } + } + return m.afterScroll() // spacing changes how many lines there are +} + +// settingsWidth is the width of the settings menu. +const settingsWidth = 30 + +// settingsBox is where the settings menu is drawn: centered, a title line +// above one line per setting. +func (m *model) settingsBox() (x, y, w int) { + w = min(settingsWidth, m.width) + return max(0, (m.width-w)/2), max(0, (m.bodyRows()-1-len(settingsItems))/2), w +} + +// settingsLines renders the settings menu, w cells wide. The highlighted +// setting shows arrows around its value, which change it. +func (m *model) settingsLines(w int) []string { + lines := []string{m.st.menu.Bold(true).Render(fit(" Settings", w))} + for i, s := range settingsItems { + style, value := m.st.menu, " "+s.value(m.look)+" " + if i == m.settings.sel { + style, value = m.st.menuSel, "‹ "+s.value(m.look)+" ›" + } + lines = append(lines, style.Render(spread(" "+s.name, value+" ", w))) + } + return lines +} + +// keyName writes a key the way the keyboard labels it. On a Mac option and +// command are symbols, followed by an upper case letter: "cmd+v" is ⌘V, +// "alt+↑↓" is ⌥↑↓. ctrl stays a word, as on the key. +func (m *model) keyName(key string) string { + if !m.look.mac() { + return key + } + out := strings.NewReplacer("alt+", "⌥", "cmd+", "⌘").Replace(key) + if last := len(out) - 1; out != key && out[last] >= 'a' && out[last] <= 'z' && out[last-1] >= 0x80 { + out = out[:last] + strings.ToUpper(out[last:]) + } + return out +} diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 4da9690..8375fc8 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -67,7 +67,11 @@ type model struct { // graphics is set when the terminal can draw pictures. graphics bool st styles - spaced bool // gaps between messages, see Look + look Look + // save writes a change of the settings menu to config.json, nil when + // there is nowhere to save it. + save func(change func(*Look)) error + settings *settingsMenu // the open settings menu, nil when there is none width, height int focus focus @@ -105,6 +109,9 @@ type model struct { // drafts holds what was typed and not sent in the chats left since. drafts map[int64]string menu *menu // the open context menu, nil when there is none + // presses counts bot buttons pressed, copies and chats opened: only the + // answer to the latest press, in the chat it was made in, is shown. + presses int // images holds the pictures uploaded to the terminal. An entry with ID // 0 is loading, or failed and shows as text. @@ -223,6 +230,13 @@ type ( text string err error } + // pressedMsg is a bot's answer to a pressed button. seq is presses when + // it was pressed. + pressedMsg struct { + seq int + answer core.BotAnswer + err error + } editedMsg struct { chatID int64 id int @@ -237,16 +251,18 @@ type ( type Look struct { Theme string // one of Themes, "" for the default Spaced bool // a gap between messages of different senders or moments + Keys string // "mac" or "pc" shortcut labels, "" for the system's } // Run starts the TUI and blocks until the user quits. account, when not -// empty, is shown so it is clear whose chats these are. -func Run(ctx context.Context, be core.Backend, version, account string, look Look) error { +// empty, is shown so it is clear whose chats these are. save writes changes +// made in the settings menu. +func Run(ctx context.Context, be core.Backend, version, account string, look Look, save func(change func(*Look)) error) error { ctx, cancel := context.WithCancel(ctx) defer cancel() - m := newModel(ctx, be, look.Theme) - m.spaced = look.Spaced + m := newModel(ctx, be, look) + m.save = save m.version, m.account, m.graphics = version, account, termimg.Supported() p := tea.NewProgram(m, tea.WithContext(ctx)) go func() { @@ -272,17 +288,17 @@ func Run(ctx context.Context, be core.Backend, version, account string, look Loo return err } -// newModel sets up an empty model drawn with the named theme. A name that -// is not a theme falls back to the default and says so. -func newModel(ctx context.Context, be core.Backend, theme string) *model { - t, ok := FindTheme(theme) +// newModel sets up an empty model drawn with look. A theme name that is not +// a theme falls back to the default and says so. +func newModel(ctx context.Context, be core.Backend, look Look) *model { + t, ok := FindTheme(look.Theme) m := &model{ - ctx: ctx, be: be, histories: map[int64]*history{}, images: map[imageKey]shown{}, saving: map[int64]int{}, drafts: map[int64]string{}, + ctx: ctx, be: be, look: look, histories: map[int64]*history{}, images: map[imageKey]shown{}, saving: map[int64]int{}, drafts: map[int64]string{}, jobs: make(chan struct{}, 3), freedAt: map[int]time.Time{}, uploading: map[int]bool{}, } m.view, m.leave = context.WithCancel(ctx) if !ok { - m.status = fmt.Sprintf("no theme %q, pick one of %s with `tg config theme `", theme, strings.Join(ThemeNames(), ", ")) + m.status = fmt.Sprintf("no theme %q, pick one of %s with `tg config theme `", look.Theme, strings.Join(ThemeNames(), ", ")) } m.st = newStyles(t) m.input, m.filter = m.newInput("> "), m.newInput("/ ") @@ -293,13 +309,17 @@ func (m *model) newInput(prompt string) textinput.Model { in := textinput.New() in.Prompt = prompt in.SetVirtualCursor(false) - // Every color comes from the theme: the defaults assume a dark terminal. + m.paint(&in) + return in +} + +// paint colors an input with the theme: the defaults assume a dark terminal. +func (m *model) paint(in *textinput.Model) { styles := in.Styles() styles.Focused = textinput.StyleState{Text: m.st.text, Placeholder: m.st.muted, Suggestion: m.st.muted, Prompt: m.st.accent} styles.Blurred = textinput.StyleState{Text: m.st.muted, Placeholder: m.st.muted, Suggestion: m.st.muted, Prompt: m.st.muted} styles.Cursor.Color = m.st.theme.Accent in.SetStyles(styles) - return in } // Init enters the alternate screen before anything else, then loads the @@ -344,6 +364,9 @@ func (m *model) update(msg tea.Msg) tea.Cmd { return m.key(msg) case tea.MouseWheelMsg: + if m.settings != nil { + return nil + } m.menu = nil delta := 1 if msg.Button == tea.MouseWheelUp { @@ -358,6 +381,16 @@ func (m *model) update(msg tea.Msg) tea.Cmd { case tea.MouseClickMsg: lw, _ := m.layout() + if m.settings != nil { + // A click on a setting changes it, anywhere else closes the menu. + x, y, w := m.settingsBox() + if i := msg.Y - y - 1; msg.Button == tea.MouseLeft && i >= 0 && i < len(settingsItems) && msg.X >= x && msg.X < x+w { + m.settings.sel = i + return m.changeSetting(1) + } + m.settings = nil + return nil + } if m.menu != nil { if i := msg.Y - m.menu.y; msg.Button == tea.MouseLeft && i >= 0 && i < len(m.menu.items) && msg.X >= m.menu.x && msg.X < m.menu.x+menuWidth(m.menu.items) { @@ -369,7 +402,7 @@ func (m *model) update(msg tea.Msg) tea.Cmd { return nil } } - if msg.Y < 1 || msg.Y >= m.height-1 { + if msg.Y < 1 || msg.Y >= m.bodyRows() { return nil } if msg.Button == tea.MouseRight { @@ -382,6 +415,9 @@ func (m *model) update(msg tea.Msg) tea.Cmd { return nil } if msg.X >= lw { + if cmd, ok := m.pressAt(msg.X, msg.Y); ok { + return cmd + } return m.setFocus(focusInput) } if k := (msg.Y - 1) / chatStride; (msg.Y-1)%chatStride < 2 && k < m.chatsDrawn() && m.top+k < len(m.visible()) { @@ -444,6 +480,30 @@ func (m *model) update(msg tea.Msg) tea.Cmd { m.scroll = 0 return nil + case pressedMsg: + if msg.seq != m.presses { + return nil // another button or chat since, the answer would be mistaken for its + } + if msg.err != nil { + m.note = "" + if m.status == "" { // an error since, like a failed send, matters more + m.status = "the button failed: " + msg.err.Error() + } + return nil + } + text := strings.Join(strings.Fields(msg.answer.Text), " ") + if msg.answer.URL == "" { + if text != "" { + m.note = text + } + return nil + } + cmd := m.copy(msg.answer.URL, "the bot's link "+msg.answer.URL) + if text != "" { + m.note = text + ", link copied" + } + return cmd + case editedMsg: if m.saving[msg.chatID]--; m.saving[msg.chatID] <= 0 { delete(m.saving, msg.chatID) @@ -601,9 +661,31 @@ func (m *model) key(msg tea.KeyPressMsg) tea.Cmd { key := msg.String() m.status, m.note = "", "" if key == "ctrl+c" { + if m.focus == focusInput && m.composing() { + m.menu = nil + m.clearComposer() + return m.afterScroll() + } return tea.Quit } + if m.settings != nil { + n := len(settingsItems) + switch key { + case "up", "k", "shift+tab": + m.settings.sel = (m.settings.sel + n - 1) % n + case "down", "j", "tab": + m.settings.sel = (m.settings.sel + 1) % n + case "left", "h": + return m.changeSetting(-1) + case "right", "l", "enter", "space": + return m.changeSetting(1) + case "esc", "q": + m.settings = nil + } + return nil + } + if m.menu != nil { n := len(m.menu.items) switch key { @@ -653,6 +735,10 @@ func (m *model) key(msg tea.KeyPressMsg) tea.Cmd { case "/": return m.setFocus(focusFilter) case "esc": + if m.filter.Value() == "" { + m.settings = &settingsMenu{} + return nil + } m.filter.Reset() case "enter", "right", "l": return m.openSelected() @@ -729,6 +815,24 @@ func (m *model) key(msg tea.KeyPressMsg) tea.Cmd { func (m *model) attached() bool { return m.attach.File != "" || m.attach.Photo != nil } +// composing reports whether the composer holds something ctrl+c would clear: +// text, an attachment or an edit. +func (m *model) composing() bool { return m.input.Value() != "" || m.attached() || m.editing != 0 } + +// clearComposer drops what is being written and any attachment. An edit is +// cancelled, which gives back what the composer held before it. A reply +// stays picked. +func (m *model) clearComposer() { + if m.editing != 0 { + m.cancelDraft() + } else { + m.input.Reset() + } + if m.attached() || m.readingClipboard() { + m.setAttach(core.SendRequest{}) // also drops a clipboard read in progress + } +} + // savingNote asks to wait while an edit is saved in the open chat. const savingNote = "saving the edit, a moment" @@ -924,10 +1028,46 @@ func (m *model) openMenu(x, y int) { lw++ // the border } x = max(lw, min(x, m.width-menuWidth(items))) - y = max(0, min(y, m.height-1-len(items))) + y = max(0, min(y, m.bodyRows()-len(items))) m.menu = &menu{msg: msg, items: items, x: x, y: y} } +// pressAt presses the bot button drawn at screen cell x, y, and reports +// whether there is one. +func (m *model) pressAt(x, y int) (tea.Cmd, bool) { + line, msg, ok := m.lineAt(y) + if lw, _ := m.layout(); lw > 0 { + x -= lw + 1 // the chat list and the border + } + if i := slices.IndexFunc(line.keys, func(k key) bool { return x >= k.x && x < k.x+k.w }); ok && i >= 0 { + return m.press(msg, line.keys[i].button), true + } + return nil, false +} + +// press acts on a button of msg's keyboard: a callback goes to the bot, whose +// answer shows in the status line. Links are copied, the terminal may run +// on another machine than the browser. +func (m *model) press(msg core.Message, b core.Button) tea.Cmd { + m.status, m.note = "", "" // what an earlier button left + m.presses++ + seq := m.presses + switch b.Kind { + case core.ButtonCallback: + m.note = "pressed " + strings.Join(strings.Fields(b.Text), " ") + return func() tea.Msg { + answer, err := m.be.Press(m.ctx, msg.ChatID, msg.ID, b.Value) + return pressedMsg{seq, answer, err} + } + case core.ButtonURL: + return m.copy(b.Value, "link "+b.Value) + case core.ButtonCopy: + return m.copy(b.Value, "text") + } + m.status = "this button only works in Telegram's own apps" + return nil +} + // editable reports whether the TUI offers to edit msg: the account sent it // and it has text. Media without a caption, like a sticker, has none. func editable(msg core.Message) bool { return msg.Out && !msg.Service && msg.Text != "" } @@ -956,6 +1096,7 @@ func (m *model) runMenu() tea.Cmd { // copy puts s on the clipboard with OSC 52, which also works over SSH. func (m *model) copy(s, what string) tea.Cmd { m.note = "copied " + what + m.presses++ // a bot's link answered later must not replace it return tea.SetClipboard(s) } @@ -1393,6 +1534,7 @@ func (m *model) openSelected() tea.Cmd { m.drafts[m.openID] = d } m.openID, m.scroll = chatID, 0 + m.presses++ m.replyTo, m.editing, m.stash = 0, 0, nil m.input.Reset() m.input.SetValue(m.drafts[chatID]) diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go index 97555fd..8033e20 100644 --- a/internal/tui/tui_test.go +++ b/internal/tui/tui_test.go @@ -30,7 +30,7 @@ import ( func loaded(t *testing.T, width, height int) *model { t.Helper() be := demo.New() - m := newModel(context.Background(), be, "") + m := newModel(context.Background(), be, Look{}) m.version = "test" chats, err := be.Chats(m.ctx, core.ChatQuery{}) if err != nil { @@ -79,16 +79,19 @@ func upload(m *model, cmd tea.Cmd) { func TestViewFillsTheTerminal(t *testing.T) { for _, size := range [][2]int{{120, 30}, {80, 24}, {72, 10}, {50, 20}, {20, 6}} { m := loaded(t, size[0], size[1]) - for _, state := range []string{"list", "opened", "replying with a menu open"} { + for _, state := range []string{"list", "opened", "replying with a menu open", "settings"} { switch state { case "opened": open(t, m, 1) case "replying with a menu open": m.pickReply(-1) - m.openMenu(m.width-1, m.height-5) // the newest message + m.openMenu(m.width-1, m.height-6) // the newest message if m.menu == nil && size[1] >= 10 { t.Errorf("%v: no menu opened on the newest message", size) } + case "settings": + m.menu = nil + m.settings = &settingsMenu{} } rows := strings.Split(m.View().Content, "\n") if len(rows) != size[1] { @@ -828,7 +831,7 @@ func TestSpacingSetsMessagesApart(t *testing.T) { if n := blanks(); n != 0 { t.Errorf("packed by default, got %d blank lines", n) } - m.spaced = true + m.look.Spaced = true if blanks() == 0 { t.Error("spacing on left no gap between messages") } @@ -980,3 +983,138 @@ func TestHiddenConversationKeepsItsPictures(t *testing.T) { t.Error("the conversation moved while hidden") } } + +// ctrl+c clears what is typed first, and quits only from an empty composer. +func TestCtrlCClearsTheComposerFirst(t *testing.T) { + m := loaded(t, 120, 30) + open(t, m, 1) + m.input.SetValue("half a thought") + m.openMenu(m.width-1, screenRow(m, "backups finished")) // a menu open must not make it quit + if m.menu == nil { + t.Fatal("no menu opened") + } + ctrlC := tea.KeyPressMsg{Code: 'c', Mod: tea.ModCtrl} + if cmd := m.key(ctrlC); cmd != nil { + if _, quit := cmd().(tea.QuitMsg); quit { + t.Fatal("ctrl+c quit with text in the composer") + } + } + if m.input.Value() != "" { + t.Fatalf("composer holds %q", m.input.Value()) + } + if cmd := m.key(ctrlC); cmd == nil { + t.Fatal("ctrl+c did not quit from an empty composer") + } else if _, quit := cmd().(tea.QuitMsg); !quit { + t.Fatal("ctrl+c did not quit from an empty composer") + } +} + +// A setting changes at once, and is saved as a value of its own: the other +// settings in config.json stay as they are there. +func TestSettingsShowAndSaveOneChange(t *testing.T) { + m := loaded(t, 120, 30) + var saved []func(*Look) + m.save = func(change func(*Look)) error { saved = append(saved, change); return nil } + + m.Update(tea.KeyPressMsg{Code: tea.KeyEscape}) + if m.settings == nil || screenRow(m, "Settings") < 0 { + t.Fatal("esc on the chat list did not open the settings") + } + m.Update(tea.KeyPressMsg{Code: tea.KeyRight}) // Theme + if m.look.Theme != "macchiato" || m.st.theme.Name != "macchiato" { + t.Fatalf("theme is %q, drawn with %q", m.look.Theme, m.st.theme.Name) + } + m.Update(tea.KeyPressMsg{Code: tea.KeyDown}) + m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) // Spacing + if !m.look.Spaced { + t.Fatal("spacing did not turn on") + } + + file := Look{Theme: "latte", Keys: "mac"} // changed elsewhere meanwhile + for _, change := range saved { + change(&file) + } + if want := (Look{Theme: "macchiato", Spaced: true, Keys: "mac"}); file != want { + t.Fatalf("config.json holds %+v, want %+v", file, want) + } + m.Update(tea.KeyPressMsg{Code: tea.KeyEscape}) + if m.settings != nil { + t.Fatal("esc did not close the settings") + } +} + +// A bot's inline keyboard is drawn under its message, as part of it. +func TestBotButtonsAreDrawn(t *testing.T) { + for _, width := range []int{120, 72} { + m := loaded(t, width, 30) + open(t, m, slices.IndexFunc(m.visible(), func(c *core.Chat) bool { return c.Title == "BotFather" })) + row := screenRow(m, "@weather_d") // cut short in a narrow pane + if row < 0 || !strings.Contains(ansi.Strip(strings.Split(m.View().Content, "\n")[row]), "@build_d") { + t.Fatalf("width %d: the first row of buttons is not drawn on one line", width) + } + if screenRow(m, "Bot API docs") != row+2 { + t.Fatalf("width %d: the second row of buttons is not below the first", width) + } + if msg, ok := m.messageAt(row); !ok || len(msg.Buttons) == 0 { + t.Fatalf("width %d: the buttons do not belong to their message", width) + } + } + // A calendar row in a narrow pane keeps every date readable. + m := loaded(t, 72, 30) + days := []string{"24", "25", "26", "27", "28", "29", "✅ 30"} + var calendar []core.Button + for _, day := range days { + calendar = append(calendar, core.Button{Text: day}) + } + row := ansi.Strip(m.buttonLines([][]core.Button{calendar}, 26)[0].text) + for _, day := range days { + if !strings.Contains(row, day) { + t.Fatalf("%s is cut from %q", day, row) + } + } +} + +func TestMacKeysUseSymbols(t *testing.T) { + m := loaded(t, 120, 30) + m.look.Keys = "mac" + for key, want := range map[string]string{"cmd+v": "⌘V", "alt+↑↓": "⌥↑↓", "ctrl+c": "ctrl+c", "esc": "esc"} { + if got := m.keyName(key); got != want { + t.Errorf("%s is written %q, want %q", key, got, want) + } + } + m.look.Keys = "pc" + if got := m.keyName("ctrl+v"); got != "ctrl+v" { + t.Errorf("on a PC ctrl+v is written %q", got) + } +} + +// A click on a bot's button presses it and shows the answer, or copies a link. +func TestClickPressesBotButtons(t *testing.T) { + m := loaded(t, 120, 30) + open(t, m, slices.IndexFunc(m.visible(), func(c *core.Chat) bool { return c.Title == "BotFather" })) + click := func(label string) tea.Cmd { + t.Helper() + y := screenRow(m, label) + if y < 0 { + t.Fatalf("%s is not on screen", label) + } + row := ansi.Strip(strings.Split(m.View().Content, "\n")[y]) + x := ansi.StringWidth(row[:strings.Index(row, label)]) + return m.update(tea.MouseClickMsg{X: x, Y: y, Button: tea.MouseLeft}) + } + m.update(click("@build_demo_bot")()) + if m.note != "Editing @build_demo_bot" || m.status != "" { + t.Fatalf("note %q, status %q", m.note, m.status) + } + m.status = "this button only works in Telegram's own apps" // left by an earlier button + click("Bot API docs") + if m.note != "copied link https://core.telegram.org/bots/api" || m.status != "" { + t.Fatalf("a link button left the note %q under the status %q", m.note, m.status) + } + late := click("@weather_demo_bot") + click("Bot API docs") + m.update(late()) + if m.note != "copied link https://core.telegram.org/bots/api" { + t.Fatalf("an answer to an earlier press replaced the note with %q", m.note) + } +} diff --git a/internal/tui/view.go b/internal/tui/view.go index b2e6028..c8a1767 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -3,6 +3,7 @@ package tui import ( "fmt" "path/filepath" + "slices" "strings" "time" "unicode" @@ -35,9 +36,13 @@ const ( chatStride = 2 + chatGap ) +// bodyRows is how many rows the panes take: all but the status line and the +// rule above it. +func (m *model) bodyRows() int { return max(0, m.height-2) } + // chatsDrawn is how many chats fit in the list, possibly none. listRows is // the same at least one, for paging and keeping the selection in view. -func (m *model) chatsDrawn() int { return max(0, (m.height-1)/chatStride) } +func (m *model) chatsDrawn() int { return m.bodyRows() / chatStride } func (m *model) listRows() int { return max(1, m.chatsDrawn()) } @@ -52,7 +57,7 @@ func (m *model) conversationWidth() int { } // The conversation pane is, top to bottom: the title and a gap, the messages, -// a gap, the reply or edit being written when there is one, and the composer. +// a rule, the reply or edit being written when there is one, and the composer. const messagesTop = 2 func (m *model) draftRows() int { @@ -63,7 +68,7 @@ func (m *model) draftRows() int { } // messageRows is how many lines of conversation fit. -func (m *model) messageRows() int { return max(1, m.height-1-messagesTop-m.draftRows()-2) } +func (m *model) messageRows() int { return max(1, m.bodyRows()-messagesTop-m.draftRows()-2) } // shown picks the n lines of conversation that are on screen: lines[start:end], // drawn below pad empty rows. overflow is how many rows at the top of the pane @@ -74,24 +79,30 @@ func (m *model) shown(n int) (start, end, pad, overflow int) { // scrolled must not leave it blank. end = max(0, n-min(m.scroll, max(0, n-view))) start = max(0, end-view) - overflow = max(0, messagesTop+view+m.draftRows()+2-(m.height-1)) + overflow = max(0, messagesTop+view+m.draftRows()+2-m.bodyRows()) return start, end, view - (end - start), overflow } // messageAt is the message drawn on screen row y. func (m *model) messageAt(y int) (core.Message, bool) { + _, msg, ok := m.lineAt(y) + return msg, ok +} + +// lineAt is the line of conversation drawn on screen row y, and its message. +func (m *model) lineAt(y int) (msgLine, core.Message, bool) { h := m.histories[m.openID] _, rw := m.layout() if h == nil || !h.loaded || rw == 0 { - return core.Message{}, false + return msgLine{}, core.Message{}, false } lines := m.messageLines(h, rw) start, end, pad, overflow := m.shown(len(lines)) i := start + y - (messagesTop - overflow) - pad if i < start || i >= end || lines[i].msg < 0 { - return core.Message{}, false + return msgLine{}, core.Message{}, false } - return h.msgs[lines[i].msg], true + return lines[i], h.msgs[lines[i].msg], true } // revealMessage scrolls the conversation so message id is on screen. @@ -135,18 +146,21 @@ func (m *model) View() tea.View { } lw, rw := m.layout() - body := m.height - 1 + body := m.bodyRows() var left, right []string + rule := -1 // the row of the rule above the composer if lw > 0 { left = m.chatList(lw, body) } if rw > 0 { - right = m.conversation(rw, body) + right, rule = m.conversation(rw, body) } rows := make([]string, 0, m.height) for i := range body { switch { + case lw > 0 && rw > 0 && i == rule: + rows = append(rows, left[i]+m.st.border.Render("├")+right[i]) case lw > 0 && rw > 0: rows = append(rows, left[i]+m.st.border.Render("│")+right[i]) case lw > 0: @@ -155,6 +169,14 @@ func (m *model) View() tea.View { rows = append(rows, right[i]) } } + // A rule sets the hints apart from the panes. + if m.height >= 2 { + line := strings.Repeat("─", m.width) + if lw > 0 && rw > 0 { + line = strings.Repeat("─", lw) + "┴" + strings.Repeat("─", rw) + } + rows = append(rows, m.st.border.Render(line)) + } rows = append(rows, m.statusLine()) if m.menu != nil { w := menuWidth(m.menu.items) @@ -168,6 +190,14 @@ func (m *model) View() tea.View { } } } + if m.settings != nil { + x, y, w := m.settingsBox() + for i, line := range m.settingsLines(w) { + if y+i < len(rows) { + rows[y+i] = overlay(rows[y+i], line, x, m.width) + } + } + } v.SetContent(strings.Join(rows, "\n")) // The terminal's own cursor marks the focused input, so nothing blinks @@ -290,8 +320,9 @@ func (m *model) avatar(c *core.Chat) []string { } } -// conversation renders the title, the messages and the composer. -func (m *model) conversation(w, h int) []string { +// conversation renders the title, the messages and the composer, and tells +// which row is the rule above the composer, -1 for none. +func (m *model) conversation(w, h int) ([]string, int) { rows := make([]string, 0, h) c := m.chat(m.openID) hist := m.histories[m.openID] @@ -302,7 +333,7 @@ func (m *model) conversation(w, h int) []string { if h > 2 { rows[h/2] = center(m.st.muted.Render("select a chat and press enter"), w) } - return rows + return rows, -1 } title := " " + m.st.bold.Render(c.Title) @@ -314,7 +345,7 @@ func (m *model) conversation(w, h int) []string { lines := m.messageLines(hist, w) if !hist.loaded { - lines = []msgLine{{m.st.muted.Render(" loading"), -1}} + lines = []msgLine{{text: m.st.muted.Render(" loading"), msg: -1}} } start, end, pad, overflow := m.shown(len(lines)) for range pad { @@ -324,7 +355,8 @@ func (m *model) conversation(w, h int) []string { rows = append(rows, fit(l.text, w)) } - rows = append(rows, strings.Repeat(" ", w)) + rule := len(rows) + rows = append(rows, m.st.border.Render(strings.Repeat("─", w))) if m.draftRows() > 0 { rows = append(rows, m.draftLine(w)) } @@ -346,7 +378,7 @@ func (m *model) conversation(w, h int) []string { m.input.SetWidth(max(1, w-2-ansi.StringWidth(m.input.Prompt))) m.input.SetCursor(m.input.Position()) // SetWidth alone keeps the old visible window rows = append(rows, fit(" "+m.input.View(), w)) - return rows[overflow:] + return rows[overflow:], rule - overflow } // draftLine names the message the composer replies to or edits. @@ -374,10 +406,18 @@ const groupGap = 5 * time.Minute const photoIndent = 7 // msgLine is one line of the conversation, msg is the index of the message -// it belongs to, -1 for date lines. +// it belongs to, -1 for date lines. keys are the bot buttons drawn on it. type msgLine struct { text string msg int + keys []key +} + +// key is a button of a bot's keyboard, drawn w cells wide from cell x of the +// conversation pane. +type key struct { + x, w int + button core.Button } // messageLines lays the history out for a pane of width w: a date line per @@ -396,14 +436,14 @@ func (m *model) messageLines(h *history, w int) []msgLine { byID[msg.ID] = msg if d := msg.Date.Format("Mon 2 Jan 2006"); d != day { - if day != "" && m.spaced { - lines = append(lines, msgLine{"", -1}) + if day != "" && m.look.Spaced { + lines = append(lines, msgLine{text: "", msg: -1}) } day = d - lines = append(lines, msgLine{center(m.st.muted.Render(d), w), -1}) - } else if prev := h.msgs[i-1]; m.spaced && (prev.Out != msg.Out || prev.FromID != msg.FromID || + lines = append(lines, msgLine{text: m.dayLine(d, w), msg: -1}) + } else if prev := h.msgs[i-1]; m.look.Spaced && (prev.Out != msg.Out || prev.FromID != msg.FromID || prev.Service != msg.Service || msg.Date.Sub(prev.Date) > groupGap) { - lines = append(lines, msgLine{"", -1}) + lines = append(lines, msgLine{text: "", msg: -1}) } // The message being replied to or edited is marked in the first @@ -415,7 +455,7 @@ func (m *model) messageLines(h *history, w int) []msgLine { } if ref := byID[msg.ReplyTo]; ref != nil { quote := ansi.Truncate(firstWord(ref.From)+": "+strings.Join(strings.Fields(ref.Preview()), " "), w-indent-3, "…") - lines = append(lines, msgLine{padded + m.st.muted.Render("↪ "+quote), i}) + lines = append(lines, msgLine{text: padded + m.st.muted.Render("↪ "+quote), msg: i}) } name := lipgloss.NewStyle().Foreground(m.st.peer(msg.FromID)).Render(msg.From) @@ -451,33 +491,131 @@ func (m *model) messageLines(h *history, w int) []msgLine { if j == 0 { prefix = mark + m.st.muted.Render(msg.Date.Format("15:04")) + " " } - lines = append(lines, msgLine{prefix + l, i}) + lines = append(lines, msgLine{text: prefix + l, msg: i}) } if pic.id != 0 { for _, l := range termimg.Placeholder(pic.id, pic.cols, pic.rows) { - lines = append(lines, msgLine{padded + l, i}) + lines = append(lines, msgLine{text: padded + l, msg: i}) } } else { for range keptRows { - lines = append(lines, msgLine{padded, i}) + lines = append(lines, msgLine{text: padded, msg: i}) + } + } + for _, l := range m.buttonLines(msg.Buttons, w-indent-1) { + for k := range l.keys { + l.keys[k].x += indent + } + l.text, l.msg = padded+l.text, i + lines = append(lines, l) + } + } + return lines +} + +// buttonCells shares free cells among buttons whose labels are widths wide. +// They are equal when the widest label fits, as Telegram draws them. Else +// each label gets its own width and the rest is shared, so a crowded row stays +// readable, and only labels that cannot all fit are cut short. Spare cells go +// one each to the first buttons. +func buttonCells(widths []int, free int) []int { + k, total := len(widths), 0 + for _, w := range widths { + total += w + } + base, spare := make([]int, k), free + if slices.Max(widths) > free/k && total <= free { + copy(base, widths) + spare = free - total + } + cells := make([]int, k) + for j := range cells { + cells[j] = base[j] + spare/k + if j < spare%k { + cells[j]++ + } + } + return cells +} + +// dayLine is the date that starts a day of messages, centered on a rule. +func (m *model) dayLine(date string, w int) string { + label := " " + date + " " + side := max(0, w-2-ansi.StringWidth(label)) + return fit(" "+m.st.border.Render(strings.Repeat("─", side/2))+m.st.muted.Render(label)+ + m.st.border.Render(strings.Repeat("─", side-side/2)), w) +} + +// buttonLines draws a bot's inline keyboard in at most w cells: every row as +// wide, its buttons sharing it as buttonCells does. A blank line sets rows +// apart, as a blank cell does buttons. Keys are placed from cell 0, and the +// lines belong to no message yet. +func (m *model) buttonLines(keyboard [][]core.Button, w int) []msgLine { + label := func(b core.Button) string { return strings.Join(strings.Fields(b.Text), " ") } + width := 0 + for _, row := range keyboard { + widest := 0 + for _, b := range row { + widest = max(widest, ansi.StringWidth(label(b))) + } + width = max(width, len(row)*(widest+4)-1) + } + width = min(width, w) + var lines []msgLine + for _, row := range keyboard { + if len(row) == 0 || width < 2*len(row)-1 { + continue + } + widths := make([]int, len(row)) + for j, b := range row { + widths[j] = max(1, ansi.StringWidth(label(b))) // a blank one still shows + } + var line strings.Builder + var keys []key + x := 0 + for j, cell := range buttonCells(widths, width-len(row)+1) { // one cell between buttons + line.WriteString(m.st.menu.Render(center(ansi.Truncate(label(row[j]), cell, "…"), cell))) + keys = append(keys, key{x, cell, row[j]}) + x += cell + 1 + if j < len(row)-1 { + line.WriteString(" ") } } + if len(lines) > 0 { + lines = append(lines, msgLine{msg: -1}) + } + lines = append(lines, msgLine{text: line.String(), msg: -1, keys: keys}) } return lines } func (m *model) statusLine() string { // Each hint is a key and what it does. - hints := [][2]string{{"↑↓", "move"}, {"enter", "open"}, {"/", "filter"}, {"tab", "compose"}, {"q", "quit"}} + hints := [][2]string{{"↑↓", "move"}, {"enter", "open"}, {"/", "filter"}, {"tab", "compose"}, {"esc", "settings"}, {"q", "quit"}} + if m.filter.Value() != "" { + hints[4] = [2]string{"esc", "clear filter"} + } + // Both work everywhere, but on a Mac ctrl+arrows switch desktops, and + // the terminal's own paste brings images as ctrl+v does. + reply, paste := "ctrl+↑↓", "ctrl+v" + if m.look.mac() { + reply, paste = "alt+↑↓", "cmd+v" + } + quit := "quit" + if m.composing() { + quit = "clear" + } switch { + case m.settings != nil: + hints = [][2]string{{"↑↓", "move"}, {"←→", "change"}, {"esc", "close"}} case m.menu != nil: hints = [][2]string{{"↑↓", "move"}, {"enter", "pick"}, {"esc", "close"}} case m.focus == focusInput && m.editing != 0: hints = [][2]string{{"esc", "cancel"}} case m.focus == focusInput && m.replyTo != 0: - hints = [][2]string{{"ctrl+↑↓", "pick"}, {"esc", "cancel"}} + hints = [][2]string{{reply, "pick"}, {"esc", "cancel"}} case m.focus == focusInput: - hints = [][2]string{{"ctrl+↑↓", "reply"}, {"↑", "edit last"}, {"right click", "more"}, {"ctrl+v", "paste image"}, {"esc", "chats"}, {"pgup/pgdn", "scroll"}, {"ctrl+c", "quit"}} + hints = [][2]string{{reply, "reply"}, {"↑", "edit last"}, {"right click", "more"}, {paste, "paste image"}, {"esc", "chats"}, {"pgup/pgdn", "scroll"}, {"ctrl+c", quit}} if m.attached() { hints[3] = [2]string{"backspace", "remove attachment"} } @@ -501,7 +639,7 @@ func (m *model) statusLine() string { var help strings.Builder room := m.width - ansi.StringWidth(right) - 2 for _, h := range hints { - hint := " " + m.st.key.Render(h[0]) + " " + m.st.dim.Render(h[1]) + " " + hint := " " + m.st.key.Render(m.keyName(h[0])) + " " + m.st.dim.Render(h[1]) + " " if room -= ansi.StringWidth(hint); room < 0 { break }