| 1 |
use crate::compositor::{Component, Context}; |
| 2 |
use tui::buffer::Buffer as Surface; |
| 3 |
|
| 4 |
use helix_view::graphics::Rect; |
| 5 |
|
| 6 |
pub struct Text { |
| 7 |
pub(crate) contents: tui::text::Text<'static>, |
| 8 |
size: (u16, u16), |
| 9 |
viewport: (u16, u16), |
| 10 |
} |
| 11 |
|
| 12 |
impl Text { |
| 13 |
pub fn new(contents: String) -> Self { |
| 14 |
Self { |
| 15 |
contents: tui::text::Text::from(contents), |
| 16 |
size: (0, 0), |
| 17 |
viewport: (0, 0), |
| 18 |
} |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
impl From<tui::text::Text<'static>> for Text { |
| 23 |
fn from(contents: tui::text::Text<'static>) -> Self { |
| 24 |
Self { |
| 25 |
contents, |
| 26 |
size: (0, 0), |
| 27 |
viewport: (0, 0), |
| 28 |
} |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
impl Component for Text { |
| 33 |
fn render(&mut self, area: Rect, surface: &mut Surface, _cx: &mut Context) { |
| 34 |
use tui::widgets::{Paragraph, Widget, Wrap}; |
| 35 |
|
| 36 |
let par = Paragraph::new(&self.contents).wrap(Wrap { trim: false }); |
| 37 |
|
| 38 |
|
| 39 |
par.render(area, surface); |
| 40 |
} |
| 41 |
|
| 42 |
fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> { |
| 43 |
if viewport != self.viewport { |
| 44 |
let width = std::cmp::min(self.contents.width() as u16, viewport.0); |
| 45 |
let height = std::cmp::min(self.contents.height() as u16, viewport.1); |
| 46 |
self.size = (width, height); |
| 47 |
self.viewport = viewport; |
| 48 |
} |
| 49 |
Some(self.size) |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
pub fn required_size(text: &tui::text::Text, max_text_width: u16) -> (u16, u16) { |
| 54 |
let mut text_width = 0; |
| 55 |
let mut height = 0; |
| 56 |
for content in &text.lines { |
| 57 |
height += 1; |
| 58 |
let content_width = content.width() as u16; |
| 59 |
if content_width > max_text_width { |
| 60 |
text_width = max_text_width; |
| 61 |
height += content_width.checked_div(max_text_width).unwrap_or(0); |
| 62 |
} else if content_width > text_width { |
| 63 |
text_width = content_width; |
| 64 |
} |
| 65 |
} |
| 66 |
(text_width, height) |
| 67 |
} |