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
//! A View representing a Gopher text entry.
//! Responds to user input by producing an Action which is then handed
//! to the main UI to perform.

use crate::{
    config::SharedConfig as Config,
    encoding::Encoding,
    terminal,
    ui::{self, Action, Key, View, MAX_COLS},
};
use std::{borrow::Cow, fmt, str};

/// The Text View holds the raw Gopher response as well as information
/// about which lines should currently be displayed on screen.
pub struct Text {
    /// Ref to our global config
    config: Config,
    /// Gopher URL
    url: String,
    /// Gopher response
    raw_response: Vec<u8>,
    /// Encoded response
    encoded_response: String,
    /// Current scroll offset, in rows
    offset: usize,
    /// Number of lines
    lines: usize,
    /// Size of longest line
    longest: usize,
    /// Current screen size, cols and rows
    size: (usize, usize),
    /// Was this page retrieved view TLS?
    pub tls: bool,
    /// Retrieved via Tor?
    pub tor: bool,
    /// UI mode. Interactive (Run), Printing, Raw mode...
    mode: ui::Mode,
    /// Text Encoding of Response
    encoding: Encoding,
    /// Currently in wide mode?
    pub wide: bool,
    /// How many lines to scroll by. 0 = full screen
    scroll: usize,
}

impl fmt::Display for Text {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.url())
    }
}

impl View for Text {
    fn is_tls(&self) -> bool {
        self.tls
    }

    fn is_tor(&self) -> bool {
        self.tor
    }

    fn url(&self) -> &str {
        self.url.as_ref()
    }

    fn raw(&self) -> &str {
        str::from_utf8(&self.raw_response).unwrap_or_default()
    }

    fn term_size(&mut self, cols: usize, rows: usize) {
        self.size = (cols, rows);
    }

    fn set_wide(&mut self, wide: bool) {
        self.wide = wide;
    }

    fn wide(&mut self) -> bool {
        self.wide
    }

    fn encoding(&self) -> Encoding {
        self.encoding
    }

    fn respond(&mut self, c: Key) -> Action {
        match c {
            Key::Home => {
                self.offset = 0;
                Action::Redraw
            }
            Key::End => {
                self.offset = self.final_scroll();
                Action::Redraw
            }
            Key::Ctrl('e') | Key::Char('e') => self.toggle_encoding(),
            Key::Down | Key::Ctrl('n') | Key::Char('n') | Key::Ctrl('j') | Key::Char('j') => {
                if self.offset < self.final_scroll() {
                    self.offset += 1;
                    Action::Redraw
                } else {
                    Action::None
                }
            }
            Key::Up | Key::Ctrl('p') | Key::Char('p') | Key::Ctrl('k') | Key::Char('k') => {
                if self.offset > 0 {
                    self.offset -= 1;
                    Action::Redraw
                } else {
                    Action::None
                }
            }
            Key::PageUp | Key::Char('-') => {
                if self.offset > 0 {
                    if self.offset >= self.scroll_by() {
                        self.offset -= self.scroll_by();
                    } else {
                        self.offset = 0;
                    }
                    Action::Redraw
                } else {
                    Action::None
                }
            }
            Key::PageDown | Key::Char(' ') => {
                self.offset += self.scroll_by();
                if self.offset > self.final_scroll() {
                    self.offset = self.final_scroll();
                }
                Action::Redraw
            }
            _ => Action::Keypress(c),
        }
    }

    fn render(&mut self) -> String {
        let (_cols, rows) = self.size;
        let mut out = String::new();
        let wrap = self.config.read().unwrap().wrap;
        let indent = self.indent_str(wrap);
        let limit = if self.mode == ui::Mode::Run {
            rows - 1
        } else {
            self.lines
        };

        let iter = wrap_text(&self.encoded_response, wrap)
            .into_iter()
            .skip(self.offset)
            .take(limit);

        for line in iter {
            // Check for Gopher's weird "end of response" line.
            if line == ".\r" || line == "." {
                continue;
            }
            if !self.wide {
                out.push_str(&indent);
            }
            let line = line.trim_end_matches('\r').replace('\t', "    ");
            out.push_str(&line);

            // clear rest of line
            out.push_str(&format!("{}", terminal::ClearUntilNewline));

            out.push_str("\r\n");
        }

        // clear remainder of screen
        out.push_str(&format!("{}", terminal::ClearAfterCursor));

        out
    }
}

impl Text {
    /// Create a Text View from a raw Gopher response and a few options.
    pub fn from(url: &str, response: Vec<u8>, config: Config, tls: bool) -> Text {
        let mode = config.read().unwrap().mode;
        let tor = config.read().unwrap().tor;
        let encoding = config.read().unwrap().encoding;
        let wide = config.read().unwrap().wide;
        let scroll = config.read().unwrap().scroll;

        let mut new = Text {
            config,
            url: url.into(),
            encoded_response: String::new(),
            raw_response: response,
            offset: 0,
            lines: 0,
            longest: 0,
            size: (0, 0),
            mode,
            tls,
            tor,
            encoding,
            wide,
            scroll,
        };
        new.encode_response();
        new
    }

    /// Toggle between our two encodings.
    fn toggle_encoding(&mut self) -> Action {
        if matches!(self.encoding, Encoding::UTF8) {
            self.encoding = Encoding::CP437;
        } else {
            self.encoding = Encoding::UTF8;
        }
        self.config.write().unwrap().encoding = self.encoding;
        self.encode_response();
        Action::Redraw
    }

    /// Convert the response to a Rust String and cache metadata like
    /// the number of lines.
    fn encode_response(&mut self) {
        self.encoded_response = self.encoding.encode(&self.raw_response).into();
        let wrapped = wrap_text(
            self.encoded_response.as_ref(),
            self.config.read().unwrap().wrap,
        );
        self.lines = wrapped.len();
        self.longest = wrapped.iter().map(|line| line.len()).max().unwrap_or(0) as usize;
    }

    /// Final `self.scroll` value.
    fn final_scroll(&self) -> usize {
        let padding = (self.size.1 as f64 * 0.9) as usize;
        if self.lines > padding {
            self.lines - padding
        } else {
            0
        }
    }

    /// How many lines to scroll by when paging up or down.
    fn scroll_by(&self) -> usize {
        if self.scroll == 0 {
            self.size.1 - 1
        } else {
            self.scroll
        }
    }

    /// Determine the longest line, considering any line wrapping and
    /// `MAX_COL`.
    fn longest_line_with_wrap(&self, wrap: usize) -> usize {
        let longest = if self.longest > MAX_COLS {
            MAX_COLS
        } else {
            self.longest
        };

        if wrap > 0 && longest > wrap {
            wrap
        } else {
            longest
        }
    }

    /// Produce the string to use for indentation, or the left margin,
    /// for a given text document.
    fn indent_str(&self, wrap: usize) -> Cow<str> {
        let (cols, _) = self.size;
        let longest = self.longest_line_with_wrap(wrap);

        if cols >= longest && cols - longest <= 6 {
            Cow::from("")
        } else if cols >= longest {
            Cow::from(" ".repeat((cols - longest) / 2))
        } else {
            Cow::from("")
        }
    }
}

/// Splits a chunk of text into a vector of strings with at most
/// `wrap` characters each. Tries to be smart and wrap at punctuation,
/// otherwise just wraps at `wrap`.
fn wrap_text(lines: &str, wrap: usize) -> Vec<&str> {
    if wrap == 0 {
        return lines.split('\n').collect();
    }

    let mut out = vec![];
    for mut line in lines.lines() {
        let mut len = line.chars().count();
        if len > wrap {
            while len > wrap {
                let (end, _) = line.char_indices().take(wrap + 1).last().unwrap();

                if !matches!(&line[end - 1..end], " " | "-" | "," | "." | ":") {
                    if let Some(&(end, _)) = line
                        .char_indices()
                        .take(wrap + 1)
                        .collect::<Vec<_>>()
                        .iter()
                        .rev()
                        .skip(1)
                        .find(|(_, c)| matches!(c, ' ' | '-' | ',' | '.' | ':'))
                    {
                        out.push(&line[..=end]);
                        if end + 1 < line.len() {
                            line = &line[end + 1..];
                            len -= end;
                        } else {
                            len = 0;
                            break;
                        }
                        continue;
                    }
                }

                out.push(&line[..end]);
                line = &line[end..];
                len -= wrap;
            }
            if len > 0 {
                out.push(line);
            }
        } else {
            out.push(line);
        }
    }
    out
}

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

    #[test]
    fn test_cp437() {
        let body = include_bytes!("../tests/CP437.txt");
        let mut text = Text::from("", body.to_vec(), Config::default(), false);
        text.mode = ui::Mode::Print;

        let res = text.render();
        assert!(!res.contains("╟"));
        assert!(!res.contains("≈"));
        assert!(!res.contains("Ω"));
        assert!(!res.contains("Θ"));

        text.toggle_encoding();
        let res = text.render();
        assert!(res.contains("╟"));
        assert!(res.contains("≈"));
        assert!(res.contains("Ω"));
        assert!(res.contains("Θ"));
    }

    #[test]
    fn test_wrapping() {
        let text = "regular line
really really really really really really really really really really long line
super duper extra scooper hoopa loopa double doopa maxi paxi giga baxi very very long line
Qua nova re oblata omnis administratio belliconsistit militesque aversi a proelio ad studium audiendi et cognoscendi feruntur ubi hostes ad legatosexercitumque pervenerunt universi se ad pedes proiciunt orant ut adventus Caesaris expectetur captamsuam urbem videre...
really really really really really really really really really kinda-but-not-really long line
another regular line
";

        let lines = wrap_text(text, 70);

        assert_eq!("regular line", lines[0]);
        assert_eq!(
            "really really really really really really really really really really",
            lines[1].trim()
        );
        assert_eq!("long line", lines[2].trim());
        assert_eq!(
            "super duper extra scooper hoopa loopa double doopa maxi paxi giga",
            lines[3].trim()
        );
        assert_eq!("baxi very very long line", lines[4].trim());

        assert_eq!(
            "Qua nova re oblata omnis administratio belliconsistit militesque",
            lines[5].trim()
        );
        assert_eq!(
            "aversi a proelio ad studium audiendi et cognoscendi feruntur ubi",
            lines[6].trim()
        );
        assert_eq!(
            "hostes ad legatosexercitumque pervenerunt universi se ad pedes",
            lines[7].trim()
        );
        assert_eq!(
            "really really really really really really really really really kinda-",
            lines[10].trim()
        );
        assert_eq!("but-not-really long line", lines[11].trim());

        assert_eq!(13, lines.len());
    }
}