Skip to main content

atmos/kernel/
pending_events.rs

1//! OS 側(メインループ)が持つ、アプリへまだ渡せていない入力の控え(TODO R4 (b)、2026-11-17)。
2//!
3//! `ProxyApp` はアプリのスレッドと入力のキュー(`event_queue`)を錠で共有している。以前は OS 側が
4//! `lock()` で取っていたので、アプリのスレッドが錠を持っている間(持ったまま切り替えられた間も)、
5//! メインループ(core 0・Realtime)が待たされた。今は OS 側は錠を待たず(`try_lock`)、取れなかった入力を
6//! ここに控えて、次の周に錠が取れたときにまとめて渡す。
7//!
8//! 決まり(純粋なデータ構造。ホスト試験 `tests/src/test_pending_events.rs`):
9//! - 控えは来た順のまま渡す。控えが残っている間に来た入力も控えの後ろに並べる(追い越さない)。
10//! - キー・マウスは捨てない・まとめない。
11//! - 「置き換え型」(ウィンドウの大きさの変更)は、最後の 1 つだけ残す(以前の `on_resize` と同じ)。
12//!   控えの中の古い物も、渡す先のキューに残っている古い物も外し、新しい物を末尾に置く。
13
14extern crate alloc;
15use alloc::collections::VecDeque;
16use alloc::vec::Vec;
17
18/// アプリへまだ渡せていない入力の控え。OS 側だけが持つ(錠は要らない)。
19pub struct PendingEvents<T> {
20    buf: VecDeque<T>,
21}
22
23impl<T> Default for PendingEvents<T> {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28
29impl<T> PendingEvents<T> {
30    pub const fn new() -> Self {
31        Self { buf: VecDeque::new() }
32    }
33
34    pub fn is_empty(&self) -> bool {
35        self.buf.is_empty()
36    }
37
38    pub fn len(&self) -> usize {
39        self.buf.len()
40    }
41
42    /// 末尾に積む(キー・マウス・タブの操作)。
43    pub fn push(&mut self, ev: T) {
44        self.buf.push_back(ev);
45    }
46
47    /// 置き換え型の入力を積む。控えの中の同じ種類の物を外してから末尾に置く。
48    pub fn push_replacing(&mut self, ev: T, same_kind: impl Fn(&T) -> bool) {
49        self.buf.retain(|e| !same_kind(e));
50        self.buf.push_back(ev);
51    }
52
53    /// 控えを全部、渡す先のキュー `dst`(錠を取れたアプリのキュー)の末尾へ移す。
54    /// 控えに置き換え型が入っていれば、`dst` に残っている同じ種類の古い物を先に外す。
55    /// 移した数を返す。
56    pub fn flush_into(&mut self, dst: &mut Vec<T>, same_kind: impl Fn(&T) -> bool) -> usize {
57        if self.buf.is_empty() {
58            return 0;
59        }
60        if self.buf.iter().any(&same_kind) {
61            dst.retain(|e| !same_kind(e));
62        }
63        let n = self.buf.len();
64        dst.extend(self.buf.drain(..));
65        n
66    }
67
68    /// 控えを捨てる(アプリが止まって、渡す先がもう無いとき)。
69    pub fn clear(&mut self) {
70        self.buf.clear();
71    }
72}