hyprshell_exec_lib/
switch.rs

1use anyhow::Context;
2use hyprland::data::Workspace;
3use hyprland::dispatch::{
4    Dispatch, DispatchType, WindowIdentifier, WorkspaceIdentifierWithSpecial,
5};
6use hyprland::prelude::*;
7use hyprland::shared::{Address, WorkspaceId};
8use tracing::{trace, warn};
9
10pub fn switch_client(address: Address) -> anyhow::Result<()> {
11    trace!("execute switch to client: {address}");
12    Dispatch::call(DispatchType::FocusWindow(WindowIdentifier::Address(
13        address,
14    )))?;
15    Dispatch::call(DispatchType::BringActiveToTop)?;
16    Ok(())
17}
18
19pub fn switch_client_by_initial_class(class: &str) -> anyhow::Result<()> {
20    trace!("execute switch to client: {class} by initial_class");
21    Dispatch::call(DispatchType::FocusWindow(
22        WindowIdentifier::ClassRegularExpression(&format!(
23            "initialclass:{}",
24            class.to_ascii_lowercase()
25        )),
26    ))?;
27    Dispatch::call(DispatchType::BringActiveToTop)?;
28    Ok(())
29}
30
31pub fn switch_workspace(workspace_id: WorkspaceId) -> anyhow::Result<()> {
32    // check if already on workspace (if so, don't switch because it throws an error `Previous workspace doesn't exist`)
33    let current_workspace = Workspace::get_active();
34    if let Ok(workspace) = current_workspace {
35        if workspace_id == workspace.id {
36            trace!("Already on workspace {}", workspace_id);
37            return Ok(());
38        }
39    }
40
41    if workspace_id < 0 {
42        warn!(
43            "Special workspace id detected, not switching to special workspace, TODO not supported"
44        );
45    } else {
46        switch_normal_workspace(workspace_id).with_context(|| {
47            format!("Failed to execute switch workspace with id {workspace_id}",)
48        })?;
49    }
50    Ok(())
51}
52
53fn switch_normal_workspace(workspace_id: WorkspaceId) -> anyhow::Result<()> {
54    trace!("execute switch to workspace {workspace_id}");
55    Dispatch::call(DispatchType::Workspace(WorkspaceIdentifierWithSpecial::Id(
56        workspace_id,
57    )))?;
58    Ok(())
59}