Skip to content

Commit 6ecee49

Browse files
committed
refactor: refactor lockfile listener to wait on channels instead of polling
1 parent feb2658 commit 6ecee49

1 file changed

Lines changed: 35 additions & 24 deletions

File tree

src-tauri/src/lib.rs

Lines changed: 35 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -174,15 +174,31 @@ pub fn handle_first_run() {
174174
pub fn listen_for_lockfile() {
175175
thread::spawn(|| {
176176
let runtime_path = get_runtime_path();
177-
let watcher = SpecificFileWatcher::new(&runtime_path, "single_instance.lock")
178-
.expect("Failed to create file watcher");
179177
loop {
180-
if watcher.wait_for_file().is_ok() {
181-
remove_file(get_runtime_path().join("single_instance.lock"))
182-
.expect("Failed to remove lock file");
183-
let app = &*get_app_handle().lock().expect("Failed to get app handle");
184-
if let Some(window) = app.webview_windows().get("main") {
185-
window.show().expect("Failed to show main window");
178+
let watcher = match SpecificFileWatcher::new(&runtime_path, "single_instance.lock") {
179+
Ok(w) => w,
180+
Err(e) => {
181+
warn!("Failed to create file watcher: {}. Retrying in 2s...", e);
182+
thread::sleep(Duration::from_secs(2));
183+
continue;
184+
}
185+
};
186+
187+
loop {
188+
match watcher.wait_for_file() {
189+
Ok(()) => {
190+
remove_file(get_runtime_path().join("single_instance.lock"))
191+
.expect("Failed to remove lock file");
192+
let app = &*get_app_handle().lock().expect("Failed to get app handle");
193+
if let Some(window) = app.webview_windows().get("main") {
194+
window.show().expect("Failed to show main window");
195+
}
196+
}
197+
Err(e) => {
198+
warn!("File watcher exited: {}. Relaunching in 1s...", e);
199+
thread::sleep(Duration::from_secs(1));
200+
break;
201+
}
186202
}
187203
}
188204
}
@@ -218,25 +234,20 @@ impl SpecificFileWatcher {
218234
}
219235

220236
pub fn wait_for_file(&self) -> Result<(), Box<dyn std::error::Error>> {
221-
loop {
222-
// Check for events
223-
if let Ok(result) = self.rx.try_recv() {
224-
match result {
225-
Ok(event) => match event.kind {
226-
EventKind::Create(_) | EventKind::Modify(_) => {
227-
if event.paths.iter().any(|p| p == &self.target_file) {
228-
return Ok(());
229-
}
237+
for result in self.rx.iter() {
238+
match result {
239+
Ok(event) => match event.kind {
240+
EventKind::Create(_) | EventKind::Modify(_) => {
241+
if event.paths.iter().any(|p| p == &self.target_file) {
242+
return Ok(());
230243
}
231-
_ => {}
232-
},
233-
Err(e) => warn!("Watch error: {}", e),
234-
}
244+
}
245+
_ => {}
246+
},
247+
Err(e) => warn!("Watch error: {}", e),
235248
}
236-
237-
// Avoid busy waiting
238-
std::thread::sleep(Duration::from_millis(300));
239249
}
250+
Err("Watcher channel closed".into())
240251
}
241252
}
242253

0 commit comments

Comments
 (0)