Pi66

pind
Simple Rust hotkey daemon.
git clone https://git.pi66.xyz/pind

← back to log

less code & fix reconnect kboard

author: 6z7y
date: 2025-08-31 00:02
hash: 1772bd62edd27deb1b4b19643094aff5ea3ac5a6

Diffstat:

M

Cargo.lock
2

M

libs/evdev/src/attribute_set.rs
2

M

src/main.rs
156 +++++++++++++-----------------
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
diff --git a/Cargo.lock b/Cargo.lock
index da8e1f4..01bed55 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -68,7 +68,7 @@ dependencies = [

 [[package]]
 name = "pind"
-version = "0.1.4"
+version = "0.1.5"
 dependencies = [
  "evdev",
 ]
diff --git a/libs/evdev/src/attribute_set.rs b/libs/evdev/src/attribute_set.rs
index 32645b0..9c59a38 100644
--- a/libs/evdev/src/attribute_set.rs
+++ b/libs/evdev/src/attribute_set.rs
@@ -53,7 +53,7 @@ impl<T: EvdevEnum> AttributeSetRef<T> {
     }

     #[inline]
-    pub(crate) fn slice_iter(&self, start: T) -> AttributeSetRefIter<T> {
+    pub(crate) fn slice_iter(&self, start: T) -> AttributeSetRefIter<'_, T> {
         let slice = Self::new(&self.bitslice[start.to_index()..]);

         AttributeSetRefIter {
diff --git a/src/main.rs b/src/main.rs
index c04117a..81ac9dc 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -26,36 +26,38 @@


 use evdev::{AttributeSet, Device, KeyCode, enumerate};
-use std::{env::{var,args},fs::read_to_string, path::PathBuf, process::{exit,Command, Stdio}, thread, time::Duration};
+use std::{env::{var,args},fs::read_to_string, path::PathBuf, process::{exit,Command, Stdio}, sync::{Arc, OnceLock}, thread, time::Duration};

 const DELAY  :u64  =  25; // 25ms
 const CONFIG :&str =  "/etc/pind/pindrc";

-fn error(title: &str, message: &str) 
+static BINDINGS: OnceLock<Arc<Vec<(AttributeSet<KeyCode>, String)>>> = OnceLock::new();
+
+fn get_bindings() -> Arc<Vec<(AttributeSet<KeyCode>, String)>>
 {
-    println!("[\x1b[33mE\x1b[0m] \x1b[31m{title}:\x1b[0m {message}.");
+    BINDINGS.get_or_init(|| Arc::new(load_config(CONFIG))).clone()
 }

-fn run(command: &str,  user: &str) 
+fn error(title: &str, message: &str) -> !
 {
-    let shell = var("SHELL").unwrap_or_else(|_| "sh".to_string());
+    eprintln!("[\x1b[33mE\x1b[0m] \x1b[31m{title}:\x1b[0m {message}.");
+    exit(1)
+}
+
+fn run(command: &str, user: &str)
+{
+    let shell = var("SHELL").unwrap_or_else(|_| "sh".into());
+    
     Command::new("runuser")
-        .arg("-u")
-        .arg(user)
-        .arg("--")
-        .arg(&shell)
-        .arg("-c")
-        .arg(command)
-        // .stdin(Stdio::null())
+        .args(["-u", user, "--", &shell, "-c", command])
+        .stdin(Stdio::null())
         .stdout(Stdio::null())
         .stderr(Stdio::null())
-        .spawn().unwrap_or_else(|e| {
-            error("Command error: {}", &e.to_string());
-            exit(1);
-        });
+        .spawn()
+        .unwrap_or_else(|e| error("Command execution failed", &e.to_string()));
 }

-fn key_to_keycode(input: String) -> AttributeSet<KeyCode> 
+fn key_to_keycode(input: &str) -> AttributeSet<KeyCode> 
 {
     let mut attribute_set = AttributeSet::new();

@@ -125,71 +127,39 @@ fn key_to_keycode(input: String) -> AttributeSet<KeyCode>
     attribute_set
 }

-fn is_keyboard(path: &PathBuf) -> bool 
-{
-    let dev = Device::open(path).unwrap();
-    if let Some(keys) = dev.supported_keys() {
-        if keys.contains(KeyCode::KEY_A) && keys.contains(KeyCode::KEY_ENTER) {
-            return true;
-        }
-    }
-    false
-}
-
-fn keyboards() -> Vec<PathBuf> 
+fn keyboards() -> Vec<PathBuf>
 {
-    let mut devices: Vec<PathBuf> = vec![];
-
-    for (path, _) in enumerate() {
-        if is_keyboard(&path) {
-            devices.push(path);
-        }
-    }
-    devices
+    enumerate().filter_map(|(path, dev)| {
+        dev.supported_keys()
+            .filter(|keys| keys.contains(KeyCode::KEY_A) && keys.contains(KeyCode::KEY_ENTER))
+            .map(|_| path)
+    })
+    .collect()
 }

-
-fn load_config(config:&str) -> Vec<(AttributeSet<KeyCode>, String)> 
+fn load_config(config: &str) -> Vec<(AttributeSet<KeyCode>, String)>
 {
-    let mut binding: Vec<(AttributeSet<KeyCode>, String)> = vec![];
-    let content = read_to_string(config).unwrap_or_else(|e| {
-        error("config file", &e.to_string());
-        exit(1)
-    });
-    for line in content.lines() {
-        if !line.starts_with("#") && !line.trim().is_empty() {
-            let mut l = line.splitn(2, ":");
-            let key = l
-                .next()
-                .unwrap_or_else(|| {
-                    error("Binding", "missing key");
-                    exit(1)
-                })
-                .to_string();
-            let cmd = l
-                .next()
-                .unwrap_or_else(|| {
-                    error("Binding", "missing command");
-                    exit(1)
-                })
-                .to_string();
-            binding.push((key_to_keycode(key), cmd));
-        }
-    }
-    binding
+    let content = read_to_string(config)
+        .unwrap_or_else(|e| error("Config file read failed", &e.to_string()));
+    
+    content.lines()
+        .filter(|line| !line.starts_with('#') && !line.trim().is_empty())
+        .filter_map(|line| {
+            let mut parts = line.splitn(2, ':');
+            let key = parts.next()?.trim();
+            let cmd = parts.next()?.trim();
+            Some((key_to_keycode(key), cmd.to_string()))
+        })
+        .collect()
 }

-fn read_keys(kc: &Vec<(AttributeSet<KeyCode>, String)>, kbs: PathBuf,delay:u64,user:String) 
+fn read_keys(bindings: &[(AttributeSet<KeyCode>, String)], device_path: PathBuf, delay: u64, user: String)
 {
-    let dev = Device::open(kbs).unwrap();
-    let mut pressed = AttributeSet::new();
-
-    while let Ok(event) = dev.get_key_state() {
-        if event != pressed {
-            pressed = event.clone();
-            for (key, cmd) in kc {
-                if event == *key {
-                    run(&cmd, &user);
+    loop {
+        if let Ok(dev) = Device::open(&device_path).and_then(|d| d.get_key_state()) {
+            for (key, cmd) in bindings {
+                if dev == *key {
+                    run(cmd, &user);
                 }
             }
         }
@@ -199,24 +169,32 @@ fn read_keys(kc: &Vec<(AttributeSet<KeyCode>, String)>, kbs: PathBuf,delay:u64,u

 fn main()
 {
-    let user = args().nth(1).unwrap_or_else(||{error("USER", "add your username in $USER");exit(1)});
-
-    let binding = load_config(CONFIG);
-    if binding.is_empty() {
-        error("Binding", "no binding detected");
+    let user = args().nth(1).unwrap_or_else(|| error("USER", "Username argument required"));
+    
+    let bindings = get_bindings();
+    if bindings.is_empty() {
+        error("binding", "No key bindings detected");
     }
+    
     let keyboards = keyboards();
     if keyboards.is_empty() {
-        error("Keyboard", "no keyboard detected");
+        error("Hardware", "No keyboards detected");
     }

-    for keyboard in keyboards {
-        let bind  = binding.clone();
-        let user_ = user.clone(); 
-        let _ = std::thread::spawn(move || {
-            read_keys(&bind, keyboard, DELAY, user_);
-        });
+    // Use a single Arc and share references
+    let handles: Vec<_> = keyboards.into_iter()
+        .map(|keyboard| {
+            let bindings_ref = Arc::clone(&bindings);
+            let user_ref = user.clone();
+            
+            thread::spawn(move || {
+                let bindings_slice: &[(AttributeSet<KeyCode>, String)] = &bindings_ref;
+                read_keys(bindings_slice, keyboard, DELAY, user_ref);
+            })
+        })
+        .collect();
+    
+    for handle in handles {
+        handle.join().unwrap_or_else(|_| error("Thread", "Keyboard thread panicked"));
     }
-
-    std::thread::park();
 }