concord 2.4.2

A terminal user interface client for Discord
Documentation
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
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

pub fn truncate_text(value: &str, limit: usize) -> String {
    let mut chars = value.chars();
    let text: String = chars.by_ref().take(limit).collect();

    if chars.next().is_some() {
        format!("{text}...")
    } else {
        text
    }
}

pub fn truncate_display_width(value: &str, limit: usize) -> String {
    if value.width() <= limit {
        return value.to_owned();
    }

    const ELLIPSIS: &str = "...";
    let ellipsis_width = ELLIPSIS.width();
    if limit <= ellipsis_width {
        return ELLIPSIS.chars().take(limit).collect::<String>();
    }

    let text_width = limit.saturating_sub(ellipsis_width);
    let mut width = 0usize;
    let mut text = String::new();
    for grapheme in value.graphemes(true) {
        let grapheme_width = grapheme.width();
        if width.saturating_add(grapheme_width) > text_width {
            break;
        }
        text.push_str(grapheme);
        width = width.saturating_add(grapheme_width);
    }
    text.push_str(ELLIPSIS);
    text
}

pub fn truncate_display_width_from(value: &str, offset: usize, limit: usize) -> String {
    if offset == 0 {
        return truncate_display_width(value, limit);
    }
    if limit == 0 {
        return String::new();
    }

    let mut skipped_width = 0usize;
    let mut start = value.len();
    for (index, grapheme) in value.grapheme_indices(true) {
        let next_width = skipped_width.saturating_add(grapheme.width());
        if next_width > offset {
            start = index;
            break;
        }
        skipped_width = next_width;
    }

    truncate_display_width(&value[start..], limit)
}

pub(in crate::tui) fn format_byte_size(bytes: u64) -> String {
    const KIB: u64 = 1024;
    const MIB: u64 = KIB * 1024;

    if bytes >= MIB {
        format!("{:.1} MiB", bytes as f64 / MIB as f64)
    } else if bytes >= KIB {
        format!("{:.1} KiB", bytes as f64 / KIB as f64)
    } else {
        format!("{bytes} B")
    }
}

pub fn sanitize_for_display_width(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for grapheme in value.graphemes(true) {
        if grapheme.width() == 1 && grapheme_is_likely_wide_emoji(grapheme) {
            out.push('?');
        } else {
            out.push_str(grapheme);
        }
    }
    out
}

pub(crate) fn detected_urls(value: &str) -> Vec<String> {
    detected_url_ranges(value)
        .into_iter()
        .map(|(start, end)| value[start..end].to_owned())
        .collect()
}

pub(crate) fn detected_url_ranges(value: &str) -> Vec<(usize, usize)> {
    let mut ranges = Vec::new();
    let mut cursor = 0usize;

    while let Some(start) = next_url_start(value, cursor) {
        let mut end = value.len();
        for (relative_index, ch) in value[start..].char_indices().skip(1) {
            if ch.is_whitespace() || matches!(ch, '>' | ')' | ']' | '}' | '"' | '\'') {
                end = start.saturating_add(relative_index);
                break;
            }
        }

        while let Some((last_index, ch)) = value[..end].char_indices().next_back()
            && matches!(ch, '.' | ',' | '!' | '?' | ':' | ';')
            && last_index >= start
        {
            end = last_index;
        }

        if start < end {
            ranges.push((start, end));
        }
        cursor = end.max(start.saturating_add(1));
    }

    ranges
}

fn next_url_start(value: &str, cursor: usize) -> Option<usize> {
    let rest = value.get(cursor..)?;
    match (rest.find("https://"), rest.find("http://")) {
        (Some(https), Some(http)) => Some(cursor.saturating_add(https.min(http))),
        (Some(https), None) => Some(cursor.saturating_add(https)),
        (None, Some(http)) => Some(cursor.saturating_add(http)),
        (None, None) => None,
    }
}

fn grapheme_is_likely_wide_emoji(grapheme: &str) -> bool {
    grapheme.chars().any(|c| {
        let cp = c as u32;
        matches!(
            cp,
            0x2300..=0x27FF       // Misc Tech / Misc Symbols / Dingbats
            | 0x2900..=0x2BFF     // Supp Arrows-A/B, Misc Symbols & Arrows
            | 0x1F000..=0x1FFFF   // Most modern emoji blocks
        )
    })
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MentionTarget {
    User(u64),
    Role(u64),
    Channel(u64),
}

pub fn render_user_mentions<U, R, C>(
    value: &str,
    mut resolve_user_name: U,
    mut resolve_role_name: R,
    mut resolve_channel_name: C,
) -> String
where
    U: FnMut(u64) -> Option<String>,
    R: FnMut(u64) -> Option<String>,
    C: FnMut(u64) -> Option<String>,
{
    if !contains_any_mention_prefix(value) {
        return value.to_owned();
    }

    let mut rendered = String::with_capacity(value.len());
    let mut cursor = 0usize;
    while let Some(start) = next_mention_start(value, cursor) {
        rendered.push_str(&value[cursor..start]);

        let Some((end, target)) = parse_mention(value, start) else {
            rendered.push('<');
            cursor = start.saturating_add(1);
            continue;
        };

        let resolved = match target {
            MentionTarget::User(user_id) => resolve_user_name(user_id),
            MentionTarget::Role(role_id) => resolve_role_name(role_id),
            MentionTarget::Channel(channel_id) => resolve_channel_name(channel_id),
        };
        match resolved {
            Some(name) => {
                rendered.push(mention_prefix(target));
                rendered.push_str(&name);
            }
            None => rendered.push_str(&value[start..end]),
        }
        cursor = end;
    }
    rendered.push_str(&value[cursor..]);
    rendered
}

fn mention_prefix(target: MentionTarget) -> char {
    match target {
        MentionTarget::Channel(_) => '#',
        MentionTarget::User(_) | MentionTarget::Role(_) => '@',
    }
}

fn contains_any_mention_prefix(value: &str) -> bool {
    value.contains("<@") || value.contains("<#")
}

fn next_mention_start(value: &str, cursor: usize) -> Option<usize> {
    let rest = &value[cursor..];
    let user = rest.find("<@");
    let channel = rest.find("<#");
    let relative = match (user, channel) {
        (Some(a), Some(b)) => a.min(b),
        (Some(a), None) => a,
        (None, Some(b)) => b,
        (None, None) => return None,
    };
    Some(cursor.saturating_add(relative))
}

const CUSTOM_EMOJI_CDN_BASE: &str = "https://cdn.discordapp.com/emojis";

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct RenderedText {
    pub text: String,
    pub highlights: Vec<TextHighlight>,
    pub emoji_slots: Vec<InlineEmojiSlot>,
}

/// `byte_start..byte_start+byte_len` holds the `:name:` textual fallback.
/// the renderer overwrites it with spaces and blits the image only once the
/// cache has a protocol for `url`. `display_width` equals `byte_len` because
/// Discord emoji names are ASCII-only.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InlineEmojiSlot {
    pub byte_start: usize,
    pub byte_len: usize,
    pub display_width: u16,
    pub url: String,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TextHighlight {
    pub start: usize,
    pub end: usize,
    pub kind: TextHighlightKind,
}

/// Style class for an inline mention or link highlight.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TextHighlightKind {
    /// The current user is being notified (`<@me>`, `@everyone`, `@here`).
    SelfMention,
    /// Some other user or channel is being mentioned.
    OtherMention,
    /// A role mention with a nonzero Discord RGB role color.
    RoleMention {
        color: u32,
        notifies_current_user: bool,
    },
    /// A detected URL that can be opened from message actions.
    Url,
}

pub fn render_user_mentions_with_highlights<U, R, C, H>(
    value: &str,
    mut resolve_user_name: U,
    mut resolve_role_name: R,
    mut resolve_channel_name: C,
    mut highlight_kind: H,
) -> RenderedText
where
    U: FnMut(u64) -> Option<String>,
    R: FnMut(u64) -> Option<String>,
    C: FnMut(u64) -> Option<String>,
    H: FnMut(MentionTarget) -> Option<TextHighlightKind>,
{
    if !contains_any_mention_prefix(value) {
        return RenderedText {
            text: value.to_owned(),
            highlights: Vec::new(),
            emoji_slots: Vec::new(),
        };
    }

    let mut rendered = String::with_capacity(value.len());
    let mut highlights = Vec::new();
    let mut cursor = 0usize;
    while let Some(start) = next_mention_start(value, cursor) {
        rendered.push_str(&value[cursor..start]);

        let Some((end, target)) = parse_mention(value, start) else {
            rendered.push('<');
            cursor = start.saturating_add(1);
            continue;
        };

        let resolved = match target {
            MentionTarget::User(user_id) => resolve_user_name(user_id),
            MentionTarget::Role(role_id) => resolve_role_name(role_id),
            MentionTarget::Channel(channel_id) => resolve_channel_name(channel_id),
        };
        match resolved {
            Some(name) => {
                let highlight_start = rendered.len();
                rendered.push(mention_prefix(target));
                rendered.push_str(&name);
                let highlight_end = rendered.len();
                if let Some(kind) = highlight_kind(target) {
                    highlights.push(TextHighlight {
                        start: highlight_start,
                        end: highlight_end,
                        kind,
                    });
                }
            }
            None => rendered.push_str(&value[start..end]),
        }
        cursor = end;
    }
    rendered.push_str(&value[cursor..]);

    RenderedText {
        text: rendered,
        highlights,
        emoji_slots: Vec::new(),
    }
}

/// String-only fallback used by thread/channel previews where no image
/// overlay is possible. Replaces `<:name:id>` and `<a:name:id>` with
/// `:name:`. The body pipeline uses
/// [`replace_custom_emoji_markup_in_rendered`].
pub fn replace_custom_emoji_markup(value: &str) -> String {
    if !value.contains('<') {
        return value.to_owned();
    }

    let mut output = String::with_capacity(value.len());
    let mut cursor = 0usize;
    while let Some(relative_start) = value[cursor..].find('<') {
        let start = cursor.saturating_add(relative_start);
        output.push_str(&value[cursor..start]);

        match parse_custom_emoji(value, start) {
            Some((end, name)) => {
                output.push(':');
                output.push_str(name);
                output.push(':');
                cursor = end;
            }
            None => {
                output.push('<');
                cursor = start.saturating_add(1);
            }
        }
    }
    output.push_str(&value[cursor..]);
    output
}

/// Text fallback used when custom emoji images are disabled. The id is the
/// most stable value Discord gives us and matches the user's requested
/// fallback better than the display name, which can be missing or renamed.
pub fn replace_custom_emoji_markup_with_ids(value: &str) -> String {
    if !value.contains('<') {
        return value.to_owned();
    }

    let mut output = String::with_capacity(value.len());
    let mut cursor = 0usize;
    while let Some(relative_start) = value[cursor..].find('<') {
        let start = cursor.saturating_add(relative_start);
        output.push_str(&value[cursor..start]);

        match parse_custom_emoji_full(value, start) {
            Some((end, _name, id, _animated)) => {
                output.push_str(id);
                cursor = end;
            }
            None => {
                output.push('<');
                cursor = start.saturating_add(1);
            }
        }
    }
    output.push_str(&value[cursor..]);
    output
}

/// Image-overlay variant of [`replace_custom_emoji_markup`]: rewrites each
/// match to its `:name:` fallback and records a slot the renderer can blit
/// the image over. Mention highlights are remapped through the byte-shift.
#[cfg(test)]
pub fn replace_custom_emoji_markup_in_rendered(rendered: RenderedText) -> RenderedText {
    replace_custom_emoji_markup_in_rendered_with_images(rendered, true)
}

pub fn replace_custom_emoji_markup_in_rendered_with_images(
    rendered: RenderedText,
    images_enabled: bool,
) -> RenderedText {
    let matches = scan_custom_emoji_matches(&rendered.text);
    if matches.is_empty() {
        return rendered;
    }

    let RenderedText {
        text,
        highlights,
        mut emoji_slots,
    } = rendered;

    let mut output = String::with_capacity(text.len());
    let mut cursor = 0usize;
    for emoji in &matches {
        output.push_str(&text[cursor..emoji.input_start]);
        let slot_byte_start = output.len();
        if images_enabled {
            output.push(':');
            output.push_str(&emoji.name);
            output.push(':');
        } else {
            output.push_str(&emoji.id);
        }
        let slot_byte_len = output.len() - slot_byte_start;
        if images_enabled {
            let extension = if emoji.animated { "gif" } else { "png" };
            emoji_slots.push(InlineEmojiSlot {
                byte_start: slot_byte_start,
                byte_len: slot_byte_len,
                display_width: u16::try_from(slot_byte_len).unwrap_or(u16::MAX),
                url: format!("{CUSTOM_EMOJI_CDN_BASE}/{}.{extension}", emoji.id),
            });
        }
        cursor = emoji.input_end;
    }
    output.push_str(&text[cursor..]);

    let new_highlights = highlights
        .into_iter()
        .map(|highlight| TextHighlight {
            start: remap_offset(&matches, highlight.start, images_enabled),
            end: remap_offset(&matches, highlight.end, images_enabled),
            kind: highlight.kind,
        })
        .collect();

    RenderedText {
        text: output,
        highlights: new_highlights,
        emoji_slots,
    }
}

struct CustomEmojiMatch {
    input_start: usize,
    input_end: usize,
    name: String,
    id: String,
    animated: bool,
}

impl CustomEmojiMatch {
    fn input_len(&self) -> usize {
        self.input_end - self.input_start
    }

    /// Bytes the textual fallback (`:name:`) consumes in the rewritten string.
    fn output_len(&self, images_enabled: bool) -> usize {
        if images_enabled {
            self.name.len() + 2
        } else {
            self.id.len()
        }
    }
}

fn scan_custom_emoji_matches(text: &str) -> Vec<CustomEmojiMatch> {
    if !text.contains('<') {
        return Vec::new();
    }
    let mut matches = Vec::new();
    let mut cursor = 0usize;
    while let Some(rel) = text[cursor..].find('<') {
        let start = cursor.saturating_add(rel);
        match parse_custom_emoji_full(text, start) {
            Some((end, name, id, animated)) => {
                matches.push(CustomEmojiMatch {
                    input_start: start,
                    input_end: end,
                    name: name.to_owned(),
                    id: id.to_owned(),
                    animated,
                });
                cursor = end;
            }
            None => cursor = start.saturating_add(1),
        }
    }
    matches
}

fn remap_offset(matches: &[CustomEmojiMatch], pos: usize, images_enabled: bool) -> usize {
    let mut delta: isize = 0;
    for emoji in matches {
        if emoji.input_end <= pos {
            delta += emoji.output_len(images_enabled) as isize - emoji.input_len() as isize;
        } else {
            break;
        }
    }
    let new = pos as isize + delta;
    new.max(0) as usize
}

fn parse_custom_emoji_full(value: &str, start: usize) -> Option<(usize, &str, &str, bool)> {
    let bytes = value.as_bytes();
    if bytes.get(start) != Some(&b'<') {
        return None;
    }

    let mut index = start.saturating_add(1);
    let animated = bytes.get(index) == Some(&b'a');
    if animated {
        index = index.saturating_add(1);
    }
    if bytes.get(index) != Some(&b':') {
        return None;
    }
    index = index.saturating_add(1);

    let name_start = index;
    while let Some(byte) = bytes.get(index) {
        if *byte == b':' {
            break;
        }
        if !(byte.is_ascii_alphanumeric() || *byte == b'_') {
            return None;
        }
        index = index.saturating_add(1);
    }
    if index == name_start || bytes.get(index) != Some(&b':') {
        return None;
    }
    let name_end = index;
    index = index.saturating_add(1);

    let id_start = index;
    while matches!(bytes.get(index), Some(byte) if byte.is_ascii_digit()) {
        index = index.saturating_add(1);
    }
    if index == id_start || bytes.get(index) != Some(&b'>') {
        return None;
    }

    Some((
        index.saturating_add(1),
        &value[name_start..name_end],
        &value[id_start..index],
        animated,
    ))
}

fn parse_custom_emoji(value: &str, start: usize) -> Option<(usize, &str)> {
    let (end, name, _id, _animated) = parse_custom_emoji_full(value, start)?;
    Some((end, name))
}

fn parse_mention(value: &str, start: usize) -> Option<(usize, MentionTarget)> {
    let bytes = value.as_bytes();
    if bytes.get(start) != Some(&b'<') {
        return None;
    }

    enum Prefix {
        User,
        Role,
        Channel,
    }

    let mut index = start.saturating_add(1);
    let prefix = match bytes.get(index) {
        Some(&b'@') => {
            index = index.saturating_add(1);
            match bytes.get(index) {
                Some(&b'&') => {
                    index = index.saturating_add(1);
                    Prefix::Role
                }
                Some(&b'!') => {
                    // Legacy nickname-mention prefix. Same target as a plain user mention.
                    index = index.saturating_add(1);
                    Prefix::User
                }
                _ => Prefix::User,
            }
        }
        Some(&b'#') => {
            index = index.saturating_add(1);
            Prefix::Channel
        }
        _ => return None,
    };

    let digits_start = index;
    while matches!(bytes.get(index), Some(byte) if byte.is_ascii_digit()) {
        index = index.saturating_add(1);
    }
    if index == digits_start || bytes.get(index) != Some(&b'>') {
        return None;
    }

    let id: u64 = value[digits_start..index].parse().ok()?;
    if id == 0 {
        return None;
    }
    let target = match prefix {
        Prefix::User => MentionTarget::User(id),
        Prefix::Role => MentionTarget::Role(id),
        Prefix::Channel => MentionTarget::Channel(id),
    };
    Some((index.saturating_add(1), target))
}

#[cfg(test)]
mod tests;