ghosttytheme 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: ghosttytheme
3
+ Version: 0.2.0
4
+ Summary: Live Ghostty theme picker for macOS
5
+ Project-URL: Homepage, https://hypercryptoman.github.io/gtheme/
6
+ Project-URL: Repository, https://github.com/hypercryptoman/gtheme
7
+ Project-URL: Issues, https://github.com/hypercryptoman/gtheme/issues
8
+ Classifier: Environment :: Console
9
+ Classifier: Operating System :: MacOS :: MacOS X
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+
14
+ # ghosttytheme | Live Ghostty theme picker for macOS
15
+
16
+ ghosttytheme lets you preview and change Ghostty themes on macOS with your keyboard. Filter bundled or custom themes by name and see how they color a sample prompt, diff, code, and ANSI palette before you save.
17
+
18
+ [Project site](https://hypercryptoman.github.io/gtheme/) · [Top 50 Ghostty themes](https://hypercryptoman.github.io/gtheme/ghostty-themes/)
19
+
20
+ ## Install
21
+
22
+ Requires Ghostty on macOS and Python 3.8 or newer.
23
+
24
+ ```sh
25
+ pip install ghosttytheme
26
+ ghosttytheme
27
+ ```
28
+
29
+ If your Python reports an externally managed environment, use a virtual environment or run `pipx install ghosttytheme`. The package also provides the original `gtheme` command.
30
+
31
+ Update with `pip install --upgrade ghosttytheme` or `pipx upgrade ghosttytheme`, depending on how you installed it.
32
+
33
+ ## Use
34
+
35
+ ```sh
36
+ ghosttytheme
37
+ ```
38
+
39
+ Press Tab to cycle through All, Top 50, Dark, and Light. Search with `/` inside any list. You can also open a list directly.
40
+
41
+ ```sh
42
+ ghosttytheme --top
43
+ ghosttytheme --dark
44
+ ghosttytheme --light
45
+ ```
46
+
47
+ Top 50 follows the gallery’s curated order and shows themes available in your installation. Dark and Light classify installed themes by their background color, including custom themes with a defined background.
48
+
49
+ | Key | Action |
50
+ | --- | --- |
51
+ | ↑ / ↓ or `k` / `j` | Move one theme and preview it |
52
+ | Tab / Shift+Tab | Switch to the next or previous list |
53
+ | Page Up / Page Down | Jump up or down by ten themes |
54
+ | `/` | Start a case-insensitive name filter |
55
+ | Backspace | Remove a character while editing the filter |
56
+ | Enter while filtering | Finish typing and keep the filtered results |
57
+ | Esc while filtering | Clear the filter and stay in the current list |
58
+ | Enter while browsing | Save the highlighted theme |
59
+ | `q` or Esc while browsing | Cancel and restore the previous colors |
60
+ | Ctrl+C | Cancel from either mode |
61
+
62
+ Saving writes one `theme` value to your Ghostty config and prints the file it updated. If you use an automatic light/dark pair, saving replaces the pair in that file. The picker checks both the macOS Application Support and XDG config directories, including legacy files named `config`. With no existing config, it uses the macOS Application Support directory. It requests a reload from the Ghostty instance running the terminal when it can verify support for the reload signal.
63
+
64
+ ### Command-line options
65
+
66
+ | Option | Purpose |
67
+ | --- | --- |
68
+ | `-h`, `--help` | Show usage and exit |
69
+ | `--config PATH` | Edit a specific config file, such as a file loaded through a `config-file` directive. |
70
+ | `--themes-dir PATH` | Browse only this directory. The picker saves the selected theme as an absolute path so Ghostty can find it. |
71
+ | `--top`, `--dark`, `--light` | Open the picker in the chosen list |
72
+ | `--no-reload` | Write the config and leave reloading to you. |
73
+
74
+ ### Examples
75
+
76
+ - **Compare Catppuccin variants.** Run `ghosttytheme`, press `/`, type `catppuccin`, and press Enter. Use ↑ and ↓ to compare results. Press Enter again to save the highlighted variant.
77
+ - **Try Dracula and keep your current theme.** Press `/`, type `dracula`, and press Enter to leave the filter. Press `q` to exit with your config untouched.
78
+ - **Use a Ghostty installation in your home folder.** Run `ghosttytheme --themes-dir "$HOME/Applications/Ghostty.app/Contents/Resources/ghostty/themes"`.
79
+ - **Use an alternate Ghostty config.** Run `ghosttytheme --config "$HOME/Library/Application Support/com.mitchellh.ghostty/config"` if that’s the file Ghostty reads.
80
+
81
+ ## Troubleshooting
82
+
83
+ - **`ghosttytheme: command not found`.** If you installed it in a virtual environment, activate that environment first. For a pipx install, run `pipx ensurepath` and open a new Ghostty tab.
84
+ - **No themes found or colors don’t preview.** Run the picker directly in Ghostty on your Mac. A remote shell or terminal multiplexer can block the escape sequences used for previews. The picker looks in the app bundle and in `$XDG_CONFIG_HOME/ghostty/themes` (or `~/.config/ghostty/themes`). If Ghostty is installed elsewhere, pass its theme directory with `--themes-dir`.
85
+ - **The saved theme doesn’t take effect.** Press Cmd+Shift+, or use Ghostty’s Reload Configuration command. Check the config path printed by `ghosttytheme`. An included config file, a launch argument, or explicit color settings can override the chosen theme. Use `--config` to target the file that sets the effective theme. Use `--no-reload` when testing or editing a separate config. [Ghostty configuration guide](https://ghostty.org/docs/config)
86
+ - **A custom theme can’t be selected.** Use a readable Ghostty theme file with color settings such as `background = #1e1e2e`. If the picker reports a filename problem, remove commas, colons, equal signs, and double quotes from its filename or the absolute path used with `--themes-dir`.
87
+
88
+ ## Screenshots
89
+
90
+ The picker displays sample terminal output to show how each theme colors text.
91
+
92
+ **Browsing themes with Catppuccin Mocha highlighted**
93
+
94
+ ![gtheme previewing Catppuccin Mocha with a sample diff, ANSI color swatches, and the theme list](https://raw.githubusercontent.com/hypercryptoman/gtheme/main/assets/gtheme-browsing.png)
95
+
96
+ **Filtering by `nord` with Nord highlighted**
97
+
98
+ ![gtheme previewing Nord with the theme list narrowed to names that match nord](https://raw.githubusercontent.com/hypercryptoman/gtheme/main/assets/gtheme-filtering.png)
@@ -0,0 +1,6 @@
1
+ ghosttytheme.py,sha256=bM2LukGZa43nRASqcKEX0Zje7nHtvuUBCFN264U1AfE,25227
2
+ ghosttytheme-0.2.0.dist-info/METADATA,sha256=-_rlI5evPtaQVlp5PRmYlRwVwJAX93Uz7J_lIEwFyXQ,5900
3
+ ghosttytheme-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ ghosttytheme-0.2.0.dist-info/entry_points.txt,sha256=RPiD1sOJ6JdrXMIa2iHqyA02Fe-z00GbeU0tSf0Uw8M,78
5
+ ghosttytheme-0.2.0.dist-info/top_level.txt,sha256=9zIF_XRQ8qz3BMqlu5K87zs_4_VeZ9S7hECrKYvFXWg,13
6
+ ghosttytheme-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ ghosttytheme = ghosttytheme:main
3
+ gtheme = ghosttytheme:main
@@ -0,0 +1 @@
1
+ ghosttytheme
ghosttytheme.py ADDED
@@ -0,0 +1,558 @@
1
+ #!/usr/bin/env python3
2
+ """Preview and save Ghostty themes from an interactive macOS terminal."""
3
+
4
+ import argparse
5
+ import contextlib
6
+ import fcntl
7
+ import os
8
+ import plistlib
9
+ import re
10
+ import select
11
+ import signal
12
+ import stat
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ import termios
17
+ import tty
18
+ import unicodedata
19
+ from pathlib import Path
20
+
21
+ APPLICATIONS = Path("/Applications/Ghostty.app")
22
+ THEME_SETTING = re.compile(r"^[ \t]*theme[ \t]*=[ \t]*([^\r\n]*)", re.MULTILINE)
23
+ COLORS = {"foreground": 10, "background": 11, "cursor-color": 12,
24
+ "selection-background": 17, "selection-foreground": 19}
25
+ ANSI = re.compile(r"\033\[[0-9;]*m|.", re.DOTALL)
26
+ CSI = "\033["
27
+ OSC_END = "\033\\"
28
+ COLLECTIONS = {"all": "All", "top": "Top 50", "dark": "Dark", "light": "Light"}
29
+ # Match the published gallery order. Each name is a Ghostty theme filename.
30
+ TOP_THEMES = (
31
+ 'Catppuccin Mocha', 'TokyoNight Storm', 'Dracula', 'Nord', 'Gruvbox Dark', 'Rose Pine',
32
+ 'Kanagawa Wave', 'Everforest Dark Hard', 'Nightfox', 'GitHub Dark Default', 'Ayu Mirage',
33
+ 'One Half Dark', 'Catppuccin Macchiato', 'TokyoNight Night', 'Poimandres',
34
+ 'Solarized Dark Higher Contrast', 'Carbonfox', 'Material Ocean', 'Night Owl',
35
+ 'Flexoki Dark', 'Melange Dark', 'Monokai Pro', 'Selenized Dark', 'Cyberpunk', 'Horizon',
36
+ 'Rose Pine Moon', 'Iceberg Dark', 'Moonfly', 'Zenburn', 'Vercel', 'Catppuccin Latte',
37
+ 'Rose Pine Dawn', 'Gruvbox Light', 'GitHub Light Default', 'TokyoNight Day',
38
+ 'Kanagawa Lotus', 'Ayu Light', 'Nord Light', 'Dayfox', 'Everforest Light Med',
39
+ 'One Half Light', 'Atom One Light', 'Flexoki Light', 'Light Owl', 'Selenized Light',
40
+ 'Iceberg Light', 'iTerm2 Solarized Light', 'Melange Light', 'Alabaster', 'Tomorrow',
41
+ )
42
+ PREFERRED_THEMES = [
43
+ 'Catppuccin Mocha', 'Catppuccin Macchiato', 'Catppuccin Frappe', 'Catppuccin Latte',
44
+ 'TokyoNight', 'TokyoNight Storm', 'TokyoNight Night', 'Dracula', 'Gruvbox Dark',
45
+ 'Gruvbox Dark Hard', 'Nord', 'Rose Pine', 'Rose Pine Moon', 'Rose Pine Dawn',
46
+ 'Kanagawa Wave', 'Kanagawa Dragon', 'Everforest Dark Hard', 'Everforest Light Med',
47
+ 'Solarized Dark Higher Contrast', 'One Half Dark', 'Atom One Dark', 'Nightfox', 'Carbonfox',
48
+ 'Github Dark', 'Monokai Pro', 'Ayu Mirage', 'Zenburn', 'Synthwave', 'Poimandres',
49
+ 'Melange Dark', 'Github Light Default', 'Github Dark Default', 'GitHub Dark Dimmed',
50
+ 'Ayu Light', 'Material Darker', 'Material Ocean', 'Dawnfox', 'Dayfox', 'Duskfox', 'Nordfox',
51
+ 'Terafox', 'Night Owl', 'Light Owl', 'Cobalt2', 'Horizon', 'Sonokai', 'Moonfly',
52
+ 'Iceberg Dark', 'Iceberg Light', 'Tomorrow Night', 'Tomorrow Night Bright',
53
+ 'Tomorrow Night Burns', 'Tomorrow Night Eighties', 'Tomorrow', 'Snazzy',
54
+ 'Monokai Remastered', 'Monokai Soda', 'Monokai Vivid', 'Selenized Dark', 'Selenized Light',
55
+ 'Selenized Black', 'Gruvbox Light', 'Gruvbox Light Hard', 'Gruvbox Material',
56
+ 'Gruvbox Material Dark', 'Gruvbox Material Light', 'Kanagawa Lotus', 'TokyoNight Day',
57
+ 'Nord Light', 'Nord Wave', 'Challenger Deep', 'Cyberpunk', 'Dark Pastel', 'Darkside',
58
+ 'Doom One', 'Doom Peacock', 'Espresso', 'Fahrenheit', 'Flat', 'Flatland', 'Framer',
59
+ 'Fish Tank', 'Galaxy', 'Hardcore', 'Harper', 'Hax0r Blue', 'Hurtado', 'Hybrid',
60
+ 'Jackie Brown', 'Kibble', 'Laser', 'Liquid Carbon', 'Lovelace', 'Man Page', 'Mariana',
61
+ 'Mathias', 'Medallion', 'Mirage', 'Molokai', 'Monokai Pro Machine', 'Monokai Pro Octagon',
62
+ 'Monokai Pro Ristretto', 'Monokai Pro Spectrum', 'Neon', 'Neopolitan', 'Nvim Dark',
63
+ 'Nvim Light', 'Obsidian', 'Ocean', 'Oceanic Next', 'One Half Light', 'Atom One Light',
64
+ 'Onenord', 'Paraiso Dark', 'Pencil Dark', 'Pencil Light', 'Pro', 'Red Alert', 'Red Planet',
65
+ 'Rouge 2', 'Royal', 'Seafoam Pastel', 'Seoulbones Dark', 'Shades Of Purple', 'Slate',
66
+ 'Smyck', 'Spacedust', 'Spiderman', 'Square', 'Sundried', '0x96f', 'Abernathy', 'Agave Dusk',
67
+ 'Apple System Colors', 'Aubade', 'base16-icy', 'Black Metal (Burzum)', 'Blood Moon',
68
+ 'branch', 'Builtin Tango Light', 'Canyon Walnut', 'Cholla', 'CLRS', 'Copper Canyon',
69
+ 'Cutie Pro', 'datum (dark)', 'Desert Morning', 'Django Smooth', 'Earthsong', 'Embark',
70
+ 'Everforest Dark Med', 'Farmhouse Light', 'Forged in Steel', 'GitHub Dark', 'Glacier',
71
+ 'Graveyard Shift', 'Harvest Moon', 'High Desert Snow', 'Hopscotch.256', 'IC Orange PPL',
72
+ 'Isocon Light', 'iTerm2 Tango Light', 'Kanagawabones', 'Karma Light', 'Konsolas',
73
+ 'Liquid Carbon Transparent', 'Matcha Zen', 'Mesa Twilight', 'Modus Operandi Deuteranopia',
74
+ 'Monokai Pro Light', 'N0Tch2K', 'Night Lion V2', 'Noctis Hibernus', 'Novel', 'Onenord Light',
75
+ 'Painted Desert', 'Patina Light', 'Pierre Light', 'Possessed Toaster', 'Pumpkin Patch',
76
+ 'Raycast Dark', 'Rhoads Concord', 'Safety Glass', 'Sea Shells', 'SeedFlip Inkwell',
77
+ 'Sequoia Monochrome Light', 'Shokunin', 'SLOMP', 'Spacegray Bright', 'Stardust Voltage',
78
+ 'Sunset Drive', 'Tango Adapted', 'Thermal Receipt', 'Trapped in Amber', 'Undead', 'Vercel',
79
+ 'Warm Neon', 'Wryan', 'X Paris', 'Zacess Cream',
80
+ ]
81
+
82
+
83
+ def xdg_config():
84
+ configured = os.environ.get("XDG_CONFIG_HOME")
85
+ root = Path(configured) if configured and Path(configured).is_absolute() else Path.home() / ".config"
86
+ return root / "ghostty"
87
+
88
+
89
+ def choose_config(version):
90
+ app_support = Path.home() / "Library/Application Support/com.mitchellh.ghostty"
91
+ locations = [
92
+ app_support / "config.ghostty", app_support / "config",
93
+ xdg_config() / "config.ghostty", xdg_config() / "config",
94
+ ]
95
+ return next(
96
+ (path for path in locations if path.exists() or path.is_symlink()),
97
+ app_support / ("config" if version and version < (1, 2, 3) else "config.ghostty"),
98
+ )
99
+
100
+
101
+ def find_bundled_themes():
102
+ candidates = []
103
+ if os.environ.get("GHOSTTY_RESOURCES_DIR"):
104
+ resources = Path(os.environ["GHOSTTY_RESOURCES_DIR"])
105
+ candidates.extend([resources / "themes", resources / "ghostty/themes"])
106
+ if os.environ.get("GHOSTTY_BIN_DIR"):
107
+ candidates.append(Path(os.environ["GHOSTTY_BIN_DIR"]).parent / "Resources/ghostty/themes")
108
+ for app in (APPLICATIONS, Path.home() / "Applications/Ghostty.app"):
109
+ candidates.append(app / "Contents/Resources/ghostty/themes")
110
+ return next((path for path in candidates if path.is_dir()), candidates[-2])
111
+
112
+
113
+ def fold(text):
114
+ return unicodedata.normalize("NFC", text).casefold()
115
+
116
+
117
+ def theme_paths(bundled, explicit):
118
+ themes = {}
119
+ dirs = [bundled] if explicit else [bundled, xdg_config() / "themes"]
120
+ for directory in dirs:
121
+ if directory.is_dir():
122
+ for path in directory.iterdir():
123
+ if path.is_file() and not path.name.startswith(".") and path.name.isprintable():
124
+ themes[path.name] = path
125
+ if not explicit:
126
+ custom = dirs[-1]
127
+ # Look up the same spelling Ghostty will use on this filesystem.
128
+ for name in themes:
129
+ override = custom / name
130
+ if override.is_file():
131
+ themes[name] = override
132
+ order = {}
133
+ for index, name in enumerate(PREFERRED_THEMES):
134
+ order.setdefault(fold(name), index)
135
+
136
+ def sort_key(item):
137
+ name = item[0]
138
+ folded = fold(name)
139
+ return order.get(folded, len(PREFERRED_THEMES)), folded, name
140
+
141
+ return dict(sorted(themes.items(), key=sort_key))
142
+
143
+
144
+ def read_theme_colors(theme):
145
+ palette = {}
146
+ colors = {}
147
+ with theme.open(encoding="utf-8-sig") as file:
148
+ for line in file:
149
+ if line.lstrip().startswith("#"):
150
+ continue
151
+ key, _, value = line.partition("=")
152
+ key, value = key.strip(), value.strip()
153
+ if key == "palette":
154
+ index, _, value = value.partition("=")
155
+ index = index.strip()
156
+ if not (1 <= len(index) <= 9 and index.isascii() and index.isdecimal()):
157
+ continue
158
+ # Ghostty accepts up to 256 palette entries.
159
+ index = int(index)
160
+ if 0 <= index <= 255 and re.fullmatch(r"#?[0-9a-fA-F]{6}", value.strip()):
161
+ palette[index] = "#" + value.strip().lstrip("#")
162
+ elif key in COLORS and re.fullmatch(r"#?[0-9a-fA-F]{6}", value):
163
+ colors[COLORS[key]] = "#" + value.lstrip("#")
164
+ return palette, colors
165
+
166
+
167
+ def collection_names(themes, collection):
168
+ if collection == "all":
169
+ return list(themes)
170
+ if collection == "top":
171
+ return [name for name in TOP_THEMES if name in themes]
172
+
173
+ names = []
174
+ for name, path in themes.items():
175
+ try:
176
+ _, colors = read_theme_colors(path)
177
+ except (OSError, UnicodeError):
178
+ continue
179
+ background = colors.get(COLORS["background"])
180
+ if background:
181
+ red, green, blue = bytes.fromhex(background[1:])
182
+ # Use the same brightness cutoff as Ghostty's theme list.
183
+ is_dark = (0.2126 * red + 0.7152 * green + 0.0722 * blue) < 127.5
184
+ if is_dark == (collection == "dark"):
185
+ names.append(name)
186
+ return names
187
+
188
+
189
+ def terminal_colors(theme):
190
+ palette, colors = read_theme_colors(theme)
191
+ if not (palette or colors):
192
+ raise ValueError("no supported color settings")
193
+ return "".join(
194
+ f"\033]4;{index};{value}{OSC_END}" for index, value in palette.items()
195
+ ) + "".join(f"\033]{code};{value}{OSC_END}" for code, value in colors.items())
196
+
197
+
198
+ def reset_colors():
199
+ return "".join(f"\033]{code}{OSC_END}" for code in (104, 110, 111, 112, 117, 119))
200
+
201
+
202
+ def config_bytes(path):
203
+ try:
204
+ metadata = path.stat()
205
+ except FileNotFoundError:
206
+ return b"", None
207
+ if not stat.S_ISREG(metadata.st_mode):
208
+ raise OSError("config must be a regular file")
209
+ return path.read_bytes(), metadata
210
+
211
+
212
+ def theme_value(path, explicit):
213
+ value = str(path.absolute()) if explicit else path.name
214
+ if not value.isprintable():
215
+ raise ValueError("theme path contains control characters")
216
+ if value != value.strip() or any(char in value for char in ',:="'):
217
+ raise ValueError("Ghostty cannot use this filename as a single theme; rename or move the theme")
218
+ return value
219
+
220
+
221
+ def save_theme(path, value):
222
+ path = path.resolve()
223
+ path.parent.mkdir(parents=True, exist_ok=True)
224
+ # Lock the directory so concurrent picker instances read the latest config
225
+ # before replacing it, including when invoked through a config symlink.
226
+ directory = os.open(path.parent, os.O_RDONLY)
227
+ try:
228
+ fcntl.flock(directory, fcntl.LOCK_EX)
229
+ original, metadata = config_bytes(path)
230
+ if metadata and not os.access(path, os.W_OK):
231
+ raise PermissionError("config is read-only")
232
+ encoding = "utf-8-sig" if original.startswith(b"\xef\xbb\xbf") else "utf-8"
233
+ config = original.decode(encoding)
234
+ setting = "theme = " + value
235
+ matches = list(THEME_SETTING.finditer(config))
236
+ if matches:
237
+ # Ghostty uses the last setting; preserve earlier lines and their formatting.
238
+ last = matches[-1]
239
+ config = config[:last.start()] + setting + config[last.end():]
240
+ else:
241
+ newline = "\r\n" if "\r\n" in config else "\n"
242
+ config += (newline if config and not config.endswith("\n") else "") + setting + newline
243
+
244
+ temporary = None
245
+ try:
246
+ with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as output:
247
+ temporary = Path(output.name)
248
+ output.write(config.encode(encoding))
249
+ if metadata:
250
+ os.fchmod(output.fileno(), stat.S_IMODE(metadata.st_mode))
251
+ if config_bytes(path)[0] != original:
252
+ raise OSError("config changed during save; run gtheme and try again")
253
+ temporary.replace(path)
254
+ finally:
255
+ if temporary is not None:
256
+ temporary.unlink(missing_ok=True)
257
+ finally:
258
+ os.close(directory)
259
+
260
+
261
+ def ghostty_version(executable):
262
+ try:
263
+ with (executable.parent.parent / "Info.plist").open("rb") as file:
264
+ value = plistlib.load(file).get("CFBundleShortVersionString", "")
265
+ match = re.match(r"^(\d+)\.(\d+)\.(\d+)", value)
266
+ return tuple(map(int, match.groups())) if match else None
267
+ except (OSError, ValueError, TypeError, plistlib.InvalidFileException):
268
+ return None
269
+
270
+
271
+ def owning_ghostty():
272
+ """Find the app that owns this terminal without signaling other instances."""
273
+ try:
274
+ # A nested or detached PTY is not the terminal owned by an app ancestor.
275
+ if os.tcgetpgrp(sys.stdin.fileno()) != os.getpgrp():
276
+ return None, None
277
+ except OSError:
278
+ return None, None
279
+ pid = os.getppid()
280
+ while pid > 1:
281
+ try:
282
+ parent, command = subprocess.check_output(
283
+ ["/bin/ps", "-p", str(pid), "-o", "ppid=", "-o", "comm="],
284
+ text=True, stderr=subprocess.DEVNULL,
285
+ ).strip().split(maxsplit=1)
286
+ except (OSError, ValueError, subprocess.SubprocessError):
287
+ break
288
+ executable = Path(command)
289
+ if executable.is_absolute() and executable.parts[-3:] == ("Contents", "MacOS", "ghostty"):
290
+ return pid, ghostty_version(executable)
291
+ pid = int(parent)
292
+ return None, None
293
+
294
+
295
+ def read_key(fd):
296
+ key = os.read(fd, 1)
297
+ if key == b"\x1b":
298
+ if not select.select([fd], [], [], 0.05)[0]:
299
+ return "\x1b"
300
+ key += os.read(fd, 1)
301
+ if key in (b"\x1b[", b"\x1bO"):
302
+ while len(key) < 32 and select.select([fd], [], [], 0.05)[0]:
303
+ part = os.read(fd, 1)
304
+ if not part:
305
+ break
306
+ key += part
307
+ if 0x40 <= part[0] <= 0x7e:
308
+ break
309
+ return key.decode("ascii", errors="ignore")
310
+ if key and 0xC2 <= key[0] <= 0xF4:
311
+ length = 2 if key[0] < 0xE0 else 3 if key[0] < 0xF0 else 4
312
+ for _ in range(length - 1):
313
+ if not select.select([fd], [], [], 0.05)[0]:
314
+ break
315
+ key += os.read(fd, 1)
316
+ return key.decode("utf-8", errors="replace")
317
+
318
+
319
+ def clip(text, columns):
320
+ result = []
321
+ width = 0
322
+ for token in ANSI.findall(text):
323
+ if token.startswith(CSI):
324
+ result.append(token)
325
+ continue
326
+ if not unicodedata.combining(token):
327
+ width += 2 if unicodedata.east_asian_width(token) in ("F", "W") else 1
328
+ if width > columns:
329
+ break
330
+ result.append(token)
331
+ return "".join(result) + CSI + "0m"
332
+
333
+
334
+ def sample_lines():
335
+ def c(code, value):
336
+ return f"{CSI}{code}m{value}{CSI}0m"
337
+
338
+ R, G, Y, B, M, C, DIM = 31, 32, 33, 34, 35, 36, 90
339
+ return [
340
+ c(G,"➜")+" "+c(C,"~/demo")+" "+c(M,"git:(")+c(R,"demo")+c(M,")")+" "+c(Y,"✗")+" git status -sb",
341
+ "## demo...origin/demo [ahead 2]",
342
+ c(G," M")+" src/auth/session.ts "+c(G," M")+" src/routes/login.ts",
343
+ c(R,"??")+" tests/config.spec.ts "+c(R,"??")+" notes.txt",
344
+ "",
345
+ c(G,"➜")+" "+c(C,"~/demo")+" git diff src/auth/session.ts",
346
+ c(B,"@@ -12,7 +12,9 @@")+" export async function verify(token: string) {",
347
+ c(R,"- const user = jwt.decode(token)"),
348
+ c(G,"+ const user = await jwt.verify(token, demoKey, { algorithms: ['HS256'] })"),
349
+ c(G,"+ if (!user) throw new AuthError('invalid token')"),
350
+ " return db.users.find({ id: user.sub })",
351
+ "",
352
+ c(M,"import")+" "+c(Y,"os")+", "+c(Y,"json")+" "+c(DIM,"# python"),
353
+ c(M,"def")+" "+c(B,"load_config")+"("+c(Y,"path")+": "+c(C,"str")+") -> "+c(C,"dict")+":",
354
+ " "+c(M,"with")+" "+c(B,"open")+"(path) "+c(M,"as")+" f: "+c(M,"return")+" json."+c(B,"load")+"(f) "+c(DIM,"# 42, True, None"),
355
+ " "+c(M,"print")+"("+c(G,"f\"loaded {len(cfg)} keys\"")+", "+c(Y,"3.14")+", "+c(Y,"True")+")",
356
+ "",
357
+ c(G,"➜")+" "+c(C,"~/demo")+" npm test",
358
+ c(G," ✓")+" login returns 200 for valid creds "+c(DIM,"(12ms)"),
359
+ c(G," ✓")+" session expires after 30m "+c(DIM,"(4ms)"),
360
+ c(R," ✗")+" rejects forged token "+c(R,"AssertionError: expected 401, got 200"),
361
+ c(Y," ⚠")+" "+c(Y,"warn")+" deprecated: Buffer() is unsafe, use Buffer.from()",
362
+ c(R,"Tests:")+" "+c(R,"1 failed")+", "+c(G,"2 passed")+", 3 total",
363
+ "",
364
+ c(B,"drwxr-xr-x")+" "+c(B,"src/")+" "+c(B,"tests/")+" "+c(G,"deploy.sh")+" "+c(Y,"README.md")+" "+c(C,"link → src/")+" "+c(R,"backup.tar.gz"),
365
+ "CPU "+c(G,"██████")+c(Y,"███")+c(R,"█")+c(DIM,"░░░░░")+" 54% MEM "+c(B,"███████")+c(DIM,"░░░░░░░")+" 3.1G",
366
+ "",
367
+ ]
368
+
369
+
370
+ def draw(rows, cols, collection, view, selected, query, typing, issue):
371
+ count = len(view)
372
+ status = f"{selected + 1 if count else 0}/{count}"
373
+ if query or typing:
374
+ status += f" filter: {query}" + ("_" if typing else "")
375
+ controls = ("Enter done Esc clear" if typing else "Tab lists ↑↓ preview / filter Enter save q cancel")
376
+ heading = f"{CSI}1m gtheme{CSI}0m [{COLLECTIONS[collection]}] {status} {controls}"
377
+ current = view[selected] if view else "No matching themes"
378
+ highlight = f"{CSI}7m > {current} {CSI}0m"
379
+ lines = [heading]
380
+ if rows < 8 or cols < 42:
381
+ lines.append(highlight)
382
+ if issue:
383
+ lines.append(issue)
384
+ else:
385
+ def nearby(offset):
386
+ return view[(selected + offset) % count] if view else ""
387
+
388
+ if count:
389
+ lines.append(f" ‹ {nearby(-1)} {highlight} {nearby(1)} ›")
390
+ else:
391
+ lines.append("No matching themes. Press Tab to switch lists.")
392
+ lines.append("".join(f"{CSI}3{i}m██{CSI}9{i}m██{CSI}0m " for i in range(8)))
393
+ if issue:
394
+ lines.append(issue)
395
+ reserved = min(10, count)
396
+ lines.extend(sample_lines()[:max(0, rows - len(lines) - reserved - 1)])
397
+ if count:
398
+ lines.append(f"── themes ({count}) " + "─" * 46)
399
+ room = max(0, rows - len(lines))
400
+ start = max(0, min(selected - room // 2, count - room))
401
+ for index in range(start, min(count, start + room)):
402
+ lines.append(highlight if index == selected else " " + view[index])
403
+ screen = "\r\n".join(clip(line, max(1, cols - 1)) + CSI + "K" for line in lines[:rows])
404
+ sys.stdout.write(CSI + "H" + CSI + "2J" + screen)
405
+ sys.stdout.flush()
406
+
407
+
408
+ def interrupt(_signum, _frame):
409
+ raise KeyboardInterrupt
410
+
411
+
412
+ def pick(themes, original, explicit=False, collection="all"):
413
+ fd = sys.stdin.fileno()
414
+ old = termios.tcgetattr(fd)
415
+ collections = tuple(COLLECTIONS)
416
+ names = collection_names(themes, collection)
417
+ cached = {collection: names}
418
+ view = names
419
+ selected = next(
420
+ (i for i, name in enumerate(names) if original in (name, str(themes[name].absolute()))),
421
+ 0,
422
+ )
423
+ query = ""
424
+ typing = False
425
+ previewed = None
426
+ issue = ""
427
+
428
+ def filter_names():
429
+ search = fold(query)
430
+ return [name for name in names if search in fold(name)] if search else names
431
+
432
+ handlers = {sig: signal.signal(sig, interrupt) for sig in (signal.SIGTERM, signal.SIGHUP)}
433
+ try:
434
+ tty.setraw(fd)
435
+ sys.stdout.write(CSI + "?1049h" + CSI + "?25l")
436
+ while True:
437
+ current = view[selected] if view else None
438
+ if current != previewed:
439
+ sys.stdout.write(reset_colors())
440
+ issue = ""
441
+ if current:
442
+ try:
443
+ sys.stdout.write(terminal_colors(themes[current]))
444
+ theme_value(themes[current], explicit)
445
+ except (OSError, UnicodeError, ValueError) as error:
446
+ issue = f"Cannot select this theme: {error}"
447
+ previewed = current
448
+
449
+ size = os.get_terminal_size(fd)
450
+ draw(size.lines or 24, size.columns or 80, collection, view, selected, query, typing, issue)
451
+ while not select.select([fd], [], [], 0.15)[0]:
452
+ if os.get_terminal_size(fd) != size:
453
+ break
454
+ else:
455
+ key = read_key(fd)
456
+ if not key or key == "\x03":
457
+ return None
458
+ if key in ("\t", "\x1b[Z"):
459
+ direction = 1 if key == "\t" else -1
460
+ collection = collections[(collections.index(collection) + direction) % len(collections)]
461
+ if collection not in cached:
462
+ cached[collection] = collection_names(themes, collection)
463
+ names = cached[collection]
464
+ view = filter_names()
465
+ selected = view.index(current) if current in view else 0
466
+ elif typing:
467
+ if key in ("\r", "\n"):
468
+ typing = False
469
+ continue
470
+ if key == "\x1b":
471
+ query = ""
472
+ typing = False
473
+ elif key in ("\x7f", "\b"):
474
+ query = query[:-1]
475
+ elif key.isprintable() and len(query) < 256:
476
+ query += key
477
+ else:
478
+ continue
479
+ view = filter_names()
480
+ selected = 0
481
+ elif key in ("\x1b[A", "\x1bOA", "k"):
482
+ selected = (selected - 1) % max(1, len(view))
483
+ elif key in ("\x1b[B", "\x1bOB", "j"):
484
+ selected = (selected + 1) % max(1, len(view))
485
+ elif key == "\x1b[5~":
486
+ selected = max(0, selected - 10)
487
+ elif key == "\x1b[6~":
488
+ selected = min(max(0, len(view) - 1), selected + 10)
489
+ elif key == "/":
490
+ query, view, selected, typing = "", names, 0, True
491
+ elif key in ("\r", "\n") and current and not issue:
492
+ return current
493
+ elif key in ("q", "\x1b"):
494
+ return None
495
+ except KeyboardInterrupt:
496
+ return None
497
+ finally:
498
+ with contextlib.suppress(OSError):
499
+ termios.tcsetattr(fd, termios.TCSANOW, old)
500
+ with contextlib.suppress(OSError):
501
+ sys.stdout.write(CSI + "0m" + reset_colors() + CSI + "?25h" + CSI + "?1049l")
502
+ sys.stdout.flush()
503
+ for sig, handler in handlers.items():
504
+ signal.signal(sig, handler)
505
+
506
+
507
+ def main():
508
+ parser = argparse.ArgumentParser(description="Preview and save Ghostty themes on macOS.")
509
+ parser.add_argument("--config", type=Path, help="Ghostty config to edit")
510
+ parser.add_argument("--themes-dir", type=Path, help="Read themes from this directory")
511
+ parser.add_argument("--no-reload", action="store_true", help="Save without signaling Ghostty")
512
+ lists = parser.add_mutually_exclusive_group()
513
+ lists.add_argument("--top", dest="collection", action="store_const", const="top",
514
+ help="Start in the curated Top 50 list")
515
+ lists.add_argument("--dark", dest="collection", action="store_const", const="dark",
516
+ help="Start with dark themes")
517
+ lists.add_argument("--light", dest="collection", action="store_const", const="light",
518
+ help="Start with light themes")
519
+ parser.set_defaults(collection="all")
520
+ args = parser.parse_args()
521
+ if sys.version_info < (3, 8):
522
+ parser.error("Python 3.8 or newer is required")
523
+ if not (sys.stdin.isatty() and sys.stdout.isatty()) or os.environ.get("TERM") == "dumb":
524
+ parser.error("open gtheme in an interactive Ghostty terminal")
525
+
526
+ pid, version = owning_ghostty()
527
+ directory = args.themes_dir.expanduser() if args.themes_dir else find_bundled_themes()
528
+ config = args.config.expanduser() if args.config else choose_config(version)
529
+ try:
530
+ themes = theme_paths(directory, args.themes_dir is not None)
531
+ if not themes:
532
+ parser.error(f"no themes found in {directory}; check Ghostty or pass --themes-dir")
533
+ settings = THEME_SETTING.findall(config_bytes(config)[0].decode("utf-8-sig"))
534
+ original = settings[-1].strip().strip('"') if settings else None
535
+ chosen = pick(themes, original, args.themes_dir is not None, args.collection)
536
+ if not chosen:
537
+ print("Cancelled. Ghostty config was not changed.")
538
+ return 0
539
+ # Recheck the file in case the app or theme was updated during browsing.
540
+ terminal_colors(themes[chosen])
541
+ save_theme(config, theme_value(themes[chosen], args.themes_dir is not None))
542
+ except (OSError, UnicodeError, ValueError, RuntimeError) as error:
543
+ parser.exit(1, f"gtheme: {error}\n")
544
+
545
+ print(f"Saved {chosen} to {config}.")
546
+ if not args.no_reload:
547
+ if pid and version and version >= (1, 2, 3) and owning_ghostty() == (pid, version):
548
+ try:
549
+ os.kill(pid, signal.SIGUSR2)
550
+ return 0
551
+ except OSError:
552
+ pass
553
+ print("Reload Ghostty with Cmd+Shift+, to apply the theme.")
554
+ return 0
555
+
556
+
557
+ if __name__ == "__main__":
558
+ raise SystemExit(main())