hyprcorrect_core/runtime.rs
1//! Runtime coordination between the daemon and the prefs subprocess.
2//!
3//! Both write/read a PID file at the platform's runtime location
4//! (`$XDG_RUNTIME_DIR/hyprcorrect.pid` on Linux, `$TMPDIR/...` on
5//! macOS) so the prefs window can target SIGHUP at the daemon
6//! specifically — `pkill -x hyprcorrect` would catch both processes
7//! since they share a binary name.
8
9use std::fs;
10use std::path::PathBuf;
11
12/// An error reading or writing the daemon PID file.
13#[derive(Debug, thiserror::Error)]
14pub enum PidError {
15 #[error("pid file I/O: {0}")]
16 Io(String),
17 #[error("pid file content is not a number: {0}")]
18 Parse(String),
19}
20
21/// Path to the daemon PID file. Falls back to the OS temp dir when
22/// `$XDG_RUNTIME_DIR` is unset (macOS, restricted environments).
23pub fn pid_path() -> PathBuf {
24 runtime_dir().join("hyprcorrect.pid")
25}
26
27/// Path to the trigger-action file. The hyprctl bind writes "word",
28/// "sentence", or "review" here before signaling the daemon; the
29/// daemon reads it on `SIGUSR1` to know which action fired. The
30/// review subprocess also writes "review-apply" / "review-cancel"
31/// here when it closes, so the daemon knows what to do with the
32/// pending request file.
33pub fn action_path() -> PathBuf {
34 runtime_dir().join("hyprcorrect.action")
35}
36
37/// Path to the chord-capture Unix socket. The prefs window connects
38/// here and writes `capture\n` to ask the daemon to deliver the
39/// next non-modifier key press (with full modifier mask, including
40/// Super) as a chord string. The socket exists because egui-winit
41/// on Linux discards Super from `Modifiers`, so the prefs UI cannot
42/// record SUPER-containing chords on its own.
43pub fn chord_socket_path() -> PathBuf {
44 runtime_dir().join("hyprcorrect-chord.sock")
45}
46
47/// Path to the review-request file. The daemon writes the original
48/// sentence + the proposed correction + trailing whitespace + the
49/// originating window's address here when the review chord fires;
50/// the review subprocess reads it to populate the popup, then
51/// updates the same path with its decision on exit so the daemon's
52/// apply handler can finish the job.
53pub fn review_path() -> PathBuf {
54 runtime_dir().join("hyprcorrect.review")
55}
56
57/// A pending review request — what the user typed, what the smart
58/// provider suggested, and where to emit the result.
59#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
60pub struct ReviewRequest {
61 /// The sentence as it sits in the focused window's buffer.
62 pub original: String,
63 /// The smart provider's proposed correction.
64 pub corrected: String,
65 /// Whitespace between the sentence's right edge and the caret —
66 /// preserved so the emit lands with the user's spacing intact.
67 pub trailing: String,
68 /// How many characters of `original` sit BEFORE the caret —
69 /// determines the BackSpace count when the apply path emits.
70 #[serde(default)]
71 pub chars_before_caret: usize,
72 /// How many characters of `original` sit AFTER the caret —
73 /// determines the Delete count when the apply path emits.
74 /// Zero for the common case where the caret is at the end of
75 /// (or in trailing whitespace after) the sentence.
76 #[serde(default)]
77 pub chars_after_caret: usize,
78 /// Hyprland address of the window the request originated from —
79 /// the daemon uses it to update that window's buffer when the
80 /// user accepts.
81 pub window_address: String,
82}
83
84/// Write a fresh review request to disk. Overwrites any pending one.
85///
86/// # Errors
87///
88/// I/O errors are surfaced; the daemon logs and skips the spawn if
89/// this fails, so a half-written file doesn't trip up the popup.
90pub fn write_review_request(req: &ReviewRequest) -> Result<(), PidError> {
91 let json = serde_json::to_string(req).map_err(|e| PidError::Io(e.to_string()))?;
92 let path = review_path();
93 if let Some(parent) = path.parent() {
94 fs::create_dir_all(parent).map_err(|e| PidError::Io(e.to_string()))?;
95 }
96 fs::write(&path, json).map_err(|e| PidError::Io(e.to_string()))
97}
98
99/// Read the pending review request, or `None` if no file exists.
100///
101/// # Errors
102///
103/// See [`PidError`].
104pub fn read_review_request() -> Result<Option<ReviewRequest>, PidError> {
105 match fs::read_to_string(review_path()) {
106 Ok(text) => serde_json::from_str(&text)
107 .map(Some)
108 .map_err(|e| PidError::Parse(e.to_string())),
109 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
110 Err(e) => Err(PidError::Io(e.to_string())),
111 }
112}
113
114/// Remove the review-request file (idempotent).
115pub fn clear_review() {
116 let _ = fs::remove_file(review_path());
117}
118
119/// Read the trigger-action file, returning the trimmed contents. An
120/// empty string is returned if the file is missing or unreadable —
121/// callers treat that as "default action" (fix-last-word).
122pub fn read_action() -> String {
123 std::fs::read_to_string(action_path())
124 .map(|s| s.trim().to_string())
125 .unwrap_or_default()
126}
127
128fn runtime_dir() -> PathBuf {
129 std::env::var_os("XDG_RUNTIME_DIR")
130 .map(PathBuf::from)
131 .unwrap_or_else(std::env::temp_dir)
132}
133
134/// Write the current process's PID to the daemon PID file.
135///
136/// # Errors
137///
138/// Returns [`PidError::Io`] if the file can't be written.
139pub fn write_self_pid() -> Result<(), PidError> {
140 let path = pid_path();
141 if let Some(parent) = path.parent() {
142 fs::create_dir_all(parent).map_err(|e| PidError::Io(e.to_string()))?;
143 }
144 fs::write(&path, std::process::id().to_string()).map_err(|e| PidError::Io(e.to_string()))
145}
146
147/// Remove the daemon PID file (idempotent — missing file is OK). The
148/// action file is removed alongside it since the two have the same
149/// lifecycle: both are owned by the running daemon.
150pub fn clear_pid() {
151 let _ = fs::remove_file(pid_path());
152 let _ = fs::remove_file(action_path());
153}
154
155/// Read the daemon's PID from the file. Returns `Ok(None)` if no file
156/// exists (no daemon running).
157///
158/// # Errors
159///
160/// See [`PidError`].
161pub fn read_daemon_pid() -> Result<Option<i32>, PidError> {
162 match fs::read_to_string(pid_path()) {
163 Ok(text) => text
164 .trim()
165 .parse::<i32>()
166 .map(Some)
167 .map_err(|e| PidError::Parse(e.to_string())),
168 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
169 Err(e) => Err(PidError::Io(e.to_string())),
170 }
171}