yabai.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. _dual_display: None | Literal[True] | Literal[False] = None
  93. _exit_with_rule_apply: bool = False
  94. _exit_with_refocus: bool = False
  95. _display_labels: tuple[str, str] = ("Main", "Secondary")
  96. def __init__(self):
  97. self._dual_display = len(self.get_displays()) > 1
  98. if self._dual_display:
  99. self.spaces.append(
  100. (
  101. "Communication",
  102. False,
  103. ["Slack", "Signal", "Spotify"],
  104. False,
  105. )
  106. )
  107. for application in [
  108. "Google Meet",
  109. "Obsidian",
  110. "Asana",
  111. "Notion",
  112. "Netflix",
  113. "YouTube",
  114. ]:
  115. self.spaces.append(
  116. (
  117. application,
  118. True,
  119. [application],
  120. False,
  121. )
  122. )
  123. else:
  124. self.spaces.append(
  125. (
  126. "Communication",
  127. False,
  128. ["Slack", "Signal", "Spotify", "Notion"],
  129. False,
  130. )
  131. )
  132. self.spaces.append(("Notetaking", True, ["Obsidian", "Asana"], False))
  133. def __enter__(self):
  134. self._initial_window = self.get_focused_window()
  135. return self
  136. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any):
  137. if exc_type is not None:
  138. debug(f"Exited with {exc_type} {exc_value}")
  139. if self._exit_with_rule_apply:
  140. self.message(["rule", "--apply"])
  141. if self._exit_with_refocus or self._exit_with_rule_apply:
  142. if self._initial_window is not None:
  143. self.message(["window", "--focus", self._initial_window.id])
  144. if exc_type is None:
  145. debug(f"Executed successfully")
  146. def get_windows(self) -> set[Window]:
  147. return {
  148. Window(window) for window in loads(self.message(["query", "--windows"]))
  149. }
  150. def get_spaces(self) -> set[Space]:
  151. return {Space(space) for space in loads(self.message(["query", "--spaces"]))}
  152. def get_displays(self) -> set[YabaiDisplay]:
  153. return {
  154. YabaiDisplay(display)
  155. for display in loads(self.message(["query", "--displays"]))
  156. }
  157. def get_main_display(
  158. self, displays: set[YabaiDisplay] | None = None
  159. ) -> YabaiDisplay:
  160. return sorted(list(displays if displays != None else self.get_displays()))[-1]
  161. def is_blank_space(self, space: Space) -> bool:
  162. return (
  163. space.label not in {s[0] for s in self.spaces}
  164. and not space.is_native_fullscreen
  165. )
  166. def manage_displays(self):
  167. displays = self.get_displays()
  168. main_display = self.get_main_display(displays)
  169. secondary_display = None
  170. for display in displays:
  171. if display.index == main_display.index:
  172. self.message(
  173. ["display", display.index, "--label", self._display_labels[0]]
  174. )
  175. elif secondary_display == None:
  176. self.message(
  177. ["display", display.index, "--label", self._display_labels[1]]
  178. )
  179. secondary_display = display
  180. else:
  181. self.message(
  182. [
  183. "display",
  184. display.index,
  185. "--label",
  186. f"YabaiDisplay {display.index}",
  187. ]
  188. )
  189. def manage_spaces(self):
  190. initial_window = self.get_focused_window()
  191. # Start by making sure that the expected number of spaces are present
  192. spaces = self.get_spaces()
  193. occupied_spaces = {
  194. space
  195. for space in spaces
  196. if not self.is_blank_space(space) and not space.is_native_fullscreen
  197. }
  198. blank_spaces = {space for space in spaces if self.is_blank_space(space)}
  199. for _ in range(
  200. max(0, len(self.spaces) - (len(occupied_spaces) + len(blank_spaces)))
  201. ):
  202. self.message(["space", "--create"])
  203. # Use blank spaces to create occupied spaces as necessary
  204. spaces = self.get_spaces()
  205. blank_spaces = {space for space in spaces if self.is_blank_space(space)}
  206. created_space_labels: set[tuple[str, bool]] = set()
  207. for space_label, space_fullscreen, _, _ in self.spaces:
  208. if any(space.label == space_label for space in spaces):
  209. continue
  210. space = blank_spaces.pop()
  211. self.message(["space", space.index, "--label", space_label])
  212. created_space_labels.add((space_label, space_fullscreen))
  213. # Remove unnecessary spaces
  214. spaces = self.get_spaces()
  215. blank_spaces = [space for space in spaces if self.is_blank_space(space)]
  216. blank_spaces.sort(key=lambda s: s.index, reverse=True)
  217. # Make sure that the focused space isn't a blank one
  218. if any(space.has_focus for space in blank_spaces):
  219. self.message(["space", "--focus", self.spaces[0][0]])
  220. for space in blank_spaces:
  221. self.message(["space", "--destroy", space.index])
  222. # Configure the new spaces
  223. main_display = self.get_main_display()
  224. for label, fullscreen in created_space_labels:
  225. self.set_space_background(label)
  226. for label, fullscreen, _, _ in self.spaces:
  227. self.set_config(
  228. label,
  229. fullscreen=fullscreen,
  230. horizontal_padding=int(
  231. (main_display.frame["w"] - TARGET_DISPLAY_WIDTH) / 2
  232. ),
  233. vertical_padding=int(
  234. (main_display.frame["h"] - TARGET_DISPLAY_HEIGHT) / 2
  235. ),
  236. )
  237. if len(created_space_labels) > 0 and initial_window is not None:
  238. self.message(["window", "--focus", initial_window.id])
  239. # Return focus
  240. if initial_window is not None:
  241. self.message(["window", "--focus", initial_window.id])
  242. info(f"Spaces configured: {sorted(self.get_spaces())}")
  243. def set_space_background(self, space: SpaceSel):
  244. try:
  245. self.message(["space", "--focus", space])
  246. except CalledProcessError:
  247. # Almost certainly thrown because space is already focused, so no problem
  248. pass
  249. self.execute(
  250. [
  251. "osascript",
  252. "-e",
  253. 'tell application "System Events" to tell every desktop to set picture to "/System/Library/Desktop Pictures/Solid Colors/Black.png"',
  254. ]
  255. )
  256. def set_config(
  257. self,
  258. space: SpaceSel,
  259. fullscreen: bool = False,
  260. gap: int = 10,
  261. vertical_padding: int = 0,
  262. horizontal_padding: int = 0,
  263. ):
  264. for config in [
  265. ["window_shadow", "float"],
  266. ["window_opacity", "on"],
  267. ["layout", "bsp"],
  268. ["top_padding", int(max(0 if fullscreen else gap, vertical_padding))],
  269. ["bottom_padding", int(max(0 if fullscreen else gap, vertical_padding))],
  270. ["left_padding", int(max(0 if fullscreen else gap, horizontal_padding))],
  271. ["right_padding", int(max(0 if fullscreen else gap, horizontal_padding))],
  272. ["window_gap", gap],
  273. ]:
  274. self.message(["config", "--space", space] + config)
  275. def set_rules_and_signals(self):
  276. # Reset rules and signals
  277. for domain in ["rule", "signal"]:
  278. for _ in range(len(loads(self.message([domain, "--list"])))):
  279. self.message([domain, "--remove", 0])
  280. # Load the system agent on dock restart
  281. self.message(
  282. [
  283. "signal",
  284. "--add",
  285. "label=SystemAgentReloadSignal",
  286. "event=dock_did_restart",
  287. "action=sudo yabai --load-sa",
  288. ]
  289. )
  290. # Reload spaces when displays are reset
  291. for reload_event in ["display_added", "display_removed"]:
  292. self.message(
  293. [
  294. "signal",
  295. "--add",
  296. f"label={reload_event}RestartSignal",
  297. f"event={reload_event}",
  298. f"action=/bin/zsh {XDG_CONFIG_HOME}/yabai/yabairc",
  299. ]
  300. )
  301. # Normal windows should be put on the desktop
  302. self.message(
  303. [
  304. "rule",
  305. "--add",
  306. "label=DefaultDesktopRule",
  307. "subrole=AXStandardWindow",
  308. "space=^Desktop",
  309. ]
  310. )
  311. # Rules for applications that get their own spaces
  312. for label, _, apps, _ in self.spaces:
  313. for app in apps:
  314. if app == "*":
  315. continue
  316. self.message(
  317. [
  318. "rule",
  319. "--add",
  320. f"label={app}{label}Rule",
  321. f"app={app}",
  322. f"space=^{label}",
  323. ]
  324. )
  325. # Compile SurfingKeys configuration when Firefox is launched
  326. self.message(
  327. [
  328. "signal",
  329. "--add",
  330. "event=application_launched",
  331. "app=Firefox",
  332. "label=FirefoxCompileExtensionsSignal",
  333. f"action=/bin/zsh {XDG_CONFIG_HOME}/surfingkeys/compile.sh",
  334. ]
  335. )
  336. # Run Slack client script (populating cached values) when Slack is launched
  337. self.message(
  338. [
  339. "signal",
  340. "--add",
  341. "event=application_launched",
  342. "app=Slack",
  343. "label=SlackRunSlackClientScript",
  344. f"action=/usr/bin/env python3 {HOME}/.scripts/slack_client.py",
  345. ]
  346. )
  347. # "Attach" OBS to Google Meet
  348. self.message(
  349. [
  350. "signal",
  351. "--add",
  352. "event=application_launched",
  353. "app=Google Meet",
  354. "label=GoogleMeetOBSJoiner",
  355. f"action=/usr/bin/env python3 {HOME}/.scripts/obs_client.py Activate Default StartVirtualCam",
  356. ]
  357. )
  358. self.message(
  359. [
  360. "signal",
  361. "--add",
  362. "event=application_terminated",
  363. "app=Google Meet",
  364. "label=GoogleMeetOBSJoinerEnd",
  365. f"action=/usr/bin/env python3 {HOME}/.scripts/obs_client.py StopVirtualCam Activate Disabled",
  366. ]
  367. )
  368. # Check if dark mode settings have been updated when focusing terminal
  369. self.message(
  370. [
  371. "signal",
  372. "--add",
  373. "event=window_focused",
  374. "app=Alacritty",
  375. "label=AlacrittyCheckDarkMode",
  376. f"action=/bin/zsh {HOME}/.scripts/lightmode.zsh",
  377. ]
  378. )
  379. for trigger in [
  380. "display_added",
  381. "display_removed",
  382. "display_resized",
  383. "system_woke",
  384. ]:
  385. self.message(
  386. [
  387. "signal",
  388. "--add",
  389. f"event={trigger}",
  390. f"label=DisplayChange{trigger}",
  391. f"action=/usr/bin/env python3 {HOME}/.config/yabai.py manage",
  392. ]
  393. )
  394. # Rules that differ for one or multiple displays
  395. if self._dual_display:
  396. pass
  397. else:
  398. # Google Meet and Slack Huddles should be "sticky"
  399. for app, title in (("Google Meet", ".*"), ("Slack", "Huddle.*")):
  400. self.message(
  401. [
  402. "rule",
  403. "--add",
  404. f"label={app}VideoCallFloatingWindowRule",
  405. f"app={app}",
  406. f"title={title}",
  407. "sticky=on",
  408. "manage=on",
  409. "opacity=0.9",
  410. "grid=10:10:6:6:4:4",
  411. ]
  412. )
  413. # Tiny streaming player
  414. self.message(
  415. [
  416. "rule",
  417. "--add",
  418. f"label=NetflixFloatingWindowRule",
  419. f"app=Netflix",
  420. "sticky=on",
  421. "manage=on",
  422. ]
  423. )
  424. def move_spaces_to_displays(self):
  425. if not self._dual_display:
  426. return
  427. current_spaces = self.get_spaces()
  428. displays = self.get_displays()
  429. main_display = next(
  430. (d for d in displays if d.label == self._display_labels[0]), None
  431. )
  432. secondary_display = next(
  433. (d for d in displays if d.label == self._display_labels[1]), None
  434. )
  435. if main_display is None or secondary_display is None:
  436. return
  437. incorrect_main_spaces: set[Space] = set()
  438. incorrect_secondary_spaces: set[Space] = set()
  439. for space_label, _, _, is_main_display_space in self.spaces:
  440. mapped_space = next(
  441. (s for s in current_spaces if s.label == space_label), None
  442. )
  443. if mapped_space is None:
  444. continue
  445. if (
  446. mapped_space.display == main_display.index
  447. and not is_main_display_space
  448. and secondary_display
  449. ):
  450. incorrect_secondary_spaces.add(mapped_space)
  451. elif mapped_space.display != main_display.index and is_main_display_space:
  452. incorrect_main_spaces.add(mapped_space)
  453. last_focus = next((s.label for s in current_spaces if s.has_focus), None)
  454. while len(incorrect_main_spaces) > 0 and len(incorrect_secondary_spaces) > 0:
  455. from_space = incorrect_main_spaces.pop()
  456. to_space = incorrect_secondary_spaces.pop()
  457. if to_space.label == last_focus:
  458. from_space, to_space = to_space, from_space
  459. self.message(
  460. [
  461. "space",
  462. from_space.label,
  463. "--switch",
  464. to_space.label,
  465. ]
  466. )
  467. last_focus = to_space.label
  468. for spaces, secondary in (
  469. (incorrect_main_spaces, False),
  470. (incorrect_secondary_spaces, True),
  471. ):
  472. for space in spaces:
  473. self.message(
  474. [
  475. "space",
  476. space.label,
  477. "--display",
  478. secondary_display.label
  479. if secondary and secondary_display
  480. else main_display.label,
  481. ]
  482. )
  483. def sort_spaces(self):
  484. all_spaces = [s.label for s in sorted(self.get_spaces())]
  485. for is_main in (True, False) if self._dual_display else [None]:
  486. order = [
  487. s[0]
  488. for s in self.spaces
  489. if s[0] in all_spaces and (s[3] == is_main) or is_main is None
  490. ]
  491. spaces = [s for s in all_spaces if s in order]
  492. while tuple(spaces) != tuple(order) and len(spaces) == len(order):
  493. for index in range(1, len(spaces)):
  494. if order.index(spaces[index]) < order.index(spaces[index - 1]):
  495. self.message(["space", spaces[index], "--move", "prev"])
  496. spaces[index], spaces[index - 1] = (
  497. spaces[index - 1],
  498. spaces[index],
  499. )
  500. def get_focused_window(self) -> Window | None:
  501. windows = [
  502. window
  503. for window in [
  504. Window(window) for window in loads(self.message(["query", "--windows"]))
  505. ]
  506. if window.has_focus
  507. ]
  508. if len(windows) > 0:
  509. return windows.pop()
  510. return None
  511. def invert_displays(self) -> None:
  512. if not self._dual_display:
  513. return
  514. displays = self.get_displays()
  515. for display in displays:
  516. self.message(
  517. [
  518. "display",
  519. display.index,
  520. "--label",
  521. f"TEMP{display.label}",
  522. ]
  523. )
  524. for display in displays:
  525. if display.label == self._display_labels[0]:
  526. self.message(
  527. [
  528. "display",
  529. display.index,
  530. "--label",
  531. self._display_labels[1],
  532. ]
  533. )
  534. elif display.label == self._display_labels[1]:
  535. self.message(
  536. [
  537. "display",
  538. display.index,
  539. "--label",
  540. self._display_labels[0],
  541. ]
  542. )
  543. else:
  544. self.message(
  545. [
  546. "display",
  547. display.index,
  548. "--label",
  549. display.label,
  550. ]
  551. )
  552. def enable_exit_with_rule_apply(self):
  553. self._exit_with_rule_apply = True
  554. self.enable_exit_with_refocus()
  555. def enable_exit_with_refocus(self):
  556. self._exit_with_refocus = True
  557. if __name__ == "__main__":
  558. basicConfig(level=NOTSET)
  559. debug(f"Called with parameters {argv}")
  560. with Yabai() as yabai:
  561. if argv[1] == "manage" or argv[1] == "initialize":
  562. yabai.enable_exit_with_rule_apply()
  563. yabai.manage_displays()
  564. yabai.manage_spaces()
  565. if argv[1] == "initialize":
  566. yabai.set_rules_and_signals()
  567. if argv[1] == "invert":
  568. yabai.invert_displays()
  569. yabai.enable_exit_with_rule_apply()
  570. if (
  571. argv[1] == "move"
  572. or argv[1] == "manage"
  573. or argv[1] == "initialize"
  574. or argv[1] == "invert"
  575. ):
  576. yabai.move_spaces_to_displays()
  577. # Disabled until moving spaces no longer triggers mission control
  578. # yabai.sort_spaces()
  579. yabai.enable_exit_with_refocus()