hyprshell_exec_lib/
util.rs

1use anyhow::Context;
2use core_lib::{Active, ClientId, Warn};
3use hyprland::ctl::{notify, reload, Color};
4use hyprland::data::{Client, Clients, Monitor, Monitors, Workspace};
5use hyprland::dispatch::{Dispatch, DispatchType};
6use hyprland::keyword::Keyword;
7use hyprland::prelude::*;
8use tracing::{debug, span, trace, warn, Level};
9
10pub fn get_clients() -> Vec<Client> {
11    Clients::get().map_or(vec![], |clients| clients.to_vec())
12}
13
14pub fn get_monitors() -> Vec<Monitor> {
15    Monitors::get().map_or(vec![], |monitors| monitors.to_vec())
16}
17
18pub fn get_current_monitor() -> Option<Monitor> {
19    Monitor::get_active().ok()
20}
21
22pub fn reload_config() {
23    debug!("Reloading hyprland config");
24    reload::call().warn("Failed to reload hyprland config");
25}
26
27pub fn toast(body: &str) {
28    warn!("toast: {}", body);
29    let _ = notify::call(
30        notify::Icon::Warning,
31        std::time::Duration::from_secs(10),
32        Color::new(255, 0, 0, 255),
33        format!("hyprshell Error: {}", body),
34    );
35}
36
37pub fn apply_keybinds(list: Vec<(&str, String)>) {
38    trace!("Applying binds and submaps");
39    for (a, b) in list {
40        trace!("{}={}", a, b);
41        Keyword::set(a, b).warn("Failed to apply bind and submap");
42    }
43}
44
45/// trim 0x from hexadecimal (base-16) string and convert to id
46pub fn to_client_id(id: &hyprland::shared::Address) -> ClientId {
47    u64::from_str_radix(id.to_string().trim_start_matches("0x"), 16)
48        .expect("Failed to parse client id, this should never happen")
49}
50/// convert id to hexadecimal (base-16) string
51pub fn to_client_address(id: ClientId) -> hyprland::shared::Address {
52    hyprland::shared::Address::new(format!("{:x}", id))
53}
54
55pub fn activate_submap(submap_name: &str) -> anyhow::Result<()> {
56    let _span = span!(Level::TRACE, "submap").entered();
57    Dispatch::call(DispatchType::Custom("submap", submap_name)).warn("unable to activate submap");
58    debug!("Activated submap: {}", submap_name);
59    Ok(())
60}
61
62pub fn get_initial_active() -> anyhow::Result<Active> {
63    let active_client = Client::get_active()?.map(|c| to_client_id(&c.address));
64    let active_ws = Workspace::get_active()?.id;
65    let active_monitor = Monitor::get_active()?.id;
66    Ok(Active {
67        client: active_client,
68        workspace: active_ws,
69        monitor: active_monitor,
70    })
71}
72
73pub fn get_version() -> anyhow::Result<String> {
74    let version = hyprland::data::Version::get()
75        .context("Failed to get version! (hyprland is probably outdated or too new??)")?;
76
77    trace!("hyprland {version:?}");
78
79    Ok(version
80        .version
81        .unwrap_or(version.tag.trim_start_matches('v').to_string()))
82}