1use std::io::Write;
26use std::sync::OnceLock;
27use std::time::{SystemTime, UNIX_EPOCH};
28
29use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
30
31fn target() -> Option<&'static std::path::PathBuf> {
33 static TARGET: OnceLock<Option<std::path::PathBuf>> = OnceLock::new();
34 TARGET
35 .get_or_init(|| {
36 let value = std::env::var("RPI_DEBUG_KEYS").ok()?;
37 let value = value.trim();
38 if value.is_empty() || value == "0" {
39 return None;
40 }
41 if value == "1" || value.eq_ignore_ascii_case("true") {
42 Some(std::env::temp_dir().join("rpi-keys.log"))
43 } else {
44 Some(std::path::PathBuf::from(value))
45 }
46 })
47 .as_ref()
48}
49
50pub fn enabled() -> bool {
52 target().is_some()
53}
54
55pub fn path() -> Option<&'static std::path::Path> {
57 target().map(std::path::PathBuf::as_path)
58}
59
60pub fn key(event: &KeyEvent, note: &str) {
62 let Some(path) = target() else {
63 return;
64 };
65 let mut line = format!(
66 "{} code={} mods={} kind={:?}",
67 timestamp(),
68 code_name(event.code),
69 modifiers_name(event.modifiers),
70 event.kind
71 );
72 if !note.is_empty() {
73 line.push(' ');
74 line.push_str(note);
75 }
76 line.push('\n');
77 append(path, &line);
78}
79
80pub fn note(text: &str) {
82 let Some(path) = target() else {
83 return;
84 };
85 append(path, &format!("{} {text}\n", timestamp()));
86}
87
88fn append(path: &std::path::Path, line: &str) {
89 if let Ok(mut file) = std::fs::OpenOptions::new()
90 .create(true)
91 .append(true)
92 .open(path)
93 {
94 let _ = file.write_all(line.as_bytes());
95 }
96}
97
98fn timestamp() -> String {
100 let now = SystemTime::now()
101 .duration_since(UNIX_EPOCH)
102 .unwrap_or_default();
103 let millis = now.as_millis();
104 let secs = (millis / 1000) as i64;
105 let sub = millis % 1000;
106 let (year, month, day, hour, min, sec) = civil_from_unix(secs);
107 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}.{sub:03}Z")
108}
109
110fn civil_from_unix(secs: i64) -> (i64, u32, u32, u32, u32, u32) {
113 let days = secs.div_euclid(86_400);
114 let secs_of_day = secs.rem_euclid(86_400);
115 let z = days + 719_468;
116 let era = z.div_euclid(146_097);
117 let doe = z.rem_euclid(146_097);
118 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
119 let y = yoe + era * 400;
120 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
121 let mp = (5 * doy + 2) / 153;
122 let d = doy - (153 * mp + 2) / 5 + 1;
123 let m = if mp < 10 { mp + 3 } else { mp - 9 };
124 let y = if m <= 2 { y + 1 } else { y };
125 (
126 y,
127 m as u32,
128 d as u32,
129 (secs_of_day / 3600) as u32,
130 ((secs_of_day % 3600) / 60) as u32,
131 (secs_of_day % 60) as u32,
132 )
133}
134
135fn code_name(code: KeyCode) -> String {
138 match code {
139 KeyCode::Char(c) if c.is_control() => {
140 format!("Char({c:?}) [U+{:04X}]", c as u32)
141 }
142 KeyCode::Char(c) => format!("Char({c:?})"),
143 other => format!("{other:?}"),
144 }
145}
146
147fn modifiers_name(modifiers: KeyModifiers) -> String {
148 if modifiers.is_empty() {
149 return "NONE".to_string();
150 }
151 let mut parts = Vec::new();
152 for (flag, name) in [
153 (KeyModifiers::CONTROL, "CONTROL"),
154 (KeyModifiers::SHIFT, "SHIFT"),
155 (KeyModifiers::ALT, "ALT"),
156 (KeyModifiers::SUPER, "SUPER"),
157 (KeyModifiers::HYPER, "HYPER"),
158 (KeyModifiers::META, "META"),
159 ] {
160 if modifiers.contains(flag) {
161 parts.push(name);
162 }
163 }
164 parts.join("|")
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170
171 #[test]
172 fn timestamp_matches_the_unix_epoch() {
173 assert_eq!(civil_from_unix(0), (1970, 1, 1, 0, 0, 0));
174 assert_eq!(civil_from_unix(1_700_000_000), (2023, 11, 14, 22, 13, 20));
175 }
176
177 #[test]
178 fn control_characters_and_modifiers_are_spelled_out() {
179 assert_eq!(code_name(KeyCode::Char('j')), "Char('j')");
180 assert_eq!(code_name(KeyCode::Char('\n')), "Char('\\n') [U+000A]");
181 assert_eq!(code_name(KeyCode::Enter), "Enter");
182 assert_eq!(
183 modifiers_name(KeyModifiers::CONTROL | KeyModifiers::SHIFT),
184 "CONTROL|SHIFT"
185 );
186 assert_eq!(modifiers_name(KeyModifiers::NONE), "NONE");
187 }
188}