0
0

yabai.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. # Check if dark mode settings have been updated when focusing terminal
  348. self.message(
  349. [
  350. "signal",
  351. "--add",
  352. "event=window_focused",
  353. "app=Alacritty",
  354. "label=AlacrittyCheckDarkMode",
  355. f"action=/bin/zsh {HOME}/.scripts/lightmode.zsh",
  356. ]
  357. )
  358. for trigger in [
  359. "display_added",
  360. "display_removed",
  361. "display_resized",
  362. "system_woke",
  363. ]:
  364. self.message(
  365. [
  366. "signal",
  367. "--add",
  368. f"event={trigger}",
  369. f"label=DisplayChange{trigger}",
  370. f"action=/usr/bin/env python3 {HOME}/.config/yabai.py manage",
  371. ]
  372. )
  373. # Rules that differ for one or multiple displays
  374. if self._dual_display:
  375. pass
  376. else:
  377. # Google Meet and Slack Huddles should be "sticky"
  378. for app, title in (("Google Meet", ".*"), ("Slack", "Huddle.*")):
  379. self.message(
  380. [
  381. "rule",
  382. "--add",
  383. f"label={app}VideoCallFloatingWindowRule",
  384. f"app={app}",
  385. f"title={title}",
  386. "sticky=on",
  387. "manage=on",
  388. "opacity=0.9",
  389. "grid=10:10:6:6:4:4",
  390. ]
  391. )
  392. # Tiny streaming player
  393. self.message(
  394. [
  395. "rule",
  396. "--add",
  397. f"label=NetflixFloatingWindowRule",
  398. f"app=Netflix",
  399. "sticky=on",
  400. "manage=on",
  401. ]
  402. )
  403. def move_spaces_to_displays(self):
  404. if not self._dual_display:
  405. return
  406. current_spaces = self.get_spaces()
  407. displays = self.get_displays()
  408. main_display = next(
  409. (d for d in displays if d.label == self._display_labels[0]), None
  410. )
  411. secondary_display = next(
  412. (d for d in displays if d.label == self._display_labels[1]), None
  413. )
  414. if main_display is None or secondary_display is None:
  415. return
  416. incorrect_main_spaces: set[Space] = set()
  417. incorrect_secondary_spaces: set[Space] = set()
  418. for space_label, _, _, is_main_display_space in self.spaces:
  419. mapped_space = next(
  420. (s for s in current_spaces if s.label == space_label), None
  421. )
  422. if mapped_space is None:
  423. continue
  424. if (
  425. mapped_space.display == main_display.index
  426. and not is_main_display_space
  427. and secondary_display
  428. ):
  429. incorrect_secondary_spaces.add(mapped_space)
  430. elif mapped_space.display != main_display.index and is_main_display_space:
  431. incorrect_main_spaces.add(mapped_space)
  432. last_focus = next((s.label for s in current_spaces if s.has_focus), None)
  433. while len(incorrect_main_spaces) > 0 and len(incorrect_secondary_spaces) > 0:
  434. from_space = incorrect_main_spaces.pop()
  435. to_space = incorrect_secondary_spaces.pop()
  436. if to_space.label == last_focus:
  437. from_space, to_space = to_space, from_space
  438. self.message(
  439. [
  440. "space",
  441. from_space.label,
  442. "--switch",
  443. to_space.label,
  444. ]
  445. )
  446. last_focus = to_space.label
  447. for spaces, secondary in (
  448. (incorrect_main_spaces, False),
  449. (incorrect_secondary_spaces, True),
  450. ):
  451. for space in spaces:
  452. self.message(
  453. [
  454. "space",
  455. space.label,
  456. "--display",
  457. secondary_display.label
  458. if secondary and secondary_display
  459. else main_display.label,
  460. ]
  461. )
  462. def sort_spaces(self):
  463. all_spaces = [s.label for s in sorted(self.get_spaces())]
  464. for is_main in (True, False) if self._dual_display else [None]:
  465. order = [
  466. s[0]
  467. for s in self.spaces
  468. if s[0] in all_spaces and (s[3] == is_main) or is_main is None
  469. ]
  470. spaces = [s for s in all_spaces if s in order]
  471. while tuple(spaces) != tuple(order) and len(spaces) == len(order):
  472. for index in range(1, len(spaces)):
  473. if order.index(spaces[index]) < order.index(spaces[index - 1]):
  474. self.message(["space", spaces[index], "--move", "prev"])
  475. spaces[index], spaces[index - 1] = (
  476. spaces[index - 1],
  477. spaces[index],
  478. )
  479. def get_focused_window(self) -> Window | None:
  480. windows = [
  481. window
  482. for window in [
  483. Window(window) for window in loads(self.message(["query", "--windows"]))
  484. ]
  485. if window.has_focus
  486. ]
  487. if len(windows) > 0:
  488. return windows.pop()
  489. return None
  490. def invert_displays(self) -> None:
  491. if not self._dual_display:
  492. return
  493. displays = self.get_displays()
  494. for display in displays:
  495. self.message(
  496. [
  497. "display",
  498. display.index,
  499. "--label",
  500. f"TEMP{display.label}",
  501. ]
  502. )
  503. for display in displays:
  504. if display.label == self._display_labels[0]:
  505. self.message(
  506. [
  507. "display",
  508. display.index,
  509. "--label",
  510. self._display_labels[1],
  511. ]
  512. )
  513. elif display.label == self._display_labels[1]:
  514. self.message(
  515. [
  516. "display",
  517. display.index,
  518. "--label",
  519. self._display_labels[0],
  520. ]
  521. )
  522. else:
  523. self.message(
  524. [
  525. "display",
  526. display.index,
  527. "--label",
  528. display.label,
  529. ]
  530. )
  531. def enable_exit_with_rule_apply(self):
  532. self._exit_with_rule_apply = True
  533. self.enable_exit_with_refocus()
  534. def enable_exit_with_refocus(self):
  535. self._exit_with_refocus = True
  536. if __name__ == "__main__":
  537. basicConfig(level=NOTSET)
  538. debug(f"Called with parameters {argv}")
  539. with Yabai() as yabai:
  540. if argv[1] == "manage" or argv[1] == "initialize":
  541. yabai.enable_exit_with_rule_apply()
  542. yabai.manage_displays()
  543. yabai.manage_spaces()
  544. if argv[1] == "initialize":
  545. yabai.set_rules_and_signals()
  546. if argv[1] == "invert":
  547. yabai.invert_displays()
  548. yabai.enable_exit_with_rule_apply()
  549. if (
  550. argv[1] == "move"
  551. or argv[1] == "manage"
  552. or argv[1] == "initialize"
  553. or argv[1] == "invert"
  554. ):
  555. yabai.enable_exit_with_refocus()
  556. yabai.move_spaces_to_displays()
  557. # Disabled until moving spaces no longer triggers mission control
  558. # yabai.sort_spaces()