muxi/commands/sessions/
switch.rs

1use std::fmt::Display;
2
3use color_eyre::Result;
4use dialoguer::Select;
5use dialoguer::theme::ColorfulTheme;
6use owo_colors::OwoColorize;
7
8use crate::muxi::{Muxi, Session, Sessions};
9use crate::tmux;
10
11pub fn switch(key: &tmux::Key) -> Result<()> {
12    let sessions = Muxi::new()?.sessions;
13
14    let Some(session) = sessions.0.get(key) else {
15        println!("{}", "Session not found!".red());
16        return Ok(());
17    };
18
19    if !tmux::has_session(session) {
20        tmux::create_session(session);
21    }
22
23    tmux::switch_to(session)?;
24
25    Ok(())
26}
27
28pub fn tmux_menu() -> Result<()> {
29    let sessions = Muxi::new()?.sessions;
30    tmux::sessions_menu(&sessions)?;
31
32    Ok(())
33}
34
35pub fn picker() -> Result<()> {
36    let sessions = Muxi::new()?.sessions;
37    let choices = SessionChoice::from(sessions);
38
39    let selection = Select::with_theme(&ColorfulTheme::default())
40        .items(&choices)
41        .default(0)
42        .interact_opt()?;
43
44    if selection.is_none() {
45        return Ok(());
46    }
47
48    let session = &choices[selection.unwrap()];
49
50    switch(&session.key)
51}
52
53#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
54struct SessionChoice {
55    pub key: tmux::Key,
56    pub session: Session,
57}
58
59impl SessionChoice {
60    pub fn from(sessions: Sessions) -> Vec<Self> {
61        let mut choices = Vec::with_capacity(sessions.0.len());
62
63        for (key, session) in sessions.0 {
64            choices.push(Self { key, session });
65        }
66
67        choices.sort();
68        choices
69    }
70}
71
72impl Display for SessionChoice {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        write!(
75            f,
76            "{} {} {}",
77            self.key.green(),
78            self.session.name.blue(),
79            self.session.path.display().dimmed()
80        )
81    }
82}