1

How can I get the mouse's position relative to the terminal on Linux? This is what I have so far:

use std::ptr;
use x11::xlib;

fn main() {
    unsafe {
        let display = xlib::XOpenDisplay(ptr::null());

        if display.is_null() {
            panic!("XOpenDisplay failed");
        }

        let mut root_return = 0;
        let mut child_return = 0;
        let mut root_x_return = 0;
        let mut root_y_return = 0;
        let mut win_x_return = 0;
        let mut win_y_return = 0;
        let mut mask_return = 0;

        let screen = xlib::XDefaultScreen(display);
        let window = xlib::XRootWindow(display, screen);

        xlib::XQueryPointer(
            display,
            window,
            &mut root_return,
            &mut child_return,
            &mut root_x_return,
            &mut root_y_return,
            &mut win_x_return,
            &mut win_y_return,
            &mut mask_return,
        );
        // root_x_return and root_y_return are the same as win_x_return and win_y_return
        dbg!(root_x_return, root_y_return, win_x_return, win_y_return,);
    }
}

It gives me the global mouse's position on the whole screen. What do I have to do to get the output relative only to the current terminal's window? So that 0, 0 starts at the first terminal cell pixel.

치큰0
  • 43
  • 2
  • 3

1 Answers1

1

It looks like you are getting the root window with XRootWindow(), and then passing that to XQueryPointer() as the window to get relative mouse coordinates for. In that case, you would expect that root_return and win_return values to be the same.

If you created a new X window, and passed that in to XQueryPointer() instead, then for the win_*_return values, you should get coordinates relative to that new window instead of to the root window.

Getting the current terminal window is a bit tricky, since it's actually owned by another process (the terminal process that is running the shell). The process you launch from the terminal window is sending and receiving text through the OS and doesn't have direct access to the terminal process or it's windows. You could possibly find the process id of the terminal and then find the X window id that belongs to that process, but that is by no means trivial

transistor
  • 1,480
  • 1
  • 9
  • 12