desktop-icons-overlay.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. #!/usr/bin/env python3
  2. """
  3. Desktop icons overlay for we_manager.
  4. Renders desktop icons on a transparent layer-shell surface (LAYER_BOTTOM)
  5. so they appear on top of the linux-wallpaperengine wallpaper.
  6. The overlay is purely visual: input passes through via an empty wl_region
  7. to plasmashell's Folder View underneath, which handles clicks normally.
  8. Launch with: LD_PRELOAD=/usr/lib64/libgtk4-layer-shell.so python3 this.py [MONITOR]
  9. """
  10. import sys
  11. import os
  12. import json
  13. import subprocess
  14. import configparser
  15. import cairo as _cairo # pycairo, needed for the empty input region
  16. import gi
  17. gi.require_version('Gtk4LayerShell', '1.0')
  18. gi.require_version('Gtk', '4.0')
  19. from gi.repository import Gtk4LayerShell, Gtk, Gdk, Gio, GLib
  20. def get_desktop_dir():
  21. try:
  22. result = subprocess.run(
  23. ['xdg-user-dir', 'DESKTOP'], capture_output=True, text=True, timeout=3
  24. )
  25. if result.returncode == 0 and result.stdout.strip():
  26. return result.stdout.strip()
  27. except Exception:
  28. pass
  29. return os.path.expanduser('~/Desktop')
  30. def get_panel_offset():
  31. """Detect KDE panel position and size to offset the icon grid."""
  32. try:
  33. output = subprocess.run(
  34. ['qdbus', 'org.kde.plasmashell', '/PlasmaShell',
  35. 'org.kde.PlasmaShell.evaluateScript',
  36. '''var p = panels();
  37. for (var i = 0; i < p.length; i++)
  38. print(p[i].location + "," + p[i].height);'''],
  39. capture_output=True, text=True, timeout=3
  40. )
  41. if output.returncode == 0:
  42. for line in output.stdout.strip().split('\n'):
  43. parts = line.strip().split(',')
  44. if len(parts) == 2:
  45. loc, size = parts[0], int(parts[1])
  46. # location: 3=left, 4=right, 5=top, 6=bottom
  47. if loc == 'left':
  48. return size, 0, 0, 0 # left, right, top, bottom
  49. elif loc == 'right':
  50. return 0, size, 0, 0
  51. elif loc == 'top':
  52. return 0, 0, size, 0
  53. elif loc == 'bottom':
  54. return 0, 0, 0, size
  55. except Exception:
  56. pass
  57. return 0, 0, 0, 0
  58. def parse_kde_positions(screen_key='2560x1440'):
  59. """Parse icon positions from KDE's plasma desktop config."""
  60. config_path = os.path.expanduser(
  61. '~/.config/plasma-org.kde.plasma.desktop-appletsrc'
  62. )
  63. if not os.path.exists(config_path):
  64. return {}, 1, 1
  65. try:
  66. cp = configparser.ConfigParser(strict=False)
  67. cp.read(config_path)
  68. for section in cp.sections():
  69. if not section.endswith('][General]'):
  70. continue
  71. if not cp.has_option(section, 'positions'):
  72. continue
  73. positions_raw = cp.get(section, 'positions')
  74. try:
  75. positions_data = json.loads(positions_raw)
  76. except json.JSONDecodeError:
  77. continue
  78. if screen_key not in positions_data:
  79. for key in positions_data:
  80. screen_key = key
  81. break
  82. else:
  83. continue
  84. arr = positions_data[screen_key]
  85. if len(arr) < 2:
  86. continue
  87. cols = int(arr[0])
  88. rows = int(arr[1])
  89. icons = {}
  90. i = 2
  91. while i + 2 < len(arr):
  92. name = arr[i]
  93. col = int(arr[i + 1])
  94. row = int(arr[i + 2])
  95. if name.startswith('desktop:/'):
  96. name = name[len('desktop:/'):]
  97. icons[name] = (col, row)
  98. i += 3
  99. return icons, cols, rows
  100. except Exception as e:
  101. print(f'Error parsing KDE positions: {e}', file=sys.stderr)
  102. return {}, 1, 1
  103. def get_desktop_entries(desktop_dir):
  104. entries = []
  105. if not os.path.isdir(desktop_dir):
  106. return entries
  107. for name in sorted(os.listdir(desktop_dir)):
  108. if name.startswith('.'):
  109. continue
  110. full_path = os.path.join(desktop_dir, name)
  111. if name.endswith('.desktop'):
  112. entry = parse_desktop_file(full_path)
  113. if entry:
  114. entry['filename'] = name
  115. entries.append(entry)
  116. else:
  117. entries.append({
  118. 'filename': name,
  119. 'name': name,
  120. 'icon_name': get_mime_icon(full_path),
  121. 'path': full_path,
  122. })
  123. return entries
  124. def parse_desktop_file(path):
  125. try:
  126. real_path = os.path.realpath(path)
  127. kf = GLib.KeyFile()
  128. kf.load_from_file(real_path, GLib.KeyFileFlags.NONE)
  129. name = kf.get_locale_string('Desktop Entry', 'Name', None)
  130. icon = kf.get_string('Desktop Entry', 'Icon')
  131. return {
  132. 'name': name or os.path.basename(path),
  133. 'icon_name': icon or 'application-x-executable',
  134. 'path': path,
  135. }
  136. except Exception:
  137. return None
  138. def get_mime_icon(path):
  139. try:
  140. f = Gio.File.new_for_path(path)
  141. info = f.query_info('standard::icon', Gio.FileQueryInfoFlags.NONE, None)
  142. icon = info.get_icon()
  143. if isinstance(icon, Gio.ThemedIcon):
  144. names = icon.get_names()
  145. if names:
  146. return names[0]
  147. except Exception:
  148. pass
  149. return 'folder' if os.path.isdir(path) else 'text-x-generic'
  150. # Kirigami icon size table (index to pixels), matching FolderTools.js
  151. _ICON_SIZE_TABLE = [22, 32, 48, 64, 96, 128, 256]
  152. # CSS font-weight mapping from KDE weight values (Qt::Weight)
  153. _KDE_WEIGHT_MAP = {
  154. 25: 200, # Light
  155. 50: 400, # Normal
  156. 57: 500, # Medium
  157. 63: 600, # DemiBold
  158. 75: 700, # Bold
  159. 81: 800, # ExtraBold
  160. 87: 900, # Black
  161. }
  162. def detect_kde_settings():
  163. """Auto-detect icon size, font, and label styling from KDE config.
  164. Returns a dict with keys:
  165. icon_size (int), font_family (str), font_size_pt (int),
  166. font_weight (int CSS weight), font_italic (bool)
  167. """
  168. settings = {
  169. 'icon_size': 64,
  170. 'font_family': 'Noto Sans',
  171. 'font_size_pt': 11,
  172. 'font_weight': 400,
  173. 'font_italic': False,
  174. }
  175. # --- Icon size from Folder View config ---
  176. try:
  177. config_path = os.path.expanduser(
  178. '~/.config/plasma-org.kde.plasma.desktop-appletsrc'
  179. )
  180. if os.path.exists(config_path):
  181. cp = configparser.ConfigParser(strict=False)
  182. cp.read(config_path)
  183. # Find the desktop containment's General section
  184. for section in cp.sections():
  185. if 'General' not in section:
  186. continue
  187. if cp.has_option(section, 'iconSize'):
  188. idx = int(cp.get(section, 'iconSize'))
  189. if 0 <= idx < len(_ICON_SIZE_TABLE):
  190. settings['icon_size'] = _ICON_SIZE_TABLE[idx]
  191. break
  192. except Exception:
  193. pass
  194. # --- System font from kreadconfig6 ---
  195. try:
  196. result = subprocess.run(
  197. ['kreadconfig6', '--file', 'kdeglobals',
  198. '--group', 'General', '--key', 'font'],
  199. capture_output=True, text=True, timeout=3
  200. )
  201. if result.returncode == 0 and result.stdout.strip():
  202. # Format: family,pointSize,pixelSize,styleHint,weight,italic,...
  203. parts = result.stdout.strip().split(',')
  204. if len(parts) >= 6:
  205. settings['font_family'] = parts[0]
  206. try:
  207. settings['font_size_pt'] = int(parts[1])
  208. except ValueError:
  209. pass
  210. try:
  211. kde_weight = int(parts[4])
  212. closest = min(_KDE_WEIGHT_MAP.keys(),
  213. key=lambda k: abs(k - kde_weight))
  214. settings['font_weight'] = _KDE_WEIGHT_MAP[closest]
  215. except (ValueError, IndexError):
  216. pass
  217. try:
  218. settings['font_italic'] = parts[5] == '1'
  219. except IndexError:
  220. pass
  221. except FileNotFoundError:
  222. pass
  223. except Exception:
  224. pass
  225. # KDE Folder View always renders desktop icon labels in italic
  226. settings['font_italic'] = True
  227. return settings
  228. _kde = detect_kde_settings()
  229. ICON_SIZE = _kde['icon_size']
  230. CELL_WIDTH = 120
  231. CELL_HEIGHT = 96
  232. # KDE Folder View internal padding (approx)
  233. GRID_MARGIN = 8
  234. def build_icon_widget(entry, icon_theme):
  235. box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
  236. box.set_halign(Gtk.Align.CENTER)
  237. box.set_size_request(CELL_WIDTH, CELL_HEIGHT)
  238. icon_name = entry.get('icon_name', 'application-x-executable')
  239. image = Gtk.Image()
  240. image.set_pixel_size(ICON_SIZE)
  241. paintable = icon_theme.lookup_icon(
  242. icon_name, None, ICON_SIZE, 1,
  243. Gtk.TextDirection.NONE, Gtk.IconLookupFlags(0)
  244. )
  245. if paintable:
  246. image.set_from_paintable(paintable)
  247. else:
  248. fallback = icon_theme.lookup_icon(
  249. 'application-x-executable', None, ICON_SIZE, 1,
  250. Gtk.TextDirection.NONE, Gtk.IconLookupFlags(0)
  251. )
  252. if fallback:
  253. image.set_from_paintable(fallback)
  254. image.set_halign(Gtk.Align.CENTER)
  255. box.append(image)
  256. label = Gtk.Label(label=entry.get('name', ''))
  257. label.set_max_width_chars(12)
  258. label.set_ellipsize(3) # PANGO_ELLIPSIZE_END
  259. label.set_halign(Gtk.Align.CENTER)
  260. label.set_justify(Gtk.Justification.CENTER)
  261. label.set_wrap(True)
  262. label.set_wrap_mode(2) # PANGO_WRAP_WORD_CHAR
  263. label.set_lines(2)
  264. label.add_css_class('icon-label')
  265. box.append(label)
  266. return box
  267. def main():
  268. monitor_name = sys.argv[1] if len(sys.argv) > 1 else None
  269. desktop_dir = get_desktop_dir()
  270. window = None
  271. file_monitor = None
  272. empty_region = _cairo.Region()
  273. def apply_empty_input_region(widget, frame_clock):
  274. """Tick callback: reapply empty input region every frame."""
  275. surface = window.get_surface()
  276. if surface:
  277. surface.set_input_region(empty_region)
  278. return True # Keep the callback active
  279. def on_activate(app):
  280. nonlocal window, file_monitor
  281. if window:
  282. return
  283. window = Gtk.Window()
  284. window.set_application(app)
  285. # Layer shell init BEFORE present
  286. Gtk4LayerShell.init_for_window(window)
  287. Gtk4LayerShell.set_layer(window, Gtk4LayerShell.Layer.BOTTOM)
  288. Gtk4LayerShell.set_namespace(window, 'desktop')
  289. if monitor_name:
  290. display = Gdk.Display.get_default()
  291. monitors = display.get_monitors()
  292. for i in range(monitors.get_n_items()):
  293. mon = monitors.get_item(i)
  294. if mon.get_connector() == monitor_name:
  295. Gtk4LayerShell.set_monitor(window, mon)
  296. break
  297. # Fullscreen
  298. for edge in (Gtk4LayerShell.Edge.TOP, Gtk4LayerShell.Edge.BOTTOM,
  299. Gtk4LayerShell.Edge.LEFT, Gtk4LayerShell.Edge.RIGHT):
  300. Gtk4LayerShell.set_anchor(window, edge, True)
  301. Gtk4LayerShell.set_exclusive_zone(window, -1)
  302. Gtk4LayerShell.set_keyboard_mode(window, Gtk4LayerShell.KeyboardMode.NONE)
  303. font_style = 'italic' if _kde['font_italic'] else 'normal'
  304. font_weight = _kde['font_weight']
  305. css = Gtk.CssProvider()
  306. css.load_from_string(f"""
  307. window {{ background: transparent; }}
  308. .icon-label {{
  309. color: white;
  310. font-family: "{_kde['font_family']}";
  311. font-size: {_kde['font_size_pt']}pt;
  312. font-weight: {font_weight};
  313. font-style: {font_style};
  314. }}
  315. """)
  316. Gtk.StyleContext.add_provider_for_display(
  317. Gdk.Display.get_default(), css,
  318. Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
  319. )
  320. build_icons()
  321. desktop_file = Gio.File.new_for_path(desktop_dir)
  322. file_monitor = desktop_file.monitor_directory(
  323. Gio.FileMonitorFlags.NONE, None
  324. )
  325. file_monitor.connect('changed', on_desktop_changed)
  326. window.present()
  327. # Reapply empty input region every frame so GTK4 can't override it
  328. window.add_tick_callback(apply_empty_input_region)
  329. def build_icons():
  330. if not window:
  331. return
  332. display = Gdk.Display.get_default()
  333. monitors = display.get_monitors()
  334. screen_w, screen_h = 2560, 1440
  335. for i in range(monitors.get_n_items()):
  336. mon = monitors.get_item(i)
  337. if monitor_name and mon.get_connector() != monitor_name:
  338. continue
  339. geo = mon.get_geometry()
  340. screen_w = geo.width
  341. screen_h = geo.height
  342. break
  343. panel_left, panel_right, panel_top, panel_bottom = get_panel_offset()
  344. screen_key = f'{screen_w}x{screen_h}'
  345. kde_positions, grid_cols, grid_rows = parse_kde_positions(screen_key)
  346. # KDE Folder View uses a fixed cell size based on icon size (not screen/grid ratio).
  347. # The grid_rows value tells us how many cells fit vertically.
  348. # cell_h = available_height / grid_rows (typically ~62px for 48px icons)
  349. avail_h = screen_h - panel_top - panel_bottom
  350. cell_h = avail_h / max(grid_rows, 1)
  351. # Cell width is the same fixed size regardless of column count
  352. cell_w = CELL_WIDTH
  353. entries = get_desktop_entries(desktop_dir)
  354. if not entries:
  355. window.set_child(Gtk.Box())
  356. return
  357. fixed = Gtk.Fixed()
  358. icon_theme = Gtk.IconTheme.get_for_display(Gdk.Display.get_default())
  359. for entry in entries:
  360. filename = entry['filename']
  361. if filename in kde_positions:
  362. col, row = kde_positions[filename]
  363. else:
  364. col, row = 0, len(kde_positions)
  365. kde_positions[filename] = (col, row)
  366. # Top-left alignment within grid cell (matches KDE Folder View)
  367. x = panel_left + GRID_MARGIN + col * cell_w
  368. y = panel_top + GRID_MARGIN + row * cell_h
  369. widget = build_icon_widget(entry, icon_theme)
  370. fixed.put(widget, max(0, x), max(0, y))
  371. window.set_child(fixed)
  372. def on_desktop_changed(monitor, file, other_file, event_type):
  373. if event_type in (
  374. Gio.FileMonitorEvent.CREATED,
  375. Gio.FileMonitorEvent.DELETED,
  376. Gio.FileMonitorEvent.MOVED_IN,
  377. Gio.FileMonitorEvent.MOVED_OUT,
  378. ):
  379. GLib.timeout_add(500, build_icons)
  380. app = Gtk.Application(application_id='com.wemanager.desktop-icons-overlay')
  381. app.connect('activate', on_activate)
  382. app.run(None)
  383. if __name__ == '__main__':
  384. main()