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
//! This module contains [`Truncate`] structure, used to decrease width of a [`Table`]s or a cell on a [`Table`] by truncating the width.
//!
//! [`Table`]: crate::Table

use std::{borrow::Cow, iter, marker::PhantomData};

use crate::{
    grid::{
        config::{ColoredConfig, Entity, SpannedConfig},
        dimension::CompleteDimensionVecRecords,
        records::{EmptyRecords, ExactRecords, IntoRecords, PeekableRecords, Records, RecordsMut},
        util::string::{string_width, string_width_multiline},
    },
    settings::{
        measurement::Measurement,
        peaker::{Peaker, PriorityNone},
        CellOption, TableOption, Width,
    },
};

use super::util::{get_table_widths, get_table_widths_with_total};
use crate::util::string::cut_str;

/// Truncate cut the string to a given width if its length exceeds it.
/// Otherwise keeps the content of a cell untouched.
///
/// The function is color aware if a `color` feature is on.
///
/// Be aware that it doesn't consider padding.
/// So if you want to set a exact width you might need to use [`Padding`] to set it to 0.
///    
/// ## Example
///
/// ```
/// use tabled::{Table, settings::{object::Segment, Width, Modify}};
///
/// let table = Table::new(&["Hello World!"])
///     .with(Modify::new(Segment::all()).with(Width::truncate(3)));
/// ```
///
/// [`Padding`]: crate::settings::Padding
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Truncate<'a, W = usize, P = PriorityNone> {
    width: W,
    suffix: Option<TruncateSuffix<'a>>,
    multiline: bool,
    _priority: PhantomData<P>,
}

#[cfg(feature = "ansi")]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct TruncateSuffix<'a> {
    text: Cow<'a, str>,
    limit: SuffixLimit,
    try_color: bool,
}

#[cfg(not(feature = "ansi"))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct TruncateSuffix<'a> {
    text: Cow<'a, str>,
    limit: SuffixLimit,
}

impl Default for TruncateSuffix<'_> {
    fn default() -> Self {
        Self {
            text: Cow::default(),
            limit: SuffixLimit::Cut,
            #[cfg(feature = "ansi")]
            try_color: false,
        }
    }
}

/// A suffix limit settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SuffixLimit {
    /// Cut the suffix.
    Cut,
    /// Don't show the suffix.
    Ignore,
    /// Use a string with n chars instead.
    Replace(char),
}

impl<W> Truncate<'static, W>
where
    W: Measurement<Width>,
{
    /// Creates a [`Truncate`] object
    pub fn new(width: W) -> Truncate<'static, W> {
        Self {
            width,
            multiline: false,
            suffix: None,
            _priority: PhantomData,
        }
    }
}

impl<'a, W, P> Truncate<'a, W, P> {
    /// Sets a suffix which will be appended to a resultant string.
    ///
    /// The suffix is used in 3 circumstances:
    ///     1. If original string is *bigger* than the suffix.
    ///        We cut more of the original string and append the suffix.
    ///     2. If suffix is bigger than the original string.
    ///        We cut the suffix to fit in the width by default.
    ///        But you can peak the behaviour by using [`Truncate::suffix_limit`]
    pub fn suffix<S: Into<Cow<'a, str>>>(self, suffix: S) -> Truncate<'a, W, P> {
        let mut suff = self.suffix.unwrap_or_default();
        suff.text = suffix.into();

        Truncate {
            width: self.width,
            multiline: self.multiline,
            suffix: Some(suff),
            _priority: PhantomData,
        }
    }

    /// Sets a suffix limit, which is used when the suffix is too big to be used.
    pub fn suffix_limit(self, limit: SuffixLimit) -> Truncate<'a, W, P> {
        let mut suff = self.suffix.unwrap_or_default();
        suff.limit = limit;

        Truncate {
            width: self.width,
            multiline: self.multiline,
            suffix: Some(suff),
            _priority: PhantomData,
        }
    }

    /// Use trancate logic per line, not as a string as a whole.
    pub fn multiline(self) -> Truncate<'a, W, P> {
        Truncate {
            width: self.width,
            multiline: true,
            suffix: self.suffix,
            _priority: self._priority,
        }
    }

    #[cfg(feature = "ansi")]
    /// Sets a optional logic to try to colorize a suffix.
    pub fn suffix_try_color(self, color: bool) -> Truncate<'a, W, P> {
        let mut suff = self.suffix.unwrap_or_default();
        suff.try_color = color;

        Truncate {
            width: self.width,
            multiline: self.multiline,
            suffix: Some(suff),
            _priority: PhantomData,
        }
    }
}

impl<'a, W, P> Truncate<'a, W, P> {
    /// Priority defines the logic by which a truncate will be applied when is done for the whole table.
    ///
    /// - [`PriorityNone`] which cuts the columns one after another.
    /// - [`PriorityMax`] cuts the biggest columns first.
    /// - [`PriorityMin`] cuts the lowest columns first.
    ///
    /// [`PriorityMax`]: crate::settings::peaker::PriorityMax
    /// [`PriorityMin`]: crate::settings::peaker::PriorityMin
    pub fn priority<PP: Peaker>(self) -> Truncate<'a, W, PP> {
        Truncate {
            width: self.width,
            multiline: self.multiline,
            suffix: self.suffix,
            _priority: PhantomData,
        }
    }
}

impl Truncate<'_, (), ()> {
    /// Truncate a given string
    pub fn truncate_text(text: &str, width: usize) -> Cow<'_, str> {
        truncate_text(text, width, "", false)
    }
}

impl<W, P, R> CellOption<R, ColoredConfig> for Truncate<'_, W, P>
where
    W: Measurement<Width>,
    R: Records + ExactRecords + PeekableRecords + RecordsMut<String>,
    for<'a> &'a R: Records,
    for<'a> <<&'a R as Records>::Iter as IntoRecords>::Cell: AsRef<str>,
{
    fn change(self, records: &mut R, cfg: &mut ColoredConfig, entity: Entity) {
        let available = self.width.measure(&*records, cfg);

        let mut width = available;
        let mut suffix = Cow::Borrowed("");

        if let Some(x) = self.suffix.as_ref() {
            let (cutted_suffix, rest_width) = make_suffix(x, width);
            suffix = cutted_suffix;
            width = rest_width;
        };

        let count_rows = records.count_rows();
        let count_columns = records.count_columns();

        let colorize = need_suffix_color_preservation(&self.suffix);

        for pos in entity.iter(count_rows, count_columns) {
            let is_valid_pos = pos.0 < count_rows && pos.1 < count_columns;
            if !is_valid_pos {
                continue;
            }

            let text = records.get_text(pos);

            let cell_width = string_width_multiline(text);
            if available >= cell_width {
                continue;
            }

            let text =
                truncate_multiline(text, &suffix, width, available, colorize, self.multiline);

            records.set(pos, text.into_owned());
        }
    }
}

fn truncate_multiline<'a>(
    text: &'a str,
    suffix: &'a str,
    width: usize,
    twidth: usize,
    suffix_color: bool,
    multiline: bool,
) -> Cow<'a, str> {
    if multiline {
        let mut buf = String::new();
        for (i, line) in crate::grid::util::string::get_lines(text).enumerate() {
            if i != 0 {
                buf.push('\n');
            }

            let line = make_text_truncated(&line, suffix, width, twidth, suffix_color);
            buf.push_str(&line);
        }

        Cow::Owned(buf)
    } else {
        make_text_truncated(text, suffix, width, twidth, suffix_color)
    }
}

fn make_text_truncated<'a>(
    text: &'a str,
    suffix: &'a str,
    width: usize,
    twidth: usize,
    suffix_color: bool,
) -> Cow<'a, str> {
    if width == 0 {
        if twidth == 0 {
            Cow::Borrowed("")
        } else {
            Cow::Borrowed(suffix)
        }
    } else {
        truncate_text(text, width, suffix, suffix_color)
    }
}

fn need_suffix_color_preservation(_suffix: &Option<TruncateSuffix<'_>>) -> bool {
    #[cfg(not(feature = "ansi"))]
    {
        false
    }
    #[cfg(feature = "ansi")]
    {
        _suffix.as_ref().map_or(false, |s| s.try_color)
    }
}

fn make_suffix<'a>(suffix: &'a TruncateSuffix<'_>, width: usize) -> (Cow<'a, str>, usize) {
    let suffix_length = string_width(&suffix.text);
    if width > suffix_length {
        return (Cow::Borrowed(suffix.text.as_ref()), width - suffix_length);
    }

    match suffix.limit {
        SuffixLimit::Ignore => (Cow::Borrowed(""), width),
        SuffixLimit::Cut => {
            let suffix = cut_str(&suffix.text, width);
            (suffix, 0)
        }
        SuffixLimit::Replace(c) => {
            let suffix = Cow::Owned(iter::repeat(c).take(width).collect());
            (suffix, 0)
        }
    }
}

impl<W, P, R> TableOption<R, ColoredConfig, CompleteDimensionVecRecords<'_>> for Truncate<'_, W, P>
where
    W: Measurement<Width>,
    P: Peaker,
    R: Records + ExactRecords + PeekableRecords + RecordsMut<String>,
    for<'a> &'a R: Records,
    for<'a> <<&'a R as Records>::Iter as IntoRecords>::Cell: AsRef<str>,
{
    fn change(
        self,
        records: &mut R,
        cfg: &mut ColoredConfig,
        dims: &mut CompleteDimensionVecRecords<'_>,
    ) {
        if records.count_rows() == 0 || records.count_columns() == 0 {
            return;
        }

        let width = self.width.measure(&*records, cfg);
        let (widths, total) = get_table_widths_with_total(&*records, cfg);
        if total <= width {
            return;
        }

        let suffix = self.suffix.as_ref().map(|s| TruncateSuffix {
            text: Cow::Borrowed(&s.text),
            limit: s.limit,
            #[cfg(feature = "ansi")]
            try_color: s.try_color,
        });

        let priority = P::create();
        let multiline = self.multiline;
        let widths = truncate_total_width(
            records, cfg, widths, total, width, priority, suffix, multiline,
        );

        dims.set_widths(widths);
    }
}

#[allow(clippy::too_many_arguments)]
fn truncate_total_width<P, R>(
    records: &mut R,
    cfg: &mut ColoredConfig,
    mut widths: Vec<usize>,
    total: usize,
    width: usize,
    priority: P,
    suffix: Option<TruncateSuffix<'_>>,
    multiline: bool,
) -> Vec<usize>
where
    P: Peaker,
    R: Records + PeekableRecords + ExactRecords + RecordsMut<String>,
    for<'a> &'a R: Records,
    for<'a> <<&'a R as Records>::Iter as IntoRecords>::Cell: AsRef<str>,
{
    let count_rows = records.count_rows();
    let count_columns = records.count_columns();

    let min_widths = get_table_widths(EmptyRecords::new(count_rows, count_columns), cfg);

    decrease_widths(&mut widths, &min_widths, total, width, priority);

    let points = get_decrease_cell_list(cfg, &widths, &min_widths, (count_rows, count_columns));

    for ((row, col), width) in points {
        let mut truncate = Truncate::new(width);
        truncate.suffix = suffix.clone();
        truncate.multiline = multiline;
        CellOption::change(truncate, records, cfg, (row, col).into());
    }

    widths
}

fn truncate_text<'a>(
    text: &'a str,
    width: usize,
    suffix: &str,
    _suffix_color: bool,
) -> Cow<'a, str> {
    let content = cut_str(text, width);
    if suffix.is_empty() {
        return content;
    }

    #[cfg(feature = "ansi")]
    {
        if _suffix_color {
            if let Some(block) = ansi_str::get_blocks(text).last() {
                if block.has_ansi() {
                    let style = block.style();
                    Cow::Owned(format!(
                        "{}{}{}{}",
                        content,
                        style.start(),
                        suffix,
                        style.end()
                    ))
                } else {
                    let mut content = content.into_owned();
                    content.push_str(suffix);
                    Cow::Owned(content)
                }
            } else {
                let mut content = content.into_owned();
                content.push_str(suffix);
                Cow::Owned(content)
            }
        } else {
            let mut content = content.into_owned();
            content.push_str(suffix);
            Cow::Owned(content)
        }
    }

    #[cfg(not(feature = "ansi"))]
    {
        let mut content = content.into_owned();
        content.push_str(suffix);
        Cow::Owned(content)
    }
}

fn get_decrease_cell_list(
    cfg: &SpannedConfig,
    widths: &[usize],
    min_widths: &[usize],
    shape: (usize, usize),
) -> Vec<((usize, usize), usize)> {
    let mut points = Vec::new();
    (0..shape.1).for_each(|col| {
        (0..shape.0)
            .filter(|&row| cfg.is_cell_visible((row, col)))
            .for_each(|row| {
                let (width, width_min) = match cfg.get_column_span((row, col)) {
                    Some(span) => {
                        let width = (col..col + span).map(|i| widths[i]).sum::<usize>();
                        let min_width = (col..col + span).map(|i| min_widths[i]).sum::<usize>();
                        let count_borders = count_borders(cfg, col, col + span, shape.1);
                        (width + count_borders, min_width + count_borders)
                    }
                    None => (widths[col], min_widths[col]),
                };

                if width >= width_min {
                    let padding = cfg.get_padding((row, col).into());
                    let width = width.saturating_sub(padding.left.size + padding.right.size);

                    points.push(((row, col), width));
                }
            });
    });

    points
}

fn decrease_widths<F>(
    widths: &mut [usize],
    min_widths: &[usize],
    total_width: usize,
    mut width: usize,
    mut peeaker: F,
) where
    F: Peaker,
{
    let mut empty_list = 0;
    for col in 0..widths.len() {
        if widths[col] == 0 || widths[col] <= min_widths[col] {
            empty_list += 1;
        }
    }

    while width != total_width {
        if empty_list == widths.len() {
            break;
        }

        let col = match peeaker.peak(min_widths, widths) {
            Some(col) => col,
            None => break,
        };

        if widths[col] == 0 || widths[col] <= min_widths[col] {
            continue;
        }

        widths[col] -= 1;

        if widths[col] == 0 || widths[col] <= min_widths[col] {
            empty_list += 1;
        }

        width += 1;
    }
}

fn count_borders(cfg: &SpannedConfig, start: usize, end: usize, count_columns: usize) -> usize {
    (start..end)
        .skip(1)
        .filter(|&i| cfg.has_vertical(i, count_columns))
        .count()
}