Skip to main content

atmos/os_lib/aura/builtins/
system.rs

1// 分割: aura/builtins.rs より機械的に移動(2026-07-16 リファクタ フェーズ6)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5/// ICMP Echo Request (Ping) を送信するビルトイン関数。
6/// IPアドレスの他、ホスト名(ドメイン名)が指定された場合は自動的に DNS 解決を試みます。
7pub(crate) fn builtin_ping(env: &mut Env, args: &[AST]) -> Result<Value, String> {
8    let vals = eval_args(env, args)?;
9    if vals.is_empty() {
10        return Err(String::from("USAGE: ping(\"host_or_ip\")"));
11    }
12    let ip_s = unquote(&vals[0]);
13
14    // まず指定された文字列をIPv4アドレスとしてパースを試みる
15    let dst_ip = match crate::kernel::net::parse_ipv4(&ip_s) {
16        Some(ip) => ip,
17        None => {
18            // パースに失敗した場合(ドメイン名が指定されたと判断)、DNS Aレコードの解決(UDP経由)を試みる
19            match crate::kernel::net::dns_query_a_via_udp(&ip_s) {
20                Ok(ip) => ip,
21                Err(e) => {
22                    return Err(alloc::format!(
23                        "ERROR: invalid IPv4 address or DNS query failed: {}",
24                        e
25                    ))
26                }
27            }
28        }
29    };
30
31    match crate::kernel::net::ping_once_real(dst_ip) {
32        Ok((seq, rtt_ms, bytes)) => Ok(Value::Str(alloc::format!(
33            "PING {}: seq={} bytes={} time={}ms",
34            crate::kernel::net::format_ipv4(dst_ip),
35            seq,
36            bytes,
37            rtt_ms
38        ))),
39        Err(e) => Err(alloc::format!("PING error: {}", e)),
40    }
41}
42
43/// アプリケーション起動時のウィンドウ初期化用設定パラメータ
44pub(crate) struct WindowLaunchConfig {
45    /// ウィンドウ表示状態 ("normal" / "maximized" / "minimized" / "fullscreen")
46    state: &'static str,
47    /// 通常(normal)表示時のデフォルトの幅
48    width: u32,
49    /// 通常(normal)表示時のデフォルトの高さ
50    height: u32,
51    /// デフォルトの左上X座標 (通常表示時の原点位置)
52    def_x: i32,
53    /// デフォルトの左上Y座標 (通常表示時の原点位置)
54    def_y: i32,
55}
56
57/// アプリ起動引数からウィンドウ状態およびサイズに関するオプションをパースするヘルパー関数
58///
59/// 状態オプション(normal 等)やサイズ指定(800x600 等)はアプリ本体への引数から除去されます。
60pub(crate) fn parse_launch_options(
61    app_args: &[Value],
62    raw_name: &str,
63    manifest: &crate::kernel::app_sandbox::AppManifest,
64) -> (Vec<Value>, WindowLaunchConfig) {
65    let mut state = "maximized"; // デフォルトは最大化
66    let mut custom_size = None;
67    let mut cleaned_args = alloc::vec![];
68
69    for val in app_args {
70        let s = unquote(val);
71        if s == "normal" || s == "maximized" || s == "minimized" || s == "fullscreen" {
72            state = if s == "normal" {
73                "normal"
74            } else if s == "maximized" {
75                "maximized"
76            } else if s == "minimized" {
77                "minimized"
78            } else {
79                "fullscreen"
80            };
81        } else if let Some((left, right)) = s.split_once('x') {
82            if let (Ok(w), Ok(h)) = (left.parse::<u32>(), right.parse::<u32>()) {
83                custom_size = Some((w, h));
84                state = "normal"; // サイズ直接指定があれば自動的に通常状態
85            } else {
86                cleaned_args.push(val.clone());
87            }
88        } else {
89            cleaned_args.push(val.clone());
90        }
91    }
92
93    let (def_w, def_h) = if let Some((w, h)) = custom_size {
94        (w, h)
95    } else if let (Some(w), Some(h)) = (manifest.width, manifest.height) {
96        (w, h)
97    } else {
98        (500, 600)
99    };
100
101    let (def_x, def_y) = match raw_name {
102        "browser" => (100, 100),
103        "note" => (150, 150),
104        "settings" => (150, 100),
105        "music" => (180, 120),
106        "files" => (140, 90),
107        "drive" => (160, 110),
108        "onedrive" => (170, 120),
109        _ => (100, 100),
110    };
111
112    (
113        cleaned_args,
114        WindowLaunchConfig {
115            state,
116            width: def_w,
117            height: def_h,
118            def_x,
119            def_y,
120        },
121    )
122}
123
124/// 解析された `WindowLaunchConfig` に従ってウィンドウオブジェクトを生成し、WindowManager に登録する
125pub(crate) fn create_and_register_window(
126    config: WindowLaunchConfig,
127    title: &str,
128    app: Box<dyn crate::kernel::window_mgr::App>,
129) {
130    let (sw, sh) = unsafe {
131        if let Some(screen) = crate::CURRENT_SCREEN.as_ref() {
132            (screen.width, screen.height)
133        } else {
134            (1024, 768) // 画面が取得できない場合の安全なデフォルトフォールバック
135        }
136    };
137
138    let (win_x, win_y, win_w, win_h, is_fs, is_min) = match config.state {
139        "normal" => (
140            config.def_x,
141            config.def_y,
142            config.width,
143            config.height,
144            false,
145            false,
146        ),
147        "fullscreen" => (0, 0, sw, sh, true, false),
148        "minimized" => (
149            config.def_x,
150            config.def_y,
151            config.width,
152            config.height,
153            false,
154            true,
155        ),
156        _ => {
157            // maximized: 画面最下部の常時表示 F キー帯(BAR_HEIGHT)を除いた表示領域を使う。
158            let avail_h = sh.saturating_sub(crate::kernel::fn_bar::BAR_HEIGHT);
159            (0, 0, sw, avail_h, false, false)
160        }
161    };
162
163    // ProxyApp を使用して、アプリケーションスレッドを Core 2 または 3 で非同期に立ち上げる
164    use alloc::sync::Arc;
165    use spin::Mutex;
166    use core::sync::atomic::AtomicBool;
167    use crate::kernel::window_mgr::{ProxyApp, AppRunnerParams, app_runner_entry};
168
169    let shared_buf = Arc::new(Mutex::new(alloc::vec![0u32; (win_w * win_h) as usize]));
170    let event_q = Arc::new(Mutex::new(alloc::vec![]));
171    let is_alive = Arc::new(AtomicBool::new(true));
172    let active_tab = Arc::new(Mutex::new(0));
173    let tabs = Arc::new(Mutex::new(app.tabs()));
174    let needs_timer_redraw = Arc::new(AtomicBool::new(true));
175    // app_runner 側が shared_buffer を更新した際に Core 0 の dirty 判定へ伝達するフラグ
176    let buffer_updated = Arc::new(AtomicBool::new(false));
177    let app_name = app.name();
178
179    let live_title = alloc::sync::Arc::new(spin::Mutex::new(None));
180    let proxy = ProxyApp::new(
181        app_name,
182        shared_buf.clone(),
183        event_q.clone(),
184        is_alive.clone(),
185        active_tab.clone(),
186        tabs.clone(),
187        live_title.clone(),
188        needs_timer_redraw.clone(),
189        buffer_updated.clone(),
190    );
191
192    let params = Box::new(AppRunnerParams {
193        app,
194        shared_buffer: shared_buf,
195        event_queue: event_q,
196        is_alive,
197        active_tab,
198        tabs,
199        live_title,
200        needs_timer_redraw,
201        buffer_updated,
202        heartbeat_ms: proxy.heartbeat_ms.clone(),
203        tab_kill: proxy.tab_kill.clone(),
204        running_tab: proxy.running_tab.clone(),
205        width: win_w,
206        height: win_h,
207    });
208    let params_ptr = Box::into_raw(params) as usize;
209
210    static mut NEXT_APP_CORE: usize = 2;
211    let target_core = unsafe {
212        let c = NEXT_APP_CORE;
213        NEXT_APP_CORE = if c == 2 { 3 } else { 2 };
214        c
215    };
216
217    // アプリ(ブラウザ)の描画の中で JS(iframe の子フレームを含む)が走るので、
218    // JS 用の大きなスタックで起動する(`scheduler::LARGE_STACK_SIZE`)。
219    crate::kernel::scheduler::spawn_with_arg_on_core_with_stack(
220        app_runner_entry,
221        params_ptr,
222        crate::kernel::scheduler::Priority::Normal,
223        "app_runner",
224        target_core,
225        crate::kernel::scheduler::LARGE_STACK_SIZE,
226    );
227
228    let mut win = crate::kernel::window_mgr::Window::new(win_x, win_y, win_w, win_h, title, Box::new(proxy));
229    if config.state == "maximized" || config.state == "fullscreen" {
230        win.saved_x = config.def_x;
231        win.saved_y = config.def_y;
232        win.saved_w = config.width;
233        win.saved_h = config.height;
234    }
235    win.is_fullscreen = is_fs;
236    win.is_minimized = is_min;
237    crate::kernel::window_mgr::get_instance().add_window(win);
238}
239
240/// アプリを OS のメインループではなくアプリのスレッド(`app_runner`、`ProxyApp`)で開く(2026-11-18、TODO R3)。
241/// ほかのアプリ(files など)が直接 `Window::new` + `add_window` で開くと、そのアプリの描画・入力・JS・
242/// 同期の取得(`<script src>` など)が OS のメインループ(`gui_shell`)の上で走り、遅い相手に OS ごと待たされる。
243pub(crate) fn launch_in_app_thread(
244    x: i32,
245    y: i32,
246    w: u32,
247    h: u32,
248    title: &str,
249    app: Box<dyn crate::kernel::window_mgr::App>,
250) {
251    let config = WindowLaunchConfig { state: "normal", width: w, height: h, def_x: x, def_y: y };
252    create_and_register_window(config, title, app);
253}
254
255pub(crate) fn builtin_sys_launch_gui(env: &mut Env, args: &[AST]) -> Result<Value, String> {
256    let vals = eval_args(env, args)?;
257    if vals.is_empty() {
258        return Err(String::from(
259            "USAGE: sys_launch_gui(\"app_name\" [\"args\"])",
260        ));
261    }
262    let raw_name = unquote(&vals[0]);
263
264    // unpack arguments if passed as a single list (which ARGS would be)
265    let app_args = if vals.len() > 1 {
266        if let Value::List(l) = &vals[1] {
267            l.clone()
268        } else {
269            vals[1..].to_vec()
270        }
271    } else {
272        alloc::vec![]
273    };
274
275    let manifest_path = alloc::format!("/apps/{}/manifest.json", raw_name);
276    let fs = crate::kernel::fs::get_fs();
277    let manifest = match fs.read_file_checked(&manifest_path) {
278        Ok(Some((_meta, manifest_bytes))) => core::str::from_utf8(&manifest_bytes)
279            .ok()
280            .and_then(crate::kernel::app_sandbox::AppManifest::parse)
281            .unwrap_or_default(),
282        Ok(None) => crate::kernel::app_sandbox::AppManifest::default(),
283        Err(e) => {
284            crate::warn!("[SYS] failed to read manifest '{}': {}", manifest_path, e);
285            crate::kernel::app_sandbox::AppManifest::default()
286        }
287    };
288
289    let (cleaned_args, config) = parse_launch_options(&app_args, &raw_name, &manifest);
290
291    if raw_name == "browser" && !cleaned_args.is_empty() {
292        // 2 度目の起動で URL が付いていたら、既存のブラウザの新しいタブで開く(ウィンドウは 1 つのまま。2026-11-18)。
293        // 以前は URL が捨てられ、既存のウィンドウが前に出るだけだった。
294        let mut wm = crate::kernel::window_mgr::get_instance();
295        let (existing, stopped) = match wm.existing_window_state("browser") {
296            Some(st) => (true, st),
297            None => (false, false),
298        };
299        if crate::kernel::launch_policy::decide(existing, stopped, true)
300            == crate::kernel::launch_policy::LaunchAction::OpenInNewTab
301        {
302            let url_arg = unquote(&cleaned_args[0]);
303            if wm.open_url_in_existing("browser", &url_arg) {
304                return Ok(Value::Str(String::from("Opened in new tab")));
305            }
306        }
307    }
308    if raw_name == "browser" {
309        let mut app = crate::apps::browser::WebBrowser::new();
310        let top = app.top_offset();
311        let win_title = if cleaned_args.is_empty() {
312            String::from("Browser - AtmOS")
313        } else {
314            let url_arg = unquote(&cleaned_args[0]);
315            if url_arg.starts_with('/') {
316                match fs.read_file_checked(&url_arg) {
317                    Ok(Some((_meta, content))) => {
318                        if let Ok(html) = core::str::from_utf8(&content) {
319                            app.engine.load_html(html, &url_arg, top);
320                        } else {
321                            app.engine.load_html(
322                                "<html><body><h1>Invalid UTF-8 in local file</h1></body></html>",
323                                &url_arg,
324                                top,
325                            );
326                        }
327                    }
328                    Ok(None) => {
329                        app.engine.load_html(
330                            "<html><body><h1>File not found</h1></body></html>",
331                            &url_arg,
332                            top,
333                        );
334                    }
335                    Err(e) => {
336                        let err_html = alloc::format!(
337                            "<html><body><h1>Failed to read file</h1><p>{}</p></body></html>",
338                            e
339                        );
340                        app.engine.load_html(&err_html, &url_arg, top);
341                    }
342                }
343            } else if let Some(about) = crate::os_lib::web_engine::url_resolve::normalize_about(&url_arg) {
344                // 【2026-11-17】`about:blank` 等はネットワークへ出さない内蔵ページ。
345                app.engine.load_page(false, &about, "", false, top);
346            } else {
347                let mut is_https = false;
348                let clean_url = if let Some(rest) = url_arg.strip_prefix("http://") {
349                    rest
350                } else if let Some(rest) = url_arg.strip_prefix("https://") {
351                    is_https = true;
352                    rest
353                } else {
354                    &url_arg
355                };
356                let parts: Vec<&str> = clean_url.splitn(2, '/').collect();
357                let host = parts[0];
358                let path = if parts.len() > 1 {
359                    alloc::format!("/{}", parts[1])
360                } else {
361                    String::from("/")
362                };
363                app.engine.load_page(is_https, host, &path, false, top);
364            }
365            alloc::format!("Browser - {}", url_arg)
366        };
367        create_and_register_window(config, &win_title, Box::new(app));
368        return Ok(Value::Str(String::from("Launched Browser")));
369    } else if raw_name == "note" {
370        let file_arg = if !cleaned_args.is_empty() {
371            unquote(&cleaned_args[0])
372        } else {
373            String::from("Untitled")
374        };
375        let app = if file_arg != "Untitled" {
376            let content = match fs.read_file_checked(&file_arg) {
377                Ok(Some((_meta, bytes))) => {
378                    core::str::from_utf8(&bytes).ok().map(String::from).unwrap_or_default()
379                }
380                Ok(None) => String::new(),
381                Err(e) => {
382                    crate::warn!("[SYS] failed to read note file '{}': {}", file_arg, e);
383                    String::new()
384                }
385            };
386            crate::apps::note::NoteApp::open_file(&file_arg, &content)
387        } else {
388            crate::apps::note::NoteApp::new()
389        };
390        create_and_register_window(
391            config,
392            &alloc::format!("Note - {}", file_arg),
393            Box::new(app),
394        );
395        return Ok(Value::Str(String::from("Launched Note")));
396    } else if raw_name == "settings" {
397        let app = crate::apps::settings::SettingsApp::new();
398        create_and_register_window(config, "OS Settings", Box::new(app));
399        return Ok(Value::Str(String::from("Launched OS Settings App")));
400    } else if raw_name == "music" {
401        let app = crate::apps::music::MusicApp::new();
402        create_and_register_window(config, "Music Player", Box::new(app));
403        return Ok(Value::Str(String::from("Launched Music Player App")));
404    } else if raw_name == "files" {
405        let app = crate::apps::files::FilesApp::new();
406        create_and_register_window(config, "Files", Box::new(app));
407        return Ok(Value::Str(String::from("Launched Files App")));
408    } else if raw_name == "drive" {
409        let app = crate::apps::drive::DriveApp::new();
410        create_and_register_window(config, "Google Drive", Box::new(app));
411        return Ok(Value::Str(String::from("Launched Google Drive App")));
412    } else if raw_name == "onedrive" {
413        let app = crate::apps::onedrive::OneDriveApp::new();
414        create_and_register_window(config, "OneDrive", Box::new(app));
415        return Ok(Value::Str(String::from("Launched OneDrive App")));
416    } else if raw_name == "eldemo" {
417        crate::kernel::scheduler::spawn_user_on_core(
418            crate::user_pixel_demo,
419            crate::kernel::scheduler::Priority::Normal,
420            "el0_pixel_demo",
421            0,
422        );
423        return Ok(Value::Str(String::from(
424            "Launched EL0 Pixel Demo (sandboxed)",
425        )));
426    }
427
428    Err(alloc::format!("Unknown native GUI app: {}", raw_name))
429}
430
431pub(crate) fn builtin_settings(env: &mut Env, args: &[AST]) -> Result<Value, String> {
432    let vals = eval_args(env, args)?;
433    let manifest = crate::kernel::app_sandbox::AppManifest::default();
434    let (_cleaned, config) = parse_launch_options(&vals, "settings", &manifest);
435    let app = crate::apps::settings::SettingsApp::new();
436    create_and_register_window(config, "OS Settings", Box::new(app));
437    Ok(Value::Str(String::from("Launched OS Settings App")))
438}
439
440pub(crate) fn builtin_music(env: &mut Env, args: &[AST]) -> Result<Value, String> {
441    let vals = eval_args(env, args)?;
442    let manifest = crate::kernel::app_sandbox::AppManifest::default();
443    let (_cleaned, config) = parse_launch_options(&vals, "music", &manifest);
444    let app = crate::apps::music::MusicApp::new();
445    create_and_register_window(config, "Music Player", Box::new(app));
446    Ok(Value::Str(String::from("Launched Music Player App")))
447}
448
449pub(crate) fn builtin_files(env: &mut Env, args: &[AST]) -> Result<Value, String> {
450    let vals = eval_args(env, args)?;
451    let manifest = crate::kernel::app_sandbox::AppManifest::default();
452    let (_cleaned, config) = parse_launch_options(&vals, "files", &manifest);
453    let app = crate::apps::files::FilesApp::new();
454    create_and_register_window(config, "Files", Box::new(app));
455    let cwd = if let Some(Value::Str(c)) = env.get("cwd") {
456        c.clone()
457    } else {
458        String::from("/user/")
459    };
460    Ok(Value::Str(alloc::format!(
461        "FILES: Opened Files window in {}",
462        cwd
463    )))
464}
465
466pub(crate) fn builtin_help(env: &mut Env, args: &[AST]) -> Result<Value, String> {
467    // help("net") のようにカテゴリを指定すると詳細を表示する
468    let topic = if !args.is_empty() {
469        let vals = eval_args(env, args)?;
470        unquote(&vals[0]).to_lowercase()
471    } else {
472        String::new()
473    };
474
475    let mut out = String::new();
476    match topic.as_str() {
477        "net" | "network" => {
478            out.push_str("Network (net.*)\n");
479            out.push_str("  net.info                  show interface / IP / link state\n");
480            out.push_str("  net.nic                   NIC + DHCP debug info\n");
481            out.push_str("  net.dhcp(\"show\"|\"start\"|\"renew\"|\"release\")  DHCP client\n");
482            out.push_str("  net.ping(\"ip\")            send ICMP echo\n");
483            out.push_str("  net.dns(\"host\")           resolve hostname via DNS\n");
484            out.push_str("  net.ntp                   sync wall clock via NTP\n");
485            out.push_str("  net.http(\"get\" host [path])      HTTP GET\n");
486            out.push_str("  net.http(\"post\" host path ct body)  HTTP POST\n");
487            out.push_str("  net.https(\"get\" host [path])     HTTPS GET (TLS 1.3)\n");
488            out.push_str("  cache.stats() / cache.clear()     HTTP response cache management\n");
489            out.push_str("  net.tcp(...)  net.udp(...)  net.arp(...)  low-level\n");
490        }
491        "fs" | "file" | "files" => {
492            out.push_str("Files (top-level + fs.*)\n");
493            out.push_str("  ls [dir]   cd <dir>   pwd   mkdir <dir>\n");
494            out.push_str("  cp <src> <dst>   mv <src> <dst>   rm <path>\n");
495            out.push_str("  rename <old> <new>   truncate <file> <size>   stat <file>\n");
496            out.push_str("  cat <file>   head <file>   tail <file>   grep \"pat\" <file>\n");
497            out.push_str("  fs.save(name \"data\" \"labels\")   save labelled file\n");
498            out.push_str("  fs.find(\"l1,l2\" [\"and\"|\"or\"])   find files by label(s)\n");
499            out.push_str("  fs.addlabel(name \"label\")       add label to a file\n");
500            out.push_str("  fs.setlabel(name \"labels\")      set labels for a file\n");
501            out.push_str("  fs.labels([name])                list all labels or file labels\n");
502            out.push_str("  fs.stat(name)                    get file extent and sector stats\n");
503            out.push_str("  (these also exist under fs.* and os.*)\n");
504        }
505        "math" => {
506            out.push_str("Math (math.*) — arbitrary-precision\n");
507            out.push_str("  abs sign sqrt exp log2 log10  factorial random\n");
508            out.push_str("  sin cos tan  arc-sin arc-cos arc-tan  hyp-sin ...\n");
509            out.push_str("  greatest-com-div  least-com-mul  odd even\n");
510            out.push_str("  complex real-part imag-part  numerator denominator\n");
511            out.push_str("  PI EULER   bit.and/or/xor/not/l-shift/r-shift\n");
512        }
513        "cloud" | "drive" | "gh" | "github" => {
514            out.push_str("Cloud (Phase 7 — Google Drive / GitHub)\n");
515            out.push_str("  drive ls [folder_id]      list Drive files (root, or a folder id)\n");
516            out.push_str("  drive cat <file_id>       print a Drive file's text content\n");
517            out.push_str("  drive download <id> <name>  save a Drive file's raw bytes locally\n");
518            out.push_str("  drive rm <file_id>        delete a Drive file\n");
519            out.push_str("  drive.upload(name content)  create a new text file (no shell alias)\n");
520            out.push_str("  (Drive login is device-flow via the 'drive' app: run(\"drive\"))\n");
521            out.push_str("  gh login <client_id>      request a GitHub device code\n");
522            out.push_str("  gh poll                   finish login after authorizing in browser\n");
523            out.push_str("  gh user                   show the authenticated GitHub user\n");
524            out.push_str("  gh repos                  list the authenticated user's repos\n");
525            out.push_str("  gh logout                 discard the stored GitHub token\n");
526        }
527        "script" | "lang" | "aura" => {
528            out.push_str("Aura basics\n");
529            out.push_str("  set x 10        define / assign a variable\n");
530            out.push_str("  fn(a b ...)     lambda;  func name fn(...)  named\n");
531            out.push_str("  print x   type x   if(c t e)   while(c body)   for(...)\n");
532            out.push_str("  list/cons/car/cdr/map/filter/fold/range/take\n");
533            out.push_str("  str.split/join/substring/length/replace\n");
534            out.push_str("  load(\"f.aura\")  require(\"f.aura\")   run a script file\n");
535            out.push_str("  arithmetic: + - * /   compare: = != < <= > >=   and or not\n");
536        }
537        "" => {
538            out.push_str("AtmOS Terminal — type a command, then Enter.\n");
539            out.push_str("Strings need quotes. `help(\"net\")` for category detail.\n");
540            out.push_str("---------------------------------------------------------------\n");
541            out.push_str("Apps     browser  note  files  music  settings  (type the name)\n");
542            out.push_str("Files    ls cd pwd mkdir cp mv rm cat head tail grep   help(\"fs\")\n");
543            out.push_str("Network  net.info  net.ping  net.dns  net.dhcp  net.https\n");
544            out.push_str("                                                     help(\"net\")\n");
545            out.push_str("System   os.apps  os.run(\"app\")  os.kill(\"app\")  os.keymap(\"us\"|\"jis\")\n");
546            out.push_str("         os.settings  os.keyrepeat  date  ntp\n");
547            out.push_str("Media    sound.play(freq ms)  sound.play_mml(\"mml\")\n");
548            out.push_str("         draw.boxfill  draw.draw_string  draw.clear_screen\n");
549            out.push_str(
550                "Script   set print if while for fn  list/map/filter   help(\"script\")\n",
551            );
552            out.push_str("Math     math.sin math.sqrt ...  str.* bit.*   help(\"math\")\n");
553            out.push_str("Cloud    drive ls  drive cat <id>  gh user  gh repos   help(\"cloud\")\n");
554            out.push_str("---------------------------------------------------------------\n");
555            out.push_str("Tip: Esc exits the browser. F1 focuses the terminal.");
556        }
557        other => {
558            out.push_str(&alloc::format!("help: unknown topic '{}'.\n", other));
559            out.push_str("Try: help  |  help(\"net\")  |  help(\"fs\")  |  help(\"math\")  |  help(\"script\")  |  help(\"cloud\")");
560        }
561    }
562    Ok(Value::Str(out))
563}
564
565pub(crate) fn get_num_u32(val: &Value) -> Result<u32, String> {
566    match val {
567        Value::Num(n) => {
568            let s = n.to_string();
569            Ok(s.parse::<u32>().unwrap_or(0))
570        }
571        _ => Err(String::from("expected number")),
572    }
573}
574
575pub(crate) fn builtin_create_canvas(env: &mut Env, args: &[AST]) -> Result<Value, String> {
576    let vals = eval_args(env, args)?;
577    let title = if !vals.is_empty() {
578        unquote(&vals[0])
579    } else {
580        String::from("Canvas")
581    };
582
583    let id_num = {
584        let mut counter = crate::apps::canvas::CANVAS_ID_COUNTER.lock();
585        let current = *counter;
586        *counter += 1;
587        current
588    };
589    let id = alloc::format!("canvas_{}", id_num);
590
591    crate::apps::canvas::CANVAS_QUEUES
592        .lock()
593        .insert(id.clone(), alloc::collections::VecDeque::new());
594
595    let app = crate::apps::canvas::CanvasApp::new(id.clone(), title.clone(), 400, 300);
596    let win = crate::kernel::window_mgr::Window::new(200, 150, 400, 300, &title, Box::new(app));
597    crate::kernel::window_mgr::get_instance().add_window(win);
598    crate::kernel::window_mgr::get_instance().dirty = true;
599
600    Ok(Value::Str(id))
601}
602
603pub(crate) fn builtin_boxfill(env: &mut Env, args: &[AST]) -> Result<Value, String> {
604    let vals = eval_args(env, args)?;
605    if vals.len() < 6 {
606        return Err(String::from(
607            "USAGE: boxfill(canvas_id, x0, y0, x1, y1, color)",
608        ));
609    }
610    let canvas_id = unquote(&vals[0]);
611    let x0 = get_num_u32(&vals[1])?;
612    let y0 = get_num_u32(&vals[2])?;
613    let x1 = get_num_u32(&vals[3])?;
614    let y1 = get_num_u32(&vals[4])?;
615    let color = get_num_u32(&vals[5])?;
616
617    {
618        let mut queues = crate::apps::canvas::CANVAS_QUEUES.lock();
619        if let Some(q) = queues.get_mut(&canvas_id) {
620            q.push_back(crate::apps::canvas::DrawCommand::BoxFill {
621                x0,
622                y0,
623                x1,
624                y1,
625                color,
626            });
627        } else {
628            return Err(alloc::format!("Canvas ID not found: {}", canvas_id));
629        }
630    }
631    crate::kernel::window_mgr::get_instance().dirty = true;
632
633    Ok(Value::Str(alloc::format!(
634        "boxfill('{}', {}, {}, {}, {}, 0x{:08X})",
635        canvas_id,
636        x0,
637        y0,
638        x1,
639        y1,
640        color
641    )))
642}
643
644pub(crate) fn builtin_draw_string(env: &mut Env, args: &[AST]) -> Result<Value, String> {
645    let vals = eval_args(env, args)?;
646    if vals.len() < 6 {
647        return Err(String::from(
648            "USAGE: draw_string(canvas_id, x, y, text, color, size)",
649        ));
650    }
651    let canvas_id = unquote(&vals[0]);
652    let x = get_num_u32(&vals[1])?;
653    let y = get_num_u32(&vals[2])?;
654    let text = unquote(&vals[3]);
655    let color = get_num_u32(&vals[4])?;
656    let size = get_num_u32(&vals[5])?;
657
658    {
659        let mut queues = crate::apps::canvas::CANVAS_QUEUES.lock();
660        if let Some(q) = queues.get_mut(&canvas_id) {
661            q.push_back(crate::apps::canvas::DrawCommand::DrawString {
662                x,
663                y,
664                text: text.clone(),
665                color,
666                size,
667            });
668        } else {
669            return Err(alloc::format!("Canvas ID not found: {}", canvas_id));
670        }
671    }
672    crate::kernel::window_mgr::get_instance().dirty = true;
673
674    Ok(Value::Str(alloc::format!(
675        "draw_string('{}', {}, {}, '{}', 0x{:08X}, {})",
676        canvas_id,
677        x,
678        y,
679        text,
680        color,
681        size
682    )))
683}
684
685pub(crate) fn builtin_clear_screen(env: &mut Env, args: &[AST]) -> Result<Value, String> {
686    let vals = eval_args(env, args)?;
687    if vals.len() < 2 {
688        return Err(String::from("USAGE: clear_screen(canvas_id, color)"));
689    }
690    let canvas_id = unquote(&vals[0]);
691    let color = get_num_u32(&vals[1])?;
692
693    {
694        let mut queues = crate::apps::canvas::CANVAS_QUEUES.lock();
695        if let Some(q) = queues.get_mut(&canvas_id) {
696            q.push_back(crate::apps::canvas::DrawCommand::ClearScreen { color });
697        } else {
698            return Err(alloc::format!("Canvas ID not found: {}", canvas_id));
699        }
700    }
701    crate::kernel::window_mgr::get_instance().dirty = true;
702
703    Ok(Value::Str(alloc::format!(
704        "clear_screen('{}', 0x{:08X})",
705        canvas_id,
706        color
707    )))
708}
709
710pub fn builtin_run(env: &mut Env, args: &[AST]) -> Result<Value, String> {
711    let vals = eval_args(env, args)?;
712    if vals.is_empty() {
713        return Err(String::from(
714            "USAGE: run(\"app_name_or_filename\" [\"arg\"])",
715        ));
716    }
717    let raw_name = unquote(&vals[0]);
718
719    // --- Step 2: /apps/{name}/ パッケージを自動検索 ---
720    let manifest_path = alloc::format!("/apps/{}/manifest.json", raw_name);
721    let fs = crate::kernel::fs::get_fs();
722    let manifest_bytes_opt = match fs.read_file_checked(&manifest_path) {
723        Ok(v) => v,
724        Err(e) => {
725            crate::warn!("[SYS] failed to read manifest '{}': {}", manifest_path, e);
726            None
727        }
728    };
729    if let Some((_meta, manifest_bytes)) = manifest_bytes_opt {
730        // manifest.json をパース(失敗時はデフォルト値を使用)
731        let manifest = core::str::from_utf8(&manifest_bytes)
732            .ok()
733            .and_then(crate::kernel::app_sandbox::AppManifest::parse)
734            .unwrap_or_default();
735
736        let entry_path = alloc::format!("/apps/{}/{}", raw_name, manifest.entry);
737        let display = if manifest.display_name.is_empty() {
738            manifest.name.clone()
739        } else {
740            manifest.display_name.clone()
741        };
742
743        let entry_bytes_res = fs.read_file_checked(&entry_path);
744        if let Ok(Some((_meta2, entry_bytes))) = entry_bytes_res {
745            let script = match core::str::from_utf8(&entry_bytes) {
746                Ok(s) => s,
747                Err(_) => {
748                    return Err(alloc::format!(
749                        "ERROR: App '{}' entry file contains invalid UTF-8",
750                        raw_name
751                    ))
752                }
753            };
754
755            let tokens = super::super::lexer::tokenize(script);
756            if tokens.is_empty() {
757                return Ok(Value::Str(alloc::format!(
758                    "App '{}' ({}): entry script is empty",
759                    raw_name,
760                    display
761                )));
762            }
763
764            let asts = match super::super::parser::parse(&tokens) {
765                Ok(a) => a,
766                Err(e) => return Err(alloc::format!("Syntax Error in app '{}': {}", raw_name, e)),
767            };
768
769            // サンドボックス付き環境で実行
770            let sandbox = crate::kernel::app_sandbox::AppSandbox::new(0, manifest);
771            let mut app_env = super::super::eval::Env::with_sandbox(sandbox);
772            // 親環境から cwd を引き継ぎ
773            if let Some(cwd_val) = env.get("cwd") {
774                app_env.set(alloc::string::String::from("cwd"), cwd_val);
775            }
776
777            // 引数 ARGS の設定
778            let mut args_list = Vec::new();
779            for v in &vals[1..] {
780                args_list.push(v.clone());
781            }
782            app_env.set(alloc::string::String::from("ARGS"), Value::List(args_list));
783
784            super::super::builtins::register(&mut app_env);
785
786            let mut last_val = Value::Str(String::from(""));
787            for ast in asts {
788                let val = eval(&mut app_env, &ast)?;
789                last_val = force_eval(&mut app_env, val)?;
790            }
791            return Ok(last_val);
792        } else if let Err(e) = entry_bytes_res {
793            return Err(alloc::format!(
794                "ERROR: Failed to read entry file '{}' in app '{}': {}",
795                entry_path,
796                raw_name,
797                e
798            ));
799        } else {
800            return Err(alloc::format!(
801                "ERROR: App '{}' entry file '{}' not found in /apps/",
802                raw_name,
803                entry_path
804            ));
805        }
806    }
807
808    // --- Step 3: 従来のパス解決によるスクリプト実行 ---
809    let filename = resolve_path(env, &raw_name)?;
810    let content = match fs.read_file_checked(&filename) {
811        Ok(Some((_meta, c))) => c,
812        Ok(None) => return Err(alloc::format!("ERROR: Script file '{}' not found", filename)),
813        Err(e) => return Err(alloc::format!("ERROR: Failed to read script '{}': {}", filename, e)),
814    };
815    let script = match core::str::from_utf8(&content) {
816        Ok(s) => s,
817        Err(_) => return Err(String::from("ERROR: Script file contains invalid UTF-8")),
818    };
819
820    let tokens = super::super::lexer::tokenize(script);
821    if tokens.is_empty() {
822        return Ok(Value::Str(String::from("RUN: Script is empty")));
823    }
824
825    let asts = match super::super::parser::parse(&tokens) {
826        Ok(a) => a,
827        Err(e) => return Err(alloc::format!("Syntax Error in '{}': {}", filename, e)),
828    };
829
830    let mut last_val = Value::Str(String::from(""));
831    for ast in asts {
832        let val = eval(env, &ast)?;
833        last_val = force_eval(env, val)?;
834    }
835
836    Ok(last_val)
837}
838
839/// kill("name") - 名前(アプリ名かウィンドウの題名の一部。大文字小文字は区別しない)に合うウィンドウを強制終了する。
840/// アプリが描画や JS の実行の途中で返ってこなくても、OS の側から閉じる(TODO R2、2026-11-14)。
841pub(crate) fn builtin_kill(env: &mut Env, args: &[AST]) -> Result<Value, String> {
842    let vals = eval_args(env, args)?;
843    let Some(first) = vals.first() else {
844        return Err(String::from("USAGE: os.kill(\"app_name_or_title\")"));
845    };
846    let needle = unquote(first).to_lowercase();
847    crate::warn!("[WM] os.kill(\"{}\")", needle);
848    if needle.is_empty() {
849        return Err(String::from("USAGE: os.kill(\"app_name_or_title\")"));
850    }
851    let mut wm = crate::kernel::window_mgr::get_instance();
852    let mut killed: alloc::vec::Vec<String> = alloc::vec::Vec::new();
853    // 後ろ(手前のウィンドウ)から見る。閉じると番号が詰まるので、毎回探し直す。
854    loop {
855        let hit = wm
856            .windows
857            .iter()
858            .rposition(|w| w.app.name().to_lowercase() == needle || w.title.to_lowercase().contains(&needle));
859        let Some(idx) = hit else { break };
860        match wm.kill_window(idx) {
861            Some(name) => killed.push(name),
862            None => break,
863        }
864    }
865    if killed.is_empty() {
866        return Err(alloc::format!("ERROR: no window matches '{}'", needle));
867    }
868    Ok(Value::Str(alloc::format!("killed {} window(s): {}", killed.len(), killed.join(", "))))
869}
870
871/// apps() - /apps/ 配下のインストール済みアプリを一覧表示
872pub(crate) fn builtin_apps(_env: &mut Env, _args: &[AST]) -> Result<Value, String> {
873    use alloc::collections::BTreeSet;
874    let fs = crate::kernel::fs::get_fs();
875    let entries = fs.list_dir("/apps/");
876
877    // /apps/ 配下の全ファイルからアプリ名(最初のパスコンポーネント)を一意に集める。
878    // 旧実装はファイル毎に 1 行出していたため、同一アプリが複数回表示される不具合があった。
879    let mut names: BTreeSet<String> = BTreeSet::new();
880    for entry in &entries {
881        let filepath = entry.get_filename();
882        let without_prefix = filepath
883            .trim_start_matches("/apps/")
884            .trim_start_matches("apps/");
885        let app_name = without_prefix
886            .split('/')
887            .next()
888            .unwrap_or("")
889            .trim_matches('/');
890        if !app_name.is_empty() {
891            names.insert(String::from(app_name));
892        }
893    }
894
895    if names.is_empty() {
896        return Ok(Value::Str(String::from(
897            "Installed Apps (/apps/)\n-----------------------\n  (no apps installed)\n\nInstall: copy an app directory to /apps/<name>/"
898        )));
899    }
900
901    let mut out = String::from("Installed Apps (/apps/)  [click to launch]\n");
902    out.push_str("---------------------------------------------------------------------\n");
903    out.push_str("   Name             Version   Display name\n");
904    out.push_str("---------------------------------------------------------------------\n");
905
906    for app_name in &names {
907        let manifest_path = alloc::format!("/apps/{}/manifest.json", app_name);
908        let (manifest, _has_manifest) = match fs.read_file_checked(&manifest_path) {
909            Ok(Some((_meta, bytes))) => {
910                let m = core::str::from_utf8(&bytes)
911                    .ok()
912                    .and_then(crate::kernel::app_sandbox::AppManifest::parse)
913                    .unwrap_or_default();
914                (m, true)
915            }
916            Ok(None) => {
917                let m = crate::kernel::app_sandbox::AppManifest {
918                    name: app_name.clone(),
919                    ..Default::default()
920                };
921                (m, false)
922            }
923            Err(e) => {
924                crate::warn!("[SYS] apps: failed to read manifest '{}': {}", manifest_path, e);
925                let m = crate::kernel::app_sandbox::AppManifest {
926                    name: app_name.clone(),
927                    ..Default::default()
928                };
929                (m, false)
930            }
931        };
932
933        let name = if manifest.name.is_empty() {
934            app_name.clone()
935        } else {
936            manifest.name.clone()
937        };
938        let version = if manifest.version.is_empty() {
939            String::from("-")
940        } else {
941            manifest.version.clone()
942        };
943        let display = if manifest.display_name.is_empty() {
944            name.clone()
945        } else {
946            manifest.display_name.clone()
947        };
948
949        // マーカー行: \x02LAUNCHER:<appname>:<name_col>/<version_col>/<display_col>\x02
950        // ターミナルの draw() がアイコン + テキストとして描画し、クリック可能にする。
951        let row_text = alloc::format!(
952            "   {:<16} {:<9} {}",
953            truncate_cols(&name, 16),
954            truncate_cols(&version, 9),
955            truncate_cols(&display, 22),
956        );
957        out.push('\x02');
958        out.push_str("LAUNCHER:");
959        out.push_str(app_name);
960        out.push(':');
961        out.push_str(&row_text);
962        out.push('\x02');
963        out.push('\n');
964    }
965
966    out.push_str("---------------------------------------------------------------------\n");
967    out.push_str(&alloc::format!("{} app(s) installed.\n", names.len()));
968    out.push_str("Run     : os.run(\"<name>\") or click a row above\n");
969    out.push_str("Install : copy an app dir to /apps/<name>/  (no installer needed)\n");
970    out.push_str("Remove  : delete the /apps/<name>/ directory");
971
972    Ok(Value::Str(out))
973}
974
975/// 表の桁あふれを防ぐため、文字数で切り詰める(マルチバイト安全)。
976pub(crate) fn truncate_cols(s: &str, max_chars: usize) -> String {
977    if s.chars().count() <= max_chars {
978        String::from(s)
979    } else {
980        let mut t: String = s.chars().take(max_chars.saturating_sub(1)).collect();
981        t.push('…');
982        t
983    }
984}
985
986pub(crate) fn builtin_play(env: &mut Env, args: &[AST]) -> Result<Value, String> {
987    let vals = eval_args(env, args)?;
988    if vals.len() < 2 {
989        return Err(String::from("USAGE: play(frequency, duration_ms)"));
990    }
991    let freq = get_num_u32(&vals[0])?;
992    let duration = get_num_u32(&vals[1])?;
993
994    crate::kernel::audio::Audio::play_tone_async(freq, duration);
995    Ok(Value::Str(alloc::format!("play({}, {})", freq, duration)))
996}
997
998pub(crate) fn builtin_play_mml(env: &mut Env, args: &[AST]) -> Result<Value, String> {
999    let vals = eval_args(env, args)?;
1000    if vals.is_empty() {
1001        return Err(String::from("USAGE: play_mml(\"mml_string\")"));
1002    }
1003    let mml = unquote(&vals[0]);
1004
1005    crate::kernel::audio::Audio::play_mml(&mml);
1006    Ok(Value::Str(alloc::format!("play_mml('{}')", mml)))
1007}
1008
1009pub(crate) fn builtin_sound_volume(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1010    let vals = eval_args(env, args)?;
1011    if vals.is_empty() {
1012        let cur = crate::kernel::audio::AudioStream::volume();
1013        return Ok(Value::Num(BigInt::from_i64(cur as i64)));
1014    }
1015    let vol = get_num_u32(&vals[0])?;
1016    crate::kernel::audio::AudioStream::set_volume(vol);
1017    Ok(Value::Num(BigInt::from_i64(crate::kernel::audio::AudioStream::volume() as i64)))
1018}
1019
1020pub(crate) fn builtin_sound_mute(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1021    let vals = eval_args(env, args)?;
1022    if vals.is_empty() {
1023        let is_m = crate::kernel::audio::AudioStream::is_muted();
1024        return Ok(Value::Bool(is_m));
1025    }
1026    let m = match &vals[0] {
1027        Value::Bool(b) => *b,
1028        Value::Num(n) => !n.is_zero(),
1029        Value::Str(s) => s == "true" || s == "1",
1030        _ => false,
1031    };
1032    crate::kernel::audio::AudioStream::set_muted(m);
1033    Ok(Value::Bool(crate::kernel::audio::AudioStream::is_muted()))
1034}
1035
1036pub(crate) fn builtin_sound_stats(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1037    let _ = eval_args(env, args)?;
1038    let (underrun_frames, underrun_events, dropped_frames) = crate::kernel::audio::AudioStream::stats();
1039    let peak = crate::kernel::audio::AudioStream::peak_level();
1040    let buffered = crate::kernel::audio::AudioStream::buffered_ms();
1041    let active = crate::kernel::audio::AudioStream::is_active();
1042
1043    let mut dict = alloc::collections::BTreeMap::new();
1044    dict.insert(alloc::string::String::from("active"), Value::Bool(active));
1045    dict.insert(alloc::string::String::from("buffered_ms"), Value::Num(BigInt::from_i64(buffered as i64)));
1046    dict.insert(alloc::string::String::from("peak_level"), Value::Num(BigInt::from_i64(peak as i64)));
1047    dict.insert(alloc::string::String::from("underrun_frames"), Value::Num(BigInt::from_i64(underrun_frames as i64)));
1048    dict.insert(alloc::string::String::from("underrun_events"), Value::Num(BigInt::from_i64(underrun_events as i64)));
1049    dict.insert(alloc::string::String::from("dropped_frames"), Value::Num(BigInt::from_i64(dropped_frames as i64)));
1050    Ok(Value::Dict(dict))
1051}
1052
1053pub(crate) fn builtin_keyrepeat(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1054    let vals = eval_args(env, args)?;
1055
1056    if vals.is_empty() {
1057        unsafe {
1058            let params = &crate::REPEAT_PARAMS;
1059            let out = alloc::format!(
1060                "Keyboard Repeat Configurations:\n\
1061                 - First Repeat Delay:    {} ms\n\
1062                 - First Repeat Interval: {} ms\n\
1063                 - Second Repeat Count:   {} chars/loop\n\
1064                 - Second Repeat Delay:   {} ms\n\
1065                 - Second Repeat Interval: {} ms",
1066                params.first_delay_ms,
1067                params.first_interval_ms,
1068                params.second_repeat_count,
1069                params.second_delay_ms,
1070                params.second_interval_ms
1071            );
1072            return Ok(Value::Str(out));
1073        }
1074    }
1075
1076    if vals.len() < 5 {
1077        return Err(String::from("USAGE: keyrepeat(first_delay, first_interval, second_count, second_delay, second_interval)"));
1078    }
1079
1080    let first_delay = get_num_u32(&vals[0])?;
1081    let first_interval = get_num_u32(&vals[1])?;
1082    let second_count = get_num_u32(&vals[2])?;
1083    let second_delay = get_num_u32(&vals[3])?;
1084    let second_interval = get_num_u32(&vals[4])?;
1085
1086    unsafe {
1087        crate::REPEAT_PARAMS.first_delay_ms = first_delay;
1088        crate::REPEAT_PARAMS.first_interval_ms = first_interval;
1089        crate::REPEAT_PARAMS.second_repeat_count = second_count;
1090        crate::REPEAT_PARAMS.second_delay_ms = second_delay;
1091        crate::REPEAT_PARAMS.second_interval_ms = second_interval;
1092    }
1093
1094    Ok(Value::Str(alloc::format!(
1095        "SUCCESS: Keyboard repeat parameters updated:\n\
1096         Delay1: {}ms, Interval1: {}ms, Repeat2 Count: {} chars, Delay2: {}ms, Interval2: {}ms",
1097        first_delay,
1098        first_interval,
1099        second_count,
1100        second_delay,
1101        second_interval
1102    )))
1103}
1104
1105pub(crate) fn builtin_dom_get_value(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1106    let vals = eval_args(env, args)?;
1107    if vals.len() != 1 {
1108        return Err(String::from("dom_get_value requires 1 argument (id)"));
1109    }
1110    if let Value::Str(id) = &vals[0] {
1111        let wm = crate::kernel::window_mgr::get_instance();
1112        if !wm.windows.is_empty() {
1113            let last_idx = wm.windows.len() - 1;
1114            if let Some(val) = wm.windows[last_idx].app.get_dom_value(id) {
1115                return Ok(Value::Str(val));
1116            }
1117        }
1118        let browser = crate::apps::browser::get_instance();
1119        if let Some(val) = browser.engine.form_values.get(id) {
1120            Ok(Value::Str(val.clone()))
1121        } else {
1122            Ok(Value::Str(String::new()))
1123        }
1124    } else {
1125        Err(String::from("dom_get_value id must be string"))
1126    }
1127}
1128
1129pub(crate) fn builtin_dom_set_value(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1130    let vals = eval_args(env, args)?;
1131    if vals.len() != 2 {
1132        return Err(String::from(
1133            "dom_set_value requires 2 arguments (id, value)",
1134        ));
1135    }
1136    let id = match &vals[0] {
1137        Value::Str(s) => s.clone(),
1138        _ => return Err(String::from("dom_set_value id must be string")),
1139    };
1140    let val = unquote(&vals[1]);
1141
1142    let mut wm = crate::kernel::window_mgr::get_instance();
1143    let mut handled = false;
1144    if !wm.windows.is_empty() {
1145        let last_idx = wm.windows.len() - 1;
1146        wm.windows[last_idx].app.set_dom_value(&id, &val);
1147        handled = true;
1148    }
1149
1150    if !handled {
1151        let browser = crate::apps::browser::get_instance();
1152        browser.engine.form_values.insert(id, val);
1153        browser.engine.dirty = true;
1154    }
1155    Ok(Value::Nil)
1156}
1157
1158/// 【2026-07-30】ブラウザを指定量スクロールする。
1159///
1160/// スクリーンショットでファーストビューより下のセクションを確認したかったが、
1161/// キー入力が届かなかった(シリアルのエスケープシーケンスも QEMU の
1162/// `sendkey pgdn` も効かない。ブラウザのキー処理は
1163/// `apps::browser::is_active()` が真のときだけ動く)。
1164/// 検証手段として、スクリプトから直接スクロールできるようにする。
1165///
1166/// `browser.scroll(600)` で 600px 下へ。負値で上へ。
1167pub(crate) fn builtin_browser_scroll(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1168    let vals = eval_args(env, args)?;
1169    if vals.is_empty() {
1170        return Err(String::from("USAGE: browser.scroll(dy)"));
1171    }
1172    let dy: i32 = unquote(&vals[0])
1173        .trim()
1174        .parse()
1175        .map_err(|_| String::from("scroll: dy は整数で指定してください"))?;
1176    let browser = crate::apps::browser::get_instance();
1177    browser.engine.scroll(dy);
1178    browser.engine.dirty = true;
1179    Ok(Value::Str(alloc::format!("scrolled dy={}", dy)))
1180}
1181
1182pub(crate) fn builtin_dom_get_content(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1183    let vals = eval_args(env, args)?;
1184    if vals.len() != 1 {
1185        return Err(String::from("dom_get_content requires 1 argument (id)"));
1186    }
1187    if let Value::Str(id) = &vals[0] {
1188        let wm = crate::kernel::window_mgr::get_instance();
1189        if !wm.windows.is_empty() {
1190            let last_idx = wm.windows.len() - 1;
1191            if let Some(val) = wm.windows[last_idx].app.get_dom_content(id) {
1192                return Ok(Value::Str(val));
1193            }
1194        }
1195        let browser = crate::apps::browser::get_instance();
1196        if let Some(val) = browser.engine.dom_contents.get(id) {
1197            Ok(Value::Str(val.clone()))
1198        } else {
1199            Ok(Value::Str(String::new()))
1200        }
1201    } else {
1202        Err(String::from("dom_get_content id must be string"))
1203    }
1204}
1205
1206pub(crate) fn builtin_dom_set_content(env: &mut Env, args: &[AST]) -> Result<Value, String> {
1207    let vals = eval_args(env, args)?;
1208    if vals.len() != 2 {
1209        return Err(String::from(
1210            "dom_set_content requires 2 arguments (id, value)",
1211        ));
1212    }
1213    let id = match &vals[0] {
1214        Value::Str(s) => s.clone(),
1215        _ => return Err(String::from("dom_set_content id must be string")),
1216    };
1217    let val = unquote(&vals[1]);
1218
1219    let mut wm = crate::kernel::window_mgr::get_instance();
1220    let mut handled = false;
1221    if !wm.windows.is_empty() {
1222        let last_idx = wm.windows.len() - 1;
1223        wm.windows[last_idx].app.set_dom_content(&id, &val);
1224        handled = true;
1225    }
1226
1227    if !handled {
1228        let browser = crate::apps::browser::get_instance();
1229        browser.engine.set_dom_content(&id, &val);
1230    }
1231    Ok(Value::Nil)
1232}
1233
1234// ---- load / require ----
1235