yabai.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. #!/usr/bin/env python3
  2. # pyright: strict, reportAny=false, reportExplicitAny=false, reportUnusedCallResult=false
  3. from json import loads
  4. from logging import NOTSET, basicConfig, debug, info
  5. from os import getenv
  6. from subprocess import CalledProcessError, check_output
  7. from sys import argv
  8. from typing import Any, Literal, TypeAlias, cast, override
  9. HOME = getenv("HOME")
  10. XDG_CONFIG_HOME = getenv("XDG_CONFIG_HOME")
  11. TARGET_DISPLAY_WIDTH = 1920
  12. TARGET_DISPLAY_HEIGHT = 1080
  13. class Window:
  14. def __init__(self, data: dict[str, Any]):
  15. self.id: int = data["id"]
  16. self.app: str = data["app"]
  17. self.space: str = data["space"]
  18. self.title: str = data["title"]
  19. self.has_focus: bool = data["has-focus"]
  20. self.frame_w: int = data["frame"]["w"]
  21. self.frame_h: int = data["frame"]["h"]
  22. @property
  23. def size(self) -> int:
  24. return self.frame_w * self.frame_h
  25. @override
  26. def __repr__(self) -> str:
  27. return (
  28. f"Window({self.title} | {self.app}"
  29. f", {self.id}"
  30. f"{', Focused' if self.has_focus else ''})"
  31. )
  32. def __gt__(self, other: "Window"):
  33. return self.id.__gt__(other.id)
  34. class Space:
  35. def __init__(self, data: dict[str, Any]):
  36. self.id: int = data["id"]
  37. self.index: int = data["index"]
  38. self.label: str = data["label"]
  39. self.display: int = data["display"]
  40. self.windows: list[int] = data["label"]
  41. self.is_visible: str = data["is-visible"]
  42. self.has_focus: bool = data["has-focus"]
  43. self.is_native_fullscreen: bool = data["is-native-fullscreen"]
  44. @override
  45. def __repr__(self) -> str:
  46. return (
  47. f"Space({self.label if self.label and len(self.label) > 0 else '<NoLabel>'}"
  48. f", {self.index}"
  49. f"{', Fullscreen' if self.is_native_fullscreen else ''}"
  50. f", {self.display}"
  51. f"{', Focused' if self.has_focus else ''})"
  52. )
  53. def __gt__(self, other: "Space"):
  54. return self.index.__gt__(other.index)
  55. class YabaiDisplay:
  56. def __init__(self, data: dict[str, Any]):
  57. self.id: int = data["id"]
  58. self.uuid: str = data["uuid"]
  59. self.index: int = data["index"]
  60. self.label: str = data["label"]
  61. self.has_focus: bool = data["has-focus"]
  62. self.spaces: list[str] = data["spaces"]
  63. self.frame: dict[str, int] = data["frame"]
  64. @override
  65. def __repr__(self) -> str:
  66. return (
  67. f"Display({self.label if self.label and len(self.label) > 0 else '<NoLabel>'}"
  68. f", {self.index}"
  69. f", Frame ({self.frame})"
  70. f"{', Focused' if self.has_focus else ''})"
  71. )
  72. def __gt__(self, other: "YabaiDisplay"):
  73. return self.frame["w"].__gt__(other.frame["w"])
  74. SpaceSel: TypeAlias = int | str
  75. class CLIWrapper:
  76. _base_args: list[str] = []
  77. def message(self, args: list[str | int]) -> str:
  78. return self.execute(self._base_args + [str(arg) for arg in args]).decode("utf8")
  79. def execute(self, *args: Any, **kwargs: Any) -> Any:
  80. debug(f"Executing: ({args}), ({kwargs})")
  81. return cast(str, check_output(*args, **kwargs))
  82. class Yabai(CLIWrapper):
  83. _base_args: list[str] = ["yabai", "-m"]
  84. # Label, Full-Page, Apps, Main Display
  85. spaces: list[tuple[str, bool, list[str], bool]] = [
  86. ("Desktop", False, ["*"], True),
  87. ("Finder", False, ["Finder"], True),
  88. ("Terminal", True, ["Alacritty"], True),
  89. ("Browser", True, ["Firefox"], True),
  90. ]
  91. _initial_window: Window | None = None
  92. _initial_spaces: list[Space] = []
  93. _dual_display: None | Literal[True] | Literal[False] = None
  94. _exit_with_rule_apply: bool = False
  95. _exit_with_refocus: bool = False
  96. _display_labels: tuple[str, str] = ("Main", "Secondary")
  97. def __init__(self):
  98. self._dual_display = len(self.get_displays()) > 1
  99. self.spaces.append(
  100. (
  101. "Communication",
  102. False,
  103. ["Slack", "Signal", "Spotify"],
  104. False,
  105. )
  106. )
  107. if self._dual_display:
  108. for application in [
  109. "Google Meet",
  110. "Obsidian",
  111. "Asana",
  112. "Notion",
  113. "Netflix",
  114. "YouTube",
  115. ]:
  116. self.spaces.append(
  117. (
  118. application,
  119. True,
  120. [application],
  121. False,
  122. )
  123. )
  124. else:
  125. self.spaces.append(("Notetaking", True, ["Obsidian", "Asana", "Notion"], False))
  126. def __enter__(self):
  127. self._initial_window = self.get_focused_window()
  128. self._initial_spaces = [s for s in self.get_spaces() if s.is_visible and len(s.label)]
  129. return self
  130. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any):
  131. if exc_type is not None:
  132. debug(f"Exited with {exc_type} {exc_value}")
  133. if self._exit_with_rule_apply:
  134. self.message(["rule", "--apply"])
  135. if self._exit_with_refocus or self._exit_with_rule_apply:
  136. for space in self._initial_spaces:
  137. try:
  138. self.message(["space", "--focus", space.label])
  139. except CalledProcessError:
  140. pass
  141. if self._initial_window is not None:
  142. self.message(["window", "--focus", self._initial_window.id])
  143. if exc_type is None:
  144. debug("Executed successfully")
  145. def get_windows(self) -> set[Window]:
  146. return {
  147. Window(window) for window in loads(self.message(["query", "--windows"]))
  148. }
  149. def get_spaces(self) -> set[Space]:
  150. return {Space(space) for space in loads(self.message(["query", "--spaces"]))}
  151. def get_displays(self) -> set[YabaiDisplay]:
  152. return {
  153. YabaiDisplay(display)
  154. for display in loads(self.message(["query", "--displays"]))
  155. }
  156. def get_main_display(
  157. self, displays: set[YabaiDisplay] | None = None
  158. ) -> YabaiDisplay:
  159. return sorted(list(displays if displays is not None else self.get_displays()))[-1]
  160. def is_blank_space(self, space: Space) -> bool:
  161. return (
  162. space.label not in {s[0] for s in self.spaces}
  163. and not space.is_native_fullscreen
  164. )
  165. def manage_displays(self):
  166. displays = self.get_displays()
  167. main_display = self.get_main_display(displays)
  168. secondary_display = None
  169. for display in displays:
  170. if display.index == main_display.index:
  171. self.message(
  172. ["display", display.index, "--label", self._display_labels[0]]
  173. )
  174. elif secondary_display is None:
  175. self.message(
  176. ["display", display.index, "--label", self._display_labels[1]]
  177. )
  178. secondary_display = display
  179. else:
  180. self.message(
  181. [
  182. "display",
  183. display.index,
  184. "--label",
  185. f"YabaiDisplay {display.index}",
  186. ]
  187. )
  188. def manage_spaces(self):
  189. initial_window = self.get_focused_window()
  190. # Start by making sure that the expected number of spaces are present
  191. spaces = self.get_spaces()
  192. occupied_spaces = {
  193. space
  194. for space in spaces
  195. if not self.is_blank_space(space) and not space.is_native_fullscreen
  196. }
  197. blank_spaces = {space for space in spaces if self.is_blank_space(space)}
  198. for _ in range(
  199. max(0, len(self.spaces) - (len(occupied_spaces) + len(blank_spaces)))
  200. ):
  201. self.message(["space", "--create"])
  202. # Use blank spaces to create occupied spaces as necessary
  203. spaces = self.get_spaces()
  204. blank_spaces = {space for space in spaces if self.is_blank_space(space)}
  205. created_space_labels: set[tuple[str, bool]] = set()
  206. for space_label, space_fullscreen, _, _ in self.spaces:
  207. if any(space.label == space_label for space in spaces):
  208. continue
  209. space = blank_spaces.pop()
  210. self.message(["space", space.index, "--label", space_label])
  211. created_space_labels.add((space_label, space_fullscreen))
  212. # Remove unnecessary spaces
  213. spaces = self.get_spaces()
  214. blank_spaces = [space for space in spaces if self.is_blank_space(space)]
  215. blank_spaces.sort(key=lambda s: s.index, reverse=True)
  216. # Make sure that the focused space isn't a blank one
  217. if any(space.has_focus for space in blank_spaces):
  218. self.message(["space", "--focus", self.spaces[0][0]])
  219. for space in blank_spaces:
  220. self.message(["space", "--destroy", space.index])
  221. # Configure the new spaces
  222. main_display = self.get_main_display()
  223. for label, fullscreen in created_space_labels:
  224. self.set_space_background(label)
  225. for label, fullscreen, _, _ in self.spaces:
  226. self.set_config(
  227. label,
  228. fullscreen=fullscreen,
  229. horizontal_padding=int(
  230. (main_display.frame["w"] - TARGET_DISPLAY_WIDTH) / 2
  231. ),
  232. vertical_padding=int(
  233. (main_display.frame["h"] - TARGET_DISPLAY_HEIGHT) / 2
  234. ),
  235. )
  236. if len(created_space_labels) > 0 and initial_window is not None:
  237. self.message(["window", "--focus", initial_window.id])
  238. # Return focus
  239. if initial_window is not None:
  240. self.message(["window", "--focus", initial_window.id])
  241. if self._dual_display:
  242. display_by_space_label = {s[0]: 1 if s[-1] else 2 for s in self.spaces}
  243. spaces = self.get_spaces()
  244. wrong_spaces = [s for s in spaces
  245. if s.label in display_by_space_label and
  246. s.display != display_by_space_label[s.label]]
  247. wrong_main_spaces = [s for s in wrong_spaces if s.display != 1]
  248. wrong_secondary_spaces = [s for s in wrong_spaces if s.display != 2]
  249. while len(wrong_main_spaces) and len (wrong_secondary_spaces):
  250. self.message([ "space", wrong_main_spaces.pop().label, "--swap", wrong_secondary_spaces.pop().label ])
  251. wrong_spaces = wrong_main_spaces + wrong_secondary_spaces
  252. while len(wrong_spaces) and (space := wrong_spaces.pop().label):
  253. self.message([ "space", space, "--display", display_by_space_label[space]])
  254. info(f"Spaces configured: {sorted(self.get_spaces())}")
  255. def set_space_background(self, space: SpaceSel):
  256. try:
  257. self.message(["space", "--focus", space])
  258. except CalledProcessError:
  259. # Almost certainly thrown because space is already focused, so no problem
  260. pass
  261. self.execute(
  262. [
  263. "osascript",
  264. "-e",
  265. 'tell application "System Events" to tell every desktop to set picture to "/System/Library/Desktop Pictures/Solid Colors/Black.png"',
  266. ]
  267. )
  268. def set_global_config( self,):
  269. self.message(["config", "auto_balance", "on"])
  270. self.message(["config", "mouse_follows_focus", "on"])
  271. def set_config(
  272. self,
  273. space: SpaceSel,
  274. fullscreen: bool = False,
  275. gap: int = 10,
  276. vertical_padding: int = 0,
  277. horizontal_padding: int = 0,
  278. ):
  279. for config in [
  280. ["window_shadow", "float"],
  281. ["window_opacity", "on"],
  282. ["layout", "bsp"],
  283. ["top_padding", int(max(0 if fullscreen else gap, vertical_padding))],
  284. ["bottom_padding", int(max(0 if fullscreen else gap, vertical_padding))],
  285. ["left_padding", int(max(0 if fullscreen else gap, horizontal_padding))],
  286. ["right_padding", int(max(0 if fullscreen else gap, horizontal_padding))],
  287. ["window_gap", gap],
  288. ]:
  289. self.message(["config", "--space", space] + config)
  290. def set_rules_and_signals(self):
  291. # Reset rules and signals
  292. for domain in ["rule", "signal"]:
  293. for _ in range(len(loads(self.message([domain, "--list"])))):
  294. self.message([domain, "--remove", 0])
  295. # Load the system agent on dock restart
  296. self.message(
  297. [
  298. "signal",
  299. "--add",
  300. "label=SystemAgentReloadSignal",
  301. "event=dock_did_restart",
  302. "action=sudo yabai --load-sa",
  303. ]
  304. )
  305. # Reload spaces when displays are reset
  306. for reload_event in ["display_added", "display_removed"]:
  307. self.message(
  308. [
  309. "signal",
  310. "--add",
  311. f"label={reload_event}RestartSignal",
  312. f"event={reload_event}",
  313. f"action=/bin/zsh {XDG_CONFIG_HOME}/yabai/yabairc",
  314. ]
  315. )
  316. # Normal windows should be put on the desktop
  317. self.message(
  318. [
  319. "rule",
  320. "--add",
  321. "label=DefaultDesktopRule",
  322. "subrole=AXStandardWindow",
  323. "space=^Desktop",
  324. ]
  325. )
  326. # Rules for applications that get their own spaces
  327. for label, _, apps, _ in self.spaces:
  328. for app in apps:
  329. if app == "*":
  330. continue
  331. self.message(
  332. [
  333. "rule",
  334. "--add",
  335. f"label={app}{label}Rule",
  336. f"app={app}",
  337. f"space=^{label}",
  338. ]
  339. )
  340. # Compile SurfingKeys configuration when Firefox is launched
  341. self.message(
  342. [
  343. "signal",
  344. "--add",
  345. "event=application_launched",
  346. "app=Firefox",
  347. "label=FirefoxCompileExtensionsSignal",
  348. f"action=/bin/zsh {XDG_CONFIG_HOME}/surfingkeys/compile.sh",
  349. ]
  350. )
  351. # Run Slack client script (populating cached values) when Slack is launched
  352. self.message(
  353. [
  354. "signal",
  355. "--add",
  356. "event=application_launched",
  357. "app=Slack",
  358. "label=SlackRunSlackClientScript",
  359. f"action=/usr/bin/env python3 {HOME}/.scripts/slack_client.py",
  360. ]
  361. )
  362. # Check if dark mode settings have been updated when focusing terminal
  363. self.message(
  364. [
  365. "signal",
  366. "--add",
  367. "event=window_focused",
  368. "app=Alacritty",
  369. "label=AlacrittyCheckDarkMode",
  370. "action=/bin/zsh $DOTFILES_DIR/.scripts/lightmode.zsh",
  371. ]
  372. )
  373. self.message(
  374. [
  375. "signal",
  376. "--add",
  377. "event=display_added",
  378. "label=DisplayBrightnessManager",
  379. "action=/bin/zsh $DOTFILES_DIR/.scripts/display_brightness.zsh",
  380. ]
  381. )
  382. if self._dual_display:
  383. self.message(
  384. [
  385. "signal",
  386. "--add",
  387. "event=window_focused",
  388. "label=DisplayBrightnessManager",
  389. "action=/bin/zsh $DOTFILES_DIR/.scripts/display_brightness.zsh",
  390. ]
  391. )
  392. for trigger in [
  393. "display_added",
  394. "display_removed",
  395. "display_resized",
  396. "system_woke",
  397. ]:
  398. self.message(
  399. [
  400. "signal",
  401. "--add",
  402. f"event={trigger}",
  403. f"label=DisplayChange{trigger}",
  404. f"action=/usr/bin/env python3 {HOME}/.config/yabai.py manage",
  405. ]
  406. )
  407. # Rules that differ for one or multiple displays
  408. if not self._dual_display:
  409. # Google Meet and Slack Huddles should be "sticky"
  410. for app, title in (("Google Meet", ".*"), ("Slack", "Huddle.*")):
  411. self.message(
  412. [
  413. "rule",
  414. "--add",
  415. f"label={app}VideoCallFloatingWindowRule",
  416. f"app={app}",
  417. f"title={title}",
  418. "sticky=on",
  419. "manage=on",
  420. "opacity=0.9",
  421. "grid=10:10:6:6:4:4",
  422. ]
  423. )
  424. # Tiny streaming player
  425. self.message(
  426. [
  427. "rule",
  428. "--add",
  429. "label=NetflixFloatingWindowRule",
  430. "app=Netflix",
  431. "sticky=on",
  432. "manage=on",
  433. ]
  434. )
  435. def move_spaces_to_displays(self):
  436. if not self._dual_display:
  437. return
  438. current_spaces = self.get_spaces()
  439. displays = self.get_displays()
  440. main_display = next(
  441. (d for d in displays if d.label == self._display_labels[0]), None
  442. )
  443. secondary_display = next(
  444. (d for d in displays if d.label == self._display_labels[1]), None
  445. )
  446. if main_display is None or secondary_display is None:
  447. return
  448. incorrect_main_spaces: set[Space] = set()
  449. incorrect_secondary_spaces: set[Space] = set()
  450. for space_label, _, _, is_main_display_space in self.spaces:
  451. mapped_space = next(
  452. (s for s in current_spaces if s.label == space_label), None
  453. )
  454. if mapped_space is None:
  455. continue
  456. if (
  457. mapped_space.display == main_display.index
  458. and not is_main_display_space
  459. and secondary_display
  460. ):
  461. incorrect_secondary_spaces.add(mapped_space)
  462. elif mapped_space.display != main_display.index and is_main_display_space:
  463. incorrect_main_spaces.add(mapped_space)
  464. last_focus = next((s.label for s in current_spaces if s.has_focus), None)
  465. while len(incorrect_main_spaces) > 0 and len(incorrect_secondary_spaces) > 0:
  466. from_space = incorrect_main_spaces.pop()
  467. to_space = incorrect_secondary_spaces.pop()
  468. if to_space.label == last_focus:
  469. from_space, to_space = to_space, from_space
  470. self.message(
  471. [
  472. "space",
  473. from_space.label,
  474. "--switch",
  475. to_space.label,
  476. ]
  477. )
  478. last_focus = to_space.label
  479. for spaces, secondary in (
  480. (incorrect_main_spaces, False),
  481. (incorrect_secondary_spaces, True),
  482. ):
  483. for space in spaces:
  484. self.message(
  485. [
  486. "space",
  487. space.label,
  488. "--display",
  489. secondary_display.label
  490. if secondary and secondary_display
  491. else main_display.label,
  492. ]
  493. )
  494. def sort_spaces(self):
  495. all_spaces = [s.label for s in sorted(self.get_spaces())]
  496. for is_main in (True, False) if self._dual_display else [None]:
  497. order = [
  498. s[0]
  499. for s in self.spaces
  500. if s[0] in all_spaces and (s[3] == is_main) or is_main is None
  501. ]
  502. spaces = [s for s in all_spaces if s in order]
  503. while tuple(spaces) != tuple(order) and len(spaces) == len(order):
  504. for index in range(1, len(spaces)):
  505. if order.index(spaces[index]) < order.index(spaces[index - 1]):
  506. self.message(["space", spaces[index], "--move", "prev"])
  507. spaces[index], spaces[index - 1] = (
  508. spaces[index - 1],
  509. spaces[index],
  510. )
  511. def get_focused_window(self) -> Window | None:
  512. windows = [
  513. window
  514. for window in [
  515. Window(window) for window in loads(self.message(["query", "--windows"]))
  516. ]
  517. if window.has_focus
  518. ]
  519. if len(windows) > 0:
  520. return windows.pop()
  521. return None
  522. def enable_exit_with_rule_apply(self):
  523. self._exit_with_rule_apply = True
  524. self.enable_exit_with_refocus()
  525. def enable_exit_with_refocus(self):
  526. self._exit_with_refocus = True
  527. if __name__ == "__main__":
  528. basicConfig(level=NOTSET)
  529. debug(f"Called with parameters {argv}")
  530. with Yabai() as yabai:
  531. if argv[1] == "manage" or argv[1] == "initialize":
  532. yabai.set_global_config()
  533. yabai.enable_exit_with_rule_apply()
  534. yabai.manage_displays()
  535. yabai.manage_spaces()
  536. if argv[1] == "initialize":
  537. yabai.set_rules_and_signals()
  538. if (
  539. argv[1] == "move"
  540. or argv[1] == "manage"
  541. or argv[1] == "initialize"
  542. ):
  543. yabai.enable_exit_with_refocus()
  544. yabai.move_spaces_to_displays()