|
1 | 1 | import sys |
| 2 | +import json |
2 | 3 | from typing import Optional |
3 | 4 |
|
4 | 5 |
|
5 | | -def get_current_window_linux() -> Optional[dict]: |
6 | | - from . import xlib |
7 | | - window = xlib.get_current_window() |
| 6 | +class Linux: |
| 7 | + def __init__(self): |
| 8 | + try: |
| 9 | + import pydbus |
| 10 | + self.bus = pydbus.SessionBus() |
| 11 | + except ModuleNotFoundError: |
| 12 | + self.bus = False |
| 13 | + |
| 14 | + if self.bus: |
| 15 | + import gi.repository.GLib |
| 16 | + try: |
| 17 | + self.gnome_shell = self.bus.get("org.gnome.Shell") |
| 18 | + except gi.repository.GLib.Error: |
| 19 | + self.gnome_shell = None |
| 20 | + |
| 21 | + def get_current_window(self) -> dict: |
| 22 | + if self.gnome_shell: |
| 23 | + return self.get_current_window_gnome_shell() |
| 24 | + |
| 25 | + return self.get_current_window_x11() |
| 26 | + |
| 27 | + def get_current_window_gnome_shell(self) -> dict: |
| 28 | + """get current app from GNOME Shell via dbus""" |
| 29 | + js_code = """ |
| 30 | + var window_list = global.get_window_actors(); |
| 31 | + var active_window_actor = window_list.find(window => window.meta_window.has_focus()); |
| 32 | + var active_window = active_window_actor.get_meta_window() |
| 33 | + var vm_class = active_window.get_wm_class(); |
| 34 | + var title = active_window.get_title() |
| 35 | + var result = {"title": title, "appname": vm_class}; |
| 36 | + result |
| 37 | + """ |
| 38 | + |
| 39 | + ok, result = self.gnome_shell.Eval(js_code) |
| 40 | + if ok: |
| 41 | + result_data = json.loads(result) |
| 42 | + return result_data |
| 43 | + |
| 44 | + return {"appname": "unknown", "title": "unknown"} |
| 45 | + |
| 46 | + def get_current_window_x11() -> dict: |
| 47 | + from . import xlib |
| 48 | + window = xlib.get_current_window() |
| 49 | + |
| 50 | + if window is None: |
| 51 | + cls = "unknown" |
| 52 | + name = "unknown" |
| 53 | + else: |
| 54 | + cls = xlib.get_window_class(window) |
| 55 | + name = xlib.get_window_name(window) |
| 56 | + |
| 57 | + return {"appname": cls, "title": name} |
8 | 58 |
|
9 | | - if window is None: |
10 | | - cls = "unknown" |
11 | | - name = "unknown" |
12 | | - else: |
13 | | - cls = xlib.get_window_class(window) |
14 | | - name = xlib.get_window_name(window) |
15 | 59 |
|
16 | | - return {"appname": cls, "title": name} |
| 60 | +if sys.platform.startswith("linux"): |
| 61 | + linux = Linux() |
17 | 62 |
|
18 | 63 |
|
19 | 64 | def get_current_window_macos() -> Optional[dict]: |
@@ -41,7 +86,7 @@ def get_current_window_windows() -> Optional[dict]: |
41 | 86 |
|
42 | 87 | def get_current_window() -> Optional[dict]: |
43 | 88 | if sys.platform.startswith("linux"): |
44 | | - return get_current_window_linux() |
| 89 | + return linux.get_current_window() |
45 | 90 | elif sys.platform == "darwin": |
46 | 91 | return get_current_window_macos() |
47 | 92 | elif sys.platform in ["win32", "cygwin"]: |
|
0 commit comments