Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changing profiles based on the active window title/class #27

Open
teras opened this issue Oct 13, 2024 · 5 comments
Open

Changing profiles based on the active window title/class #27

teras opened this issue Oct 13, 2024 · 5 comments

Comments

@teras
Copy link

teras commented Oct 13, 2024

Recapping some info based on previous discussions.

When the focus moved to another application's window then (probably) a new profile should be selected. For example the focus is on FIrefox, now it's on Nemo, now it's on the Desktop (i.e. none).

This is a feature of the app itself, and this is what other applications are doing, and maybe the paradigm should be similar.

StreamController screenshot
image

StreamDeck screenshot
image

Demo code in rust

Cargo.toml

[package]
name = "focus_listener"
version = "0.1.0"
edition = "2021"

[dependencies]
x11rb = "0.13.1"

test.rs

use std::error::Error;
use x11rb::atom_manager;
use x11rb::connection::Connection;
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt, EventMask, PropertyNotifyEvent, Window};
use x11rb::rust_connection::RustConnection;

atom_manager! {
    pub Atoms: AtomsCookie {
        _NET_ACTIVE_WINDOW,
        WM_CLASS,
        _NET_WM_NAME,
        WM_NAME,
        UTF8_STRING,
    }
}

struct X11FocusListener {
    conn: RustConnection,
    root: Window,
    atoms: Atoms,
    last_active_window: Option<Window>,
}

impl X11FocusListener {
    fn new() -> Result<Self, Box<dyn Error>> {
        let (conn, screen_num) = RustConnection::connect(None)?;
        let screen = &conn.setup().roots[screen_num];
        let root = screen.root;

        let atoms = Atoms::new(&conn)?.reply()?;

        conn.change_window_attributes(root, &x11rb::protocol::xproto::ChangeWindowAttributesAux::new()
            .event_mask(EventMask::PROPERTY_CHANGE | EventMask::SUBSTRUCTURE_NOTIFY))?;

        for child in conn.query_tree(root)?.reply()?.children {
            conn.change_window_attributes(child, &x11rb::protocol::xproto::ChangeWindowAttributesAux::new()
                .event_mask(EventMask::PROPERTY_CHANGE))?;
        }

        Ok(Self {
            conn,
            root,
            atoms,
            last_active_window: None,
        })
    }

    fn get_next_focus_change(&mut self) -> Result<(String, String), Box<dyn Error>> {
        loop {
            let event = self.conn.wait_for_event()?;
            if let x11rb::protocol::Event::PropertyNotify(PropertyNotifyEvent { atom, .. }) = event {
                if atom == self.atoms._NET_ACTIVE_WINDOW {
                    if let Ok(reply) = self.conn.get_property(false, self.root, self.atoms._NET_ACTIVE_WINDOW, AtomEnum::WINDOW, 0, 1)?.reply() {
                        if let Some(window_id) = reply.value32().and_then(|mut v| v.next()) {
                            if self.last_active_window != Some(window_id) {
                                self.last_active_window = Some(window_id);
                                let wm_class = self.get_window_class(window_id)?;
                                let wm_title = self.get_window_title(window_id)?;
                                return Ok((wm_title.unwrap_or_default(), wm_class.unwrap_or_default()));
                            }
                        }
                    }
                }
            }
        }
    }

    fn get_window_class(&self, window: Window) -> Result<Option<String>, Box<dyn Error>> {
        if let Ok(reply) = self.conn.get_property(false, window, self.atoms.WM_CLASS, AtomEnum::STRING, 0, 1024)?.reply() {
            if let Some(value) = reply.value8() {
                return Ok(Some(String::from_utf8_lossy(&value.collect::<Vec<u8>>()).split(' ').filter(|s| !s.is_empty()).collect::<Vec<_>>().join(".")));
            }
        }
        Ok(None)
    }

    fn get_window_title(&self, window: Window) -> Result<Option<String>, Box<dyn Error>> {
        if let Ok(reply) = self.conn.get_property(false, window, self.atoms._NET_WM_NAME, self.atoms.UTF8_STRING, 0, 1024)?.reply() {
            if let Some(value) = reply.value8() {
                return Ok(Some(String::from_utf8_lossy(&value.collect::<Vec<u8>>()).to_string()));
            }
        }
        if let Ok(reply) = self.conn.get_property(false, window, self.atoms.WM_NAME, AtomEnum::STRING, 0, 1024)?.reply() {
            if let Some(value) = reply.value8() {
                return Ok(Some(String::from_utf8_lossy(&value.collect::<Vec<u8>>()).to_string()));
            }
        }
        Ok(None)
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut listener = X11FocusListener::new()?;
    loop {
        let (title, class) = listener.get_next_focus_change()?;
        println!("Class: {}", class);
        println!("Title: {}", title);
    }
}

Some key notes need discussion

  • The solution can't be multi platform, since i.e. Wayland doesn't support this (in many cases, like in Gnome)
  • About being a plugin, I think we agreed to it
  • Something I forgot?
@ninjadev64
Copy link
Owner

ninjadev64 commented Oct 13, 2024

All good :)

Looking forward to it!

@teras
Copy link
Author

teras commented Oct 13, 2024

Actually I am not sure I can do this , at least alone. I know that I requested it, but it's not something I feel I can manage there.

@ninjadev64
Copy link
Owner

Well, you've done 75% of the work already! If you have Discord or Matrix, feel free to join the OpenDeck chats and I can show you which bits of the OpenDeck internals you need to interface with ;)

@teras
Copy link
Author

teras commented Oct 15, 2024

I might have an old Discord account. We''l find some time that both of us are online.

@ninjadev64
Copy link
Owner

Awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants