use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use anyhow::Result;
use crossterm::event::{
Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
MouseEventKind,
};
use futures::StreamExt;
use ratatui::style::Style;
use ratatui_textarea::{DataCursor, TextArea};
use tdlib_rs::enums::{
AuthenticationCodeType, AuthorizationState, ChatMemberStatus, ConnectionState, MessageContent,
MessageReplyTo, MessageSender, MessageTopic, NotificationType, OptionValue, ProxyType, Update,
UserType,
};
use tdlib_rs::types::{ForumTopic, ForumTopics, Message, Proxy, UpdateNotificationGroup};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use tokio::time::{Instant, sleep_until};
use crate::attach::{self, Attachment, Dropped};
use crate::buttons::{ButtonMenu, Press};
use crate::chats::{Badge, Chats, List, Peer, Presence};
use crate::chime::{self, Sounds, Stamp};
use crate::clipboard::{Clipboard, ClipboardEvent, Copied, Decoded, Paste, Pasted};
use crate::complete::{self, Commands, Completion, Kind, Suggestion};
use crate::config::{self, ApiKeys};
use crate::draft::{self, Draft};
use crate::images::{self, ImageEvent, Images};
use crate::info::ChatInfo;
use crate::lang;
use crate::messages::{
Editable, Editing, Link, MediaFile, OpenChat, Replied, SendState, Sender, link_host, one_line,
web_url,
};
use crate::motion::{self, Motion};
use crate::notify::{self, Note, Notifications, Notifier};
use crate::picker::{self, ChatPicker, Choice, Purpose};
use crate::pins::{PinMenu, Pinned, PinnedMenu, Place};
use crate::poll::{PollDraft, PollFlags, PollStep, Vote, VoteMenu};
use crate::proxy;
use crate::reactions::{self, ReactMenu, ReactionKind};
use crate::record::{Recorder, Take};
use crate::schedule;
use crate::search::{self, MediaMenu, MessageSearch, Who};
use crate::secret::{KeyView, Secret, SecretState, TimerMenu};
use crate::select::{self, TextSelect};
use crate::settings::{self, Settings, Side, VideoNoteSize};
use crate::stickers::{self, Source, StickerPanel};
use crate::term::Terminal;
use crate::text;
use crate::tg::{Deletable, EditText, Found, Invite, Mentions, Missed, Page, Tagged, Tg, TgEvent};
use crate::theme::{Colors, Corners, Themes};
use crate::tmux;
use crate::topics::{self, Forum};
use crate::ui;
use crate::video::{Inline, VideoEvent, VideoView};
use crate::viewer::{self, PhotoView};
use crate::voice::{Happened, Player, VoiceEvent};
const CHAT_PAGE: i32 = 50;
const HISTORY_PAGE: i32 = 50;
const SEARCH_PAGE: i32 = 50;
const MEDIA_ROWS_MAX: usize = 500;
const MIN_LOADED: usize = 30;
const LOAD_AHEAD: usize = 10;
const HALF_PAGE: isize = 10;
const WHEEL_LINES: isize = 3;
const CLOSE_TIMEOUT: Duration = Duration::from_secs(3);
const TOAST_TIME: Duration = Duration::from_secs(2);
const CONFIRM_GRACE: Duration = Duration::from_millis(500);
const IDLE_AFTER: Duration = Duration::from_secs(60);
const AWAY_AFTER: Duration = Duration::from_secs(5 * 60);
const TMUX_SETTLE: Duration = Duration::from_millis(300);
const TYPING_EVERY: Duration = Duration::from_secs(5);
const RING_GAP: Duration = Duration::from_secs(1);
#[derive(Clone, Copy, PartialEq, Eq)]
enum KeySource {
Env,
Saved,
BuiltIn,
}
enum ProxyChange {
Start,
Set(Option<String>),
}
pub enum Screen {
Login(Box<Login>),
Main,
}
pub enum LoginStep {
Connecting,
LoggingOut,
ApiId,
ApiHash {
id: i32,
},
Phone,
Code {
sent_via: &'static str,
},
Password {
hint: String,
},
Email,
EmailCode,
OtherDevice {
link: String,
},
Unsupported(&'static str),
BadProxy {
from: &'static str,
why: String,
},
}
pub struct Login {
pub step: LoginStep,
pub input: TextArea<'static>,
pub error: Option<String>,
pub busy: bool,
}
impl Login {
pub fn new(step: LoginStep) -> Self {
let mut input = TextArea::default();
input.set_cursor_line_style(Style::default());
if let LoginStep::Password { .. } = step {
input.set_mask_char('•');
}
Self {
step,
input,
error: None,
busy: false,
}
}
pub fn takes_input(&self) -> bool {
!matches!(
self.step,
LoginStep::Connecting
| LoginStep::LoggingOut
| LoginStep::OtherDevice { .. }
| LoginStep::Unsupported(_)
| LoginStep::BadProxy { .. }
)
}
}
pub enum Target {
File(MediaFile),
Voice {
message_id: i64,
file: MediaFile,
},
Photo {
message_id: i64,
file: MediaFile,
},
Video {
message_id: i64,
file: MediaFile,
},
Link(Link),
Text(String),
}
impl Target {
pub fn label(&self) -> &str {
match self {
Target::File(file)
| Target::Voice { file, .. }
| Target::Photo { file, .. }
| Target::Video { file, .. } => &file.label,
Target::Link(link) => &link.url,
Target::Text(_) => lang::t("Whole message"),
}
}
}
pub struct Confirm {
pub title: String,
pub lines: Vec<String>,
pub site: Option<Site>,
pub badge: Option<Badge>,
pub action: Confirmed,
pub shown: Instant,
}
impl Confirm {
pub fn new(title: impl Into<String>, lines: Vec<String>, action: Confirmed) -> Self {
Self {
title: title.into(),
lines,
site: None,
badge: None,
action,
shown: Instant::now(),
}
}
}
pub struct Site {
pub label: &'static str,
pub host: String,
}
impl Site {
pub fn link(host: String) -> Self {
Self {
label: lang::t("It goes to:"),
host,
}
}
pub fn server(address: String) -> Self {
Self {
label: lang::t("Server:"),
host: address,
}
}
}
pub struct Recording {
recorder: Recorder,
chat_id: i64,
topic: Option<i32>,
}
impl Recording {
pub fn duration(&self) -> std::time::Duration {
self.recorder.duration()
}
}
pub enum Confirmed {
OpenFile(String),
OpenLink(String),
Edit {
id: i64,
text: String,
},
Join {
chat_id: i64,
channel: bool,
},
JoinLink {
link: String,
request: String,
channel: bool,
},
Leave(i64),
ReadChat {
chat_id: i64,
topic: Option<i32>,
},
ReadForum {
chat_id: i64,
},
Logout,
StartSecret {
user_id: i64,
with: String,
},
EndSecret {
chat_id: i64,
secret_id: i32,
},
UseProxy(String),
NoProxy,
Voice {
chat_id: i64,
topic: Option<i32>,
take: Take,
},
}
impl Confirmed {
pub fn verb(&self) -> &'static str {
match self {
Confirmed::OpenFile(_) | Confirmed::OpenLink(_) => lang::t("open"),
Confirmed::Edit { .. } => lang::t("edit"),
Confirmed::Join { channel: true, .. } | Confirmed::JoinLink { channel: true, .. } => {
lang::tc("channel", "join")
}
Confirmed::Join { .. } | Confirmed::JoinLink { .. } => lang::t("join"),
Confirmed::Leave(_) => lang::t("leave"),
Confirmed::ReadChat { .. } | Confirmed::ReadForum { .. } => lang::t("mark it read"),
Confirmed::Logout => lang::t("log out"),
Confirmed::StartSecret { .. } => lang::t("start it"),
Confirmed::EndSecret { .. } => lang::t("end it"),
Confirmed::UseProxy(_) => lang::t("use it"),
Confirmed::NoProxy => lang::t("connect directly"),
Confirmed::Voice { .. } => lang::t("send"),
}
}
}
const SAFE_TO_OPEN: &[&str] = &[
"jpg", "jpeg", "png", "gif", "webp", "heic", "heif", "avif", "bmp", "tif", "tiff", "mp4",
"m4v", "mov", "mkv", "webm", "avi", "3gp", "mpg", "mpeg", "mp3", "m4a", "aac", "ogg", "oga",
"opus", "wav", "flac", "pdf", "txt", "md", "epub", "docx", "xlsx", "pptx", "odt", "ods", "odp",
"zip", "rar", "7z", "tar", "gz", "tgz",
];
fn opens_once(msg: &crate::messages::Msg) -> bool {
msg.destruct.is_some_and(|d| d.on_open)
}
fn posts_in_channel(status: &ChatMemberStatus) -> bool {
match status {
ChatMemberStatus::Creator(_) => true,
ChatMemberStatus::Administrator(admin) => admin.rights.can_post_messages,
_ => false,
}
}
pub(crate) fn openable_file(msg: &crate::messages::Msg) -> Option<&MediaFile> {
msg.file
.as_ref()
.filter(|_| !opens_once(msg) || msg.voice.is_some())
}
fn file_target(id: i64, msg: &crate::messages::Msg, file: MediaFile) -> Target {
if msg.voice.as_ref().is_some_and(|v| v.file_id == file.id) {
Target::Voice {
message_id: id,
file,
}
} else if msg.photo.as_ref().is_some_and(|p| p.file_id == file.id) {
Target::Photo {
message_id: id,
file,
}
} else if msg.video.as_ref().is_some_and(|v| v.file_id == file.id) {
Target::Video {
message_id: id,
file,
}
} else {
Target::File(file)
}
}
fn safe_to_open(path: &str) -> bool {
Path::new(path)
.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| SAFE_TO_OPEN.contains(&e.to_ascii_lowercase().as_str()))
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum MenuAction {
Open,
Copy,
}
pub struct PickMenu {
pub action: MenuAction,
pub targets: Vec<Target>,
pub selected: usize,
}
pub struct Notice {
pub title: String,
pub text: String,
}
pub struct Toast {
pub title: String,
pub detail: String,
pub shown: Instant,
pub until: Instant,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DeleteChoice {
Everyone,
OnlyMe,
}
impl DeleteChoice {
pub fn label(self) -> &'static str {
match self {
DeleteChoice::Everyone => lang::t("Delete for everyone"),
DeleteChoice::OnlyMe => lang::t("Delete for me"),
}
}
}
pub struct DeleteMenu {
pub message_id: i64,
pub snippet: String,
pub choices: Vec<DeleteChoice>,
pub selected: usize,
}
impl DeleteMenu {
pub fn set_allowed(&mut self, deletable: Deletable) {
self.choices = [
(deletable.for_everyone, DeleteChoice::Everyone),
(deletable.for_me, DeleteChoice::OnlyMe),
]
.into_iter()
.filter_map(|(allowed, choice)| allowed.then_some(choice))
.collect();
self.selected = self
.choices
.iter()
.position(|&c| c == DeleteChoice::OnlyMe)
.unwrap_or(0);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HelpTab {
Shortcuts,
Settings,
}
pub struct SettingsMenu {
pub tab: HelpTab,
pub scroll: usize,
pub selected: usize,
pub settings_scroll: usize,
pub saved_notifications: Notifications,
pub drawn: crate::mouse::Popup,
}
impl SettingsMenu {
pub const LANGUAGE: usize = 0;
pub const NOTIFICATIONS: usize = Self::LANGUAGE + crate::lang::Lang::ALL.len();
pub const CHAT_GAPS: usize = Self::NOTIFICATIONS + 1;
pub const LIST_RIGHT: usize = Self::CHAT_GAPS + 1;
pub const BLOCK_GAPS: usize = Self::LIST_RIGHT + 1;
pub const VIDEO_SIZE: usize = Self::BLOCK_GAPS + 1;
pub const CORNERS: usize = Self::VIDEO_SIZE + 1;
pub const PILLS: usize = Self::CORNERS + 1;
pub const ANIMATIONS: usize = Self::PILLS + 1;
pub const AFTER_SEND: usize = Self::ANIMATIONS + 1;
pub const WRAP_COMPOSER: usize = Self::AFTER_SEND + 1;
pub const SECRET_CHATS: usize = Self::WRAP_COMPOSER + 1;
pub const SOUND_FOCUSED: usize = Self::SECRET_CHATS + 1;
pub const SOUNDS: usize = Self::SOUND_FOCUSED + 1;
pub fn themes(sounds: &Sounds) -> usize {
Self::SOUNDS + 1 + sounds.list.len()
}
pub fn new(tab: HelpTab, settings: &Settings) -> Self {
Self {
tab,
scroll: 0,
selected: 0,
settings_scroll: 0,
saved_notifications: settings.notifications,
drawn: crate::mouse::Popup::default(),
}
}
}
const MAX_JUMPS: usize = 100;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Jump {
pub chat_id: i64,
pub topic: Option<i32>,
pub message_id: Option<i64>,
}
#[derive(Default)]
pub struct Jumps {
back: Vec<Jump>,
forward: Vec<Jump>,
}
impl Jumps {
pub fn leave(&mut self, from: Jump) {
self.forward.clear();
if self.back.last() != Some(&from) {
self.back.push(from);
}
if self.back.len() > MAX_JUMPS {
self.back.remove(0);
}
}
fn go(&mut self, back: bool, here: Option<Jump>) -> Option<Jump> {
let (from, to) = if back {
(&mut self.back, &mut self.forward)
} else {
(&mut self.forward, &mut self.back)
};
let next = from.pop()?;
to.extend(here);
Some(next)
}
pub fn can_go_back(&self) -> bool {
!self.back.is_empty()
}
pub fn can_go_forward(&self) -> bool {
!self.forward.is_empty()
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PromptKind {
Chats,
Messages,
Command,
Attach,
Proxy,
Schedule,
Poll(PollStep),
}
pub struct Prompt {
pub kind: PromptKind,
pub input: TextArea<'static>,
pub completions: Vec<String>,
pub tabbed: Option<(String, usize)>,
previous_filter: String,
previous_selected: Option<i64>,
poll: Option<PollDraft>,
}
impl Prompt {
pub fn query(&self) -> String {
self.input.lines().concat()
}
fn typed(&self) -> String {
match &self.tabbed {
Some((typed, _)) => typed.clone(),
None => self.query(),
}
}
fn tab(&mut self, step: isize, typed: String, options: Vec<String>) {
let at = self.tabbed.take().map(|(_, at)| at);
let count = options.len() as isize;
if count == 0 {
return;
}
let next = match at {
Some(at) => (at as isize + step).rem_euclid(count),
None if step > 0 => 0,
None => count - 1,
} as usize;
self.input = prompt_input(&options[next]);
self.tabbed = Some((typed, next));
}
fn complete_command(&mut self, step: isize) {
let typed = self.typed();
let options = Command::ALL
.into_iter()
.map(Command::name)
.filter(|name| name.starts_with(typed.trim()))
.map(String::from)
.collect();
self.tab(step, typed, options);
}
}
pub struct Finding {
pub request: String,
pub link: Option<Link>,
}
impl Finding {
fn new(request: &str) -> Self {
Self {
request: request.to_string(),
link: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Command {
Info,
Key,
Leave,
Logout,
Poll,
Proxy,
Schedule,
Secret,
Timer,
}
impl Command {
pub const ALL: [Command; 9] = [
Command::Info,
Command::Key,
Command::Leave,
Command::Logout,
Command::Poll,
Command::Proxy,
Command::Schedule,
Command::Secret,
Command::Timer,
];
pub fn name(self) -> &'static str {
match self {
Command::Info => "info",
Command::Key => "key",
Command::Leave => "leave",
Command::Logout => "logout",
Command::Poll => "poll",
Command::Proxy => "proxy",
Command::Schedule => "schedule",
Command::Secret => "secret",
Command::Timer => "timer",
}
}
pub fn about(self) -> &'static str {
match self {
Command::Info => lang::t("Show what this chat is, and who's in it (also I)"),
Command::Key => lang::t("Show a secret chat's key, to compare with the other person's"),
Command::Leave => {
lang::t("Leave this group or channel, or end a secret chat (asks first)")
}
Command::Logout => lang::t("Log out of Telegram on this computer (asks first)"),
Command::Poll => lang::t("Make a poll in this chat: question, answers, flags"),
Command::Proxy => {
lang::t("Connect through a proxy where Telegram is blocked, or directly")
}
Command::Schedule => lang::t("Send what's written later, at a time you set"),
Command::Secret => lang::t("Start a secret chat with this person (asks first)"),
Command::Timer => lang::t("Set how long messages in a secret chat last once seen"),
}
}
pub fn parse(text: &str) -> Option<Command> {
Command::ALL.into_iter().find(|c| c.name() == text)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Resizing {
List,
Topics,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Focus {
Chats,
Topics,
Messages,
Input,
}
pub struct ForumRead {
pub chat_id: i64,
page: Option<(u32, topics::Offset)>,
topics: HashSet<(i64, i32)>,
waiting: VecDeque<i32>,
}
const FORUM_READ_ASKS: usize = 8;
#[derive(Debug, PartialEq)]
enum TopicRead {
Now(i64),
Done,
Ask,
}
fn topic_read(unread: i32, newest: Option<i64>, read_up_to: i64) -> TopicRead {
match newest {
Some(newest) if unread > 0 => TopicRead::Now(newest),
Some(newest) if read_up_to >= newest => TopicRead::Done,
_ => TopicRead::Ask,
}
}
pub struct App {
tg: Tg,
pub screen: Screen,
pub focus: Focus,
pub chats: Chats,
pub users: HashMap<i64, String>,
pub selected: Option<i64>,
pub open: Option<OpenChat>,
pub forum: Option<Forum>,
read_forum: Option<ForumRead>,
pub composer: TextArea<'static>,
pub images: Images,
pub player: Player,
pub recording: Option<Recording>,
pub opening: HashSet<i32>,
pub revealing: HashSet<i32>,
clipboard: Clipboard,
pub copying: HashMap<i32, MediaFile>,
pub pasting: bool,
pub toast: Option<Toast>,
pub menu: Option<PickMenu>,
pub delete_menu: Option<DeleteMenu>,
pub react_menu: Option<ReactMenu>,
pub vote_menu: Option<VoteMenu>,
pub button_menu: Option<ButtonMenu>,
pub notice: Option<Notice>,
pub pin_menu: Option<PinMenu>,
pub pinned_menu: Option<PinnedMenu>,
pub media_menu: Option<MediaMenu>,
pub media_columns: usize,
pub timer_menu: Option<TimerMenu>,
pub key_view: Option<KeyView>,
pub photo_view: Option<PhotoView>,
pub video_view: Option<VideoView>,
pub inline_video: Option<Inline>,
pub mouse: crate::mouse::Map,
video_tx: UnboundedSender<VideoEvent>,
pub chat_info: Option<ChatInfo>,
pub text_select: Option<TextSelect>,
pub picker: Option<ChatPicker>,
pub finding: Option<Finding>,
pub completion: Option<Completion>,
pub stickers: Option<StickerPanel>,
pub resizing: Option<Resizing>,
pub confirm: Option<Confirm>,
pub settings: Settings,
settings_path: PathBuf,
pub themes: Themes,
pub sounds: Sounds,
sound: Option<Arc<[i16]>>,
sound_stamp: Option<Stamp>,
rang_at: Option<Instant>,
pub over_ssh: bool,
pub pepper: Option<PathBuf>,
pub colors: Colors,
pub rounded: bool,
premium: bool,
env_keys: Option<ApiKeys>,
keys_source: Option<KeySource>,
built_in_rejected: bool,
pub settings_menu: Option<SettingsMenu>,
pub prompt: Option<Prompt>,
topics_asked: u32,
loading_lists: HashSet<List>,
loaded_lists: HashSet<List>,
wanted_lists: HashSet<List>,
pub jumps: Jumps,
pub status: Option<String>,
pub connection: Option<&'static str>,
proxy_changes: BTreeMap<u64, ProxyChange>,
pending_g: bool,
pub quit_deadline: Option<Instant>,
terminal_focused: bool,
focus_reported: bool,
last_input: Instant,
last_input_wall: SystemTime,
online: bool,
typing: Option<((i64, Option<i32>), Instant)>,
notifier: Notifier,
notify_with: Notifications,
in_tmux: bool,
tmux_clients: Option<BTreeSet<String>>,
tmux_check_at: Option<Instant>,
notifications_sent: u64,
notify_since: i32,
unread_chats: i32,
shown_viewing: Option<i64>,
shown_in_viewer: Option<(i32, Option<usize>, (u32, u32))>,
shown_media_grid: Option<(usize, usize)>,
cells_resized: bool,
pub motion: Motion,
relogin: bool,
exit: bool,
}
impl App {
#[allow(clippy::too_many_arguments)]
pub fn new(
tg: Tg,
images: Images,
player: Player,
clipboard: Clipboard,
settings: Settings,
settings_path: PathBuf,
env_keys: Option<ApiKeys>,
video_tx: UnboundedSender<VideoEvent>,
) -> Self {
let over_ssh = chime::over_ssh(|name| std::env::var(name).ok());
crate::lang::set(settings.lang());
let mut chats = Chats::default();
chats.set_highlighted(&settings.highlighted_chats);
let notify_with = settings
.notifications
.resolve(|name| std::env::var(name).ok());
let rounded = settings.corners.rounded(|name| std::env::var(name).ok());
let mut app = Self {
tg,
screen: login_screen(LoginStep::Connecting),
focus: Focus::Chats,
chats,
users: HashMap::new(),
selected: None,
open: None,
forum: None,
read_forum: None,
composer: new_composer(),
images,
player,
recording: None,
opening: HashSet::new(),
revealing: HashSet::new(),
clipboard,
copying: HashMap::new(),
pasting: false,
toast: None,
menu: None,
delete_menu: None,
react_menu: None,
vote_menu: None,
button_menu: None,
notice: None,
pin_menu: None,
pinned_menu: None,
media_menu: None,
media_columns: search::GRID_DEFAULT_COLUMNS,
timer_menu: None,
key_view: None,
photo_view: None,
video_view: None,
inline_video: None,
mouse: crate::mouse::Map::default(),
video_tx,
chat_info: None,
text_select: None,
picker: None,
finding: None,
completion: None,
stickers: None,
resizing: None,
confirm: None,
settings,
themes: Themes::load(&settings_path.with_file_name("themes")),
sounds: Sounds::load(&settings_path.with_file_name("sounds")),
sound: None,
sound_stamp: None,
rang_at: None,
over_ssh,
pepper: (!cfg!(test) && !over_ssh)
.then(crate::pepper::player)
.flatten(),
settings_path,
colors: Colors::default(),
rounded,
premium: false,
env_keys,
keys_source: None,
built_in_rejected: false,
settings_menu: None,
prompt: None,
topics_asked: 0,
loading_lists: HashSet::new(),
loaded_lists: HashSet::new(),
wanted_lists: HashSet::new(),
jumps: Jumps::default(),
status: config::dotenv_ignored()
.then(|| lang::t("./.env is ignored: only development builds read it").into()),
connection: None,
pending_g: false,
quit_deadline: None,
terminal_focused: true,
focus_reported: false,
last_input: Instant::now(),
last_input_wall: SystemTime::now(),
online: false,
typing: None,
notifier: Notifier::default(),
notify_with,
in_tmux: std::env::var_os("TMUX").is_some(),
tmux_clients: None,
tmux_check_at: None,
notifications_sent: 0,
notify_since: i32::MAX,
unread_chats: 0,
shown_viewing: None,
shown_in_viewer: None,
shown_media_grid: None,
cells_resized: false,
motion: Motion::default(),
relogin: false,
proxy_changes: BTreeMap::new(),
exit: false,
};
app.use_saved_theme();
app.use_saved_sound();
crate::record::clean_stale(&app.outbox(), SystemTime::now());
app
}
fn use_saved_theme(&mut self) {
match self.themes.colors(&self.settings.theme) {
Ok(colors) => self.colors = colors,
Err(e) => {
self.colors = Colors::default();
self.status = Some(format!("{}{e}", lang::t("Theme not used: ")));
}
}
}
fn use_saved_sound(&mut self) {
let Some(id) = &self.settings.notification_sound else {
(self.sound, self.sound_stamp) = (None, None);
return;
};
let stamp = self.sounds.stamp(id);
if self.sound.is_some() && stamp.is_some() && stamp == self.sound_stamp {
return;
}
(self.sound, self.sound_stamp) = (None, None);
match self.sounds.samples(id) {
Ok(samples) => (self.sound, self.sound_stamp) = (Some(samples), stamp),
Err(e) => self.status = Some(format!("{}{e}", lang::t("Sound not used: "))),
}
}
pub async fn run(
mut self,
terminal: &mut Terminal,
mut events: UnboundedReceiver<Tagged>,
mut image_events: UnboundedReceiver<ImageEvent>,
mut clipboard: UnboundedReceiver<ClipboardEvent>,
mut voice_events: UnboundedReceiver<VoiceEvent>,
mut video_events: UnboundedReceiver<VideoEvent>,
) -> Result<()> {
let mut keys =
EventStream::new().filter(|event| futures::future::ready(!mouse_moved(event)));
let mut signals = quit_signals();
let mut failed: Option<anyhow::Error> = None;
if self.in_tmux && self.images.kitty() {
self.tmux_clients = tmux::clients();
}
std::thread::spawn(|| crate::video::ffmpeg().is_some());
while !self.exit {
if self
.toast
.as_ref()
.is_some_and(|t| t.until <= Instant::now())
{
self.toast = None;
}
self.chats.refresh();
if self
.selected
.is_none_or(|id| !self.chats.ids().contains(&id))
{
self.selected = self.chats.ids().first().copied();
}
self.cover_unseen();
let viewing = self.open.as_ref().and_then(|o| o.viewing);
let in_viewer = self.photo_view.as_ref().map(|v| {
let photo = self.images.measured_photo(&v.photo);
(v.photo.file_id, v.zoom, (photo.width, photo.height))
});
let media_grid = self
.media_menu
.as_ref()
.filter(|m| m.wants_grid() && self.images.draws_photos())
.map(|m| (m.selected / m.grid_page.max(1), self.media_columns));
if ((self.shown_viewing.is_some() && viewing != self.shown_viewing)
|| in_viewer != self.shown_in_viewer
|| media_grid != self.shown_media_grid)
&& self.images.paints_over()
{
let _ = terminal.clear();
}
self.shown_viewing = viewing;
self.shown_in_viewer = in_viewer;
self.shown_media_grid = media_grid;
if std::mem::take(&mut self.cells_resized) {
let _ = terminal.clear();
}
self.mark_seen();
self.update_online();
self.send_notification();
if let Some(query) = self
.picker
.as_mut()
.and_then(|p| p.due_search(Instant::now()))
{
self.tg.find_chats(query);
}
if let Some(open) = &self.open
&& let Some(query) = self
.completion
.as_mut()
.and_then(|c| c.due_search(Instant::now()))
{
self.tg.find_members(open.chat_id, query);
}
if self.tmux_check_at.is_some_and(|at| at <= Instant::now()) {
self.tmux_check_at = None;
if self.tmux_client_came() && self.images.terminal_changed() {
self.cells_resized = true;
}
}
if failed.is_none() {
self.images.send_deletions(terminal);
self.images.prime_transmits(terminal);
}
if let Some(inline) = self.inline_video.as_mut() {
inline.seen = false;
}
self.update_sticker_focus();
if failed.is_none()
&& let Err(e) = terminal.draw(|frame| ui::draw(frame, &mut self))
{
failed = Some(e.into());
self.hang_up();
}
if failed.is_none() {
self.images.send_pictures(terminal);
}
if failed.is_none()
&& let Some(view) = self.video_view.as_mut()
{
if let Some(why) = view.error.take() {
self.status = Some(format!(
"{}{why}",
lang::t("Can't play this video message: ")
));
self.video_view = None;
} else {
view.send_frame(terminal);
}
}
if failed.is_none() && self.inline_video.is_some() {
let (seen, started) = self
.inline_video
.as_ref()
.map_or((false, false), |i| (i.seen, i.started()));
if seen {
if let Some(inline) = self.inline_video.as_mut() {
inline.resume();
inline.send_frame(terminal);
}
} else if started && !self.inline_video.as_mut().is_some_and(Inline::stop_unseen) {
self.inline_video = None;
}
}
self.images.fetch(&self.tg);
if let Some(open) = self.open.as_mut() {
for id in open.missing_replied() {
self.tg.get_replied_message(open.chat_id, id);
}
}
let deadline = self.quit_deadline;
let countdown = self
.open
.as_ref()
.and_then(|o| o.next_tick(SystemTime::now()))
.map(|left| Instant::now() + left);
let playing = self.player.next_tick().map(|soon| Instant::now() + soon);
let recording = self
.recording
.as_ref()
.map(|_| Instant::now() + Duration::from_millis(500));
let open = self.open.as_ref().map(|o| o.chat_id);
let moving = self.motion.next_frame(Instant::now(), open);
let sliding = self
.toast
.as_ref()
.filter(|_| self.slides_toast())
.and_then(|t| motion::toast_frame(t.shown, t.until, Instant::now()));
let away = self
.open
.as_ref()
.filter(|o| o.viewing.is_some())
.map(|_| self.last_input + self.away_after());
let wake = [
countdown,
playing,
recording,
moving,
sliding,
away,
self.toast.as_ref().map(|t| t.until),
self.online.then_some(self.last_input + IDLE_AFTER),
self.notifier.next_at(),
self.picker.as_ref().and_then(ChatPicker::search_at),
self.completion.as_ref().and_then(Completion::search_at),
self.tmux_check_at,
]
.into_iter()
.flatten()
.min();
tokio::select! {
Some(event) = events.recv() => {
self.on_tagged(event);
while let Ok(event) = events.try_recv() {
self.on_tagged(event);
}
}
Some(event) = image_events.recv() => self.images.on_built(event),
Some(event) = clipboard.recv() => self.on_clipboard(event),
Some(event) = voice_events.recv() => self.on_voice(event),
Some(event) = video_events.recv() => self.on_video(event),
Some(event) = keys.next(), if failed.is_none() => match event {
Ok(event) => self.on_terminal_event(event),
Err(e) => {
failed = Some(e.into());
self.hang_up();
}
},
Some(()) = signals.recv() => self.hang_up(),
_ = sleep_until(deadline.unwrap_or_else(Instant::now)), if deadline.is_some() => break,
_ = sleep_until(wake.unwrap_or_else(Instant::now)), if wake.is_some() => {}
else => break,
}
if let Some(why) = self.recording.as_ref().and_then(|r| r.recorder.failed()) {
self.recording = None;
self.status = Some(format!("{}{why}", lang::t("Can't record: ")));
}
}
self.images.drop_all();
if failed.is_none() {
self.images.send_deletions(terminal);
}
match failed {
Some(e) => Err(e),
None => Ok(()),
}
}
fn hang_up(&mut self) {
self.terminal_focused = false;
self.focus_reported = true;
if self.quit_deadline.is_none() {
self.quit();
}
}
fn tmux_client_came(&mut self) -> bool {
if !self.in_tmux || !self.images.kitty() {
return false;
}
let Some(now) = tmux::clients() else {
return false;
};
let came = tmux::newcomer(self.tmux_clients.as_ref(), &now);
self.tmux_clients = Some(now);
came
}
fn on_terminal_event(&mut self, event: Event) {
if matches!(
event,
Event::Key(_) | Event::Paste(_) | Event::FocusGained | Event::Mouse(_)
) {
self.last_input = Instant::now();
self.last_input_wall = SystemTime::now();
}
if matches!(event, Event::Resize(..) | Event::FocusGained)
&& self.images.measured(images::measure_cells())
{
self.cells_resized = true;
}
if self.in_tmux && self.images.kitty() {
match event {
Event::Resize(..) | Event::FocusGained => {
self.tmux_check_at = Some(Instant::now() + TMUX_SETTLE);
}
Event::FocusLost => self.tmux_check_at = Some(Instant::now()),
_ => {}
}
}
match event {
Event::Key(key) => self.on_key(key),
Event::Mouse(mouse) => self.on_mouse(mouse),
Event::FocusGained => {
self.terminal_focused = true;
self.focus_reported = true;
self.notifier.clear();
if self.settings.animations
&& matches!(self.screen, Screen::Main)
&& !self.over_panes()
{
self.motion.focused = Some(Instant::now());
}
}
Event::FocusLost => {
self.terminal_focused = false;
self.focus_reported = true;
}
Event::Paste(text) if matches!(self.screen, Screen::Login(_)) => {
if let Screen::Login(login) = &mut self.screen
&& login.takes_input()
{
login.input.insert_str(text.trim());
}
}
Event::Paste(text) if self.picker.is_some() => {
let text = text::clean(&text).replace(['\n', '\t'], " ");
if let Some(picker) = self.picker.as_mut() {
picker.edit_query(|q| q.push_str(text.trim()), Instant::now());
}
}
Event::Paste(text) if self.prompt.is_some() => {
if let Some(prompt) = self.prompt.as_mut() {
prompt.input.insert_str(text.replace(['\r', '\n'], " "));
}
self.on_prompt_edit();
}
Event::Paste(_) if self.over_panes() => {
self.status = Some(lang::t("Close what's open to paste").into());
}
Event::Paste(text) if matches!(self.focus, Focus::Input | Focus::Messages) => {
self.on_paste(text)
}
_ => {}
}
}
fn on_tagged(&mut self, (client_id, event): Tagged) {
if client_id == self.tg.client_id() {
self.on_tg(event);
}
}
fn on_tg(&mut self, event: TgEvent) {
match event {
TgEvent::Update(update) => self.on_update(*update),
TgEvent::ProxyApplied { number, result } => self.on_proxy_applied(number, result),
TgEvent::Error(message)
if matches!(
message.as_str(),
"API_ID_INVALID" | "API_ID_PUBLISHED_FLOOD"
) =>
{
self.reject_api_keys()
}
TgEvent::Error(message) => match &mut self.screen {
Screen::Login(login) => {
login.busy = false;
login.error = Some(message);
}
Screen::Main => self.status = Some(message),
},
TgEvent::ChatsLoaded { list, all, failed } => {
self.loading_lists.remove(&list);
if all {
self.loaded_lists.insert(list);
}
if !failed && self.wanted_lists.contains(&list) {
self.load_more_chats(list);
}
if all && list == List::Main {
self.load_more_chats(List::Archive);
}
}
TgEvent::History {
chat_id,
topic,
page,
messages,
} => self.on_history((chat_id, topic), page, messages),
TgEvent::Found {
chat_id,
topic,
query,
found,
} => self.on_found((chat_id, topic), &query, found),
TgEvent::Topics {
chat_id,
request,
page,
} => {
let read_asked = self.read_forum.as_ref().is_some_and(|r| {
r.chat_id == chat_id && r.page.is_some_and(|(asked, _)| asked == request)
});
if read_asked {
self.read_forum_page(chat_id, request, page.as_ref());
} else if let Some(forum) = self.forum.as_mut().filter(|f| f.chat_id == chat_id) {
forum.add_page(request, page.as_ref());
self.ask_topics();
self.topic_known();
}
}
TgEvent::Topic {
chat_id,
topic_id,
topic,
} => {
let read_asked = self
.read_forum
.as_ref()
.is_some_and(|r| r.topics.contains(&(chat_id, topic_id)));
if read_asked {
self.read_forum_topic(chat_id, topic_id, topic.as_deref());
}
if let Some(forum) = self
.forum
.as_mut()
.filter(|f| f.chat_id == chat_id && (!read_asked || f.wants(topic_id)))
{
match topic {
Some(topic) => forum.upsert(&topic),
None => forum.not_found(topic_id),
}
self.topic_known();
}
}
TgEvent::Replied {
chat_id,
message_id,
replied,
} => {
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == chat_id) {
open.set_replied(message_id, replied.map(|m| *m));
}
}
TgEvent::DraftReply {
chat_id,
topic,
message_id,
message,
} => self.on_draft_reply((chat_id, topic), message_id, message.map(|m| *m)),
TgEvent::Deletable {
chat_id,
message_id,
deletable,
} => self.on_deletable(chat_id, message_id, deletable),
TgEvent::Pinned {
chat_id,
topic,
request,
messages,
} => self.on_pinned((chat_id, topic), request, messages),
TgEvent::Pinnable {
chat_id,
message_id,
pinnable,
} => self.on_pinnable(chat_id, message_id, pinnable),
TgEvent::Editable {
chat_id,
message_id,
editable,
text,
} => self.on_editable(chat_id, message_id, editable, text),
TgEvent::Reactions {
chat_id,
message_id,
available,
} => self.on_available_reactions(chat_id, message_id, available),
TgEvent::Stickers { source, stickers } => self.on_stickers(source, stickers),
TgEvent::StickerSets(sets) => {
if let Some(panel) = self.stickers.as_mut() {
panel.set_sets(sets.unwrap_or_default());
self.load_sticker_set();
}
}
TgEvent::StickersFound { query, stickers } => {
let premium = self.premium;
if let Some(panel) = self.stickers.as_mut() {
let found = stickers::convert(&stickers.unwrap_or_default(), premium);
panel.set_found(&query, found);
}
}
TgEvent::Downloaded { file_id, path } => {
if let Some(open) = self.open.as_mut()
&& let Some((id, _)) = open.opening.filter(|&(_, f)| f == file_id)
{
open.opening = None;
if path.is_some() && open.viewing == Some(id) {
self.tg.open_content(open.chat_id, id);
open.start_timer(id, SystemTime::now());
}
}
if self.opening.remove(&file_id) {
match &path {
Some(path) => self.open_downloaded(path.clone()),
None => self.status = Some(lang::t("Download failed").into()),
}
}
if self.revealing.remove(&file_id) {
match &path {
Some(path) => {
mark_downloaded(path);
reveal_in_file_manager(path);
self.status = Some(lang::t("Shown in the file manager").into());
}
None => self.status = Some(lang::t("Download failed").into()),
}
}
if let Some(file) = self.copying.remove(&file_id) {
match &path {
Some(path) => {
mark_downloaded(path);
self.copy_downloaded(file, path)
}
None => self.status = Some(lang::t("Download failed").into()),
}
}
if self.player.waits_for(file_id) {
match &path {
Some(_) if !self.present() => {
self.player.stop();
self.status =
Some(lang::t("Voice message downloaded: Enter plays it").into());
}
Some(path) => self.player.start(PathBuf::from(path)),
None => {
self.player.stop();
self.status = Some(lang::t("Download failed").into());
}
}
}
let present = self.present();
if let Some(view) = self.video_view.as_mut()
&& view.waits_for(file_id)
{
match &path {
Some(_) if !present => {
self.status =
Some(lang::t("Video message downloaded: Enter plays it").into());
self.video_view = None;
}
Some(path) => view.downloaded(PathBuf::from(path)),
None => {
self.status = Some(lang::t("Download failed").into());
self.video_view = None;
}
}
}
if let Some(inline) = self.inline_video.as_mut()
&& inline.waits_for(file_id)
{
match &path {
Some(_) if !present => {
if !inline.is_sticker() {
self.status = Some(
lang::t("Video message downloaded: Space plays it").into(),
);
}
self.inline_video = None;
}
Some(path) => {
if let Err(why) = inline.downloaded(PathBuf::from(path))
&& !inline.is_sticker()
{
self.status = Some(format!(
"{}{why}",
lang::t("Can't play this video message: ")
));
self.inline_video = None;
}
}
None => {
if !inline.is_sticker() {
self.status = Some(lang::t("Download failed").into());
self.inline_video = None;
}
}
}
}
self.images.on_downloaded(file_id, path);
}
TgEvent::Members {
chat_id,
query,
user_ids,
} => {
let open = self.open.as_ref().is_some_and(|o| o.chat_id == chat_id);
let Some(completion) = self.completion.as_mut().filter(|_| open) else {
return;
};
if completion.set_found(&query, user_ids) {
let (query, found) = (completion.word.query.clone(), completion.found.clone());
let items = self.mention_items(&query, &found);
if let Some(completion) = self.completion.as_mut() {
completion.set_items(items);
}
}
}
TgEvent::Commands { chat_id, commands } => {
let Some(open) = self.open.as_mut().filter(|o| o.chat_id == chat_id) else {
return;
};
open.commands = Commands::Known(commands);
let query = self
.completion
.as_ref()
.filter(|c| c.word.kind == Kind::Command)
.map(|c| c.word.query.clone());
if let Some(query) = query {
let items = self.command_items(&query);
if let Some(completion) = self.completion.as_mut() {
completion.set_items(items);
}
}
}
TgEvent::ChatsFound {
query,
chat_ids,
user_ids,
} => {
if let Some(picker) = self.picker.as_mut() {
picker.set_found(&query, chat_ids, user_ids);
}
}
TgEvent::ChatFound { request, found } => {
if self.finding.as_ref().is_none_or(|f| f.request != request) {
return;
}
let link = self.finding.take().and_then(|f| f.link);
if self.busy() {
if found.is_ok() {
self.status = Some(lang::f(
"Found {request}: press s to open it",
&[("request", &request)],
));
}
return;
}
match (found, link) {
(Ok(spot), _) => {
self.open_chat(spot.chat_id);
if let Some(topic) = spot.topic
&& self
.forum
.as_ref()
.is_some_and(|f| f.chat_id == spot.chat_id)
{
self.open_topic(topic);
}
if let Some(id) = spot.message_id {
self.jump_to_message(id);
}
}
(Err(Missed::Quiet), _) => {}
(Err(Missed::Said(why)), _) => self.status = Some(why),
(Err(Missed::Elsewhere), Some(link)) => self.open_link_outside(link),
(Err(Missed::Elsewhere), None) => {
self.status = Some(lang::t("tuigram can't open this kind of link").into());
}
}
}
TgEvent::Forwarded { chat_id } => {
let title = self.chats.title(chat_id).unwrap_or_default().to_string();
let to = lang::t("to");
let to = match self.chats.is_forum(chat_id) {
true => format!("{to} {title} › General"),
false => format!("{to} {title}"),
};
self.show_toast(lang::t("Forwarded"), &to);
}
TgEvent::Joined { chat_id } => {
let title = self.chats.title(chat_id).unwrap_or_default().to_string();
let joined = match self.chats.get(chat_id).is_some_and(|c| c.is_channel) {
true => lang::tc("channel", "Joined"),
false => lang::t("Joined"),
};
self.show_toast(joined, &title);
}
TgEvent::Left { chat_id } => {
let title = self.chats.title(chat_id).unwrap_or_default().to_string();
if self.chats.is_secret(chat_id) {
let with = format!("{} {title}", lang::t("with"));
self.show_toast(lang::t("Ended the secret chat"), &with);
} else {
self.show_toast(lang::t("Left"), &title);
}
}
TgEvent::BotAnswer {
chat_id,
topic,
label,
text,
alert,
url,
} => self.on_bot_answer((chat_id, topic), label, &text, alert, &url),
TgEvent::Invite {
request,
link,
invite,
} => {
if self.finding.as_ref().is_some_and(|f| f.request == request) && !self.busy() {
self.confirm_invite(link, request, invite);
}
}
TgEvent::Mentions {
chat_id,
topic,
ask,
ids,
} => self.on_mentions((chat_id, topic), ask, ids),
TgEvent::ChatInfo { chat_id, about } => {
if let Some(info) = self
.chat_info
.as_mut()
.filter(|i| i.chat_id == chat_id && i.about.is_none())
{
match about {
Some(about) => info.set_about(*about),
None => info.failed = true,
}
self.ask_members();
}
}
TgEvent::ChatMembers {
chat_id,
offset,
members,
} => {
if let Some(info) = self.chat_info.as_mut().filter(|i| i.chat_id == chat_id) {
info.add_page(offset, members);
self.ask_members();
}
}
}
}
fn on_history(
&mut self,
place: (i64, Option<i32>),
page: Page,
messages: Option<Vec<tdlib_rs::types::Message>>,
) {
let Some(open) = self
.open
.as_mut()
.filter(|o| o.place() == place && o.loading == Some(page))
else {
return;
};
open.loading = None;
let Some(messages) = messages else {
return;
};
if let Page::Around(target) = page
&& open.topic.is_some()
&& open.unread_after.is_none()
&& !messages.iter().any(|m| m.id == target)
{
self.status = Some(lang::t("That message isn't in this topic").into());
return;
}
open.add_page(
page,
messages.into_iter().map(|m| (m.id, m.into())).collect(),
);
let newest = match open.topic {
Some(topic) => self
.forum
.as_ref()
.and_then(|f| f.get(topic))
.map_or(0, |t| t.newest()),
None => self.chats.last_message(open.chat_id),
};
open.reached(newest);
open.go_to_unread();
if open.messages.len() < MIN_LOADED {
self.load_older_messages();
}
}
fn on_found(
&mut self,
place: (i64, Option<i32>),
query: &str,
found: Result<Box<Found>, String>,
) {
if self
.media_menu
.as_ref()
.is_some_and(|m| m.loading && m.query == query)
{
self.on_media_found(place, found);
return;
}
let Some(open) = self.open.as_mut().filter(|o| o.place() == place) else {
return;
};
let Some(search) = open
.search
.as_mut()
.filter(|s| s.query == query && s.loading)
else {
return;
};
search.loading = false;
let wanted = search.wanted.take();
match found {
Ok(found) => {
search.add(*found);
if let Some(index) = wanted {
self.go_to_match(index);
}
}
Err(why) => {
self.status = Some(why);
if open.search.as_ref().is_some_and(|s| s.results.is_empty()) {
open.search = None;
}
}
}
}
fn on_media_found(&mut self, place: (i64, Option<i32>), found: Result<Box<Found>, String>) {
let Some(open) = self.open.as_ref().filter(|o| o.place() == place) else {
self.media_menu = None;
return;
};
let (chat_id, topic) = (open.chat_id, open.topic);
let secret = self.chats.is_secret(chat_id);
let next = {
let Some(menu) = self.media_menu.as_mut() else {
return;
};
menu.loading = false;
match found {
Ok(found) => {
menu.add(*found);
if !menu.done && menu.rows.len() < MEDIA_ROWS_MAX {
menu.loading = true;
Some((
menu.query.clone(),
menu.ask.clone(),
menu.next_from,
menu.next_offset.clone(),
))
} else {
None
}
}
Err(why) => {
menu.error = Some(why.clone());
self.status = Some(why);
None
}
}
};
if let Some((query, ask, from, offset)) = next {
self.tg.search_messages(
chat_id,
topic,
secret,
query,
ask,
from,
offset,
SEARCH_PAGE,
);
}
}
fn on_update(&mut self, update: Update) {
match update {
Update::AuthorizationState(u) => self.on_auth_state(u.authorization_state),
Update::NewChat(u) => self.chats.insert(u.chat),
Update::ChatPosition(u) => self.chats.set_position(u.chat_id, &u.position),
Update::ChatLastMessage(u) => {
self.chats
.set_last_message(u.chat_id, u.last_message.as_ref(), &u.positions)
}
Update::ChatTitle(u) => self.chats.set_title(u.chat_id, u.title),
Update::ConnectionState(u) => self.connection = connection_words(&u.state),
Update::ChatDraftMessage(u) => {
self.chats
.set_draft(u.chat_id, u.draft_message.as_ref(), &u.positions)
}
Update::ChatIsMarkedAsUnread(u) => self
.chats
.set_marked_unread(u.chat_id, u.is_marked_as_unread),
Update::ChatNotificationSettings(u) => self
.chats
.set_notifications(u.chat_id, u.notification_settings),
Update::ScopeNotificationSettings(u) => self
.chats
.set_default_mute(&u.scope, u.notification_settings.mute_for),
Update::ChatAction(u) => {
let topic = match u.topic_id {
Some(MessageTopic::Forum(t)) => Some(t.forum_topic_id),
_ => None,
};
self.chats
.set_action(u.chat_id, topic, &u.sender_id, &u.action);
}
Update::NotificationGroup(u) => self.on_notifications(u),
Update::UnreadChatCount(u) => {
let list = List::of(&u.chat_list);
self.chats.set_unread_in(list, u.unread_unmuted_count);
if list == List::Main {
self.set_unread_chats(u.unread_unmuted_count);
}
}
Update::ChatFolders(u) => self
.chats
.set_folders(&u.chat_folders, u.main_chat_list_position),
Update::ChatPhoto(u) => self.chats.set_photo(u.chat_id, u.photo.as_ref()),
Update::ChatAccentColors(u) => self.chats.set_accent(u.chat_id, u.accent_color_id),
Update::AccentColors(u) => self.chats.set_accent_colors(&u.colors),
Update::ChatReadInbox(u) => {
self.chats.set_unread(u.chat_id, u.unread_count);
self.chats
.set_read_inbox(u.chat_id, u.last_read_inbox_message_id);
}
Update::ChatUnreadMentionCount(u) => {
self.chats.set_mentions(u.chat_id, u.unread_mention_count);
if u.unread_mention_count == 0
&& let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id)
{
open.messages.values_mut().for_each(|m| m.mention = false);
}
}
Update::MessageMentionRead(u) => {
self.chats.set_mentions(u.chat_id, u.unread_mention_count);
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
open.set_mention_read(u.message_id);
}
}
Update::ChatReadOutbox(u) => {
self.chats
.set_read_outbox(u.chat_id, u.last_read_outbox_message_id);
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
open.start_timers(true, u.last_read_outbox_message_id, SystemTime::now());
}
}
Update::SecretChat(u) => {
self.chats
.set_secret(u.secret_chat.id, Secret::of(&u.secret_chat));
if let Some(view) = &self.key_view
&& self
.chats
.secret(view.chat_id)
.is_none_or(|s| s.key_hash != view.hash || s.state == SecretState::Closed)
{
self.key_view = None;
}
}
Update::ChatMessageAutoDeleteTime(u) => self
.chats
.set_auto_delete(u.chat_id, u.message_auto_delete_time),
Update::MessageContentOpened(u) => {
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
open.set_opened(u.message_id);
open.start_timer(u.message_id, SystemTime::now());
}
}
Update::Option(u) if u.name == "is_premium" => {
self.premium = matches!(u.value, OptionValue::Boolean(v) if v.value);
}
Update::Option(u) if u.name == "my_id" => {
if let OptionValue::Integer(v) = u.value {
self.chats.set_my_id(v.value);
}
}
Update::User(u) => {
let name = format!("{} {}", u.user.first_name, u.user.last_name);
self.users.insert(u.user.id, text::clean(name.trim()));
let badge = Badge::of(u.user.verification_status.as_ref(), u.user.is_support);
self.chats.set_badge(Peer::User(u.user.id), badge);
self.chats
.set_username(Peer::User(u.user.id), u.user.usernames.as_ref());
self.chats
.set_presence(u.user.id, Presence::of(&u.user.status));
let bot = matches!(u.user.r#type, UserType::Bot(_));
self.chats.set_bot(u.user.id, bot);
}
Update::UserStatus(u) => {
self.chats.set_presence(u.user_id, Presence::of(&u.status));
}
Update::Supergroup(u) => {
let group = &u.supergroup;
let badge = Badge::of(group.verification_status.as_ref(), false);
self.chats.set_badge(Peer::Supergroup(group.id), badge);
self.chats
.set_username(Peer::Supergroup(group.id), group.usernames.as_ref());
let member = !matches!(group.status, ChatMemberStatus::Left);
self.chats.set_member(group.id, member);
let read_only = group.is_channel && !posts_in_channel(&group.status);
self.chats.set_read_only(group.id, read_only);
self.chats.set_forum(group.id, group.is_forum);
}
Update::NewMessage(u) if u.message.scheduling_state.is_some() => {}
Update::NewMessage(u) => {
let mut topic = None;
let mut ask = None;
if let Some(forum) = self
.forum
.as_mut()
.filter(|f| f.chat_id == u.message.chat_id)
{
let arrived = forum.arrived(&u.message);
topic = Some(arrived.topic);
ask = forum.add_message(&arrived);
}
if let Some(id) = ask {
self.ask_topic(id);
}
let seen = self.present() && !self.popup_open();
if let Some(open) = self.open.as_mut().filter(|o| {
o.chat_id == u.message.chat_id
&& o.at_newest
&& (o.topic.is_none() || o.topic == topic)
}) {
let (id, theirs) = (u.message.id, !u.message.is_outgoing);
open.insert(u.message);
let in_sight = seen && open.selected.is_none();
let bubbles = self.colors.other_bubble != self.colors.bg;
let glows = theirs && in_sight && bubbles && self.settings.animations;
if glows && open.messages.contains_key(&id) {
self.motion.arrived(open.chat_id, id, Instant::now());
}
}
}
Update::ForumTopicInfo(u) => {
if let Some(forum) = self.forum.as_mut().filter(|f| f.chat_id == u.info.chat_id) {
forum.set_info(&u.info);
}
}
Update::ForumTopic(u) => {
let ask = self
.forum
.as_mut()
.filter(|f| f.chat_id == u.chat_id)
.and_then(|f| f.set_state(&u));
if let Some(id) = ask {
self.ask_topic(id);
}
}
Update::MessageSendSucceeded(u) => {
if let MessageContent::MessageVoiceNote(v) = &u.message.content {
let path = Path::new(&v.voice_note.voice.local.path);
if crate::record::is_recording(path, &self.outbox()) {
let _ = std::fs::remove_file(path);
}
}
if let Some(open) = self
.open
.as_mut()
.filter(|o| o.chat_id == u.message.chat_id)
{
open.replace(u.old_message_id, u.message);
}
}
Update::MessageSendFailed(u) => {
self.status = Some(format!(
"{}{}",
lang::t("Message not sent: "),
u.error.message
));
if u.message.scheduling_state.is_some() {
self.give_back_scheduled(&u.message, &u.error.message);
}
if let Some(open) = self
.open
.as_mut()
.filter(|o| o.chat_id == u.message.chat_id)
{
open.replace(u.old_message_id, u.message);
}
}
Update::File(u) => {
if let Some(open) = self.open.as_mut() {
open.set_upload(&u.file);
}
}
Update::MessageContent(u) => {
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
open.set_content(u.message_id, &u.new_content);
let msg = open.messages.get(&u.message_id);
if self
.photo_view
.as_ref()
.is_some_and(|v| v.lost(u.chat_id, u.message_id, msg))
{
self.photo_view = None;
}
if self
.video_view
.as_ref()
.is_some_and(|v| v.lost(u.chat_id, u.message_id, msg))
{
self.video_view = None;
}
if self
.inline_video
.as_ref()
.is_some_and(|v| v.lost(u.chat_id, u.message_id, msg))
{
self.inline_video = None;
}
if self.text_select.as_ref().is_some_and(|s| {
s.chat_id == u.chat_id
&& s.message_id == u.message_id
&& msg.is_none_or(|m| m.source_text != s.source)
}) {
self.text_select = None;
self.status =
Some(lang::t("The message was edited: v selects again").into());
}
}
}
Update::MessageEdited(u) => {
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
open.set_edited(u.message_id);
open.set_keyboard(u.message_id, u.reply_markup.as_ref());
if self
.button_menu
.as_ref()
.is_some_and(|m| m.message_id == u.message_id)
{
self.button_menu = None;
}
}
}
Update::MessageIsPinned(u) => {
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
open.set_pinned(u.message_id, u.is_pinned);
self.ask_pinned();
}
}
Update::MessageInteractionInfo(u) => {
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
open.set_reactions(u.message_id, u.interaction_info.as_ref());
}
}
Update::DeleteMessages(u) if u.is_permanent => {
if u.message_ids
.iter()
.any(|&id| self.player.is_on(u.chat_id, id))
{
self.player.stop();
}
let stale = self
.forum
.as_ref()
.filter(|f| f.chat_id == u.chat_id)
.map(|f| f.deleted(&u.message_ids))
.unwrap_or_default();
for id in stale {
self.ask_topic(id);
}
if self
.photo_view
.as_ref()
.is_some_and(|v| u.message_ids.iter().any(|&id| v.lost(u.chat_id, id, None)))
{
self.photo_view = None;
}
if self
.video_view
.as_ref()
.is_some_and(|v| u.message_ids.iter().any(|&id| v.lost(u.chat_id, id, None)))
{
self.video_view = None;
}
if self
.inline_video
.as_ref()
.is_some_and(|v| u.message_ids.iter().any(|&id| v.lost(u.chat_id, id, None)))
{
self.inline_video = None;
}
if self.text_select.as_ref().is_some_and(|s| {
s.chat_id == u.chat_id && u.message_ids.contains(&s.message_id)
}) {
self.text_select = None;
}
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
open.remove(&u.message_ids);
let gone = |id: i64| u.message_ids.contains(&id);
if self
.button_menu
.as_ref()
.is_some_and(|m| gone(m.message_id))
{
self.button_menu = None;
}
if self
.delete_menu
.as_ref()
.is_some_and(|m| gone(m.message_id))
{
self.delete_menu = None;
}
if self.react_menu.as_ref().is_some_and(|m| gone(m.message_id)) {
self.react_menu = None;
}
if self.vote_menu.as_ref().is_some_and(|m| gone(m.message_id)) {
self.vote_menu = None;
}
if self.pin_menu.as_ref().is_some_and(|m| gone(m.message_id)) {
self.pin_menu = None;
}
}
}
_ => {}
}
}
fn on_auth_state(&mut self, state: AuthorizationState) {
if let Screen::Login(login) = &self.screen
&& matches!(login.step, LoginStep::BadProxy { .. })
&& !matches!(
state,
AuthorizationState::Closing | AuthorizationState::Closed
)
{
return;
}
let step = match state {
AuthorizationState::WaitTdlibParameters => match self.api_keys() {
Some((source, keys)) => {
self.keys_source = Some(source);
self.start_tdlib(keys);
return;
}
None => LoginStep::ApiId,
},
AuthorizationState::WaitPhoneNumber => LoginStep::Phone,
AuthorizationState::WaitCode(s) => LoginStep::Code {
sent_via: code_destination(&s.code_info.r#type),
},
AuthorizationState::WaitPassword(s) => LoginStep::Password {
hint: s.password_hint,
},
AuthorizationState::WaitEmailAddress(_) => LoginStep::Email,
AuthorizationState::WaitEmailCode(_) => LoginStep::EmailCode,
AuthorizationState::WaitOtherDeviceConfirmation(s) => {
LoginStep::OtherDevice { link: s.link }
}
AuthorizationState::WaitRegistration(_) => LoginStep::Unsupported(lang::t(
"This number has no Telegram account. Sign up in the official app first.",
)),
AuthorizationState::WaitPremiumPurchase(_) => LoginStep::Unsupported(lang::t(
"Telegram requires a Premium purchase to log in with this number. Use the official app.",
)),
AuthorizationState::Ready => {
self.screen = Screen::Main;
self.wanted_lists.insert(List::Main);
self.load_more_chats(List::Main);
self.tg.enable_notifications();
self.tg
.accept_secret_chats(self.settings.accept_secret_chats);
self.notify_since = unix_now();
return;
}
AuthorizationState::LoggingOut => {
self.relogin = true;
if let Screen::Login(_) = self.screen {
return;
}
LoginStep::LoggingOut
}
AuthorizationState::Closing => return,
AuthorizationState::Closed if self.relogin && self.quit_deadline.is_none() => {
self.relogin = false;
self.keys_source = None;
self.forget_session();
self.tg.reopen();
self.screen = login_screen(LoginStep::Connecting);
return;
}
AuthorizationState::Closed => {
self.exit = true;
return;
}
};
self.screen = login_screen(step);
}
fn on_key(&mut self, key: KeyEvent) {
if key.kind != KeyEventKind::Press {
return;
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
if ctrl
&& key.code == KeyCode::Char('c')
&& self.focus != Focus::Input
&& self.prompt.is_none()
&& self.picker.is_none()
{
self.quit();
return;
}
self.status = None;
let typing = matches!(self.screen, Screen::Login(_))
|| self.prompt.is_some()
|| self.picker.is_some()
|| self.focus == Focus::Input;
let key = match (typing, key.code) {
(false, KeyCode::Char(c)) => {
let c = match key.modifiers.contains(KeyModifiers::SHIFT) {
true => c.to_uppercase().next().unwrap_or(c),
false => c,
};
KeyEvent::new(KeyCode::Char(qwerty(c)), key.modifiers)
}
_ => key,
};
match self.screen {
Screen::Login(_) => self.on_login_key(key),
Screen::Main if self.confirm.is_some() => self.on_confirm_key(key),
Screen::Main if self.notice.is_some() => {
if matches!(key.code, KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q')) {
self.notice = None;
}
}
Screen::Main if self.key_view.is_some() => {
if matches!(key.code, KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q')) {
self.key_view = None;
}
}
Screen::Main if self.photo_view.is_some() => self.on_viewer_key(key),
Screen::Main if self.video_view.is_some() => self.on_video_key(key),
Screen::Main if self.settings_menu.is_some() => self.on_settings_key(key, ctrl),
Screen::Main if self.delete_menu.is_some() => self.on_delete_key(key),
Screen::Main if self.react_menu.is_some() => self.on_react_key(key, ctrl),
Screen::Main if self.vote_menu.is_some() => self.on_vote_key(key),
Screen::Main if self.button_menu.is_some() => self.on_button_key(key),
Screen::Main if self.pin_menu.is_some() => self.on_pin_key(key),
Screen::Main if self.media_menu.is_some() => self.on_media_key(key, ctrl),
Screen::Main if self.pinned_menu.is_some() => self.on_pinned_key(key),
Screen::Main if self.timer_menu.is_some() => self.on_timer_key(key),
Screen::Main if self.chat_info.is_some() => self.on_info_key(key, ctrl),
Screen::Main if self.text_select.is_some() => self.on_select_key(key, ctrl),
Screen::Main if self.menu.is_some() => self.on_menu_key(key),
Screen::Main if self.picker.is_some() => self.on_picker_key(key, ctrl),
Screen::Main if self.resizing.is_some() => self.on_resize_key(key, ctrl),
Screen::Main if self.prompt.is_some() => self.on_prompt_key(key, ctrl),
Screen::Main if self.focus == Focus::Input && self.stickers.is_some() => {
self.on_sticker_key(key, ctrl)
}
Screen::Main if self.focus == Focus::Input => self.on_insert_key(key, ctrl),
Screen::Main => self.on_normal_key(key, ctrl),
}
if self.focus != Focus::Input {
self.stickers = None;
self.completion = None;
}
if self.busy() {
self.finding = None;
}
}
fn on_login_key(&mut self, key: KeyEvent) {
let Screen::Login(login) = &mut self.screen else {
return;
};
match (&login.step, key.code) {
(LoginStep::Phone, KeyCode::Tab) if !login.busy => {
login.busy = true;
login.error = None;
self.tg.request_qr_code();
return;
}
(LoginStep::OtherDevice { .. }, KeyCode::Esc) => {
self.tg.log_out();
self.relogin = true;
self.screen = login_screen(LoginStep::Connecting);
return;
}
_ => {}
}
if !login.takes_input() {
return;
}
if key.code != KeyCode::Enter {
login.input.input(key);
return;
}
let value = login.input.lines().concat().trim().to_string();
if value.is_empty() || login.busy {
return;
}
match login.step {
LoginStep::ApiId => {
match config::parse_api_id(&value) {
Some(id) => self.screen = login_screen(LoginStep::ApiHash { id }),
None => {
login.error = Some(lang::t("The API ID is a number, like 1234567").into())
}
}
return;
}
LoginStep::ApiHash { id } => {
if !config::is_api_hash(&value) {
login.error = Some(lang::t("The API hash is 32 letters and digits").into());
return;
}
let keys = ApiKeys { id, hash: value };
self.settings.api_keys = Some(keys.clone());
if let Err(e) = self.settings.save(&self.settings_path) {
login.error = Some(format!("{}{e:#}", lang::t("Couldn't save them: ")));
return;
}
if self.keys_source.is_some() {
self.relogin = true;
self.tg.close(None);
self.screen = login_screen(LoginStep::Connecting);
} else {
self.keys_source = Some(KeySource::Saved);
self.screen = login_screen(LoginStep::Connecting);
self.start_tdlib(keys);
}
return;
}
_ => {}
}
login.busy = true;
login.error = None;
match login.step {
LoginStep::Phone => self.tg.send_phone_number(value),
LoginStep::Code { .. } => self.tg.send_code(value),
LoginStep::Password { .. } => self.tg.send_password(value),
LoginStep::Email => self.tg.send_email(value),
LoginStep::EmailCode => self.tg.send_email_code(value),
LoginStep::Connecting
| LoginStep::LoggingOut
| LoginStep::ApiId
| LoginStep::ApiHash { .. }
| LoginStep::OtherDevice { .. }
| LoginStep::Unsupported(_)
| LoginStep::BadProxy { .. } => {}
}
}
fn api_keys(&self) -> Option<(KeySource, ApiKeys)> {
let built_in = config::built_in_keys().filter(|_| !self.built_in_rejected);
let env = self.env_keys.clone().map(|k| (KeySource::Env, k));
env.or_else(|| {
self.settings
.api_keys
.clone()
.map(|k| (KeySource::Saved, k))
})
.or_else(|| built_in.map(|k| (KeySource::BuiltIn, k)))
}
fn reject_api_keys(&mut self) {
let message = match self.keys_source {
Some(KeySource::Env) => {
lang::t("Telegram rejected TG_API_ID / TG_API_HASH.").to_string()
}
Some(KeySource::BuiltIn) => {
self.built_in_rejected = true;
lang::t("Telegram rejected tuigram's built-in key. Use your own.").into()
}
Some(KeySource::Saved) | None => {
self.settings.api_keys = None;
match self.settings.save(&self.settings_path) {
Ok(()) => lang::t("Telegram rejected that API ID and hash.").into(),
Err(e) => format!(
"{}{e:#}",
lang::t("Telegram rejected the API key; can't forget it: ")
),
}
}
};
match &mut self.screen {
Screen::Login(_) if self.keys_source != Some(KeySource::Env) => {
let mut login = Login::new(LoginStep::ApiId);
login.error = Some(message);
self.screen = Screen::Login(Box::new(login));
}
Screen::Login(login) => {
login.busy = false;
login.error = Some(message);
}
Screen::Main => self.status = Some(message),
}
}
fn on_mouse(&mut self, mouse: MouseEvent) {
if matches!(self.screen, Screen::Main) && self.settings_on_top() {
self.on_settings_mouse(mouse);
return;
}
if !matches!(self.screen, Screen::Main)
|| self.over_panes()
|| self.photo_view.is_some()
|| self.video_view.is_some()
{
return;
}
let (x, y) = (mouse.column, mouse.row);
match mouse.kind {
MouseEventKind::ScrollDown => self.mouse_scroll(x, y, 1),
MouseEventKind::ScrollUp => self.mouse_scroll(x, y, -1),
MouseEventKind::Down(MouseButton::Left) => self.mouse_click(x, y),
_ => {}
}
}
fn settings_on_top(&self) -> bool {
self.settings_menu.is_some()
&& self.confirm.is_none()
&& self.notice.is_none()
&& self.key_view.is_none()
&& self.photo_view.is_none()
&& self.video_view.is_none()
}
fn on_settings_mouse(&mut self, mouse: MouseEvent) {
let Some(menu) = self.settings_menu.as_ref() else {
return;
};
let (x, y) = (mouse.column, mouse.row);
let drawn = &menu.drawn;
let wheel = |code| drawn.contains(x, y).then_some(code);
let code = match mouse.kind {
MouseEventKind::ScrollDown => wheel(KeyCode::Char('j')),
MouseEventKind::ScrollUp => wheel(KeyCode::Char('k')),
MouseEventKind::Down(MouseButton::Left) => {
let tab = drawn.tab_at(x, y);
let on_settings = menu.tab == HelpTab::Settings;
let row = drawn.setting_at(x, y).filter(|_| on_settings);
let selected = menu.selected;
match (tab, row) {
(Some(tab), _) => {
if let Some(menu) = self.settings_menu.as_mut() {
menu.tab = [HelpTab::Shortcuts, HelpTab::Settings][tab];
}
}
(None, Some(row)) if row == selected => self.change_setting(),
(None, Some(row)) => {
if let Some(menu) = self.settings_menu.as_mut() {
menu.selected = row;
}
}
(None, None) => {}
}
None
}
_ => None,
};
if let Some(code) = code {
self.on_settings_key(KeyEvent::new(code, KeyModifiers::NONE), false);
}
}
fn mouse_scroll(&mut self, x: u16, y: u16, delta: isize) {
match self.mouse.pane_at(x, y) {
Some(crate::mouse::Pane::Chats) => self.move_chat_cursor(delta),
Some(crate::mouse::Pane::Topics) => self.move_topic_cursor(delta),
Some(crate::mouse::Pane::Messages) => self.wheel_messages(delta * WHEEL_LINES),
None => {}
}
}
fn mouse_click(&mut self, x: u16, y: u16) {
if let Some(chat_id) = self.mouse.chat_at(x, y) {
self.focus = Focus::Chats;
self.selected = Some(chat_id);
if self.open.as_ref().is_none_or(|o| o.chat_id != chat_id) {
self.open_chat(chat_id);
}
return;
}
if let Some(topic_id) = self.mouse.topic_at(x, y) {
self.focus = Focus::Topics;
if let Some(forum) = self.forum.as_mut() {
forum.selected = Some(topic_id);
}
if self.open.as_ref().and_then(|o| o.topic) != Some(topic_id) {
self.open_selected_topic();
}
return;
}
if let Some(message_id) = self.mouse.message_at(x, y) {
let was_focused = self.focus == Focus::Messages;
let was_selected = self.open.as_ref().and_then(|o| o.selected);
if self.focus == Focus::Input {
self.leave_insert();
}
self.focus = Focus::Messages;
if let Some(open) = self.open.as_mut() {
open.selected = Some(message_id);
}
if was_focused && was_selected == Some(message_id) {
let is_note = self
.open
.as_ref()
.and_then(|o| o.messages.get(&message_id))
.is_some_and(|m| m.video.is_some());
if is_note {
self.toggle_inline_video();
} else {
self.open_selected_message();
}
}
return;
}
if self.mouse.over_composer(x, y) && self.open.is_some() {
self.start_writing();
}
}
fn on_normal_key(&mut self, key: KeyEvent, ctrl: bool) {
let pending_g = std::mem::take(&mut self.pending_g);
let (to_chat, to_list) = match self.settings.chat_list_side {
Side::Left => ('l', 'h'),
Side::Right => ('h', 'l'),
};
let motion = match key.code {
KeyCode::Char('j') | KeyCode::Down => Some(1),
KeyCode::Char('k') | KeyCode::Up => Some(-1),
KeyCode::Char('d') if ctrl => Some(HALF_PAGE),
KeyCode::Char('u') if ctrl => Some(-HALF_PAGE),
KeyCode::Char('g') if pending_g => Some(isize::MIN),
KeyCode::Char('G') => Some(isize::MAX),
_ => None,
};
if let Some(delta) = motion {
match self.focus {
Focus::Chats => self.move_chat_cursor(delta),
Focus::Topics => self.move_topic_cursor(delta),
Focus::Messages => self.move_message_cursor(delta),
Focus::Input => {}
}
return;
}
match (self.focus, key.code) {
(_, KeyCode::Esc) if self.recording.is_some() => self.cancel_recording(),
(_, KeyCode::Char('V')) if self.recording.is_some() => self.stop_recording(),
(Focus::Topics, KeyCode::Char('r')) if ctrl && self.forum.is_some() => {
self.resizing = Some(Resizing::Topics);
}
(_, KeyCode::Char('r')) if ctrl => {
self.resizing = Some(Resizing::List);
}
(_, KeyCode::Char('g')) => self.pending_g = true,
(Focus::Chats | Focus::Topics, KeyCode::Char('m')) if pending_g => {
match self.focus {
Focus::Chats => self.open_selected_chat(),
_ => self.open_selected_topic(),
}
if self.focus == Focus::Messages {
self.go_to_mention(true);
}
}
(_, KeyCode::Char('q')) => self.quit(),
(_, KeyCode::Char('H')) => self.toggle_highlight(),
(_, KeyCode::Char('?')) => {
if let Some(dir) = self.themes.dir.clone() {
self.themes = Themes::load(&dir);
}
self.use_saved_theme();
if let Some(dir) = self.sounds.dir.clone() {
self.sounds = Sounds::load(&dir);
}
self.use_saved_sound();
self.settings_menu = Some(SettingsMenu::new(HelpTab::Shortcuts, &self.settings));
}
(_, KeyCode::Char(':')) => self.open_prompt(PromptKind::Command),
(_, KeyCode::Char('o')) if ctrl => self.jump(true),
(_, KeyCode::Char('i')) if ctrl => self.jump(false),
(Focus::Messages, KeyCode::Tab) => self.jump(false),
(Focus::Chats, KeyCode::Tab) => self.switch_list(1),
(Focus::Chats, KeyCode::BackTab) => self.switch_list(-1),
(_, KeyCode::Char('s')) => self.picker = Some(ChatPicker::new(Purpose::Open)),
(Focus::Chats, KeyCode::Char('/')) => self.open_prompt(PromptKind::Chats),
(Focus::Messages, KeyCode::Char('/')) => self.open_prompt(PromptKind::Messages),
(Focus::Messages, KeyCode::Char('n')) => self.next_match(1),
(Focus::Messages, KeyCode::Char('N')) => self.next_match(-1),
(_, KeyCode::Esc) if self.finding.is_some() => self.finding = None,
(Focus::Chats, KeyCode::Esc) => self.chats.set_filter(""),
(Focus::Chats, KeyCode::Char('p')) if !ctrl => self.toggle_pin(),
(Focus::Chats, KeyCode::Char('m')) if !ctrl => self.toggle_mute(),
(Focus::Chats, KeyCode::Char('a')) if !ctrl => self.toggle_archive(),
(Focus::Chats | Focus::Topics, KeyCode::Char('R')) if !ctrl => self.ask_to_read_chat(),
(Focus::Messages, KeyCode::Esc)
if self.open.as_ref().is_some_and(|o| o.search.is_some()) =>
{
if let Some(open) = self.open.as_mut() {
open.search = None;
}
}
(Focus::Messages, KeyCode::Esc)
if self.open.as_ref().is_some_and(|o| o.editing.is_some()) =>
{
self.end_edit();
}
(Focus::Messages, KeyCode::Esc)
if self
.open
.as_ref()
.is_some_and(|o| !o.attachments.is_empty()) =>
{
if let Some(open) = self.open.as_mut() {
open.attachments.clear();
open.dropped = None;
open.as_files = false;
}
}
(Focus::Messages, KeyCode::Esc)
if self.open.as_ref().is_some_and(|o| o.reply.is_some()) =>
{
if let Some(open) = self.open.as_mut() {
open.reply = None;
open.draft_reply = None;
}
}
(Focus::Messages, KeyCode::Char('r')) => self.reply_to_selected(),
(Focus::Messages, KeyCode::Char('e')) => self.edit_selected(),
(Focus::Messages, KeyCode::Char('y')) => self.copy_selected(),
(Focus::Messages, KeyCode::Char('O')) => self.reveal_selected_file(),
(Focus::Messages, KeyCode::Char('v')) if !ctrl => self.open_text_select(),
(Focus::Messages, KeyCode::Char('a')) => self.open_prompt(PromptKind::Attach),
(Focus::Messages, KeyCode::Char('V')) => self.toggle_recording(),
(Focus::Messages, KeyCode::Char('p')) if pending_g => self.open_pinned_menu(),
(Focus::Messages, KeyCode::Char('u')) if pending_g => self.go_to_unread(),
(Focus::Messages, KeyCode::Char('m')) if pending_g => self.go_to_mention(true),
(Focus::Messages, KeyCode::Char('M')) if pending_g => self.go_to_mention(false),
(_, KeyCode::Char('I')) => self.open_chat_info(),
(Focus::Messages, KeyCode::Char('p')) => self.paste_clipboard(),
(Focus::Messages, KeyCode::Char('P')) => self.toggle_pin_message(),
(Focus::Messages, KeyCode::Char('t')) if ctrl => self.toggle_as_files(),
(Focus::Messages, KeyCode::Char('d')) if pending_g => self.go_to_replied(),
(Focus::Messages, KeyCode::Char('d')) => self.open_delete_menu(),
(Focus::Messages, KeyCode::Char('R')) => self.open_react_menu(),
(Focus::Messages, KeyCode::Char('X')) => self.remove_reactions(),
(Focus::Messages, KeyCode::Char('J')) => self.join_open_chat(),
(Focus::Messages, KeyCode::Char('Q')) => self.close_open_chat(),
(Focus::Messages, KeyCode::Char('f')) => self.forward_selected(),
(Focus::Chats, KeyCode::Enter) => self.open_selected_chat(),
(Focus::Chats, KeyCode::Char(c)) if c == to_chat => self.open_selected_chat(),
(Focus::Chats, KeyCode::Char('i')) => {
self.open_selected_chat();
if self.focus == Focus::Topics {
self.open_selected_topic();
}
self.start_writing();
}
(Focus::Messages, KeyCode::Char('i')) => self.start_writing(),
(Focus::Topics, KeyCode::Enter) => self.open_selected_topic(),
(Focus::Topics, KeyCode::Char(c)) if c == to_chat => self.open_selected_topic(),
(Focus::Topics, KeyCode::Char('i')) => {
self.open_selected_topic();
self.start_writing();
}
(Focus::Topics, KeyCode::Esc) => self.focus = Focus::Chats,
(Focus::Topics, KeyCode::Char('Q')) => self.close_open_chat(),
(Focus::Topics, KeyCode::Char(c)) if c == to_list => self.focus = Focus::Chats,
(Focus::Messages, KeyCode::Enter) => self.open_selected_message(),
(Focus::Messages, KeyCode::Char(' ')) => self.toggle_inline_video(),
(Focus::Messages, KeyCode::Char('z')) => self.zoom_inline_video(),
(Focus::Messages, KeyCode::Esc) => self.focus = self.left_of_messages(),
(Focus::Messages, KeyCode::Char(c)) if c == to_list => {
self.focus = self.left_of_messages();
}
_ => {}
}
}
fn on_insert_key(&mut self, key: KeyEvent, ctrl: bool) {
let alt = key.modifiers.contains(KeyModifiers::ALT);
let shift = key.modifiers.contains(KeyModifiers::SHIFT);
if let Some(completion) = self.completion.as_mut().filter(|c| !c.items.is_empty()) {
match key.code {
KeyCode::Tab => {
self.accept_completion();
return;
}
KeyCode::Up | KeyCode::BackTab => {
completion.move_by(-1);
return;
}
KeyCode::Down => {
completion.move_by(1);
return;
}
KeyCode::Char('p') if ctrl => {
completion.move_by(-1);
return;
}
KeyCode::Char('n') if ctrl => {
completion.move_by(1);
return;
}
_ => {}
}
}
match key.code {
KeyCode::Esc => self.leave_insert(),
KeyCode::Char('c') if ctrl => self.leave_insert(),
KeyCode::Enter if alt || shift => {
self.composer.insert_newline();
self.on_composer_edit();
}
KeyCode::Char('j') if ctrl => {
self.composer.insert_newline();
self.on_composer_edit();
}
KeyCode::Enter => self.send(None),
KeyCode::Char('v') if ctrl => self.paste_clipboard(),
KeyCode::Char('z') if ctrl => self.undo_drop(),
KeyCode::Char('t') if ctrl => self.toggle_as_files(),
KeyCode::Char('u') if ctrl => {
if self.composer.delete_line_by_head() {
self.on_composer_edit();
}
}
KeyCode::Tab => self.open_stickers(),
_ => {
if self.composer.input(key) {
self.on_composer_edit();
}
}
}
self.update_completion();
}
fn update_completion(&mut self) {
let DataCursor(row, col) = self.composer.cursor();
let word = self
.composer
.lines()
.get(row)
.and_then(|line| complete::word_at(line, col));
let group = self
.open
.as_ref()
.and_then(|o| self.chats.get(o.chat_id))
.is_some_and(|c| !c.is_private);
let Some(word) = word.filter(|w| match w.kind {
Kind::Emoji => true,
Kind::Mention => group,
Kind::Command => row == 0 && col == w.chars,
}) else {
self.completion = None;
return;
};
if word.kind == Kind::Command {
self.ask_bot_commands();
}
if self.completion.as_ref().is_some_and(|c| c.word == word) {
return;
}
let completion = self
.completion
.get_or_insert_with(|| Completion::new(word.clone()));
completion.retype(word.clone(), Instant::now());
let items = match word.kind {
Kind::Emoji => complete::emoji(&word.query),
Kind::Mention => {
let found = completion.found.clone();
self.mention_items(&word.query, &found)
}
Kind::Command => self.command_items(&word.query),
};
if let Some(completion) = self.completion.as_mut() {
completion.set_items(items);
}
}
fn ask_bot_commands(&mut self) {
let Some(open) = self
.open
.as_mut()
.filter(|o| o.commands == Commands::NotAsked)
else {
return;
};
let peer = self.chats.get(open.chat_id).and_then(|c| c.peer);
open.commands = match peer {
Some(Peer::User(id)) if !self.chats.is_bot(id) => Commands::Known(Vec::new()),
Some(peer) => {
self.tg.bot_commands(open.chat_id, peer);
Commands::Asked
}
None => Commands::Known(Vec::new()),
};
}
fn search_people(&self) -> Vec<String> {
let mut people = vec!["me".to_string()];
if let Some(open) = &self.open {
for msg in open.messages.values().rev() {
if let Sender::User(id) = msg.sender
&& !self.chats.is_saved(id)
&& let Some(name) = self.chats.user_username(id)
{
let name = format!("@{name}");
if !people.contains(&name) {
people.push(name);
}
}
}
}
for &id in self.chats.ids() {
let Some(name) = self.chats.username(id) else {
continue;
};
let name = format!("@{name}");
if !people.contains(&name) {
people.push(name);
}
}
people
}
fn resolve_sender(&self, mut ask: search::Query) -> Result<search::Query, String> {
let sender = match &ask.from {
Some(Who::Me) => {
let me = self
.chats
.my_id()
.ok_or(lang::t("Your account isn't known yet"))?;
Sender::User(me)
}
Some(Who::Username(name)) => match self.chats.user_by_username(name) {
Some(id) => Sender::User(id),
None => return Ok(ask),
},
Some(Who::Name(name)) => {
let mut matching: Vec<(i64, &str)> = Vec::new();
for msg in self.open.iter().flat_map(|o| o.messages.values()) {
let Sender::User(id) = msg.sender else {
continue;
};
if let Some(n) = self.users.get(&id)
&& !search::find(n, name).is_empty()
&& !matching.iter().any(|&(seen, _)| seen == id)
{
matching.push((id, n));
}
}
let exact: Vec<i64> = matching
.iter()
.filter(|(_, n)| n.to_lowercase() == name.to_lowercase())
.map(|&(id, _)| id)
.collect();
match (exact.as_slice(), matching.as_slice()) {
([id], _) | ([], [(id, _)]) => Sender::User(*id),
([], []) => {
return Err(lang::f(
"Nobody called {name} wrote in the messages loaded: try from:@username",
&[("name", &name)],
));
}
_ => {
let names: Vec<&str> = matching.iter().map(|&(_, n)| n).take(3).collect();
let names = names.join(", ");
return Err(lang::f(
"{name} could be {names}: use from:@username",
&[("name", &name), ("names", &names)],
));
}
}
}
Some(Who::Sender(_)) | None => return Ok(ask),
};
ask.from = Some(Who::Sender(sender));
Ok(ask)
}
fn command_items(&self, query: &str) -> Vec<Suggestion> {
let Some(Commands::Known(list)) = self.open.as_ref().map(|o| &o.commands) else {
return Vec::new();
};
complete::commands(list, query, |bot| {
self.chats.user_username(bot).map(String::from)
})
}
fn mention_items(&self, query: &str, found: &[i64]) -> Vec<Suggestion> {
let Some(open) = &self.open else {
return Vec::new();
};
let senders = open.messages.values().rev().filter_map(|m| match m.sender {
Sender::User(id) => Some(id),
Sender::Chat(_) => None,
});
let mut seen = HashSet::new();
let mut items = Vec::new();
for user_id in senders.chain(found.iter().copied()) {
if self.chats.is_saved(user_id) || !seen.insert(user_id) {
continue;
}
let Some(name) = self.users.get(&user_id) else {
continue;
};
let username = self.chats.user_username(user_id);
let matches = query.is_empty()
|| !search::find(name, query).is_empty()
|| username.is_some_and(|u| !search::find(u, query).is_empty());
if matches {
items.push(complete::mention(user_id, name, username));
}
if items.len() == complete::MAX_SUGGESTIONS {
break;
}
}
items
}
fn accept_completion(&mut self) {
let Some(completion) = self.completion.take() else {
return;
};
let Some(suggestion) = completion.current() else {
return;
};
for _ in 0..completion.word.chars {
self.composer.delete_char();
}
self.composer.insert_str(&suggestion.insert);
self.on_composer_edit();
}
fn start_writing(&mut self) {
let Some(open) = &self.open else {
return;
};
if let Some(why) = self.cant_send(open.chat_id) {
self.status = Some(why);
return;
}
if self.chats.joined(open.chat_id) {
self.focus = Focus::Input;
return;
}
self.confirm_join(open.chat_id);
}
fn confirm_join(&mut self, chat_id: i64) {
let title = self.chats.title(chat_id);
let channel = self.chats.get(chat_id).is_some_and(|c| c.is_channel);
let (ask, why) = if channel {
(
lang::t("Join this channel?"),
lang::t("Join it to have it in your chat list."),
)
} else {
(
lang::t("Join to write here?"),
lang::t("Join it to write, and to have it in your chat list."),
)
};
let (not_in, this) = match channel {
true => (
lang::tc("channel", "You're not in {title}."),
lang::tc("channel", "this chat"),
),
false => (
lang::t("You're not in {title}."),
lang::tc("group", "this chat"),
),
};
let not_in = lang::fill(not_in, &[("title", &title.unwrap_or(this))]);
let action = Confirmed::Join { chat_id, channel };
let mut confirm = Confirm::new(ask, vec![not_in, why.into()], action);
confirm.badge = self.chats.badge(chat_id);
self.confirm = Some(confirm);
}
fn join_open_chat(&mut self) {
let Some(open) = &self.open else {
return;
};
if self.chats.joined(open.chat_id) {
return;
}
self.confirm_join(open.chat_id);
}
fn cant_send(&self, chat_id: i64) -> Option<String> {
let secret = self.chats.secret(chat_id)?;
let name = self
.users
.get(&secret.user_id)
.map_or(lang::t("them"), String::as_str);
secret.cant_send(name)
}
fn leave_insert(&mut self) {
self.focus = Focus::Messages;
self.set_typing(false);
self.keep_draft();
}
fn written(&self) -> Option<(String, Option<i64>)> {
let open = self.open.as_ref()?;
let (text, reply) = match &open.editing {
Some(editing) => (editing.draft.clone(), editing.reply.as_ref().map(|r| r.id)),
None => (
self.composer.lines().join("\n"),
open.reply.as_ref().map(|r| r.id).or(open.draft_reply),
),
};
let text = if text.trim().is_empty() {
String::new()
} else {
text
};
Some((text, reply))
}
fn draft_to_keep(&mut self) -> Option<draft::Keep> {
let written = self.written()?;
let open = self.open.as_mut()?;
if open.draft == written {
return None;
}
let draft = Draft::new(&written.0, written.1);
let had_none = open.draft.0.is_empty();
open.draft = written;
if draft.is_none() && had_none {
return None;
}
let (chat_id, topic) = open.place();
match topic {
Some(topic) => {
if let Some(forum) = self.forum.as_mut().filter(|f| f.chat_id == chat_id) {
forum.keep_draft(topic, draft.clone());
}
}
None => self.chats.keep_draft(chat_id, draft.clone()),
}
Some(draft::Keep {
chat_id,
topic,
draft,
})
}
fn forget_draft(&mut self, chat_id: i64) {
self.chats.keep_draft(chat_id, None);
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == chat_id) {
open.editing = None;
open.reply = None;
open.draft_reply = None;
open.draft = Default::default();
self.composer = new_composer();
}
}
fn keep_draft(&mut self) {
if let Some(keep) = self.draft_to_keep() {
self.tg.set_draft(keep);
}
}
fn on_draft_reply(
&mut self,
place: (i64, Option<i32>),
message_id: i64,
message: Option<Message>,
) {
let Some(open) = self
.open
.as_mut()
.filter(|o| o.place() == place && o.draft_reply == Some(message_id))
else {
return;
};
open.draft_reply = None;
if let Some(message) = message
&& open.reply.is_none()
&& open.editing.is_none()
{
open.reply = Some(Replied::new(
message_id,
&crate::messages::Msg::from(message),
));
}
}
fn on_composer_edit(&mut self) {
let editing = self.open.as_ref().is_some_and(|o| o.editing.is_some());
let typing = !editing && self.composer.lines().iter().any(|l| !l.trim().is_empty());
self.set_typing(typing);
}
fn set_typing(&mut self, typing: bool) {
let place = self.open.as_ref().map(|o| (o.chat_id, o.topic));
if typing && let Some(place) = place {
let told = self
.typing
.is_some_and(|(at, when)| at == place && when.elapsed() < TYPING_EVERY);
if !told {
self.tg.send_typing(place.0, place.1, true);
self.typing = Some((place, Instant::now()));
}
} else if let Some(((chat_id, topic), _)) = self.typing.take() {
self.tg.send_typing(chat_id, topic, false);
}
}
fn toggle_recording(&mut self) {
if self.recording.is_some() {
self.stop_recording();
return;
}
let Some(open) = &self.open else {
return;
};
if let Some(why) = self.cant_send(open.chat_id) {
self.status = Some(why);
return;
}
let (chat_id, topic) = (open.chat_id, open.topic);
match Recorder::start(&self.outbox()) {
Ok(recorder) => {
self.recording = Some(Recording {
recorder,
chat_id,
topic,
});
}
Err(e) => {
self.status = Some(format!("{}{e:#}", lang::t("Can't record: ")));
}
}
}
fn stop_recording(&mut self) {
let Some(recording) = self.recording.take() else {
return;
};
let take = match recording.recorder.stop() {
Ok(take) => take,
Err(e) => {
self.status = Some(format!("{}{e:#}", lang::t("Can't record: ")));
return;
}
};
let length = crate::messages::duration(take.duration);
let chat_id = recording.chat_id;
let mut confirm = Confirm::new(
lang::t("Send the voice message?"),
vec![
self.chats.title(chat_id).unwrap_or_default().to_string(),
lang::f("Voice message, {length}", &[("length", &length)]),
],
Confirmed::Voice {
chat_id,
topic: recording.topic,
take,
},
);
confirm.badge = self.chats.badge(chat_id);
self.confirm = Some(confirm);
}
fn outbox(&self) -> PathBuf {
self.settings_path.with_file_name("outbox")
}
fn cancel_recording(&mut self) {
self.recording = None;
}
fn send_voice(&mut self, chat_id: i64, topic: Option<i32>, take: Take) {
if let Some(why) = self.cant_send(chat_id) {
self.status = Some(why);
return;
}
let (duration, waveform, temp) = (take.duration, take.waveform.clone(), take.into_path());
self.tg.send_voice(chat_id, topic, temp, duration, waveform);
if self.open.as_ref().is_some_and(|o| o.chat_id == chat_id) {
self.jump_to_newest();
}
}
fn send(&mut self, schedule_at: Option<i32>) {
if self.open.as_ref().is_some_and(|o| o.editing.is_some()) {
if schedule_at.is_none() {
self.save_edit();
}
return;
}
let Some(chat_id) = self.open.as_ref().map(|o| o.chat_id) else {
return;
};
let cant_send = self.cant_send(chat_id);
let secret = self.chats.is_secret(chat_id);
let Some(open) = self.open.as_mut() else {
return;
};
let text = self.composer.lines().join("\n");
let text = text.trim().to_string();
if text.is_empty() && open.attachments.is_empty() {
return;
}
if let Some(why) = cant_send {
self.status = Some(why);
return;
}
if let Some(changed) = open.attachments.iter().find(|a| a.swapped()) {
self.status = Some(lang::f(
"{name} changed since it was attached. Drop the files (Esc in Normal mode) and attach it again",
&[("name", &changed.name)],
));
return;
}
if schedule_at.is_some() && !open.attachments.is_empty() {
self.status = Some(
lang::t(
"Scheduled messages take text only: drop the files (Esc in Normal mode) first",
)
.into(),
);
return;
}
let reply_to = open.take_reply();
if open.attachments.is_empty() {
self.tg.send_text(
open.chat_id,
open.topic,
text,
reply_to,
secret,
schedule_at,
);
open.draft = (String::new(), None);
} else {
let as_files = open.as_files;
let groups = attach::albums(&open.attachments, as_files)
.into_iter()
.map(|album| album.iter().map(|a| a.upload(as_files)).collect())
.collect();
self.tg
.send_files(open.chat_id, open.topic, groups, text, reply_to);
open.attachments.clear();
open.dropped = None;
open.as_files = false;
}
self.composer = new_composer();
if self.settings.normal_after_send {
self.focus = Focus::Messages;
}
if let Some(at) = schedule_at {
self.set_typing(false);
let when = schedule::describe(at, &chrono::Local::now());
self.status = Some(lang::f("Scheduled for {when}", &[("when", &when)]));
} else {
self.typing = None;
self.jump_to_newest();
}
}
fn give_back_scheduled(&mut self, message: &Message, why: &str) {
let MessageContent::MessageText(text) = &message.content else {
return;
};
let topic = (self.forum.as_ref())
.filter(|f| f.chat_id == message.chat_id)
.map(|f| f.topic_of(message));
let here = self.open.as_ref().is_some_and(|o| {
o.chat_id == message.chat_id
&& o.editing.is_none()
&& (o.topic.is_none() || o.topic == topic)
});
if !here || !self.composer.is_empty() {
return;
}
let Some(written) = crate::tg::to_markdown(&text.text) else {
return;
};
self.composer.insert_str(written.markdown);
if let Some(MessageReplyTo::Message(r)) = &message.reply_to
&& r.chat_id == message.chat_id
&& let Some(open) = self.open.as_mut()
&& open.reply.is_none()
{
match open.messages.get(&r.message_id) {
Some(msg) => open.reply = Some(Replied::new(r.message_id, msg)),
None => {
open.draft_reply = Some(r.message_id);
self.tg.draft_reply(open.chat_id, open.topic, r.message_id);
}
}
}
self.status = Some(lang::f(
"Scheduled message not sent ({why}): its text is back in the composer",
&[("why", &why)],
));
}
fn open_schedule_prompt(&mut self) {
let Some(open) = self.open.as_ref() else {
self.status = Some(lang::t("Open a chat to schedule a message in it").into());
return;
};
if open.editing.is_some() {
self.status =
Some(lang::t("Scheduling sends a new message: finish the edit first").into());
return;
}
if !open.attachments.is_empty() {
self.status = Some(
lang::t(
"Scheduled messages take text only: drop the files (Esc in Normal mode) first",
)
.into(),
);
return;
}
if self.composer.lines().join("\n").trim().is_empty() {
self.status =
Some(lang::t("Write the message first, then :schedule when to send it").into());
return;
}
if let Some(why) = self.cant_send(open.chat_id) {
self.status = Some(why);
return;
}
if self.chats.is_secret(open.chat_id) {
self.status = Some(lang::t("Messages can't be scheduled in secret chats").into());
return;
}
self.open_prompt(PromptKind::Schedule);
}
fn schedule_send(&mut self, query: &str) {
match schedule::parse(query, chrono::Local::now()) {
Ok(at) => self.send(Some(at)),
Err(why) => self.status = Some(why),
}
}
fn open_prompt(&mut self, kind: PromptKind) {
let input = prompt_input("");
if kind == PromptKind::Attach && !self.can_attach() {
return;
}
self.prompt = Some(Prompt {
kind,
input,
completions: Vec::new(),
tabbed: None,
previous_filter: self.chats.filter().to_string(),
previous_selected: self.selected,
poll: None,
});
}
fn on_prompt_key(&mut self, key: KeyEvent, ctrl: bool) {
let Some(prompt) = self.prompt.as_mut() else {
return;
};
match key.code {
KeyCode::Esc => self.close_prompt(false),
KeyCode::Char('c') if ctrl => self.close_prompt(false),
KeyCode::Enter => self.close_prompt(true),
KeyCode::Char('m' | 'j') if ctrl => self.close_prompt(true),
KeyCode::Backspace if prompt.query().is_empty() => self.close_prompt(false),
KeyCode::Tab if prompt.kind == PromptKind::Attach => {
let completion = attach::complete(&prompt.query());
prompt.input = prompt_input(&completion.text);
prompt.completions = completion.matches;
}
KeyCode::Tab if prompt.kind == PromptKind::Command => prompt.complete_command(1),
KeyCode::BackTab if prompt.kind == PromptKind::Command => prompt.complete_command(-1),
KeyCode::Tab | KeyCode::BackTab if prompt.kind == PromptKind::Messages => {
let step = if key.code == KeyCode::Tab { 1 } else { -1 };
let typed = prompt.typed();
let today = chrono::Local::now().format("%Y-%m-%d").to_string();
let options = search::complete(&typed, &self.search_people(), &today);
if let Some(prompt) = self.prompt.as_mut() {
prompt.tab(step, typed, options);
}
}
_ => {
prompt.input.input(key);
prompt.completions.clear();
prompt.tabbed = None;
self.on_prompt_edit();
}
}
}
fn on_prompt_edit(&mut self) {
let Some(prompt) = self.prompt.as_ref() else {
return;
};
if prompt.kind == PromptKind::Chats {
self.chats.set_filter(prompt.query().trim());
self.chats.refresh();
self.selected = self.chats.ids().first().copied();
}
}
fn close_prompt(&mut self, submit: bool) {
let Some(prompt) = self.prompt.take() else {
return;
};
let query = prompt.query().trim().to_string();
match prompt.kind {
PromptKind::Chats => {
if submit && (query.is_empty() || !self.chats.ids().is_empty()) {
return;
}
if submit {
self.status = Some(lang::f("No chats match \"{query}\"", &[("query", &query)]));
}
self.chats.set_filter(&prompt.previous_filter);
self.selected = prompt.previous_selected;
}
PromptKind::Messages => {
if self.open.is_none() || !submit || query.is_empty() {
return;
}
let secret = self
.open
.as_ref()
.is_some_and(|o| self.chats.is_secret(o.chat_id));
let ask = search::parse(&query)
.and_then(|ask| match ask.from {
Some(_) if secret => {
Err(lang::t("from: doesn't work in secret chats").into())
}
_ => Ok(ask),
})
.and_then(|ask| self.resolve_sender(ask));
match ask {
Ok(ask) if ask.has.is_some() => {
self.open_media_menu(query, ask);
}
Ok(ask) => {
if let Some(open) = self.open.as_mut() {
open.search = Some(MessageSearch::new(query, ask));
}
self.go_to_match(0);
}
Err(why) => self.status = Some(why),
}
}
PromptKind::Attach if !submit || query.is_empty() => {}
PromptKind::Attach => {
let path = attach::expand_home(&query);
let paths = match attach::pasted_paths(&query) {
Some(paths) if !path.exists() => paths,
_ => vec![path],
};
self.attach(paths, None);
}
PromptKind::Proxy if !submit => {}
PromptKind::Proxy => self.ask_to_change_proxy(&query),
PromptKind::Schedule if !submit || query.is_empty() => {}
PromptKind::Schedule => self.schedule_send(&query),
PromptKind::Poll(_) if !submit => {}
PromptKind::Poll(step) => self.on_poll_step(step, prompt, &query),
PromptKind::Command if !submit || query.is_empty() => {}
PromptKind::Command => match Command::parse(&query) {
Some(Command::Info) => self.open_chat_info(),
Some(Command::Key) => self.show_key(),
Some(Command::Leave) => self.ask_to_leave(),
Some(Command::Logout) => self.ask_to_log_out(),
Some(Command::Poll) => self.start_poll(),
Some(Command::Proxy) => self.open_proxy_prompt(),
Some(Command::Schedule) => self.open_schedule_prompt(),
Some(Command::Secret) => self.ask_secret_chat(),
Some(Command::Timer) => self.open_timer_menu(),
None => self.status = Some(format!("{}{query}", lang::t("Not a command: "))),
},
}
}
fn mark_seen(&mut self) {
let Some(chat_id) = self.open.as_ref().map(|o| o.chat_id) else {
return;
};
let watching = self.watching(chat_id);
let mention = self.mention_seen();
let Some(open) = self.open.as_mut() else {
return;
};
let newest = open.messages.iter().rev().find(|(_, m)| !m.outgoing);
if watching
&& let Some((&id, _)) = newest
&& id > open.seen
{
open.seen = id;
open.set_mention_read(id);
self.tg.view_messages(open.chat_id, open.topic, vec![id]);
open.start_timers(false, id, SystemTime::now());
}
if let Some(id) = mention {
open.set_mention_read(id);
open.seen = open.seen.max(id);
self.tg.view_messages(open.chat_id, open.topic, vec![id]);
}
}
fn mention_seen(&self) -> Option<i64> {
let open = self.open.as_ref()?;
if !self.looking_at(open.chat_id)
|| self.busy()
|| self.focus != Focus::Messages
|| self.chats.is_secret(open.chat_id)
{
return None;
}
let id = open.cursor_id()?;
let msg = open.messages.get(&id)?;
(msg.mention && !msg.unplayed && !msg.outgoing && msg.state == SendState::Sent)
.then_some(id)
}
fn idle(&self) -> Duration {
let wall = SystemTime::now()
.duration_since(self.last_input_wall)
.unwrap_or_default();
self.last_input.elapsed().max(wall)
}
fn watching(&self, chat_id: i64) -> bool {
self.looking_at(chat_id)
&& self
.open
.as_ref()
.is_some_and(|o| o.at_newest && o.selected.is_none())
}
fn looking_at(&self, chat_id: i64) -> bool {
matches!(self.screen, Screen::Main)
&& self.present()
&& matches!(self.focus, Focus::Messages | Focus::Input)
&& !self.popup_open()
&& self.open.as_ref().is_some_and(|o| {
o.chat_id == chat_id
&& !matches!(o.loading, Some(Page::Around(_)))
&& o.topic.is_none_or(|t| {
self.forum.as_ref().is_some_and(|f| f.get(t).is_some())
})
})
}
fn cover_unseen(&mut self) {
let looking = self.focus == Focus::Messages && self.present() && !self.popup_open();
if let Some(open) = self.open.as_mut() {
open.cover_unless_viewed(looking);
}
}
fn present(&self) -> bool {
self.terminal_focused && self.idle() < self.away_after()
}
fn away_after(&self) -> Duration {
if self.focus_reported {
AWAY_AFTER
} else {
IDLE_AFTER
}
}
fn sees(&self, chat_id: i64, topic: Option<i32>) -> bool {
if self.photo_view.is_some() || self.video_view.is_some() {
return false;
}
if self.focus_reported {
self.terminal_focused
} else {
self.watching(chat_id)
&& self
.open
.as_ref()
.is_some_and(|o| o.topic.is_none() || o.topic == topic)
}
}
fn update_online(&mut self) {
let online = matches!(self.screen, Screen::Main)
&& self.quit_deadline.is_none()
&& self.terminal_focused
&& self.idle() < IDLE_AFTER;
if online != self.online {
self.online = online;
self.tg.set_online(online);
}
}
fn on_notifications(&mut self, update: UpdateNotificationGroup) {
self.notifier.remove(&update.removed_notification_ids);
let taken = update
.added_notifications
.iter()
.any(|n| matches!(n.r#type, NotificationType::NewSecretChat));
if taken && !self.settings.accept_secret_chats {
let who = self
.chats
.title(update.chat_id)
.unwrap_or(lang::t("Someone"));
self.status = Some(lang::f(
"{who} started a secret chat, which this computer took anyway: :leave ends it",
&[("who", &who)],
));
}
let chat_id = update.chat_id;
let no_sound = update.notification_sound_id == 0;
for notification in update.added_notifications {
let topic = match ¬ification.r#type {
NotificationType::NewMessage(new) => self
.forum
.as_ref()
.filter(|f| f.chat_id == chat_id)
.map(|f| f.topic_of(&new.message)),
_ => None,
};
if notification.date < self.notify_since {
continue;
}
let seen = self.sees(chat_id, topic);
if matches!(
notification.r#type,
NotificationType::NewMessage(_) | NotificationType::NewSecretChat
) {
self.ring_for(notification.is_silent || no_sound, seen);
}
if seen || self.notify_with == Notifications::Off {
continue;
}
let new = match notification.r#type {
NotificationType::NewMessage(new) => new,
NotificationType::NewSecretChat => {
let note = Note {
id: notification.id,
chat_id,
chat: lang::t("Secret chat").into(),
text: lang::t("Someone started a secret chat with you").into(),
silent: notification.is_silent || no_sound,
};
self.notifier.add(note, Instant::now());
continue;
}
_ => continue,
};
if self.chats.is_secret(chat_id) {
let note = Note {
id: notification.id,
chat_id,
chat: lang::t("Secret chat").into(),
text: lang::t("New message").into(),
silent: notification.is_silent || no_sound,
};
self.notifier.add(note, Instant::now());
continue;
}
let text = if new.show_preview {
self.notification_text(&new.message)
} else {
lang::t("New message").into()
};
let note = Note {
id: notification.id,
chat_id,
chat: format!(
"{}{}",
self.chats.title(chat_id).unwrap_or("Telegram"),
self.chats.badge(chat_id).map_or("", Badge::mark)
),
text,
silent: notification.is_silent || no_sound,
};
self.notifier.add(note, Instant::now());
}
}
fn notification_text(&self, message: &Message) -> String {
if let Some(service) = crate::service::Service::of(&message.content) {
let sender = Sender::from(&message.sender_id);
let name = |id| {
self.users
.get(&id)
.cloned()
.unwrap_or_else(|| lang::t("Someone").into())
};
let actor = match sender {
Sender::User(id) => name(id),
Sender::Chat(id) => self
.chats
.title(id)
.unwrap_or(lang::t("Someone"))
.to_string(),
};
let parts = service.sentence(sender, crate::service::Part::Name(actor), name);
return crate::service::text(&parts);
}
let text = crate::chats::content_text(&message.content);
match &message.sender_id {
MessageSender::User(sender) if sender.user_id != message.chat_id => {
match self.users.get(&sender.user_id) {
Some(name) => format!("{name}: {text}"),
None => text,
}
}
_ => text,
}
}
fn ring_for(&mut self, silent: bool, seen: bool) {
let now = Instant::now();
if silent
|| (seen && !self.settings.sound_when_focused)
|| self.over_ssh
|| self.rang_at.is_some_and(|at| now < at + RING_GAP)
{
return;
}
let Some(sound) = &self.sound else {
return;
};
self.rang_at = Some(now);
self.player.ring(Arc::clone(sound));
}
fn send_notification(&mut self) {
let Some(mut alert) = self.notifier.due(Instant::now()) else {
return;
};
if self.sound.is_some() && !self.over_ssh {
alert.silent = true;
}
self.notifications_sent += 1;
let id = self.notifications_sent;
let (with, in_tmux, over_ssh) = (self.notify_with, self.in_tmux, self.over_ssh);
if notify::goes_to_desktop(with, in_tmux, over_ssh, tmux::any_client_attached) {
notify::desktop(&alert);
return;
}
if let Some(code) = notify::escape(self.notify_with, &alert, id, self.in_tmux) {
notify::send(&code);
}
}
fn set_unread_chats(&mut self, count: i32) {
if count != self.unread_chats {
self.unread_chats = count;
notify::send(¬ify::title(count));
}
}
fn ask_to_leave(&mut self) {
let chat_id = match self.focus {
Focus::Chats => self.selected,
_ => self.open.as_ref().map(|o| o.chat_id),
};
let Some((chat_id, chat)) = chat_id.and_then(|id| Some((id, self.chats.get(id)?))) else {
self.status = Some(lang::t("Open the group or channel to leave first").into());
return;
};
if let Some(secret_id) = chat.secret_id {
let title = self.chats.title(chat_id).unwrap_or_default();
self.confirm = Some(Confirm::new(
lang::t("End this secret chat?"),
vec![
format!("{} {title}.", lang::t("With")),
lang::t("Nothing more can be sent in it, by either of you,").into(),
lang::t("and its messages are deleted from this computer.").into(),
],
Confirmed::EndSecret { chat_id, secret_id },
));
return;
}
if chat.is_private {
self.status = Some(lang::t("A chat with one person can't be left").into());
return;
}
if !self.chats.joined(chat_id) {
self.status = Some(lang::t("You're not in this chat").into());
return;
}
let title = self.chats.title(chat_id).unwrap_or_default();
let (ask, why) = if chat.is_channel {
(
lang::t("Leave this channel?"),
lang::t("Its posts stop coming to you."),
)
} else {
(
lang::t("Leave this group?"),
lang::t("Its messages stop coming to you."),
)
};
let mut confirm = Confirm::new(
ask,
vec![title.to_string(), why.into()],
Confirmed::Leave(chat_id),
);
confirm.badge = self.chats.badge(chat_id);
self.confirm = Some(confirm);
}
fn ask_to_read_chat(&mut self) {
let (chat_id, topic, unread, name) = match self.focus {
Focus::Topics => {
let Some(forum) = self.forum.as_ref() else {
return;
};
let Some(topic) = forum.current() else {
return;
};
(
forum.chat_id,
Some(topic.id),
topic.unread,
topic.name.clone(),
)
}
_ => {
let Some(chat_id) = self.selected else {
return;
};
if self.chats.is_forum(chat_id) {
self.ask_to_read_forum(chat_id);
return;
}
if self.chats.is_secret(chat_id) {
self.status = Some(lang::t("Open a secret chat to read it").into());
return;
}
let Some(chat) = self.chats.get(chat_id) else {
return;
};
(chat_id, None, chat.unread, chat.title.clone())
}
};
let marked = topic.is_none() && self.chats.get(chat_id).is_some_and(|c| c.marked_unread);
if unread == 0 && !marked {
self.status = Some(lang::t("Nothing unread in it").into());
return;
}
if unread > 0 && self.read_newest(chat_id, topic) == 0 {
self.status = Some(lang::t("Its messages aren't loaded yet").into());
return;
}
let mut lines = vec![
name,
lang::t("Everything in it shows as read,").into(),
lang::t("on all your devices.").into(),
];
if marked {
lines.push(lang::t("Its unread marker goes too.").into());
}
let mut confirm = Confirm::new(
lang::t("Mark all messages as read?"),
lines,
Confirmed::ReadChat { chat_id, topic },
);
confirm.badge = self.chats.badge(chat_id);
self.confirm = Some(confirm);
}
fn ask_to_read_forum(&mut self, chat_id: i64) {
if let Some(read) = &self.read_forum {
let forum = self.chats.title(read.chat_id).unwrap_or_default();
self.status = Some(lang::f(
"Still reading the topics of {forum}",
&[("forum", &forum)],
));
return;
}
let Some(chat) = self.chats.get(chat_id) else {
return;
};
let mut lines = vec![
chat.title.clone(),
lang::t("Every topic in it shows as read,").into(),
lang::t("on all your devices.").into(),
];
if chat.marked_unread {
lines.push(lang::t("Its unread marker goes too.").into());
}
let mut confirm = Confirm::new(
lang::t("Mark all its topics as read?"),
lines,
Confirmed::ReadForum { chat_id },
);
confirm.badge = self.chats.badge(chat_id);
self.confirm = Some(confirm);
}
fn read_forum(&mut self, chat_id: i64) {
let request = self.topics_asked.wrapping_add(1);
self.topics_asked = request;
let from = topics::Offset::default();
self.read_forum = Some(ForumRead {
chat_id,
page: Some((request, from)),
topics: HashSet::new(),
waiting: VecDeque::new(),
});
self.tg.forum_topics(chat_id, request, from);
}
fn read_forum_page(&mut self, chat_id: i64, request: u32, page: Option<&ForumTopics>) {
let Some(read) = self.read_forum.as_mut() else {
return;
};
if read.chat_id != chat_id || read.page.map(|(asked, _)| asked) != Some(request) {
return;
}
let from = read.page.map(|(_, from)| from).unwrap_or_default();
read.page = None;
let Some(page) = page else {
self.read_forum = None;
self.status = Some(lang::t("Its topics couldn't be read").into());
return;
};
let next = topics::Offset {
date: page.next_offset_date,
message_id: page.next_offset_message_id,
topic_id: page.next_offset_forum_topic_id,
};
let more = !page.topics.is_empty() && next != topics::Offset::default() && next != from;
let mut read_now = Vec::new();
for topic in &page.topics {
let id = topic.info.forum_topic_id;
let newest = topic.last_message.as_ref().map(|m| m.id);
match topic_read(topic.unread_count, newest, topic.last_read_inbox_message_id) {
TopicRead::Now(newest) => read_now.push((id, newest)),
TopicRead::Done => {}
TopicRead::Ask => read.waiting.push_back(id),
}
}
if more {
let request = self.topics_asked.wrapping_add(1);
self.topics_asked = request;
read.page = Some((request, next));
}
let page_ask = read.page;
for (id, newest) in read_now {
self.read_up_to(chat_id, Some(id), newest);
}
if let Some((request, from)) = page_ask {
self.tg.forum_topics(chat_id, request, from);
}
self.ask_read_topics();
self.finish_forum_read();
}
fn ask_read_topics(&mut self) {
let Some(read) = self.read_forum.as_mut() else {
return;
};
while read.topics.len() < FORUM_READ_ASKS
&& let Some(id) = read.waiting.pop_front()
{
read.topics.insert((read.chat_id, id));
self.tg.forum_topic(read.chat_id, id);
}
}
fn read_forum_topic(&mut self, chat_id: i64, topic_id: i32, topic: Option<&ForumTopic>) {
if let Some(read) = self.read_forum.as_mut() {
read.topics.remove(&(chat_id, topic_id));
}
if let Some(last) = topic
.filter(|t| t.unread_count > 0)
.and_then(|t| t.last_message.as_ref())
{
self.read_up_to(chat_id, Some(topic_id), last.id);
}
self.ask_read_topics();
self.finish_forum_read();
}
fn finish_forum_read(&mut self) {
if !self
.read_forum
.as_ref()
.is_some_and(|r| r.page.is_none() && r.topics.is_empty() && r.waiting.is_empty())
{
return;
}
let Some(read) = self.read_forum.take() else {
return;
};
self.mark_chat_read(read.chat_id, None);
self.status = Some(lang::t("Its topics are read").into());
}
fn read_newest(&self, chat_id: i64, topic: Option<i32>) -> i64 {
match topic {
Some(id) => self
.forum
.as_ref()
.and_then(|f| f.get(id))
.map_or(0, |t| t.newest()),
None => self.chats.last_message(chat_id),
}
}
fn mark_chat_read(&mut self, chat_id: i64, topic: Option<i32>) {
let newest = self.read_newest(chat_id, topic);
if newest != 0 {
self.read_up_to(chat_id, topic, newest);
}
if topic.is_none() && self.chats.get(chat_id).is_some_and(|c| c.marked_unread) {
self.unmark_unread(chat_id);
}
}
fn read_up_to(&mut self, chat_id: i64, topic: Option<i32>, newest: i64) {
self.tg.view_messages(chat_id, topic, vec![newest]);
if let Some(open) = self
.open
.as_mut()
.filter(|o| o.chat_id == chat_id && o.topic == topic)
{
open.seen = open.seen.max(newest);
open.start_timers(false, newest, SystemTime::now());
}
}
fn command_chat(&self) -> Option<i64> {
match self.focus {
Focus::Chats => self.selected,
_ => self.open.as_ref().map(|o| o.chat_id),
}
}
fn ask_secret_chat(&mut self) {
let Some(user_id) = self.command_chat().and_then(|id| self.chats.person(id)) else {
self.status =
Some(lang::t("Open a chat with someone to start a secret chat with them").into());
return;
};
if self.chats.is_bot(user_id) {
self.status = Some(lang::t("Bots can't be in secret chats").into());
return;
}
let with = self
.users
.get(&user_id)
.cloned()
.unwrap_or_else(|| lang::t("them").into());
let lines = vec![
lang::f(
"With {with}. It's end-to-end encrypted, and kept only",
&[("with", &with)],
),
lang::t("on this computer and on the device of theirs that").into(),
lang::t("accepts it: your other devices won't have it.").into(),
];
self.confirm = Some(Confirm::new(
lang::t("Start a secret chat?"),
lines,
Confirmed::StartSecret { user_id, with },
));
let badge = self.command_chat().and_then(|id| self.chats.badge(id));
if let Some(confirm) = self.confirm.as_mut() {
confirm.badge = badge;
}
}
fn open_secret_chat(&mut self) -> Option<(i64, Secret)> {
let found = self
.open
.as_ref()
.map(|o| o.chat_id)
.filter(|&id| self.chats.is_secret(id))
.and_then(|id| Some((id, self.chats.secret(id)?.clone())));
if found.is_none() {
self.status = Some(lang::t("Open a secret chat first (:secret starts one)").into());
}
found
}
fn open_timer_menu(&mut self) {
let Some((chat_id, _)) = self.open_secret_chat() else {
return;
};
if let Some(why) = self.cant_send(chat_id) {
self.status = Some(why);
return;
}
self.timer_menu = Some(TimerMenu::new(chat_id, self.chats.auto_delete(chat_id)));
}
fn on_timer_key(&mut self, key: KeyEvent) {
let Some(menu) = self.timer_menu.as_mut() else {
return;
};
let last = menu.choices.len() - 1;
match key.code {
KeyCode::Char('j') | KeyCode::Down => menu.selected = (menu.selected + 1).min(last),
KeyCode::Char('k') | KeyCode::Up => menu.selected = menu.selected.saturating_sub(1),
KeyCode::Char('g') => menu.selected = 0,
KeyCode::Char('G') => menu.selected = last,
KeyCode::Enter | KeyCode::Char('l') => {
let (chat_id, seconds) = (menu.chat_id, menu.choices[menu.selected]);
self.timer_menu = None;
if let Some(why) = self.cant_send(chat_id) {
self.status = Some(why);
return;
}
if seconds != self.chats.auto_delete(chat_id) {
self.tg.set_timer(chat_id, seconds);
self.chats.set_auto_delete(chat_id, seconds);
}
}
KeyCode::Esc | KeyCode::Char('q' | 'h') => self.timer_menu = None,
_ => {}
}
}
fn show_key(&mut self) {
let Some((chat_id, secret)) = self.open_secret_chat() else {
return;
};
let with = self
.chats
.title(chat_id)
.unwrap_or(lang::t("them"))
.to_string();
if crate::secret::key_picture(&secret.key_hash).is_none() {
self.status = Some(match secret.state {
SecretState::Pending => lang::f(
"The key is made once {with} accepts the secret chat",
&[("with", &with)],
),
_ => lang::t("Telegram gave no key to compare for this chat").into(),
});
return;
}
self.key_view = Some(KeyView {
chat_id,
with,
hash: secret.key_hash,
});
}
fn ask_to_log_out(&mut self) {
let mut lines: Vec<String> = vec![
lang::t("This ends the session on Telegram and deletes what").into(),
lang::t("tuigram keeps on this computer. Logging in again").into(),
lang::t("takes a code, and your password if you have one.").into(),
];
if self.chats.has_secret_chats() {
lines.push(lang::t("Your secret chats go too: they're kept only here.").into());
}
self.confirm = Some(Confirm::new(lang::t("Log out?"), lines, Confirmed::Logout));
}
fn log_out(&mut self) {
self.tg.log_out();
self.relogin = true;
self.screen = login_screen(LoginStep::LoggingOut);
}
fn forget_session(&mut self) {
self.settings.highlighted_chats.clear();
if let Err(e) = self.settings.save(&self.settings_path) {
self.status = Some(format!("{}{e:#}", lang::t("Couldn't save settings: ")));
}
self.chats = Chats::default();
self.users.clear();
self.selected = None;
self.open = None;
self.forum = None;
self.read_forum = None;
self.focus = Focus::Chats;
self.composer = new_composer();
self.images.forget_files();
self.player.stop();
self.recording = None;
self.inline_video = None;
self.opening.clear();
self.revealing.clear();
self.copying.clear();
self.close_popups();
self.finding = None;
self.completion = None;
self.stickers = None;
self.premium = false;
self.prompt = None;
self.resizing = None;
self.loading_lists.clear();
self.loaded_lists.clear();
self.wanted_lists.clear();
self.jumps = Jumps::default();
self.pending_g = false;
self.online = false;
self.typing = None;
self.notifier.clear();
self.notify_since = i32::MAX;
self.set_unread_chats(0);
}
fn next_match(&mut self, step: isize) {
let Some(search) = self.open.as_ref().and_then(|o| o.search.as_ref()) else {
return;
};
let Some(current) = search.current else {
return;
};
match current.checked_add_signed(step) {
Some(index) => self.go_to_match(index),
None => self.status = Some(lang::t("No newer matches").into()),
}
}
fn go_to_match(&mut self, index: usize) {
let Some(open) = self.open.as_mut() else {
return;
};
let Some(search) = open.search.as_mut() else {
return;
};
if let Some(&id) = search.results.get(index) {
search.current = Some(index);
self.jump_to_message(id);
} else if !search.done {
search.wanted = Some(index);
if !search.loading {
search.loading = true;
let (query, ask) = (search.query.clone(), search.ask.clone());
let (from, offset) = (search.next_from, search.next_offset.clone());
let secret = self.chats.is_secret(open.chat_id);
self.tg.search_messages(
open.chat_id,
open.topic,
secret,
query,
ask,
from,
offset,
SEARCH_PAGE,
);
}
} else if search.results.is_empty() {
self.status = Some(lang::f(
"No messages match \"{query}\"",
&[("query", &search.query)],
));
open.search = None;
} else {
self.status = Some(lang::t("No older matches").into());
}
}
fn jump_to_message(&mut self, id: i64) {
let Some(open) = self.open.as_mut() else {
return;
};
open.unread_after = None;
if open.messages.contains_key(&id) {
open.selected = Some(id);
if matches!(open.loading, Some(Page::Around(_))) {
open.loading = None;
}
return;
}
let page = Page::Around(id);
open.loading = Some(page);
self.tg
.load_history(open.chat_id, open.topic, page, HISTORY_PAGE);
}
fn jump_to_newest(&mut self) {
let Some(open) = self.open.as_mut() else {
return;
};
open.unread_after = None;
open.selected = None;
if open.at_newest && !matches!(open.loading, Some(Page::Around(_))) {
return;
}
open.messages.clear();
open.scroll = None;
open.layout = None;
open.at_newest = true;
open.all_loaded = false;
open.loading = None;
self.load_older_messages();
}
fn open_selected_chat(&mut self) {
if let Some(chat_id) = self.selected {
self.open_chat(chat_id);
}
}
fn open_chat(&mut self, chat_id: i64) {
if let Some(here) = self.here().filter(|h| h.chat_id != chat_id) {
self.jumps.leave(here);
}
self.enter_chat(chat_id);
}
fn here(&self) -> Option<Jump> {
self.open.as_ref().map(|o| Jump {
chat_id: o.chat_id,
topic: o.topic,
message_id: o.selected,
})
}
fn jump(&mut self, back: bool) {
let here = self.here();
match self.jumps.go(back, here) {
Some(to) => {
let entered = self
.open
.as_ref()
.is_none_or(|o| o.place() != (to.chat_id, to.topic));
if entered {
self.enter_chat(to.chat_id);
if let Some(topic) = to.topic {
self.enter_topic(topic);
}
}
if self
.open
.as_ref()
.is_none_or(|o| o.place() != (to.chat_id, to.topic))
{
return;
}
self.focus = Focus::Messages;
match to.message_id {
Some(id) => self.jump_to_message(id),
None if entered => {}
None => self.jump_to_newest(),
}
}
None if back => self.status = Some(lang::t("Nothing to go back to").into()),
None => self.status = Some(lang::t("Nothing to go forward to").into()),
}
}
fn enter_chat(&mut self, chat_id: i64) {
self.close_chat_popups();
if self.chats.in_list(chat_id, self.chats.shown()) && self.selected != Some(chat_id) {
if !self.chats.ids().contains(&chat_id) {
self.chats.set_filter("");
}
self.selected = Some(chat_id);
}
if self.chats.is_forum(chat_id) {
self.enter_forum(chat_id);
return;
}
self.focus = Focus::Messages;
let marked = self.chats.get(chat_id).is_some_and(|c| c.marked_unread);
if self.open.as_ref().is_some_and(|o| o.chat_id == chat_id) {
if marked {
self.chats.opened(chat_id);
self.unmark_unread(chat_id);
}
return;
}
self.leave_chat();
self.tg.open_chat(chat_id);
self.chats.opened(chat_id);
if marked {
self.unmark_unread(chat_id);
}
let mut open = OpenChat::new(chat_id);
if self.chats.get(chat_id).is_some_and(|c| c.unread > 0) {
open.open_at_unread(self.chats.read_inbox(chat_id));
}
self.show_messages(open);
}
fn enter_forum(&mut self, chat_id: i64) {
self.focus = Focus::Topics;
let marked = self.chats.get(chat_id).is_some_and(|c| c.marked_unread);
if self.forum.as_ref().is_some_and(|f| f.chat_id == chat_id) {
if marked {
self.chats.opened(chat_id);
self.unmark_unread(chat_id);
}
return;
}
self.leave_chat();
self.tg.open_chat(chat_id);
self.chats.opened(chat_id);
if marked {
self.unmark_unread(chat_id);
}
self.composer = new_composer();
self.forum = Some(Forum::new(chat_id));
self.ask_topics();
}
fn open_topic(&mut self, topic_id: i32) {
let Some(chat_id) = self.forum.as_ref().map(|f| f.chat_id) else {
return;
};
if let Some(here) = self
.here()
.filter(|h| (h.chat_id, h.topic) != (chat_id, Some(topic_id)))
{
self.jumps.leave(here);
}
self.enter_topic(topic_id);
}
fn enter_topic(&mut self, topic_id: i32) {
let Some(forum) = self.forum.as_mut() else {
return;
};
forum.selected = Some(topic_id);
let chat_id = forum.chat_id;
if forum.get(topic_id).is_none() {
self.ask_topic(topic_id);
}
self.focus = Focus::Messages;
if self
.open
.as_ref()
.is_some_and(|o| o.place() == (chat_id, Some(topic_id)))
{
return;
}
self.close_chat_popups();
self.leave_messages();
let mut open = OpenChat::new(chat_id);
open.topic = Some(topic_id);
if let Some(read) = self
.forum
.as_ref()
.and_then(|f| f.get(topic_id))
.filter(|t| t.unread > 0)
.map(|t| t.read_inbox())
{
open.open_at_unread(read);
}
self.show_messages(open);
}
fn topic_known(&mut self) {
let Some(open) = self.open.as_mut().filter(|o| {
o.unread_line.is_none()
&& o.selected.is_none()
&& o.seen == 0
&& !matches!(o.loading, Some(Page::Around(_)))
}) else {
return;
};
let Some(read) = open
.topic
.and_then(|id| self.forum.as_ref()?.get(id))
.filter(|t| t.unread > 0)
.map(|t| t.read_inbox())
else {
return;
};
open.open_at_unread(read);
match open.first_page() {
Page::Latest => {}
page => self.load_page(page),
}
}
fn open_selected_topic(&mut self) {
let id = self
.forum
.as_ref()
.and_then(|f| f.current().map(|t| t.id).or(f.selected));
if let Some(id) = id {
self.open_topic(id);
}
}
fn ask_topics(&mut self) {
let request = self.topics_asked.wrapping_add(1);
if let Some(forum) = self.forum.as_mut()
&& let Some(from) = forum.page_to_ask(request)
{
self.topics_asked = request;
self.tg.forum_topics(forum.chat_id, request, from);
}
}
fn ask_topic(&mut self, topic_id: i32) {
if let Some(forum) = self.forum.as_mut()
&& forum.ask(topic_id)
{
self.tg.forum_topic(forum.chat_id, topic_id);
}
}
fn move_topic_cursor(&mut self, delta: isize) {
if let Some(forum) = self.forum.as_mut() {
forum.move_cursor(delta);
}
self.ask_topics();
}
fn left_of_messages(&self) -> Focus {
match (&self.open, &self.forum) {
(Some(open), Some(_)) if open.topic.is_some() => Focus::Topics,
_ => Focus::Chats,
}
}
fn close_chat_popups(&mut self) {
self.finding = None;
self.close_message_popups();
}
fn close_popups(&mut self) {
self.close_message_popups();
self.confirm = None;
self.notice = None;
self.settings_menu = None;
self.picker = None;
}
fn close_message_popups(&mut self) {
self.menu = None;
self.delete_menu = None;
self.react_menu = None;
self.vote_menu = None;
self.button_menu = None;
self.pin_menu = None;
self.pinned_menu = None;
self.media_menu = None;
self.timer_menu = None;
self.key_view = None;
self.photo_view = None;
self.video_view = None;
self.chat_info = None;
self.text_select = None;
}
fn leave_chat(&mut self) {
self.leave_messages();
let open = self.open.take().map(|o| o.chat_id);
let forum = self.forum.take().map(|f| f.chat_id);
if let Some(chat_id) = open.or(forum) {
self.tg.close_chat(chat_id);
}
}
fn close_open_chat(&mut self) {
if self.open.is_none() && self.forum.is_none() {
return;
}
self.close_chat_popups();
self.leave_chat();
self.focus = Focus::Chats;
}
fn leave_messages(&mut self) {
self.keep_draft();
self.set_typing(false);
self.pasting = false;
self.player.stop();
self.inline_video = None;
self.recording = None;
if self.open.is_some() {
self.images.clear();
}
}
fn show_messages(&mut self, mut open: OpenChat) {
let page = open.first_page();
self.composer = new_composer();
let draft = match open.topic {
Some(topic) => self
.forum
.as_ref()
.and_then(|f| f.get(topic))
.and_then(|t| t.draft.as_ref()),
None => self.chats.draft(open.chat_id),
};
if let Some(draft) = draft.cloned() {
self.composer.insert_str(&draft.text);
if let Some(id) = draft.reply_to {
open.draft_reply = Some(id);
self.tg.draft_reply(open.chat_id, open.topic, id);
}
open.draft = (draft.text, draft.reply_to);
}
self.open = Some(open);
match page {
Page::Latest => self.load_older_messages(),
page => self.load_page(page),
}
self.ask_pinned();
}
fn load_page(&mut self, page: Page) {
if let Some(open) = self.open.as_mut() {
open.loading = Some(page);
self.tg
.load_history(open.chat_id, open.topic, page, HISTORY_PAGE);
}
}
fn ask_pinned(&mut self) {
if let Some(open) = self
.open
.as_mut()
.filter(|o| !self.chats.is_secret(o.chat_id))
{
open.pinned_asked += 1;
self.tg
.pinned_messages(open.chat_id, open.topic, open.pinned_asked);
}
}
fn on_pinned(
&mut self,
place: (i64, Option<i32>),
request: u32,
messages: Option<Vec<Message>>,
) {
let Some(open) = self
.open
.as_mut()
.filter(|o| o.place() == place && o.pinned_asked == request)
else {
return;
};
let Some(messages) = messages else {
return;
};
open.pinned = messages
.into_iter()
.map(|m| {
let id = m.id;
Pinned::new(id, &m.into())
})
.collect();
if open.pinned.is_empty() {
self.pinned_menu = None;
}
}
fn toggle_pin_message(&mut self) {
let Some(open) = &self.open else {
return;
};
let Some((&id, msg)) = open
.cursor_id()
.and_then(|id| open.messages.get_key_value(&id))
else {
return;
};
match msg.state {
SendState::Pending => self.status = Some(lang::t("Wait until it's sent").into()),
SendState::Failed { .. } => {
self.status = Some(lang::t("This message wasn't sent").into())
}
SendState::Sent if msg.pinned => self.tg.unpin_message(open.chat_id, id),
SendState::Sent => {
let chat = self.chats.get(open.chat_id);
let place = match chat {
_ if self.chats.is_saved(open.chat_id) => Place::Saved,
Some(c) if c.is_private => Place::Private,
Some(c) if c.is_channel => Place::Channel,
_ => Place::Group,
};
let with = self
.chats
.title(open.chat_id)
.unwrap_or(lang::t("them"))
.to_string();
self.pin_menu = Some(PinMenu::new(id, msg.snippet(), place, with));
self.tg.check_pinnable(open.chat_id, id);
}
}
}
fn on_pinnable(&mut self, chat_id: i64, message_id: i64, pinnable: Option<bool>) {
if self.open.as_ref().is_none_or(|o| o.chat_id != chat_id) {
return;
}
let Some(menu) = self
.pin_menu
.as_mut()
.filter(|m| m.message_id == message_id)
else {
return;
};
match pinnable {
None => self.pin_menu = None,
Some(false) => {
self.pin_menu = None;
self.status = Some(lang::t("You can't pin messages here").into());
}
Some(true) if menu.choices.is_empty() => menu.allow(),
Some(true) => {}
}
}
fn on_pin_key(&mut self, key: KeyEvent) {
let Some(menu) = self.pin_menu.as_mut() else {
return;
};
let last = menu.choices.len().saturating_sub(1);
let pick = match key.code {
KeyCode::Char('j') | KeyCode::Down => {
menu.selected = (menu.selected + 1).min(last);
None
}
KeyCode::Char('k') | KeyCode::Up => {
menu.selected = menu.selected.saturating_sub(1);
None
}
KeyCode::Enter | KeyCode::Char('l') => Some(menu.selected),
KeyCode::Char(c @ '1'..='9') => Some(c as usize - '1' as usize),
KeyCode::Esc | KeyCode::Char('q' | 'h') => {
self.pin_menu = None;
return;
}
_ => None,
};
let Some(choice) = pick.and_then(|i| menu.choices.get(i).copied()) else {
return;
};
let message_id = menu.message_id;
self.pin_menu = None;
if let Some(open) = &self.open {
let (quietly, only_for_self) = choice.flags();
self.tg
.pin_message(open.chat_id, message_id, quietly, only_for_self);
}
}
fn open_pinned_menu(&mut self) {
let Some(open) = &self.open else {
return;
};
self.pinned_menu = PinnedMenu::new(&open.pinned);
if self.pinned_menu.is_none() {
self.status = Some(lang::t("No pinned messages in this chat").into());
}
}
fn open_media_menu(&mut self, query: String, ask: search::Query) {
let Some(open) = self.open.as_ref() else {
return;
};
let mut menu = MediaMenu::new(query, ask);
menu.loading = true;
let secret = self.chats.is_secret(open.chat_id);
self.tg.search_messages(
open.chat_id,
open.topic,
secret,
menu.query.clone(),
menu.ask.clone(),
0,
String::new(),
SEARCH_PAGE,
);
self.media_menu = Some(menu);
}
fn on_media_key(&mut self, key: KeyEvent, ctrl: bool) {
let grid =
self.media_menu.as_ref().is_some_and(|m| m.wants_grid()) && self.images.draws_photos();
let Some(menu) = self.media_menu.as_mut() else {
return;
};
if matches!(key.code, KeyCode::Enter) || (matches!(key.code, KeyCode::Char('l')) && !grid) {
let id = menu.current().map(|r| r.id);
self.media_menu = None;
if let Some(id) = id {
if let Some(here) = self.here() {
self.jumps.leave(here);
}
self.jump_to_message(id);
}
return;
}
match key.code {
KeyCode::Char('j') | KeyCode::Down if grid => menu.move_by_grid(menu.grid_columns, 1),
KeyCode::Char('k') | KeyCode::Up if grid => menu.move_by_grid(menu.grid_columns, -1),
KeyCode::Char('h') | KeyCode::Left if grid => menu.move_by(-1),
KeyCode::Char('l') | KeyCode::Right if grid => menu.move_by(1),
KeyCode::Char('d') if ctrl && grid => menu.move_by_grid(menu.grid_page, 1),
KeyCode::Char('u') if ctrl && grid => menu.move_by_grid(menu.grid_page, -1),
KeyCode::PageDown if grid => menu.move_by_grid(menu.grid_page, 1),
KeyCode::PageUp if grid => menu.move_by_grid(menu.grid_page, -1),
KeyCode::Char('-') if grid => {
self.media_columns = self
.media_columns
.saturating_sub(1)
.max(search::GRID_MIN_COLUMNS)
}
KeyCode::Char('=') if grid => {
self.media_columns = (self.media_columns + 1).min(search::GRID_MAX_COLUMNS)
}
KeyCode::Char('j') | KeyCode::Down => menu.move_by(1),
KeyCode::Char('k') | KeyCode::Up => menu.move_by(-1),
KeyCode::Char('d') if ctrl => menu.move_by(20),
KeyCode::Char('u') if ctrl => menu.move_by(-20),
KeyCode::Char('g') => menu.jump(false),
KeyCode::Char('G') => menu.jump(true),
KeyCode::Esc | KeyCode::Char('q') => self.media_menu = None,
KeyCode::Char('h') if !grid => self.media_menu = None,
KeyCode::Char('O') => {
let file_id = menu.current().and_then(|r| r.file_id);
match file_id {
Some(id) if self.revealing.insert(id) => {
self.tg.download(id);
self.status =
Some(lang::t("Downloading to show in the file manager…").into());
}
Some(_) => {}
None => self.status = Some(lang::t("No file in this message").into()),
}
}
_ => {}
}
}
fn on_pinned_key(&mut self, key: KeyEvent) {
let (Some(open), Some(menu)) = (&self.open, self.pinned_menu.as_mut()) else {
self.pinned_menu = None;
return;
};
let current = menu.current(&open.pinned).map(|p| p.id);
match key.code {
KeyCode::Char('j') | KeyCode::Down => menu.move_by(&open.pinned, 1),
KeyCode::Char('k') | KeyCode::Up => menu.move_by(&open.pinned, -1),
KeyCode::Char('g') => menu.move_by(&open.pinned, isize::MIN),
KeyCode::Char('G') => menu.move_by(&open.pinned, isize::MAX),
KeyCode::Enter | KeyCode::Char('l') => {
self.pinned_menu = None;
if let Some(id) = current {
if let Some(here) = self.here() {
self.jumps.leave(here);
}
self.jump_to_message(id);
}
}
KeyCode::Char('P') => {
if let Some(id) = current {
self.tg.unpin_message(open.chat_id, id);
}
}
KeyCode::Esc | KeyCode::Char('q' | 'h') => self.pinned_menu = None,
_ => {}
}
}
fn open_selected_message(&mut self) {
if self.resend_selected() {
return;
}
let Some(open) = self.open.as_mut() else {
return;
};
if let Some(id) = open.cursor_id()
&& open.uncover(id)
{
let photo = open
.messages
.get(&id)
.filter(|m| !m.outgoing && m.state == SendState::Sent)
.and_then(|m| m.preview.as_ref())
.map(|p| p.file_id);
if let Some(file_id) = photo {
open.opening = Some((id, file_id));
self.tg.download(file_id);
}
return;
}
if let Some(id) = open.cursor_id()
&& open.reveal_spoilers(id)
{
return;
}
if let Some(id) = open.cursor_id()
&& self.player.is_on(open.chat_id, id)
{
self.player.toggle();
return;
}
if let Some((&id, msg)) = open
.cursor_id()
.and_then(|id| open.messages.get_key_value(&id))
&& let Some(poll) = &msg.poll
{
match (msg.state, poll.cant_vote()) {
(SendState::Sent, None) => self.vote_menu = Some(VoteMenu::new(id, poll)),
(SendState::Sent, Some(why)) => self.status = Some(why.into()),
_ => self.status = Some(lang::t("Wait until it's sent").into()),
}
return;
}
if let Some((&id, msg)) = open
.cursor_id()
.and_then(|id| open.messages.get_key_value(&id))
&& let Some(keyboard) = &msg.keyboard
{
match msg.state {
SendState::Sent => {
let Some((_, captioned)) = open.caption_holder() else {
return;
};
self.button_menu = Some(ButtonMenu::new(
id,
msg.snippet(),
keyboard,
openable_file(msg),
&captioned.links,
));
}
_ => self.status = Some(lang::t("Wait until it's sent").into()),
}
return;
}
let Some((&id, msg)) = open
.cursor_id()
.and_then(|id| open.messages.get_key_value(&id))
else {
return;
};
let file = openable_file(msg).map(|file| file_target(id, msg, file.clone()));
let mut targets: Vec<Target> = file.into_iter().collect();
let Some((_, captioned)) = open.caption_holder() else {
return;
};
targets.extend(captioned.links.iter().cloned().map(Target::Link));
match targets.len() {
0 if opens_once(msg) => {
self.status = Some(format!(
"{}: {}",
lang::t("tuigram can't show this only while it's open"),
crate::messages::on_phone()
));
}
0 => self.status = Some(lang::t("Nothing to open in this message").into()),
1 => self.open_target(targets.remove(0)),
_ => {
self.menu = Some(PickMenu {
action: MenuAction::Open,
targets,
selected: 0,
})
}
}
}
fn resend_selected(&mut self) -> bool {
let Some(open) = self.open.as_ref() else {
return false;
};
let Some((id, msg)) = open
.cursor_id()
.and_then(|id| open.messages.get_key_value(&id))
else {
return false;
};
let SendState::Failed { can_retry } = msg.state else {
return false;
};
let (chat_id, ids) = (open.chat_id, open.retry_ids(*id));
if !can_retry {
self.status =
Some(lang::t("Telegram won't take this message again: `d` deletes it").into());
} else if let Some(why) = self.cant_send(chat_id) {
self.status = Some(why);
} else {
self.tg.resend(chat_id, ids);
}
true
}
fn reply_to_selected(&mut self) {
self.end_edit();
let Some(open) = self.open.as_mut() else {
return;
};
let Some((&id, msg)) = open
.cursor_id()
.and_then(|id| open.messages.get_key_value(&id))
else {
return;
};
if matches!(msg.state, SendState::Failed { .. }) {
self.status = Some(lang::t("Can't reply to a message that wasn't sent").into());
return;
}
open.reply = Some(Replied::new(id, msg));
open.draft_reply = None;
self.focus = Focus::Input;
}
fn edit_selected(&mut self) {
let Some(open) = &self.open else {
return;
};
let Some(id) = open.edit_target() else {
return;
};
match open.cant_edit(id) {
Some(why) => self.status = Some(why.into()),
None => self.tg.check_editable(open.chat_id, id),
}
}
fn on_editable(
&mut self,
chat_id: i64,
message_id: i64,
editable: Option<bool>,
text: Option<EditText>,
) {
let Some(open) = self
.open
.as_ref()
.filter(|o| o.chat_id == chat_id && o.edit_target() == Some(message_id))
else {
return;
};
let Some(msg) = open.messages.get(&message_id) else {
return;
};
if self.over_panes() {
self.status =
Some(lang::t("The edit came while something else was open: e edits again").into());
return;
}
let (text, loses) = match text {
Some(text) => (text.markdown, text.loses),
None => (msg.source_text.clone(), msg.formatted),
};
match editable {
None => {}
Some(false) => self.status = Some(lang::t("You can't edit this message").into()),
Some(true) if loses => {
self.confirm = Some(Confirm::new(
lang::t("Edit and lose some formatting?"),
vec![
lang::t("Some of its formatting can't be written in Markdown").into(),
lang::t("(underline, custom emoji…), so an edit would lose it.").into(),
],
Confirmed::Edit {
id: message_id,
text,
},
));
}
Some(true) => self.start_edit(message_id, text),
}
}
fn start_edit(&mut self, id: i64, text: String) {
self.end_edit();
let Some(open) = self.open.as_mut() else {
return;
};
let Some(msg) = open.messages.get(&id) else {
return;
};
open.editing = Some(Editing {
id,
snippet: msg.snippet(),
original: text.clone(),
editable: msg.editable,
draft: self.composer.lines().join("\n"),
reply: open.reply.take(),
attachments: std::mem::take(&mut open.attachments),
});
open.dropped = None;
self.set_typing(false);
self.composer = new_composer();
self.composer.insert_str(text);
self.focus = Focus::Input;
}
fn end_edit(&mut self) {
let Some(editing) = self.open.as_mut().and_then(|o| o.editing.take()) else {
return;
};
self.composer = new_composer();
self.composer.insert_str(editing.draft);
if let Some(open) = self.open.as_mut() {
open.reply = editing.reply;
open.attachments = editing.attachments;
}
}
fn save_edit(&mut self) {
let Some(open) = &self.open else {
return;
};
let Some(editing) = &open.editing else {
return;
};
let text = self.composer.lines().join("\n");
let text = text.trim();
if text.is_empty() && editing.editable == Editable::Text {
self.status = Some(lang::t("A message can't be empty (d deletes it)").into());
return;
}
if text != editing.original.trim() {
let (chat_id, id, text) = (open.chat_id, editing.id, text.to_string());
match editing.editable {
Editable::Text => self.tg.edit_text(chat_id, id, text),
Editable::Caption { above } => self.tg.edit_caption(chat_id, id, text, above),
Editable::No => {}
}
}
self.end_edit();
if self.settings.normal_after_send {
self.focus = Focus::Messages;
}
}
fn open_delete_menu(&mut self) {
let Some(open) = &self.open else {
return;
};
let Some((&message_id, msg)) = open
.cursor_id()
.and_then(|id| open.messages.get_key_value(&id))
else {
return;
};
self.delete_menu = Some(DeleteMenu {
message_id,
snippet: msg.snippet(),
choices: Vec::new(),
selected: 0,
});
self.tg.check_deletable(open.chat_id, message_id);
}
fn on_deletable(&mut self, chat_id: i64, message_id: i64, deletable: Option<Deletable>) {
if self.open.as_ref().is_none_or(|o| o.chat_id != chat_id) {
return;
}
let Some(menu) = self
.delete_menu
.as_mut()
.filter(|m| m.message_id == message_id)
else {
return;
};
let Some(deletable) = deletable else {
self.delete_menu = None;
return;
};
menu.set_allowed(deletable);
if menu.choices.is_empty() {
self.delete_menu = None;
self.status = Some(lang::t("You can't delete this message").into());
}
}
fn on_delete_key(&mut self, key: KeyEvent) {
let Some(menu) = self.delete_menu.as_mut() else {
return;
};
let last = menu.choices.len().saturating_sub(1);
let pick = match key.code {
KeyCode::Char('j') | KeyCode::Down => {
menu.selected = (menu.selected + 1).min(last);
None
}
KeyCode::Char('k') | KeyCode::Up => {
menu.selected = menu.selected.saturating_sub(1);
None
}
KeyCode::Enter | KeyCode::Char('l') => Some(menu.selected),
KeyCode::Char(c @ '1'..='9') => Some(c as usize - '1' as usize),
KeyCode::Esc | KeyCode::Char('q' | 'h') => {
self.delete_menu = None;
return;
}
_ => None,
};
let Some(choice) = pick.and_then(|i| menu.choices.get(i).copied()) else {
return;
};
let message_id = menu.message_id;
self.delete_menu = None;
if let Some(open) = &self.open {
let revoke = choice == DeleteChoice::Everyone;
self.tg.delete_message(open.chat_id, message_id, revoke);
}
}
fn open_react_menu(&mut self) {
let Some(open) = &self.open else {
return;
};
let Some((&message_id, msg)) = open
.react_target()
.and_then(|id| open.messages.get_key_value(&id))
else {
return;
};
match msg.state {
SendState::Pending => self.status = Some(lang::t("Wait until it's sent").into()),
SendState::Failed { .. } => {
self.status = Some(lang::t("This message wasn't sent").into())
}
SendState::Sent => {
self.react_menu = Some(ReactMenu::new(message_id, msg.snippet()));
self.tg.available_reactions(open.chat_id, message_id);
}
}
}
fn on_available_reactions(
&mut self,
chat_id: i64,
message_id: i64,
available: Option<reactions::Available>,
) {
if self.open.as_ref().is_none_or(|o| o.chat_id != chat_id)
|| self
.react_menu
.as_ref()
.is_none_or(|m| m.message_id != message_id)
{
return;
}
let Some(available) = available else {
self.react_menu = None;
return;
};
if available.emoji.is_empty() {
self.react_menu = None;
let reason = available
.reason
.unwrap_or(lang::t("Reactions are off in this chat"));
self.status = Some(reason.into());
return;
}
let yours: Vec<String> = self
.open
.iter()
.flat_map(|o| o.your_emoji(message_id))
.map(|(_, emoji)| emoji)
.collect();
if let Some(menu) = self.react_menu.as_mut() {
menu.set_choices(available.emoji, &yours);
}
}
fn on_react_key(&mut self, key: KeyEvent, ctrl: bool) {
let Some(menu) = self.react_menu.as_mut() else {
return;
};
let row = reactions::COLUMNS as isize;
let searching = menu.query.is_some();
match key.code {
KeyCode::Enter => self.react_with_selected(),
KeyCode::Left => menu.move_by(-1),
KeyCode::Right | KeyCode::Tab => menu.move_by(1),
KeyCode::BackTab => menu.move_by(-1),
KeyCode::Up => menu.move_by(-row),
KeyCode::Down => menu.move_by(row),
KeyCode::Char('n') if ctrl => menu.move_by(1),
KeyCode::Char('p') if ctrl => menu.move_by(-1),
KeyCode::Esc if searching => menu.leave_search(),
KeyCode::Backspace if menu.query.as_ref().is_some_and(|q| q.is_empty()) => {
menu.leave_search();
}
KeyCode::Backspace if searching => menu.edit_query(|q| {
q.pop();
}),
KeyCode::Char('u' | 'w') if ctrl && searching => menu.edit_query(String::clear),
KeyCode::Char(c) if searching && !ctrl => menu.edit_query(|q| q.push(c)),
KeyCode::Char('h') => menu.move_by(-1),
KeyCode::Char('l') => menu.move_by(1),
KeyCode::Char('k') => menu.move_by(-row),
KeyCode::Char('j') => menu.move_by(row),
KeyCode::Char('/') => menu.edit_query(|_| {}),
KeyCode::Char('X') => {
self.react_menu = None;
self.remove_reactions();
}
KeyCode::Esc | KeyCode::Char('q' | 'R') => self.react_menu = None,
_ => {}
}
}
fn react_with_selected(&mut self) {
let Some((message_id, emoji)) = self
.react_menu
.as_ref()
.and_then(|m| Some((m.message_id, m.current()?.to_string())))
else {
return;
};
self.react_menu = None;
let Some(open) = &self.open else {
return;
};
let yours = open
.your_emoji(message_id)
.into_iter()
.find(|(_, e)| *e == emoji);
let kind = ReactionKind::Emoji(emoji);
match yours {
Some((on, _)) => self.tg.react(open.chat_id, on, &kind, false),
None => self.tg.react(open.chat_id, message_id, &kind, true),
}
}
fn on_vote_key(&mut self, key: KeyEvent) {
let Some(menu) = self.vote_menu.as_mut() else {
return;
};
match key.code {
KeyCode::Char('j') | KeyCode::Down => menu.move_by(1),
KeyCode::Char('k') | KeyCode::Up => menu.move_by(-1),
KeyCode::Char(' ') => menu.tick(),
KeyCode::Char(c @ '1'..='9') => {
let index = c as usize - '1' as usize;
if index < menu.answers.len() {
menu.selected = index;
if menu.several {
menu.tick();
} else {
self.cast_vote();
}
}
}
KeyCode::Enter | KeyCode::Char('l') => self.cast_vote(),
KeyCode::Esc | KeyCode::Char('q' | 'h') => self.vote_menu = None,
_ => {}
}
}
fn cast_vote(&mut self) {
let Some(menu) = self.vote_menu.take() else {
return;
};
let Some(open) = &self.open else {
return;
};
let answers = match menu.vote() {
Vote::For(answers) => answers,
Vote::Retract => Vec::new(),
};
self.tg.vote(open.chat_id, menu.message_id, answers);
}
fn on_button_key(&mut self, key: KeyEvent) {
let Some(menu) = self.button_menu.as_mut() else {
return;
};
match key.code {
KeyCode::Char('j') | KeyCode::Down => menu.move_rows(1),
KeyCode::Char('k') | KeyCode::Up => menu.move_rows(-1),
KeyCode::Char('h') | KeyCode::Left => menu.move_cols(-1),
KeyCode::Char('l') | KeyCode::Right => menu.move_cols(1),
KeyCode::Tab => menu.move_by(1),
KeyCode::BackTab => menu.move_by(-1),
KeyCode::Enter if menu.shown.elapsed() >= CONFIRM_GRACE => self.press_button(),
KeyCode::Esc | KeyCode::Char('q') => self.button_menu = None,
_ => {}
}
}
fn press_button(&mut self) {
let Some(menu) = &self.button_menu else {
return;
};
let Some(button) = menu.current().cloned() else {
return;
};
if let Press::Unsupported(why) = button.press {
self.status = Some(why.into());
return;
}
let message_id = menu.message_id;
self.button_menu = None;
let Some(chat_id) = self.open.as_ref().map(|o| o.chat_id) else {
return;
};
match button.press {
Press::Callback(data) => {
self.show_toast(lang::t("Pressed"), &button.label);
let topic = self.open.as_ref().and_then(|o| o.topic);
self.tg
.press_button(chat_id, topic, message_id, data, button.label);
}
Press::Open(link) => self.open_target(Target::Link(link)),
Press::File(file) => {
let target = self
.open
.as_ref()
.and_then(|o| o.messages.get(&message_id))
.map(|msg| file_target(message_id, msg, file));
match target {
Some(target) => self.open_target(target),
None => {
self.status = Some(lang::t("That message isn't loaded any more").into())
}
}
}
Press::Telegram(url) => {
self.finding = Some(Finding::new(&url));
self.tg.find_link(url.clone(), url);
}
Press::User(user_id) => {
let name = self
.users
.get(&user_id)
.cloned()
.unwrap_or_else(|| button.label.clone());
self.finding = Some(Finding::new(&name));
self.tg.find_private_chat(user_id, name);
}
Press::Copy(text) => self.copy_target(Target::Text(text)),
Press::Send(text) => {
let private = self.chats.get(chat_id).is_some_and(|c| c.is_private);
let reply_to = (!private).then_some(message_id);
let topic = self.open.as_ref().and_then(|o| o.topic);
self.tg.send_plain(chat_id, topic, text, reply_to);
self.jump_to_newest();
}
Press::Unsupported(_) => {}
}
}
fn on_bot_answer(
&mut self,
place: (i64, Option<i32>),
label: String,
text: &str,
alert: bool,
url: &str,
) {
let text = one_line(text);
let here = self.open.as_ref().is_some_and(|o| o.place() == place) && !self.busy();
if !text.is_empty() {
if alert && here {
self.notice = Some(Notice {
title: label.clone(),
text,
});
} else {
self.show_toast(&label, &text);
}
}
if url.is_empty() || !here || self.notice.is_some() {
return;
}
match web_url(url) {
Some(url) => self.open_link_outside(Link {
url,
disguise: Some(label),
}),
None => self.status = Some(lang::t("The bot's link isn't a web address").into()),
}
}
fn forward_selected(&mut self) {
let Some(open) = &self.open else {
return;
};
if self.chats.is_secret(open.chat_id) {
self.status = Some(lang::t("Messages in secret chats can't be forwarded").into());
return;
}
let Some((&id, msg)) = open
.cursor_id()
.and_then(|id| open.messages.get_key_value(&id))
else {
return;
};
match msg.state {
SendState::Pending => self.status = Some(lang::t("Wait until it's sent").into()),
SendState::Failed { .. } => {
self.status = Some(lang::t("This message wasn't sent").into())
}
SendState::Sent => {
self.picker = Some(ChatPicker::new(Purpose::Forward {
from: open.chat_id,
message_ids: open.forward_ids(id),
snippet: msg.snippet(),
}));
}
}
}
fn on_picker_key(&mut self, key: KeyEvent, ctrl: bool) {
let choices = self
.picker
.as_ref()
.map_or(Vec::new(), |p| p.choices(&self.chats));
let Some(picker) = self.picker.as_mut() else {
return;
};
let now = Instant::now();
match key.code {
KeyCode::Enter => self.pick_chat(),
KeyCode::Esc => self.picker = None,
KeyCode::Char('c') if ctrl => self.picker = None,
KeyCode::Up | KeyCode::BackTab => picker.move_by(-1, &choices),
KeyCode::Down | KeyCode::Tab => picker.move_by(1, &choices),
KeyCode::Char('p') if ctrl => picker.move_by(-1, &choices),
KeyCode::Char('n') if ctrl => picker.move_by(1, &choices),
KeyCode::PageUp => picker.move_by(-HALF_PAGE, &choices),
KeyCode::PageDown => picker.move_by(HALF_PAGE, &choices),
KeyCode::Backspace => picker.edit_query(
|q| {
q.pop();
},
now,
),
KeyCode::Char('u' | 'w') if ctrl => picker.edit_query(String::clear, now),
KeyCode::Char(c) if !ctrl => picker.edit_query(|q| q.push(c), now),
_ => {}
}
}
fn pick_chat(&mut self) {
let Some(picker) = self.picker.as_ref() else {
return;
};
let Some(choice) = picker.current(&picker.choices(&self.chats)) else {
return;
};
let Some(picker) = self.picker.take() else {
return;
};
match (picker.purpose, choice) {
(
Purpose::Forward {
from, message_ids, ..
},
Choice::Chat(to),
) => match self.cant_send(to) {
Some(why) => self.status = Some(why),
None => self.tg.forward(to, from, message_ids),
},
(Purpose::Forward { .. }, _) => {}
(Purpose::Open, Choice::Chat(id)) => self.open_chat(id),
(Purpose::Open, Choice::User(user_id)) => {
let name = self
.users
.get(&user_id)
.cloned()
.unwrap_or_else(|| lang::t("your contact").into());
self.finding = Some(Finding::new(&name));
self.tg.find_private_chat(user_id, name);
}
(Purpose::Open, Choice::Username(name)) => {
let request = format!("@{name}");
self.finding = Some(Finding::new(&request));
self.tg.find_username(name, request);
}
(Purpose::Open, Choice::Link(link)) => {
self.finding = Some(Finding::new(&link));
self.tg.find_link(link.clone(), link);
}
}
}
fn confirm_invite(&mut self, link: String, request: String, invite: Invite) {
let n = invite.members;
let (about, title) = match invite.channel {
true => (
lang::n(
n.into(),
"A channel with {n} member.",
"A channel with {n} members.",
&[],
),
match invite.by_request {
true => lang::t("Ask to join this channel?"),
false => lang::t("Join this channel?"),
},
),
false => (
lang::n(
n.into(),
"A group with {n} member.",
"A group with {n} members.",
&[],
),
match invite.by_request {
true => lang::t("Ask to join this group?"),
false => lang::t("Join this group?"),
},
),
};
let mut lines = vec![invite.title, about];
if invite.by_request {
lines.push(lang::t("An admin has to let you in.").into());
}
let channel = invite.channel;
let action = Confirmed::JoinLink {
link,
request,
channel,
};
let mut confirm = Confirm::new(title, lines, action);
confirm.badge = invite.badge;
self.confirm = Some(confirm);
}
fn remove_reactions(&mut self) {
let Some(open) = &self.open else {
return;
};
let yours = open.your_reactions();
if yours.is_empty() {
self.status = Some(lang::t("You haven't reacted to this message").into());
return;
}
for (message_id, kind) in yours {
self.tg.react(open.chat_id, message_id, &kind, false);
}
}
fn on_resize_key(&mut self, key: KeyEvent, ctrl: bool) {
let Some(pane) = self.resizing else {
return;
};
let left = match self.settings.chat_list_side {
Side::Left => -1,
Side::Right => 1,
};
let widths = |s: &Settings| (s.chat_list_width, s.topics_width);
let before = widths(&self.settings);
let settings = &mut self.settings;
match (pane, key.code) {
(Resizing::List, KeyCode::Char('h') | KeyCode::Left) => settings.resize_list(left),
(Resizing::List, KeyCode::Char('l') | KeyCode::Right) => settings.resize_list(-left),
(Resizing::Topics, KeyCode::Char('h') | KeyCode::Left) => settings.resize_topics(left),
(Resizing::Topics, KeyCode::Char('l') | KeyCode::Right) => {
settings.resize_topics(-left)
}
(Resizing::List, KeyCode::Char('=')) => {
settings.chat_list_width = settings::DEFAULT_LIST_WIDTH;
}
(Resizing::Topics, KeyCode::Char('=')) => {
settings.topics_width = settings::DEFAULT_TOPICS_WIDTH;
}
(_, KeyCode::Enter | KeyCode::Esc) => self.resizing = None,
(_, KeyCode::Char('r')) if ctrl => self.resizing = None,
_ => {}
}
if widths(&self.settings) != before
&& let Err(e) = self.settings.save(&self.settings_path)
{
self.status = Some(format!("{}{e:#}", lang::t("Couldn't save settings: ")));
}
}
fn open_stickers(&mut self) {
let Some(open) = &self.open else {
return;
};
if open.editing.is_some() {
self.status = Some(lang::t("An edit can't change a message into a sticker").into());
return;
}
self.stickers = Some(StickerPanel::new(open.chat_id));
self.tg.stickers(Source::Recent);
self.tg.stickers(Source::Favorites);
self.tg.sticker_sets();
}
fn on_sticker_key(&mut self, key: KeyEvent, ctrl: bool) {
let Some(panel) = self.stickers.as_mut() else {
return;
};
let searching = panel.query.is_some();
let before = panel.search_query();
match key.code {
KeyCode::Enter => self.send_sticker(),
KeyCode::Char('c') if ctrl => self.leave_insert(),
KeyCode::Left => panel.move_by(-1),
KeyCode::Right => panel.move_by(1),
KeyCode::Up => panel.move_rows(-1),
KeyCode::Down => panel.move_rows(1),
KeyCode::Char('n') if ctrl => panel.move_by(1),
KeyCode::Char('p') if ctrl => panel.move_by(-1),
KeyCode::Esc if searching => panel.leave_search(),
KeyCode::Backspace if panel.query.as_ref().is_some_and(|q| q.is_empty()) => {
panel.leave_search();
}
KeyCode::Backspace if searching => panel.edit_query(|q| {
q.pop();
}),
KeyCode::Char('u' | 'w') if ctrl && searching => panel.edit_query(String::clear),
KeyCode::Char(c) if searching && !ctrl => panel.edit_query(|q| q.push(c)),
KeyCode::Char('h') => panel.move_by(-1),
KeyCode::Char('l') => panel.move_by(1),
KeyCode::Char('k') => panel.move_rows(-1),
KeyCode::Char('j') => panel.move_rows(1),
KeyCode::Char('H') => panel.switch(-1),
KeyCode::Char('L') => panel.switch(1),
KeyCode::Char('/') => panel.edit_query(|_| {}),
KeyCode::Esc | KeyCode::Tab | KeyCode::Char('i' | 'q') => self.stickers = None,
_ => {}
}
self.find_stickers(before);
self.load_sticker_set();
}
fn find_stickers(&mut self, before: Option<String>) {
if let Some(panel) = &self.stickers
&& let Some(query) = panel.search_query()
&& Some(&query) != before.as_ref()
{
self.tg.find_stickers(panel.chat_id, query);
}
}
fn load_sticker_set(&mut self) {
if let Some(set_id) = self.stickers.as_mut().and_then(StickerPanel::pending_set) {
self.tg.stickers(Source::Set(set_id));
}
}
fn on_stickers(&mut self, source: Source, stickers: Option<Vec<tdlib_rs::types::Sticker>>) {
let premium = self.premium;
let Some(panel) = self.stickers.as_mut() else {
return;
};
let stickers = stickers::convert(&stickers.unwrap_or_default(), premium);
panel.set_stickers(source, stickers);
self.load_sticker_set();
}
fn send_sticker(&mut self) {
let Some(panel) = &self.stickers else {
return;
};
let Some(sticker) = panel.current().cloned() else {
return;
};
if let Some(why) = self.cant_send(panel.chat_id) {
self.status = Some(why);
return;
}
let Some(open) = self.open.as_mut().filter(|o| o.chat_id == panel.chat_id) else {
return;
};
let reply_to = open.reply.take().map(|r| r.id);
self.tg
.send_sticker(open.chat_id, open.topic, &sticker, reply_to);
self.stickers = None;
self.typing = None;
if self.settings.normal_after_send {
self.focus = Focus::Messages;
}
self.jump_to_newest();
}
fn go_to_replied(&mut self) {
let Some(open) = self.open.as_ref() else {
return;
};
match open.replied_jump() {
Ok((from, to)) => {
self.jumps.leave(Jump {
chat_id: open.chat_id,
topic: open.topic,
message_id: Some(from),
});
self.jump_to_message(to);
}
Err(why) => self.status = Some(why.into()),
}
}
fn go_to_unread(&mut self) {
let Some(open) = self.open.as_ref() else {
return;
};
let unread_now = match open.topic {
Some(topic) => self
.forum
.as_ref()
.and_then(|f| f.get(topic))
.filter(|t| t.unread > 0)
.map(|t| t.read_inbox()),
None => self
.chats
.get(open.chat_id)
.filter(|c| c.unread > 0)
.map(|_| self.chats.read_inbox(open.chat_id)),
};
let Some(read) = open.unread_line.or(unread_now) else {
self.status = Some(lang::t("No unread messages").into());
return;
};
if open.unread_after == Some(read) && matches!(open.loading, Some(Page::Around(_))) {
return;
}
if let Some(here) = self.here() {
self.jumps.leave(here);
}
let Some(open) = self.open.as_mut() else {
return;
};
open.unread_after = Some(read);
if open.unread_loaded(read) {
if matches!(open.loading, Some(Page::Around(_))) {
open.loading = None;
}
open.go_to_unread();
open.unread_after = None;
return;
}
self.load_page(Page::Around(read.max(1)));
}
fn go_to_mention(&mut self, older: bool) {
let unread = self.unread_mentions() > 0;
let Some(open) = self.open.as_mut() else {
return;
};
let from = open.cursor_id().unwrap_or(0);
let ask = match (older, unread) {
(true, true) => Mentions::Unread,
(true, false) => Mentions::Before(from),
(false, _) if open.selected.is_none() && open.at_newest => {
self.status = Some(lang::t("No newer mentions").into());
return;
}
(false, _) => Mentions::After(from),
};
open.mentions_asked = Some(ask);
let general = self.forum.as_ref().map_or(topics::GENERAL, |f| f.general());
self.tg.mentions(open.chat_id, open.topic, general, ask);
}
pub fn unread_mentions(&self) -> i32 {
let Some(open) = &self.open else {
return 0;
};
match open.topic {
Some(topic) => self
.forum
.as_ref()
.and_then(|f| f.get(topic))
.map_or(0, |t| t.mentions),
None => self.chats.get(open.chat_id).map_or(0, |c| c.mentions),
}
}
fn on_mentions(&mut self, place: (i64, Option<i32>), ask: Mentions, ids: Option<Vec<i64>>) {
let Some(open) = self
.open
.as_mut()
.filter(|o| o.place() == place && o.mentions_asked == Some(ask))
else {
return;
};
open.mentions_asked = None;
let Some(ids) = ids else {
return;
};
if self.busy() || self.focus != Focus::Messages {
return;
}
let Some(to) = ask.pick(&ids) else {
let said = match ask {
Mentions::Unread => lang::t("No unread mentions"),
Mentions::Before(0) => lang::t("Nobody mentioned you here"),
Mentions::Before(_) => lang::t("No older mentions"),
Mentions::After(_) => lang::t("No newer mentions"),
};
self.status = Some(said.into());
return;
};
if let Some(here) = self.here() {
self.jumps.leave(here);
}
self.jump_to_message(to);
}
fn open_chat_info(&mut self) {
let Some(chat_id) = self.info_chat() else {
self.status = Some(lang::t("No chat selected").into());
return;
};
let Some(peer) = self.chats.get(chat_id).and_then(|c| c.peer) else {
return;
};
self.chat_info = Some(ChatInfo::new(chat_id));
self.tg.chat_info(chat_id, peer);
}
fn info_chat(&self) -> Option<i64> {
match self.focus {
Focus::Chats => self.selected,
Focus::Topics => self.forum.as_ref().map(|f| f.chat_id),
Focus::Messages | Focus::Input => self.open.as_ref().map(|o| o.chat_id),
}
}
fn on_info_key(&mut self, key: KeyEvent, ctrl: bool) {
let Some(info) = self.chat_info.as_mut() else {
return;
};
match key.code {
KeyCode::Char('j') | KeyCode::Down => info.move_cursor(1),
KeyCode::Char('k') | KeyCode::Up => info.move_cursor(-1),
KeyCode::Char('d') if ctrl => info.move_cursor(HALF_PAGE),
KeyCode::Char('u') if ctrl => info.move_cursor(-HALF_PAGE),
KeyCode::Char('g') => info.move_cursor(isize::MIN),
KeyCode::Char('G') => info.move_cursor(isize::MAX),
KeyCode::Enter => self.write_to_member(),
KeyCode::Esc | KeyCode::Char('q' | 'I') => self.chat_info = None,
_ => {}
}
self.ask_members();
}
fn ask_members(&mut self) {
if let Some(info) = self.chat_info.as_mut()
&& let Some((supergroup_id, offset)) = info.page_to_ask()
{
self.tg.chat_members(info.chat_id, supergroup_id, offset);
}
}
fn write_to_member(&mut self) {
let Some(who) = self
.chat_info
.as_ref()
.and_then(|i| i.current())
.map(|m| m.who)
else {
return;
};
self.chat_info = None;
match who {
Sender::User(user_id) => {
let name = self
.users
.get(&user_id)
.cloned()
.unwrap_or_else(|| lang::t("them").into());
self.finding = Some(Finding::new(&name));
self.tg.find_private_chat(user_id, name);
}
Sender::Chat(chat_id) => self.open_chat(chat_id),
}
}
fn open_target(&mut self, target: Target) {
match target {
Target::Voice { message_id, file } => self.play_voice(message_id, file.id),
Target::Photo { message_id, file } => self.view_photo(message_id, file),
Target::Video { message_id, file } => self.view_video(message_id, file),
Target::File(file) => {
if self.opening.insert(file.id) {
self.tg.download(file.id);
}
}
Target::Link(link) if proxy::is_link(&link.url) => self.ask_to_use_proxy(&link.url),
Target::Link(link) if picker::telegram_link(&link.url) => {
self.finding = Some(Finding {
request: link.url.clone(),
link: Some(link.clone()),
});
self.tg.find_link(link.url.clone(), link.url);
}
Target::Link(link) => self.open_link_outside(link),
Target::Text(_) => {}
}
}
fn view_photo(&mut self, message_id: i64, file: MediaFile) {
let Some(open) = self.open.as_mut() else {
return;
};
let view = match open.messages.get(&message_id) {
Some(msg) => PhotoView::of(open.chat_id, message_id, msg),
None => {
self.open_target(Target::File(file));
return;
}
};
let Some(view) = view else {
self.status = Some(lang::t("This photo can't be shown here").into());
return;
};
if open.selected.is_none() {
open.selected = Some(message_id);
}
self.photo_view = Some(view);
}
fn on_viewer_key(&mut self, key: KeyEvent) {
let Some(view) = self.photo_view.as_mut() else {
return;
};
if key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
{
return;
}
match key.code {
KeyCode::Char('h') | KeyCode::Left => self.view_next_photo(false),
KeyCode::Char('l') | KeyCode::Right => self.view_next_photo(true),
KeyCode::Char('j' | '+' | '=') => view.zoom_in(),
KeyCode::Char('k' | '-') => view.zoom_out(),
KeyCode::Char('o') if view.cant_copy.is_some() => {
self.status =
Some(lang::t("This photo can't be saved, so it opens only here").into());
}
KeyCode::Char('o') => {
let file = view.file.clone();
self.photo_view = None;
self.open_target(Target::File(file));
}
KeyCode::Char('y') => match view.cant_copy {
Some(why) => self.status = Some(why.into()),
None => {
let file = view.file.clone();
self.copy_target(Target::File(file));
}
},
KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q') => self.photo_view = None,
_ => {}
}
}
fn view_next_photo(&mut self, newer: bool) {
let Some(view) = &self.photo_view else {
return;
};
let Some(open) = self.open.as_ref().filter(|o| o.chat_id == view.chat_id) else {
return;
};
let id = view.message_id;
let photo =
|(&id, msg): (&i64, &crate::messages::Msg)| PhotoView::of(open.chat_id, id, msg);
let next = match newer {
true => open.messages.range(id + 1..).find_map(photo),
false => open.messages.range(..id).rev().find_map(photo),
};
if next.is_some() {
self.photo_view = next;
return;
}
match (newer, open.all_loaded, open.at_newest) {
(false, false, _) => {
self.status = Some(lang::t("Loading older messages…").into());
self.load_older_messages();
}
(true, _, false) => {
self.status = Some(lang::t("Loading newer messages…").into());
self.load_newer_messages();
}
(false, true, _) => self.status = Some(lang::t("No older photos in this chat").into()),
(true, _, true) => self.status = Some(lang::t("No newer photos in this chat").into()),
}
}
fn view_video(&mut self, message_id: i64, file: MediaFile) {
if self.pepper.is_none() && !self.images.kitty() {
self.status = Some(
lang::t("Video messages play in the terminal only with kitty's protocol").into(),
);
self.open_target(Target::File(file));
return;
}
if self.over_ssh {
self.status =
Some(lang::t("Video messages play in the terminal only on this computer").into());
self.open_target(Target::File(file));
return;
}
let Some(open) = self.open.as_mut() else {
return;
};
let chat_id = open.chat_id;
let view = match open.messages.get(&message_id) {
Some(msg) => VideoView::of(
chat_id,
message_id,
msg,
self.video_tx.clone(),
self.images.tmux(),
self.pepper.clone(),
&self.colors,
),
None => {
self.open_target(Target::File(file));
return;
}
};
let Some(mut view) = view else {
self.status = Some(lang::t("This video message can't be played here").into());
return;
};
if view.note.size > crate::video::MAX_FILE {
self.status = Some(lang::t("Can't play this video message: it's too big").into());
return;
}
if let Some(inline) = self.inline_video.take()
&& inline.is_on(chat_id, message_id)
{
view.resume_at(inline.position());
}
if open.selected.is_none() {
open.selected = Some(message_id);
}
view.tell = open.tells(message_id);
self.tg.download(view.note.file_id);
self.video_view = Some(view);
}
fn update_sticker_focus(&mut self) {
let under_cursor = self.open.as_ref().and_then(|open| {
let id = open.cursor_id()?;
let msg = open.messages.get(&id)?;
msg.video_sticker.map(|_| (open.chat_id, id))
});
if let Some(inline) = &self.inline_video {
let keep = if inline.is_sticker() {
self.present() && under_cursor == Some((inline.chat_id, inline.message_id))
} else {
!inline.played_out() || under_cursor.is_none()
};
if keep {
return;
}
self.inline_video = None;
}
let Some((chat_id, message_id)) = under_cursor else {
return;
};
if !self.present() || self.over_ssh || !self.images.kitty() {
return;
}
let Some(msg) = self
.open
.as_ref()
.and_then(|open| open.messages.get(&message_id))
else {
return;
};
let Some(inline) = Inline::of_sticker(
chat_id,
message_id,
msg,
self.video_tx.clone(),
self.images.tmux(),
) else {
return;
};
self.tg.download_quiet(inline.note.file_id);
self.inline_video = Some(inline);
}
fn toggle_inline_video(&mut self) {
let Some(open) = self.open.as_mut() else {
return;
};
let Some(message_id) = open.cursor_id() else {
return;
};
let chat_id = open.chat_id;
if self
.inline_video
.as_mut()
.is_some_and(|i| i.plays_note(chat_id, message_id))
{
if let Some(inline) = self.inline_video.as_mut() {
inline.toggle();
}
return;
}
let Some(msg) = open.messages.get(&message_id) else {
return;
};
if msg.video.is_none() {
return;
}
let Some(file) = openable_file(msg).cloned() else {
return;
};
let tell = open.tells(message_id);
if self.settings.video_note_size == VideoNoteSize::Large || msg.preview.is_none() {
self.view_video(message_id, file);
return;
}
if self.pepper.is_none() && !self.images.kitty() {
self.status = Some(
lang::t("This terminal can't play video messages in the chat; Enter plays one on the whole window")
.into(),
);
return;
}
if self.over_ssh {
self.status =
Some(lang::t("Video messages play in the terminal only on this computer").into());
return;
}
let Some(mut inline) = Inline::of(
chat_id,
message_id,
msg,
self.video_tx.clone(),
self.images.tmux(),
self.pepper.clone(),
&self.colors,
) else {
return;
};
if inline.note.size > crate::video::MAX_FILE {
self.status = Some(lang::t("Can't play this video message: it's too big").into());
return;
}
if self.settings.video_note_size == VideoNoteSize::Medium {
inline.toggle_zoom();
}
inline.tell = tell;
let file_id = inline.note.file_id;
self.inline_video = None; self.tg.download(file_id);
self.status = Some(lang::t("Downloading the video message…").into());
self.inline_video = Some(inline);
}
fn zoom_inline_video(&mut self) {
let Some(open) = self.open.as_ref() else {
return;
};
let Some(message_id) = open.cursor_id() else {
return;
};
let chat_id = open.chat_id;
if let Some(inline) = self
.inline_video
.as_mut()
.filter(|i| i.plays_note(chat_id, message_id))
{
inline.toggle_zoom();
return;
}
if open
.messages
.get(&message_id)
.is_none_or(|m| m.video.is_none())
{
return;
}
self.toggle_inline_video();
if let Some(inline) = self
.inline_video
.as_mut()
.filter(|i| i.plays_note(chat_id, message_id) && !i.medium())
{
inline.toggle_zoom();
}
}
fn on_video_key(&mut self, key: KeyEvent) {
let Some(view) = self.video_view.as_mut() else {
return;
};
if key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
{
return;
}
match key.code {
KeyCode::Char('j' | '+' | '=') => view.zoom_in(),
KeyCode::Char('k' | '-') => view.zoom_out(),
KeyCode::Char(' ') => view.toggle(),
KeyCode::Char('o') if view.cant_copy.is_some() => {
self.status = Some(
lang::t("This video message can't be saved, so it plays only here").into(),
);
}
KeyCode::Char('o') => {
let file = view.file.clone();
self.video_view = None;
self.open_target(Target::File(file));
}
KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q') => self.video_view = None,
_ => {}
}
}
fn on_video(&mut self, event: VideoEvent) {
let present = self.present();
if event.tag == crate::video::TAG_INLINE {
let Some(inline) = self.inline_video.as_mut() else {
return;
};
match inline.on_event(event) {
Err(why) => {
self.status = Some(format!(
"{}{why}",
lang::t("Can't play this video message: ")
));
self.inline_video = None;
}
Ok(()) if present && inline.tell_now() => {
let (chat_id, id) = (inline.chat_id, inline.message_id);
self.played_video(chat_id, id);
}
Ok(()) => {}
}
return;
}
let Some(view) = self.video_view.as_mut() else {
return;
};
if let Err(why) = view.on_event(event) {
self.status = Some(format!(
"{}{why}",
lang::t("Can't play this video message: ")
));
self.video_view = None;
return;
}
let tell = (present && view.tell_now()).then_some((view.chat_id, view.message_id));
if view.finished() {
self.video_view = None;
}
if let Some((chat_id, id)) = tell {
self.played_video(chat_id, id);
}
}
fn played_video(&mut self, chat_id: i64, message_id: i64) {
self.tg.open_content(chat_id, message_id);
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == chat_id) {
open.set_opened(message_id);
}
}
fn reveal_selected_file(&mut self) {
let Some(open) = self.open.as_ref() else {
return;
};
let msg = open.cursor_id().and_then(|id| open.messages.get(&id));
let Some((msg, file)) = msg.and_then(|m| Some((m, openable_file(m)?.clone()))) else {
self.status = Some(lang::t("No file in this message").into());
return;
};
if let Some(why) = crate::viewer::cant_copy(msg) {
self.status = Some(why.into());
return;
}
if self.revealing.insert(file.id) {
self.tg.download(file.id);
self.status = Some(lang::t("Downloading to show in the file manager…").into());
}
}
fn play_voice(&mut self, message_id: i64, file_id: i32) {
let Some(open) = self.open.as_ref() else {
return;
};
if self.player.is_on(open.chat_id, message_id) {
self.player.toggle();
return;
}
let size = open
.messages
.get(&message_id)
.and_then(|m| m.voice.as_ref())
.map_or(0, |v| v.size);
if size > crate::voice::MAX_FILE {
self.status = Some(lang::t("Can't play this voice message: it's too long").into());
return;
}
let tell = open.tells(message_id);
self.player.play(open.chat_id, message_id, file_id, tell);
self.tg.download(file_id);
}
fn open_link_outside(&mut self, link: Link) {
match link {
Link {
url,
disguise: Some(shown),
} => {
let site = link_host(&url).map(|host| match host.is_ascii() {
true => host,
false => format!("{host} {}", lang::t("(has non-Latin letters)")),
});
let (said, address) = (lang::t("The text says: "), lang::t("Full address: "));
let mut confirm = Confirm::new(
lang::t("Open this link?"),
vec![format!("{said}{shown}"), format!("{address}{url}")],
Confirmed::OpenLink(url),
);
confirm.site = site.map(Site::link);
self.confirm = Some(confirm);
}
link => self.open_externally(&link.url),
}
}
fn open_downloaded(&mut self, path: String) {
mark_downloaded(&path);
if safe_to_open(&path) {
self.open_externally(&path);
return;
}
let name = text::clean(
&Path::new(&path)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
);
if self.busy() {
self.status = Some(lang::f(
"{name} downloaded: press Enter on it again to open it",
&[("name", &name)],
));
return;
}
self.confirm = Some(Confirm::new(
format!("{} {name}?", lang::t("Open")),
vec![
lang::t("Files like this can run programs on your computer.").into(),
lang::t("Only open it if you trust whoever sent it.").into(),
],
Confirmed::OpenFile(path),
));
}
fn busy(&self) -> bool {
self.over_panes() || self.focus == Focus::Input
}
pub fn slides_toast(&self) -> bool {
self.settings.animations && !self.images.paints_over()
}
pub fn over_panes(&self) -> bool {
self.popup_open() || self.prompt.is_some() || self.resizing.is_some()
}
pub fn popup_open(&self) -> bool {
self.confirm.is_some()
|| self.notice.is_some()
|| self.settings_menu.is_some()
|| self.picker.is_some()
|| self.menu.is_some()
|| self.delete_menu.is_some()
|| self.react_menu.is_some()
|| self.vote_menu.is_some()
|| self.button_menu.is_some()
|| self.pin_menu.is_some()
|| self.pinned_menu.is_some()
|| self.media_menu.is_some()
|| self.timer_menu.is_some()
|| self.key_view.is_some()
|| self.photo_view.is_some()
|| self.video_view.is_some()
|| self.chat_info.is_some()
|| self.text_select.is_some()
}
fn open_externally(&mut self, target: &str) {
if let Err(e) = open_externally(target) {
self.status = Some(format!("{}{e}", lang::t("Couldn't open it: ")));
}
}
fn on_confirm_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Char('y')
if self
.confirm
.as_ref()
.is_some_and(|c| c.shown.elapsed() >= CONFIRM_GRACE) =>
{
if let Some(confirm) = self.confirm.take() {
match confirm.action {
Confirmed::OpenFile(target) | Confirmed::OpenLink(target) => {
self.open_externally(&target)
}
Confirmed::Edit { id, text } => self.start_edit(id, text),
Confirmed::Join { chat_id, .. } => self.tg.join_chat(chat_id),
Confirmed::Leave(chat_id) => self.tg.leave_chat(chat_id),
Confirmed::ReadChat { chat_id, topic } => {
self.mark_chat_read(chat_id, topic)
}
Confirmed::ReadForum { chat_id } => self.read_forum(chat_id),
Confirmed::Logout => self.log_out(),
Confirmed::StartSecret { user_id, with } => {
let request = format!("{} {with}", lang::t("a secret chat with"));
self.finding = Some(Finding::new(&request));
self.tg.start_secret_chat(user_id, request);
}
Confirmed::EndSecret { chat_id, secret_id } => {
let open = self
.chats
.secret(chat_id)
.is_some_and(|s| s.state != SecretState::Closed);
self.forget_draft(chat_id);
self.tg.end_secret_chat(chat_id, secret_id, open)
}
Confirmed::JoinLink { link, request, .. } => {
self.finding = Some(Finding::new(&request));
self.tg.join_by_link(link, request);
}
Confirmed::UseProxy(link) => self.set_proxy(&link),
Confirmed::NoProxy => self.set_proxy(""),
Confirmed::Voice {
chat_id,
topic,
take,
} => self.send_voice(chat_id, topic, take),
}
}
}
KeyCode::Char('n' | 'q') | KeyCode::Esc => self.confirm = None,
_ => {}
}
}
fn copy_selected(&mut self) {
let Some(open) = &self.open else {
return;
};
let Some(msg) = open.cursor_id().and_then(|id| open.messages.get(&id)) else {
return;
};
let Some((_, captioned)) = open.caption_holder() else {
return;
};
if let Some(why) = viewer::cant_copy(msg).or_else(|| viewer::cant_copy(captioned)) {
self.status = Some(why.into());
return;
}
let mut targets = Vec::new();
if !captioned.source_text.is_empty() {
targets.push(Target::Text(captioned.source_text.clone()));
}
targets.extend(captioned.links.iter().cloned().map(Target::Link));
targets.extend(
msg.file
.clone()
.filter(|_| !opens_once(msg))
.map(Target::File),
);
match targets.len() {
0 => self.status = Some(lang::t("Nothing to copy in this message").into()),
1 => self.copy_target(targets.remove(0)),
_ => {
self.menu = Some(PickMenu {
action: MenuAction::Copy,
targets,
selected: 0,
})
}
}
}
fn open_text_select(&mut self) {
let Some(open) = self.open.as_mut() else {
return;
};
let Some((id, msg)) = open.caption_holder() else {
return;
};
if let Some(why) = viewer::cant_copy(msg) {
self.status = Some(why.into());
return;
}
if msg.source_text.is_empty() {
self.status = Some(lang::t("No text to select in this message").into());
return;
}
let select = TextSelect::new(open.chat_id, id, msg.source_text.clone());
open.reveal_spoilers(id);
self.text_select = Some(select);
}
fn on_select_key(&mut self, key: KeyEvent, ctrl: bool) {
let Some(select) = self.text_select.as_mut() else {
return;
};
if let Some(motion) = select::motion(key.code, ctrl) {
select.go(motion);
return;
}
match key.code {
_ if ctrl => {}
KeyCode::Char('v') => select.toggle(),
KeyCode::Esc if select.selecting() => select.cancel(),
KeyCode::Esc | KeyCode::Char('q') => self.text_select = None,
KeyCode::Char('y') => match select.selected() {
Some(text) => {
self.text_select = None;
self.copy_target(Target::Text(text));
}
None => {
self.status = Some(lang::t("Nothing selected: v starts a selection").into())
}
},
_ => {}
}
}
fn copy_target(&mut self, target: Target) {
let text = match target {
Target::Text(text) => text,
Target::Link(link) => link.url,
Target::File(file) | Target::Photo { file, .. } | Target::Video { file, .. } => {
if self.clipboard.remote {
self.status = Some(
lang::t("Over SSH, only text reaches your computer's clipboard").into(),
);
return;
}
let id = file.id;
if self.copying.insert(id, file).is_none() {
self.tg.download(id);
}
return;
}
Target::Voice { .. } => return,
};
match self.clipboard.copy_text(&text) {
Ok(Copied::System) => self.show_toast(lang::t("Copied"), &text),
Ok(Copied::Terminal) => {
self.show_toast(lang::t("Sent to the terminal's clipboard"), &text)
}
Err(e) => self.status = Some(format!("{}{e}", lang::t("Couldn't copy: "))),
}
}
fn copy_downloaded(&mut self, file: MediaFile, path: &str) {
if file.photo {
self.clipboard.decode_image(path.to_string(), file.label);
return;
}
match self.clipboard.copy_file(Path::new(path)) {
Ok(()) => self.show_toast(lang::t("Copied"), &file.label),
Err(e) => self.status = Some(format!("{}{e}", lang::t("Couldn't copy: "))),
}
}
fn on_voice(&mut self, event: VoiceEvent) {
if let Some(why) = event.ring_failed() {
self.status = Some(format!(
"{}{why}",
lang::t("Can't play the sound for new messages: ")
));
return;
}
let Some(news) = self.player.on_event(event) else {
return;
};
match news.happened {
Happened::Started if news.tell => {
self.tg.open_content(news.chat_id, news.message_id);
if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == news.chat_id) {
open.set_opened(news.message_id);
open.start_timer(news.message_id, SystemTime::now());
}
}
Happened::Started | Happened::Ended => {}
Happened::Failed(why) => {
self.status = Some(format!(
"{}{why}",
lang::t("Can't play this voice message: ")
));
}
}
}
fn on_clipboard(&mut self, event: ClipboardEvent) {
match event {
ClipboardEvent::Decoded(decoded) => self.on_decoded(decoded),
ClipboardEvent::Pasted(pasted) => self.on_pasted(pasted),
}
}
fn can_attach(&mut self) -> bool {
match &self.open {
None => false,
Some(open) if open.editing.is_some() => {
self.status = Some(lang::t("Files can't be added to an edit").into());
false
}
Some(_) => true,
}
}
fn attach(&mut self, paths: Vec<PathBuf>, pasted: Option<String>) -> usize {
if !self.can_attach() {
return 0;
}
let Some(open) = self.open.as_mut() else {
return 0;
};
let mut added = 0;
for path in paths {
match Attachment::new(&path) {
Ok(attachment) => {
open.attachments.push(attachment);
added += 1;
}
Err(e) => self.status = Some(e),
}
}
if added == 0 {
return 0;
}
open.dropped = pasted.map(|text| Dropped { text, count: added });
self.focus = Focus::Input;
added
}
fn on_paste(&mut self, text: String) {
let editing = self.open.as_ref().is_some_and(|o| o.editing.is_some());
if !editing && let Some(paths) = attach::pasted_paths(&text) {
self.attach(paths, Some(text));
return;
}
if self.focus == Focus::Input
&& self
.open
.as_ref()
.is_some_and(|o| self.chats.is_secret(o.chat_id))
{
self.stickers = None;
}
if self.focus == Focus::Input
&& let Some(panel) = self.stickers.as_mut()
{
let before = panel.search_query();
let line = text::flat(&text);
panel.edit_query(|q| q.push_str(&line));
self.find_stickers(before);
return;
}
if self.focus == Focus::Input {
self.composer.insert_str(text.replace('\r', ""));
self.on_composer_edit();
}
}
fn paste_clipboard(&mut self) {
let Some(open) = &self.open else {
return;
};
if self.clipboard.remote {
self.status = Some(
lang::t("Over SSH, paste with your terminal's own paste key: the clipboard here is the other computer's")
.into(),
);
return;
}
self.clipboard.paste(open.place());
self.pasting = true;
}
fn on_pasted(&mut self, pasted: Pasted) {
self.pasting = false;
if self.open.as_ref().is_none_or(|o| o.place() != pasted.place) {
return;
}
if !matches!(self.focus, Focus::Messages | Focus::Input) {
self.status =
Some(lang::t("The paste came after you left the messages: p pastes again").into());
return;
}
if self.over_panes() {
self.status = Some(
lang::t("The paste came while something else was open: p pastes again").into(),
);
return;
}
match pasted.content {
Ok(Paste::Files(paths)) => {
let (paths, relative): (Vec<_>, Vec<_>) =
paths.into_iter().partition(|p| p.is_absolute());
if !relative.is_empty() {
self.status =
Some(lang::t("Copied files without a full path were left out").into());
}
self.attach(paths, None);
}
Ok(Paste::Image(path)) => {
if self.attach(vec![path], None) == 1
&& let Some(last) = self.open.as_mut().and_then(|o| o.attachments.last_mut())
{
last.name = lang::t("Pasted image").into();
}
}
Ok(Paste::Text(text)) => {
self.focus = Focus::Input;
self.on_paste(text);
}
Err(e) => self.status = Some(e),
}
}
fn toggle_as_files(&mut self) {
let Some(open) = self.open.as_mut() else {
return;
};
if open.attachments.iter().any(|a| a.kind.is_photo()) {
open.as_files = !open.as_files;
} else if !open.attachments.is_empty() {
self.status =
Some(lang::t("These go as files already: only photos can go either way").into());
}
}
fn undo_drop(&mut self) {
let Some(text) = self.open.as_mut().and_then(OpenChat::undo_drop) else {
return;
};
self.composer.insert_str(text.replace('\r', ""));
self.on_composer_edit();
}
fn on_decoded(&mut self, decoded: Decoded) {
let result = decoded
.image
.and_then(|image| self.clipboard.copy_image(image).map_err(|e| e.to_string()));
match result {
Ok(()) => self.show_toast(lang::t("Copied"), &decoded.label),
Err(e) => self.status = Some(format!("{}{e}", lang::t("Couldn't copy: "))),
}
}
fn show_toast(&mut self, title: &str, detail: &str) {
let now = Instant::now();
let shown = self
.toast
.as_ref()
.filter(|t| t.until > now)
.map_or(now, |t| {
let going = now.checked_sub(t.until - now).unwrap_or(t.shown);
t.shown.max(going)
});
self.toast = Some(Toast {
title: title.into(),
detail: crate::messages::one_line(detail),
shown,
until: now + TOAST_TIME,
});
}
fn on_menu_key(&mut self, key: KeyEvent) {
let Some(menu) = self.menu.as_mut() else {
return;
};
let last = menu.targets.len() - 1;
match key.code {
KeyCode::Char('j') | KeyCode::Down => menu.selected = (menu.selected + 1).min(last),
KeyCode::Char('k') | KeyCode::Up => menu.selected = menu.selected.saturating_sub(1),
KeyCode::Enter | KeyCode::Char('l') => {
let index = menu.selected;
self.pick(index);
}
KeyCode::Char(c @ '1'..='9') => {
let index = c as usize - '1' as usize;
if index <= last {
self.pick(index);
}
}
KeyCode::Esc | KeyCode::Char('q' | 'h') => self.menu = None,
_ => {}
}
}
fn pick(&mut self, index: usize) {
let Some(mut menu) = self.menu.take() else {
return;
};
let target = menu.targets.swap_remove(index);
match menu.action {
MenuAction::Open => self.open_target(target),
MenuAction::Copy => self.copy_target(target),
}
}
fn on_settings_key(&mut self, key: KeyEvent, ctrl: bool) {
let Some(menu) = self.settings_menu.as_mut() else {
return;
};
match key.code {
KeyCode::Tab | KeyCode::BackTab | KeyCode::Char('h' | 'l') => {
menu.tab = match menu.tab {
HelpTab::Shortcuts => HelpTab::Settings,
HelpTab::Settings => HelpTab::Shortcuts,
};
return;
}
KeyCode::Enter | KeyCode::Char(' ') if menu.tab == HelpTab::Settings => {
self.change_setting();
return;
}
KeyCode::Esc | KeyCode::Char('q' | '?') => {
self.settings_menu = None;
return;
}
_ => {}
}
let delta = match key.code {
KeyCode::Char('j') | KeyCode::Down => 1,
KeyCode::Char('k') | KeyCode::Up => -1,
KeyCode::Char('d') if ctrl => HALF_PAGE,
KeyCode::Char('u') if ctrl => -HALF_PAGE,
KeyCode::Char('g') => isize::MIN,
KeyCode::Char('G') => isize::MAX,
_ => return,
};
match menu.tab {
HelpTab::Shortcuts => menu.scroll = menu.scroll.saturating_add_signed(delta),
HelpTab::Settings => {
let last = SettingsMenu::themes(&self.sounds) + self.themes.list.len() - 1;
menu.selected = menu.selected.saturating_add_signed(delta).min(last);
}
}
}
fn change_setting(&mut self) {
let Some(menu) = self.settings_menu.as_mut() else {
return;
};
let settings = &mut self.settings;
let themes = SettingsMenu::themes(&self.sounds);
match menu.selected {
i if i >= themes => {
let Some(theme) = self.themes.list.get(i - themes) else {
return;
};
match &theme.colors {
Ok(colors) => {
self.colors = *colors;
settings.theme = theme.id.clone();
}
Err(e) => {
self.status = Some(format!("{}{e}", lang::t("Theme not used: ")));
return;
}
}
}
i if i >= SettingsMenu::SOUNDS => match i
.checked_sub(SettingsMenu::SOUNDS + 1)
.and_then(|n| self.sounds.list.get(n))
{
None => {
(self.sound, self.sound_stamp) = (None, None);
settings.notification_sound = None;
}
Some(sound) => match self.sounds.samples(&sound.id) {
Ok(samples) => {
if self.over_ssh {
self.status = Some(
lang::t("Over SSH, tuigram plays no sound: it would play on the other computer")
.into(),
);
} else {
self.player.ring(Arc::clone(&samples));
}
self.sound_stamp = self.sounds.stamp(&sound.id);
self.sound = Some(samples);
settings.notification_sound = Some(sound.id.clone());
}
Err(e) => {
self.status = Some(format!("{}{e}", lang::t("Sound not used: ")));
return;
}
},
},
i if i < SettingsMenu::NOTIFICATIONS => {
let lang = crate::lang::Lang::ALL[i - SettingsMenu::LANGUAGE];
settings.language = lang.code().into();
crate::lang::set(lang);
if let Some(dir) = self.themes.dir.clone() {
self.themes = Themes::load(&dir);
}
if let Some(dir) = self.sounds.dir.clone() {
self.sounds = Sounds::load(&dir);
}
}
SettingsMenu::NOTIFICATIONS => {
let on = match menu.saved_notifications {
Notifications::Off => Notifications::Auto,
saved => saved,
};
let next = match settings.notifications {
Notifications::Off => on,
_ => Notifications::Off,
};
self.set_notifications(next);
}
SettingsMenu::CHAT_GAPS => settings.chat_gaps = !settings.chat_gaps,
SettingsMenu::LIST_RIGHT => {
settings.chat_list_side = match settings.chat_list_side {
Side::Left => Side::Right,
Side::Right => Side::Left,
};
}
SettingsMenu::BLOCK_GAPS => settings.block_gaps = !settings.block_gaps,
SettingsMenu::VIDEO_SIZE => {
settings.video_note_size = settings.video_note_size.next();
}
SettingsMenu::CORNERS => {
self.rounded = !self.rounded;
settings.corners = match self.rounded {
true => Corners::Rounded,
false => Corners::Square,
};
}
SettingsMenu::PILLS => settings.nerd_font = !settings.nerd_font,
SettingsMenu::ANIMATIONS => {
settings.animations = !settings.animations;
if !settings.animations {
self.motion.stop();
}
}
SettingsMenu::AFTER_SEND => settings.normal_after_send = !settings.normal_after_send,
SettingsMenu::WRAP_COMPOSER => settings.wrap_composer = !settings.wrap_composer,
SettingsMenu::SOUND_FOCUSED => {
settings.sound_when_focused = !settings.sound_when_focused;
}
SettingsMenu::SECRET_CHATS => {
settings.accept_secret_chats = !settings.accept_secret_chats;
self.tg.accept_secret_chats(settings.accept_secret_chats);
}
_ => return,
}
if let Err(e) = self.settings.save(&self.settings_path) {
self.status = Some(format!("{}{e:#}", lang::t("Settings not saved: ")));
}
}
fn set_notifications(&mut self, notifications: Notifications) {
self.settings.notifications = notifications;
self.notify_with = notifications.resolve(|name| std::env::var(name).ok());
if notifications == Notifications::Off {
self.notifier.clear();
}
}
fn load_older_messages(&mut self) {
let Some(open) = self.open.as_mut() else {
return;
};
if open.loading.is_some() || open.all_loaded {
return;
}
let page = open.oldest_id().map_or(Page::Latest, Page::Older);
open.loading = Some(page);
self.tg
.load_history(open.chat_id, open.topic, page, HISTORY_PAGE);
}
fn load_newer_messages(&mut self) {
let Some(open) = self.open.as_mut() else {
return;
};
if open.loading.is_some() || open.at_newest {
return;
}
let Some(newest) = open.newest_id() else {
return;
};
let page = Page::Newer(newest);
open.loading = Some(page);
self.tg
.load_history(open.chat_id, open.topic, page, HISTORY_PAGE);
}
fn move_message_cursor(&mut self, delta: isize) {
let Some(open) = self.open.as_mut() else {
return;
};
open.unread_after = None;
if delta == isize::MAX && (!open.at_newest || matches!(open.loading, Some(Page::Around(_))))
{
self.jump_to_newest();
return;
}
let Some(index) = open.move_cursor(delta) else {
return;
};
let len = open.messages.len();
if index < LOAD_AHEAD {
self.load_older_messages();
}
if index + LOAD_AHEAD >= len {
self.load_newer_messages();
}
}
fn wheel_messages(&mut self, lines: isize) {
let Some(open) = self.open.as_mut() else {
return;
};
open.unread_after = None;
let Some((top, bottom)) = open.scroll_lines(lines) else {
return;
};
let len = open.messages.len();
if top < LOAD_AHEAD {
self.load_older_messages();
}
if bottom + LOAD_AHEAD >= len {
self.load_newer_messages();
}
}
fn move_chat_cursor(&mut self, delta: isize) {
let ids = self.chats.ids();
if ids.is_empty() {
return;
}
let last = ids.len() - 1;
let index = match self
.selected
.and_then(|id| ids.iter().position(|&x| x == id))
{
Some(current) => current.saturating_add_signed(delta).min(last),
None => 0,
};
self.selected = Some(ids[index]);
if index + LOAD_AHEAD >= last {
self.load_more_chats(self.chats.shown());
}
}
fn load_more_chats(&mut self, list: List) {
if self.loading_lists.contains(&list) || self.loaded_lists.contains(&list) {
return;
}
self.loading_lists.insert(list);
self.tg.load_chats(list, CHAT_PAGE);
}
pub fn chats_loading(&self) -> bool {
self.loading_lists.contains(&self.chats.shown())
}
fn switch_list(&mut self, step: isize) {
if self.chats.tabs().is_empty() {
self.status = Some(lang::t("No folders yet: Telegram's apps can make them").into());
return;
}
let list = self.chats.next_list(step);
self.chats.show(list);
self.chats.refresh();
self.selected = self.chats.ids().first().copied();
self.wanted_lists.insert(list);
self.load_more_chats(list);
}
fn toggle_pin(&mut self) {
let Some(chat_id) = self.selected else {
return;
};
let pinned = self.chats.pinned(chat_id);
self.tg.pin_chat(self.chats.shown(), chat_id, !pinned);
}
fn toggle_mute(&mut self) {
let Some(chat_id) = self.selected else {
return;
};
let mute = !self.chats.muted(chat_id);
if let Some(settings) = self.chats.with_mute(chat_id, mute) {
self.tg.set_notifications(chat_id, settings);
}
}
fn start_tdlib(&mut self, keys: ApiKeys) {
match self.proxy_setting() {
Ok(proxy) => {
let number = self.tg.set_tdlib_parameters(keys, proxy);
self.proxy_changes.insert(number, ProxyChange::Start);
}
Err((from, why)) => self.screen = login_screen(LoginStep::BadProxy { from, why }),
}
}
fn proxy_source(&self) -> &'static str {
if self.tg.env_proxy().is_some() {
"TG_PROXY"
} else {
lang::t("the proxy in settings.toml")
}
}
fn proxy_setting(&self) -> Result<Option<Proxy>, (&'static str, String)> {
let (link, from) = match (self.tg.env_proxy(), &self.settings.proxy) {
(Some(link), _) => (link, "TG_PROXY"),
(None, Some(link)) => (link.as_str(), lang::t("the proxy in settings.toml")),
(None, None) => return Ok(None),
};
proxy::parse(link).map(Some).map_err(|why| (from, why))
}
fn open_proxy_prompt(&mut self) {
if self.tg.env_proxy().is_some() {
self.status = Some(lang::t("TG_PROXY sets the proxy: change it there").into());
return;
}
self.open_prompt(PromptKind::Proxy);
let link = self
.settings
.proxy
.as_deref()
.map(proxy::masked)
.unwrap_or_default();
if let Some(prompt) = self.prompt.as_mut() {
prompt.input = prompt_input(&link);
}
}
fn start_poll(&mut self) {
let Some(open) = &self.open else {
self.status = Some(lang::t("Open a chat to make a poll in").into());
return;
};
if self.chats.is_secret(open.chat_id) {
self.status = Some(lang::t("Polls can't be sent in secret chats").into());
return;
}
if (self.chats.person(open.chat_id)).is_some_and(|id| !self.chats.is_bot(id)) {
self.status =
Some(lang::t("Polls go to groups, channels, bots and Saved Messages").into());
return;
}
if self.chats.read_only(open.chat_id) {
self.status = Some(lang::t("Only the channel's admins post in it").into());
return;
}
self.open_poll_prompt(PollStep::Question, PollDraft::default());
}
fn open_poll_prompt(&mut self, step: PollStep, draft: PollDraft) {
self.open_prompt(PromptKind::Poll(step));
if let Some(prompt) = self.prompt.as_mut() {
prompt.poll = Some(draft);
if step == PollStep::Flags {
prompt.input = prompt_input("a");
}
}
}
fn on_poll_step(&mut self, step: PollStep, mut prompt: Prompt, query: &str) {
let mut draft = prompt.poll.take().unwrap_or_default();
let channel = (self.open.as_ref())
.and_then(|open| self.chats.get(open.chat_id))
.is_some_and(|chat| chat.is_channel);
let next = match step {
PollStep::Question => draft.set_question(query),
PollStep::Answer => draft.add_answer(query),
PollStep::Flags => match PollFlags::parse(query, channel) {
Ok(flags) => {
if let Some(open) = &self.open {
self.tg.send_poll(
open.chat_id,
open.topic,
draft.question,
draft.answers,
flags.anonymous,
flags.several,
);
}
self.jump_to_newest();
return;
}
Err(why) => Err(why),
},
};
match next {
Ok(next) => self.open_poll_prompt(next, draft),
Err(why) => {
self.status = Some(why);
prompt.poll = Some(draft);
self.prompt = Some(prompt);
}
}
}
fn ask_to_change_proxy(&mut self, link: &str) {
let link = link.trim();
let saved = self.settings.proxy.clone();
if let Some(saved) = saved.filter(|saved| link == proxy::masked(saved)) {
self.ask_to_use_proxy(&saved);
return;
}
if link.contains(proxy::MASK) {
self.status = Some(lang::f(
"The link still has {mask} for the hidden password or secret: write it out",
&[("mask", &proxy::MASK)],
));
return;
}
if !link.is_empty() {
self.ask_to_use_proxy(link);
return;
}
let Some(saved) = self.settings.proxy.as_deref() else {
self.status = Some(lang::t("No proxy: tuigram connects to Telegram directly").into());
return;
};
let what = proxy::parse(saved)
.map(|proxy| proxy::describe(&proxy))
.unwrap_or_else(|_| lang::t("the proxy").into());
self.confirm = Some(Confirm::new(
lang::t("Connect directly?"),
vec![
lang::f("tuigram would stop using {what}.", &[("what", &what)]),
lang::t(
"Telegram would see your IP address, and your network that you use Telegram.",
)
.into(),
],
Confirmed::NoProxy,
));
}
fn ask_to_use_proxy(&mut self, link: &str) {
if self.tg.env_proxy().is_some() {
self.status = Some(lang::t("TG_PROXY sets the proxy: change it there").into());
return;
}
match proxy::parse(link) {
Ok(proxy) => {
let mut lines = vec![
format!("{}{}", lang::t("Proxy: "), proxy::kind(&proxy)),
lang::t(
"tuigram would connect to Telegram through it. It sees your IP address \
and when you use Telegram, not your messages.",
)
.into(),
];
if matches!(proxy.r#type, ProxyType::Mtproto(_)) {
lines.push(
lang::t(
"It can also put a channel it promotes in your chat list, marked \
\"proxy sponsor\".",
)
.into(),
);
}
lines.push(
lang::t("`:proxy` changes it, or goes back to connecting directly.").into(),
);
let mut confirm = Confirm::new(
lang::t("Use this proxy?"),
lines,
Confirmed::UseProxy(link.to_string()),
);
confirm.site = Some(Site::server(proxy::address(&proxy)));
self.confirm = Some(confirm);
}
Err(why) => self.status = Some(why),
}
}
fn set_proxy(&mut self, link: &str) {
let link = link.trim();
let proxy = if link.is_empty() {
None
} else {
match proxy::parse(link) {
Ok(proxy) => Some(proxy),
Err(why) => {
self.status = Some(why);
return;
}
}
};
self.status = Some(match &proxy {
Some(proxy) => format!("{} {}…", lang::t("Switching to"), proxy::describe(proxy)),
None => lang::t("Switching to connecting directly…").into(),
});
let number = self.tg.use_proxy(proxy);
let link = (!link.is_empty()).then(|| link.to_string());
self.proxy_changes.insert(number, ProxyChange::Set(link));
}
fn on_proxy_applied(&mut self, number: u64, result: Result<(), String>) {
let Some(change) = self.proxy_changes.remove(&number) else {
return;
};
self.proxy_changes.retain(|&n, _| n > number);
match (change, result) {
(ProxyChange::Start, Ok(())) => {}
(ProxyChange::Start, Err(why)) => {
let from = self.proxy_source();
self.screen = login_screen(LoginStep::BadProxy { from, why });
}
(ProxyChange::Set(link), Ok(())) => {
let proxy = link.as_deref().and_then(|l| proxy::parse(l).ok());
self.settings.proxy = link;
self.status = None;
if let Err(e) = self.settings.save(&self.settings_path) {
self.status = Some(format!(
"{}{e:#}",
lang::t("Proxy not saved for next time: ")
));
}
match &proxy {
Some(proxy) => {
self.show_toast(lang::t("Connecting through"), &proxy::describe(proxy))
}
None => self.show_toast(
lang::t("No proxy"),
lang::t("Connecting to Telegram directly"),
),
}
}
(ProxyChange::Set(_), Err(why)) => {
self.status = Some(format!("{}{why}", lang::t("The proxy wasn't changed: ")));
}
}
}
fn unmark_unread(&mut self, chat_id: i64) {
self.chats.set_marked_unread(chat_id, false);
self.tg.mark_unread(chat_id, false);
}
fn toggle_archive(&mut self) {
let Some(chat_id) = self.selected else {
return;
};
let archived = self.chats.in_list(chat_id, List::Archive);
if matches!(self.chats.shown(), List::Main | List::Archive) {
let ids = self.chats.ids();
if let Some(i) = ids.iter().position(|&id| id == chat_id) {
let next = ids
.get(i + 1)
.or_else(|| i.checked_sub(1).and_then(|i| ids.get(i)));
self.selected = next.copied();
}
}
self.tg.archive(chat_id, !archived);
let title = self.chats.title(chat_id).unwrap_or_default().to_string();
let done = if archived {
lang::t("Moved out of the archive")
} else {
lang::t("Archived")
};
self.show_toast(done, &title);
}
fn toggle_highlight(&mut self) {
let Some(chat_id) = self.selected else {
return;
};
self.settings.highlighted_chats = self.chats.toggle_highlight(chat_id);
if let Err(e) = self.settings.save(&self.settings_path) {
self.status = Some(format!("{}{e:#}", lang::t("Highlight not saved: ")));
}
}
fn quit(&mut self) {
self.player.stop();
self.recording = None;
if self.quit_deadline.is_some() {
self.exit = true;
return;
}
let draft = self.draft_to_keep();
self.tg.close(draft);
self.quit_deadline = Some(Instant::now() + CLOSE_TIMEOUT);
}
}
fn quit_signals() -> UnboundedReceiver<()> {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
#[cfg(unix)]
tokio::spawn(async move {
use tokio::signal::unix::{SignalKind, signal};
let (Ok(mut hangup), Ok(mut terminate)) = (
signal(SignalKind::hangup()),
signal(SignalKind::terminate()),
) else {
return;
};
loop {
tokio::select! {
_ = hangup.recv() => {}
_ = terminate.recv() => {}
}
if tx.send(()).is_err() {
return;
}
}
});
#[cfg(not(unix))]
drop(tx);
rx
}
fn open_externally(target: &str) -> std::io::Result<()> {
if cfg!(target_os = "macos") {
let target = target.to_string();
std::thread::spawn(move || open::that_detached(target));
Ok(())
} else {
open::that_detached(target)
}
}
fn mouse_moved(event: &std::io::Result<Event>) -> bool {
matches!(
event,
Ok(Event::Mouse(MouseEvent {
kind: MouseEventKind::Moved | MouseEventKind::Drag(_),
..
}))
)
}
fn qwerty(c: char) -> char {
let lower = c.to_lowercase().next().unwrap_or(c);
let mapped = match lower {
'й' => 'q',
'ц' => 'w',
'у' => 'e',
'к' => 'r',
'е' => 't',
'н' => 'y',
'г' => 'u',
'ш' => 'i',
'щ' => 'o',
'з' => 'p',
'х' => '[',
'ъ' => ']',
'ё' => '`',
'ф' => 'a',
'ы' => 's',
'в' => 'd',
'а' => 'f',
'п' => 'g',
'р' => 'h',
'о' => 'j',
'л' => 'k',
'д' => 'l',
'ж' => ';',
'э' => '\'',
'я' => 'z',
'ч' => 'x',
'с' => 'c',
'м' => 'v',
'и' => 'b',
'т' => 'n',
'ь' => 'm',
'б' => ',',
'ю' => '.',
_ => return c,
};
if c.is_uppercase() {
mapped.to_ascii_uppercase()
} else {
mapped
}
}
fn reveal_in_file_manager(path: &str) {
let path = path.to_string();
std::thread::spawn(move || {
let uri = format!("file://{}", percent_encode(&path));
let run = |args: &[String]| {
std::process::Command::new("dbus-send")
.arg("--session")
.arg("--print-reply")
.args(args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
};
let started = run(&[
"--dest=org.freedesktop.DBus".into(),
"/org/freedesktop/DBus".into(),
"org.freedesktop.DBus.StartServiceByName".into(),
"string:org.freedesktop.FileManager1".into(),
"uint32:0".into(),
]);
let shown = matches!(started, Ok(s) if s.success())
&& matches!(
run(&[
"--dest=org.freedesktop.FileManager1".into(),
"/org/freedesktop/FileManager1".into(),
"org.freedesktop.FileManager1.ShowItems".into(),
format!("array:string:{uri}"),
"string:".into(),
]),
Ok(s) if s.success()
);
if !shown && let Some(dir) = Path::new(&path).parent() {
let _ = open::that_detached(dir);
}
});
}
fn percent_encode(path: &str) -> String {
let mut out = String::with_capacity(path.len());
for &b in path.as_bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b'.' | b'-' | b'_' | b'~' => {
out.push(char::from(b));
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn mark_downloaded(path: &str) {
#[cfg(target_os = "macos")]
{
use std::process::{Command, Stdio};
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let _ = Command::new("/usr/bin/xattr")
.args([
"-w",
"com.apple.quarantine",
&format!("0081;{now:x};tuigram;"),
path,
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
#[cfg(windows)]
{
let _ = std::fs::write(
format!("{path}:Zone.Identifier"),
"[ZoneTransfer]\r\nZoneId=3\r\n",
);
}
#[cfg(not(any(target_os = "macos", windows)))]
let _ = path;
}
pub const CONNECTING: &str = lang::key("Connecting…");
fn connection_words(state: &ConnectionState) -> Option<&'static str> {
Some(match state {
ConnectionState::WaitingForNetwork => lang::key("Waiting for network…"),
ConnectionState::ConnectingToProxy => lang::key("Connecting to the proxy…"),
ConnectionState::Connecting => CONNECTING,
ConnectionState::Updating => lang::key("Updating…"),
ConnectionState::Ready => return None,
})
}
fn prompt_input(text: &str) -> TextArea<'static> {
let mut input = TextArea::new(vec![text.to_string()]);
input.set_cursor_line_style(Style::default());
input.set_cursor_style(Style::default().reversed());
input.move_cursor(ratatui_textarea::CursorMove::End);
input
}
fn login_screen(step: LoginStep) -> Screen {
Screen::Login(Box::new(Login::new(step)))
}
pub fn new_composer() -> TextArea<'static> {
let mut composer = TextArea::default();
composer.set_cursor_line_style(Style::default());
composer
}
fn code_destination(kind: &AuthenticationCodeType) -> &'static str {
match kind {
AuthenticationCodeType::TelegramMessage(_) => {
lang::t("to your Telegram app on another device")
}
AuthenticationCodeType::Sms(_)
| AuthenticationCodeType::SmsWord(_)
| AuthenticationCodeType::SmsPhrase(_) => lang::t("by SMS"),
AuthenticationCodeType::Call(_) => lang::t("by phone call"),
AuthenticationCodeType::MissedCall(_) | AuthenticationCodeType::FlashCall(_) => {
lang::t("as a missed call: enter the last digits of the calling number")
}
AuthenticationCodeType::Fragment(_) => lang::t("to fragment.com"),
_ => lang::t("to one of your devices"),
}
}
fn unix_now() -> i32 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i32)
}
#[cfg(test)]
mod tests {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::style::Color;
use ratatui_image::picker::Picker;
use tokio::sync::mpsc::unbounded_channel;
use super::*;
use crate::tg::Spot;
fn press(app: &mut App, code: KeyCode, modifiers: KeyModifiers) {
app.on_key(KeyEvent::new(code, modifiers));
}
fn screen(app: &mut App) -> Vec<String> {
screen_of(app, 100)
}
fn screen_of(app: &mut App, width: u16) -> Vec<String> {
let mut terminal = Terminal::new(TestBackend::new(width, 20)).unwrap();
terminal.draw(|f| ui::draw(f, app)).unwrap();
let buf = terminal.backend().buffer();
(0..buf.area.height)
.map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect())
.collect()
}
fn screen_tall(app: &mut App) -> Vec<String> {
let mut terminal = Terminal::new(TestBackend::new(100, 40)).unwrap();
terminal.draw(|f| ui::draw(f, app)).unwrap();
let buf = terminal.backend().buffer();
(0..buf.area.height)
.map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect())
.collect()
}
#[test]
fn the_look_rows_change_only_their_own_settings() {
let dir = std::env::temp_dir().join(format!("tuigram-look-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
let none = KeyModifiers::NONE;
let saved = || Settings::load(&settings::path(&dir)).unwrap();
press(&mut app, KeyCode::Char('?'), none);
press(&mut app, KeyCode::Tab, none);
let selected = |app: &App| app.settings_menu.as_ref().unwrap().selected;
app.settings_menu.as_mut().unwrap().selected = SettingsMenu::BLOCK_GAPS;
press(&mut app, KeyCode::Char('j'), none);
assert_eq!(selected(&app), SettingsMenu::VIDEO_SIZE);
press(&mut app, KeyCode::Enter, none);
assert_eq!(
saved().video_note_size,
crate::settings::VideoNoteSize::Medium
);
press(&mut app, KeyCode::Char('j'), none);
assert_eq!(selected(&app), SettingsMenu::CORNERS);
let rounded = app.rounded;
press(&mut app, KeyCode::Enter, none);
assert_eq!(app.rounded, !rounded, "at once");
let expected = if rounded {
Corners::Square
} else {
Corners::Rounded
};
assert_eq!(saved().corners, expected, "kept, whatever the terminal");
press(&mut app, KeyCode::Char('j'), none);
assert_eq!(selected(&app), SettingsMenu::PILLS);
press(&mut app, KeyCode::Enter, none);
assert!(saved().nerd_font);
let status = screen(&mut app).pop().unwrap();
assert!(status.starts_with("\u{e0b6}NORMAL\u{e0b4}"), "{status}");
let after = saved();
assert!(!after.accept_secret_chats, "{after:?}");
assert!(!after.normal_after_send, "{after:?}");
assert!(after.block_gaps, "{after:?}");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn getting_focus_back_runs_lights_round_the_pane_with_the_keys() {
let dir = std::env::temp_dir().join(format!("tuigram-flash-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
app.focus = Focus::Chats;
let corner = |app: &mut App| {
let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap();
terminal.draw(|f| ui::draw(f, app)).unwrap();
terminal.backend().buffer()[(0, 18)].fg
};
assert_eq!(corner(&mut app), app.colors.accent);
app.on_terminal_event(Event::FocusLost);
assert_eq!(app.motion.focused, None);
app.on_terminal_event(Event::FocusGained);
assert!(app.motion.focused.is_some());
app.motion.focused = Some(Instant::now() + Duration::from_secs(60));
assert_eq!(corner(&mut app), app.colors.border, "not come round yet");
press(&mut app, KeyCode::Char('?'), KeyModifiers::NONE);
assert_eq!(corner(&mut app), app.colors.accent);
press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
app.motion.focused = None;
app.settings.animations = false;
app.on_terminal_event(Event::FocusGained);
assert_eq!(app.motion.focused, None, "turned off in ?");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_toast_replaced_while_up_stays_in_place() {
let dir = std::env::temp_dir().join(format!("tuigram-toast-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
app.show_toast("Copied", "first");
let shown = app.toast.as_ref().unwrap().shown;
app.show_toast("Copied", "second");
let toast = app.toast.as_ref().unwrap();
assert_eq!(toast.detail, "second");
assert_eq!(toast.shown, shown, "not sliding in again");
let now = Instant::now();
let until = now + motion::SLIDE / 2;
app.toast.as_mut().unwrap().until = until;
let out = motion::toast_out(shown, until, now);
app.show_toast("Copied", "third");
let back = motion::toast_out(app.toast.as_ref().unwrap().shown, until + TOAST_TIME, now);
assert!((back - out).abs() < 0.1, "{out} then {back}");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_chat_list_can_go_on_the_right_where_h_and_l_follow_it() {
let dir = std::env::temp_dir().join(format!("tuigram-side-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
app.focus = Focus::Chats;
let none = KeyModifiers::NONE;
let saved = || Settings::load(&settings::path(&dir)).unwrap();
let halves = |app: &mut App| {
let top = screen(app).remove(0);
let (left, right) = top.split_once(['╮', '┐']).unwrap();
(left.to_string(), right.to_string())
};
press(&mut app, KeyCode::Char('?'), none);
press(&mut app, KeyCode::Tab, none);
app.settings_menu.as_mut().unwrap().selected = SettingsMenu::LIST_RIGHT;
press(&mut app, KeyCode::Char(' '), none);
assert_eq!(saved().chat_list_side, Side::Right, "saved at once");
press(&mut app, KeyCode::Enter, none);
assert_eq!(saved().chat_list_side, Side::Left, "Enter toggles too");
assert!(app.settings_menu.is_some(), "the popup stays open");
press(&mut app, KeyCode::Enter, none);
press(&mut app, KeyCode::Esc, none);
assert!(app.settings_menu.is_none());
assert_eq!(saved().chat_list_side, Side::Right, "Esc keeps it");
let (left, right) = halves(&mut app);
assert!(
left.contains("Weekend Hike") && right.contains("Chats ("),
"{left}╮{right}"
);
press(&mut app, KeyCode::Char('l'), none);
assert!(app.focus == Focus::Chats, "l points away from the chat");
press(&mut app, KeyCode::Char('h'), none);
assert!(
app.focus == Focus::Messages,
"h goes to the chat, on the left"
);
let status = screen_of(&mut app, 300).pop().unwrap();
assert!(
status.contains("l back") && !status.contains("h back"),
"{status}"
);
press(&mut app, KeyCode::Char('h'), none);
assert!(app.focus == Focus::Messages);
press(&mut app, KeyCode::Char('l'), none);
assert!(app.focus == Focus::Chats, "l goes back to the list");
press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
press(&mut app, KeyCode::Char('h'), none);
assert_eq!(app.settings.list_width(), 40);
press(&mut app, KeyCode::Esc, none);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn without_focus_reports_a_minute_without_a_key_counts_as_away() {
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &std::env::temp_dir());
app.focus = Focus::Messages;
let chat = app.open.as_ref().unwrap().chat_id;
assert!(
app.watching(chat) && app.sees(chat, None),
"a key was just pressed"
);
app.last_input_wall = SystemTime::now() - (IDLE_AFTER + Duration::from_secs(1));
assert!(!app.watching(chat), "new messages aren't marked read");
assert!(!app.sees(chat, None), "and they notify");
app.focus_reported = true;
assert!(app.watching(chat) && app.sees(chat, None));
app.last_input_wall = SystemTime::now() - AWAY_AFTER;
assert!(
!app.watching(chat),
"not for good: the screen may be left on"
);
assert!(
app.sees(chat, None),
"the window has focus, so no notification"
);
app.last_input_wall = SystemTime::now();
app.terminal_focused = false;
assert!(!app.watching(chat) && !app.sees(chat, None));
}
#[test]
fn time_the_computer_slept_counts_as_time_away() {
let mut app = test_app("sleep");
app.focus = Focus::Messages;
let chat = app.open.as_ref().unwrap().chat_id;
app.last_input = Instant::now();
app.last_input_wall = SystemTime::now() - Duration::from_secs(2 * 3600);
assert!(!app.watching(chat), "nothing is marked read on waking");
app.online = false;
app.update_online();
assert!(!app.online, "and you aren't shown online");
app.last_input_wall = SystemTime::now() + Duration::from_secs(3600);
assert!(app.watching(chat));
}
#[test]
fn once_the_terminal_is_gone_nothing_more_is_marked_read() {
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &std::env::temp_dir());
app.focus = Focus::Messages;
let chat = app.open.as_ref().unwrap().chat_id;
assert!(app.watching(chat));
app.quit_deadline = Some(Instant::now() + CLOSE_TIMEOUT);
app.hang_up();
assert!(!app.watching(chat) && !app.sees(chat, None));
}
#[test]
fn a_theme_is_used_and_saved_as_soon_as_it_is_picked() {
let dir = std::env::temp_dir().join(format!("tuigram-theme-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
let none = KeyModifiers::NONE;
press(&mut app, KeyCode::Char('?'), none);
press(&mut app, KeyCode::Tab, none);
press(&mut app, KeyCode::Char('G'), none);
assert_eq!(app.settings.theme, "mocha", "moving doesn't change it");
press(&mut app, KeyCode::Char(' '), none);
assert_eq!(app.settings.theme, "rose-pine");
assert_eq!(app.colors, app.themes.colors("rose-pine").unwrap());
let saved = Settings::load(&settings::path(&dir)).unwrap();
assert_eq!(saved.theme, "rose-pine");
press(&mut app, KeyCode::Char('q'), none);
assert_eq!(app.settings.theme, "rose-pine", "closing keeps it");
std::fs::remove_dir_all(&dir).unwrap();
}
fn grid(app: &mut App, width: u16) -> Vec<Vec<char>> {
let mut terminal = Terminal::new(TestBackend::new(width, 20)).unwrap();
terminal.draw(|f| ui::draw(f, app)).unwrap();
let buf = terminal.backend().buffer();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
.collect()
})
.collect()
}
fn cell_of(grid: &[Vec<char>], rows: std::ops::Range<u16>, text: &str) -> (u16, u16) {
let want: Vec<char> = text.chars().collect();
rows.clone()
.find_map(|y| {
let row = &grid[usize::from(y)];
let x = row.windows(want.len()).position(|w| w == want.as_slice())?;
Some((x as u16, y))
})
.unwrap_or_else(|| panic!("{text} isn't on rows {rows:?}"))
}
fn mouse_at(kind: MouseEventKind, (x, y): (u16, u16)) -> MouseEvent {
MouseEvent {
kind,
column: x,
row: y,
modifiers: KeyModifiers::NONE,
}
}
#[test]
fn the_settings_popup_takes_the_mouse() {
let dir = std::env::temp_dir().join(format!("tuigram-mouse-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
let click = |at| mouse_at(MouseEventKind::Down(MouseButton::Left), at);
let menu = |app: &App| {
let menu = app.settings_menu.as_ref().unwrap();
(menu.tab, menu.selected)
};
press(&mut app, KeyCode::Char('?'), KeyModifiers::NONE);
let screen = grid(&mut app, 120);
let top = app.settings_menu.as_ref().unwrap().drawn.area.y;
let settings_tab = cell_of(&screen, top..top + 1, "Settings");
app.on_mouse(click(settings_tab));
assert_eq!(menu(&app).0, HelpTab::Settings, "its tab");
let gaps = app.settings.chat_gaps;
let screen = grid(&mut app, 120);
let row = cell_of(&screen, 0..20, "A gap between chats");
app.on_mouse(click(row));
assert_eq!(menu(&app).1, SettingsMenu::CHAT_GAPS);
assert_eq!(app.settings.chat_gaps, gaps, "not yet");
grid(&mut app, 120);
app.on_mouse(click(row));
assert_eq!(app.settings.chat_gaps, !gaps);
let saved = Settings::load(&settings::path(&dir)).unwrap();
assert_eq!(saved.chat_gaps, !gaps, "saved at once");
app.on_mouse(mouse_at(MouseEventKind::ScrollDown, row));
assert_eq!(menu(&app).1, SettingsMenu::LIST_RIGHT);
app.on_mouse(mouse_at(MouseEventKind::ScrollUp, (0, 0)));
assert_eq!(menu(&app).1, SettingsMenu::LIST_RIGHT);
app.confirm = Some(Confirm::new("Log out?", Vec::new(), Confirmed::Logout));
app.on_mouse(mouse_at(MouseEventKind::ScrollDown, row));
app.on_mouse(click(settings_tab));
assert_eq!(menu(&app).1, SettingsMenu::LIST_RIGHT);
app.confirm = None;
let screen = grid(&mut app, 120);
let shortcuts_tab = cell_of(&screen, top..top + 1, "Shortcuts");
app.on_mouse(click(shortcuts_tab));
assert_eq!(menu(&app).0, HelpTab::Shortcuts);
std::fs::remove_dir_all(&dir).unwrap();
}
fn top_of(app: &App) -> usize {
let open = app.open.as_ref().unwrap();
let layout = open.layout.as_ref().unwrap();
let max_top = (layout.spans.last().unwrap().2).saturating_sub(layout.height);
open.scroll.map_or(max_top, |anchor| {
let (_, start, _) = layout
.spans
.iter()
.find(|span| span.0 == anchor.msg_id)
.unwrap();
start + anchor.offset
})
}
#[test]
fn the_wheel_scrolls_the_history_lines_at_a_time() {
let mut app = test_app("wheel");
grid(&mut app, 100);
let history = app.mouse.history;
let cell = (history.x + 2, history.y + 2);
let bottom = top_of(&app);
assert!(bottom >= WHEEL_LINES as usize, "enough history to scroll");
app.on_mouse(mouse_at(MouseEventKind::ScrollUp, cell));
assert_eq!(top_of(&app), bottom - WHEEL_LINES as usize);
assert!(
app.open.as_ref().unwrap().selected.is_some(),
"leaves following"
);
app.on_mouse(mouse_at(MouseEventKind::ScrollDown, cell));
assert_eq!(top_of(&app), bottom);
assert!(app.open.as_ref().unwrap().selected.is_none());
let ids = app.chats.ids();
let at = ids.iter().position(|id| Some(*id) == app.selected).unwrap();
let next = ids[(at + 1).min(ids.len() - 1)];
let row = app
.mouse
.chat_rows
.iter()
.find(|(_, _, id)| *id == ids[at])
.map(|(from, _, _)| *from)
.unwrap();
let cell = (app.mouse.chats.x, row);
app.on_mouse(mouse_at(MouseEventKind::ScrollDown, cell));
assert_eq!(app.selected, Some(next));
}
#[test]
fn a_long_setting_wraps_and_a_click_on_any_of_its_rows_picks_it() {
let dir = std::env::temp_dir().join(format!("tuigram-wrap-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
lang::set(lang::Lang::Vi);
press(&mut app, KeyCode::Char('?'), KeyModifiers::NONE);
press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
app.settings_menu.as_mut().unwrap().selected = SettingsMenu::SOUND_FOCUSED;
let screen = grid(&mut app, 80);
let first = cell_of(&screen, 0..20, "Nhận các cuộc");
let last = cell_of(&screen, 0..20, "thoại");
assert!(last.1 > first.1, "on rows of its own");
let popup = app.settings_menu.as_ref().unwrap().drawn.area;
assert!(last.0 + 5 < popup.right(), "inside the popup");
app.on_mouse(mouse_at(MouseEventKind::Down(MouseButton::Left), last));
let selected = app.settings_menu.as_ref().unwrap().selected;
assert_eq!(selected, SettingsMenu::SECRET_CHATS);
assert!(
!app.settings.accept_secret_chats,
"a first click only picks it"
);
lang::set(lang::Lang::En);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_language_picked_in_the_settings_speaks_at_once_and_is_saved() {
let dir = std::env::temp_dir().join(format!("tuigram-language-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
let none = KeyModifiers::NONE;
press(&mut app, KeyCode::Char('?'), none);
press(&mut app, KeyCode::Tab, none);
let rows = screen_of(&mut app, 140).join("\n");
for row in [" ● English", " ○ Русский", " ○ Tiếng Việt"] {
assert!(rows.contains(row), "{row}: {rows}");
}
app.settings_menu.as_mut().unwrap().selected = SettingsMenu::LANGUAGE + 2;
press(&mut app, KeyCode::Enter, none);
assert_eq!(lang::current(), lang::Lang::Vi, "at once");
let saved = Settings::load(&settings::path(&dir)).unwrap();
assert_eq!(saved.language, "vi");
let rows = screen_of(&mut app, 140).join("\n");
assert!(rows.contains(" ● Tiếng Việt"), "{rows}");
assert!(rows.contains(lang::t(" Notifications").trim()), "{rows}");
lang::set(lang::Lang::En);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_connection_is_said_in_the_language_picked_since() {
let mut app = test_app("connection-words");
app.on_update(Update::ConnectionState(
tdlib_rs::types::UpdateConnectionState {
state: ConnectionState::Connecting,
},
));
assert!(screen(&mut app)[19].contains("Connecting…"));
lang::set(lang::Lang::Vi);
let row = screen(&mut app)[19].clone();
assert!(row.contains(lang::t("Connecting…")), "{row}");
assert!(!row.contains("Connecting…"), "{row}");
lang::set(lang::Lang::En);
}
#[test]
fn a_sound_picked_in_the_settings_plays_and_is_saved() {
let dir = std::env::temp_dir().join(format!("tuigram-sound-{}", std::process::id()));
std::fs::create_dir_all(dir.join("sounds")).unwrap();
std::fs::write(dir.join("sounds/broken.wav"), b"RIFF, and no more").unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
app.over_ssh = false;
let pick = |app: &mut App, row| {
if app.settings_menu.is_none() {
press(app, KeyCode::Char('?'), KeyModifiers::NONE);
press(app, KeyCode::Tab, KeyModifiers::NONE);
}
app.settings_menu.as_mut().unwrap().selected = row;
press(app, KeyCode::Enter, KeyModifiers::NONE);
};
app.player = Player::new(unbounded_channel().0, crate::voice::Output::Nowhere);
pick(&mut app, SettingsMenu::SOUNDS + 2);
assert_eq!(app.settings.notification_sound.as_deref(), Some("chime"));
assert!(app.player.rang(), "played, to hear it");
let saved = Settings::load(&settings::path(&dir)).unwrap();
assert_eq!(saved.notification_sound.as_deref(), Some("chime"));
let broken = app.sounds.list.iter().position(|s| s.id == "broken");
pick(&mut app, SettingsMenu::SOUNDS + 1 + broken.unwrap());
let status = app.status.take().unwrap_or_default();
assert!(
status.starts_with("Sound not used: broken.wav: "),
"{status}"
);
assert_eq!(app.settings.notification_sound.as_deref(), Some("chime"));
assert!(app.sound.is_some());
pick(&mut app, SettingsMenu::SOUNDS);
assert_eq!(app.settings.notification_sound, None);
assert!(app.sound.is_none());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn opening_the_settings_keeps_the_sound_decoded_unless_it_changed() {
let mut app = test_app("keep-sound");
app.settings.notification_sound = Some("chime".into());
app.use_saved_sound();
let marked: Arc<[i16]> = vec![1].into();
app.sound = Some(Arc::clone(&marked));
press(&mut app, KeyCode::Char('?'), KeyModifiers::NONE);
assert!(
app.sound.as_ref().is_some_and(|s| Arc::ptr_eq(s, &marked)),
"not decoded again"
);
press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
app.settings.notification_sound = Some("ding".into());
app.use_saved_sound();
assert!(app.sound.as_ref().is_some_and(|s| !Arc::ptr_eq(s, &marked)));
app.settings.notification_sound = None;
app.use_saved_sound();
assert!(app.sound.is_none());
}
#[test]
fn the_sound_rings_for_each_new_message_at_most_once_a_second() {
let mut app = test_app("ring");
app.over_ssh = false;
app.sound = Some(vec![100; 480].into());
let quiet = || Player::new(unbounded_channel().0, crate::voice::Output::Nowhere);
let ring = |app: &mut App, silent, seen| {
app.player = quiet();
app.rang_at = None;
app.ring_for(silent, seen);
app.player.rang()
};
assert!(ring(&mut app, false, false));
assert!(!ring(&mut app, true, false), "a chat whose sound is off");
assert!(!ring(&mut app, false, true), "seen while focused");
app.settings.sound_when_focused = true;
assert!(ring(&mut app, false, true), "asked for while focused too");
app.over_ssh = true;
assert!(
!ring(&mut app, false, false),
"it'd play on the other computer"
);
app.over_ssh = false;
assert!(ring(&mut app, false, false));
app.player = quiet();
app.ring_for(false, false);
assert!(!app.player.rang(), "within a second of the last");
app.rang_at = app.rang_at.map(|at| at - RING_GAP);
app.ring_for(false, false);
assert!(app.player.rang());
use tdlib_rs::enums::NotificationGroupType;
use tdlib_rs::types::Notification;
app.notify_with = Notifications::Bell;
app.notify_since = 0;
(app.focus_reported, app.terminal_focused) = (true, false);
let update = |id, sound| UpdateNotificationGroup {
notification_group_id: 1,
r#type: NotificationGroupType::SecretChat,
chat_id: 1,
notification_settings_chat_id: 1,
notification_sound_id: sound,
total_count: 1,
added_notifications: vec![Notification {
id,
date: unix_now(),
is_silent: false,
r#type: NotificationType::NewSecretChat,
}],
removed_notification_ids: Vec::new(),
};
for id in [1, 2] {
(app.player, app.rang_at) = (quiet(), None);
app.on_notifications(update(id, -1));
assert!(app.player.rang(), "notification {id}");
assert!(app.notifier.due(Instant::now()).is_some() == (id == 1));
}
(app.player, app.rang_at) = (quiet(), None);
app.on_notifications(update(3, 0));
assert!(!app.player.rang(), "the chat's sound is off in Telegram");
app.notify_with = Notifications::Off;
(app.player, app.rang_at) = (quiet(), None);
app.notifier = crate::notify::Notifier::default();
app.on_notifications(update(4, -1));
assert!(app.player.rang(), "a setting of its own");
assert!(
app.notifier.due(Instant::now()).is_none(),
"no notification"
);
}
#[test]
fn themes_in_the_data_folder_are_read_again_when_the_popup_opens() {
let dir = std::env::temp_dir().join(format!("tuigram-own-theme-{}", std::process::id()));
std::fs::create_dir_all(dir.join("themes")).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
let none = KeyModifiers::NONE;
let file = dir.join("themes/mine.toml");
app.settings.theme = "mine".into();
std::fs::write(&file, "inherits = \"mocha\"\n[colors]\nbg = \"#000000\"").unwrap();
press(&mut app, KeyCode::Char('?'), none);
assert_eq!(app.colors.bg, Color::Rgb(0, 0, 0));
assert_eq!(app.status, None);
press(&mut app, KeyCode::Esc, none);
std::fs::write(&file, "inherits = 3").unwrap();
press(&mut app, KeyCode::Char('?'), none);
assert_eq!(app.colors, Colors::default());
let status = app.status.clone().unwrap();
assert!(status.contains("mine.toml: line 1"), "{status}");
assert_eq!(app.settings.theme, "mine", "kept, for when it's fixed");
press(&mut app, KeyCode::Tab, none);
press(&mut app, KeyCode::Char('G'), none);
press(&mut app, KeyCode::Enter, none);
assert!(app.status.as_ref().unwrap().contains("mine.toml"));
assert_eq!(app.colors, Colors::default());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn ctrl_r_resizes_the_panes_and_each_press_is_kept_for_next_time() {
let dir = std::env::temp_dir().join(format!("tuigram-resize-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
app.focus = Focus::Messages;
let edge = |rows: &[String]| {
rows[0]
.chars()
.position(|c| matches!(c, '╮' | '┐'))
.unwrap()
};
let none = KeyModifiers::NONE;
assert_eq!(edge(&screen(&mut app)), 34, "35% of 100 columns");
press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
assert!(app.open.as_ref().unwrap().reply.is_none(), "not a reply");
press(&mut app, KeyCode::Char('l'), none);
press(&mut app, KeyCode::Char('l'), none);
let rows = screen(&mut app);
assert_eq!(edge(&rows), 44, "wider as you press");
let status = rows.last().unwrap();
assert!(
status.contains(" RESIZE ") && status.contains("chat list 45%"),
"{status}"
);
let saved = || {
Settings::load(&settings::path(&dir))
.unwrap()
.chat_list_width
};
assert_eq!(saved(), 45, "saved as it's pressed, no Enter needed");
press(&mut app, KeyCode::Enter, none);
assert!(app.resizing.is_none());
press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
press(&mut app, KeyCode::Char('h'), none);
assert_eq!(edge(&screen(&mut app)), 39);
assert_eq!(saved(), 40);
press(&mut app, KeyCode::Esc, none);
assert!(app.resizing.is_none());
assert_eq!(edge(&screen(&mut app)), 39, "Esc leaves it as it is");
assert_eq!(saved(), 40);
assert!(app.focus == Focus::Messages, "and stays in the chat");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn only_files_that_cant_run_code_open_without_asking() {
for path in [
"/d/photo.JPG",
"/d/clip.mp4",
"/d/report.pdf",
"/d/notes.txt",
] {
assert!(safe_to_open(path), "{path}");
}
for path in [
"/d/setup.exe",
"/d/run.bat",
"/d/x.command",
"/d/x.terminal",
"/d/app.jar",
"/d/page.html",
"/d/invoice.pdf.exe",
"/d/no-extension",
"/d/data.csv",
] {
assert!(!safe_to_open(path), "{path}");
}
}
fn test_app(tag: &str) -> App {
let dir = std::env::temp_dir().join(format!("tuigram-test-{tag}"));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
crate::demo::demo_app(Tg::detached(unbounded_channel().0), images, &dir)
}
#[test]
fn the_wheel_down_to_the_last_loaded_message_asks_for_newer_ones() {
let mut app = test_app("wheel-newer");
let open = app.open.as_mut().unwrap();
let mut stretch = OpenChat::new(open.chat_id);
stretch.add_page(Page::Around(20), crate::messages::tests::page(1..=40));
stretch.at_newest = false;
let spans = (1..=40)
.map(|id| (id, id as usize - 1, id as usize))
.collect();
stretch.layout = Some(crate::messages::LineLayout { spans, height: 30 });
stretch.scroll = Some(crate::messages::ScrollAnchor {
msg_id: 1,
offset: 0,
});
stretch.loading = None;
*open = stretch;
app.wheel_messages(20);
assert!(
matches!(app.open.as_ref().unwrap().loading, Some(Page::Newer(_))),
"the bottom of the view is at the last message loaded"
);
}
#[test]
fn a_recording_is_dropped_on_leaving_its_chat_or_the_account() {
let mut app = test_app("record-leave");
let (here, other) = two_chats(&app);
let recording = |chat_id| {
Some(Recording {
recorder: Recorder::idle(),
chat_id,
topic: None,
})
};
app.recording = recording(here);
app.open_chat(other);
assert!(
app.recording.is_none(),
"its y would send it to the chat left"
);
app.recording = recording(other);
app.forget_session();
assert!(app.recording.is_none(), "nor to another account");
}
#[test]
fn v_stops_a_recording_from_whichever_pane_has_the_keys() {
let mut app = test_app("record-stop-anywhere");
let (here, _) = two_chats(&app);
for focus in [Focus::Chats, Focus::Messages] {
app.recording = Some(Recording {
recorder: Recorder::idle(),
chat_id: here,
topic: None,
});
app.focus = focus;
press(&mut app, KeyCode::Char('V'), KeyModifiers::NONE);
assert!(app.recording.is_none(), "{focus:?}: the status bar says V");
}
}
#[test]
fn a_recorded_voice_message_goes_once_sent_and_stays_to_send_again() {
use tdlib_rs::types;
let mut app = test_app("record-upload");
let outbox = app.outbox();
std::fs::create_dir_all(&outbox).unwrap();
let path = outbox.join("tuigram-voice-1-2.ogg");
let elsewhere = outbox.with_file_name("tuigram-voice-1-3.ogg");
for file in [&path, &elsewhere] {
std::fs::write(file, b"x").unwrap();
}
let file = uploaded_file(&path);
app.on_update(Update::File(types::UpdateFile { file }));
assert!(path.exists(), "uploaded, not yet sent");
app.on_update(voice_sent(&elsewhere));
assert!(elsewhere.exists(), "not a recording in the outbox");
app.on_update(voice_sent(&path));
assert!(!path.exists(), "sent");
std::fs::remove_file(&elsewhere).unwrap();
}
fn uploaded_file(path: &Path) -> tdlib_rs::types::File {
use tdlib_rs::types;
types::File {
id: 5,
local: types::LocalFile {
path: path.to_string_lossy().into_owned(),
..Default::default()
},
remote: types::RemoteFile {
is_uploading_completed: true,
..Default::default()
},
..Default::default()
}
}
fn voice_sent(path: &Path) -> Update {
use tdlib_rs::{enums, types};
let mut message = tdlib_text(1, 9, "");
message.content = enums::MessageContent::MessageVoiceNote(types::MessageVoiceNote {
voice_note: types::VoiceNote {
voice: uploaded_file(path),
..Default::default()
},
caption: types::FormattedText::default(),
is_listened: false,
});
Update::MessageSendSucceeded(types::UpdateMessageSendSucceeded {
message,
old_message_id: 8,
})
}
fn tdlib_text(chat_id: i64, id: i64, text: &str) -> tdlib_rs::types::Message {
use tdlib_rs::{enums, types};
types::Message {
id,
sender_id: enums::MessageSender::User(types::MessageSenderUser { user_id: 2 }),
chat_id,
sending_state: None,
scheduling_state: None,
is_outgoing: false,
is_pinned: false,
is_from_offline: false,
can_be_saved: true,
has_timestamped_media: false,
is_channel_post: false,
is_paid_star_suggested_post: false,
is_paid_ton_suggested_post: false,
contains_unread_mention: false,
date: 1_800_000_000,
edit_date: 0,
forward_info: None,
import_info: None,
interaction_info: None,
unread_reactions: Vec::new(),
fact_check: None,
suggested_post_info: None,
reply_to: None,
topic_id: None,
self_destruct_type: None,
self_destruct_in: 0.0,
auto_delete_in: 0.0,
via_bot_user_id: 0,
sender_business_bot_user_id: 0,
sender_boost_count: 0,
paid_message_star_count: 0,
author_signature: String::new(),
media_album_id: 0,
effect_id: 0,
restriction_info: None,
summary_language_code: String::new(),
content: enums::MessageContent::MessageText(types::MessageText {
text: types::FormattedText {
text: text.into(),
..Default::default()
},
link_preview: None,
link_preview_options: None,
}),
reply_markup: None,
}
}
#[test]
fn a_scheduled_message_joins_the_history_only_once_its_sent() {
use tdlib_rs::{enums, types};
let mut app = test_app("scheduled-new");
let open = app.open.as_ref().unwrap();
let (chat_id, newest) = (open.chat_id, open.newest_id().unwrap());
let arrive = |app: &mut App, message: &types::Message| {
app.on_update(Update::NewMessage(types::UpdateNewMessage {
message: message.clone(),
}));
app.open
.as_ref()
.unwrap()
.messages
.contains_key(&message.id)
};
let mut later = tdlib_text(chat_id, newest + 1, "later");
later.is_outgoing = true;
later.scheduling_state = Some(enums::MessageSchedulingState::SendAtDate(
types::MessageSchedulingStateSendAtDate {
send_date: 1_900_000_000,
repeat_period: 0,
},
));
assert!(!arrive(&mut app, &later), "waits to be sent");
later.id = newest + 2;
later.scheduling_state = None;
assert!(arrive(&mut app, &later), "sent");
}
#[test]
fn a_scheduled_message_telegram_refuses_gives_its_text_back_to_an_empty_composer() {
use tdlib_rs::{enums, types};
crate::tg::quiet();
let mut app = test_app("schedule-refused");
let answered = plain_message(&mut app);
let chat_id = app.open.as_ref().unwrap().chat_id;
let refused = |text: &str| {
let mut message = tdlib_text(chat_id, 77, text);
message.is_outgoing = true;
message.reply_to = Some(enums::MessageReplyTo::Message(
types::MessageReplyToMessage {
chat_id,
message_id: answered,
quote: None,
checklist_task_id: 0,
origin: None,
origin_send_date: 0,
content: None,
},
));
message.scheduling_state = Some(enums::MessageSchedulingState::SendAtDate(
types::MessageSchedulingStateSendAtDate {
send_date: 1_900_000_000,
repeat_period: 0,
},
));
Update::MessageSendFailed(types::UpdateMessageSendFailed {
message,
old_message_id: 76,
error: types::Error {
code: 400,
message: "SCHEDULE_TOO_MUCH".into(),
},
})
};
app.on_update(refused("see you at 9"));
assert_eq!(app.composer.lines(), ["see you at 9"]);
let open = app.open.as_ref().unwrap();
assert_eq!(
open.reply.as_ref().map(|r| r.id),
Some(answered),
"still a reply"
);
let status = app.status.as_deref().unwrap_or_default();
assert!(
status.contains("SCHEDULE_TOO_MUCH") && status.contains("composer"),
"{status}"
);
app.composer = new_composer();
app.composer.insert_str("something else");
app.on_update(refused("see you at 9"));
assert_eq!(app.composer.lines(), ["something else"]);
}
#[cfg(unix)]
#[test]
fn a_recording_is_deleted_once_sent_though_its_folder_is_a_link() {
let mut app = test_app("record-upload-link");
let outbox = app.outbox();
let real = outbox.with_file_name("real-outbox");
std::fs::create_dir_all(&real).unwrap();
let _ = std::fs::remove_file(&outbox);
std::os::unix::fs::symlink(&real, &outbox).unwrap();
let path = std::fs::canonicalize(&real)
.unwrap()
.join("tuigram-voice-1-2.ogg");
std::fs::write(&path, b"x").unwrap();
app.on_update(voice_sent(&path));
assert!(!path.exists());
}
fn two_chats(app: &App) -> (i64, i64) {
let here = app.open.as_ref().unwrap().chat_id;
let other = app
.chats
.ids()
.iter()
.copied()
.find(|&id| id != here && !app.chats.is_forum(id) && !app.chats.is_secret(id))
.unwrap();
(here, other)
}
fn draft_text(app: &App, chat_id: i64) -> Option<&str> {
app.chats.draft(chat_id).map(|d| d.text.as_str())
}
#[test]
fn what_is_left_written_in_a_chat_is_its_draft_and_comes_back_when_it_opens() {
crate::tg::quiet();
let mut app = test_app("drafts");
let none = KeyModifiers::NONE;
let (here, other) = two_chats(&app);
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('i'), none);
for c in "on my **way**".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Esc, none);
assert_eq!(draft_text(&app, here), Some("on my **way**"));
app.open_chat(other);
assert_eq!(app.composer.lines().join("\n"), "");
app.open_chat(here);
assert_eq!(app.composer.lines().join("\n"), "on my **way**");
app.composer = new_composer();
app.open_chat(other);
assert_eq!(draft_text(&app, here), None);
}
#[test]
fn a_draft_written_elsewhere_is_not_replaced_by_a_composer_nobody_touched() {
crate::tg::quiet();
let mut app = test_app("drafts-elsewhere");
let (here, other) = two_chats(&app);
app.chats
.keep_draft(here, Draft::new("from my phone", Some(7)));
app.open_chat(other);
assert_eq!(draft_text(&app, here), Some("from my phone"));
app.open_chat(here);
assert_eq!(app.composer.lines().join("\n"), "from my phone");
let open = app.open.as_ref().unwrap();
assert_eq!((open.draft_reply, open.reply.is_none()), (Some(7), true));
app.open_chat(other);
assert_eq!(app.chats.draft(here).and_then(|d| d.reply_to), Some(7));
}
#[test]
fn a_drafts_reply_that_is_not_shown_is_not_sent() {
crate::tg::quiet();
let mut app = test_app("drafts-hidden-reply");
let none = KeyModifiers::NONE;
let (here, other) = two_chats(&app);
app.chats
.keep_draft(here, Draft::new("from my phone", Some(7)));
app.open_chat(other);
app.open_chat(here);
app.focus = Focus::Messages;
let open = app.open.as_mut().unwrap();
assert_eq!(open.draft_reply, Some(7));
open.add_page(Page::Latest, crate::messages::tests::page([1, 2, 3]));
let another = 2;
open.selected = Some(another);
press(&mut app, KeyCode::Char('r'), none);
let open = app.open.as_ref().unwrap();
assert_eq!(open.reply.as_ref().map(|r| r.id), Some(another));
assert_eq!(open.draft_reply, None, "message 7 can't come back over it");
press(&mut app, KeyCode::Esc, none);
press(&mut app, KeyCode::Esc, none);
assert!(app.open.as_ref().unwrap().reply.is_none());
assert_eq!(app.written().unwrap().1, None, "the draft answers nothing");
app.open_chat(other);
app.chats
.keep_draft(here, Draft::new("from my phone", Some(7)));
app.open_chat(here);
let open = app.open.as_mut().unwrap();
assert_eq!(open.draft_reply, Some(7));
assert_eq!(open.take_reply(), None);
assert_eq!(open.draft_reply, None);
open.add_page(Page::Latest, crate::messages::tests::page([1, 2, 3]));
open.selected = Some(2);
press(&mut app, KeyCode::Char('r'), none);
assert_eq!(app.open.as_mut().unwrap().take_reply(), Some(2));
}
#[test]
fn the_status_bar_says_while_telegram_cant_be_reached() {
let mut app = test_app("connection");
let state =
|state| Update::ConnectionState(tdlib_rs::types::UpdateConnectionState { state });
app.on_update(state(ConnectionState::WaitingForNetwork));
let rows = screen(&mut app);
assert!(
rows[19].starts_with(" NORMAL Waiting for network…"),
"{:?}",
rows[19]
);
app.on_update(state(ConnectionState::ConnectingToProxy));
assert!(screen(&mut app)[19].contains("Connecting to the proxy…"));
app.on_update(state(ConnectionState::Ready));
assert!(!screen(&mut app)[19].contains('…'));
}
#[test]
fn ctrl_o_and_ctrl_i_go_back_and_forward_like_vims_jump_list() {
let at = |chat_id, message_id| Jump {
chat_id,
topic: None,
message_id,
};
let mut jumps = Jumps::default();
jumps.leave(at(1, None));
jumps.leave(at(2, Some(5)));
jumps.leave(at(2, Some(5)));
assert_eq!(jumps.go(true, Some(at(3, None))), Some(at(2, Some(5))));
assert_eq!(jumps.go(true, Some(at(2, Some(5)))), Some(at(1, None)));
assert_eq!(
jumps.go(true, Some(at(1, None))),
None,
"the same place once"
);
assert_eq!(jumps.go(false, Some(at(1, None))), Some(at(2, Some(5))));
assert!(jumps.can_go_back() && jumps.can_go_forward());
jumps.leave(at(2, Some(5)));
assert!(!jumps.can_go_forward());
for id in 0..MAX_JUMPS as i64 * 2 {
jumps.leave(at(id, None));
}
assert_eq!(jumps.back.len(), MAX_JUMPS);
}
#[test]
fn gd_then_ctrl_o_and_ctrl_i_move_between_a_reply_and_what_it_answers() {
let mut app = test_app("jumps");
app.focus = Focus::Messages;
let (none, ctrl) = (KeyModifiers::NONE, KeyModifiers::CONTROL);
let reply = app
.open
.as_ref()
.unwrap()
.messages
.iter()
.find_map(|(&id, m)| {
let to = m.reply_to.as_ref()?.message_id?;
Some((id, to))
});
let (from, to) = reply.expect("the demo has a reply");
let cursor = |app: &App| app.open.as_ref().unwrap().selected;
app.open.as_mut().unwrap().selected = Some(from);
press(&mut app, KeyCode::Char('g'), none);
press(&mut app, KeyCode::Char('d'), none);
assert_eq!(cursor(&app), Some(to));
press(&mut app, KeyCode::Char('o'), ctrl);
assert_eq!(cursor(&app), Some(from));
press(&mut app, KeyCode::Char('i'), ctrl);
assert_eq!(cursor(&app), Some(to));
assert!(app.focus == Focus::Messages, "not Insert mode");
press(&mut app, KeyCode::Char('o'), ctrl);
press(&mut app, KeyCode::Tab, none);
assert_eq!(cursor(&app), Some(to));
press(&mut app, KeyCode::Tab, none);
assert_eq!(app.status.as_deref(), Some("Nothing to go forward to"));
}
#[test]
fn h_and_l_go_from_the_chats_to_a_forums_topics_to_a_topics_messages_and_back() {
let mut app = test_app("forum");
crate::demo::show_forum(&mut app);
let none = KeyModifiers::NONE;
let topic = |app: &App| app.forum.as_ref().and_then(|f| f.current()).map(|t| t.id);
assert!(app.focus == Focus::Topics);
let open = topic(&app);
assert_eq!(app.open.as_ref().and_then(|o| o.topic), open);
press(&mut app, KeyCode::Char('j'), none);
assert_ne!(topic(&app), open);
press(&mut app, KeyCode::Char('k'), none);
assert_eq!(topic(&app), open);
press(&mut app, KeyCode::Char('l'), none);
assert!(app.focus == Focus::Messages);
press(&mut app, KeyCode::Char('h'), none);
assert!(
app.focus == Focus::Topics,
"back to the topics, not the chats"
);
press(&mut app, KeyCode::Char('h'), none);
assert!(app.focus == Focus::Chats);
press(&mut app, KeyCode::Char('l'), none);
assert!(app.focus == Focus::Topics);
assert_eq!(app.open.as_ref().and_then(|o| o.topic), open);
press(&mut app, KeyCode::Esc, none);
assert!(app.focus == Focus::Chats);
press(&mut app, KeyCode::Enter, none);
press(&mut app, KeyCode::Enter, none);
press(&mut app, KeyCode::Esc, none);
assert!(
app.focus == Focus::Topics,
"Esc leaves a topic for the topics"
);
}
#[test]
fn whats_meant_for_one_topic_stays_out_of_another() {
let mut app = test_app("forum-place");
crate::demo::show_forum(&mut app);
let (chat, topic) = app.open.as_ref().unwrap().place();
let other = (chat, topic.map(|t| t + 1));
app.focus = Focus::Messages;
app.pasting = true;
app.on_pasted(Pasted {
place: other,
content: Ok(Paste::Text("the screenshot".into())),
});
assert!(app.focus == Focus::Messages, "not Insert mode");
assert!(!app.pasting);
assert!(app.composer.is_empty());
app.focus = Focus::Topics;
app.on_pasted(Pasted {
place: (chat, topic),
content: Ok(Paste::Text("the screenshot".into())),
});
assert!(app.focus == Focus::Topics);
assert!(app.composer.is_empty());
app.focus = Focus::Messages;
app.on_bot_answer(other, "Buy".into(), "Sold out", true, "");
assert!(app.notice.is_none());
app.on_bot_answer((chat, topic), "Buy".into(), "Sold out", true, "");
assert!(app.notice.is_some());
app.notice = None;
let before: Vec<i64> = app
.open
.as_ref()
.unwrap()
.messages
.keys()
.copied()
.collect();
app.open.as_mut().unwrap().loading = Some(Page::Around(1));
app.on_history((chat, topic), Page::Around(1), Some(Vec::new()));
let after: Vec<i64> = app
.open
.as_ref()
.unwrap()
.messages
.keys()
.copied()
.collect();
assert_eq!(before, after);
assert_eq!(
app.status.as_deref(),
Some("That message isn't in this topic")
);
assert!(app.sees(chat, topic));
assert!(!app.sees(chat, other.1));
}
#[test]
fn ctrl_r_in_a_forums_topics_resizes_their_pane() {
let mut app = test_app("forum-resize");
crate::demo::show_forum(&mut app);
let none = KeyModifiers::NONE;
let edge = |rows: &[String]| {
let top: Vec<char> = rows[0].chars().collect();
top.iter()
.enumerate()
.filter(|&(_, &c)| matches!(c, '╮' | '┐'))
.map(|(i, _)| i)
.nth(1)
.unwrap()
};
let start = edge(&screen_of(&mut app, 140));
let list = app.settings.chat_list_width;
press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
assert_eq!(app.resizing, Some(Resizing::Topics));
press(&mut app, KeyCode::Char('l'), none);
press(&mut app, KeyCode::Char('l'), none);
let rows = screen_of(&mut app, 140);
assert_eq!(edge(&rows), start + 4, "two columns a press");
assert!(rows.last().unwrap().contains("topics 34 columns"));
assert_eq!(app.settings.chat_list_width, list, "the chat list stays");
let saved = |app: &App| Settings::load(&app.settings_path).unwrap().topics_width;
assert_eq!(saved(&app), 34, "kept for next time as it's pressed");
press(&mut app, KeyCode::Esc, none);
assert_eq!(
edge(&screen_of(&mut app, 140)),
start + 4,
"Esc leaves it as it is"
);
press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
press(&mut app, KeyCode::Char('h'), none);
press(&mut app, KeyCode::Enter, none);
assert!(app.resizing.is_none());
assert_eq!(app.settings.topics_width, 32);
assert_eq!(saved(&app), 32);
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
assert!(matches!(app.resizing, Some(Resizing::List)));
}
#[test]
fn with_the_chat_list_on_the_right_the_topics_are_still_between_it_and_the_messages() {
let mut app = test_app("forum-right");
crate::demo::show_forum(&mut app);
app.settings.chat_list_side = Side::Right;
let rows = screen_of(&mut app, 140);
let top = &rows[0];
let messages = top.find("Rustaceans › Async").expect("the messages' title");
let topics = top.find("Rustaceans · topics").expect("the topics' title");
let chats = top.find("Chats (").expect("the chat list's title");
assert!(messages < topics && topics < chats, "{top}");
press(&mut app, KeyCode::Char('l'), KeyModifiers::NONE);
assert!(app.focus == Focus::Chats);
press(&mut app, KeyCode::Char('h'), KeyModifiers::NONE);
assert!(app.focus == Focus::Topics);
press(&mut app, KeyCode::Char('h'), KeyModifiers::NONE);
assert!(app.focus == Focus::Messages);
}
#[test]
fn tab_and_shift_tab_in_the_chat_list_go_round_the_folders() {
let mut app = test_app("folders");
app.focus = Focus::Chats;
let (friends, work) = (List::Folder(1), List::Folder(2));
app.loaded_lists.extend([List::Main, friends, work]);
let none = KeyModifiers::NONE;
let top = |app: &mut App| screen(app)[1].clone();
assert!(top(&mut app).contains(" All 3 "), "{}", top(&mut app));
press(&mut app, KeyCode::Tab, none);
assert_eq!(app.chats.shown(), friends);
app.chats.refresh();
assert!(
app.chats
.ids()
.iter()
.all(|&id| app.chats.in_list(id, friends))
);
press(&mut app, KeyCode::Tab, none);
assert_eq!(app.chats.shown(), work);
press(&mut app, KeyCode::Tab, none);
assert_eq!(app.chats.shown(), List::Main, "round the end");
press(&mut app, KeyCode::BackTab, none);
assert_eq!(app.chats.shown(), work);
let first = app.chats.ids()[0];
assert_eq!(app.selected, Some(first), "on the folder's first chat");
}
fn plain_message(app: &mut App) -> i64 {
let open = app.open.as_mut().unwrap();
let id = open
.messages
.iter()
.find(|(_, m)| m.state == SendState::Sent && m.poll.is_none() && !m.hides_spoilers())
.map(|(&id, _)| id)
.unwrap();
open.selected = Some(id);
id
}
#[test]
fn enter_on_a_message_that_was_not_sent_sends_it_again_if_telegram_can_take_it() {
let mut app = test_app("resend");
app.focus = Focus::Messages;
let id = plain_message(&mut app);
let set = |app: &mut App, can_retry| {
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().state = SendState::Failed { can_retry };
};
set(&mut app, true);
let rows = screen(&mut app);
assert!(rows[19].contains("Enter send again"), "{:?}", rows[19]);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert_eq!(app.status, None);
assert!(app.menu.is_none(), "nothing opens instead");
set(&mut app, false);
assert!(!screen(&mut app)[19].contains("Enter send again"));
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert_eq!(
app.status.as_deref(),
Some("Telegram won't take this message again: `d` deletes it")
);
}
#[test]
fn a_chat_marked_unread_elsewhere_is_unmarked_once_opened_even_the_one_open() {
let mut app = test_app("marked-unread");
let (here, other) = two_chats(&app);
app.chats.set_marked_unread(other, true);
app.open_chat(other);
assert!(!app.chats.get(other).unwrap().marked_unread);
app.chats.set_marked_unread(other, true);
app.focus = Focus::Chats;
app.selected = Some(other);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(!app.chats.get(other).unwrap().marked_unread);
assert!(!app.chats.get(here).unwrap().marked_unread);
}
#[test]
fn a_archives_the_chat_and_the_cursor_goes_on_to_the_next() {
let mut app = test_app("archive");
app.focus = Focus::Chats;
app.chats.refresh();
let ids = app.chats.ids().to_vec();
app.selected = Some(ids[1]);
press(&mut app, KeyCode::Char('a'), KeyModifiers::CONTROL);
assert!(app.toast.is_none() && app.selected == Some(ids[1]));
press(&mut app, KeyCode::Char('a'), KeyModifiers::NONE);
assert_eq!(app.selected, Some(ids[2]));
assert_eq!(
app.toast.as_ref().map(|t| t.title.as_str()),
Some("Archived")
);
let last = *ids.last().unwrap();
app.selected = Some(last);
press(&mut app, KeyCode::Char('a'), KeyModifiers::NONE);
assert_eq!(app.selected, Some(ids[ids.len() - 2]));
}
#[test]
fn tab_in_a_chats_search_finishes_filters_and_a_bad_one_says_why() {
let mut app = test_app("search-filters");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
let typed = |app: &App| app.prompt.as_ref().unwrap().query();
press(&mut app, KeyCode::Char('/'), none);
for c in "trail h".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "trail has:");
for c in "ph".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "trail has:photo");
for c in " from:".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "trail has:photo from:me");
for c in " has:video".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Enter, none);
assert_eq!(app.status.as_deref(), Some("Only one has: at a time"));
assert!(app.open.as_ref().unwrap().search.is_none(), "nothing asked");
}
#[test]
fn from_tab_offers_the_usernames_of_chats_in_the_list() {
let mut app = test_app("from-tab-chats");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
let (_, other) = two_chats(&app);
app.chats.add_local(other, "Hiking", None).peer = Some(Peer::Supergroup(9));
app.chats.set_username(
Peer::Supergroup(9),
Some(&tdlib_rs::types::Usernames {
active_usernames: vec!["hikingclub".into()],
..Default::default()
}),
);
press(&mut app, KeyCode::Char('/'), none);
for c in "from:@h".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Tab, none);
assert_eq!(app.prompt.as_ref().unwrap().query(), "from:@hikingclub");
}
#[test]
fn a_search_with_a_media_filter_opens_the_media_browser() {
let mut app = test_app("media-browser");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
press(&mut app, KeyCode::Char('/'), none);
for c in "has:file".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Enter, none);
let menu = app.media_menu.as_ref().expect("the browser opened");
assert_eq!(menu.query, "has:file");
assert!(menu.loading, "the first page was asked for");
assert!(app.open.as_ref().unwrap().search.is_none(), "no n/N search");
press(&mut app, KeyCode::Esc, none);
assert!(app.media_menu.is_none());
press(&mut app, KeyCode::Char('/'), none);
for c in "hello".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Enter, none);
assert!(app.media_menu.is_none());
assert!(app.open.as_ref().unwrap().search.is_some());
}
#[test]
fn a_failed_media_search_says_so_in_its_window() {
let mut app = test_app("media-error");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
press(&mut app, KeyCode::Char('/'), none);
for c in "has:file".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Enter, none);
assert!(app.media_menu.is_some());
let chat_id = app.open.as_ref().unwrap().chat_id;
app.on_tg(TgEvent::Found {
chat_id,
topic: None,
query: "has:file".into(),
found: Err("Nobody on Telegram is called @x".into()),
});
assert!(app.media_menu.is_some(), "the window stays");
let text = screen(&mut app).join("\n");
assert!(text.contains("Nobody on Telegram"), "says why: {text}");
}
#[test]
fn a_photo_search_shows_a_grid_of_previews() {
use ratatui_image::picker::ProtocolType;
let mut app = test_app("mediagrid");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
let mut picker = Picker::halfblocks();
picker.set_protocol_type(ProtocolType::Kitty);
app.images = Images::new(picker, unbounded_channel().0);
let row = |id: i64| crate::search::MediaRow {
id,
label: format!("photo {id}"),
sender: crate::messages::Sender::User(1),
outgoing: false,
date: 0,
file_id: None,
downloaded: false,
preview: Some(crate::messages::Preview {
file_id: id as i32,
width: 800,
height: 600,
thumbnail: None,
sticker: false,
}),
round: false,
};
let mut menu = crate::search::MediaMenu::new(
"has:photo".into(),
crate::search::parse("has:photo").unwrap(),
);
menu.rows = (1..=13).map(row).collect();
menu.done = true;
app.media_menu = Some(menu);
let shown = screen_tall(&mut app);
let at = |needle: &str| {
shown
.iter()
.enumerate()
.find_map(|(y, line)| line.find(needle).map(|x| (y, x)))
.unwrap_or_else(|| panic!("{needle} on screen: {}", shown.join("\n")))
};
let menu = app.media_menu.as_ref().unwrap();
assert_eq!(menu.grid_columns, 4);
let page = menu.grid_page;
assert_eq!(page % 4, 0, "whole rows: {page}");
let (one, five) = (at("photo 1"), at("photo 5"));
assert_eq!(one.0, at("photo 2").0, "a row across");
assert!(at("photo 2").1 > one.1, "newer on the left");
assert!(five.0 > one.0, "the next row under it");
let text = shown.join("\n");
assert!(text.contains("has:photo (13) · 1/2"), "title: {text}");
assert!(text.contains("· photo 1"), "the cursor's match: {text}");
press(&mut app, KeyCode::Char('j'), none);
assert_eq!(app.media_menu.as_ref().unwrap().selected, 4, "a row down");
press(&mut app, KeyCode::Char('h'), none);
assert_eq!(app.media_menu.as_ref().unwrap().selected, 3, "a cell left");
assert!(app.media_menu.is_some(), "h moves in the grid");
press(&mut app, KeyCode::Char('l'), none);
assert_eq!(app.media_menu.as_ref().unwrap().selected, 4, "l moves too");
press(&mut app, KeyCode::Char('d'), KeyModifiers::CONTROL);
let wanted = (4 + page).min(12);
assert_eq!(
app.media_menu.as_ref().unwrap().selected,
wanted,
"a page down"
);
let text = screen_tall(&mut app).join("\n");
assert!(text.contains("· 2/2"), "the second page: {text}");
press(&mut app, KeyCode::Char('-'), none);
assert_eq!(app.media_columns, 3);
for _ in 0..3 {
press(&mut app, KeyCode::Char('='), none);
}
assert_eq!(app.media_columns, 5, "no more than 5");
for _ in 0..3 {
press(&mut app, KeyCode::Char('-'), none);
}
assert_eq!(app.media_columns, 3, "no fewer than 3");
press(&mut app, KeyCode::Esc, none);
assert!(app.media_menu.is_none());
}
#[test]
fn other_media_searches_keep_the_list() {
use ratatui_image::picker::ProtocolType;
let mut app = test_app("medialist");
app.focus = Focus::Messages;
let mut picker = Picker::halfblocks();
picker.set_protocol_type(ProtocolType::Kitty);
app.images = Images::new(picker, unbounded_channel().0);
let row = |id: i64| crate::search::MediaRow {
id,
label: format!("photo {id}"),
sender: crate::messages::Sender::User(1),
outgoing: false,
date: 0,
file_id: Some(id as i32),
downloaded: true,
preview: Some(crate::messages::Preview {
file_id: id as i32,
width: 800,
height: 600,
thumbnail: None,
sticker: false,
}),
round: false,
};
let mut menu = crate::search::MediaMenu::new(
"has:file".into(),
crate::search::parse("has:file").unwrap(),
);
menu.rows = vec![row(1)];
app.media_menu = Some(menu);
let text = screen(&mut app).join("\n");
assert!(text.contains("✓ photo 1"), "a list row: {text}");
assert_eq!(
app.media_menu.as_ref().unwrap().grid_columns,
0,
"no grid drawn"
);
app.images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let mut menu = crate::search::MediaMenu::new(
"has:photo".into(),
crate::search::parse("has:photo").unwrap(),
);
menu.rows = vec![row(1)];
app.media_menu = Some(menu);
let text = screen(&mut app).join("\n");
assert!(text.contains("✓ photo 1"), "a list row: {text}");
assert_eq!(
app.media_menu.as_ref().unwrap().grid_columns,
0,
"no grid without photos"
);
}
#[test]
fn from_turns_me_a_name_or_a_known_username_into_a_sender() {
let mut app = test_app("search-from");
let resolve = |app: &App, typed: &str| {
let ask = search::parse(typed).unwrap();
app.resolve_sender(ask).map(|a| a.from)
};
let me = app.chats.my_id().unwrap();
assert_eq!(
resolve(&app, "from:me"),
Ok(Some(Who::Sender(Sender::User(me))))
);
let (id, name) = app
.open
.as_ref()
.unwrap()
.messages
.values()
.find_map(|m| match m.sender {
Sender::User(id) if id != me => Some((id, app.users.get(&id)?.clone())),
_ => None,
})
.expect("someone else wrote");
let first = name.split_whitespace().next().unwrap().to_lowercase();
let found = resolve(&app, &format!("from:{first}"));
assert_eq!(found, Ok(Some(Who::Sender(Sender::User(id)))));
assert!(
resolve(&app, "from:Zelda")
.unwrap_err()
.starts_with("Nobody called Zelda")
);
app.chats.set_username(
Peer::User(id),
Some(&tdlib_rs::types::Usernames {
active_usernames: vec!["maya".into()],
..Default::default()
}),
);
assert_eq!(
resolve(&app, "from:@Maya"),
Ok(Some(Who::Sender(Sender::User(id))))
);
assert_eq!(
resolve(&app, "from:@stranger"),
Ok(Some(Who::Username("stranger".into()))),
"TDLib looks it up"
);
}
#[test]
fn tab_completes_a_command_and_goes_on_to_the_next_that_fits() {
let mut app = test_app("command-tab");
let none = KeyModifiers::NONE;
let typed = |app: &App| app.prompt.as_ref().unwrap().query();
press(&mut app, KeyCode::Char(':'), none);
press(&mut app, KeyCode::Char('l'), none);
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "leave");
let rows = screen(&mut app).join("\n");
assert!(rows.contains("Commands · Tab completes"), "{rows}");
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "logout");
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "leave", "round the end");
press(&mut app, KeyCode::BackTab, none);
assert_eq!(typed(&app), "logout");
for _ in 0.."logout".len() - 2 {
press(&mut app, KeyCode::Backspace, none);
}
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "logout", "the only one with lo");
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "logout");
app.prompt = None;
press(&mut app, KeyCode::Char(':'), none);
press(&mut app, KeyCode::Char('x'), none);
press(&mut app, KeyCode::Tab, none);
assert_eq!(typed(&app), "x", "nothing fits");
assert!(app.prompt.is_some(), "and nothing ran");
}
#[test]
fn gp_lists_the_pinned_messages_and_enter_goes_to_one() {
let mut app = test_app("pinned");
app.focus = Focus::Messages;
let (none, ctrl) = (KeyModifiers::NONE, KeyModifiers::CONTROL);
let pinned = app.open.as_ref().unwrap().pinned[0].id;
let cursor = |app: &App| app.open.as_ref().unwrap().selected;
assert_eq!(cursor(&app), None, "on the newest");
press(&mut app, KeyCode::Char('g'), none);
press(&mut app, KeyCode::Char('p'), none);
assert!(app.pinned_menu.is_some(), "not a paste");
assert!(
screen(&mut app)
.join("\n")
.contains(" Pinned messages (1) ")
);
press(&mut app, KeyCode::Enter, none);
assert!(app.pinned_menu.is_none());
assert_eq!(cursor(&app), Some(pinned));
press(&mut app, KeyCode::Char('o'), ctrl);
assert_eq!(cursor(&app), None, "Ctrl-o comes back");
app.open.as_mut().unwrap().pinned.clear();
press(&mut app, KeyCode::Char('g'), none);
press(&mut app, KeyCode::Char('p'), none);
assert!(app.pinned_menu.is_none());
assert_eq!(
app.status.as_deref(),
Some("No pinned messages in this chat")
);
}
#[test]
fn the_pin_popup_fills_in_once_tdlib_says_and_old_lists_are_dropped() {
let mut app = test_app("pin");
let chat_id = app.open.as_ref().unwrap().chat_id;
let menu = |id| PinMenu::new(id, "hi".into(), Place::Group, String::new());
let pinnable = |message_id, pinnable| TgEvent::Pinnable {
chat_id,
message_id,
pinnable: Some(pinnable),
};
app.pin_menu = Some(menu(4));
app.on_tg(pinnable(5, true));
assert!(
app.pin_menu.as_ref().unwrap().choices.is_empty(),
"another message"
);
app.on_tg(pinnable(4, true));
assert_eq!(app.pin_menu.as_ref().unwrap().choices.len(), 2);
app.pin_menu = Some(menu(4));
app.on_tg(pinnable(4, false));
assert!(app.pin_menu.is_none());
assert_eq!(app.status.as_deref(), Some("You can't pin messages here"));
app.open.as_mut().unwrap().pinned_asked = 2;
app.on_tg(TgEvent::Pinned {
chat_id,
topic: None,
request: 1,
messages: Some(Vec::new()),
});
assert_eq!(app.open.as_ref().unwrap().pinned.len(), 1);
app.on_tg(TgEvent::Pinned {
chat_id,
topic: None,
request: 2,
messages: Some(Vec::new()),
});
assert!(app.open.as_ref().unwrap().pinned.is_empty());
}
#[test]
fn enter_on_a_bots_message_lists_its_buttons_then_its_links() {
use crate::buttons::{Button, Keyboard};
let mut app = test_app("buttons");
app.focus = Focus::Messages;
let id = plain_message(&mut app);
let none = KeyModifiers::NONE;
let msg = app.open.as_mut().unwrap().messages.get_mut(&id).unwrap();
msg.links = vec![Link::from("https://example.com/menu")];
msg.keyboard = Some(Keyboard {
rows: vec![vec![
Button {
label: "Play".into(),
press: Press::Unsupported("Games only run in Telegram's own apps"),
},
Button {
label: "Our site".into(),
press: Press::Open(Link {
url: "https://shop.example/".into(),
disguise: Some("Our site".into()),
}),
},
]],
reply: false,
});
press(&mut app, KeyCode::Enter, none);
let menu = app.button_menu.as_ref().expect("the buttons");
assert_eq!(menu.rows.len(), 2, "and the message's link");
let rows = screen(&mut app).join("\n");
assert!(rows.contains(" Buttons "), "{rows}");
assert!(rows.contains("Open link: example.com"), "{rows}");
assert!(
rows.contains("Games only run in Telegram's own apps"),
"what Enter does"
);
press(&mut app, KeyCode::Enter, none);
assert_eq!(app.status, None);
let ago = Instant::now() - CONFIRM_GRACE;
app.button_menu.as_mut().unwrap().shown = ago;
press(&mut app, KeyCode::Enter, none);
assert_eq!(
app.status.as_deref(),
Some("Games only run in Telegram's own apps")
);
assert!(app.button_menu.is_some(), "stays up");
press(&mut app, KeyCode::Char('l'), none);
press(&mut app, KeyCode::Enter, none);
assert!(app.button_menu.is_none());
let confirm = app.confirm.as_ref().expect("its words aren't its address");
assert!(matches!(&confirm.action, Confirmed::OpenLink(u) if u == "https://shop.example/"));
app.confirm = None;
press(&mut app, KeyCode::Enter, none);
app.button_menu.as_mut().unwrap().shown = ago;
press(&mut app, KeyCode::Char('2'), none);
assert!(app.confirm.is_none() && app.button_menu.is_some());
}
#[test]
fn logout_asks_first_now_that_tab_can_put_it_in() {
let mut app = test_app("logout");
let none = KeyModifiers::NONE;
press(&mut app, KeyCode::Char(':'), none);
press(&mut app, KeyCode::Char('l'), none);
press(&mut app, KeyCode::Char('o'), none);
press(&mut app, KeyCode::Tab, none);
assert_eq!(app.prompt.as_ref().unwrap().query(), "logout");
press(&mut app, KeyCode::Enter, none);
let confirm = app.confirm.as_ref().expect("asks");
assert!(matches!(confirm.action, Confirmed::Logout));
assert!(matches!(app.screen, Screen::Main), "still logged in");
press(&mut app, KeyCode::Char('n'), none);
assert!(app.confirm.is_none() && matches!(app.screen, Screen::Main));
}
#[test]
fn nothing_is_marked_read_while_a_jump_to_an_older_message_loads() {
let mut app = test_app("jump-read");
app.focus = Focus::Messages;
let chat = app.open.as_ref().unwrap().chat_id;
assert!(app.watching(chat));
app.open.as_mut().unwrap().loading = Some(Page::Around(3));
assert!(!app.watching(chat));
}
#[test]
fn a_bots_answer_is_a_note_or_an_alert_and_its_link_asks_first() {
let mut app = test_app("bot-answer");
app.focus = Focus::Messages;
let chat_id = app.open.as_ref().unwrap().chat_id;
let answer = |text: &str, alert, url: &str| TgEvent::BotAnswer {
chat_id,
topic: None,
label: "Buy".into(),
text: text.into(),
alert,
url: url.into(),
};
app.on_tg(answer("Added\nto cart", false, ""));
let toast = app.toast.as_ref().expect("a note in the corner");
assert_eq!(
(toast.title.as_str(), toast.detail.as_str()),
("Buy", "Added to cart")
);
app.on_tg(answer("Sold \u{202e}out", true, ""));
assert_eq!(app.notice.as_ref().unwrap().text, "Sold out");
assert!(screen(&mut app).join("\n").contains("Sold out"));
press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE);
assert!(app.notice.is_some(), "only Enter or Esc closes it");
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.notice.is_none());
app.on_tg(answer("", false, "https://game.example/play"));
let confirm = app.confirm.take().expect("asks before opening");
assert!(
matches!(confirm.action, Confirmed::OpenLink(u) if u == "https://game.example/play")
);
app.focus = Focus::Input;
app.on_tg(answer("Sold out", true, "https://game.example/play"));
assert!(app.notice.is_none() && app.confirm.is_none());
assert_eq!(app.toast.as_ref().unwrap().detail, "Sold out");
}
#[test]
fn f_opens_a_list_of_your_chats_to_forward_to_saved_messages_first() {
let mut app = test_app("forward");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
press(&mut app, KeyCode::Char('f'), none);
let picker = app.picker.as_ref().expect("the picker is open");
let Purpose::Forward {
from, message_ids, ..
} = &picker.purpose
else {
panic!("forwarding");
};
let open = app.open.as_ref().unwrap();
assert_eq!(*from, open.chat_id);
assert_eq!(message_ids, &[open.cursor_id().unwrap()]);
assert!(
matches!(picker.choices(&app.chats)[0], Choice::Chat(id) if app.chats.is_saved(id)),
"Saved Messages first"
);
let rows = screen(&mut app);
assert!(rows.iter().any(|r| r.contains("Forward to")), "{rows:#?}");
assert!(rows.iter().any(|r| r.contains("Saved Messages")));
for c in "tokyo".chars() {
press(&mut app, KeyCode::Char(c), none);
}
let picker = app.picker.as_ref().unwrap();
assert_eq!(picker.query, "tokyo");
let titles: Vec<&str> = picker
.choices(&app.chats)
.iter()
.map(|c| match c {
Choice::Chat(id) => app.chats.title(*id).unwrap(),
_ => "",
})
.collect();
assert_eq!(titles, ["Tokyo Trip"]);
press(&mut app, KeyCode::Esc, none);
assert!(app.picker.is_none());
}
#[test]
fn s_finds_a_chat_by_username_or_link_and_pastes_go_into_its_search() {
let mut app = test_app("find");
let none = KeyModifiers::NONE;
press(&mut app, KeyCode::Char('s'), none);
assert!(app.picker.as_ref().is_some_and(|p| !p.forwarding()));
for c in "@durov".chars() {
press(&mut app, KeyCode::Char(c), none);
}
let rows = screen(&mut app);
assert!(rows.iter().any(|r| r.contains("Open @durov")), "{rows:#?}");
press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL);
app.on_terminal_event(Event::Paste("t.me/+AbCdEf\n".into()));
let picker = app.picker.as_ref().unwrap();
assert_eq!(picker.query, "t.me/+AbCdEf", "not attached as a file");
assert_eq!(
picker.choices(&app.chats)[0],
Choice::Link("https://t.me/+AbCdEf".into())
);
assert!(picker.search_at().is_none(), "links aren't searched for");
press(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL);
assert!(app.picker.is_none(), "Ctrl-c closes it");
assert!(app.quit_deadline.is_none(), "without quitting");
}
#[test]
fn ctrl_u_deletes_back_to_the_start_of_the_line_and_then_the_line_break() {
let mut app = test_app("ctrl-u");
let chat_id = app.open.as_ref().unwrap().chat_id;
app.focus = Focus::Input;
app.typing = Some(((chat_id, None), Instant::now()));
app.composer.insert_str("first line");
app.composer.insert_newline();
app.composer.insert_str("second line");
app.composer
.move_cursor(ratatui_textarea::CursorMove::WordBack);
press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL);
assert_eq!(app.composer.lines(), ["first line", "line"]);
press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL);
assert_eq!(app.composer.lines(), ["first lineline"]);
assert!(app.focus == Focus::Input);
}
#[test]
fn long_lines_in_the_composer_wrap_and_it_grows_with_them_unless_turned_off() {
let mut app = test_app("wrap");
app.focus = Focus::Input;
app.composer
.insert_str("zebra crossing ".repeat(12).trim_end());
let count = |screen: &[String]| -> usize {
screen.iter().map(|r| r.matches("zebra").count()).sum()
};
let rows = |screen: &[String]| screen.iter().filter(|r| r.contains("zebra")).count();
assert!(app.settings.wrap_composer, "on unless turned off");
let wrapped = screen(&mut app);
assert_eq!(count(&wrapped), 12, "all of it shows: {wrapped:#?}");
assert!(rows(&wrapped) >= 3, "{wrapped:#?}");
let last = wrapped.iter().rposition(|r| r.contains("zebra")).unwrap();
assert!(
wrapped[last + 1].contains(['╰', '└']),
"no blank row under the text: {wrapped:#?}"
);
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('?'), KeyModifiers::NONE);
press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
app.settings_menu.as_mut().unwrap().selected = SettingsMenu::WRAP_COMPOSER;
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(!app.settings.wrap_composer);
assert!(
!Settings::load(&app.settings_path).unwrap().wrap_composer,
"saved"
);
app.settings_menu = None;
app.focus = Focus::Input;
let one_row = screen(&mut app);
assert_eq!(rows(&one_row), 1, "{one_row:#?}");
assert!(count(&one_row) < 12, "{one_row:#?}");
}
#[test]
fn a_chat_found_while_you_write_does_not_open_over_what_you_type() {
let mut app = test_app("late-find");
let chat_id = app.open.as_ref().unwrap().chat_id;
app.focus = Focus::Input;
app.composer.insert_str("see you at 5");
app.finding = Some(Finding::new("@bob"));
app.on_tg(TgEvent::ChatFound {
request: "@bob".into(),
found: Ok(Spot::chat(999)),
});
assert_eq!(app.open.as_ref().unwrap().chat_id, chat_id);
assert!(app.focus == Focus::Input);
assert_eq!(app.composer.lines(), ["see you at 5"]);
assert!(app.finding.is_none());
assert_eq!(
app.status.as_deref(),
Some("Found @bob: press s to open it")
);
app.finding = Some(Finding::new("https://t.me/+x"));
let invite = Invite {
title: "Group".into(),
members: 3,
channel: false,
badge: None,
by_request: false,
};
app.on_tg(TgEvent::Invite {
request: "https://t.me/+x".into(),
link: "https://t.me/+x".into(),
invite,
});
assert!(app.confirm.is_none());
}
#[test]
fn writing_a_popup_or_esc_stops_a_lookup() {
let mut app = test_app("stop-find");
app.focus = Focus::Messages;
app.finding = Some(Finding::new("@bob"));
press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
assert!(app.finding.is_none());
assert!(app.focus == Focus::Messages, "only the lookup stopped");
app.finding = Some(Finding::new("@bob"));
press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE);
assert!(app.finding.is_none(), "writing in this chat instead");
}
#[test]
fn e_edits_your_message_as_markdown_and_an_untouched_edit_sends_nothing() {
let mut app = test_app("edit-markdown");
app.focus = Focus::Messages;
let open = app.open.as_ref().unwrap();
let (chat_id, id) = (open.chat_id, open.edit_target().unwrap());
let text = EditText {
markdown: "On my **way**!".into(),
loses: false,
};
app.on_editable(chat_id, id, Some(true), Some(text));
assert!(app.focus == Focus::Input);
assert_eq!(app.composer.lines(), ["On my **way**!"]);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.open.as_ref().unwrap().editing.is_none());
app.focus = Focus::Messages;
let text = EditText {
markdown: "On my way!".into(),
loses: true,
};
app.on_editable(chat_id, id, Some(true), Some(text));
let confirm = app.confirm.as_ref().expect("asks");
assert!(matches!(&confirm.action, Confirmed::Edit { text, .. } if text == "On my way!"));
}
#[test]
fn at_and_colon_suggest_people_and_emoji_and_tab_puts_one_in() {
let mut app = test_app("complete");
let chat_id = app.open.as_ref().unwrap().chat_id;
app.focus = Focus::Input;
app.typing = Some(((chat_id, None), Instant::now()));
app.composer.insert_str("hi @ma");
app.update_completion();
let completion = app.completion.as_ref().expect("suggestions");
let labels: Vec<&str> = completion.items.iter().map(|s| s.label.as_str()).collect();
assert_eq!(labels, ["Maya Chen"], "senders of the loaded messages");
assert!(
completion.search_at().is_some(),
"members are searched once typing pauses"
);
press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
assert_eq!(app.composer.lines(), ["hi [Maya Chen](tg://user?id=2) "]);
assert!(
app.stickers.is_none(),
"Tab took the suggestion, not the stickers"
);
app.composer.insert_str(":tada");
app.update_completion();
assert_eq!(app.completion.as_ref().unwrap().items[0].label, "🎉");
press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
assert_eq!(app.composer.lines(), ["hi [Maya Chen](tg://user?id=2) 🎉"]);
assert!(app.completion.is_none());
app.composer.insert_str(" @sam");
app.update_completion();
assert!(
app.completion.as_ref().is_none_or(|c| c.items.is_empty()),
"not yourself"
);
}
#[test]
fn slash_starting_a_message_suggests_the_bots_commands() {
let mut app = test_app("commands");
let chat_id = app.open.as_ref().unwrap().chat_id;
app.focus = Focus::Input;
app.typing = Some(((chat_id, None), Instant::now()));
let command = |name: &str| complete::Command {
bot: 9,
name: name.into(),
description: format!("{name} the bot"),
};
app.open.as_mut().unwrap().commands =
Commands::Known(vec![command("start"), command("help")]);
app.composer.insert_str("/he");
app.update_completion();
let completion = app.completion.as_ref().expect("suggestions");
assert_eq!(completion.items[0].label, "/help");
assert_eq!(completion.items[0].detail, "help the bot");
press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
assert_eq!(app.composer.lines(), ["/help "]);
app.composer.insert_str("see /st");
app.update_completion();
assert!(app.completion.is_none(), "only at the start of a message");
}
#[test]
fn proxy_asks_then_sets_the_proxy_now_and_for_next_time_and_says_what_is_wrong() {
let dir = std::env::temp_dir().join(format!("tuigram-proxy-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
let tg = Tg::detached(unbounded_channel().0);
let mut app = crate::demo::demo_app(tg, images, &dir);
let none = KeyModifiers::NONE;
let saved = || Settings::load(&settings::path(&dir)).unwrap().proxy;
let type_in = |app: &mut App, text: &str| {
app.prompt.as_mut().unwrap().input = prompt_input("");
for c in text.chars() {
press(app, KeyCode::Char(c), none);
}
press(app, KeyCode::Enter, none);
};
let answer = |app: &mut App| {
press(app, KeyCode::Char('y'), none);
let confirm = app.confirm.as_mut().expect("still asking");
confirm.shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(app, KeyCode::Char('y'), none);
assert!(app.confirm.is_none());
};
let answers = |app: &mut App, result: Result<(), String>| {
let number = *app.proxy_changes.keys().next_back().expect("one asked");
app.on_tg(TgEvent::ProxyApplied { number, result });
};
command(&mut app, "proxy");
assert!(
app.prompt
.as_ref()
.is_some_and(|p| p.kind == PromptKind::Proxy)
);
type_in(&mut app, "socks5://10.0.0.1:1080");
let confirm = app.confirm.as_ref().expect("asks first");
assert_eq!(confirm.lines[0], "Proxy: SOCKS5");
assert_eq!(confirm.site.as_ref().unwrap().host, "10.0.0.1:1080");
assert!(!confirm.lines.iter().any(|l| l.contains("proxy sponsor")));
assert_eq!(saved(), None, "not before `y`");
answer(&mut app);
assert_eq!(saved(), None, "not before TDLib takes it");
assert!(app.toast.is_none());
let status = app.status.as_deref().unwrap();
assert_eq!(status, "Switching to SOCKS5 proxy 10.0.0.1:1080…");
answers(&mut app, Ok(()));
assert_eq!(saved().as_deref(), Some("socks5://10.0.0.1:1080"));
assert!(app.status.is_none());
let toast = app.toast.as_ref().unwrap();
assert_eq!(
(toast.title.as_str(), toast.detail.as_str()),
("Connecting through", "SOCKS5 proxy 10.0.0.1:1080")
);
command(&mut app, "proxy");
let prompt = app.prompt.as_ref().unwrap();
assert_eq!(prompt.query(), "socks5://10.0.0.1:1080");
type_in(&mut app, "socks5://10.0.0.1");
assert!(app.confirm.is_none());
assert!(app.status.as_deref().unwrap().contains("no port"));
assert_eq!(saved().as_deref(), Some("socks5://10.0.0.1:1080"));
command(&mut app, "proxy");
type_in(&mut app, "");
let confirm = app.confirm.as_ref().expect("asks first");
assert_eq!(confirm.title, "Connect directly?");
assert!(confirm.lines[0].contains("SOCKS5 proxy 10.0.0.1:1080"));
assert_eq!(saved().as_deref(), Some("socks5://10.0.0.1:1080"));
answer(&mut app);
answers(&mut app, Ok(()));
assert_eq!(saved(), None);
assert_eq!(app.toast.as_ref().unwrap().title, "No proxy");
command(&mut app, "proxy");
type_in(&mut app, "");
assert!(app.confirm.is_none());
assert!(app.status.as_deref().unwrap().contains("directly"));
}
#[test]
fn a_proxy_is_saved_only_once_tdlib_takes_it_and_one_it_refuses_changes_nothing() {
let mut app = test_app("proxy-answers");
app.settings.proxy = None;
let link = |port| format!("socks5://10.0.0.1:{port}");
let answer = |app: &mut App, number, result| {
app.on_tg(TgEvent::ProxyApplied { number, result });
};
app.set_proxy(&link(1080));
let refused = *app.proxy_changes.keys().next_back().unwrap();
answer(&mut app, refused, Err("Wrong port".into()));
assert_eq!(app.settings.proxy, None);
assert!(app.toast.is_none());
let status = app.status.clone().unwrap();
assert_eq!(status, "The proxy wasn't changed: Wrong port");
app.set_proxy(&link(1081));
let first = *app.proxy_changes.keys().next_back().unwrap();
app.set_proxy(&link(1082));
let second = *app.proxy_changes.keys().next_back().unwrap();
answer(&mut app, first, Ok(()));
assert_eq!(app.settings.proxy, Some(link(1081)));
answer(&mut app, second, Err("refused".into()));
assert_eq!(app.settings.proxy, Some(link(1081)), "what TDLib uses");
app.set_proxy(&link(1083));
app.set_proxy(&link(1084));
let last = *app.proxy_changes.keys().next_back().unwrap();
answer(&mut app, last, Ok(()));
assert_eq!(app.settings.proxy, Some(link(1084)));
assert!(
app.proxy_changes.is_empty(),
"the skipped one isn't waited for"
);
app.settings.proxy = Some(link(1084));
let keys = ApiKeys {
id: 1,
hash: "0123456789abcdef0123456789abcdef".into(),
};
app.screen = login_screen(LoginStep::Connecting);
app.start_tdlib(keys.clone());
let start = *app.proxy_changes.keys().next_back().unwrap();
answer(&mut app, start, Err("Unsupported proxy secret".into()));
let Screen::Login(login) = &app.screen else {
panic!("still logging in");
};
assert!(
matches!(&login.step, LoginStep::BadProxy { why, .. } if why == "Unsupported proxy secret")
);
assert_eq!(
app.settings.proxy,
Some(link(1084)),
"startup saves nothing"
);
app.screen = Screen::Main;
app.start_tdlib(keys);
let start = *app.proxy_changes.keys().next_back().unwrap();
answer(&mut app, start, Err("Unsupported proxy secret".into()));
app.on_auth_state(AuthorizationState::Ready);
let Screen::Login(login) = &app.screen else {
panic!("the main screen is gone");
};
assert!(matches!(login.step, LoginStep::BadProxy { .. }));
let rows = screen(&mut app).concat();
assert!(
rows.contains("Can't use the proxy in settings.toml"),
"{rows}"
);
}
#[test]
fn proxy_hides_the_saved_password_and_keeps_it_only_for_the_same_server() {
let mut app = test_app("proxy-masked");
let saved = "socks5://me:hunter2@10.0.0.1:1080";
app.settings.proxy = Some(saved.into());
let type_in = |app: &mut App, text: &str| {
app.prompt.as_mut().unwrap().input = prompt_input(text);
press(app, KeyCode::Enter, KeyModifiers::NONE);
};
command(&mut app, "proxy");
let shown = app.prompt.as_ref().unwrap().query();
assert_eq!(shown, "socks5://me:•••@10.0.0.1:1080");
assert!(!screen(&mut app).concat().contains("hunter2"));
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let confirm = app.confirm.take().expect("asks first");
assert!(matches!(&confirm.action, Confirmed::UseProxy(link) if link == saved));
command(&mut app, "proxy");
type_in(&mut app, "socks5://me:•••@203.0.113.9:1080");
assert!(app.confirm.is_none());
assert!(app.status.as_deref().unwrap().contains("write it out"));
}
#[test]
fn a_proxy_set_that_cant_be_used_keeps_tdlib_from_starting_and_says_why() {
let bad_proxy = |app: &App| match &app.screen {
Screen::Login(login) => match &login.step {
LoginStep::BadProxy { from, why } => Some((*from, why.clone())),
_ => None,
},
Screen::Main => None,
};
let keys = ApiKeys {
id: 1,
hash: "0123456789abcdef0123456789abcdef".into(),
};
let mut app = test_app("proxy-unusable");
app.settings.api_keys = Some(keys.clone());
app.settings.proxy = Some("socks5://10.0.0.1".into());
app.screen = login_screen(LoginStep::Connecting);
app.on_auth_state(AuthorizationState::WaitTdlibParameters);
let (from, why) = bad_proxy(&app).expect("TDLib isn't started");
assert_eq!(from, "the proxy in settings.toml");
assert!(why.contains("no port"), "{why}");
let said = |app: &mut App| {
let rows = screen(app);
let words: Vec<&str> = rows
.iter()
.flat_map(|r| r.split_whitespace())
.filter(|w| w != &"│")
.collect();
words.join(" ")
};
let rows = said(&mut app);
assert!(
rows.contains("Can't use the proxy in settings.toml"),
"{rows}"
);
assert!(rows.contains("The link has no port"), "{rows}");
assert!(rows.contains("start tuigram again"), "{rows}");
app.on_auth_state(AuthorizationState::WaitPhoneNumber);
assert!(bad_proxy(&app).is_some());
assert!(said(&mut app).contains("The link has no port"));
press(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL);
assert!(app.quit_deadline.is_some());
let mut app = test_app("proxy-unusable-typed-key");
app.settings.api_keys = None;
app.settings.proxy = Some("ftp://10.0.0.1:21".into());
app.screen = login_screen(LoginStep::ApiHash { id: 1 });
for c in keys.hash.chars() {
press(&mut app, KeyCode::Char(c), KeyModifiers::NONE);
}
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let (_, why) = bad_proxy(&app).expect("TDLib isn't started");
assert!(why.starts_with("Not a proxy link"), "{why}");
let mut app = test_app("proxy-usable");
app.settings.api_keys = Some(keys);
app.settings.proxy = Some("socks5://10.0.0.1:1080".into());
app.screen = login_screen(LoginStep::Connecting);
app.on_auth_state(AuthorizationState::WaitTdlibParameters);
assert!(bad_proxy(&app).is_none());
}
#[test]
fn a_paste_arriving_as_keys_cannot_set_a_proxy_without_a_y() {
let mut app = test_app("paste-proxy");
app.focus = Focus::Messages;
assert!(app.settings.proxy.is_none());
let key = |app: &mut App, code: KeyCode| {
let modifiers = match code {
KeyCode::Char(c) if !c.is_alphanumeric() => KeyModifiers::SHIFT,
_ => KeyModifiers::NONE,
};
app.on_terminal_event(Event::Key(KeyEvent::new(code, modifiers)));
};
let pasted = ":proxy\nsocks5://192.0.2.1:1080\ny";
for c in pasted.chars() {
key(
&mut app,
if c == '\n' {
KeyCode::Enter
} else {
KeyCode::Char(c)
},
);
}
let confirm = app.confirm.as_ref().expect("asks first");
assert_eq!(confirm.site.as_ref().unwrap().host, "192.0.2.1:1080");
assert!(app.settings.proxy.is_none(), "the pasted `y` came too soon");
assert!(app.toast.is_none());
let mut app = test_app("paste-proxy-bracketed");
app.focus = Focus::Messages;
app.on_terminal_event(Event::Paste(":proxy\r\nsocks5://192.0.2.1:1080\r\n".into()));
assert!(app.settings.proxy.is_none());
assert!(app.prompt.is_none() && app.confirm.is_none());
}
#[test]
fn a_proxy_link_names_the_end_of_a_long_server_and_says_what_it_sees() {
let mut app = test_app("proxy-long-host");
let server = "proxy.my-vpn-provider.com.cdn-relay-node-77.attacker.example";
let url = format!(
"https://t.me/proxy?server={server}&port=443&secret=ee0123456789abcdef0123456789abcdef6578616d706c652e636f6d"
);
app.open_target(Target::Link(Link {
url,
disguise: Some("MyVPN proxy".into()),
}));
assert!(app.confirm.is_some(), "asks first");
let rows = screen_of(&mut app, 80);
let server = rows.iter().find(|r| r.contains("Server:")).unwrap();
assert!(server.contains("attacker.example:443"), "{rows:#?}");
let top = rows
.iter()
.position(|r| r.contains("Use this proxy?"))
.unwrap();
let bottom = rows.iter().position(|r| r.contains("y use it ·")).unwrap();
let said = rows[top + 1..bottom]
.iter()
.filter_map(|r| r.split_once("││"))
.flat_map(|(_, inside)| inside.trim_end_matches('│').split_whitespace())
.collect::<Vec<_>>()
.join(" ");
assert!(
said.contains("It sees your IP address and when you use Telegram, not your messages."),
"{rows:#?}"
);
assert!(said.contains("MTProto"), "{rows:#?}");
}
#[test]
fn a_chat_an_mtproto_proxy_sponsors_is_marked_in_the_list() {
let mut app = test_app("proxy-sponsor");
app.focus = Focus::Chats;
let (_, chat_id) = two_chats(&app);
let title = app.chats.title(chat_id).unwrap().to_string();
let position = tdlib_rs::types::ChatPosition {
list: tdlib_rs::enums::ChatList::Main,
order: 9_000_000,
is_pinned: false,
source: Some(tdlib_rs::enums::ChatSource::MtprotoProxy),
};
app.on_update(Update::ChatPosition(tdlib_rs::types::UpdateChatPosition {
chat_id,
position,
}));
let rows = screen(&mut app);
let marked: Vec<&String> = rows
.iter()
.filter(|r| r.contains("proxy sponsor"))
.collect();
assert_eq!(marked.len(), 1, "{rows:#?}");
let first_word = title.split(' ').next().unwrap();
assert!(marked[0].contains(first_word), "{rows:#?}");
}
#[test]
fn a_proxy_link_in_a_message_asks_first_naming_the_proxy() {
let mut app = test_app("proxy-link");
let url = "https://t.me/proxy?server=1.2.3.4&port=443&secret=ee0123456789abcdef0123456789abcdef6578616d706c652e636f6d";
app.open_target(Target::Link(Link {
url: url.into(),
disguise: Some("free fast proxy".into()),
}));
assert!(app.finding.is_none(), "not looked up as a chat");
let confirm = app.confirm.as_ref().expect("asks first");
assert_eq!(confirm.lines[0], "Proxy: MTProto");
assert_eq!(confirm.site.as_ref().unwrap().host, "1.2.3.4:443");
assert!(
confirm
.lines
.iter()
.any(|l| l.contains("\"proxy sponsor\"")),
"it can put a channel in the list"
);
assert!(matches!(&confirm.action, Confirmed::UseProxy(u) if u == url));
let rows = screen(&mut app);
assert!(rows[19].contains("y use it"), "{:?}", rows[19]);
app.confirm = None;
app.open_target(Target::Link(Link {
url: "https://t.me/proxy?server=1.2.3.4&port=443".into(),
disguise: None,
}));
assert!(app.confirm.is_none());
assert_eq!(app.status.as_deref(), Some("The link has no secret"));
}
#[test]
fn a_telegram_link_tuigram_cant_open_goes_to_the_browser_with_its_warning() {
let mut app = test_app("link-elsewhere");
let url = "https://t.me/addstickers/cats";
app.finding = Some(Finding {
request: url.into(),
link: Some(Link {
url: url.into(),
disguise: Some("cute cats".into()),
}),
});
app.on_tg(TgEvent::ChatFound {
request: url.into(),
found: Err(Missed::Elsewhere),
});
let confirm = app.confirm.as_ref().expect("the disguised link asks first");
assert!(matches!(&confirm.action, Confirmed::OpenLink(u) if u == url));
app.confirm = None;
app.finding = Some(Finding::new(url));
app.on_tg(TgEvent::ChatFound {
request: url.into(),
found: Err(Missed::Elsewhere),
});
assert!(app.confirm.is_none());
assert_eq!(
app.status.as_deref(),
Some("tuigram can't open this kind of link")
);
}
#[test]
fn enter_on_a_poll_opens_its_answers_unless_it_is_closed() {
let mut app = test_app("poll");
app.focus = Focus::Messages;
let open = app.open.as_mut().unwrap();
let id = open.cursor_id().unwrap();
let mut poll = crate::poll::Poll {
question: "Lunch?".into(),
answers: vec![crate::poll::Answer {
text: "Pizza".into(),
voters: 0,
percent: 0,
chosen: false,
}],
voters: 0,
several: false,
quiz: false,
correct: None,
anonymous: true,
closed: false,
};
open.messages.get_mut(&id).unwrap().poll = Some(poll.clone());
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let menu = app.vote_menu.as_ref().expect("the vote popup");
assert_eq!(menu.answers, ["Pizza"]);
let rows = screen(&mut app);
assert!(rows.iter().any(|r| r.contains("Vote")), "{rows:#?}");
press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
assert!(app.vote_menu.is_none());
poll.closed = true;
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().poll = Some(poll);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.vote_menu.is_none());
assert_eq!(app.status.as_deref(), Some("This poll is closed"));
}
#[test]
fn leave_asks_first_and_only_for_groups_and_channels() {
let mut app = test_app("leave");
let none = KeyModifiers::NONE;
let leave = |app: &mut App| {
press(app, KeyCode::Char(':'), none);
for c in "leave".chars() {
press(app, KeyCode::Char(c), none);
}
press(app, KeyCode::Enter, none);
};
app.focus = Focus::Messages;
leave(&mut app);
let confirm = app.confirm.as_ref().expect("asks");
let chat_id = app.open.as_ref().unwrap().chat_id;
assert!(matches!(confirm.action, Confirmed::Leave(id) if id == chat_id));
assert_eq!(confirm.title, "Leave this group?");
press(&mut app, KeyCode::Esc, none);
app.focus = Focus::Chats;
let mom = app
.chats
.ids()
.iter()
.copied()
.find(|&id| app.chats.title(id) == Some("Mom"))
.unwrap();
app.selected = Some(mom);
leave(&mut app);
assert!(app.confirm.is_none());
assert_eq!(
app.status.as_deref(),
Some("A chat with one person can't be left")
);
}
#[test]
fn r_asks_first_and_y_reads_the_chat_up_to_its_newest_message() {
let mut app = test_app("mark-read");
let none = KeyModifiers::NONE;
let chat_id = 7131;
let chat = app.chats.add_local(chat_id, "Catch up", None);
chat.unread = 5;
chat.last_message = 42;
app.open_chat(chat_id);
app.focus = Focus::Chats;
app.selected = Some(chat_id);
press(&mut app, KeyCode::Char('R'), none);
let confirm = app.confirm.as_ref().expect("asks first");
assert_eq!(confirm.title, "Mark all messages as read?");
assert!(matches!(
confirm.action,
Confirmed::ReadChat {
chat_id: id,
topic: None
} if id == chat_id
));
assert!(confirm.lines.iter().any(|l| l == "Catch up"));
press(&mut app, KeyCode::Char('y'), none);
assert!(app.confirm.is_some(), "still up, it just came");
app.confirm.as_mut().unwrap().shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), none);
assert!(app.confirm.is_none(), "read");
assert_eq!(app.open.as_ref().unwrap().seen, 42);
}
#[test]
fn r_when_there_is_nothing_to_read_says_so_without_asking() {
let mut app = test_app("mark-read-nothing");
let none = KeyModifiers::NONE;
let chat_id = 7132;
let chat = app.chats.add_local(chat_id, "Done", None);
chat.last_message = 9;
app.focus = Focus::Chats;
app.selected = Some(chat_id);
press(&mut app, KeyCode::Char('R'), none);
assert!(app.confirm.is_none());
assert_eq!(app.status.as_deref(), Some("Nothing unread in it"));
app.chats.add_local(chat_id, "Done", None).unread = 3;
press(&mut app, KeyCode::Char('R'), none);
assert!(app.confirm.is_none());
assert_eq!(
app.status.as_deref(),
Some("Its messages aren't loaded yet")
);
let forum_id = app
.chats
.ids()
.iter()
.copied()
.find(|&id| app.chats.is_forum(id))
.unwrap();
app.selected = Some(forum_id);
press(&mut app, KeyCode::Char('R'), none);
let confirm = app.confirm.as_ref().expect("a forum asks too");
assert!(matches!(
confirm.action,
Confirmed::ReadForum { chat_id } if chat_id == forum_id
));
app.confirm.as_mut().unwrap().shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), none);
assert!(app.confirm.is_none(), "the ask is spent");
assert_eq!(
app.read_forum
.as_ref()
.map(|r| (r.chat_id, r.page.is_some())),
Some((forum_id, true)),
"its topics are asked for"
);
let second = 7133;
app.chats.add_local(second, "Other forum", None).peer = Some(Peer::Supergroup(33));
app.chats.set_forum(33, true);
app.selected = Some(second);
press(&mut app, KeyCode::Char('R'), none);
assert!(app.confirm.is_none());
let status = app.status.as_deref().unwrap_or_default();
assert!(
status.starts_with("Still reading the topics of "),
"{status}"
);
assert_eq!(app.read_forum.as_ref().map(|r| r.chat_id), Some(forum_id));
}
#[test]
fn a_forum_read_asks_for_the_topics_a_page_left_blank() {
let mut app = test_app("mark-read");
let none = KeyModifiers::NONE;
let forum_id = app
.chats
.ids()
.iter()
.copied()
.find(|&id| app.chats.is_forum(id))
.unwrap();
app.selected = Some(forum_id);
press(&mut app, KeyCode::Char('R'), none);
app.confirm.as_mut().unwrap().shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), none);
let asked = app.read_forum.as_ref().unwrap().page.unwrap().0;
let topics = vec![
topic(11, "First", 3, 2),
topic(12, "Second", 2, 1),
topic(13, "Quiet", 1, 0),
];
app.on_tg(TgEvent::Topics {
chat_id: forum_id,
request: asked,
page: Some(topics_page(topics, 3)),
});
assert!(app.read_forum.is_some(), "the page said nothing");
assert_eq!(
app.read_forum.as_ref().unwrap().topics.len(),
3,
"each topic is asked for"
);
app.on_tg(TgEvent::Topic {
chat_id: forum_id,
topic_id: 11,
topic: Some(Box::new(topic(11, "First", 3, 2))),
});
assert!(
app.read_forum.as_ref().is_some_and(|r| r.topics.len() == 2),
"two owed yet"
);
app.on_tg(TgEvent::Topic {
chat_id: forum_id,
topic_id: 12,
topic: Some(Box::new(topic(12, "Second", 2, 1))),
});
app.on_tg(TgEvent::Topic {
chat_id: forum_id,
topic_id: 13,
topic: Some(Box::new(topic(13, "Quiet", 1, 0))),
});
assert!(app.read_forum.is_none(), "nothing owed");
assert_eq!(app.status.as_deref(), Some("Its topics are read"));
}
#[test]
fn a_forum_read_leaves_the_open_topics_pane_its_own_answers() {
let mut app = test_app("mark-read-pane");
let none = KeyModifiers::NONE;
let forum_id = app
.chats
.ids()
.iter()
.copied()
.find(|&id| app.chats.is_forum(id))
.unwrap();
app.enter_forum(forum_id);
let pane_asked = app.topics_asked;
app.focus = Focus::Chats;
app.selected = Some(forum_id);
press(&mut app, KeyCode::Char('R'), none);
app.confirm.as_mut().unwrap().shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), none);
let read_asked = app.read_forum.as_ref().unwrap().page.unwrap().0;
app.on_tg(TgEvent::Topics {
chat_id: forum_id,
request: pane_asked,
page: Some(topics_page(vec![topic(21, "Shown", 2, 0)], 1)),
});
let name = |app: &App, id| app.forum.as_ref().unwrap().get(id).map(|t| t.name.clone());
assert_eq!(name(&app, 21).as_deref(), Some("Shown"), "the pane's page");
assert!(
app.read_forum.as_ref().unwrap().page.is_some(),
"the read's waits"
);
app.on_tg(TgEvent::Topics {
chat_id: forum_id,
request: read_asked,
page: Some(topics_page(
vec![topic(21, "Shown", 2, 0), topic(22, "Unseen", 1, 0)],
2,
)),
});
for (id, title) in [(21, "Renamed"), (22, "Unseen")] {
app.on_tg(TgEvent::Topic {
chat_id: forum_id,
topic_id: id,
topic: Some(Box::new(topic(id, title, 1, 0))),
});
}
assert_eq!(name(&app, 21).as_deref(), Some("Renamed"));
assert_eq!(name(&app, 22), None, "left for the pane's pages");
assert!(app.read_forum.is_none(), "the read is over");
}
#[test]
fn a_forum_read_asks_about_a_few_topics_at_a_time() {
let mut app = test_app("mark-read-many");
let none = KeyModifiers::NONE;
let forum_id = app
.chats
.ids()
.iter()
.copied()
.find(|&id| app.chats.is_forum(id))
.unwrap();
app.selected = Some(forum_id);
press(&mut app, KeyCode::Char('R'), none);
app.confirm.as_mut().unwrap().shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), none);
let asked = app.read_forum.as_ref().unwrap().page.unwrap().0;
let many: Vec<_> = (0..20).map(|id| topic(id, "Blank", 2, 0)).collect();
app.on_tg(TgEvent::Topics {
chat_id: forum_id,
request: asked,
page: Some(topics_page(many, 20)),
});
let owed = |app: &App| {
let read = app.read_forum.as_ref().unwrap();
(read.topics.len(), read.waiting.len())
};
assert_eq!(owed(&app), (FORUM_READ_ASKS, 20 - FORUM_READ_ASKS));
let first = app
.read_forum
.as_ref()
.unwrap()
.topics
.iter()
.next()
.unwrap()
.1;
app.on_tg(TgEvent::Topic {
chat_id: forum_id,
topic_id: first,
topic: None,
});
assert_eq!(
owed(&app),
(FORUM_READ_ASKS, 20 - FORUM_READ_ASKS - 1),
"an answer lets the next one be asked"
);
}
#[test]
fn a_forum_read_whose_topics_dont_come_says_so_and_reads_no_more() {
let mut app = test_app("mark-read-failed");
let forum_id = app
.chats
.ids()
.iter()
.copied()
.find(|&id| app.chats.is_forum(id))
.unwrap();
app.selected = Some(forum_id);
press(&mut app, KeyCode::Char('R'), KeyModifiers::NONE);
app.confirm.as_mut().unwrap().shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
let asked = app.read_forum.as_ref().unwrap().page.unwrap().0;
app.on_tg(TgEvent::Topics {
chat_id: forum_id,
request: asked,
page: None,
});
assert!(app.read_forum.is_none());
assert_eq!(app.status.as_deref(), Some("Its topics couldn't be read"));
}
#[test]
fn a_forum_read_ends_with_the_account_that_agreed_to_it() {
let mut app = test_app("mark-read-logout");
let none = KeyModifiers::NONE;
let forum_id = app
.chats
.ids()
.iter()
.copied()
.find(|&id| app.chats.is_forum(id))
.unwrap();
app.selected = Some(forum_id);
press(&mut app, KeyCode::Char('R'), none);
app.confirm.as_mut().unwrap().shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), none);
assert!(app.read_forum.is_some());
app.forget_session();
assert!(app.read_forum.is_none());
}
#[test]
fn a_forum_read_asks_only_about_topics_its_page_cant_tell() {
assert_eq!(topic_read(3, Some(40), 30), TopicRead::Now(40));
assert_eq!(topic_read(0, Some(40), 40), TopicRead::Done);
assert_eq!(
topic_read(0, Some(40), 0),
TopicRead::Ask,
"a forum never opened says zero unread"
);
assert_eq!(topic_read(2, None, 0), TopicRead::Ask, "no newest named");
}
fn topic(id: i32, name: &str, order: i64, unread: i32) -> ForumTopic {
ForumTopic {
info: tdlib_rs::types::ForumTopicInfo {
chat_id: 0,
forum_topic_id: id,
name: name.into(),
icon: tdlib_rs::types::ForumTopicIcon {
color: 0,
custom_emoji_id: 0,
},
creation_date: 0,
creator_id: tdlib_rs::enums::MessageSender::User(
tdlib_rs::types::MessageSenderUser { user_id: 2 },
),
is_general: false,
is_outgoing: false,
is_closed: false,
is_hidden: false,
is_name_implicit: false,
},
last_message: None,
order,
is_pinned: false,
unread_count: unread,
last_read_inbox_message_id: 0,
last_read_outbox_message_id: 0,
unread_mention_count: 0,
unread_reaction_count: 0,
notification_settings: tdlib_rs::types::ChatNotificationSettings::default(),
draft_message: None,
}
}
fn topics_page(topics: Vec<ForumTopic>, total: i32) -> ForumTopics {
ForumTopics {
total_count: total,
topics,
next_offset_date: 0,
next_offset_message_id: 0,
next_offset_forum_topic_id: 0,
}
}
#[test]
fn r_on_a_chat_marked_unread_asks_to_take_its_marker_too() {
let mut app = test_app("mark-read-marker");
let none = KeyModifiers::NONE;
let chat_id = 7133;
let chat = app.chats.add_local(chat_id, "Reminder", None);
chat.marked_unread = true;
chat.last_message = 11;
app.focus = Focus::Chats;
app.selected = Some(chat_id);
press(&mut app, KeyCode::Char('R'), none);
let confirm = app.confirm.as_ref().expect("the marker asks too");
assert!(
confirm
.lines
.iter()
.any(|l| l == "Its unread marker goes too."),
"{:?}",
confirm.lines
);
press(&mut app, KeyCode::Char('n'), none);
assert!(app.confirm.is_none());
assert!(app.chats.get(chat_id).unwrap().marked_unread, "kept");
press(&mut app, KeyCode::Char('R'), none);
app.confirm.as_mut().unwrap().shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), none);
assert!(!app.chats.get(chat_id).unwrap().marked_unread);
}
#[test]
fn r_on_a_topic_reads_that_topic() {
let mut app = test_app("mark-read-topic");
let none = KeyModifiers::NONE;
crate::demo::show_forum(&mut app);
assert_eq!(app.focus, Focus::Topics);
let chat_id = app.forum.as_ref().unwrap().chat_id;
let mut topic = crate::topics::Topic::local(77, "Fresh", 0, 3, "unread things");
topic.newest = 100;
let forum = app.forum.as_mut().unwrap();
forum.add_local(topic);
forum.selected = Some(77);
press(&mut app, KeyCode::Char('R'), none);
let confirm = app.confirm.as_ref().expect("asks first");
assert!(matches!(
confirm.action,
Confirmed::ReadChat {
chat_id: id,
topic: Some(77)
} if id == chat_id
));
assert!(confirm.lines.iter().any(|l| l == "Fresh"));
press(&mut app, KeyCode::Esc, none);
let read = app
.forum
.as_ref()
.unwrap()
.topics()
.iter()
.find(|t| t.unread == 0)
.unwrap()
.id;
app.forum.as_mut().unwrap().selected = Some(read);
press(&mut app, KeyCode::Char('R'), none);
assert!(app.confirm.is_none());
assert_eq!(app.status.as_deref(), Some("Nothing unread in it"));
}
#[test]
fn i_in_a_public_group_you_are_not_in_asks_to_join_first() {
let mut app = test_app("join");
let chat_id = app.open.as_ref().unwrap().chat_id;
app.chats.add_local(chat_id, "Weekend Hike", None).peer = Some(Peer::Supergroup(77));
app.chats.set_member(77, false);
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE);
assert!(app.focus == Focus::Messages, "not writing yet");
let confirm = app.confirm.as_ref().expect("asks");
assert!(matches!(confirm.action, Confirmed::Join { chat_id: id, .. } if id == chat_id));
press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
app.chats.set_member(77, true);
press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE);
assert!(app.focus == Focus::Input, "once you're in");
}
#[test]
fn j_joins_the_public_chat_you_are_viewing() {
let mut app = test_app("jjoin");
let chat_id = app.open.as_ref().unwrap().chat_id;
app.chats.add_local(chat_id, "Weekend Hike", None).peer = Some(Peer::Supergroup(77));
app.chats.set_member(77, false);
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('J'), KeyModifiers::NONE);
let confirm = app.confirm.as_ref().expect("asks");
assert!(matches!(confirm.action, Confirmed::Join { chat_id: id, .. } if id == chat_id));
press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
app.chats.set_member(77, true);
press(&mut app, KeyCode::Char('J'), KeyModifiers::NONE);
assert!(app.confirm.is_none(), "already in");
}
#[test]
fn q_closes_the_chat_leaving_the_list() {
let mut app = test_app("qclose");
assert!(app.open.is_some());
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('Q'), KeyModifiers::NONE);
assert!(app.open.is_none(), "nothing open on the right");
assert!(app.focus == Focus::Chats);
press(&mut app, KeyCode::Char('Q'), KeyModifiers::NONE);
}
#[test]
fn a_shifted_letter_reported_as_shift_and_the_small_one_is_the_capital() {
let mut app = test_app("shiftletter");
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('q'), KeyModifiers::SHIFT);
assert!(app.open.is_none(), "closed as Q closes");
assert!(app.quit_deadline.is_none(), "not quit as q quits");
let mut app = test_app("shiftcyr");
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('й'), KeyModifiers::SHIFT);
assert!(app.open.is_none(), "closed as Q closes");
assert!(app.quit_deadline.is_none());
}
#[test]
fn o_in_the_media_browser_shows_the_file_in_its_manager() {
let mut app = test_app("mediao");
let mut menu = crate::search::MediaMenu::new(
"has:file".into(),
crate::search::parse("has:file").unwrap(),
);
menu.rows = vec![crate::search::MediaRow {
id: 1,
label: "file".into(),
sender: crate::messages::Sender::User(1),
outgoing: false,
date: 0,
file_id: Some(42),
downloaded: true,
preview: None,
round: false,
}];
app.media_menu = Some(menu);
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('O'), KeyModifiers::NONE);
assert!(app.media_menu.is_some(), "the list stays");
assert!(app.revealing.contains(&42), "downloading to show");
assert_eq!(
app.status.as_deref(),
Some("Downloading to show in the file manager…")
);
let text = screen(&mut app).join("\n");
assert!(text.contains("✓ file"), "on disk is marked: {text}");
}
#[test]
fn a_y_typed_just_before_a_warning_came_up_does_not_answer_it() {
let mut app = test_app("grace");
let edit = Confirmed::Edit {
id: -1,
text: String::new(),
};
app.confirm = Some(Confirm::new("Edit?", vec![], edit));
press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
assert!(app.confirm.is_some(), "too soon to count");
let confirm = app.confirm.as_mut().unwrap();
confirm.shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
assert!(
app.confirm.is_none(),
"answered once it has been up a moment"
);
}
#[test]
fn a_download_finishing_while_you_type_waits_for_enter_instead_of_asking() {
let mut app = test_app("busy");
let dir = std::env::temp_dir().join("tuigram-no-such-folder");
let downloaded = |app: &mut App, name: &str| {
app.opening.insert(77);
let path = dir.join(name).to_string_lossy().into_owned();
app.on_tg(TgEvent::Downloaded {
file_id: 77,
path: Some(path),
});
};
app.focus = Focus::Input;
downloaded(&mut app, "run me.sh");
assert!(app.confirm.is_none(), "no popup over the composer");
let status = app.status.clone().unwrap_or_default();
assert!(status.contains("run me.sh downloaded"), "{status}");
app.focus = Focus::Messages;
downloaded(&mut app, "evil\u{202e}txt.sh");
let title = &app
.confirm
.as_ref()
.expect("asks when nothing else is up")
.title;
assert!(
!title.contains('\u{202e}'),
"the sender's name is cleaned: {title:?}"
);
}
fn command(app: &mut App, name: &str) {
press(app, KeyCode::Char(':'), KeyModifiers::NONE);
for c in name.chars() {
press(app, KeyCode::Char(c), KeyModifiers::NONE);
}
press(app, KeyCode::Enter, KeyModifiers::NONE);
}
#[test]
fn poll_asks_for_its_question_answers_and_flags_and_sends_it() {
crate::tg::quiet();
let mut app = test_app("poll");
let none = KeyModifiers::NONE;
let at = |app: &App, step| {
app.prompt
.as_ref()
.is_some_and(|p| p.kind == PromptKind::Poll(step))
};
let type_in = |app: &mut App, text: &str| {
for c in text.chars() {
press(app, KeyCode::Char(c), none);
}
press(app, KeyCode::Enter, none);
};
press(&mut app, KeyCode::Char(':'), none);
for c in "po".chars() {
press(&mut app, KeyCode::Char(c), none);
}
press(&mut app, KeyCode::Tab, none);
assert_eq!(app.prompt.as_ref().unwrap().query(), "poll");
press(&mut app, KeyCode::Enter, none);
assert!(at(&app, PollStep::Question));
press(&mut app, KeyCode::Enter, none);
assert_eq!(app.status.as_deref(), Some("A poll needs a question"));
assert!(at(&app, PollStep::Question));
type_in(&mut app, "Lunch?");
assert!(at(&app, PollStep::Answer));
type_in(&mut app, "Pizza");
press(&mut app, KeyCode::Enter, none);
assert_eq!(
app.status.as_deref(),
Some("A poll takes at least 2 answers")
);
assert!(at(&app, PollStep::Answer));
type_in(&mut app, "Sushi");
press(&mut app, KeyCode::Enter, none);
let Some(prompt) = app.prompt.as_ref() else {
panic!("asking for the flags")
};
assert!(prompt.kind == PromptKind::Poll(PollStep::Flags));
assert_eq!(prompt.query(), "a", "anonymous to start with");
press(&mut app, KeyCode::Char('x'), none);
press(&mut app, KeyCode::Enter, none);
assert_eq!(
app.status.as_deref(),
Some("Poll flags are only a (anonymous) and m (several answers)")
);
assert!(at(&app, PollStep::Flags));
app.open.as_mut().unwrap().selected = Some(1);
press(&mut app, KeyCode::Backspace, none);
press(&mut app, KeyCode::Enter, none);
assert!(app.prompt.is_none(), "sent: the wizard is done");
assert!(app.status.is_none());
assert_eq!(
app.open.as_ref().unwrap().selected,
None,
"down to watch it arrive"
);
}
#[test]
fn poll_needs_a_chat_that_takes_polls() {
let mut app = test_app("poll-secret");
app.open = None;
command(&mut app, "poll");
assert_eq!(app.status.as_deref(), Some("Open a chat to make a poll in"));
assert!(app.prompt.is_none());
open_chardy(&mut app, Some(crate::secret::SecretState::Ready));
command(&mut app, "poll");
assert_eq!(
app.status.as_deref(),
Some("Polls can't be sent in secret chats")
);
assert!(app.prompt.is_none());
open_chardy(&mut app, None);
command(&mut app, "poll");
assert_eq!(
app.status.as_deref(),
Some("Polls go to groups, channels, bots and Saved Messages")
);
assert!(app.prompt.is_none());
app.chats.set_bot(2, true);
command(&mut app, "poll");
assert!(app.prompt.is_some(), "a bot takes one");
app.prompt = None;
let channel = app.chats.add_local(-10044, "News", None);
channel.is_channel = true;
channel.peer = Some(Peer::Supergroup(44));
app.chats.set_read_only(44, true);
app.open = Some(OpenChat::new(-10044));
command(&mut app, "poll");
assert_eq!(
app.status.as_deref(),
Some("Only the channel's admins post in it")
);
assert!(app.prompt.is_none());
app.chats.set_read_only(44, false);
command(&mut app, "poll");
assert!(app.prompt.is_some(), "an admin's");
}
#[test]
fn a_channel_is_posted_in_by_its_owner_and_admins_who_may() {
use tdlib_rs::types::{ChatMemberStatusCreator, ChatMemberStatusMember};
let owner = ChatMemberStatus::Creator(ChatMemberStatusCreator {
custom_title: String::new(),
is_anonymous: false,
is_member: true,
});
assert!(posts_in_channel(&owner));
let reader = ChatMemberStatus::Member(ChatMemberStatusMember {
member_until_date: 0,
});
assert!(!posts_in_channel(&reader));
assert!(!posts_in_channel(&ChatMemberStatus::Left));
}
#[test]
fn a_scheduled_message_leaves_the_view_where_it_was() {
crate::tg::quiet();
let mut app = test_app("schedule-stay");
let id = plain_message(&mut app);
app.open.as_mut().unwrap().selected = Some(id);
app.composer.insert_str("later");
app.send(Some(i32::MAX));
assert!(app.composer.is_empty(), "sent, to go out later");
assert_eq!(
app.open.as_ref().unwrap().selected,
Some(id),
"nothing arrives to watch"
);
let status = app.status.as_deref().unwrap_or_default();
assert!(
status.starts_with("Scheduled for ") && status.contains("2038"),
"{status}"
);
}
#[test]
fn schedule_needs_a_chat_that_isnt_secret() {
let mut app = test_app("schedule-secret");
open_chardy(&mut app, Some(crate::secret::SecretState::Ready));
app.composer.insert_str("later");
command(&mut app, "schedule");
assert_eq!(
app.status.as_deref(),
Some("Messages can't be scheduled in secret chats")
);
assert!(app.prompt.is_none());
assert_eq!(app.composer.lines(), ["later"], "kept");
}
fn chat_with_chardy(app: &mut App, secret: Option<crate::secret::SecretState>) -> i64 {
let chat_id = if secret.is_some() { 600 } else { 500 };
let chat = app.chats.add_local(chat_id, "Chardy", None);
(chat.is_private, chat.peer) = (true, Some(Peer::User(2)));
if let Some(state) = secret {
chat.secret_id = Some(9);
let secret = Secret {
user_id: 2,
state,
outbound: true,
key_hash: Vec::new(),
};
app.chats.set_secret(9, secret);
}
app.users.insert(2, "Chardy".into());
app.chats.refresh();
app.focus = Focus::Chats;
app.selected = Some(chat_id);
chat_id
}
#[test]
fn r_wont_read_a_secret_chat_from_the_list() {
let mut app = test_app("mark-read-secret");
let chat_id = 600;
let chat = app.chats.add_local(chat_id, "Chardy", None);
(chat.unread, chat.last_message, chat.secret_id) = (10, 42, Some(9));
let secret = Secret {
user_id: 2,
state: crate::secret::SecretState::Ready,
outbound: true,
key_hash: Vec::new(),
};
app.chats.set_secret(9, secret);
app.chats.refresh();
app.focus = Focus::Chats;
app.selected = Some(chat_id);
press(&mut app, KeyCode::Char('R'), KeyModifiers::NONE);
assert!(app.confirm.is_none(), "its timers would start unseen");
assert_eq!(app.status.as_deref(), Some("Open a secret chat to read it"));
}
fn open_chardy(app: &mut App, secret: Option<crate::secret::SecretState>) -> i64 {
let chat_id = chat_with_chardy(app, secret);
app.open = Some(OpenChat::new(chat_id));
app.selected = None;
chat_id
}
#[test]
fn secret_asks_before_starting_a_secret_chat_with_a_person_only() {
let mut app = test_app("secret-start");
chat_with_chardy(&mut app, None);
command(&mut app, "secret");
let confirm = app.confirm.take().expect("asks");
assert!(matches!(
&confirm.action,
Confirmed::StartSecret { user_id: 2, with } if with == "Chardy"
));
app.chats.set_bot(2, true);
command(&mut app, "secret");
assert!(app.confirm.is_none());
assert_eq!(app.status.as_deref(), Some("Bots can't be in secret chats"));
app.focus = Focus::Messages;
command(&mut app, "secret");
assert!(app.confirm.is_none());
let status = app.status.clone().unwrap_or_default();
assert!(status.starts_with("Open a chat with someone"), "{status}");
}
#[test]
fn leave_in_a_secret_chat_asks_to_end_it() {
let mut app = test_app("secret-leave");
let chat_id = chat_with_chardy(&mut app, Some(crate::secret::SecretState::Ready));
command(&mut app, "leave");
let confirm = app.confirm.as_ref().expect("asks");
assert_eq!(confirm.title, "End this secret chat?");
assert!(matches!(
confirm.action,
Confirmed::EndSecret { chat_id: id, secret_id: 9 } if id == chat_id
));
}
#[test]
fn ending_a_secret_chat_forgets_its_draft() {
crate::tg::quiet();
let mut app = test_app("secret-end-draft");
let chat_id = open_chardy(&mut app, Some(crate::secret::SecretState::Ready));
app.chats
.keep_draft(chat_id, Draft::new("meet at noon", None));
app.composer.insert_str("meet at noon");
app.open.as_mut().unwrap().draft = ("meet at noon".into(), None);
app.focus = Focus::Messages;
command(&mut app, "leave");
let confirm = app.confirm.as_mut().expect("asks");
confirm.shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
assert!(app.confirm.is_none());
assert!(app.chats.draft(chat_id).is_none());
assert_eq!(app.composer.lines(), [""]);
assert!(app.draft_to_keep().is_none(), "leaving keeps nothing");
}
#[test]
fn timer_lists_the_timers_with_the_cursor_on_the_chats_own() {
use crate::secret::SecretState;
let mut app = test_app("secret-timer");
let chat_id = open_chardy(&mut app, Some(SecretState::Pending));
command(&mut app, "timer");
assert!(app.timer_menu.is_none(), "not until they accept it");
assert_eq!(
app.status.as_deref(),
Some("Waiting for Chardy to come online")
);
open_chardy(&mut app, Some(SecretState::Ready));
app.chats.set_auto_delete(chat_id, 30);
command(&mut app, "timer");
let at_30 = crate::secret::TIMERS.iter().position(|&t| t == 30).unwrap();
assert_eq!(app.timer_menu.as_ref().map(|m| m.selected), Some(at_30));
let rows = screen(&mut app).join("\n");
assert!(rows.contains("Self-destruct timer · Chardy"), "{rows}");
assert!(rows.contains("● 30 seconds"), "{rows}");
press(&mut app, KeyCode::Char('j'), KeyModifiers::NONE);
press(&mut app, KeyCode::Char('k'), KeyModifiers::NONE);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.timer_menu.is_none());
open_chardy(&mut app, None);
app.focus = Focus::Chats;
app.selected = Some(chat_id);
command(&mut app, "timer");
assert!(app.timer_menu.is_none());
}
#[test]
fn key_shows_the_secret_chats_key_once_there_is_one() {
use crate::secret::SecretState;
let mut app = test_app("secret-key");
open_chardy(&mut app, Some(SecretState::Pending));
command(&mut app, "key");
assert!(app.key_view.is_none());
assert_eq!(
app.status.as_deref(),
Some("The key is made once Chardy accepts the secret chat")
);
let key = Secret {
user_id: 2,
state: SecretState::Ready,
outbound: true,
key_hash: (0..36).collect(),
};
app.chats.set_secret(9, key);
command(&mut app, "key");
assert!(app.key_view.is_some());
let rows = screen(&mut app).join("\n");
assert!(rows.contains("Encryption key · Chardy"), "{rows}");
assert!(rows.contains("00 01 02 03 04 05 06 07"), "{rows}");
assert!(rows.contains("If Chardy sees the same picture"), "{rows}");
press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
assert!(app.key_view.is_none());
}
#[test]
fn a_secret_chat_takes_no_message_until_accepted_and_none_forwarded_from_it() {
use crate::secret::SecretState;
let mut app = test_app("secret-write");
let chat_id = chat_with_chardy(&mut app, Some(SecretState::Pending));
let mut open = OpenChat::new(chat_id);
let id = app
.open
.as_ref()
.unwrap()
.messages
.keys()
.copied()
.next()
.unwrap();
let msg = app.open.as_mut().unwrap().messages.remove(&id).unwrap();
open.messages.insert(id, msg);
app.open = Some(open);
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE);
assert!(app.focus == Focus::Messages, "stays in Normal mode");
assert_eq!(
app.status.as_deref(),
Some("Waiting for Chardy to come online")
);
chat_with_chardy(&mut app, Some(SecretState::Closed));
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE);
assert_eq!(app.status.as_deref(), Some("This secret chat has ended"));
press(&mut app, KeyCode::Char('f'), KeyModifiers::NONE);
assert!(app.picker.is_none());
assert_eq!(
app.status.as_deref(),
Some("Messages in secret chats can't be forwarded")
);
}
fn video_message(app: &mut App) -> (i64, i64) {
let mut picker = Picker::halfblocks();
picker.set_protocol_type(ratatui_image::picker::ProtocolType::Kitty);
app.images = Images::new(picker, unbounded_channel().0);
app.over_ssh = false;
let id = plain_message(app);
let open = app.open.as_mut().unwrap();
let msg = open.messages.get_mut(&id).unwrap();
msg.outgoing = false;
msg.links.clear();
msg.unplayed = true;
msg.preview = Some(crate::messages::Preview {
file_id: 51,
width: 240,
height: 240,
thumbnail: None,
sticker: false,
});
msg.file = Some(MediaFile {
id: 50,
label: "Video message".into(),
photo: false,
downloaded: false,
});
msg.video = Some(crate::video::Note {
file_id: 50,
size: 1000,
duration: 5,
length: 240,
});
(open.chat_id, id)
}
fn video_sticker_message(app: &mut App) -> (i64, i64) {
let (chat_id, id) = video_message(app);
let msg = app.open.as_mut().unwrap().messages.get_mut(&id).unwrap();
msg.video = None;
msg.preview.as_mut().unwrap().sticker = true;
msg.video_sticker = Some(50);
(chat_id, id)
}
#[test]
fn space_and_z_leave_a_video_sticker_to_the_cursor() {
let mut app = test_app("sticker-keys");
app.focus = Focus::Messages;
let (chat_id, id) = video_sticker_message(&mut app);
app.update_sticker_focus();
let sticker = app.inline_video.as_ref().unwrap();
assert!(sticker.is_on(chat_id, id) && !sticker.plays_note(chat_id, id));
press(&mut app, KeyCode::Char('z'), KeyModifiers::NONE);
assert!(!app.inline_video.as_ref().unwrap().medium(), "not zoomed");
press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE);
assert!(app.inline_video.as_ref().unwrap().is_sticker(), "still it");
}
#[test]
fn a_video_message_played_out_gives_way_to_a_sticker_under_the_cursor() {
let mut app = test_app("sticker-after-note");
app.focus = Focus::Messages;
let (chat_id, id) = video_message(&mut app);
let note = |app: &App| {
let msg = &app.open.as_ref().unwrap().messages[&id];
let tx = app.video_tx.clone();
Inline::of(chat_id, id + 100, msg, tx, false, None, &app.colors).unwrap()
};
let (downloading, mut played) = (note(&app), note(&app));
video_sticker_message(&mut app);
app.inline_video = Some(downloading);
app.update_sticker_focus();
assert!(
!app.inline_video.as_ref().unwrap().is_sticker(),
"untouched"
);
played.play_out_for_test();
app.inline_video = Some(played);
app.update_sticker_focus();
assert!(
app.inline_video.as_ref().unwrap().is_sticker(),
"the cursor's sticker plays"
);
}
#[test]
fn a_video_sticker_plays_while_the_cursor_is_on_it() {
let mut app = test_app("sticker-focus");
app.focus = Focus::Messages;
let (_, id) = video_sticker_message(&mut app);
app.update_sticker_focus();
assert!(app.inline_video.is_some(), "downloading to play");
assert!(app.inline_video.as_ref().unwrap().is_sticker());
app.update_sticker_focus();
assert!(app.inline_video.is_some(), "not restarted");
app.open
.as_mut()
.unwrap()
.messages
.get_mut(&id)
.unwrap()
.video_sticker = None;
app.update_sticker_focus();
assert!(app.inline_video.is_none(), "left behind");
}
#[test]
fn tmux_is_asked_for_its_client_once_a_burst_of_resizes_settles() {
let mut app = test_app("tmux-settle");
let mut picker = Picker::halfblocks();
picker.set_protocol_type(ratatui_image::picker::ProtocolType::Kitty);
app.images = Images::new(picker, unbounded_channel().0);
app.in_tmux = false;
app.on_terminal_event(Event::Resize(100, 40));
assert!(app.tmux_check_at.is_none(), "not in tmux");
app.in_tmux = true;
app.on_terminal_event(Event::Resize(100, 40));
let first = app.tmux_check_at.unwrap();
assert!(first > Instant::now(), "not on the resize itself");
std::thread::sleep(Duration::from_millis(2));
app.on_terminal_event(Event::Resize(101, 40));
assert!(app.tmux_check_at.unwrap() > first, "put off by the next");
app.tmux_check_at = None;
app.on_terminal_event(Event::FocusGained);
assert!(app.tmux_check_at.is_some(), "asked on focus too");
app.on_terminal_event(Event::FocusLost);
assert!(app.tmux_check_at.is_some_and(|at| at <= Instant::now()));
}
#[test]
fn a_video_sticker_out_of_sight_for_a_while_plays_again_once_back() {
let mut app = test_app("sticker-back");
app.focus = Focus::Messages;
video_sticker_message(&mut app);
app.update_sticker_focus();
let mut terminal = Terminal::new(TestBackend::new(100, 40)).unwrap();
terminal.draw(|f| ui::draw(f, &mut app)).unwrap();
assert!(
!app.inline_video.as_ref().unwrap().seen,
"still downloading: nothing to play yet"
);
assert!(app.inline_video.as_mut().unwrap().stop_unseen(), "kept");
terminal.draw(|f| ui::draw(f, &mut app)).unwrap();
let inline = app.inline_video.as_mut().unwrap();
assert!(inline.seen, "its still is in sight again");
inline.resume();
assert!(!inline.resumes(), "started over, once");
}
#[test]
fn a_video_sticker_plays_only_while_someone_is_there() {
let mut app = test_app("sticker-away");
app.focus = Focus::Messages;
video_sticker_message(&mut app);
app.update_sticker_focus();
app.terminal_focused = false;
app.on_tg(TgEvent::Downloaded {
file_id: 50,
path: Some("/nowhere/sticker.webm".into()),
});
assert!(app.inline_video.is_none(), "nobody to play to");
app.terminal_focused = true;
app.update_sticker_focus();
assert!(app.inline_video.is_some(), "the cursor's still on it");
app.terminal_focused = false;
app.update_sticker_focus();
assert!(app.inline_video.is_none(), "nobody to play to any more");
}
#[test]
fn a_video_sticker_that_cant_be_had_isnt_asked_for_again() {
let mut app = test_app("sticker-failed");
app.focus = Focus::Messages;
video_sticker_message(&mut app);
app.update_sticker_focus();
app.on_tg(TgEvent::Downloaded {
file_id: 50,
path: None,
});
let inline = app.inline_video.as_ref();
assert!(
inline.is_some_and(|i| i.is_sticker() && !i.started()),
"kept, showing its still, so it isn't made and downloaded again"
);
}
#[test]
fn a_video_sticker_needs_a_terminal_that_shows_it() {
let mut app = test_app("sticker-nokitty");
app.focus = Focus::Messages;
let id = plain_message(&mut app);
let msg = app.open.as_mut().unwrap().messages.get_mut(&id).unwrap();
msg.preview = Some(crate::messages::Preview {
file_id: 51,
width: 512,
height: 512,
thumbnail: None,
sticker: true,
});
msg.video_sticker = Some(50);
app.update_sticker_focus();
assert!(app.inline_video.is_none(), "no kitty frames here");
}
#[test]
fn a_playing_video_message_isnt_stopped_for_a_sticker_under_the_cursor() {
let mut app = test_app("sticker-vs-space");
app.focus = Focus::Messages;
let (_, id) = video_message(&mut app);
press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE);
assert!(app.inline_video.is_some(), "Space started it");
app.open
.as_mut()
.unwrap()
.messages
.get_mut(&id)
.unwrap()
.video_sticker = Some(50);
app.update_sticker_focus();
let inline = app.inline_video.as_ref().unwrap();
assert!(!inline.is_sticker(), "Space's player is left alone");
}
#[test]
fn space_plays_a_video_message_but_not_one_seen_only_while_open() {
let mut app = test_app("video-once");
app.focus = Focus::Messages;
let (_, id) = video_message(&mut app);
press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE);
assert!(app.inline_video.is_some(), "downloading to play");
app.inline_video = None;
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().destruct = Some(crate::secret::Destruct {
after: 10,
on_open: true,
ends: None,
});
press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE);
assert!(app.inline_video.is_none());
assert!(app.video_view.is_none());
}
#[test]
fn a_video_message_downloaded_while_nobody_is_there_waits_and_tells_nobody() {
let mut app = test_app("video-away");
app.focus = Focus::Messages;
let (_, id) = video_message(&mut app);
press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE);
assert!(
app.inline_video.as_ref().unwrap().tell,
"someone else's, unplayed"
);
app.terminal_focused = false;
app.on_tg(TgEvent::Downloaded {
file_id: 50,
path: Some("/nowhere/file_50.mp4".into()),
});
assert!(app.inline_video.is_none(), "not played to an empty room");
assert_eq!(
app.status.as_deref(),
Some("Video message downloaded: Space plays it")
);
assert!(
app.open.as_ref().unwrap().messages[&id].unplayed,
"nobody told"
);
app.terminal_focused = true;
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().outgoing = true;
press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE);
assert!(!app.inline_video.as_ref().unwrap().tell);
}
#[test]
fn what_telegram_says_cant_be_saved_isnt_handed_on_from_a_video_message() {
let mut app = test_app("video-save");
app.focus = Focus::Messages;
let (chat_id, id) = video_message(&mut app);
let open = app.open.as_mut().unwrap();
let msg = open.messages.get_mut(&id).unwrap();
msg.saveable = false;
app.video_view = VideoView::of(
chat_id,
id,
msg,
app.video_tx.clone(),
false,
None,
&app.colors,
);
press(&mut app, KeyCode::Char('o'), KeyModifiers::NONE);
assert!(app.video_view.is_some(), "it stays");
assert_eq!(
app.status.as_deref(),
Some("This video message can't be saved, so it plays only here")
);
assert!(app.opening.is_empty());
app.video_view = None;
press(&mut app, KeyCode::Char('O'), KeyModifiers::NONE);
assert!(app.revealing.is_empty());
assert_eq!(
app.status.as_deref(),
Some("This chat doesn't allow copying its messages")
);
}
#[test]
fn a_video_message_stops_on_leaving_its_chat_or_logging_out() {
let mut app = test_app("video-leave");
app.focus = Focus::Messages;
let (chat_id, id) = video_message(&mut app);
press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE);
assert!(app.inline_video.is_some());
let msg = &app.open.as_ref().unwrap().messages[&id];
app.video_view = VideoView::of(
chat_id,
id,
msg,
app.video_tx.clone(),
false,
None,
&app.colors,
);
let (_, other) = two_chats(&app);
app.open_chat(other);
assert!(app.inline_video.is_none(), "its chat was left");
assert!(app.video_view.is_none());
let mut app = test_app("video-logout");
let (chat_id, id) = video_message(&mut app);
let msg = &app.open.as_ref().unwrap().messages[&id];
app.video_view = VideoView::of(
chat_id,
id,
msg,
app.video_tx.clone(),
false,
None,
&app.colors,
);
app.forget_session();
assert!(app.video_view.is_none(), "the session ended");
}
#[test]
fn the_media_browser_holds_back_read_receipts_and_pastes_as_popups_do() {
let mut app = test_app("media-popup");
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('/'), KeyModifiers::NONE);
for c in "has:file".chars() {
press(&mut app, KeyCode::Char(c), KeyModifiers::NONE);
}
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.media_menu.is_some());
assert!(app.popup_open());
app.on_terminal_event(Event::Paste("hello".into()));
assert!(app.focus != Focus::Input, "no Insert mode under it");
}
#[test]
fn mouse_motion_is_nobody_doing_anything() {
let mouse = |kind| {
Ok(Event::Mouse(MouseEvent {
kind,
column: 3,
row: 4,
modifiers: KeyModifiers::NONE,
}))
};
assert!(mouse_moved(&mouse(MouseEventKind::Moved)));
assert!(mouse_moved(&mouse(MouseEventKind::Drag(MouseButton::Left))));
assert!(!mouse_moved(&mouse(MouseEventKind::Down(
MouseButton::Left
))));
assert!(!mouse_moved(&mouse(MouseEventKind::ScrollUp)));
assert!(!mouse_moved(&Ok(Event::FocusGained)));
}
#[test]
fn commands_work_in_the_cyrillic_layout_too() {
assert_eq!(qwerty('н'), 'y');
assert_eq!(qwerty('Н'), 'Y');
assert_eq!(qwerty('р'), 'h');
assert_eq!(qwerty('ю'), '.');
assert_eq!(qwerty('a'), 'a');
assert_eq!(qwerty('/'), '/');
let mut app = test_app("layout");
app.focus = Focus::Messages;
plain_message(&mut app);
press(&mut app, KeyCode::Char('н'), KeyModifiers::NONE);
assert!(app.toast.is_some(), "copied as y copies");
app.focus = Focus::Input;
press(&mut app, KeyCode::Char('ы'), KeyModifiers::NONE);
assert_eq!(app.composer.lines().join("\n"), "ы");
}
#[test]
fn a_file_uri_encodes_what_breaks_one() {
assert_eq!(
percent_encode("/tmp/a b/файл.pdf"),
"/tmp/a%20b/%D1%84%D0%B0%D0%B9%D0%BB.pdf"
);
}
#[test]
fn y_copies_nothing_telegram_says_cant_be_saved() {
let mut app = test_app("secret-copy");
app.focus = Focus::Messages;
let id = plain_message(&mut app);
let open = app.open.as_mut().unwrap();
let msg = open.messages.get_mut(&id).unwrap();
msg.saveable = false;
msg.destruct = Some(crate::secret::Destruct {
after: 10,
on_open: true,
ends: None,
});
press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
assert!(app.menu.is_none() && app.toast.is_none());
assert_eq!(
app.status.as_deref(),
Some("Self-destructing media can't be copied")
);
}
#[test]
fn v_shows_the_text_to_pick_out_part_of_it_with_vim_motions() {
let mut app = test_app("select");
app.focus = Focus::Messages;
let id = plain_message(&mut app);
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().source_text = "meet at the old station".into();
let none = KeyModifiers::NONE;
press(&mut app, KeyCode::Char('v'), none);
let rows = screen(&mut app);
assert!(rows.iter().any(|r| r.contains("Select text")), "{rows:#?}");
assert!(rows.iter().any(|r| r.contains("meet at the old station")));
assert!(rows[19].contains("v start selecting"), "{:?}", rows[19]);
for c in "wwwve".chars() {
press(&mut app, KeyCode::Char(c), none);
}
let selected = |app: &App| app.text_select.as_ref().unwrap().selected();
assert_eq!(selected(&app).as_deref(), Some("old"));
press(&mut app, KeyCode::Char('w'), none);
press(&mut app, KeyCode::Char('e'), none);
assert_eq!(selected(&app).as_deref(), Some("old station"));
let rows = screen(&mut app);
assert!(rows[19].contains("VISUAL"), "{:?}", rows[19]);
press(&mut app, KeyCode::Esc, none);
assert_eq!(selected(&app), None);
press(&mut app, KeyCode::Char('y'), none);
assert_eq!(
app.status.as_deref(),
Some("Nothing selected: v starts a selection")
);
assert!(app.toast.is_none(), "nothing copied");
press(&mut app, KeyCode::Esc, none);
assert!(app.text_select.is_none());
assert!(app.focus == Focus::Messages, "back where it was");
}
#[test]
fn v_takes_nothing_telegram_says_cant_be_saved_nor_a_message_without_text() {
let mut app = test_app("select-none");
app.focus = Focus::Messages;
let id = plain_message(&mut app);
let msg = app.open.as_mut().unwrap().messages.get_mut(&id).unwrap();
msg.saveable = false;
press(&mut app, KeyCode::Char('v'), KeyModifiers::NONE);
assert!(app.text_select.is_none());
assert_eq!(
app.status.as_deref(),
Some("This chat doesn't allow copying its messages")
);
let msg = app.open.as_mut().unwrap().messages.get_mut(&id).unwrap();
msg.saveable = true;
msg.source_text.clear();
press(&mut app, KeyCode::Char('v'), KeyModifiers::NONE);
assert!(app.text_select.is_none());
assert_eq!(
app.status.as_deref(),
Some("No text to select in this message")
);
}
#[test]
fn nothing_is_read_under_the_text_popup_and_it_closes_once_the_text_changes_or_goes() {
let mut app = test_app("select-gone");
app.focus = Focus::Messages;
let chat_id = app.open.as_ref().unwrap().chat_id;
let id = plain_message(&mut app);
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().source_text = "hello".into();
assert!(app.looking_at(chat_id));
press(&mut app, KeyCode::Char('v'), KeyModifiers::NONE);
assert!(app.text_select.is_some());
assert!(!app.looking_at(chat_id), "it's over the messages");
let edited = |text: &str| {
Update::MessageContent(tdlib_rs::types::UpdateMessageContent {
chat_id,
message_id: id,
new_content: tdlib_rs::enums::MessageContent::MessageText(
tdlib_rs::types::MessageText {
text: tdlib_rs::types::FormattedText {
text: text.into(),
..Default::default()
},
link_preview: None,
link_preview_options: None,
},
),
})
};
app.on_tg(TgEvent::Update(Box::new(edited("hello"))));
assert!(app.text_select.is_some(), "the text didn't change");
app.on_tg(TgEvent::Update(Box::new(edited("goodbye"))));
assert!(app.text_select.is_none());
assert_eq!(
app.status.as_deref(),
Some("The message was edited: v selects again")
);
press(&mut app, KeyCode::Char('v'), KeyModifiers::NONE);
assert!(app.text_select.is_some());
let deleted = Update::DeleteMessages(tdlib_rs::types::UpdateDeleteMessages {
chat_id,
message_ids: vec![id],
is_permanent: true,
from_cache: false,
});
app.on_tg(TgEvent::Update(Box::new(deleted)));
assert!(app.text_select.is_none());
}
fn secret_photo(app: &mut App) -> i64 {
let open = app.open.as_mut().unwrap();
let id = open.newest_id().unwrap() + 1;
let mut photo = crate::messages::test_secret_photo(10);
photo.outgoing = false;
open.messages.insert(id, photo);
open.selected = None;
app.focus = Focus::Messages;
id
}
#[test]
fn a_photo_shown_only_while_open_is_covered_once_nobody_is_there() {
let mut app = test_app("secret-away");
let id = secret_photo(&mut app);
assert!(app.open.as_mut().unwrap().uncover(id));
app.cover_unseen();
assert_eq!(app.open.as_ref().unwrap().viewing, Some(id), "looked at");
app.last_input_wall = SystemTime::now() - (IDLE_AFTER + Duration::from_secs(1));
app.cover_unseen();
let open = app.open.as_ref().unwrap();
assert_eq!(open.viewing, None);
assert!(open.messages[&id].preview.is_none(), "covered");
}
#[test]
fn the_sender_hears_a_photo_was_opened_only_if_it_was_seen() {
let mut app = test_app("secret-opened");
let id = secret_photo(&mut app);
let open = app.open.as_mut().unwrap();
open.uncover(id);
open.opening = Some((id, 20));
app.on_tg(TgEvent::Downloaded {
file_id: 20,
path: None,
});
assert_eq!(app.open.as_ref().unwrap().opening, None);
let open = app.open.as_mut().unwrap();
open.opening = Some((id, 20));
open.selected = Some(id - 1);
app.cover_unseen();
assert_eq!(app.open.as_ref().unwrap().opening, None);
app.on_tg(TgEvent::Downloaded {
file_id: 20,
path: Some("/nowhere/photo.jpg".into()),
});
let photo = &app.open.as_ref().unwrap().messages[&id];
assert!(
photo.destruct.is_some_and(|d| d.ends.is_none()),
"its timer didn't start"
);
}
#[test]
fn media_seen_only_while_open_is_never_handed_to_another_app() {
let mut app = test_app("secret-voice");
app.focus = Focus::Messages;
let id = plain_message(&mut app);
let msg = app.open.as_mut().unwrap().messages.get_mut(&id).unwrap();
msg.file = Some(MediaFile {
id: 30,
label: "Voice message".into(),
photo: false,
downloaded: false,
});
msg.links.clear();
msg.source_text.clear();
msg.destruct = Some(crate::secret::Destruct {
after: 30,
on_open: true,
ends: None,
});
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.opening.is_empty(), "not downloaded to open");
let status = app.status.clone().unwrap_or_default();
assert!(status.ends_with(crate::messages::ON_PHONE), "{status}");
press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
assert!(app.copying.is_empty());
assert_eq!(
app.status.as_deref(),
Some("Nothing to copy in this message")
);
}
fn voice_message(app: &mut App) -> (i64, i64) {
let id = plain_message(app);
let open = app.open.as_mut().unwrap();
let msg = open.messages.get_mut(&id).unwrap();
msg.outgoing = false;
msg.links.clear();
msg.file = Some(MediaFile {
id: 30,
label: "Voice message".into(),
photo: false,
downloaded: false,
});
msg.voice = Some(crate::voice::Voice {
file_id: 30,
size: 0,
duration: 1,
levels: Vec::new(),
ogg: true,
listened: false,
});
(open.chat_id, id)
}
fn photo_message(app: &mut App) -> (i64, i64) {
let id = plain_message(app);
make_photo(app, id, 40);
(app.open.as_ref().unwrap().chat_id, id)
}
fn make_photo(app: &mut App, id: i64, file_id: i32) {
let open = app.open.as_mut().unwrap();
let msg = open.messages.get_mut(&id).unwrap();
msg.links.clear();
let preview = |file_id, width, height| crate::messages::Preview {
file_id,
width,
height,
thumbnail: None,
sticker: false,
};
msg.preview = Some(preview(file_id, 800, 600));
msg.photo = Some(preview(file_id + 1, 2560, 1920));
msg.file = Some(MediaFile {
id: file_id + 1,
label: "Photo".into(),
photo: true,
downloaded: false,
});
}
#[test]
fn h_and_l_in_the_viewer_go_to_the_photo_before_and_after_it() {
let mut app = test_app("viewer-next");
let none = KeyModifiers::NONE;
let open = app.open.as_mut().unwrap();
open.all_loaded = true;
open.at_newest = true;
let (chat_id, ids) = (
open.chat_id,
open.messages.keys().copied().collect::<Vec<_>>(),
);
let (older, newer) = (ids[1], ids[ids.len() - 1]);
assert!(ids.len() > 3);
make_photo(&mut app, older, 50);
make_photo(&mut app, newer, 60);
let open = app.open.as_ref().unwrap();
app.photo_view = PhotoView::of(chat_id, newer, &open.messages[&newer]);
let shown = |app: &App| app.photo_view.as_ref().map(|v| v.message_id);
press(&mut app, KeyCode::Char('k'), none);
press(&mut app, KeyCode::Char('h'), none);
assert_eq!(
shown(&app),
Some(older),
"past the messages that aren't photos"
);
assert_eq!(app.photo_view.as_ref().unwrap().zoom, None, "unzoomed");
press(&mut app, KeyCode::Char('h'), none);
assert_eq!(shown(&app), Some(older));
assert_eq!(app.status.as_deref(), Some("No older photos in this chat"));
press(&mut app, KeyCode::Right, none);
assert_eq!(shown(&app), Some(newer));
press(&mut app, KeyCode::Char('l'), none);
assert_eq!(shown(&app), Some(newer));
assert_eq!(app.status.as_deref(), Some("No newer photos in this chat"));
}
#[test]
fn j_and_k_in_the_viewer_zoom_out_and_back_in_never_past_filling_the_window() {
let mut app = test_app("viewer-zoom");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
photo_message(&mut app);
press(&mut app, KeyCode::Enter, none);
let zoom = |app: &App| app.photo_view.as_ref().unwrap().zoom;
screen(&mut app);
press(&mut app, KeyCode::Char('j'), none);
assert_eq!(zoom(&app), None);
press(&mut app, KeyCode::Char('k'), none);
assert_eq!(zoom(&app), Some(viewer::SIZES.len() - 2));
for _ in 0..10 {
press(&mut app, KeyCode::Char('-'), none);
}
assert_eq!(zoom(&app), Some(0));
let rows = screen(&mut app);
assert!(rows[0].contains("Photo · 25% · loading…"), "{rows:#?}");
for _ in 0..10 {
press(&mut app, KeyCode::Char('j'), none);
}
assert_eq!(zoom(&app), Some(viewer::SIZES.len() - 1));
assert!(screen(&mut app)[0].contains("Photo · 100%"));
}
#[test]
fn enter_on_a_photo_shows_it_in_the_viewer_not_in_another_app() {
let mut app = test_app("viewer-enter");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
let (chat_id, id) = photo_message(&mut app);
press(&mut app, KeyCode::Enter, none);
let view = app.photo_view.as_ref().expect("the viewer is up");
assert_eq!((view.chat_id, view.message_id), (chat_id, id));
assert_eq!(view.photo.file_id, 41, "at its largest");
assert_eq!(view.stand_in.as_ref().map(|p| p.file_id), Some(40));
assert!(app.opening.is_empty(), "nothing waits for another app");
assert!(app.busy(), "a download finishing won't pop up over it");
press(&mut app, KeyCode::Char('k'), none);
assert_eq!(app.open.as_ref().unwrap().selected, Some(id));
press(&mut app, KeyCode::Char('o'), KeyModifiers::CONTROL);
assert!(app.photo_view.is_some(), "Ctrl-o isn't o");
assert!(app.opening.is_empty());
for close in [KeyCode::Esc, KeyCode::Char('q'), KeyCode::Enter] {
assert!(app.photo_view.is_some());
press(&mut app, close, none);
assert!(app.photo_view.is_none(), "{close:?} closes it");
press(&mut app, KeyCode::Enter, none);
}
}
#[test]
fn what_arrives_while_a_photo_is_open_is_neither_marked_read_nor_kept_quiet() {
let mut app = test_app("viewer-unseen");
app.focus = Focus::Messages;
let open = app.open.as_mut().unwrap();
let (chat_id, newest) = (open.chat_id, open.newest_id().unwrap());
make_photo(&mut app, newest, 40);
let open = app.open.as_mut().unwrap();
open.selected = None;
open.at_newest = true;
assert!(app.watching(chat_id));
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.photo_view.is_some());
assert_eq!(
app.open.as_ref().unwrap().selected,
Some(newest),
"the cursor stays on the photo"
);
assert!(!app.watching(chat_id));
app.open.as_mut().unwrap().selected = None;
assert!(!app.watching(chat_id), "the photo hides the chat");
assert!(!app.sees(chat_id, None), "so it's notified");
app.focus_reported = true;
assert!(!app.sees(chat_id, None), "even in a focused window");
}
#[test]
fn pastes_and_late_edits_wait_until_the_photo_is_closed() {
let mut app = test_app("viewer-paste");
app.focus = Focus::Messages;
let (chat_id, id) = photo_message(&mut app);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let file = std::env::temp_dir().join("tuigram-test-viewer-paste.txt");
std::fs::write(&file, b"notes").unwrap();
app.on_terminal_event(Event::Paste(file.to_string_lossy().into_owned()));
assert_eq!(
app.status.take().as_deref(),
Some("Close what's open to paste")
);
let place = app.open.as_ref().unwrap().place();
app.on_pasted(Pasted {
place,
content: Ok(Paste::Text("the screenshot".into())),
});
assert!(app.status.take().is_some());
app.on_editable(chat_id, id, Some(true), None);
assert!(app.status.take().is_some());
assert!(app.focus == Focus::Messages, "not Insert mode under it");
assert!(app.composer.is_empty());
assert!(app.open.as_ref().unwrap().attachments.is_empty());
assert!(app.open.as_ref().unwrap().editing.is_none());
}
#[test]
fn pastes_and_late_edits_wait_until_any_popup_is_closed() {
let mut app = test_app("popup-paste");
app.focus = Focus::Messages;
let chat_id = app.open.as_ref().unwrap().chat_id;
let id = plain_message(&mut app);
let file = std::env::temp_dir().join("tuigram-test-popup-paste.txt");
std::fs::write(&file, b"notes").unwrap();
for popup in 0..3 {
match popup {
0 => {
app.confirm = Some(Confirm::new(
"Open this link?",
vec!["https://example.com".into()],
Confirmed::OpenLink("https://example.com".into()),
))
}
1 => {
app.delete_menu = Some(DeleteMenu {
message_id: id,
snippet: "hi".into(),
choices: Vec::new(),
selected: 0,
})
}
_ => app.react_menu = Some(ReactMenu::new(id, "hi".into())),
}
app.on_terminal_event(Event::Paste(file.to_string_lossy().into_owned()));
assert_eq!(
app.status.take().as_deref(),
Some("Close what's open to paste")
);
let place = app.open.as_ref().unwrap().place();
app.on_pasted(Pasted {
place,
content: Ok(Paste::Text("the screenshot".into())),
});
let status = app.status.take().unwrap_or_default();
assert!(status.starts_with("The paste came while"), "{status}");
app.on_editable(chat_id, id, Some(true), None);
let status = app.status.take().unwrap_or_default();
assert!(status.starts_with("The edit came while"), "{status}");
assert!(app.focus == Focus::Messages, "not Insert mode under it");
assert!(app.composer.is_empty());
let open = app.open.as_ref().unwrap();
assert!(open.attachments.is_empty() && open.editing.is_none());
if popup == 0 {
assert_eq!(app.confirm.as_ref().unwrap().title, "Open this link?");
}
app.close_popups();
}
}
#[test]
fn nothing_is_read_while_any_popup_is_over_the_messages() {
let mut app = test_app("popup-unseen");
app.focus = Focus::Messages;
let open = app.open.as_mut().unwrap();
open.selected = None;
open.at_newest = true;
let (chat_id, newest) = (open.chat_id, open.newest_id().unwrap());
assert!(app.watching(chat_id));
let pinned = Pinned::new(newest, &app.open.as_ref().unwrap().messages[&newest]);
app.pinned_menu = PinnedMenu::new(&[pinned]);
assert!(app.pinned_menu.is_some());
assert!(!app.watching(chat_id));
assert!(!app.sees(chat_id, None), "so it's notified");
app.pinned_menu = None;
app.picker = Some(ChatPicker::new(Purpose::Open));
assert!(!app.watching(chat_id));
app.picker = None;
assert!(app.watching(chat_id));
}
#[test]
fn popups_about_a_message_close_once_it_is_deleted() {
let mut app = test_app("popup-deleted");
app.focus = Focus::Messages;
let chat_id = app.open.as_ref().unwrap().chat_id;
let deleted = |ids: Vec<i64>| {
TgEvent::Update(Box::new(Update::DeleteMessages(
tdlib_rs::types::UpdateDeleteMessages {
chat_id,
message_ids: ids,
is_permanent: true,
from_cache: false,
},
)))
};
let id = plain_message(&mut app);
app.react_menu = Some(ReactMenu::new(id, "hi".into()));
app.on_tg(deleted(vec![id + 1000]));
assert!(app.react_menu.is_some(), "another message went");
app.on_tg(deleted(vec![id]));
assert!(app.react_menu.is_none());
let id = plain_message(&mut app);
app.pin_menu = Some(PinMenu::new(id, "hi".into(), Place::Group, String::new()));
app.on_tg(deleted(vec![id]));
assert!(app.pin_menu.is_none());
let id = plain_message(&mut app);
app.delete_menu = Some(DeleteMenu {
message_id: id,
snippet: "hi".into(),
choices: Vec::new(),
selected: 0,
});
app.on_tg(deleted(vec![id]));
assert!(app.delete_menu.is_none());
}
#[test]
fn logging_out_leaves_no_popup_or_resize_mode_behind() {
let mut app = test_app("forget-popups");
app.resizing = Some(Resizing::List);
app.confirm = Some(Confirm::new("Log out?", Vec::new(), Confirmed::Logout));
app.react_menu = Some(ReactMenu::new(1, "hi".into()));
app.forget_session();
assert!(app.resizing.is_none());
assert!(!app.popup_open());
}
#[test]
fn only_telegram_refusing_the_key_forgets_it() {
let mut app = test_app("api-id-error");
app.settings.api_keys = Some(ApiKeys {
id: 1234567,
hash: "0123456789abcdef0123456789abcdef".into(),
});
app.keys_source = Some(KeySource::Saved);
app.on_tg(TgEvent::Error(
"Nobody on Telegram is called @API_ID_bot".into(),
));
assert!(app.settings.api_keys.is_some());
app.on_tg(TgEvent::Error("API_ID_INVALID".into()));
assert!(app.settings.api_keys.is_none());
}
#[test]
fn over_ssh_files_and_photos_arent_copied_to_the_other_computer() {
let mut app = test_app("ssh-copy");
app.clipboard.remote = true;
app.copy_target(Target::File(MediaFile {
id: 7,
label: "notes.pdf".into(),
photo: false,
downloaded: false,
}));
assert_eq!(
app.status.as_deref(),
Some("Over SSH, only text reaches your computer's clipboard")
);
assert!(app.copying.is_empty(), "nothing downloaded for it");
}
#[test]
fn over_ssh_p_doesnt_paste_the_other_computers_clipboard() {
let mut app = test_app("ssh-paste");
app.clipboard.remote = true;
app.focus = Focus::Messages;
press(&mut app, KeyCode::Char('p'), KeyModifiers::NONE);
assert!(!app.pasting, "nothing read");
let status = app.status.take().unwrap_or_default();
assert!(
status.starts_with("Over SSH, paste with your terminal's"),
"{status}"
);
app.focus = Focus::Input;
app.on_terminal_event(Event::Paste("see you at 5".into()));
assert_eq!(app.composer.lines().join("\n"), "see you at 5");
}
#[test]
fn the_viewer_never_takes_a_photo_shown_only_while_open() {
let mut app = test_app("viewer-once");
app.focus = Focus::Messages;
let (_, id) = photo_message(&mut app);
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().destruct = Some(crate::secret::Destruct {
after: 10,
on_open: true,
ends: None,
});
let file = open.messages[&id].file.clone().unwrap();
app.view_photo(id, file);
assert!(app.photo_view.is_none());
assert!(app.opening.is_empty(), "nor hands it to another app");
assert_eq!(
app.status.as_deref(),
Some("This photo can't be shown here")
);
}
#[test]
fn o_in_the_viewer_closes_it_and_opens_the_photo_in_its_app_as_enter_did() {
let mut app = test_app("viewer-o");
app.focus = Focus::Messages;
photo_message(&mut app);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
app.opening.insert(41);
press(&mut app, KeyCode::Char('o'), KeyModifiers::NONE);
assert!(app.photo_view.is_none());
assert!(app.opening.contains(&41), "opens once downloaded");
app.on_tg(TgEvent::Downloaded {
file_id: 41,
path: Some("/nonexistent/photo.exe".into()),
});
assert!(matches!(
app.confirm.as_ref().map(|c| &c.action),
Some(Confirmed::OpenFile(_))
));
}
#[test]
fn y_and_o_in_the_viewer_hand_on_nothing_telegram_says_cant_be_saved() {
let mut app = test_app("viewer-y");
app.focus = Focus::Messages;
let (_, id) = photo_message(&mut app);
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().saveable = false;
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
assert_eq!(
app.status.as_deref(),
Some("This chat doesn't allow copying its messages")
);
assert!(app.copying.is_empty());
assert!(app.photo_view.is_some(), "still up");
press(&mut app, KeyCode::Char('o'), KeyModifiers::NONE);
assert_eq!(
app.status.as_deref(),
Some("This photo can't be saved, so it opens only here")
);
assert!(app.opening.is_empty(), "not handed to an app that saves it");
assert!(app.photo_view.is_some());
}
#[test]
fn the_viewer_closes_once_its_message_is_deleted_or_edited_to_another_photo() {
let mut app = test_app("viewer-gone");
app.focus = Focus::Messages;
let (chat_id, id) = photo_message(&mut app);
let deleted = |message_ids| {
Update::DeleteMessages(tdlib_rs::types::UpdateDeleteMessages {
chat_id,
message_ids,
is_permanent: true,
from_cache: false,
})
};
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
app.on_tg(TgEvent::Update(Box::new(deleted(vec![id + 1000]))));
assert!(app.photo_view.is_some(), "another message went");
app.on_tg(TgEvent::Update(Box::new(deleted(vec![id]))));
assert!(app.photo_view.is_none());
let (_, id) = photo_message(&mut app);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let edited = tdlib_rs::types::UpdateMessageContent {
chat_id,
message_id: id,
new_content: tdlib_rs::enums::MessageContent::MessageText(
tdlib_rs::types::MessageText {
text: tdlib_rs::types::FormattedText {
text: "no photo now".into(),
..Default::default()
},
link_preview: None,
link_preview_options: None,
},
),
};
app.on_tg(TgEvent::Update(Box::new(Update::MessageContent(edited))));
assert!(app.photo_view.is_none());
}
#[test]
fn the_viewer_covers_the_chats_and_messages_and_says_its_keys() {
let mut app = test_app("viewer-draw");
app.focus = Focus::Messages;
photo_message(&mut app);
let chat_id = app.open.as_ref().unwrap().chat_id;
let title = app.chats.title(chat_id).unwrap().to_string();
assert!(screen(&mut app).iter().any(|r| r.contains(&title)));
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let rows = screen(&mut app);
assert!(rows[0].contains("Photo · loading…"), "{rows:#?}");
assert!(!rows.iter().any(|r| r.contains(&title)), "{rows:#?}");
assert!(rows.iter().any(|r| r.contains("Loading…")), "{rows:#?}");
assert!(
rows[rows.len() - 1].contains("o open in its app · y copy"),
"{rows:#?}"
);
}
#[test]
fn enter_pauses_the_voice_message_playing_and_plays_it_on() {
let mut app = test_app("voice-pause");
app.focus = Focus::Messages;
let (chat_id, id) = voice_message(&mut app);
app.player.play(chat_id, id, 30, true);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(app.player.playback(chat_id).unwrap().paused);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
assert!(!app.player.playback(chat_id).unwrap().paused);
}
#[test]
fn a_voice_message_plays_once_downloaded_says_why_it_cant_and_stops_if_deleted() {
let mut app = test_app("voice-download");
let (tx, mut rx) = unbounded_channel();
app.player = Player::new(tx, crate::voice::Output::Nowhere);
let (chat_id, id) = voice_message(&mut app);
app.player.play(chat_id, id, 30, true);
app.on_tg(TgEvent::Downloaded {
file_id: 30,
path: None,
});
assert_eq!(app.status.take().as_deref(), Some("Download failed"));
assert!(!app.player.is_on(chat_id, id));
app.player.play(chat_id, id, 30, true);
app.terminal_focused = false;
app.on_tg(TgEvent::Downloaded {
file_id: 30,
path: Some("/nonexistent/voice.ogg".into()),
});
assert!(!app.player.is_on(chat_id, id));
assert_eq!(
app.status.take().as_deref(),
Some("Voice message downloaded: Enter plays it")
);
app.terminal_focused = true;
app.player.play(chat_id, id, 30, true);
let path = std::env::temp_dir().join("tuigram-test-voice-download.ogg");
std::fs::write(&path, b"<html>").unwrap();
app.on_tg(TgEvent::Downloaded {
file_id: 30,
path: Some(path.to_string_lossy().into_owned()),
});
app.on_voice(rx.blocking_recv().unwrap());
assert_eq!(
app.status.take().as_deref(),
Some("Can't play this voice message: it isn't an Ogg file")
);
assert!(!app.player.is_on(chat_id, id));
app.player.play(chat_id, id, 30, true);
let deleted = tdlib_rs::types::UpdateDeleteMessages {
chat_id,
message_ids: vec![id],
is_permanent: true,
from_cache: false,
};
app.on_tg(TgEvent::Update(Box::new(Update::DeleteMessages(deleted))));
assert!(!app.player.is_on(chat_id, id), "stopped");
}
#[test]
fn playing_your_own_voice_message_tells_nobody() {
let mut app = test_app("voice-own");
let (chat_id, id) = voice_message(&mut app);
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().outgoing = true;
let tell = open.tells(id);
assert!(!tell);
app.player.play(chat_id, id, 30, tell);
app.on_voice(app.player.event(Happened::Started));
assert!(app.player.is_on(chat_id, id), "still playing");
}
#[test]
fn a_voice_message_picked_from_a_menu_is_the_one_enter_was_on() {
let mut app = test_app("voice-menu");
app.focus = Focus::Messages;
let (_, id) = voice_message(&mut app);
let msg = app.open.as_mut().unwrap().messages.get_mut(&id).unwrap();
msg.links = vec![Link {
url: "https://x.dev".into(),
disguise: None,
}];
msg.destruct = Some(crate::secret::Destruct {
after: 0,
on_open: true,
ends: None,
});
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let menu = app.menu.as_ref().expect("the voice message and its link");
assert!(
matches!(&menu.targets[0], Target::Voice { message_id, file } if *message_id == id && file.id == 30),
"names its message"
);
assert!(app.opening.is_empty());
}
#[test]
fn enter_and_y_on_any_photo_of_an_album_offer_the_links_of_its_caption() {
let mut app = test_app("album-links");
app.focus = Focus::Messages;
let first = plain_message(&mut app);
let second = {
let open = app.open.as_ref().unwrap();
let next = open.messages.range(first + 1..).next();
*next.unwrap().0
};
make_photo(&mut app, first, 50);
make_photo(&mut app, second, 60);
let open = app.open.as_mut().unwrap();
for id in [first, second] {
let msg = open.messages.get_mut(&id).unwrap();
msg.album = 7;
msg.state = SendState::Sent;
msg.source_text.clear();
msg.poll = None;
msg.keyboard = None;
msg.styles.clear();
}
let captioned = open.messages.get_mut(&first).unwrap();
captioned.source_text = "see https://x.dev".into();
captioned.links = vec![Link {
url: "https://x.dev".into(),
disguise: None,
}];
open.selected = Some(second);
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let menu = app.menu.take().expect("the photo and the caption's link");
assert!(
matches!(&menu.targets[..], [Target::Photo { message_id, .. }, Target::Link(l)]
if *message_id == second && l.url == "https://x.dev"),
"the photo under the cursor, and the link"
);
assert!(app.photo_view.is_none(), "nothing opens instead");
press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
let menu = app
.menu
.take()
.expect("the caption, its link and the photo");
assert!(
matches!(&menu.targets[..], [Target::Text(t), Target::Link(_), Target::File(f)]
if t == "see https://x.dev" && f.id == 61),
"the caption's text and link, then the photo under the cursor (61), not the captioned one (51)"
);
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&second).unwrap().keyboard = Some(crate::buttons::Keyboard {
rows: vec![vec![crate::buttons::Button {
label: "Like".into(),
press: crate::buttons::Press::Callback(String::new()),
}]],
reply: false,
});
press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
let menu = app.button_menu.as_ref().expect("the bot's buttons");
assert!(
menu.rows.iter().flatten().any(
|b| matches!(&b.press, crate::buttons::Press::Open(l) if l.url == "https://x.dev")
),
"the caption's link is among them"
);
}
#[test]
fn a_secret_chat_taken_although_the_setting_says_not_is_told() {
use tdlib_rs::enums::NotificationGroupType;
use tdlib_rs::types::Notification;
let mut app = test_app("secret-taken");
let chat_id = chat_with_chardy(&mut app, Some(crate::secret::SecretState::Ready));
let update = |app: &mut App| {
app.on_notifications(UpdateNotificationGroup {
notification_group_id: 1,
r#type: NotificationGroupType::SecretChat,
chat_id,
notification_settings_chat_id: chat_id,
notification_sound_id: 0,
total_count: 1,
added_notifications: vec![Notification {
id: 1,
date: unix_now(),
is_silent: false,
r#type: NotificationType::NewSecretChat,
}],
removed_notification_ids: Vec::new(),
});
};
update(&mut app);
let status = app.status.take().unwrap_or_default();
assert!(status.contains("Chardy started a secret chat"), "{status}");
assert!(status.contains(":leave ends it"), "{status}");
app.settings.accept_secret_chats = true;
update(&mut app);
assert_eq!(app.status, None, "taken as asked");
}
#[test]
fn logging_out_says_secret_chats_go_too() {
let mut app = test_app("secret-logout");
command(&mut app, "logout");
let lines = app.confirm.take().expect("asks").lines.join(" ");
assert!(lines.contains("Your secret chats go too"), "{lines}");
app.chats = Chats::default();
command(&mut app, "logout");
let lines = app.confirm.take().expect("asks").lines.join(" ");
assert!(!lines.contains("secret chats"), "{lines}");
}
fn message_ids(app: &App) -> Vec<i64> {
app.open
.as_ref()
.unwrap()
.messages
.keys()
.copied()
.collect()
}
#[test]
fn gu_goes_to_the_first_unread_message_and_ctrl_o_comes_back() {
let mut app = test_app("unread");
app.focus = Focus::Messages;
let (none, ctrl) = (KeyModifiers::NONE, KeyModifiers::CONTROL);
let cursor = |app: &App| app.open.as_ref().unwrap().selected;
press(&mut app, KeyCode::Char('g'), none);
press(&mut app, KeyCode::Char('u'), none);
assert_eq!(app.status.as_deref(), Some("No unread messages"));
let ids = message_ids(&app);
let read = ids[1];
let open = app.open.as_mut().unwrap();
open.unread_line = Some(read);
let first = open.first_unread(read).unwrap();
press(&mut app, KeyCode::Char('g'), none);
press(&mut app, KeyCode::Char('u'), none);
assert_eq!(cursor(&app), Some(first));
press(&mut app, KeyCode::Char('o'), ctrl);
assert_eq!(cursor(&app), None, "back on the newest");
}
#[test]
fn gm_goes_to_the_oldest_unread_mention_which_seeing_reads() {
let mut app = test_app("mentions");
app.focus = Focus::Messages;
let none = KeyModifiers::NONE;
let chat = app.open.as_ref().unwrap().chat_id;
let ids = message_ids(&app);
let (older, newer) = (ids[1], ids[3]);
let cursor = |app: &App| app.open.as_ref().unwrap().selected;
press(&mut app, KeyCode::Char('g'), none);
press(&mut app, KeyCode::Char('M'), none);
assert_eq!(app.status.as_deref(), Some("No newer mentions"));
app.chats.set_mentions(chat, 2);
for id in [older, newer] {
let open = app.open.as_mut().unwrap();
open.messages.get_mut(&id).unwrap().mention = true;
}
app.open.as_mut().unwrap().mentions_asked = Some(Mentions::Unread);
app.on_mentions((chat + 1, None), Mentions::Unread, Some(vec![newer]));
app.on_mentions((chat, None), Mentions::Before(0), Some(vec![newer]));
assert_eq!(cursor(&app), None);
app.on_mentions((chat, None), Mentions::Unread, Some(vec![newer, older]));
assert_eq!(cursor(&app), Some(older));
assert!(app.jumps.can_go_back(), "Ctrl-o comes back");
app.on_mentions((chat, None), Mentions::Unread, Some(vec![newer]));
assert_eq!(cursor(&app), Some(older));
assert_eq!(app.mention_seen(), Some(older));
assert!(app.open.as_ref().unwrap().messages[&newer].mention);
app.open.as_mut().unwrap().mentions_asked = Some(Mentions::Before(older));
app.on_mentions((chat, None), Mentions::Before(older), Some(vec![]));
assert_eq!(app.status.as_deref(), Some("No older mentions"));
app.open.as_mut().unwrap().mentions_asked = Some(Mentions::After(older));
app.on_mentions(
(chat, None),
Mentions::After(older),
Some(vec![newer, older]),
);
assert_eq!(cursor(&app), Some(newer));
}
#[test]
fn gm_picks_the_oldest_unseen_mention_or_the_nearest_one_before_or_after() {
let found = [90, 70, 50, 30];
assert_eq!(Mentions::Unread.pick(&found), Some(30));
assert_eq!(Mentions::Before(0).pick(&found), Some(90), "the newest");
assert_eq!(Mentions::Before(70).pick(&found), Some(50));
assert_eq!(Mentions::After(70).pick(&found), Some(90));
assert_eq!(Mentions::After(90).pick(&found), None);
assert_eq!(Mentions::Before(30).pick(&found), None);
}
#[test]
fn a_mention_is_not_read_under_a_popup_while_away_or_in_a_secret_chat() {
let mut app = test_app("mentions-unseen");
app.focus = Focus::Messages;
let id = message_ids(&app)[2];
let open = app.open.as_mut().unwrap();
open.selected = Some(id);
open.messages.get_mut(&id).unwrap().mention = true;
assert_eq!(app.mention_seen(), Some(id));
app.chat_info = Some(ChatInfo::new(1));
assert_eq!(app.mention_seen(), None, "a popup is over it");
app.chat_info = None;
app.terminal_focused = false;
assert_eq!(app.mention_seen(), None, "nobody is there");
app.terminal_focused = true;
app.focus = Focus::Input;
assert_eq!(app.mention_seen(), None, "writing");
app.focus = Focus::Messages;
app.open.as_mut().unwrap().loading = Some(Page::Around(id));
assert_eq!(app.mention_seen(), None, "on its way elsewhere");
app.open.as_mut().unwrap().loading = None;
app.open
.as_mut()
.unwrap()
.messages
.get_mut(&id)
.unwrap()
.unplayed = true;
assert_eq!(app.mention_seen(), None, "not played");
let chat = app.open.as_ref().unwrap().chat_id;
app.on_update(Update::ChatUnreadMentionCount(
tdlib_rs::types::UpdateChatUnreadMentionCount {
chat_id: chat,
unread_mention_count: 0,
},
));
assert!(!app.open.as_ref().unwrap().messages[&id].mention);
let mut app = test_app("mentions-secret");
open_chardy(&mut app, Some(SecretState::Ready));
app.focus = Focus::Messages;
let open = app.open.as_mut().unwrap();
open.add_page(Page::Latest, crate::messages::tests::page([1, 2, 3]));
open.messages.get_mut(&2).unwrap().mention = true;
open.selected = Some(2);
assert_eq!(app.mention_seen(), None);
}
#[test]
fn nothing_is_read_under_the_info_popup_or_in_a_topic_not_known_yet() {
let mut app = test_app("info-read");
app.focus = Focus::Messages;
let chat = app.open.as_ref().unwrap().chat_id;
assert!(app.watching(chat));
app.chat_info = Some(ChatInfo::new(chat));
assert!(!app.watching(chat));
app.chat_info = None;
crate::demo::show_forum(&mut app);
app.focus = Focus::Messages;
let (forum, topic) = app.open.as_ref().unwrap().place();
assert!(app.watching(forum), "a topic that's loaded");
app.open.as_mut().unwrap().topic = topic.map(|t| t + 100);
assert!(!app.watching(forum));
}
#[test]
fn i_is_about_the_chat_under_the_cursor_or_the_one_open_and_goes_down_its_members() {
let mut app = test_app("info");
let none = KeyModifiers::NONE;
app.focus = Focus::Chats;
let listed = app.selected.unwrap();
assert_eq!(app.info_chat(), Some(listed));
app.focus = Focus::Messages;
let open = app.open.as_ref().map(|o| o.chat_id);
assert_eq!(app.info_chat(), open);
app.chat_info = Some(ChatInfo::new(listed));
assert!(app.busy(), "it takes the keys");
let member = |id| crate::info::Member {
who: Sender::User(id),
role: crate::info::Role::Member,
title: String::new(),
};
let about = crate::info::About {
roster: crate::info::Roster::All((1..=3).map(member).collect()),
..Default::default()
};
app.on_tg(TgEvent::ChatInfo {
chat_id: listed + 1,
about: None,
});
assert!(!app.chat_info.as_ref().unwrap().failed, "another chat's");
app.on_tg(TgEvent::ChatInfo {
chat_id: listed,
about: Some(Box::new(about)),
});
let current = |app: &App| app.chat_info.as_ref().unwrap().current().map(|m| m.who);
press(&mut app, KeyCode::Char('j'), none);
assert_eq!(current(&app), Some(Sender::User(2)));
press(&mut app, KeyCode::Char('G'), none);
assert_eq!(current(&app), Some(Sender::User(3)));
press(&mut app, KeyCode::Char('g'), none);
assert_eq!(current(&app), Some(Sender::User(1)));
let rows = screen(&mut app);
assert!(rows.iter().any(|r| r.contains("Members (3)")), "{rows:#?}");
let file = std::env::temp_dir().join("tuigram-test-info-drop.txt");
std::fs::write(&file, "notes").unwrap();
app.on_terminal_event(Event::Paste(file.display().to_string()));
assert!(app.focus == Focus::Messages, "not Insert mode");
assert!(app.open.as_ref().unwrap().attachments.is_empty());
press(&mut app, KeyCode::Esc, none);
assert!(app.chat_info.is_none());
assert!(app.focus == Focus::Messages);
crate::demo::show_forum(&mut app);
app.focus = Focus::Topics;
assert_eq!(app.info_chat(), app.forum.as_ref().map(|f| f.chat_id));
}
fn russian_app(tag: &str) -> App {
let mut app = test_app(tag);
app.settings.language = "ru".into();
crate::lang::set(crate::lang::Lang::Ru);
app
}
#[test]
fn in_russian_the_status_bar_says_what_went_wrong_in_russian() {
crate::lang::set(crate::lang::Lang::Ru);
let mut app = russian_app("ru-status");
command(&mut app, "nope");
assert_eq!(app.status.as_deref(), Some("Нет такой команды: nope"));
let rows = screen_of(&mut app, 600);
assert!(
rows[19].contains("Нет такой команды: nope"),
"{:?}",
rows[19]
);
app.on_update(Update::ConnectionState(
tdlib_rs::types::UpdateConnectionState {
state: ConnectionState::WaitingForNetwork,
},
));
let rows = screen(&mut app);
assert!(
rows[19].starts_with(" ОБЫЧНЫЙ Ожидание сети…"),
"{:?}",
rows[19]
);
crate::lang::set(crate::lang::Lang::En);
}
#[test]
fn in_russian_a_toast_says_what_was_done() {
crate::lang::set(crate::lang::Lang::Ru);
let mut app = russian_app("ru-toast");
app.focus = Focus::Chats;
app.chats.refresh();
app.selected = app.chats.ids().first().copied();
press(&mut app, KeyCode::Char('a'), KeyModifiers::NONE);
assert_eq!(
app.toast.as_ref().map(|t| t.title.as_str()),
Some("Перенесено в архив")
);
crate::lang::set(crate::lang::Lang::En);
}
#[test]
fn in_russian_a_disguised_link_asks_with_the_site_on_its_own_line_and_lined_up() {
crate::lang::set(crate::lang::Lang::Ru);
let mut app = russian_app("ru-link");
app.open_link_outside(Link {
url: "https://shop.example/pay".into(),
disguise: Some("Мой банк".into()),
});
let confirm = app.confirm.as_ref().expect("asks first");
assert_eq!(confirm.title, "Открыть ссылку?");
assert_eq!(confirm.action.verb(), "открыть");
let rows = screen(&mut app);
let at = |label: &str| {
let row = rows.iter().find(|r| r.contains(label)).expect(label);
let (before, after) = row.split_once(label).unwrap();
let gap = after.chars().take_while(|&c| c == ' ').count();
before.chars().count() + label.chars().count() + gap
};
let column = at("В тексте:");
assert_eq!(at("Ведёт на:"), column);
assert_eq!(at("Полный адрес:"), column);
let text = rows.iter().position(|r| r.contains("Мой банк")).unwrap();
assert!(rows[text + 1].contains("shop.example"), "{rows:#?}");
assert!(
rows[text + 2].contains("https://shop.example/pay"),
"{rows:#?}"
);
crate::lang::set(crate::lang::Lang::En);
}
#[test]
fn in_russian_logging_out_asks_in_russian_line_by_line() {
crate::lang::set(crate::lang::Lang::Ru);
let mut app = russian_app("ru-logout");
command(&mut app, "logout");
let confirm = app.confirm.as_ref().expect("asks");
assert_eq!(confirm.title, "Выйти из аккаунта?");
assert_eq!(confirm.lines.len(), 4);
let rows = screen(&mut app).join("\n");
assert!(rows.contains(" Выйти из аккаунта? "), "{rows}");
assert!(rows.contains("Сеанс в Telegram завершится"), "{rows}");
assert!(rows.contains("понадобятся код и пароль"), "{rows}");
assert!(rows.contains("Секретные чаты тоже пропадут"), "{rows}");
crate::lang::set(crate::lang::Lang::En);
}
#[test]
fn in_russian_an_invite_counts_its_members_as_russian_does() {
crate::lang::set(crate::lang::Lang::Ru);
let mut app = russian_app("ru-invite");
let invite = |members, channel, by_request| Invite {
title: "Hikers".into(),
members,
channel,
badge: None,
by_request,
};
app.confirm_invite(
"https://t.me/+x".into(),
"x".into(),
invite(21, true, false),
);
let confirm = app.confirm.take().unwrap();
assert_eq!(confirm.title, "Подписаться на канал?");
assert_eq!(confirm.lines, ["Hikers", "Канал, 21 подписчик."]);
assert_eq!(confirm.action.verb(), "подписаться", "as the title asks");
app.confirm_invite("https://t.me/+x".into(), "x".into(), invite(3, false, true));
let confirm = app.confirm.take().unwrap();
assert_eq!(confirm.title, "Подать заявку на вступление в группу?");
assert_eq!(confirm.action.verb(), "вступить");
assert_eq!(
confirm.lines,
[
"Hikers",
"Группа, 3 участника.",
"Заявку должен одобрить администратор."
]
);
crate::lang::set(crate::lang::Lang::En);
app.confirm_invite("https://t.me/+x".into(), "x".into(), invite(3, false, true));
let confirm = app.confirm.take().unwrap();
assert_eq!(confirm.title, "Ask to join this group?");
assert_eq!(
confirm.lines,
[
"Hikers",
"A group with 3 members.",
"An admin has to let you in."
]
);
}
#[test]
fn joining_says_you_are_not_in_the_chat_as_each_language_does() {
let mut app = test_app("join-words");
let chat_id = app.open.as_ref().unwrap().chat_id;
app.chats.add_local(chat_id, "Hikers", None);
let not_in = |app: &mut App, chat_id| {
app.confirm_join(chat_id);
app.confirm.take().unwrap().lines[0].clone()
};
assert_eq!(not_in(&mut app, chat_id), "You're not in Hikers.");
crate::lang::set(crate::lang::Lang::Ru);
assert_eq!(not_in(&mut app, chat_id), "Вы не участник: Hikers.");
assert_eq!(not_in(&mut app, 424242), "Вы не участник: эта группа.");
crate::lang::set(crate::lang::Lang::Vi);
assert_eq!(not_in(&mut app, chat_id), "Bạn chưa tham gia Hikers.");
assert_eq!(not_in(&mut app, 424242), "Bạn chưa tham gia nhóm này.");
app.chats.add_local(chat_id, "Hikers", None).is_channel = true;
crate::lang::set(crate::lang::Lang::Ru);
assert_eq!(not_in(&mut app, chat_id), "Вы не подписчик: Hikers.");
crate::lang::set(crate::lang::Lang::En);
assert_eq!(not_in(&mut app, chat_id), "You're not in Hikers.");
assert_eq!(not_in(&mut app, 424242), "You're not in this chat.");
}
#[test]
fn starting_a_secret_chat_asks_in_three_lines_in_each_language() {
let mut app = test_app("secret-start-words");
let lines = |app: &mut App| {
chat_with_chardy(app, None);
command(app, "secret");
app.confirm.take().expect("asks").lines
};
assert_eq!(
lines(&mut app),
[
"With Chardy. It's end-to-end encrypted, and kept only",
"on this computer and on the device of theirs that",
"accepts it: your other devices won't have it.",
]
);
crate::lang::set(crate::lang::Lang::Ru);
assert_eq!(
lines(&mut app),
[
"Собеседник: Chardy. Чат защищён сквозным шифрованием и хранится",
"только на этом компьютере и на том устройстве собеседника,",
"которое его примет: на других ваших устройствах его не будет.",
]
);
crate::lang::set(crate::lang::Lang::Vi);
assert_eq!(
lines(&mut app),
[
"Với Chardy. Được mã hóa đầu cuối và chỉ được lưu",
"trên máy tính này và trên thiết bị mà người kia",
"dùng để chấp nhận: các thiết bị khác của bạn sẽ không có.",
]
);
crate::lang::set(crate::lang::Lang::En);
}
fn vietnamese_app(tag: &str) -> App {
let mut app = test_app(tag);
app.settings.language = "vi".into();
crate::lang::set(crate::lang::Lang::Vi);
app
}
fn column_after(rows: &[String], label: &str) -> usize {
let row = rows.iter().find(|r| r.contains(label)).expect(label);
let (before, after) = row.split_once(label).unwrap();
let gap = after.chars().take_while(|&c| c == ' ').count();
before.chars().count() + label.chars().count() + gap
}
#[test]
fn in_vietnamese_the_status_bar_says_what_went_wrong_in_vietnamese() {
let mut app = vietnamese_app("vi-status");
command(&mut app, "nope");
assert_eq!(app.status.as_deref(), Some("Không có lệnh: nope"));
app.on_update(Update::ConnectionState(
tdlib_rs::types::UpdateConnectionState {
state: ConnectionState::WaitingForNetwork,
},
));
let rows = screen(&mut app);
assert!(rows[19].contains("Đang chờ mạng…"), "{:?}", rows[19]);
crate::lang::set(crate::lang::Lang::En);
}
#[test]
fn in_vietnamese_a_disguised_link_and_a_proxy_ask_with_their_labels_lined_up() {
let mut app = vietnamese_app("vi-link");
app.open_link_outside(Link {
url: "https://shop.example/pay".into(),
disguise: Some("Ngân hàng của tôi".into()),
});
let confirm = app.confirm.as_ref().expect("asks first");
assert_eq!(confirm.title, "Mở liên kết này?");
assert_eq!(confirm.action.verb(), "mở");
let rows = screen(&mut app);
let column = column_after(&rows, "Văn bản ghi:");
assert_eq!(column_after(&rows, "Dẫn đến:"), column);
assert_eq!(column_after(&rows, "Địa chỉ thật:"), column);
let text = rows
.iter()
.position(|r| r.contains("Ngân hàng của tôi"))
.unwrap();
assert!(rows[text + 1].contains("shop.example"), "{rows:#?}");
assert!(
rows[text + 2].contains("https://shop.example/pay"),
"{rows:#?}"
);
app.confirm = None;
app.ask_to_use_proxy("socks5://10.0.0.1:1080");
let confirm = app.confirm.as_ref().expect("asks first");
assert_eq!(confirm.title, "Dùng proxy này?");
let rows = screen(&mut app);
assert_eq!(
column_after(&rows, "Proxy:"),
column_after(&rows, "Máy chủ:")
);
crate::lang::set(crate::lang::Lang::En);
}
#[test]
fn in_vietnamese_logging_out_asks_line_by_line() {
let mut app = vietnamese_app("vi-logout");
command(&mut app, "logout");
let confirm = app.confirm.as_ref().expect("asks");
assert_eq!(confirm.title, "Đăng xuất?");
assert_eq!(confirm.lines.len(), 4);
let rows = screen(&mut app).join("\n");
assert!(rows.contains(" Đăng xuất? "), "{rows}");
assert!(rows.contains("Phiên trên Telegram sẽ kết thúc"), "{rows}");
assert!(rows.contains("cần mã, và mật khẩu"), "{rows}");
assert!(
rows.contains("Các cuộc trò chuyện bí mật cũng mất"),
"{rows}"
);
crate::lang::set(crate::lang::Lang::En);
}
#[test]
fn in_vietnamese_an_invite_says_what_it_is_whatever_the_count() {
let mut app = vietnamese_app("vi-invite");
let invite = |members, channel, by_request| Invite {
title: "Hikers".into(),
members,
channel,
badge: None,
by_request,
};
app.confirm_invite(
"https://t.me/+x".into(),
"x".into(),
invite(21, true, false),
);
let confirm = app.confirm.take().unwrap();
assert_eq!(confirm.title, "Tham gia kênh này?");
assert_eq!(confirm.lines, ["Hikers", "Kênh có 21 người đăng ký."]);
app.confirm_invite("https://t.me/+x".into(), "x".into(), invite(1, false, true));
let confirm = app.confirm.take().unwrap();
assert_eq!(confirm.title, "Gửi yêu cầu tham gia nhóm này?");
assert_eq!(
confirm.lines,
[
"Hikers",
"Nhóm có 1 thành viên.",
"Quản trị viên phải duyệt cho bạn vào."
]
);
crate::lang::set(crate::lang::Lang::En);
}
}