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
use std::io::Write;

use crate::OmaConsoleResult;
use console::Term;
use indicatif::{MultiProgress, ProgressBar};

/// Gen oma style message prefix
pub fn gen_prefix(prefix: &str, prefix_len: u16) -> String {
    if console::measure_text_width(prefix) > (prefix_len - 1).into() {
        panic!("Line prefix \"{prefix}\" too long!");
    }

    // Make sure the real_prefix has desired PREFIX_LEN in console
    let left_padding_size = (prefix_len as usize) - 1 - console::measure_text_width(prefix);
    let mut real_prefix: String = " ".repeat(left_padding_size);
    real_prefix.push_str(prefix);
    real_prefix.push(' ');
    real_prefix
}

impl Default for Writer {
    fn default() -> Self {
        Writer {
            term: Term::stderr(),
            prefix_len: 10,
        }
    }
}

pub struct Writer {
    term: Term,
    prefix_len: u16,
}

impl Writer {
    pub fn new(prefix_len: u16) -> Self {
        Self {
            prefix_len,
            ..Default::default()
        }
    }

    /// See environment is terminal
    pub fn is_terminal(&self) -> bool {
        self.term.is_term()
    }

    /// Show terminal cursor
    pub fn show_cursor(&self) -> OmaConsoleResult<()> {
        self.term.show_cursor()?;
        Ok(())
    }

    /// Get terminal max len to writer message to terminal
    pub fn get_max_len(&self) -> u16 {
        let len = self.term.size_checked().unwrap_or((25, 80)).1 - self.prefix_len;

        if len > 150 {
            150
        } else {
            len
        }
    }

    /// Get terminal height
    pub fn get_height(&self) -> u16 {
        self.term.size_checked().unwrap_or((25, 80)).0
    }

    /// Get writer to write something to terminal
    pub fn get_writer(&self) -> Box<dyn Write> {
        Box::new(self.term.clone())
    }

    /// Write oma-style message prefix to terminal
    fn write_prefix(&self, prefix: &str) -> OmaConsoleResult<()> {
        self.term.write_str(&gen_prefix(prefix, self.prefix_len))?;

        Ok(())
    }

    /// Write oma-style string to terminal
    pub fn writeln(
        &self,
        prefix: &str,
        msg: &str,
        is_pb: bool,
    ) -> OmaConsoleResult<(Vec<String>, Vec<String>)> {
        let max_len = self.get_max_len();
        let mut first_run = true;

        let mut ref_s = msg;
        let mut i = 1;

        let mut added_count = 0;

        let (mut prefix_res, mut msg_res) = (vec![], vec![]);

        // Print msg with left padding
        loop {
            let line_msg = if console::measure_text_width(ref_s) <= max_len.into() {
                format!("{}\n", ref_s).into()
            } else {
                console::truncate_str(ref_s, max_len.into(), "\n")
            };

            if first_run {
                if !is_pb {
                    self.write_prefix(prefix)?;
                } else {
                    prefix_res.push(gen_prefix(prefix, self.prefix_len));
                }
                first_run = false;
            } else if !is_pb {
                self.write_prefix("")?;
            } else {
                prefix_res.push(gen_prefix("", self.prefix_len));
            }

            if !is_pb {
                self.term.write_str(&line_msg)?;
            } else {
                msg_res.push(line_msg.to_string());
            }

            // added_count 是已经处理过字符串的长度
            added_count += line_msg.len();

            // i 代表了有多少个换行符
            // 因此,当预处理的消息长度等于已经处理的消息长度,减去加入的换行符
            // 则处理结束
            if msg.len() == added_count - i {
                break;
            }

            // 把本次已经处理的字符串切片剔除
            ref_s = &ref_s[line_msg.len() - 1..];
            i += 1;
        }

        Ok((prefix_res, msg_res))
    }

    /// Write oma-style string to terminal with progress bar
    pub fn writeln_with_pb(
        &self,
        pb: &ProgressBar,
        prefix: &str,
        msg: &str,
    ) -> OmaConsoleResult<()> {
        let (prefix, line_msgs) = self.writeln(prefix, msg, true)?;

        for (i, c) in prefix.iter().enumerate() {
            pb.println(format!("{c}{}", line_msgs[i]));
        }

        Ok(())
    }

    pub fn writeln_with_mb(
        &self,
        mb: &MultiProgress,
        prefix: &str,
        msg: &str,
    ) -> OmaConsoleResult<()> {
        let (prefix, line_msgs) = self.writeln(prefix, msg, true)?;

        for (i, c) in prefix.iter().enumerate() {
            mb.println(format!("{c}{}", line_msgs[i]))?;
        }

        Ok(())
    }

    pub fn write_chunks<S: AsRef<str>>(
        &self,
        prefix: &str,
        chunks: &[S],
        prefix_len: u16,
    ) -> OmaConsoleResult<()> {
        if chunks.is_empty() {
            return Ok(());
        }

        let max_len: usize = (self.get_max_len() - prefix_len).into();
        // Write prefix first
        self.write_prefix(prefix)?;
        let mut cur_line_len: usize = prefix_len.into();
        for chunk in chunks {
            let chunk = chunk.as_ref();
            let chunk_len = console::measure_text_width(chunk);
            // If going to overflow the line, create new line
            // The `1` is the preceding space
            if cur_line_len + chunk_len + 1 > max_len {
                self.term.write_str("\n")?;
                self.write_prefix("")?;
                cur_line_len = 0;
            }
            self.term.write_str(chunk)?;
            self.term.write_str(" ")?;
            cur_line_len += chunk_len + 1;
        }
        // Write a new line
        self.term.write_str("\n")?;

        Ok(())
    }
}