about summary refs log tree commit diff stats
path: root/pkgs/by-name/ts/tskm/src/interface/open
diff options
context:
space:
mode:
Diffstat (limited to 'pkgs/by-name/ts/tskm/src/interface/open')
-rw-r--r--pkgs/by-name/ts/tskm/src/interface/open/handle.rs190
-rw-r--r--pkgs/by-name/ts/tskm/src/interface/open/mod.rs170
2 files changed, 360 insertions, 0 deletions
diff --git a/pkgs/by-name/ts/tskm/src/interface/open/handle.rs b/pkgs/by-name/ts/tskm/src/interface/open/handle.rs
new file mode 100644
index 00000000..0cf60b41
--- /dev/null
+++ b/pkgs/by-name/ts/tskm/src/interface/open/handle.rs
@@ -0,0 +1,190 @@
+// 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 std::str::FromStr;
+
+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)?;
+
+    if tabs.is_empty() {
+        Ok(true)
+    } else if tabs.len() > 1 {
+        Ok(false)
+    } else {
+        let url = &tabs[0].1;
+
+        Ok(url == &Url::from_str("qute://start/").expect("Hardcoded"))
+    }
+}
+
+#[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, urls } => {
+            project.touch().context("Failed to touch project")?;
+            open_in_browser(&project, state, urls).with_context(|| {
+                format!("Failed to open project: {}", project.to_project_display())
+            })?;
+        }
+        OpenCommand::Select { urls } => {
+            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, urls).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())
+}
diff --git a/pkgs/by-name/ts/tskm/src/interface/open/mod.rs b/pkgs/by-name/ts/tskm/src/interface/open/mod.rs
new file mode 100644
index 00000000..e302c7d1
--- /dev/null
+++ b/pkgs/by-name/ts/tskm/src/interface/open/mod.rs
@@ -0,0 +1,170 @@
+// 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 std::{fs::File, io::Read, str::FromStr};
+
+use anyhow::{anyhow, Context, Result};
+use taskchampion::chrono::NaiveDateTime;
+use url::Url;
+use yaml_rust2::Yaml;
+
+use crate::task::Project;
+
+pub mod handle;
+pub use handle::handle;
+
+impl Project {
+    pub(super) fn get_sessionstore(&self) -> Result<SessionStore> {
+        let path = dirs::data_local_dir()
+            .context("Failed to get data dir")?
+            .join("qutebrowser")
+            .join(self.to_project_display())
+            .join("data/sessions/default.yml");
+
+        let mut file = File::open(&path)
+            .with_context(|| format!("Failed to open path '{}'", path.display()))?;
+
+        let mut yaml_str = String::new();
+        file.read_to_string(&mut yaml_str)
+            .context("Failed to read _autosave.yml path")?;
+        let yaml = yaml_rust2::YamlLoader::load_from_str(&yaml_str)?;
+
+        let store = qute_store_from_yaml(&yaml).context("Failed to read yaml store")?;
+
+        Ok(store)
+    }
+}
+
+fn qute_store_from_yaml(yaml: &[Yaml]) -> Result<SessionStore> {
+    assert_eq!(yaml.len(), 1);
+    let doc = &yaml[0];
+
+    let hash = doc.as_hash().context("Invalid yaml")?;
+    let windows = hash
+        .get(&Yaml::String("windows".to_owned()))
+        .ok_or(anyhow!("Missing windows"))?
+        .as_vec()
+        .ok_or(anyhow!("Windows not vector"))?;
+
+    Ok(SessionStore {
+        windows: windows
+            .iter()
+            .map(|window| {
+                let hash = window.as_hash().ok_or(anyhow!("Windows not hashmap"))?;
+
+                Ok::<_, anyhow::Error>(Window {
+                    geometry: hash
+                        .get(&Yaml::String("geometry".to_owned()))
+                        .ok_or(anyhow!("Missing window geometry"))?
+                        .as_str()
+                        .ok_or(anyhow!("geometry not string"))?
+                        .to_owned(),
+                    tabs: hash
+                        .get(&Yaml::String("tabs".to_owned()))
+                        .ok_or(anyhow!("Missing window tabs"))?
+                        .as_vec()
+                        .ok_or(anyhow!("Tabs not vec"))?
+                        .iter()
+                        .map(|tab| {
+                            let hash = tab.as_hash().ok_or(anyhow!("Tab not hashmap"))?;
+
+                            Ok::<_, anyhow::Error>(Tab {
+                                history: hash
+                                    .get(&Yaml::String("history".to_owned()))
+                                    .ok_or(anyhow!("Missing tab history"))?
+                                    .as_vec()
+                                    .ok_or(anyhow!("tab history not vec"))?
+                                    .iter()
+                                    .map(|history| {
+                                        let hash = history
+                                            .as_hash()
+                                            .ok_or(anyhow!("Tab history not hashmap"))?;
+
+                                        Ok::<_, anyhow::Error>(TabHistory {
+                                            active: hash
+                                                .get(&Yaml::String("active".to_owned()))
+                                                .unwrap_or(&Yaml::Boolean(false))
+                                                .as_bool()
+                                                .ok_or(anyhow!("tab history active not bool"))?,
+                                            last_visited: NaiveDateTime::from_str(
+                                                hash.get(&Yaml::String("last_visited".to_owned()))
+                                                    .ok_or(anyhow!(
+                                                        "Missing tab history last_visited"
+                                                    ))?
+                                                    .as_str()
+                                                    .ok_or(anyhow!(
+                                                        "tab history last_visited not string"
+                                                    ))?,
+                                            )
+                                            .context("Failed to parse last_visited")?,
+                                            pinned: hash
+                                                .get(&Yaml::String("pinned".to_owned()))
+                                                .ok_or(anyhow!("Missing tab history pinned"))?
+                                                .as_bool()
+                                                .ok_or(anyhow!("tab history pinned not bool"))?,
+                                            title: hash
+                                                .get(&Yaml::String("title".to_owned()))
+                                                .ok_or(anyhow!("Missing tab history title"))?
+                                                .as_str()
+                                                .ok_or(anyhow!("tab history title not string"))?
+                                                .to_owned(),
+                                            url: Url::parse(
+                                                hash.get(&Yaml::String("url".to_owned()))
+                                                    .ok_or(anyhow!("Missing tab history url"))?
+                                                    .as_str()
+                                                    .ok_or(anyhow!("tab history url not string"))?,
+                                            )
+                                            .context("Failed to parse url")?,
+                                            zoom: hash
+                                                .get(&Yaml::String("zoom".to_owned()))
+                                                .unwrap_or(&Yaml::Real("1.0".to_owned()))
+                                                .as_f64()
+                                                .ok_or(anyhow!("tab history zoom not 64"))?,
+                                        })
+                                    })
+                                    .collect::<Result<Vec<_>, _>>()?,
+                                active: hash
+                                    .get(&Yaml::String("active".to_owned()))
+                                    .unwrap_or(&Yaml::Boolean(false))
+                                    .as_bool()
+                                    .ok_or(anyhow!("active not bool"))?,
+                            })
+                        })
+                        .collect::<Result<Vec<_>, _>>()?,
+                })
+            })
+            .collect::<Result<Vec<_>, _>>()?,
+    })
+}
+
+#[derive(Debug)]
+pub struct SessionStore {
+    pub windows: Vec<Window>,
+}
+#[derive(Debug)]
+pub struct Window {
+    pub geometry: String,
+    pub tabs: Vec<Tab>,
+}
+#[derive(Debug)]
+pub struct Tab {
+    pub history: Vec<TabHistory>,
+    pub active: bool,
+}
+#[derive(Debug)]
+pub struct TabHistory {
+    pub active: bool,
+    pub last_visited: NaiveDateTime,
+    pub pinned: bool,
+    // pub scroll-pos:
+    pub title: String,
+    pub url: Url,
+    pub zoom: f64,
+}