tuigram-cli 1.10.0

Telegram in your terminal: a fast, vim-style Telegram client built on TDLib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
//! `/` search: matching text against a query, and the state of a message
//! search in the open chat, with the filters it can take (`from:@alice
//! has:photo before:2025-10-01`).

use std::ops::Range;

use chrono::{Local, NaiveDate};
use tdlib_rs::enums::SearchMessagesFilter;

use crate::lang;
use crate::messages::{Msg, Sender};
use crate::tg::Found;

/// What a `/` search in a chat asks TDLib for: its words, and the filters
/// typed with them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Query {
    /// The words to find, without the filters; what's highlighted.
    pub words: String,
    /// `from:`: who sent it.
    pub from: Option<Who>,
    /// `has:`: what's in it.
    pub has: Option<Has>,
    /// `before:`: sent before this unix time, the start of the day typed.
    pub before: Option<i32>,
    /// `after:`: sent at this unix time or later, the start of the day
    /// typed, so that day counts.
    pub after: Option<i32>,
}

/// Who `from:` means. The app turns `Me` and `Name` into a sender, and a
/// username it knows too; TDLib looks up the rest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Who {
    Me,
    /// `from:Alice`: someone whose name has this in it, among the senders
    /// of the messages loaded.
    Name(String),
    /// `from:@alice`, without the @.
    Username(String),
    Sender(Sender),
}

/// What `has:` looks for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Has {
    Photo,
    Video,
    /// Photos and videos.
    Media,
    File,
    Link,
    Voice,
    /// A video message: the round ones.
    Note,
    Gif,
    Audio,
}

impl Has {
    /// Every kind, by the word `has:` takes.
    pub const ALL: [(&'static str, Has); 9] = [
        ("photo", Has::Photo),
        ("video", Has::Video),
        ("media", Has::Media),
        ("file", Has::File),
        ("link", Has::Link),
        ("voice", Has::Voice),
        ("note", Has::Note),
        ("gif", Has::Gif),
        ("audio", Has::Audio),
    ];

    pub fn tdlib(self) -> SearchMessagesFilter {
        match self {
            Has::Photo => SearchMessagesFilter::Photo,
            Has::Video => SearchMessagesFilter::Video,
            Has::Media => SearchMessagesFilter::PhotoAndVideo,
            Has::File => SearchMessagesFilter::Document,
            Has::Link => SearchMessagesFilter::Url,
            Has::Voice => SearchMessagesFilter::VoiceNote,
            Has::Note => SearchMessagesFilter::VideoNote,
            Has::Gif => SearchMessagesFilter::Animation,
            Has::Audio => SearchMessagesFilter::Audio,
        }
    }
}

/// The filters a search takes, as typed.
pub const FILTERS: [&str; 4] = ["from:", "has:", "before:", "after:"];

/// Reads a `/` search typed in a chat: filters anywhere among the words,
/// each at most once. Says what's wrong with one that can't be read.
pub fn parse(typed: &str) -> Result<Query, String> {
    let mut query = Query::default();
    let mut words = Vec::new();
    let mut seen = Vec::new();
    for token in typed.split_whitespace() {
        let lower = token.to_lowercase();
        let Some(key) = FILTERS.into_iter().find(|f| lower.starts_with(f)) else {
            words.push(token);
            continue;
        };
        let value = &token[key.len()..];
        if seen.contains(&key) {
            return Err(lang::f("Only one {key} at a time", &[("key", &key)]));
        }
        seen.push(key);
        match key {
            // `from:this` is everyone in the chat the search is in: no
            // sender filter at all.
            "from:" if value.eq_ignore_ascii_case("this") => {}
            "from:" => query.from = Some(who(value)?),
            "has:" => {
                let kind = Has::ALL
                    .into_iter()
                    .find(|(name, _)| value.eq_ignore_ascii_case(name))
                    .ok_or(lang::t(
                        "has: takes photo, video, media, file, link, voice, note, gif or audio",
                    ))?;
                query.has = Some(kind.1);
            }
            "before:" => query.before = Some(day_start(value)?),
            _ => query.after = Some(day_start(value)?),
        }
    }
    query.words = words.join(" ");
    if query.words.is_empty() && query.from.is_none() && query.has.is_none() {
        return Err(lang::t("Add words, from: or has: to search for").into());
    }
    if let (Some(before), Some(after)) = (query.before, query.after)
        && after >= before
    {
        return Err(lang::t("after: has to be a day before before:").into());
    }
    Ok(query)
}

fn who(value: &str) -> Result<Who, String> {
    match value {
        "" | "@" => Err(lang::t("from: takes me, @username or a name, like from:@alice").into()),
        _ if value.eq_ignore_ascii_case("me") => Ok(Who::Me),
        _ => Ok(match value.strip_prefix('@') {
            Some(name) => Who::Username(name.to_string()),
            None => Who::Name(value.to_string()),
        }),
    }
}

/// The start of a day typed like 2025-10-01, in local time, as a unix time.
fn day_start(value: &str) -> Result<i32, String> {
    let wrong = || {
        lang::f(
            "Dates are like 2025-10-01, not \"{value}\"",
            &[("value", &value)],
        )
    };
    let day = NaiveDate::parse_from_str(value, "%Y-%m-%d").map_err(|_| wrong())?;
    let midnight = day.and_hms_opt(0, 0, 0).ok_or_else(wrong)?;
    let start = crate::schedule::moment(&Local, midnight).ok_or_else(wrong)?;
    i32::try_from(start.timestamp()).map_err(|_| wrong())
}

/// What Tab can put in place of the last word of a search typed so far,
/// each as the whole search: a filter's name, what `has:` takes, one of
/// `people` (`me`, `@username`s) after `from:`, or `today` after
/// `before:` and `after:`.
pub fn complete(typed: &str, people: &[String], today: &str) -> Vec<String> {
    // After the last space, which may be wider than a byte (a no-break
    // space).
    let start = typed
        .char_indices()
        .rev()
        .find(|(_, c)| c.is_whitespace())
        .map_or(0, |(i, c)| i + c.len_utf8());
    let (head, word) = typed.split_at(start);
    let lower = word.to_lowercase();
    let with = |key: &str, values: Vec<&str>| -> Vec<String> {
        let typed = lower[key.len()..].to_string();
        values
            .into_iter()
            .filter(|v| v.to_lowercase().starts_with(&typed))
            .map(|v| format!("{head}{key}{v}"))
            .collect()
    };
    match FILTERS.into_iter().find(|f| lower.starts_with(f)) {
        Some("has:") => with("has:", Has::ALL.iter().map(|(name, _)| *name).collect()),
        Some("from:") => with("from:", people.iter().map(String::as_str).collect()),
        Some(key) if lower == key => vec![format!("{head}{key}{today}")],
        Some(_) => Vec::new(),
        None => FILTERS
            .into_iter()
            .filter(|f| f.starts_with(&lower))
            .map(|f| format!("{head}{f}"))
            .collect(),
    }
}

/// Byte ranges of `text` where `query` appears, ignoring case. In order and
/// non-overlapping. An empty query matches nothing.
pub fn find(text: &str, query: &str) -> Vec<Range<usize>> {
    let query: Vec<char> = query.chars().flat_map(char::to_lowercase).collect();
    let mut out = Vec::new();
    if query.is_empty() {
        return out;
    }
    let mut next_free = 0;
    for (start, _) in text.char_indices() {
        if start < next_free {
            continue;
        }
        if let Some(end) = match_at(text, start, &query) {
            out.push(start..end);
            next_free = end;
        }
    }
    out
}

/// Where a match of the (lowercased) query starting at byte `start` ends.
fn match_at(text: &str, start: usize, query: &[char]) -> Option<usize> {
    let mut want = query.iter();
    let mut next = want.next();
    for (i, c) in text[start..].char_indices() {
        // Some characters lowercase to several, e.g. 'İ'.
        for lower in c.to_lowercase() {
            match next {
                Some(&q) if q == lower => next = want.next(),
                Some(_) => return None,
                None => break,
            }
        }
        if next.is_none() {
            return Some(start + i + c.len_utf8());
        }
    }
    None
}

/// A `/` search in the open chat. TDLib searches the whole history and
/// returns matches newest first, a page at a time.
pub struct MessageSearch {
    /// The search as typed, filters and all, for the pane's title and to
    /// match TDLib's answers.
    pub query: String,
    /// What TDLib is asked for.
    pub ask: Query,
    /// Matching message ids, newest first, as far as fetched.
    pub results: Vec<i64>,
    /// Index into `results` of the match the cursor was sent to.
    pub current: Option<usize>,
    /// TDLib's estimate of how many messages match; -1 if it doesn't know.
    total: i32,
    /// Where the next page of results starts.
    pub next_from: i64,
    /// Or this, for words found in a secret chat.
    pub next_offset: String,
    /// Every match has been fetched.
    pub done: bool,
    /// A page of results is being fetched.
    pub loading: bool,
    /// The match to go to once the page being fetched arrives.
    pub wanted: Option<usize>,
}

impl MessageSearch {
    pub fn new(query: String, ask: Query) -> Self {
        Self {
            query,
            ask,
            results: Vec::new(),
            current: None,
            total: -1,
            next_from: 0,
            next_offset: String::new(),
            done: false,
            loading: false,
            wanted: None,
        }
    }

    pub fn add(&mut self, found: Found) {
        for id in found.ids {
            if !self.results.contains(&id) {
                self.results.push(id);
            }
        }
        self.total = found.total;
        self.next_from = found.next_from;
        self.next_offset = found.next_offset;
        // Neither means no more pages.
        self.done = self.next_from == 0 && self.next_offset.is_empty();
    }

    /// "3 of 41" for the pane title, or "searching…" before the first match.
    pub fn position(&self) -> String {
        match self.current {
            Some(i) => {
                let total = (self.total.max(0) as usize).max(self.results.len());
                format!("{} {} {total}", i + 1, lang::t("of"))
            }
            None => lang::t("searching…").into(),
        }
    }
}

/// One match in the media browser: what a `/` search with `has:` lists.
pub struct MediaRow {
    pub id: i64,
    /// What it holds: the file's name, "Photo", "Video message"…
    pub label: String,
    pub sender: Sender,
    pub outgoing: bool,
    pub date: i32,
    /// Its file's number, for `O` to show it in the file manager: none for
    /// what Enter wouldn't open or `y` wouldn't copy.
    pub file_id: Option<i32>,
    /// The file is on this computer already.
    pub downloaded: bool,
    /// Its photo or its video's thumbnail, for the grid's cell. None for
    /// what shows none (a video TDLib couldn't take one of), or seen only
    /// while open.
    pub preview: Option<crate::messages::Preview>,
    /// The preview is cut to a circle: a video message's still.
    pub round: bool,
}

impl MediaRow {
    fn of(message: tdlib_rs::types::Message) -> Self {
        let id = message.id;
        Self::of_msg(id, &Msg::from(message))
    }

    fn of_msg(id: i64, msg: &Msg) -> Self {
        let label = if msg.video.is_some() {
            lang::t("Video message").into()
        } else if msg.voice.is_some() {
            lang::t("Voice message").into()
        } else if let Some(file) = &msg.file {
            file.label.clone()
        } else if msg.photo.is_some() {
            lang::t("Photo").into()
        } else {
            msg.snippet()
        };
        Self {
            id,
            label,
            sender: msg.sender,
            outgoing: msg.outgoing,
            date: msg.date,
            file_id: crate::app::openable_file(msg)
                .filter(|_| crate::viewer::cant_copy(msg).is_none())
                .map(|f| f.id),
            downloaded: msg.file.as_ref().is_some_and(|f| f.downloaded),
            preview: msg.preview.clone(),
            round: msg.video.is_some(),
        }
    }
}

/// Columns the media browser's grid of previews starts with; `-` and `=`
/// change them between GRID_MIN_COLUMNS and GRID_MAX_COLUMNS.
pub const GRID_DEFAULT_COLUMNS: usize = 4;
/// The fewest columns the grid takes.
pub const GRID_MIN_COLUMNS: usize = 3;
/// The most columns the grid takes.
pub const GRID_MAX_COLUMNS: usize = 5;

/// The media browser: every match of a `/` search with `has:` in one
/// list, paged from Telegram until done. Enter goes to the message.
pub struct MediaMenu {
    /// The search as typed, to match TDLib's answers and for the title.
    pub query: String,
    /// What TDLib is asked for.
    pub ask: Query,
    /// Matches, newest first, as far as fetched.
    pub rows: Vec<MediaRow>,
    pub selected: usize,
    /// TDLib's estimate of how many match in all; -1 if unknown.
    pub total: i32,
    /// Where the next page of results starts.
    pub next_from: i64,
    /// Or this, for words found in a secret chat.
    pub next_offset: String,
    /// Every match has been fetched.
    pub done: bool,
    /// A page of results is being fetched.
    pub loading: bool,
    /// Why the search failed, if it did: shown in the window.
    pub error: Option<String>,
    /// Columns the grid was last drawn with; 0 before that, and in the
    /// list the other `has:` filters get.
    pub grid_columns: usize,
    /// Cells of the grid per page in the last draw.
    pub grid_page: usize,
}

impl MediaMenu {
    pub fn new(query: String, ask: Query) -> Self {
        Self {
            query,
            ask,
            rows: Vec::new(),
            selected: 0,
            total: -1,
            next_from: 0,
            next_offset: String::new(),
            done: false,
            loading: false,
            error: None,
            grid_columns: 0,
            grid_page: 0,
        }
    }

    pub fn add(&mut self, found: Found) {
        self.total = found.total;
        self.next_from = found.next_from;
        self.next_offset = found.next_offset;
        // Neither means no more pages.
        self.done = self.next_from == 0 && self.next_offset.is_empty();
        for message in found.messages {
            if self.rows.iter().any(|r| r.id == message.id) {
                continue;
            }
            self.rows.push(MediaRow::of(message));
        }
        // Newest at the top, however the pages came in.
        self.rows
            .sort_by(|a, b| b.date.cmp(&a.date).then(b.id.cmp(&a.id)));
    }

    /// Down (`delta` > 0) or up the list.
    pub fn move_by(&mut self, delta: isize) {
        if self.rows.is_empty() {
            return;
        }
        self.selected = self
            .selected
            .saturating_add_signed(delta)
            .min(self.rows.len() - 1);
    }

    /// The first or the last row.
    pub fn jump(&mut self, last: bool) {
        if self.rows.is_empty() {
            return;
        }
        self.selected = if last { self.rows.len() - 1 } else { 0 };
    }

    /// The row under the cursor.
    pub fn current(&self) -> Option<&MediaRow> {
        self.rows.get(self.selected)
    }

    /// True for the filters the grid of previews shows: photos, videos
    /// and video messages. The terminal has its say too
    /// (`Images::draws_photos`): every check for the grid is this and it.
    pub fn wants_grid(&self) -> bool {
        matches!(
            self.ask.has,
            Some(Has::Photo | Has::Video | Has::Media | Has::Note)
        )
    }

    /// Down (`delta` > 0) or up the grid: by a row (`by` columns) or a
    /// page of it. The cursor stops at the last match, however short the
    /// last row is.
    pub fn move_by_grid(&mut self, by: usize, delta: isize) {
        self.move_by(delta.saturating_mul(by.max(1) as isize));
    }

    /// The page the cursor is on and how many pages there are, 1-based,
    /// for the title.
    pub fn page(&self) -> (usize, usize) {
        let size = self.grid_page.max(1);
        (
            self.selected / size + 1,
            self.rows.len().div_ceil(size).max(1),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn found<'a>(text: &'a str, query: &str) -> Vec<&'a str> {
        find(text, query).into_iter().map(|r| &text[r]).collect()
    }

    #[test]
    fn matches_ignore_case_and_keep_the_original_text() {
        assert_eq!(
            found("Hello hello HELLO", "hello"),
            ["Hello", "hello", "HELLO"]
        );
        assert_eq!(found("Café au lait", "CAFÉ"), ["Café"]);
        assert_eq!(found("aaaa", "aa"), ["aa", "aa"], "no overlaps");
        assert!(found("abc", "").is_empty());
        assert!(found("abc", "abcd").is_empty());
    }

    #[test]
    fn ranges_are_byte_ranges_around_wide_characters() {
        let text = "🎉 Đà Nẵng 🎉";
        assert_eq!(found(text, "nẵng"), ["Nẵng"]);
        // 'İ' lowercases to two characters; the match still ends on a char boundary.
        assert_eq!(found("İstanbul", "i̇st"), ["İst"]);
    }

    #[test]
    fn the_media_browser_offers_no_file_enter_or_y_would_keep_back() {
        let (_, mut msg) = crate::messages::tests::page([1]).remove(0);
        msg.file = Some(crate::messages::MediaFile {
            id: 9,
            label: "File: map.pdf".into(),
            photo: false,
            downloaded: true,
        });
        assert_eq!(MediaRow::of_msg(1, &msg).file_id, Some(9));
        msg.saveable = false;
        assert_eq!(MediaRow::of_msg(1, &msg).file_id, None, "can't be saved");
        msg.saveable = true;
        msg.destruct = Some(crate::secret::Destruct {
            after: 10,
            on_open: true,
            ends: None,
        });
        assert_eq!(
            MediaRow::of_msg(1, &msg).file_id,
            None,
            "seen only while open"
        );
    }

    #[test]
    fn the_media_browser_moves_by_rows() {
        let mut menu = MediaMenu::new("has:file".into(), parse("has:file").unwrap());
        assert!(menu.current().is_none());
        menu.move_by(1);
        menu.jump(true);

        let row = |id| MediaRow {
            id,
            label: format!("file {id}"),
            sender: Sender::User(1),
            outgoing: false,
            date: 0,
            file_id: Some(id as i32),
            downloaded: false,
            preview: None,
            round: false,
        };
        menu.rows = vec![row(9), row(7), row(5)];
        assert_eq!(menu.current().unwrap().id, 9);
        menu.move_by(1);
        assert_eq!(menu.current().unwrap().id, 7);
        menu.move_by(10);
        assert_eq!(menu.current().unwrap().id, 5, "no further than the last");
        menu.move_by(-10);
        assert_eq!(menu.current().unwrap().id, 9, "no further than the first");
        menu.jump(true);
        assert_eq!(menu.current().unwrap().id, 5);
        menu.jump(false);
        assert_eq!(menu.current().unwrap().id, 9);
    }

    #[test]
    fn a_search_of_photos_and_videos_wants_the_grid() {
        for words in ["has:photo", "has:video", "has:media", "has:note"] {
            let menu = MediaMenu::new(words.into(), parse(words).unwrap());
            assert!(menu.wants_grid(), "{words}");
        }
        for words in ["has:file", "has:gif", "cats"] {
            let menu = MediaMenu::new(words.into(), parse(words).unwrap());
            assert!(!menu.wants_grid(), "{words}");
        }
    }

    #[test]
    fn the_media_grid_moves_by_rows_and_pages() {
        let mut menu = MediaMenu::new("has:photo".into(), parse("has:photo").unwrap());
        let row = |id| MediaRow {
            id,
            label: format!("photo {id}"),
            sender: Sender::User(1),
            outgoing: false,
            date: 0,
            file_id: None,
            downloaded: false,
            preview: None,
            round: false,
        };
        menu.rows = (1..=10).map(row).collect();
        menu.grid_columns = 3;
        menu.grid_page = 6; // 3 columns of 2 rows

        // Down a row from the second cell of the first.
        menu.selected = 1;
        menu.move_by_grid(menu.grid_columns, 1);
        assert_eq!(menu.selected, 4);
        menu.move_by_grid(menu.grid_columns, -1);
        assert_eq!(menu.selected, 1);

        // The last row is short (10 = 3 full rows and 1): down from its
        // cell stops on the last match.
        menu.selected = 9;
        menu.move_by_grid(menu.grid_columns, 1);
        assert_eq!(menu.selected, 9);
        menu.selected = 7;
        menu.move_by_grid(menu.grid_columns, 1);
        assert_eq!(menu.selected, 9, "clamped, not past the end");

        // Pages: 6 cells each, so two of them.
        assert_eq!(menu.page(), (2, 2));
        menu.selected = 0;
        menu.move_by_grid(menu.grid_page, 1);
        assert_eq!(menu.selected, 6);
        assert_eq!(menu.page(), (2, 2));
        menu.move_by_grid(menu.grid_page, 1);
        assert_eq!(menu.selected, 9, "no page past the last match");
        menu.move_by_grid(menu.grid_page, -1);
        assert_eq!(menu.selected, 3, "a page up, not the start of one");
        menu.selected = 0;
        assert_eq!(menu.page(), (1, 2));
    }

    #[test]
    fn a_media_row_keeps_its_messages_preview() {
        let (_, mut msg) = crate::messages::tests::page([1]).remove(0);
        assert!(MediaRow::of_msg(1, &msg).preview.is_none());
        msg.preview = Some(crate::messages::Preview {
            file_id: 7,
            width: 800,
            height: 600,
            thumbnail: None,
            sticker: false,
        });
        let row = MediaRow::of_msg(1, &msg);
        assert_eq!(row.preview.as_ref().map(|p| p.file_id), Some(7));
    }

    #[test]
    fn from_this_is_everyone_here() {
        let query = parse("has:file").unwrap();
        assert_eq!(query.has, Some(Has::File));
        assert_eq!(query.from, None);

        // Everyone in the chat the search is in: no sender filter.
        let query = parse("has:file from:this").unwrap();
        assert_eq!(query.has, Some(Has::File));
        assert_eq!(query.from, None);

        let query = parse("has:Video from:@Maya").unwrap();
        assert_eq!(query.has, Some(Has::Video));
        assert_eq!(query.from, Some(Who::Username("Maya".into())));
    }

    #[test]
    fn filters_mix_with_the_words_in_any_order() {
        let query = parse("trail FROM:@Maya has:Photo before:2025-10-01 map").unwrap();
        assert_eq!(query.words, "trail map");
        assert_eq!(query.from, Some(Who::Username("Maya".into())));
        assert_eq!(query.has, Some(Has::Photo));
        let day = |s| day_start(s).unwrap();
        assert_eq!(query.before, Some(day("2025-10-01")));
        assert_eq!(day("2025-10-02") - day("2025-10-01"), 86_400);

        assert_eq!(parse("from:me").unwrap().from, Some(Who::Me));
        assert_eq!(
            parse("from:Alice").unwrap().from,
            Some(Who::Name("Alice".into()))
        );
        let both = parse("has:media after:2025-09-01 before:2025-10-01").unwrap();
        assert_eq!(both.after, Some(day("2025-09-01")));
        assert_eq!(
            parse("12:30 http://x.com").unwrap().words,
            "12:30 http://x.com"
        );
    }

    #[test]
    fn a_filter_that_cant_be_read_says_why() {
        let why = |typed| parse(typed).unwrap_err();
        assert_eq!(why("has:photo has:video"), "Only one has: at a time");
        assert!(why("has:sticker").starts_with("has: takes photo"));
        assert!(why("from: hi").starts_with("from: takes me"));
        assert_eq!(
            why("hi before:10/01/2025"),
            "Dates are like 2025-10-01, not \"10/01/2025\""
        );
        assert_eq!(
            why("before:2025-10-01"),
            "Add words, from: or has: to search for"
        );
        assert!(why("hi after:2025-10-01 before:2025-10-01").starts_with("after: has to be"));
    }

    #[test]
    fn in_russian_a_filter_that_cant_be_read_says_why_in_russian() {
        crate::lang::set(crate::lang::Lang::Ru);
        let why = |typed| parse(typed).unwrap_err();
        assert_eq!(
            why("has:photo has:video"),
            "has: можно указать только один раз"
        );
        assert_eq!(
            why("hi before:10/01/2025"),
            "Даты пишутся как 2025-10-01, а не «10/01/2025»"
        );
        let mut search = MessageSearch::new("hi".into(), parse("hi").unwrap());
        assert_eq!(search.position(), "ищу…");
        search.add(Found {
            ids: vec![9, 7],
            messages: Vec::new(),
            total: 2,
            next_from: 0,
            next_offset: String::new(),
        });
        search.current = Some(0);
        assert_eq!(search.position(), "1 из 2");
    }

    #[test]
    fn in_vietnamese_a_filter_that_cant_be_read_says_why_in_vietnamese() {
        crate::lang::set(crate::lang::Lang::Vi);
        let why = |typed| parse(typed).unwrap_err();
        assert_eq!(why("has:photo has:video"), "Chỉ được dùng has: một lần");
        assert_eq!(
            why("hi before:10/01/2025"),
            "Ngày phải viết như 2025-10-01, không phải \"10/01/2025\""
        );
        let mut search = MessageSearch::new("hi".into(), parse("hi").unwrap());
        assert_eq!(search.position(), "đang tìm…");
        search.add(Found {
            ids: vec![9, 7],
            messages: Vec::new(),
            total: 2,
            next_from: 0,
            next_offset: String::new(),
        });
        search.current = Some(0);
        assert_eq!(search.position(), "1 / 2");
    }

    #[test]
    fn tab_finishes_the_last_word_with_a_filter_or_what_it_takes() {
        let people = ["me".to_string(), "@maya".to_string(), "@leo".to_string()];
        let tab = |typed| complete(typed, &people, "2026-10-07");
        assert_eq!(tab(""), ["from:", "has:", "before:", "after:"]);
        assert_eq!(tab("trail h"), ["trail has:"]);
        assert_eq!(tab("has:v"), ["has:video", "has:voice"]);
        assert_eq!(tab("from:"), ["from:me", "from:@maya", "from:@leo"]);
        assert_eq!(tab("trail from:@M"), ["trail from:@maya"]);
        assert_eq!(tab("before:"), ["before:2026-10-07"]);
        assert!(tab("before:2025").is_empty());
        assert!(tab("trail").is_empty());
        assert_eq!(
            tab("trail\u{a0}h"),
            ["trail\u{a0}has:"],
            "after a no-break space"
        );
    }

    #[test]
    fn results_pile_up_without_duplicates() {
        let mut search = MessageSearch::new("hi".into(), parse("hi").unwrap());
        assert_eq!(search.position(), "searching…");
        search.add(Found {
            ids: vec![9, 7],
            messages: Vec::new(),
            total: 3,
            next_from: 7,
            next_offset: String::new(),
        });
        assert!(!search.done);
        search.add(Found {
            ids: vec![7, 2],
            messages: Vec::new(),
            total: 3,
            next_from: 0,
            next_offset: String::new(),
        });
        assert_eq!(search.results, [9, 7, 2]);
        assert!(search.done);
        search.current = Some(1);
        assert_eq!(search.position(), "2 of 3");
    }

    #[test]
    fn a_secret_chats_search_goes_on_from_where_tdlib_says() {
        let mut search = MessageSearch::new("hi".into(), parse("hi").unwrap());
        search.add(Found {
            ids: vec![9, 7],
            messages: Vec::new(),
            total: 3,
            next_from: 0,
            next_offset: "7".into(),
        });
        assert!(!search.done, "an offset to go on from");
        assert_eq!(search.next_offset, "7");
        search.add(Found {
            ids: vec![2],
            messages: Vec::new(),
            total: 3,
            next_from: 0,
            next_offset: String::new(),
        });
        assert!(search.done);
    }
}