Debian Codegraph @

src/platform/macos_iokit/events.rs

raw symbols SCIP
1 use std::{
2 ops::Deref,
3 sync::{mpsc, Mutex},
4 thread,
5 };
6
7 use core_foundation::runloop::{CFRunLoop, CFRunLoopSource};
8 use core_foundation_sys::runloop::kCFRunLoopCommonModes;
9 use log::debug;
10
11 // Pending release of https://github.com/servo/core-foundation-rs/pull/610
12 struct SendCFRunLoop(CFRunLoop);
13 unsafe impl Send for SendCFRunLoop {}
14 impl Deref for SendCFRunLoop {
15 type Target = CFRunLoop;
16
17 fn deref(&self) -> &Self::Target {
18 &self.0
19 }
20 }
21
22 struct SendCFRunLoopSource(CFRunLoopSource);
23 unsafe impl Send for SendCFRunLoopSource {}
24 unsafe impl Sync for SendCFRunLoopSource {}
25
26 struct EventLoop {
27 runloop: Option<SendCFRunLoop>,
28 count: usize,
29 }
30
31 static EVENT_LOOP: Mutex<EventLoop> = Mutex::new(EventLoop {
32 runloop: None,
33 count: 0,
34 });
35
36 pub(crate) fn add_event_source(source: CFRunLoopSource) -> EventRegistration {
37 let mut event_loop = EVENT_LOOP.lock().unwrap();
38 if let Some(runloop) = event_loop.runloop.as_ref() {
39 if runloop.contains_source(&source, unsafe { kCFRunLoopCommonModes }) {
40 panic!("source already registered");
41 }
42 runloop.add_source(&source, unsafe { kCFRunLoopCommonModes });
43 event_loop.count += 1;
44 } else {
45 let (tx, rx) = mpsc::channel();
46 let source = SendCFRunLoopSource(source.clone());
47 debug!("starting event loop thread");
48 thread::spawn(move || {
49 let runloop = CFRunLoop::get_current();
50 let source = source;
51 runloop.add_source(&source.0, unsafe { kCFRunLoopCommonModes });
52 tx.send(SendCFRunLoop(runloop)).unwrap();
53 CFRunLoop::run_current();
54 debug!("event loop thread exited");
55 });
56 event_loop.runloop = Some(rx.recv().expect("failed to start run loop thread"));
57 event_loop.count = 1;
58 }
59 EventRegistration(SendCFRunLoopSource(source))
60 }
61 pub(crate) struct EventRegistration(SendCFRunLoopSource);
62
63 impl Drop for EventRegistration {
64 fn drop(&mut self) {
65 let mut event_loop = EVENT_LOOP.lock().unwrap();
66 event_loop.count -= 1;
67
68 let runloop = event_loop
69 .runloop
70 .as_ref()
71 .expect("runloop should exist while events are registered");
72 runloop.remove_source(&self.0 .0, unsafe { kCFRunLoopCommonModes });
73
74 if event_loop.count == 0 {
75 runloop.stop();
76 event_loop.runloop.take();
77 }
78 }
79 }