rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
//! 쪽 좌표에서 문서 위치를 조회한다.
//!
//! 기존 읽기 전용 `DocumentCore::hit_test_native` 를 호출할 뿐이며 문서를
//! 고치지 않는다. 통합 dispatcher에서 전달한 인자로 조회한다.

use rhwp::document_core::DocumentCore;
use rhwp::schema_registry::ENVELOPE_SCHEMA_VERSION;
use serde_json::{json, Value};
use std::io::Write;
use std::process;

const EXIT_OK: i32 = 0;
const EXIT_RUNTIME: i32 = 1;
const EXIT_USAGE: i32 = 2;
const TOOL: &str = "rhwp-q-hit-test";
const COMMAND: &str = "hit-test";
pub(super) const USAGE: &str = "rhwp-q hit-test <파일> --page <N> --x <F> --y <F> [--json]";

#[derive(Debug)]
struct Options {
    json: bool,
    page: u32,
    x: f64,
    y: f64,
    path: String,
}

#[derive(Debug)]
enum Cli {
    Help,
    Version,
    Run(Options),
}

pub(super) fn run_cli(args: Vec<String>) {
    let code = match parse_cli(&args) {
        Ok(Cli::Help) => {
            print_help();
            EXIT_OK
        }
        Ok(Cli::Version) => {
            write_stdout(&format!("{TOOL} v{}", rhwp::version()), true);
            EXIT_OK
        }
        Ok(Cli::Run(opts)) => run(&opts),
        Err(code) => code,
    };
    process::exit(code);
}

fn print_help() {
    write_stdout(
        &format!("{TOOL} v{} — 쪽 좌표 히트테스트 조회", rhwp::version()),
        true,
    );
    write_stdout(&format!("사용법: {USAGE}"), true);
    write_stdout("", true);
    write_stdout("  --page <N>   0부터 세는 쪽 번호 (필수)", true);
    write_stdout("  --x <F>      쪽 안 x 좌표 (필수)", true);
    write_stdout("  --y <F>      쪽 안 y 좌표 (필수)", true);
    write_stdout("  --json       stdout 순수 JSON 봉투", true);
    write_stdout("", true);
    write_stdout("종료 코드: 0 성공 · 1 실행 오류 · 2 사용법 오류", true);
    write_stdout("문서를 고치지 않는다. 편집 플래그는 받지 않는다.", true);
}

fn parse_cli(args: &[String]) -> Result<Cli, i32> {
    let mut json = false;
    let mut page: Option<u32> = None;
    let mut x: Option<f64> = None;
    let mut y: Option<f64> = None;
    let mut path: Option<String> = None;
    let mut i = 0;
    while i < args.len() {
        let arg = args[i].as_str();
        match arg {
            "--help" | "-h" => return Ok(Cli::Help),
            "--version" | "-V" => return Ok(Cli::Version),
            "--json" => {
                json = true;
                i += 1;
            }
            "--page" => {
                reject_duplicate("--page", page.is_some())?;
                page = Some(parse_required_u32(next_value(args, i, "--page")?, &mut i)?);
            }
            other if other.starts_with("--page=") => {
                page = Some(parse_equals_u32(other, "--page", page.is_some(), &mut i)?);
            }
            "--x" => {
                reject_duplicate("--x", x.is_some())?;
                x = Some(parse_required_f64(
                    next_value(args, i, "--x")?,
                    "--x",
                    &mut i,
                )?);
            }
            other if other.starts_with("--x=") => {
                x = Some(parse_equals_f64(other, "--x", x.is_some(), &mut i)?);
            }
            "--y" => {
                reject_duplicate("--y", y.is_some())?;
                y = Some(parse_required_f64(
                    next_value(args, i, "--y")?,
                    "--y",
                    &mut i,
                )?);
            }
            other if other.starts_with("--y=") => {
                y = Some(parse_equals_f64(other, "--y", y.is_some(), &mut i)?);
            }
            other if other.starts_with('-') => {
                eprintln!("오류: 알 수 없는 옵션입니다 - {other}");
                eprintln!("사용법: {USAGE}");
                return Err(EXIT_USAGE);
            }
            other => {
                if path.is_some() {
                    eprintln!("오류: 파일이 너무 많습니다 - {other}");
                    eprintln!("사용법: {USAGE}");
                    return Err(EXIT_USAGE);
                }
                path = Some(other.to_string());
                i += 1;
            }
        }
    }
    let Some(path) = path else {
        eprintln!("오류: 파일 경로가 필요합니다.");
        eprintln!("사용법: {USAGE}");
        return Err(EXIT_USAGE);
    };
    let Some(page) = page else {
        eprintln!("오류: --page 가 필요합니다.");
        eprintln!("사용법: {USAGE}");
        return Err(EXIT_USAGE);
    };
    let Some(x) = x else {
        eprintln!("오류: --x 가 필요합니다.");
        eprintln!("사용법: {USAGE}");
        return Err(EXIT_USAGE);
    };
    let Some(y) = y else {
        eprintln!("오류: --y 가 필요합니다.");
        eprintln!("사용법: {USAGE}");
        return Err(EXIT_USAGE);
    };
    Ok(Cli::Run(Options {
        json,
        page,
        x,
        y,
        path,
    }))
}

fn next_value<'a>(args: &'a [String], i: usize, flag: &str) -> Result<&'a str, i32> {
    let Some(raw) = args.get(i + 1) else {
        flag_value_error(flag);
        return Err(EXIT_USAGE);
    };
    Ok(raw.as_str())
}

fn parse_required_u32(raw: &str, i: &mut usize) -> Result<u32, i32> {
    let Ok(n) = raw.parse::<u32>() else {
        flag_value_error("--page");
        return Err(EXIT_USAGE);
    };
    *i += 2;
    Ok(n)
}

fn parse_equals_u32(arg: &str, flag: &str, already: bool, i: &mut usize) -> Result<u32, i32> {
    if already {
        duplicate_flag(flag);
        return Err(EXIT_USAGE);
    }
    let raw = &arg[flag.len() + 1..];
    let Ok(n) = raw.parse::<u32>() else {
        flag_value_error(flag);
        return Err(EXIT_USAGE);
    };
    *i += 1;
    Ok(n)
}

fn parse_required_f64(raw: &str, flag: &str, i: &mut usize) -> Result<f64, i32> {
    let Some(n) = parse_finite_f64(raw) else {
        flag_value_error(flag);
        return Err(EXIT_USAGE);
    };
    *i += 2;
    Ok(n)
}

fn parse_equals_f64(arg: &str, flag: &str, already: bool, i: &mut usize) -> Result<f64, i32> {
    if already {
        duplicate_flag(flag);
        return Err(EXIT_USAGE);
    }
    let raw = &arg[flag.len() + 1..];
    let Some(n) = parse_finite_f64(raw) else {
        flag_value_error(flag);
        return Err(EXIT_USAGE);
    };
    *i += 1;
    Ok(n)
}

fn parse_finite_f64(raw: &str) -> Option<f64> {
    let n = raw.parse::<f64>().ok()?;
    n.is_finite().then_some(n)
}

fn flag_value_error(flag: &str) {
    match flag {
        "--page" => eprintln!("오류: --page 뒤에 0 이상의 정수가 필요합니다."),
        "--x" => eprintln!("오류: --x 뒤에 숫자가 필요합니다."),
        "--y" => eprintln!("오류: --y 뒤에 숫자가 필요합니다."),
        _ => eprintln!("오류: {flag} 뒤에 숫자가 필요합니다."),
    }
    eprintln!("사용법: {USAGE}");
}

fn reject_duplicate(flag: &str, already: bool) -> Result<(), i32> {
    if already {
        duplicate_flag(flag);
        return Err(EXIT_USAGE);
    }
    Ok(())
}

fn duplicate_flag(flag: &str) {
    eprintln!("오류: {flag} 를 두 번 지정했습니다.");
    eprintln!("사용법: {USAGE}");
}

fn run(opts: &Options) -> i32 {
    let core = match open_core(&opts.path) {
        Ok(core) => core,
        Err(code) => return code,
    };
    let envelope = match hit_test_envelope(&opts.path, opts.page, opts.x, opts.y, &core) {
        Ok(value) => value,
        Err(code) => return code,
    };
    if opts.json {
        match serde_json::to_string_pretty(&envelope) {
            Ok(text) => write_stdout(&text, true),
            Err(e) => {
                eprintln!("오류: JSON 직렬화 실패 - {e}");
                return EXIT_RUNTIME;
            }
        }
    } else {
        print_text(&envelope, opts);
    }
    EXIT_OK
}

fn print_text(envelope: &Value, opts: &Options) {
    let hit = envelope.get("hit").cloned().unwrap_or(Value::Null);
    let section = display_num(&hit["sectionIndex"]);
    let para = display_num(&hit["paragraphIndex"]);
    let offset = display_num(&hit["charOffset"]);
    write_stdout(
        &format!(
            "page={} x={} y={} sectionIndex={} paragraphIndex={} charOffset={}",
            opts.page, opts.x, opts.y, section, para, offset
        ),
        true,
    );
    if let Some(rect) = hit.get("cursorRect") {
        write_stdout(
            &format!(
                "cursorRect pageIndex={} x={} y={} height={}",
                display_num(&rect["pageIndex"]),
                display_num(&rect["x"]),
                display_num(&rect["y"]),
                display_num(&rect["height"])
            ),
            true,
        );
    }
}

fn display_num(value: &Value) -> String {
    match value {
        Value::Number(n) => n.to_string(),
        _ => "-".to_string(),
    }
}

fn open_core(path: &str) -> Result<DocumentCore, i32> {
    let data = match std::fs::read(path) {
        Ok(data) => data,
        Err(e) => {
            eprintln!("오류: 파일을 읽을 수 없습니다 - {path}: {e}");
            return Err(EXIT_RUNTIME);
        }
    };
    DocumentCore::from_bytes(&data).map_err(|e| {
        eprintln!("오류: 문서를 열 수 없습니다 - {path}: {e}");
        EXIT_RUNTIME
    })
}

fn hit_test_envelope(
    source: &str,
    page: u32,
    x: f64,
    y: f64,
    core: &DocumentCore,
) -> Result<Value, i32> {
    let raw = match core.hit_test_native(page, x, y) {
        Ok(raw) => raw,
        Err(e) => {
            eprintln!("오류: 히트테스트를 읽지 못했습니다 - {e}");
            return Err(EXIT_RUNTIME);
        }
    };
    let hit: Value = match serde_json::from_str(&raw) {
        Ok(value) => value,
        Err(e) => {
            eprintln!("오류: 히트테스트 JSON 이 깨졌습니다 - {e}");
            return Err(EXIT_RUNTIME);
        }
    };
    if !hit.is_object() {
        eprintln!("오류: 히트테스트 JSON 이 깨졌습니다 - 객체가 아닙니다");
        return Err(EXIT_RUNTIME);
    }
    let untrusted = untrusted_fields(&hit);
    Ok(json!({
        "schemaVersion": ENVELOPE_SCHEMA_VERSION,
        "tool": TOOL,
        "command": COMMAND,
        "version": rhwp::version(),
        "untrustedContent": !untrusted.is_empty(),
        "untrustedFields": untrusted,
        "source": source,
        "page": page,
        "x": x,
        "y": y,
        "pageCount": core.page_count(),
        "hit": hit,
    }))
}

fn untrusted_fields(hit: &Value) -> Vec<String> {
    let mut fields = vec!["source".to_string(), "hit".to_string()];
    collect_string_paths(hit, "hit", &mut fields);
    fields
}

fn collect_string_paths(value: &Value, prefix: &str, out: &mut Vec<String>) {
    match value {
        Value::String(_) => {
            if !out.iter().any(|f| f == prefix) {
                out.push(prefix.to_string());
            }
        }
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            for key in keys {
                if let Some(child) = map.get(key) {
                    collect_string_paths(child, &format!("{prefix}.{key}"), out);
                }
            }
        }
        Value::Array(items) => {
            for item in items {
                collect_string_paths(item, &format!("{prefix}[]"), out);
            }
        }
        _ => {}
    }
}

fn write_stdout(text: &str, newline: bool) {
    let stdout = std::io::stdout();
    let mut lock = stdout.lock();
    let result = if newline {
        writeln!(lock, "{text}")
    } else {
        write!(lock, "{text}")
    };
    if let Err(e) = result {
        eprintln!("오류: stdout 쓰기 실패 - {e}");
        process::exit(EXIT_RUNTIME);
    }
}