Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,30 @@ Notable changes are recorded here. The format follows
bundle declares that it sends Apple events, so macOS asks once to let IdleWalker control
Terminal instead of refusing silently. When the permission is refused, the window now says
where to allow it.
- The terminal prompt's icons and colours now come out right in every terminal profile, not
only the default one, following the Oh My Posh documentation for each terminal:
- Windows Terminal: the font goes into every profile that had a font of its own (those
overrode the default), the older `fontFace` key is replaced, and the colour adjustment
that breaks Powerline separators is turned off.
- VS Code: the contrast rule that recolours the prompt's segments is turned off along
with setting the font.
- Console windows: every program or window title with its own font under `HKCU\Console`
is set, not only the default; those kept Consolas before.
- macOS Terminal, GNOME Terminal and Konsole: every profile, not only the default.
- macOS Terminal and iTerm2 now get the font's real PostScript name, `MesloLGMNFM-Regular`:
Nerd Fonts have shortened it since version 3, and Terminal answers "done" to a name it
does not know while keeping its old font. The name macOS itself resolves the font to
is used first, the profiles are read back afterwards, the font's other names are tried
in turn, and the window says which profiles still have another font if none took,
instead of reporting the font as set. The window could not read Terminal's answer
before, since `tab` inside a `tell application "Terminal"` is its window-tab class.
The status line asks the running Terminal too, instead of its settings file, which
Terminal writes only when it quits.
- iTerm2: the font for non-ASCII text as well, where a profile has one.
- Bash: a `.bash_profile` that hid `.bashrc` is made to load it on Windows (Git Bash) and
Linux too, not only on macOS.
- Nushell: the window says when Nushell is too old (0.104 is needed), and "Remove" and
"Uninstall" delete the script `oh-my-posh init nu` leaves in Nushell's autoload folder.

### Added

Expand All @@ -46,6 +70,20 @@ Notable changes are recorded here. The format follows
out of every shell again or uninstall Oh My Posh
altogether, through the package manager that installed it. On Windows it also lets
PowerShell load its profile when the execution policy forbids it.
- The terminal prompt window also knows Tilix, Xfce Terminal, kitty, Alacritty and Tabby,
Windows Terminal Canary and Code - OSS, and reports WezTerm and Ghostty as needing nothing, since
they carry the icons themselves. It then grew to cover the rest of the popular terminals:
on Windows ConEmu and Cmder (every configuration, in `ConEmu.xml` or the registry), PuTTY
(every saved session), and mintty as Git Bash, MSYS2, Cygwin and wsltty ship it; on Linux
MATE Terminal (every profile), Ptyxis, GNOME Console, Guake, elementary Terminal, Terminator
(every profile), LXTerminal, QTerminal, Deepin Terminal, Sakura, foot, PuTTY, and xterm and
urxvt through `~/.Xresources`; and everywhere Hyper, Rio, Warp, Wave and the Zed editor's
terminal. Every terminal setting it changes is recorded with the
value that was there, in `terminal-undo.txt` in IdleWalker's folder; "Put the terminals
back" restores them all, and "Uninstall" restores them and removes the font files the
window installed, leaving a font that was already there alone. After each font task it
writes `terminal-debug.txt` beside it: every program it ran and what that printed, for
working out why a terminal did not take the font.

### Changed

Expand Down
13 changes: 10 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,16 @@ cargo build --release
- 💻 **Terminal prompt.** A window that sets up [Oh My Posh](https://ohmyposh.dev) for you:
installs or updates it, fetches its themes, puts the one you pick into every shell you have
(PowerShell, Windows PowerShell, bash, zsh, fish, Command Prompt through Clink, nu), installs
the Nerd Font its icons need, and points your terminals at that font: VS Code, Windows
Terminal and console windows, macOS Terminal and iTerm2, GNOME Terminal and Konsole. One click
takes the prompt out of every shell again, and another uninstalls Oh My Posh altogether.
the Nerd Font its icons need, and points your terminals at that font, every profile of
each: VS Code and its cousins, Zed, Windows Terminal, console windows, ConEmu and Cmder,
PuTTY, Git Bash, MSYS2, Cygwin and wsltty, macOS Terminal and iTerm2, GNOME Terminal and
Console, Ptyxis, Tilix, MATE Terminal, Konsole, Xfce Terminal, Terminator, Guake,
elementary Terminal, LXTerminal, QTerminal, Deepin Terminal, Sakura, foot, xterm and
urxvt, and the cross-platform kitty, Alacritty, Tabby, Hyper, Rio, Warp and Wave. It also
turns off the colour rules in VS Code and Windows Terminal that recolour the prompt.
Everything it changes is written down first, so one click puts the terminals back as they
were, another takes the prompt out of every shell, and "Uninstall" does both and removes
Oh My Posh and the font it installed.
- ☕ **Anti-idle nudge.** Keeps your machine awake when you want it to.
- 🔄 **Update check.** It tells you when there's a new release, but never installs anything on
its own.
Expand Down
238 changes: 215 additions & 23 deletions crates/application/src/jsonc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Small edits to JSON-with-comments settings files (VS Code's and Windows Terminal's)
//! that leave everything else as it was: comments, trailing commas and the person's own
//! layout. Only what is needed: reading one string at a key path, and setting one.
//! layout. Only what is needed: reading, setting and removing one value at a key path,
//! either from the top of the file or from an object inside an array (Windows Terminal's
//! profile list). A value is handled as its raw JSON text, so a number or `true` is as
//! easy to put back as a string.

struct Member {
key: String,
Expand Down Expand Up @@ -191,48 +194,134 @@ fn quote(s: &str) -> String {
out
}

/// `{ "a": { "b": "value" } }` for a path, or just the quoted value for an empty one.
/// `{ "a": { "b": value } }` for a path, or just the raw value for an empty one.
fn nested(path: &[&str], value: &str) -> String {
match path.split_first() {
None => quote(value),
None => value.to_string(),
Some((k, rest)) => format!("{{ {}: {} }}", quote(k), nested(rest, value)),
}
}

/// A JSON string literal's text for a value.
pub fn quoted(value: &str) -> String {
quote(value)
}

/// The value a JSON string literal holds, if the raw text is one.
pub fn unquoted(raw: &str) -> Option<String> {
let sc = Scanner { b: raw.as_bytes() };
let end = sc.string_end(0)?;
(raw.as_bytes().first() == Some(&b'"') && end == raw.len()).then(|| sc.unquote(0, end))
}

/// The `{` of the object at the top of the file, or `None` when the file holds nothing.
fn root(text: &str) -> Option<usize> {
let sc = Scanner { b: text.as_bytes() };
let open = sc.skip_blank(0);
(open < text.len()).then_some(open)
}

/// The raw text of the value at a key path, whatever its kind.
pub fn get_raw(text: &str, path: &[&str]) -> Option<String> {
get_raw_at(text, root(text)?, path)
}

/// The string at a key path, when it is there and is a string.
pub fn get_string(text: &str, path: &[&str]) -> Option<String> {
get_raw(text, path).and_then(|raw| unquoted(&raw))
}

/// As `get_raw`, from the object whose `{` is at `open`.
pub fn get_raw_at(text: &str, open: usize, path: &[&str]) -> Option<String> {
let sc = Scanner { b: text.as_bytes() };
let mut open = sc.skip_blank(0);
let mut open = open;
let mut path = path;
loop {
let (key, rest) = path.split_first()?;
let members = sc.members(open)?;
let m = members.into_iter().find(|m| m.key == *key)?;
if rest.is_empty() {
return (text.as_bytes()[m.value_start] == b'"')
.then(|| sc.unquote(m.value_start, m.value_end));
return Some(text[m.value_start..m.value_end].to_string());
}
open = m.value_start;
path = rest;
}
}

/// As `get_string`, from the object whose `{` is at `open`.
pub fn get_string_at(text: &str, open: usize, path: &[&str]) -> Option<String> {
get_raw_at(text, open, path).and_then(|raw| unquoted(&raw))
}

/// The `{` of every object in the array at a key path; nothing when there is no array.
pub fn objects_in(text: &str, path: &[&str]) -> Vec<usize> {
let Some(open) = root(text) else {
return Vec::new();
};
let sc = Scanner { b: text.as_bytes() };
let mut open = open;
let mut path = path;
loop {
let Some((key, rest)) = path.split_first() else {
break;
};
let Some(members) = sc.members(open) else {
return Vec::new();
};
let Some(m) = members.into_iter().find(|m| m.key == *key) else {
return Vec::new();
};
open = m.value_start;
path = rest;
}
let b = text.as_bytes();
if b.get(open) != Some(&b'[') {
return Vec::new();
}
let mut out = Vec::new();
let mut i = sc.skip_blank(open + 1);
loop {
match b.get(i) {
Some(b']') | None => return out,
Some(b'{') => out.push(i),
_ => {}
}
let Some(end) = sc.value_end(i) else {
return out;
};
i = sc.skip_blank(end);
if b.get(i) == Some(&b',') {
i = sc.skip_blank(i + 1);
}
}
}

/// The text with the string at a key path set, the objects on the way made as needed.
/// An empty file becomes an object; a file that is not an object is left alone.
pub fn set_string(text: &str, path: &[&str], value: &str) -> Result<String, String> {
set_raw(text, path, &quote(value))
}

/// The text with the value at a key path set to the raw JSON `value` (a string must
/// come quoted, see `quoted`), the objects on the way made as needed.
pub fn set_raw(text: &str, path: &[&str], value: &str) -> Result<String, String> {
if path.is_empty() {
return Err("no key".into());
}
let sc = Scanner { b: text.as_bytes() };
let open = sc.skip_blank(0);
if open >= text.len() {
let member = format!("{}: {}", quote(path[0]), nested(&path[1..], value));
return Ok(format!("{text}{{\n {member}\n}}\n"));
match root(text) {
None => {
let member = format!("{}: {}", quote(path[0]), nested(&path[1..], value));
Ok(format!("{text}{{\n {member}\n}}\n"))
}
Some(open) => set_raw_at(text, open, path, value),
}
set_in(text, open, path, value)
}

fn set_in(text: &str, open: usize, path: &[&str], value: &str) -> Result<String, String> {
/// As `set_raw`, in the object whose `{` is at `open`.
pub fn set_raw_at(text: &str, open: usize, path: &[&str], value: &str) -> Result<String, String> {
if path.is_empty() {
return Err("no key".into());
}
let sc = Scanner { b: text.as_bytes() };
let members = sc
.members(open)
Expand All @@ -243,35 +332,97 @@ fn set_in(text: &str, open: usize, path: &[&str], value: &str) -> Result<String,
};
if let Some(m) = members.iter().find(|m| m.key == key) {
if rest.is_empty() {
return Ok(splice(m.value_start, m.value_end, &quote(value)));
return Ok(splice(m.value_start, m.value_end, value));
}
if text.as_bytes()[m.value_start] == b'{' {
return set_in(text, m.value_start, rest, value);
return set_raw_at(text, m.value_start, rest, value);
}
return Ok(splice(m.value_start, m.value_end, &nested(rest, value)));
}
let member = format!("{}: {}", quote(key), nested(rest, value));
// New lines end the way the file's do, so taking the member out again leaves the
// file as it was.
let nl = if text.contains("\r\n") { "\r\n" } else { "\n" };
match members.first() {
Some(first) => {
// In front of the others, on a line of its own with their indentation.
let indent = sc
.indent_before(first.key_start)
.unwrap_or_else(|| " ".into());
Ok(splice(open + 1, open + 1, &format!("\n{indent}{member},")))
}
// In front of the others: on a line of its own with their indentation, or on
// their line when they share one with the brace.
Some(first) => Ok(match sc.indent_before(first.key_start) {
Some(indent) => splice(open + 1, open + 1, &format!("{nl}{indent}{member},")),
None => splice(first.key_start, first.key_start, &format!("{member}, ")),
}),
None => {
let close = sc.skip_blank(open + 1);
let outer = sc.line_indent(open);
let inner = format!("{outer} ");
Ok(splice(
open + 1,
close,
&format!("\n{inner}{member}\n{outer}"),
&format!("{nl}{inner}{member}{nl}{outer}"),
))
}
}
}

/// The text without the member at a key path; unchanged when there is none.
pub fn remove(text: &str, path: &[&str]) -> Result<String, String> {
match root(text) {
None => Ok(text.to_string()),
Some(open) => remove_at(text, open, path),
}
}

/// As `remove`, in the object whose `{` is at `open`.
pub fn remove_at(text: &str, open: usize, path: &[&str]) -> Result<String, String> {
let sc = Scanner { b: text.as_bytes() };
let members = sc
.members(open)
.ok_or_else(|| "the file is not a JSON object".to_string())?;
let (key, rest) = path.split_first().ok_or_else(|| "no key".to_string())?;
let Some(at) = members.iter().position(|m| m.key == *key) else {
return Ok(text.to_string());
};
let m = &members[at];
if !rest.is_empty() {
return if text.as_bytes()[m.value_start] == b'{' {
remove_at(text, m.value_start, rest)
} else {
Ok(text.to_string())
};
}
// The member with the comma after it, or the comma before it when it is the last;
// and the line it was alone on.
let b = text.as_bytes();
let mut start = m.key_start;
let mut end = m.value_end;
let after = sc.skip_blank(end);
if b.get(after) == Some(&b',') {
end = after + 1;
while matches!(b.get(end), Some(b' ' | b'\t')) {
end += 1;
}
} else if at > 0 {
let prev = members[at - 1].value_end;
let comma = sc.skip_blank(prev);
if b.get(comma) == Some(&b',') {
start = comma;
}
}
if let Some(lead) = sc.indent_before(start) {
let line_start = start - lead.len();
let rest_of_line = &text[end..];
let to_eol = rest_of_line
.find('\n')
.filter(|n| rest_of_line[..*n].trim().is_empty());
if let Some(n) = to_eol {
if line_start > 0 || end + n + 1 < text.len() {
start = line_start;
end += n + 1;
}
}
}
Ok(format!("{}{}", &text[..start], &text[end..]))
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -369,6 +520,47 @@ mod tests {
assert_eq!(get_string(&wrong, &path).as_deref(), Some("F"));
}

#[test]
fn raw_values_arrays_and_removal_work_on_windows_terminal_s_shape() {
let wt = "{\n \"profiles\": {\n \"defaults\": { \"fontFace\": \"Cascadia Code\", \"opacity\": 90 },\n \"list\": [\n { \"name\": \"a\", \"font\": { \"face\": \"x\" } },\n \"not an object\",\n { \"name\": \"b\" }\n ]\n }\n}\n";
let opens = objects_in(wt, &["profiles", "list"]);
assert_eq!(opens.len(), 2);
assert_eq!(get_string_at(wt, opens[0], &["name"]).as_deref(), Some("a"));
assert_eq!(get_string_at(wt, opens[1], &["name"]).as_deref(), Some("b"));
assert_eq!(get_raw(wt, &["profiles", "defaults", "opacity"]).as_deref(), Some("90"));
assert_eq!(unquoted("\"a \\\"b\\\"\"").as_deref(), Some("a \"b\""));
assert_eq!(unquoted("90"), None);
assert!(objects_in(wt, &["profiles", "defaults"]).is_empty());
assert!(objects_in("", &["x"]).is_empty());

let set = set_raw_at(wt, opens[1], &["font", "face"], &quoted("F")).unwrap();
assert!(set.contains("{ \"font\": { \"face\": \"F\" }, \"name\": \"b\" }"), "{set}");
let raw = set_raw(wt, &["profiles", "defaults", "opacity"], "50").unwrap();
assert_eq!(get_raw(&raw, &["profiles", "defaults", "opacity"]).as_deref(), Some("50"));

// Removal takes the comma with it, whichever side it is on, and the line when
// the member had one of its own.
let gone = remove(wt, &["profiles", "defaults", "fontFace"]).unwrap();
assert!(gone.contains("\"defaults\": { \"opacity\": 90 }"), "{gone}");
let last = remove(wt, &["profiles", "defaults", "opacity"]).unwrap();
assert!(last.contains("\"defaults\": { \"fontFace\": \"Cascadia Code\" }"), "{last}");
let lines = "{\n \"k\": \"v\",\n \"a\": 1\n}\n";
assert_eq!(remove(lines, &["k"]).unwrap(), "{\n \"a\": 1\n}\n");
assert_eq!(remove(lines, &["a"]).unwrap(), "{\n \"k\": \"v\"\n}\n");
assert_eq!(remove(lines, &["missing"]).unwrap(), lines);
assert_eq!(remove("", &["a"]).unwrap(), "");
let inner = remove_at(wt, opens[0], &["font", "face"]).unwrap();
assert!(inner.contains("{ \"name\": \"a\", \"font\": { } }"), "{inner}");

// A file with Windows line endings keeps them, and comes back as it was.
let crlf = "{\r\n \"a\": 1,\r\n \"o\": {}\r\n}\r\n";
let set = set_raw(crlf, &["k"], "true").unwrap();
assert_eq!(set, "{\r\n \"k\": true,\r\n \"a\": 1,\r\n \"o\": {}\r\n}\r\n");
assert_eq!(remove(&set, &["k"]).unwrap(), crlf);
let deep = set_raw(crlf, &["o", "k"], "1").unwrap();
assert!(deep.contains("\"o\": {\r\n \"k\": 1\r\n }"), "{deep:?}");
}

#[test]
fn a_file_that_is_not_an_object_is_refused() {
assert!(set_string("[1, 2]", &["k"], "v").is_err());
Expand Down
2 changes: 2 additions & 0 deletions crates/application/src/ports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ pub trait Workstation: Send + Sync {
fn os(&self) -> Os;
fn home_dir(&self) -> Option<PathBuf>;
fn temp_dir(&self) -> PathBuf;
/// This program's own folder, for what it must remember between runs.
fn app_dir(&self) -> PathBuf;
fn env(&self, name: &str) -> Option<String>;
/// A program on the PATH, as the shells see it.
fn find_program(&self, name: &str) -> Option<PathBuf>;
Expand Down
Loading
Loading