├── .gitattributes ├── src ├── components │ ├── mod.rs │ ├── static_widgets.rs │ └── station_list.rs ├── constants.rs ├── main.rs ├── tui.rs ├── event.rs ├── update.rs ├── api.rs ├── ui.rs └── app.rs ├── .gitignore ├── .github └── FUNDING.yml ├── LICENSE ├── Cargo.toml └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /src/components/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod static_widgets; 2 | pub mod station_list; 3 | // I expose the static_widgets module from the components module. 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 8 | Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # MSVC Windows builds of rustc generate these, which store debugging information 14 | *.pdb 15 | .DS_Store 16 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: faisalbin 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 12 | polar: # Replace with a single Polar username 13 | buy_me_a_coffee: faisalbin 14 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Faisal Bin Ahmed 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/components/static_widgets.rs: -------------------------------------------------------------------------------- 1 | use ratatui::{ 2 | prelude::{Alignment, Constraint, Direction, Layout, Rect}, 3 | widgets::{Block, BorderType, Borders}, 4 | }; 5 | 6 | pub fn get_app_border() -> Block<'static> { 7 | return Block::default() 8 | .borders(Borders::ALL) 9 | .title(" MVG Departures ") 10 | .border_type(BorderType::Rounded) 11 | .title_alignment(Alignment::Center); 12 | } 13 | 14 | pub fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect { 15 | let popup_layout = Layout::default() 16 | .direction(Direction::Vertical) 17 | .constraints([ 18 | Constraint::Percentage((100 - percent_y) / 2), 19 | Constraint::Percentage(percent_y), 20 | Constraint::Percentage((100 - percent_y) / 2), 21 | ]) 22 | .split(r); 23 | 24 | Layout::default() 25 | .direction(Direction::Horizontal) 26 | .constraints([ 27 | Constraint::Percentage((100 - percent_x) / 2), 28 | Constraint::Percentage(percent_x), 29 | Constraint::Percentage((100 - percent_x) / 2), 30 | ]) 31 | .split(popup_layout[1])[1] 32 | } 33 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mvgfahrinfo" 3 | description = "Get up-to-date departure times for Munich public transport in your terminal." 4 | version = "1.2.0" 5 | edition = "2021" 6 | 7 | authors = ["Faisal Ahmed"] 8 | include = [ 9 | "src/**/*", 10 | "Cargo.toml", 11 | "README.md", 12 | "LICENCE" 13 | ] 14 | homepage = "https://github.com/FaisalBinAhmed/MVGFahrinfo" 15 | repository = "https://github.com/FaisalBinAhmed/MVGFahrinfo" 16 | keywords = [ 17 | "cli", 18 | "munich", 19 | "public-transport", 20 | "mvg", 21 | "ubahn" 22 | ] 23 | categories = ["command-line-interface"] 24 | license = "MIT" 25 | 26 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 27 | 28 | [dependencies] 29 | reqwest = { version = "0.11", features = ["json"] } # for http requests 30 | tokio = { version = "1", features = ["full"] } # for async runtime 31 | serde_json = "1" # for json parsing 32 | serde = { version = "1.0", features = ["derive"] } # for serialization and deserialization 33 | anyhow = "1" # for generic error handling 34 | ratatui = "0.23.0" # terminal ui framework 35 | crossterm = "0.27.0" # for terminal manipulation 36 | chrono = "0.4.31" # for date and time 37 | phf = { version = "0.11", features = ["macros"] } # for static hashmap -------------------------------------------------------------------------------- /src/constants.rs: -------------------------------------------------------------------------------- 1 | use phf::phf_map; 2 | use ratatui::style::Color; 3 | 4 | static UBAHN_COLOR: phf::Map<&'static str, Color> = phf_map! { 5 | "U1" => Color::Rgb(60, 114, 53), 6 | "U2" => Color::Rgb(167, 45, 66), 7 | "U3" => Color::Rgb(235, 103, 32), 8 | "U4" => Color::Rgb(1, 171, 133), 9 | "U5" => Color::Rgb(190, 123, 0), 10 | "U6" => Color::Rgb(1, 101, 175), 11 | "U7" => Color::Rgb(79, 131, 43), 12 | "U8" => Color::Rgb(167, 45, 67), 13 | }; 14 | 15 | static SBAHN_COLOR: phf::Map<&'static str, Color> = phf_map! { 16 | "S1" => Color::Rgb(16, 194, 233), 17 | "S2" => Color::Rgb(113, 193, 70), 18 | "S3" => Color::Rgb(118, 25, 113), 19 | "S4" => Color::Rgb(118, 25, 113), 20 | // "S5" => Color::Rgb(0, 0, 0), 21 | "S6" => Color::Rgb(3, 139, 79), 22 | "S7" => Color::Rgb(151, 53, 48), 23 | "S8" => Color::Rgb(0, 0, 0), 24 | }; 25 | 26 | pub fn get_ubahn_color(keyword: &str) -> Color { 27 | return match UBAHN_COLOR.get(keyword) { 28 | Some(color) => *color, 29 | None => Color::Rgb(29, 43, 83), 30 | }; 31 | } 32 | 33 | pub fn get_sbahn_color(keyword: &str) -> Color { 34 | return match SBAHN_COLOR.get(keyword) { 35 | Some(color) => *color, 36 | None => Color::Rgb(84, 253, 84), 37 | }; 38 | } 39 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; //to avoid writing the error type everywhere 2 | 3 | pub mod api; 4 | pub mod app; 5 | pub mod components; 6 | pub mod constants; 7 | pub mod event; 8 | pub mod tui; 9 | pub mod ui; 10 | pub mod update; 11 | 12 | //own modules 13 | 14 | use app::App; 15 | use event::{Event, EventHandler}; 16 | use tui::Tui; 17 | use update::update; 18 | 19 | use ratatui::prelude::{CrosstermBackend, Terminal}; 20 | 21 | use crate::update::initiate_auto_refresh; 22 | 23 | pub type Frame<'a> = ratatui::Frame<'a, CrosstermBackend>; // alias for the frame type 24 | 25 | #[tokio::main] 26 | async fn main() -> Result<()> { 27 | println!("fetching stations..."); 28 | 29 | let backend = CrosstermBackend::new(std::io::stderr()); 30 | let terminal = Terminal::new(backend)?; 31 | let events = EventHandler::new(250); 32 | 33 | let sender = events.sender.clone(); //we can clone it as we can have multiple senders for this channel 34 | 35 | let mut app = App::new().await; 36 | 37 | initiate_auto_refresh(sender); 38 | 39 | let mut tui = Tui::new(terminal, events); 40 | tui.enter()?; 41 | 42 | while !app.should_quit { 43 | if app.should_redraw { 44 | //this makes sure that we don't redraw the screen if there is no change 45 | tui.draw(&mut app)?; 46 | app.should_redraw = false; 47 | } 48 | 49 | match tui.events.next().await? { 50 | Event::Tick => {} //every 250ms we get a tick event, we ignore it 51 | Event::Key(key_event) => update(&mut app, key_event).await, 52 | }; 53 | } 54 | 55 | tui.exit()?; 56 | return Ok(()); 57 | } 58 | -------------------------------------------------------------------------------- /src/tui.rs: -------------------------------------------------------------------------------- 1 | use std::{io, panic}; 2 | 3 | use anyhow::Result; 4 | use crossterm::{ 5 | event::{DisableMouseCapture, EnableMouseCapture}, 6 | terminal::{self, EnterAlternateScreen, LeaveAlternateScreen}, 7 | }; 8 | 9 | pub type Frame<'a> = ratatui::Frame<'a, ratatui::backend::CrosstermBackend>; 10 | pub type CrosstermTerminal = ratatui::Terminal>; 11 | 12 | use crate::{app::App, event::EventHandler, ui}; 13 | 14 | pub struct Tui { 15 | terminal: CrosstermTerminal, 16 | pub events: EventHandler, 17 | } 18 | 19 | // boilerplate code from the ratatui book 20 | 21 | impl Tui { 22 | pub fn new(terminal: CrosstermTerminal, events: EventHandler) -> Self { 23 | Self { terminal, events } //setting own fields and returning an instance of the struct 24 | } 25 | pub fn enter(&mut self) -> Result<()> { 26 | terminal::enable_raw_mode()?; // we handle all the key events 27 | crossterm::execute!(io::stderr(), EnterAlternateScreen, EnableMouseCapture)?; 28 | let panic_hook = panic::take_hook(); 29 | panic::set_hook(Box::new(move |panic| { 30 | Self::reset().expect("failed to reset the terminal"); 31 | panic_hook(panic); 32 | })); 33 | 34 | self.terminal.hide_cursor()?; 35 | self.terminal.clear()?; // in case of panic, we clear the terminal 36 | Ok(()) 37 | } 38 | 39 | pub fn draw(&mut self, app: &mut App) -> Result<()> { 40 | self.terminal.draw(|frame| ui::render(app, frame))?; 41 | Ok(()) 42 | } 43 | 44 | fn reset() -> Result<()> { 45 | terminal::disable_raw_mode()?; 46 | crossterm::execute!(io::stderr(), LeaveAlternateScreen, DisableMouseCapture)?; 47 | Ok(()) 48 | } 49 | 50 | pub fn exit(&mut self) -> Result<()> { 51 | Self::reset()?; 52 | self.terminal.show_cursor()?; 53 | Ok(()) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/event.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use crossterm::event::{self, Event as CrosstermEvent, KeyEvent}; 3 | use std::time::{Duration, Instant}; 4 | 5 | /// reference: https://ratatui.rs/tutorial/counter-app/event.html 6 | 7 | #[derive(Clone, Copy, Debug)] 8 | pub enum Event { 9 | Tick, 10 | Key(KeyEvent), 11 | } 12 | 13 | #[derive(Debug)] 14 | pub struct EventHandler { 15 | pub sender: tokio::sync::mpsc::UnboundedSender, 16 | receiver: tokio::sync::mpsc::UnboundedReceiver, 17 | } 18 | 19 | impl EventHandler { 20 | pub fn new(tick_rate: u64) -> Self { 21 | let tick_rate = Duration::from_millis(tick_rate); 22 | let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); 23 | let _handler = { 24 | let sender = sender.clone(); 25 | tokio::spawn(async move { 26 | let mut last_tick = Instant::now(); 27 | loop { 28 | let timeout = tick_rate 29 | .checked_sub(last_tick.elapsed()) 30 | .unwrap_or(tick_rate); 31 | 32 | if event::poll(timeout).expect("no events available") { 33 | match event::read().expect("unable to read event") { 34 | CrosstermEvent::Key(e) => { 35 | if e.kind == event::KeyEventKind::Press { 36 | sender.send(Event::Key(e)) 37 | } else { 38 | Ok(()) // ignore KeyEventKind::Release on windows 39 | } 40 | } 41 | _ => { 42 | // ignore other events 43 | Ok(()) 44 | } 45 | } 46 | .expect("failed to send terminal event") 47 | } 48 | 49 | if last_tick.elapsed() >= tick_rate { 50 | sender.send(Event::Tick).expect("failed to send tick event"); 51 | last_tick = Instant::now(); 52 | } 53 | } 54 | }) 55 | }; 56 | Self { sender, receiver } 57 | } 58 | 59 | pub async fn next(&mut self) -> Result { 60 | self.receiver 61 | .recv() 62 | .await 63 | .ok_or_else(|| anyhow::anyhow!("failed to receive event from event handler")) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MVG Fahrinfo 2 | 3 | MVG Fahrinfo is a CLI tool to keep up-to-date with latest departure times of Munich public transport. 4 | The app is a native binary and uses official (albeit unpublished) MVG API. 5 | 6 | It is made with Rust. 🦀 7 | 8 | It features: 9 | 10 | - Very low resource usage. 11 | - Beautiful terminal interface. 12 | - Automatic refreshing of departures. 13 | - Searching of stations. 14 | - Saving stations to file. 15 | - Real-life colors for vehicles for easier identification. 16 | - Easy navigation with shortcuts. 17 | 18 | ## Using 19 | 20 | Clone the repository and run `cargo run` in the root directory. 21 | In the first run, it will fetch the stations list from the server and save it to `stations.json` file. 22 | 23 | To force update the stations list file, just delete the file and run the app again. 24 | The app will stay open in your terminal and will refresh the departures every 60 seconds. 25 | 26 | To exit the app, press `q` or `Ctrl+C`. 27 | 28 | ## Installing 29 | 30 | To run it globally, you can install the app with `cargo binstall mvgfahrinfo`. Make sure you have `binstall` [binstall repo](https://github.com/cargo-bins/cargo-binstall) installed. Once installed, you can invoke the app just by running `mvgfahrinfo` in the terminal. 31 | This is a binary crate and not a library, so you shouldn't use it as a dependency. 32 | 33 | I might provide some pre-built binaries for Windows/MacOS/Linux in the future. :) 34 | 35 | ## Shortcuts 36 | 37 | ### Normal mode 38 | 39 | - `tab` - Switch between departures and stations list. 40 | - `r` - Refresh departures. 41 | - `s` - Search for a station. 42 | - `Up/Down` - Navigate through the list of stations. 43 | - `Enter` - Select a station. 44 | - `q` - Quit the app. 45 | - `Ctrl+C` - Quit the app. 46 | 47 | ### Search mode 48 | 49 | - `Esc` - Exit search mode. 50 | - `Up/Down` - Navigate through the list of stations. 51 | - `Enter` - Select a station. 52 | 53 | ## Screenshots 54 | 55 | ![Current Departures in Munich Hauptbahnhof](https://imgur.com/jsHDPsd.png) 56 | ![All stations list](https://imgur.com/8hVONcX.png) 57 | ![Station search](https://imgur.com/7d4Xk6Q.png) 58 | 59 | ## Credits 60 | 61 | - [MVG](https://mvg.de) for the API. 62 | - Ratatui for the beautiful terminal interface framework. 63 | 64 | ## License 65 | 66 | MIT 67 | 68 | ### Limitations 69 | 70 | Currently, the app only handles ASCII or 1 byte UTF-8 character input. If you are searching a station with non-ASCII characters (i.e. "ö", "ß" etc.) in its name, the app will ignore the input. Please type the closest characters & scroll a bit down to select the station from the list (this will be fixed at a later version.) 71 | -------------------------------------------------------------------------------- /src/update.rs: -------------------------------------------------------------------------------- 1 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; 2 | use ratatui::widgets::ListState; 3 | 4 | use crate::{ 5 | app::{App, AppMode}, 6 | event::Event, 7 | }; 8 | 9 | //todo: should_redraw refactor 10 | pub async fn update(app: &mut App, key_event: KeyEvent) { 11 | match app.app_mode { 12 | AppMode::Normal => match key_event.code { 13 | KeyCode::Char('q') => app.quit(), 14 | KeyCode::Char('s') => { 15 | app.app_mode = AppMode::Search; 16 | app.should_redraw = true; 17 | } 18 | KeyCode::Char('r') => { 19 | app.update_departures().await; 20 | // app.should_redraw = true; 21 | } 22 | KeyCode::Down => { 23 | app.increment_station(); 24 | app.should_redraw = true; 25 | } 26 | KeyCode::Up => { 27 | app.decrement_station(); 28 | app.should_redraw = true; 29 | } 30 | KeyCode::Enter => { 31 | app.select_station().await; 32 | app.should_redraw = true; 33 | } 34 | KeyCode::Tab => { 35 | app.toggle_tabs(); 36 | app.should_redraw = true; 37 | } 38 | KeyCode::Char('c') | KeyCode::Char('C') => { 39 | if key_event.modifiers == KeyModifiers::CONTROL { 40 | app.quit() 41 | } 42 | } 43 | _ => { 44 | // todo: pass the key event? 45 | } 46 | }, 47 | AppMode::Search => match key_event.code { 48 | KeyCode::Enter => { 49 | app.select_searched_station().await; 50 | app.should_redraw = true; 51 | } 52 | KeyCode::Char(to_insert) => { 53 | app.search_scroll_state = ListState::default(); 54 | app.enter_char(to_insert); 55 | app.should_redraw = true; 56 | } 57 | KeyCode::Backspace => { 58 | app.search_scroll_state = ListState::default(); 59 | app.delete_char(); 60 | app.should_redraw = true; 61 | } 62 | KeyCode::Down => { 63 | app.scroll_down(); 64 | app.should_redraw = true; 65 | } 66 | KeyCode::Up => { 67 | app.scroll_up(); 68 | app.should_redraw = true; 69 | } 70 | KeyCode::Left => { 71 | app.move_cursor_left(); 72 | app.should_redraw = true; 73 | } 74 | KeyCode::Right => { 75 | app.move_cursor_right(); 76 | app.should_redraw = true; 77 | } 78 | KeyCode::Esc => { 79 | app.app_mode = AppMode::Normal; 80 | app.should_redraw = true; 81 | } 82 | _ => {} 83 | }, 84 | } 85 | } 86 | 87 | // this lets us mutate the app state without having to pass a mutable reference and blocking the main ui/event thread or having to use a mutex 88 | // we simulate the refresh command by sending a key event to the event handler 89 | // the event handler has a mutable reference to the app and can mutate it 90 | pub fn initiate_auto_refresh(sender: tokio::sync::mpsc::UnboundedSender) { 91 | tokio::spawn(async move { 92 | loop { 93 | tokio::time::sleep(std::time::Duration::from_secs(60)).await; 94 | // println!("sending refresh event"); 95 | let _ = sender.send(Event::Key(KeyEvent::from(KeyCode::Char('r')))); 96 | } 97 | }); 98 | } 99 | -------------------------------------------------------------------------------- /src/api.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | 3 | // #[allow(unused, dead_code, unused_)] 4 | use anyhow::Result; 5 | use serde::{Deserialize, Serialize}; 6 | 7 | #[derive(Debug, Deserialize, Clone)] 8 | #[serde(rename_all = "camelCase")] //to avoid renaming all the fields to snake_case 9 | pub struct StationInfo { 10 | pub house_number: String, 11 | pub latitude: f32, 12 | pub longitude: f32, 13 | pub name: String, 14 | pub place: String, 15 | pub post_code: String, 16 | pub street: String, 17 | pub r#type: String, //type is a reserved keyword in Rust 18 | } 19 | 20 | #[derive(Debug, Deserialize, Clone)] 21 | #[serde(rename_all = "camelCase")] //to avoid renaming all the fields to snake_case 22 | pub struct DepartureInfo { 23 | pub planned_departure_time: i64, 24 | pub realtime: bool, 25 | pub delay_in_minutes: Option, 26 | pub realtime_departure_time: i64, // utc time stamp 27 | pub transport_type: String, //"UBAHN", 28 | pub label: String, //"U8", 29 | pub diva_id: String, //"010U8", 30 | pub network: String, //"swm", 31 | pub train_type: String, //"", 32 | pub destination: String, //"Messestadt Ost", 33 | pub cancelled: bool, 34 | pub sev: bool, 35 | pub platform: Option, 36 | pub messages: Vec, 37 | pub banner_hash: String, //"", 38 | pub occupancy: String, //"UNKNOWN", 39 | pub stop_point_global_id: String, //"de:09162:6:52:52" 40 | } 41 | 42 | pub async fn get_departures(id: &str) -> Result> { 43 | let full_url = format!("https://www.mvg.de/api/bgw-pt/v3/departures?globalId={}", id); 44 | 45 | let resp = reqwest::get(full_url) 46 | .await? 47 | .json::>() 48 | .await?; 49 | // println!("{:#?}", resp[0]); 50 | // return Ok(resp[0].clone()); 51 | Ok(resp) 52 | } 53 | 54 | #[derive(Debug, Deserialize, Clone, Serialize)] 55 | #[serde(rename_all = "camelCase")] 56 | pub struct Station { 57 | pub name: String, 58 | pub place: String, 59 | pub id: String, 60 | pub diva_id: i64, 61 | pub abbreviation: Option, //"DBR" 62 | pub tariff_zones: String, // "m" , "m|1" 63 | pub products: Vec, 64 | pub latitude: f32, 65 | pub longitude: f32, //type is a reserved keyword in Rust 66 | } 67 | 68 | // "name":"Karlsplatz (Stachus)", 69 | // "place":"München", 70 | // "id":"de:09162:1", 71 | // "divaId":1, 72 | // "abbreviation":"KA", 73 | // "tariffZones":"m", 74 | // "products":[ 75 | // "UBAHN", 76 | // "BUS", 77 | // "TRAM", 78 | // "SBAHN" 79 | // ], 80 | // "latitude":48.13951, 81 | // "longitude":11.56613 82 | 83 | // todo: we need a way to manually refrest this file 84 | pub async fn get_stations() -> Result> { 85 | if let Ok(file) = File::open("stations.json") { 86 | //todo: handle the error propagation here, it should fetch from api instead 87 | let stations = serde_json::from_reader(file)?; //it inferres the type from the function return type and automatically deserializes it 88 | Ok(stations) 89 | } else { 90 | let full_url = "https://www.mvg.de/.rest/zdm/stations"; 91 | 92 | let resp = reqwest::get(full_url).await?; 93 | 94 | let stations = resp.json::>().await?; 95 | match save_response_to_json_file(stations.clone()).await { 96 | Ok(_) => println!("saved stations to file"), 97 | Err(_) => println!("failed to save stations to file"), 98 | } 99 | Ok(stations) 100 | } 101 | } 102 | 103 | async fn save_response_to_json_file(station_response: Vec) -> Result<()> { 104 | let json = serde_json::to_string_pretty(&station_response)?; 105 | std::fs::write("stations.json", json)?; //stores this file in the root directory 106 | 107 | Ok(()) 108 | } 109 | -------------------------------------------------------------------------------- /src/ui.rs: -------------------------------------------------------------------------------- 1 | use ratatui::{ 2 | prelude::{Constraint, Direction, Layout}, 3 | style::{Color, Modifier, Style, Stylize}, 4 | text::{Line, Span, Text}, 5 | widgets::{Block, Borders, Clear, Padding, Paragraph, Tabs}, 6 | }; 7 | 8 | use crate::{ 9 | app::{App, AppTabs}, 10 | components::{ 11 | self, static_widgets, 12 | station_list::{display_departures_table, get_suggested_station_list}, 13 | }, 14 | tui::Frame, 15 | }; 16 | 17 | pub fn render(app: &mut App, f: &mut Frame) { 18 | let size = f.size(); 19 | let chunks = Layout::default() 20 | .direction(Direction::Vertical) 21 | .constraints([ 22 | Constraint::Length(3), 23 | Constraint::Min(0), 24 | Constraint::Length(1), 25 | ]) 26 | .split(size); 27 | 28 | let block = Block::default(); 29 | f.render_widget(block, size); 30 | 31 | let titles = ["Departures", "Station List"] 32 | .iter() 33 | .map(|t| { 34 | Line::from(Span::styled( 35 | format!("{}", t), 36 | Style::default().fg(Color::LightCyan), 37 | )) 38 | }) 39 | .collect(); 40 | 41 | let index: usize = match app.selected_tab { 42 | AppTabs::HomeTab => 0, 43 | AppTabs::StationTab => 1, 44 | }; 45 | 46 | let itemlist = components::station_list::get_station_list_widget(app); 47 | 48 | let tabs = Tabs::new(titles) 49 | .block( 50 | Block::default() 51 | .borders(Borders::ALL) 52 | .title(" MVG FahrInfo "), 53 | ) 54 | .select(index) 55 | .style(Style::default()) 56 | .highlight_style(Style::default().fg(Color::Green)); 57 | 58 | f.render_widget(tabs, chunks[0]); 59 | 60 | let list_state = &mut app.scroll_state.clone(); //we can clone this value, because it is cheap and the function is called only once per frame 61 | 62 | match app.selected_tab { 63 | AppTabs::HomeTab => draw_departures(f, app), 64 | AppTabs::StationTab => f.render_stateful_widget(itemlist, chunks[1], list_state), 65 | }; 66 | 67 | //Status bar 68 | 69 | let app_mode_indicator: Vec = match app.app_mode { 70 | crate::app::AppMode::Normal => { 71 | vec![ 72 | Span::styled(format!(" NORMAL "), Style::default().bg(Color::Blue).bold()), 73 | Span::styled( 74 | format!(" Q: close app. Tab: switch tabs. Enter: select station. R: reload departures. S: search. "), 75 | Style::default()), 76 | Span::styled( 77 | format!("Last refreshed: {}", &app.last_refreshed), 78 | Style::default().fg(Color::LightCyan))] 79 | } 80 | crate::app::AppMode::Search => { 81 | vec![ 82 | Span::styled(format!(" SEARCH "), Style::default().bg(Color::Red).bold()), 83 | Span::styled( 84 | format!( 85 | " Esc: back to normal mode. Up/Down: navigate. Enter: select station. " 86 | ), 87 | Style::default(), 88 | ), 89 | ] 90 | } 91 | }; 92 | 93 | let status_bar = Line::from(app_mode_indicator); 94 | 95 | f.render_widget(Paragraph::new(status_bar), chunks[2]); 96 | 97 | //SEARCH MODAL 98 | //todo: move to its own component 99 | 100 | if app.app_mode == crate::app::AppMode::Search { 101 | let popup_title = " ⌕ Search for a station "; 102 | 103 | let mut text = Text::from(Line::from(app.query.clone())); 104 | text.patch_style(Style::default().add_modifier(Modifier::RAPID_BLINK)); 105 | 106 | let input_field = Paragraph::new(text) 107 | .block(Block::default().borders(Borders::ALL).title(popup_title)) 108 | .style(Style::default().fg(Color::LightCyan)) 109 | .alignment(ratatui::prelude::Alignment::Left); 110 | 111 | let area = static_widgets::centered_rect(69, 50, f.size()); //size of the MODAL 112 | 113 | let chunks = Layout::default() 114 | .direction(Direction::Vertical) 115 | .constraints([Constraint::Length(3), Constraint::Min(0)]) 116 | .split(area); 117 | 118 | f.render_widget(Clear, area); //this clears out the background 119 | f.render_widget(input_field, chunks[0]); 120 | f.set_cursor( 121 | // Draw the cursor at the current position in the input field. 122 | // This position is can be controlled via the left and right arrow key 123 | chunks[0].x + app.cursor_position as u16 + 1, 124 | // Move one line down, from the border to the input line 125 | chunks[0].y + 1, 126 | ); 127 | 128 | //search suggestion section 129 | 130 | let search_scroll_state = &mut app.search_scroll_state.clone(); 131 | let suggested_stations = get_suggested_station_list(app).highlight_style( 132 | Style::default() 133 | .bg(Color::Rgb(38, 35, 53)) 134 | .add_modifier(Modifier::BOLD), 135 | ); 136 | 137 | f.render_stateful_widget(suggested_stations, chunks[1], search_scroll_state); 138 | } 139 | } 140 | 141 | fn draw_departures(f: &mut Frame<'_>, app: &App) { 142 | let popup_title = match &app.selected_station { 143 | Some(station) => format!(" {} ", station.name), 144 | None => " No station selected ".to_string(), 145 | }; 146 | 147 | let block = Block::default() 148 | .title(popup_title) 149 | .borders(Borders::ALL) 150 | .padding(Padding::new(2, 2, 1, 1)) 151 | .style(Style::default()); 152 | 153 | let table = display_departures_table(&app.departures).block(block); 154 | 155 | let area = static_widgets::centered_rect(80, 69, f.size()); 156 | f.render_widget(Clear, area); //this clears out the background 157 | f.render_widget(table, area); 158 | } 159 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | use ratatui::widgets::ListState; 2 | 3 | use crate::api; 4 | 5 | #[derive(PartialEq)] // need this to do binary comparison 6 | pub enum AppTabs { 7 | HomeTab, 8 | StationTab, 9 | } 10 | 11 | #[derive(PartialEq)] 12 | pub enum AppMode { 13 | Normal, 14 | Search, 15 | } 16 | 17 | pub struct App { 18 | pub selected_tab: AppTabs, 19 | pub should_quit: bool, 20 | pub stations: Vec, 21 | pub selected_station: Option, 22 | pub departures: Vec, 23 | pub should_redraw: bool, 24 | pub status: String, 25 | pub last_refreshed: String, 26 | //scroll related 27 | pub scroll_state: ListState, 28 | //search related 29 | pub app_mode: AppMode, 30 | pub query: String, 31 | pub cursor_position: usize, 32 | pub suggested_stations: Vec, 33 | pub search_scroll_state: ListState, 34 | } 35 | 36 | impl App { 37 | pub async fn new() -> Self { 38 | Self { 39 | selected_tab: AppTabs::HomeTab, 40 | should_quit: false, 41 | stations: api::get_stations().await.unwrap_or_else(|_| vec![]), 42 | selected_station: None, 43 | departures: vec![], 44 | should_redraw: true, 45 | status: "Loading stations...".to_string(), 46 | last_refreshed: " ".to_string(), 47 | scroll_state: ListState::default(), 48 | app_mode: AppMode::Normal, 49 | query: String::new(), 50 | cursor_position: 0, 51 | search_scroll_state: ListState::default(), 52 | suggested_stations: vec![], 53 | } 54 | } 55 | pub fn quit(&mut self) { 56 | self.should_quit = true; 57 | } 58 | pub fn increment_station(&mut self) { 59 | let i = match self.scroll_state.selected() { 60 | Some(i) => { 61 | if i >= self.stations.len() - 1 { 62 | 0 63 | } else { 64 | i + 1 65 | } 66 | } 67 | None => 0, 68 | }; 69 | self.scroll_state.select(Some(i)); 70 | } 71 | 72 | pub fn decrement_station(&mut self) { 73 | let i = match self.scroll_state.selected() { 74 | Some(i) => { 75 | if i == 0 { 76 | self.stations.len() - 1 77 | } else { 78 | i - 1 79 | } 80 | } 81 | None => 0, 82 | }; 83 | self.scroll_state.select(Some(i)); 84 | } 85 | pub fn toggle_tabs(&mut self) { 86 | match self.selected_tab { 87 | AppTabs::HomeTab => self.selected_tab = AppTabs::StationTab, 88 | AppTabs::StationTab => self.selected_tab = AppTabs::HomeTab, 89 | } 90 | } 91 | 92 | pub async fn update_departures(&mut self) { 93 | if let Some(station) = &self.selected_station { 94 | if let Ok(departures) = api::get_departures(&station.id).await { 95 | // we don't update the departures if the api call returns an error variant 96 | self.departures = departures; 97 | self.update_last_refreshed(); 98 | self.should_redraw = true; 99 | } 100 | } 101 | } 102 | 103 | fn update_last_refreshed(&mut self) { 104 | let time_now = chrono::Local::now(); 105 | self.last_refreshed = format!("{}", time_now.format("%H:%M:%S")); 106 | } 107 | 108 | pub async fn select_station(&mut self) { 109 | self.selected_station = match self.scroll_state.selected() { 110 | Some(i) => Some(self.stations[i].clone()), 111 | None => None, 112 | }; 113 | self.status = format!("Fetching departures"); 114 | self.update_departures().await; 115 | self.selected_tab = AppTabs::HomeTab; // switch to home tab immidiatelyq 116 | self.should_redraw = true; 117 | } 118 | } 119 | 120 | //second impl block for the search mode and to keep the code clean 121 | //reference: ratatui book https://github.com/ratatui-org/ratatui/blob/main/examples/user_input.rs 122 | 123 | impl App { 124 | pub fn move_cursor_left(&mut self) { 125 | let cursor_moved_left = self.cursor_position.saturating_sub(1); 126 | self.cursor_position = self.clamp_cursor(cursor_moved_left); 127 | } 128 | 129 | pub fn move_cursor_right(&mut self) { 130 | let cursor_moved_right = self.cursor_position.saturating_add(1); 131 | self.cursor_position = self.clamp_cursor(cursor_moved_right); 132 | } 133 | 134 | pub fn enter_char(&mut self, new_char: char) { 135 | if new_char.len_utf8() == 1 { 136 | // temporary workaround: ignoring non-ascii characters that are more than 1 byte 137 | self.query.insert(self.cursor_position, new_char); 138 | self.move_cursor_right(); 139 | } 140 | //should also commence the search 141 | } 142 | 143 | //boilerplate code from the ratatui book 144 | pub fn delete_char(&mut self) { 145 | let is_not_cursor_leftmost = self.cursor_position != 0; 146 | if is_not_cursor_leftmost { 147 | let current_index = self.cursor_position; 148 | let from_left_to_current_index = current_index - 1; 149 | 150 | // Getting all characters before the selected character. 151 | let before_char_to_delete = self.query.chars().take(from_left_to_current_index); 152 | // Getting all characters after selected character. 153 | let after_char_to_delete = self.query.chars().skip(current_index); 154 | 155 | // Put all characters together except the selected one. 156 | // By leaving the selected one out, it is forgotten and therefore deleted. 157 | self.query = before_char_to_delete.chain(after_char_to_delete).collect(); 158 | self.move_cursor_left(); 159 | } 160 | } 161 | pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize { 162 | new_cursor_pos.clamp(0, self.query.chars().count()) 163 | } 164 | 165 | pub fn reset_cursor(&mut self) { 166 | self.cursor_position = 0; 167 | } 168 | 169 | //search result related 170 | 171 | pub fn scroll_down(&mut self) { 172 | let i = match self.search_scroll_state.selected() { 173 | Some(i) => { 174 | if i >= self.suggested_stations.len() - 1 { 175 | 0 176 | } else { 177 | i + 1 178 | } 179 | } 180 | None => 0, 181 | }; 182 | self.search_scroll_state.select(Some(i)); 183 | } 184 | 185 | pub fn scroll_up(&mut self) { 186 | let i = match self.search_scroll_state.selected() { 187 | Some(i) => { 188 | if i == 0 { 189 | self.suggested_stations.len() - 1 190 | } else { 191 | i - 1 192 | } 193 | } 194 | None => 0, 195 | }; 196 | self.search_scroll_state.select(Some(i)); 197 | } 198 | 199 | pub async fn select_searched_station(&mut self) { 200 | self.selected_station = match self.search_scroll_state.selected() { 201 | Some(i) => Some(self.suggested_stations[i].clone()), 202 | None => None, 203 | }; 204 | self.status = format!("Fetching departures from search"); 205 | self.suggested_stations.clear(); 206 | self.search_scroll_state = ListState::default(); 207 | self.update_departures().await; 208 | self.selected_tab = AppTabs::HomeTab; 209 | self.app_mode = AppMode::Normal; 210 | self.query.clear(); 211 | self.reset_cursor(); 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/components/station_list.rs: -------------------------------------------------------------------------------- 1 | use chrono::Utc; 2 | use ratatui::{ 3 | prelude::Constraint, 4 | style::{Color, Modifier, Style}, 5 | text::{Line, Span}, 6 | widgets::{Cell, List, ListItem, Row, Table}, 7 | }; 8 | 9 | use crate::{ 10 | api::{self, Station}, 11 | constants::{get_sbahn_color, get_ubahn_color}, 12 | App, 13 | }; 14 | // this is used in the Station List tab 15 | pub fn get_station_list_widget(app: &App) -> List { 16 | return List::new( 17 | app.stations 18 | .iter() 19 | .map(|station| { 20 | ListItem::new(vec![ 21 | Line::from(vec![ 22 | Span::styled(format!("{}", station.name), Style::default()), 23 | Span::styled( 24 | format!(" ({})", station.tariff_zones), 25 | Style::default().fg(Color::LightCyan), 26 | ), 27 | ]), 28 | Line::from(get_product_icon_spans(&station.products)), 29 | ]) 30 | }) 31 | .collect::>(), 32 | ) 33 | .highlight_style( 34 | Style::default() 35 | .bg(Color::Rgb(38, 35, 38)) 36 | .add_modifier(Modifier::BOLD), 37 | ); 38 | // .highlight_symbol(">> "); 39 | } 40 | 41 | fn get_type_icon(product: &str) -> Span { 42 | let icon = match product { 43 | "UBAHN" => Span::styled( 44 | " U ", 45 | Style::default().bg(Color::Rgb(29, 43, 83)).fg(Color::White), // .bold(), 46 | ), 47 | "BUS" => Span::styled( 48 | " BUS ", 49 | Style::default() 50 | .bg(Color::Rgb(17, 93, 111)) 51 | .fg(Color::White), 52 | ), 53 | "TRAM" => Span::styled( 54 | " Tram ", 55 | Style::default() 56 | .bg(Color::Rgb(231, 27, 30)) 57 | .fg(Color::White), 58 | ), 59 | "SBAHN" => Span::styled( 60 | " S ", 61 | Style::default() 62 | .bg(Color::Rgb(84, 253, 84)) 63 | .fg(Color::Black), 64 | ), 65 | // .bold(), 66 | _ => Span::styled( 67 | product, 68 | Style::default().bg(Color::LightYellow).fg(Color::Black), 69 | ), 70 | }; 71 | icon 72 | } 73 | 74 | fn get_product_icon_spans(products: &Vec) -> Vec { 75 | let mut spans = vec![]; 76 | for product in products { 77 | let icon = get_type_icon(product); 78 | spans.push(icon); 79 | spans.push(Span::raw(" ")); // add a space between the icons 80 | } 81 | spans 82 | } 83 | 84 | pub fn display_departures_table(departures: &[api::DepartureInfo]) -> Table { 85 | let header_cells = ["Vehicle", "Direction", "Platform", "ETA"] 86 | .iter() 87 | .map(|h| Cell::from(*h).style(Style::default().fg(Color::Gray))); 88 | 89 | let header = Row::new(header_cells) 90 | .style( 91 | Style::default(), // .bg(Color::White) 92 | ) 93 | .height(2) 94 | .bottom_margin(1); 95 | 96 | let rows = departures.iter().enumerate().map(|(index, item)| { 97 | let cells = vec![ 98 | Cell::from(get_vehicle_label(&item.label, &item.transport_type)), 99 | Cell::from(format!("{}", item.destination)), 100 | Cell::from(get_platform_number(item.platform, index)), 101 | Cell::from(match get_minutes(item.realtime_departure_time) { 102 | ETA::Minutes(minutes) => format!("{} min", minutes), 103 | ETA::Now => "now".to_string(), 104 | }), 105 | ]; 106 | return Row::new(cells).height(1); 107 | }); 108 | 109 | let t = Table::new(rows) 110 | .header(header) 111 | .style(Style::default().fg(Color::White)) 112 | .widths(&[ 113 | Constraint::Percentage(20), 114 | Constraint::Max(50), 115 | Constraint::Percentage(20), 116 | Constraint::Min(10), 117 | ]); 118 | t 119 | } 120 | 121 | fn get_platform_number<'a>(platform: Option, index: usize) -> Span<'a> { 122 | let bg = if index % 2 == 0 { 123 | Color::White 124 | } else { 125 | Color::Gray 126 | }; 127 | return match platform { 128 | Some(p) => Span::styled(format!(" {} ", p), Style::default().bg(bg).fg(Color::Black)), 129 | None => Span::styled(" ", Style::default().fg(Color::White)), 130 | }; 131 | } 132 | 133 | fn get_vehicle_label<'a>(label: &'a str, transport_type: &str) -> Line<'a> { 134 | let icon = match transport_type { 135 | "UBAHN" => vec![ 136 | Span::styled( 137 | format!(" U "), 138 | Style::default().bg(Color::Rgb(29, 43, 83)).fg(Color::White), 139 | ), 140 | Span::raw(" "), 141 | Span::styled( 142 | format!(" {} ", label), 143 | Style::default().bg(get_ubahn_color(label)).fg(Color::White), 144 | ), 145 | ], 146 | "BUS" => vec![ 147 | Span::styled( 148 | format!(" B "), 149 | Style::default() 150 | .bg(Color::Rgb(17, 93, 111)) 151 | .fg(Color::White), 152 | ), 153 | Span::raw(" "), 154 | Span::styled( 155 | format!(" {} ", label), 156 | Style::default() 157 | .bg(Color::Rgb(17, 93, 111)) 158 | .fg(Color::White), 159 | ), 160 | ], 161 | "TRAM" => vec![ 162 | Span::styled( 163 | format!(" T "), 164 | Style::default() 165 | .bg(Color::Rgb(231, 27, 30)) 166 | .fg(Color::White), 167 | ), 168 | Span::raw(" "), 169 | Span::styled( 170 | format!(" {} ", label), 171 | Style::default() 172 | .bg(Color::Rgb(231, 27, 30)) 173 | .fg(Color::White), 174 | ), 175 | ], 176 | "SBAHN" => vec![ 177 | Span::styled( 178 | format!(" S "), 179 | Style::default() 180 | .bg(Color::Rgb(84, 253, 84)) 181 | .fg(Color::Black), 182 | ), 183 | Span::raw(" "), 184 | Span::styled( 185 | format!(" {} ", label), 186 | Style::default().bg(get_sbahn_color(label)).fg(Color::White), 187 | ), 188 | ], 189 | // .bold(), 190 | _ => vec![Span::styled( 191 | label, 192 | Style::default().bg(Color::LightYellow).fg(Color::Black), 193 | )], 194 | }; 195 | Line::from(icon) 196 | } 197 | 198 | // sometimes, the departure time is negative 199 | // in that case, we return a string instead of a number. This is a temporary fix though 200 | enum ETA { 201 | Minutes(i64), 202 | Now, // it might also be depaurtures that are late and come in any moment. Needs more investigation 203 | } 204 | 205 | fn get_minutes(time: i64) -> ETA { 206 | let now = Utc::now(); 207 | let timestamp_in_seconds = time / 1000; 208 | let future_time = chrono::DateTime::from_timestamp(timestamp_in_seconds, 0).unwrap(); 209 | let diff = future_time.signed_duration_since(now); //now.signed_duration_since(future_time); 210 | 211 | let minutes = diff.num_minutes(); 212 | 213 | if minutes < 1 { 214 | return ETA::Now; 215 | } else { 216 | return ETA::Minutes(minutes); 217 | } 218 | } 219 | 220 | // search suggestions 221 | 222 | pub fn get_suggested_station_list(app: &mut App) -> List { 223 | let mut suggested_stations: Vec = vec![]; 224 | 225 | let suggested_stations_list = app 226 | .stations 227 | .iter() 228 | .filter(|station| { 229 | // todo: move to filter_map 230 | station 231 | .name 232 | .to_ascii_lowercase() 233 | .contains(&app.query.to_ascii_lowercase()) 234 | }) 235 | .map(|station| { 236 | suggested_stations.push(station.clone()); 237 | return ListItem::new(vec![Line::from(vec![ 238 | Span::styled(format!("{}", station.name), Style::default()), 239 | Span::styled( 240 | format!(" ({})", station.tariff_zones), 241 | Style::default().fg(Color::LightCyan), 242 | ), 243 | ])]); 244 | }) 245 | .collect::>(); 246 | 247 | app.suggested_stations = suggested_stations; 248 | 249 | return List::new(suggested_stations_list); 250 | } 251 | --------------------------------------------------------------------------------