x-win 5.7.0

This package allows you to retrieve precise information about active and open windows on Windows, MacOS, and Linux. You can obtain the position, size, title, and other memory of windows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#![deny(unused_imports)]

use base64::Engine;
use image::ImageFormat;

use xcb::{x, Connection, Xid, XidNew};

use crate::{
  common::{
    api::{empty_icon, Api},
    result::Result,
    x_win_struct::{icon_info::IconInfo, window_info::WindowInfo, window_position::WindowPosition},
  },
  empty_entity,
  linux::api::common_api::{get_window_memory_usage, get_window_path_name},
};

use super::common_api::init_entity;

/**
 * Struct to use similar as API to get active window and open windows for XOrg desktop
 */
pub struct X11Api {}

/**
 * Impl. for windows system
 */
impl Api for X11Api {
  fn get_active_window(&self) -> Result<WindowInfo> {
    let conn = connection()?;
    let setup = conn.get_setup();

    match setup.roots().next() {
      Some(screen) => {
        let active_window_atom = get_active_window_atom(&conn);
        if active_window_atom != x::ATOM_NONE {
          let active_windows = conn.send_request(&x::GetProperty {
            delete: false,
            window: screen.root(),
            property: active_window_atom,
            r#type: x::ATOM_WINDOW,
            long_offset: 0,
            long_length: 1,
          });
          if let Ok(active_windows) = conn.wait_for_reply(active_windows) {
            return match active_windows.value::<x::Window>().first() {
              Some(active_window) => {
                let active_window = get_window_information(&conn, active_window)?;
                Ok(active_window)
              }
              None => Ok(empty_entity()),
            };
          }
        }
        Err(
          String::from(
            "Something got wrong, not possible to get active window calling _NET_ACTIVE_WINDOW",
          )
          .into(),
        )
      }
      None => {
        Err(String::from("Something got wrong, not possible to get access of X Server!").into())
      }
    }
  }

  fn get_open_windows(&self) -> Result<Vec<WindowInfo>> {
    let conn = connection()?;
    let setup = conn.get_setup();

    match setup.roots().next() {
      Some(screen) => {
        let open_windows_atom = get_client_list_stacking_atom(&conn);

        if open_windows_atom != x::ATOM_NONE {
          let window_list = conn.send_request(&x::GetProperty {
            delete: false,
            window: screen.root(),
            property: open_windows_atom,
            r#type: x::ATOM_WINDOW,
            long_offset: 0,
            long_length: u32::MAX,
          });

          if let Ok(windows_reply) = conn.wait_for_reply(window_list) {
            let window_list: Vec<x::Window> = windows_reply.value::<x::Window>().to_vec();
            let mut results: Vec<WindowInfo> = Vec::new();

            if window_list.len().ne(&0) {
              for window in window_list {
                let window: &x::Window = &window;
                if let Ok(result) = get_window_information(&conn, window) {
                  if result.id.ne(&0) && is_normal_window(&conn, *window) {
                    results.push(result);
                  }
                }
              }
            }

            return Ok(results);
          }
        }
        Err(String::from("Something got wrong, not possible to get active window calling _NET_CLIENT_LIST_STACKING").into())
      }
      None => {
        Err(String::from("Something got wrong, not possible to get access of X Server!").into())
      }
    }
  }

  fn get_app_icon(&self, window_info: &WindowInfo) -> Result<IconInfo> {
    let conn = connection()?;
    let setup = conn.get_setup();

    let root_window = setup.roots().next();
    if root_window.is_some() {
      let window = XidNew::new(window_info.id);
      let icon_atom = get_window_icon_atom(&conn);
      if icon_atom != x::ATOM_NONE {
        let icon_cookie = conn.send_request(&x::GetProperty {
          delete: false,
          window,
          property: icon_atom,
          r#type: x::ATOM_CARDINAL,
          long_offset: 0,
          long_length: u32::MAX,
        });
        if let Ok(icon_reply) = conn.wait_for_reply(icon_cookie) {
          let icon_data: &[u32] = icon_reply.value::<u32>();
          if !icon_data.is_empty() {
            let width = icon_data[0] as usize;
            let height = icon_data[1] as usize;
            let bgra_data: &[u32] = &icon_data[2..2 + (width * height)];

            let mut buffer: Vec<u8> = vec![0u8; height * width * 4];

            for (i, &bgra) in bgra_data.iter().enumerate() {
              let b = (bgra & 0xFF) as u8;
              let g = ((bgra >> 8) & 0xFF) as u8;
              let r = ((bgra >> 16) & 0xFF) as u8;
              let a = ((bgra >> 24) & 0xFF) as u8;
              let index = i * 4;
              buffer[index] = r;
              buffer[index + 1] = g;
              buffer[index + 2] = b;
              buffer[index + 3] = a;
            }
            let mut png_data: Vec<u8> = Vec::new();
            {
              if let Some(buffer) = image::RgbaImage::from_raw(width as u32, height as u32, buffer)
              {
                let _ = buffer.write_to(&mut std::io::Cursor::new(&mut png_data), ImageFormat::Png);
                let data = base64::prelude::BASE64_STANDARD.encode(png_data);
                return Ok(IconInfo {
                  data: format!("data:image/png;base64,{data}").to_owned(),
                  height: height as u32,
                  width: width as u32,
                });
              }
            }
          }
        }
      }
    }
    Ok(empty_icon())
  }

  fn get_browser_url(&self, _: &WindowInfo) -> Result<String> {
    Ok(super::common_api::get_browser_url())
  }
}

fn connection() -> Result<Connection> {
  let (conn, _) = xcb::Connection::connect(None)?;
  Ok(conn)
}

/**
 * Get window information
 */
fn get_window_information(conn: &xcb::Connection, window: &x::Window) -> Result<WindowInfo> {
  let mut window_info: WindowInfo = init_entity();
  if window.is_none() {
    return Ok(window_info);
  }
  let window_pid: u32 = get_window_pid(conn, *window)?;
  if window_pid != 0 {
    let (path, exec_name) = get_window_path_name(window_pid)?;
    window_info.id = window.resource_id();
    window_info.title = get_window_title(conn, *window);
    window_info.info.process_id = window_pid;
    window_info.info.path = path;
    window_info.info.exec_name = exec_name;
    window_info.info.name = get_window_class_name(conn, *window);
    window_info.usage.memory = get_window_memory_usage(window_pid)?;
    window_info.position = get_window_position(conn, *window);
  }

  Ok(window_info)
}

/**
 * Get pid
 */
fn get_window_pid(conn: &xcb::Connection, window: x::Window) -> Result<u32> {
  let window_pid_atom = get_window_pid_atom(conn);

  if window_pid_atom != x::ATOM_NONE {
    let window_pid = conn.send_request(&x::GetProperty {
      delete: false,
      window,
      property: window_pid_atom,
      r#type: x::ATOM_ANY,
      long_offset: 0,
      long_length: 1,
    });

    if let Ok(window_pid) = conn.wait_for_reply(window_pid) {
      if let Some(pid) = window_pid.value::<u32>().first() {
        return Ok(*pid);
      }
    }
  }
  Err(String::from("Not possible to recver pid for the window when calling _NET_WM_PID!").into())
}

/**
 * Get window width, height, x and y
 */
fn get_window_position(conn: &xcb::Connection, window: x::Window) -> WindowPosition {
  let mut position = WindowPosition {
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    is_full_screen: is_full_screen_window(conn, window),
  };
  let window_geometry = conn.send_request(&x::GetGeometry {
    drawable: x::Drawable::Window(window),
  });
  if let Ok(window_geometry) = conn.wait_for_reply(window_geometry) {
    position.height = window_geometry.height() as i32;
    position.width = window_geometry.width() as i32;
    let window_geometry_x = window_geometry.x();
    let window_geometry_y = window_geometry.y();
    let translated_position = conn.send_request(&x::TranslateCoordinates {
      dst_window: window_geometry.root(),
      src_window: window,
      src_x: window_geometry_x,
      src_y: window_geometry_y,
    });
    if let Ok(translated_position) = conn.wait_for_reply(translated_position) {
      position.x = (translated_position.dst_x() - window_geometry_x) as i32;
      position.y = (translated_position.dst_y() - window_geometry_y) as i32;
    }
  }

  position
}

/**
 * Get window title
 */
fn get_window_title(conn: &xcb::Connection, window: x::Window) -> String {
  _get_string_response(conn, window, x::ATOM_WM_NAME)
}

fn _get_string_response(conn: &xcb::Connection, window: x::Window, property: x::Atom) -> String {
  let window_title = conn.send_request(&x::GetProperty {
    delete: false,
    window,
    property,
    r#type: x::ATOM_NONE,
    long_offset: 0,
    long_length: u32::MAX,
  });
  if let Ok(window_title) = conn.wait_for_reply(window_title) {
    let window_title: &[u8] = window_title.value();
    unsafe { std::str::from_utf8_unchecked(window_title).to_string() }
  } else {
    String::from("")
  }
}

/**
 * Get process name
 */
fn get_window_class_name(conn: &xcb::Connection, window: x::Window) -> String {
  let window_class = conn.send_request(&x::GetProperty {
    delete: false,
    window,
    property: x::ATOM_WM_CLASS,
    r#type: x::ATOM_STRING,
    long_offset: 0,
    long_length: u32::MAX,
  });
  if let Ok(window_class) = conn.wait_for_reply(window_class) {
    let window_class = window_class.value();
    let window_class = std::str::from_utf8(window_class);

    let mut process_name = window_class
      .unwrap_or("")
      .split('\u{0}')
      .filter(|str| !str.is_empty())
      .collect::<Vec<&str>>();
    return process_name.pop().unwrap_or("").to_owned();
  }

  String::from("")
}

fn get_window_pid_atom(conn: &xcb::Connection) -> x::Atom {
  get_atom(conn, b"_NET_WM_PID", true)
}

/**
 * Generate Atom of _NET_ACTIVE_WINDOW value
 */
fn get_active_window_atom(conn: &xcb::Connection) -> x::Atom {
  get_atom(conn, b"_NET_ACTIVE_WINDOW", true)
}

/**
 * Generate Atom of _NET_CLIENT_LIST_STACKING value
 */
fn get_client_list_stacking_atom(conn: &xcb::Connection) -> x::Atom {
  get_atom(conn, b"_NET_CLIENT_LIST_STACKING", true)
}

/**
 * Generate Atom of _NET_WM_WINDOW_TYPE value
 */
fn get_window_type_atom(conn: &xcb::Connection) -> x::Atom {
  get_atom(conn, b"_NET_WM_WINDOW_TYPE", true)
}

/**
 * Generate Atom of _NET_WM_WINDOW_TYPE_NORMAL value
 */
fn get_window_type_normal_atom(conn: &xcb::Connection) -> x::Atom {
  get_atom(conn, b"_NET_WM_WINDOW_TYPE_NORMAL", true)
}

/**
 * Generate Atom of _NET_WM_STATE value
 */
fn get_window_state_atom(conn: &xcb::Connection) -> x::Atom {
  get_atom(conn, b"_NET_WM_STATE", false)
}

/**
 * Generate Atom of _NET_WM_STATE_FULLSCREEN value
 */
fn get_window_state_fullscreen_atom(conn: &xcb::Connection) -> x::Atom {
  get_atom(conn, b"_NET_WM_STATE_FULLSCREEN", false)
}

/**
 * Generate Atom of _NET_WM_ICON value
 */
fn get_window_icon_atom(conn: &xcb::Connection) -> x::Atom {
  get_atom(conn, b"_NET_WM_ICON", false)
}

/**
 * Generate Atom of name parameter
 */
fn get_atom(conn: &xcb::Connection, name: &[u8], only_if_exists: bool) -> x::Atom {
  let atom_name = conn.send_request(&x::InternAtom {
    only_if_exists,
    name,
  });
  if let Ok(value) = conn.wait_for_reply(atom_name) {
    value.atom()
  } else {
    x::ATOM_NONE
  }
}

/**
 * Check if the window is a normal type
 */
fn is_normal_window(conn: &xcb::Connection, window: x::Window) -> bool {
  let window_type_atom = get_window_type_atom(conn);
  let type_normal_atom = get_window_type_normal_atom(conn);
  if window_type_atom != x::ATOM_NONE && type_normal_atom != x::ATOM_NONE {
    let window_state = conn.send_request(&x::GetProperty {
      delete: false,
      window,
      property: window_type_atom,
      r#type: x::ATOM_ATOM,
      long_offset: 0,
      long_length: u32::MAX,
    });
    if let Ok(window_state) = conn.wait_for_reply(window_state) {
      return window_state.value().contains(&type_normal_atom);
    }
  }
  false
}

/**
 * Check if the window is full screened
 */
fn is_full_screen_window(conn: &xcb::Connection, window: x::Window) -> bool {
  let state_window_atom = get_window_state_atom(conn);
  let state_fullscreen_atom = get_window_state_fullscreen_atom(conn);
  if state_window_atom != x::ATOM_NONE && state_fullscreen_atom != x::ATOM_NONE {
    let window_state = conn.send_request(&x::GetProperty {
      delete: false,
      window,
      property: state_window_atom,
      r#type: x::ATOM_ATOM,
      long_offset: 0,
      long_length: u32::MAX,
    });
    if let Ok(window_state) = conn.wait_for_reply(window_state) {
      return window_state.value().contains(&state_fullscreen_atom);
    }
  }
  false
}