use crate::error::HwpError;
pub fn command_uri(command: &str) -> String {
let mut out = String::new();
let mut chars = command.chars();
while let Some(c) = chars.next() {
match c {
'\\' => {
if let Some(next) = chars.next() {
out.push(next);
}
}
';' => break,
_ => out.push(c),
}
}
out.trim().to_string()
}
pub fn web_command(uri: &str) -> Result<String, HwpError> {
let invalid = || HwpError::InvalidField("공백 없는 HTTP/HTTPS 절대 주소가 필요합니다".into());
let (scheme, rest) = uri.split_once("://").ok_or_else(invalid)?;
if !(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"))
|| uri
.chars()
.any(|c| c.is_whitespace() || c.is_control() || c == '\\')
{
return Err(invalid());
}
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
if authority.is_empty() || authority.starts_with(':') || authority.contains('@') {
return Err(invalid());
}
let mut command = String::with_capacity(uri.len() + 16);
for c in uri.chars() {
if matches!(c, '\\' | ':' | ';' | '#') {
command.push('\\');
}
command.push(c);
}
command.push_str(";1;0;0;");
checked_length(command)
}
pub fn bookmark_command(name: &str) -> Result<String, HwpError> {
if name.trim().is_empty() || name.chars().any(char::is_control) {
return Err(HwpError::InvalidField(
"책갈피 이름이 비어 있거나 제어 문자를 포함합니다".into(),
));
}
let mut command = String::with_capacity(name.len() + 8);
command.push('?');
for c in name.chars() {
if matches!(c, '\\' | ':' | ';') {
command.push('\\');
}
command.push(c);
}
command.push_str(";0;0;0;");
checked_length(command)
}
pub fn command_bookmark(command: &str) -> Option<String> {
command_uri(command)
.strip_prefix('?')
.filter(|name| !name.is_empty())
.map(str::to_string)
}
fn checked_length(command: String) -> Result<String, HwpError> {
if command.encode_utf16().count() > u16::MAX as usize {
return Err(HwpError::InvalidField(
"하이퍼링크 주소가 너무 깁니다".into(),
));
}
Ok(command)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum LinkDestinationKind {
Web,
Mail,
DocumentAnchor,
RelativeFile,
LocalFile,
RegisteredApplication,
}
pub fn classify_destination(uri: &str) -> Option<LinkDestinationKind> {
use LinkDestinationKind::*;
if uri.is_empty() || uri.trim() != uri || uri.chars().any(char::is_control) {
return None;
}
if let Some(anchor) = uri.strip_prefix('#') {
return (!anchor.is_empty()).then_some(DocumentAnchor);
}
if uri.starts_with('/')
|| uri.starts_with("\\\\")
|| (uri.as_bytes().get(1) == Some(&b':')
&& uri.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
&& uri
.as_bytes()
.get(2)
.is_some_and(|b| matches!(b, b'/' | b'\\')))
{
return Some(LocalFile);
}
if let Some((scheme, rest)) = uri.split_once(':') {
if rest.is_empty()
|| !scheme
.as_bytes()
.first()
.is_some_and(u8::is_ascii_alphabetic)
|| !scheme
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"+-.".contains(&b))
{
return None;
}
return match scheme.to_ascii_lowercase().as_str() {
"http" | "https" => web_command(uri).ok().map(|_| Web),
"mailto" => (!rest.trim().is_empty()).then_some(Mail),
"file" => Some(LocalFile),
"javascript" | "vbscript" | "data" => None,
_ => Some(RegisteredApplication),
};
}
Some(RelativeFile)
}
pub fn destination_command(uri: &str) -> Result<String, HwpError> {
classify_destination(uri)
.ok_or_else(|| HwpError::InvalidField("유효한 링크 목적지가 필요합니다".into()))?;
let mut command = String::with_capacity(uri.len() + 16);
for c in uri.chars() {
if matches!(c, '\\' | ':' | ';' | '#') {
command.push('\\');
}
command.push(c);
}
command.push_str(";1;0;0;");
if command.encode_utf16().count() > u16::MAX as usize {
return Err(HwpError::InvalidField(
"하이퍼링크 주소가 너무 깁니다".into(),
));
}
Ok(command)
}