Last active
March 1, 2022 06:30
-
-
Save doingweb/0125cf6e4fc11123d8d61aa2b430f51f to your computer and use it in GitHub Desktop.
Have iTerm use a random background for each new window. See https://iterm2.com/python-api/ for details.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.7 | |
# Be sure "Separate background images per pane" is unchecked. | |
import asyncio | |
import iterm2 | |
import json | |
import os | |
import random | |
window_backgrounds = {} | |
async def main(connection): | |
app = await iterm2.async_get_app(connection) | |
async with iterm2.LayoutChangeMonitor(connection) as mon: | |
while True: | |
await mon.async_get() | |
for window in app.windows: | |
background_path = get_background_for_window(window) | |
await set_session_background_paths(window, background_path) | |
purge_closed_windows(app) | |
def get_random_background_path(): | |
backgrounds_dir = "/Users/chris/Pictures/Terminal Backgrounds" | |
random_background_file = random.choice(os.listdir(backgrounds_dir)) | |
return os.path.join(backgrounds_dir, random_background_file) | |
async def set_background(profile, path): | |
await profile.async_set_background_image_location(path) | |
await set_background_settings(profile) | |
async def set_background_settings(profile): | |
await profile.async_set_blend(0.25) | |
await profile.async_set_background_image_mode(2) | |
def get_background_for_window(window): | |
global window_backgrounds; | |
if window.window_id not in window_backgrounds: | |
window_backgrounds[window.window_id] = get_random_background_path() | |
print(f"New background chosen for window {window.window_id}") | |
print(json.dumps(window_backgrounds, indent=2)) | |
return window_backgrounds[window.window_id] | |
async def set_session_background_paths(window, background_path): | |
for tab in window.tabs: | |
for session in tab.sessions: | |
profile = await session.async_get_profile() | |
if not profile: | |
continue | |
if profile.background_image_location != background_path: | |
await set_background(profile, background_path) | |
def purge_closed_windows(app): | |
global window_backgrounds | |
windows_to_purge = [] | |
for window_id in window_backgrounds.keys(): | |
if not app.get_window_by_id(window_id): | |
print(f"Window {window_id} has been closed. Purging.") | |
windows_to_purge.append(window_id) | |
for window_id in windows_to_purge: | |
del window_backgrounds[window_id] | |
iterm2.run_forever(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment