| 1 |
//! Watcher implementation for Darwin's FSEvents API |
| 2 |
//! |
| 3 |
//! The FSEvents API provides a mechanism to notify clients about directories they ought to re-scan |
| 4 |
//! in order to keep their internal data structures up-to-date with respect to the true state of |
| 5 |
//! the file system. (For example, when files or directories are created, modified, or removed.) It |
| 6 |
//! sends these notifications "in bulk", possibly notifying the client of changes to several |
| 7 |
//! directories in a single callback. |
| 8 |
//! |
| 9 |
//! For more information see the [FSEvents API reference][ref]. |
| 10 |
//! |
| 11 |
//! TODO: document event translation |
| 12 |
//! |
| 13 |
//! [ref]: https://developer.apple.com/library/mac/documentation/Darwin/Reference/FSEvents_Ref/ |
| 14 |
|
| 15 |
#![allow(non_upper_case_globals, dead_code)] |
| 16 |
|
| 17 |
use crate::event::*; |
| 18 |
use crate::{ |
| 19 |
unbounded, Config, Error, EventHandler, PathsMut, RecursiveMode, Result, Sender, Watcher, |
| 20 |
}; |
| 21 |
use fsevent_sys as fs; |
| 22 |
use fsevent_sys::core_foundation as cf; |
| 23 |
use std::collections::HashMap; |
| 24 |
use std::ffi::CStr; |
| 25 |
use std::fmt; |
| 26 |
use std::os::raw; |
| 27 |
use std::path::{Path, PathBuf}; |
| 28 |
use std::ptr; |
| 29 |
use std::sync::{Arc, Mutex}; |
| 30 |
use std::thread; |
| 31 |
|
| 32 |
bitflags::bitflags! { |
| 33 |
#[repr(C)] |
| 34 |
#[derive(Debug)] |
| 35 |
struct StreamFlags: u32 { |
| 36 |
const NONE = fs::kFSEventStreamEventFlagNone; |
| 37 |
const MUST_SCAN_SUBDIRS = fs::kFSEventStreamEventFlagMustScanSubDirs; |
| 38 |
const USER_DROPPED = fs::kFSEventStreamEventFlagUserDropped; |
| 39 |
const KERNEL_DROPPED = fs::kFSEventStreamEventFlagKernelDropped; |
| 40 |
const IDS_WRAPPED = fs::kFSEventStreamEventFlagEventIdsWrapped; |
| 41 |
const HISTORY_DONE = fs::kFSEventStreamEventFlagHistoryDone; |
| 42 |
const ROOT_CHANGED = fs::kFSEventStreamEventFlagRootChanged; |
| 43 |
const MOUNT = fs::kFSEventStreamEventFlagMount; |
| 44 |
const UNMOUNT = fs::kFSEventStreamEventFlagUnmount; |
| 45 |
const ITEM_CREATED = fs::kFSEventStreamEventFlagItemCreated; |
| 46 |
const ITEM_REMOVED = fs::kFSEventStreamEventFlagItemRemoved; |
| 47 |
const INODE_META_MOD = fs::kFSEventStreamEventFlagItemInodeMetaMod; |
| 48 |
const ITEM_RENAMED = fs::kFSEventStreamEventFlagItemRenamed; |
| 49 |
const ITEM_MODIFIED = fs::kFSEventStreamEventFlagItemModified; |
| 50 |
const FINDER_INFO_MOD = fs::kFSEventStreamEventFlagItemFinderInfoMod; |
| 51 |
const ITEM_CHANGE_OWNER = fs::kFSEventStreamEventFlagItemChangeOwner; |
| 52 |
const ITEM_XATTR_MOD = fs::kFSEventStreamEventFlagItemXattrMod; |
| 53 |
const IS_FILE = fs::kFSEventStreamEventFlagItemIsFile; |
| 54 |
const IS_DIR = fs::kFSEventStreamEventFlagItemIsDir; |
| 55 |
const IS_SYMLINK = fs::kFSEventStreamEventFlagItemIsSymlink; |
| 56 |
const OWN_EVENT = fs::kFSEventStreamEventFlagOwnEvent; |
| 57 |
const IS_HARDLINK = fs::kFSEventStreamEventFlagItemIsHardlink; |
| 58 |
const IS_LAST_HARDLINK = fs::kFSEventStreamEventFlagItemIsLastHardlink; |
| 59 |
const ITEM_CLONED = fs::kFSEventStreamEventFlagItemCloned; |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
/// FSEvents-based `Watcher` implementation |
| 64 |
pub struct FsEventWatcher { |
| 65 |
paths: cf::CFMutableArrayRef, |
| 66 |
since_when: fs::FSEventStreamEventId, |
| 67 |
latency: cf::CFTimeInterval, |
| 68 |
flags: fs::FSEventStreamCreateFlags, |
| 69 |
event_handler: Arc<Mutex<dyn EventHandler>>, |
| 70 |
runloop: Option<(cf::CFRunLoopRef, thread::JoinHandle<()>)>, |
| 71 |
recursive_info: HashMap<PathBuf, bool>, |
| 72 |
} |
| 73 |
|
| 74 |
impl fmt::Debug for FsEventWatcher { |
| 75 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 76 |
f.debug_struct("FsEventWatcher") |
| 77 |
.field("paths", &self.paths) |
| 78 |
.field("since_when", &self.since_when) |
| 79 |
.field("latency", &self.latency) |
| 80 |
.field("flags", &self.flags) |
| 81 |
.field("event_handler", &Arc::as_ptr(&self.event_handler)) |
| 82 |
.field("runloop", &self.runloop) |
| 83 |
.field("recursive_info", &self.recursive_info) |
| 84 |
.finish() |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
// CFMutableArrayRef is a type alias to *mut libc::c_void, so FsEventWatcher is not Send/Sync |
| 89 |
// automatically. It's Send because the pointer is not used in other threads. |
| 90 |
unsafe impl Send for FsEventWatcher {} |
| 91 |
|
| 92 |
// It's Sync because all methods that change the mutable state use `&mut self`. |
| 93 |
unsafe impl Sync for FsEventWatcher {} |
| 94 |
|
| 95 |
fn translate_flags(flags: StreamFlags, precise: bool) -> Vec<Event> { |
| 96 |
let mut evs = Vec::new(); |
| 97 |
|
| 98 |
// «Denotes a sentinel event sent to mark the end of the "historical" events |
| 99 |
// sent as a result of specifying a `sinceWhen` value in the FSEvents.Create |
| 100 |
// call that created this event stream. After invoking the client's callback |
| 101 |
// with all the "historical" events that occurred before now, the client's |
| 102 |
// callback will be invoked with an event where the HistoryDone flag is set. |
| 103 |
// The client should ignore the path supplied in this callback.» |
| 104 |
// — https://www.mbsplugins.eu/FSEventsNextEvent.shtml |
| 105 |
// |
| 106 |
// As a result, we just stop processing here and return an empty vec, which |
| 107 |
// will ignore this completely and not emit any Events whatsoever. |
| 108 |
if flags.contains(StreamFlags::HISTORY_DONE) { |
| 109 |
return evs; |
| 110 |
} |
| 111 |
|
| 112 |
// FSEvents provides two possible hints as to why events were dropped, |
| 113 |
// however documentation on what those mean is scant, so we just pass them |
| 114 |
// through in the info attr field. The intent is clear enough, and the |
| 115 |
// additional information is provided if the user wants it. |
| 116 |
if flags.contains(StreamFlags::MUST_SCAN_SUBDIRS) { |
| 117 |
let e = Event::new(EventKind::Other).set_flag(Flag::Rescan); |
| 118 |
evs.push(if flags.contains(StreamFlags::USER_DROPPED) { |
| 119 |
e.set_info("rescan: user dropped") |
| 120 |
} else if flags.contains(StreamFlags::KERNEL_DROPPED) { |
| 121 |
e.set_info("rescan: kernel dropped") |
| 122 |
} else { |
| 123 |
e |
| 124 |
}); |
| 125 |
} |
| 126 |
|
| 127 |
// In imprecise mode, let's not even bother parsing the kind of the event |
| 128 |
// except for the above very special events. |
| 129 |
if !precise { |
| 130 |
evs.push(Event::new(EventKind::Any)); |
| 131 |
return evs; |
| 132 |
} |
| 133 |
|
| 134 |
// This is most likely a rename or a removal. We assume rename but may want |
| 135 |
// to figure out if it was a removal some way later (TODO). To denote the |
| 136 |
// special nature of the event, we add an info string. |
| 137 |
if flags.contains(StreamFlags::ROOT_CHANGED) { |
| 138 |
evs.push( |
| 139 |
Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::From))) |
| 140 |
.set_info("root changed"), |
| 141 |
); |
| 142 |
} |
| 143 |
|
| 144 |
// A path was mounted at the event path; we treat that as a create. |
| 145 |
if flags.contains(StreamFlags::MOUNT) { |
| 146 |
evs.push(Event::new(EventKind::Create(CreateKind::Other)).set_info("mount")); |
| 147 |
} |
| 148 |
|
| 149 |
// A path was unmounted at the event path; we treat that as a remove. |
| 150 |
if flags.contains(StreamFlags::UNMOUNT) { |
| 151 |
evs.push(Event::new(EventKind::Remove(RemoveKind::Other)).set_info("mount")); |
| 152 |
} |
| 153 |
|
| 154 |
if flags.contains(StreamFlags::ITEM_CREATED) { |
| 155 |
evs.push(if flags.contains(StreamFlags::IS_DIR) { |
| 156 |
Event::new(EventKind::Create(CreateKind::Folder)) |
| 157 |
} else if flags.contains(StreamFlags::IS_FILE) { |
| 158 |
Event::new(EventKind::Create(CreateKind::File)) |
| 159 |
} else { |
| 160 |
let e = Event::new(EventKind::Create(CreateKind::Other)); |
| 161 |
if flags.contains(StreamFlags::IS_SYMLINK) { |
| 162 |
e.set_info("is: symlink") |
| 163 |
} else if flags.contains(StreamFlags::IS_HARDLINK) { |
| 164 |
e.set_info("is: hardlink") |
| 165 |
} else if flags.contains(StreamFlags::ITEM_CLONED) { |
| 166 |
e.set_info("is: clone") |
| 167 |
} else { |
| 168 |
Event::new(EventKind::Create(CreateKind::Any)) |
| 169 |
} |
| 170 |
}); |
| 171 |
} |
| 172 |
|
| 173 |
if flags.contains(StreamFlags::ITEM_REMOVED) { |
| 174 |
evs.push(if flags.contains(StreamFlags::IS_DIR) { |
| 175 |
Event::new(EventKind::Remove(RemoveKind::Folder)) |
| 176 |
} else if flags.contains(StreamFlags::IS_FILE) { |
| 177 |
Event::new(EventKind::Remove(RemoveKind::File)) |
| 178 |
} else { |
| 179 |
let e = Event::new(EventKind::Remove(RemoveKind::Other)); |
| 180 |
if flags.contains(StreamFlags::IS_SYMLINK) { |
| 181 |
e.set_info("is: symlink") |
| 182 |
} else if flags.contains(StreamFlags::IS_HARDLINK) { |
| 183 |
e.set_info("is: hardlink") |
| 184 |
} else if flags.contains(StreamFlags::ITEM_CLONED) { |
| 185 |
e.set_info("is: clone") |
| 186 |
} else { |
| 187 |
Event::new(EventKind::Remove(RemoveKind::Any)) |
| 188 |
} |
| 189 |
}); |
| 190 |
} |
| 191 |
|
| 192 |
// FSEvents provides no mechanism to associate the old and new sides of a |
| 193 |
// rename event. |
| 194 |
if flags.contains(StreamFlags::ITEM_RENAMED) { |
| 195 |
evs.push(Event::new(EventKind::Modify(ModifyKind::Name( |
| 196 |
RenameMode::Any, |
| 197 |
)))); |
| 198 |
} |
| 199 |
|
| 200 |
// This is only described as "metadata changed", but it may be that it's |
| 201 |
// only emitted for some more precise subset of events... if so, will need |
| 202 |
// amending, but for now we have an Any-shaped bucket to put it in. |
| 203 |
if flags.contains(StreamFlags::INODE_META_MOD) { |
| 204 |
evs.push(Event::new(EventKind::Modify(ModifyKind::Metadata( |
| 205 |
MetadataKind::Any, |
| 206 |
)))); |
| 207 |
} |
| 208 |
|
| 209 |
if flags.contains(StreamFlags::FINDER_INFO_MOD) { |
| 210 |
evs.push( |
| 211 |
Event::new(EventKind::Modify(ModifyKind::Metadata(MetadataKind::Other))) |
| 212 |
.set_info("meta: finder info"), |
| 213 |
); |
| 214 |
} |
| 215 |
|
| 216 |
if flags.contains(StreamFlags::ITEM_CHANGE_OWNER) { |
| 217 |
evs.push(Event::new(EventKind::Modify(ModifyKind::Metadata( |
| 218 |
MetadataKind::Ownership, |
| 219 |
)))); |
| 220 |
} |
| 221 |
|
| 222 |
if flags.contains(StreamFlags::ITEM_XATTR_MOD) { |
| 223 |
evs.push(Event::new(EventKind::Modify(ModifyKind::Metadata( |
| 224 |
MetadataKind::Extended, |
| 225 |
)))); |
| 226 |
} |
| 227 |
|
| 228 |
// This is specifically described as a data change, which we take to mean |
| 229 |
// is a content change. |
| 230 |
if flags.contains(StreamFlags::ITEM_MODIFIED) { |
| 231 |
evs.push(Event::new(EventKind::Modify(ModifyKind::Data( |
| 232 |
DataChange::Content, |
| 233 |
)))); |
| 234 |
} |
| 235 |
|
| 236 |
if flags.contains(StreamFlags::OWN_EVENT) { |
| 237 |
for ev in &mut evs { |
| 238 |
*ev = std::mem::take(ev).set_process_id(std::process::id()); |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
evs |
| 243 |
} |
| 244 |
|
| 245 |
struct StreamContextInfo { |
| 246 |
event_handler: Arc<Mutex<dyn EventHandler>>, |
| 247 |
recursive_info: HashMap<PathBuf, bool>, |
| 248 |
} |
| 249 |
|
| 250 |
// Free the context when the stream created by `FSEventStreamCreate` is released. |
| 251 |
extern "C" fn release_context(info: *const libc::c_void) { |
| 252 |
// Safety: |
| 253 |
// - The [documentation] for `FSEventStreamContext` states that `release` is only |
| 254 |
// called when the stream is deallocated, so it is safe to convert `info` back into a |
| 255 |
// box and drop it. |
| 256 |
// |
| 257 |
// [docs]: https://developer.apple.com/documentation/coreservices/fseventstreamcontext?language=objc |
| 258 |
unsafe { |
| 259 |
drop(Box::from_raw( |
| 260 |
info as *const StreamContextInfo as *mut StreamContextInfo, |
| 261 |
)); |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
extern "C" { |
| 266 |
/// Indicates whether the run loop is waiting for an event. |
| 267 |
fn CFRunLoopIsWaiting(runloop: cf::CFRunLoopRef) -> cf::Boolean; |
| 268 |
} |
| 269 |
|
| 270 |
struct FsEventPathsMut<'a>(&'a mut FsEventWatcher); |
| 271 |
impl<'a> FsEventPathsMut<'a> { |
| 272 |
fn new(watcher: &'a mut FsEventWatcher) -> Self { |
| 273 |
watcher.stop(); |
| 274 |
Self(watcher) |
| 275 |
} |
| 276 |
} |
| 277 |
impl PathsMut for FsEventPathsMut<'_> { |
| 278 |
fn add(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> { |
| 279 |
self.0.append_path(path, recursive_mode) |
| 280 |
} |
| 281 |
|
| 282 |
fn remove(&mut self, path: &Path) -> Result<()> { |
| 283 |
self.0.remove_path(path) |
| 284 |
} |
| 285 |
|
| 286 |
fn commit(self: Box<Self>) -> Result<()> { |
| 287 |
// ignore return error: may be empty path list |
| 288 |
let _ = self.0.run(); |
| 289 |
Ok(()) |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
impl FsEventWatcher { |
| 294 |
fn from_event_handler(event_handler: Arc<Mutex<dyn EventHandler>>) -> Result<Self> { |
| 295 |
Ok(FsEventWatcher { |
| 296 |
paths: unsafe { |
| 297 |
cf::CFArrayCreateMutable(cf::kCFAllocatorDefault, 0, &cf::kCFTypeArrayCallBacks) |
| 298 |
}, |
| 299 |
since_when: fs::kFSEventStreamEventIdSinceNow, |
| 300 |
latency: 0.0, |
| 301 |
flags: fs::kFSEventStreamCreateFlagFileEvents | fs::kFSEventStreamCreateFlagNoDefer, |
| 302 |
event_handler, |
| 303 |
runloop: None, |
| 304 |
recursive_info: HashMap::new(), |
| 305 |
}) |
| 306 |
} |
| 307 |
|
| 308 |
fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> { |
| 309 |
self.stop(); |
| 310 |
let result = self.append_path(path, recursive_mode); |
| 311 |
// ignore return error: may be empty path list |
| 312 |
let _ = self.run(); |
| 313 |
result |
| 314 |
} |
| 315 |
|
| 316 |
fn unwatch_inner(&mut self, path: &Path) -> Result<()> { |
| 317 |
self.stop(); |
| 318 |
let result = self.remove_path(path); |
| 319 |
// ignore return error: may be empty path list |
| 320 |
let _ = self.run(); |
| 321 |
result |
| 322 |
} |
| 323 |
|
| 324 |
#[inline] |
| 325 |
fn is_running(&self) -> bool { |
| 326 |
self.runloop.is_some() |
| 327 |
} |
| 328 |
|
| 329 |
fn stop(&mut self) { |
| 330 |
if !self.is_running() { |
| 331 |
return; |
| 332 |
} |
| 333 |
|
| 334 |
if let Some((runloop, thread_handle)) = self.runloop.take() { |
| 335 |
unsafe { |
| 336 |
let runloop = runloop as *mut raw::c_void; |
| 337 |
|
| 338 |
while CFRunLoopIsWaiting(runloop) == 0 { |
| 339 |
thread::yield_now(); |
| 340 |
} |
| 341 |
|
| 342 |
cf::CFRunLoopStop(runloop); |
| 343 |
} |
| 344 |
|
| 345 |
// Wait for the thread to shut down. |
| 346 |
thread_handle.join().expect("thread to shut down"); |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
fn remove_path(&mut self, path: &Path) -> Result<()> { |
| 351 |
let str_path = path.to_str().unwrap(); |
| 352 |
unsafe { |
| 353 |
let mut err: cf::CFErrorRef = ptr::null_mut(); |
| 354 |
let cf_path = cf::str_path_to_cfstring_ref(str_path, &mut err); |
| 355 |
if cf_path.is_null() { |
| 356 |
cf::CFRelease(err as cf::CFRef); |
| 357 |
return Err(Error::watch_not_found().add_path(path.into())); |
| 358 |
} |
| 359 |
|
| 360 |
let mut to_remove = Vec::new(); |
| 361 |
for idx in 0..cf::CFArrayGetCount(self.paths) { |
| 362 |
let item = cf::CFArrayGetValueAtIndex(self.paths, idx); |
| 363 |
if cf::CFStringCompare(item, cf_path, cf::kCFCompareCaseInsensitive) |
| 364 |
== cf::kCFCompareEqualTo |
| 365 |
{ |
| 366 |
to_remove.push(idx); |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
cf::CFRelease(cf_path); |
| 371 |
|
| 372 |
for idx in to_remove.iter().rev() { |
| 373 |
cf::CFArrayRemoveValueAtIndex(self.paths, *idx); |
| 374 |
} |
| 375 |
} |
| 376 |
let p = if let Ok(canonicalized_path) = path.canonicalize() { |
| 377 |
canonicalized_path |
| 378 |
} else { |
| 379 |
path.to_owned() |
| 380 |
}; |
| 381 |
match self.recursive_info.remove(&p) { |
| 382 |
Some(_) => Ok(()), |
| 383 |
None => Err(Error::watch_not_found()), |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
// https://github.com/thibaudgg/rb-fsevent/blob/master/ext/fsevent_watch/main.c |
| 388 |
fn append_path(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> { |
| 389 |
if !path.exists() { |
| 390 |
return Err(Error::path_not_found().add_path(path.into())); |
| 391 |
} |
| 392 |
let canonical_path = path.to_path_buf().canonicalize()?; |
| 393 |
let str_path = path.to_str().unwrap(); |
| 394 |
unsafe { |
| 395 |
let mut err: cf::CFErrorRef = ptr::null_mut(); |
| 396 |
let cf_path = cf::str_path_to_cfstring_ref(str_path, &mut err); |
| 397 |
if cf_path.is_null() { |
| 398 |
// Most likely the directory was deleted, or permissions changed, |
| 399 |
// while the above code was running. |
| 400 |
cf::CFRelease(err as cf::CFRef); |
| 401 |
return Err(Error::path_not_found().add_path(path.into())); |
| 402 |
} |
| 403 |
cf::CFArrayAppendValue(self.paths, cf_path); |
| 404 |
cf::CFRelease(cf_path); |
| 405 |
} |
| 406 |
self.recursive_info |
| 407 |
.insert(canonical_path, recursive_mode.is_recursive()); |
| 408 |
Ok(()) |
| 409 |
} |
| 410 |
|
| 411 |
fn run(&mut self) -> Result<()> { |
| 412 |
if unsafe { cf::CFArrayGetCount(self.paths) } == 0 { |
| 413 |
// TODO: Reconstruct and add paths to error |
| 414 |
return Err(Error::path_not_found()); |
| 415 |
} |
| 416 |
|
| 417 |
// We need to associate the stream context with our callback in order to propagate events |
| 418 |
// to the rest of the system. This will be owned by the stream, and will be freed when the |
| 419 |
// stream is closed. This means we will leak the context if we panic before reaching |
| 420 |
// `FSEventStreamRelease`. |
| 421 |
let context = Box::into_raw(Box::new(StreamContextInfo { |
| 422 |
event_handler: self.event_handler.clone(), |
| 423 |
recursive_info: self.recursive_info.clone(), |
| 424 |
})); |
| 425 |
|
| 426 |
let stream_context = fs::FSEventStreamContext { |
| 427 |
version: 0, |
| 428 |
info: context as *mut libc::c_void, |
| 429 |
retain: None, |
| 430 |
release: Some(release_context), |
| 431 |
copy_description: None, |
| 432 |
}; |
| 433 |
|
| 434 |
let stream = unsafe { |
| 435 |
fs::FSEventStreamCreate( |
| 436 |
cf::kCFAllocatorDefault, |
| 437 |
callback, |
| 438 |
&stream_context, |
| 439 |
self.paths, |
| 440 |
self.since_when, |
| 441 |
self.latency, |
| 442 |
self.flags, |
| 443 |
) |
| 444 |
}; |
| 445 |
|
| 446 |
// Wrapper to help send CFRef types across threads. |
| 447 |
struct CFSendWrapper(cf::CFRef); |
| 448 |
|
| 449 |
// Safety: |
| 450 |
// - According to the Apple documentation, it's safe to move `CFRef`s across threads. |
| 451 |
// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html |
| 452 |
unsafe impl Send for CFSendWrapper {} |
| 453 |
|
| 454 |
// move into thread |
| 455 |
let stream = CFSendWrapper(stream); |
| 456 |
|
| 457 |
// channel to pass runloop around |
| 458 |
let (rl_tx, rl_rx) = unbounded(); |
| 459 |
|
| 460 |
let thread_handle = thread::Builder::new() |
| 461 |
.name("notify-rs fsevents loop".to_string()) |
| 462 |
.spawn(move || { |
| 463 |
let _ = &stream; |
| 464 |
let stream = stream.0; |
| 465 |
|
| 466 |
unsafe { |
| 467 |
let cur_runloop = cf::CFRunLoopGetCurrent(); |
| 468 |
|
| 469 |
fs::FSEventStreamScheduleWithRunLoop( |
| 470 |
stream, |
| 471 |
cur_runloop, |
| 472 |
cf::kCFRunLoopDefaultMode, |
| 473 |
); |
| 474 |
fs::FSEventStreamStart(stream); |
| 475 |
|
| 476 |
// the calling to CFRunLoopRun will be terminated by CFRunLoopStop call in drop() |
| 477 |
rl_tx |
| 478 |
.send(CFSendWrapper(cur_runloop)) |
| 479 |
.expect("Unable to send runloop to watcher"); |
| 480 |
|
| 481 |
cf::CFRunLoopRun(); |
| 482 |
fs::FSEventStreamStop(stream); |
| 483 |
// There are edge-cases, when many events are pending, |
| 484 |
// despite the stream being stopped, that the stream's |
| 485 |
// associated callback will be invoked. Purging events |
| 486 |
// is intended to prevent this. |
| 487 |
let event_id = fs::FSEventsGetCurrentEventId(); |
| 488 |
let device = fs::FSEventStreamGetDeviceBeingWatched(stream); |
| 489 |
fs::FSEventsPurgeEventsForDeviceUpToEventId(device, event_id); |
| 490 |
fs::FSEventStreamInvalidate(stream); |
| 491 |
fs::FSEventStreamRelease(stream); |
| 492 |
} |
| 493 |
})?; |
| 494 |
// block until runloop has been sent |
| 495 |
self.runloop = Some((rl_rx.recv().unwrap().0, thread_handle)); |
| 496 |
|
| 497 |
Ok(()) |
| 498 |
} |
| 499 |
|
| 500 |
fn configure_raw_mode(&mut self, _config: Config, tx: Sender<Result<bool>>) { |
| 501 |
tx.send(Ok(false)) |
| 502 |
.expect("configuration channel disconnect"); |
| 503 |
} |
| 504 |
} |
| 505 |
|
| 506 |
extern "C" fn callback( |
| 507 |
stream_ref: fs::FSEventStreamRef, |
| 508 |
info: *mut libc::c_void, |
| 509 |
num_events: libc::size_t, // size_t numEvents |
| 510 |
event_paths: *mut libc::c_void, // void *eventPaths |
| 511 |
event_flags: *const fs::FSEventStreamEventFlags, // const FSEventStreamEventFlags eventFlags[] |
| 512 |
event_ids: *const fs::FSEventStreamEventId, // const FSEventStreamEventId eventIds[] |
| 513 |
) { |
| 514 |
unsafe { |
| 515 |
callback_impl( |
| 516 |
stream_ref, |
| 517 |
info, |
| 518 |
num_events, |
| 519 |
event_paths, |
| 520 |
event_flags, |
| 521 |
event_ids, |
| 522 |
) |
| 523 |
} |
| 524 |
} |
| 525 |
|
| 526 |
unsafe fn callback_impl( |
| 527 |
_stream_ref: fs::FSEventStreamRef, |
| 528 |
info: *mut libc::c_void, |
| 529 |
num_events: libc::size_t, // size_t numEvents |
| 530 |
event_paths: *mut libc::c_void, // void *eventPaths |
| 531 |
event_flags: *const fs::FSEventStreamEventFlags, // const FSEventStreamEventFlags eventFlags[] |
| 532 |
_event_ids: *const fs::FSEventStreamEventId, // const FSEventStreamEventId eventIds[] |
| 533 |
) { |
| 534 |
let event_paths = event_paths as *const *const libc::c_char; |
| 535 |
let info = info as *const StreamContextInfo; |
| 536 |
let event_handler = &(*info).event_handler; |
| 537 |
|
| 538 |
for p in 0..num_events { |
| 539 |
let path = CStr::from_ptr(*event_paths.add(p)) |
| 540 |
.to_str() |
| 541 |
.expect("Invalid UTF8 string."); |
| 542 |
let path = PathBuf::from(path); |
| 543 |
|
| 544 |
let flag = *event_flags.add(p); |
| 545 |
let flag = StreamFlags::from_bits(flag).unwrap_or_else(|| { |
| 546 |
panic!("Unable to decode StreamFlags: {}", flag); |
| 547 |
}); |
| 548 |
|
| 549 |
let mut handle_event = false; |
| 550 |
for (p, r) in &(*info).recursive_info { |
| 551 |
if path.starts_with(p) { |
| 552 |
if *r || &path == p { |
| 553 |
handle_event = true; |
| 554 |
break; |
| 555 |
} else if let Some(parent_path) = path.parent() { |
| 556 |
if parent_path == p { |
| 557 |
handle_event = true; |
| 558 |
break; |
| 559 |
} |
| 560 |
} |
| 561 |
} |
| 562 |
} |
| 563 |
|
| 564 |
if !handle_event { |
| 565 |
continue; |
| 566 |
} |
| 567 |
|
| 568 |
log::trace!("FSEvent: path = `{}`, flag = {:?}", path.display(), flag); |
| 569 |
|
| 570 |
for ev in translate_flags(flag, true).into_iter() { |
| 571 |
// TODO: precise |
| 572 |
let ev = ev.add_path(path.clone()); |
| 573 |
let mut event_handler = event_handler.lock().expect("lock not to be poisoned"); |
| 574 |
event_handler.handle_event(Ok(ev)); |
| 575 |
} |
| 576 |
} |
| 577 |
} |
| 578 |
|
| 579 |
impl Watcher for FsEventWatcher { |
| 580 |
/// Create a new watcher. |
| 581 |
fn new<F: EventHandler>(event_handler: F, _config: Config) -> Result<Self> { |
| 582 |
Self::from_event_handler(Arc::new(Mutex::new(event_handler))) |
| 583 |
} |
| 584 |
|
| 585 |
fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> { |
| 586 |
self.watch_inner(path, recursive_mode) |
| 587 |
} |
| 588 |
|
| 589 |
fn paths_mut<'me>(&'me mut self) -> Box<dyn PathsMut + 'me> { |
| 590 |
Box::new(FsEventPathsMut::new(self)) |
| 591 |
} |
| 592 |
|
| 593 |
fn unwatch(&mut self, path: &Path) -> Result<()> { |
| 594 |
self.unwatch_inner(path) |
| 595 |
} |
| 596 |
|
| 597 |
fn configure(&mut self, config: Config) -> Result<bool> { |
| 598 |
let (tx, rx) = unbounded(); |
| 599 |
self.configure_raw_mode(config, tx); |
| 600 |
rx.recv()? |
| 601 |
} |
| 602 |
|
| 603 |
fn kind() -> crate::WatcherKind { |
| 604 |
crate::WatcherKind::Fsevent |
| 605 |
} |
| 606 |
} |
| 607 |
|
| 608 |
impl Drop for FsEventWatcher { |
| 609 |
fn drop(&mut self) { |
| 610 |
self.stop(); |
| 611 |
unsafe { |
| 612 |
cf::CFRelease(self.paths); |
| 613 |
} |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
#[test] |
| 618 |
fn test_fsevent_watcher_drop() { |
| 619 |
use super::*; |
| 620 |
use std::time::Duration; |
| 621 |
|
| 622 |
let dir = tempfile::tempdir().unwrap(); |
| 623 |
|
| 624 |
let (tx, rx) = std::sync::mpsc::channel(); |
| 625 |
|
| 626 |
{ |
| 627 |
let mut watcher = FsEventWatcher::new(tx, Default::default()).unwrap(); |
| 628 |
watcher.watch(dir.path(), RecursiveMode::Recursive).unwrap(); |
| 629 |
thread::sleep(Duration::from_millis(2000)); |
| 630 |
println!("is running -> {}", watcher.is_running()); |
| 631 |
|
| 632 |
thread::sleep(Duration::from_millis(1000)); |
| 633 |
watcher.unwatch(dir.path()).unwrap(); |
| 634 |
println!("is running -> {}", watcher.is_running()); |
| 635 |
} |
| 636 |
|
| 637 |
thread::sleep(Duration::from_millis(1000)); |
| 638 |
|
| 639 |
for res in rx { |
| 640 |
let e = res.unwrap(); |
| 641 |
println!("debug => {:?} {:?}", e.kind, e.paths); |
| 642 |
} |
| 643 |
|
| 644 |
println!("in test: {} works", file!()); |
| 645 |
} |
| 646 |
|
| 647 |
#[test] |
| 648 |
fn test_steam_context_info_send_and_sync() { |
| 649 |
fn check_send<T: Send + Sync>() {} |
| 650 |
check_send::<StreamContextInfo>(); |
| 651 |
} |