1#![allow(dead_code, unused_variables, unused_imports)]
3
4use crate::kernel::draw;
5use crate::kernel::vector_font;
6
7pub static RELAYOUT_IN_DRAW_TICKS: core::sync::atomic::AtomicU32 =
13 core::sync::atomic::AtomicU32::new(0);
14
15static LAST_DUMP_TICK: core::sync::atomic::AtomicUsize =
19 core::sync::atomic::AtomicUsize::new(0);
20const DUMP_INTERVAL_TICKS: usize = 500;
22
23pub static DRAW_GAP_SUM: core::sync::atomic::AtomicUsize =
24 core::sync::atomic::AtomicUsize::new(0);
25pub static DRAW_GAP_MAX: core::sync::atomic::AtomicUsize =
26 core::sync::atomic::AtomicUsize::new(0);
27static DRAW_LAST_END: core::sync::atomic::AtomicUsize =
28 core::sync::atomic::AtomicUsize::new(0);
29use crate::os_lib::css::parse_color;
30use alloc::format;
31use alloc::string::String;
32use alloc::vec::Vec;
33
34use super::draw_helpers::{
35 bg_clip_rect, bg_origin_shift, blend_pixel, clip_inside, draw_background_image, draw_border,
36 draw_border_with_style, draw_decoration_line, draw_gradation, draw_img_object_fit,
37 draw_individual_borders, draw_outline, draw_rotated_rect_filled, draw_skewed_rect_filled, extract_border_color,
38 extract_border_style, parse_clip_shape, parse_clip_shape_with_font, point_in_rounded_rect,
39};
40use super::helpers::{extract_url_path, hash_str, parse_font_size, url_encode};
41use super::image::{enqueue_image, ImageFetchReq, IMAGE_QUEUE};
42use super::video::{
43 stop_video_playback, video_playback_thread, VideoPlayState, CURRENT_VIDEO_FRAME, VIDEO_STATE,
44};
45use super::{
46 key_name_for, HyperlinkArea, ASYNC_LOAD, NEXT_ENGINE_ID, SVG_LOAD, SVG_SAVE, SVG_WRAP,
47};
48
49const DBLCLICK_MAX_TICKS: usize = 50;
51
52fn log_bg_image_miss(path: &str, cache_len: usize, site: &str) {
58 static MISS: spin::Mutex<alloc::collections::BTreeSet<alloc::string::String>> =
59 spin::Mutex::new(alloc::collections::BTreeSet::new());
60 let key = alloc::format!("{}@{}", site, path);
61 let mut seen = MISS.lock();
62 if seen.insert(key) {
63 crate::warn!(
64 "[IMG][MISS] 背景画像がキャッシュに無い site={} path={} cache_entries={}",
65 site,
66 path,
67 cache_len
68 );
69 }
70}
71
72impl super::WebEngine {
73 pub fn draw(
97 &mut self,
98 screen: &draw::Screen,
99 win_x: u32,
100 win_y: u32,
101 win_w: u32,
102 win_h: u32,
103 top_offset: i32,
104 ) {
105 let draw_start_tick = crate::kernel::timer::get_ticks();
106 if self.frame_depth == 0 {
107 super::video::begin_app_draw();
108 }
109 self.relayout_done_this_draw = false;
110 {
116 use core::sync::atomic::Ordering;
117 let last = DRAW_LAST_END.load(Ordering::Relaxed);
118 if last != 0 {
119 let gap = draw_start_tick.wrapping_sub(last);
120 DRAW_GAP_SUM.fetch_add(gap, Ordering::Relaxed);
121 DRAW_GAP_MAX.fetch_max(gap, Ordering::Relaxed);
122 }
123 }
124 let relayout_before = RELAYOUT_IN_DRAW_TICKS.load(core::sync::atomic::Ordering::Relaxed);
127 if !self.pending_scripts.is_empty() && !self.loading {
129 let _t0 = crate::kernel::timer::get_ticks();
130 self.run_pending_scripts(top_offset, win_w, win_h);
131 RELAYOUT_IN_DRAW_TICKS.fetch_add(
132 crate::kernel::timer::get_ticks().wrapping_sub(_t0) as u32,
133 core::sync::atomic::Ordering::Relaxed,
134 );
135 }
136 let theme = &crate::kernel::config::get_config().theme;
137 let now_tick = crate::kernel::timer::get_ticks();
148 super::fetch_limit::set_draw_stage(2);
152
153 super::font_queue::pump();
154 {
157 use core::sync::atomic::{AtomicU32, Ordering};
158 static N: AtomicU32 = AtomicU32::new(0);
159 if N.fetch_add(1, Ordering::Relaxed).is_multiple_of(25) {
160 super::font_queue::diag_line();
161 }
162 }
163 super::image::pump();
164 if super::font_queue::take_fonts_updated() {
165 if self.pending_reflow_since == 0 {
167 self.pending_reflow_since = now_tick;
168 }
169 self.pending_reflow_last = now_tick;
170 }
171
172 if self.poll_image_results() {
174 if self.pending_reflow_since == 0 {
186 self.pending_reflow_since = now_tick;
187 }
188 self.pending_reflow_last = now_tick;
189 self.dirty = true;
190 self.dirty_reason = "render.rs:image_arrived";
191 }
192
193 {
204 const QUIET: usize = 200;
214 const MAX_WAIT: usize = 600;
217 if self.pending_reflow_since != 0 {
218 let quiet_enough = now_tick.wrapping_sub(self.pending_reflow_last) >= QUIET;
219 let waited_enough = now_tick.wrapping_sub(self.pending_reflow_since) >= MAX_WAIT;
220 if quiet_enough || waited_enough {
227 self.pending_reflow_since = 0;
228 self.pending_reflow_last = 0;
229 self.dom_needs_rebuild = true;
232 let html = self.last_html.clone();
262 let _t0 = crate::kernel::timer::get_ticks();
263 super::fetch_limit::set_draw_stage(3);
264
265 self.parse_and_layout(&html, None, top_offset, self.win_w, self.win_h);
266
267 super::fetch_limit::set_draw_stage(4);
268 RELAYOUT_IN_DRAW_TICKS.fetch_add(
269 crate::kernel::timer::get_ticks().wrapping_sub(_t0) as u32,
270 core::sync::atomic::Ordering::Relaxed,
271 );
272 self.dirty = true;
273 self.dirty_reason = "render.rs:reflow_coalesced";
274 }
275 }
276 }
277
278 if self.ready_complete_pending {
284 let settle_ms = super::site_hooks::hooks().load_settle_ms(&self.current_host);
285 let now = crate::kernel::timer::get_system_time_ms();
286 let nodes = self.js_runtime.dom().borrow().nodes.len();
287 let busy = !self.pending_scripts.is_empty()
288 || self.executing_script
289 || super::fetch_limit::active() != 0
290 || super::font_queue::pending_len() != 0
291 || super::image::pending_count() != 0
292 || (settle_ms.is_some() && nodes != self.ready_last_nodes);
293 if busy {
294 self.ready_last_nodes = nodes;
295 self.ready_interactive_at = now;
296 }
297 let waited = crate::kernel::timer::get_system_time_ms().saturating_sub(self.ready_interactive_at);
298 if !busy && waited >= settle_ms.unwrap_or(0) {
299 self.ready_complete_now = true;
300 }
301 }
302 if self.ready_complete_pending && core::mem::take(&mut self.ready_complete_now) {
303 self.ready_complete_pending = false;
304 self.js_runtime.set_document_ready_state("complete");
305 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
306 }
307 if self.js_runtime.pump_timers(30) {
310 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
311 self.process_pending_location(top_offset);
312 }
313
314 if self.pending_scripts.is_empty() && !self.loading && self.run_dynamic_scripts() {
316 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
317 self.dirty = true;
318 self.dirty_reason = "dynamic_scripts";
319 }
320
321 self.process_media_request(top_offset);
323 super::site_hooks::hooks().page_tick(&self.current_url_with_hash, self.frame_depth, &mut self.js_runtime);
324
325 if self.anim_engine.is_active() {
328 self.tick_animations(top_offset);
329 }
330 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
333
334 if self.scroll_anim_active {
336 self.tick_scroll_anim();
337 }
338
339 {
347 let (pending_abs, pending_by) = {
348 let mut dom = self.js_runtime.dom().borrow_mut();
349 (dom.pending_scroll_abs_y.take(), dom.pending_scroll_by_y.take())
350 };
351 if pending_abs.is_some() || pending_by.is_some() {
352 let base = pending_abs.unwrap_or(self.scroll_y);
353 let target = (base + pending_by.unwrap_or(0)).max(0).min(self.max_scroll_y);
354 if target != self.scroll_y {
355 self.scroll_y = target;
356 self.fire_scroll_and_sync();
357 self.dirty = true;
358 self.dirty_reason = "render.rs:102";
359 }
360 }
361 }
362
363 let mut loaded_result = None;
365 {
366 let mut lock = ASYNC_LOAD.lock();
367 if let Some(pos) = lock
368 .requests
369 .iter()
370 .position(|r| r.owner == self.engine_id && (r.status == 2 || r.status == 3))
371 {
372 let mut req = lock.requests.remove(pos);
373 if req.status == 2 {
374 loaded_result = Some(Ok((req.result_body.unwrap_or_default(), req.result_dom.take())));
375 } else {
376 loaded_result = Some(Err(req.error_msg.unwrap_or_default()));
377 }
378 }
379 }
380
381 if let Some(res) = loaded_result {
382 self.loading = false;
383 match res {
384 Ok((body, pre_parsed_dom)) => {
385 {
388 let _t0 = crate::kernel::timer::get_ticks();
389 self.parse_and_layout(&body, pre_parsed_dom, top_offset, self.win_w, self.win_h);
390 RELAYOUT_IN_DRAW_TICKS.fetch_add(
391 crate::kernel::timer::get_ticks().wrapping_sub(_t0) as u32,
392 core::sync::atomic::Ordering::Relaxed,
393 );
394 }
395 if self.elements.iter().any(|e| e.is_video) {
397 if self.video_controls.subtitle_tracks.is_empty() {
398 let ja_vtt_text = "WEBVTT\n\n00:00.500 --> 00:04.000\nAtmOS ネイティブ Web ブラウザエンジン\n\n00:04.500 --> 00:08.500\nARM64 ベアメタル環境で動画と字幕を高速描画\n\n00:09.000 --> 00:15.000\n[CC] ボタンまたは C キーで字幕言語を瞬時に切り替え可能\n";
399 let en_vtt_text = "WEBVTT\n\n00:00.500 --> 00:04.000\nAtmOS Native Web Browser Engine\n\n00:04.500 --> 00:08.500\nHigh performance video & subtitle rendering on baremetal ARM64\n\n00:09.000 --> 00:15.000\nSwitch subtitle tracks instantly via [CC] button or C key\n";
400 if let Ok(ja_vtt) = super::vtt::WebVtt::parse(ja_vtt_text) {
401 self.video_controls.add_subtitle_track(super::vtt::SubtitleTrack::new("日本語", "ja", "subtitles", ja_vtt));
402 }
403 if let Ok(en_vtt) = super::vtt::WebVtt::parse(en_vtt_text) {
404 self.video_controls.add_subtitle_track(super::vtt::SubtitleTrack::new("English", "en", "subtitles", en_vtt));
405 }
406 }
407 } else {
408 self.video_controls.subtitle_tracks.clear();
409 self.video_controls.active_track_idx = None;
410 }
411 }
412 Err(e) => {
413 crate::warn!("[NET] BROWSER: Load page FAILED. err={}", e);
414 let schema = if self.current_is_https {
415 "https://"
416 } else {
417 "http://"
418 };
419 let err_html = alloc::format!(
420 "<html><title>Connection Error</title><body style=\"background-color: #282a36; color: #f8f8f2;\"><h1 style=\"color: #ff5555;\">HTTP Request Failed</h1><p>Failed to connect to {}{}{}</p><p>Error detail: {}</p><hr style=\"color: #6272a4;\"><p><a href=\"/\">Go Home</a></p></body></html>",
421 schema, self.current_host, self.current_path, e
422 );
423 {
424 let _t0 = crate::kernel::timer::get_ticks();
425 self.parse_and_layout(&err_html, None, top_offset, self.win_w, self.win_h);
426 RELAYOUT_IN_DRAW_TICKS.fetch_add(
427 crate::kernel::timer::get_ticks().wrapping_sub(_t0) as u32,
428 core::sync::atomic::Ordering::Relaxed,
429 );
430 }
431 }
432 }
433 }
434
435 if !self.video_playing && !self.loading {
437 if let Some(el) = self.elements.iter().find(|e| e.is_video && e.video_autoplay && !e.video_src.is_empty()) {
438 self.video_playing = true;
439 let v_width = if el.width > 0 { el.width } else { (win_w as i32 - 80).clamp(400, 800) };
440 let v_loop = el.video_loop;
441 let mut state = VIDEO_STATE.lock();
442 *state = Some(VideoPlayState {
443 src_url: el.video_src.clone(),
444 x: el.x_offset.max(0) as u32,
445 y: el.y_offset.max(0) as u32,
446 width: v_width as u32,
447 height: el.height as u32,
448 playing: true,
449 stop_request: false,
450 paused: false,
451 loop_playback: v_loop,
452 });
453 let pid = crate::kernel::scheduler::spawn_away_from_current(
454 video_playback_thread,
455 crate::kernel::scheduler::Priority::High,
456 "video_playback",
457 );
458 if pid == 0 {
459 crate::warn!("[SYS] 自動再生スレッドを起動できませんでした(ヒープ不足)");
460 stop_video_playback();
461 self.video_playing = false;
462 } else {
463 crate::info!("[SYS] 自動再生スレッドを起動しました (pid={}, url={})", pid, el.video_src);
464 }
465 }
466 }
467
468 let is_yt = super::site_hooks::hooks().is_dark_host(&self.current_host);
471 let default_bg = if is_yt { 0xFF0F0F0F } else { 0xFFFFFFFF };
472 let bg = self.page_bg_color.unwrap_or(default_bg);
473 screen.boxfill(
474 win_x,
475 win_y + top_offset as u32,
476 win_x + win_w,
477 win_y + win_h,
478 draw::Color(bg),
479 );
480
481 if self.loading {
483 let lx = win_w / 2;
484 let ly = (win_h + top_offset as u32) / 2;
485
486 let mx_rel = self.mouse_x;
487 let my_rel = self.mouse_y;
488
489 let dx = mx_rel - lx as i32;
490 let dy = my_rel - ly as i32;
491 let dist = libm::sqrtf((dx * dx + dy * dy) as f32);
492
493 let pull = if dist < 160.0f32 {
494 (160.0f32 - dist) / 160.0f32
495 } else {
496 0.0f32
497 };
498
499 let pull_x = (dx as f32 * 0.12f32 * pull) as i32;
501 let pull_y = (dy as f32 * 0.12f32 * pull) as i32;
502
503 let cx = (win_x as i32 + lx as i32 + pull_x) as u32;
504 let cy = (win_y as i32 + ly as i32 + pull_y) as u32;
505
506 let speed_mult = 1.0f32 + pull * 1.5f32;
508 self.loading_tick = self.loading_tick.wrapping_add(speed_mult as u32);
509
510 let t = (self.loading_tick as f32) * 0.015f32;
512 let phase = (t as i32) % 4;
513 let ratio = t - libm::floorf(t);
514
515 let c0 = (255f32, 121f32, 198f32); let c1 = (189f32, 147f32, 249f32); let c2 = (139f32, 233f32, 253f32); let c3 = (80f32, 250f32, 123f32); let (from, to) = match phase {
521 0 => (c0, c1),
522 1 => (c1, c2),
523 2 => (c2, c3),
524 _ => (c3, c0),
525 };
526
527 let r_col = from.0 + (to.0 - from.0) * ratio;
528 let g_col = from.1 + (to.1 - from.1) * ratio;
529 let b_col = from.2 + (to.2 - from.2) * ratio;
530
531 let base_color = ((r_col as u32) << 16) | ((g_col as u32) << 8) | (b_col as u32);
532 let inner_color = (((r_col * 0.7f32) as u32) << 16)
533 | (((g_col * 0.9f32 + 25f32) as u32) << 8)
534 | ((b_col as u32).max(180));
535
536 let draw_dot = |px: u32, py: u32, alpha: u8, color_val: u32| {
537 for dy in -3..=3 {
538 for dx in -3..=3 {
539 let dist = dx * dx + dy * dy;
540 if dist <= 9 {
541 let a = if dist <= 4 { alpha } else { alpha / 2 };
542 screen.draw_pixel_alpha(
543 (px as i32 + dx) as u32,
544 (py as i32 + dy) as u32,
545 draw::Color(color_val),
546 a,
547 );
548 }
549 }
550 }
551 };
552
553 let r_out = 28.0f32 + libm::sinf(self.loading_tick as f32 * 0.05f32) * 5.0f32;
555 for i in 0..8 {
556 let angle = (i as f32) * (core::f32::consts::PI / 4.0)
557 + (self.loading_tick as f32 * 0.02f32);
558 let dx = libm::cosf(angle) * r_out;
559 let dy = libm::sinf(angle) * r_out;
560
561 let active_idx = (self.loading_tick / 4) % 8;
562 let distance = (i - active_idx as i32 + 8) % 8;
563 let alpha = match distance {
564 0 => 255,
565 1 => 180,
566 2 => 120,
567 3 => 70,
568 _ => 25,
569 };
570
571 let dot_x = (cx as f32 + dx) as u32;
572 let dot_y = (cy as f32 + dy) as u32;
573 draw_dot(dot_x, dot_y, alpha, base_color);
574 }
575
576 let r_in = 14.0f32 - libm::cosf(self.loading_tick as f32 * 0.07f32) * 3.0f32;
578 for i in 0..6 {
579 let angle = (i as f32) * (core::f32::consts::PI / 3.0)
580 - (self.loading_tick as f32 * 0.035f32);
581 let dx = libm::cosf(angle) * r_in;
582 let dy = libm::sinf(angle) * r_in;
583
584 let active_idx = (self.loading_tick / 5) % 6;
585 let distance = (i - active_idx as i32 + 6) % 6;
586 let alpha = match distance {
587 0 => 230,
588 1 => 160,
589 2 => 100,
590 _ => 20,
591 };
592
593 let dot_x = (cx as f32 + dx) as u32;
594 let dot_y = (cy as f32 + dy) as u32;
595 draw_dot(dot_x, dot_y, alpha, inner_color);
596 }
597
598 screen.draw_string_ja_size_bg(
599 cx - 75,
600 cy + 45,
601 "Loading Secure Page...",
602 14,
603 draw::Color(theme.sysmon_accent),
604 draw::Color(bg),
605 );
606 self.dirty = true;
607 self.dirty_reason = "render.rs:285";
608 return;
609 }
610
611 let t_pre = crate::kernel::timer::get_ticks();
661 let mut needed_images = alloc::vec::Vec::new();
673 let mut bg_urls: alloc::vec::Vec<alloc::string::String> = alloc::vec::Vec::new();
674 let scan_key = (
678 self.elements_gen,
679 self.scroll_y,
680 top_offset,
681 win_h,
682 self.image_cache.len(),
683 self.image_attempted.len(),
684 self.osm_states.len(),
685 );
686 self.image_scan_frames = self.image_scan_frames.wrapping_add(1);
687 let skip_scan = self.image_scan_key == Some(scan_key) && !self.image_scan_frames.is_multiple_of(16);
688 self.image_scan_key = Some(scan_key);
689 if !skip_scan {
690 let want = |me: &Self, u: &str| {
692 !u.is_empty()
693 && !me.image_cache.contains_key(u)
694 && (!me.image_attempted.contains(u) || super::image::shared_image(u).is_some())
695 };
696 let mut offscreen_imgs: alloc::vec::Vec<alloc::string::String> = alloc::vec::Vec::new();
701 for el in &self.elements {
702 let el_y = el.y_offset - self.scroll_y + top_offset;
703 if el_y + el.height < top_offset || el_y > win_h as i32 {
704 if el.is_img && !el.img_lazy && want(self, &el.video_src) {
705 offscreen_imgs.push(el.video_src.clone());
706 }
707 continue;
708 }
709 if el.is_img && want(self, &el.video_src) {
710 needed_images.push(el.video_src.clone());
711 }
712 if let Some(ref bg_img) = el.bg_image {
715 if !self.background_image_urls.contains(bg_img.as_str()) {
716 bg_urls.push(bg_img.clone());
717 }
718 if want(self, bg_img) {
719 needed_images.push(bg_img.clone());
720 }
721 }
722 for extra in &el.bg_images {
723 if !self.background_image_urls.contains(extra.as_str()) {
724 bg_urls.push(extra.clone());
725 }
726 if want(self, extra) {
727 needed_images.push(extra.clone());
728 }
729 }
730 if el.is_li && want(self, &el.list_style_image) {
731 needed_images.push(el.list_style_image.clone());
732 }
733 if el.is_video && want(self, &el.video_poster) {
734 needed_images.push(el.video_poster.clone());
735 }
736 if el.is_iframe && !el.iframe_src.is_empty() {
737 if let Some(embed) = crate::os_lib::web_engine::embed_map::parse_embed_url(&el.iframe_src) {
738 let state = self.osm_states.get(&el.iframe_src).copied().unwrap_or_default();
739 if let Some(plan) = crate::os_lib::web_engine::embed_map::plan_with_state(&embed, el.width, el.height, &state) {
740 for (tile_url, _, _) in plan.tiles {
741 if want(self, &tile_url) {
742 needed_images.push(tile_url);
743 }
744 }
745 }
746 }
747 }
748 }
749 needed_images.extend(offscreen_imgs);
750 }
751 for u in bg_urls {
752 self.background_image_urls.insert(u);
753 }
754 for img_path in needed_images {
755 self.ensure_image_cached(&img_path);
756 }
757
758 {
761 let mut idx = core::mem::take(&mut self.bg_layer_idx);
762 idx.clear();
763 for (i, el) in self.elements.iter().enumerate() {
764 if el.bg_color.is_some() || element_has_painted_bg(el) {
765 idx.push(i as u32);
766 }
767 }
768 self.bg_layer_idx = idx;
769 }
770
771 self.links.clear();
772
773 self.hovered_cursor_is_text = false;
778 self.hovered_cursor_kind.clear();
779
780 let t_imgprep = crate::kernel::timer::get_ticks();
781 super::draw_helpers::BG_IMG_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
782 super::draw_helpers::GRAD_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
783 crate::kernel::draw::TEXT_DRAW_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
784 super::draw_helpers::IMG_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
785 crate::kernel::draw::BOXFILL_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
786 crate::kernel::draw::SHADOW_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
787 crate::kernel::draw::RRECT_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
788 crate::kernel::draw::PIXBG_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
789 super::draw_helpers::OTHERFILL_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
790 super::draw_helpers::BORDER_TICKS.store(0, core::sync::atomic::Ordering::Relaxed);
791 let mut sorted_indices: Vec<usize> = (0..self.elements.len()).collect();
793 sorted_indices.sort_by(|&a, &b| {
798 let (ea, eb) = (&self.elements[a], &self.elements[b]);
799 super::paint_order::paint_cmp(
800 &ea.stack_path,
801 super::paint_order::stack_step_ext(
802 ea.z_index,
803 ea.is_positioned,
804 false,
805 ea.is_inline_content(),
806 ea.paint_depth,
807 ea.paint_seq,
808 ),
809 &eb.stack_path,
810 super::paint_order::stack_step_ext(
811 eb.z_index,
812 eb.is_positioned,
813 false,
814 eb.is_inline_content(),
815 eb.paint_depth,
816 eb.paint_seq,
817 ),
818 )
819 });
820
821 let mut frame_hits_now: Vec<(String, i32, i32, i32, i32)> = Vec::new();
822 let mut frame_ordinal = 0usize;
823 let mut video_rect: Option<(i32, i32, i32, i32)> = None;
825 let mut video_occluders: Vec<(i32, i32, i32, i32)> = Vec::new();
826 let mut pending_outlines: Vec<(i32, i32, i32, i32, i32, i32, u32, alloc::string::String, Option<(u32, u32, u32, u32)>)> = Vec::new();
828 let mut backdrop_painted = false;
829 for &ei in &sorted_indices {
830 let el = &self.elements[ei];
831 let el_start = crate::kernel::timer::get_ticks();
832 screen.round_clip.set(None);
834
835 if el.is_modal && !backdrop_painted {
837 if let Some(bg) = el.backdrop_color {
838 let alpha = ((bg >> 24) & 0xFF) as u8;
839 let rgb = bg & 0x00FFFFFF;
840 if alpha > 0 {
841 let saved_clip = screen.clip_rect();
842 screen.clear_clip();
843 screen.fill_signed_alpha(
844 win_x as i32,
845 top_offset,
846 (win_x + win_w) as i32 - 1,
847 (win_y + win_h) as i32 - 1,
848 crate::kernel::draw::Color(rgb),
849 alpha,
850 );
851 if let Some((sx0, sy0, sx1, sy1)) = saved_clip {
852 screen.set_clip(sx0, sy0, sx1, sy1);
853 } else {
854 screen.clear_clip();
855 }
856 backdrop_painted = true;
857 }
858 }
859 }
860
861
862 if el.visibility_hidden {
864 continue;
865 }
866
867 let (sub_scroll_x, sub_scroll_y) = if el.scroll_container_id.is_empty() {
872 (0, 0)
873 } else {
874 let sx = self.scroll_regions_x
875 .get(&el.scroll_container_id)
876 .copied()
877 .unwrap_or(0);
878 let sy = self.scroll_regions
879 .get(&el.scroll_container_id)
880 .copied()
881 .unwrap_or(0);
882 (sx, sy)
883 };
884 let natural_y = el.y_offset + el.transform_ty - self.scroll_y - sub_scroll_y + top_offset;
885 let el_y = if el.is_fixed {
886 el.y_offset + el.transform_ty + top_offset
887 } else if el.is_sticky {
888 if let Some(top) = el.sticky_top {
890 super::sticky::sticky_top_y(
891 natural_y,
892 top_offset,
893 top,
894 el.sticky_bound_max_y,
895 el.transform_ty,
896 self.scroll_y,
897 sub_scroll_y,
898 )
899 } else if let Some(bottom) = el.sticky_bottom {
900 super::sticky::sticky_bottom_y(natural_y, win_h as i32, bottom, el.height)
901 } else {
902 natural_y
903 }
904 } else {
905 natural_y
906 };
907 let natural_x = el.x_offset + el.transform_tx - sub_scroll_x;
908 let el_x = if el.is_fixed {
909 el.x_offset + el.transform_tx
910 } else {
911 natural_x
912 };
913
914 if el_y + el.height < top_offset || el_y > win_h as i32 {
915 continue;
916 }
917 let has_overflow_clip = if el.overflow_hidden {
929 let clip_scroll = if el.is_fixed { 0 } else { self.scroll_y };
932 let clip_y = el.clip_y0.saturating_sub(clip_scroll).saturating_add(top_offset);
933 let clip_y1 = el.clip_y1.saturating_sub(clip_scroll).saturating_add(top_offset);
934 if el_y + el.height <= clip_y || el_y >= clip_y1 {
935 continue;
936 }
937 if el_x + el.width <= el.clip_x0 || el_x >= el.clip_x1 {
938 continue;
939 }
940 let sx0 = (win_x as i32).saturating_add(el.clip_x0).max(0) as u32;
943 let sy0 = (win_y as i32).saturating_add(clip_y).max(0) as u32;
944 let sx1 = (win_x as i32).saturating_add(el.clip_x1).max(0) as u32;
945 let sy1 = (win_y as i32).saturating_add(clip_y1).max(0) as u32;
946 screen.push_clip(sx0, sy0, sx1, sy1);
947 if el.clip_radius > 0 {
948 screen.round_clip.set(Some((
949 sx0 as i32,
950 sy0 as i32,
951 sx1 as i32,
952 sy1 as i32,
953 el.clip_radius,
954 )));
955 }
956 true
957 } else {
958 false
959 };
960
961 let draw_y = win_y + el_y as u32;
962 let draw_x_base = win_x as i32 + el_x;
964
965 if self.mouse_y >= draw_y as i32
967 && self.mouse_y <= (draw_y + el.height as u32) as i32
968 && self.mouse_x >= draw_x_base
969 && self.mouse_x <= draw_x_base + el.width
970 {
971 if el.cursor_style == "text" {
972 self.hovered_cursor_is_text = true;
973 }
974 if !el.cursor_style.is_empty() {
975 self.hovered_cursor_kind = el.cursor_style.clone();
976 }
977 }
978
979 let scale_x = el.transform_scale_x;
981 let scale_y = el.transform_scale_y;
982 let eff_w = if (scale_x - 1.0f32).abs() < 0.001 {
983 el.width
984 } else {
985 (el.width as f32 * scale_x) as i32
986 };
987 let eff_h = if (scale_y - 1.0f32).abs() < 0.001 {
988 el.height
989 } else {
990 (el.height as f32 * scale_y) as i32
991 };
992 let draw_x_base =
995 draw_x_base + ((el.width - eff_w) as f32 * el.transform_origin_x) as i32;
996 let origin_adj = ((el.height - eff_h) as f32 * el.transform_origin_y) as i32;
1013 let draw_y = if origin_adj == 0 {
1014 draw_y
1015 } else {
1016 (draw_y as i32).wrapping_add(origin_adj) as u32
1017 };
1018
1019 let blur_radius = crate::os_lib::web_engine::draw_helpers::parse_blur_radius(&el.filter);
1021 let blur_before = (blur_radius > 0)
1022 .then(|| {
1023 let r = blur_radius.clamp(1, 8);
1024 crate::os_lib::web_engine::draw_helpers::capture_screen_rect(
1025 screen,
1026 draw_x_base - r,
1027 draw_y as i32 - r,
1028 draw_x_base + el.width + r,
1029 draw_y as i32 + el.height + r,
1030 )
1031 })
1032 .flatten();
1033
1034 if let Some((vx0, vy0, vx1, vy1)) = video_rect {
1037 let opaque = |c: Option<u32>| c.is_some_and(|c| c >> 24 != 0);
1038 let paints = !el.is_video
1039 && el.opacity > 0
1040 && (opaque(el.bg_color)
1041 || !el.text.trim().is_empty()
1042 || el.is_img
1043 || el.bg_image.is_some()
1044 || !el.bg_images.is_empty()
1045 || (el.border_style != super::BorderStyle::None && opaque(el.border_color)));
1046 let (ex0, ey0) = (draw_x_base, draw_y as i32);
1047 let (ex1, ey1) = (ex0.saturating_add(eff_w), ey0.saturating_add(eff_h));
1048 if paints && ex0 < vx1 && ex1 > vx0 && ey0 < vy1 && ey1 > vy0 && video_occluders.len() < 64 {
1049 video_occluders.push((ex0.max(vx0), ey0.max(vy0), ex1.min(vx1), ey1.min(vy1)));
1050 }
1051 }
1052
1053 if el.is_hr {
1054 screen.boxfill(
1055 draw_x_base as u32,
1056 draw_y + 3,
1057 win_x + win_w - 40,
1058 draw_y + 5,
1059 draw::Color(el.color),
1060 );
1061 } else if let Some(cid) = el.canvas_ctx_id {
1062 crate::os_lib::canvas2d::with_context(cid, |c| {
1072 let sw = c.surface.width as i32;
1073 let sh = c.surface.height as i32;
1074 if sw <= 0 || sh <= 0 || el.width <= 0 || el.height <= 0 {
1075 return;
1076 }
1077 let sx_lut: alloc::vec::Vec<i32> = (0..el.width)
1078 .map(|dx| (dx as i64 * sw as i64 / el.width as i64) as i32)
1079 .collect();
1080 let mut row_buf = alloc::vec![0u32; el.width as usize];
1081
1082 for dy in 0..el.height {
1083 let py = el_y + dy;
1084 if py < top_offset || py >= win_h as i32 {
1085 continue;
1086 }
1087 let sy = (dy as i64 * sh as i64 / el.height as i64) as i32;
1088 if sy < 0 || sy >= sh {
1089 continue;
1090 }
1091 let sy_offset = (sy * sw) as usize;
1092 for dx in 0..el.width {
1093 let sx = sx_lut[dx as usize];
1094 if sx >= 0 && sx < sw {
1095 row_buf[dx as usize] = c.surface.pixels[sy_offset + sx as usize];
1096 } else {
1097 row_buf[dx as usize] = 0;
1098 }
1099 }
1100 screen.draw_scanline_colors(draw_x_base, win_y as i32 + py, &row_buf);
1101 }
1102 });
1103 } else if el.is_img {
1104 let img_clip = if el.clip_path.is_empty() {
1105 None
1106 } else {
1107 parse_clip_shape_with_font(&el.clip_path, el.width, el.height, el.font_size as f32)
1108 };
1109 let mut bmp_drawn = false;
1110 if !el.video_src.is_empty() {
1111 if let Some(img) = self.image_cache.get(&el.video_src) {
1113 draw_img_object_fit(
1114 screen,
1115 img,
1116 el,
1117 draw_x_base,
1118 draw_y as i32,
1119 &img_clip,
1120 );
1121 bmp_drawn = true;
1122 }
1123 }
1124
1125 if !bmp_drawn {
1126 let is_small_icon = el.width < 40 || el.height < 24;
1127 if !is_small_icon && !el.img_alt.is_empty() {
1131 let hash = hash_str(&el.img_alt);
1132 let r1 = (hash & 0x7F) + 0x80;
1133 let g1 = ((hash >> 8) & 0x7F) + 0x80;
1134 let b1 = ((hash >> 16) & 0x7F) + 0x80;
1135 let c1 = 0xFF000000 | (r1 << 16) | (g1 << 8) | b1;
1136
1137 let r2 = ((hash >> 4) & 0x7F) + 0x60;
1138 let g2 = ((hash >> 12) & 0x7F) + 0x60;
1139 let b2 = ((hash >> 20) & 0x7F) + 0x60;
1140 let c2 = 0xFF000000 | (r2 << 16) | (g2 << 8) | b2;
1141
1142 let x0 = (draw_x_base as u32) as i32;
1143 let y0 = draw_y as i32;
1144 let x1 = (draw_x_base as u32 + el.width as u32) as i32;
1145 let y1 = (draw_y + el.height as u32) as i32;
1146
1147 if el.border_radius != (0, 0, 0, 0) {
1148 screen.draw_rounded_rect_fill(
1149 x0,
1150 y0,
1151 x1,
1152 y1,
1153 el.border_radius,
1154 draw::Color(c1),
1155 );
1156 screen.draw_rounded_rect_border(
1157 x0,
1158 y0,
1159 x1,
1160 y1,
1161 el.border_radius,
1162 draw::Color(el.border_color.unwrap_or(theme.browser_secondary)),
1163 el.border_style.as_str(),
1164 );
1165 } else {
1166 draw_gradation(screen, x0, y0, el.width, el.height, c1, c2);
1167 draw_border_with_style(
1168 screen,
1169 x0,
1170 y0,
1171 x1,
1172 y1,
1173 el.border_color.unwrap_or(theme.browser_secondary),
1174 el.border_style,
1175 );
1176 }
1177
1178 if !el.img_alt.is_empty() {
1179 let label = alloc::format!("[Image: {}]", el.img_alt);
1180 screen.draw_string_ja_size_bg(
1181 draw_x_base as u32 + 13,
1182 draw_y + 9,
1183 &label,
1184 16,
1185 draw::Color(theme.browser_bg),
1186 draw::Color(c1),
1187 ); screen.draw_string_ja_size_bg(
1189 draw_x_base as u32 + 12,
1190 draw_y + 8,
1191 &label,
1192 16,
1193 draw::Color(theme.browser_fg),
1194 draw::Color(c1),
1195 ); }
1197 }
1198 }
1199
1200 let is_mixed = self.current_is_https && el.video_src.starts_with("http://");
1201 if is_mixed {
1202 screen.boxfill(
1203 draw_x_base as u32,
1204 draw_y,
1205 draw_x_base as u32 + 220,
1206 draw_y + 20,
1207 draw::Color(theme.error_fg),
1208 );
1209 screen.draw_string_ja_size_bg(
1210 draw_x_base as u32 + 4,
1211 draw_y + 2,
1212 "⚠️ HTTP Mixed Blocked",
1213 12,
1214 draw::Color(theme.browser_fg),
1215 draw::Color(theme.error_fg),
1216 );
1217 }
1218 } else if el.is_video {
1219 let frame_opt = if self.video_playing || !el.video_src.is_empty() {
1220 CURRENT_VIDEO_FRAME.lock().clone()
1221 } else {
1222 None
1223 };
1224 let v_width = if el.width > 0 { el.width } else { (win_w as i32 - 80).clamp(400, 800) };
1226 #[allow(clippy::manual_checked_ops)] let v_height = if el.height > 0 {
1230 el.height
1231 } else if let Some(ref frame) = frame_opt {
1232 if frame.width > 0 { (v_width as u32 * frame.height / frame.width) as i32 } else { v_width * 9 / 16 }
1233 } else {
1234 v_width * 9 / 16
1235 };
1236 let native_ui = el.video_has_controls;
1239 let x0 = draw_x_base as u32;
1240 let y0 = draw_y;
1241 let x1 = draw_x_base as u32 + v_width as u32;
1242 let y1 = draw_y + v_height as u32;
1243
1244 if !native_ui {
1245 } else if el.border_radius != (0, 0, 0, 0) {
1247 screen.draw_rounded_rect_fill(
1248 x0 as i32,
1249 y0 as i32,
1250 x1 as i32,
1251 y1 as i32,
1252 el.border_radius,
1253 draw::Color(theme.browser_bg),
1254 );
1255 screen.draw_rounded_rect_border(
1256 x0 as i32,
1257 y0 as i32,
1258 x1 as i32,
1259 y1 as i32,
1260 el.border_radius,
1261 draw::Color(el.border_color.unwrap_or(theme.browser_secondary)),
1262 el.border_style.as_str(),
1263 );
1264 } else {
1265 screen.boxfill(x0, y0, x1, y1, draw::Color(theme.browser_bg));
1266 draw_border_with_style(
1267 screen,
1268 x0 as i32,
1269 y0 as i32,
1270 x1 as i32,
1271 y1 as i32,
1272 el.border_color.unwrap_or(theme.browser_secondary),
1273 el.border_style,
1274 );
1275 }
1276
1277 if let Some(frame) = frame_opt {
1278 let (fx, fy, dst_w, dst_h) =
1280 super::video_fit::fit_contain(frame.width, frame.height, v_width as u32, v_height as u32);
1281 if dst_w < v_width as u32 || dst_h < v_height as u32 {
1282 screen.boxfill(x0, y0, x1, y1, draw::Color(0xFF00_0000));
1283 }
1284 let (x0, y0) = (x0 + fx, y0 + fy);
1285 if self.video_playing {
1287 super::video::note_app_video_draw(
1288 (x0 as i32, y0 as i32, dst_w, dst_h),
1289 screen.clip_rect().unwrap_or((0, 0, screen.width, screen.height)),
1290 );
1291 video_rect = Some((x0 as i32, y0 as i32, x0 as i32 + dst_w as i32, y0 as i32 + dst_h as i32));
1292 video_occluders.clear();
1293 }
1294 let col_src_byte: alloc::vec::Vec<usize> =
1295 (0..dst_w).map(|col| (((col * frame.width) / dst_w) as usize) * 3).collect();
1296 let mut row_buf = alloc::vec![0u32; dst_w as usize];
1297 let frame_stride_3 = (frame.width as usize) * 3;
1298 let rgb_len = frame.rgb_data.len();
1299
1300 for row in 0..dst_h {
1301 let src_row = (row * frame.height) / dst_h;
1302 let row_start_byte = (src_row as usize) * frame_stride_3;
1303 for col in 0..dst_w {
1304 let idx = row_start_byte + col_src_byte[col as usize];
1305 if idx + 2 < rgb_len {
1306 let r = frame.rgb_data[idx] as u32;
1307 let g = frame.rgb_data[idx + 1] as u32;
1308 let b = frame.rgb_data[idx + 2] as u32;
1309 row_buf[col as usize] =
1310 0xFF00_0000 | (r << 16) | (g << 8) | b;
1311 } else {
1312 row_buf[col as usize] = 0;
1313 }
1314 }
1315 screen.draw_scanline_colors(x0 as i32, (y0 + row) as i32, &row_buf);
1316 }
1317 let paused = VIDEO_STATE.lock().as_ref().is_some_and(|st| st.paused);
1318 if self.video_playing && !paused {
1319 self.video_tick = self.video_tick.wrapping_add(1);
1320 self.video_controls.current_time += 1.0 / 30.0;
1321 if self.video_controls.current_time >= self.video_controls.duration {
1322 self.video_controls.current_time = 0.0;
1323 }
1324 self.dirty = true; }
1326 } else if self.video_playing {
1327 if !native_ui {
1328 screen.boxfill(x0, y0, x1, y1, draw::Color(0xFF00_0000));
1330 } else {
1331 screen.boxfill(x0, y0, x1, y1, draw::Color(theme.video_bar_bg));
1333 let cx = x0 + v_width as u32 / 2;
1334 let cy = y0 + el.height as u32 / 2;
1335 screen.draw_string_ja_size_bg(
1336 cx - 50,
1337 cy - 10,
1338 "Loading Video...",
1339 16,
1340 draw::Color(theme.fn_bar_key_fg),
1341 draw::Color(theme.video_bar_bg),
1342 );
1343 }
1344 self.video_tick = self.video_tick.wrapping_add(1);
1345 self.video_controls.current_time += 1.0 / 30.0;
1346 if self.video_controls.current_time >= self.video_controls.duration {
1347 self.video_controls.current_time = 0.0;
1348 }
1349 self.dirty = true; } else {
1351 let mut poster_drawn = false;
1352 if !el.video_poster.is_empty() {
1353 if let Some(img) = self.image_cache.get(&el.video_poster) {
1354 let img_clip = if el.clip_path.is_empty() {
1355 None
1356 } else {
1357 parse_clip_shape_with_font(&el.clip_path, v_width, el.height, el.font_size as f32)
1358 };
1359 draw_img_object_fit(
1360 screen,
1361 img,
1362 el,
1363 draw_x_base,
1364 draw_y as i32,
1365 &img_clip,
1366 );
1367 poster_drawn = true;
1368 }
1369 }
1370 if !poster_drawn {
1371 screen.boxfill(x0, y0, x1, y1, draw::Color(0xFF0F0F0F));
1372 }
1373 if native_ui {
1374 let cx = draw_x_base as u32 + v_width as u32 / 2;
1375 let cy = draw_y + el.height as u32 / 2;
1376 screen.boxfill(cx - 50, cy - 20, cx + 50, cy + 20, draw::Color(theme.browser_secondary));
1377 draw_border_with_style(
1378 screen,
1379 (cx - 50) as i32,
1380 (cy - 20) as i32,
1381 (cx + 50) as i32,
1382 (cy + 20) as i32,
1383 el.border_color.unwrap_or(theme.success_fg),
1384 el.border_style,
1385 );
1386 screen.draw_string_ja_size_bg(
1387 cx - 30,
1388 cy - 10,
1389 "PLAY ▶",
1390 16,
1391 draw::Color(theme.success_fg),
1392 draw::Color(theme.browser_secondary),
1393 );
1394 }
1395 }
1396
1397 if let Some(msg) = self.video_controls.tick_hud() {
1399 let hud_w = 160u32;
1400 let hud_h = 44u32;
1401 let cx = draw_x_base as u32 + v_width as u32 / 2;
1402 let cy = draw_y + el.height as u32 / 2;
1403 let hx0 = cx.saturating_sub(hud_w / 2);
1404 let hy0 = cy.saturating_sub(hud_h / 2);
1405 let hx1 = hx0 + hud_w;
1406 let hy1 = hy0 + hud_h;
1407 screen.boxfill(hx0, hy0, hx1, hy1, draw::Color(0xCC111111));
1408 screen.draw_string_ja_size_bg(
1409 hx0 + 16,
1410 hy0 + 14,
1411 msg,
1412 16,
1413 draw::Color(0xFFFFFFFF),
1414 draw::Color(0xCC111111),
1415 );
1416 video_occluders.push((hx0 as i32, hy0 as i32, hx1 as i32, hy1 as i32));
1417 self.dirty = true;
1418 }
1419
1420 if let Some(sub_text) = self.video_controls.current_subtitle_text() {
1422 let sub_lines: alloc::vec::Vec<&str> = sub_text.lines().collect();
1423 let font_size = 16u32;
1424 let line_h = 22u32;
1425 let total_h = (sub_lines.len() as u32) * line_h + 8;
1426 let bottom_y = if native_ui {
1427 draw_y + (el.height as u32).saturating_sub(48)
1428 } else {
1429 draw_y + (el.height as u32).saturating_sub(24)
1430 };
1431 let sub_y0 = bottom_y.saturating_sub(total_h);
1432
1433 for (i, line) in sub_lines.iter().enumerate() {
1434 let text_w = (line.chars().count() as u32) * 10 + 16;
1435 let cx = draw_x_base as u32 + (v_width as u32) / 2;
1436 let sx0 = cx.saturating_sub(text_w / 2);
1437 let sy0 = sub_y0 + (i as u32) * line_h;
1438 let sx1 = sx0 + text_w;
1439 let sy1 = sy0 + line_h;
1440
1441 screen.boxfill(sx0, sy0, sx1, sy1, draw::Color(0xCC000000));
1442 screen.draw_string_ja_size_bg(
1443 sx0 + 8,
1444 sy0 + 3,
1445 line,
1446 font_size,
1447 draw::Color(0xFFFFFFFF),
1448 draw::Color(0xCC000000),
1449 );
1450 video_occluders.push((sx0 as i32, sy0 as i32, sx1 as i32, sy1 as i32));
1451 }
1452 self.dirty = true;
1453 }
1454
1455 if native_ui {
1457 let bar_y = draw_y + (el.height as u32).saturating_sub(40);
1458 video_occluders.push((draw_x_base, bar_y as i32, draw_x_base + v_width, (bar_y + 40) as i32));
1459 screen.boxfill(
1460 draw_x_base as u32,
1461 bar_y,
1462 draw_x_base as u32 + v_width as u32,
1463 bar_y + 40,
1464 draw::Color(theme.video_bar_bg),
1465 );
1466 screen.boxfill(
1467 draw_x_base as u32,
1468 bar_y,
1469 draw_x_base as u32 + v_width as u32,
1470 bar_y + 1,
1471 draw::Color(theme.video_bar_sep),
1472 );
1473
1474 let play_lbl = if self.video_playing { "‖" } else { "▶" };
1475 screen.draw_string_ja_size_bg(
1476 win_x + 55,
1477 bar_y + 10,
1478 play_lbl,
1479 16,
1480 draw::Color(theme.video_thumb_fg),
1481 draw::Color(theme.video_bar_bg),
1482 );
1483
1484 let sb_w = v_width - 370;
1485 if sb_w > 50 {
1486 screen.boxfill(
1487 win_x + 80,
1488 bar_y + 18,
1489 win_x + 80 + sb_w as u32,
1490 bar_y + 22,
1491 draw::Color(theme.video_bar_sep),
1492 );
1493 let ratio = self.video_controls.progress_ratio();
1494 let progress = (sb_w as f32 * ratio) as u32;
1495 screen.boxfill(
1497 win_x + 80,
1498 bar_y + 18,
1499 win_x + 80 + progress,
1500 bar_y + 22,
1501 draw::Color(0xFFFF0000),
1502 );
1503 screen.boxfill(
1504 win_x + 80 + progress.saturating_sub(4),
1505 bar_y + 14,
1506 win_x + 80 + progress + 4,
1507 bar_y + 26,
1508 draw::Color(0xFFFF0000),
1509 );
1510
1511 let time_str = self.video_controls.format_display();
1512 screen.draw_string_ja_size_bg(
1513 win_x + 80 + sb_w as u32 + 10,
1514 bar_y + 14,
1515 &alloc::format!("{} [{}]", time_str, if self.video_controls.muted { "MUTE" } else { "VOL" }),
1516 12,
1517 draw::Color(theme.video_thumb_fg),
1518 draw::Color(theme.video_bar_bg),
1519 );
1520 }
1521
1522 if v_width > 220 {
1523 let rate_str = alloc::format!("{:.2}x", self.video_controls.playback_rate);
1524 let q_badge = self.video_controls.quality_badge();
1525 let q_icon = alloc::format!("[{}]", q_badge);
1526 let cc_badge = self.video_controls.current_track_badge();
1527 let cc_icon = if self.video_controls.subtitles_enabled() {
1528 alloc::format!("[{}]", cc_badge)
1529 } else {
1530 alloc::string::String::from(" CC ")
1531 };
1532 let fs_icon = if self.video_controls.fullscreen { "[_]" } else { "[⛶]" };
1533 let right_x = draw_x_base as u32 + v_width as u32 - 195;
1534 screen.draw_string_ja_size_bg(
1535 right_x,
1536 bar_y + 14,
1537 &rate_str,
1538 12,
1539 draw::Color(0xFFFFCC00),
1540 draw::Color(theme.video_bar_bg),
1541 );
1542 let is_hd = q_badge == "HD" || q_badge == "FHD";
1543 screen.draw_string_ja_size_bg(
1544 right_x + 45,
1545 bar_y + 12,
1546 &q_icon,
1547 14,
1548 draw::Color(if is_hd { 0xFFFFCC00 } else { theme.video_thumb_fg }),
1549 draw::Color(theme.video_bar_bg),
1550 );
1551 screen.draw_string_ja_size_bg(
1552 right_x + 95,
1553 bar_y + 12,
1554 &cc_icon,
1555 14,
1556 draw::Color(if self.video_controls.subtitles_enabled() { 0xFF00FFCC } else { theme.video_thumb_fg }),
1557 draw::Color(theme.video_bar_bg),
1558 );
1559 screen.draw_string_ja_size_bg(
1560 right_x + 145,
1561 bar_y + 12,
1562 fs_icon,
1563 14,
1564 draw::Color(theme.video_thumb_fg),
1565 draw::Color(theme.video_bar_bg),
1566 );
1567 }
1568 }
1569 } else if el.is_iframe {
1570 let x0 = draw_x_base;
1571 let y0 = draw_y as i32;
1572 let x1 = x0 + el.width;
1573 let y1 = y0 + el.height;
1574 if x1 > x0 && y1 > y0 {
1575 screen.fill_signed(x0, y0, x1, y1, draw::Color(0xFFE8ECEF));
1576
1577 let frame_parent = super::frames::FrameParent {
1579 is_https: self.current_is_https,
1580 host: &self.current_host,
1581 path: &self.current_path,
1582 depth: self.frame_depth,
1583 };
1584 let is_osm = crate::os_lib::web_engine::embed_map::parse_embed_url(&el.iframe_src).is_some();
1585 let child_drawn = !is_osm
1586 && match super::frames::frame_url(&frame_parent, &el.iframe_src) {
1587 Some(url) => {
1588 let key = super::frames::frame_key(frame_ordinal, &url);
1589 frame_ordinal += 1;
1590 let drawn = super::frames::draw_child_frame(
1591 &mut self.child_frames,
1592 &frame_parent,
1593 &key,
1594 &url,
1595 screen,
1596 x0,
1597 y0,
1598 x1 - x0,
1599 y1 - y0,
1600 );
1601 if drawn {
1602 frame_hits_now.push((key, x0 - win_x as i32, y0 - win_y as i32, x1 - x0, y1 - y0));
1603 }
1604 drawn
1605 }
1606 None => false,
1607 };
1608 if child_drawn {
1609 } else if let Some(embed) = crate::os_lib::web_engine::embed_map::parse_embed_url(&el.iframe_src) {
1611 let state = self.osm_states.get(&el.iframe_src).copied().unwrap_or_default();
1612 if let Some(plan) = crate::os_lib::web_engine::embed_map::plan_with_state(&embed, el.width, el.height, &state) {
1613 let mut missing_tile = false;
1614 for (tile_url, rel_x, rel_y) in &plan.tiles {
1615 let tx0 = x0 + rel_x;
1616 let ty0 = y0 + rel_y;
1617 if let Some(img) = super::shared_image(tile_url) {
1618 for r in 0..img.height {
1619 let py = ty0 + r as i32;
1620 if py < y0 || py >= y1 { continue; }
1621 for c in 0..img.width {
1622 let px = tx0 + c as i32;
1623 if px < x0 || px >= x1 { continue; }
1624 let idx = ((r * img.width + c) * 4) as usize;
1625 if idx + 4 <= img.rgba.len() {
1626 let red = img.rgba[idx];
1627 let green = img.rgba[idx + 1];
1628 let blue = img.rgba[idx + 2];
1629 let alpha = img.rgba[idx + 3];
1630 if alpha > 0 {
1631 let color = draw::Color(0xFF000000 | ((red as u32) << 16) | ((green as u32) << 8) | (blue as u32));
1632 screen.draw_pixel(px as u32, py as u32, color);
1633 }
1634 }
1635 }
1636 }
1637 } else {
1638 missing_tile = true;
1639 }
1640 }
1641
1642 if let Some((mx, my)) = plan.marker {
1643 let pin_x = x0 + mx;
1644 let pin_y = y0 + my;
1645 if pin_x >= x0 && pin_x < x1 && pin_y >= y0 && pin_y < y1 {
1646 let pin_col = draw::Color(0xFFEA4335);
1647 for dy in -5..=5 {
1648 for dx in -5..=5 {
1649 if dx * dx + dy * dy <= 25 {
1650 let px = pin_x + dx;
1651 let py = pin_y - 6 + dy;
1652 if px >= x0 && px < x1 && py >= y0 && py < y1 {
1653 screen.draw_pixel(px as u32, py as u32, pin_col);
1654 }
1655 }
1656 }
1657 }
1658 for dy in -2..=2 {
1659 for dx in -2..=2 {
1660 if dx * dx + dy * dy <= 4 {
1661 let px = pin_x + dx;
1662 let py = pin_y - 6 + dy;
1663 if px >= x0 && px < x1 && py >= y0 && py < y1 {
1664 screen.draw_pixel(px as u32, py as u32, draw::Color(0xFFFFFFFF));
1665 }
1666 }
1667 }
1668 }
1669 }
1670 }
1671
1672 let btn_x = x0 + crate::os_lib::web_engine::embed_map::CTRL_BTN_MARGIN;
1674 let btn_y_in = y0 + crate::os_lib::web_engine::embed_map::CTRL_BTN_MARGIN;
1675 let btn_sz = crate::os_lib::web_engine::embed_map::CTRL_BTN_SIZE;
1676 let btn_y_out = btn_y_in + btn_sz + crate::os_lib::web_engine::embed_map::CTRL_BTN_GAP;
1677
1678 if btn_x + btn_sz < x1 && btn_y_out + btn_sz < y1 {
1679 screen.boxfill(btn_x as u32, btn_y_in as u32, (btn_x + btn_sz) as u32, (btn_y_in + btn_sz) as u32, draw::Color(0xFFFFFFFF));
1681 draw_border(screen, btn_x, btn_y_in, btn_x + btn_sz, btn_y_in + btn_sz, 0xFFCCCCCC);
1682 screen.boxfill((btn_x + 9) as u32, (btn_y_in + 13) as u32, (btn_x + 19) as u32, (btn_y_in + 15) as u32, draw::Color(0xFF333333));
1684 screen.boxfill((btn_x + 13) as u32, (btn_y_in + 9) as u32, (btn_x + 15) as u32, (btn_y_in + 19) as u32, draw::Color(0xFF333333));
1686
1687 screen.boxfill(btn_x as u32, btn_y_out as u32, (btn_x + btn_sz) as u32, (btn_y_out + btn_sz) as u32, draw::Color(0xFFFFFFFF));
1689 draw_border(screen, btn_x, btn_y_out, btn_x + btn_sz, btn_y_out + btn_sz, 0xFFCCCCCC);
1690 screen.boxfill((btn_x + 9) as u32, (btn_y_out + 13) as u32, (btn_x + 19) as u32, (btn_y_out + 15) as u32, draw::Color(0xFF333333));
1692 }
1693
1694 if missing_tile {
1695 screen.draw_string_ja_size_bg(
1696 (x0 + 10) as u32,
1697 (y0 + 10) as u32,
1698 "地図タイル読み込み中 (OpenStreetMap)...",
1699 14,
1700 draw::Color(0xFF4A5568),
1701 draw::Color(0xFFEDF2F7),
1702 );
1703 }
1704
1705 let credit = "© OpenStreetMap contributors";
1706 let cw = (credit.len() as i32) * 7;
1707 if x1 - cw - 8 > x0 && y1 - 18 > y0 {
1708 screen.draw_string_ja_size_bg(
1709 (x1 - cw - 8) as u32,
1710 (y1 - 18) as u32,
1711 credit,
1712 12,
1713 draw::Color(0xFF718096),
1714 draw::Color(0xCCFFFFFF),
1715 );
1716 }
1717 }
1718 } else if let Some(pv) = &el.iframe_preview {
1719 screen.boxfill(x0 as u32, y0 as u32, x1 as u32, y1 as u32, draw::Color(0xFFF7F8FA));
1723 let w = x1 - x0;
1724 let h = y1 - y0;
1725 let pad = (w / 12).clamp(12, 70);
1726 let max_w = w - pad * 2;
1727 let adv = |size: u32| move |c: char| screen.measure_string_ja(c.encode_utf8(&mut [0u8; 4]), size) as i32;
1728 let title_size: u32 = if w >= 480 { 26 } else { 20 };
1729 let desc_size: u32 = if w >= 480 { 15 } else { 13 };
1730 let mut y = y0 + (h / 5).clamp(pad.min(24), 90);
1731 if max_w > 0 {
1732 for line in super::iframe_preview::wrap_lines(&pv.title, max_w, adv(title_size)) {
1733 if y + title_size as i32 > y1 - 4 {
1734 break;
1735 }
1736 screen.draw_string_ja_size((x0 + pad) as u32, y as u32, &line, title_size, draw::Color(0xFF1C8ADB));
1737 y += title_size as i32 * 3 / 2;
1738 }
1739 y += desc_size as i32 * 2;
1740 for line in super::iframe_preview::wrap_lines(&pv.description, max_w, adv(desc_size)) {
1741 if y + desc_size as i32 > y1 - 24 {
1742 break;
1743 }
1744 screen.draw_string_ja_size((x0 + pad) as u32, y as u32, &line, desc_size, draw::Color(0xFF333333));
1745 y += desc_size as i32 * 9 / 5;
1746 }
1747 }
1748 let host = el
1750 .iframe_src
1751 .trim_start_matches("https:")
1752 .trim_start_matches("http:")
1753 .trim_start_matches("//");
1754 let host = host.split('/').next().unwrap_or("");
1755 if !host.is_empty() && y1 - 20 > y0 {
1756 screen.draw_string_ja_size((x0 + 8) as u32, (y1 - 18) as u32, host, 12, draw::Color(0xFF8A94A6));
1757 }
1758 } else {
1759 screen.draw_string_ja_size_bg(
1760 (x0 + 10) as u32,
1761 (y0 + 10) as u32,
1762 "<iframe> 埋め込みコンテンツ",
1763 14,
1764 draw::Color(theme.browser_fg),
1765 draw::Color(theme.browser_bg),
1766 );
1767 }
1768
1769 if let Some(bc) = el.border_color {
1771 draw_border_with_style(screen, x0, y0, x1, y1, bc, el.border_style);
1772 }
1773 }
1774 } else if el.input_kind == 1 || el.input_kind == 2 {
1775 let checked = !self
1778 .form_values
1779 .get(&el.element_id)
1780 .cloned()
1781 .unwrap_or_default()
1782 .is_empty();
1783 let box_sz: u32 = 16;
1784 let bx0 = draw_x_base as u32;
1785 let by0 = draw_y + (el.height as u32).saturating_sub(box_sz) / 2;
1786 let bx1 = bx0 + box_sz;
1787 let by1 = by0 + box_sz;
1788 let border_col = theme.form_input_border;
1789 let fill_col = if checked {
1791 el.accent_color.unwrap_or(theme.form_checkbox_checked)
1792 } else {
1793 theme.form_checkbox_unchecked
1794 };
1795 if el.input_kind == 2 {
1796 screen.draw_rounded_rect_fill(
1798 bx0 as i32,
1799 by0 as i32,
1800 bx1 as i32,
1801 by1 as i32,
1802 ((box_sz / 2) as i32, (box_sz / 2) as i32, (box_sz / 2) as i32, (box_sz / 2) as i32),
1803 draw::Color(fill_col),
1804 );
1805 screen.draw_rounded_rect_border(
1806 bx0 as i32,
1807 by0 as i32,
1808 bx1 as i32,
1809 by1 as i32,
1810 ((box_sz / 2) as i32, (box_sz / 2) as i32, (box_sz / 2) as i32, (box_sz / 2) as i32),
1811 draw::Color(border_col),
1812 "solid",
1813 );
1814 if checked {
1815 let cx = (bx0 + bx1) / 2;
1816 let cy = (by0 + by1) / 2;
1817 screen.draw_rounded_rect_fill(
1818 (cx - 3) as i32,
1819 (cy - 3) as i32,
1820 (cx + 3) as i32,
1821 (cy + 3) as i32,
1822 (3, 3, 3, 3),
1823 draw::Color(theme.form_input_bg),
1824 );
1825 }
1826 } else {
1827 screen.boxfill(bx0, by0, bx1, by1, draw::Color(fill_col));
1829 draw_border_with_style(
1830 screen, bx0 as i32, by0 as i32, bx1 as i32, by1 as i32, border_col, super::BorderStyle::Solid,
1831 );
1832 if checked {
1833 screen.boxfill(bx0 + 4, by0 + 4, bx1 - 4, by1 - 4, draw::Color(theme.form_input_bg));
1834 }
1835 }
1836 } else if el.input_kind == 3 {
1837 let bg_col = theme.form_input_bg;
1839 let border_col = theme.form_input_border;
1840 let sx0 = draw_x_base;
1841 let sy0 = draw_y as i32;
1842 let sx1 = draw_x_base + el.width;
1843 let sy1 = draw_y as i32 + el.height;
1844 screen.fill_signed(sx0, sy0, sx1, sy1, draw::Color(bg_col));
1845 draw_border_with_style(
1846 screen, sx0, sy0, sx1, sy1, border_col, super::BorderStyle::Solid,
1847 );
1848 let x0 = draw_x_base.max(0) as u32;
1849 let y0 = draw_y;
1850 let x1 = (draw_x_base + el.width).max(0) as u32;
1851 let y1 = draw_y + el.height as u32;
1852 let cur_val = self
1854 .form_values
1855 .get(&el.element_id)
1856 .cloned()
1857 .unwrap_or_default();
1858 let label = el
1859 .select_options
1860 .iter()
1861 .find(|(v, _)| *v == cur_val)
1862 .map(|(_, l)| l.clone())
1863 .or_else(|| el.select_options.first().map(|(_, l)| l.clone()))
1864 .unwrap_or_default();
1865 let text_y = y0 + (el.height as u32).saturating_sub(16) / 2;
1866 screen.push_clip(x0, y0, x1.saturating_sub(18), y1);
1867 screen.draw_string_ja_size_bg(
1868 x0 + 6,
1869 text_y,
1870 &label,
1871 16,
1872 draw::Color(theme.form_input_fg),
1873 draw::Color(bg_col),
1874 );
1875 screen.pop_clip();
1876 let arrow_x = x1.saturating_sub(16);
1878 screen.draw_string_ja_size_bg(
1879 arrow_x,
1880 text_y,
1881 "▼",
1882 12,
1883 draw::Color(theme.form_input_accent),
1884 draw::Color(bg_col),
1885 );
1886 } else if el.input_kind == 4 {
1887 let ratio: f32 = el.input_value.parse().unwrap_or(0.0);
1890 let x0 = draw_x_base as u32;
1891 let y0 = draw_y;
1892 let x1 = draw_x_base as u32 + el.width as u32;
1893 let y1 = draw_y + el.height as u32;
1894 let track_col = theme.form_input_bg;
1895 let fill_col = el.accent_color.unwrap_or(theme.form_checkbox_checked);
1896 screen.boxfill(x0, y0, x1, y1, draw::Color(track_col));
1897 let fill_x1 = x0 + ((x1 - x0) as f32 * ratio) as u32;
1898 if fill_x1 > x0 {
1899 screen.boxfill(x0, y0, fill_x1, y1, draw::Color(fill_col));
1900 }
1901 draw_border_with_style(
1902 screen, x0 as i32, y0 as i32, x1 as i32, y1 as i32,
1903 theme.form_input_border, super::BorderStyle::Solid,
1904 );
1905 } else if el.input_kind == 5 {
1906 let get = |k: &str, d: f32| -> f32 {
1909 el.select_options
1910 .iter()
1911 .find(|(n, _)| n == k)
1912 .and_then(|(_, v)| v.parse::<f32>().ok())
1913 .unwrap_or(d)
1914 };
1915 let min = get("min", 0.0);
1916 let max = get("max", 100.0);
1917 let cur: f32 = self
1918 .form_values
1919 .get(&el.element_id)
1920 .and_then(|v| v.parse().ok())
1921 .unwrap_or((min + max) / 2.0);
1922 let ratio = if max > min { ((cur - min) / (max - min)).clamp(0.0, 1.0) } else { 0.0 };
1923 let x0 = draw_x_base as u32;
1924 let x1 = draw_x_base as u32 + el.width as u32;
1925 let mid_y = draw_y + el.height as u32 / 2;
1926 let track_h = 4u32;
1927 screen.boxfill(x0, mid_y.saturating_sub(track_h / 2), x1, mid_y + track_h / 2, draw::Color(theme.form_input_bg));
1928 let thumb_r = (el.height as u32 / 2).clamp(6, 10);
1929 let thumb_x = (x0 + ((x1 - x0) as f32 * ratio) as u32).clamp(x0, x1);
1930 let thumb_col = el.accent_color.unwrap_or(theme.form_checkbox_checked);
1931 screen.draw_rounded_rect_fill(
1932 (thumb_x.saturating_sub(thumb_r)) as i32,
1933 (mid_y.saturating_sub(thumb_r)) as i32,
1934 (thumb_x.saturating_add(thumb_r)) as i32,
1935 (mid_y.saturating_add(thumb_r)) as i32,
1936 (thumb_r as i32, thumb_r as i32, thumb_r as i32, thumb_r as i32),
1937 draw::Color(thumb_col),
1938 );
1939 draw_border_with_style(
1940 screen,
1941 (thumb_x.saturating_sub(thumb_r)) as i32,
1942 (mid_y.saturating_sub(thumb_r)) as i32,
1943 (thumb_x.saturating_add(thumb_r)) as i32,
1944 (mid_y.saturating_add(thumb_r)) as i32,
1945 theme.form_input_border,
1946 super::BorderStyle::Solid,
1947 );
1948 } else if el.is_input || el.is_textarea {
1949 let is_focused = self.focused_id.as_ref() == Some(&el.element_id);
1950 let bg_col = el.bg_color.unwrap_or(theme.form_input_bg);
1951 let border_col = if is_focused { theme.form_input_border_focus } else { theme.form_input_border };
1952
1953 let sx0 = draw_x_base;
1954 let sy0 = draw_y as i32;
1955 let sx1 = draw_x_base + el.width;
1956 let sy1 = draw_y as i32 + el.height;
1957
1958 if el.border_radius != (0, 0, 0, 0) {
1959 screen.draw_rounded_rect_fill(
1960 sx0,
1961 sy0,
1962 sx1,
1963 sy1,
1964 el.border_radius,
1965 draw::Color(bg_col),
1966 );
1967 if !el.border_style.is_none() {
1968 screen.draw_rounded_rect_border(
1969 sx0,
1970 sy0,
1971 sx1,
1972 sy1,
1973 el.border_radius,
1974 draw::Color(el.border_color.unwrap_or(border_col)),
1975 el.border_style.as_str(),
1976 );
1977 }
1978 } else {
1979 screen.fill_signed(sx0, sy0, sx1, sy1, draw::Color(bg_col));
1980 if !el.border_style.is_none() {
1981 draw_border_with_style(
1982 screen,
1983 sx0,
1984 sy0,
1985 sx1,
1986 sy1,
1987 el.border_color.unwrap_or(border_col),
1988 el.border_style,
1989 );
1990 }
1991 }
1992
1993 let x0 = draw_x_base.max(0) as u32;
1994 let y0 = draw_y;
1995 let x1 = (draw_x_base + el.width).max(0) as u32;
1996 let y1 = draw_y + el.height as u32;
1997
1998 let mut show_cursor = false;
1999 let mut cursor_pos = 0;
2000
2001 let text_val = if is_focused {
2002 if self.active_text_box.is_none() && !el.element_id.is_empty() {
2003 let val = self
2004 .form_values
2005 .get(&el.element_id)
2006 .cloned()
2007 .unwrap_or_default();
2008 let restore = if self.focus_caret_owner == el.element_id {
2009 Some(self.focus_cursor_pos)
2010 } else {
2011 None
2012 };
2013 self.active_text_box =
2014 Some(Self::build_text_box(&val, el.is_textarea, restore));
2015 }
2016
2017 if let Some(ref tb) = self.active_text_box {
2018 show_cursor = (self.loading_tick / 15).is_multiple_of(2);
2019 if show_cursor {
2020 self.dirty = true;
2021 self.dirty_reason = "render.rs:1055";
2022 }
2023 cursor_pos = tb.cursor_pos;
2024 tb.text.clone()
2025 } else {
2026 String::new()
2027 }
2028 } else if !el.element_id.is_empty() {
2029 self.form_values
2030 .get(&el.element_id)
2031 .cloned()
2032 .unwrap_or(String::new())
2033 } else {
2034 String::new()
2035 };
2036
2037 if el.is_textarea {
2038 let lines = Self::wrap_editor_lines(&text_val, el.width, self.editor_wrap);
2039
2040 let max_scroll_y = (lines.len() as i32 - (el.height / 20) + 1).max(0);
2041 if self.editor_scroll_y > max_scroll_y {
2042 self.editor_scroll_y = max_scroll_y;
2043 }
2044 if self.editor_scroll_y < 0 {
2045 self.editor_scroll_y = 0;
2046 }
2047
2048 let start_line = self.editor_scroll_y as usize;
2049 let mut line_y = y0 + 8;
2050
2051 let cx0 = x0;
2052 let cy0 = y0;
2053 let cx1 = x1;
2054 let cy1 = y1;
2055 screen.push_clip(cx0, cy0, cx1, cy1);
2056
2057 if text_val.is_empty() && !el.placeholder.is_empty() {
2058 screen.draw_string_ja_size_bg(
2059 x0 + 8,
2060 y0 + 8,
2061 &el.placeholder,
2062 16,
2063 draw::Color(el.placeholder_color.unwrap_or(theme.editor_dim_fg)),
2064 draw::Color(bg_col),
2065 );
2066 }
2067
2068 let total_chars = text_val.chars().count();
2069 let mut global_char_idx = 0;
2070 for i in 0..lines.len() {
2071 let (line_text, is_phys_end) = &lines[i];
2072 let is_visible = i >= start_line && line_y + 16 <= y1;
2073 let draw_x = if self.editor_wrap {
2074 x0 + 8
2075 } else {
2076 (x0 as i32 + 8 - self.editor_scroll_x) as u32
2077 };
2078
2079 let line_start_idx = global_char_idx;
2080 let line_len = line_text.chars().count();
2081 let has_newline = *is_phys_end && (line_start_idx + line_len < total_chars);
2082 let line_end_idx =
2083 line_start_idx + line_len + (if has_newline { 1 } else { 0 });
2084
2085 let is_last_line = i == lines.len() - 1;
2086 let is_cursor_line = is_focused
2087 && ((cursor_pos >= line_start_idx && cursor_pos < line_end_idx)
2088 || (is_last_line && cursor_pos == line_end_idx));
2089
2090 if is_cursor_line && is_visible {
2091 screen.boxfill(
2093 x0 + 2,
2094 line_y + 18,
2095 x1.saturating_sub(8),
2096 line_y + 19,
2097 draw::Color(theme.editor_line_highlight),
2098 );
2099 }
2100
2101 let mut cur_x = draw_x;
2102 for c in line_text.chars() {
2103 if is_focused
2104 && global_char_idx == cursor_pos
2105 && is_visible
2106 && show_cursor
2107 {
2108 screen.boxfill(
2110 cur_x,
2111 line_y,
2112 cur_x + 1,
2113 line_y + 16,
2114 draw::Color(el.caret_color.unwrap_or_else(crate::kernel::ime::cursor_color)),
2115 );
2116 }
2117
2118 let cw = crate::kernel::vector_font::get_vector_char_width(c, 16);
2119 if is_visible {
2120 match c {
2121 ' ' | '\u{3000}' | '\t' => {
2122 }
2124 _ => {
2125 let char_color = draw::Color(el.color);
2126 let s_char = String::from(c);
2127 screen.draw_string_ja_size_bg(
2128 cur_x,
2129 line_y,
2130 &s_char,
2131 16,
2132 char_color,
2133 draw::Color(bg_col),
2134 );
2135 }
2136 }
2137 }
2138 cur_x += cw;
2139 global_char_idx += 1;
2140 }
2141
2142 if is_focused && global_char_idx == cursor_pos && is_visible && show_cursor
2143 {
2144 screen.boxfill(
2145 cur_x,
2146 line_y,
2147 cur_x + 1,
2148 line_y + 16,
2149 draw::Color(el.caret_color.unwrap_or_else(crate::kernel::ime::cursor_color)),
2150 );
2151 }
2152
2153 if *is_phys_end && global_char_idx < total_chars {
2154 global_char_idx += 1;
2155 }
2156
2157 if is_visible {
2158 line_y += 20;
2159 }
2160 }
2161
2162 screen.pop_clip();
2163
2164 let content_px = lines.len() as i32 * 20 + 16;
2166 screen.draw_vscrollbar(
2167 x1.saturating_sub(8),
2168 y0 as i32,
2169 el.height,
2170 content_px,
2171 el.height,
2172 self.editor_scroll_y * 20,
2173 );
2174 } else {
2175 let text_y = y0 + (el.height as u32 - 16) / 2;
2179 screen.push_clip(x0, y0, x1, y1);
2180 if text_val.is_empty() && !el.placeholder.is_empty() {
2183 screen.draw_string_ja_size_bg(
2184 x0 + 8,
2185 text_y,
2186 &el.placeholder,
2187 16,
2188 draw::Color(el.placeholder_color.unwrap_or(theme.editor_dim_fg)),
2189 draw::Color(bg_col),
2190 );
2191 }
2192 let mut cur_x = x0 + 8;
2193 let mut idx = 0usize;
2194 for c in text_val.chars() {
2195 if is_focused && idx == cursor_pos && show_cursor {
2196 screen.boxfill(
2197 cur_x,
2198 text_y,
2199 cur_x + 1,
2200 text_y + 16,
2201 draw::Color(el.caret_color.unwrap_or_else(crate::kernel::ime::cursor_color)),
2202 );
2203 }
2204 let cw = crate::kernel::vector_font::get_vector_char_width(c, 16);
2205 if !c.is_whitespace() {
2206 let char_color = draw::Color(el.color);
2207 screen.draw_string_ja_size_bg(
2208 cur_x,
2209 text_y,
2210 &String::from(c),
2211 16,
2212 char_color,
2213 draw::Color(bg_col),
2214 );
2215 }
2216 cur_x += cw;
2217 idx += 1;
2218 }
2219 if is_focused && idx == cursor_pos && show_cursor {
2220 screen.boxfill(
2221 cur_x,
2222 text_y,
2223 cur_x + 1,
2224 text_y + 16,
2225 draw::Color(el.caret_color.unwrap_or_else(crate::kernel::ime::cursor_color)),
2226 );
2227 }
2228 screen.pop_clip();
2229 }
2230 } else if el.is_button {
2231 let is_hovered = self.mouse_y >= draw_y as i32
2232 && self.mouse_y <= (draw_y + el.height as u32) as i32
2233 && self.mouse_x >= (draw_x_base)
2234 && self.mouse_x <= (draw_x_base + el.width);
2235 let is_focused = !el.element_id.is_empty()
2236 && self.focused_id.as_deref() == Some(el.element_id.as_str());
2237 let is_active = is_hovered && self.mouse_btn_left_down;
2240 let base_bg = super::button_paint::button_base_bg(el.bg_color, el.btn_author_bg, theme.btn_default_bg);
2244 let bg_col = if is_active {
2245 el.active_bg_color.or(base_bg)
2246 } else if is_hovered {
2247 el.hover_bg_color.or(base_bg)
2248 } else if is_focused {
2249 el.focus_bg_color.or(base_bg)
2250 } else {
2251 base_bg
2252 };
2253 let base_border = el.border_color.unwrap_or(theme.btn_default_border);
2254 let border_col = if is_active {
2255 el.active_border_color.unwrap_or(base_border)
2256 } else if is_hovered {
2257 el.hover_border_color.unwrap_or(base_border)
2258 } else if is_focused {
2259 el.focus_border_color.unwrap_or(base_border)
2260 } else {
2261 base_border
2262 };
2263
2264 let sx0 = draw_x_base;
2265 let sy0 = draw_y as i32;
2266 let sx1 = draw_x_base + el.width;
2267 let sy1 = draw_y as i32 + el.height;
2268
2269 if el.border_radius != (0, 0, 0, 0) {
2270 if let Some(bg_col) = bg_col {
2271 screen.draw_rounded_rect_fill(
2272 sx0,
2273 sy0,
2274 sx1,
2275 sy1,
2276 el.border_radius,
2277 draw::Color(bg_col),
2278 );
2279 }
2280 if !el.border_style.is_none() {
2282 screen.draw_rounded_rect_border(
2283 sx0,
2284 sy0,
2285 sx1,
2286 sy1,
2287 el.border_radius,
2288 draw::Color(border_col),
2289 el.border_style.as_str(),
2290 );
2291 }
2292 } else {
2293 if let Some(bg_col) = bg_col {
2294 screen.fill_signed(sx0, sy0, sx1, sy1, draw::Color(bg_col));
2295 }
2296 draw_border_with_style(
2297 screen,
2298 sx0,
2299 sy0,
2300 sx1,
2301 sy1,
2302 border_col,
2303 el.border_style,
2304 );
2305 }
2306
2307 let x0 = draw_x_base.max(0) as u32;
2308 let y0 = draw_y;
2309 let x1 = (draw_x_base + el.width).max(0) as u32;
2310 let y1 = draw_y + el.height as u32;
2311
2312 let has_icon = el.button_icon > 0;
2313 let icon_size = 16;
2314 let icon_spacing = 6;
2315
2316 let text_w =
2317 crate::kernel::vector_font::get_vector_string_width(&el.text, el.font_size)
2318 as i32;
2319 let content_w = text_w
2320 + if has_icon {
2321 (icon_size + icon_spacing) as i32
2322 } else {
2323 0
2324 };
2325
2326 let draw_content_x = x0 + ((el.width - content_w).max(0) as u32) / 2;
2327 let draw_text_y = y0 + ((el.height - el.font_size as i32).max(0) as u32) / 2;
2328
2329 let mut draw_text_x = draw_content_x;
2330
2331 if has_icon {
2332 let icon_y = y0 + ((el.height - icon_size as i32).max(0) as u32) / 2;
2333 let svg_data = match el.button_icon {
2334 1 => SVG_SAVE,
2335 2 => SVG_LOAD,
2336 3 => SVG_WRAP,
2337 _ => &[],
2338 };
2339 if !svg_data.is_empty() {
2340 screen.draw_svg_icon(
2341 draw_content_x,
2342 icon_y,
2343 svg_data,
2344 icon_size,
2345 draw::Color(theme.success_fg),
2346 );
2347 }
2348 draw_text_x += icon_size + icon_spacing;
2349 }
2350
2351 match bg_col {
2352 Some(bg_col) => screen.draw_string_ja_size_bg(
2353 draw_text_x,
2354 draw_text_y,
2355 &el.text,
2356 el.font_size,
2357 draw::Color(theme.browser_fg),
2358 draw::Color(bg_col),
2359 ),
2360 None => screen.draw_string_ja_size(
2361 draw_text_x,
2362 draw_text_y,
2363 &el.text,
2364 el.font_size,
2365 draw::Color(theme.browser_fg),
2366 ),
2367 }
2368 } else {
2369 let is_hovered = self.mouse_y >= draw_y as i32
2370 && self.mouse_y <= (draw_y + eff_h as u32) as i32
2371 && self.mouse_x >= (draw_x_base)
2372 && self.mouse_x <= (draw_x_base + eff_w);
2373 let is_focused = !el.element_id.is_empty()
2374 && self.focused_id.as_deref() == Some(el.element_id.as_str());
2375 let is_active = is_hovered && self.mouse_btn_left_down;
2378
2379 let actual_bg_color = if is_active {
2382 el.active_bg_color.or(el.bg_color)
2383 } else if is_hovered {
2384 el.hover_bg_color.or(el.bg_color)
2385 } else if is_focused {
2386 el.focus_bg_color.or(el.bg_color)
2387 } else {
2388 el.bg_color
2389 }
2390 .map(|c| super::draw_helpers::apply_css_filters_argb(&el.filter, c));
2391 let actual_color_raw = if is_active {
2392 el.active_color.unwrap_or(el.color)
2393 } else if is_hovered {
2394 el.hover_color.unwrap_or(el.color)
2395 } else if is_focused {
2396 el.focus_color.unwrap_or(el.color)
2397 } else {
2398 el.color
2399 };
2400 let actual_color = if el.opacity < 255 {
2402 let a = el.opacity as u32;
2403 let r = (actual_color_raw >> 16) & 0xFF;
2404 let g = (actual_color_raw >> 8) & 0xFF;
2405 let b = actual_color_raw & 0xFF;
2406 (a << 24) | (r << 16) | (g << 8) | b
2407 } else {
2408 actual_color_raw
2409 };
2410 let w = if eff_w > 0 {
2411 eff_w
2412 } else {
2413 vector_font::get_vector_string_width(&el.text, el.font_size) as i32
2414 };
2415
2416 let x0_rect = (draw_x_base as u32) as i32;
2417 let y0_rect = draw_y as i32;
2418 let x1_rect = (draw_x_base as u32 + w as u32) as i32;
2419 let y1_rect = (draw_y + eff_h as u32) as i32;
2420
2421 if !el.backdrop_filter.is_empty() {
2424 let (cx0, cy0, cx1, cy1) = screen
2425 .clip
2426 .get()
2427 .map(|(c0, c1, c2, c3)| (c0 as i32, c1 as i32, c2 as i32, c3 as i32))
2428 .unwrap_or((0, 0, screen.width as i32, screen.height as i32));
2429 let bx0 = x0_rect.max(cx0);
2430 let by0 = y0_rect.max(cy0);
2431 let bx1 = x1_rect.min(cx1);
2432 let by1 = y1_rect.min(cy1);
2433 if bx1 > bx0 && by1 > by0 {
2434 crate::os_lib::web_engine::draw_helpers::apply_backdrop_filters_to_screen_rect(
2435 screen, bx0, by0, bx1, by1, &el.backdrop_filter,
2436 );
2437 }
2438 }
2439
2440 for &(ox, oy, blur, s_color, is_inset) in el.box_shadow.iter().rev() {
2443 if !is_inset {
2444 screen.draw_shadow_rect_rounded(
2445 x0_rect,
2446 y0_rect,
2447 x1_rect,
2448 y1_rect,
2449 ox,
2450 oy,
2451 blur,
2452 el.border_radius,
2453 draw::Color(s_color),
2454 );
2455 }
2456 }
2457
2458 let clip_s = if el.clip_path.is_empty() {
2460 None
2461 } else {
2462 parse_clip_shape_with_font(&el.clip_path, w, eff_h, el.font_size as f32)
2463 };
2464
2465 let rotate_deg = el.transform_rotate_deg;
2468 if rotate_deg.abs() > 0.1 {
2469 if let Some(bg) = actual_bg_color {
2470 let cx = x0_rect + w / 2;
2471 let cy = y0_rect + eff_h / 2;
2472 draw_rotated_rect_filled(screen, cx, cy, w, eff_h, rotate_deg, bg);
2473 }
2474 }
2475 let skew_x = el.transform_skew_x;
2476 let skew_y = el.transform_skew_y;
2477 if skew_x.abs() > 0.1 || skew_y.abs() > 0.1 {
2478 if let Some(bg) = actual_bg_color {
2479 let cx = x0_rect + w / 2;
2480 let cy = y0_rect + eff_h / 2;
2481 draw_skewed_rect_filled(screen, cx, cy, w, eff_h, skew_x, skew_y, bg);
2482 }
2483 }
2484
2485 if el.border_radius != (0, 0, 0, 0) {
2486 let bg_clipped = el.bg_clip != "border-box";
2489 if bg_clipped {
2490 let (cx0, cy0, cx1, cy1) = bg_clip_rect(el, x0_rect, y0_rect, x1_rect, y1_rect);
2491 screen.push_clip(cx0, cy0, cx1, cy1);
2492 }
2493 if clip_s.is_some() {
2495 let bg_col = actual_bg_color
2496 .or(el.linear_gradient.as_ref().map(|g| g.stops.first().map_or(0, |s| s.color)))
2497 .or(el.radial_gradient.as_ref().map(|g| g.stops.first().map_or(0, |s| s.color)))
2498 .or(el.conic_gradient.as_ref().and_then(|stops| stops.first().map(|s| s.color)))
2499 .or(el.repeating_linear_gradient.as_ref().and_then(|(colors, _, _)| colors.first().copied()))
2500 .or(el.repeating_radial_gradient.as_ref().and_then(|(colors, _)| colors.first().copied()));
2501 if let Some(bg) = bg_col {
2502 let bg_with_opacity = if el.opacity < 255 {
2503 let a = el.opacity as u32;
2504 let r = (bg >> 16) & 0xFF;
2505 let g = (bg >> 8) & 0xFF;
2506 let b = bg & 0xFF;
2507 (a << 24) | (r << 16) | (g << 8) | b
2508 } else { bg };
2509 let _t_rr = crate::kernel::draw::RRectTimer::new();
2513 for ry in 0..eff_h {
2514 for rx in 0..w {
2515 let in_clip = clip_s.as_ref().map(|cs| clip_inside(cs, rx, ry)).unwrap_or(true);
2516 let in_rr = point_in_rounded_rect(rx, ry, w, eff_h, el.border_radius);
2517 if in_clip && in_rr {
2518 screen.draw_pixel_alpha(
2519 (x0_rect + rx) as u32,
2520 (y0_rect + ry) as u32,
2521 draw::Color(bg_with_opacity),
2522 el.opacity,
2523 );
2524 }
2525 }
2526 }
2527 }
2528 } else {
2529 if let Some(grad) = &el.linear_gradient {
2531 let c1 = grad.stops.first().map_or(0, |s| s.color);
2532 let c2 = grad.stops.last().map_or(c1, |s| s.color);
2537 let is_vertical = {
2538 let a = ((grad.angle_deg % 360.0) + 360.0) % 360.0;
2541 !((45.0..135.0).contains(&a) || (225.0..315.0).contains(&a))
2542 };
2543 if el.border_radius == (0, 0, 0, 0) && grad.stops.len() >= 2 && x1_rect > x0_rect && y1_rect > y0_rect {
2544 screen.draw_gradient_rect(
2545 x0_rect as u32,
2546 y0_rect as u32,
2547 x1_rect as u32,
2548 y1_rect as u32,
2549 draw::Color(c1),
2550 draw::Color(c2),
2551 is_vertical,
2552 );
2553 } else {
2554 screen.draw_rounded_rect_fill(
2555 x0_rect,
2556 y0_rect,
2557 x1_rect,
2558 y1_rect,
2559 el.border_radius,
2560 draw::Color(c1),
2561 );
2562 }
2563 } else if let Some(grad) = &el.radial_gradient {
2564 let c1 = grad.stops.first().map_or(0, |s| s.color);
2566 screen.draw_rounded_rect_fill(
2567 x0_rect,
2568 y0_rect,
2569 x1_rect,
2570 y1_rect,
2571 el.border_radius,
2572 draw::Color(c1),
2573 );
2574 } else if let Some(stops) = &el.conic_gradient {
2575 let c1 = stops.first().map_or(0, |s| s.color);
2577 screen.draw_rounded_rect_fill(
2578 x0_rect,
2579 y0_rect,
2580 x1_rect,
2581 y1_rect,
2582 el.border_radius,
2583 draw::Color(c1),
2584 );
2585 } else if let Some((colors, _, _)) = &el.repeating_linear_gradient {
2586 let c1 = colors.first().copied().unwrap_or(0);
2588 screen.draw_rounded_rect_fill(
2589 x0_rect,
2590 y0_rect,
2591 x1_rect,
2592 y1_rect,
2593 el.border_radius,
2594 draw::Color(c1),
2595 );
2596 } else if let Some((colors, _)) = &el.repeating_radial_gradient {
2597 let c1 = colors.first().copied().unwrap_or(0);
2599 screen.draw_rounded_rect_fill(
2600 x0_rect,
2601 y0_rect,
2602 x1_rect,
2603 y1_rect,
2604 el.border_radius,
2605 draw::Color(c1),
2606 );
2607 } else if let Some(bg) = actual_bg_color {
2608 let bg_with_opacity = if el.opacity < 255 {
2609 let a = el.opacity as u32;
2610 let r = (bg >> 16) & 0xFF;
2611 let g = (bg >> 8) & 0xFF;
2612 let b = bg & 0xFF;
2613 (a << 24) | (r << 16) | (g << 8) | b
2614 } else {
2615 bg
2616 };
2617 if rotate_deg.abs() < 0.1 {
2618 screen.draw_rounded_rect_fill(
2619 x0_rect,
2620 y0_rect,
2621 x1_rect,
2622 y1_rect,
2623 el.border_radius,
2624 draw::Color(bg_with_opacity),
2625 );
2626 }
2627 }
2628 } let bg_attach_shift_y = if el.bg_attachment == "fixed" {
2631 self.scroll_y
2632 } else {
2633 0
2634 };
2635 let (bg_origin_sx, bg_origin_sy, bg_origin_w, bg_origin_h) =
2637 bg_origin_shift(el, eff_w, eff_h);
2638 if el.bg_images.len() > 1 {
2639 for (i, layer_path) in el.bg_images.iter().enumerate().rev() {
2643 if !self.image_cache.contains_key(layer_path) {
2644 log_bg_image_miss(layer_path, self.image_cache.len(), "layer");
2645 }
2646 if let Some(img) = self.image_cache.get(layer_path) {
2647 let layer_override = el.bg_layers.get(i).copied();
2648 draw_background_image(
2649 screen, img, el, x0_rect, y0_rect, eff_w, eff_h, &clip_s,
2650 bg_attach_shift_y, bg_origin_sx, bg_origin_sy, bg_origin_w,
2651 bg_origin_h, layer_override,
2652 );
2653 }
2654 }
2655 } else if let Some(ref bg_img_path) = el.bg_image {
2656 if !self.image_cache.contains_key(bg_img_path) {
2662 static MISS: spin::Mutex<alloc::collections::BTreeSet<String>> =
2663 spin::Mutex::new(alloc::collections::BTreeSet::new());
2664 let mut seen = MISS.lock();
2665 if seen.insert(bg_img_path.clone()) {
2666 crate::warn!(
2667 "[IMG][MISS] 背景画像がキャッシュに無い path={} cache_keys={}",
2668 bg_img_path,
2669 self.image_cache.len()
2670 );
2671 }
2672 }
2673 if let Some(img) = self.image_cache.get(bg_img_path) {
2674 draw_background_image(
2675 screen, img, el, x0_rect, y0_rect, eff_w, eff_h, &clip_s,
2676 bg_attach_shift_y, bg_origin_sx, bg_origin_sy, bg_origin_w,
2677 bg_origin_h, None,
2678 );
2679 }
2680 }
2681 if bg_clipped {
2682 screen.pop_clip();
2683 }
2684 for &(ox, oy, blur, s_color, is_inset) in el.box_shadow.iter().rev() {
2686 if is_inset {
2687 screen.draw_inset_shadow_rect(
2688 x0_rect,
2689 y0_rect,
2690 x1_rect,
2691 y1_rect,
2692 ox,
2693 oy,
2694 blur,
2695 el.border_radius,
2696 draw::Color(s_color),
2697 );
2698 }
2699 }
2700
2701 if el.opacity > 0 {
2705 let state_col = if is_active {
2706 el.active_border_color
2707 } else if is_hovered {
2708 el.hover_border_color
2709 } else if is_focused {
2710 el.focus_border_color
2711 } else {
2712 None
2713 };
2714 let side = |wd: i32, none: bool, c: Option<u32>| -> (i32, u32) {
2715 if wd <= 0 || none {
2716 return (0, 0);
2717 }
2718 let col = state_col.or(c).or(el.border_color).unwrap_or(el.color);
2719 (wd, super::alpha_blend::scale_alpha(col, el.opacity))
2720 };
2721 let (wt, ct) = side(el.border_top_width, el.border_top_style.is_none(), el.border_top_color);
2722 let (wr, cr) = side(el.border_right_width, el.border_right_style.is_none(), el.border_right_color);
2723 let (wb, cb) = side(el.border_bottom_width, el.border_bottom_style.is_none(), el.border_bottom_color);
2724 let (wl, cl) = side(el.border_left_width, el.border_left_style.is_none(), el.border_left_color);
2725 screen.draw_rounded_rect_border_sides(
2726 x0_rect,
2727 y0_rect,
2728 x1_rect,
2729 y1_rect,
2730 el.border_radius,
2731 (wt, wr, wb, wl),
2732 (ct, cr, cb, cl),
2733 );
2734 }
2735 } else {
2736 let bg_clipped = el.bg_clip != "border-box";
2739 if bg_clipped {
2740 let (cx0, cy0, cx1, cy1) = bg_clip_rect(el, x0_rect, y0_rect, x1_rect, y1_rect);
2741 screen.push_clip(cx0, cy0, cx1, cy1);
2742 }
2743 if let Some(grad) = &el.linear_gradient {
2745 if rotate_deg.abs() < 0.1 {
2746 crate::os_lib::web_engine::draw_helpers::draw_linear_gradient(
2747 screen,
2748 x0_rect,
2749 y0_rect,
2750 x1_rect - x0_rect,
2751 y1_rect - y0_rect,
2752 grad,
2753 );
2754 }
2755 } else if let Some(grad) = &el.radial_gradient {
2756 if rotate_deg.abs() < 0.1 {
2757 crate::os_lib::web_engine::draw_helpers::draw_radial_gradient(
2758 screen,
2759 x0_rect,
2760 y0_rect,
2761 x1_rect - x0_rect,
2762 y1_rect - y0_rect,
2763 grad,
2764 );
2765 }
2766 } else if let Some(stops) = &el.conic_gradient {
2767 if rotate_deg.abs() < 0.1 {
2768 crate::os_lib::web_engine::draw_helpers::draw_conic_gradient(
2769 screen,
2770 x0_rect,
2771 y0_rect,
2772 x1_rect - x0_rect,
2773 y1_rect - y0_rect,
2774 stops,
2775 );
2776 }
2777 } else if let Some((colors, cycle, is_vert)) = &el.repeating_linear_gradient {
2778 if rotate_deg.abs() < 0.1 {
2779 let draw_colors: alloc::vec::Vec<draw::Color> =
2780 colors.iter().map(|c| draw::Color(*c)).collect();
2781 screen.draw_repeating_linear_gradient_rect(
2782 x0_rect as u32,
2783 y0_rect as u32,
2784 x1_rect as u32,
2785 y1_rect as u32,
2786 &draw_colors,
2787 *cycle,
2788 *is_vert,
2789 );
2790 }
2791 } else if let Some((colors, cycle)) = &el.repeating_radial_gradient {
2792 if rotate_deg.abs() < 0.1 {
2793 let draw_colors: alloc::vec::Vec<draw::Color> =
2794 colors.iter().map(|c| draw::Color(*c)).collect();
2795 screen.draw_repeating_radial_gradient_rect(
2796 x0_rect as u32,
2797 y0_rect as u32,
2798 x1_rect as u32,
2799 y1_rect as u32,
2800 &draw_colors,
2801 *cycle,
2802 );
2803 }
2804 } else if let Some(bg) = actual_bg_color {
2805 let bg_with_opacity = if el.opacity < 255 {
2806 let a = el.opacity as u32;
2807 let r = (bg >> 16) & 0xFF;
2808 let g = (bg >> 8) & 0xFF;
2809 let b = bg & 0xFF;
2810 (a << 24) | (r << 16) | (g << 8) | b
2811 } else {
2812 bg
2813 };
2814 if rotate_deg.abs() < 0.1 {
2816 let _t_pix = crate::kernel::draw::PixBgTimer::new();
2817 if let Some(ref cs) = clip_s {
2818 for ry in 0..eff_h {
2820 for rx in 0..w {
2821 if clip_inside(cs, rx, ry) {
2822 screen.draw_pixel_alpha(
2823 (x0_rect + rx) as u32,
2824 (y0_rect + ry) as u32,
2825 draw::Color(bg_with_opacity),
2826 el.opacity,
2827 );
2828 }
2829 }
2830 }
2831 } else if el.opacity < 255 {
2832 if x1_rect > x0_rect && y1_rect > y0_rect {
2834 screen.fill_signed_alpha(
2835 x0_rect,
2836 y0_rect,
2837 x1_rect - 1,
2838 y1_rect - 1,
2839 draw::Color(bg_with_opacity),
2840 el.opacity,
2841 );
2842 }
2843 } else if !el.mix_blend_mode.is_empty()
2844 && el.mix_blend_mode != "normal"
2845 {
2846 let src = (
2849 ((bg >> 16) & 0xFF) as u8,
2850 ((bg >> 8) & 0xFF) as u8,
2851 (bg & 0xFF) as u8,
2852 );
2853 let my0 = y0_rect.max(0) as u32;
2854 let my1 = y1_rect.max(0) as u32;
2855 let mx0 = x0_rect.max(0) as u32;
2856 let mx1 = x1_rect.max(0) as u32;
2857 for ry in my0..my1 {
2858 for rx in mx0..mx1 {
2859 let dst_c = screen.read_pixel(rx, ry).0;
2860 let dst = (
2861 ((dst_c >> 16) & 0xFF) as u8,
2862 ((dst_c >> 8) & 0xFF) as u8,
2863 (dst_c & 0xFF) as u8,
2864 );
2865 let (r, g, b) =
2866 blend_pixel(&el.mix_blend_mode, src, dst);
2867 screen.draw_pixel(
2868 rx,
2869 ry,
2870 draw::Color(
2871 0xFF000000
2872 | ((r as u32) << 16)
2873 | ((g as u32) << 8)
2874 | (b as u32),
2875 ),
2876 );
2877 }
2878 }
2879 } else {
2880 screen.fill_signed(
2884 x0_rect,
2885 y0_rect,
2886 x1_rect - 1,
2887 y1_rect - 1,
2888 draw::Color(bg),
2889 );
2890 }
2891 }
2892 }
2893 let bg_attach_shift_y = if el.bg_attachment == "fixed" {
2895 self.scroll_y
2896 } else {
2897 0
2898 };
2899 let (bg_origin_sx, bg_origin_sy, bg_origin_w, bg_origin_h) =
2901 bg_origin_shift(el, eff_w, eff_h);
2902 if el.bg_images.len() > 1 {
2903 for (i, layer_path) in el.bg_images.iter().enumerate().rev() {
2907 if !self.image_cache.contains_key(layer_path) {
2908 log_bg_image_miss(layer_path, self.image_cache.len(), "layer");
2909 }
2910 if let Some(img) = self.image_cache.get(layer_path) {
2911 let layer_override = el.bg_layers.get(i).copied();
2912 draw_background_image(
2913 screen, img, el, x0_rect, y0_rect, eff_w, eff_h, &clip_s,
2914 bg_attach_shift_y, bg_origin_sx, bg_origin_sy, bg_origin_w,
2915 bg_origin_h, layer_override,
2916 );
2917 }
2918 }
2919 } else if let Some(ref bg_img_path) = el.bg_image {
2920 if let Some(img) = self.image_cache.get(bg_img_path) {
2921 draw_background_image(
2922 screen, img, el, x0_rect, y0_rect, eff_w, eff_h, &clip_s,
2923 bg_attach_shift_y, bg_origin_sx, bg_origin_sy, bg_origin_w,
2924 bg_origin_h, None,
2925 );
2926 }
2927 }
2928 if bg_clipped {
2929 screen.pop_clip();
2930 }
2931 for &(ox, oy, blur, s_color, is_inset) in el.box_shadow.iter().rev() {
2933 if is_inset {
2934 screen.draw_inset_shadow_rect(
2935 x0_rect,
2936 y0_rect,
2937 x1_rect,
2938 y1_rect,
2939 ox,
2940 oy,
2941 blur,
2942 el.border_radius,
2943 draw::Color(s_color),
2944 );
2945 }
2946 }
2947 draw_individual_borders(
2948 screen, x0_rect, y0_rect, x1_rect, y1_rect, el, is_hovered, is_focused,
2949 is_active,
2950 );
2951 if let Some(outline_color) = el.outline_color {
2952 if el.outline_width > 0 {
2953 let current_clip = screen.clip_rect();
2957 pending_outlines.push((
2958 x0_rect,
2959 y0_rect,
2960 x1_rect,
2961 y1_rect,
2962 el.outline_width,
2963 el.outline_offset,
2964 outline_color,
2965 el.outline_style.clone(),
2966 current_clip,
2967 ));
2968 }
2969 }
2970 }
2971
2972 if el.is_blockquote {
2973 let line_x0 = x0_rect as u32;
2974 let line_y0 = y0_rect as u32;
2975 let line_x1 = (x0_rect + 4) as u32;
2976 let line_y1 = y1_rect as u32;
2977 screen.boxfill(line_x0, line_y0, line_x1, line_y1, draw::Color(theme.sysmon_accent));
2978 }
2979
2980 if !el.text.is_empty()
2981 || !el.before_content.is_empty()
2982 || !el.after_content.is_empty()
2983 {
2984 let mut text_draw_x = draw_x_base as u32;
2985 let list_style_image_cached = if el.is_li && !el.list_style_image.is_empty() {
2986 self.image_cache.get(&el.list_style_image)
2987 } else {
2988 None
2989 };
2990 if let (true, Some(img)) = (el.is_li, list_style_image_cached) {
2991 let size = el.font_size.max(1);
2993 let marker_x = if el.list_style_inside {
2994 text_draw_x
2995 } else {
2996 text_draw_x.saturating_sub(size + 4)
2997 };
2998 crate::os_lib::web_engine::draw_helpers::draw_image_nn_blit(
2999 screen, img, marker_x as i32, draw_y as i32, size, size,
3000 );
3001 if el.list_style_inside {
3002 text_draw_x += size + 4;
3003 }
3004 } else if el.is_li && el.list_style_type != super::ListStyleType::None {
3005 let marker_color = el.marker_color.unwrap_or(el.color);
3009 let marker_font_size = el.marker_font_size.unwrap_or(el.font_size);
3010 let is_ordinal_style = matches!(
3012 el.list_style_type,
3013 super::ListStyleType::Decimal
3014 | super::ListStyleType::UpperAlpha
3015 | super::ListStyleType::LowerAlpha
3016 | super::ListStyleType::UpperRoman
3017 | super::ListStyleType::LowerRoman
3018 );
3019 let use_number = is_ordinal_style
3020 || (el.li_num.is_some() && el.list_style_type == super::ListStyleType::Unset);
3021 let bg_color = el.bg_color.unwrap_or_else(|| self.effective_bg_behind(el));
3022 let marker_str = if let Some(custom) = &el.marker_content {
3023 custom.clone()
3024 } else if use_number {
3025 let n = el.li_num.unwrap_or(1);
3026 match el.list_style_type {
3027 super::ListStyleType::UpperAlpha => {
3028 alloc::format!("{}.", super::number_to_alpha(n, true))
3029 }
3030 super::ListStyleType::LowerAlpha => {
3031 alloc::format!("{}.", super::number_to_alpha(n, false))
3032 }
3033 super::ListStyleType::UpperRoman => {
3034 alloc::format!("{}.", super::number_to_roman(n, true))
3035 }
3036 super::ListStyleType::LowerRoman => {
3037 alloc::format!("{}.", super::number_to_roman(n, false))
3038 }
3039 _ => alloc::format!("{}.", n),
3040 }
3041 } else {
3042 match el.list_style_type {
3043 super::ListStyleType::Circle => alloc::string::String::from("◦"),
3044 super::ListStyleType::Square => alloc::string::String::from("▪"),
3045 _ => alloc::string::String::from("•"), }
3047 };
3048 let marker_w = crate::kernel::vector_font::get_vector_string_width(
3049 &marker_str,
3050 marker_font_size,
3051 ) as u32;
3052 let marker_x = if el.list_style_inside {
3055 text_draw_x
3056 } else {
3057 text_draw_x.saturating_sub(marker_w + 4)
3058 };
3059 screen.draw_string_ja_size_bg(
3060 marker_x,
3061 draw_y,
3062 &marker_str,
3063 marker_font_size,
3064 draw::Color(marker_color),
3065 draw::Color(bg_color),
3066 );
3067 if el.list_style_inside {
3068 text_draw_x += marker_w + 4;
3069 }
3070 }
3071
3072 let split_before = !el.before_content.is_empty()
3088 && !el.before_font_family.is_empty()
3089 && !el
3090 .font_family
3091 .to_lowercase()
3092 .contains(&el.before_font_family.to_lowercase());
3093 if split_before {
3094 screen.draw_string_family(
3095 text_draw_x,
3096 draw_y,
3097 &el.before_content,
3098 el.font_size,
3099 draw::Color(el.color),
3100 el.font_italic,
3101 draw::Color(el.bg_color.unwrap_or_else(|| self.effective_bg_behind(el))),
3102 el.letter_spacing,
3103 el.word_spacing,
3104 &el.before_font_family,
3105 el.weight(),
3106 );
3107 text_draw_x += crate::kernel::vector_font::get_vector_string_width(
3108 &el.before_content,
3109 el.font_size,
3110 );
3111 }
3112 let text_with_pseudo = if (el.before_content.is_empty() || split_before)
3113 && el.after_content.is_empty()
3114 {
3115 el.text.clone()
3116 } else if split_before {
3117 alloc::format!("{}{}", el.text, el.after_content)
3118 } else {
3119 alloc::format!("{}{}{}", el.before_content, el.text, el.after_content)
3120 };
3121
3122 let draw_text = if el.text_overflow_ellipsis && eff_w > 0 {
3124 crate::os_lib::web_engine::text_ellipsis::truncate_text_ellipsis(
3125 &text_with_pseudo,
3126 eff_w,
3127 "…",
3128 el.text_overflow_rtl,
3129 |s| crate::kernel::vector_font::get_vector_string_width(s, el.font_size) as i32,
3130 )
3131 } else {
3132 text_with_pseudo
3133 };
3134 let bg_color = el.bg_color.unwrap_or_else(|| self.effective_bg_behind(el));
3135 for &(sx, sy, _blur, s_color) in el.text_shadow.iter().rev() {
3140 screen.draw_string_ja_size_ext_bg_ls_ws(
3141 (text_draw_x as i32 + sx).max(0) as u32,
3142 (draw_y as i32 + sy).max(0) as u32,
3143 &draw_text,
3144 el.font_size,
3145 draw::Color(s_color),
3146 el.font_italic,
3147 draw::Color(0),
3148 el.letter_spacing,
3149 el.word_spacing,
3150 );
3151 }
3152
3153 if el.text_stroke_width > 0 {
3154 let stroke_color = el.text_stroke_color.unwrap_or(0xFF000000);
3155 let sw = el.text_stroke_width.min(4);
3156 for dy in -sw..=sw {
3157 for dx in -sw..=sw {
3158 if dx == 0 && dy == 0 { continue; }
3159 screen.draw_string_ja_size_ext_bg_ls_ws(
3160 (text_draw_x as i32 + dx).max(0) as u32,
3161 (draw_y as i32 + dy).max(0) as u32,
3162 &draw_text,
3163 el.font_size,
3164 draw::Color(stroke_color),
3165 el.font_italic,
3166 draw::Color(0),
3167 el.letter_spacing,
3168 el.word_spacing,
3169 );
3170 }
3171 }
3172 }
3173
3174 let used_weight = screen.draw_string_family(
3192 text_draw_x,
3193 draw_y,
3194 &draw_text,
3195 el.font_size,
3196 draw::Color(actual_color),
3197 el.font_italic,
3198 draw::Color(bg_color),
3199 el.letter_spacing,
3200 el.word_spacing,
3201 &el.font_family,
3202 el.weight(),
3203 );
3204 if el.font_bold && used_weight < 600 {
3208 screen.draw_string_family(
3209 text_draw_x + 1,
3210 draw_y,
3211 &draw_text,
3212 el.font_size,
3213 draw::Color(actual_color),
3214 el.font_italic,
3215 draw::Color(bg_color),
3216 el.letter_spacing,
3217 el.word_spacing,
3218 &el.font_family,
3219 el.weight(),
3220 );
3221 }
3222 if !el.text_emphasis_style.is_empty() {
3224 screen.draw_text_emphasis(
3225 text_draw_x,
3226 draw_y,
3227 &draw_text,
3228 el.font_size,
3229 &el.text_emphasis_style,
3230 draw::Color(el.text_emphasis_color.unwrap_or(actual_color)),
3231 el.letter_spacing,
3232 el.word_spacing,
3233 );
3234 }
3235 }
3236
3237 let decoration_color = el.decoration_color.unwrap_or(actual_color);
3238 if el.underline {
3239 let line_y = ((draw_y as i32) + el.font_size as i32 + 2
3242 + el.decoration_underline_offset)
3243 .max(0) as u32;
3244 if line_y < win_y + win_h {
3245 draw_decoration_line(
3246 screen,
3247 draw_x_base as u32,
3248 line_y,
3249 draw_x_base as u32 + w as u32,
3250 &el.decoration_style,
3251 decoration_color,
3252 el.decoration_thickness as u32,
3253 );
3254 }
3255 }
3256
3257 if el.line_through {
3258 let line_y = draw_y + el.font_size / 2 + 1;
3259 if line_y < win_y + win_h {
3260 draw_decoration_line(
3261 screen,
3262 draw_x_base as u32,
3263 line_y,
3264 draw_x_base as u32 + w as u32,
3265 &el.decoration_style,
3266 decoration_color,
3267 el.decoration_thickness as u32,
3268 );
3269 }
3270 }
3271
3272 if el.overline {
3273 let line_y = draw_y;
3274 if line_y < win_y + win_h {
3275 draw_decoration_line(
3276 screen,
3277 draw_x_base as u32,
3278 line_y,
3279 draw_x_base as u32 + w as u32,
3280 &el.decoration_style,
3281 decoration_color,
3282 el.decoration_thickness as u32,
3283 );
3284 }
3285 }
3286
3287 if el.is_link && !el.pointer_events_none {
3288 self.links.push(HyperlinkArea {
3289 href: el.href.clone(),
3290 x0: el.x_offset,
3291 y0: el.y_offset,
3292 x1: el.x_offset + w,
3293 y1: el.y_offset + el.height,
3294 });
3295 }
3296 }
3297
3298 if let Some(before) = &blur_before {
3300 crate::os_lib::web_engine::draw_helpers::blur_element_paint(screen, before, blur_radius);
3301 }
3302
3303 if has_overflow_clip {
3304 screen.pop_clip();
3305 }
3306 screen.round_clip.set(None);
3307 let _ = el_start;
3308 }
3309
3310 if let Some(ref range) = self.selection {
3312 if !range.is_empty() {
3313 let text_layouts: alloc::vec::Vec<super::selection::TextElementLayout> = self
3314 .elements
3315 .iter()
3316 .enumerate()
3317 .filter(|(_, el)| !el.text.is_empty() && !el.is_button)
3318 .map(|(idx, el)| super::selection::TextElementLayout {
3319 element_index: idx,
3320 text: el.text.clone(),
3321 x: el.x_offset,
3322 y: el.y_offset,
3323 width: el.width,
3324 height: el.height,
3325 })
3326 .collect();
3327 let highlights = super::selection::compute_selection_highlights(&text_layouts, range);
3328 let sel_color = self.selection_style.bg_color.unwrap_or(0x003399FF);
3329 let sel_alpha = self.selection_style.bg_alpha;
3330 for h in highlights {
3331 let h_screen_x = win_x as i32 + 20 + h.x;
3332 let h_screen_y = win_y as i32 + top_offset + h.y - self.scroll_y;
3333 let bottom_limit = (win_y + win_h) as i32;
3334 let top_limit = win_y as i32 + top_offset;
3335 if h_screen_y + h.height > top_limit && h_screen_y < bottom_limit {
3336 let draw_y0 = h_screen_y.max(top_limit);
3337 let draw_y1 = (h_screen_y + h.height).min(bottom_limit);
3338 let draw_x0 = h_screen_x.max(win_x as i32);
3339 let draw_x1 = (h_screen_x + h.width).min((win_x + win_w) as i32);
3340 if draw_x1 > draw_x0 && draw_y1 > draw_y0 {
3341 screen.boxfill_alpha(
3342 draw_x0 as u32,
3343 draw_y0 as u32,
3344 (draw_x1 as u32).saturating_sub(1),
3345 (draw_y1 as u32).saturating_sub(1),
3346 draw::Color(sel_color),
3347 sel_alpha,
3348 );
3349 }
3350 }
3351 }
3352 }
3353 }
3354
3355 for (ox0, oy0, ox1, oy1, o_width, o_offset, o_color, o_style, o_clip) in pending_outlines {
3359 let saved_clip = screen.clip_rect();
3360 if let Some((cx0, cy0, cx1, cy1)) = o_clip {
3361 screen.set_clip(cx0, cy0, cx1, cy1);
3362 } else {
3363 screen.clear_clip();
3364 }
3365 draw_outline(
3366 screen,
3367 ox0,
3368 oy0,
3369 ox1,
3370 oy1,
3371 o_width,
3372 o_offset,
3373 o_color,
3374 &o_style,
3375 );
3376 if let Some((sx0, sy0, sx1, sy1)) = saved_clip {
3377 screen.set_clip(sx0, sy0, sx1, sy1);
3378 } else {
3379 screen.clear_clip();
3380 }
3381 }
3382
3383 if self.max_scroll_y > 0 && !self.scrollbar_width.is_none() {
3384 let bar_track_h = win_h as i32 - top_offset;
3386 let bar_track_y = (win_y + top_offset as u32) as i32;
3387 let content_h = self.max_scroll_y + bar_track_h;
3388 let thumb_w = self.scrollbar_width.thumb_width_px() as u32;
3389 let thumb_col = self
3390 .scrollbar_color
3391 .map(|c| draw::Color(c.thumb))
3392 .unwrap_or_else(|| draw::Color(crate::kernel::config::get_config().theme.scrollbar_thumb));
3393 let track_col = self.scrollbar_color.map(|c| draw::Color(c.track));
3394 let bar_x = win_x + win_w - (thumb_w + 4);
3395 screen.draw_vscrollbar_styled(
3396 bar_x,
3397 bar_track_y,
3398 bar_track_h,
3399 content_h,
3400 bar_track_h,
3401 self.scroll_y,
3402 thumb_w,
3403 thumb_col,
3404 track_col,
3405 );
3406 }
3407
3408 for (cid, max_y, cx, cy, cw, ch, sc_width, sc_color) in &self.scroll_containers {
3410 if *max_y <= 0 || sc_width.is_none() {
3411 continue;
3412 }
3413 let cur = self.scroll_regions.get(cid).copied().unwrap_or(0);
3414 let thumb_w = sc_width.thumb_width_px() as u32;
3415 let bar_x = win_x as i32 + cx + cw - (thumb_w as i32 + 4);
3416 let bar_y = cy - self.scroll_y + top_offset;
3417 let content_h = max_y + ch;
3418 let thumb_col = sc_color
3419 .map(|c| draw::Color(c.thumb))
3420 .unwrap_or_else(|| draw::Color(crate::kernel::config::get_config().theme.scrollbar_thumb));
3421 let track_col = sc_color.map(|c| draw::Color(c.track));
3422 screen.draw_vscrollbar_styled(
3423 bar_x as u32,
3424 bar_y,
3425 *ch,
3426 content_h,
3427 *ch,
3428 cur,
3429 thumb_w,
3430 thumb_col,
3431 track_col,
3432 );
3433 }
3434
3435
3436 if self.frame_depth == 0 {
3437 super::video::end_app_draw(core::mem::take(&mut video_occluders));
3438 }
3439 let draw_end_tick = crate::kernel::timer::get_ticks();
3440 DRAW_LAST_END.store(draw_end_tick, core::sync::atomic::Ordering::Relaxed);
3441 let elapsed = draw_end_tick.wrapping_sub(draw_start_tick);
3442 {
3446 use core::sync::atomic::{AtomicU32, Ordering};
3447 static FRAMES: AtomicU32 = AtomicU32::new(0);
3448 static TICKS: AtomicU32 = AtomicU32::new(0);
3449 static MAXT: AtomicU32 = AtomicU32::new(0);
3450 let prev_max = MAXT.load(Ordering::Relaxed);
3455 if elapsed as u32 > prev_max && elapsed > 50 {
3456 let relayout_this = RELAYOUT_IN_DRAW_TICKS
3457 .load(Ordering::Relaxed)
3458 .wrapping_sub(relayout_before);
3459 crate::warn!(
3460 "[PERF][DRAW] 最長更新 {}tick(うち再レイアウト {}tick, 要素={})",
3461 elapsed,
3462 relayout_this,
3463 self.elements.len()
3464 );
3465 }
3466 let n = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
3467 TICKS.fetch_add(elapsed as u32, Ordering::Relaxed);
3468 MAXT.fetch_max(elapsed as u32, Ordering::Relaxed);
3469 let last_dump = LAST_DUMP_TICK.load(Ordering::Relaxed);
3478 let due = last_dump == 0
3479 || draw_end_tick.wrapping_sub(last_dump) >= DUMP_INTERVAL_TICKS;
3480 if due {
3481 LAST_DUMP_TICK.store(draw_end_tick, Ordering::Relaxed);
3482 }
3483 if due {
3484 crate::warn!(
3485 "[PERF][DRAW] 要素={} frames={} total={}tick max={}tick relayout={}tick 間隔合計={}tick 間隔最大={}tick 送信待ち={}tick/{}回 再送={}回",
3486 self.elements.len(),
3487 n,
3488 TICKS.load(Ordering::Relaxed),
3489 MAXT.load(Ordering::Relaxed),
3490 RELAYOUT_IN_DRAW_TICKS.load(Ordering::Relaxed),
3491 DRAW_GAP_SUM.load(Ordering::Relaxed),
3492 DRAW_GAP_MAX.load(Ordering::Relaxed),
3493 crate::kernel::tls::WRITE_WAIT_TICKS.load(Ordering::Relaxed),
3494 crate::kernel::tls::WRITE_WAIT_CALLS.load(Ordering::Relaxed),
3495 crate::kernel::tls::WRITE_RETX_COUNT.load(Ordering::Relaxed)
3496 );
3497 super::perf::dump("frame");
3499 }
3500 }
3501 if elapsed > 1 {
3502 crate::apps::browser::log_redraw_reasons();
3506 }
3507 self.frame_hits = frame_hits_now;
3508 if !self.child_frames.is_empty() {
3509 let to_children: Vec<(String, crate::os_lib::ecma::value::Value, String)> = core::mem::take(
3510 &mut self.js_runtime.dom().borrow_mut().pending_child_messages,
3511 );
3512 for (target_src, data, origin) in to_children {
3513 for (key, child) in self.child_frames.iter_mut() {
3514 if key.ends_with(&target_src) || key.contains(&target_src) {
3515 let (cw, ch) = (child.win_w, child.win_h);
3516 child.js_runtime.deliver_message(data.clone(), &origin);
3517 child.relayout_if_dom_dirty(0, cw, ch);
3518 }
3519 }
3520 }
3521 let mut from_children: Vec<(crate::os_lib::ecma::value::Value, String)> = Vec::new();
3522 for child in self.child_frames.values_mut() {
3523 let mut msgs = core::mem::take(
3524 &mut child.js_runtime.dom().borrow_mut().pending_parent_messages,
3525 );
3526 from_children.append(&mut msgs);
3527 }
3528 if !from_children.is_empty() {
3529 for (data, origin) in from_children {
3530 self.js_runtime.deliver_message(data, &origin);
3531 }
3532 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
3533 }
3534 }
3535 self.dirty = false;
3536 }
3537
3538 fn hovered_scroll_container(&self, top_offset: i32) -> Option<String> {
3541 let mx = self.mouse_x;
3542 let my = self.mouse_y;
3543 for (cid, max_y, cx, cy, cw, ch, ..) in &self.scroll_containers {
3544 if *max_y <= 0 {
3545 continue;
3546 }
3547 let screen_y = cy - self.scroll_y + top_offset;
3548 if mx >= *cx && mx < cx + cw && my >= screen_y && my < screen_y + ch {
3549 return Some(cid.clone());
3550 }
3551 }
3552 None
3553 }
3554
3555 fn fire_scroll_and_sync(&mut self) {
3561 self.js_runtime.fire_scroll(self.scroll_y);
3562 self.relayout_if_dom_dirty(self.top_offset, self.win_w, self.win_h);
3565 }
3566
3567 pub fn scroll(&mut self, dy: i32) {
3568 let top = self.top_offset;
3569 self.scroll_with_top(dy, top);
3570 }
3571
3572 pub fn scroll_with_top(&mut self, dy: i32, top_offset: i32) {
3573 if let Some(cid) = self.hovered_scroll_container(top_offset) {
3575 let max = self.scroll_containers
3576 .iter()
3577 .find(|(id, ..)| *id == cid)
3578 .map(|(_, m, ..)| *m)
3579 .unwrap_or(0);
3580 let entry = self.scroll_regions.entry(cid).or_insert(0);
3581 let prev = *entry;
3582 *entry = (*entry + dy).max(0).min(max);
3583 if *entry != prev {
3584 self.dirty = true;
3585 self.dirty_reason = "render.rs:2462";
3586 }
3587 return;
3588 }
3589 let prev = self.scroll_y;
3591 self.scroll_y = (self.scroll_y + dy).max(0).min(self.max_scroll_y);
3592 if self.scroll_y != prev {
3593 self.dirty = true;
3594 self.dirty_reason = "render.rs:2470";
3595 self.fire_scroll_and_sync();
3597 }
3598 }
3599
3600 pub fn handle_mouse_click(&mut self, mx: u32, my: u32, top_offset: i32) {
3601 let x = mx as i32;
3602 let y = my as i32;
3603
3604 self.focused_id = None;
3605 self.dirty = true;
3606 self.dirty_reason = "render.rs:2481";
3607
3608 if y < top_offset {
3609 return;
3610 }
3611
3612 for link in &self.links {
3613 if x >= link.x0 && x <= link.x1 && y >= link.y0 && y <= link.y1 {
3614 let href = link.href.clone();
3615 self.navigate_to_href(&href, top_offset);
3616 break;
3617 }
3618 }
3619 }
3620
3621 pub fn navigate_to_href(&mut self, href: &str, top_offset: i32) {
3622 crate::warn!("[NAV] navigate_to_href {:?} depth={}", href.chars().take(100).collect::<String>(), self.frame_depth);
3623 if href.is_empty() {
3624 return;
3625 }
3626
3627 if href.starts_with('#') {
3630 self.navigate_to_fragment(href);
3631 return;
3632 }
3633
3634 let direct_target = super::site_hooks::hooks().resolve_redirect_link(href);
3636 let effective_href = direct_target.as_deref().unwrap_or(href);
3637
3638 match super::url_resolve::resolve_nav_target(
3641 self.current_is_https,
3642 &self.current_host,
3643 &self.current_path,
3644 effective_href,
3645 ) {
3646 super::url_resolve::NavTarget::Ignore => {}
3647 super::url_resolve::NavTarget::About(name) => {
3648 self.load_page(self.current_is_https, &name, "/", true, top_offset);
3649 }
3650 super::url_resolve::NavTarget::Fragment(frag) => {
3651 self.navigate_to_fragment(&frag);
3652 }
3653 super::url_resolve::NavTarget::Page(is_https, host, path) => {
3654 if let Some((no_frag, frag)) = path.split_once('#') {
3656 let same = is_https == self.current_is_https
3657 && host == self.current_host
3658 && no_frag == self.current_path;
3659 if same {
3660 let frag = alloc::format!("#{}", frag);
3661 self.navigate_to_fragment(&frag);
3662 return;
3663 }
3664 }
3665 self.load_page(is_https, &host, &path, true, top_offset);
3666 }
3667 }
3668 }
3669
3670 pub(crate) fn navigate_to_fragment(&mut self, href: &str) {
3674 let frag = href.trim_start_matches('#');
3675 let scheme = if self.current_is_https {
3677 "https://"
3678 } else {
3679 "http://"
3680 };
3681 let base = alloc::format!("{}{}{}", scheme, self.current_host, self.current_path);
3682 let base = match base.split_once('#') {
3683 Some((before, _)) => String::from(before),
3684 None => base,
3685 };
3686 let old_url = self.current_url_with_hash.clone();
3687 let new_url = alloc::format!("{}#{}", base, frag);
3688
3689 if frag.is_empty() {
3691 if self.scroll_y != 0 {
3692 self.scroll_y = 0;
3693 self.dirty = true;
3694 self.dirty_reason = "render.rs:2561";
3695 }
3696 } else if let Some(el) = self.elements.iter().find(|e| e.element_id == frag) {
3697 let target = (el.y_offset - el.scroll_margin_top)
3700 .max(0)
3701 .min(self.max_scroll_y);
3702 if self.scroll_y != target {
3703 if self.scroll_smooth {
3704 self.scroll_anim_active = true;
3707 self.scroll_anim_from = self.scroll_y;
3708 self.scroll_anim_to = target;
3709 self.scroll_anim_start_ms = self.now_ms();
3710 self.dirty = true;
3711 self.dirty_reason = "render.rs:2577";
3712 } else {
3713 self.scroll_y = target;
3714 self.dirty = true;
3715 self.dirty_reason = "render.rs:2580";
3716 self.fire_scroll_and_sync();
3717 }
3718 }
3719 }
3720
3721 if old_url != new_url {
3723 self.current_url_with_hash = new_url.clone();
3724 self.js_runtime.fire_hashchange(&old_url, &new_url);
3725 self.dirty = true;
3726 self.dirty_reason = "render.rs:2590";
3727 }
3728
3729 {
3732 let mut current = crate::os_lib::viewport::CURRENT_TARGET_ID.lock();
3733 if current.as_str() != frag {
3734 *current = String::from(frag);
3735 drop(current);
3736 self.dom_needs_rebuild = true;
3737 }
3738 }
3739 }
3740
3741 fn fire_media_events(&mut self) -> bool {
3747 use core::sync::atomic::{AtomicU64, Ordering};
3748 static LAST: AtomicU64 = AtomicU64::new(0);
3749 let st = crate::os_lib::mse::PLAYBACK.lock().clone();
3750 if st.url.is_empty()
3751 || !(st.playing
3752 || st.ended_pending
3753 || st.waiting_pending
3754 || st.playing_pending
3755 || st.stalled_pending)
3756 {
3757 return false;
3758 }
3759 let idx = {
3760 let dom = self.js_runtime.dom().borrow();
3761 dom.first_by_tag("video").or_else(|| dom.first_by_tag("audio"))
3762 };
3763 let Some(idx) = idx else { return false };
3764 let mut fired = false;
3765 let now = crate::kernel::timer::get_system_time_ms();
3766 static COST: AtomicU64 = AtomicU64::new(0);
3770 let interval = 250u64.max(COST.load(Ordering::Relaxed) * 2);
3771 if st.playing && now.wrapping_sub(LAST.load(Ordering::Relaxed)) >= interval {
3772 self.js_runtime.dispatch_event(idx, "timeupdate");
3773 let end = crate::kernel::timer::get_system_time_ms();
3774 COST.store(end.wrapping_sub(now), Ordering::Relaxed);
3775 LAST.store(end, Ordering::Relaxed);
3776 fired = true;
3777 }
3778 if st.waiting_pending {
3779 crate::os_lib::mse::PLAYBACK.lock().waiting_pending = false;
3780 self.js_runtime.dispatch_event(idx, "waiting");
3781 fired = true;
3782 }
3783 if st.playing_pending {
3784 crate::os_lib::mse::PLAYBACK.lock().playing_pending = false;
3785 self.js_runtime.dispatch_event(idx, "playing");
3786 fired = true;
3787 }
3788 if st.stalled_pending {
3789 crate::os_lib::mse::PLAYBACK.lock().stalled_pending = false;
3790 self.js_runtime.dispatch_event(idx, "stalled");
3791 fired = true;
3792 }
3793 if st.ended_pending {
3794 crate::os_lib::mse::PLAYBACK.lock().ended_pending = false;
3795 self.js_runtime.dom().borrow_mut().set_attr(idx, "_paused", "true");
3796 self.js_runtime.dispatch_event(idx, "timeupdate");
3797 self.js_runtime.dispatch_event(idx, "pause");
3798 self.js_runtime.dispatch_event(idx, "ended");
3799 self.video_playing = false;
3800 self.dirty = true;
3801 self.dirty_reason = "render.rs:media_ended";
3802 fired = true;
3803 }
3804 fired
3805 }
3806
3807
3808 fn process_media_request(&mut self, top_offset: i32) {
3810 if self.fire_media_events() {
3811 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
3813 }
3814 let req = {
3817 let mut lock = crate::os_lib::mse::MEDIA_REQUEST.lock();
3818 let mine = match &*lock {
3819 Some(crate::os_lib::mse::MediaRequest::Play(src)) => {
3820 let dom = self.js_runtime.dom().borrow();
3821 dom.nodes.iter().any(|n| (n.tag == "video" || n.tag == "audio") && n.attrs.get("src") == Some(src))
3822 }
3823 Some(_) => self.video_playing,
3824 None => false,
3825 };
3826 if mine { lock.take() } else { None }
3827 };
3828 match req {
3829 Some(crate::os_lib::mse::MediaRequest::Play(src))
3831 if self.video_playing
3832 && VIDEO_STATE.lock().as_ref().is_some_and(|st| st.paused && st.src_url == src) =>
3833 {
3834 if let Some(st) = VIDEO_STATE.lock().as_mut() {
3835 st.paused = false;
3836 }
3837 crate::warn!("[VIDEO] 再開");
3838 self.dirty = true;
3839 self.dirty_reason = "render.rs:media_resume";
3840 }
3841 Some(crate::os_lib::mse::MediaRequest::Play(src))
3846 if self.video_playing && VIDEO_STATE.lock().as_ref().is_some_and(|st| st.src_url != src) =>
3847 {
3848 crate::warn!("[VIDEO] src の付け替え: 再生し直す src={}", src.chars().take(60).collect::<String>());
3849 stop_video_playback();
3850 self.video_playing = false;
3851 *crate::os_lib::mse::MEDIA_REQUEST.lock() = Some(crate::os_lib::mse::MediaRequest::Play(src));
3853 self.dirty = true;
3854 self.dirty_reason = "render.rs:media_src_switch";
3855 }
3856 Some(crate::os_lib::mse::MediaRequest::Play(src)) if !self.video_playing => {
3857 let geom = self.elements.iter().find(|e| e.is_video).map(|e| (e.x_offset, e.y_offset, e.height));
3858 crate::warn!("[VIDEO] 再生要求 depth={} geom={:?} src={}", self.frame_depth, geom, src.chars().take(60).collect::<String>());
3859 {
3861 let dom = self.js_runtime.dom().borrow();
3862 if let Some(vi) = dom.nodes.iter().position(|n| n.tag == "video" && n.attrs.get("src") == Some(&src)) {
3863 let mut cur = Some(vi);
3864 let mut depth = 0;
3865 while let (Some(i), true) = (cur, depth < 16) {
3866 let n = &dom.nodes[i];
3867 crate::warn!(
3868 "[VIDEO][TREE] {} {}#{} .{} rect={:?} attrs={:?} style={:?}",
3869 depth,
3870 n.tag,
3871 n.id,
3872 n.classes.iter().take(3).cloned().collect::<Vec<_>>().join("."),
3873 dom.get_rect(i),
3874 n.attrs.iter().filter(|(k, _)| !k.starts_with('_') && *k != "class" && *k != "style").map(|(k, v)| alloc::format!("{}={}", k, v.chars().take(20).collect::<String>())).take(10).collect::<Vec<_>>(),
3875 n.style.iter().filter(|(k, _)| !k.starts_with("--")).take(8).collect::<Vec<_>>()
3876 );
3877 cur = n.parent;
3878 depth += 1;
3879 }
3880 }
3881 }
3882 {
3884 let dom = self.js_runtime.dom().borrow();
3885 let muted = dom.nodes.iter().enumerate().any(|(i, n)| {
3886 (n.tag == "video" || n.tag == "audio") && n.attrs.get("src") == Some(&src) && dom.has_attr(i, "muted")
3887 });
3888 crate::os_lib::mse::PLAYBACK.lock().muted = muted;
3889 }
3890 let Some((x, y, h)) = geom else {
3891 crate::warn!("[VIDEO] 再生要求を破棄: 描画中の <video> が無い src={}", src.chars().take(60).collect::<String>());
3893 return;
3894 };
3895 let v_width = (self.win_w as i32 - 80).clamp(400, 800);
3896 let is_loop = {
3897 let dom = self.js_runtime.dom().borrow();
3898 dom.nodes.iter().enumerate().any(|(i, n)| {
3899 (n.tag == "video" || n.tag == "audio") && n.attrs.get("src") == Some(&src) && dom.has_attr(i, "loop")
3900 })
3901 };
3902 *VIDEO_STATE.lock() = Some(VideoPlayState {
3903 src_url: src,
3904 x: x.max(0) as u32,
3905 y: y.max(0) as u32,
3906 width: v_width as u32,
3907 height: h as u32,
3908 playing: true,
3909 stop_request: false,
3910 paused: false,
3911 loop_playback: is_loop,
3912 });
3913 let pid = crate::kernel::scheduler::spawn_away_from_current(
3914 video_playback_thread,
3915 crate::kernel::scheduler::Priority::High,
3916 "video_playback",
3917 );
3918 if pid == 0 {
3919 crate::warn!("[VIDEO] 再生スレッドを起動できません(ヒープ不足)");
3920 stop_video_playback();
3921 return;
3922 }
3923 self.video_playing = true;
3924 self.dirty = true;
3925 self.dirty_reason = "render.rs:media_play";
3926 }
3927 Some(crate::os_lib::mse::MediaRequest::Pause)
3929 if self.video_playing
3930 && VIDEO_STATE.lock().as_ref().is_some_and(|st| st.src_url.starts_with("blob:mediasource-")) =>
3931 {
3932 if let Some(st) = VIDEO_STATE.lock().as_mut() {
3933 st.paused = true;
3934 }
3935 crate::warn!("[VIDEO] 一時停止");
3936 self.dirty = true;
3937 self.dirty_reason = "render.rs:media_pause";
3938 }
3939 Some(crate::os_lib::mse::MediaRequest::Pause) if self.video_playing => {
3940 stop_video_playback();
3941 self.video_playing = false;
3942 self.dirty = true;
3943 self.dirty_reason = "render.rs:media_pause";
3944 }
3945 _ => {}
3946 }
3947 }
3948
3949 fn tick_scroll_anim(&mut self) {
3950 const DURATION_MS: f32 = 300.0;
3951 let now = self.now_ms();
3952 let elapsed = (now - self.scroll_anim_start_ms).max(0.0);
3953 let t = (elapsed / DURATION_MS).min(1.0);
3954 let eased = 1.0 - (1.0 - t) * (1.0 - t);
3955 let from = self.scroll_anim_from as f32;
3956 let to = self.scroll_anim_to as f32;
3957 self.scroll_y = libm::roundf(from + (to - from) * eased) as i32;
3958 self.dirty = true;
3959 self.dirty_reason = "render.rs:2618";
3960 if t >= 1.0 {
3961 self.scroll_y = self.scroll_anim_to;
3962 self.scroll_anim_active = false;
3963 self.fire_scroll_and_sync();
3964 }
3965 }
3966
3967 pub(crate) fn resolve_url_parts(&self, url: &str) -> (bool, String, String) {
3976 match super::url_resolve::resolve_nav_target(
3978 self.current_is_https,
3979 &self.current_host,
3980 &self.current_path,
3981 url,
3982 ) {
3983 super::url_resolve::NavTarget::Page(is_https, host, path) => {
3984 let path = match path.split_once('#') {
3986 Some((before, _)) => String::from(before),
3987 None => path,
3988 };
3989 (is_https, host, path)
3990 }
3991 super::url_resolve::NavTarget::About(name) => (self.current_is_https, name, String::from("/")),
3992 super::url_resolve::NavTarget::Fragment(_) | super::url_resolve::NavTarget::Ignore => (
3993 self.current_is_https,
3994 self.current_host.clone(),
3995 self.current_path.clone(),
3996 ),
3997 }
3998 }
3999
4000 fn url_encode(s: &str) -> String {
4001 let mut out = String::new();
4002 for b in s.bytes() {
4003 match b {
4004 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
4005 out.push(b as char);
4006 }
4007 b' ' => {
4008 out.push('+');
4009 }
4010 _ => {
4011 out.push_str(&alloc::format!("%{:02X}", b));
4012 }
4013 }
4014 }
4015 out
4016 }
4017
4018 fn wrap_editor_lines(text_val: &str, el_width: i32, wrap: bool) -> Vec<(String, bool)> {
4024 if !wrap {
4025 return text_val
4026 .split('\n')
4027 .map(|s| (String::from(s), true))
4028 .collect();
4029 }
4030 let max_w = (el_width - 16).max(50) as u32;
4031 let mut lines = Vec::new();
4032 for phys_line in text_val.split('\n') {
4033 if phys_line.is_empty() {
4034 lines.push((String::new(), true));
4035 continue;
4036 }
4037 let mut current_line = String::new();
4038 let mut cur_w = 0u32;
4039 let mut sub_lines = Vec::new();
4040 for c in phys_line.chars() {
4041 let cw = crate::kernel::vector_font::get_vector_char_width(c, 16);
4042 if cur_w + cw > max_w {
4043 sub_lines.push(current_line);
4044 current_line = String::from(c);
4045 cur_w = cw;
4046 } else {
4047 current_line.push(c);
4048 cur_w += cw;
4049 }
4050 }
4051 if !current_line.is_empty() {
4052 sub_lines.push(current_line);
4053 }
4054 let sub_len = sub_lines.len();
4055 for (idx, line) in sub_lines.into_iter().enumerate() {
4056 let is_phys_end = idx == sub_len - 1;
4057 lines.push((line, is_phys_end));
4058 }
4059 }
4060 lines
4061 }
4062
4063 fn get_cursor_line_idx(&self, text_val: &str, cursor_pos: usize, el_width: i32) -> usize {
4065 let wrap = self.editor_wrap;
4066 if !wrap {
4067 let mut line_idx = 0;
4068 for (idx, c) in text_val.chars().enumerate() {
4069 if idx >= cursor_pos {
4070 break;
4071 }
4072 if c == '\n' {
4073 line_idx += 1;
4074 }
4075 }
4076 return line_idx;
4077 }
4078
4079 let max_w = (el_width - 16).max(50) as u32;
4080 let mut line_idx = 0;
4081 let mut cur_w = 0u32;
4082
4083 for (idx, c) in text_val.chars().enumerate() {
4084 if idx >= cursor_pos {
4085 break;
4086 }
4087 if c == '\n' {
4088 line_idx += 1;
4089 cur_w = 0;
4090 continue;
4091 }
4092 let cw = crate::kernel::vector_font::get_vector_char_width(c, 16);
4093 if cur_w + cw > max_w {
4094 line_idx += 1;
4095 cur_w = cw;
4096 } else {
4097 cur_w += cw;
4098 }
4099 }
4100 line_idx
4101 }
4102
4103
4104 fn build_text_box(
4112 val: &str,
4113 is_textarea: bool,
4114 restore: Option<usize>,
4115 ) -> crate::kernel::text_box::TextBox {
4116 let mut tb = if is_textarea {
4117 crate::kernel::text_box::TextBox::with_text_multiline(val)
4118 } else {
4119 crate::kernel::text_box::TextBox::with_text(val)
4120 };
4121 if let Some(pos) = restore {
4122 tb.cursor_pos = pos.min(tb.text.chars().count());
4123 }
4124 tb
4125 }
4126
4127 fn flush_focused_input(&mut self) {
4130 if let Some(ref fid) = self.focused_id {
4131 if let Some(ref tb) = self.active_text_box {
4132 self.form_values.insert(fid.clone(), tb.text.clone());
4133 }
4134 }
4135 }
4136
4137 pub fn submit_form(&mut self, action: &str, method: &str, top_offset: i32) {
4138 crate::warn!("[NAV] submit_form action={:?} method={} depth={}", action, method, self.frame_depth);
4139 self.flush_focused_input();
4141
4142 let form_idx = {
4144 let dom = self.js_runtime.dom().borrow();
4145 let from_focus = self
4146 .focused_id
4147 .as_ref()
4148 .and_then(|fid| dom.get_element_by_id(fid))
4149 .and_then(|i| dom.closest_tag(i, "form"));
4150 from_focus.or_else(|| dom.first_by_tag("form"))
4151 };
4152
4153 if let Some(fi) = form_idx {
4156 let novalidate = self.js_runtime.dom().borrow().has_attr(fi, "novalidate");
4157 if !novalidate {
4158 let invalid_fields: Vec<(usize, String, String)> = {
4160 let dom = self.js_runtime.dom().borrow();
4161 let fields = dom.descendants_by_tags(fi, &["input", "textarea", "select"]);
4162 let mut out = Vec::new();
4163 for node in fields {
4164 let eid = dom
4166 .get_attr(node, "id")
4167 .filter(|s| !s.is_empty())
4168 .or_else(|| dom.get_attr(node, "name"))
4169 .unwrap_or_default();
4170 let value = if eid.is_empty() {
4171 String::new()
4172 } else {
4173 self.form_values.get(&eid).cloned().unwrap_or_default()
4174 };
4175 if let Some(msg) = dom.validate_field(node, &value) {
4176 out.push((node, eid, msg));
4177 }
4178 }
4179 out
4180 };
4181 if let Some((node, eid, msg)) = invalid_fields.into_iter().next() {
4182 self.js_runtime.dispatch_event(node, "invalid");
4184 if !eid.is_empty() {
4186 self.focused_id = Some(eid.clone());
4187 self.dom_needs_rebuild = true; let cur = self.form_values.get(&eid).cloned().unwrap_or_default();
4189 self.active_text_box =
4190 Some(crate::kernel::text_box::TextBox::with_text(&cur));
4191 self.focus_value = cur;
4192 }
4193 crate::warn!("[GPU] Form validation failed [{}]: {}", eid, msg);
4195 self.dirty = true;
4196 self.dirty_reason = "render.rs:2846";
4197 return;
4198 }
4199 }
4200 }
4201
4202 if let Some(fi) = form_idx {
4205 let (_fired, prevented) = self.js_runtime.dispatch_event_with(fi, "submit", &[]);
4206 if self.js_runtime.dom().borrow().dirty {
4207 self.dom_needs_rebuild = true;
4208 self.dirty = true;
4209 self.dirty_reason = "render.rs:2858";
4210 }
4211 if prevented {
4212 return; }
4214 }
4215
4216 let mut query = String::new();
4217 let mut first = true;
4218 let unchecked: alloc::collections::BTreeSet<String> = self
4220 .elements
4221 .iter()
4222 .filter(|e| (e.input_kind == 1 || e.input_kind == 2) && !e.element_id.is_empty())
4223 .filter(|e| {
4224 self.form_values
4225 .get(&e.element_id)
4226 .map(|v| v.is_empty())
4227 .unwrap_or(true)
4228 })
4229 .map(|e| e.element_id.clone())
4230 .collect();
4231 for (k, v) in &self.form_values {
4232 if v.is_empty() && unchecked.contains(k) {
4234 continue;
4235 }
4236 let param_name = self
4238 .field_names
4239 .get(k)
4240 .cloned()
4241 .unwrap_or_else(|| k.clone());
4242 if param_name.is_empty() {
4243 continue;
4244 }
4245 if !first {
4246 query.push('&');
4247 }
4248 let enc_k = Self::url_encode(¶m_name);
4249 let enc_v = Self::url_encode(v);
4250 query.push_str(&enc_k);
4251 query.push('=');
4252 query.push_str(&enc_v);
4253 first = false;
4254 }
4255
4256 let mut target_action = String::from(action);
4257 if target_action.is_empty() {
4258 target_action = self.current_path.clone();
4259 }
4260
4261 crate::info!(
4262 "SUBMIT_FORM: {} {} ({} fields)",
4263 method,
4264 target_action,
4265 self.form_values.len()
4266 );
4267
4268 if method.eq_ignore_ascii_case("POST") {
4269 let (is_https, host, path) = self.resolve_url_parts(&target_action);
4271 self.load_page_post(is_https, &host, &path, &query, top_offset);
4272 } else {
4273 let separator = if target_action.contains('?') {
4274 "&"
4275 } else {
4276 "?"
4277 };
4278 let full_url = alloc::format!("{}{}{}", target_action, separator, query);
4279 self.navigate_to_href(&full_url, top_offset);
4280 }
4281 }
4282
4283 pub fn reset_form(&mut self, button_id: &str) {
4287 let form_idx = {
4289 let dom = self.js_runtime.dom().borrow();
4290 let from_btn = (!button_id.is_empty())
4291 .then(|| dom.get_element_by_id(button_id))
4292 .flatten()
4293 .and_then(|i| dom.closest_tag(i, "form"));
4294 from_btn.or_else(|| dom.first_by_tag("form"))
4295 };
4296 if let Some(fi) = form_idx {
4297 self.reset_form_node(fi);
4298 }
4299 }
4300
4301 pub fn reset_form_node(&mut self, fi: usize) {
4303 self.active_text_box = None;
4305 self.focus_value = String::new();
4306
4307 let fields: Vec<(usize, String)> = {
4309 let dom = self.js_runtime.dom().borrow();
4310 dom.descendants_by_tags(fi, &["input", "textarea", "select"])
4311 .into_iter()
4312 .map(|node| {
4313 let eid = dom
4314 .get_attr(node, "id")
4315 .filter(|s| !s.is_empty())
4316 .or_else(|| dom.get_attr(node, "name"))
4317 .unwrap_or_default();
4318 (node, eid)
4319 })
4320 .collect()
4321 };
4322
4323 for (node, eid) in &fields {
4325 if eid.is_empty() {
4326 continue;
4327 }
4328 let init = self
4329 .initial_form_values
4330 .get(eid)
4331 .cloned()
4332 .unwrap_or_default();
4333 self.form_values.insert(eid.clone(), init.clone());
4334
4335 let kind = self
4337 .elements
4338 .iter()
4339 .find(|e| &e.element_id == eid)
4340 .map(|e| e.input_kind)
4341 .unwrap_or(0);
4342 let mut dom = self.js_runtime.dom().borrow_mut();
4343 dom.remove_attr(*node, "_live_value");
4344 dom.remove_attr(*node, "_live_checked");
4345 match kind {
4346 1 | 2 => {
4347 if init.is_empty() {
4349 dom.remove_attr(*node, "checked");
4350 } else {
4351 dom.set_attr(*node, "checked", "");
4352 }
4353 }
4354 _ => {
4355 dom.set_attr(*node, "value", &init);
4357 }
4358 }
4359 }
4360
4361 if let Some(fid) = self.focused_id.clone() {
4363 if fields.iter().any(|(_, e)| e == &fid) {
4364 let init = self
4365 .initial_form_values
4366 .get(&fid)
4367 .cloned()
4368 .unwrap_or_default();
4369 let is_ta = self
4370 .elements
4371 .iter()
4372 .find(|e| e.element_id == fid)
4373 .map(|e| e.is_textarea)
4374 .unwrap_or(false);
4375 self.active_text_box = Some(if is_ta {
4376 crate::kernel::text_box::TextBox::with_text_multiline(&init)
4377 } else {
4378 crate::kernel::text_box::TextBox::with_text(&init)
4379 });
4380 self.focus_value = init;
4381 }
4382 }
4383
4384 self.js_runtime.dispatch_event(fi, "reset");
4386 if self.js_runtime.dom().borrow().dirty {
4387 self.dom_needs_rebuild = true;
4388 }
4389 self.dom_needs_rebuild = true;
4390 self.dirty = true;
4391 self.dirty_reason = "render.rs:3039";
4392 }
4393
4394 fn effective_bg_behind(&self, target: &super::RenderElement) -> u32 {
4409 let tx0 = target.x_offset;
4410 let ty0 = target.y_offset;
4411 let tx1 = tx0 + target.width;
4412 let ty1 = ty0 + target.height;
4413
4414 let mut layers: alloc::vec::Vec<super::backdrop::Layer> = alloc::vec::Vec::new();
4417 for el in self.bg_layer_idx.iter().filter_map(|&i| self.elements.get(i as usize)) {
4419 let painted = element_has_painted_bg(el);
4427 let color = el.bg_color;
4428 if color.is_none() && !painted {
4429 continue;
4430 }
4431 let x0 = el.x_offset;
4437 let y0 = el.y_offset;
4438 let x1 = x0 + el.width;
4439 let y1 = y0 + el.height;
4440 if x0 <= tx0 && y0 <= ty0 && x1 >= tx1 && y1 >= ty1 {
4441 let area = (x1 - x0) as i64 * (y1 - y0) as i64;
4442 layers.push(super::backdrop::Layer { area, color, painted });
4443 }
4444 }
4445 match super::backdrop::resolve_backdrop(&layers, self.page_bg_color.unwrap_or(0xFFFFFFFF)) {
4446 super::backdrop::Backdrop::Solid(c) => c,
4447 super::backdrop::Backdrop::Framebuffer => crate::kernel::vector_font::BG_FROM_FRAMEBUFFER,
4448 }
4449 }
4450
4451 fn hit_test_element_id(&self, local_x: i32, local_y: i32, top_offset: i32) -> Option<String> {
4454 let hx = local_x;
4455 let hy = local_y - top_offset + self.scroll_y;
4456 let mut found: Option<String> = None;
4457 for el in self.elements.iter() {
4458 let element_id = if !el.element_id.is_empty() {
4461 el.element_id.clone()
4462 } else if let Some(n) = el.node_idx {
4463 format!("_node_idx_{}", n)
4464 } else {
4465 continue;
4466 };
4467 let hit_y = hy >= el.y_offset && hy < el.y_offset + el.height;
4468 let hit_x = if el.x_offset > 0 || el.width < 1000 {
4469 hx >= el.x_offset && hx < el.x_offset + el.width
4470 } else {
4471 hx >= 0
4472 };
4473 if hit_y && hit_x {
4474 found = Some(element_id); }
4476 }
4477 found
4478 }
4479
4480 pub fn on_mouse(
4481 &mut self,
4482 local_x: i32,
4483 local_y: i32,
4484 btn_left: bool,
4485 btn_right: bool,
4486 wheel: i32,
4487 top_offset: i32,
4488 ) {
4489 crate::debug!(
4490 "[GPU] TRACE: on_mouse x={}, y={}, btn={}, wheel={}",
4491 local_x,
4492 local_y,
4493 btn_left,
4494 wheel
4495 );
4496 let active_drag_frame = self.child_frames.iter().find_map(|(k, c)| {
4499 if c.dragging_scrollbar || c.dragging_sub_scrollbar.is_some() {
4500 self.frame_hits.iter().find(|(fk, ..)| fk == k).map(|(_, fx, fy, ..)| (k.clone(), *fx, *fy))
4501 } else {
4502 None
4503 }
4504 });
4505
4506 let hit = active_drag_frame.or_else(|| {
4507 self.frame_hits
4508 .iter()
4509 .find(|(_, x, y, w, h)| local_x >= *x && local_x < x + w && local_y >= *y && local_y < y + h)
4510 .map(|(k, x, y, _, _)| (k.clone(), *x, *y))
4511 });
4512 if let Some((key, fx, fy)) = hit {
4513 if btn_left && !self.prev_btn_left {
4514 self.focused_frame = Some(key.clone());
4515 }
4516 if let Some(child) = self.child_frames.get_mut(&key) {
4517 let prev_child_scroll = child.scroll_y;
4518 let prev_child_sub_scrolls = child.scroll_regions.clone();
4519 let child_has_wheel = child.js_runtime.dom().borrow().has_listener("wheel");
4520 child.on_mouse(local_x - fx, local_y - fy, btn_left, btn_right, wheel, 0);
4521 self.mouse_x = local_x;
4522 self.mouse_y = local_y;
4523 self.prev_btn_left = btn_left;
4524 self.prev_btn_right = btn_right;
4525 if child.dirty {
4526 self.dirty = true;
4527 self.dirty_reason = "child_frame_input";
4528 }
4529 let child_scrolled = child.scroll_y != prev_child_scroll
4530 || child.scroll_regions != prev_child_sub_scrolls
4531 || child_has_wheel;
4532 if wheel != 0 && !child_scrolled {
4533 self.scroll_with_top(wheel * 24, top_offset);
4534 }
4535 return;
4536 }
4537 }
4538 if btn_left && !self.prev_btn_left {
4539 self.focused_frame = None;
4540 }
4541 self.mouse_x = local_x;
4542 self.mouse_y = local_y;
4543 self.mouse_btn_left_down = btn_left;
4545 if btn_left != self.prev_btn_left {
4549 self.relayout_now_if_dom_dirty(top_offset, self.win_w, self.win_h);
4550 }
4551
4552 let pressed_edge = btn_left && !self.prev_btn_left;
4554 let released_edge = !btn_left && self.prev_btn_left;
4555 self.prev_btn_left = btn_left;
4556
4557 if pressed_edge && self.js_runtime.dom().borrow().has_listener("mousedown") {
4559 if let Some(id) = self.hit_test_element_id(local_x, local_y, top_offset) {
4560 let node = self.js_runtime.dom().borrow().get_element_by_id(&id);
4561 if let Some(i) = node {
4562 self.js_runtime
4563 .dispatch_mouse(i, "mousedown", local_x, local_y);
4564 }
4565 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
4566 }
4567 }
4568 if released_edge && self.js_runtime.dom().borrow().has_listener("mouseup") {
4570 if let Some(id) = self.hit_test_element_id(local_x, local_y, top_offset) {
4571 let node = self.js_runtime.dom().borrow().get_element_by_id(&id);
4572 if let Some(i) = node {
4573 self.js_runtime
4574 .dispatch_mouse(i, "mouseup", local_x, local_y);
4575 }
4576 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
4577 }
4578 }
4579 let right_pressed_edge = btn_right && !self.prev_btn_right;
4581 self.prev_btn_right = btn_right;
4582 if right_pressed_edge && self.js_runtime.dom().borrow().has_listener("contextmenu") {
4583 if let Some(id) = self.hit_test_element_id(local_x, local_y, top_offset) {
4584 let node = self.js_runtime.dom().borrow().get_element_by_id(&id);
4585 if let Some(i) = node {
4586 self.js_runtime
4587 .dispatch_mouse_full(i, "contextmenu", local_x, local_y, 2, 0);
4588 }
4589 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
4590 }
4591 }
4592 if pressed_edge {
4594 let now = crate::kernel::timer::get_ticks();
4595 let hit = self.hit_test_element_id(local_x, local_y, top_offset);
4596 if let Some(ref id) = hit {
4597 let is_double = self.last_click_id.as_ref() == Some(id)
4598 && now.saturating_sub(self.last_click_tick) <= DBLCLICK_MAX_TICKS;
4599 if is_double {
4600 let has = self.js_runtime.dom().borrow().has_listener("dblclick");
4601 if has {
4602 let node = self.js_runtime.dom().borrow().get_element_by_id(id);
4603 if let Some(i) = node {
4604 self.js_runtime
4605 .dispatch_mouse(i, "dblclick", local_x, local_y);
4606 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
4607 }
4608 }
4609 self.last_click_id = None;
4611 self.last_click_tick = 0;
4612 } else {
4613 self.last_click_id = hit.clone();
4614 self.last_click_tick = now;
4615 }
4616 } else {
4617 self.last_click_id = None;
4618 }
4619 }
4620
4621 let want_mouse_events = {
4624 let d = self.js_runtime.dom().borrow();
4625 d.has_listener("mouseover")
4626 || d.has_listener("mouseout")
4627 || d.has_listener("mousemove")
4628 || d.has_listener("mouseenter")
4629 || d.has_listener("mouseleave")
4630 };
4631 if want_mouse_events {
4632 let hx = local_x;
4633 let hy = local_y - top_offset + self.scroll_y;
4634 let mut new_hover: Option<String> = None;
4635 for el in &self.elements {
4636 if el.element_id.is_empty() {
4637 continue;
4638 }
4639 let hit_y = hy >= el.y_offset && hy < el.y_offset + el.height;
4640 let hit_x = if el.x_offset > 0 || el.width < 1000 {
4641 hx >= el.x_offset && hx < el.x_offset + el.width
4642 } else {
4643 hx >= 0
4644 };
4645 if hit_y && hit_x {
4646 new_hover = Some(el.element_id.clone()); }
4648 }
4649 if new_hover != self.hovered_id {
4650 if let Some(old) = self.hovered_id.clone() {
4651 let oi = self.js_runtime.dom().borrow().get_element_by_id(&old);
4652 if let Some(i) = oi {
4653 self.js_runtime
4654 .dispatch_mouse(i, "mouseout", local_x, local_y);
4655 }
4656 }
4657 if let Some(nh) = new_hover.clone() {
4658 let ni = self.js_runtime.dom().borrow().get_element_by_id(&nh);
4659 if let Some(i) = ni {
4660 self.js_runtime
4661 .dispatch_mouse(i, "mouseover", local_x, local_y);
4662 }
4663 }
4664 self.hovered_id = new_hover.clone();
4665 }
4666 if let Some(nh) = new_hover {
4667 let ni = self.js_runtime.dom().borrow().get_element_by_id(&nh);
4668 if let Some(i) = ni {
4669 self.js_runtime
4670 .dispatch_mouse(i, "mousemove", local_x, local_y);
4671 }
4672 }
4673 if self.js_runtime.dom().borrow().dirty {
4674 self.dom_needs_rebuild = true;
4675 self.dirty = true;
4676 self.dirty_reason = "render.rs:3264";
4677 }
4678 }
4679
4680 if wheel != 0 {
4681 let mut osm_wheel_handled = false;
4683 for el in &self.elements {
4684 if el.is_iframe && !el.iframe_src.is_empty() {
4685 if let Some(embed) = crate::os_lib::web_engine::embed_map::parse_embed_url(&el.iframe_src) {
4686 let el_y = if el.is_fixed { local_y - top_offset } else { local_y - top_offset + self.scroll_y };
4687 let el_x = local_x;
4688 if el_x >= el.x_offset && el_x < el.x_offset + el.width && el_y >= el.y_offset && el_y < el.y_offset + el.height {
4689 let base_z = crate::os_lib::web_engine::embed_map::fit_zoom(&embed, el.width, el.height);
4690 let state = self.osm_states.entry(el.iframe_src.clone()).or_default();
4691 if wheel < 0 {
4692 state.zoom_in(base_z);
4693 } else {
4694 state.zoom_out(base_z);
4695 }
4696 self.dirty = true;
4697 self.dirty_reason = "render.rs:osm_wheel";
4698 osm_wheel_handled = true;
4699 break;
4700 }
4701 }
4702 }
4703 }
4704 if osm_wheel_handled {
4705 return;
4706 }
4707
4708 let mut wheel_prevented = false;
4711 if self.js_runtime.dom().borrow().has_listener("wheel") {
4712 if let Some(id) = self.hit_test_element_id(local_x, local_y, top_offset) {
4713 let idx = self.js_runtime.dom().borrow().get_element_by_id(&id);
4714 if let Some(i) = idx {
4715 let (_f, prevented) = self
4716 .js_runtime
4717 .dispatch_mouse_full(i, "wheel", local_x, local_y, 0, wheel);
4718 wheel_prevented = prevented;
4719 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
4720 }
4721 }
4722 }
4723 if wheel_prevented {
4724 return;
4725 }
4726 let mut focus_on_textarea = false;
4727 let mut text_lines_len = 0;
4728 let mut text_area_h = 200;
4729 if let Some(ref focused_id) = self.focused_id {
4730 if let Some(el) = self.elements.iter().find(|e| &e.element_id == focused_id) {
4731 if el.is_textarea {
4732 focus_on_textarea = true;
4733 text_area_h = el.height;
4734 if let Some(val) = self.form_values.get(&el.element_id) {
4735 text_lines_len =
4736 Self::wrap_editor_lines(val, el.width, self.editor_wrap).len();
4737 }
4738 }
4739 }
4740 }
4741
4742 if focus_on_textarea {
4743 let max_scroll_y = (text_lines_len as i32 - (text_area_h / 20) + 1).max(0);
4744 self.editor_scroll_y = (self.editor_scroll_y + wheel).max(0).min(max_scroll_y);
4745 self.dirty = true;
4746 self.dirty_reason = "render.rs:3306";
4747 } else {
4748 self.scroll_with_top(wheel * 24, top_offset);
4749 }
4750 }
4751 if !btn_left {
4752 self.dragging_scrollbar = false;
4754 self.dragging_sub_scrollbar = None;
4755 self.dragging_osm = None;
4756 if self.is_selecting_text {
4757 self.is_selecting_text = false;
4758 if self.selection.as_ref().map(|s| s.is_empty()).unwrap_or(false) {
4759 self.selection = None;
4760 self.dirty = true;
4761 self.dirty_reason = "selection_empty_drop";
4762 }
4763 }
4764 }
4765
4766 if btn_left {
4767 if self.is_selecting_text {
4769 if let Some(anchor) = self.selecting_anchor {
4770 let click_y = local_y - top_offset + self.scroll_y;
4771 let click_x = local_x;
4772 let mut best_target: Option<(usize, usize)> = None;
4773 let mut min_dist_y = i32::MAX;
4774 for (idx, el) in self.elements.iter().enumerate() {
4775 if el.text.is_empty() || el.is_button || el.is_input || el.is_textarea {
4776 continue;
4777 }
4778 let el_y = if el.is_fixed { local_y - top_offset } else { click_y };
4779 let el_x = click_x;
4780 let dist_y = if el_y < el.y_offset {
4781 el.y_offset - el_y
4782 } else if el_y >= el.y_offset + el.height {
4783 el_y - (el.y_offset + el.height)
4784 } else {
4785 0
4786 };
4787 if dist_y < min_dist_y {
4788 min_dist_y = dist_y;
4789 let char_off = super::selection::hit_test_text_char(&el.text, el.width, el_x - el.x_offset);
4790 best_target = Some((idx, char_off));
4791 if dist_y == 0 && el_x >= el.x_offset && el_x <= el.x_offset + el.width {
4792 break;
4793 }
4794 }
4795 }
4796 if let Some((t_idx, t_char)) = best_target {
4797 let focus = super::selection::TextPosition::new(t_idx, t_char);
4798 let new_range = super::selection::SelectionRange::new(anchor, focus);
4799 if self.selection != Some(new_range) {
4800 self.selection = Some(new_range);
4801 self.dirty = true;
4802 self.dirty_reason = "text_selection_drag";
4803 }
4804 }
4805 return;
4806 }
4807 }
4808
4809 if let Some((src, last_x, last_y)) = self.dragging_osm.clone() {
4811 let dx = local_x - last_x;
4812 let dy = local_y - last_y;
4813 if dx != 0 || dy != 0 {
4814 let state = self.osm_states.entry(src.clone()).or_default();
4815 state.pan(dx, dy);
4816 self.dragging_osm = Some((src, local_x, local_y));
4817 self.dirty = true;
4818 self.dirty_reason = "render.rs:osm_drag";
4819 }
4820 return;
4821 }
4822 if self.dragging_sub_scrollbar.is_none() && !self.dragging_scrollbar {
4824 for (cid, max_y, cx, cy, cw, ch, sc_width, ..) in &self.scroll_containers {
4825 if *max_y <= 0 || sc_width.is_none() {
4826 continue;
4827 }
4828 let hit_w = sc_width.track_width_px().max(8);
4829 let bar_x = cx + cw - (hit_w + 2);
4830 let bar_y = cy - self.scroll_y + top_offset;
4831 if local_x >= bar_x && local_x <= cx + cw
4832 && local_y >= bar_y && local_y < bar_y + ch
4833 {
4834 self.dragging_sub_scrollbar = Some(cid.clone());
4835 break;
4836 }
4837 }
4838 }
4839 if let Some(cid) = self.dragging_sub_scrollbar.clone() {
4841 let meta = self.scroll_containers.iter()
4842 .find(|(id, ..)| *id == cid)
4843 .cloned();
4844 if let Some((_cid, max_y, _cx, cy, _cw, ch, ..)) = meta {
4845 let content_h = max_y + ch;
4846 let thumb_h = ((ch * ch) / content_h).max(20);
4847 let bar_y = cy - self.scroll_y + top_offset;
4848 let ratio = (local_y - bar_y - thumb_h / 2) as f32
4849 / (ch - thumb_h) as f32;
4850 let entry = self.scroll_regions.entry(cid).or_insert(0);
4851 *entry = (ratio.clamp(0.0, 1.0) * max_y as f32) as i32;
4852 self.dirty = true;
4853 self.dirty_reason = "render.rs:3347";
4854 }
4855 return;
4856 }
4857
4858 if !self.dragging_scrollbar && self.max_scroll_y > 0 && !self.scrollbar_width.is_none() && local_y >= top_offset {
4859 let hit_w = self.scrollbar_width.track_width_px().max(8);
4861 if local_x >= (self.win_w as i32 - hit_w - 2) && local_x <= self.win_w as i32 {
4862 self.dragging_scrollbar = true;
4863 }
4864 }
4865
4866 if self.dragging_scrollbar {
4867 let bar_track_h = self.win_h as i32 - top_offset;
4868 let content_h = self.max_scroll_y + bar_track_h;
4869 let thumb_h = ((bar_track_h * bar_track_h) / content_h).max(30);
4870
4871 let scroll_ratio =
4872 (local_y - top_offset - (thumb_h / 2)) as f32 / (bar_track_h - thumb_h) as f32;
4873 let prev = self.scroll_y;
4874 self.scroll_y = (scroll_ratio.clamp(0.0, 1.0) * self.max_scroll_y as f32) as i32;
4875 if self.scroll_y != prev {
4876 self.dirty = true;
4877 self.dirty_reason = "render.rs:3369";
4878 }
4879 return;
4880 }
4881
4882 if pressed_edge {
4884 for el in &self.elements {
4885 if el.is_iframe && !el.iframe_src.is_empty() {
4886 if let Some(embed) = crate::os_lib::web_engine::embed_map::parse_embed_url(&el.iframe_src) {
4887 let el_y = if el.is_fixed { local_y - top_offset } else { local_y - top_offset + self.scroll_y };
4888 let el_x = local_x;
4889 if el_x >= el.x_offset && el_x < el.x_offset + el.width && el_y >= el.y_offset && el_y < el.y_offset + el.height {
4890 let rel_x = el_x - el.x_offset;
4891 let rel_y = el_y - el.y_offset;
4892 if let Some(action) = crate::os_lib::web_engine::embed_map::hit_test_controls(rel_x, rel_y) {
4893 let base_z = crate::os_lib::web_engine::embed_map::fit_zoom(&embed, el.width, el.height);
4894 let state = self.osm_states.entry(el.iframe_src.clone()).or_default();
4895 match action {
4896 crate::os_lib::web_engine::embed_map::MapControlAction::ZoomIn => {
4897 state.zoom_in(base_z);
4898 }
4899 crate::os_lib::web_engine::embed_map::MapControlAction::ZoomOut => {
4900 state.zoom_out(base_z);
4901 }
4902 }
4903 self.dirty = true;
4904 self.dirty_reason = "render.rs:osm_zoom_btn";
4905 return;
4906 } else {
4907 self.dragging_osm = Some((el.iframe_src.clone(), local_x, local_y));
4909 return;
4910 }
4911 }
4912 }
4913 }
4914 }
4915 }
4916
4917 let click_y = local_y - top_offset + self.scroll_y;
4918 let click_x = local_x;
4921
4922 let mut clicked_href = None;
4923 let mut new_focus = None;
4924 let mut script_to_run = None;
4925 let mut form_to_submit = None;
4926 let mut focused_input = false; let mut clicked_ids: Vec<String> = Vec::new();
4929 let mut toggle_action: Option<(String, u8, String, String, Vec<(String, String)>)> =
4931 None;
4932 let mut reset_target_id: Option<String> = None;
4933 let mut range_action: Option<(String, String)> = None;
4936
4937 for el in &self.elements {
4938 if el.visibility_hidden || el.pointer_events_none {
4941 continue;
4942 }
4943 let el_click_y = if el.is_fixed { click_y - self.scroll_y } else { click_y };
4946 let hit_y = el_click_y >= el.y_offset && el_click_y < el.y_offset + el.height;
4947 let hit_x = if el.x_offset > 0 || el.width < 1000 {
4949 click_x >= el.x_offset && click_x < el.x_offset + el.width
4950 } else {
4951 click_x >= 0
4952 };
4953
4954 if hit_y && hit_x {
4955 if !el.element_id.is_empty() {
4956 clicked_ids.push(el.element_id.clone());
4957 }
4958 if !el.label_for.is_empty() {
4960 let target_id = el.label_for.clone();
4961 if let Some(t) = self.elements.iter().find(|e| e.element_id == target_id) {
4962 if t.input_kind == 1 || t.input_kind == 2 || t.input_kind == 3 {
4963 toggle_action = Some((
4964 t.element_id.clone(),
4965 t.input_kind,
4966 t.radio_group.clone(),
4967 t.input_value.clone(),
4968 t.select_options.clone(),
4969 ));
4970 } else if t.is_input || t.is_textarea {
4971 new_focus = Some(t.element_id.clone());
4972 focused_input = true;
4973 }
4974 break;
4975 }
4976 }
4977 if el.input_kind == 1 || el.input_kind == 2 || el.input_kind == 3 {
4978 toggle_action = Some((
4980 el.element_id.clone(),
4981 el.input_kind,
4982 el.radio_group.clone(),
4983 el.input_value.clone(),
4984 el.select_options.clone(),
4985 ));
4986 break;
4987 } else if el.input_kind == 5 && !el.element_id.is_empty() {
4988 let get = |k: &str, d: f32| -> f32 {
4991 el.select_options
4992 .iter()
4993 .find(|(n, _)| n == k)
4994 .and_then(|(_, v)| v.parse::<f32>().ok())
4995 .unwrap_or(d)
4996 };
4997 let min = get("min", 0.0);
4998 let max = get("max", 100.0);
4999 let step = get("step", 1.0).max(0.0001);
5000 let ratio = ((click_x - el.x_offset) as f32 / (el.width.max(1) as f32))
5001 .clamp(0.0, 1.0);
5002 let raw = min + (max - min) * ratio;
5003 let stepped = (libm::roundf((raw - min) / step) * step + min).clamp(min, max);
5004 range_action = Some((el.element_id.clone(), alloc::format!("{}", stepped)));
5005 break;
5006 } else if el.is_input || el.is_textarea {
5007 new_focus = Some(el.element_id.clone());
5008 focused_input = true;
5009 break; } else if el.is_video && el.video_has_controls {
5011 let rel_y = el_click_y - el.y_offset;
5015 let v_width = (self.win_w as i32 - 80).clamp(400, 800);
5016 let region = super::media_controls::hit_test_media_controls(
5017 local_x,
5018 rel_y,
5019 v_width,
5020 el.height,
5021 self.video_controls.duration,
5022 );
5023 match region {
5024 super::media_controls::MediaClickRegion::SeekBar(target_time) => {
5025 self.video_controls.current_time = target_time;
5026 *crate::os_lib::mse::SEEK_REQUEST.lock() = Some(target_time);
5027 crate::os_lib::mse::PLAYBACK.lock().current_time = target_time;
5028 self.dirty = true;
5029 self.dirty_reason = "render.rs:video_seek";
5030 return;
5031 }
5032 super::media_controls::MediaClickRegion::MuteToggle => {
5033 let muted = self.video_controls.toggle_mute();
5034 self.video_controls.set_hud(if muted { "🔇 消音" } else { "🔊 音量 ON" }, 45);
5035 crate::os_lib::mse::PLAYBACK.lock().muted = muted;
5036 crate::kernel::audio::AudioStream::set_paused(muted);
5037 self.dirty = true;
5038 self.dirty_reason = "render.rs:video_mute";
5039 return;
5040 }
5041 super::media_controls::MediaClickRegion::FullscreenToggle => {
5042 let fs = self.video_controls.toggle_fullscreen();
5043 self.video_controls.set_hud(if fs { "⛶ 全画面" } else { "⛶ 通常表示" }, 45);
5044 if let Some(ref mut state) = *VIDEO_STATE.lock() {
5045 if fs {
5046 state.x = 0;
5047 state.y = self.top_offset.max(0) as u32;
5048 state.width = self.win_w;
5049 state.height = self.win_h.saturating_sub(self.top_offset.max(0) as u32);
5050 } else {
5051 let v_width = (self.win_w as i32 - 80).clamp(400, 800);
5052 state.x = el.x_offset.max(0) as u32;
5053 state.y = el.y_offset.max(0) as u32;
5054 state.width = v_width as u32;
5055 state.height = el.height as u32;
5056 }
5057 }
5058 self.dirty = true;
5059 self.dirty_reason = "render.rs:video_fullscreen_click";
5060 return;
5061 }
5062 super::media_controls::MediaClickRegion::QualityToggle => {
5063 let (name, idx, total) = self.video_controls.cycle_quality();
5064 let hud = alloc::format!("🎦 画質: {} [{}/{}]", name, idx, total);
5065 self.video_controls.set_hud(&hud, 45);
5066 self.dirty = true;
5067 self.dirty_reason = "render.rs:video_quality_click";
5068 return;
5069 }
5070 super::media_controls::MediaClickRegion::SubtitleToggle => {
5071 let hud = if let Some((label, idx, total)) = self.video_controls.cycle_subtitles() {
5072 alloc::format!("CC 字幕: {} [{}/{}]", label, idx, total)
5073 } else {
5074 alloc::string::String::from("CC 字幕: オフ")
5075 };
5076 self.video_controls.set_hud(&hud, 45);
5077 self.dirty = true;
5078 self.dirty_reason = "render.rs:video_subtitles_click";
5079 return;
5080 }
5081 super::media_controls::MediaClickRegion::Screen => {
5082 let now = crate::kernel::timer::get_ticks();
5083 let is_double = now.saturating_sub(self.last_video_click_tick) <= DBLCLICK_MAX_TICKS;
5084 self.last_video_click_tick = if is_double { 0 } else { now };
5085 if is_double {
5086 let fs = self.video_controls.toggle_fullscreen();
5088 self.video_controls.set_hud(if fs { "⛶ 全画面" } else { "⛶ 通常表示" }, 45);
5089 if let Some(ref mut state) = *VIDEO_STATE.lock() {
5090 if fs {
5091 state.x = 0;
5092 state.y = self.top_offset.max(0) as u32;
5093 state.width = self.win_w;
5094 state.height = self.win_h.saturating_sub(self.top_offset.max(0) as u32);
5095 } else {
5096 let v_width = (self.win_w as i32 - 80).clamp(400, 800);
5097 state.x = el.x_offset.max(0) as u32;
5098 state.y = el.y_offset.max(0) as u32;
5099 state.width = v_width as u32;
5100 state.height = el.height as u32;
5101 }
5102 }
5103 self.dirty = true;
5104 self.dirty_reason = "render.rs:video_dblclick_fullscreen";
5105 return;
5106 }
5107
5108 self.video_playing = !self.video_playing;
5110 self.video_controls.set_hud(if self.video_playing { "▶ 再生" } else { "⏸ 一時停止" }, 45);
5111 if self.video_playing {
5112 let v_width = (self.win_w as i32 - 80).clamp(400, 800);
5113 let mut state = VIDEO_STATE.lock();
5114 let v_loop = el.video_loop;
5115 *state = Some(VideoPlayState {
5116 src_url: el.video_src.clone(),
5117 x: el.x_offset.max(0) as u32,
5118 y: el.y_offset.max(0) as u32,
5119 width: v_width as u32,
5120 height: el.height as u32,
5121 playing: true,
5122 stop_request: false,
5123 paused: false,
5124 loop_playback: v_loop,
5125 });
5126 let pid = crate::kernel::scheduler::spawn_away_from_current(
5127 video_playback_thread,
5128 crate::kernel::scheduler::Priority::High,
5129 "video_playback",
5130 );
5131 if pid == 0 {
5132 crate::warn!("[VIDEO] 再生スレッドを起動できません(ヒープ不足)");
5133 stop_video_playback();
5134 }
5135 } else {
5136 stop_video_playback();
5137 }
5138 self.dirty = true;
5139 self.dirty_reason = "render.rs:video_screen_click";
5140 return;
5141 }
5142 super::media_controls::MediaClickRegion::PlayPause => {
5143 self.video_playing = !self.video_playing;
5144 self.video_controls.set_hud(if self.video_playing { "▶ 再生" } else { "⏸ 一時停止" }, 45);
5145 if self.video_playing {
5146 let v_width = (self.win_w as i32 - 80).clamp(400, 800);
5147 let mut state = VIDEO_STATE.lock();
5148 let v_loop = el.video_loop;
5149 *state = Some(VideoPlayState {
5150 src_url: el.video_src.clone(),
5151 x: el.x_offset.max(0) as u32,
5152 y: el.y_offset.max(0) as u32,
5153 width: v_width as u32,
5154 height: el.height as u32,
5155 playing: true,
5156 stop_request: false,
5157 paused: false,
5158 loop_playback: v_loop,
5159 });
5160 let pid = crate::kernel::scheduler::spawn_away_from_current(
5161 video_playback_thread,
5162 crate::kernel::scheduler::Priority::High,
5163 "video_playback",
5164 );
5165 if pid == 0 {
5166 crate::warn!("[VIDEO] 再生スレッドを起動できません(ヒープ不足)");
5167 stop_video_playback();
5168 }
5169 } else {
5170 stop_video_playback();
5171 }
5172 self.dirty = true;
5173 self.dirty_reason = "render.rs:video_playpause_click";
5174 return;
5175 }
5176 super::media_controls::MediaClickRegion::None => {}
5177 }
5178 } else if el.is_button && !focused_input {
5179 script_to_run = Some(el.onclick.clone());
5180 if el.is_reset {
5181 reset_target_id = Some(el.element_id.clone());
5183 break;
5184 }
5185 if !el.form_action.is_empty() {
5187 let method = if el.form_method.is_empty() {
5188 String::from("GET")
5189 } else {
5190 el.form_method.clone()
5191 };
5192 form_to_submit = Some((el.form_action.clone(), method));
5193 } else if !el.form_method.is_empty() {
5194 form_to_submit = Some((self.current_path.clone(), el.form_method.clone()));
5199 }
5200 break;
5201 }
5202 }
5203 }
5204
5205 let mut details_toggle_id = None;
5207 for id in &clicked_ids {
5208 let node = self.js_runtime.dom().borrow().get_element_by_id(id);
5209 if let Some(idx) = node {
5210 let dom = self.js_runtime.dom().borrow();
5211 let n = &dom.nodes[idx];
5212 if n.tag == "summary" {
5213 if let Some(parent_idx) = n.parent {
5214 let parent = &dom.nodes[parent_idx];
5215 if parent.tag == "details" {
5216 let p_id = if parent.id.is_empty() {
5217 alloc::format!("_node_idx_{}", parent_idx)
5218 } else {
5219 parent.id.clone()
5220 };
5221 details_toggle_id = Some(p_id);
5222 break;
5223 }
5224 }
5225 }
5226 }
5227 }
5228
5229 if let Some(pid) = details_toggle_id {
5230 let node = self.js_runtime.dom().borrow().get_element_by_id(&pid);
5231 if let Some(i) = node {
5232 let mut closed_group_siblings = alloc::vec::Vec::new();
5233 {
5234 let mut dom = self.js_runtime.dom().borrow_mut();
5235 if dom.has_attr(i, "open") {
5236 dom.remove_attr(i, "open");
5237 } else {
5238 dom.set_attr(i, "open", "");
5239 closed_group_siblings = dom.close_details_group_siblings(i);
5243 }
5244 }
5245 for &sibling in &closed_group_siblings {
5246 self.js_runtime.dispatch_event_with(
5247 sibling,
5248 "toggle",
5249 &[
5250 (alloc::string::String::from("oldState"), crate::os_lib::ecma::value::Value::str("open")),
5251 (alloc::string::String::from("newState"), crate::os_lib::ecma::value::Value::str("closed")),
5252 ],
5253 );
5254 }
5255 self.dirty = true;
5256 self.dirty_reason = "render.rs:3561";
5257 let new_state = if self.js_runtime.dom().borrow().has_attr(i, "open") {
5267 "open"
5268 } else {
5269 "closed"
5270 };
5271 let old_state = if new_state == "open" { "closed" } else { "open" };
5272 self.js_runtime.dispatch_event_with(
5273 i,
5274 "toggle",
5275 &[
5276 (alloc::string::String::from("oldState"), crate::os_lib::ecma::value::Value::str(old_state)),
5277 (alloc::string::String::from("newState"), crate::os_lib::ecma::value::Value::str(new_state)),
5278 ],
5279 );
5280 }
5281 if self.js_runtime.dom().borrow().dirty {
5282 self.dom_needs_rebuild = true;
5283 }
5284 return;
5285 }
5286
5287 let mut popover_toggle: Option<(usize, &'static str)> = None;
5294 for id in &clicked_ids {
5295 let node = self.js_runtime.dom().borrow().get_element_by_id(id);
5296 if let Some(idx) = node {
5297 let dom = self.js_runtime.dom().borrow();
5298 if let Some(target_id) = dom.get_attr(idx, "popovertarget") {
5299 if let Some(target_idx) = dom.get_element_by_id(&target_id) {
5300 let action = match dom.get_attr(idx, "popovertargetaction").as_deref() {
5301 Some("show") => "show",
5302 Some("hide") => "hide",
5303 _ => "toggle",
5304 };
5305 popover_toggle = Some((target_idx, action));
5306 break;
5307 }
5308 }
5309 }
5310 }
5311 if let Some((idx, action)) = popover_toggle {
5312 {
5313 let mut dom = self.js_runtime.dom().borrow_mut();
5314 let is_open = dom.has_attr(idx, "_popover_open");
5315 let open = match action {
5316 "show" => true,
5317 "hide" => false,
5318 _ => !is_open,
5319 };
5320 if open {
5321 dom.set_attr(idx, "_popover_open", "");
5322 } else {
5323 dom.remove_attr(idx, "_popover_open");
5324 }
5325 }
5326 self.dirty = true;
5327 self.dirty_reason = "render.rs:3631";
5328 if self.js_runtime.dom().borrow().dirty {
5329 self.dom_needs_rebuild = true;
5330 }
5331 return;
5332 }
5333
5334 if let Some((tid, kind, group, value, options)) = toggle_action {
5336 if !tid.is_empty() {
5337 if kind == 1 {
5338 let cur = self.form_values.get(&tid).cloned().unwrap_or_default();
5340 let next = if cur.is_empty() { value } else { String::new() };
5341 self.form_values.insert(tid.clone(), next);
5342 } else if kind == 2 {
5343 if !group.is_empty() {
5345 let group_ids: Vec<String> = self
5346 .elements
5347 .iter()
5348 .filter(|e| {
5349 e.input_kind == 2
5350 && e.radio_group == group
5351 && !e.element_id.is_empty()
5352 })
5353 .map(|e| e.element_id.clone())
5354 .collect();
5355 for gid in group_ids {
5356 self.form_values.insert(gid, String::new());
5357 }
5358 }
5359 self.form_values.insert(tid.clone(), value);
5360 } else if kind == 3 {
5361 if !options.is_empty() {
5363 let cur = self.form_values.get(&tid).cloned().unwrap_or_default();
5364 let cur_idx = options.iter().position(|(v, _)| *v == cur).unwrap_or(0);
5365 let next_idx = (cur_idx + 1) % options.len();
5366 self.form_values
5367 .insert(tid.clone(), options[next_idx].0.clone());
5368 }
5369 }
5370 let new_val = self.form_values.get(&tid).cloned().unwrap_or_default();
5372 let node = self.js_runtime.dom().borrow().get_element_by_id(&tid);
5373 if let Some(i) = node {
5374 {
5376 let mut dom = self.js_runtime.dom().borrow_mut();
5377 if kind == 1 || kind == 2 {
5378 if new_val.is_empty() {
5379 dom.remove_attr(i, "checked");
5380 } else {
5381 dom.set_attr(i, "checked", "");
5382 }
5383 } else {
5384 dom.set_attr(i, "value", &new_val);
5385 }
5386 }
5387 self.js_runtime.dispatch_event(i, "change");
5388 }
5389 self.dirty = true;
5390 self.dirty_reason = "render.rs:3693";
5391 }
5392 if self.js_runtime.dom().borrow().dirty {
5393 self.dom_needs_rebuild = true;
5394 }
5395 return;
5396 }
5397
5398 if let Some((tid, new_val)) = range_action {
5399 self.form_values.insert(tid.clone(), new_val.clone());
5400 let node = self.js_runtime.dom().borrow().get_element_by_id(&tid);
5401 if let Some(i) = node {
5402 {
5403 let mut dom = self.js_runtime.dom().borrow_mut();
5404 dom.set_attr(i, "value", &new_val);
5405 }
5406 self.js_runtime.dispatch_event(i, "input");
5407 self.js_runtime.dispatch_event(i, "change");
5408 }
5409 self.dirty = true;
5410 self.dirty_reason = "render.rs:3712";
5411 if self.js_runtime.dom().borrow().dirty {
5412 self.dom_needs_rebuild = true;
5413 }
5414 return;
5415 }
5416
5417 let old_focus = self.focused_id.clone();
5419 self.focused_id = new_focus.clone();
5420 {
5424 let didx = match &self.focused_id {
5425 Some(fid) => self.js_runtime.dom().borrow().get_element_by_id(fid),
5426 None => None,
5427 };
5428 self.js_runtime.dom().borrow_mut().focused_idx = didx;
5429 }
5430
5431 if old_focus != self.focused_id {
5432 self.dom_needs_rebuild = true;
5438 if let Some(ref fid) = old_focus {
5440 if let Some(ref tb) = self.active_text_box {
5441 self.form_values.insert(fid.clone(), tb.text.clone());
5442 }
5443 }
5444 if let Some(fid) = old_focus.clone() {
5446 let node = self.js_runtime.dom().borrow().get_element_by_id(&fid);
5447 if let Some(i) = node {
5448 let cur = self.form_values.get(&fid).cloned().unwrap_or_default();
5449 self.js_runtime.dispatch_event(i, "blur");
5450 self.js_runtime.dispatch_event(i, "focusout");
5452 if cur != self.focus_value {
5453 self.js_runtime.dispatch_event(i, "change");
5454 }
5455 }
5456 }
5457 self.active_text_box = None;
5462 if let Some(fid) = self.focused_id.clone() {
5463 let is_ta = self
5464 .elements
5465 .iter()
5466 .find(|e| e.element_id == fid)
5467 .map(|e| e.is_textarea)
5468 .unwrap_or(false);
5469 let val = self.form_values.get(&fid).cloned().unwrap_or_default();
5470 let tb = Self::build_text_box(&val, is_ta, None);
5472 self.focus_cursor_pos = tb.cursor_pos;
5473 self.focus_caret_owner = fid;
5474 self.active_text_box = Some(tb);
5475 }
5476 if let Some(fid) = self.focused_id.clone() {
5478 self.focus_value = self.form_values.get(&fid).cloned().unwrap_or_default();
5479 let node = self.js_runtime.dom().borrow().get_element_by_id(&fid);
5480 if let Some(i) = node {
5481 self.js_runtime.dispatch_event(i, "focus");
5482 self.js_runtime.dispatch_event(i, "focusin");
5484 }
5485 } else {
5486 self.focus_value = String::new();
5487 }
5488 if self.js_runtime.dom().borrow().dirty {
5489 self.dom_needs_rebuild = true;
5490 }
5491 self.dirty = true;
5492 self.dirty_reason = "render.rs:3782";
5493 }
5494
5495 if let Some(rid) = reset_target_id {
5497 self.reset_form(&rid);
5498 if let Some(script) = script_to_run {
5499 if !script.is_empty() {
5500 if let Err(e) = crate::os_lib::ecma::eval(&script, &mut self.js_runtime) {
5505 crate::debug!("[JS] onclick/onreset handler error: {}", e);
5506 }
5507 }
5508 }
5509 self.dirty = true;
5510 self.dirty_reason = "render.rs:3793";
5511 return;
5512 }
5513
5514 if !focused_input {
5516 if let Some((action, method)) = form_to_submit {
5517 self.submit_form(&action, &method, top_offset);
5518 if let Some(script) = script_to_run {
5521 if !script.is_empty() {
5522 if let Err(e) = crate::os_lib::ecma::eval(&script, &mut self.js_runtime) {
5527 crate::debug!("[JS] onclick/onreset handler error: {}", e);
5528 }
5529 }
5530 }
5531 return;
5532 }
5533 }
5534
5535 for link in &self.links {
5537 if click_y >= link.y0
5538 && click_y < link.y1
5539 && local_x >= link.x0
5540 && local_x < link.x1
5541 {
5542 clicked_href = Some(link.href.clone());
5543 break;
5544 }
5545 }
5546 if pressed_edge && clicked_href.is_none() && form_to_submit.is_none() && new_focus.is_none() && reset_target_id.is_none() {
5554 let mut hit_text: Option<(usize, usize)> = None;
5555 for (idx, el) in self.elements.iter().enumerate() {
5556 if el.text.is_empty() || el.is_button || el.is_input || el.is_textarea {
5557 continue;
5558 }
5559 let el_y = if el.is_fixed { local_y - top_offset } else { click_y };
5560 let el_x = click_x;
5561 if el_x >= el.x_offset && el_x <= el.x_offset + el.width && el_y >= el.y_offset && el_y < el.y_offset + el.height {
5562 let char_off = super::selection::hit_test_text_char(&el.text, el.width, el_x - el.x_offset);
5563 hit_text = Some((idx, char_off));
5564 break;
5565 }
5566 }
5567 if let Some((t_idx, t_char)) = hit_text {
5568 let pos = super::selection::TextPosition::new(t_idx, t_char);
5569 self.selecting_anchor = Some(pos);
5570 self.selection = Some(super::selection::SelectionRange::new(pos, pos));
5571 self.is_selecting_text = true;
5572 self.dirty = true;
5573 self.dirty_reason = "text_selection_start";
5574 } else {
5575 self.clear_selection();
5576 }
5577 }
5578
5579 let mut default_prevented = false;
5580
5581 if let Some(script) = script_to_run {
5582 if !script.is_empty() {
5583 match crate::os_lib::ecma::eval(&script, &mut self.js_runtime) {
5588 Ok(v) => {
5589 if matches!(v, crate::os_lib::ecma::value::Value::Bool(false)) {
5590 default_prevented = true;
5591 }
5592 }
5593 Err(e) => {
5594 crate::debug!("[JS] onclick/onreset handler error: {}", e);
5595 }
5596 }
5597 }
5598 }
5599
5600 let front = clicked_ids
5605 .iter()
5606 .filter_map(|id| {
5607 let node = self.js_runtime.dom().borrow().get_element_by_id(id)?;
5608 let el = self.elements.iter().find(|e| &e.element_id == id)?;
5609 let step = super::paint_order::stack_step_ext(
5610 el.z_index,
5611 el.is_positioned,
5612 false,
5613 el.is_inline_content(),
5614 el.paint_depth,
5615 el.paint_seq,
5616 );
5617 Some(((el.stack_path.as_slice(), step), node))
5618 })
5619 .max_by(|((pa, sa), _), ((pb, sb), _)| super::paint_order::paint_cmp(pa, *sa, pb, *sb))
5620 .map(|(_, n)| n);
5621 if let Some(idx) = front {
5622 let (_dispatched, prevented) = self.js_runtime.dispatch_mouse(idx, "click", local_x, local_y);
5623 if prevented {
5624 default_prevented = true;
5625 }
5626 }
5627
5628 if !default_prevented {
5630 if let Some(ref href) = clicked_href {
5631 self.navigate_to_href(href, top_offset);
5632 }
5633 }
5634
5635 self.process_pending_reset();
5637
5638 self.relayout_if_dom_dirty(top_offset, self.win_w, self.win_h);
5640
5641 self.process_pending_nav(top_offset);
5643 self.process_pending_location(top_offset);
5645 } else {
5646 self.dragging_scrollbar = false;
5647 self.dragging_sub_scrollbar = None;
5648 }
5649 }
5650
5651 pub fn on_key(&mut self, keycode: u8, _pressed: bool, ascii: Option<char>) {
5652 if !_pressed {
5653 return;
5654 }
5655
5656 if let Some(ref key) = self.focused_frame.clone() {
5657 if let Some(child) = self.child_frames.get_mut(key) {
5658 child.on_key(keycode, _pressed, ascii);
5659 if child.dirty {
5660 self.dirty = true;
5661 self.dirty_reason = "child_frame_key";
5662 }
5663 return;
5664 }
5665 }
5666
5667 let target_node = match self.focused_id.clone() {
5669 Some(fid) => self.js_runtime.dom().borrow().get_element_by_id(&fid),
5670 None => {
5671 let d = self.js_runtime.dom().borrow();
5672 d.nodes.iter().position(|n| n.tag == "body").or_else(|| if d.nodes.is_empty() { None } else { Some(0) })
5673 }
5674 };
5675 if let Some(idx) = target_node {
5676 let key_name = match ascii {
5677 Some(c) => {
5678 let mut s = String::new();
5679 s.push(c);
5680 s
5681 }
5682 None => String::from(key_name_for(keycode)),
5683 };
5684 let (_fired, prevented) = self.js_runtime.dispatch_key(idx, "keydown", &key_name);
5685 self.relayout_if_dom_dirty(self.top_offset, self.win_w, self.win_h);
5686 if self.process_pending_nav(self.top_offset) {
5688 return;
5689 }
5690 self.process_pending_reset();
5691 if self.process_pending_location(self.top_offset) {
5693 return;
5694 }
5695 if prevented {
5696 return; }
5698 if ascii.is_some() {
5701 let (_f, kp_prevented) =
5702 self.js_runtime.dispatch_key(idx, "keypress", &key_name);
5703 self.relayout_if_dom_dirty(self.top_offset, self.win_w, self.win_h);
5704 if kp_prevented {
5705 return;
5706 }
5707 }
5708 }
5709
5710 if keycode == 0x01 {
5713 let modal_dialog = {
5714 let d = self.js_runtime.dom().borrow();
5715 d.nodes.iter().enumerate().rev().find_map(|(idx, n)| {
5717 if n.tag == "dialog" && d.has_attr(idx, "_modal") {
5718 Some(idx)
5719 } else {
5720 None
5721 }
5722 })
5723 };
5724 if let Some(dialog_idx) = modal_dialog {
5725 let (_fired, prevented) = self.js_runtime.dispatch_event_with(dialog_idx, "cancel", &[]);
5726 if !prevented {
5727 let mut d = self.js_runtime.dom().borrow_mut();
5728 d.remove_attr(dialog_idx, "_modal");
5729 d.remove_attr(dialog_idx, "open");
5730 drop(d);
5731 self.js_runtime.dispatch_event(dialog_idx, "close");
5732 self.dirty = true;
5733 self.dirty_reason = "dialog_escape_close";
5734 self.relayout_if_dom_dirty(self.top_offset, self.win_w, self.win_h);
5735 return;
5736 }
5737 }
5738 }
5739
5740 let mut focus_on_textarea = false;
5741 let mut textarea_el = None;
5742 if let Some(ref focused_id) = self.focused_id {
5743 if let Some(el) = self.elements.iter().find(|e| &e.element_id == focused_id) {
5744 if el.is_textarea {
5745 focus_on_textarea = true;
5746 textarea_el = Some(el.clone());
5747 }
5748 }
5749 }
5750
5751 if keycode == 0x1C && !focus_on_textarea && self.focused_id.is_some() {
5755 self.flush_focused_input();
5756 let submit = self
5757 .elements
5758 .iter()
5759 .find(|e| e.is_button && !e.form_action.is_empty())
5760 .map(|e| {
5761 let m = if e.form_method.is_empty() {
5762 String::from("GET")
5763 } else {
5764 e.form_method.clone()
5765 };
5766 (e.form_action.clone(), m)
5767 });
5768 if let Some((action, method)) = submit {
5769 let top = self.top_offset;
5770 self.submit_form(&action, &method, top);
5771 return;
5772 }
5773 }
5774
5775 if let Some(ref focused_id) = self.focused_id {
5777 if self.active_text_box.is_none() {
5778 let val = self
5779 .form_values
5780 .get(focused_id)
5781 .cloned()
5782 .unwrap_or_default();
5783 let is_ta = self
5784 .elements
5785 .iter()
5786 .find(|e| &e.element_id == focused_id)
5787 .map(|e| e.is_textarea)
5788 .unwrap_or(false);
5789 let restore = if &self.focus_caret_owner == focused_id {
5790 Some(self.focus_cursor_pos)
5791 } else {
5792 None
5793 };
5794 self.active_text_box = Some(Self::build_text_box(&val, is_ta, restore));
5795 }
5796 let mut handled = false;
5797 let mut text_changed = false;
5798 let mut cursor_pos = 0;
5799 let mut new_text = String::new();
5800 if let Some(ref mut tb) = self.active_text_box {
5801 let outcome = tb.handle_key_outcome(keycode, ascii);
5802 if outcome != crate::kernel::text_box::KeyOutcome::Ignored {
5803 self.form_values.insert(focused_id.clone(), tb.text.clone());
5804 self.dirty = true;
5805 self.dirty_reason = "render.rs:3969";
5806 handled = true;
5807 text_changed =
5808 outcome == crate::kernel::text_box::KeyOutcome::TextChanged;
5809 cursor_pos = tb.cursor_pos;
5810 new_text = tb.text.clone();
5811 }
5812 }
5813 if handled {
5814 self.focus_cursor_pos = cursor_pos;
5817 self.focus_caret_owner = focused_id.clone();
5818 if text_changed {
5824 let didx = self.js_runtime.dom().borrow().get_element_by_id(focused_id);
5825 if let Some(i) = didx {
5826 self.js_runtime
5827 .dom()
5828 .borrow_mut()
5829 .set_attr(i, "value", &new_text);
5830 self.js_runtime.dispatch_event(i, "input");
5831 if self.js_runtime.dom().borrow().dirty {
5832 self.dom_needs_rebuild = true;
5833 }
5834 self.dirty = true;
5835 self.dirty_reason = "render.rs:3988";
5836 }
5837 }
5838 if focus_on_textarea {
5839 if let Some(ref el) = textarea_el {
5840 let text_val = self
5841 .form_values
5842 .get(focused_id)
5843 .cloned()
5844 .unwrap_or(String::new());
5845 let cursor_line = self.get_cursor_line_idx(&text_val, cursor_pos, el.width);
5846
5847 let visible_lines = ((el.height - 16) / 20).max(1);
5848 let scroll_y = self.editor_scroll_y;
5849
5850 if (cursor_line as i32) < scroll_y {
5851 self.editor_scroll_y = cursor_line as i32;
5852 } else if (cursor_line as i32) >= scroll_y + visible_lines {
5853 self.editor_scroll_y = cursor_line as i32 - visible_lines + 1;
5854 }
5855
5856 let lines_len =
5858 Self::wrap_editor_lines(&text_val, el.width, self.editor_wrap).len();
5859 let max_scroll_y = (lines_len as i32 - visible_lines + 1).max(0);
5860 self.editor_scroll_y = self.editor_scroll_y.min(max_scroll_y).max(0);
5861 }
5862 }
5863 return;
5864 }
5865 }
5866
5867 let video_action = super::media_controls::parse_media_key_action(keycode, ascii);
5869 let has_video = self.elements.iter().any(|e| e.is_video);
5870 if has_video && video_action != super::media_controls::MediaKeyAction::None {
5871 match video_action {
5872 super::media_controls::MediaKeyAction::TogglePlay => {
5873 self.video_playing = !self.video_playing;
5874 if self.video_playing {
5875 self.video_controls.set_hud("▶ 再生", 45);
5876 if let Some(el) = self.elements.iter().find(|e| e.is_video) {
5877 let v_width = (self.win_w as i32 - 80).clamp(400, 800);
5878 let mut state = VIDEO_STATE.lock();
5879 let v_loop = el.video_loop;
5880 *state = Some(VideoPlayState {
5881 src_url: el.video_src.clone(),
5882 x: el.x_offset.max(0) as u32,
5883 y: el.y_offset.max(0) as u32,
5884 width: v_width as u32,
5885 height: el.height as u32,
5886 playing: true,
5887 stop_request: false,
5888 paused: false,
5889 loop_playback: v_loop,
5890 });
5891 let pid = crate::kernel::scheduler::spawn_away_from_current(
5892 video_playback_thread,
5893 crate::kernel::scheduler::Priority::High,
5894 "video_playback",
5895 );
5896 if pid == 0 {
5897 stop_video_playback();
5898 }
5899 }
5900 } else {
5901 self.video_controls.set_hud("⏸ 一時停止", 45);
5902 stop_video_playback();
5903 }
5904 self.dirty = true;
5905 self.dirty_reason = "render.rs:video_key_play";
5906 return;
5907 }
5908 super::media_controls::MediaKeyAction::ToggleMute => {
5909 let muted = self.video_controls.toggle_mute();
5910 self.video_controls.set_hud(if muted { "🔇 消音" } else { "🔊 音量 ON" }, 45);
5911 crate::os_lib::mse::PLAYBACK.lock().muted = muted;
5912 crate::kernel::audio::AudioStream::set_paused(muted);
5913 self.dirty = true;
5914 self.dirty_reason = "render.rs:video_key_mute";
5915 return;
5916 }
5917 super::media_controls::MediaKeyAction::SeekRelative(delta) => {
5918 let target = (self.video_controls.current_time + delta as f64).clamp(0.0, self.video_controls.duration);
5919 self.video_controls.current_time = target;
5920 let seek_hud = if delta > 0 {
5921 alloc::format!("⏩ +{}秒", delta)
5922 } else {
5923 alloc::format!("⏪ {}秒", delta)
5924 };
5925 self.video_controls.set_hud(&seek_hud, 45);
5926 *crate::os_lib::mse::SEEK_REQUEST.lock() = Some(target);
5927 crate::os_lib::mse::PLAYBACK.lock().current_time = target;
5928 self.dirty = true;
5929 self.dirty_reason = "render.rs:video_key_seek";
5930 return;
5931 }
5932 super::media_controls::MediaKeyAction::VolumeRelative(delta) => {
5933 let new_vol = (self.video_controls.volume + delta as f32 / 100.0).clamp(0.0, 1.0);
5934 self.video_controls.set_volume(new_vol);
5935 let vol_hud = alloc::format!("🔊 {}%", (new_vol * 100.0) as u32);
5936 self.video_controls.set_hud(&vol_hud, 45);
5937 crate::os_lib::mse::PLAYBACK.lock().volume = new_vol as f64;
5938 self.dirty = true;
5939 self.dirty_reason = "render.rs:video_key_vol";
5940 return;
5941 }
5942 super::media_controls::MediaKeyAction::ToggleFullscreen => {
5943 let fs = self.video_controls.toggle_fullscreen();
5944 self.video_controls.set_hud(if fs { "⛶ 全画面" } else { "⛶ 通常表示" }, 45);
5945 if let Some(ref mut state) = *VIDEO_STATE.lock() {
5946 if fs {
5947 state.x = 0;
5948 state.y = self.top_offset.max(0) as u32;
5949 state.width = self.win_w;
5950 state.height = self.win_h.saturating_sub(self.top_offset.max(0) as u32);
5951 } else if let Some(el) = self.elements.iter().find(|e| e.is_video) {
5952 let v_width = (self.win_w as i32 - 80).clamp(400, 800);
5953 state.x = el.x_offset.max(0) as u32;
5954 state.y = el.y_offset.max(0) as u32;
5955 state.width = v_width as u32;
5956 state.height = el.height as u32;
5957 }
5958 }
5959 self.dirty = true;
5960 self.dirty_reason = "render.rs:video_key_fullscreen";
5961 return;
5962 }
5963 super::media_controls::MediaKeyAction::ToggleSubtitles => {
5964 let hud = if let Some((label, idx, total)) = self.video_controls.cycle_subtitles() {
5965 alloc::format!("CC 字幕: {} [{}/{}]", label, idx, total)
5966 } else {
5967 alloc::string::String::from("CC 字幕: オフ")
5968 };
5969 self.video_controls.set_hud(&hud, 45);
5970 self.dirty = true;
5971 self.dirty_reason = "render.rs:video_key_subtitles";
5972 return;
5973 }
5974 super::media_controls::MediaKeyAction::CycleQuality => {
5975 let (name, idx, total) = self.video_controls.cycle_quality();
5976 let hud = alloc::format!("🎦 画質: {} [{}/{}]", name, idx, total);
5977 self.video_controls.set_hud(&hud, 45);
5978 self.dirty = true;
5979 self.dirty_reason = "render.rs:video_key_quality";
5980 return;
5981 }
5982 super::media_controls::MediaKeyAction::DirectSeekPercent(pct) => {
5983 let dur = if self.video_controls.duration > 0.0 {
5984 self.video_controls.duration
5985 } else {
5986 100.0
5987 };
5988 let target = (dur * (pct as f64) / 100.0).clamp(0.0, dur);
5989 self.video_controls.current_time = target;
5990 let seek_hud = alloc::format!("⏮ {}%", pct);
5991 self.video_controls.set_hud(&seek_hud, 45);
5992 *crate::os_lib::mse::SEEK_REQUEST.lock() = Some(target);
5993 crate::os_lib::mse::PLAYBACK.lock().current_time = target;
5994 self.dirty = true;
5995 self.dirty_reason = "render.rs:video_key_direct_seek";
5996 return;
5997 }
5998 super::media_controls::MediaKeyAction::PlaybackRateStep(step) => {
5999 let new_rate = self.video_controls.adjust_playback_rate(step);
6000 let rate_hud = alloc::format!("⚡ {:.2}x", new_rate);
6001 self.video_controls.set_hud(&rate_hud, 45);
6002 crate::os_lib::mse::PLAYBACK.lock().playback_rate = new_rate as f64;
6003 self.dirty = true;
6004 self.dirty_reason = "render.rs:video_key_rate";
6005 return;
6006 }
6007 super::media_controls::MediaKeyAction::None => {}
6008 }
6009 }
6010
6011 if keycode == 0x48 {
6012 self.scroll_with_top(-24, self.top_offset);
6014 } else if keycode == 0x50 {
6015 self.scroll_with_top(24, self.top_offset);
6017 }
6018 }
6019
6020 pub fn on_key_up(&mut self, keycode: u8, ascii: Option<char>) {
6023 if let Some(ref key) = self.focused_frame.clone() {
6024 if let Some(child) = self.child_frames.get_mut(key) {
6025 child.on_key_up(keycode, ascii);
6026 if child.dirty {
6027 self.dirty = true;
6028 self.dirty_reason = "child_frame_keyup";
6029 }
6030 return;
6031 }
6032 }
6033 let target_node = match self.focused_id.clone() {
6034 Some(fid) => self.js_runtime.dom().borrow().get_element_by_id(&fid),
6035 None => {
6036 let d = self.js_runtime.dom().borrow();
6037 d.nodes.iter().position(|n| n.tag == "body").or_else(|| if d.nodes.is_empty() { None } else { Some(0) })
6038 }
6039 };
6040 if let Some(idx) = target_node {
6041 let key_name = match ascii {
6042 Some(c) => {
6043 let mut s = String::new();
6044 s.push(c);
6045 s
6046 }
6047 None => String::from(key_name_for(keycode)),
6048 };
6049 let _ = self.js_runtime.dispatch_key(idx, "keyup", &key_name);
6050 self.relayout_if_dom_dirty(self.top_offset, self.win_w, self.win_h);
6051 self.process_pending_reset();
6052 self.process_pending_nav(self.top_offset);
6053 self.process_pending_location(self.top_offset);
6054 }
6055 }
6056}
6057
6058fn element_has_painted_bg(el: &super::RenderElement) -> bool {
6060 el.bg_image.is_some()
6061 || !el.bg_images.is_empty()
6062 || el.linear_gradient.is_some()
6063 || el.radial_gradient.is_some()
6064 || el.conic_gradient.is_some()
6065}