tmerr / i3ipc-rs

A Rust library for controlling i3-wm through its IPC interface
MIT License
107 stars 33 forks source link

How to get focussed client #29

Closed spacekookie closed 6 years ago

spacekookie commented 6 years ago

Hey there!

First of all, thank you for all the work that went into writing this library! I'm really glad it exists :)

I've been playing around with it a little bit but there's something I'm not super sure about – maybe because the i3 IPC interface is generally new to me.

I want to find out what client is actually focused. Now, there is the focused field but it includes several id's and when I try to query those from the nodes field I just get back generic eDP-1 or _i3 or whatever.

I guess I'm misunderstanding the API here? Any help would be appreciated! :)

tmerr commented 6 years ago

Hello! If you recursively visit the first element of focus down the tree you will eventually get to the node with focused set to true. Example:

extern crate i3ipc;

use i3ipc::I3Connection;
use i3ipc::reply::Node;

fn find_focused(node: &Node) -> Option<&Node> {
    if node.focused {
        Some(node)
    } else {
        if let Some(&want) = node.focus.get(0) {
            let child = node.nodes.iter().find(|n| want == n.id).unwrap();
            find_focused(child)
        } else {
            None
        }
    }
}

fn main() {
    let mut connection = I3Connection::connect().unwrap();
    println!("{:?}", find_focused(&connection.get_tree().unwrap()).unwrap());
}

Btw eDP-1 is the name of your display which is near the top of the tree.

edit: I forgot, this should iterate through floating_nodes too.

tmerr commented 6 years ago

Closing this out, feel free to reopen if you have any questions