Skip to content

Commit

Permalink
Merge pull request #30 from lautarodragan/taro/remember-last-visited-…
Browse files Browse the repository at this point in the history
…path-between-sessions

feat: persist last_visited_path
  • Loading branch information
TrevorSatori authored Jul 28, 2024
2 parents 1f65ce4 + 549ebab commit 128f5c2
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 16 deletions.
17 changes: 16 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use kronos::music_handler::MusicHandle;
use kronos::queue::Queue;
use kronos::stateful_list::StatefulList;
use kronos::stateful_table::StatefulTable;
use crate::state::{save_state, State};

#[derive(Clone, Copy)]
pub enum InputMode {
Expand Down Expand Up @@ -47,7 +48,13 @@ pub struct App<'a> {
}

impl<'a> App<'a> {
pub fn new() -> Self {
pub fn new(initial_directory: Option<String>) -> Self {
if let Some(path) = initial_directory {
env::set_current_dir(&path).unwrap_or_else(|err| {
eprintln!("Could not set_current_dir to last_visited_path\n\tPath: {}\n\tError: {:?}", path, err);
});
}

Self {
browser_items: StatefulList::with_items(gen_funcs::scan_and_filter_directory()),
queue_items: Queue::with_items(),
Expand All @@ -60,6 +67,14 @@ impl<'a> App<'a> {
}
}

pub fn save_state(self) {
save_state(State {
last_visited_path: self.last_visited_path.to_str().map(String::from),
}).unwrap_or_else(|error| {
eprintln!("Error in save_state {}", error);
});
}

pub fn next(&mut self) {
self.active_tab = self.active_tab.next();
}
Expand Down
12 changes: 6 additions & 6 deletions src/helpers/music_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use super::gen_funcs;
pub struct MusicHandle {
music_output: Arc<(OutputStream, OutputStreamHandle)>,
sink: Arc<Sink>,
song_length: u16,
time_played: Arc<Mutex<u16>>,
song_length: u32,
time_played: Arc<Mutex<u32>>,
currently_playing: String,
volume: f32,
}
Expand All @@ -43,19 +43,19 @@ impl MusicHandle {
self.currently_playing.clone()
}

pub fn song_length(&self) -> u16 {
pub fn song_length(&self) -> u32 {
self.song_length
}

pub fn time_played(&self) -> u16 {
pub fn time_played(&self) -> u32 {
*self.time_played.lock().unwrap()
}

pub fn sink_empty(&self) -> bool {
self.sink.empty()
}

pub fn set_time_played(&mut self, t: u16) {
pub fn set_time_played(&mut self, t: u32) {
*self.time_played.lock().unwrap() = t;
}
// set currently playing song
Expand Down Expand Up @@ -138,7 +138,7 @@ impl MusicHandle {
let duration = properties.duration();

// update song length, currently playing
self.song_length = duration.as_secs() as u16;
self.song_length = duration.as_secs() as u32;
}

pub fn change_volume(&mut self, volume: f32) {
Expand Down
22 changes: 13 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
mod app;
mod config;
mod state;

use std::{
error::Error,
io,
time::{Duration, Instant},
};
use std::{error::Error, io, time::{Duration, Instant}};

use crossterm::{
event::{self, DisableMouseCapture, Event, KeyCode},
Expand All @@ -24,8 +21,11 @@ use tui::{
use app::{App, AppTab, InputMode};
use config::Config;
use kronos::gen_funcs;
use state::load_state;

fn main() -> Result<(), Box<dyn Error>> {
let state = load_state();

// setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
Expand All @@ -36,7 +36,7 @@ fn main() -> Result<(), Box<dyn Error>> {

// create app and run it
let tick_rate = Duration::from_secs(1);
let app = App::new();
let app = App::new(state.last_visited_path);
let cfg = Config::new();

let res = run_app(&mut terminal, app, cfg, tick_rate);
Expand Down Expand Up @@ -75,7 +75,7 @@ fn run_app<B: Backend>(
if let Event::Key(key) = event::read()? {
match app.input_mode() {
InputMode::Browser => match key.code {
KeyCode::Char('q') => return Ok(()),
KeyCode::Char('q') => break,
KeyCode::Char('p') | KeyCode::Char(' ') => app.music_handle.play_pause(),
KeyCode::Char('g') => app.music_handle.skip(),
KeyCode::Char('a') => app.queue_items.add(app.selected_item()),
Expand All @@ -100,7 +100,7 @@ fn run_app<B: Backend>(
_ => {}
},
InputMode::Queue => match key.code {
KeyCode::Char('q') => return Ok(()),
KeyCode::Char('q') => break,
KeyCode::Char('p') => app.music_handle.play_pause(),
KeyCode::Char('g') => app.music_handle.skip(),
KeyCode::Enter => {
Expand All @@ -126,7 +126,7 @@ fn run_app<B: Backend>(
_ => {}
},
InputMode::Controls => match key.code {
KeyCode::Char('q') => return Ok(()),
KeyCode::Char('q') => break,
KeyCode::Char('p') => app.music_handle.play_pause(),
KeyCode::Char('g') => app.music_handle.skip(),
KeyCode::Down | KeyCode::Char('j') => app.control_table.next(),
Expand All @@ -147,6 +147,10 @@ fn run_app<B: Backend>(
last_tick = Instant::now();
}
}

app.save_state();

Ok(())
}

fn ui<B: Backend>(f: &mut Frame<B>, app: &mut App, cfg: &Config) {
Expand Down
44 changes: 44 additions & 0 deletions src/state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use std::fs;

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
pub struct State {
pub last_visited_path: Option<String>,
}

pub fn load_state() -> State {
let state_file_paths = [home::home_dir()
.unwrap()
.as_path()
.join(".config/kronos/state.toml")];

let mut content: String = "".to_owned();

for state_file_path in state_file_paths {
let result: Result<String, std::io::Error> = fs::read_to_string(state_file_path);

if let Ok(file_content) = result {
content = file_content;
break;
}
}

let state_toml: State = toml::from_str(&content).unwrap_or_else(|_| {
eprintln!("FAILED TO CREATE STATE OBJECT FROM FILE");
State {
last_visited_path: None,
}
});

state_toml
}
pub fn save_state(state: State) -> Result<(), String> {
let state_file_path = home::home_dir()
.unwrap()
.as_path()
.join(".config/kronos/state.toml");

toml::to_string(&state).map_err(|e| e.to_string())
.and_then(|serialized| fs::write(state_file_path, serialized).map_err(|e| e.to_string()))
}

0 comments on commit 128f5c2

Please sign in to comment.