kael 0.2.0

GPU-accelerated native UI framework for Rust — build desktop apps with Metal, DirectX, and Vulkan rendering
Documentation
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::{
    collections::BTreeMap,
    io,
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use anyhow::{Context as _, Result, anyhow, bail};
use notify::{
    Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher,
    event::{CreateKind, ModifyKind, RemoveKind, RenameMode},
};
use smol::channel;

use crate::{App, ForegroundExecutor, Task};

/// Options that control how a path is watched.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FileWatchOptions {
    /// Whether directory changes should be watched recursively.
    pub recursive: bool,
    /// The maximum relative depth to emit events for when `recursive` is enabled.
    ///
    /// A depth of `1` includes direct children of the watched directory, `2`
    /// includes grandchildren, and so on. `None` means there is no depth limit.
    pub max_depth: Option<usize>,
}

impl FileWatchOptions {
    /// Returns recursive watch options with no depth limit.
    pub fn recursive() -> Self {
        Self {
            recursive: true,
            max_depth: None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct WatchRegistration {
    recursive: bool,
    max_depth: Option<usize>,
}

/// A file-system change delivered by [`FileWatcher`].
#[derive(Debug)]
pub enum FileWatchEvent {
    /// A new file or directory was created.
    Created(PathBuf),
    /// An existing file or directory was modified.
    Modified(PathBuf),
    /// A file or directory was deleted.
    Deleted(PathBuf),
    /// A file or directory was renamed or moved.
    Renamed {
        /// The previous path.
        from: PathBuf,
        /// The new path.
        to: PathBuf,
    },
    /// Watching failed for a specific path.
    Error {
        /// The watched path associated with the error.
        path: PathBuf,
        /// The underlying I/O error.
        error: io::Error,
    },
}

/// Cross-platform file-system watcher backed by the `notify` crate.
///
/// Callbacks are always executed on the GPUI foreground executor so they can
/// safely interact with other UI state.
pub struct FileWatcher {
    watcher: RecommendedWatcher,
    registrations: Arc<Mutex<BTreeMap<PathBuf, WatchRegistration>>>,
    event_tx: channel::Sender<FileWatchEvent>,
    _callback_task: Task<()>,
}

impl FileWatcher {
    /// Creates a file watcher that dispatches callbacks on the given app's
    /// foreground executor.
    pub fn new(app: &App, callback: impl FnMut(FileWatchEvent) + 'static) -> Result<Self> {
        Self::new_with_executor(app.foreground_executor().clone(), callback)
    }

    /// Creates a file watcher that dispatches callbacks on the given
    /// foreground executor.
    pub fn new_with_executor(
        executor: ForegroundExecutor,
        mut callback: impl FnMut(FileWatchEvent) + 'static,
    ) -> Result<Self> {
        let registrations = Arc::new(Mutex::new(BTreeMap::new()));
        let (event_tx, event_rx) = channel::unbounded();
        let callback_task = executor.spawn(async move {
            while let Ok(event) = event_rx.recv().await {
                callback(event);
            }
        });

        let watcher_registrations = registrations.clone();
        let watcher_tx = event_tx.clone();
        let mut watcher = notify::recommended_watcher(move |result| {
            let events = {
                let registrations = watcher_registrations
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
                translate_notify_result(result, &registrations)
            };

            for event in events {
                let _ = watcher_tx.try_send(event);
            }
        })
        .context("failed to create file watcher")?;

        watcher
            .configure(Config::default())
            .context("failed to configure file watcher")?;

        Ok(Self {
            watcher,
            registrations,
            event_tx,
            _callback_task: callback_task,
        })
    }

    /// Starts watching a file or directory.
    ///
    /// When `recursive` is `true`, all descendants are watched without a depth
    /// limit. Use [`Self::watch_with_options`] to constrain recursive depth.
    pub fn watch(&mut self, path: impl AsRef<Path>, recursive: bool) -> Result<()> {
        self.watch_with_options(
            path,
            FileWatchOptions {
                recursive,
                max_depth: None,
            },
        )
    }

    /// Starts watching a file or directory with explicit options.
    pub fn watch_with_options(
        &mut self,
        path: impl AsRef<Path>,
        options: FileWatchOptions,
    ) -> Result<()> {
        if options.max_depth.is_some() && !options.recursive {
            bail!("file watch depth limits require recursive watching");
        }

        let normalized_path = match normalize_watch_path(path.as_ref()) {
            Ok(path) => path,
            Err(error) => {
                self.emit_watch_error(resolve_input_path(path.as_ref())?, anyhow!("{error}"));
                return Err(error);
            }
        };
        let recursive_mode = if options.recursive {
            RecursiveMode::Recursive
        } else {
            RecursiveMode::NonRecursive
        };

        self.watcher
            .watch(&normalized_path, recursive_mode)
            .with_context(|| format!("failed to watch {}", normalized_path.display()))?;

        let registration = WatchRegistration {
            recursive: options.recursive,
            max_depth: options.max_depth,
        };
        self.registrations
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .insert(normalized_path, registration);

        Ok(())
    }

    /// Stops watching a previously-registered path.
    pub fn unwatch(&mut self, path: impl AsRef<Path>) -> Result<()> {
        let normalized_path = match normalize_watch_path(path.as_ref()) {
            Ok(path) => path,
            Err(error) => {
                self.emit_watch_error(resolve_input_path(path.as_ref())?, anyhow!("{error}"));
                return Err(error);
            }
        };
        self.watcher
            .unwatch(&normalized_path)
            .with_context(|| format!("failed to unwatch {}", normalized_path.display()))?;
        self.registrations
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .remove(&normalized_path);
        Ok(())
    }

    fn emit_watch_error(&self, path: PathBuf, error: anyhow::Error) {
        let _ = self.event_tx.try_send(FileWatchEvent::Error {
            path,
            error: io::Error::other(error.to_string()),
        });
    }
}

fn normalize_watch_path(path: &Path) -> Result<PathBuf> {
    let absolute = resolve_input_path(path)?;

    if !absolute.exists() {
        bail!("watched path does not exist: {}", absolute.display());
    }

    absolute
        .canonicalize()
        .with_context(|| format!("failed to canonicalize {}", absolute.display()))
}

fn resolve_input_path(path: &Path) -> Result<PathBuf> {
    Ok(if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .context("failed to resolve current working directory")?
            .join(path)
    })
}

fn translate_notify_result(
    result: notify::Result<Event>,
    registrations: &BTreeMap<PathBuf, WatchRegistration>,
) -> Vec<FileWatchEvent> {
    match result {
        Ok(event) => translate_notify_event(event, registrations),
        Err(error) => translate_notify_error(error, registrations),
    }
}

fn translate_notify_event(
    event: Event,
    registrations: &BTreeMap<PathBuf, WatchRegistration>,
) -> Vec<FileWatchEvent> {
    if matches!(event.kind, EventKind::Access(_)) {
        return Vec::new();
    }

    match event.kind {
        EventKind::Create(
            CreateKind::Any | CreateKind::File | CreateKind::Folder | CreateKind::Other,
        ) => paths_matching_registrations(&event.paths, registrations)
            .into_iter()
            .map(FileWatchEvent::Created)
            .collect(),
        EventKind::Modify(ModifyKind::Name(RenameMode::Any | RenameMode::Both))
            if event.paths.len() >= 2
                && rename_matches_registrations(
                    &event.paths[0],
                    &event.paths[1],
                    registrations,
                ) =>
        {
            vec![FileWatchEvent::Renamed {
                from: event.paths[0].clone(),
                to: event.paths[1].clone(),
            }]
        }
        EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
            paths_matching_registrations(&event.paths, registrations)
                .into_iter()
                .map(FileWatchEvent::Deleted)
                .collect()
        }
        EventKind::Modify(ModifyKind::Name(RenameMode::To)) => {
            paths_matching_registrations(&event.paths, registrations)
                .into_iter()
                .map(FileWatchEvent::Created)
                .collect()
        }
        EventKind::Modify(_) => paths_matching_registrations(&event.paths, registrations)
            .into_iter()
            .map(FileWatchEvent::Modified)
            .collect(),
        EventKind::Remove(
            RemoveKind::Any | RemoveKind::File | RemoveKind::Folder | RemoveKind::Other,
        ) => paths_matching_registrations(&event.paths, registrations)
            .into_iter()
            .map(FileWatchEvent::Deleted)
            .collect(),
        _ => Vec::new(),
    }
}

fn translate_notify_error(
    error: notify::Error,
    registrations: &BTreeMap<PathBuf, WatchRegistration>,
) -> Vec<FileWatchEvent> {
    let message = error.to_string();
    let mut paths = error.paths;
    if paths.is_empty() {
        paths.extend(registrations.keys().cloned());
    }
    paths
        .into_iter()
        .filter(|path| {
            registrations.is_empty()
                || registrations.contains_key(path)
                || path_matches_any_registration(path, registrations)
        })
        .map(|path| FileWatchEvent::Error {
            path,
            error: io::Error::other(message.clone()),
        })
        .collect()
}

fn paths_matching_registrations(
    paths: &[PathBuf],
    registrations: &BTreeMap<PathBuf, WatchRegistration>,
) -> Vec<PathBuf> {
    paths
        .iter()
        .filter(|path| path_matches_any_registration(path, registrations))
        .cloned()
        .collect()
}

fn rename_matches_registrations(
    from: &Path,
    to: &Path,
    registrations: &BTreeMap<PathBuf, WatchRegistration>,
) -> bool {
    path_matches_any_registration(from, registrations)
        || path_matches_any_registration(to, registrations)
}

fn path_matches_any_registration(
    path: &Path,
    registrations: &BTreeMap<PathBuf, WatchRegistration>,
) -> bool {
    registrations
        .iter()
        .any(|(root, registration)| path_matches_registration(path, root, registration))
}

fn path_matches_registration(path: &Path, root: &Path, registration: &WatchRegistration) -> bool {
    if path == root {
        return true;
    }

    let Ok(relative_path) = path.strip_prefix(root) else {
        return false;
    };

    let depth = relative_path.components().count();
    if depth == 0 {
        return true;
    }

    if !registration.recursive {
        return depth == 1;
    }

    registration
        .max_depth
        .is_none_or(|max_depth| depth <= max_depth)
}

#[cfg(any(test, feature = "test-support"))]
#[allow(dead_code)]
pub(crate) fn translate_watch_event_for_test(
    result: notify::Result<Event>,
    watched_path: &Path,
    options: FileWatchOptions,
) -> Vec<FileWatchEvent> {
    let mut registrations = BTreeMap::new();
    registrations.insert(
        watched_path.to_path_buf(),
        WatchRegistration {
            recursive: options.recursive,
            max_depth: options.max_depth,
        },
    );
    translate_notify_result(result, &registrations)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn path_matching_honors_depth_limits() {
        let root = PathBuf::from("/tmp/root");
        let registration = WatchRegistration {
            recursive: true,
            max_depth: Some(2),
        };

        assert!(path_matches_registration(
            Path::new("/tmp/root/child"),
            &root,
            &registration
        ));
        assert!(path_matches_registration(
            Path::new("/tmp/root/child/grandchild"),
            &root,
            &registration
        ));
        assert!(!path_matches_registration(
            Path::new("/tmp/root/child/grandchild/great-grandchild"),
            &root,
            &registration
        ));
    }

    #[test]
    fn path_matching_honors_non_recursive_watches() {
        let root = PathBuf::from("/tmp/root");
        let registration = WatchRegistration {
            recursive: false,
            max_depth: None,
        };

        assert!(path_matches_registration(
            Path::new("/tmp/root/file.txt"),
            &root,
            &registration
        ));
        assert!(!path_matches_registration(
            Path::new("/tmp/root/nested/file.txt"),
            &root,
            &registration
        ));
    }
}