| 1 | //! `helix-event` contains systems that allow (often async) communication between |
| 2 | //! different editor components without strongly coupling them. Specifically |
| 3 | //! it allows defining synchronous hooks that run when certain editor events |
| 4 | //! occur. |
| 5 | //! |
| 6 | //! The core of the event system are hook callbacks and the [`Event`] trait. A |
| 7 | //! hook is essentially just a closure `Fn(event: &mut impl Event) -> Result<()>` |
| 8 | //! that gets called every time an appropriate event is dispatched. The implementation |
| 9 | //! details of the [`Event`] trait are considered private. The [`events`] macro is |
| 10 | //! provided which automatically declares event types. Similarly the `register_hook` |
| 11 | //! macro should be used to (safely) declare event hooks. |
| 12 | //! |
| 13 | //! Hooks run synchronously which can be advantageous since they can modify the |
| 14 | //! current editor state right away (for example to immediately hide the completion |
| 15 | //! popup). However, they can not contain their own state without locking since |
| 16 | //! they only receive immutable references. For handler that want to track state, do |
| 17 | //! expensive background computations or debouncing an [`AsyncHook`] is preferable. |
| 18 | //! Async hooks are based around a channels that receive events specific to |
| 19 | //! that `AsyncHook` (usually an enum). These events can be sent by synchronous |
| 20 | //! hooks. Due to some limitations around tokio channels the [`send_blocking`] |
| 21 | //! function exported in this crate should be used instead of the builtin |
| 22 | //! `blocking_send`. |
| 23 | //! |
| 24 | //! In addition to the core event system, this crate contains some message queues |
| 25 | //! that allow transfer of data back to the main event loop from async hooks and |
| 26 | //! hooks that may not have access to all application data (for example in helix-view). |
| 27 | //! This include the ability to control rendering ([`lock_frame`], [`request_redraw`]) and |
| 28 | //! display status messages ([`status`]). |
| 29 | //! |
| 30 | //! Hooks declared in helix-term can furthermore dispatch synchronous jobs to be run on the |
| 31 | //! main loop (including access to the compositor). Ideally that queue will be moved |
| 32 | //! to helix-view in the future if we manage to detach the compositor from its rendering backend. |
| 33 | |
| 34 | use anyhow::Result; |
| 35 | pub use cancel::{cancelable_future, TaskController, TaskHandle}; |
| 36 | pub use debounce::{send_blocking, AsyncHook}; |
| 37 | pub use redraw::{ |
| 38 | lock_frame, redraw_requested, request_redraw, start_frame, RenderLockGuard, RequestRedrawOnDrop, |
| 39 | }; |
| 40 | pub use registry::Event; |
| 41 | |
| 42 | mod cancel; |
| 43 | mod debounce; |
| 44 | mod hook; |
| 45 | mod redraw; |
| 46 | mod registry; |
| 47 | #[doc(hidden)] |
| 48 | pub mod runtime; |
| 49 | pub mod status; |
| 50 | |
| 51 | #[cfg(test)] |
| 52 | mod test; |
| 53 | |
| 54 | pub fn register_event<E: Event + 'static>() { |
| 55 | registry::with_mut(|registry| registry.register_event::<E>()) |
| 56 | } |
| 57 | |
| 58 | /// Registers a hook that will be called when an event of type `E` is dispatched. |
| 59 | /// This function should usually not be used directly, use the [`register_hook`] |
| 60 | /// macro instead. |
| 61 | /// |
| 62 | /// |
| 63 | /// # Safety |
| 64 | /// |
| 65 | /// `hook` must be totally generic over all lifetime parameters of `E`. For |
| 66 | /// example if `E` was a known type `Foo<'a, 'b>`, then the correct trait bound |
| 67 | /// would be `F: for<'a, 'b, 'c> Fn(&'a mut Foo<'b, 'c>)`, but there is no way to |
| 68 | /// express that kind of constraint for a generic type with the Rust type system |
| 69 | /// as of this writing. |
| 70 | pub unsafe fn register_hook_raw<E: Event>( |
| 71 | hook: impl Fn(&mut E) -> Result<()> + 'static + Send + Sync, |
| 72 | ) { |
| 73 | registry::with_mut(|registry| registry.register_hook(hook)) |
| 74 | } |
| 75 | |
| 76 | /// Register a hook solely by event name |
| 77 | pub fn register_dynamic_hook( |
| 78 | hook: impl Fn() -> Result<()> + 'static + Send + Sync, |
| 79 | id: &str, |
| 80 | ) -> Result<()> { |
| 81 | registry::with_mut(|reg| reg.register_dynamic_hook(hook, id)) |
| 82 | } |
| 83 | |
| 84 | pub fn dispatch(e: impl Event) { |
| 85 | registry::with(|registry| registry.dispatch(e)); |
| 86 | } |
| 87 | |
| 88 | /// Macro to declare events |
| 89 | /// |
| 90 | /// # Examples |
| 91 | /// |
| 92 | /// ``` no-compile |
| 93 | /// events! { |
| 94 | /// FileWrite(&Path) |
| 95 | /// ViewScrolled{ view: View, new_pos: ViewOffset } |
| 96 | /// DocumentChanged<'a> { old_doc: &'a Rope, doc: &'a mut Document, changes: &'a ChangeSet } |
| 97 | /// } |
| 98 | /// |
| 99 | /// fn init() { |
| 100 | /// register_event::<FileWrite>(); |
| 101 | /// register_event::<ViewScrolled>(); |
| 102 | /// register_event::<DocumentChanged>(); |
| 103 | /// } |
| 104 | /// |
| 105 | /// fn save(path: &Path, content: &str){ |
| 106 | /// std::fs::write(path, content); |
| 107 | /// dispatch(FileWrite(path)); |
| 108 | /// } |
| 109 | /// ``` |
| 110 | #[macro_export] |
| 111 | macro_rules! events { |
| 112 | ($name: ident<$($lt: lifetime),*> { $($data:ident : $data_ty:ty),* } $($rem:tt)*) => { |
| 113 | pub struct $name<$($lt),*> { $(pub $data: $data_ty),* } |
| 114 | unsafe impl<$($lt),*> $crate::Event for $name<$($lt),*> { |
| 115 | const ID: &'static str = stringify!($name); |
| 116 | const LIFETIMES: usize = $crate::events!(@sum $(1, $lt),*); |
| 117 | type Static = $crate::events!(@replace_lt $name, $('static, $lt),*); |
| 118 | } |
| 119 | $crate::events!{ $($rem)* } |
| 120 | }; |
| 121 | ($name: ident { $($data:ident : $data_ty:ty),* } $($rem:tt)*) => { |
| 122 | pub struct $name { $(pub $data: $data_ty),* } |
| 123 | unsafe impl $crate::Event for $name { |
| 124 | const ID: &'static str = stringify!($name); |
| 125 | const LIFETIMES: usize = 0; |
| 126 | type Static = Self; |
| 127 | } |
| 128 | $crate::events!{ $($rem)* } |
| 129 | }; |
| 130 | () => {}; |
| 131 | (@replace_lt $name: ident, $($lt1: lifetime, $lt2: lifetime),* ) => {$name<$($lt1),*>}; |
| 132 | (@sum $($val: expr, $lt1: lifetime),* ) => {0 $(+ $val)*}; |
| 133 | } |
| 134 | |
| 135 | /// Safely register statically typed event hooks |
| 136 | #[macro_export] |
| 137 | macro_rules! register_hook { |
| 138 | // Safety: this is safe because we fully control the type of the event here and |
| 139 | // ensure all lifetime arguments are fully generic and the correct number of lifetime arguments |
| 140 | // is present |
| 141 | (move |$event:ident: &mut $event_ty: ident<$($lt: lifetime),*>| $body: expr) => { |
| 142 | let val = move |$event: &mut $event_ty<$($lt),*>| $body; |
| 143 | unsafe { |
| 144 | // Lifetimes are a bit of a pain. We want to allow events being |
| 145 | // non-static. Lifetimes don't actually exist at runtime so its |
| 146 | // fine to essentially transmute the lifetimes as long as we can |
| 147 | // prove soundness. The hook must therefore accept any combination |
| 148 | // of lifetimes. In other words fn(&'_ mut Event<'_, '_>) is ok |
| 149 | // but examples like fn(&'_ mut Event<'_, 'static>) or fn<'a>(&'a |
| 150 | // mut Event<'a, 'a>) are not. To make this safe we use a macro to |
| 151 | // forbid the user from specifying lifetimes manually (all lifetimes |
| 152 | // specified are always function generics and passed to the event so |
| 153 | // lifetimes can't be used multiple times and using 'static causes a |
| 154 | // syntax error). |
| 155 | // |
| 156 | // There is one soundness hole tough: Type Aliases allow |
| 157 | // "accidentally" creating these problems. For example: |
| 158 | // |
| 159 | // type Event2 = Event<'static>. |
| 160 | // type Event2<'a> = Event<'a, a>. |
| 161 | // |
| 162 | // These cases can be caught by counting the number of lifetimes |
| 163 | // parameters at the parameter declaration site and then at the hook |
| 164 | // declaration site. By asserting the number of lifetime parameters |
| 165 | // are equal we can catch all bad type aliases under one assumption: |
| 166 | // There are no unused lifetime parameters. Introducing a static |
| 167 | // would reduce the number of arguments of the alias by one in the |
| 168 | // above example Event2 has zero lifetime arguments while the original |
| 169 | // event has one lifetime argument. Similar logic applies to using |
| 170 | // a lifetime argument multiple times. The ASSERT below performs a |
| 171 | // a compile time assertion to ensure exactly this property. |
| 172 | // |
| 173 | // With unused lifetime arguments it is still one way to cause unsound code: |
| 174 | // |
| 175 | // type Event2<'a, 'b> = Event<'a, 'a>; |
| 176 | // |
| 177 | // However, this case will always emit a compiler warning/cause CI |
| 178 | // failures so a user would have to introduce #[allow(unused)] which |
| 179 | // is easily caught in review (and a very theoretical case anyway). |
| 180 | // If we want to be pedantic we can simply compile helix with |
| 181 | // forbid(unused). All of this is just a safety net to prevent |
| 182 | // very theoretical misuse. This won't come up in real code (and is |
| 183 | // easily caught in review). |
| 184 | #[allow(unused)] |
| 185 | const ASSERT: () = { |
| 186 | if <$event_ty as $crate::Event>::LIFETIMES != 0 + $crate::events!(@sum $(1, $lt),*){ |
| 187 | panic!("invalid type alias"); |
| 188 | } |
| 189 | }; |
| 190 | $crate::register_hook_raw::<$crate::events!(@replace_lt $event_ty, $('static, $lt),*)>(val); |
| 191 | } |
| 192 | }; |
| 193 | (move |$event:ident: &mut $event_ty: ident| $body: expr) => { |
| 194 | let val = move |$event: &mut $event_ty| $body; |
| 195 | unsafe { |
| 196 | #[allow(unused)] |
| 197 | const ASSERT: () = { |
| 198 | if <$event_ty as $crate::Event>::LIFETIMES != 0{ |
| 199 | panic!("invalid type alias"); |
| 200 | } |
| 201 | }; |
| 202 | $crate::register_hook_raw::<$event_ty>(val); |
| 203 | } |
| 204 | }; |
| 205 | } |