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
use regex::Regex;

/// Regex pattern for maching ANSI codes.
pub const ANSI_REGEX: &'static str = r"[\x1b\x9b][\[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]";

/// List of supported ANSI codes.
pub const ANSI_PAIR: [[&'static str; 2]; 23] = [
  ["\x1B[0m", "\x1B[0m"], // reset
  ["\x1B[1m", "\x1B[22m"], // bold
  ["\x1B[2m", "\x1B[22m"], // dim
  ["\x1B[3m", "\x1B[23m"], // italic
  ["\x1B[4m", "\x1B[24m"], // underline
  ["\x1B[7m", "\x1B[27m"], // inverse
  ["\x1B[8m", "\x1B[28m"], // hidden
  ["\x1B[30m", "\x1B[39m"], // black
  ["\x1B[31m", "\x1B[39m"], // red
  ["\x1B[32m", "\x1B[39m"], // green
  ["\x1B[33m", "\x1B[39m"], // yellow
  ["\x1B[34m", "\x1B[39m"], // blue
  ["\x1B[35m", "\x1B[39m"], // magenta
  ["\x1B[36m", "\x1B[39m"], // cyan
  ["\x1B[37m", "\x1B[39m"], // white
  ["\x1B[40m", "\x1B[49m"], // bgblack
  ["\x1B[41m", "\x1B[49m"], // bgred
  ["\x1B[42m", "\x1B[49m"], // bggreen
  ["\x1B[43m", "\x1B[49m"], // bgyellow
  ["\x1B[44m", "\x1B[49m"], // bgblue
  ["\x1B[45m", "\x1B[49m"], // bgmagenta
  ["\x1B[46m", "\x1B[49m"], // bgcyan
  ["\x1B[47m", "\x1B[49m"], // bgwhite
];

/// Text alignement options.
#[derive(Debug, Clone, PartialEq)]
pub enum Alignment {
    Left,
    Center,
    Right,
}

/// Returns opening and closing code for the provided ANSI code.
pub fn ansi_pair<'a>(code: &'a str) -> Option<&[&str; 2]> {
    ANSI_PAIR.iter().find(|&pair| pair.iter().any(|&v| v == code))
}

/// Removes ANSI codes from the provided text and return a new string.
pub fn strip_codes(txt: &str) -> String {
    let regex = Regex::new(ANSI_REGEX).unwrap();
    let clean = String::from_utf8(regex.replace_all(txt, "").as_bytes().to_vec());
    if clean.is_ok() {
        clean.unwrap()
    } else {
        txt.to_string()
    }
}

/// Uses regex to split the provided text on ANSI codes. It returned list
/// includes text chinks and ANSI delimiters.
pub fn match_indices(txt: &str) -> Vec<String> {
    let regex = Regex::new(ANSI_REGEX).unwrap();
    let mut result = Vec::new();
    let mut data: String = txt.to_string();

    loop {
        let mat = regex.find(data.as_str());
        if mat.is_some() {
            let mat = mat.unwrap();
            let start = mat.start();
            let end = mat.end();
            result.push(data[0..start].to_string());
            result.push(data[start..end].to_string());

            let size = data.chars().count();
            if size == 0 {
                break;
            } else {
                data = data[end..].to_string();
            }
        } else {
            result.push(data);
            break;
        }
    }

    result
}

/// Returns a slice of a string containing ANSI codes.
pub fn slice_text(txt: &str, start: usize, end: usize) -> String {
    let mut u_start = None;
    let mut u_end = None;
    let mut offset = 0;
    let mut u_offset = 0;

    for chunk in match_indices(txt).iter() {
        let size = strip_codes(chunk).len();
        
        if u_start.is_none() && offset + size >= start {
            u_start = Some(u_offset + start - offset);
        }
        if u_end.is_none() && offset + size >= end {
            u_end = Some(u_offset + end - offset);
            break;
        }
        offset += size;
        u_offset += chunk.len();
    }

    let u_start = match u_start {
        Some(v) => v,
        None => 0,
    };
    let u_end = match u_end {
        Some(v) => v,
        None => txt.len(),
    };
    txt[u_start..u_end].to_string()
}

/// Calculates the length of a unicode string containing ANSI codes. The length
/// returned represents the visible string length.
pub fn size_text(txt: &str) -> usize {
    unicode_width::UnicodeWidthStr::width(strip_codes(txt).as_str())
}

/// Pads a string to fill a certain number of characters.
pub fn pad_text(
    txt: &str,
    width: usize,
    align: &Alignment,
    chr: char,
) -> String {
    let size = size_text(txt);
    if size >= width {
        return txt.to_string();
    }

    let diff = width - size;
    let (left_pad, right_pad) = match align {
        Alignment::Left => (0, diff),
        Alignment::Right => (diff, 0),
        Alignment::Center => (diff / 2, diff - diff / 2),
    };

    let mut result = String::new();
    for _ in 0..left_pad {
        result.push(chr);
    }
    result.push_str(txt);
    for _ in 0..right_pad {
        result.push(chr);
    }
    result
}

/// Truncates a string to a certain number of characters. 
pub fn trucate_text(
    txt: &str,
    width: usize,
    align: &Alignment,
    tail: &str
) -> String {

    let size = size_text(txt);
    if width >= size {
        return txt.to_string();
    }

    let t_size = size_text(tail);
    match align {
        Alignment::Left => {
            let text = slice_text(txt, 0, width - t_size).trim().to_string();
            format!("{}{}", text, tail)
        },
        Alignment::Right => {
            let text = slice_text(txt, size - width + t_size, size).trim().to_string();
            format!("{}{}", tail, text)
        },
        Alignment::Center => {
            let dim = (width - t_size) / 2;
            let left = slice_text(txt, 0, dim).trim().to_string();
            let right = slice_text(txt, size - width + t_size + dim, size).trim().to_string();
            format!("{}{}{}", left, tail, right)
        },
    }
}

/// Splits long string into multiple lines.
pub fn wrap_text(txt: &str, width: usize) -> Vec<String> {
    let mut result: Vec<String> = Vec::new();

    for line in txt.lines() {
        let mut words: Vec<String> = Vec::new();
        let mut length = 0;

        for (wcount, word) in line.split(" ").enumerate() {
            let word_size = size_text(word);
            if length + word_size >= width && words.len() > 0 {
                result.push(words.join(" "));
                words =  Vec::new();
                length = 0;
            }
            length += word_size + if wcount > 0 { 1 } else { 0 }; // include spaces
            words.push(word.to_string());
        }

        if words.len() > 0 {
            result.push(words.join(" "));
        }
    }

    result
}

/// Adds missing closing ANSI codes to the multi-line string.
pub fn repaire_text(lines: Vec<String>) -> Vec<String> {
    let mut ansis: Vec<Vec<String>> = Vec::new();

    lines.iter().map(|line| {
        let parts = match_indices(line.as_str());

        let mut result: Vec<String> = Vec::new();
        let ansiiter = &ansis;
        for ansi in ansiiter.into_iter() {
            result.push(ansi[0].to_string());
        }
        for part in parts.into_iter() {
            let pair = ansi_pair(part.as_str());
            if pair.is_some() {
                let pair = pair.unwrap();
                let opentag = pair[0].to_string();
                let closetag = pair[1].to_string();
                if part == opentag {
                    ansis.push(vec![opentag, closetag]);
                } else if part == closetag {
                    let index = ansis.iter().position(|a| a[1].to_string() == closetag);
                    if index.is_some() {
                        ansis.remove(index.unwrap());
                    }
                }
            }
            result.push(part.to_string());
        }
        let ansiiter = &ansis;
        for ansi in ansiiter.into_iter() {
            result.push(ansi[1].to_string());
        }
        result.join("")
    }).collect()
}

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

    #[test]
    fn finds_ansi_pair() {
        assert_eq!(ansi_pair(&ANSI_PAIR[0][1]), Some(&ANSI_PAIR[0]));
        assert_eq!(ansi_pair("foo"), None);
    }

    #[test]
    fn strips_ansi_codes() {
        assert_eq!(strip_codes("aaa\x1B[0mbbb\x1B[0mccc"), "aaabbbccc");
    }

    #[test]
    fn matches_ansi_indices() {
        assert_eq!(match_indices("This is\x1B[39m long"), vec!["This is", "\x1B[39m", " long"]);
        assert_eq!(match_indices("This is\x1B[39m long \x1B[46mtext for test"), vec!["This is", "\x1B[39m", " long ", "\x1B[46m", "text for test"]);
    }

    #[test]
    fn slices_ansi_text() {
        assert_eq!(slice_text("a\x1B[32maa\x1B[32mb\x1B[32mbb\x1B[32mcccdddeeefff", 5, 10), "b\x1B[32mcccd");
    }

    #[test]
    fn sizes_ansi_text() {
        assert_eq!(size_text("aaa\x1B[0mbbb\x1B[0mccc"), 9);
    }

    #[test]
    fn pads_ansi_text() {
        assert_eq!(pad_text("fo\x1B[39mobar", 10, &Alignment::Left, '+'), "fo\x1B[39mobar++++");
        assert_eq!(pad_text("fo\x1B[39mobar", 10, &Alignment::Right, '+'), "++++fo\x1B[39mobar");
        assert_eq!(pad_text("fo\x1B[39mobar", 10, &Alignment::Center, '+'), "++fo\x1B[39mobar++");
    }

    #[test]
    fn truncates_ansi_text() {
        assert_eq!(trucate_text("fo\x1B[39mobarbaz", 5, &Alignment::Left, "+"), "fo\x1B[39mob+");
        assert_eq!(trucate_text("fo\x1B[39mobarbaz", 5, &Alignment::Right, "+++"), "+++az");
        assert_eq!(trucate_text("fo\x1B[39mobarbaz", 5, &Alignment::Center, "+++"), "f+++z");
    }

    #[test]
    fn wraps_ansi_text() {
        assert_eq!(wrap_text("This is \x1B[39ma very long tekst for testing\x1B[39m only.", 10), vec![
            "This is \x1B[39ma",
            "very long",
            "tekst for",
            "testing\x1B[39m",
            "only."
        ]);
    }

    #[test]
    fn repairs_multiline_ansi_text() {
        assert_eq!(repaire_text(vec![
            "This is \x1B[31mlong".to_string(),
            "string 利干 sample".to_string(),
            "this is 利干 sample\x1B[39m long code".to_string(),
        ]), vec![
            "This is \x1B[31mlong\x1B[39m",
            "\x1B[31mstring 利干 sample\x1B[39m",
            "\x1B[31mthis is 利干 sample\x1B[39m long code",
        ]);        
    }
}