Skip to main content

atmos/kernel/
window_mgr.rs

1//! 多層ウィンドウマネージャ。
2//!
3//! [`App`] トレイトを実装する各アプリ([`crate::apps`])をウィンドウとして重ね合わせ表示・
4//! 入力ルーティングする。スタートボタン・タスクバーは持たず、ウィンドウは重ね合わせ型
5//! (`spec/README.md`「UI 方針」)。`ProxyApp` はバックグラウンドスレッドで動くアプリ
6//! (別コアで動く `app_runner_entry`)をメインループ側の `App` として橋渡しする。
7// src/window_mgr.rs - Multi-layered Window Manager for AtmOS
8#![allow(dead_code)]
9
10extern crate alloc;
11use alloc::boxed::Box;
12use alloc::string::String;
13use alloc::vec::Vec;
14
15use crate::kernel::draw::{Color, Screen};
16
17/// アプリケーションが実装すべきトレイト
18pub trait App {
19    fn name(&self) -> &str;
20
21    /// ProxyApp であるかどうか
22    fn is_proxy(&self) -> bool {
23        false
24    }
25
26    /// 共有されるバックバッファを返す
27    fn get_shared_buffer(&self) -> Option<alloc::sync::Arc<spin::Mutex<alloc::vec::Vec<u32>>>> {
28        None
29    }
30
31    /// インスタンス特有の情報(ファイル名やURLなど)を返す
32    fn instance_info(&self) -> alloc::string::String {
33        alloc::string::String::new()
34    }
35
36    /// ウィンドウ内の描画要求
37    fn draw(&mut self, screen: &Screen, win_x: u32, win_y: u32, win_w: u32, win_h: u32);
38
39    /// マウスイベント。ローカル座標とホイール移動量が渡される。
40    fn on_mouse(&mut self, local_x: i32, local_y: i32, btn_left: bool, btn_right: bool, wheel: i32);
41
42    /// キーボードイベント
43    fn on_key(&mut self, keycode: u8, pressed: bool, ascii: Option<char>);
44
45    // -----------------------------------------------------------------------
46    // OS一元管理型 縦タブ API (デフォルト実装付き)
47    // -----------------------------------------------------------------------
48
49    /// タブタイトル一覧。空を返すとタブなし扱い(非推奨: 全アプリは最低1タブ持つ)
50    /// タイトルバーに出す文字(`None` なら作成時の `Window.title`)。ページで変わるアプリが使う。
51    fn live_title(&self) -> Option<alloc::string::String> {
52        None
53    }
54
55    fn tabs(&self) -> alloc::vec::Vec<alloc::string::String> {
56        alloc::vec![alloc::string::String::from(self.name())]
57    }
58    fn active_tab(&self) -> usize {
59        0
60    }
61    fn switch_tab(&mut self, _idx: usize) {}
62    /// アプリのスレッドの 1 周の頭(錠を持っていない所)で呼ばれる。メモリが足りないときに裏のタブを破棄する
63    /// アプリ(ブラウザ)が実装する(2026-11-19。判定は `kernel/tab_discard.rs`)。
64    fn memory_checkpoint(&mut self) {}
65    fn add_tab(&mut self) {}
66    /// 同じアプリが URL つきで 2 度目に起動されたとき、その URL を新しいタブで開く(2026-11-18。ブラウザだけが実装する)。
67    fn open_url_in_new_tab(&mut self, _url: &str) {}
68    /// タブを閉じる。最後のタブが閉じられウィンドウも閉じる場合は true を返す。
69    fn close_tab(&mut self, _idx: usize) -> bool {
70        true
71    }
72
73    /// Alt+O: ファイルオープンダイアログを開く(未実装アプリはno-op)
74    fn open_file_dialog(&mut self) {}
75    /// Alt+S: ファイルを保存する(未実装アプリはno-op)
76    fn save_file(&mut self) {}
77
78    /// このアプリの各タブ用バックグラウンドスレッド関数を返す。
79    /// Some(fn) を返したアプリはタブ追加時にスケジューラでスレッドを起動する。
80    /// スレッド関数は引数なしの fn() で、グローバル Mutex 経由でアプリ状態と通信する。
81    fn tab_thread_fn(&self) -> Option<fn()> {
82        None
83    }
84
85    // DOM値操作用API (デフォルト実装付き)
86    fn get_dom_value(&self, _id: &str) -> Option<alloc::string::String> {
87        None
88    }
89    fn set_dom_value(&mut self, _id: &str, _val: &str) {}
90
91    // タイマーベースの再描画要求(ローディングアニメーション用など)
92    fn needs_timer_redraw(&self) -> bool {
93        false
94    }
95
96    /// ProxyApp の shared_buffer が更新されたことを通知する AtomicBool を返す。
97    /// ProxyApp でない通常のアプリは None を返す(デフォルト実装)。
98    /// Core 0 の dirty 判定がこのフラグを読んで矩形を登録する。
99    fn get_buffer_updated_flag(&self) -> Option<alloc::sync::Arc<core::sync::atomic::AtomicBool>> {
100        None
101    }
102
103    // DOMコンテンツ操作用API (デフォルト実装付き)
104    fn get_dom_content(&self, _id: &str) -> Option<alloc::string::String> {
105        None
106    }
107    fn set_dom_content(&mut self, _id: &str, _val: &str) {}
108
109    /// ウィンドウサイズ変更の通知
110    fn on_resize(&mut self, _width: u32, _height: u32) {}
111
112    /// アプリのスレッドがもう居ない(panic・メモリの使いすぎで止めた)か。ウィンドウは最後の画面のまま残る。
113    /// 同じアプリを開き直すとき、[`WindowManager::add_window`] はこのウィンドウを使い回さず置き換える。
114    fn is_stopped(&self) -> bool {
115        false
116    }
117
118    /// アプリが応答していない時間(ms)。応答しているなら `None`(TODO R2 (a))。
119    /// `ProxyApp` はアプリのスレッドの 1 周の始まりが [`UNRESPONSIVE_MS`] 以上前なら返す。
120    /// メインループで描くアプリは、ウォッチドッグの Not Responding(`watchdog::is_not_responding`)で見る([`Window::unresponsive`])。
121    fn unresponsive_ms(&self) -> Option<u64> {
122        None
123    }
124
125    /// タブを 1 つだけ止める(TODO R2 (d)、2026-11-18)。受け付けたら true。
126    /// `ProxyApp` は合図を立てるだけで、アプリのスレッドが、そのタブの JS を打ち切ってから 1 周の頭でタブを閉じる。
127    fn kill_tab(&mut self, _idx: usize) -> bool {
128        false
129    }
130
131    /// アプリのスレッドが今動かしているタブ(TODO R2 (d))。`ProxyApp` では、利用者が応答しない間に
132    /// 別のタブを選んでも([`App::active_tab`] は選んだ先を返す)、アプリが実際に動かしているタブを返す。
133    fn running_tab(&self) -> usize {
134        self.active_tab()
135    }
136
137    /// タブを止める合図を立てたが、まだ閉じていないタブ(TODO R2 (d))。
138    fn tab_kill_pending(&self) -> Option<usize> {
139        None
140    }
141
142    /// メインループが毎周 1 回呼ぶ(TODO R4 (b)、2026-11-17)。`ProxyApp` はここで、錠が取れずに控えた入力・
143    /// タブの切り替えをアプリへ渡し直し、題名・タブの写しを取り直す。錠は待たない(`try_lock`)。
144    fn os_tick(&mut self) {}
145}
146
147use alloc::sync::Arc;
148use spin::Mutex;
149use core::sync::atomic::AtomicBool;
150
151#[derive(Clone, Debug)]
152pub enum AppEvent {
153    Mouse {
154        local_x: i32,
155        local_y: i32,
156        btn_left: bool,
157        btn_right: bool,
158        wheel: i32,
159    },
160    Key {
161        keycode: u8,
162        pressed: bool,
163        ascii: Option<char>,
164    },
165    SwitchTab(usize),
166    AddTab,
167    CloseTab(usize),
168    /// 2 度目の起動で渡された URL を、新しいタブで開く(2026-11-18)。
169    OpenUrl(String),
170    Resize {
171        width: u32,
172        height: u32,
173    },
174}
175
176pub struct ProxyApp {
177    pub name: String,
178    pub shared_buffer: Arc<Mutex<Vec<u32>>>,
179    pub event_queue: Arc<Mutex<Vec<AppEvent>>>,
180    pub is_alive: Arc<AtomicBool>,
181    pub active_tab: Arc<Mutex<usize>>,
182    pub tabs: Arc<Mutex<Vec<String>>>,
183    /// `App::live_title` の写し(`app_runner_entry` が更新する)。
184    pub live_title: Arc<Mutex<Option<String>>>,
185    pub needs_timer_redraw: Arc<AtomicBool>,
186    /// app_runner_entry 側が shared_buffer を更新したらセットされるフラグ。
187    /// Core 0 の dirty 判定がこれを読んでウィンドウ矩形を dirty 登録し、クリアする。
188    pub buffer_updated: Arc<AtomicBool>,
189    /// アプリのスレッドが 1 周(イベントの処理+描画)を始めた最後の時刻(ms。0 はまだ)。
190    /// OS 側はこれで「返ってこないアプリ」を見分け、止める入口を出す(TODO R2 (a)。[`App::unresponsive_ms`])。
191    pub heartbeat_ms: Arc<core::sync::atomic::AtomicU64>,
192    /// 「このタブだけ止める」の合図(タブの番号+1。0 は無し。TODO R2 (d)、2026-11-18)。OS 側が書き、アプリのスレッドが読んで倒す。
193    pub tab_kill: Arc<AtomicUsize>,
194    /// アプリのスレッドが今動かしているタブの番号(アプリのスレッドが書く。TODO R2 (d))。
195    pub running_tab: Arc<AtomicUsize>,
196    /// 錠(`event_queue`)が取れずにまだ渡せていない入力。OS 側だけが持つ(TODO R4 (b)、2026-11-17)。
197    /// 次の周の [`App::os_tick`] か、次の入力のときに来た順のまま渡す。
198    pending: crate::kernel::pending_events::PendingEvents<AppEvent>,
199    /// 錠が取れずにまだ書けていないタブの切り替え先(`active_tab` へ書く値)。
200    deferred_active: Option<usize>,
201    /// 錠が取れないときに返す、最後に読めた写し(題名・タブ・選んでいるタブ)。
202    cached_title: Option<String>,
203    cached_tabs: Vec<String>,
204    cached_active: usize,
205}
206
207/// アプリのスレッドと共有する錠を、OS 側が待たずに取る(TODO R4 (b)、2026-11-17)。
208/// アプリ側は錠を短く持つだけ(中身の入れ替え・写し)なので、少しだけ取り直す。取れなければ `None`
209/// (呼び出し側は写しを使うか、次の周に回す)。持ったまま切り替えられていても、待つのはここの数十回だけ。
210fn try_lock_briefly<T>(m: &Mutex<T>) -> Option<spin::MutexGuard<'_, T>> {
211    for _ in 0..32 {
212        if let Some(g) = m.try_lock() {
213            return Some(g);
214        }
215        core::hint::spin_loop();
216    }
217    None
218}
219
220fn is_resize_event(e: &AppEvent) -> bool {
221    matches!(e, AppEvent::Resize { .. })
222}
223
224impl ProxyApp {
225    /// 控えた入力をアプリのキューへ渡す。錠が取れなければ控えたまま(次の周に渡す)。
226    fn flush_pending(&mut self) {
227        if self.pending.is_empty() {
228            return;
229        }
230        if !self.is_alive.load(Ordering::Relaxed) {
231            // アプリが止まった。渡す先が無いので捨てる。
232            self.pending.clear();
233            return;
234        }
235        if let Some(mut q) = try_lock_briefly(&self.event_queue) {
236            self.pending.flush_into(&mut q, is_resize_event);
237        }
238    }
239
240    /// 入力を来た順のまま渡す。控えが残っていれば、その後ろに並べてから渡す(追い越さない)。
241    fn deliver(&mut self, ev: AppEvent) {
242        self.pending.push(ev);
243        self.flush_pending();
244    }
245}
246
247impl ProxyApp {
248    pub fn new(
249        name: &str,
250        shared_buffer: Arc<Mutex<Vec<u32>>>,
251        event_queue: Arc<Mutex<Vec<AppEvent>>>,
252        is_alive: Arc<AtomicBool>,
253        active_tab: Arc<Mutex<usize>>,
254        tabs: Arc<Mutex<Vec<String>>>,
255        live_title: Arc<Mutex<Option<String>>>,
256        needs_timer_redraw: Arc<AtomicBool>,
257        buffer_updated: Arc<AtomicBool>,
258    ) -> Self {
259        // 写しの初期値(アプリのスレッドはまだ動いていないので普通は取れる。取れなければ空)。
260        let cached_title = live_title.try_lock().and_then(|t| t.clone());
261        let cached_tabs = tabs.try_lock().map(|t| t.clone()).unwrap_or_default();
262        let cached_active = active_tab.try_lock().map(|a| *a).unwrap_or(0);
263        Self {
264            name: String::from(name),
265            shared_buffer,
266            event_queue,
267            is_alive,
268            active_tab,
269            tabs,
270            live_title,
271            needs_timer_redraw,
272            buffer_updated,
273            heartbeat_ms: Arc::new(core::sync::atomic::AtomicU64::new(0)),
274            tab_kill: Arc::new(AtomicUsize::new(0)),
275            running_tab: Arc::new(AtomicUsize::new(cached_active)),
276            pending: crate::kernel::pending_events::PendingEvents::new(),
277            deferred_active: None,
278            cached_title,
279            cached_tabs,
280            cached_active,
281        }
282    }
283}
284
285impl App for ProxyApp {
286    fn name(&self) -> &str {
287        &self.name
288    }
289
290    fn is_proxy(&self) -> bool {
291        true
292    }
293
294    fn get_shared_buffer(&self) -> Option<alloc::sync::Arc<spin::Mutex<alloc::vec::Vec<u32>>>> {
295        Some(self.shared_buffer.clone())
296    }
297
298    fn draw(&mut self, _screen: &Screen, _win_x: u32, _win_y: u32, _win_w: u32, _win_h: u32) {
299        // ProxyApp 自体の draw() は、Core 0 側の draw_windows で ProxyApp を検知して
300        // 特殊な memcpy 処理を行うため、ここでは何もしない(あるいは no-op)。
301    }
302
303    // 【2026-11-17 TODO R4 (b)】ここから下は OS 側(メインループ)から呼ばれる。アプリのスレッドと共有する錠は
304    // 待たない(`try_lock_briefly`)。入力は取れなければ控えて次の周に渡し、読み出しは最後に読めた写しを返す。
305    fn on_mouse(&mut self, local_x: i32, local_y: i32, btn_left: bool, btn_right: bool, wheel: i32) {
306        self.deliver(AppEvent::Mouse {
307            local_x,
308            local_y,
309            btn_left,
310            btn_right,
311            wheel,
312        });
313    }
314
315    fn on_key(&mut self, keycode: u8, pressed: bool, ascii: Option<char>) {
316        self.deliver(AppEvent::Key {
317            keycode,
318            pressed,
319            ascii,
320        });
321    }
322
323    fn live_title(&self) -> Option<alloc::string::String> {
324        match self.live_title.try_lock() {
325            Some(t) => t.clone(),
326            None => self.cached_title.clone(),
327        }
328    }
329
330    fn tabs(&self) -> alloc::vec::Vec<alloc::string::String> {
331        match self.tabs.try_lock() {
332            Some(t) => t.clone(),
333            None => self.cached_tabs.clone(),
334        }
335    }
336
337    fn active_tab(&self) -> usize {
338        // 切り替えをまだ書けていなければ、切り替え先を返す(画面は利用者の操作どおりに見せる)。
339        if let Some(idx) = self.deferred_active {
340            return idx;
341        }
342        match self.active_tab.try_lock() {
343            Some(a) => *a,
344            None => self.cached_active,
345        }
346    }
347
348    fn switch_tab(&mut self, idx: usize) {
349        self.cached_active = idx;
350        match try_lock_briefly(&self.active_tab) {
351            Some(mut a) => {
352                *a = idx;
353                self.deferred_active = None;
354            }
355            None => self.deferred_active = Some(idx),
356        }
357        self.deliver(AppEvent::SwitchTab(idx));
358    }
359
360    fn add_tab(&mut self) {
361        self.deliver(AppEvent::AddTab);
362    }
363
364    fn open_url_in_new_tab(&mut self, url: &str) {
365        self.deliver(AppEvent::OpenUrl(String::from(url)));
366    }
367
368    fn close_tab(&mut self, idx: usize) -> bool {
369        self.deliver(AppEvent::CloseTab(idx));
370        self.tabs().len() <= 1
371    }
372
373    fn needs_timer_redraw(&self) -> bool {
374        self.needs_timer_redraw.load(Ordering::Relaxed)
375    }
376
377    fn get_buffer_updated_flag(&self) -> Option<alloc::sync::Arc<core::sync::atomic::AtomicBool>> {
378        Some(self.buffer_updated.clone())
379    }
380
381    fn on_resize(&mut self, width: u32, height: u32) {
382        // 大きさの変更は最後の 1 つだけ残す(控えの中・アプリのキューの中の古い物を外す)。
383        self.pending.push_replacing(AppEvent::Resize { width, height }, is_resize_event);
384        self.flush_pending();
385    }
386
387    fn os_tick(&mut self) {
388        self.flush_pending();
389        if let Some(idx) = self.deferred_active {
390            if let Some(mut a) = self.active_tab.try_lock() {
391                *a = idx;
392                self.deferred_active = None;
393            }
394        }
395        // 写しを取り直す(取れなければ前の写しのまま)。
396        if let Some(t) = self.live_title.try_lock() {
397            if *t != self.cached_title {
398                self.cached_title = t.clone();
399            }
400        }
401        if let Some(t) = self.tabs.try_lock() {
402            if *t != self.cached_tabs {
403                self.cached_tabs = t.clone();
404            }
405        }
406        if self.deferred_active.is_none() {
407            if let Some(a) = self.active_tab.try_lock() {
408                self.cached_active = *a;
409            }
410        }
411    }
412
413    fn is_stopped(&self) -> bool {
414        // `ProxyApp` が生きている間に偽になるのは、アプリのスレッドが止まって(`drop_runner_of_dead_process`)
415        // 合図を倒したときだけ。
416        !self.is_alive.load(Ordering::Relaxed)
417    }
418
419    fn unresponsive_ms(&self) -> Option<u64> {
420        if self.is_stopped() {
421            return None;
422        }
423        let last = self.heartbeat_ms.load(Ordering::Relaxed);
424        if last == 0 {
425            return None;
426        }
427        let gap = crate::kernel::timer::get_system_time_ms().saturating_sub(last);
428        (gap >= UNRESPONSIVE_MS).then_some(gap)
429    }
430
431    fn kill_tab(&mut self, idx: usize) -> bool {
432        if self.is_stopped() {
433            return false;
434        }
435        // 錠は取らない(アトミックの書き込み 1 回)。アプリが応答していなくても届く。
436        self.tab_kill.store(idx + 1, Ordering::Release);
437        true
438    }
439
440    fn running_tab(&self) -> usize {
441        self.running_tab.load(Ordering::Relaxed)
442    }
443
444    fn tab_kill_pending(&self) -> Option<usize> {
445        self.tab_kill.load(Ordering::Acquire).checked_sub(1)
446    }
447}
448
449/// アプリのスレッドの 1 周がこれより長く返らなければ「応答なし」として、ウィンドウに止める入口(Delete)を出す(TODO R2 (a))。
450/// YouTube の視聴ページの読み込みでは 1 回の描画が 18〜36 秒かかるので、その間も出る(止めるかは利用者が決める。
451/// 出すだけでは何も止めない)。
452pub const UNRESPONSIVE_MS: u64 = 10_000;
453
454impl Drop for ProxyApp {
455    fn drop(&mut self) {
456        self.is_alive.store(false, Ordering::Relaxed);
457    }
458}
459
460pub struct AppRunnerParams {
461    pub app: Box<dyn App>,
462    pub shared_buffer: Arc<Mutex<Vec<u32>>>,
463    pub event_queue: Arc<Mutex<Vec<AppEvent>>>,
464    pub is_alive: Arc<AtomicBool>,
465    pub active_tab: Arc<Mutex<usize>>,
466    pub tabs: Arc<Mutex<Vec<String>>>,
467    pub live_title: Arc<Mutex<Option<String>>>,
468    pub needs_timer_redraw: Arc<AtomicBool>,
469    /// shared_buffer 更新通知フラグ(Core 0 への dirty 伝達用)
470    pub buffer_updated: Arc<AtomicBool>,
471    /// `ProxyApp::heartbeat_ms` と同じ物(1 周の始まりで書く)。
472    pub heartbeat_ms: Arc<core::sync::atomic::AtomicU64>,
473    /// `ProxyApp::tab_kill`・`ProxyApp::running_tab` と同じ物(TODO R2 (d))。
474    pub tab_kill: Arc<AtomicUsize>,
475    pub running_tab: Arc<AtomicUsize>,
476    pub width: u32,
477    pub height: u32,
478}
479
480/// アプリのスレッドが描いている共有バッファ(画面へ出すウィンドウのバッファ)。
481/// 動画の再生スレッドが、アプリの描画が詰まっている間もフレームを直接書くために使う
482/// (`web_engine::video` の動画レイヤ)。
483#[derive(Clone)]
484pub struct DrawTarget {
485    pub buffer: Arc<Mutex<Vec<u32>>>,
486    pub width: u32,
487    pub height: u32,
488    pub updated: Arc<AtomicBool>,
489}
490
491/// プロセス ID → そのアプリのスレッドの描画先。`app_runner_entry` が登録・更新・削除する。
492static DRAW_TARGETS: Mutex<alloc::collections::BTreeMap<usize, DrawTarget>> =
493    Mutex::new(alloc::collections::BTreeMap::new());
494
495/// 今のスレッド(アプリの描画中)の描画先。
496pub fn current_draw_target() -> Option<DrawTarget> {
497    let pid = crate::kernel::scheduler::get_current_process_id()?;
498    DRAW_TARGETS.lock().get(&pid).cloned()
499}
500
501fn register_draw_target(params: &AppRunnerParams, w: u32, h: u32) {
502    if let Some(pid) = crate::kernel::scheduler::get_current_process_id() {
503        DRAW_TARGETS.lock().insert(
504            pid,
505            DrawTarget { buffer: params.shared_buffer.clone(), width: w, height: h, updated: params.buffer_updated.clone() },
506        );
507    }
508}
509
510/// 動いているアプリのスレッドの `AppRunnerParams`(プロセス ID+1 → ポインタ)。
511///
512/// 【2026-10-27】panic したスレッドは巻き戻し無しで止まり(`scheduler::exit`)、デストラクタが
513/// 走らない。アプリ(ブラウザなら `WebEngine`・JS 実行環境)がそのまま残り、ヒープが数百 MB
514/// 減らなかった(QEMU で確保失敗の panic 後も 384MB)。panic ハンドラがここから取り出して解放する
515/// ([`drop_runner_of_dead_process`])。panic ハンドラから使うのでロックを取らない固定長の表にする。
516const MAX_RUNNERS: usize = 16;
517static RUNNER_PIDS: [AtomicUsize; MAX_RUNNERS] = [const { AtomicUsize::new(0) }; MAX_RUNNERS];
518static RUNNER_PARAMS: [AtomicUsize; MAX_RUNNERS] = [const { AtomicUsize::new(0) }; MAX_RUNNERS];
519
520fn register_runner(pid: usize, params: *mut AppRunnerParams) {
521    for (row, (slot, ptr)) in RUNNER_PIDS.iter().zip(RUNNER_PARAMS.iter()).enumerate() {
522        if slot.compare_exchange(0, pid + 1, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
523            // 前の持ち主の消し忘れの欄を、このアプリを止めたときに誤って解放しないよう空ける(TODO R2 (c) ③)。
524            KILL_DROPS.reset_row(row);
525            ptr.store(params as usize, Ordering::Release);
526            return;
527        }
528    }
529    // 表が埋まっていたら登録しない(panic 時に回収されないだけで、動作は従来どおり)。
530}
531
532/// アプリのスレッドの関数の中の大きな物(組み立て中の DOM・レイアウトの木など)を、止めるときに解放するための欄
533/// (TODO R2 (c) ③、2026-11-18。`kernel/kill_drop.rs`)。行の番号は上の表の番号と同じ。
534static KILL_DROPS: crate::kernel::kill_drop::KillDropTable = crate::kernel::kill_drop::KillDropTable::new();
535
536/// 今のスレッドがアプリのスレッド本人なら、その表の番号。
537fn current_runner_row() -> Option<usize> {
538    let pid = crate::kernel::scheduler::get_current_process_id()?;
539    RUNNER_PIDS.iter().zip(RUNNER_PARAMS.iter()).position(|(slot, ptr)| {
540        slot.load(Ordering::Acquire) == pid + 1 && ptr.load(Ordering::Acquire) != 0
541    })
542}
543
544/// `value` を、アプリのスレッドを止めたときにも解放される箱に入れる(TODO R2 (c) ③、2026-11-18)。
545///
546/// アプリのスレッドは巻き戻し無しで終わるので、関数の中の変数が持つ物は解放されない。長い処理
547/// (止める確かめ `kill_checkpoint` を中で呼ぶ処理)の間、大きな物を持つ変数はこれに入れる。
548/// アプリのスレッド以外で呼んだときは、ふつうの箱として振る舞う。ほかのスレッドへは渡せない(`Send` でない)。
549/// 負担: 箱の確保 1 回と、実行キューの `try_lock` 1 回・16 行の表の読み出し。
550pub fn kill_owned<T>(value: T) -> crate::kernel::kill_drop::KillOwned<T> {
551    crate::kernel::kill_drop::KillOwned::new_in(&KILL_DROPS, current_runner_row(), value)
552}
553
554/// `pid` がアプリのスレッド(`app_runner`)か。錠を取らず、固定長の表をアトミックに読むだけ(TODO R3、`kernel::sync_fetch`)。
555pub fn is_app_runner_pid(pid: usize) -> bool {
556    pid != 0 && RUNNER_PIDS.iter().any(|slot| slot.load(Ordering::Acquire) == pid + 1)
557}
558
559/// プロセス `pid` の登録を外し、その `AppRunnerParams` のポインタと表の番号を返す。
560fn unregister_runner(pid: usize) -> Option<(*mut AppRunnerParams, usize)> {
561    for (row, (slot, ptr)) in RUNNER_PIDS.iter().zip(RUNNER_PARAMS.iter()).enumerate() {
562        if slot.load(Ordering::Acquire) == pid + 1 {
563            let p = ptr.swap(0, Ordering::AcqRel);
564            slot.store(0, Ordering::Release);
565            return (p != 0).then_some((p as *mut AppRunnerParams, row));
566        }
567    }
568    None
569}
570
571/// panic したプロセス `pid` がアプリのスレッドなら、そのアプリを解放する(panic ハンドラが
572/// `scheduler::exit` の直前に呼ぶ)。ウィンドウ側の `ProxyApp` は最後の画面を出したまま残る。
573///
574/// # Safety
575/// 呼び出し元のスレッド(`pid`)は二度と再開しないこと。死ぬスレッドのスタックには解放する
576/// アプリへの参照が残っているが、そのフレームには戻らない。アプリの Drop が取るロック
577/// (確保・JS の循環回収の台帳)は、呼ぶ前に強制解放しておくこと。
578pub unsafe fn drop_runner_of_dead_process(pid: usize) {
579    let Some((p, row)) = unregister_runner(pid) else { return };
580    // 解放の間、「このスレッドは片付けの最中」の印を立てる([`tearing_down_current_thread`])。
581    TEARDOWN_PID.store(pid + 1, Ordering::Release);
582    let _ = KILL_UNWIND_PID.compare_exchange(pid + 1, 0, Ordering::AcqRel, Ordering::Relaxed);
583    let before = crate::kernel::allocator::get_heap_stats().0;
584    // 【2026-11-18 TODO R2 (c) ③】関数の中の変数が持っていた大きな物(`kill_owned` に入れた物)を先に解放する。
585    // 登録を外した後なので、ここで解放する物のデストラクタが止める確かめを呼んでも、もう一度止めには入らない。
586    // SAFETY: このスレッド(`pid`)は二度と再開しない(呼び出し元の約束)。錠は呼び出し元が外した。
587    let stack_objs = unsafe { KILL_DROPS.drain(row) };
588    let mid = crate::kernel::allocator::get_heap_stats().0;
589    // SAFETY: `app_runner_entry` が `Box::into_raw` から受け取ったもので、登録を外したので二重には解放しない。
590    let params = unsafe { Box::from_raw(p) };
591    params.is_alive.store(false, Ordering::Relaxed);
592    drop(params);
593    TEARDOWN_PID.store(0, Ordering::Release);
594    if let Some(mut t) = DRAW_TARGETS.try_lock() {
595        t.remove(&pid);
596    }
597    let after = crate::kernel::allocator::get_heap_stats().0;
598    // メモリの帳簿の組を閉じる(TODO R5。解放の後に閉じるので、解放の分はこの組から引かれている)。
599    // 組が閉じたことが、同じ組の背景のスレッドへの止まる合図になる(TODO R2 (c))。
600    let closed = crate::kernel::allocator::MEM_LEDGER.close_group_of(pid);
601    // 【2026-11-18 TODO R2 (c) ③】組の残り=この組のスレッドが確保して、まだだれも(この組では)解放していない量。
602    // 止めた後もヒープが戻らないとき、残りがこの組に付いたままか(止めたスレッドのスタックの上の物・置き場へ渡した物)を見る。
603    let left = closed.map(|g| crate::kernel::allocator::MEM_LEDGER.bytes_of(g)).unwrap_or(0);
604    crate::warn!(
605        "[WM] 止まったアプリ(PID {})を解放: ヒープ {}MB → {}MB(途中の物 {} 個で {}MB、アプリ本体 {}MB)、組の残り {}MB",
606        pid,
607        before >> 20,
608        after >> 20,
609        stack_objs,
610        before.saturating_sub(mid) >> 20,
611        mid.saturating_sub(after) >> 20,
612        left >> 20
613    );
614    if let Some(g) = closed {
615        on_group_closed(g, pid);
616    }
617}
618
619/// 止めたアプリの片付け([`drop_runner_of_dead_process`])をしているスレッドのプロセス ID + 1(0 は無し。TODO R5 (c)、2026-11-18)。
620static TEARDOWN_PID: AtomicUsize = AtomicUsize::new(0);
621
622/// 今のスレッドが、止めたアプリの片付けの最中か(TODO R5 (c)、2026-11-18)。
623///
624/// 片付けは止まるスレッド自身の上で行い、そのスレッドは二度と再開しない。なのでこの間は、スタックの上に残った
625/// 借用(`RefCell` の借用の印・写した `Rc`)の持ち主はもう動かない。アプリ本体の `Drop` は、これが真なら
626/// 借用中の印が残っていても中身を捨ててよい(`JsRuntime` の DOM ブリッジ)。負担: アトミックの読み出し 1 回と、プロセス ID の読み出し。
627pub fn tearing_down_current_thread() -> bool {
628    let t = TEARDOWN_PID.load(Ordering::Acquire);
629    t != 0 && crate::kernel::scheduler::get_current_process_id().map(|p| p + 1) == Some(t)
630}
631
632/// 閉じた組の後の量を、5 秒後と 20 秒後に 1 行ずつ出すための控え(TODO R2 (c) ③⑤、2026-11-18)。
633/// 組の番号(0 は無し)・閉じた時刻(ms)・出した回数。最後に閉じた 1 組だけを見る。
634static CLOSE_PROBE_GROUP: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0);
635static CLOSE_PROBE_AT_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
636static CLOSE_PROBE_STAGE: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0);
637
638/// OS のメインループが毎周呼ぶ(TODO R2 (c) ③⑤、2026-11-18)。アプリの組を閉じてから 5 秒後と 20 秒後に、
639/// ヒープの使用量と、閉じた組にまだ付いている量を 1 行ずつ出す。ふだんはアトミックの読み出し 1 回だけ。
640pub fn report_closed_group_memory(now_ms: u64) {
641    let g = CLOSE_PROBE_GROUP.load(Ordering::Relaxed);
642    if g == 0 {
643        return;
644    }
645    let at = CLOSE_PROBE_AT_MS.load(Ordering::Relaxed);
646    let stage = CLOSE_PROBE_STAGE.load(Ordering::Relaxed);
647    let wait_ms = if stage == 0 { 5_000 } else { 20_000 };
648    if now_ms.saturating_sub(at) < wait_ms {
649        return;
650    }
651    let ledger = &crate::kernel::allocator::MEM_LEDGER;
652    let used = crate::kernel::allocator::get_heap_stats().0;
653    // 番号が新しいアプリに配り直されていたら、組の量は 0 から数え直しになっているので出さない。
654    if ledger.is_closed(g) {
655        crate::warn!(
656            "[WM] 閉じた組 {} の {} 秒後: ヒープ {}MB、組の残り {}MB",
657            g,
658            wait_ms / 1000,
659            used >> 20,
660            ledger.bytes_of(g) >> 20
661        );
662    } else {
663        crate::warn!("[WM] 閉じた組 {} の {} 秒後: ヒープ {}MB(組は配り直し済み)", g, wait_ms / 1000, used >> 20);
664    }
665    if stage == 0 {
666        CLOSE_PROBE_STAGE.store(1, Ordering::Relaxed);
667    } else {
668        CLOSE_PROBE_GROUP.store(0, Ordering::Relaxed);
669    }
670}
671
672/// いちばん新しい強制終了の要求の時刻(ms。0 は「無い」)。止まるまでにかかった時間を記録に出すため。
673static LAST_KILL_REQUEST_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
674
675/// 今のスレッドが「止めたアプリ」の物か(TODO R2 (c)、2026-11-17 続報)。
676///
677/// アプリを止めると(強制終了・メモリの上限・panic・ウィンドウを閉じた後の正常終了)、そのアプリの組
678/// (`Process::mem_group`)が閉じる。そのアプリが起こした背景のスレッド(動画・音声の補給など)と、
679/// そのアプリの要求を処理している最中の共有のワーカー(組を借りている)は、同じ組のままなのでここが真になる。
680///
681/// 負担: コア番号の読み出しと、アトミックの読み出し 2 回(今のコアの組・その組の持ち主)。錠は取らない。
682#[inline]
683pub fn current_group_stopped() -> bool {
684    let ledger = &crate::kernel::allocator::MEM_LEDGER;
685    ledger.is_closed(ledger.core_group(crate::kernel::scheduler::core_id()))
686}
687
688/// 今のスレッドの組(`kernel/mem_quota.rs`。0 は OS 側)。大域の置き場に入れる物に、持ち主のアプリの印として添える。
689#[inline]
690pub fn current_group() -> u8 {
691    crate::kernel::allocator::MEM_LEDGER.core_group(crate::kernel::scheduler::core_id())
692}
693
694/// 組 `g` のアプリが止まったか(共有のワーカーが、積まれた要求を捨てるか決めるのに使う)。
695#[inline]
696pub fn group_stopped(g: u8) -> bool {
697    crate::kernel::allocator::MEM_LEDGER.is_closed(g)
698}
699
700/// 今のスレッドが止まるべきか: アプリのスレッド本人に強制終了の合図が立っている([`app_kill_pending`])か、
701/// 止めたアプリの組のスレッド([`current_group_stopped`])か。
702///
703/// 通信の待ち(`tls::TcpIoWrapper::read`・`net::http` の受信待ち)がこれを見て、待ちをやめる。
704/// アプリのスレッドならその場で終わらせ([`abort_wait_if_stopped`])、背景のスレッドなら失敗として返し、
705/// 呼び出し元が普通の失敗の経路で後片付けをして(接続を閉じる・確保を解放する)自分から終わる。
706pub fn kill_pending_for_current() -> bool {
707    current_group_stopped()
708        || app_kill_pending()
709        || tab_kill_pending_for_current()
710        || crate::os_lib::web_apis::builtins::xhr_cancelled_for_current()
711}
712
713/// 通信の待ちの中で呼ぶ(TODO R2 (c))。
714/// - 今のスレッドがアプリのスレッドで強制終了の合図が立っていれば、`close` で接続を閉じてからスレッドを終わらせる(戻らない)。
715/// - 止めたアプリの組のスレッドなら `true`(呼び出し元は失敗として返す。ここでは閉じない。接続を持っている側が
716///   落とすときに閉じる〔`tls::PooledConn` の `Drop`〕。二重に閉じると「socket not found」の警告が出る)。
717/// - どちらでもなければ `false`。
718pub fn abort_wait_if_stopped(close: impl FnOnce()) -> bool {
719    if current_group_stopped() {
720        // アプリのスレッド本人の組が閉じるのは、本人が終わる最中だけ(`drop_runner_of_dead_process` の後)。
721        return true;
722    }
723    // 【2026-11-18 TODO R2 (d) ③】XHR のワーカーが取っている要求のタブが閉じられた・止められた(`abort()` も)。
724    // 止めたアプリの背景のスレッドと同じく失敗として返す(接続は持ち主が落とすときに閉じる)。ワーカーは次の要求へ移る。
725    if crate::os_lib::web_apis::builtins::xhr_cancelled_for_current() {
726        return true;
727    }
728    if app_kill_pending() {
729        close();
730        terminate_current_app_thread("受信の待ちの途中");
731    }
732    // 【2026-11-18 TODO R2 (d)】今動いているタブだけを止めるときは、スレッドは終わらせず失敗として返す
733    // (呼び出し元が普通の失敗の経路で後片付けをし、JS は次の確かめで打ち切られる)。
734    tab_kill_pending_for_current()
735}
736
737/// 今のスレッドがアプリのスレッドで、そのアプリがもう要らない(ウィンドウ・タブが閉じられた/強制終了された)か。
738///
739/// 錠を取らない(固定長の表とアトミックだけを読む)。プロセス ID が取れなかったとき(実行キューが競合中)は
740/// false(次の確認で見る)。
741pub fn app_kill_pending() -> bool {
742    current_runner_params().is_some_and(|p| !p.is_alive.load(Ordering::Relaxed))
743}
744
745/// 今のスレッドがアプリのスレッド本人なら、その `AppRunnerParams`(錠を取らず、固定長の表を読むだけ)。
746fn current_runner_params() -> Option<&'static AppRunnerParams> {
747    let pid = crate::kernel::scheduler::get_current_process_id()?;
748    for (slot, ptr) in RUNNER_PIDS.iter().zip(RUNNER_PARAMS.iter()) {
749        if slot.load(Ordering::Acquire) == pid + 1 {
750            let p = ptr.load(Ordering::Acquire) as *const AppRunnerParams;
751            // SAFETY: この表の中身は、登録したスレッド自身(=今のスレッド)が外すまで有効。
752            // ほかのスレッドが外すのは panic の回収だけで、それは当のスレッドの上で動く。
753            // 返す参照は今のスレッドの中だけで使う(ほかのスレッドへ渡さない)。
754            return unsafe { p.as_ref() };
755        }
756    }
757    None
758}
759
760/// 今のスレッドがアプリのスレッドで、そのアプリが今動かしているタブに「このタブだけ止める」の合図が
761/// 立っているか(TODO R2 (d)、2026-11-18)。
762///
763/// JS の処理系は 32,768 ステップごとにこれを見て、真なら今のスクリプトを打ち切る(`try`/`catch` では捕まらない。
764/// ステップの上限で打ち切るのと同じ道)。受信の待ちも失敗として返す([`kill_pending_for_current`])。
765/// タブはアプリのスレッドの 1 周の頭で閉じる(`take_tab_kill`)。
766/// 負担: 実行キューの `try_lock` 1 回・16 行の表の読み出し・アトミックの読み出し 2 回。
767pub fn tab_kill_pending_for_current() -> bool {
768    let Some(p) = current_runner_params() else { return false };
769    let k = p.tab_kill.load(Ordering::Acquire);
770    k != 0 && k - 1 == p.running_tab.load(Ordering::Relaxed)
771}
772
773/// 「タブだけ止める」の要求があった時刻(ms。0 は無し)。レイアウトの長いループが毎回見る関門([`layout_aborting`])。
774/// [`LAST_TAB_KILL_REQUEST_MS`] と違ってタブを閉じても 0 に戻さない(別の窓の要求を消さないため)。要求から
775/// [`TAB_KILL_GATE_MS`] の間だけ開き、その間だけ今のスレッドのタブに合図が立っているかを確かめる(2026-11-18)。
776static TAB_KILL_GATE_AT_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
777/// 関門を開けておく長さ(ms)。これより長くレイアウトが続いたら、レイアウトは最後まで走ってからタブを閉じる(今までどおり)。
778const TAB_KILL_GATE_MS: u64 = 60_000;
779/// レイアウトの長いループの回数の数え(全部のスレッドで共有。[`layout_poll`])。
780static LAYOUT_POLLS: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
781/// [`layout_poll`] が [`kill_checkpoint`] を呼ぶ間隔(回。2 の冪)。1 回は要素 1 つ分のスタイル・箱・要素の組み立て。
782const LAYOUT_POLL_EVERY: u32 = 64;
783
784/// レイアウトの長いループ(スタイルの計算・箱の組み立て・要素の組み立て・折り返し)の 1 回ごとに呼ぶ
785/// (TODO R2 (b) ②・(d) ①、2026-11-18)。
786///
787/// - [`LAYOUT_POLL_EVERY`] 回に 1 回 [`kill_checkpoint`] を呼ぶ。ウィンドウごと止める要求ならここで終わる(戻らない)。
788/// - 戻り値: 今動かしているタブだけを止める合図が立っていれば `true`([`layout_aborting`])。呼び出し側は
789///   残りの子を飛ばして戻る(巻き戻しはしない。途中までの木は普通の値として返り、タブごと捨てられる)。
790///
791/// 呼ぶ所の決まりは [`kill_checkpoint`] と同じ(錠を持ったまま呼ばない)。呼んでいるのは `parse_and_layout` の中の
792/// 再帰の入口・子のループの頭だけで、そこでは錠を持っていない(入口の `parse_and_layout` も同じ錠の状況で
793/// `kill_checkpoint` を呼んでいる)。背景のスレッド・OS のメインループでは、[`kill_checkpoint`] は何もしない。
794///
795/// 負担: 普段はアトミックの足し算 1 回と読み出し 1 回。64 回に 1 回 [`kill_checkpoint`](実行キューの `try_lock`・表の読み出し)。
796///
797/// 【2026-11-18 TODO R5 (c)】ウィンドウごと止める要求(強制終了・ウィンドウを閉じた)は、ここでは終わらせず
798/// `true` を返して再帰を普通に戻らせる([`layout_kill_unwind_check`])。再帰の途中で終わらせると、作りかけの
799/// スタイルの木・箱の木(関数の中の変数)が解放されずに残っていた(20 万ノードのページのスタイルの計算の途中で
800/// 止めて約 170MB)。戻った先の `parse_and_layout`(大きな物は `kill_owned` の箱)で [`kill_checkpoint`] が終わらせる。
801#[inline]
802pub fn layout_poll() -> bool {
803    let n = LAYOUT_POLLS.fetch_add(1, Ordering::Relaxed);
804    if n & (LAYOUT_POLL_EVERY - 1) == 0 && layout_kill_unwind_check() {
805        return true;
806    }
807    layout_aborting()
808}
809
810/// [`layout_poll`] の、毎回確かめる版。呼び出し側が自分で間引くループ(1 文字ずつのループを
811/// 4096 文字ごとに呼ぶ折り返しの計算など)で使う。戻り値は [`layout_poll`] と同じ。
812#[inline]
813pub fn layout_check() -> bool {
814    layout_kill_unwind_check() || layout_aborting()
815}
816
817/// レイアウトの再帰を戻らせている最中のアプリのスレッド(プロセス ID + 1。0 は無し)と、戻らせ始めた時刻(ms)。
818static KILL_UNWIND_PID: AtomicUsize = AtomicUsize::new(0);
819static KILL_UNWIND_AT_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
820/// 戻らせ始めてからこれだけ経っても [`kill_checkpoint`] に届かなければ、その場で終わらせる(戻り値を見ない呼び出し元への備え)。
821const KILL_UNWIND_MAX_MS: u64 = 2_000;
822
823/// レイアウトの確かめ([`layout_poll`]・[`layout_check`])の中身(TODO R5 (c)、2026-11-18)。
824///
825/// ウィンドウごと止める要求なら、印を立てて `true`(呼び出し側は途中でやめて戻る。[`layout_aborting`] も真になる)。
826/// メモリの上限([`mem_quota_checkpoint`])はこれまでどおりその場で終わらせる(戻らせると量が減って判定が外れ、
827/// 同じページの組み立てを繰り返すため)。
828fn layout_kill_unwind_check() -> bool {
829    if app_kill_pending() {
830        let me = crate::kernel::scheduler::get_current_process_id().map(|p| p + 1).unwrap_or(0);
831        let now = crate::kernel::timer::get_system_time_ms();
832        if me != 0 && KILL_UNWIND_PID.load(Ordering::Acquire) != me {
833            KILL_UNWIND_AT_MS.store(now, Ordering::Relaxed);
834            KILL_UNWIND_PID.store(me, Ordering::Release);
835        } else if now.saturating_sub(KILL_UNWIND_AT_MS.load(Ordering::Relaxed)) > KILL_UNWIND_MAX_MS {
836            kill_checkpoint();
837        }
838        return true;
839    }
840    mem_quota_checkpoint();
841    false
842}
843
844/// 今のスレッドが、ウィンドウごと止める要求でレイアウトの再帰を戻らせている最中か。ふだんはアトミックの読み出し 1 回。
845#[inline]
846fn kill_unwinding_current() -> bool {
847    let t = KILL_UNWIND_PID.load(Ordering::Acquire);
848    t != 0 && crate::kernel::scheduler::get_current_process_id().map(|p| p + 1) == Some(t)
849}
850
851/// 今のスレッドのレイアウトをやめるべきか(このタブだけを止める合図。[`layout_poll`])。
852/// 普段(要求から 60 秒より後)はアトミックの読み出し 1 回で `false`。
853#[inline]
854pub fn layout_aborting() -> bool {
855    let at = TAB_KILL_GATE_AT_MS.load(Ordering::Relaxed);
856    (at != 0 && layout_aborting_slow(at)) || kill_unwinding_current()
857}
858
859#[cold]
860#[inline(never)]
861fn layout_aborting_slow(at: u64) -> bool {
862    crate::kernel::timer::get_system_time_ms().saturating_sub(at) < TAB_KILL_GATE_MS && tab_kill_pending_for_current()
863}
864
865/// いちばん新しい「タブだけ止める」の要求の時刻(ms。0 は無し)。閉じるまでにかかった時間を記録に出すため。
866static LAST_TAB_KILL_REQUEST_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
867
868/// アプリのスレッドの 1 周の頭で呼ぶ(TODO R2 (d)、2026-11-18)。「このタブだけ止める」の合図が立っていれば、
869/// そのタブを閉じる(ブラウザならそのタブの `WebEngine`・JS の実行環境を捨てる)。ほかのタブとウィンドウは残す。
870/// ここに来るのは、そのタブの JS が打ち切られて描画から戻った後(または止めるタブが動いていなかったとき)。
871fn take_tab_kill(params: &mut AppRunnerParams) {
872    let k = params.tab_kill.swap(0, Ordering::AcqRel);
873    let Some(idx) = k.checked_sub(1) else { return };
874    let asked = LAST_TAB_KILL_REQUEST_MS.swap(0, Ordering::Relaxed);
875    let waited = if asked == 0 { 0 } else { crate::kernel::timer::get_system_time_ms().saturating_sub(asked) };
876    let tabs = params.app.tabs();
877    if idx >= tabs.len() || tabs.len() <= 1 {
878        // 最後の 1 つは閉じない(ウィンドウを止めるのは OS 側の `kill_window`)。
879        crate::warn!("[WM] タブ {} を止める合図を捨てた(タブは {} 個)", idx, tabs.len());
880        return;
881    }
882    let name = tabs.get(idx).cloned().unwrap_or_default();
883    drop(tabs);
884    let ledger = &crate::kernel::allocator::MEM_LEDGER;
885    let g = current_group();
886    let before = crate::kernel::allocator::get_heap_stats().0;
887    let group_before = ledger.bytes_of(g);
888    let _ = params.app.close_tab(idx);
889    let after = crate::kernel::allocator::get_heap_stats().0;
890    let group_after = ledger.bytes_of(g);
891    let active = params.app.active_tab();
892    params.running_tab.store(active, Ordering::Relaxed);
893    crate::warn!(
894        "[WM] タブ {}({})だけを止めて閉じた(要求から {}ms): ヒープ {}MB → {}MB、このアプリの組 {} {}MB → {}MB、残りのタブ {} 個(表示はタブ {})",
895        idx,
896        name,
897        waited,
898        before >> 20,
899        after >> 20,
900        g,
901        group_before >> 20,
902        group_after >> 20,
903        params.app.tabs().len(),
904        active
905    );
906}
907
908/// アプリのスレッドの中の「ここでなら止めてよい」所で呼ぶ(TODO R2、2026-11-14)。
909///
910/// ウィンドウを閉じても、アプリのスレッドは 1 周(イベントの処理+描画)の終わりまで動き続けていた。
911/// JS の 1 個のタスクは最大 約 60 秒かかるので、閉じたはずのアプリが CPU とヒープを使い続けた。
912/// 長い処理の途中の、錠を持っていない所(JS が CPU を譲る 32,768 ステップごと・再レイアウトの入口・
913/// 受信の待ち)でこれを呼び、要らなくなっていたらその場でスレッドを終わらせる。
914///
915/// 呼ぶ所の決まり: `spin::Mutex` などの錠を持ったまま呼ばない(持ち主が居なくなり、以後だれも取れなくなる。
916/// 確保・ネットワーク・USB・ファイルシステム・JS の循環回収の錠だけは、このコアが持っていれば外す)。
917///
918/// 背景のスレッド(止めたアプリの組のスレッドを含む)はここでは終わらせない(TODO R2 (c)、2026-11-17 続報)。
919/// 背景のスレッドは巻き戻し無しで終わらせると、スタックの上の確保(復号器の状態・受信のバッファ・接続)が
920/// 解放されずに残り、共有の状態(動画の再生中の印・取得の枠・ワーカーの本数)も戻らない。背景のスレッドは
921/// [`current_group_stopped`](とそれを含む [`kill_pending_for_current`])を自分の区切りで見て、関数から戻る形で終わる。
922#[inline]
923pub fn kill_checkpoint() {
924    if app_kill_pending() {
925        terminate_current_app_thread("閉じられた/強制終了されたアプリ");
926    }
927    mem_quota_checkpoint();
928}
929
930/// アプリの組を閉じた直後に呼ぶ(3 つの経路: 強制終了・メモリの上限〔`terminate_app_thread_inner`〕、panic の回復
931/// 〔どちらも `drop_runner_of_dead_process`〕、ウィンドウを閉じた後の正常終了〔`app_runner_entry` の最後〕)。TODO R2 (c)。
932///
933/// - 同じ組の背景のスレッドは、組が閉じたこと([`current_group_stopped`])を自分で見て終わる。ここでは数と名前を記録に出す。
934/// - 共有のワーカーの待ち行列から、そのアプリの要求と届いた結果を捨てる(錠は `try_lock`。塞がっていれば
935///   ワーカーが取り出すときに捨てる)。
936///
937/// panic の回復からも呼ばれるので、待つ錠を取らない(実行キューも `try_lock`)。
938fn on_group_closed(g: u8, pid: usize) {
939    // 5 秒後・20 秒後の量を出す控え([`report_closed_group_memory`])。
940    CLOSE_PROBE_AT_MS.store(crate::kernel::timer::get_system_time_ms(), Ordering::Relaxed);
941    CLOSE_PROBE_STAGE.store(0, Ordering::Relaxed);
942    CLOSE_PROBE_GROUP.store(g, Ordering::Relaxed);
943    let ledger = &crate::kernel::allocator::MEM_LEDGER;
944    let left = ledger.threads_of(g);
945    let names: alloc::vec::Vec<alloc::string::String> = crate::kernel::scheduler::threads_in_group(g)
946        .into_iter()
947        .filter(|(p, _)| *p != pid)
948        .map(|(p, n)| alloc::format!("{}#{}", n, p))
949        .collect();
950    let (xq, xr) = crate::os_lib::web_apis::builtins::forget_xhr_of_group(g);
951    let (lq, iq, fq) = crate::os_lib::web_engine::forget_requests_of_group(g);
952    // 【2026-11-18 TODO R2 (c) ③】大域の置き場に残る、そのアプリのページの物を捨てる(錠は待たない)。
953    let heap0 = crate::kernel::allocator::get_heap_stats().0;
954    let memo = crate::os_lib::web_engine::forget_flatten_memo_of_closed_groups();
955    let imgs = crate::os_lib::web_engine::forget_shared_images_of_group(g);
956    let heap1 = crate::kernel::allocator::get_heap_stats().0;
957    let opt = |v: Option<usize>| v.map(|n| alloc::format!("{}", n)).unwrap_or_else(|| alloc::string::String::from("後で"));
958    crate::warn!(
959        "[WM] アプリ(PID {})の組 {} を閉じた: 背景のスレッド {} 本に止まる合図 [{}]、捨てた要求 XHR {} 件・結果 {} 件・ページ {} 件・画像 {} 件・フォント等 {} 件、置き場から捨てた 要素の写し {} 個・共有の画像 {} 枚({}MB)",
960        pid,
961        g,
962        left.saturating_sub(1),
963        names.join(", "),
964        xq,
965        xr,
966        lq,
967        iq,
968        fq,
969        opt(memo),
970        opt(imgs),
971        heap0.saturating_sub(heap1) >> 20
972    );
973}
974
975/// 背景のスレッド・共有のワーカー(アプリの組を借りている)が、大きな処理(ページの HTML の解析など)を
976/// 途中でやめるべきか(TODO R5 (c)、2026-11-18)。
977///
978/// 借りている組が閉じた(アプリを止めた)か、その組がメモリの上限を超えた・全体が尽きかけで一番多く持っている
979/// ([`crate::kernel::mem_quota::Ledger::verdict`])なら真。アプリのスレッド本人は [`kill_checkpoint`] で止まるが、
980/// ワーカーは止まる地点を通らないので、以前は 20MB のページの解析でヒープを使い切り、OS のスレッドまで確保に失敗していた。
981/// ここでは止めず、呼び出し側が作りかけの物を捨てて失敗を返す(アプリは次の確かめで上限の判定を受ける)。
982/// 負担: コア番号の読み出しと、アトミックの読み出し 3〜4 回。
983pub fn borrowed_group_should_stop() -> bool {
984    use crate::kernel::mem_quota::Verdict;
985    let ledger = &crate::kernel::allocator::MEM_LEDGER;
986    let g = ledger.core_group(crate::kernel::scheduler::core_id());
987    if g == 0 {
988        return false;
989    }
990    ledger.is_closed(g) || ledger.verdict(g, crate::kernel::allocator::heap_total()) != Verdict::Keep
991}
992
993/// アプリごとのメモリの上限(TODO R5、2026-11-17。判定は `kernel/mem_quota.rs`)。
994///
995/// [`kill_checkpoint`] から呼ぶ(錠を持っていない安全な地点)。今のスレッドの組がメモリを使いすぎていて、
996/// 今のスレッドがその組のアプリのスレッド(`app_runner`)なら、そのアプリを止める。背景のスレッド
997/// (XHR・画像・フォント・動画)は判定だけして何もしない(アプリのスレッドが次の確認で止まる)。
998///
999/// ふだんの負担: コア番号の読み出しと、アトミックの読み出し 3 回(組・量・尽きかけの印)。
1000#[inline]
1001fn mem_quota_checkpoint() {
1002    use crate::kernel::mem_quota::Verdict;
1003    let ledger = &crate::kernel::allocator::MEM_LEDGER;
1004    let g = ledger.core_group(crate::kernel::scheduler::core_id());
1005    if g == 0 {
1006        return;
1007    }
1008    let verdict = ledger.verdict(g, crate::kernel::allocator::heap_total());
1009    if verdict == Verdict::Keep {
1010        return;
1011    }
1012    let Some(pid) = crate::kernel::scheduler::get_current_process_id() else { return };
1013    if ledger.owner_of(g) != Some(pid) || !ledger.begin_kill(g) {
1014        return;
1015    }
1016    let own_mb = ledger.bytes_of(g) >> 20;
1017    let (used, total) = crate::kernel::allocator::get_heap_stats();
1018    let why = match verdict {
1019        Verdict::OverLimit => "1 つのアプリの上限を超えた",
1020        _ => "ヒープ全体が尽きかけ、一番多く使っていた",
1021    };
1022    crate::warn!(
1023        "[MEM] [QUOTA] アプリ(PID {}、組 {})を止める: {}(このアプリ {}MB / 上限 {}MB、ヒープ {}MB / {}MB)",
1024        pid,
1025        g,
1026        why,
1027        own_mb,
1028        crate::kernel::mem_quota::app_limit(total) >> 20,
1029        used >> 20,
1030        total >> 20
1031    );
1032    let notice = alloc::format!("Stopped: this app used too much memory ({} MB).", own_mb);
1033    terminate_app_thread_inner("メモリの使いすぎ", Some(&notice), Some(pid));
1034}
1035
1036/// 今のスレッド(アプリのスレッド)を、巻き戻し無しで終わらせる。アプリ本体(ブラウザなら `WebEngine`・
1037/// JS の実行環境)は解放する。panic からの復帰(`main.rs` の panic ハンドラ)と同じ手順。
1038pub fn terminate_current_app_thread(reason: &str) -> ! {
1039    terminate_app_thread_inner(reason, None, None)
1040}
1041
1042/// 止めたアプリのウィンドウに、止めた理由を書く(ウィンドウは最後の画面のまま残るので、その上に帯を描く)。
1043/// アプリ本体を解放した後に呼ぶ(メモリが空いてから描く)。描画先の錠が塞がっていたら描かない。
1044fn draw_stop_notice(target: &DrawTarget, line1: &str) {
1045    let Some(mut buf) = target.buffer.try_lock() else { return };
1046    let (w, h) = (target.width, target.height);
1047    // 左の 100px はタブの列で、OS 側が上から描く(`app_runner_entry` の `tab_w`)。その右に描く。
1048    const LEFT: u32 = 100;
1049    if buf.len() != (w as usize) * (h as usize) || w < LEFT + 40 || h < 120 {
1050        return;
1051    }
1052    let screen = Screen::new(buf.as_mut_ptr(), w, h, w * 4);
1053    screen.boxfill(LEFT, 36, w - 1, 110, Color(0xFF5A1E1E));
1054    screen.draw_string_vector(LEFT + 16, 48, line1, Color(0xFFFFFFFF), 16);
1055    screen.draw_string_vector(
1056        LEFT + 16,
1057        78,
1058        "The OS and other apps keep running. Close this window (Alt+W) and open it again.",
1059        Color(0xFFE0E0E0),
1060        13,
1061    );
1062    drop(buf);
1063    target.updated.store(true, Ordering::Release);
1064}
1065
1066/// 応答していないアプリのウィンドウ(`ProxyApp`)に、止める入口の帯を描く(TODO R2 (a)、2026-11-17 続報)。
1067/// 描く先はウィンドウのバッファ(`draw_all` の描画先)。左のタブの列(`app_x`)の右、題名の帯の下。
1068///
1069/// 【2026-11-18 TODO R2 (d)】タブが 2 つ以上なら、End で今動いているタブだけを止める案内も出す。
1070/// タブを止める合図を立てた後(`tab_kill`)は、閉じるのを待っていることと、閉じないときは Delete を出す。
1071fn draw_unresponsive_band(screen: &Screen, app_x: u32, w: u32, gap_ms: u64, tab_count: usize, tab_kill: Option<usize>) {
1072    if w < app_x + 40 {
1073        return;
1074    }
1075    let bottom = if tab_count > 1 { 120 } else { 100 };
1076    screen.boxfill(app_x, 36, w - 1, bottom, Color(0xFF5A1E1E));
1077    let line1 = alloc::format!("Not responding for {} s.", gap_ms / 1000);
1078    screen.draw_string_vector(app_x + 16, 44, &line1, Color(0xFFFFFFFF), 16);
1079    screen.draw_string_vector(
1080        app_x + 16,
1081        70,
1082        "Press Delete to stop this app (the OS and other apps keep running), or wait.",
1083        Color(0xFFE0E0E0),
1084        13,
1085    );
1086    if tab_count > 1 {
1087        let line3 = match tab_kill {
1088            Some(t) => alloc::format!(
1089                "Closing tab {}... If it does not close, press Delete to stop the whole window.",
1090                t + 1
1091            ),
1092            None => alloc::string::String::from("Press End to close only this tab (the other tabs keep running)."),
1093        };
1094        screen.draw_string_vector(app_x + 16, 92, &line3, Color(0xFFFFE0A0), 13);
1095    }
1096}
1097
1098fn terminate_app_thread_inner(reason: &str, notice: Option<&str>, known_pid: Option<usize>) -> ! {
1099    let cid = crate::kernel::scheduler::core_id() as i16;
1100    crate::kernel::allocator::force_release_lock(cid);
1101    crate::kernel::net::force_release_locks(cid);
1102    crate::kernel::usb::force_release_locks(cid);
1103    crate::kernel::fs::force_release_locks(cid);
1104    crate::os_lib::ecma::cycle_gc::force_release_lock(cid);
1105    // SAFETY: このスレッドは直後の `exit()` で止まり、二度と再開しない。
1106    unsafe { force_release_lock_of_current() };
1107    let pid = known_pid.or_else(crate::kernel::scheduler::get_current_process_id).unwrap_or(0);
1108    let name = crate::kernel::scheduler::get_current_process_name().unwrap_or("unknown");
1109    // 取得の枠(全体で 8 本)を返す。錠は取らない。
1110    crate::os_lib::web_engine::fetch_limit::on_process_died(pid);
1111    // XHR/`fetch` のワーカーの枠も返す(2026-11-18、TODO R3 (e)。錠は取らない)。
1112    crate::os_lib::web_apis::builtins::xhr_pool_on_process_died(pid);
1113    let asked = LAST_KILL_REQUEST_MS.swap(0, Ordering::Relaxed);
1114    let waited = if asked == 0 { 0 } else { crate::kernel::timer::get_system_time_ms().saturating_sub(asked) };
1115    crate::warn!(
1116        "[WM] アプリのスレッド '{}'(PID {})を途中で終わらせる: {}(強制終了の要求から {}ms)",
1117        name, pid, reason, waited
1118    );
1119    // 止めた理由を画面に出すなら、描画先を先に控える(`drop_runner_of_dead_process` が表から外す)。
1120    let target = match notice {
1121        Some(_) => DRAW_TARGETS.try_lock().and_then(|t| t.get(&pid).cloned()),
1122        None => None,
1123    };
1124    // SAFETY: このスレッドは直後の `exit()` で止まり、二度と再開しない。錠は上で外した。
1125    unsafe { drop_runner_of_dead_process(pid) };
1126    if let (Some(t), Some(msg)) = (target, notice) {
1127        draw_stop_notice(&t, msg);
1128    }
1129    crate::kernel::scheduler::exit();
1130}
1131
1132pub fn app_runner_entry(arg: usize) {
1133    let params_ptr = arg as *mut AppRunnerParams;
1134    // `get_current_process_id` は実行キューを try_lock で読むので、競合すると None になる。
1135    // 取れないと panic 時に回収されないので、取れるまで少し取り直す。
1136    let mut pid = None;
1137    for _ in 0..1000 {
1138        pid = crate::kernel::scheduler::get_current_process_id();
1139        if pid.is_some() {
1140            break;
1141        }
1142        core::hint::spin_loop();
1143    }
1144    if let Some(pid) = pid {
1145        register_runner(pid, params_ptr);
1146        // メモリの帳簿の組を受け取る(TODO R5)。以後このスレッドと、このスレッドが起こす背景のスレッドの
1147        // 確保がこの組で数えられ、使いすぎたら `kill_checkpoint` でこのアプリだけが止まる。
1148        let g = crate::kernel::allocator::MEM_LEDGER.open_group(pid);
1149        if g == 0 || !crate::kernel::scheduler::set_current_mem_group(g) {
1150            crate::kernel::allocator::MEM_LEDGER.close_group_of(pid);
1151            crate::warn!("[MEM] [QUOTA] アプリのスレッド(PID {})に帳簿の組を配れなかった(数えない)", pid);
1152        }
1153    } else {
1154        crate::warn!("[WM] アプリのスレッドのプロセス ID が取れず、panic 時の回収表に登録できなかった");
1155    }
1156    // 所有は登録表に預ける(panic 時に `drop_runner_of_dead_process` が解放する)。正常終了では
1157    // 最後に登録を外して自分で解放する。
1158    // SAFETY: `Box::into_raw` で渡されたもので、このスレッドだけが触る。
1159    let params: &mut AppRunnerParams = unsafe { &mut *params_ptr };
1160
1161    let mut w = params.width;
1162    let mut h = params.height;
1163
1164    // スレッドローカルなバックバッファを用意してロック競合を回避
1165    // 【2026-11-18 TODO R2 (c) ③】止めたときにも解放されるよう `kill_owned` の箱に入れる(窓の大きさで数 MB)。
1166    let mut local_buf = kill_owned(alloc::vec![0u32; (w * h) as usize]);
1167    register_draw_target(params, w, h);
1168
1169    let mut last_draw_time = 0;
1170
1171    while params.is_alive.load(Ordering::Relaxed) {
1172        // 1 周ごとに、強制終了とメモリの上限を確かめる(錠を持っていない所。TODO R2・R5)。
1173        kill_checkpoint();
1174        // 「このタブだけ止める」の合図があれば、ここでそのタブを閉じる(TODO R2 (d)。錠を持っていない所)。
1175        take_tab_kill(params);
1176        // メモリが足りなければ裏のタブを破棄する(ブラウザのみ。2026-11-19)。
1177        params.app.memory_checkpoint();
1178        // OS 側へ「まだ応答している」を知らせる(TODO R2 (a)。アトミックの書き込み 1 回)。
1179        params.heartbeat_ms.store(crate::kernel::timer::get_system_time_ms().max(1), Ordering::Relaxed);
1180        let current_time = crate::kernel::timer::get_ticks();
1181        // アプリの 1 周(イベントの処理+描画)の時間を測る(TODO R1。この間、このアプリは入力に答えない)。
1182        let loop_start_us = crate::kernel::timer::get_system_time_us();
1183
1184        // OS側に現在のアプリの needs_timer_redraw 状態をアトミックに同期
1185        let app_needs_timer = params.app.needs_timer_redraw();
1186        params.needs_timer_redraw.store(app_needs_timer, Ordering::Relaxed);
1187
1188        // 1. イベントの処理
1189        // 錠を持つのは中身の入れ替えだけ(写しを作らない。OS 側は錠を待たないが、短いほど控えに回る入力が減る。TODO R4 (b))。
1190        let events = core::mem::take(&mut *params.event_queue.lock());
1191
1192        let mut need_redraw = false;
1193
1194        for evt in events {
1195            // イベントで選ぶタブが変わることがあるので、毎回動かしているタブを書き直す(TODO R2 (d))。
1196            params.running_tab.store(params.app.active_tab(), Ordering::Relaxed);
1197            match evt {
1198                AppEvent::Mouse { local_x, local_y, btn_left, btn_right, wheel } => {
1199                    params.app.on_mouse(local_x, local_y, btn_left, btn_right, wheel);
1200                    if btn_left || btn_right || wheel != 0 {
1201                        need_redraw = true;
1202                    }
1203                }
1204                AppEvent::Key { keycode, pressed, ascii } => {
1205                    params.app.on_key(keycode, pressed, ascii);
1206                    need_redraw = true;
1207                }
1208                AppEvent::SwitchTab(idx) => {
1209                    params.app.switch_tab(idx);
1210                    need_redraw = true;
1211                }
1212                AppEvent::AddTab => {
1213                    params.app.add_tab();
1214                    need_redraw = true;
1215                }
1216                AppEvent::CloseTab(idx) => {
1217                    let _ = params.app.close_tab(idx);
1218                    need_redraw = true;
1219                }
1220                AppEvent::OpenUrl(url) => {
1221                    params.app.open_url_in_new_tab(&url);
1222                    need_redraw = true;
1223                }
1224                AppEvent::Resize { width, height } => {
1225                    w = width;
1226                    h = height;
1227                    *local_buf = alloc::vec![0u32; (w * h) as usize];
1228                    {
1229                        let mut shared = params.shared_buffer.lock();
1230                        *shared = alloc::vec![0u32; (w * h) as usize];
1231                    }
1232                    params.app.on_resize(w, h);
1233                    register_draw_target(params, w, h);
1234                    need_redraw = true;
1235                }
1236            }
1237        }
1238
1239        // 定期同期
1240        // 【2026-11-17 TODO R4 (b)】アプリから値を取ってから錠を取る(以前はタブの一覧を、錠を持ったまま
1241        // `app.tabs()` で作っていた)。錠を持つのは書き込みの間だけ。
1242        {
1243            let tab_list = params.app.tabs();
1244            let title = params.app.live_title();
1245            let active = params.app.active_tab();
1246            params.running_tab.store(active, Ordering::Relaxed);
1247            // 古い値の解放も錠の外で行う(`replace` の戻り値は文の後で落ちる)。
1248            let old_tabs = core::mem::replace(&mut *params.tabs.lock(), tab_list);
1249            let old_title = core::mem::replace(&mut *params.live_title.lock(), title);
1250            *params.active_tab.lock() = active;
1251            drop(old_tabs);
1252            drop(old_title);
1253        }
1254
1255        if params.app.needs_timer_redraw() {
1256            need_redraw = true;
1257        }
1258
1259        let time_since_last_draw = current_time.saturating_sub(last_draw_time);
1260
1261        // 描画レートを最大30fps(33ms)程度に制限し、かつ不要な背景全クリアを削除してチラつきを完全防止!
1262        if need_redraw || time_since_last_draw >= 33 {
1263            // 2. アプリの描画 (ローカルバッファに対して行うため、描画中にロックを保持しない)
1264            {
1265                let screen = Screen::new(local_buf.as_mut_ptr(), w, h, w * 4);
1266                let tab_list = params.app.tabs();
1267                let has_tabs = !tab_list.is_empty();
1268                let tab_w = if has_tabs { 100 } else { 0 };
1269                let app_x = tab_w;
1270                let app_y = 31u32;
1271                let app_w = w.saturating_sub(tab_w);
1272                let app_h = h.saturating_sub(31);
1273
1274                screen.set_clip(app_x, app_y, w, h);
1275                let draw_start_us = crate::kernel::timer::get_system_time_us();
1276                params.app.draw(&screen, app_x, app_y, app_w, app_h);
1277                crate::kernel::responsiveness::record_span_us(
1278                    crate::kernel::responsiveness::Lat::AppDraw,
1279                    draw_start_us,
1280                    crate::kernel::timer::get_system_time_us(),
1281                );
1282                screen.clear_clip();
1283            }
1284
1285            // 3. 描画完了後、一瞬だけ共有バッファに一括コピーする(保持時間を極小化)
1286            {
1287                let mut buf_guard = params.shared_buffer.lock();
1288                if buf_guard.len() == local_buf.len() {
1289                    buf_guard.copy_from_slice(&local_buf);
1290                    // ★ Core 0 に「バッファが更新された」ことを通知する
1291                    // Ordering::Release で書き込み順序を保証し、Core 0 側の Acquire と対になる
1292                    params.buffer_updated.store(true, Ordering::Release);
1293                } else {
1294                    // 【2026-07-26診断】長さ不一致だと**黙って転送をスキップ**していた。
1295                    // ウィンドウリサイズ等で共有バッファとローカルバッファの大きさが
1296                    // ずれると、以降アプリの描画結果が一切画面へ反映されなくなる
1297                    // (画面には古いフレームが residual として残り続ける)。
1298                    // 「ピクセルは書き込まれているのに画面に出ない」症状の
1299                    // 有力な候補なので、発生を可視化する。
1300                    static SKIP_DIAG: core::sync::atomic::AtomicU32 =
1301                        core::sync::atomic::AtomicU32::new(0);
1302                    let n = SKIP_DIAG.fetch_add(1, Ordering::Relaxed);
1303                    if n < 4 || n.is_multiple_of(64) {
1304                        crate::warn!(
1305                            "[WM][DIAG] shared_buffer copy SKIPPED (size mismatch): shared={} local={} w={} h={} count={}",
1306                            buf_guard.len(),
1307                            local_buf.len(),
1308                            w,
1309                            h,
1310                            n + 1
1311                        );
1312                    }
1313                }
1314            }
1315
1316            last_draw_time = current_time;
1317        }
1318
1319        crate::kernel::responsiveness::record_span_us(
1320            crate::kernel::responsiveness::Lat::AppLoop,
1321            loop_start_us,
1322            crate::kernel::timer::get_system_time_us(),
1323        );
1324
1325        // CPU負荷を劇的に下げ、ホストCPUエミュレーションに十分な余裕を残すためのスリープ
1326        crate::kernel::scheduler::sleep(5);
1327    }
1328    if let Some(pid) = pid {
1329        DRAW_TARGETS.lock().remove(&pid);
1330        if let Some((p, _)) = unregister_runner(pid) {
1331            // SAFETY: 登録を外したので、以後このポインタに触れるのはここだけ。
1332            drop(unsafe { Box::from_raw(p) });
1333        }
1334        // ウィンドウを閉じた後の正常終了でも、同じ組の背景のスレッドを止める(TODO R2 (c))。
1335        if let Some(g) = crate::kernel::allocator::MEM_LEDGER.close_group_of(pid) {
1336            on_group_closed(g, pid);
1337        }
1338    } else {
1339        // 登録していない(プロセス ID が取れなかった)ので自分で解放する。
1340        // SAFETY: 同上。
1341        drop(unsafe { Box::from_raw(params_ptr) });
1342    }
1343}
1344
1345/// 画面上の1つのウィンドウを表現する
1346pub struct Window {
1347    pub x: i32,
1348    pub y: i32,
1349    pub width: u32,
1350    pub height: u32,
1351    pub title: String,
1352    pub app: Box<dyn App>,
1353    pub is_dragging: bool,
1354    pub drag_offset_x: i32,
1355    pub drag_offset_y: i32,
1356    pub buffer: Option<alloc::vec::Vec<u32>>,
1357    // 空間・マルチタスク拡張
1358    pub workspace: u8,
1359    pub is_minimized: bool,
1360    pub is_fullscreen: bool,
1361    pub saved_x: i32,
1362    pub saved_y: i32,
1363    pub saved_w: u32,
1364    pub saved_h: u32,
1365    pub saved_ws: u8,
1366    /// タブごとのバックグラウンドスレッド PID(None = スレッドなし)
1367    pub tab_pids: alloc::vec::Vec<Option<usize>>,
1368    /// 「応答なし」の帯(止める入口)を今の画面に描いてあるか(TODO R2 (a)。変わったら描き直す)。
1369    pub unresp_shown: bool,
1370}
1371
1372impl Window {
1373    pub fn new(x: i32, y: i32, w: u32, h: u32, title: &str, app: Box<dyn App>) -> Self {
1374        let buffer = alloc::vec![0u32; (w * h) as usize];
1375        // アプリの初期タブ数だけ PID スロットを確保(最低1)
1376        let init_tabs = 1;
1377        Self {
1378            x,
1379            y,
1380            width: w,
1381            height: h,
1382            title: String::from(title),
1383            app,
1384            is_dragging: false,
1385            drag_offset_x: 0,
1386            drag_offset_y: 0,
1387            buffer: Some(buffer),
1388            workspace: 1,
1389            is_minimized: false,
1390            is_fullscreen: false,
1391            saved_x: x,
1392            saved_y: y,
1393            saved_w: w,
1394            saved_h: h,
1395            saved_ws: 1,
1396            tab_pids: alloc::vec![None; init_tabs],
1397            unresp_shown: false,
1398        }
1399    }
1400
1401    /// このウィンドウのアプリが応答していないか(TODO R2 (a))。別のスレッドで動くアプリ(`ProxyApp`)は 1 周が
1402    /// [`UNRESPONSIVE_MS`] 以上返っていないとき、メインループで描くアプリはウォッチドッグが Not Responding と決めたとき。
1403    /// 応答していないウィンドウが前面なら、Delete でそのアプリを止められる([`WindowManager::handle_key`])。
1404    pub fn unresponsive(&self) -> bool {
1405        if self.app.is_proxy() {
1406            self.app.unresponsive_ms().is_some()
1407        } else {
1408            crate::kernel::watchdog::is_not_responding(self.app.name())
1409        }
1410    }
1411
1412    /// ウィンドウを new_w × new_h にリサイズする。
1413    /// バッファは「容量が足りていれば再利用」し、足りない時だけ再確保する(Phase 1: churn 撲滅)。
1414    /// 再確保時はヒープ残量を確認し、不足ならリサイズを拒否して旧状態を保つ(Phase 2: OOM ガード)。
1415    /// 描画・合成は stride=width で先頭 width×height 要素のみ使うため、より大きいバッファの再利用は安全。
1416    /// 戻り値: リサイズに成功したか。
1417    pub fn resize(&mut self, new_w: u32, new_h: u32) -> bool {
1418        if new_w == 0 || new_h == 0 {
1419            return false;
1420        }
1421        let needed = (new_w as usize).saturating_mul(new_h as usize);
1422        let have = self.buffer.as_ref().map(|b| b.len()).unwrap_or(0);
1423
1424        if have < needed {
1425            // 拡張が必要: OOM ガード(必要バイト + 64KB の余裕を確認)
1426            let (used, total) = crate::kernel::allocator::get_heap_stats();
1427            let free = total.saturating_sub(used);
1428            let need_bytes = needed.saturating_mul(4).saturating_add(64 * 1024);
1429            if free < need_bytes {
1430                crate::warn!(
1431                    "[WM] resize denied: insufficient heap (free {} KB, need {} KB) — keeping current size",
1432                    free / 1024, need_bytes / 1024
1433                );
1434                return false;
1435            }
1436            // 旧バッファを先に解放してから確保する(新旧同時確保によるピークを避ける)
1437            self.buffer = None;
1438            self.buffer = Some(alloc::vec![0u32; needed]);
1439        }
1440
1441        self.width = new_w;
1442        self.height = new_h;
1443        self.app.on_resize(new_w, new_h);
1444        true
1445    }
1446
1447    /// タブ idx にスレッドを起動してPIDを記録する
1448    pub fn spawn_tab_thread(&mut self, tab_idx: usize) {
1449        while self.tab_pids.len() <= tab_idx {
1450            self.tab_pids.push(None);
1451        }
1452        if let Some(thread_fn) = self.app.tab_thread_fn() {
1453            let pid = crate::kernel::scheduler::spawn_with_stack(
1454                thread_fn,
1455                crate::kernel::scheduler::Priority::Normal,
1456                "app_tab",
1457                crate::kernel::scheduler::LARGE_STACK_SIZE,
1458            );
1459            if pid != 0 {
1460                self.tab_pids[tab_idx] = Some(pid);
1461                crate::info!("[WM] tab {} thread spawned pid={}", tab_idx, pid);
1462            } else {
1463                // 【2026-08-25】`spawn` はヒープ不足で 0 を返す。
1464                // 状態を先に立てていないので壊れはしないが、
1465                // 黙って何もしないとタブは開いているのに
1466                // 中身が動かない、という説明の付かない状態になる。
1467                // 他の 8 箇所と同じく失敗は必ず記録する。
1468                crate::warn!(
1469                    "[WM] tab {} のスレッドを起動できません(ヒープ不足)",
1470                    tab_idx
1471                );
1472            }
1473        }
1474    }
1475
1476    /// タブ idx のスレッド PID スロットをクリアする
1477    /// (スレッド自体はアプリ側の終了フラグで自然に終了させる)
1478    pub fn clear_tab_thread(&mut self, tab_idx: usize) {
1479        if tab_idx < self.tab_pids.len() {
1480            if let Some(pid) = self.tab_pids[tab_idx] {
1481                crate::info!("[WM] tab {} thread pid={} released", tab_idx, pid);
1482            }
1483            self.tab_pids[tab_idx] = None;
1484        }
1485    }
1486}
1487
1488#[derive(Copy, Clone, Debug)]
1489pub struct Rect {
1490    pub x: i32,
1491    pub y: i32,
1492    pub w: u32,
1493    pub h: u32,
1494}
1495
1496impl Rect {
1497    pub fn new(x: i32, y: i32, w: u32, h: u32) -> Self {
1498        Self { x, y, w, h }
1499    }
1500
1501    pub fn union(&self, other: &Self) -> Self {
1502        let x0 = self.x.min(other.x);
1503        let y0 = self.y.min(other.y);
1504        let x1 = (self.x + self.w as i32).max(other.x + other.w as i32);
1505        let y1 = (self.y + self.h as i32).max(other.y + other.h as i32);
1506        Self {
1507            x: x0,
1508            y: y0,
1509            w: (x1 - x0).max(0) as u32,
1510            h: (y1 - y0).max(0) as u32,
1511        }
1512    }
1513}
1514
1515pub struct WindowManager {
1516    // リストの最後尾が「最前面(アクティブ)」
1517    pub windows: Vec<Window>,
1518    pub dirty: bool,
1519    pub terminal_focused: bool,
1520    pub active_workspace: u8,
1521    pub slide_out: bool,
1522    pub alt_hold_mode: bool,
1523    pub alt_input_buffer: String,
1524
1525    // ダーティ矩形の追跡用
1526    pub dirty_rects: Vec<Rect>,
1527
1528    // 直前のマウス状態を記憶してドラッグを判定
1529    last_mouse_x: i32,
1530    last_mouse_y: i32,
1531    last_mouse_btn: bool,
1532}
1533
1534// グローバルマネージャ
1535pub use crate::kernel::reentrant_lock::{ReentrantMutex, ReentrantMutexGuard};
1536
1537static mut GLOBAL_WM: Option<ReentrantMutex<WindowManager>> = None;
1538
1539impl Default for WindowManager {
1540    fn default() -> Self {
1541        Self::new()
1542    }
1543}
1544
1545impl WindowManager {
1546    pub fn new() -> Self {
1547        Self {
1548            windows: Vec::new(),
1549            dirty: true,
1550            terminal_focused: true,
1551            active_workspace: 1,
1552            slide_out: false,
1553            alt_hold_mode: false,
1554            alt_input_buffer: String::new(),
1555            dirty_rects: Vec::new(),
1556            last_mouse_x: 0,
1557            last_mouse_y: 0,
1558            last_mouse_btn: false,
1559        }
1560    }
1561
1562    pub fn add_dirty_rect(&mut self, rect: Rect) {
1563        self.dirty_rects.push(rect);
1564    }
1565
1566    pub fn clear_dirty_rects(&mut self) {
1567        self.dirty_rects.clear();
1568    }
1569
1570    pub fn get_dirty_bounding_box(&self, screen_w: u32, screen_h: u32) -> Option<Rect> {
1571        if self.dirty_rects.is_empty() {
1572            return None;
1573        }
1574        let mut r = self.dirty_rects[0];
1575        for i in 1..self.dirty_rects.len() {
1576            r = r.union(&self.dirty_rects[i]);
1577        }
1578
1579        let x0 = r.x.clamp(0, screen_w as i32);
1580        let y0 = r.y.clamp(0, screen_h as i32);
1581        let x1 = (r.x + r.w as i32).clamp(0, screen_w as i32);
1582        let y1 = (r.y + r.h as i32).clamp(0, screen_h as i32);
1583
1584        Some(Rect::new(x0, y0, (x1 - x0) as u32, (y1 - y0) as u32))
1585    }
1586
1587    /// 同じ名前のウィンドウがあれば `(止まっているか)` を返す(なければ `None`)。2026-11-18。
1588    pub fn existing_window_state(&self, app_name: &str) -> Option<bool> {
1589        self.windows
1590            .iter()
1591            .find(|w| w.app.name() == app_name)
1592            .map(|w| w.app.is_stopped())
1593    }
1594
1595    /// 既存の `app_name` のウィンドウを前に出し、`url` をそのアプリの新しいタブで開かせる(2026-11-18)。
1596    /// ウィンドウが 1 つだけという決まりは変えない(新しいウィンドウは作らない)。開けたら true。
1597    pub fn open_url_in_existing(&mut self, app_name: &str, url: &str) -> bool {
1598        let Some(idx) = self.windows.iter().position(|w| w.app.name() == app_name) else {
1599            return false;
1600        };
1601        self.windows[idx].is_minimized = false;
1602        self.windows[idx].app.open_url_in_new_tab(url);
1603        self.activate_window(idx);
1604        self.dirty = true;
1605        true
1606    }
1607
1608    pub fn add_window(&mut self, mut win: Window) {
1609        let app_name = win.app.name();
1610        let mut existing_idx = None;
1611        for (i, w) in self.windows.iter().enumerate() {
1612            if w.app.name() == app_name {
1613                existing_idx = Some(i);
1614                break;
1615            }
1616        }
1617
1618        // 止まったアプリ(panic・メモリの使いすぎ。TODO R5)のウィンドウは使い回さず、閉じて開き直す。
1619        if let Some(idx) = existing_idx {
1620            if self.windows[idx].app.is_stopped() {
1621                let old = self.windows.remove(idx);
1622                self.add_dirty_rect(Rect::new(old.x, old.y, old.width, old.height));
1623                crate::kernel::watchdog::clear(old.app.name());
1624                crate::warn!("[WM] 止まっていた '{}' のウィンドウを閉じて開き直す", old.title);
1625                drop(old);
1626                existing_idx = None;
1627            }
1628        }
1629        if let Some(idx) = existing_idx {
1630            // 既に同じアプリが起動している場合:最小化解除、ワークスペースへジャンプ、最前面引き上げ
1631            self.windows[idx].is_minimized = false;
1632            let target_ws = self.windows[idx].workspace;
1633            self.active_workspace = target_ws;
1634            self.activate_window(idx);
1635            self.dirty = true;
1636            return;
1637        }
1638
1639        // 新規ウィンドウは現在のアクティブワークスペースに割り当て
1640        win.workspace = self.active_workspace;
1641        let name = win.title.clone();
1642        // 初期タブ (index 0) のバックグラウンドスレッドを起動
1643        win.spawn_tab_thread(0);
1644        self.add_dirty_rect(Rect::new(win.x, win.y, win.width, win.height));
1645        self.windows.push(win);
1646        self.dirty = true;
1647        self.terminal_focused = false;
1648        let (used, total) = crate::kernel::allocator::get_heap_stats();
1649        crate::debug!(
1650            "[WM] open '{}' -> {} windows | heap {}/{} KB",
1651            name,
1652            self.windows.len(),
1653            used / 1024,
1654            total / 1024
1655        );
1656    }
1657
1658    pub fn remove_active_window(&mut self) {
1659        if !self.windows.is_empty() {
1660            let name = self
1661                .windows
1662                .last()
1663                .map(|w| w.title.clone())
1664                .unwrap_or_else(|| alloc::string::String::from("?"));
1665            // ウォッチドッグ of 違反/Not Responding 状態をリセット
1666            let info = self.windows.last().map(|w| {
1667                (
1668                    Rect::new(w.x, w.y, w.width, w.height),
1669                    alloc::string::String::from(w.app.name()),
1670                )
1671            });
1672            if let Some((rect, app_name)) = info {
1673                self.add_dirty_rect(rect);
1674                crate::kernel::watchdog::clear(&app_name);
1675            }
1676            self.windows.pop();
1677            self.dirty = true;
1678            let (used, total) = crate::kernel::allocator::get_heap_stats();
1679            crate::debug!(
1680                "[WM] close '{}' -> {} windows | heap {}/{} KB",
1681                name,
1682                self.windows.len(),
1683                used / 1024,
1684                total / 1024
1685            );
1686        }
1687    }
1688
1689    /// 指定した番号のウィンドウを閉じ、そのアプリを強制終了する(TODO R2)。
1690    /// アプリのスレッドは、次の確認の所([`kill_checkpoint`])で終わる。描画や JS の実行の途中でも待たない。
1691    /// 戻り値: 閉じたアプリの名前(番号が範囲外なら `None`)。
1692    pub fn kill_window(&mut self, idx: usize) -> Option<alloc::string::String> {
1693        if idx >= self.windows.len() {
1694            return None;
1695        }
1696        let win = self.windows.remove(idx);
1697        let app_name = alloc::string::String::from(win.app.name());
1698        self.add_dirty_rect(Rect::new(win.x, win.y, win.width, win.height));
1699        crate::kernel::watchdog::clear(&app_name);
1700        crate::warn!("[WM] 強制終了: '{}'({})", win.title, app_name);
1701        LAST_KILL_REQUEST_MS.store(crate::kernel::timer::get_system_time_ms().max(1), Ordering::Relaxed);
1702        // ここでウィンドウ(と `ProxyApp`)が落ち、アプリのスレッドへ「要らない」の合図が立つ。
1703        drop(win);
1704        if self.windows.is_empty() {
1705            self.terminal_focused = true;
1706        }
1707        self.dirty = true;
1708        Some(app_name)
1709    }
1710
1711    /// ウィンドウ `win_idx` のタブ `tab_idx` だけを止める(TODO R2 (d)、2026-11-18)。ウィンドウとほかのタブは残す。
1712    /// タブが 1 つしか無ければ、ウィンドウごと止める([`Self::kill_window`])。
1713    ///
1714    /// アプリのスレッドへ合図を立てるだけで待たない。そのタブが JS を実行中なら、JS は次の確かめ(32,768 ステップごと)で
1715    /// 打ち切られ、アプリのスレッドが描画から戻った 1 周の頭でタブを閉じる。JS 以外の長い処理(大きなページのレイアウト・
1716    /// 画像の復号など)の途中では、その処理が終わるまで閉じない(そのときはウィンドウごと止める Delete が使える)。
1717    /// 戻り値: 止めるタブの名前(受け付けなかったら `None`)。
1718    pub fn kill_tab(&mut self, win_idx: usize, tab_idx: usize) -> Option<alloc::string::String> {
1719        let win = self.windows.get_mut(win_idx)?;
1720        let tabs = win.app.tabs();
1721        if tabs.len() <= 1 {
1722            return self.kill_window(win_idx);
1723        }
1724        let tab_name = tabs.get(tab_idx)?.clone();
1725        if !win.app.kill_tab(tab_idx) {
1726            return None;
1727        }
1728        crate::warn!(
1729            "[WM] タブだけを止める: '{}' のタブ {}({})。動かしているタブ {}、タブ {} 個",
1730            win.title,
1731            tab_idx,
1732            tab_name,
1733            win.app.running_tab(),
1734            tabs.len()
1735        );
1736        LAST_TAB_KILL_REQUEST_MS.store(crate::kernel::timer::get_system_time_ms().max(1), Ordering::Relaxed);
1737        TAB_KILL_GATE_AT_MS.store(crate::kernel::timer::get_system_time_ms().max(1), Ordering::Relaxed);
1738        let r = Rect::new(win.x, win.y, win.width, win.height);
1739        self.add_dirty_rect(r);
1740        self.dirty = true;
1741        Some(tab_name)
1742    }
1743
1744    /// 指定したインデックス of ウィンドウを最前面に移動してアクティブにする
1745    pub fn activate_window(&mut self, idx: usize) {
1746        // インデックスの境界チェックを行い、範囲外アクセスによる unwrap のパニックや
1747        // 境界外例外を防止して安全にウィンドウをアクティブ化します。
1748        if idx < self.windows.len() {
1749            let target_ws = self.windows[idx].workspace;
1750            self.active_workspace = target_ws;
1751            self.terminal_focused = false;
1752            // ウィンドウを前面に出す際、退避(スライドアウト)状態を解除して
1753            // 確実に画面内・最前面へ復帰させる。
1754            self.slide_out = false;
1755            let win = self.windows.remove(idx);
1756            let rect = Rect::new(win.x, win.y, win.width, win.height);
1757            self.add_dirty_rect(rect);
1758            self.windows.push(win);
1759            self.add_dirty_rect(rect);
1760            self.dirty = true;
1761        }
1762    }
1763
1764    /// 全画面(背景の上にウィンドウ)を描画 (合成ウィンドウマネージャ方式)
1765    /// 指定矩形 (スクリーン座標) を、可視ウィンドウ (アクティブ WS・非最小化) が
1766    /// 少しでも覆っているかを返す。
1767    ///
1768    /// システムモニタのような「背景レイヤー」要素を部分再描画してよいかの判定に使う。
1769    /// 背景要素はウィンドウより下の z 順にあるため、ウィンドウが覆っている領域へ
1770    /// 単独で描画すると z 順を破ってウィンドウを突き破ってしまう。それを防ぐ。
1771    pub fn any_window_covers_rect(&self, x0: i32, y0: i32, x1: i32, y1: i32) -> bool {
1772        // スライドアウト中 (WS1) は全ウィンドウが画面外へ退避しているため覆わない
1773        if self.active_workspace == 1 && self.slide_out {
1774            return false;
1775        }
1776        for win in self.windows.iter() {
1777            if win.workspace != self.active_workspace || win.is_minimized {
1778                continue;
1779            }
1780            let wx1 = win.x + win.width as i32;
1781            let wy1 = win.y + win.height as i32;
1782            // 矩形交差判定
1783            if win.x < x1 && wx1 > x0 && win.y < y1 && wy1 > y0 {
1784                return true;
1785            }
1786        }
1787        false
1788    }
1789
1790    pub fn draw_all(&mut self, screen: &Screen) {
1791        self.dirty = false;
1792        let config = crate::kernel::config::get_config();
1793        let base_frame_color = Color(config.theme.non_active_window_border);
1794        let title_bar_color = Color(config.theme.window_title_bar);
1795        let title_fg_color = Color(config.theme.window_title_fg);
1796        let active_frame_color = Color(config.theme.active_window_border);
1797
1798        let num_windows = self.windows.len();
1799        for (i, win) in self.windows.iter_mut().enumerate() {
1800            // アクティブなワークスペースかつ最小化されていないウィンドウのみを描画
1801            if win.workspace != self.active_workspace || win.is_minimized {
1802                continue;
1803            }
1804            let is_active = i == num_windows.saturating_sub(1) && !self.terminal_focused;
1805            let current_frame_color = if is_active {
1806                active_frame_color
1807            } else {
1808                base_frame_color
1809            };
1810            let border_w = 2; // 常に2pxの極太ボーダー
1811
1812            let w = win.width;
1813            let h = win.height;
1814
1815            if let Some(ref mut win_buf) = win.buffer {
1816                // 1. 描画先をウィンドウ固有のバッファに切り替える
1817                screen.set_render_target(win_buf.as_mut_ptr(), w, h);
1818
1819                // アプリケーション領域のレイアウト計算(描画前に確定させる)
1820                let mut tab_list = win.app.tabs();
1821                let active_idx = win.app.active_tab();
1822                let is_terminal = win.app.name() == "Terminal";
1823                if is_terminal && tab_list.is_empty() {
1824                    tab_list.push(alloc::string::String::from("Shell"));
1825                }
1826                let has_tabs = !tab_list.is_empty();
1827                let tab_w = if has_tabs { 100 } else { 0 };
1828                let app_x = tab_w;
1829                let app_y = 31u32;
1830                let app_w = w.saturating_sub(tab_w);
1831                let _app_h = h.saturating_sub(31);
1832
1833                let app_name = win.app.name();
1834
1835                // 【2026-07-27診断】表示フレームの通し番号を進め、
1836                // 「ヒーロー文字を最後に描いたフレーム」との差を可視化する。
1837                // 差が開き続けるなら、文字を描いたフレームは画面に出ていない。
1838                {
1839                    let f = crate::kernel::draw::FRAME_NO
1840                        .fetch_add(1, Ordering::Relaxed)
1841                        .wrapping_add(1);
1842                    if f.is_multiple_of(64) {
1843                        // 【2026-08-25】取得の待機状態はここから出す。
1844                        //
1845                        // 最初はブラウザの `draw()` から出していたが、
1846                        // **待機に入ると `draw()` 自体が止まる**ので
1847                        // 最後に出た行が古い標本のまま残り、
1848                        // 「まだ取得中」に見えたまま更新されなくなった。
1849                        // 採取スクリプトはこの行で撮影時期を決めるので、
1850                        // 止まらない側(画面の提示ループ)から出す必要がある。
1851                        crate::os_lib::web_engine::fetch_limit::idle_line();
1852                        let ht = crate::kernel::draw::HERO_TEXT_FRAME.load(Ordering::Relaxed);
1853                        crate::warn!(
1854                            "[WM][FRAME] present_frame={} last_hero_text_frame={}",
1855                            f,
1856                            if ht == u32::MAX { 0 } else { ht }
1857                        );
1858                    }
1859                }
1860
1861                if win.app.is_proxy() {
1862                    // ★ ProxyApp の描画順序:
1863                    //   ① shared_buf → win_buf の全面コピー(前フレームの内容で埋める)
1864                    //   ② タイトルバー・枠線を上書き
1865                    // これにより「一瞬 app_bg 単色状態」が発生せずちらつきを防止する。
1866                    if let Some(shared_buf_arc) = win.app.get_shared_buffer() {
1867                        if let Some(shared_buf) = shared_buf_arc.try_lock() {
1868                            // shared_buf は app_runner が w×h 全面に描画済みなので全コピー
1869                            let copy_len = (w * h) as usize;
1870                            if shared_buf.len() >= copy_len && win_buf.len() >= copy_len {
1871                                unsafe {
1872                                    core::ptr::copy_nonoverlapping(
1873                                        shared_buf.as_ptr(),
1874                                        win_buf.as_mut_ptr(),
1875                                        copy_len,
1876                                    );
1877                                }
1878                            } else {
1879                                // 【2026-07-26診断】ここも長さ不足だと**黙ってスキップ**して
1880                                // win_buf の前フレーム内容をそのまま表示し続ける。
1881                                // アプリ側(app_runner)の転送は成功しているのに画面が
1882                                // 更新されない、という症状の候補。発生を可視化する。
1883                                static CSKIP: core::sync::atomic::AtomicU32 =
1884                                    core::sync::atomic::AtomicU32::new(0);
1885                                let n = CSKIP.fetch_add(1, Ordering::Relaxed);
1886                                if n < 4 || n.is_multiple_of(128) {
1887                                    crate::warn!(
1888                                        "[WM][DIAG] compositor copy SKIPPED: shared={} win_buf={} need={} (w={} h={}) count={}",
1889                                        shared_buf.len(),
1890                                        win_buf.len(),
1891                                        copy_len,
1892                                        w,
1893                                        h,
1894                                        n + 1
1895                                    );
1896                                }
1897                            }
1898                        } else {
1899                            // try_lock 失敗 = app_runner 側が書き込み中。
1900                            // win_buf の前フレーム内容をそのまま使い、次フレームでリトライ。
1901                            //
1902                            // 【2026-07-26診断】ここが連続して失敗し続けると
1903                            // **古いフレームを表示し続ける**。ブラウザのように
1904                            // 1 フレームの描画が重いアプリでは app_runner が
1905                            // ロックを長く保持するため、コンポジタが毎回負ける
1906                            // 可能性がある。成功率を可視化する。
1907                            static TRYLOCK_FAIL: core::sync::atomic::AtomicU32 =
1908                                core::sync::atomic::AtomicU32::new(0);
1909                            let n = TRYLOCK_FAIL.fetch_add(1, Ordering::Relaxed);
1910                            if n < 4 || n.is_multiple_of(128) {
1911                                crate::warn!(
1912                                    "[WM][DIAG] compositor try_lock FAILED (using stale frame) count={}",
1913                                    n + 1
1914                                );
1915                            }
1916                            self.dirty = true;
1917                        }
1918                    }
1919                    // 応答していないアプリには、止める入口を帯で出す(TODO R2 (a)。止めたアプリの赤い帯〔`draw_stop_notice`〕と同じ流儀)。
1920                    // 帯はアプリの描いた画面の上に毎回描き直す(アプリの画面は止まっていても、動画の層の書き込みで写し直されることがある)。
1921                    let gap = win.app.unresponsive_ms();
1922                    win.unresp_shown = gap.is_some();
1923                    if let Some(gap) = gap {
1924                        let tab_count = win.app.tabs().len();
1925                        draw_unresponsive_band(screen, app_x, w, gap, tab_count, win.app.tab_kill_pending());
1926                    }
1927                } else {
1928                    // 2. 非Proxy: 従来通りバッファをクリアしてからアプリが描画
1929                    screen.boxfill(0, 0, w, h, Color(config.theme.app_bg)); // 背景
1930
1931                    // アプリの描画(ウォッチドッグで監視)
1932                    screen.set_clip(app_x, app_y, w, h);
1933                    if crate::kernel::watchdog::is_not_responding(app_name) {
1934                        screen.boxfill(app_x, app_y, w, h, Color(config.theme.ui_overlay_bg));
1935                        screen.draw_string_vector(
1936                            app_x + 16,
1937                            app_y + 16,
1938                            "Application Not Responding",
1939                            Color(config.theme.error_fg),
1940                            16,
1941                        );
1942                        // 止める入口(TODO R2 (a)): このウィンドウが前面のとき Delete で止める(`handle_key`)。
1943                        screen.draw_string_vector(
1944                            app_x + 16,
1945                            app_y + 40,
1946                            "Press Delete to stop it, or close the window (Alt+W).",
1947                            Color(config.theme.terminal_fg),
1948                            13,
1949                        );
1950                    } else {
1951                        crate::kernel::watchdog::enter(app_name);
1952                        win.app.draw(screen, app_x, app_y, app_w, _app_h);
1953                        crate::kernel::watchdog::exit();
1954                    }
1955                    screen.clear_clip();
1956                }
1957
1958                // 3. タイトルバー・枠線・ボタンを最前面に上書き(ProxyApp でも共通)
1959                // タイトルバー (高さ30px)
1960                screen.boxfill(0, 0, w, 30, title_bar_color);
1961
1962                // 境界線 (Premium Border Highlight with 立体極暗シャドウ)
1963                let shadow_color = Color(0xFF111217);
1964                screen.boxfill(0, 0, w, 1, shadow_color); // 最上部極暗
1965                screen.boxfill(0, 0, 1, h, shadow_color); // 最左部極暗
1966                screen.boxfill(w - 1, 0, w, h, shadow_color); // 最右部極暗
1967                screen.boxfill(0, h - 1, w, h, shadow_color); // 最下部極暗
1968
1969                screen.boxfill(1, 1, w - 1, 1 + border_w, current_frame_color); // 上
1970                screen.boxfill(1, 1, 1 + border_w, h - 1, current_frame_color); // 左
1971                screen.boxfill(w - 1 - border_w, 1, w - 1, h - 1, current_frame_color); // 右
1972                screen.boxfill(1, h - 1 - border_w, w - 1, h - 1, current_frame_color); // 下
1973                screen.boxfill(1, 30, w - 1, 30 + border_w, current_frame_color); // タイトル下
1974
1975                // タイトルテキスト
1976                let live_title = win.app.live_title();
1977                screen.draw_string_vector(10, 5, live_title.as_deref().unwrap_or(&win.title), title_fg_color, 16);
1978
1979                // ウィンドウ制御ボタン群 (右から順に配置) - Fluent UI System Icons (MIT)。
1980                // 絵は [`TITLE_ICONS`](起動時に [`prewarm_title_icons`] で先に描いておく)。
1981                let [icon_close, icon_fs, icon_max, icon_norm, icon_min] = TITLE_ICONS;
1982
1983                let btn_w = TITLE_ICON_PX;
1984                let _btn_h = 20u32;
1985                let btn_y = 5u32;
1986                let gap = 5i32;
1987
1988                // [X] 閉じるボタン
1989                let bx_close = w - 10 - btn_w;
1990                screen.draw_svg_icon(bx_close, btn_y, icon_close, btn_w, Color(config.theme.win_btn_close));
1991
1992                // [F] フルスクリーンボタン
1993                let bx_fs = (bx_close as i32 - btn_w as i32 - gap) as u32;
1994                screen.draw_svg_icon(bx_fs, btn_y, icon_fs, btn_w, Color(config.theme.win_btn_fullscreen));
1995
1996                // [M] 最大化ボタン
1997                let bx_max = (bx_fs as i32 - btn_w as i32 - gap) as u32;
1998                screen.draw_svg_icon(bx_max, btn_y, icon_max, btn_w, Color(config.theme.win_btn_maximize));
1999
2000                // [N] 通常化ボタン
2001                let bx_norm = (bx_max as i32 - btn_w as i32 - gap) as u32;
2002                screen.draw_svg_icon(bx_norm, btn_y, icon_norm, btn_w, Color(config.theme.win_btn_restore));
2003
2004                // [m] 最小化ボタン
2005                let bx_min = (bx_norm as i32 - btn_w as i32 - gap) as u32;
2006                screen.draw_svg_icon(bx_min, btn_y, icon_min, btn_w, Color(config.theme.win_btn_minimize));
2007
2008                // ウィンドウ内タブの描画(ProxyApp・非Proxy 共通)
2009                if has_tabs {
2010                    screen.boxfill(0, app_y, tab_w, h, Color(config.theme.tab_area_bg));
2011                    screen.boxfill(tab_w - 1, app_y, tab_w, h, Color(config.theme.tab_area_border)); // 境界線
2012
2013                    screen.draw_string_vector(10, app_y + 10, "TABS", Color(config.theme.tab_inactive_fg), 14);
2014
2015                    // (+) button
2016                    screen.boxfill(75, app_y + 8, 92, app_y + 25, Color(config.theme.tab_area_border));
2017                    screen.draw_string_vector(80, app_y + 10, "+", Color(config.theme.tab_active_fg), 14);
2018
2019                    screen.boxfill(10, app_y + 30, 90, app_y + 31, Color(config.theme.tab_area_border));
2020
2021                    let mut tab_y = app_y + 40;
2022                    for (idx, tab_title) in tab_list.iter().enumerate() {
2023                        if tab_y + 42 > h {
2024                            break;
2025                        }
2026
2027                        let is_active_tab = idx == active_idx;
2028                        let bg_color = if is_active_tab {
2029                            Color(config.theme.tab_active_bg)
2030                        } else {
2031                            Color(config.theme.tab_area_bg)
2032                        };
2033                        let fg_color = if is_active_tab {
2034                            Color(config.theme.tab_active_fg)
2035                        } else {
2036                            Color(config.theme.tab_inactive_fg)
2037                        };
2038
2039                        screen.boxfill(5, tab_y, 95, tab_y + 36, bg_color);
2040
2041                        let label = alloc::format!("{})", idx + 1);
2042                        screen.draw_string_vector(10, tab_y + 12, &label, fg_color, 12);
2043
2044                        // 改行許容および文字数拡大ロジック
2045                        let mut lines = alloc::vec![];
2046                        if tab_title.contains('\n') {
2047                            for (count, part) in tab_title.split('\n').enumerate() {
2048                                if count >= 2 {
2049                                    break;
2050                                }
2051                                lines.push(alloc::string::String::from(part));
2052                            }
2053                        } else {
2054                            let chars: alloc::vec::Vec<char> = tab_title.chars().collect();
2055                            if chars.len() <= 6 {
2056                                lines.push(tab_title.clone());
2057                            } else {
2058                                let first: alloc::string::String = chars.iter().take(6).collect();
2059                                let mut second: alloc::string::String =
2060                                    chars.iter().skip(6).collect();
2061                                if second.chars().count() > 6 {
2062                                    let mut sec_trunc: alloc::string::String =
2063                                        second.chars().take(4).collect();
2064                                    sec_trunc.push_str("..");
2065                                    second = sec_trunc;
2066                                }
2067                                lines.push(first);
2068                                lines.push(second);
2069                            }
2070                        }
2071
2072                        if lines.len() == 1 {
2073                            screen.draw_string_vector(22, tab_y + 12, &lines[0], fg_color, 10);
2074                        } else if lines.len() >= 2 {
2075                            screen.draw_string_vector(22, tab_y + 5, &lines[0], fg_color, 10);
2076                            screen.draw_string_vector(22, tab_y + 19, &lines[1], fg_color, 10);
2077                        }
2078
2079                        // (x) button
2080                        screen.boxfill(78, tab_y + 10, 92, tab_y + 24, Color(config.theme.tab_area_border));
2081                        screen.draw_string_vector(82, tab_y + 12, "x", Color(config.theme.win_btn_close), 10);
2082
2083                        tab_y += 42;
2084                    }
2085                }
2086
2087                // 4. 描画ターゲットをメイン画面バッファへリセット
2088                screen.reset_render_target();
2089
2090                // 5. win_buf → back_buffer へ行単位の高速コピー(ピクセルループを廃止)
2091                let screen_w = screen.width;
2092                let screen_h = screen.height;
2093                let main_ptr = if screen.use_back_buffer.get() && !screen.back_buffer.is_null() {
2094                    screen.back_buffer
2095                } else {
2096                    screen.vram
2097                };
2098
2099                let win_x = if self.active_workspace == 1 && self.slide_out {
2100                    win.x + screen.width as i32
2101                } else {
2102                    win.x
2103                };
2104                let win_y = win.y;
2105
2106                // クリップ計算(ウィンドウが画面端にかかる場合、および画面のダーティクリップ領域に対応)
2107                let src_x0 = if win_x < 0 { (-win_x) as u32 } else { 0 };
2108                let src_y0 = if win_y < 0 { (-win_y) as u32 } else { 0 };
2109                let dst_x0 = win_x.max(0) as u32;
2110                let dst_y0 = win_y.max(0) as u32;
2111                let copy_w = w.saturating_sub(src_x0).min(screen_w.saturating_sub(dst_x0));
2112                let copy_h = h.saturating_sub(src_y0).min(screen_h.saturating_sub(dst_y0));
2113
2114                let (clip_x0, clip_y0, clip_x1, clip_y1) = if let Some(c) = screen.clip.get() {
2115                    c
2116                } else {
2117                    (0, 0, screen_w, screen_h)
2118                };
2119                let eff_dst_x0 = dst_x0.max(clip_x0);
2120                let eff_dst_y0 = dst_y0.max(clip_y0);
2121                let eff_dst_x1 = (dst_x0 + copy_w).min(clip_x1);
2122                let eff_dst_y1 = (dst_y0 + copy_h).min(clip_y1);
2123
2124                if eff_dst_x1 > eff_dst_x0 && eff_dst_y1 > eff_dst_y0 {
2125                    let eff_w = eff_dst_x1 - eff_dst_x0;
2126                    let eff_h = eff_dst_y1 - eff_dst_y0;
2127                    let eff_src_x0 = src_x0 + (eff_dst_x0 - dst_x0);
2128                    let eff_src_y0 = src_y0 + (eff_dst_y0 - dst_y0);
2129                    unsafe {
2130                        for row in 0..eff_h {
2131                            let src_ptr = win_buf.as_ptr().add(((eff_src_y0 + row) * w + eff_src_x0) as usize);
2132                            let dst_ptr = main_ptr.add(((eff_dst_y0 + row) * screen_w + eff_dst_x0) as usize);
2133                            core::ptr::copy_nonoverlapping(src_ptr, dst_ptr, eff_w as usize);
2134                        }
2135                    }
2136                }
2137            }
2138        }
2139
2140        // 6. Altホールド複数桁遅延実行オーバーレイの描画
2141        if self.alt_hold_mode {
2142            let overlay_w = 200u32;
2143            let overlay_h = 100u32;
2144            let overlay_x = (screen.width - overlay_w) / 2;
2145            let overlay_y = (screen.height - overlay_h) / 2;
2146
2147            let overlay_bg_semi = Color(0xEE000000 | (config.theme.ui_overlay_bg & 0x00FFFFFF));
2148            screen.boxfill(
2149                overlay_x,
2150                overlay_y,
2151                overlay_x + overlay_w,
2152                overlay_y + overlay_h,
2153                overlay_bg_semi,
2154            );
2155            screen.boxfill(
2156                overlay_x,
2157                overlay_y,
2158                overlay_x + overlay_w,
2159                overlay_y + 2,
2160                Color(config.theme.ui_overlay_accent),
2161            );
2162            screen.draw_string_vector(
2163                overlay_x + 15,
2164                overlay_y + 10,
2165                "STATELESS JUMP",
2166                Color(config.theme.terminal_fg),
2167                14,
2168            );
2169
2170            let val_str = if self.alt_input_buffer.is_empty() {
2171                alloc::string::String::from("_")
2172            } else {
2173                alloc::format!("{}_", self.alt_input_buffer)
2174            };
2175            screen.draw_string_vector(
2176                overlay_x + 80,
2177                overlay_y + 40,
2178                &val_str,
2179                Color(config.theme.success_fg),
2180                32,
2181            );
2182        }
2183    }
2184
2185    /// マウスイベント処理。Zオーダー順(手前から)判定する。
2186    pub fn handle_mouse(
2187        &mut self,
2188        mx: i32,
2189        my: i32,
2190        btn_left: bool,
2191        btn_right: bool,
2192        wheel: i32,
2193        screen: &Screen,
2194    ) -> bool {
2195        let mut handled = false;
2196
2197        let dx = mx - self.last_mouse_x;
2198        let dy = my - self.last_mouse_y;
2199
2200        // 1. ドラッグ中のウィンドウがあれば移動 (アクティブなワークスペースかつ非最小化時のみ)
2201        // 1. ドラッグ中のウィンドウがあれば移動 (アクティブなワークスペースかつ非最小化時のみ)
2202        let is_dragging = if let Some(win) = self.windows.last() {
2203            win.is_dragging && win.workspace == self.active_workspace && !win.is_minimized
2204        } else {
2205            false
2206        };
2207
2208        if is_dragging {
2209            if btn_left {
2210                // 移動前の矩形をダーティ登録
2211                let old_rect = if let Some(win) = self.windows.last() {
2212                    Rect::new(win.x, win.y, win.width, win.height)
2213                } else {
2214                    Rect::new(0, 0, 0, 0)
2215                };
2216                self.add_dirty_rect(old_rect);
2217
2218                if let Some(win) = self.windows.last_mut() {
2219                    win.x += dx;
2220                    win.y += dy;
2221                }
2222                self.dirty = true;
2223
2224                // 移動後の矩形をダーティ登録
2225                let new_rect = if let Some(win) = self.windows.last() {
2226                    Rect::new(win.x, win.y, win.width, win.height)
2227                } else {
2228                    Rect::new(0, 0, 0, 0)
2229                };
2230                self.add_dirty_rect(new_rect);
2231
2232                self.last_mouse_x = mx;
2233                self.last_mouse_y = my;
2234                self.last_mouse_btn = btn_left;
2235                return true;
2236            } else {
2237                if let Some(win) = self.windows.last_mut() {
2238                    win.is_dragging = false;
2239                }
2240            }
2241        }
2242
2243        // 2. マウスクリック時のヒットテスト(手前から奥へ)
2244        let btn_just_pressed = btn_left && !self.last_mouse_btn;
2245        let mut target_index = None;
2246        let mut close_clicked = false;
2247        let mut fs_clicked = false;
2248        let mut max_clicked = false;
2249        let mut norm_clicked = false;
2250        let mut min_clicked = false;
2251
2252        for (i, win) in self.windows.iter_mut().enumerate().rev() {
2253            // 現在アクティブな空間かつ非最小化ウィンドウのみを対象とする
2254            if win.workspace != self.active_workspace || win.is_minimized {
2255                continue;
2256            }
2257            let win_x = if self.active_workspace == 1 && self.slide_out {
2258                win.x + 2000 // 画面外へ
2259            } else {
2260                win.x
2261            };
2262            if mx >= win_x
2263                && mx <= win_x + win.width as i32
2264                && my >= win.y
2265                && my <= win.y + win.height as i32
2266            {
2267                target_index = Some(i);
2268
2269                // タイトルバー判定 (Y: 0..30)
2270                if my < win.y + 30 {
2271                    let btn_w = 20;
2272                    let gap = 5;
2273                    let bx_close = win_x + win.width as i32 - 10 - btn_w;
2274                    let bx_fs = bx_close - btn_w - gap;
2275                    let bx_max = bx_fs - btn_w - gap;
2276                    let bx_norm = bx_max - btn_w - gap;
2277                    let bx_min = bx_norm - btn_w - gap;
2278
2279                    if btn_just_pressed {
2280                        if mx >= bx_close && mx <= bx_close + btn_w {
2281                            close_clicked = true;
2282                        } else if mx >= bx_fs && mx <= bx_fs + btn_w {
2283                            fs_clicked = true;
2284                        } else if mx >= bx_max && mx <= bx_max + btn_w {
2285                            max_clicked = true;
2286                        } else if mx >= bx_norm && mx <= bx_norm + btn_w {
2287                            norm_clicked = true;
2288                        } else if mx >= bx_min && mx <= bx_min + btn_w {
2289                            min_clicked = true;
2290                        } else {
2291                            // タイトルバークリックでドラッグ開始
2292                            win.is_dragging = true;
2293                            win.drag_offset_x = mx - win.x;
2294                            win.drag_offset_y = my - win.y;
2295                        }
2296                    }
2297                } else {
2298                    let mut tab_list = win.app.tabs();
2299                    let is_terminal = win.app.name() == "Terminal";
2300                    if is_terminal && tab_list.is_empty() {
2301                        tab_list.push(alloc::string::String::from("Shell"));
2302                    }
2303                    let has_tabs = !tab_list.is_empty();
2304                    let tab_w = if has_tabs { 100 } else { 0 };
2305
2306                    let local_x = mx - win_x;
2307                    let local_y = my - (win.y + 31);
2308
2309                    if has_tabs && local_x < tab_w {
2310                        // タブ領域のクリック処理
2311                        if btn_just_pressed {
2312                            let tab_y_click = local_y as u32;
2313                            if (8..=25).contains(&tab_y_click) && (75..=92).contains(&local_x) {
2314                                // '+' ボタン: タブ追加 → バックグラウンドスレッド起動
2315                                let new_tab_idx = win.app.tabs().len();
2316                                win.app.add_tab();
2317                                win.spawn_tab_thread(new_tab_idx);
2318                                self.dirty = true;
2319                                crate::kernel::audio::play_system_se(
2320                                    crate::kernel::audio::SeType::Apply,
2321                                );
2322                            } else if tab_y_click >= 40 {
2323                                let clicked_tab = ((tab_y_click - 40) / 42) as usize;
2324                                if clicked_tab < tab_list.len() {
2325                                    let relative_y = (tab_y_click - 40) % 42;
2326                                    if relative_y <= 36 {
2327                                        if (78..=92).contains(&local_x)
2328                                            && (10..=24).contains(&relative_y)
2329                                        {
2330                                            // 'x' ボタン: タブ削除 → スレッドを解放
2331                                            win.clear_tab_thread(clicked_tab);
2332                                            let should_close = win.app.close_tab(clicked_tab);
2333                                            if should_close {
2334                                                close_clicked = true;
2335                                            } else {
2336                                                crate::kernel::audio::play_system_se(
2337                                                    crate::kernel::audio::SeType::Apply,
2338                                                );
2339                                            }
2340                                        } else {
2341                                            win.app.switch_tab(clicked_tab);
2342                                        }
2343                                        self.dirty = true;
2344                                    }
2345                                }
2346                            }
2347                        }
2348                    } else {
2349                        // アプリ内部の処理(ローカルX座標はタブ幅分シフトする)
2350                        win.app
2351                            .on_mouse(local_x - tab_w, local_y, btn_left, btn_right, wheel);
2352                        // マウスを動かしただけで全画面再描画すると重くなるため、クリックやスクロール時のみ再描画
2353                        if btn_just_pressed || wheel != 0 || (btn_left != self.last_mouse_btn) {
2354                            self.dirty = true;
2355                        }
2356                    }
2357                }
2358
2359                handled = true;
2360                break;
2361            }
2362        }
2363
2364        // フォーカス切り替え(アクティブ化)と閉じる・サイズ変更処理
2365        if let Some(idx) = target_index {
2366            if btn_just_pressed {
2367                self.activate_window(idx);
2368            }
2369            if close_clicked {
2370                if let Some(w) = self.windows.last() {
2371                    self.add_dirty_rect(Rect::new(w.x, w.y, w.width, w.height));
2372                }
2373                self.windows.pop();
2374                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Close);
2375                self.dirty = true;
2376                if self.windows.is_empty() {
2377                    self.terminal_focused = true;
2378                }
2379            } else if fs_clicked {
2380                // 1. 空いているワークスペースを探す(2〜8)
2381                let mut target_ws = None;
2382                for ws in 2..=8 {
2383                    let mut used = false;
2384                    for w in &self.windows {
2385                        if w.workspace == ws && !w.is_minimized {
2386                            used = true;
2387                            break;
2388                        }
2389                    }
2390                    if !used {
2391                        target_ws = Some(ws);
2392                        break;
2393                    }
2394                }
2395                let target_ws = target_ws.unwrap_or(self.active_workspace);
2396
2397                let old_rect = self
2398                    .windows
2399                    .last()
2400                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2401                if let Some(r) = old_rect {
2402                    self.add_dirty_rect(r);
2403                }
2404
2405                if let Some(win) = self.windows.last_mut() {
2406                    win.is_fullscreen = true;
2407                    win.saved_x = win.x;
2408                    win.saved_y = win.y;
2409                    win.saved_w = win.width;
2410                    win.saved_h = win.height;
2411                    win.saved_ws = win.workspace;
2412                    let sw = screen.width;
2413                    let sh = screen.height;
2414                    win.x = 0;
2415                    win.y = 0;
2416                    win.resize(sw, sh);
2417                    win.workspace = target_ws;
2418                    self.active_workspace = target_ws;
2419                    self.dirty = true;
2420                }
2421                let sw = screen.width;
2422                let sh = screen.height;
2423                self.add_dirty_rect(Rect::new(0, 0, sw, sh));
2424                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
2425            } else if max_clicked {
2426                let old_rect = self
2427                    .windows
2428                    .last()
2429                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2430                if let Some(r) = old_rect {
2431                    self.add_dirty_rect(r);
2432                }
2433
2434                if let Some(win) = self.windows.last_mut() {
2435                    win.is_fullscreen = false;
2436                    win.saved_x = win.x;
2437                    win.saved_y = win.y;
2438                    win.saved_w = win.width;
2439                    win.saved_h = win.height;
2440                    let sh = screen.height.saturating_sub(crate::kernel::fn_bar::BAR_HEIGHT);
2441                    let sysmon_w = if screen.width >= 1920 { 518 } else { 300 };
2442                    let max_w = screen.width.saturating_sub(sysmon_w);
2443                    win.x = 0;
2444                    win.y = 0;
2445                    win.resize(max_w, sh);
2446                    self.dirty = true;
2447                }
2448
2449                let new_rect = self
2450                    .windows
2451                    .last()
2452                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2453                if let Some(r) = new_rect {
2454                    self.add_dirty_rect(r);
2455                }
2456                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
2457            } else if norm_clicked {
2458                let old_rect = self
2459                    .windows
2460                    .last()
2461                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2462                if let Some(r) = old_rect {
2463                    self.add_dirty_rect(r);
2464                }
2465
2466                if let Some(win) = self.windows.last_mut() {
2467                    win.is_fullscreen = false;
2468                    win.x = win.saved_x;
2469                    win.y = win.saved_y;
2470                    let (rw, rh) = (win.saved_w, win.saved_h);
2471
2472                    self.active_workspace = win.saved_ws;
2473                    win.workspace = win.saved_ws;
2474
2475                    win.resize(rw, rh);
2476                    self.dirty = true;
2477                }
2478
2479                let new_rect = self
2480                    .windows
2481                    .last()
2482                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2483                if let Some(r) = new_rect {
2484                    self.add_dirty_rect(r);
2485                }
2486                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
2487            } else if min_clicked {
2488                let old_rect = self
2489                    .windows
2490                    .last()
2491                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2492                if let Some(r) = old_rect {
2493                    self.add_dirty_rect(r);
2494                }
2495
2496                if let Some(win) = self.windows.last_mut() {
2497                    win.is_minimized = true;
2498                }
2499                self.dirty = true;
2500                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Close);
2501            }
2502        } else if btn_just_pressed {
2503            // ウィンドウ外をクリックした場合はターミナル等にフォーカスを戻す
2504            // ただし、右側ペイン(システムモニター:X >= 1600)をクリックした場合はターミナルにフォーカスを奪わない
2505            let sysmon_w = if screen.width >= 1920 { 518 } else { 300 };
2506            let sysmon_x = screen.width - sysmon_w;
2507            if mx < sysmon_x as i32 {
2508                self.terminal_focused = true;
2509            }
2510        }
2511
2512        self.last_mouse_x = mx;
2513        self.last_mouse_y = my;
2514        self.last_mouse_btn = btn_left;
2515
2516        handled
2517    }
2518
2519    /// キーボードイベントの処理(ファンクションキーおよびアクティブウィンドウ宛て)
2520    pub fn handle_key(
2521        &mut self,
2522        keycode: u8,
2523        pressed: bool,
2524        ascii: Option<char>,
2525        alt_pressed: bool,
2526        screen: &Screen,
2527    ) -> bool {
2528        if !pressed {
2529            return false;
2530        }
2531
2532        // --- ファンクションキーの絶対アサイン判定 ---
2533
2534        // 1. F1 (単体) & F1 (フォーカス時再押下でウィンドウ退避)
2535        if keycode == 0x3B && !alt_pressed {
2536            if self.terminal_focused && !self.slide_out {
2537                // すでにターミナルが前面・フォーカス中なら、ウィンドウ退避スライドへトグル
2538                self.slide_out = true;
2539                self.dirty = true;
2540            } else {
2541                // 初回(未フォーカス、または退避中)は一段でターミナルを前面+フォーカス化
2542                self.terminal_focused = true;
2543                self.slide_out = false;
2544                self.dirty = true;
2545            }
2546            crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
2547            return true;
2548        }
2549
2550        // 2. Alt + F1 〜 F8 (空間移動)
2551        if alt_pressed && (0x3B..=0x42).contains(&keycode) {
2552            let target_ws = if keycode == 0x3B {
2553                1
2554            } else {
2555                (keycode - 0x3C) + 2
2556            };
2557            self.active_workspace = target_ws;
2558            self.dirty = true;
2559
2560            // 移動先にウィンドウがあれば最前面をアクティブにする
2561            let mut last_win_idx = None;
2562            for (i, win) in self.windows.iter().enumerate() {
2563                if win.workspace == target_ws && !win.is_minimized {
2564                    last_win_idx = Some(i);
2565                }
2566            }
2567            if let Some(idx) = last_win_idx {
2568                self.activate_window(idx);
2569            } else {
2570                self.terminal_focused = true;
2571            }
2572            crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
2573            return true;
2574        }
2575
2576        // 3. Alt + F9 (アクティブウィンドウの最小化)
2577        if alt_pressed && keycode == 0x43 {
2578            let active_is_matching = if let Some(win) = self.windows.last() {
2579                win.workspace == self.active_workspace && !win.is_minimized
2580            } else {
2581                false
2582            };
2583
2584            if active_is_matching {
2585                let old_rect = self
2586                    .windows
2587                    .last()
2588                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2589                if let Some(r) = old_rect {
2590                    self.add_dirty_rect(r);
2591                }
2592
2593                if let Some(win) = self.windows.last_mut() {
2594                    win.is_minimized = true;
2595                }
2596                self.dirty = true;
2597
2598                // フォーカスを背面のウィンドウまたはターミナルに戻す
2599                let mut found_next = false;
2600                let len = self.windows.len();
2601                if len > 1 {
2602                    for i in (0..len - 1).rev() {
2603                        let is_candidate = {
2604                            let w = &self.windows[i];
2605                            w.workspace == self.active_workspace && !w.is_minimized
2606                        };
2607                        if is_candidate {
2608                            self.activate_window(i);
2609                            found_next = true;
2610                            break;
2611                        }
2612                    }
2613                }
2614                if !found_next {
2615                    self.terminal_focused = true;
2616                }
2617                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Close);
2618                // 最小化時の音
2619            }
2620            return true;
2621        }
2622
2623        // 4. Alt + F10 (通常のフローティング状態へ移行)
2624        if alt_pressed && keycode == 0x44 {
2625            let matches_ws = if let Some(win) = self.windows.last() {
2626                win.workspace == self.active_workspace
2627            } else {
2628                false
2629            };
2630
2631            if matches_ws {
2632                let old_rect = self
2633                    .windows
2634                    .last()
2635                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2636                if let Some(r) = old_rect {
2637                    self.add_dirty_rect(r);
2638                }
2639
2640                if let Some(win) = self.windows.last_mut() {
2641                    win.is_fullscreen = false;
2642                    win.x = win.saved_x;
2643                    win.y = win.saved_y;
2644                    let (rw, rh) = (win.saved_w, win.saved_h);
2645                    win.resize(rw, rh);
2646                }
2647                self.dirty = true;
2648
2649                let new_rect = self
2650                    .windows
2651                    .last()
2652                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2653                if let Some(r) = new_rect {
2654                    self.add_dirty_rect(r);
2655                }
2656                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
2657            }
2658            return true;
2659        }
2660
2661        // 5. Alt + F11 (フローティング最大化)
2662        if alt_pressed && keycode == 0x57 {
2663            let matches_ws = if let Some(win) = self.windows.last() {
2664                win.workspace == self.active_workspace
2665            } else {
2666                false
2667            };
2668
2669            if matches_ws {
2670                let old_rect = self
2671                    .windows
2672                    .last()
2673                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2674                if let Some(r) = old_rect {
2675                    self.add_dirty_rect(r);
2676                }
2677
2678                if let Some(win) = self.windows.last_mut() {
2679                    if !win.is_fullscreen {
2680                        win.saved_x = win.x;
2681                        win.saved_y = win.y;
2682                        win.saved_w = win.width;
2683                        win.saved_h = win.height;
2684                    }
2685
2686                    // メイン空間表示可能領域 (左端縦タブ100px、右端モニター領域を除く)
2687                    let sysmon_w = if screen.width >= 1920 { 518 } else { 300 };
2688                    let avail_w = screen.width.saturating_sub(100 + sysmon_w);
2689                    win.x = 100;
2690                    win.y = 0;
2691                    let sh = screen.height.saturating_sub(crate::kernel::fn_bar::BAR_HEIGHT);
2692                    win.resize(avail_w, sh);
2693                }
2694                self.dirty = true;
2695
2696                let new_rect = self
2697                    .windows
2698                    .last()
2699                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2700                if let Some(r) = new_rect {
2701                    self.add_dirty_rect(r);
2702                }
2703                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
2704            }
2705            return true;
2706        }
2707
2708        // 6. Alt + F12 (アプリ全体のフルスクリーン化)
2709        if alt_pressed && keycode == 0x58 {
2710            // 空きスロット (2..=8) 探索 (可変借用の前に実施して競合を回避)
2711            let mut target_ws = None;
2712            for ws in 2..=8 {
2713                let mut occupied = false;
2714                for w in &self.windows {
2715                    if w.workspace == ws && !w.is_minimized {
2716                        occupied = true;
2717                        break;
2718                    }
2719                }
2720                if !occupied {
2721                    target_ws = Some(ws);
2722                    break;
2723                }
2724            }
2725
2726            if let Some(ws) = target_ws {
2727                let old_rect = self
2728                    .windows
2729                    .last()
2730                    .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2731                if let Some(r) = old_rect {
2732                    self.add_dirty_rect(r);
2733                }
2734
2735                if let Some(win) = self.windows.last_mut() {
2736                    if !win.is_fullscreen {
2737                        win.saved_x = win.x;
2738                        win.saved_y = win.y;
2739                        win.saved_w = win.width;
2740                        win.saved_h = win.height;
2741                    }
2742
2743                    win.is_fullscreen = true;
2744                    win.workspace = ws;
2745                    win.x = 0;
2746                    win.y = 0;
2747                    let (sw, sh) = (screen.width, screen.height);
2748                    win.resize(sw, sh);
2749                }
2750                self.active_workspace = ws;
2751                self.dirty = true;
2752                let (sw, sh) = (screen.width, screen.height);
2753                self.add_dirty_rect(Rect::new(0, 0, sw, sh));
2754                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
2755            } else {
2756                // 空きスロット上限による拒否 (警告音)
2757                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Close);
2758            }
2759            return true;
2760        }
2761
2762        // --- 通常のアプリ宛キーイベント送信 ---
2763        if self.terminal_focused {
2764            return false;
2765        }
2766        let is_active = if let Some(win) = self.windows.last() {
2767            win.workspace == self.active_workspace && !win.is_minimized
2768        } else {
2769            false
2770        };
2771
2772        if is_active {
2773            // 応答していないアプリが前面なら、Delete でそのアプリを止める(TODO R2 (a)。帯に案内を出している。
2774            // アプリは応答していないので、このキーをアプリへ渡しても処理されない)。
2775            if keycode == 0x53 && pressed && self.windows.last().is_some_and(|w| w.unresponsive()) {
2776                let idx = self.windows.len() - 1;
2777                if let Some(name) = self.kill_window(idx) {
2778                    crate::warn!("[WM] 応答していない '{}' を Delete で止める", name);
2779                }
2780                return true;
2781            }
2782            // 【2026-11-18 TODO R2 (d)】応答していないアプリにタブが 2 つ以上あれば、End で今動いているタブだけを止める。
2783            if keycode == 0x4F
2784                && pressed
2785                && self.windows.last().is_some_and(|w| w.unresponsive() && w.app.tabs().len() > 1)
2786            {
2787                let idx = self.windows.len() - 1;
2788                let running = self.windows.last().map(|w| w.app.running_tab()).unwrap_or(0);
2789                if let Some(name) = self.kill_tab(idx, running) {
2790                    crate::warn!("[WM] 応答していないタブ '{}' を End で止める", name);
2791                }
2792                return true;
2793            }
2794            if let Some(win) = self.windows.last_mut() {
2795                win.app.on_key(keycode, pressed, ascii);
2796            }
2797
2798            let rect = self
2799                .windows
2800                .last()
2801                .map(|win| Rect::new(win.x, win.y, win.width, win.height));
2802            if let Some(r) = rect {
2803                self.add_dirty_rect(r);
2804            }
2805            self.dirty = true;
2806            return true;
2807        }
2808        false
2809    }
2810
2811    /// 何らかのアクティブなウィンドウがタイマー再描画を要求しているか
2812    pub fn needs_timer_redraw(&self) -> bool {
2813        for win in &self.windows {
2814            if win.workspace == self.active_workspace
2815                && !win.is_minimized
2816                && win.app.needs_timer_redraw()
2817            {
2818                return true;
2819            }
2820        }
2821        false
2822    }
2823}
2824
2825pub fn init() {
2826    unsafe {
2827        GLOBAL_WM = Some(ReentrantMutex::new(WindowManager::new()));
2828    }
2829}
2830
2831/// ウィンドウの題名の帯のボタンの絵(閉じる・全画面・最大化・通常化・最小化)と大きさ。
2832static TITLE_ICONS: [&[u8]; 5] = [
2833    include_bytes!("../../icons/ic_fluent_dismiss_circle_20_regular.svg"),
2834    include_bytes!("../../icons/ic_fluent_full_screen_maximize_20_regular.svg"),
2835    include_bytes!("../../icons/ic_fluent_maximize_20_regular.svg"),
2836    include_bytes!("../../icons/ic_fluent_full_screen_minimize_20_regular.svg"),
2837    include_bytes!("../../icons/ic_fluent_subtract_circle_20_regular.svg"),
2838];
2839const TITLE_ICON_PX: u32 = 20;
2840
2841/// 題名の帯のボタンの絵を、メインループに入る前に描いて(ラスタライズして)おく(TODO R4、2026-11-16)。
2842/// 以前は最初のウィンドウを開いた周にメインループがこれを描き、その 1 周が 65〜78ms かかっていた
2843/// (一時計測で、40ms を超えた周の core 0 の割り込み位置が `svg::get_or_rasterize` の中だった)。
2844pub fn prewarm_title_icons() {
2845    for icon in TITLE_ICONS {
2846        let _ = crate::os_lib::svg::get_or_rasterize(icon, TITLE_ICON_PX);
2847    }
2848}
2849
2850/// ウィンドウ管理を取る(同じスレッドなら入り直せる。持ち主はスレッドで見る。TODO R4 (a)、2026-11-17。
2851/// 作りと理由は `kernel/reentrant_lock.rs`)。割り込みの中から呼ばないこと。
2852pub fn get_instance() -> ReentrantMutexGuard<'static, WindowManager> {
2853    let me = crate::kernel::scheduler::current_owner_token();
2854    // init() 前に呼ばれた場合も panic せず、その場で初期化する
2855    unsafe {
2856        GLOBAL_WM
2857            .get_or_insert_with(|| ReentrantMutex::new(WindowManager::new()))
2858            .lock_as(me, wm_lock_wait)
2859    }
2860}
2861
2862/// ウィンドウ管理の錠を別のスレッドが持っていて回り続けたときに CPU を譲る。同じコアの持ち主は、
2863/// 待つ側が譲らないと動けない(待つ側が `gui_shell`〔Realtime〕ならなおさら)。割り込みを止めている所・
2864/// 切り替えを止めている所・PID 0(起動の流れ・待機)では譲らずに回り続ける(以前と同じ)。
2865fn wm_lock_wait() {
2866    let daif: u64;
2867    // SAFETY: DAIF を読むだけ。
2868    unsafe { core::arch::asm!("mrs {}, daif", out(reg) daif, options(nomem, nostack, preserves_flags)) };
2869    let irqs_on = daif & (1 << 7) == 0;
2870    let me = crate::kernel::scheduler::current_owner_token();
2871    if irqs_on
2872        && crate::kernel::scheduler::is_preempt_enabled()
2873        && me < crate::kernel::reentrant_lock::PID0_TOKEN_BASE
2874    {
2875        crate::kernel::scheduler::yield_now();
2876    }
2877}
2878
2879/// 終わらせるスレッド(強制終了・panic の回復)がウィンドウ管理の錠を持ったままなら外す(TODO R4 (a))。
2880/// 以前は持ったまま終わると、ほかのコアのメインループが永久に回って待つ形だった。
2881/// # Safety
2882/// 呼んだスレッドは二度と再開しないこと(このスレッドの持っていた参照は以後使われない)。
2883pub unsafe fn force_release_lock_of_current() {
2884    let me = crate::kernel::scheduler::current_owner_token();
2885    // SAFETY: 呼び出し側の約束どおり、持ち主のスレッドは再開しない。
2886    unsafe {
2887        if let Some(m) = (*core::ptr::addr_of!(GLOBAL_WM)).as_ref() {
2888            let _ = m.force_release_if_owner(me);
2889        }
2890    }
2891}
2892
2893use core::sync::atomic::{AtomicUsize, Ordering};
2894