1#![allow(dead_code)]
14
15use alloc::string::String;
16use alloc::vec::Vec;
17use spin::Mutex;
18
19const MAX_RENDER_ELEMENTS: usize = 20000;
22const MAX_HTML_BYTES: usize = 2 * 1024 * 1024;
24
25pub const HOME_HTML: &str = r#"<html><title>AtmOS Browser</title><body style="background-color: #282a36; color: #f8f8f2;"><h1 style="color: #bd93f9;">AtmOS Browser</h1><p style="color: #f8f8f2;">アトモス(AtmOS)の内蔵ブラウザへようこそ。HTML/CSS パーサ・レイアウトエンジン・レンダラと JavaScript エンジンをすべて自前実装しています。</p><hr style="color: #44475a;"><h2 style="color: #8be9fd;">リンク</h2><div style="background-color: #1e1f29; color: #f8f8f2;"><p><a href="https://www.sugi-lab.net/">www.sugi-lab.net</a></p><p style="color: #6272a4;">Sugimura Lab の Web サイト。AtmOS の開発元です。研究・教育・各種プロジェクト of 情報を掲載しています。</p><p><a href="https://www.youtube.com/">YouTube を観る(ホーム)</a></p><p style="color: #6272a4;">YouTube の Web サイトを開きます。</p><p><a href="https://www.youtube.com/watch?v=aqz-KE-bpKQ">YouTube 動画再生テスト(Big Buck Bunny / H.264)</a></p><p style="color: #6272a4;">動画視聴ページを開き、H.264/AAC 自律デコーダで動画を再生します。</p></div><h2 style="color: #8be9fd;">検索</h2><p><a href="https://www.google.com/">Google で検索する</a></p><p style="color: #6272a4;">Google の検索トップページを開きます。「g キーワード」でも Google 検索できます。</p><p><a href="https://duckduckgo.com/">DuckDuckGo で検索する</a></p><p style="color: #6272a4;">上のアドレスバーにキーワードを入力しても、そのまま DuckDuckGo で検索できます。</p><hr style="color: #44475a;"><p style="font-size: 12; color: #6272a4;">AtmOS — bare-metal OS on Raspberry Pi 3B+ / ARM64 + Rust</p></body></html>"#;
29
30mod cache;
36pub(crate) mod draw_helpers;
37pub(crate) mod helpers;
38mod image;
39mod layout;
40pub(crate) use layout::forget_flatten_memo_of_closed_groups;
41pub(crate) use image::forget_shared_images_of_group;
42mod render;
43pub(crate) mod anim_budget;
44pub(crate) use crate::os_lib::css::units as css_units;
45pub(crate) mod font_budget;
46pub(crate) mod cache_path;
47pub(crate) mod rel_path;
48pub(crate) mod sticky;
49pub(crate) mod fetch_limit;
50pub(crate) mod queue_batch;
51pub(crate) mod perf;
52pub(crate) mod font_queue;
53pub(crate) mod fq_owners;
54pub(crate) mod image_budget;
55pub(crate) mod flatten_memo_budget;
56pub(crate) mod decided_spans;
57pub(crate) mod alpha_blend;
58pub(crate) mod doc_title;
59pub(crate) mod backdrop;
60pub(crate) mod text_align;
61pub(crate) mod paint_order;
62pub(crate) mod button_paint;
63pub(crate) mod inline_svg;
64pub(crate) mod repaint_scope;
65pub(crate) mod paint_update;
66pub(crate) mod inline_style_cache;
67pub(crate) mod gradient_lut;
68pub(crate) mod blur_box;
69pub mod font_gamma;
70pub mod selection;
71pub mod selection_style;
72pub mod media_controls;
73pub mod vtt;
74pub mod omnibox;
75pub mod site_hooks;
76pub(crate) mod box_shadow;
77pub(crate) mod embed_map;
78pub(crate) mod iframe_preview;
79pub(crate) mod paint_cull;
80pub(crate) mod url_resolve;
81pub(crate) mod referrer;
82pub(crate) mod video_fit;
83pub(crate) mod frames;
84pub(crate) mod clip_path;
85pub(crate) use crate::os_lib::css::filters as css_filters;
86pub(crate) mod text_ellipsis;
87pub(crate) mod scrollbar;
88pub(crate) mod bilinear;
89mod video;
90pub mod dynamic_scripts;
91
92pub use css_filters::*;
93pub use clip_path::*;
94pub use text_ellipsis::*;
95pub use scrollbar::*;
96
97pub use cache::clear_browser_cache;
98pub use draw_helpers::{draw_border, draw_gradation};
99pub(crate) use layout::{parse_line_height, parse_shadow_len_tok, resolve_border_radius, resolve_text_indent};
103pub use helpers::{hash_str, url_encode};
104pub use image::image_results_ready;
105pub use image::shared_image;
106pub use fetch_limit::set_draw_stage;
107
108pub fn font_pending() -> usize {
110 font_queue::pending_len()
111}
112
113use cache::{cache_path_for, write_cache};
115use image::{enqueue_image, ImageFetchReq, IMAGE_QUEUE};
116use video::stop_video_playback;
117
118pub(crate) fn parse_url_scheme(url: &str) -> Option<(bool, alloc::string::String, alloc::string::String)> {
119 let (is_https, rest) = if let Some(r) = url.strip_prefix("https://") {
120 (true, r)
121 } else if let Some(r) = url.strip_prefix("http://") {
122 (false, r)
123 } else {
124 return None;
125 };
126 if let Some(slash_idx) = rest.find('/') {
127 let (host, path) = rest.split_at(slash_idx);
128 Some((
129 is_https,
130 alloc::string::String::from(host),
131 alloc::string::String::from(path),
132 ))
133 } else {
134 Some((
135 is_https,
136 alloc::string::String::from(rest),
137 alloc::string::String::from("/"),
138 ))
139 }
140}
141
142fn parse_url(url: &str) -> Option<(alloc::string::String, alloc::string::String)> {
143 let (_, host, path) = parse_url_scheme(url)?;
144 Some((host, path))
145}
146
147fn key_name_for(keycode: u8) -> &'static str {
149 match keycode {
150 0x1C => "Enter",
151 0x0E => "Backspace",
152 0x0F => "Tab",
153 0x01 => "Escape",
154 0x39 => " ", 0x53 => "Delete",
156 0x48 => "ArrowUp",
157 0x50 => "ArrowDown",
158 0x4B => "ArrowLeft",
159 0x4D => "ArrowRight",
160 0x47 => "Home",
161 0x4F => "End",
162 _ => "Unidentified",
163 }
164}
165
166#[derive(Clone)]
167struct AsyncLoadRequest {
168 owner: u64, group: u8,
172 is_https: bool,
173 host: String,
174 path: String,
175 method: String, body: Option<String>, referer: Option<String>,
179 status: u8, result_body: Option<String>,
181 result_dom: Option<crate::os_lib::dom::Node>,
182 error_msg: Option<String>,
183}
184
185struct AsyncLoadState {
187 requests: Vec<AsyncLoadRequest>,
188 thread_active: bool,
189}
190
191static SVG_BACK: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12.5 16.5L6 10L12.5 3.5\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>";
196
197static SVG_HOME: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M10 2.5L3.5 8V16.5C3.5 17 4 17.5 4.5 17.5H7.5V12.5H12.5V17.5H15.5C16 17.5 16.5 17 16.5 16.5V8L10 2.5Z\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linejoin=\"round\"/></svg>";
198
199static SVG_SHIELD_SECURE: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M10 2.5C13 3.5 16.5 3.5 16.5 3.5V8.5C16.5 13 13 16.5 10 17.5C7 16.5 3.5 13 3.5 8.5V3.5C3.5 3.5 7 3.5 10 2.5Z\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linejoin=\"round\"/><path d=\"M7 10L9 12L13 8\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>";
200
201static SVG_SHIELD_WARN: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M10 2.5C13 3.5 16.5 3.5 16.5 3.5V8.5C16.5 13 13 16.5 10 17.5C7 16.5 3.5 13 3.5 8.5V3.5C3.5 3.5 7 3.5 10 2.5Z\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linejoin=\"round\"/><path d=\"M4.5 4.5L15.5 15.5\" stroke=\"currentColor\" stroke-width=\"2\"/></svg>";
202
203static SVG_SAVE: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M16 18H4C3 18 2 17 2 16V4C2 3 3 2 4 2H13L18 7V16C18 17 17 18 16 18Z\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M14 18V11H6V18\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M6 2V6H12\" stroke=\"currentColor\" stroke-width=\"2\"/></svg>";
204
205static SVG_LOAD: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M18 16C18 17 17 18 16 18H4C3 18 2 17 2 16V4C2 3 3 2 4 2H8L10 4H16C17 4 18 5 18 6V16Z\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M2 8H18\" stroke=\"currentColor\" stroke-width=\"2\"/></svg>";
206
207static SVG_WRAP: &[u8] = b"<svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M3 5H17\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M3 10H13C15 10 16 11 16 13C16 15 15 16 13 16H11\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M13 14L11 16L13 18\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M3 15H6\" stroke=\"currentColor\" stroke-width=\"2\"/></svg>";
208
209static ASYNC_LOAD: Mutex<AsyncLoadState> = Mutex::new(AsyncLoadState {
210 requests: Vec::new(),
211 thread_active: false,
212});
213static NEXT_ENGINE_ID: spin::Mutex<u64> = spin::Mutex::new(1);
214
215pub fn forget_requests_of_group(g: u8) -> (usize, usize, usize) {
226 let mut pages = 0;
227 if let Some(mut lock) = ASYNC_LOAD.try_lock() {
228 let before = lock.requests.len();
229 lock.requests.retain(|r| r.group != g);
230 pages = before - lock.requests.len();
231 }
232 let images = image::forget_requests_of_group(g);
233 let fonts = font_queue::forget_group(g);
234 (pages, images, fonts)
235}
236
237impl Drop for WebEngine {
244 fn drop(&mut self) {
245 let id = self.engine_id;
246 let mut pages = 0;
247 if let Some(mut lock) = ASYNC_LOAD.try_lock() {
248 let before = lock.requests.len();
249 lock.requests.retain(|r| r.owner != id);
250 pages = before - lock.requests.len();
251 }
252 let images = image::forget_requests_of_owner(id);
253 if pages + images != 0 {
254 crate::warn!("[WEB] 捨てたタブ(エンジン {})のページの読み込み {} 件・画像の取得の待ち {} 件を捨てた", id, pages, images);
255 }
256 }
257}
258
259fn async_load_thread_entry() {
260 loop {
261 let req_opt = {
262 let mut lock = ASYNC_LOAD.lock();
263 let before = lock.requests.len();
265 lock.requests.retain(|r| !crate::kernel::window_mgr::group_stopped(r.group));
266 if lock.requests.len() != before {
267 crate::warn!("[NET] BROWSER_LOADER: 止めたアプリの要求・結果を {} 件捨てた", before - lock.requests.len());
268 }
269 lock.requests.iter().find(|r| r.status == 1).cloned()
271 };
272
273 let req = match req_opt {
274 Some(r) => r,
275 None => {
276 let mut lock = ASYNC_LOAD.lock();
278 if !lock.requests.iter().any(|r| r.status == 1) {
279 lock.thread_active = false;
280 drop(lock);
281 fetch_limit::set_main_load_in_flight(false);
284 crate::kernel::scheduler::exit();
285 }
286 fetch_limit::set_main_load_in_flight(false);
287 continue;
288 }
289 };
290 fetch_limit::set_main_load_in_flight(true);
298 let _loan = crate::kernel::scheduler::borrow_mem_group(req.group);
301
302 {
303 let mut current_is_https = req.is_https;
311 let mut current_host = req.host.clone();
312 let mut current_path = req.path.clone();
313
314 let is_post = req.method.eq_ignore_ascii_case("POST");
315 let post_body = req.body.clone().unwrap_or_default();
316
317 let use_cache = req.referer.is_none();
322 let res = if !is_post && use_cache {
323 if let Some(cached) = cache::read_cache_strict(¤t_host, ¤t_path) {
324 match alloc::string::String::from_utf8(cached) {
325 Ok(s) => {
326 crate::info!(
327 "BROWSER_LOADER: cache hit. host={}, path={}",
328 current_host,
329 current_path
330 );
331 Some(Ok(s))
332 }
333 Err(_) => {
334 crate::warn!("[NET] BROWSER_LOADER: cache decode error, fetching from network. host={}", current_host);
336 let cp = cache_path_for(¤t_host, ¤t_path);
337 let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
338 let _ = crate::kernel::fs::get_fs().delete_file(&cp);
339 None
340 }
341 }
342 } else {
343 None
344 }
345 } else {
346 None
347 };
348
349 let res = if let Some(r) = res {
350 r
351 } else {
352 if !crate::kernel::net::status().link_up {
355 if let Some(html) = site_hooks::hooks().offline_page(¤t_host, ¤t_path, current_is_https, is_post, &post_body) {
356 Ok(html)
357 } else {
358 crate::warn!("[NET] BROWSER_LOADER: network link is down");
359 Err(String::from("Network link is down. Check QEMU network settings or USB-Ethernet adapter."))
360 }
361 } else {
362 let stack = crate::kernel::net_stack::TcpIpStack::new();
363
364 if is_post {
366 crate::info!(
367 "BROWSER_LOADER: POST {} host={}, path={}",
368 if current_is_https { "HTTPS" } else { "HTTP" },
369 current_host,
370 current_path
371 );
372 match stack.web_post(
373 current_is_https,
374 ¤t_host,
375 ¤t_path,
376 "application/x-www-form-urlencoded",
377 post_body.as_bytes(),
378 ) {
379 Ok(r) => {
380 if r.status_code == 303
382 || r.status_code == 301
383 || r.status_code == 302
384 {
385 if let Some(loc) = r.headers.get("location") {
386 let loc_str = loc.as_str();
387 if let Some(no_proto) = loc_str.strip_prefix("https://") {
388 current_is_https = true;
389 if let Some(idx) = no_proto.find('/') {
390 let (h, p) = no_proto.split_at(idx);
391 current_host = String::from(h);
392 current_path = String::from(p);
393 } else {
394 current_host = String::from(no_proto);
395 current_path = String::from("/");
396 }
397 } else if let Some(no_proto) =
398 loc_str.strip_prefix("http://")
399 {
400 current_is_https = false;
401 if let Some(idx) = no_proto.find('/') {
402 let (h, p) = no_proto.split_at(idx);
403 current_host = String::from(h);
404 current_path = String::from(p);
405 } else {
406 current_host = String::from(no_proto);
407 current_path = String::from("/");
408 }
409 } else if loc_str.starts_with('/') {
410 current_path = String::from(loc_str);
411 }
412 match stack.web_get(
414 current_is_https,
415 ¤t_host,
416 ¤t_path,
417 ) {
418 Ok(r2) => {
419 write_cache(
420 ¤t_host,
421 ¤t_path,
422 r2.body.as_bytes(),
423 );
424 Ok(r2.body)
425 }
426 Err(e) => Err(String::from(e.message)),
427 }
428 } else {
429 Ok(r.body)
430 }
431 } else {
432 Ok(r.body)
433 }
434 }
435 Err(e) => Err(String::from(e.message)),
436 }
437 } else {
438 let mut final_res = None;
439 let mut fetch_retries = 2u32;
448 for _ in 0..6 {
449 match stack.web_get_with_referer(current_is_https, ¤t_host, ¤t_path, req.referer.as_deref()) {
451 Ok(r) => {
452 let code = r.status_code;
453 if code == 301
454 || code == 302
455 || code == 303
456 || code == 307
457 || code == 308
458 {
459 if let Some(loc) = r.headers.get("location") {
460 crate::info!("[NET] BROWSER_LOADER: Redirect to {}", loc);
461 let loc_str = loc.as_str();
462 if let Some(no_proto) = loc_str.strip_prefix("http://")
463 {
464 current_is_https = false;
465 if let Some(idx) = no_proto.find('/') {
466 let (h, p) = no_proto.split_at(idx);
467 current_host = String::from(h);
468 current_path = String::from(p);
469 } else {
470 current_host = String::from(no_proto);
471 current_path = String::from("/");
472 }
473 continue;
474 } else if let Some(no_proto) =
475 loc_str.strip_prefix("https://")
476 {
477 current_is_https = true;
478 if let Some(idx) = no_proto.find('/') {
479 let (h, p) = no_proto.split_at(idx);
480 current_host = String::from(h);
481 current_path = String::from(p);
482 } else {
483 current_host = String::from(no_proto);
484 current_path = String::from("/");
485 }
486 continue;
487 } else if loc_str.starts_with('/') {
488 current_path = String::from(loc_str);
489 continue;
490 }
491 }
492 }
493 if use_cache {
495 write_cache(¤t_host, ¤t_path, r.body.as_bytes());
496 }
497 final_res = Some(Ok(r.body));
498 break;
499 }
500 Err(e) => {
501 if fetch_retries > 0 {
502 fetch_retries -= 1;
503 crate::warn!(
504 "[NET] BROWSER_LOADER: fetch failed ({}), retrying ({} left) host={} path={}",
505 e.message,
506 fetch_retries,
507 current_host,
508 current_path
509 );
510 continue;
511 }
512 final_res = Some(Err(String::from(e.message)));
513 break;
514 }
515 }
516 }
517 final_res.unwrap_or_else(|| Err(String::from("Too many redirects")))
518 } } }; let mut parse_later: Option<String> = None;
526 let mut lock = ASYNC_LOAD.lock();
527 if let Some(current_req) = lock
532 .requests
533 .iter_mut()
534 .find(|r| r.owner == req.owner && r.status == 1)
535 {
536 match res {
537 Ok(body) => {
538 crate::info!("[NET] BROWSER_LOADER: load done. size={}", body.len());
539 let final_body = site_hooks::hooks().rewrite_response(¤t_host, ¤t_path, current_is_https, body);
541 parse_later = Some(final_body);
543 }
544 Err(e) => {
545 if let Some(fallback_html) = site_hooks::hooks().load_failed_page(¤t_host, ¤t_path, current_is_https, &e) {
546 let dom_tree = crate::os_lib::dom::parse_html(&fallback_html);
547 current_req.status = 2; current_req.result_body = Some(fallback_html);
549 current_req.result_dom = Some(dom_tree);
550 } else {
551 crate::warn!("[NET] BROWSER_LOADER: load failed. err=[{}] len={}", e, e.len());
552 current_req.status = 3; current_req.error_msg = Some(e);
554 }
555 }
556 }
557 }
558 drop(lock);
559 if let Some(mut final_body) = parse_later {
560 let full_len = final_body.len();
563 if full_len > MAX_HTML_BYTES {
564 let mut cut = MAX_HTML_BYTES;
565 while cut > 0 && !final_body.is_char_boundary(cut) {
566 cut -= 1;
567 }
568 final_body.truncate(cut);
569 final_body.shrink_to_fit();
570 crate::warn!("[NET] BROWSER_LOADER: HTML が大きすぎるので {} → {} バイトで切って解析する", full_len, cut);
571 }
572 let owner = req.owner;
576 let mut over_quota = false;
577 let gone = || {
578 if crate::kernel::window_mgr::borrowed_group_should_stop() {
579 over_quota = true;
580 return true;
581 }
582 ASYNC_LOAD
583 .try_lock()
584 .is_some_and(|l| !l.requests.iter().any(|r| r.owner == owner && r.status == 1))
585 };
586 let lower_path = current_path.split(['?', '#']).next().unwrap_or("").to_ascii_lowercase();
591 let is_xhtml = lower_path.ends_with(".xht") || lower_path.ends_with(".xhtml");
592 let xml_tree = if is_xhtml {
593 match crate::os_lib::xml_parser::parse_xml(final_body.strip_prefix('\u{FEFF}').unwrap_or(&final_body)) {
594 Ok(t) => Some(t),
595 Err(e) => {
596 crate::warn!("[NET] BROWSER_LOADER: XHTML を XML として解析できず HTML として解析する: {} ({}:{})", e.message, e.line, e.column);
597 None
598 }
599 }
600 } else {
601 None
602 };
603 let (dom_tree, stats) = match xml_tree {
604 Some(t) => (t, crate::os_lib::dom::ParseStats::default()),
605 None => crate::os_lib::dom::parse_html_poll_counted(&final_body, gone),
606 };
607 if stats.node_limit_hit || stats.depth_capped != 0 {
608 crate::warn!(
609 "[NET] BROWSER_LOADER: HTML の解析を上限で抑えた: ノード {} 個(上限 {}、届いた={})・深さの上限で開かなかったタグ {} 個",
610 stats.nodes,
611 crate::os_lib::dom::MAX_DOM_NODES,
612 stats.node_limit_hit,
613 stats.depth_capped
614 );
615 }
616 let mut lock = ASYNC_LOAD.lock();
617 if over_quota {
618 let heap_mb = crate::kernel::allocator::get_heap_stats().0 >> 20;
620 drop(lock);
621 drop(dom_tree);
622 drop(final_body);
623 crate::warn!(
624 "[NET] BROWSER_LOADER: メモリの上限に当たったので HTML の解析をやめた(ノード {} 個まで、ヒープ {}MB → {}MB)",
625 stats.nodes,
626 heap_mb,
627 crate::kernel::allocator::get_heap_stats().0 >> 20
628 );
629 let mut lock = ASYNC_LOAD.lock();
630 if let Some(current_req) = lock.requests.iter_mut().find(|r| r.owner == owner && r.status == 1) {
631 current_req.status = 3; current_req.error_msg = Some(String::from("the page is too large for the memory of this app"));
633 }
634 } else if let Some(current_req) = lock.requests.iter_mut().find(|r| r.owner == owner && r.status == 1) {
635 current_req.status = 2; current_req.result_body = Some(final_body);
637 current_req.result_dom = Some(dom_tree);
638 } else {
639 drop(lock);
641 drop(dom_tree);
642 drop(final_body);
643 }
644 }
645 }
646 } }
648
649#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
652pub enum BorderStyle {
653 #[default]
654 None,
655 Solid,
656 Dashed,
657 Dotted,
658 Double,
659}
660
661impl BorderStyle {
662 pub fn as_str(self) -> &'static str {
663 match self {
664 BorderStyle::None => "none",
665 BorderStyle::Solid => "solid",
666 BorderStyle::Dashed => "dashed",
667 BorderStyle::Dotted => "dotted",
668 BorderStyle::Double => "double",
669 }
670 }
671
672 pub fn parse(s: &str) -> Self {
673 match s.trim().to_ascii_lowercase().as_str() {
674 "solid" => BorderStyle::Solid,
675 "dashed" => BorderStyle::Dashed,
676 "dotted" => BorderStyle::Dotted,
677 "double" => BorderStyle::Double,
678 _ => BorderStyle::None,
679 }
680 }
681
682 pub fn is_none(self) -> bool {
683 matches!(self, BorderStyle::None)
684 }
685}
686
687#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
689pub enum ListStyleType {
690 #[default]
692 Unset,
693 None,
694 Disc,
695 Circle,
696 Square,
697 Decimal,
698 UpperAlpha,
699 LowerAlpha,
700 UpperRoman,
701 LowerRoman,
702}
703
704impl ListStyleType {
705 pub fn parse(s: &str) -> Self {
706 match s.trim().to_ascii_lowercase().as_str() {
707 "none" => ListStyleType::None,
708 "disc" => ListStyleType::Disc,
709 "circle" => ListStyleType::Circle,
710 "square" => ListStyleType::Square,
711 "decimal" => ListStyleType::Decimal,
712 "upper-alpha" | "upper-latin" => ListStyleType::UpperAlpha,
713 "lower-alpha" | "lower-latin" => ListStyleType::LowerAlpha,
714 "upper-roman" => ListStyleType::UpperRoman,
715 "lower-roman" => ListStyleType::LowerRoman,
716 _ => ListStyleType::Unset,
717 }
718 }
719}
720
721pub use crate::os_lib::util::ordinal::{number_to_alpha, number_to_roman};
722
723#[derive(Clone, Copy, PartialEq, Debug)]
725pub enum BgSizeVal {
726 Auto,
727 Px(i32),
728 Percent(f32),
729}
730
731#[derive(Clone, Copy, PartialEq, Debug, Default)]
733pub enum BgSizeMode {
734 #[default]
736 Stretch,
737 Cover,
738 Contain,
739 Explicit(BgSizeVal, BgSizeVal),
740}
741
742#[derive(Clone, Copy, PartialEq, Debug, Default)]
744pub enum BgRepeatMode {
745 #[default]
746 Repeat,
747 NoRepeat,
748 Space,
750 Round,
752}
753
754#[derive(Clone, Copy, PartialEq, Debug, Default)]
756pub enum ObjectFit {
757 #[default]
759 Fill,
760 Contain,
761 Cover,
762 None,
764 ScaleDown,
766}
767
768#[derive(Debug, Clone, PartialEq)]
770pub struct GradientStop {
771 pub color: u32,
772 pub position: f32, }
774
775#[derive(Debug, Clone, PartialEq)]
776pub struct LinearGradient {
777 pub angle_deg: f32,
778 pub stops: alloc::vec::Vec<GradientStop>,
779}
780
781#[derive(Debug, Clone, PartialEq)]
782pub enum RadialShape {
783 Circle,
784 Ellipse,
785}
786
787#[derive(Debug, Clone, PartialEq)]
788pub struct RadialGradient {
789 pub shape: RadialShape,
790 pub pos_x: f32, pub pos_y: f32, pub stops: alloc::vec::Vec<GradientStop>,
793}
794
795#[derive(Debug, Clone, PartialEq)]
796pub enum CssFilter {
797 Blur(i32), HueRotate(f32), DropShadow(i32, i32, i32, u32), }
801
802#[derive(Debug, Clone, PartialEq)]
803pub struct RenderElement {
804 pub text: String,
805 pub font_size: u32,
806 pub color: u32,
807 pub bg_color: Option<u32>, pub hover_bg_color: Option<u32>,
809 pub hover_color: Option<u32>,
810 pub hover_border_color: Option<u32>,
811 pub focus_bg_color: Option<u32>,
814 pub focus_color: Option<u32>,
815 pub focus_border_color: Option<u32>,
816 pub active_bg_color: Option<u32>,
819 pub active_color: Option<u32>,
820 pub active_border_color: Option<u32>,
821 pub marker_color: Option<u32>,
823 pub marker_font_size: Option<u32>,
825 pub marker_content: Option<alloc::string::String>,
828 pub border_color: Option<u32>,
829 pub border_style: BorderStyle,
830 pub font_bold: bool, pub font_weight: u16,
834 pub font_italic: bool, pub underline: bool, pub line_through: bool, pub overline: bool, pub decoration_color: Option<u32>,
840 pub decoration_style: String,
842 pub decoration_thickness: i32,
844 pub decoration_underline_offset: i32,
846 pub scroll_margin_top: i32,
849 pub client_insets: Option<(i32, i32, i32, i32)>, pub caret_color: Option<u32>,
852 pub accent_color: Option<u32>,
854 pub placeholder_color: Option<u32>,
857 pub placeholder: String,
859 pub is_video: bool, pub video_src: String, pub video_has_controls: bool,
863 pub video_autoplay: bool,
865 pub video_poster: String,
867 pub video_loop: bool,
869 pub is_iframe: bool, pub iframe_src: String, pub iframe_preview: Option<iframe_preview::Preview>,
873 pub is_link: bool,
874 pub pointer_events_none: bool,
878 pub href: String,
879 pub is_hr: bool,
880 pub is_img: bool,
881 pub img_lazy: bool,
883 pub img_alt: String,
884 pub canvas_ctx_id: Option<u32>,
890 pub aspect_ratio: Option<f32>,
892 pub is_input: bool,
893 pub is_textarea: bool,
894 pub is_button: bool,
895 pub is_reset: bool,
897 pub btn_author_bg: bool,
899 pub input_kind: u8,
903 pub radio_group: String,
905 pub input_value: String,
907 pub select_options: alloc::vec::Vec<(String, String)>,
909 pub label_for: String,
912 pub button_icon: u8, pub element_id: String,
914 pub onclick: String,
915 pub form_action: String,
916 pub form_method: String,
917 pub width: i32,
918 pub x_offset: i32, pub y_offset: i32, pub height: i32,
921 pub border_radius: (i32, i32, i32, i32), pub is_li: bool,
923 pub li_num: Option<u32>,
924 pub list_style_type: ListStyleType,
925 pub list_style_inside: bool,
927 pub list_style_image: String,
930 pub is_blockquote: bool,
931 pub border_top_width: i32,
932 pub border_right_width: i32,
933 pub border_bottom_width: i32,
934 pub border_left_width: i32,
935 pub border_top_color: Option<u32>,
936 pub border_right_color: Option<u32>,
937 pub border_bottom_color: Option<u32>,
938 pub border_left_color: Option<u32>,
939 pub border_top_style: BorderStyle,
940 pub border_right_style: BorderStyle,
941 pub border_bottom_style: BorderStyle,
942 pub border_left_style: BorderStyle,
943 pub padding_top: i32,
944 pub padding_right: i32,
945 pub padding_bottom: i32,
946 pub padding_left: i32,
947 pub bg_clip: String,
950 pub bg_origin: String,
951 pub bg_attachment: String,
953 pub bg_image: Option<String>,
954 pub bg_images: Vec<String>,
957 pub background_blend_mode: String,
961 pub bg_layers: alloc::vec::Vec<(BgSizeMode, BgRepeatMode, BgRepeatMode, f32, f32)>,
965 pub pos_top: Option<i32>,
967 pub pos_left: Option<i32>,
968 pub pos_right: Option<i32>,
969 pub pos_bottom: Option<i32>,
970 pub z_index: i32,
971 pub paint_depth: u32,
975 pub is_fixed: bool,
976 pub is_positioned: bool,
980 pub overflow_hidden: bool,
981 pub clip_radius: i32,
983 pub clip_x0: i32,
984 pub clip_y0: i32,
985 pub clip_x1: i32,
986 pub clip_y1: i32,
987 pub box_shadow: alloc::vec::Vec<(i32, i32, i32, u32, bool)>,
990 pub white_space_nowrap: bool,
991 pub text_overflow_ellipsis: bool,
992 pub text_overflow_rtl: bool,
995 pub linear_gradient: Option<LinearGradient>,
996 pub radial_gradient: Option<RadialGradient>,
997 pub conic_gradient: Option<alloc::vec::Vec<GradientStop>>,
1000 pub repeating_linear_gradient: Option<(alloc::vec::Vec<u32>, i32, bool)>,
1003 pub repeating_radial_gradient: Option<(alloc::vec::Vec<u32>, i32)>,
1006 pub opacity: u8, pub visibility_hidden: bool,
1008 pub visibility_decided: bool,
1010 pub pointer_events_decided: bool,
1012 pub stack_path: Vec<paint_order::StackStep>,
1014 pub paint_seq: u32,
1016 pub stack_decided: bool,
1018 pub text_shadow: alloc::vec::Vec<(i32, i32, i32, u32)>,
1021 pub before_content: String,
1023 pub after_content: String,
1024 pub font_family: String,
1037 pub before_font_family: String,
1038 pub transform_tx: i32, pub transform_ty: i32, pub layout_tx: i32,
1049 pub layout_ty: i32,
1050 pub transform_scale_x: f32, pub transform_scale_y: f32, pub transform_rotate_deg: f32, pub transform_skew_x: f32,
1055 pub transform_skew_y: f32,
1057 pub transform_origin_x: f32,
1059 pub transform_origin_y: f32,
1060 pub letter_spacing: i32,
1062 pub word_spacing: i32,
1064 pub text_emphasis_style: String,
1068 pub text_emphasis_color: Option<u32>,
1070 pub cursor_style: String,
1073 pub scroll_container_id: String,
1075 pub clip_path: String,
1077 pub is_sticky: bool,
1079 pub sticky_top: Option<i32>,
1081 pub sticky_bottom: Option<i32>,
1082 pub sticky_bound_max_y: i32,
1085 pub bg_size: BgSizeMode,
1087 pub bg_repeat_x: BgRepeatMode,
1089 pub bg_repeat_y: BgRepeatMode,
1090 pub bg_pos_x: f32,
1092 pub bg_pos_y: f32,
1093 pub outline_color: Option<u32>,
1095 pub outline_width: i32,
1096 pub outline_offset: i32,
1098 pub outline_style: String,
1100 pub object_fit: ObjectFit,
1102 pub object_pos_x: f32,
1104 pub object_pos_y: f32,
1105 pub filter: String,
1108 pub mix_blend_mode: String,
1111 pub backdrop_filter: String,
1113 pub image_rendering: String,
1115 pub text_stroke_width: i32,
1117 pub text_stroke_color: Option<u32>,
1118 pub line_clamp: i32,
1122 pub node_idx: Option<usize>,
1123 pub is_modal: bool,
1125 pub backdrop_color: Option<u32>,
1127}
1128
1129impl RenderElement {
1130 pub fn weight(&self) -> u16 {
1132 if self.font_weight != 0 {
1133 self.font_weight
1134 } else if self.font_bold {
1135 700
1136 } else {
1137 400
1138 }
1139 }
1140
1141 pub fn is_inline_content(&self) -> bool {
1144 !self.text.is_empty()
1145 || self.is_img
1146 || self.is_video
1147 || self.is_iframe
1148 || self.is_input
1149 || self.is_textarea
1150 || self.is_button
1151 || self.is_hr
1152 || self.button_icon != 0
1153 || !self.before_content.is_empty()
1154 || !self.after_content.is_empty()
1155 || self.is_li
1156 || self.canvas_ctx_id.is_some()
1157 }
1158}
1159
1160impl Default for RenderElement {
1161 fn default() -> Self {
1162 RenderElement {
1163 node_idx: None,
1164 text: String::new(),
1165 font_size: 0,
1166 color: 0,
1167 bg_color: None,
1168 hover_bg_color: None,
1169 hover_color: None,
1170 hover_border_color: None,
1171 focus_bg_color: None,
1172 focus_color: None,
1173 focus_border_color: None,
1174 active_bg_color: None,
1175 active_color: None,
1176 active_border_color: None,
1177 marker_color: None,
1178 marker_font_size: None,
1179 marker_content: None,
1180 border_color: None,
1181 client_insets: None,
1182 border_style: BorderStyle::None,
1183 font_bold: false,
1184 font_weight: 0,
1185 font_italic: false,
1186 underline: false,
1187 line_through: false,
1188 overline: false,
1189 decoration_color: None,
1190 decoration_style: String::new(),
1191 decoration_thickness: 1,
1192 decoration_underline_offset: 0,
1193 scroll_margin_top: 0,
1194 caret_color: None,
1195 accent_color: None,
1196 placeholder_color: None,
1197 placeholder: String::new(),
1198 is_video: false,
1199 video_src: String::new(),
1200 video_has_controls: false,
1201 video_autoplay: false,
1202 video_poster: String::new(),
1203 video_loop: false,
1204 is_iframe: false,
1205 iframe_src: String::new(),
1206 iframe_preview: None,
1207 is_link: false,
1208 pointer_events_none: false,
1209 href: String::new(),
1210 is_hr: false,
1211 is_img: false,
1212 img_lazy: false,
1213 canvas_ctx_id: None,
1214 img_alt: String::new(),
1215 aspect_ratio: None,
1216 is_input: false,
1217 is_textarea: false,
1218 is_button: false,
1219 is_reset: false,
1220 btn_author_bg: false,
1221 input_kind: 0,
1222 radio_group: String::new(),
1223 input_value: String::new(),
1224 select_options: alloc::vec::Vec::new(),
1225 label_for: String::new(),
1226 button_icon: 0,
1227 element_id: String::new(),
1228 onclick: String::new(),
1229 form_action: String::new(),
1230 form_method: String::new(),
1231 width: 0,
1232 x_offset: 0,
1233 y_offset: 0,
1234 height: 0,
1235 border_radius: (0, 0, 0, 0),
1236 is_li: false,
1237 li_num: None,
1238 list_style_type: ListStyleType::Unset,
1239 list_style_inside: false,
1240 list_style_image: String::new(),
1241 is_blockquote: false,
1242 border_top_width: 0,
1243 border_right_width: 0,
1244 border_bottom_width: 0,
1245 border_left_width: 0,
1246 border_top_color: None,
1247 border_right_color: None,
1248 border_bottom_color: None,
1249 border_left_color: None,
1250 border_top_style: BorderStyle::None,
1251 border_right_style: BorderStyle::None,
1252 border_bottom_style: BorderStyle::None,
1253 border_left_style: BorderStyle::None,
1254 padding_top: 0,
1255 padding_right: 0,
1256 padding_bottom: 0,
1257 padding_left: 0,
1258 bg_clip: String::from("border-box"),
1259 bg_origin: String::from("padding-box"),
1260 bg_attachment: String::from("scroll"),
1261 bg_image: None,
1262 bg_images: Vec::new(),
1263 background_blend_mode: String::new(),
1264 bg_layers: alloc::vec::Vec::new(),
1265 pos_top: None,
1266 pos_left: None,
1267 pos_right: None,
1268 pos_bottom: None,
1269 z_index: 0,
1270 paint_depth: 0,
1271 is_fixed: false,
1272 is_positioned: false,
1273 overflow_hidden: false,
1274 clip_radius: 0,
1275 clip_x0: 0,
1276 clip_y0: 0,
1277 clip_x1: i32::MAX,
1278 clip_y1: i32::MAX,
1279 box_shadow: alloc::vec::Vec::new(),
1280 white_space_nowrap: false,
1281 text_overflow_ellipsis: false,
1282 text_overflow_rtl: false,
1283 linear_gradient: None,
1284 radial_gradient: None,
1285 conic_gradient: None,
1286 repeating_linear_gradient: None,
1287 repeating_radial_gradient: None,
1288 opacity: 255,
1289 visibility_hidden: false,
1290 visibility_decided: false,
1291 pointer_events_decided: false,
1292 stack_path: Vec::new(),
1293 paint_seq: 0,
1294 stack_decided: false,
1295 text_shadow: alloc::vec::Vec::new(),
1296 before_content: String::new(),
1297 after_content: String::new(),
1298 font_family: String::new(),
1299 before_font_family: String::new(),
1300 transform_tx: 0,
1301 transform_ty: 0,
1302 layout_tx: 0,
1303 layout_ty: 0,
1304 transform_scale_x: 1.0,
1305 transform_scale_y: 1.0,
1306 transform_rotate_deg: 0.0,
1307 transform_skew_x: 0.0,
1308 transform_skew_y: 0.0,
1309 transform_origin_x: 0.5,
1310 transform_origin_y: 0.5,
1311 letter_spacing: 0,
1312 word_spacing: 0,
1313 text_emphasis_style: String::new(),
1314 text_emphasis_color: None,
1315 cursor_style: String::new(),
1316 scroll_container_id: String::new(),
1317 clip_path: String::new(),
1318 is_sticky: false,
1319 sticky_top: None,
1320 sticky_bottom: None,
1321 sticky_bound_max_y: i32::MAX,
1322 bg_size: BgSizeMode::Stretch,
1323 bg_repeat_x: BgRepeatMode::Repeat,
1324 bg_repeat_y: BgRepeatMode::Repeat,
1325 bg_pos_x: 0.0,
1326 bg_pos_y: 0.0,
1327 outline_color: None,
1328 outline_width: 0,
1329 outline_offset: 0,
1330 outline_style: String::from("solid"),
1331 object_fit: ObjectFit::Fill,
1332 object_pos_x: 0.5,
1333 object_pos_y: 0.5,
1334 filter: String::new(),
1335 mix_blend_mode: String::new(),
1336 backdrop_filter: String::new(),
1337 image_rendering: String::new(),
1338 text_stroke_width: 0,
1339 text_stroke_color: None,
1340 line_clamp: 0,
1341 is_modal: false,
1342 backdrop_color: None,
1343 }
1344 }
1345}
1346
1347#[derive(Clone, Debug)]
1349pub struct HyperlinkArea {
1350 pub href: String,
1351 pub x0: i32,
1352 pub y0: i32,
1353 pub x1: i32,
1354 pub y1: i32,
1355}
1356
1357#[derive(Clone)]
1359pub struct DecodedImage {
1360 pub width: u32,
1361 pub height: u32,
1362 pub rgba: alloc::vec::Vec<u8>,
1363}
1364
1365pub struct WebEngine {
1366 pub engine_id: u64,
1368 pub active: bool,
1369 pub current_is_https: bool,
1370 pub current_host: String,
1371 pub current_path: String,
1372 pub current_url_with_hash: String,
1375 pub title: String,
1376 pub scroll_y: i32,
1377 pub max_scroll_y: i32,
1378 pub scroll_smooth: bool,
1382 pub scrollbar_width: ScrollbarWidth,
1384 pub scrollbar_color: Option<ScrollbarColor>,
1386 pub scrollbar_width_none: bool,
1388 pub scroll_anim_active: bool,
1390 pub scroll_anim_from: i32,
1391 pub scroll_anim_to: i32,
1392 pub scroll_anim_start_ms: f32,
1393 pub pending_fragment: String,
1396 pub elements: Vec<RenderElement>,
1397 pub dirty_reason: &'static str,
1400 pub links: Vec<HyperlinkArea>,
1401 pub history: Vec<(bool, String, String)>,
1402 pub forward_history: Vec<(bool, String, String)>,
1403 pub dirty: bool,
1404 pub form_values: alloc::collections::BTreeMap<String, String>,
1405 pub initial_form_values: alloc::collections::BTreeMap<String, String>,
1407 pub field_names: alloc::collections::BTreeMap<String, String>,
1409 pub dom_contents: alloc::collections::BTreeMap<String, String>,
1410 pub executing_script: bool,
1411 pub pending_scripts: alloc::vec::Vec<(Option<String>, String, bool)>,
1413 pub ready_complete_pending: bool,
1415 pub ready_interactive_at: u64,
1417 pub ready_complete_now: bool,
1419 pub ready_last_nodes: usize,
1421 pub scripts_ran_for: Option<u32>,
1424 pub dom_needs_rebuild: bool,
1426 pub pending_reflow_since: usize,
1434 pub pending_reflow_last: usize,
1436 pub focused_id: Option<String>,
1437 pub focus_value: String,
1439 pub hovered_id: Option<String>,
1441 pub cursor_pos: usize,
1442 pub env: crate::os_lib::aura::eval::Env,
1443 pub js_runtime: crate::os_lib::ecma::JsRuntime,
1445 pub video_playing: bool,
1447 pub video_tick: u32,
1448 pub video_controls: media_controls::MediaControlsState,
1449 pub background_image_urls: alloc::collections::BTreeSet<String>,
1453 pub iframe_previews: alloc::collections::BTreeMap<String, Option<iframe_preview::Preview>>,
1455 pub loading: bool,
1456 pub loading_tick: u32,
1457 pub mouse_x: i32,
1458 pub mouse_y: i32,
1459 pub hovered_cursor_is_text: bool,
1463 pub hovered_cursor_kind: alloc::string::String,
1467 pub prev_btn_left: bool,
1470 pub mouse_btn_left_down: bool,
1473 pub prev_btn_right: bool,
1475 pub last_click_id: Option<String>,
1477 pub last_click_tick: usize,
1478 pub last_video_click_tick: usize,
1480 pub win_w: u32,
1482 pub win_h: u32,
1483 pub top_offset: i32,
1484 pub editor_wrap: bool,
1485 pub editor_scroll_y: i32,
1486 pub editor_scroll_x: i32,
1487 pub last_html: String,
1488 pub dragging_scrollbar: bool,
1489 pub image_cache:
1493 alloc::collections::BTreeMap<String, alloc::sync::Arc<DecodedImage>>,
1494 pub image_attempted: alloc::collections::BTreeSet<String>,
1496 pub elements_gen: u64,
1498 pub image_scan_key: Option<(u64, i32, i32, u32, usize, usize, usize)>,
1500 pub image_scan_frames: u32,
1501 pub active_text_box: Option<crate::kernel::text_box::TextBox>,
1502 pub focus_cursor_pos: usize,
1511 pub focus_caret_owner: String,
1513 pub page_bg_color: Option<u32>,
1515 pub page_text_color: Option<u32>,
1517 pub anim_engine: crate::os_lib::css::AnimationEngine,
1519 pub anim_specs: alloc::collections::BTreeMap<String, (String, String)>,
1522 pub anim_prev_values:
1524 alloc::collections::BTreeMap<String, alloc::collections::BTreeMap<String, String>>,
1525 pub in_anim_relayout: bool,
1528 pub inherited_paint_z: i32,
1531 pub inherited_paint_depth: u32,
1533 pub inherited_positioned: bool,
1537 pub inherited_pos_count: u32,
1539 pub abs_marks: Vec<(usize, usize, u32)>,
1542 pub stack_prefix: Vec<paint_order::StackStep>,
1544 pub flatten_memo_covered: usize,
1547 pub flatten_decided: decided_spans::DecidedSpans,
1550 pub flatten_visibility_decided: decided_spans::DecidedSpans,
1552 pub flatten_gaps: Vec<(usize, usize)>,
1554 pub bg_layer_idx: Vec<u32>,
1556 pub last_anim_layout_ms: f32,
1559 pub last_anim_relayout_end_ms: f32,
1561 pub last_dom_layout_ms: f32,
1563 pub last_dom_relayout_end_ms: f32,
1564 pub relayout_done_this_draw: bool,
1566 pub force_relayout: bool,
1568 pub scroll_regions: alloc::collections::BTreeMap<String, i32>,
1571 pub scroll_regions_x: alloc::collections::BTreeMap<String, i32>,
1573 pub dragging_sub_scrollbar: Option<String>,
1575 pub scroll_containers: alloc::vec::Vec<(String, i32, i32, i32, i32, i32, ScrollbarWidth, Option<ScrollbarColor>)>,
1579 pub dynamic_scripts: dynamic_scripts::DynamicScriptManager,
1581 pub cached_css_hash: Option<(u64, u64)>,
1586 pub(crate) inline_style_memo: inline_style_cache::InlineStyleParseMemo,
1588 pub cached_stylesheet: Option<alloc::rc::Rc<crate::os_lib::css::StyleSheet>>,
1590 pub cached_rule_index: Option<alloc::rc::Rc<crate::os_lib::css::rule_index::RuleIndex>>,
1592 pub style_memo: crate::os_lib::css::style_memo::StyleMemo,
1594 pub external_css_cache: Option<String>,
1599 pub pending_link_css: alloc::vec::Vec<(usize, String, String)>,
1601 pub external_css_counts: Option<(usize, usize, usize, usize, alloc::vec::Vec<String>)>,
1605 pub external_css_parsed: alloc::vec::Vec<(String, String)>,
1608 pub osm_states: alloc::collections::BTreeMap<String, crate::os_lib::web_engine::embed_map::MapState>,
1610 pub dragging_osm: Option<(String, i32, i32)>,
1612 pub selection: Option<selection::SelectionRange>,
1614 pub selecting_anchor: Option<selection::TextPosition>,
1616 pub is_selecting_text: bool,
1618 pub selection_style: selection_style::SelectionStyle,
1620 pub referrer: String,
1622 pending_referer: Option<String>,
1624 pub child_frames: alloc::collections::BTreeMap<String, alloc::boxed::Box<WebEngine>>,
1628 pub frame_depth: u32,
1630 pub frame_hits: Vec<(String, i32, i32, i32, i32)>,
1632 pub focused_frame: Option<String>,
1634}
1635
1636impl Default for WebEngine {
1637 fn default() -> Self {
1638 Self::new()
1639 }
1640}
1641
1642impl WebEngine {
1643 pub fn new() -> Self {
1644 let env = crate::os_lib::aura::eval::Env::new();
1645 let engine_id = {
1646 let mut g = NEXT_ENGINE_ID.lock();
1647 let id = *g;
1648 *g += 1;
1649 id
1650 };
1651 Self {
1652 dirty_reason: "init",
1653 pending_fragment: String::new(),
1654 engine_id,
1655 active: false,
1656 current_is_https: true,
1657 current_host: String::from(site_hooks::hooks().initial_page().0),
1658 current_path: String::from("/"),
1659 current_url_with_hash: alloc::format!("https://{}/", site_hooks::hooks().initial_page().0),
1660 title: String::from(site_hooks::hooks().initial_page().1),
1661 scroll_y: 0,
1662 max_scroll_y: 0,
1663 scroll_smooth: false,
1664 scrollbar_width: ScrollbarWidth::Auto,
1665 scrollbar_color: None,
1666 scrollbar_width_none: false,
1667 scroll_anim_active: false,
1668 scroll_anim_from: 0,
1669 scroll_anim_to: 0,
1670 scroll_anim_start_ms: 0.0,
1671 elements: Vec::new(),
1672 links: Vec::new(),
1673 history: Vec::new(),
1674 forward_history: Vec::new(),
1675 dirty: true,
1676 form_values: alloc::collections::BTreeMap::new(),
1677 initial_form_values: alloc::collections::BTreeMap::new(),
1678 field_names: alloc::collections::BTreeMap::new(),
1679 dom_contents: alloc::collections::BTreeMap::new(),
1680 executing_script: false,
1681 pending_scripts: alloc::vec::Vec::new(),
1682 ready_complete_pending: false,
1683 ready_interactive_at: 0,
1684 ready_complete_now: false,
1685 ready_last_nodes: 0,
1686 scripts_ran_for: None,
1687 dom_needs_rebuild: false,
1688 pending_reflow_since: 0,
1689 pending_reflow_last: 0,
1690 focused_id: None,
1691 focus_value: String::new(),
1692 hovered_id: None,
1693 cursor_pos: 0,
1694 env,
1695 js_runtime: crate::os_lib::ecma::JsRuntime::new(),
1696 video_playing: false,
1697 video_tick: 0,
1698 video_controls: media_controls::MediaControlsState::new(120.0),
1699 background_image_urls: alloc::collections::BTreeSet::new(),
1700 iframe_previews: alloc::collections::BTreeMap::new(),
1701 loading: false,
1702 loading_tick: 0,
1703 mouse_x: -1000,
1704 mouse_y: -1000,
1705 hovered_cursor_is_text: false,
1706 hovered_cursor_kind: alloc::string::String::new(),
1707 prev_btn_left: false,
1708 mouse_btn_left_down: false,
1709 prev_btn_right: false,
1710 last_click_id: None,
1711 last_click_tick: 0,
1712 last_video_click_tick: 0,
1713 win_w: 1366,
1714 win_h: 768,
1715 top_offset: 0,
1716 editor_wrap: true,
1717 editor_scroll_y: 0,
1718 editor_scroll_x: 0,
1719 last_html: String::new(),
1720 dragging_scrollbar: false,
1721 image_cache: alloc::collections::BTreeMap::new(),
1722 image_attempted: alloc::collections::BTreeSet::new(),
1723 elements_gen: 0,
1724 image_scan_key: None,
1725 image_scan_frames: 0,
1726 active_text_box: None,
1727 focus_cursor_pos: 0,
1728 focus_caret_owner: String::new(),
1729 page_bg_color: None,
1730 page_text_color: None,
1731 anim_engine: crate::os_lib::css::AnimationEngine::new(),
1732 anim_specs: alloc::collections::BTreeMap::new(),
1733 anim_prev_values: alloc::collections::BTreeMap::new(),
1734 in_anim_relayout: false,
1735 inherited_paint_z: 0,
1736 inherited_paint_depth: 0,
1737 inherited_positioned: false,
1738 inherited_pos_count: 0,
1739 abs_marks: Vec::new(),
1740 stack_prefix: Vec::new(),
1741 flatten_memo_covered: 0,
1742 flatten_decided: decided_spans::DecidedSpans::new(),
1743 flatten_visibility_decided: decided_spans::DecidedSpans::new(),
1744 flatten_gaps: Vec::new(),
1745 bg_layer_idx: Vec::new(),
1746 last_anim_layout_ms: 0.0,
1747 last_anim_relayout_end_ms: 0.0,
1748 last_dom_layout_ms: 0.0,
1749 last_dom_relayout_end_ms: 0.0,
1750 relayout_done_this_draw: false,
1751 force_relayout: false,
1752 scroll_regions: alloc::collections::BTreeMap::new(),
1753 scroll_regions_x: alloc::collections::BTreeMap::new(),
1754 dragging_sub_scrollbar: None,
1755 scroll_containers: alloc::vec::Vec::new(),
1756 dynamic_scripts: dynamic_scripts::DynamicScriptManager::new(),
1757 cached_css_hash: None,
1758 inline_style_memo: Default::default(),
1759 cached_stylesheet: None,
1760 cached_rule_index: None,
1761 style_memo: Default::default(),
1762 external_css_cache: None,
1763 pending_link_css: alloc::vec::Vec::new(),
1764 external_css_counts: None,
1765 external_css_parsed: alloc::vec::Vec::new(),
1766 osm_states: alloc::collections::BTreeMap::new(),
1767 dragging_osm: None,
1768 selection: None,
1769 selecting_anchor: None,
1770 is_selecting_text: false,
1771 selection_style: selection_style::SelectionStyle::default(),
1772 referrer: String::new(),
1773 pending_referer: None,
1774 child_frames: alloc::collections::BTreeMap::new(),
1775 frame_depth: 0,
1776 frame_hits: Vec::new(),
1777 focused_frame: None,
1778 }
1779 }
1780
1781 pub fn has_pending_dynamic_scripts(&self) -> bool {
1783 self.dynamic_scripts.has_pending()
1784 || self.js_runtime.dom().try_borrow().is_ok_and(|d| !d.pending_dynamic_scripts.is_empty())
1785 }
1786
1787 pub fn frames_want_redraw(&self) -> bool {
1791 self.child_frames.values().any(|c| {
1792 c.loading
1793 || (c.video_playing && !video::VIDEO_STATE.lock().as_ref().is_some_and(|st| st.paused))
1794 || c.dirty
1795 || c.scroll_anim_active
1796 || c.dragging_scrollbar
1797 || c.dragging_sub_scrollbar.is_some()
1798 || c.js_runtime.dom().try_borrow().is_ok_and(|d| d.dirty)
1800 || !c.pending_scripts.is_empty()
1801 || c.has_pending_dynamic_scripts()
1802 || c.js_runtime.has_due_timers()
1803 || c.frames_want_redraw()
1804 })
1805 }
1806
1807 pub fn load_frame(&mut self, url: &str, referer: Option<String>) {
1810 let (is_https, rest) = if let Some(r) = url.strip_prefix("https://") {
1811 (true, r)
1812 } else if let Some(r) = url.strip_prefix("http://") {
1813 (false, r)
1814 } else {
1815 crate::warn!("[FRAME] 未対応の iframe URL: {}", url);
1816 return;
1817 };
1818 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
1819 let (host, tail) = rest.split_at(end);
1820 let path = if tail.starts_with('/') {
1821 String::from(tail)
1822 } else {
1823 alloc::format!("/{}", tail)
1824 };
1825 crate::info!("[FRAME] 読み込み depth={} url={} referer={:?}", self.frame_depth, url, referer);
1826 self.pending_referer = referer;
1827 self.load_page(is_https, host, &path, false, 0);
1828 }
1829
1830 pub fn get_selected_text(&self) -> String {
1832 if let Some(ref range) = self.selection {
1833 let layouts: alloc::vec::Vec<selection::TextElementLayout> = self
1834 .elements
1835 .iter()
1836 .enumerate()
1837 .filter(|(_, el)| !el.text.is_empty() && !el.is_button)
1838 .map(|(idx, el)| selection::TextElementLayout {
1839 element_index: idx,
1840 text: el.text.clone(),
1841 x: el.x_offset,
1842 y: el.y_offset,
1843 width: el.width,
1844 height: el.height,
1845 })
1846 .collect();
1847 selection::extract_selected_text(&layouts, range)
1848 } else {
1849 String::new()
1850 }
1851 }
1852
1853 pub fn clear_selection(&mut self) {
1855 if self.selection.is_some() || self.selecting_anchor.is_some() || self.is_selecting_text {
1856 self.selection = None;
1857 self.selecting_anchor = None;
1858 self.is_selecting_text = false;
1859 self.dirty = true;
1860 self.dirty_reason = "clear_selection";
1861 }
1862 }
1863
1864 fn parse_image_url(url: &str) -> Option<(bool, String, String)> {
1865 if let Some(rest) = url.strip_prefix("http://") {
1866 if let Some(idx) = rest.find('/') {
1867 let (h, p) = rest.split_at(idx);
1868 let host = String::from(h);
1869 let path = String::from(p);
1870 Some((false, host, path))
1871 } else {
1872 let host = String::from(rest);
1873 let path = String::from("/");
1874 Some((false, host, path))
1875 }
1876 } else if let Some(rest) = url.strip_prefix("https://") {
1877 if let Some(idx) = rest.find('/') {
1878 let (h, p) = rest.split_at(idx);
1879 let host = String::from(h);
1880 let path = String::from(p);
1881 Some((true, host, path))
1882 } else {
1883 let host = String::from(rest);
1884 let path = String::from("/");
1885 Some((true, host, path))
1886 }
1887 } else {
1888 None
1889 }
1890 }
1891
1892 pub fn focus_is_text_entry(&self) -> bool {
1898 let Some(id) = self.focused_id.as_deref() else { return false };
1899 if self.elements.iter().any(|e| e.element_id == id && (e.is_input || e.is_textarea)) {
1900 return true;
1901 }
1902 let dom = self.js_runtime.dom().borrow();
1903 dom.nodes.iter().any(|n| {
1904 n.id == id
1905 && (matches!(n.tag.as_str(), "input" | "textarea" | "select")
1906 || n.attrs.get("contenteditable").is_some_and(|v| !v.eq_ignore_ascii_case("false")))
1907 })
1908 }
1909
1910 fn ensure_image_cached(&mut self, src: &str) {
1912 if src.is_empty() {
1913 return;
1914 }
1915 if self.image_cache.contains_key(src) {
1916 return;
1917 }
1918 if let Some(img) = image::shared_image(src) {
1921 self.image_cache.insert(String::from(src), img);
1922 self.dirty = true;
1923 return;
1924 }
1925 if self.image_attempted.contains(src) {
1928 return;
1929 }
1930 self.image_attempted.insert(String::from(src));
1931
1932 let req = if src.starts_with("http://") || src.starts_with("https://") {
1933 if let Some((is_https, host, path)) = Self::parse_image_url(src) {
1934 if self.current_is_https && !is_https {
1935 crate::warn!(
1936 "MIXED CONTENT BLOCKED: Image {} over HTTP in HTTPS page",
1937 src
1938 );
1939 return;
1940 }
1941 ImageFetchReq {
1942 src_key: String::from(src),
1943 is_https,
1944 host,
1945 path,
1946 is_local: false,
1947 owner: self.engine_id,
1948 group: crate::kernel::scheduler::current_mem_group(),
1949 }
1950 } else {
1951 return;
1952 }
1953 } else if self.current_host == "localhost" {
1954 ImageFetchReq {
1955 src_key: String::from(src),
1956 is_https: false,
1957 host: String::new(),
1958 path: String::from(src),
1959 is_local: true,
1960 owner: self.engine_id,
1961 group: crate::kernel::scheduler::current_mem_group(),
1962 }
1963 } else {
1964 let host = self.current_host.clone();
1965 let path = if src.starts_with('/') {
1966 String::from(src)
1967 } else {
1968 let base_dir = self
1969 .current_path
1970 .rfind('/')
1971 .map(|i| self.current_path.get(..=i).unwrap_or("/"))
1972 .unwrap_or("/");
1973 let combined = alloc::format!("{}{}", base_dir, src);
1974 let mut parts: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
1975 for seg in combined.split('/') {
1976 match seg {
1977 "" | "." => {}
1978 ".." => {
1979 parts.pop();
1980 }
1981 s => parts.push(s),
1982 }
1983 }
1984 alloc::format!("/{}", parts.join("/"))
1985 };
1986 ImageFetchReq {
1987 src_key: String::from(src),
1988 is_https: self.current_is_https,
1989 host,
1990 path,
1991 is_local: false,
1992 owner: self.engine_id,
1993 group: crate::kernel::scheduler::current_mem_group(),
1994 }
1995 };
1996
1997 enqueue_image(req);
1998 }
1999
2000 fn poll_image_results(&mut self) -> bool {
2003 let mut q = IMAGE_QUEUE.lock();
2004 if q.results.is_empty() {
2005 return false;
2006 }
2007 let results: Vec<(String, DecodedImage)> = core::mem::take(&mut q.results);
2008 image::store_results_len(0);
2010 drop(q);
2011 for (key, decoded) in results {
2012 crate::os_lib::layout::register_image_natural_size(
2021 &key,
2022 decoded.width as i32,
2023 decoded.height as i32,
2024 );
2025 let shared = alloc::sync::Arc::new(decoded);
2026 image::share_image(&key, shared.clone());
2027 self.image_cache.insert(key, shared);
2028 }
2029 true
2030 }
2031
2032 fn reset_js_for_new_document(&mut self) {
2040 self.js_runtime = crate::os_lib::ecma::JsRuntime::new();
2041 self.dynamic_scripts.clear();
2042 self.ready_complete_pending = false;
2043 self.ready_last_nodes = 0;
2044 }
2045
2046 pub fn load_html(&mut self, html: &str, filename: &str, top_offset: i32) {
2047 self.scripts_ran_for = None;
2049 self.video_playing = false;
2050 stop_video_playback();
2051 self.reset_js_for_new_document();
2052 self.dom_contents.clear();
2053 self.dom_needs_rebuild = true;
2054 self.external_css_cache = None;
2056 self.pending_link_css.clear();
2057 self.external_css_counts = None;
2058 self.cached_stylesheet = None;
2059 self.cached_rule_index = None;
2060 self.cached_css_hash = None;
2061 self.inline_style_memo.clear();
2062 IMAGE_QUEUE
2064 .lock()
2065 .pending
2066 .retain(|r| r.owner != self.engine_id);
2067 self.form_values.clear();
2068 self.initial_form_values.clear();
2069 self.field_names.clear();
2070 self.current_host = String::from("localhost");
2071 self.current_path = alloc::format!("/{}", filename);
2072 self.title = alloc::format!("Local: {}", filename);
2073 {
2075 static N: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
2076 let n = N.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
2077 if n < 8 {
2078 crate::warn!("[LAYOUT][SRC] load_html('{}') #{}", filename, n + 1);
2079 }
2080 }
2081 self.parse_and_layout(html, None, top_offset, self.win_w, self.win_h);
2082 self.dirty = true;
2083 self.dirty_reason = "mod.rs:1432";
2084 }
2085
2086 pub fn sync_url_from_script(&mut self) -> bool {
2093 if self.scripts_ran_for.is_none() {
2095 return false;
2096 }
2097 let Some(href) = self.js_runtime.location_href() else { return false };
2098 let scheme = if self.current_is_https { "https://" } else { "http://" };
2099 let Some(rest) = href.strip_prefix(scheme) else { return false };
2100 let (host, path) = match rest.find('/') {
2101 Some(i) => rest.split_at(i),
2102 None => (rest, "/"),
2103 };
2104 if host != self.current_host {
2105 return false;
2106 }
2107 let (path_only, frag) = match path.split_once('#') {
2108 Some((p, f)) => (p, Some(f)),
2109 None => (path, None),
2110 };
2111 if path_only == self.current_path {
2112 return false;
2113 }
2114 self.current_path = String::from(path_only);
2115 self.current_url_with_hash = match frag {
2116 Some(f) => alloc::format!("{}{}{}#{}", scheme, host, path_only, f),
2117 None => alloc::format!("{}{}{}", scheme, host, path_only),
2118 };
2119 true
2120 }
2121
2122 pub fn get_url(&self) -> String {
2123 if url_resolve::is_about_host(&self.current_host) {
2125 return self.current_host.clone();
2126 }
2127 let schema = if self.current_is_https {
2128 "https://"
2129 } else {
2130 "http://"
2131 };
2132 alloc::format!("{}{}{}", schema, self.current_host, self.current_path)
2133 }
2134
2135 fn load_about_page(&mut self, host: &str) {
2138 crate::warn!("[BROWSER] built-in page host={}", host);
2141 self.current_is_https = false;
2142 self.current_host = String::from(host);
2143 self.current_path = String::new();
2144 self.current_url_with_hash = String::from(host);
2145 self.loading = false;
2146 ASYNC_LOAD
2148 .lock()
2149 .requests
2150 .retain(|r| r.owner != self.engine_id);
2151 let html = if host == "about:blank" {
2152 self.title = String::from("about:blank");
2153 String::from("<html><head></head><body></body></html>")
2154 } else {
2155 self.title = String::from("Not Found");
2156 alloc::format!(
2157 "<html><head><title>Not Found</title></head><body style=\"background-color: #282a36; color: #f8f8f2;\"><h1>Not Found</h1><p>Unknown page: {}</p></body></html>",
2158 host.replace('<', "<").replace('>', ">")
2159 )
2160 };
2161 let top = self.top_offset;
2162 self.parse_and_layout(&html, None, top, self.win_w, self.win_h);
2163 self.dirty = true;
2164 self.dirty_reason = "mod.rs:about";
2165 }
2166
2167 pub fn load_page(
2169 &mut self,
2170 is_https: bool,
2171 host: &str,
2172 path: &str,
2173 save_history: bool,
2174 _top_offset: i32,
2175 ) {
2176 self.load_page_with_method(is_https, host, path, save_history, "GET", None);
2177 }
2178
2179 pub fn load_page_post(
2180 &mut self,
2181 is_https: bool,
2182 host: &str,
2183 path: &str,
2184 body: &str,
2185 _top_offset: i32,
2186 ) {
2187 self.load_page_with_method(is_https, host, path, true, "POST", Some(String::from(body)));
2188 }
2189
2190 fn load_page_with_method(
2191 &mut self,
2192 is_https: bool,
2193 host: &str,
2194 path: &str,
2195 save_history: bool,
2196 method: &str,
2197 body: Option<String>,
2198 ) {
2199 self.scripts_ran_for = None;
2201 let referer = self.pending_referer.take();
2203 self.referrer = referer.clone().unwrap_or_default();
2204 self.child_frames.clear();
2206 let (path, frag) = match path.split_once('#') {
2214 Some((p, f)) => (p, String::from(f)),
2215 None => (path, String::new()),
2216 };
2217 let path = if path.is_empty() { "/" } else { path };
2218 self.pending_fragment = frag;
2219
2220 self.video_playing = false;
2221 stop_video_playback();
2222 self.reset_js_for_new_document();
2223 self.dom_contents.clear();
2224 self.dom_needs_rebuild = true;
2225 self.external_css_cache = None;
2227 self.pending_link_css.clear();
2228 self.external_css_counts = None;
2229 self.cached_stylesheet = None;
2230 self.cached_rule_index = None;
2231 self.cached_css_hash = None;
2232 self.inline_style_memo.clear();
2233 IMAGE_QUEUE
2236 .lock()
2237 .pending
2238 .retain(|r| r.owner != self.engine_id);
2239 self.form_values.clear();
2241 self.initial_form_values.clear();
2242 self.field_names.clear();
2243 if save_history {
2244 self.history.push((
2245 self.current_is_https,
2246 self.current_host.clone(),
2247 self.current_path.clone(),
2248 ));
2249 self.forward_history.clear();
2250 }
2251
2252 if url_resolve::is_about_host(host) {
2254 self.load_about_page(host);
2255 return;
2256 }
2257 crate::warn!("[BROWSER] load host={} https={}", host, is_https);
2261
2262 if host == "localhost" {
2263 self.current_is_https = false;
2264 self.current_host = String::from("localhost");
2265 self.current_path = String::from(path);
2266 self.current_url_with_hash = alloc::format!("http://localhost{}", path);
2267
2268 let clean_path = path.strip_prefix('/').unwrap_or(path);
2269 if clean_path == "home" || clean_path.is_empty() {
2270 self.title = String::from("AtmOS Browser");
2271 let html = HOME_HTML;
2272 self.parse_and_layout(html, None, self.top_offset, self.win_w, self.win_h);
2273 self.dirty = true;
2274 self.dirty_reason = "mod.rs:1513";
2275 } else {
2276 let actual_path = if path.starts_with('/') {
2277 String::from(path)
2278 } else {
2279 alloc::format!("/{}", path)
2280 };
2281 let loaded_res = {
2293 let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
2294 crate::kernel::fs::get_fs().read_file_checked(&actual_path)
2295 };
2296 match loaded_res {
2297 Ok(Some((_meta, content))) => {
2298 if let Ok(html) = core::str::from_utf8(&content) {
2299 self.title = alloc::format!("Local: {}", clean_path);
2300 self.parse_and_layout(html, None, self.top_offset, self.win_w, self.win_h);
2301 self.dirty = true;
2302 self.dirty_reason = "mod.rs:1525";
2303 } else {
2304 let err_html = alloc::format!("<html><title>Load Error</title><body style=\"background-color: #282a36; color: #ff5555;\"><h1>UTF-8 Decode Failed</h1><p>File '{}' is not valid UTF-8.</p></body></html>", actual_path);
2305 self.title = String::from("Load Error");
2306 self.parse_and_layout(&err_html, None, self.top_offset, self.win_w, self.win_h);
2307 self.dirty = true;
2308 self.dirty_reason = "mod.rs:1530";
2309 }
2310 }
2311 Ok(None) => {
2312 let err_html = alloc::format!("<html><title>Not Found</title><body style=\"background-color: #282a36; color: #ff5555;\"><h1>404 Not Found</h1><p>Local file '{}' not found in SylFS.</p></body></html>", actual_path);
2313 self.title = String::from("404 Not Found");
2314 self.parse_and_layout(&err_html, None, self.top_offset, self.win_w, self.win_h);
2315 self.dirty = true;
2316 self.dirty_reason = "mod.rs:1536";
2317 }
2318 Err(e) => {
2319 let err_html = alloc::format!("<html><title>Read Error</title><body style=\"background-color: #282a36; color: #ff5555;\"><h1>Failed to read file</h1><p>Local file '{}' could not be read: {}</p></body></html>", actual_path, e);
2320 self.title = String::from("Read Error");
2321 self.parse_and_layout(&err_html, None, self.top_offset, self.win_w, self.win_h);
2322 self.dirty = true;
2323 self.dirty_reason = "mod.rs:1542";
2324 }
2325 }
2326 }
2327 return;
2328 }
2329
2330 self.current_is_https = is_https;
2335 self.current_host = String::from(host);
2336 self.current_path = String::from(path);
2337 let scheme0 = if is_https { "https://" } else { "http://" };
2339 self.current_url_with_hash = alloc::format!("{}{}{}", scheme0, host, path);
2340
2341 let schema = if is_https { "https://" } else { "http://" };
2342 crate::info!(
2343 "BROWSER: Loading page {} {}{}{} (Async)",
2344 method,
2345 schema,
2346 host,
2347 path
2348 );
2349
2350 self.loading = true;
2351 self.loading_tick = 0;
2352
2353 let req = AsyncLoadRequest {
2354 owner: self.engine_id,
2355 group: crate::kernel::scheduler::current_mem_group(),
2356 is_https,
2357 host: String::from(host),
2358 path: String::from(path),
2359 method: String::from(method),
2360 body,
2361 referer,
2362 status: 1, result_body: None,
2364 result_dom: None,
2365 error_msg: None,
2366 };
2367
2368 let need_spawn = {
2369 let mut lock = ASYNC_LOAD.lock();
2370 lock.requests.retain(|r| r.owner != self.engine_id);
2372 lock.requests.push(req);
2373 if !lock.thread_active {
2374 lock.thread_active = true;
2375 true
2376 } else {
2377 false
2378 }
2379 };
2380
2381 if need_spawn {
2383 let pid = crate::kernel::scheduler::spawn_shared_with_stack(
2390 async_load_thread_entry,
2391 crate::kernel::scheduler::Priority::High,
2392 "browser_loader",
2393 crate::kernel::scheduler::LARGE_STACK_SIZE,
2394 );
2395 if pid == 0 {
2396 crate::warn!("[NET] ローダースレッドを起動できません(ヒープ不足)");
2397 ASYNC_LOAD.lock().thread_active = false;
2398 }
2399 }
2400 self.dirty = true;
2401 self.dirty_reason = "mod.rs:1595";
2402 }
2403
2404 pub fn set_dom_content(&mut self, id: &str, val: &str) {
2405 self.dom_contents
2406 .insert(String::from(id), String::from(val));
2407 let html = self.last_html.clone();
2408 let top_offset = self.top_offset;
2409 let win_w = self.win_w;
2410 let win_h = self.win_h;
2411 self.parse_and_layout(&html, None, top_offset, win_w, win_h);
2412 self.dirty = true;
2413 self.dirty_reason = "mod.rs:1606";
2414 }
2415
2416 pub fn go_back(&mut self, _top_offset: i32) {
2418 if self.js_runtime.has_spa_back() {
2420 if let Some(url) = self.js_runtime.spa_go_back() {
2421 let (is_https, host, path) = self.resolve_url_parts(&url);
2423 self.current_is_https = is_https;
2424 self.current_host = host;
2425 self.current_path = path;
2426 self.dirty = true;
2427 self.dirty_reason = "mod.rs:1619";
2428 }
2429 return;
2430 }
2431 if let Some((prev_is_https, prev_host, prev_path)) = self.history.pop() {
2433 self.forward_history.push((
2434 self.current_is_https,
2435 self.current_host.clone(),
2436 self.current_path.clone(),
2437 ));
2438 self.load_page_with_method(prev_is_https, &prev_host, &prev_path, false, "GET", None);
2439 }
2440 }
2441
2442 pub fn go_forward(&mut self, _top_offset: i32) {
2443 if self.js_runtime.has_spa_forward() {
2445 if let Some(url) = self.js_runtime.spa_go_forward() {
2446 let (is_https, host, path) = self.resolve_url_parts(&url);
2447 self.current_is_https = is_https;
2448 self.current_host = host;
2449 self.current_path = path;
2450 self.dirty = true;
2451 self.dirty_reason = "mod.rs:1642";
2452 }
2453 return;
2454 }
2455 if let Some((fwd_is_https, fwd_host, fwd_path)) = self.forward_history.pop() {
2457 self.history.push((
2458 self.current_is_https,
2459 self.current_host.clone(),
2460 self.current_path.clone(),
2461 ));
2462 self.load_page_with_method(fwd_is_https, &fwd_host, &fwd_path, false, "GET", None);
2463 }
2464 }
2465
2466 pub fn process_pending_reset(&mut self) -> bool {
2469 match self.js_runtime.take_pending_reset() {
2470 Some(fi) => {
2471 self.reset_form_node(fi);
2472 true
2473 }
2474 None => false,
2475 }
2476 }
2477
2478 pub fn can_go_back(&self) -> bool {
2479 !self.history.is_empty()
2480 }
2481 pub fn can_go_forward(&self) -> bool {
2482 !self.forward_history.is_empty()
2483 }
2484
2485 pub fn process_pending_nav(&mut self, top_offset: i32) -> bool {
2489 let delta = self.js_runtime.take_pending_nav();
2490 if delta == 0 {
2491 return false;
2492 }
2493 let mut navigated = false;
2494 if delta < 0 {
2495 for _ in 0..(-delta) {
2496 if !self.can_go_back() {
2497 break;
2498 }
2499 self.go_back(top_offset);
2500 navigated = true;
2501 }
2502 } else {
2503 for _ in 0..delta {
2504 if !self.can_go_forward() {
2505 break;
2506 }
2507 self.go_forward(top_offset);
2508 navigated = true;
2509 }
2510 }
2511 if navigated {
2512 let url = self.get_url();
2514 self.js_runtime.set_page_url(&url);
2515 self.js_runtime.fire_popstate();
2516 }
2517 navigated
2518 }
2519
2520 pub fn process_pending_location(&mut self, top_offset: i32) -> bool {
2523 let req = self.js_runtime.take_pending_location();
2524 let (url, mode) = match req {
2525 Some(v) => v,
2526 None => return false,
2527 };
2528 match mode.as_str() {
2529 "hash" => {
2531 let frag = match url.split_once('#') {
2532 Some((_, f)) => alloc::format!("#{}", f),
2533 None => String::from("#"),
2534 };
2535 self.navigate_to_fragment(&frag);
2536 true
2537 }
2538 "replace" => {
2540 let (is_https, host, path) = self.resolve_url_parts(&url);
2541 self.load_page(is_https, &host, &path, false, top_offset);
2542 let new_url = self.get_url();
2543 self.js_runtime.set_page_url(&new_url);
2544 true
2545 }
2546 "reload" => {
2548 let is_https = self.current_is_https;
2549 let host = self.current_host.clone();
2550 let path = self.current_path.clone();
2551 self.load_page(is_https, &host, &path, false, top_offset);
2552 true
2553 }
2554 _ => {
2556 self.navigate_to_href(&url, top_offset);
2557 let new_url = self.get_url();
2558 self.js_runtime.set_page_url(&new_url);
2559 true
2560 }
2561 }
2562 }
2563}