Commit a4505a6abe

a4505a6abeebd3b6391e48db0863ddf595220506

parent: 262311623d

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-05-08 15:27 UTC

Can switch tabs etc and stuff

Layout: unified · split

Cargo.lock +11
@@ -263,6 +263,15 @@ dependencies = [
263 "libc", 263 "libc",
264] 264]
265 265
266[[package]]
267name = "home"
268version = "0.5.3"
269source = "registry+https://github.com/rust-lang/crates.io-index"
270checksum = "2456aef2e6b6a9784192ae780c0f15bc57df0e918585282325e8c8ac27737654"
271dependencies = [
272 "winapi",
273]
274
266[[package]] 275[[package]]
267name = "hrtime" 276name = "hrtime"
268version = "0.2.0" 277version = "0.2.0"
@@ -1169,7 +1178,9 @@ version = "0.1.0"
1169dependencies = [ 1178dependencies = [
1170 "crossterm", 1179 "crossterm",
1171 "futures", 1180 "futures",
1181 "home",
1172 "hrtime", 1182 "hrtime",
1173 "invidious", 1183 "invidious",
1184 "reqwest",
1174 "tui", 1185 "tui",
1175] 1186]
Cargo.toml +2
@@ -11,6 +11,8 @@ crossterm = "0.23"
11invidious = "0.1.0" 11invidious = "0.1.0"
12futures = "0.3" 12futures = "0.3"
13hrtime = "0.2" 13hrtime = "0.2"
14home = "0.5"
15reqwest = "0.11"
14 16
15[profile.dev.package."*"] 17[profile.dev.package."*"]
16opt-level = 3 18opt-level = 3
README.md +14 −1
@@ -1 +1,14 @@
1Very bad coding, but if it works, it works.\ No newline at end of file 1## Basic Movements
2Arrow keys: Move in the direction of the arrow key.
3Enter: Select an item (Everything is an item)
4Esc: Unselect an item
5q: Quit the program (Only works when nothing is selected)
6
7## Basic Display
8Green (Or your terminal's default foreground color): All the items
9Red: The item that you have your "cursor" on (Aka hovering)
10Blue/Purple: The item that you have selected
11Yellow: Selected but not selected? (I don't know how to say that)
12
13## Bugs
14NONE! It's just a feature. If you found one, please report the feature on GitHub\ No newline at end of file
src/app/app.rs +6 −2
@@ -64,7 +64,11 @@ impl App {
64 self = item.key_input(key, self); 64 self = item.key_input(key, self);
65 self.state[y].items[x].item = Item::Global(item); 65 self.state[y].items[x].item = Item::Global(item);
66 } 66 }
67 _ => {} 67 Item::MainMenu(item) => {
68 let mut item = item.clone();
69 self = item.key_input(key, self);
70 self.state[y].items[x].item = Item::MainMenu(item);
71 }
68 } 72 }
69 73
70 return self; 74 return self;
@@ -175,7 +179,7 @@ impl App {
175 } 179 }
176} 180}
177 181
178#[derive(Debug)] 182#[derive(Debug, PartialEq)]
179pub enum Page { 183pub enum Page {
180 MainMenu { tab: MainMenuSelector }, 184 MainMenu { tab: MainMenuSelector },
181} 185}
src/app/pages/global.rs +17 −1
@@ -1,5 +1,5 @@
1use crossterm::event::KeyCode; 1use crossterm::event::KeyCode;
2use invidious::structs::{hidden::TrendingVideo, video::Video}; 2use invidious::structs::{hidden::{TrendingVideo, PopularItem}, video::Video};
3 3
4use crate::{ 4use crate::{
5 app::app::App, 5 app::app::App,
@@ -84,3 +84,19 @@ impl From<TrendingVideo> for MiniVideo {
84 } 84 }
85 } 85 }
86} 86}
87
88impl From<PopularItem> for MiniVideo {
89 fn from(original: PopularItem) -> Self {
90 MiniVideo {
91 title: original.title,
92 video_id: original.videoId,
93 video_thumbnail: original.videoThumbnails[0].url.clone(),
94 length: hrtime::from_sec(original.lengthSeconds as u64),
95 view_count: original.viewCount,
96 author: original.author,
97 author_url: original.authorUrl,
98 published: original.publishedText,
99 description: String::new(),
100 }
101 }
102}\ No newline at end of file
src/app/pages/main_menu.rs +44 −20
@@ -1,20 +1,21 @@
1use std::{collections::LinkedList, error::Error}; 1use std::{collections::LinkedList, error::Error};
2 2
3use futures::{executor::block_on, future::join_all};
4
3use crate::{ 5use crate::{
4 app::{ 6 app::{
5 app::{App, Item, Page, Row, RowItem}, 7 app::{App, Item, Page, Row, RowItem},
6 pages::global::{GlobalItem, ListItem, MiniVideo}, 8 pages::global::{GlobalItem, ListItem},
7 }, 9 },
8 traits::{KeyInput, LoadItem, SelectItem}, 10 traits::{KeyInput, LoadItem, SelectItem},
9 widgets::text_list::TextList, 11 widgets::text_list::TextList,
10}; 12};
11use crossterm::event::KeyCode; 13use crossterm::event::KeyCode;
12use invidious::{blocking::Client, structs::video::Video};
13use tui::layout::Constraint; 14use tui::layout::Constraint;
14#[derive(Debug, Clone)] 15#[derive(Debug, Clone)]
15pub enum MainMenuItem { 16pub enum MainMenuItem {
16 SeletorTab(MainMenuSelector), 17 SeletorTab(MainMenuSelector),
17 VideoList(Option<(LinkedList<ListItem>, TextList, usize)>), // Videos, List, page 18 VideoList(Option<(LinkedList<ListItem>, TextList, Option<usize>)>), // Videos, List, page
18} 19}
19 20
20// app.client.trending(None) 21// app.client.trending(None)
@@ -23,7 +24,12 @@ impl SelectItem for MainMenuItem {
23 fn select(&mut self, mut app: App) -> (App, bool) { 24 fn select(&mut self, mut app: App) -> (App, bool) {
24 let selected = match self { 25 let selected = match self {
25 MainMenuItem::SeletorTab(selector) => { 26 MainMenuItem::SeletorTab(selector) => {
27 if app.page == (Page::MainMenu { tab: *selector }) {
28 return (app, false);
29 }
26 app.page = Page::MainMenu { tab: *selector }; 30 app.page = Page::MainMenu { tab: *selector };
31 app.load = true;
32 app.message = Some(String::from("Loading videos..."));
27 false 33 false
28 } 34 }
29 35
@@ -41,6 +47,13 @@ impl SelectItem for MainMenuItem {
41impl KeyInput for MainMenuItem { 47impl KeyInput for MainMenuItem {
42 fn key_input(&mut self, key: KeyCode, app: App) -> App { 48 fn key_input(&mut self, key: KeyCode, app: App) -> App {
43 match self { 49 match self {
50 MainMenuItem::VideoList(Some((_, list, _))) => match key {
51 KeyCode::Up => list.up(),
52 KeyCode::Down => list.down(),
53 KeyCode::PageUp => list.selected = 0,
54 KeyCode::PageDown => list.selected = list.items.len() - 1,
55 _ => {}
56 },
44 _ => {} 57 _ => {}
45 } 58 }
46 59
@@ -56,7 +69,7 @@ impl LoadItem for MainMenuItem {
56 MainMenuItem::VideoList(enum_items) => match app.page { 69 MainMenuItem::VideoList(enum_items) => match app.page {
57 Page::MainMenu { tab } => match tab { 70 Page::MainMenu { tab } => match tab {
58 MainMenuSelector::Trending => { 71 MainMenuSelector::Trending => {
59 let mut list: LinkedList<ListItem> = app 72 let list: LinkedList<ListItem> = app
60 .client 73 .client
61 .trending(None)? 74 .trending(None)?
62 .videos 75 .videos
@@ -64,26 +77,41 @@ impl LoadItem for MainMenuItem {
64 .map(|t| ListItem::Video(t.into())) 77 .map(|t| ListItem::Video(t.into()))
65 .collect(); 78 .collect();
66 79
67 list.push_back(ListItem::PageTurner(true));
68
69 let mut text_list = TextList::default(); 80 let mut text_list = TextList::default();
70 81
71 if let Some((video_list, text_list, page)) = enum_items { 82 if let Some((video_list, text_list, _)) = enum_items {
72 if *page > 0 {
73 list.push_front(ListItem::PageTurner(false));
74 }
75
76 *text_list = TextList::default(); 83 *text_list = TextList::default();
77 text_list.items(textlist_from_video_list(&list)); 84 text_list.items(textlist_from_video_list(&list));
78 85
79 *video_list = list; 86 *video_list = list;
80 } else { 87 } else {
81 text_list.items(textlist_from_video_list(&list)); 88 text_list.items(textlist_from_video_list(&list));
82 *enum_items = Some((list, text_list, 0)); 89 *enum_items = Some((list, text_list, None));
83 }; 90 };
91 }
92
93 MainMenuSelector::Popular => {
94 let list: LinkedList<ListItem> = app
95 .client
96 .popular(None)?
97 .items
98 .into_iter()
99 .map(|t| ListItem::Video(t.into()))
100 .collect();
84 101
85 //let text_list = TextList::default().items(); 102 let mut text_list = TextList::default();
103
104 if let Some((video_list, text_list, _)) = enum_items {
105 *text_list = TextList::default();
106 text_list.items(textlist_from_video_list(&list));
107
108 *video_list = list;
109 } else {
110 text_list.items(textlist_from_video_list(&list));
111 *enum_items = Some((list, text_list, None));
112 };
86 } 113 }
114
87 _ => {} 115 _ => {}
88 }, 116 },
89 }, 117 },
@@ -104,18 +132,14 @@ fn textlist_from_video_list(original: &LinkedList<ListItem>) -> Vec<String> {
104 .chars() 132 .chars()
105 .map(|c| if c.is_ascii() { c } else { '?' }) 133 .map(|c| if c.is_ascii() { c } else { '?' })
106 .collect(), 134 .collect(),
107 ListItem::PageTurner(b) => { 135 _ => {
108 if *b { 136 unreachable!()
109 "Next Page".to_string()
110 } else {
111 "Previous Page".to_string()
112 }
113 } 137 }
114 }) 138 })
115 .collect() 139 .collect()
116} 140}
117 141
118#[derive(Debug, Clone, Copy)] 142#[derive(Debug, Clone, Copy, PartialEq)]
119pub enum MainMenuSelector { 143pub enum MainMenuSelector {
120 Trending, 144 Trending,
121 Popular, 145 Popular,
src/functions/download_all_thumbnails.rs added +52
@@ -0,0 +1,52 @@
1use std::{collections::LinkedList, error::Error, io::Cursor};
2
3use futures::executor::block_on;
4
5use crate::app::pages::global::ListItem;
6
7pub enum ItemType {
8 Video,
9 Playlist,
10}
11
12pub fn download_all_thumbnails(list: &LinkedList<ListItem>) -> Result<(), Box<dyn Error>>{
13 let mut urls: Vec<(&str, &str, ItemType)> = Vec::new();
14 for i in list.iter() {
15 match i {
16 ListItem::Video(video) => {
17 urls.push((&video.video_thumbnail, &video.video_id, ItemType::Video));
18 }
19 _ => {}
20 }
21 }
22
23 block_on(download_items(urls))?;
24
25 Ok(())
26}
27
28pub async fn download_items(urls: Vec<(&str, &str, ItemType)>) -> Result<(), Box<dyn Error>>{
29 let mut dir = home::home_dir().expect("Cannot get your home directory");
30 dir.push(".siriusmart");
31 dir.push("youtube-tui");
32 dir.push("cache");
33
34 for (url, video_id, item_type) in urls {
35 dir.push(match item_type {
36 ItemType::Video => "videos",
37 ItemType::Playlist => "playlists",
38 });
39
40 fetch_url(url, &format!("{:?}/{}.png", dir, video_id)).await?;
41 }
42
43 Ok(())
44}
45
46async fn fetch_url(url: &str, file_name: &str) -> Result<(), Box<dyn Error>> {
47 let response = reqwest::get(url).await?;
48 let mut file = std::fs::File::create(file_name)?;
49 let mut content = Cursor::new(response.bytes().await?);
50 std::io::copy(&mut content, &mut file)?;
51 Ok(())
52}\ No newline at end of file
src/functions/mod.rs added +2
@@ -0,0 +1,2 @@
1mod download_all_thumbnails;
2pub use download_all_thumbnails::*;\ No newline at end of file
src/lib.rs +1
@@ -1,4 +1,5 @@
1pub mod app; 1pub mod app;
2pub mod traits; 2pub mod traits;
3pub mod widgets; 3pub mod widgets;
4pub mod functions;
4mod render;\ No newline at end of file 5mod render;\ No newline at end of file
src/main.rs +49 −2
@@ -3,7 +3,7 @@ use crossterm::{
3 execute, 3 execute,
4 terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, 4 terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
5}; 5};
6use std::{error::Error, io}; 6use std::{error::Error, fs, io, path::Path};
7use tui::{ 7use tui::{
8 backend::{Backend, CrosstermBackend}, 8 backend::{Backend, CrosstermBackend},
9 Terminal, 9 Terminal,
@@ -14,6 +14,8 @@ use youtube_tui::{
14}; 14};
15 15
16fn main() -> Result<(), Box<dyn Error>> { 16fn main() -> Result<(), Box<dyn Error>> {
17 init()?;
18
17 let app = App::new(); 19 let app = App::new();
18 20
19 enable_raw_mode()?; 21 enable_raw_mode()?;
@@ -31,7 +33,9 @@ fn main() -> Result<(), Box<dyn Error>> {
31 )?; 33 )?;
32 disable_raw_mode()?; 34 disable_raw_mode()?;
33 35
34 res 36 res?;
37
38 Ok(())
35} 39}
36 40
37fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(), Box<dyn Error>> { 41fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(), Box<dyn Error>> {
@@ -111,3 +115,46 @@ fn ui<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> Result<(), Box<d
111 115
112 Ok(()) 116 Ok(())
113} 117}
118
119fn init() -> Result<(), Box<dyn Error>> {
120 let mut dir = home::home_dir().expect("Cannot get your home directory");
121
122 dir.push(".siriusmart");
123 if !dir.exists() {
124 fs::create_dir(&dir)?;
125 }
126
127 dir.push("youtube-tui");
128 if !dir.exists() {
129 fs::create_dir(&dir)?;
130 }
131
132 dir.push("cache");
133
134 if dir.exists() {
135 fs::remove_dir_all(&dir)?;
136 }
137 fs::create_dir(&dir)?;
138
139 dir.push("thumbnails");
140
141 if !dir.exists() {
142 fs::create_dir(&dir)?;
143 }
144
145 dir.push("videos");
146
147 if !dir.exists() {
148 fs::create_dir(&dir)?;
149 }
150
151 dir.pop();
152
153 dir.push("playlists");
154
155 if !dir.exists() {
156 fs::create_dir(&dir)?;
157 }
158
159 Ok(())
160}
src/render/pages/global.rs +17 −10
@@ -1,4 +1,7 @@
1use crate::{app::{pages::global::GlobalItem, app::App}, traits::RenderItem}; 1use crate::{
2 app::{app::App, pages::global::GlobalItem},
3 traits::RenderItem,
4};
2use tui::{ 5use tui::{
3 backend::Backend, 6 backend::Backend,
4 layout::{Alignment, Rect}, 7 layout::{Alignment, Rect},
@@ -19,17 +22,16 @@ impl GlobalItem {
19 ) { 22 ) {
20 match self { 23 match self {
21 GlobalItem::SearchBar(search) => { 24 GlobalItem::SearchBar(search) => {
22 let style = Style::default().fg(if selected {
23 Color::LightBlue
24 } else if hover {
25 Color::LightRed
26 } else {
27 Color::Reset
28 });
29 let block = Block::default() 25 let block = Block::default()
30 .border_type(BorderType::Rounded) 26 .border_type(BorderType::Rounded)
31 .borders(Borders::ALL) 27 .borders(Borders::ALL)
32 .style(style) 28 .border_style(Style::default().fg(if selected {
29 Color::LightBlue
30 } else if hover {
31 Color::LightRed
32 } else {
33 Color::Reset
34 }))
33 .title("Search YouTube") 35 .title("Search YouTube")
34 .title_alignment(Alignment::Center); 36 .title_alignment(Alignment::Center);
35 let paragraph = Paragraph::new(search.clone()).block(block); 37 let paragraph = Paragraph::new(search.clone()).block(block);
@@ -39,7 +41,12 @@ impl GlobalItem {
39 // let color = Color::LightYellow; 41 // let color = Color::LightYellow;
40 let block = Block::default() 42 let block = Block::default()
41 .border_type(BorderType::Rounded) 43 .border_type(BorderType::Rounded)
42 .borders(Borders::ALL); 44 .borders(Borders::ALL)
45 .border_style(Style::default().fg(if message.is_some() {
46 Color::LightRed
47 } else {
48 Color::Reset
49 }));
43 let paragraph = 50 let paragraph =
44 Paragraph::new(message.clone().unwrap_or(String::from("All good :)"))) 51 Paragraph::new(message.clone().unwrap_or(String::from("All good :)")))
45 .block(block); 52 .block(block);
src/render/pages/main_menu.rs +30 −23
@@ -1,24 +1,26 @@
1use crate::{ 1use crate::{
2 app::{pages::main_menu::{MainMenuItem, MainMenuSelector}, app::App}, 2 app::{pages::main_menu::{MainMenuItem, MainMenuSelector}, app::Page},
3 traits::RenderItem, 3 traits::RenderItem,
4 widgets::horizontal_split::HorizontalSplit,
4}; 5};
5use tui::{ 6use tui::{
6 backend::Backend, 7 backend::Backend,
7 layout::{Alignment, Constraint, Layout, Rect, Direction}, 8 layout::{Alignment, Constraint, Direction, Layout, Rect},
8 style::{Color, Style}, 9 style::{Color, Style},
9 widgets::{Block, BorderType, Borders, Paragraph}, 10 widgets::{Block, BorderType, Borders, Paragraph},
10 Frame, 11 Frame,
11}; 12};
12 13
13impl RenderItem for MainMenuItem { 14impl MainMenuItem {
14 fn render_item<B: Backend>( 15 pub fn render_item<B: Backend>(
15 &mut self, 16 &mut self,
16 frame: &mut Frame<B>, 17 frame: &mut Frame<B>,
17 rect: Rect, 18 rect: Rect,
18 selected: bool, 19 selected: bool,
19 hover: bool, 20 hover: bool,
21 page: &Page
20 ) { 22 ) {
21 let style = Style::default().fg(if selected { 23 let mut style = Style::default().fg(if selected {
22 Color::LightBlue 24 Color::LightBlue
23 } else if hover { 25 } else if hover {
24 Color::LightRed 26 Color::LightRed
@@ -28,6 +30,9 @@ impl RenderItem for MainMenuItem {
28 30
29 match self { 31 match self {
30 MainMenuItem::SeletorTab(selector) => { 32 MainMenuItem::SeletorTab(selector) => {
33 if !hover && page == &(Page::MainMenu { tab: *selector }){
34 style = style.fg(Color::LightYellow);
35 }
31 let text = match selector { 36 let text = match selector {
32 MainMenuSelector::Trending => "Trending", 37 MainMenuSelector::Trending => "Trending",
33 MainMenuSelector::Popular => "Popular", 38 MainMenuSelector::Popular => "Popular",
@@ -45,28 +50,30 @@ impl RenderItem for MainMenuItem {
45 frame.render_widget(paragraph, rect); 50 frame.render_widget(paragraph, rect);
46 } 51 }
47 MainMenuItem::VideoList(data) => { 52 MainMenuItem::VideoList(data) => {
48 let chunks = Layout::default() 53 let split = HorizontalSplit::default()
49 .constraints([Constraint::Percentage(40), Constraint::Percentage(60)].as_ref()) 54 .percentages(vec![40, 60])
50 .direction(Direction::Horizontal) 55 .border_style(Style::default().fg(if selected {
51 .split(rect); 56 Color::LightBlue
52 57 } else if hover {
53 let block = Block::default() 58 Color::LightRed
54 .border_type(BorderType::Rounded) 59 } else {
55 .borders(Borders::ALL) 60 Color::Reset
56 .border_style(style); 61 }));
57 62
58 let inner = block.inner(chunks[0]); 63 let chunks = split.inner(rect);
59 64
60 frame.render_widget(block, chunks[0]); 65 frame.render_widget(split, rect);
61
62 let block = Block::default()
63 .border_type(BorderType::Rounded)
64 .borders(Borders::ALL);
65 frame.render_widget(block, chunks[1]);
66 66
67 if let Some((videos, list, _)) = data { 67 if let Some((videos, list, _)) = data {
68 list.area(inner); 68 list.area(chunks[0]);
69 frame.render_widget(list.clone(), inner); 69 let mut list = list.clone();
70
71 if selected {
72 list.selected_style(Style::default().fg(Color::LightRed));
73 } else {
74 list.selected_style(Style::default().fg(Color::LightYellow));
75 }
76 frame.render_widget(list, chunks[0]);
70 } 77 }
71 } 78 }
72 } 79 }
src/render/render.rs +1 −1
@@ -88,7 +88,7 @@ impl App {
88 i.render_item(frame, chunk, selected, hover, &self.message); 88 i.render_item(frame, chunk, selected, hover, &self.message);
89 } 89 }
90 Item::MainMenu(i) => { 90 Item::MainMenu(i) => {
91 i.render_item(frame, chunk, selected, hover); 91 i.render_item(frame, chunk, selected, hover, &self.page);
92 } 92 }
93 } 93 }
94 } 94 }
src/widgets/horizontal_split.rs added +168
@@ -0,0 +1,168 @@
1use tui::{
2 buffer::Buffer,
3 layout::Rect,
4 style::Style,
5 symbols::line::{
6 HORIZONTAL, HORIZONTAL_DOWN, HORIZONTAL_UP, ROUNDED_BOTTOM_LEFT, ROUNDED_BOTTOM_RIGHT,
7 ROUNDED_TOP_LEFT, ROUNDED_TOP_RIGHT, VERTICAL,
8 },
9 widgets::Widget,
10};
11
12#[derive(Debug, Clone)]
13pub struct HorizontalSplit {
14 pub percentages: Vec<usize>,
15 pub border_style: Style,
16}
17
18impl Widget for HorizontalSplit {
19 fn render(self, rect: Rect, buffer: &mut Buffer) {
20 let mut width_left = rect.width as usize;
21
22 let widths = self
23 .percentages
24 .iter()
25 .enumerate()
26 .map(|(i, p)| {
27 if i == self.percentages.len() - 1 {
28 return width_left;
29 }
30 let width = p * rect.width as usize / 100;
31 width_left -= width;
32 width
33 })
34 .collect::<Vec<_>>();
35
36 let mut top = String::new();
37 let mut mid = String::new();
38 let mut bottom = String::new();
39
40 buffer.set_style(Rect { height: 1, ..rect }, self.border_style);
41 buffer.set_style(
42 Rect {
43 height: 1,
44 y: rect.y + rect.height - 1,
45 ..rect
46 },
47 self.border_style,
48 );
49
50 buffer.set_style(
51 Rect {
52 x: rect.x + rect.width - 1,
53 y: rect.y + 1,
54 width: 1,
55 height: rect.height - 2,
56 },
57 self.border_style,
58 );
59
60 let mut x = rect.x;
61
62 for (index, width) in widths.iter().enumerate() {
63 buffer.set_style(
64 Rect {
65 x,
66 y: rect.y + 1,
67 width: 1,
68 height: rect.height - 2,
69 },
70 self.border_style,
71 );
72
73 x += *width as u16;
74
75 if index == 0 {
76 top.push_str(ROUNDED_TOP_LEFT);
77 bottom.push_str(ROUNDED_BOTTOM_LEFT);
78 } else {
79 top.push_str(HORIZONTAL_DOWN);
80 bottom.push_str(HORIZONTAL_UP);
81 }
82
83 mid.push_str(VERTICAL);
84
85 if index == widths.len() - 1 {
86 top.push_str(&HORIZONTAL.repeat(*width - 2));
87 mid.push_str(&" ".repeat(*width - 2));
88 bottom.push_str(&HORIZONTAL.repeat(*width - 2));
89
90 top.push_str(ROUNDED_TOP_RIGHT);
91 mid.push_str(VERTICAL);
92 bottom.push_str(ROUNDED_BOTTOM_RIGHT);
93 } else {
94 top.push_str(&HORIZONTAL.repeat(*width - 1));
95 mid.push_str(&" ".repeat(*width - 1));
96 bottom.push_str(&HORIZONTAL.repeat(*width - 1));
97 }
98 }
99
100 buffer.set_string(rect.x, rect.y, &top, Style::default());
101
102 for y in rect.y + 1..rect.y + rect.height - 1 {
103 buffer.set_string(rect.x, y, &mid, Style::default());
104 }
105
106 buffer.set_string(rect.x, rect.y + rect.height - 1, &bottom, Style::default());
107 }
108}
109
110impl Default for HorizontalSplit {
111 fn default() -> Self {
112 HorizontalSplit {
113 percentages: vec![50, 50],
114 border_style: Style::default(),
115 }
116 }
117}
118
119impl HorizontalSplit {
120 pub fn inner(&self, rect: Rect) -> Vec<Rect> {
121 let mut width_left = rect.width as usize;
122
123 let widths = self
124 .percentages
125 .iter()
126 .enumerate()
127 .map(|(i, p)| {
128 if i == self.percentages.len() - 1 {
129 return width_left;
130 }
131 let width = p * rect.width as usize / 100;
132 width_left -= width;
133 width
134 })
135 .collect::<Vec<_>>();
136
137 let mut x = rect.x as usize + 1;
138
139 widths
140 .iter()
141 .enumerate()
142 .map(|(i, width)| {
143 let cell_rect = Rect {
144 x: x as u16,
145 y: rect.y + 1,
146 width: *width as u16 - if i == widths.len() - 1 { 2 } else { 1 },
147 height: rect.height - 2,
148 };
149 x += width;
150 cell_rect
151 })
152 .collect::<Vec<_>>()
153 }
154
155 pub fn percentages(self, percentages: Vec<usize>) -> Self{
156 Self {
157 percentages,
158 ..self
159 }
160 }
161
162 pub fn border_style(self, border_style: Style) -> Self {
163 Self {
164 border_style,
165 ..self
166 }
167 }
168}
src/widgets/item_info.rs added +3
@@ -0,0 +1,3 @@
1pub struct ItemInfo {
2
3}\ No newline at end of file
src/widgets/mod.rs +2 −1
@@ -1 +1,2 @@
1pub mod text_list;\ No newline at end of file 1pub mod text_list;
2pub mod horizontal_split;\ No newline at end of file
src/widgets/text_list.rs +18 −6
@@ -15,6 +15,8 @@ pub struct TextList {
15 pub selected: usize, 15 pub selected: usize,
16 pub scroll: usize, 16 pub scroll: usize,
17 pub area: Option<Rect>, 17 pub area: Option<Rect>,
18 pub style: Style,
19 pub selected_style: Style,
18} 20}
19 21
20impl Widget for TextList { 22impl Widget for TextList {
@@ -27,6 +29,8 @@ impl Widget for TextList {
27 let width_minus_5 = (area.width - 5) as usize; 29 let width_minus_5 = (area.width - 5) as usize;
28 let mut y = area.y; 30 let mut y = area.y;
29 31
32 buf.set_style(area, self.style);
33
30 for (i, mut item) in self 34 for (i, mut item) in self
31 .items 35 .items
32 .into_iter() 36 .into_iter()
@@ -55,15 +59,13 @@ impl Widget for TextList {
55 ROUNDED_BOTTOM_RIGHT, 59 ROUNDED_BOTTOM_RIGHT,
56 ); 60 );
57 61
58 let color = Color::LightYellow;
59
60 let mut rect = Rect { 62 let mut rect = Rect {
61 x: area.x, 63 x: area.x,
62 y: y, 64 y: y,
63 width: area.width, 65 width: area.width,
64 height: 1, 66 height: 1,
65 }; 67 };
66 buf.set_style(rect, Style::default().fg(color)); 68 buf.set_style(rect, self.selected_style);
67 69
68 rect = Rect { 70 rect = Rect {
69 x: area.x, 71 x: area.x,
@@ -71,7 +73,7 @@ impl Widget for TextList {
71 width: 1, 73 width: 1,
72 height: 1, 74 height: 1,
73 }; 75 };
74 buf.set_style(rect, Style::default().fg(color)); 76 buf.set_style(rect, self.selected_style);
75 77
76 rect = Rect { 78 rect = Rect {
77 x: area.x + area.width - 1, 79 x: area.x + area.width - 1,
@@ -79,7 +81,7 @@ impl Widget for TextList {
79 width: 1, 81 width: 1,
80 height: 1, 82 height: 1,
81 }; 83 };
82 buf.set_style(rect, Style::default().fg(color)); 84 buf.set_style(rect, self.selected_style);
83 85
84 rect = Rect { 86 rect = Rect {
85 x: area.x, 87 x: area.x,
@@ -87,7 +89,7 @@ impl Widget for TextList {
87 width: area.width, 89 width: area.width,
88 height: 1, 90 height: 1,
89 }; 91 };
90 buf.set_style(rect, Style::default().fg(color)); 92 buf.set_style(rect, self.selected_style);
91 93
92 for line in lines.lines() { 94 for line in lines.lines() {
93 for (x, c) in (0..area.width).zip(line.chars()) { 95 for (x, c) in (0..area.width).zip(line.chars()) {
@@ -112,6 +114,8 @@ impl Default for TextList {
112 selected: 0, 114 selected: 0,
113 scroll: 0, 115 scroll: 0,
114 area: None, 116 area: None,
117 style: Style::default(),
118 selected_style: Style::default().fg(Color::Yellow),
115 } 119 }
116 } 120 }
117} 121}
@@ -146,4 +150,12 @@ impl TextList {
146 } 150 }
147 } 151 }
148 } 152 }
153
154 pub fn style(&mut self, style: Style) {
155 self.style = style;
156 }
157
158 pub fn selected_style(&mut self, style: Style) {
159 self.selected_style = style;
160 }
149} 161}