about summary refs log tree commit diff stats
path: root/pkgs/by-name/ts/tskm/src/interface/open/handle.rs
blob: ca54b4229224eccb4de4b3d205206dab518413f4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// nixos-config - My current NixOS configuration
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of my nixos-config.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use anyhow::{bail, Context, Result};
use log::{error, info};
use url::Url;

use crate::{browser::open_in_browser, cli::OpenCommand, rofi, state::State, task};

fn is_empty(project: &task::Project) -> Result<bool> {
    let tabs = get_tabs(project)?;

    Ok(tabs.is_empty())
}

#[allow(clippy::too_many_lines)]
pub fn handle(command: OpenCommand, state: &mut State) -> Result<()> {
    match command {
        OpenCommand::Review { non_empty } => {
            for project in task::Project::all().context("Failed to get all project files")? {
                let is_empty = is_empty(project)?;

                if project.is_touched() || (non_empty && !is_empty) {
                    info!(
                        "Reviewing project: '{}' ({})",
                        project.to_project_display(),
                        if is_empty { "is empty" } else { "is not empty" }
                    );
                    open_in_browser(project, state, None).with_context(|| {
                        format!(
                            "Failed to open project ('{}') in qutebrowser",
                            project.to_project_display()
                        )
                    })?;

                    if project.is_touched() {
                        project.untouch().with_context(|| {
                            format!(
                                "Failed to untouch project ('{}')",
                                project.to_project_display()
                            )
                        })?;
                    }
                }
            }
        }
        OpenCommand::Project { project, url } => {
            project.touch().context("Failed to touch project")?;
            open_in_browser(&project, state, url).with_context(|| {
                format!("Failed to open project: {}", project.to_project_display())
            })?;
        }
        OpenCommand::Select { url } => {
            let selected_project: task::Project = task::Project::from_project_string(
                &rofi::select(
                    task::Project::all()
                        .context("Failed to get all registered projects")?
                        .iter()
                        .map(task::Project::to_project_display)
                        .collect::<Vec<_>>()
                        .as_slice(),
                )
                .context("Failed to get selected project")?,
            )
            .expect("This should work, as we send only projects in");

            selected_project
                .touch()
                .context("Failed to touch project")?;

            open_in_browser(&selected_project, state, url).context("Failed to open project")?;
        }
        OpenCommand::ListTabs { projects, mode } => {
            let projects = {
                if let Some(p) = projects {
                    p
                } else if mode.is_some() {
                    task::Project::all()
                        .context("Failed to get all projects")?
                        .to_owned()
                } else if let Some(p) = task::Project::get_current()
                    .context("Failed to get currently focused project")?
                {
                    vec![p]
                } else {
                    bail!("You need to either select projects or pass --mode");
                }
            };

            for project in &projects {
                if let Some(mode) = mode {
                    match mode {
                        crate::cli::ListMode::Empty => {
                            if !is_empty(project)? {
                                continue;
                            }

                            // We do not need to print, tabs they are always empty.
                            if projects.len() > 1 {
                                println!("/* {} */", project.to_project_display());
                            }
                            continue;
                        }
                        crate::cli::ListMode::NonEmpty => {
                            if is_empty(project)? {
                                continue;
                            }
                        }
                    }
                }

                if projects.len() > 1 {
                    println!("/* {} */", project.to_project_display());
                }

                let tabs = match get_tabs(project) {
                    Ok(ok) => ok,
                    Err(err) => {
                        if projects.len() > 1 {
                            error!(
                                "While trying to get the sessionstore for {}: {:?}",
                                project.to_project_display(),
                                err
                            );
                            continue;
                        }

                        return Err(err).with_context(|| {
                            format!(
                                "While trying to get the sessionstore for {}",
                                project.to_project_display()
                            )
                        });
                    }
                };

                for (active, url) in tabs {
                    let is_selected = {
                        if active {
                            "🔻 "
                        } else {
                            "   "
                        }
                    };
                    println!("{is_selected}{url}");
                }
            }
        }
    }

    Ok(())
}

fn get_tabs(project: &task::Project) -> Result<Vec<(bool, Url)>> {
    let session_store = project.get_sessionstore()?;

    let tabs = session_store
        .windows
        .iter()
        .flat_map(|window| window.tabs.iter())
        .filter_map(|tab| {
            tab.history
                .iter()
                .find(|hist| hist.active)
                .map(|hist| (tab.active, hist))
        })
        .collect::<Vec<_>>();

    Ok(tabs
        .into_iter()
        .map(|(active, hist)| (active, hist.url.clone()))
        .collect())
}