1#![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
17pub trait App {
19 fn name(&self) -> &str;
20
21 fn is_proxy(&self) -> bool {
23 false
24 }
25
26 fn get_shared_buffer(&self) -> Option<alloc::sync::Arc<spin::Mutex<alloc::vec::Vec<u32>>>> {
28 None
29 }
30
31 fn instance_info(&self) -> alloc::string::String {
33 alloc::string::String::new()
34 }
35
36 fn draw(&mut self, screen: &Screen, win_x: u32, win_y: u32, win_w: u32, win_h: u32);
38
39 fn on_mouse(&mut self, local_x: i32, local_y: i32, btn_left: bool, btn_right: bool, wheel: i32);
41
42 fn on_key(&mut self, keycode: u8, pressed: bool, ascii: Option<char>);
44
45 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 fn memory_checkpoint(&mut self) {}
65 fn add_tab(&mut self) {}
66 fn open_url_in_new_tab(&mut self, _url: &str) {}
68 fn close_tab(&mut self, _idx: usize) -> bool {
70 true
71 }
72
73 fn open_file_dialog(&mut self) {}
75 fn save_file(&mut self) {}
77
78 fn tab_thread_fn(&self) -> Option<fn()> {
82 None
83 }
84
85 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 fn needs_timer_redraw(&self) -> bool {
93 false
94 }
95
96 fn get_buffer_updated_flag(&self) -> Option<alloc::sync::Arc<core::sync::atomic::AtomicBool>> {
100 None
101 }
102
103 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 fn on_resize(&mut self, _width: u32, _height: u32) {}
111
112 fn is_stopped(&self) -> bool {
115 false
116 }
117
118 fn unresponsive_ms(&self) -> Option<u64> {
122 None
123 }
124
125 fn kill_tab(&mut self, _idx: usize) -> bool {
128 false
129 }
130
131 fn running_tab(&self) -> usize {
134 self.active_tab()
135 }
136
137 fn tab_kill_pending(&self) -> Option<usize> {
139 None
140 }
141
142 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 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 pub live_title: Arc<Mutex<Option<String>>>,
185 pub needs_timer_redraw: Arc<AtomicBool>,
186 pub buffer_updated: Arc<AtomicBool>,
189 pub heartbeat_ms: Arc<core::sync::atomic::AtomicU64>,
192 pub tab_kill: Arc<AtomicUsize>,
194 pub running_tab: Arc<AtomicUsize>,
196 pending: crate::kernel::pending_events::PendingEvents<AppEvent>,
199 deferred_active: Option<usize>,
201 cached_title: Option<String>,
203 cached_tabs: Vec<String>,
204 cached_active: usize,
205}
206
207fn 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 fn flush_pending(&mut self) {
227 if self.pending.is_empty() {
228 return;
229 }
230 if !self.is_alive.load(Ordering::Relaxed) {
231 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 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 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 }
302
303 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 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 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 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 !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 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
449pub 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 pub buffer_updated: Arc<AtomicBool>,
471 pub heartbeat_ms: Arc<core::sync::atomic::AtomicU64>,
473 pub tab_kill: Arc<AtomicUsize>,
475 pub running_tab: Arc<AtomicUsize>,
476 pub width: u32,
477 pub height: u32,
478}
479
480#[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
491static DRAW_TARGETS: Mutex<alloc::collections::BTreeMap<usize, DrawTarget>> =
493 Mutex::new(alloc::collections::BTreeMap::new());
494
495pub 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
510const 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 KILL_DROPS.reset_row(row);
525 ptr.store(params as usize, Ordering::Release);
526 return;
527 }
528 }
529 }
531
532static KILL_DROPS: crate::kernel::kill_drop::KillDropTable = crate::kernel::kill_drop::KillDropTable::new();
535
536fn 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
544pub 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
554pub fn is_app_runner_pid(pid: usize) -> bool {
556 pid != 0 && RUNNER_PIDS.iter().any(|slot| slot.load(Ordering::Acquire) == pid + 1)
557}
558
559fn 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
571pub unsafe fn drop_runner_of_dead_process(pid: usize) {
579 let Some((p, row)) = unregister_runner(pid) else { return };
580 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 let stack_objs = unsafe { KILL_DROPS.drain(row) };
588 let mid = crate::kernel::allocator::get_heap_stats().0;
589 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 let closed = crate::kernel::allocator::MEM_LEDGER.close_group_of(pid);
601 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
619static TEARDOWN_PID: AtomicUsize = AtomicUsize::new(0);
621
622pub 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
632static 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
638pub 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 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
672static LAST_KILL_REQUEST_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
674
675#[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#[inline]
690pub fn current_group() -> u8 {
691 crate::kernel::allocator::MEM_LEDGER.core_group(crate::kernel::scheduler::core_id())
692}
693
694#[inline]
696pub fn group_stopped(g: u8) -> bool {
697 crate::kernel::allocator::MEM_LEDGER.is_closed(g)
698}
699
700pub 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
713pub fn abort_wait_if_stopped(close: impl FnOnce()) -> bool {
719 if current_group_stopped() {
720 return true;
722 }
723 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 tab_kill_pending_for_current()
735}
736
737pub fn app_kill_pending() -> bool {
742 current_runner_params().is_some_and(|p| !p.is_alive.load(Ordering::Relaxed))
743}
744
745fn 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 return unsafe { p.as_ref() };
755 }
756 }
757 None
758}
759
760pub 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
773static TAB_KILL_GATE_AT_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
777const TAB_KILL_GATE_MS: u64 = 60_000;
779static LAYOUT_POLLS: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
781const LAYOUT_POLL_EVERY: u32 = 64;
783
784#[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#[inline]
813pub fn layout_check() -> bool {
814 layout_kill_unwind_check() || layout_aborting()
815}
816
817static KILL_UNWIND_PID: AtomicUsize = AtomicUsize::new(0);
819static KILL_UNWIND_AT_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
820const KILL_UNWIND_MAX_MS: u64 = 2_000;
822
823fn 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#[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#[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
865static LAST_TAB_KILL_REQUEST_MS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
867
868fn 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 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#[inline]
923pub fn kill_checkpoint() {
924 if app_kill_pending() {
925 terminate_current_app_thread("閉じられた/強制終了されたアプリ");
926 }
927 mem_quota_checkpoint();
928}
929
930fn on_group_closed(g: u8, pid: usize) {
939 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 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
975pub 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#[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(¬ice), Some(pid));
1034}
1035
1036pub fn terminate_current_app_thread(reason: &str) -> ! {
1039 terminate_app_thread_inner(reason, None, None)
1040}
1041
1042fn 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 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
1066fn 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 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 crate::os_lib::web_engine::fetch_limit::on_process_died(pid);
1111 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 let target = match notice {
1121 Some(_) => DRAW_TARGETS.try_lock().and_then(|t| t.get(&pid).cloned()),
1122 None => None,
1123 };
1124 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 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 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 let params: &mut AppRunnerParams = unsafe { &mut *params_ptr };
1160
1161 let mut w = params.width;
1162 let mut h = params.height;
1163
1164 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 kill_checkpoint();
1174 take_tab_kill(params);
1176 params.app.memory_checkpoint();
1178 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 let loop_start_us = crate::kernel::timer::get_system_time_us();
1183
1184 let app_needs_timer = params.app.needs_timer_redraw();
1186 params.needs_timer_redraw.store(app_needs_timer, Ordering::Relaxed);
1187
1188 let events = core::mem::take(&mut *params.event_queue.lock());
1191
1192 let mut need_redraw = false;
1193
1194 for evt in events {
1195 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 {
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 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 if need_redraw || time_since_last_draw >= 33 {
1263 {
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 {
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 params.buffer_updated.store(true, Ordering::Release);
1293 } else {
1294 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 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 drop(unsafe { Box::from_raw(p) });
1333 }
1334 if let Some(g) = crate::kernel::allocator::MEM_LEDGER.close_group_of(pid) {
1336 on_group_closed(g, pid);
1337 }
1338 } else {
1339 drop(unsafe { Box::from_raw(params_ptr) });
1342 }
1343}
1344
1345pub 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 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 pub tab_pids: alloc::vec::Vec<Option<usize>>,
1368 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 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 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 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 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 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 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 crate::warn!(
1469 "[WM] tab {} のスレッドを起動できません(ヒープ不足)",
1470 tab_idx
1471 );
1472 }
1473 }
1474 }
1475
1476 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 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 pub dirty_rects: Vec<Rect>,
1527
1528 last_mouse_x: i32,
1530 last_mouse_y: i32,
1531 last_mouse_btn: bool,
1532}
1533
1534pub 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 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 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 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 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 win.workspace = self.active_workspace;
1641 let name = win.title.clone();
1642 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 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 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 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 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 pub fn activate_window(&mut self, idx: usize) {
1746 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 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 pub fn any_window_covers_rect(&self, x0: i32, y0: i32, x1: i32, y1: i32) -> bool {
1772 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 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 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; let w = win.width;
1813 let h = win.height;
1814
1815 if let Some(ref mut win_buf) = win.buffer {
1816 screen.set_render_target(win_buf.as_mut_ptr(), w, h);
1818
1819 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 {
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 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 if let Some(shared_buf_arc) = win.app.get_shared_buffer() {
1867 if let Some(shared_buf) = shared_buf_arc.try_lock() {
1868 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 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 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 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 screen.boxfill(0, 0, w, h, Color(config.theme.app_bg)); 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 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 screen.boxfill(0, 0, w, 30, title_bar_color);
1961
1962 let shadow_color = Color(0xFF111217);
1964 screen.boxfill(0, 0, w, 1, shadow_color); screen.boxfill(0, 0, 1, h, shadow_color); screen.boxfill(w - 1, 0, w, h, shadow_color); screen.boxfill(0, h - 1, w, h, shadow_color); screen.boxfill(1, 1, w - 1, 1 + border_w, current_frame_color); screen.boxfill(1, 1, 1 + border_w, h - 1, current_frame_color); screen.boxfill(w - 1 - border_w, 1, w - 1, h - 1, current_frame_color); screen.boxfill(1, h - 1 - border_w, w - 1, h - 1, current_frame_color); screen.boxfill(1, 30, w - 1, 30 + border_w, current_frame_color); 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 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 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 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 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 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 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 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)); screen.draw_string_vector(10, app_y + 10, "TABS", Color(config.theme.tab_inactive_fg), 14);
2014
2015 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 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 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 screen.reset_render_target();
2089
2090 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 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 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 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 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 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 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 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 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 } 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 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 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 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 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 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 win.app
2351 .on_mouse(local_x - tab_w, local_y, btn_left, btn_right, wheel);
2352 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 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 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 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 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 if keycode == 0x3B && !alt_pressed {
2536 if self.terminal_focused && !self.slide_out {
2537 self.slide_out = true;
2539 self.dirty = true;
2540 } else {
2541 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 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 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 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 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 }
2620 return true;
2621 }
2622
2623 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 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 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 if alt_pressed && keycode == 0x58 {
2710 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 crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Close);
2758 }
2759 return true;
2760 }
2761
2762 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 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 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 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
2831static 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
2841pub 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
2850pub fn get_instance() -> ReentrantMutexGuard<'static, WindowManager> {
2853 let me = crate::kernel::scheduler::current_owner_token();
2854 unsafe {
2856 GLOBAL_WM
2857 .get_or_insert_with(|| ReentrantMutex::new(WindowManager::new()))
2858 .lock_as(me, wm_lock_wait)
2859 }
2860}
2861
2862fn wm_lock_wait() {
2866 let daif: u64;
2867 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
2879pub unsafe fn force_release_lock_of_current() {
2884 let me = crate::kernel::scheduler::current_owner_token();
2885 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