repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
rust-mcp-stack/rust-mcp-sdk | https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/src/event_store/in_memory_event_store.rs | crates/rust-mcp-transport/src/event_store/in_memory_event_store.rs | use crate::event_store::EventStoreResult;
use crate::{
event_store::{EventStore, EventStoreEntry},
EventId, SessionId, StreamId,
};
use async_trait::async_trait;
use std::collections::HashMap;
use std::collections::VecDeque;
use tokio::sync::RwLock;
const MAX_EVENTS_PER_SESSION: usize = 64;
const ID_SEPARATOR: &str = "-.-";
#[derive(Debug, Clone)]
struct EventEntry {
pub stream_id: StreamId,
pub time_stamp: u128,
pub message: String,
}
#[derive(Debug)]
pub struct InMemoryEventStore {
max_events_per_session: usize,
storage_map: RwLock<HashMap<SessionId, VecDeque<EventEntry>>>,
}
impl Default for InMemoryEventStore {
fn default() -> Self {
Self {
max_events_per_session: MAX_EVENTS_PER_SESSION,
storage_map: Default::default(),
}
}
}
/// In-memory implementation of the `EventStore` trait for MCP's Streamable HTTP transport.
///
/// Stores events in a `HashMap` of session IDs to `VecDeque`s of events, with a per-session limit.
/// Events are identified by `event_id` (format: `session-.-stream-.-timestamp`) and used for SSE resumption.
/// Thread-safe via `RwLock` for concurrent access.
impl InMemoryEventStore {
/// Creates a new `InMemoryEventStore` with an optional maximum events per session.
///
/// # Arguments
/// - `max_events_per_session`: Maximum number of events per session. Defaults to `MAX_EVENTS_PER_SESSION` (32) if `None`.
///
/// # Returns
/// A new `InMemoryEventStore` instance with an empty `HashMap` wrapped in a `RwLock`.
///
/// # Example
/// ```
/// let store = InMemoryEventStore::new(Some(10));
/// assert_eq!(store.max_events_per_session, 10);
/// ```
pub fn new(max_events_per_session: Option<usize>) -> Self {
Self {
max_events_per_session: max_events_per_session.unwrap_or(MAX_EVENTS_PER_SESSION),
storage_map: RwLock::new(HashMap::new()),
}
}
/// Generates an `event_id` string from session, stream, and timestamp components.
///
/// Format: `session-.-stream-.-timestamp`, used as a resumption cursor in SSE (`Last-Event-ID`).
///
/// # Arguments
/// - `session_id`: The session identifier.
/// - `stream_id`: The stream identifier.
/// - `time_stamp`: The event timestamp (u128).
///
/// # Returns
/// A `String` in the format `session-.-stream-.-timestamp`.
fn generate_event_id(
&self,
session_id: &SessionId,
stream_id: &StreamId,
time_stamp: u128,
) -> String {
format!("{session_id}{ID_SEPARATOR}{stream_id}{ID_SEPARATOR}{time_stamp}")
}
/// Parses an event ID into its session, stream, and timestamp components.
///
/// The event ID must follow the format `session-.-stream-.-timestamp`.
/// Returns `None` if the format is invalid, empty, or contains invalid characters (e.g., NULL).
///
/// # Arguments
/// - `event_id`: The event ID string to parse.
///
/// # Returns
/// An `Option` containing a tuple of `(session_id, stream_id, time_stamp)` as string slices,
/// or `None` if the format is invalid.
///
/// # Example
/// ```
/// let store = InMemoryEventStore::new(None);
/// let event_id = "session1-.-stream1-.-12345";
/// assert_eq!(
/// store.parse_event_id(event_id),
/// Some(("session1", "stream1", "12345"))
/// );
/// assert_eq!(store.parse_event_id("invalid"), None);
/// ```
pub fn parse_event_id<'a>(
&self,
event_id: &'a str,
) -> EventStoreResult<(&'a str, &'a str, u128)> {
// Check for empty input or invalid characters (e.g., NULL)
if event_id.is_empty() || event_id.contains('\0') {
return Err("Event ID is empty!".into());
}
// Split into exactly three parts
let parts: Vec<&'a str> = event_id.split(ID_SEPARATOR).collect();
if parts.len() != 3 {
return Err("Invalid Event ID format.".into());
}
let session_id = parts[0];
let stream_id = parts[1];
let time_stamp = parts[2];
// Ensure no part is empty
if session_id.is_empty() || stream_id.is_empty() || time_stamp.is_empty() {
return Err("Invalid Event ID format.".into());
}
let time_stamp: u128 = time_stamp
.parse()
.map_err(|err| format!("Error parsing timestamp: {err}"))?;
Ok((session_id, stream_id, time_stamp))
}
}
#[async_trait]
impl EventStore for InMemoryEventStore {
/// Stores an event for a given session and stream, returning its `event_id`.
///
/// Adds the event to the session’s `VecDeque`, removing the oldest event if the session
/// reaches `max_events_per_session`.
///
/// # Arguments
/// - `session_id`: The session identifier.
/// - `stream_id`: The stream identifier.
/// - `time_stamp`: The event timestamp (u128).
/// - `message`: The `ServerMessages` payload.
///
/// # Returns
/// The generated `EventId` for the stored event.
async fn store_event(
&self,
session_id: SessionId,
stream_id: StreamId,
time_stamp: u128,
message: String,
) -> EventStoreResult<EventId> {
let event_id = self.generate_event_id(&session_id, &stream_id, time_stamp);
let mut storage_map = self.storage_map.write().await;
tracing::trace!(
"Storing event for session: {session_id}, stream_id: {stream_id}, message: '{message}', {time_stamp} ",
);
let session_map = storage_map
.entry(session_id)
.or_insert_with(|| VecDeque::with_capacity(self.max_events_per_session));
if session_map.len() == self.max_events_per_session {
session_map.pop_front(); // remove the oldest if full
}
let entry = EventEntry {
stream_id,
time_stamp,
message,
};
session_map.push_back(entry);
Ok(event_id)
}
/// Removes all events associated with a given stream ID within a specific session.
///
/// Removes events matching `stream_id` from the specified `session_id`’s event queue.
/// If the session’s queue becomes empty, it is removed from the store.
/// Idempotent if `session_id` or `stream_id` doesn’t exist.
///
/// # Arguments
/// - `session_id`: The session identifier to target.
/// - `stream_id`: The stream identifier to remove.
async fn remove_stream_in_session(
&self,
session_id: SessionId,
stream_id: StreamId,
) -> EventStoreResult<()> {
let mut storage_map = self.storage_map.write().await;
// Check if session exists
if let Some(events) = storage_map.get_mut(&session_id) {
// Remove events with the given stream_id
events.retain(|event| event.stream_id != stream_id);
// Remove session if empty
if events.is_empty() {
storage_map.remove(&session_id);
};
}
// No action if session_id doesn’t exist (idempotent)
Ok(())
}
/// Removes all events associated with a given session ID.
///
/// Removes the entire session from the store. Idempotent if `session_id` doesn’t exist.
///
/// # Arguments
/// - `session_id`: The session identifier to remove.
async fn remove_by_session_id(&self, session_id: SessionId) -> EventStoreResult<()> {
let mut storage_map = self.storage_map.write().await;
storage_map.remove(&session_id);
Ok(())
}
/// Retrieves events after a given `event_id` for a specific session and stream.
///
/// Parses `last_event_id` to extract `session_id`, `stream_id`, and `time_stamp`.
/// Returns events after the matching event in the session’s stream, sorted by timestamp
/// in ascending order (earliest to latest). Returns `None` if the `event_id` is invalid,
/// the session doesn’t exist, or the timestamp is non-numeric.
///
/// # Arguments
/// - `last_event_id`: The event ID (format: `session-.-stream-.-timestamp`) to start after.
///
/// # Returns
/// An `Option` containing `EventStoreEntry` with the session ID, stream ID, and sorted messages,
/// or `None` if no events are found or the input is invalid.
async fn events_after(
&self,
last_event_id: EventId,
) -> EventStoreResult<Option<EventStoreEntry>> {
let (session_id, stream_id, time_stamp) = self.parse_event_id(&last_event_id)?;
let storage_map = self.storage_map.read().await;
// fail silently if session id does not exists
let Some(events) = storage_map.get(session_id) else {
tracing::warn!("could not find the session_id in the store : '{session_id}'");
return Ok(None);
};
let events = match events
.iter()
.position(|e| e.stream_id == stream_id && e.time_stamp == time_stamp)
{
Some(index) if index + 1 < events.len() => {
// Collect subsequent events that match the stream_id
let mut subsequent: Vec<_> = events
.range(index + 1..)
.filter(|e| e.stream_id == stream_id)
.cloned()
.collect();
subsequent.sort_by(|a, b| a.time_stamp.cmp(&b.time_stamp));
subsequent.iter().map(|e| e.message.clone()).collect()
}
_ => vec![],
};
tracing::trace!("{} messages after '{last_event_id}'", events.len());
Ok(Some(EventStoreEntry {
session_id: session_id.to_string(),
stream_id: stream_id.to_string(),
messages: events,
}))
}
async fn clear(&self) -> EventStoreResult<()> {
let mut storage_map = self.storage_map.write().await;
storage_map.clear();
Ok(())
}
async fn count(&self) -> EventStoreResult<usize> {
let storage_map = self.storage_map.read().await;
Ok(storage_map.len())
}
}
| rust | MIT | c25994d3d800242c1413b7401432f2a5bef3c23f | 2026-01-04T20:25:10.242745Z | false |
rust-mcp-stack/rust-mcp-sdk | https://github.com/rust-mcp-stack/rust-mcp-sdk/blob/c25994d3d800242c1413b7401432f2a5bef3c23f/crates/rust-mcp-transport/tests/check_imports.rs | crates/rust-mcp-transport/tests/check_imports.rs | #[cfg(test)]
mod tests {
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, MAIN_SEPARATOR_STR};
// List of files to exclude from the check
const EXCLUDED_FILES: &[&str] = &["src/schema.rs"];
// Check all .rs files for incorrect `use rust_mcp_schema` imports
#[test]
fn check_no_rust_mcp_schema_imports() {
let mut errors = Vec::new();
// Walk through the src directory
for entry in walk_src_dir("src").expect("Failed to read src directory") {
let entry = entry.unwrap();
let path = entry.path();
// only check files with .rs extension
if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("rs") {
let abs_path = path.to_string_lossy();
let relative_path = path.strip_prefix("src").unwrap_or(&path);
let path_str = relative_path.to_string_lossy();
// Skip excluded files
if EXCLUDED_FILES
.iter()
.any(|&excluded| abs_path.replace(MAIN_SEPARATOR_STR, "/") == excluded)
{
continue;
}
// Read the file content
match read_file(&path) {
Ok(content) => {
// Check for `use rust_mcp_schema`
if content.contains("use rust_mcp_schema") {
errors.push(format!(
"File {abs_path} contains `use rust_mcp_schema`. Use `use crate::schema` instead."
));
}
}
Err(e) => {
errors.push(format!("Failed to read file `{path_str}`: {e}"));
}
}
}
}
// If there are any errors, fail the test with all error messages
if !errors.is_empty() {
panic!(
"Found {} incorrect imports:\n{}\n\n",
errors.len(),
errors.join("\n")
);
}
}
// Helper function to walk the src directory
fn walk_src_dir<P: AsRef<Path>>(
path: P,
) -> io::Result<impl Iterator<Item = io::Result<std::fs::DirEntry>>> {
Ok(std::fs::read_dir(path)?.flat_map(|entry| {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
// Recursively walk subdirectories
walk_src_dir(&path)
.into_iter()
.flatten()
.collect::<Vec<_>>()
} else {
vec![Ok(entry)]
}
}))
}
// Helper function to read file content
fn read_file(path: &Path) -> io::Result<String> {
let mut file = File::open(path)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
}
| rust | MIT | c25994d3d800242c1413b7401432f2a5bef3c23f | 2026-01-04T20:25:10.242745Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/renderer/src/display_list.rs | renderer/src/display_list.rs | use std::{
collections::HashMap,
fmt::{Debug, Display},
hash::Hash,
mem,
ops::{Range, RangeInclusive},
sync::Mutex,
};
use cgmath::SquareMatrix;
use ldraw::{
color::{Color, ColorCatalog, ColorReference},
Matrix4, PartAlias, Vector4,
};
use ldraw_ir::model::{GroupId, Model, Object, ObjectGroup, ObjectId, ObjectInstance};
use uuid::Uuid;
use wgpu::util::DeviceExt;
use crate::{Entity, GpuUpdate, GpuUpdateResult};
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct InstanceData {
model_matrix: [[f32; 4]; 4],
color: [f32; 4],
edge_color: [f32; 4],
}
impl InstanceData {
pub fn get_matrix(&self) -> Matrix4 {
self.model_matrix.into()
}
pub fn get_color(&self) -> Vector4 {
self.color.into()
}
pub fn get_edge_color(&self) -> Vector4 {
self.edge_color.into()
}
}
#[derive(Debug)]
struct InstanceTransaction<K> {
rows_to_insert: HashMap<K, (Matrix4, Vector4, Vector4)>,
rows_to_remove: Vec<K>,
changed_indices: Vec<usize>,
}
impl<K> Default for InstanceTransaction<K> {
fn default() -> Self {
Self {
rows_to_insert: HashMap::new(),
rows_to_remove: Vec::new(),
changed_indices: Vec::new(),
}
}
}
#[derive(Debug)]
pub struct Instances<K, G> {
group: G,
index: HashMap<K, usize>,
instance_data: Vec<InstanceData>,
pub instance_buffer: Option<wgpu::Buffer>,
transaction: Mutex<Option<InstanceTransaction<K>>>,
}
impl<K, G> Instances<K, G> {
pub fn count(&self) -> usize {
self.instance_data.len()
}
pub fn range(&self) -> Range<u32> {
0..self.count() as u32
}
pub fn is_empty(&self) -> bool {
self.count() == 0
}
fn update_buffer_partial(&self, queue: &wgpu::Queue, range: RangeInclusive<usize>) {
if let Some(buffer) = &self.instance_buffer {
queue.write_buffer(
buffer,
(range.start() * mem::size_of::<InstanceData>()) as wgpu::BufferAddress,
bytemuck::cast_slice(&self.instance_data[range]),
)
}
}
pub fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<InstanceData>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 10,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress,
shader_location: 11,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress,
shader_location: 12,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 12]>() as wgpu::BufferAddress,
shader_location: 13,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 16]>() as wgpu::BufferAddress,
shader_location: 14,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 20]>() as wgpu::BufferAddress,
shader_location: 15,
format: wgpu::VertexFormat::Float32x4,
},
],
}
}
}
impl<K, G: Display> Instances<K, G> {
fn rebuild_buffer(&mut self, device: &wgpu::Device) {
self.instance_buffer = Some(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!("Instance buffer for {}", self.group)),
contents: bytemuck::cast_slice(&self.instance_data),
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
}),
);
}
}
impl<
K: Clone + Debug + Eq + PartialEq + Hash + Display,
G: Clone + Eq + PartialEq + Hash + Display,
> Instances<K, G>
{
pub fn new(group: G) -> Self {
Self {
group,
index: HashMap::new(),
instance_data: Vec::new(),
instance_buffer: None,
transaction: Mutex::new(None),
}
}
}
#[derive(Debug)]
pub enum InstanceOps<K> {
Insert {
key: K,
matrix: Matrix4,
color: Vector4,
edge_color: Vector4,
},
Update {
key: K,
matrix: Matrix4,
color: Vector4,
edge_color: Vector4,
},
UpdateMatrix {
key: K,
matrix: Matrix4,
},
UpdateColor {
key: K,
color: Vector4,
edge_color: Vector4,
},
UpdateAlpha {
key: K,
alpha: f32,
},
Remove(K),
}
impl<K: Clone + Eq + PartialEq + Hash + Debug, G: Display> GpuUpdate for Instances<K, G> {
type Mutator = InstanceOps<K>;
fn mutate(&mut self, mutator: Self::Mutator) -> GpuUpdateResult<Self::Mutator> {
let mut tr_lock = self.transaction.lock().unwrap();
let tr = tr_lock.get_or_insert_with(Default::default);
match mutator {
InstanceOps::Insert {
key,
matrix,
color,
edge_color,
} => {
tr.rows_to_insert.insert(key, (matrix, color, edge_color));
}
InstanceOps::Remove(key) => {
tr.rows_to_insert.remove(&key);
tr.rows_to_remove.push(key);
}
InstanceOps::Update {
key,
matrix,
color,
edge_color,
} => {
if let Some(entry_idx) = self.index.get(&key).cloned() {
let data = &mut self.instance_data[entry_idx];
data.model_matrix = matrix.into();
data.color = color.into();
data.edge_color = edge_color.into();
tr.changed_indices.push(entry_idx);
} else if let Some(entry) = tr.rows_to_insert.get_mut(&key) {
entry.0 = matrix;
entry.1 = color;
entry.2 = edge_color;
}
}
InstanceOps::UpdateMatrix { key, matrix } => {
if let Some(entry_idx) = self.index.get(&key).cloned() {
let data = &mut self.instance_data[entry_idx];
data.model_matrix = matrix.into();
tr.changed_indices.push(entry_idx);
} else if let Some(entry) = tr.rows_to_insert.get_mut(&key) {
entry.0 = matrix;
}
}
InstanceOps::UpdateColor {
key,
color,
edge_color,
} => {
if let Some(entry_idx) = self.index.get(&key).cloned() {
let data = &mut self.instance_data[entry_idx];
data.color = color.into();
data.edge_color = edge_color.into();
tr.changed_indices.push(entry_idx);
} else if let Some(entry) = tr.rows_to_insert.get_mut(&key) {
entry.1 = color;
entry.2 = edge_color;
}
}
InstanceOps::UpdateAlpha { key, alpha } => {
if let Some(entry_idx) = self.index.get(&key).cloned() {
let data = &mut self.instance_data[entry_idx];
data.color[3] = alpha;
data.edge_color[3] = alpha;
tr.changed_indices.push(entry_idx);
} else if let Some(entry) = tr.rows_to_insert.get_mut(&key) {
entry.1.w = alpha;
entry.2.w = alpha;
}
}
}
GpuUpdateResult::Modified
}
fn handle_gpu_update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
let Some(mut tr) = self.transaction.lock().unwrap().take() else {
return;
};
let mut layout_changed = false;
let mut rows_to_remove = tr
.rows_to_remove
.into_iter()
.filter_map(|key| self.index.get(&key).map(|v| (key, *v)))
.collect::<Vec<_>>();
rows_to_remove.sort_by_key(|v| std::cmp::Reverse(v.1));
for (key, (matrix, color, edge_color)) in tr.rows_to_insert.into_iter() {
if let Some((old_key, idx_to_reuse)) = rows_to_remove.pop() {
// Take over removed rows and fill with inserted ones if available
let data = &mut self.instance_data[idx_to_reuse];
data.model_matrix = matrix.into();
data.color = color.into();
data.edge_color = edge_color.into();
self.index.remove(&old_key);
self.index.insert(key, idx_to_reuse);
tr.changed_indices.push(idx_to_reuse);
} else {
// Insert new rows
layout_changed = true;
self.instance_data.push(InstanceData {
model_matrix: matrix.into(),
color: color.into(),
edge_color: edge_color.into(),
});
self.index.insert(key, self.instance_data.len() - 1);
}
}
// Remove rows
if !rows_to_remove.is_empty() {
let mut reverse_lookup = self
.index
.clone()
.into_iter()
.map(|(k, v)| (v, k))
.collect::<HashMap<_, _>>();
for (key, index) in rows_to_remove.iter() {
let last = self.instance_data.len() - 1;
if let Some(last_key) = reverse_lookup.get(&last) {
self.index.insert(last_key.clone(), *index);
reverse_lookup.insert(*index, last_key.clone());
}
self.index.remove(key);
reverse_lookup.remove(&last);
self.instance_data.swap_remove(*index);
layout_changed = true;
}
}
if layout_changed || self.instance_buffer.is_none() {
self.rebuild_buffer(device);
} else if !tr.changed_indices.is_empty() {
tr.changed_indices.sort();
let mut start = tr.changed_indices[0];
let mut end = start;
for index in tr.changed_indices {
if index > end + 1 {
self.update_buffer_partial(queue, start..=end);
start = index;
end = index;
} else {
end = index;
}
}
self.update_buffer_partial(queue, start..=end);
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
enum GroupKind {
Opaque,
Translucent,
}
impl GroupKind {
pub fn is_translucent(&self) -> bool {
matches!(self, GroupKind::Translucent)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
struct Group<G>(GroupKind, G);
#[derive(Debug, Default)]
pub struct DisplayList<K, G> {
map: HashMap<Group<G>, Entity<Instances<K, G>>>,
lookup_table: HashMap<K, Group<G>>,
}
impl<K, G> DisplayList<K, G> {
pub fn new() -> Self {
Self {
map: HashMap::new(),
lookup_table: HashMap::new(),
}
}
pub fn iter(&self) -> impl Iterator<Item = (&G, bool, &Entity<Instances<K, G>>)> {
self.map
.iter()
.map(|(k, v)| (&k.1, matches!(k.0, GroupKind::Translucent), v))
}
pub fn iter_opaque(&self) -> impl Iterator<Item = (&G, &Entity<Instances<K, G>>)> {
self.map.iter().filter_map(|(k, v)| {
if matches!(k.0, GroupKind::Opaque) {
Some((&k.1, v))
} else {
None
}
})
}
pub fn iter_translucent(&self) -> impl Iterator<Item = (&G, &Entity<Instances<K, G>>)> {
self.map.iter().filter_map(|(k, v)| {
if matches!(k.0, GroupKind::Translucent) {
Some((&k.1, v))
} else {
None
}
})
}
}
impl<
K: Clone + Debug + Eq + PartialEq + Hash + Display,
G: Clone + Eq + PartialEq + Hash + Display,
> DisplayList<K, G>
{
fn get_or_create(&mut self, group: Group<G>) -> &mut Entity<Instances<K, G>> {
self.map
.entry(group.clone())
.or_insert_with(|| Instances::new(group.1).into())
}
pub fn get_by_key(&self, k: &K) -> Option<&Entity<Instances<K, G>>> {
if let Some(group) = self.lookup_table.get(k) {
self.map.get(group)
} else {
None
}
}
}
fn uuid_xor(a: ObjectId, b: ObjectId) -> ObjectId {
let ba = Uuid::from(a).to_bytes_le();
let bb = Uuid::from(b).to_bytes_le();
let bc: Vec<_> = ba.iter().zip(bb).map(|(x, y)| x ^ y).collect();
Uuid::from_slice(&bc).unwrap().into()
}
impl<P: Clone + Eq + PartialEq + Hash + From<PartAlias> + Display> DisplayList<ObjectId, P> {
fn expand_object_group(
ops: &mut Vec<DisplayListOps<ObjectId, P>>,
color_catalog: &ColorCatalog,
parent_id: ObjectId,
groups: &HashMap<GroupId, ObjectGroup<P>>,
objects: &[Object<P>],
matrix: Matrix4,
color: ColorReference,
) {
for object in objects.iter() {
match &object.data {
ObjectInstance::Part(p) => {
let local_matrix = matrix * p.matrix;
let color_ref = if p.color.is_current() {
&color
} else {
&p.color
};
let color = match color_ref {
ColorReference::Color(c) => c,
_ => color_catalog.get(&0).unwrap(),
};
ops.push(DisplayListOps::Insert {
group: p.part.clone(),
key: uuid_xor(parent_id, object.id),
matrix: local_matrix,
color: color.clone(),
alpha: None,
});
}
ObjectInstance::PartGroup(g) => {
if let Some(group) = groups.get(&g.group_id) {
let color = if g.color.is_current() {
&color
} else {
&g.color
}
.clone();
Self::expand_object_group(
ops,
color_catalog,
uuid_xor(parent_id, object.id),
groups,
&group.objects,
matrix * g.matrix,
color,
);
}
}
_ => {}
}
}
}
pub fn from_model(
model: &Model<P>,
group_id: Option<GroupId>,
color_catalog: &ColorCatalog,
) -> Entity<Self> {
let mut display_list = Entity::new(Self::new());
let objects = match group_id {
Some(group_id) => model.object_groups.get(&group_id).map(|v| &v.objects),
None => Some(&model.objects),
};
let mut ops = vec![];
if let Some(objects) = objects {
Self::expand_object_group(
&mut ops,
color_catalog,
Uuid::nil().into(),
&model.object_groups,
objects,
Matrix4::identity(),
ColorReference::Color(color_catalog.get(&0).cloned().unwrap()),
)
}
display_list.mutate_all(ops.into_iter());
display_list
}
}
pub struct DisplayListOpsReinstantiate<G, K> {
group: Group<G>,
key: K,
matrix: Matrix4,
color: Vector4,
edge_color: Vector4,
}
pub enum DisplayListOps<K, G> {
Insert {
group: G,
key: K,
matrix: Matrix4,
color: Color,
alpha: Option<f32>,
},
Update {
key: K,
matrix: Matrix4,
color: Color,
},
UpdateMatrix {
key: K,
matrix: Matrix4,
},
UpdateColor {
key: K,
color: Color,
},
UpdateAlpha {
key: K,
alpha: f32,
},
Remove {
key: K,
},
_Reinstantiate(DisplayListOpsReinstantiate<G, K>),
}
impl<
K: Clone + Debug + Eq + PartialEq + Hash + Display,
G: Clone + Eq + PartialEq + Hash + Display,
> GpuUpdate for DisplayList<K, G>
{
type Mutator = DisplayListOps<K, G>;
fn mutate(&mut self, mutator: Self::Mutator) -> GpuUpdateResult<Self::Mutator> {
match mutator {
DisplayListOps::Insert {
group,
key,
matrix,
color,
alpha,
} => {
let mut main_color: Vector4 = color.color.into();
let mut edge_color: Vector4 = color.edge.into();
if self.lookup_table.contains_key(&key) {
GpuUpdateResult::NotModified
} else {
let is_translucent = main_color.w < 1.0 || alpha.unwrap_or(1.0) < 1.0;
let group = if is_translucent {
Group(GroupKind::Translucent, group)
} else {
Group(GroupKind::Opaque, group)
};
self.lookup_table.insert(key.clone(), group.clone());
if let Some(alpha) = alpha {
main_color.w = alpha;
edge_color.w = alpha;
}
self.lookup_table.insert(key.clone(), group.clone());
let entity = self.get_or_create(group);
entity
.mutate(InstanceOps::Insert {
key,
matrix,
color: main_color,
edge_color,
})
.into()
}
}
DisplayListOps::Update { key, matrix, color } => {
if let Some(group) = self.lookup_table.get(&key) {
if group.0.is_translucent() != color.is_translucent() {
let id = group.1.clone();
let new_group = if color.is_translucent() {
Group(GroupKind::Translucent, id)
} else {
Group(GroupKind::Opaque, id)
};
GpuUpdateResult::AdditionalMutations {
modified: false,
mutations: vec![DisplayListOps::_Reinstantiate(
DisplayListOpsReinstantiate {
group: new_group,
key,
matrix,
color: color.color.into(),
edge_color: color.edge.into(),
},
)],
}
} else if let Some(instances) = self.map.get_mut(group) {
instances
.mutate(InstanceOps::Update {
key,
matrix,
color: color.color.into(),
edge_color: color.edge.into(),
})
.into()
} else {
GpuUpdateResult::NotModified
}
} else {
GpuUpdateResult::NotModified
}
}
DisplayListOps::UpdateAlpha { key, alpha } => {
let is_translucent = alpha < 1.0;
if let Some((group, instances)) = self
.lookup_table
.get(&key)
.and_then(|g| self.map.get_mut(g).map(|v| (g.clone(), v)))
{
if group.0.is_translucent() != is_translucent {
let id = group.1.clone();
let group = if is_translucent {
Group(GroupKind::Translucent, id)
} else {
Group(GroupKind::Opaque, id)
};
let Some(index) = instances.get().index.get(&key) else {
return GpuUpdateResult::NotModified;
};
let instance = instances.get().instance_data[*index];
let mut color = instance.get_color();
color.w = alpha;
let mut edge_color = instance.get_edge_color();
edge_color.w = alpha;
GpuUpdateResult::AdditionalMutations {
modified: false,
mutations: vec![DisplayListOps::_Reinstantiate(
DisplayListOpsReinstantiate {
group,
key,
matrix: instance.get_matrix(),
color,
edge_color,
},
)],
}
} else if let Some(entity) = self.map.get_mut(&group) {
entity
.mutate(InstanceOps::UpdateAlpha { key, alpha })
.into()
} else {
GpuUpdateResult::NotModified
}
} else {
GpuUpdateResult::NotModified
}
}
DisplayListOps::UpdateColor { key, color } => {
if let Some((group, instances)) = self
.lookup_table
.get(&key)
.and_then(|g| self.map.get_mut(g).map(|v| (g.clone(), v)))
{
if group.0.is_translucent() != color.is_translucent() {
let id = group.1.clone();
let group = if color.is_translucent() {
Group(GroupKind::Translucent, id)
} else {
Group(GroupKind::Opaque, id)
};
let Some(index) = instances.get().index.get(&key) else {
return GpuUpdateResult::NotModified;
};
let instance = instances.get().instance_data[*index];
GpuUpdateResult::AdditionalMutations {
modified: false,
mutations: vec![DisplayListOps::_Reinstantiate(
DisplayListOpsReinstantiate {
group,
key,
matrix: instance.get_matrix(),
color: color.color.into(),
edge_color: color.edge.into(),
},
)],
}
} else if let Some(entity) = self.map.get_mut(&group) {
entity
.mutate(InstanceOps::UpdateColor {
key,
color: color.color.into(),
edge_color: color.edge.into(),
})
.into()
} else {
GpuUpdateResult::NotModified
}
} else {
GpuUpdateResult::NotModified
}
}
DisplayListOps::UpdateMatrix { key, matrix } => {
let Some(group) = self.lookup_table.get(&key) else {
return GpuUpdateResult::NotModified;
};
if let Some(entity) = self.map.get_mut(group) {
entity
.mutate(InstanceOps::UpdateMatrix { key, matrix })
.into()
} else {
GpuUpdateResult::NotModified
}
}
DisplayListOps::Remove { key } => {
let Some(group) = self.lookup_table.remove(&key) else {
return GpuUpdateResult::NotModified;
};
let Some(entity) = self.map.get_mut(&group) else {
return GpuUpdateResult::NotModified;
};
if entity.mutate(InstanceOps::Remove(key.clone())) {
self.lookup_table.remove(&key);
if (*entity).count() == 0 {
self.map.remove(&group);
}
GpuUpdateResult::Modified
} else {
GpuUpdateResult::NotModified
}
}
DisplayListOps::_Reinstantiate(DisplayListOpsReinstantiate {
group,
key,
matrix,
color,
edge_color,
}) => {
let Some(prev_group) = self.lookup_table.remove(&key) else {
return GpuUpdateResult::NotModified;
};
let Some(entity) = self.map.get_mut(&prev_group) else {
return GpuUpdateResult::NotModified;
};
entity.mutate(InstanceOps::Remove(key.clone()));
if self
.get_or_create(group.clone())
.mutate(InstanceOps::Insert {
key: key.clone(),
matrix,
color,
edge_color,
})
{
self.lookup_table.insert(key.clone(), group);
GpuUpdateResult::Modified
} else {
GpuUpdateResult::NotModified
}
}
}
}
fn handle_gpu_update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
for entity in self.map.values_mut() {
entity.update(device, queue);
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct SelectionInstanceData {
model_matrix: [[f32; 4]; 4],
instance_id: u32,
_padding: [u32; 3],
}
#[derive(Debug)]
pub struct SelectionInstances {
instance_data: Vec<SelectionInstanceData>,
pub instance_buffer: wgpu::Buffer,
}
impl SelectionInstances {
pub fn new(device: &wgpu::Device, instance_data: Vec<SelectionInstanceData>) -> Self {
let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Instance buffer for object selections"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
});
Self {
instance_data,
instance_buffer,
}
}
pub fn count(&self) -> usize {
self.instance_data.len()
}
pub fn range(&self) -> Range<u32> {
0..self.count() as u32
}
pub fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<SelectionInstanceData>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 10,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress,
shader_location: 11,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress,
shader_location: 12,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 12]>() as wgpu::BufferAddress,
shader_location: 13,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 16]>() as wgpu::BufferAddress,
shader_location: 14,
format: wgpu::VertexFormat::Uint32,
},
],
}
}
}
#[derive(Debug, Default)]
pub struct SelectionDisplayList<G, K> {
map: HashMap<G, SelectionInstances>,
lookup_table: HashMap<u32, K>,
}
impl<G, K: Clone> SelectionDisplayList<G, K> {
pub fn new(map: HashMap<G, SelectionInstances>, lookup_table: HashMap<u32, K>) -> Self {
Self { map, lookup_table }
}
pub fn iter(&self) -> impl Iterator<Item = (&G, &SelectionInstances)> {
self.map.iter()
}
pub fn get_matches(
&self,
result: impl Iterator<Item = u32> + 'static,
) -> impl Iterator<Item = K> + '_ {
result.filter_map(|v| self.lookup_table.get(&v).cloned())
}
}
impl<G: Clone + Eq + PartialEq + Hash + From<PartAlias> + Display>
SelectionDisplayList<G, ObjectId>
{
#[allow(clippy::too_many_arguments)]
fn expand_object_group(
data: &mut HashMap<G, Vec<SelectionInstanceData>>,
lookup_table: &mut HashMap<u32, ObjectId>,
cur_instance_id: &mut u32,
use_parent_object_id: bool,
parent_id: ObjectId,
groups: &HashMap<GroupId, ObjectGroup<G>>,
objects: &[Object<G>],
matrix: Matrix4,
depth: u32,
) {
for object in objects.iter() {
match &object.data {
ObjectInstance::Part(p) => {
let id = if depth == 0 {
object.id
} else if use_parent_object_id {
parent_id
} else {
uuid_xor(parent_id, object.id)
};
lookup_table.insert(*cur_instance_id, id);
data.entry(p.part.clone())
.or_default()
.push(SelectionInstanceData {
model_matrix: (matrix * p.matrix).into(),
instance_id: *cur_instance_id,
_padding: [0; 3],
});
*cur_instance_id += 1;
}
ObjectInstance::PartGroup(g) => {
if let Some(group) = groups.get(&g.group_id) {
Self::expand_object_group(
data,
lookup_table,
cur_instance_id,
use_parent_object_id,
object.id,
groups,
&group.objects,
matrix * g.matrix,
depth + 1,
);
}
}
_ => {}
}
}
}
pub fn from_model(
model: &Model<G>,
group_id: Option<GroupId>,
device: &wgpu::Device,
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | true |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/renderer/src/lib.rs | renderer/src/lib.rs | pub mod display_list;
mod entity;
pub mod error;
pub mod part;
pub mod pipeline;
pub mod projection;
pub mod util;
pub use entity::{Entity, GpuUpdate, GpuUpdateResult};
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct AspectRatio(f32);
impl From<(u32, u32)> for AspectRatio {
fn from((width, height): (u32, u32)) -> Self {
Self(width as f32 / height as f32)
}
}
impl From<AspectRatio> for f32 {
fn from(value: AspectRatio) -> f32 {
value.0
}
}
impl From<f32> for AspectRatio {
fn from(value: f32) -> Self {
Self(value)
}
}
#[derive(Clone, Debug)]
pub enum ObjectSelection {
Point(cgmath::Point2<f32>),
Range(ldraw_ir::geometry::BoundingBox2),
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/renderer/src/entity.rs | renderer/src/entity.rs | const MAX_ITERATIONS: i32 = 10;
pub enum GpuUpdateResult<M> {
Modified,
NotModified,
AdditionalMutations { modified: bool, mutations: Vec<M> },
}
impl<M> From<bool> for GpuUpdateResult<M> {
fn from(value: bool) -> Self {
if value {
Self::Modified
} else {
Self::NotModified
}
}
}
pub trait GpuUpdate {
type Mutator;
fn mutate(&mut self, mutator: Self::Mutator) -> GpuUpdateResult<Self::Mutator>;
fn handle_gpu_update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue);
}
#[derive(Debug)]
pub struct Entity<I> {
inner: I,
modified: bool,
}
impl<I> std::ops::Deref for Entity<I> {
type Target = I;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<I: GpuUpdate> Entity<I> {
pub fn new(inner: I) -> Self {
Self {
inner,
modified: true,
}
}
pub fn get(&self) -> &I {
&self.inner
}
fn mutate_inner(&mut self, mutator: I::Mutator, iteration: i32) -> bool {
if iteration >= MAX_ITERATIONS {
println!("Nested mutations more than {MAX_ITERATIONS} depths are not allowed");
false
} else {
match self.inner.mutate(mutator) {
GpuUpdateResult::Modified => true,
GpuUpdateResult::NotModified => false,
GpuUpdateResult::AdditionalMutations {
mut modified,
mutations,
} => {
for mutator in mutations {
if self.mutate_inner(mutator, iteration + 1) {
modified = true;
}
}
modified
}
}
}
}
pub fn mutate(&mut self, mutator: I::Mutator) -> bool {
if self.mutate_inner(mutator, 0) {
self.modified = true;
true
} else {
false
}
}
pub fn mutate_all<T: Iterator<Item = I::Mutator>>(&mut self, mutators: T) -> bool {
let mut modified = false;
for mutator in mutators {
if self.mutate_inner(mutator, 0) {
modified = true;
}
}
if modified {
self.modified = true;
}
modified
}
pub fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool {
if self.modified {
self.inner.handle_gpu_update(device, queue);
self.modified = false;
true
} else {
false
}
}
}
impl<I: GpuUpdate> From<I> for Entity<I> {
fn from(value: I) -> Self {
Self {
inner: value,
modified: true,
}
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/renderer/src/error.rs | renderer/src/error.rs | #[derive(thiserror::Error, Debug)]
pub enum ObjectSelectionError {
#[error("Selection coordinate is out of range: {0:?}")]
OutOfRange(crate::ObjectSelection),
#[error("Async buffer read error: {0}")]
AsyncBufferReadError(#[from] wgpu::BufferAsyncError),
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/renderer/src/util.rs | renderer/src/util.rs | use std::hash::Hash;
use cgmath::SquareMatrix;
use ldraw::Matrix4;
use ldraw_ir::{
geometry::BoundingBox3,
model::{self, GroupId},
};
use crate::part::PartQuerier;
pub async fn request_device(
adapter: &wgpu::Adapter,
label: Option<&str>,
) -> Result<(wgpu::Device, wgpu::Queue, u32), wgpu::RequestDeviceError> {
let texture_sizes = vec![8192, 4096, 2048];
let mut error = None;
for texture_size in texture_sizes {
let required_limits = wgpu::Limits {
max_texture_dimension_2d: texture_size,
..wgpu::Limits::downlevel_webgl2_defaults()
};
match adapter
.request_device(&wgpu::DeviceDescriptor {
label,
required_features: wgpu::Features::default(),
required_limits,
memory_hints: Default::default(),
trace: wgpu::Trace::Off,
})
.await
{
Ok((device, queue)) => return Ok((device, queue, texture_size)),
Err(e) => {
error = Some(e);
}
}
}
Err(error.unwrap())
}
fn calculate_bounding_box_recursive<K: Clone + Eq + PartialEq + Hash, Q: PartQuerier<K>>(
bb: &mut BoundingBox3,
parts: &Q,
matrix: Matrix4,
items: &[model::Object<K>],
model: &model::Model<K>,
) {
for item in items.iter() {
match &item.data {
model::ObjectInstance::Part(p) => {
if let Some(embedded_part) = model.embedded_parts.get(&p.part) {
bb.update(&embedded_part.bounding_box.transform(&(matrix * p.matrix)));
} else if let Some(part) = parts.get(&p.part) {
bb.update(&part.bounding_box.transform(&(matrix * p.matrix)));
}
}
model::ObjectInstance::PartGroup(pg) => {
if let Some(group) = model.object_groups.get(&pg.group_id) {
calculate_bounding_box_recursive(
bb,
parts,
matrix * pg.matrix,
&group.objects,
model,
);
}
}
_ => {}
}
}
}
pub fn calculate_model_bounding_box<K: Clone + Eq + PartialEq + Hash, Q: PartQuerier<K>>(
model: &model::Model<K>,
group_id: Option<GroupId>,
parts: &Q,
) -> BoundingBox3 {
let mut bb = BoundingBox3::nil();
if let Some(group_id) = group_id {
if let Some(subpart) = model.object_groups.get(&group_id) {
calculate_bounding_box_recursive(
&mut bb,
parts,
Matrix4::identity(),
&subpart.objects,
model,
);
}
} else {
calculate_bounding_box_recursive(
&mut bb,
parts,
Matrix4::identity(),
&model.objects,
model,
);
}
bb
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/renderer/src/projection.rs | renderer/src/projection.rs | use std::{collections::HashSet, hash::Hash};
use cgmath::{prelude::*, Deg, Matrix, Ortho, PerspectiveFov, Point3, SquareMatrix};
use ldraw::{Matrix3, Matrix4, Vector2, Vector3};
use ldraw_ir::geometry::{BoundingBox2, BoundingBox3};
use wgpu::util::DeviceExt;
use crate::{AspectRatio, GpuUpdate, GpuUpdateResult};
struct ProjectionData {
model_matrix_stack: Vec<Matrix4>,
projection_matrix: Matrix4,
view_matrix: Matrix4,
is_orthographic: bool,
}
pub enum ProjectionMutator {
PushModelMatrix(Matrix4),
PopModelMatrix,
SetProjectionMatrix {
matrix: Matrix4,
is_orthographic: bool,
},
SetViewMatrix(Matrix4),
}
impl ProjectionData {
fn push_model_matrix(&mut self, mat: Matrix4) -> Matrix4 {
let multiplied = self.model_matrix_stack.last().cloned().unwrap() * mat;
self.model_matrix_stack.push(multiplied);
multiplied
}
fn pop_model_matrix(&mut self) -> Option<Matrix4> {
if self.model_matrix_stack.len() > 1 {
self.model_matrix_stack.pop();
self.model_matrix_stack.last().cloned()
} else {
None
}
}
}
impl Default for ProjectionData {
fn default() -> Self {
Self {
model_matrix_stack: vec![Matrix4::identity()],
projection_matrix: Matrix4::identity(),
view_matrix: Matrix4::identity(),
is_orthographic: false,
}
}
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct RawProjectionData {
model_matrix: [[f32; 4]; 4],
projection_matrix: [[f32; 4]; 4],
view_matrix: [[f32; 4]; 4],
normal_matrix_0: [f32; 3],
_padding0: [u8; 4],
normal_matrix_1: [f32; 3],
_padding1: [u8; 4],
normal_matrix_2: [f32; 3],
_padding2: [u8; 4],
is_orthographic: i32,
_padding3: [u8; 12],
}
impl Default for RawProjectionData {
fn default() -> Self {
Self {
model_matrix: Matrix4::identity().into(),
projection_matrix: Matrix4::identity().into(),
view_matrix: Matrix4::identity().into(),
normal_matrix_0: [1.0, 0.0, 0.0],
_padding0: [0; 4],
normal_matrix_1: [0.0, 1.0, 0.0],
_padding1: [0; 4],
normal_matrix_2: [0.0, 0.0, 1.0],
_padding2: [0; 4],
is_orthographic: 0,
_padding3: [0; 12],
}
}
}
impl RawProjectionData {
#[rustfmt::skip]
fn truncate_matrix4(m: Matrix4) -> Matrix3 {
Matrix3::new(
m[0][0], m[0][1], m[0][2],
m[1][0], m[1][1], m[1][2],
m[2][0], m[2][1], m[2][2],
)
}
fn derive_normal_matrix(m: Matrix4) -> Option<Matrix3> {
Self::truncate_matrix4(m).invert().map(|v| v.transpose())
}
fn update_normal_matrix(&mut self, model_view: Matrix4) {
let normal_matrix =
Self::derive_normal_matrix(model_view).unwrap_or_else(Matrix3::identity);
self.normal_matrix_0 = normal_matrix.x.into();
self.normal_matrix_1 = normal_matrix.y.into();
self.normal_matrix_2 = normal_matrix.z.into();
}
}
pub struct Projection {
pub bind_group: Option<wgpu::BindGroup>,
uniform_buffer: Option<wgpu::Buffer>,
data: ProjectionData,
raw: RawProjectionData,
}
impl GpuUpdate for Projection {
type Mutator = ProjectionMutator;
fn mutate(&mut self, mutator: Self::Mutator) -> GpuUpdateResult<Self::Mutator> {
match mutator {
ProjectionMutator::PushModelMatrix(matrix) => {
let mat = self.data.push_model_matrix(matrix);
self.raw.model_matrix = mat.into();
self.raw.update_normal_matrix(self.data.view_matrix * mat);
GpuUpdateResult::Modified
}
ProjectionMutator::PopModelMatrix => {
if let Some(mat) = self.data.pop_model_matrix() {
self.raw.model_matrix = mat.into();
self.raw.update_normal_matrix(self.data.view_matrix * mat);
GpuUpdateResult::Modified
} else {
GpuUpdateResult::NotModified
}
}
ProjectionMutator::SetProjectionMatrix {
matrix,
is_orthographic,
} => {
if self.data.projection_matrix != matrix
|| self.data.is_orthographic != is_orthographic
{
self.data.projection_matrix = matrix;
self.data.is_orthographic = is_orthographic;
self.raw.projection_matrix = matrix.into();
self.raw.is_orthographic = if is_orthographic { 1 } else { 0 };
GpuUpdateResult::Modified
} else {
GpuUpdateResult::NotModified
}
}
ProjectionMutator::SetViewMatrix(matrix) => {
if self.data.view_matrix != matrix {
self.data.view_matrix = matrix;
self.raw.view_matrix = matrix.into();
self.raw.update_normal_matrix(self.get_model_view_matrix());
GpuUpdateResult::Modified
} else {
GpuUpdateResult::NotModified
}
}
}
}
fn handle_gpu_update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
let uniform_buffer = self.uniform_buffer.get_or_insert_with(|| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Uniform buffer for projection"),
contents: bytemuck::cast_slice(&[self.raw]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
})
});
if self.bind_group.is_none() {
self.bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Bind group for projection"),
layout: &device.create_bind_group_layout(&Self::desc()),
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
}],
}));
}
queue.write_buffer(
uniform_buffer,
0 as wgpu::BufferAddress,
bytemuck::cast_slice(&[self.raw]),
);
}
}
impl Projection {
pub fn new() -> Self {
let data = ProjectionData::default();
let raw = RawProjectionData::default();
Self {
uniform_buffer: None,
bind_group: None,
data,
raw,
}
}
pub fn get_model_view_matrix(&self) -> Matrix4 {
self.data.view_matrix * self.data.model_matrix_stack.last().unwrap()
}
pub fn select_objects<T: Eq + PartialEq + Hash>(
&self,
area: &BoundingBox2,
objects: impl Iterator<Item = (T, Matrix4, BoundingBox3)>,
) -> HashSet<T> {
let mvp = self.data.projection_matrix * self.get_model_view_matrix();
objects
.filter_map(|(id, matrix, bb)| {
if bb.project(&(mvp * matrix)).intersects(area) {
Some(id)
} else {
None
}
})
.collect::<HashSet<_>>()
}
pub fn desc() -> wgpu::BindGroupLayoutDescriptor<'static> {
wgpu::BindGroupLayoutDescriptor {
label: Some("Bind group descriptor for projection"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
}
}
}
impl Default for Projection {
fn default() -> Self {
Self::new()
}
}
pub trait ProjectionModifier {
fn update_projections(&self, aspect_ratio: AspectRatio) -> Vec<ProjectionMutator>;
}
#[derive(Clone, Debug)]
pub enum ViewBounds {
BoundingBox3(BoundingBox3),
BoundingBox2(BoundingBox2),
Radius(f32),
Unbounded,
}
impl ViewBounds {
pub fn fraction(&self, model_view: &Matrix4) -> Option<BoundingBox2> {
match self {
Self::BoundingBox3(bb) => {
let transformed_bb = {
let mut pbb = BoundingBox2::nil();
for point in bb.points() {
let p = model_view * point.extend(1.0);
pbb.update_point(&Vector2::new(p.x, p.y));
}
pbb
};
if transformed_bb.len_x() >= transformed_bb.len_y() {
let d = (transformed_bb.len_x() - transformed_bb.len_y()) * 0.5;
let fd = d / transformed_bb.len_x();
Some(BoundingBox2::new(
&Vector2::new(0.0, fd),
&Vector2::new(1.0, 1.0 - fd),
))
} else {
let d = (transformed_bb.len_y() - transformed_bb.len_x()) * 0.5;
let fd = d / transformed_bb.len_y();
Some(BoundingBox2::new(
&Vector2::new(fd, 0.0),
&Vector2::new(1.0 - fd, 1.0),
))
}
}
_ => None,
}
}
pub fn project(&self, model_view: &Matrix4, aspect_ratio: AspectRatio) -> BoundingBox2 {
let aspect_ratio: f32 = aspect_ratio.into();
match self {
Self::BoundingBox3(bb) => {
let transformed_bb = {
let mut pbb = BoundingBox2::nil();
for point in bb.points() {
let p = model_view * point.extend(1.0);
pbb.update_point(&Vector2::new(p.x, p.y));
}
pbb
};
if transformed_bb.len_x() >= transformed_bb.len_y() {
let margin = transformed_bb.len_x() * 0.05;
let d = (transformed_bb.len_x() - transformed_bb.len_y()) * 0.5;
BoundingBox2::new(
&Vector2::new(
transformed_bb.min.x - margin,
transformed_bb.min.y - d - margin,
),
&Vector2::new(
transformed_bb.max.x + margin,
transformed_bb.max.y + d + margin,
),
)
} else {
let margin = transformed_bb.len_x() * 0.05;
let d = (transformed_bb.len_y() - transformed_bb.len_x()) * 0.5;
BoundingBox2::new(
&Vector2::new(
transformed_bb.min.x - d - margin,
transformed_bb.min.y - margin,
),
&Vector2::new(
transformed_bb.max.x + d + margin,
transformed_bb.max.y + margin,
),
)
}
}
Self::BoundingBox2(bb) => bb.clone(),
Self::Radius(r) => BoundingBox2::new(
&Vector2::new(-r * aspect_ratio, -r / aspect_ratio),
&Vector2::new(r * aspect_ratio, r / aspect_ratio),
),
Self::Unbounded => BoundingBox2::new(
&Vector2::new(-300.0 * aspect_ratio, -300.0 / aspect_ratio),
&Vector2::new(300.0 * aspect_ratio, 300.0 / aspect_ratio),
),
}
}
}
pub struct PerspectiveCamera {
pub position: Point3<f32>,
pub look_at: Point3<f32>,
pub up: Vector3,
pub fov: Deg<f32>,
}
impl PerspectiveCamera {
pub fn new(position: Point3<f32>, look_at: Point3<f32>, fov: Deg<f32>) -> Self {
Self {
position,
look_at,
up: Vector3::new(0.0, -1.0, 0.0),
fov,
}
}
}
impl ProjectionModifier for PerspectiveCamera {
fn update_projections(&self, aspect_ratio: AspectRatio) -> Vec<ProjectionMutator> {
let projection_matrix = Matrix4::from(PerspectiveFov {
fovy: cgmath::Rad::from(self.fov),
aspect: aspect_ratio.into(),
near: 10.0,
far: 100000.0,
});
let view_matrix = Matrix4::look_at_rh(self.position, self.look_at, self.up);
vec![
ProjectionMutator::SetProjectionMatrix {
matrix: projection_matrix,
is_orthographic: false,
},
ProjectionMutator::SetViewMatrix(view_matrix),
]
}
}
#[derive(Clone, Debug)]
pub struct OrthographicCamera {
pub position: Point3<f32>,
pub look_at: Point3<f32>,
pub up: Vector3,
pub view_bounds: ViewBounds,
}
impl OrthographicCamera {
pub fn new(position: Point3<f32>, look_at: Point3<f32>, view_bounds: ViewBounds) -> Self {
Self {
position,
look_at,
up: Vector3::new(0.0, -1.0, 0.0),
view_bounds,
}
}
pub fn new_isometric(center: Point3<f32>, view_bounds: ViewBounds) -> Self {
let sin = Deg(45.0).sin() * 1000.0;
let siny = Deg(35.264).sin() * 1000.0;
let position = Point3::new(center.x + sin, center.y - siny, center.z - sin);
Self {
position,
look_at: center,
up: Vector3::new(0.0, -1.0, 0.0),
view_bounds,
}
}
}
impl ProjectionModifier for OrthographicCamera {
fn update_projections(&self, aspect_ratio: AspectRatio) -> Vec<ProjectionMutator> {
let view_matrix = Matrix4::look_at_rh(self.position, self.look_at, self.up);
let view_bounds = self.view_bounds.project(&view_matrix, aspect_ratio);
let projection_matrix = Matrix4::from(Ortho {
left: view_bounds.min.x,
right: view_bounds.max.x,
top: view_bounds.max.y,
bottom: view_bounds.min.y,
near: -10000.0,
far: 10000.0,
});
vec![
ProjectionMutator::SetProjectionMatrix {
matrix: projection_matrix,
is_orthographic: true,
},
ProjectionMutator::SetViewMatrix(view_matrix),
]
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/renderer/src/pipeline.rs | renderer/src/pipeline.rs | use std::{collections::HashSet, fmt::Display, hash::Hash, ops::Range};
use cgmath::SquareMatrix;
use image::GenericImageView;
use ldraw::{color::Color, Matrix4, Vector3, Vector4};
use wgpu::{util::DeviceExt, TextureViewDescriptor};
use crate::display_list::InstanceOps;
use super::{
display_list::{DisplayList, Instances, SelectionDisplayList, SelectionInstances},
error,
part::{EdgeBuffer, MeshBuffer, OptionalEdgeBuffer, Part, PartQuerier},
projection::Projection,
Entity, ObjectSelection,
};
const DEFAULT_OBJECT_SELECTION_FRAMEBUFFER_SIZE: u32 = 1024;
pub struct MaterialUniformData {
diffuse: Vector3,
emissive: Vector3,
roughness: f32,
metalness: f32,
}
impl Default for MaterialUniformData {
fn default() -> Self {
Self {
diffuse: Vector3::new(1.0, 1.0, 1.0),
emissive: Vector3::new(0.0, 0.0, 0.0),
roughness: 0.3,
metalness: 0.0,
}
}
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct RawMaterialUniformData {
diffuse: [f32; 3],
_padding0: [u8; 4],
emissive: [f32; 3],
roughness: f32,
metalness: f32,
_padding1: [u8; 12],
}
impl From<&MaterialUniformData> for RawMaterialUniformData {
fn from(v: &MaterialUniformData) -> Self {
Self {
diffuse: [v.diffuse.x, v.diffuse.y, v.diffuse.z],
_padding0: [0; 4],
emissive: [v.emissive.x, v.emissive.y, v.emissive.z],
roughness: v.roughness,
metalness: v.metalness,
_padding1: [0; 12],
}
}
}
impl RawMaterialUniformData {
fn update(&mut self, data: &MaterialUniformData) {
self.diffuse = data.diffuse.into();
self.emissive = data.emissive.into();
self.roughness = data.roughness;
self.metalness = data.metalness;
}
}
pub struct ShadingUniforms {
pub bind_group: wgpu::BindGroup,
pub material_data: MaterialUniformData,
material_buffer: wgpu::Buffer,
material_raw: RawMaterialUniformData,
_env_map_texture_view: wgpu::TextureView,
_env_map_sampler: wgpu::Sampler,
}
impl ShadingUniforms {
pub fn new(
device: &wgpu::Device,
env_map_texture_view: wgpu::TextureView,
env_map_sampler: wgpu::Sampler,
) -> Self {
let material_data = MaterialUniformData::default();
let material_raw = RawMaterialUniformData::from(&material_data);
let material_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Uniform buffer for materials"),
contents: bytemuck::cast_slice(&[material_raw]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Bind group for shading"),
layout: &device.create_bind_group_layout(&Self::desc()),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: material_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&env_map_texture_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&env_map_sampler),
},
],
});
Self {
bind_group,
material_data,
material_buffer,
material_raw,
_env_map_texture_view: env_map_texture_view,
_env_map_sampler: env_map_sampler,
}
}
pub fn update_materials(&mut self, queue: &wgpu::Queue) {
self.material_raw.update(&self.material_data);
queue.write_buffer(
&self.material_buffer,
0 as wgpu::BufferAddress,
bytemuck::cast_slice(&[self.material_raw]),
);
}
pub fn desc() -> wgpu::BindGroupLayoutDescriptor<'static> {
wgpu::BindGroupLayoutDescriptor {
label: Some("Bind group descriptor for shading"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
}
}
}
pub struct DefaultMeshRenderingPipeline {
pipeline: wgpu::RenderPipeline,
pub shading_uniforms: ShadingUniforms,
}
impl DefaultMeshRenderingPipeline {
fn load_envmap(device: &wgpu::Device, queue: &wgpu::Queue) -> (wgpu::Texture, wgpu::Sampler) {
let image = image::load_from_memory_with_format(
include_bytes!("../assets/env_cubemap.png"),
image::ImageFormat::Png,
)
.unwrap();
let rgba = image.to_rgba8();
let (width, height) = image.dimensions();
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Environment map"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
min_filter: wgpu::FilterMode::Linear,
mag_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Nearest,
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
..Default::default()
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
aspect: wgpu::TextureAspect::All,
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
},
&rgba,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * width),
rows_per_image: Some(height),
},
size,
);
(texture, sampler)
}
fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
texture_format: wgpu::TextureFormat,
sample_count: u32,
) -> Self {
let vertex_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Vertex shader for default mesh"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/model_vertex.wgsl").into()),
});
let fragment_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Fragment shader for default mesh"),
source: wgpu::ShaderSource::Wgsl(
include_str!("../shaders/model_fragment_base.wgsl").into(),
),
});
let projection_bind_group_layout = device.create_bind_group_layout(&Projection::desc());
let (env_map_texture, env_map_sampler) = Self::load_envmap(device, queue);
let env_map_texture_view =
env_map_texture.create_view(&wgpu::TextureViewDescriptor::default());
let shading_uniforms = ShadingUniforms::new(device, env_map_texture_view, env_map_sampler);
let shading_bind_group_layout = device.create_bind_group_layout(&ShadingUniforms::desc());
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render pipeline layout for default mesh"),
bind_group_layouts: &[&projection_bind_group_layout, &shading_bind_group_layout],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render pipeline for default meshes"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &vertex_shader,
entry_point: Some("vs"),
buffers: &[MeshBuffer::desc(), Instances::<i32, i32>::desc()],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &fragment_shader,
entry_point: Some("fs"),
targets: &[Some(wgpu::ColorTargetState {
format: texture_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::OVER,
alpha: wgpu::BlendComponent::OVER,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: sample_count,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
cache: None,
});
Self {
pipeline: render_pipeline,
shading_uniforms,
}
}
fn render<K, G>(
&self,
pass: &mut wgpu::RenderPass<'static>,
projection: &Projection,
part: &Part,
instances: &Instances<K, G>,
range: Range<u32>,
) {
let Some(buffer) = &instances.instance_buffer else {
return;
};
let Some(projection) = &projection.bind_group else {
return;
};
pass.set_vertex_buffer(0, part.mesh.vertices.slice(..));
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, projection, &[]);
pass.set_bind_group(1, &self.shading_uniforms.bind_group, &[]);
pass.set_vertex_buffer(1, buffer.slice(..));
pass.set_index_buffer(part.mesh.indices.slice(..), part.mesh.index_format);
pass.draw_indexed(range, 0, instances.range());
}
}
pub struct NoShadingMeshRenderingPipeline {
pipeline: wgpu::RenderPipeline,
}
impl NoShadingMeshRenderingPipeline {
pub fn new(
device: &wgpu::Device,
texture_format: wgpu::TextureFormat,
sample_count: u32,
) -> Self {
let vertex_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Vertex shader for default mesh without shading"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/model_vertex.wgsl").into()),
});
let fragment_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Fragment shader for default mesh"),
source: wgpu::ShaderSource::Wgsl(
include_str!("../shaders/model_fragment_no_shading.wgsl").into(),
),
});
let projection_bind_group_layout = device.create_bind_group_layout(&Projection::desc());
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render pipeline layout for default mesh without shading"),
bind_group_layouts: &[&projection_bind_group_layout],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render pipeline for default mesh without shading"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &vertex_shader,
entry_point: Some("vs"),
buffers: &[MeshBuffer::desc(), Instances::<i32, i32>::desc()],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &fragment_shader,
entry_point: Some("fs"),
targets: &[Some(wgpu::ColorTargetState {
format: texture_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::OVER,
alpha: wgpu::BlendComponent::OVER,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: sample_count,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
cache: None,
});
Self {
pipeline: render_pipeline,
}
}
fn render<K, G>(
&self,
pass: &mut wgpu::RenderPass<'static>,
projection: &Projection,
part: &Part,
instances: &Instances<K, G>,
range: Range<u32>,
) {
let Some(buffer) = &instances.instance_buffer else {
return;
};
let Some(projection) = &projection.bind_group else {
return;
};
pass.set_vertex_buffer(0, part.mesh.vertices.slice(..));
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, projection, &[]);
pass.set_vertex_buffer(1, buffer.slice(..));
pass.set_index_buffer(part.mesh.indices.slice(..), part.mesh.index_format);
pass.draw_indexed(range, 0, instances.range());
}
}
pub struct EdgeRenderingPipeline {
pipeline: wgpu::RenderPipeline,
}
impl EdgeRenderingPipeline {
pub fn new(
device: &wgpu::Device,
texture_format: wgpu::TextureFormat,
sample_count: u32,
) -> Self {
let vertex_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Vertex shader for edges"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/edge_vertex.wgsl").into()),
});
let fragment_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Fragment shader for edges"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/edge_fragment.wgsl").into()),
});
let projection_bind_group_layout = device.create_bind_group_layout(&Projection::desc());
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render pipeline layout for edges"),
bind_group_layouts: &[&projection_bind_group_layout],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render pipeline for edges"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &vertex_shader,
entry_point: Some("vs"),
buffers: &[EdgeBuffer::desc(), Instances::<i32, i32>::desc()],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &fragment_shader,
entry_point: Some("fs"),
targets: &[Some(wgpu::ColorTargetState {
format: texture_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::REPLACE,
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::LineList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: sample_count,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
cache: None,
});
Self {
pipeline: render_pipeline,
}
}
fn render<K, G>(
&self,
pass: &mut wgpu::RenderPass<'static>,
projection: &Projection,
part: &Part,
instances: &Instances<K, G>,
) -> bool {
let Some(projection) = &projection.bind_group else {
return false;
};
let Some(instance_buffer) = &instances.instance_buffer else {
return false;
};
let Some(edges) = &part.edges else {
return false;
};
pass.set_vertex_buffer(0, edges.vertices.slice(..));
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, projection, &[]);
pass.set_vertex_buffer(1, instance_buffer.slice(..));
pass.set_index_buffer(edges.indices.slice(..), edges.index_format);
pass.draw_indexed(edges.range.clone(), 0, instances.range());
true
}
}
pub struct OptionalEdgeRenderingPipeline {
pipeline: wgpu::RenderPipeline,
}
impl OptionalEdgeRenderingPipeline {
pub fn new(
device: &wgpu::Device,
texture_format: wgpu::TextureFormat,
sample_count: u32,
) -> Self {
let vertex_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Vertex shader for optional edges"),
source: wgpu::ShaderSource::Wgsl(
include_str!("../shaders/optional_edge_vertex.wgsl").into(),
),
});
let fragment_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Fragment shader for optional edges"),
source: wgpu::ShaderSource::Wgsl(
include_str!("../shaders/optional_edge_fragment.wgsl").into(),
),
});
let projection_bind_group_layout = device.create_bind_group_layout(&Projection::desc());
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render pipeline layout for optional edges"),
bind_group_layouts: &[&projection_bind_group_layout],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render pipeline for optional edges"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &vertex_shader,
entry_point: Some("vs"),
buffers: &[OptionalEdgeBuffer::desc(), Instances::<i32, i32>::desc()],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &fragment_shader,
entry_point: Some("fs"),
targets: &[Some(wgpu::ColorTargetState {
format: texture_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::REPLACE,
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::LineList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: sample_count,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
cache: None,
});
Self {
pipeline: render_pipeline,
}
}
fn render<K, G>(
&self,
pass: &mut wgpu::RenderPass<'static>,
projection: &Projection,
part: &Part,
instances: &Instances<K, G>,
) -> bool {
let Some(projection) = &projection.bind_group else {
return false;
};
let Some(optional_edges) = &part.optional_edges else {
return false;
};
let Some(instance_buffer) = &instances.instance_buffer else {
return false;
};
pass.set_vertex_buffer(0, optional_edges.vertices.slice(..));
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, projection, &[]);
pass.set_vertex_buffer(1, instance_buffer.slice(..));
pass.draw(optional_edges.range.clone(), instances.range());
true
}
}
pub struct ObjectSelectionRenderingPipeline {
pipeline: wgpu::RenderPipeline,
framebuffer_size: u32,
framebuffer_texture: wgpu::Texture,
framebuffer_texture_view: wgpu::TextureView,
_depth_texture: wgpu::Texture,
depth_texture_view: wgpu::TextureView,
output_buffer: wgpu::Buffer,
}
impl ObjectSelectionRenderingPipeline {
pub fn new(device: &wgpu::Device, framebuffer_size: u32) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Vertex shader for object selection"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/selection.wgsl").into()),
});
let projection_bind_group_layout = device.create_bind_group_layout(&Projection::desc());
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render pipeline layout for object selection"),
bind_group_layouts: &[&projection_bind_group_layout],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render pipeline for object selection"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs"),
buffers: &[MeshBuffer::desc(), SelectionInstances::desc()],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs"),
targets: &[Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::R32Uint,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::LessEqual,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
cache: None,
});
let framebuffer_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Framebuffer texture for object selection"),
format: wgpu::TextureFormat::R32Uint,
dimension: wgpu::TextureDimension::D2,
size: wgpu::Extent3d {
width: framebuffer_size,
height: framebuffer_size,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let framebuffer_texture_view =
framebuffer_texture.create_view(&TextureViewDescriptor::default());
let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Depth texture for object selection"),
format: wgpu::TextureFormat::Depth32Float,
dimension: wgpu::TextureDimension::D2,
size: wgpu::Extent3d {
width: framebuffer_size,
height: framebuffer_size,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let depth_texture_view = depth_texture.create_view(&TextureViewDescriptor::default());
let output_buffer_size = (std::mem::size_of::<u32>() as u32
* framebuffer_size
* framebuffer_size) as wgpu::BufferAddress;
let output_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Object selection buffer"),
size: output_buffer_size,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
Self {
pipeline: render_pipeline,
framebuffer_size,
framebuffer_texture,
framebuffer_texture_view,
_depth_texture: depth_texture,
depth_texture_view,
output_buffer,
}
}
pub fn render_part(
&self,
pass: &mut wgpu::RenderPass<'static>,
projection: &Projection,
part: &Part,
instances: &SelectionInstances,
range: Range<u32>,
) {
if instances.range().is_empty() {
return;
}
let Some(projection) = &projection.bind_group else {
return;
};
pass.set_vertex_buffer(0, part.mesh.vertices.slice(..));
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, projection, &[]);
pass.set_vertex_buffer(1, instances.instance_buffer.slice(..));
pass.set_index_buffer(part.mesh.indices.slice(..), part.mesh.index_format);
pass.draw_indexed(range, 0, instances.range());
}
pub fn render_display_list<G, K: Clone>(
&self,
pass: &mut wgpu::RenderPass<'static>,
projection: &Projection,
part_querier: &dyn PartQuerier<G>,
display_list: &SelectionDisplayList<G, K>,
) -> u32 {
let mut draws = 0;
for (group, instances) in display_list.iter() {
if let Some(part) = part_querier.get(group) {
self.render_part(pass, projection, part, instances, 0..part.mesh.index_length);
draws += 1;
}
}
draws
}
}
pub trait ObjectSelectionRenderingOp {
fn render(&self, projection: &Projection, pass: &mut wgpu::RenderPass<'static>);
}
pub trait ObjectSelectionTestOp {
type Result;
fn test(&self, ids: impl Iterator<Item = u32> + 'static) -> Option<Self::Result>;
}
pub trait ObjectSelectionOp: ObjectSelectionRenderingOp + ObjectSelectionTestOp {}
impl<T> ObjectSelectionOp for T where T: ObjectSelectionRenderingOp + ObjectSelectionTestOp {}
pub struct DisplayListObjectSelectionOp<'ctx, G, K> {
pipeline: &'ctx ObjectSelectionRenderingPipeline,
part_querier: &'ctx dyn PartQuerier<G>,
display_list: SelectionDisplayList<G, K>,
}
impl<'ctx, G, K> DisplayListObjectSelectionOp<'ctx, G, K> {
pub fn new(
pipeline_manager: &'ctx RenderingPipelineManager,
part_querier: &'ctx impl PartQuerier<G>,
display_list: SelectionDisplayList<G, K>,
) -> Self {
Self {
pipeline: &pipeline_manager.object_selection,
part_querier,
display_list,
}
}
}
impl<'ctx, G, K: Clone + Eq + PartialEq + Hash> ObjectSelectionRenderingOp
for DisplayListObjectSelectionOp<'ctx, G, K>
{
fn render(&self, projection: &Projection, pass: &mut wgpu::RenderPass<'static>) {
self.pipeline
.render_display_list(pass, projection, self.part_querier, &self.display_list);
}
}
impl<'ctx, G, K: Clone + Eq + PartialEq + Hash> ObjectSelectionTestOp
for DisplayListObjectSelectionOp<'ctx, G, K>
{
type Result = HashSet<K>;
fn test(&self, ids: impl Iterator<Item = u32> + 'static) -> Option<Self::Result> {
let result: HashSet<K> = self.display_list.get_matches(ids).collect();
Some(result)
}
}
pub struct RenderingPipelineManager {
mesh_default: DefaultMeshRenderingPipeline,
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | true |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/renderer/src/part.rs | renderer/src/part.rs | use std::{collections::HashMap, ops::Range};
use ldraw::{
color::{ColorCatalog, ColorReference},
Vector4,
};
use ldraw_ir::{geometry::BoundingBox3, part as part_ir};
use wgpu::util::DeviceExt;
pub struct MeshBuffer {
pub vertices: wgpu::Buffer,
pub indices: wgpu::Buffer,
pub index_format: wgpu::IndexFormat,
pub uncolored_range: Option<Range<u32>>,
pub uncolored_without_bfc_range: Option<Range<u32>>,
pub colored_opaque_range: Option<Range<u32>>,
pub colored_opaque_without_bfc_range: Option<Range<u32>>,
pub colored_translucent_range: Option<Range<u32>>,
pub colored_translucent_without_bfc_range: Option<Range<u32>>,
pub index_length: u32,
}
#[derive(Eq, PartialEq, Hash)]
struct MeshVertexIndex {
vertex: usize,
normal: usize,
color: ColorReference,
}
impl MeshBuffer {
fn expand(
metadata: &part_ir::PartMetadata,
vertices: &mut Vec<f32>,
index: &mut Vec<u32>,
index_table: &mut HashMap<MeshVertexIndex, u32>,
vertex_buffer: &part_ir::VertexBuffer,
index_buffers: Vec<(ColorReference, &part_ir::MeshBuffer)>,
) -> Option<Range<u32>> {
if index_buffers.is_empty() {
return None;
}
let start = index.len() as u32;
let mut end = start;
for (color, buffer) in index_buffers {
if !buffer.is_valid() {
eprintln!(
"{}: Corrupted mesh vertex buffer. skipping...",
metadata.name
);
return None;
}
end += buffer.len() as u32;
let color_array = match &color {
ColorReference::Current => vec![-1.0; 4],
ColorReference::Complement => vec![-2.0; 4],
ColorReference::Color(c) => {
let color: Vector4 = c.color.into();
vec![color.x, color.y, color.z, color.w]
}
ColorReference::Unknown(_) | ColorReference::Unresolved(_) => {
vec![0.0, 0.0, 0.0, 1.0]
}
};
for (vertex_idx, normal_idx) in buffer
.vertex_indices
.iter()
.zip(buffer.normal_indices.iter())
{
let vertex_idx = *vertex_idx as usize;
let normal_idx = *normal_idx as usize;
let vertex_range = vertex_idx * 3..vertex_idx * 3 + 3;
let normal_range = normal_idx * 3..normal_idx * 3 + 3;
if !vertex_buffer.check_range(&vertex_range)
|| !vertex_buffer.check_range(&normal_range)
{
eprintln!(
"{}: Corrupted mesh vertex buffer. skipping...",
metadata.name
);
return None;
}
let idx_key = MeshVertexIndex {
vertex: vertex_idx,
normal: normal_idx,
color: color.clone(),
};
if let Some(idx) = index_table.get(&idx_key) {
index.push(*idx);
} else {
let idx_val = index_table.len() as u32;
index_table.insert(idx_key, idx_val);
vertices.extend(&vertex_buffer.0[vertex_range]);
vertices.extend(&vertex_buffer.0[normal_range]);
vertices.extend(&color_array);
index.push(idx_val);
}
}
}
if start == end {
None
} else {
Some(start..end)
}
}
pub fn new(device: &wgpu::Device, part: &part_ir::Part) -> Self {
let mut data = Vec::new();
let mut index = Vec::new();
let mut index_lut = HashMap::new();
let uncolored_range = Self::expand(
&part.metadata,
&mut data,
&mut index,
&mut index_lut,
&part.geometry.vertex_buffer,
vec![(ColorReference::Current, &part.geometry.uncolored_mesh)],
);
let uncolored_without_bfc_range = Self::expand(
&part.metadata,
&mut data,
&mut index,
&mut index_lut,
&part.geometry.vertex_buffer,
vec![(
ColorReference::Current,
&part.geometry.uncolored_without_bfc_mesh,
)],
);
let colored_opaque_range = Self::expand(
&part.metadata,
&mut data,
&mut index,
&mut index_lut,
&part.geometry.vertex_buffer,
part.geometry
.colored_meshes
.iter()
.filter_map(|(k, v)| {
if let ColorReference::Color(c) = &k.color_ref {
if !c.is_translucent() && k.bfc {
Some((k.color_ref.clone(), v))
} else {
None
}
} else {
None
}
})
.collect(),
);
let colored_opaque_without_bfc_range = Self::expand(
&part.metadata,
&mut data,
&mut index,
&mut index_lut,
&part.geometry.vertex_buffer,
part.geometry
.colored_meshes
.iter()
.filter_map(|(k, v)| {
if let ColorReference::Color(c) = &k.color_ref {
if !c.is_translucent() && !k.bfc {
Some((k.color_ref.clone(), v))
} else {
None
}
} else {
None
}
})
.collect(),
);
let colored_translucent_range = Self::expand(
&part.metadata,
&mut data,
&mut index,
&mut index_lut,
&part.geometry.vertex_buffer,
part.geometry
.colored_meshes
.iter()
.filter_map(|(k, v)| {
if let ColorReference::Color(c) = &k.color_ref {
if c.is_translucent() && k.bfc {
Some((k.color_ref.clone(), v))
} else {
None
}
} else {
None
}
})
.collect(),
);
let colored_translucent_without_bfc_range = Self::expand(
&part.metadata,
&mut data,
&mut index,
&mut index_lut,
&part.geometry.vertex_buffer,
part.geometry
.colored_meshes
.iter()
.filter_map(|(k, v)| {
if let ColorReference::Color(c) = &k.color_ref {
if c.is_translucent() && !k.bfc {
Some((k.color_ref.clone(), v))
} else {
None
}
} else {
None
}
})
.collect(),
);
let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!(
"Vertex buffer for mesh data at {}",
part.metadata.name
)),
contents: bytemuck::cast_slice(&data),
usage: wgpu::BufferUsages::VERTEX,
});
let index_length = index.len() as u32;
let (indices, index_format) = if data.len() / (3 * 10) < 2 << 16 {
let mut shrunk_data = vec![];
for item in index {
shrunk_data.push(item as u16);
}
(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!(
"Index buffer for mesh data at {}",
part.metadata.name
)),
contents: bytemuck::cast_slice(&shrunk_data),
usage: wgpu::BufferUsages::INDEX,
}),
wgpu::IndexFormat::Uint16,
)
} else {
(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!(
"Index buffer for mesh data at {}",
part.metadata.name
)),
contents: bytemuck::cast_slice(&index),
usage: wgpu::BufferUsages::INDEX,
}),
wgpu::IndexFormat::Uint32,
)
};
MeshBuffer {
vertices,
indices,
uncolored_range,
uncolored_without_bfc_range,
colored_opaque_range,
colored_opaque_without_bfc_range,
colored_translucent_range,
colored_translucent_without_bfc_range,
index_format,
index_length,
}
}
pub fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<[f32; 10]>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 6]>() as wgpu::BufferAddress,
shader_location: 2,
format: wgpu::VertexFormat::Float32x4,
},
],
}
}
}
#[derive(Eq, PartialEq, Hash)]
struct EdgeVertexIndex {
vertex: usize,
color: u32,
}
pub struct EdgeBuffer {
pub vertices: wgpu::Buffer,
pub indices: wgpu::Buffer,
pub range: Range<u32>,
pub index_format: wgpu::IndexFormat,
}
impl EdgeBuffer {
fn expand(
metadata: &part_ir::PartMetadata,
vertices: &mut Vec<f32>,
index: &mut Vec<u32>,
index_table: &mut HashMap<EdgeVertexIndex, u32>,
colors: &ColorCatalog,
vertex_buffer: &part_ir::VertexBuffer,
index_buffer: &part_ir::EdgeBuffer,
) -> Option<Range<u32>> {
if index_buffer.is_empty() {
None
} else if !index_buffer.is_valid() {
eprintln!("{}: Corrupted edge buffer. skipping...", metadata.name);
None
} else {
let start = index.len() as u32;
let end = start + index_buffer.len() as u32;
for (vertex_idx, color_id) in index_buffer
.vertex_indices
.iter()
.zip(index_buffer.colors.iter())
{
let vertex_idx = *vertex_idx as usize;
let vertex_range = vertex_idx * 3..vertex_idx * 3 + 3;
if !vertex_buffer.check_range(&vertex_range) {
eprintln!("{}: Corrupted edge buffer. skipping...", metadata.name);
return None;
}
let idx_key = EdgeVertexIndex {
vertex: vertex_idx,
color: *color_id,
};
if let Some(idx) = index_table.get(&idx_key) {
index.push(*idx);
} else {
let color = if *color_id == 2u32 << 30 {
[-1.0, -1.0, -1.0]
} else if *color_id == 2u32 << 29 {
[-2.0, -2.0, -2.0]
} else {
match colors.get(&(color_id & 0x7fffffffu32)) {
Some(color) => {
let buf = if *color_id & 0x8000_0000 != 0 {
&color.edge
} else {
&color.color
};
let r = buf.red() as f32 / 255.0;
let g = buf.green() as f32 / 255.0;
let b = buf.blue() as f32 / 255.0;
[r, g, b]
}
None => [0.0, 0.0, 0.0],
}
};
let idx_val = index_table.len() as u32;
index_table.insert(idx_key, idx_val);
vertices.extend(&vertex_buffer.0[vertex_range]);
vertices.extend(&color);
index.push(idx_val);
}
}
if start == end {
None
} else {
Some(start..end)
}
}
}
pub fn new(device: &wgpu::Device, colors: &ColorCatalog, part: &part_ir::Part) -> Option<Self> {
let mut data = Vec::new();
let mut index = Vec::new();
let mut index_lut = HashMap::new();
if let Some(range) = Self::expand(
&part.metadata,
&mut data,
&mut index,
&mut index_lut,
colors,
&part.geometry.vertex_buffer,
&part.geometry.edges,
) {
let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!(
"Vertex buffer for edge data at {}",
part.metadata.name
)),
contents: bytemuck::cast_slice(&data),
usage: wgpu::BufferUsages::VERTEX,
});
let (indices, index_format) = if data.len() / (3 * 6) < 2 << 16 {
let mut shrunk_data = vec![];
for item in index {
shrunk_data.push(item as u16);
}
(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!(
"Index buffer for edge data at {}",
part.metadata.name
)),
contents: bytemuck::cast_slice(&shrunk_data),
usage: wgpu::BufferUsages::INDEX,
}),
wgpu::IndexFormat::Uint16,
)
} else {
(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!(
"Index buffer for edge data at {}",
part.metadata.name
)),
contents: bytemuck::cast_slice(&index),
usage: wgpu::BufferUsages::INDEX,
}),
wgpu::IndexFormat::Uint32,
)
};
Some(Self {
vertices,
indices,
range,
index_format,
})
} else {
None
}
}
pub fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<[f32; 6]>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
],
}
}
}
pub struct OptionalEdgeBuffer {
pub vertices: wgpu::Buffer,
pub range: Range<u32>,
}
impl OptionalEdgeBuffer {
fn expand(
metadata: &part_ir::PartMetadata,
vertices: &mut Vec<f32>,
colors: &ColorCatalog,
vertex_buffer: &part_ir::VertexBuffer,
index_buffer: &part_ir::OptionalEdgeBuffer,
) -> Option<Range<u32>> {
if index_buffer.is_empty() {
None
} else if !index_buffer.is_valid() {
eprintln!(
"{}: Corrupted optional edge buffer. skipping...",
metadata.name
);
None
} else {
let start = vertices.len() as u32 / 3;
let end = start + index_buffer.len() as u32;
for i in 0..index_buffer.vertex_indices.len() {
let vertex_idx = index_buffer.vertex_indices[i] as usize;
let control_1_idx = index_buffer.control_1_indices[i] as usize;
let control_2_idx = index_buffer.control_2_indices[i] as usize;
let direction_idx = index_buffer.direction_indices[i] as usize;
let color_id = index_buffer.colors[i];
let vertex_range = vertex_idx * 3..vertex_idx * 3 + 3;
let control_1_range = control_1_idx * 3..control_1_idx * 3 + 3;
let control_2_range = control_2_idx * 3..control_2_idx * 3 + 3;
let direction_range = direction_idx * 3..direction_idx * 3 + 3;
if !vertex_buffer.check_range(&vertex_range)
|| !vertex_buffer.check_range(&control_1_range)
|| !vertex_buffer.check_range(&control_2_range)
|| !vertex_buffer.check_range(&direction_range)
{
eprintln!(
"{}: Corrupted optional edge buffer. skipping...",
metadata.name
);
return None;
}
let color = if color_id == 2u32 << 30 {
[-1.0, -1.0, -1.0]
} else if color_id == 2u32 << 29 {
[-2.0, -2.0, -2.0]
} else {
match colors.get(&(color_id & 0x7fffffffu32)) {
Some(color) => {
let buf = if color_id & 0x8000_0000 != 0 {
&color.edge
} else {
&color.color
};
let r = buf.red() as f32 / 255.0;
let g = buf.green() as f32 / 255.0;
let b = buf.blue() as f32 / 255.0;
[r, g, b]
}
None => [0.0, 0.0, 0.0],
}
};
vertices.extend(&vertex_buffer.0[vertex_range]);
vertices.extend(&vertex_buffer.0[control_1_range]);
vertices.extend(&vertex_buffer.0[control_2_range]);
vertices.extend(&vertex_buffer.0[direction_range]);
vertices.extend(&color);
}
if start == end {
None
} else {
Some(start..end)
}
}
}
pub fn new(device: &wgpu::Device, colors: &ColorCatalog, part: &part_ir::Part) -> Option<Self> {
let mut data = Vec::new();
if let Some(range) = Self::expand(
&part.metadata,
&mut data,
colors,
&part.geometry.vertex_buffer,
&part.geometry.optional_edges,
) {
let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!(
"Vertex buffer for optional edge data at {}",
part.metadata.name
)),
contents: bytemuck::cast_slice(&data),
usage: wgpu::BufferUsages::VERTEX,
});
Some(Self { vertices, range })
} else {
None
}
}
pub fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<[f32; 15]>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 6]>() as wgpu::BufferAddress,
shader_location: 2,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 9]>() as wgpu::BufferAddress,
shader_location: 3,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 12]>() as wgpu::BufferAddress,
shader_location: 4,
format: wgpu::VertexFormat::Float32x3,
},
],
}
}
}
pub struct Part {
pub metadata: part_ir::PartMetadata,
pub mesh: MeshBuffer,
pub edges: Option<EdgeBuffer>,
pub optional_edges: Option<OptionalEdgeBuffer>,
pub bounding_box: BoundingBox3,
}
impl Part {
pub fn new(part: &part_ir::Part, device: &wgpu::Device, colors: &ColorCatalog) -> Self {
Self {
metadata: part.metadata.clone(),
mesh: MeshBuffer::new(device, part),
edges: EdgeBuffer::new(device, colors, part),
optional_edges: OptionalEdgeBuffer::new(device, colors, part),
bounding_box: part.bounding_box.clone(),
}
}
}
pub trait PartQuerier<K> {
fn get(&self, key: &K) -> Option<&Part>;
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/tools/viewer/native/src/main.rs | tools/viewer/native/src/main.rs | #![cfg(not(target_arch = "wasm32"))]
use std::{
env,
path::PathBuf,
rc::Rc,
sync::{Arc, RwLock},
time::{Duration, Instant},
};
use clap::{App as ClapApp, Arg};
use ldraw::{
color::ColorCatalog,
document::MultipartDocument,
library::{DocumentLoader, LibraryLoader, PartCache},
resolvers::local::LocalLoader,
};
use viewer_common::App;
use winit::{event, event_loop::EventLoop, window::WindowBuilder};
async fn main_loop<L: LibraryLoader + 'static>(
document: MultipartDocument,
colors: ColorCatalog,
dependency_loader: Rc<L>,
) {
let evloop = EventLoop::new().unwrap();
let window = WindowBuilder::new()
.with_title("ldraw.rs demo")
.build(&evloop)
.unwrap();
let main_window_id = window.id();
let mut app = match App::new(Arc::new(window), dependency_loader, Rc::new(colors), true).await {
Ok(v) => v,
Err(e) => {
panic!("Could not initialize app: {e}");
}
};
let cache = Arc::new(RwLock::new(PartCache::new()));
app.set_document(cache, &document, &|alias, result| {
match result {
Ok(()) => {
println!("Loaded part {}.", alias);
}
Err(e) => {
println!("Could not load part {}: {}", alias, e);
}
};
})
.await
.unwrap();
let started = Instant::now();
let mut total_duration = 0;
let mut frames = 0;
let mut now = started;
let _ = evloop.run(move |event, target| match event {
event::Event::WindowEvent { window_id, event } if window_id == main_window_id => {
match event {
event::WindowEvent::CloseRequested => {
target.exit();
}
event::WindowEvent::RedrawRequested => {
app.animate(started.elapsed().as_millis() as f32 / 1000.0);
match app.render() {
Ok(duration) => {
total_duration += duration.as_millis();
frames += 1;
if now.elapsed() > Duration::from_secs(1) {
println!(
"{} frames per second. {} msecs per frame.",
frames,
total_duration as f32 / frames as f32
);
now = Instant::now();
frames = 0;
total_duration = 0;
}
}
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
app.resize(app.size);
}
Err(wgpu::SurfaceError::OutOfMemory) => {
target.exit();
}
Err(wgpu::SurfaceError::Timeout) => {
println!("Surface timeout");
}
Err(wgpu::SurfaceError::Other) => {
println!("Unrecognized surface error");
}
}
}
event => {
app.handle_window_event(event, started.elapsed().as_millis() as f32 / 1000.0);
}
}
}
event::Event::AboutToWait => {
app.request_redraw();
}
_ => (),
});
}
#[tokio::main]
async fn main() {
let matches = ClapApp::new("viewer")
.about("LDraw Model Viewer")
.arg(
Arg::with_name("ldraw_dir")
.long("ldraw-dir")
.value_name("PATH_OR_URL")
.takes_value(true)
.help("Path or URL to LDraw directory"),
)
.arg(
Arg::with_name("file")
.takes_value(true)
.required(true)
.value_name("PATH_OR_URL")
.help("Path or URL to model file"),
)
.get_matches();
let ldrawdir = match matches.value_of("ldraw_dir") {
Some(v) => v.to_string(),
None => match env::var("LDRAWDIR") {
Ok(v) => v,
Err(_) => {
panic!("--ldraw-dir option or LDRAWDIR environment variable is required.");
}
},
};
let path = String::from(matches.value_of("file").expect("Path is required"));
// FIXME: There should be better ways than this
let ldraw_path = PathBuf::from(&ldrawdir);
let document_base_path = PathBuf::from(&path).parent().map(PathBuf::from);
let loader = LocalLoader::new(Some(ldraw_path), document_base_path);
let colors = loader.load_colors().await.unwrap();
let path_local = PathBuf::from(&path);
let document = loader.load_document(&path_local, &colors).await.unwrap();
main_loop(document, colors, Rc::new(loader)).await;
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/tools/viewer/common/src/lib.rs | tools/viewer/common/src/lib.rs | mod error;
mod texture;
use std::{
cell::RefCell,
cmp::min,
collections::{HashMap, HashSet},
f32,
rc::Rc,
sync::{Arc, RwLock},
vec::Vec,
};
use cgmath::{Deg, SquareMatrix};
use instant::{Duration, Instant};
use ldraw::{
color::{Color, ColorCatalog},
document::MultipartDocument,
error::ResolutionError,
library::{resolve_dependencies_multipart, LibraryLoader, PartCache},
Matrix4, PartAlias, Point2, Point3, Vector2,
};
use ldraw_ir::{
model::{self, GroupId, ObjectId},
part::bake_part_from_multipart_document,
};
use ldraw_renderer::{
display_list::{DisplayList, DisplayListOps},
part::{Part, PartQuerier},
pipeline::RenderingPipelineManager,
projection::{PerspectiveCamera, Projection, ProjectionModifier, ProjectionMutator},
util::calculate_model_bounding_box,
Entity,
};
use uuid::Uuid;
use winit::{
event,
keyboard::{Key, NamedKey},
window::Window,
};
use self::texture::Texture;
pub struct OrbitController {
last_pos: Option<Point2>,
pressing: bool,
latitude: f32,
longitude: f32,
pub radius: f32,
tick: Option<f32>,
velocity: Vector2,
camera: PerspectiveCamera,
}
impl OrbitController {
pub fn new() -> Self {
let camera = PerspectiveCamera::new(
Point3::new(0.0, 0.0, 0.0),
Point3::new(0.0, 0.0, 0.0),
Deg(45.0),
);
OrbitController {
last_pos: None,
pressing: false,
latitude: 0.785,
longitude: 0.262,
radius: 300.0,
velocity: Vector2::new(0.1, 0.0),
tick: None,
camera,
}
}
pub fn on_mouse_press(&mut self, pressed: bool) {
self.pressing = pressed;
if !pressed {
self.last_pos = None;
}
}
pub fn on_mouse_move(&mut self, x: f32, y: f32) {
if self.pressing {
if let Some(last_pos) = self.last_pos {
self.latitude -= (x - last_pos.x) * 0.01;
self.longitude = (self.longitude + (y - last_pos.y) * 0.01).clamp(
-f32::consts::FRAC_PI_2 + 0.017,
f32::consts::FRAC_PI_2 - 0.017,
);
}
self.last_pos = Some(Point2::new(x, y));
}
}
pub fn zoom(&mut self, delta: f32) {
if self.radius - delta > 0.0 {
self.radius -= delta;
}
}
pub fn update(&mut self, width: u32, height: u32, tick: Option<f32>) -> Vec<ProjectionMutator> {
if let (Some(p), Some(n)) = (self.tick, tick) {
let delta = n - p;
self.latitude += self.velocity.x * delta;
self.longitude = (self.longitude + self.velocity.y * delta).clamp(
-f32::consts::FRAC_PI_2 + 0.017,
f32::consts::FRAC_PI_2 - 0.017,
);
}
self.tick = tick;
self.camera.position = self.derive_coordinate();
self.camera.update_projections((width, height).into())
}
fn derive_coordinate(&self) -> Point3 {
let look_at = &self.camera.look_at;
let x = self.latitude.sin() * self.longitude.cos() * self.radius + look_at.x;
let y = -self.longitude.sin() * self.radius + look_at.y;
let z = -self.latitude.cos() * self.longitude.cos() * self.radius + look_at.z;
Point3::new(x, y, z)
}
}
impl Default for OrbitController {
fn default() -> Self {
Self::new()
}
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum State {
Playing,
Step,
Finished,
}
#[derive(Default)]
struct SimplePartsPool(pub HashMap<PartAlias, Part>);
impl PartQuerier<PartAlias> for SimplePartsPool {
fn get(&self, alias: &PartAlias) -> Option<&Part> {
self.0.get(alias)
}
}
const FALL_INTERVAL: f32 = 0.2;
const FALL_INTERVAL_UPPER_BOUND: f32 = 10.0;
const FALL_DURATION: f32 = 0.5;
#[derive(Clone, Debug)]
struct RenderingItem {
id: ObjectId,
alias: PartAlias,
matrix: Matrix4,
color: Color,
}
enum RenderingStep {
Item(RenderingItem),
Step,
}
#[derive(Debug)]
struct AnimatingRenderingItem {
item: RenderingItem,
started_at: f32,
progress: f32,
}
struct AnimatedModel {
display_list: Entity<DisplayList<ObjectId, PartAlias>>,
items: Vec<RenderingStep>,
animating: RefCell<Vec<AnimatingRenderingItem>>,
state: State,
pointer: Option<usize>,
fall_interval: f32,
last_time: Option<f32>,
}
impl Default for AnimatedModel {
fn default() -> Self {
Self {
display_list: DisplayList::new().into(),
items: Vec::new(),
animating: RefCell::new(Vec::new()),
state: State::Finished,
pointer: None,
fall_interval: FALL_INTERVAL,
last_time: None,
}
}
}
impl AnimatedModel {
fn uuid_xor(a: ObjectId, b: ObjectId) -> ObjectId {
let ba = Uuid::from(a).to_bytes_le();
let bb = Uuid::from(b).to_bytes_le();
let bc: Vec<_> = ba.iter().zip(bb).map(|(x, y)| x ^ y).collect();
Uuid::from_slice(&bc).unwrap().into()
}
fn build_item_recursive(
items: &mut Vec<RenderingStep>,
model: &model::Model<PartAlias>,
objects: &[model::Object<PartAlias>],
parent_id: ObjectId,
matrix: Matrix4,
) {
for object in objects {
match &object.data {
model::ObjectInstance::Step => items.push(RenderingStep::Step),
model::ObjectInstance::Part(p) => items.push(RenderingStep::Item(RenderingItem {
id: Self::uuid_xor(parent_id, object.id),
alias: p.part.clone(),
matrix: matrix * p.matrix,
color: p.color.get_color().cloned().unwrap_or_default(),
})),
model::ObjectInstance::PartGroup(pg) => {
if let Some(group) = model.object_groups.get(&pg.group_id) {
Self::build_item_recursive(
items,
model,
&group.objects,
object.id,
matrix * pg.matrix,
);
}
}
_ => {}
}
}
}
pub fn from_model(
model: &model::Model<PartAlias>,
group_id: Option<GroupId>,
color_catalog: &ColorCatalog,
animated: bool,
) -> Self {
if animated {
let objects = if let Some(group_id) = group_id {
model
.object_groups
.get(&group_id)
.map(|group| &group.objects)
} else {
Some(&model.objects)
};
let mut items = Vec::new();
if let Some(objects) = objects {
Self::build_item_recursive(
&mut items,
model,
objects,
uuid::Uuid::nil().into(),
Matrix4::identity(),
);
}
let items_len = items.len();
Self {
display_list: DisplayList::new().into(),
items,
animating: RefCell::new(Vec::new()),
state: State::Playing,
pointer: None,
fall_interval: if items_len as f32 * FALL_INTERVAL >= FALL_INTERVAL_UPPER_BOUND {
FALL_INTERVAL_UPPER_BOUND / items_len as f32
} else {
FALL_INTERVAL
},
last_time: None,
}
} else {
let display_list = DisplayList::from_model(model, group_id, color_catalog);
Self {
display_list,
items: Vec::new(),
animating: RefCell::new(Vec::new()),
state: State::Finished,
pointer: None,
fall_interval: 0.0,
last_time: None,
}
}
}
pub fn advance(&mut self, time: f32) {
if self.state == State::Step || self.pointer.is_none() {
let start = self.pointer.unwrap_or(0);
let mut count = 0;
for i in start..self.items.len() {
if let RenderingStep::Step = self.items[i] {
break;
}
count += 1;
}
self.fall_interval = if count as f32 * FALL_INTERVAL >= FALL_INTERVAL_UPPER_BOUND {
FALL_INTERVAL_UPPER_BOUND / count as f32
} else {
FALL_INTERVAL
};
}
let next = if self.pointer.is_none() && self.last_time.is_none() {
0
} else if time - self.last_time.unwrap() >= self.fall_interval {
self.pointer.unwrap() + 1
} else {
return;
};
if next >= self.items.len() {
self.state = State::Finished;
return;
}
self.pointer = Some(next);
match &self.items[next] {
RenderingStep::Item(item) => {
self.animating.borrow_mut().push(AnimatingRenderingItem {
item: item.clone(),
started_at: time,
progress: 0.0,
});
self.display_list.mutate(DisplayListOps::Insert {
group: item.alias.clone(),
key: item.id,
matrix: item.matrix,
color: item.color.clone(),
alpha: Some(0.0),
});
self.state = State::Playing;
self.last_time = Some(time);
}
RenderingStep::Step => {
self.state = State::Step;
}
}
}
pub fn animate(&mut self, time: f32) {
if self.state == State::Playing {
self.advance(time);
}
let mut animating = self.animating.borrow_mut();
for item in animating.iter_mut() {
let elapsed = (time - item.started_at).clamp(0.0, FALL_DURATION) / FALL_DURATION;
let ease = -(f32::consts::FRAC_PI_2 + elapsed * f32::consts::FRAC_PI_2).cos();
let alpha = ease * (item.item.color.color.alpha() as f32 / 255.0);
let mut matrix = item.item.matrix;
matrix[3][1] = item.item.matrix[3][1] + (-(1.0 - ease) * 300.0);
self.display_list.mutate_all(
vec![
DisplayListOps::UpdateMatrix {
key: item.item.id,
matrix,
},
DisplayListOps::UpdateAlpha {
key: item.item.id,
alpha,
},
]
.into_iter(),
);
item.progress = elapsed;
}
animating.retain(|v| time - v.started_at < FALL_DURATION);
}
}
pub struct App<L: LibraryLoader> {
window: Arc<Window>,
surface: wgpu::Surface<'static>,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
pub size: winit::dpi::PhysicalSize<u32>,
pub adapter_info: wgpu::AdapterInfo,
max_texture_size: u32,
framebuffer_texture: Option<Texture>,
depth_texture: Texture,
sample_count: u32,
projection: Entity<Projection>,
pipelines: RenderingPipelineManager,
loader: Rc<L>,
colors: Rc<ColorCatalog>,
parts: Rc<RefCell<SimplePartsPool>>,
model: Option<model::Model<PartAlias>>,
animated_model: AnimatedModel,
orbit_controller: RefCell<OrbitController>,
}
impl<L: LibraryLoader> App<L> {
pub async fn new(
window: Arc<Window>,
loader: Rc<L>,
colors: Rc<ColorCatalog>,
supports_antialiasing: bool,
) -> Result<Self, error::AppCreationError> {
let window_size = window.inner_size();
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
backend_options: Default::default(),
flags: if cfg!(debug_assertions) {
wgpu::InstanceFlags::DEBUG | wgpu::InstanceFlags::VALIDATION
} else {
Default::default()
},
memory_budget_thresholds: Default::default(),
});
let sample_count = if supports_antialiasing { 4 } else { 1 };
let surface = instance.create_surface(Arc::clone(&window))?;
let adapter = wgpu::util::initialize_adapter_from_env_or_default(&instance, Some(&surface))
.await
.map_err(|_| error::AppCreationError::NoAdapterFound)?;
let adapter_info = adapter.get_info();
let (device, queue, max_texture_size) =
ldraw_renderer::util::request_device(&adapter, None).await?;
let size = winit::dpi::PhysicalSize {
width: min(window_size.width, max_texture_size),
height: min(window_size.height, max_texture_size),
};
let surface_caps = surface.get_capabilities(&adapter);
let surface_format = surface_caps
.formats
.iter()
.copied()
.find(|f| f.is_srgb())
.unwrap_or(surface_caps.formats[0]);
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width,
height: size.height,
present_mode: surface_caps.present_modes[0],
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![surface_format],
desired_maximum_frame_latency: 2,
};
surface.configure(&device, &config);
let framebuffer_texture = if sample_count > 1 {
Some(Texture::create_framebuffer(
&device,
&config,
sample_count,
Some("Multisample framebuffer"),
))
} else {
None
};
let depth_texture =
Texture::create_depth_texture(&device, &config, sample_count, Some("Depth texture"));
let mut projection: Entity<Projection> = Projection::new().into();
let orbit_controller = RefCell::new(OrbitController::default());
projection.mutate_all(
orbit_controller
.borrow_mut()
.update(size.width, size.height, None)
.into_iter(),
);
let pipelines = RenderingPipelineManager::new(&device, &queue, config.format, sample_count);
Ok(App {
window,
surface,
device,
queue,
config,
size,
adapter_info,
max_texture_size,
framebuffer_texture,
depth_texture,
sample_count,
projection,
pipelines,
loader,
colors,
parts: Rc::new(RefCell::new(SimplePartsPool::default())),
model: None,
animated_model: AnimatedModel::default(),
orbit_controller,
})
}
pub fn loaded_parts(&self) -> HashSet<PartAlias> {
let mut result = HashSet::new();
result.extend(self.parts.borrow().0.keys().cloned());
result
}
pub async fn set_document<F: Fn(PartAlias, Result<(), ResolutionError>)>(
&mut self,
cache: Arc<RwLock<PartCache>>,
document: &MultipartDocument,
on_update: &F,
) -> Result<(), ResolutionError> {
let resolution_result = resolve_dependencies_multipart(
document,
Arc::clone(&cache),
&self.colors,
&*self.loader,
on_update,
)
.await;
let model = model::Model::from_ldraw_multipart_document(
document,
&self.colors,
Some((&*self.loader, cache)),
)
.await;
self.parts
.borrow_mut()
.0
.extend(
document
.list_dependencies()
.into_iter()
.filter_map(|alias| {
resolution_result.query(&alias, true).map(|(part, local)| {
(
alias.clone(),
Part::new(
&bake_part_from_multipart_document(
part,
&resolution_result,
local,
),
&self.device,
&self.colors,
),
)
})
}),
);
let bounding_box = calculate_model_bounding_box(&model, None, &*self.parts.borrow());
let center = bounding_box.center();
self.animated_model = AnimatedModel::from_model(&model, None, &self.colors, true);
self.model = Some(model);
let mut orbit_controller = self.orbit_controller.borrow_mut();
orbit_controller.camera.look_at = Point3::new(center.x, center.y, center.z);
orbit_controller.radius = (bounding_box.len_x() * bounding_box.len_x()
+ bounding_box.len_y() * bounding_box.len_y()
+ bounding_box.len_z() * bounding_box.len_z())
.sqrt()
* 2.0;
Ok(())
}
pub fn advance(&mut self, time: f32) {
self.animated_model.advance(time);
}
pub fn animate(&mut self, time: f32) {
self.projection.mutate_all(
self.orbit_controller
.borrow_mut()
.update(self.size.width, self.size.height, Some(time))
.into_iter(),
);
self.animated_model.animate(time);
}
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
if new_size.width > 0 && new_size.height > 0 {
let new_size = winit::dpi::PhysicalSize {
width: min(new_size.width, self.max_texture_size),
height: min(new_size.height, self.max_texture_size),
};
self.config.width = new_size.width;
self.config.height = new_size.height;
self.surface.configure(&self.device, &self.config);
self.size = new_size;
self.projection.mutate_all(
self.orbit_controller
.borrow_mut()
.update(self.size.width, self.size.height, None)
.into_iter(),
);
self.framebuffer_texture = if self.sample_count > 1 {
Some(Texture::create_framebuffer(
&self.device,
&self.config,
self.sample_count,
Some("Multisample framebuffer"),
))
} else {
None
};
self.depth_texture = Texture::create_depth_texture(
&self.device,
&self.config,
self.sample_count,
Some("Depth texture"),
);
}
}
pub fn render(&mut self) -> Result<Duration, wgpu::SurfaceError> {
let now = Instant::now();
self.projection.update(&self.device, &self.queue);
self.animated_model
.display_list
.update(&self.device, &self.queue);
let part_querier = self.parts.borrow();
let output = self.surface.get_current_texture()?;
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let (target_view, resolve_target) = if let Some(texture) = self.framebuffer_texture.as_ref()
{
(&texture.view, Some(&view))
} else {
(&view, None)
};
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Command Encoder"),
});
{
let mut pass = encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Main render pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target_view,
resolve_target,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 1.0,
g: 1.0,
b: 1.0,
a: 0.0,
}),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_texture.view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
occlusion_query_set: None,
timestamp_writes: None,
})
.forget_lifetime();
self.pipelines.render::<_, _>(
&mut pass,
self.projection.get(),
&*part_querier,
&self.animated_model.display_list,
);
}
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
Ok(now.elapsed())
}
pub fn get_subparts(&self) -> Vec<(GroupId, String)> {
if let Some(model) = &self.model {
let mut result = model
.object_groups
.iter()
.map(|(k, v)| (*k, v.name.clone()))
.collect::<Vec<_>>();
result.sort_by(|a, b| a.1.cmp(&b.1));
result
} else {
Vec::new()
}
}
pub fn set_render_target(&mut self, group_id: Option<GroupId>) {
if let Some(model) = &mut self.model {
self.animated_model = AnimatedModel::from_model(model, group_id, &self.colors, false);
let bounding_box = calculate_model_bounding_box(model, group_id, &*self.parts.borrow());
let center = bounding_box.center();
let mut orbit_controller = self.orbit_controller.borrow_mut();
orbit_controller.camera.look_at = Point3::new(center.x, center.y, center.z);
orbit_controller.radius = (bounding_box.len_x() * bounding_box.len_x()
+ bounding_box.len_y() * bounding_box.len_y()
+ bounding_box.len_z() * bounding_box.len_z())
.sqrt()
* 2.0;
}
}
pub fn state(&self) -> State {
self.animated_model.state
}
pub fn handle_window_event(&mut self, event: event::WindowEvent, current_time: f32) -> bool {
match event {
event::WindowEvent::Resized(size) => {
self.resize(size);
}
event::WindowEvent::KeyboardInput { event, .. } => {
if event.logical_key == Key::Named(NamedKey::Space)
&& event.state == event::ElementState::Pressed
{
self.advance(current_time);
}
}
event::WindowEvent::MouseInput { state, button, .. } => {
if button == event::MouseButton::Left {
self.orbit_controller
.borrow_mut()
.on_mouse_press(state == event::ElementState::Pressed);
}
}
event::WindowEvent::MouseWheel { delta, .. } => match delta {
event::MouseScrollDelta::LineDelta(_x, y) => {
self.orbit_controller.borrow_mut().zoom(y);
}
event::MouseScrollDelta::PixelDelta(d) => {
self.orbit_controller.borrow_mut().zoom(d.y as f32 * 0.5);
}
},
event::WindowEvent::Touch(touch) => match touch.phase {
event::TouchPhase::Started => {
self.orbit_controller.borrow_mut().on_mouse_press(true)
}
event::TouchPhase::Ended | event::TouchPhase::Cancelled => {
self.orbit_controller.borrow_mut().on_mouse_press(false)
}
event::TouchPhase::Moved => self
.orbit_controller
.borrow_mut()
.on_mouse_move(touch.location.x as f32, touch.location.y as f32),
},
event::WindowEvent::TouchpadMagnify { delta, .. } => {
self.orbit_controller.borrow_mut().zoom(delta as f32);
}
event::WindowEvent::CursorMoved { position, .. } => {
self.orbit_controller
.borrow_mut()
.on_mouse_move(position.x as f32, position.y as f32);
}
_ => return false,
}
true
}
pub fn request_redraw(&self) {
self.window.request_redraw();
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/tools/viewer/common/src/texture.rs | tools/viewer/common/src/texture.rs | pub struct Texture {
_texture: wgpu::Texture,
pub view: wgpu::TextureView,
_sampler: wgpu::Sampler,
}
impl Texture {
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
pub fn create_framebuffer(
device: &wgpu::Device,
config: &wgpu::SurfaceConfiguration,
sample_count: u32,
label: Option<&str>,
) -> Self {
let extent = wgpu::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
size: extent,
mip_level_count: 1,
sample_count,
dimension: wgpu::TextureDimension::D2,
format: config.view_formats[0],
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
label,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Nearest,
compare: Some(wgpu::CompareFunction::LessEqual),
lod_min_clamp: 0.0,
lod_max_clamp: 100.0,
..Default::default()
});
Self {
_texture: texture,
view,
_sampler: sampler,
}
}
pub fn create_depth_texture(
device: &wgpu::Device,
config: &wgpu::SurfaceConfiguration,
sample_count: u32,
label: Option<&str>,
) -> Self {
let size = wgpu::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
label,
size,
mip_level_count: 1,
sample_count,
dimension: wgpu::TextureDimension::D2,
format: Self::DEPTH_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[Self::DEPTH_FORMAT],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Nearest,
compare: Some(wgpu::CompareFunction::LessEqual),
lod_min_clamp: 0.0,
lod_max_clamp: 100.0,
..Default::default()
});
Self {
_texture: texture,
view,
_sampler: sampler,
}
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/tools/viewer/common/src/error.rs | tools/viewer/common/src/error.rs | use std::{
error::Error,
fmt::{Display, Formatter, Result as FmtResult},
};
#[derive(Debug)]
pub enum AppCreationError {
NoAdapterFound,
RequestDeviceError(wgpu::RequestDeviceError),
CreateSurfaceError(wgpu::CreateSurfaceError),
}
impl Display for AppCreationError {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
match self {
Self::NoAdapterFound => {
write!(f, "No adapter found.")
}
Self::RequestDeviceError(e) => {
write!(f, "Error requesting device: {}", e)
}
Self::CreateSurfaceError(e) => {
write!(f, "Error creating surface: {}", e)
}
}
}
}
impl Error for AppCreationError {
fn cause(&self) -> Option<&(dyn Error)> {
match *self {
Self::NoAdapterFound => None,
Self::RequestDeviceError(ref e) => Some(e),
Self::CreateSurfaceError(ref e) => Some(e),
}
}
}
impl From<wgpu::RequestDeviceError> for AppCreationError {
fn from(e: wgpu::RequestDeviceError) -> Self {
Self::RequestDeviceError(e)
}
}
impl From<wgpu::CreateSurfaceError> for AppCreationError {
fn from(e: wgpu::CreateSurfaceError) -> Self {
Self::CreateSurfaceError(e)
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/tools/viewer/web/src/lib.rs | tools/viewer/web/src/lib.rs | #![cfg(target_arch = "wasm32")]
extern crate console_error_panic_hook;
use std::{
cell::RefCell,
panic,
rc::Rc,
sync::{Arc, RwLock},
};
use gloo::events::EventListener;
use ldraw::{
document::MultipartDocument,
error::ResolutionError,
library::{CacheCollectionStrategy, LibraryLoader, PartCache},
parser::parse_multipart_document,
resolvers::http::HttpLoader,
PartAlias,
};
use reqwest::{Client, Url};
use tokio::io::BufReader;
use uuid::Uuid;
use viewer_common::{App, State};
use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::spawn_local;
use web_sys::{
HtmlButtonElement, HtmlCanvasElement, HtmlDivElement, HtmlSelectElement, HtmlTextAreaElement,
};
use winit::{
event, event_loop::EventLoop, platform::web::WindowBuilderExtWebSys, window::WindowBuilder,
};
// A huge mess. Needs refactoring.
const ANTIALIAS: bool = true;
fn log(s: &str, error: bool) {
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let console = document.get_element_by_id("console-pane").unwrap();
let node = document.create_element("p").unwrap();
node.set_attribute(
"class",
match error {
false => "log",
true => "error",
},
)
.unwrap();
node.set_inner_html(s);
console.prepend_with_node_1(&node).unwrap();
}
fn alert(s: &str) {
let window = web_sys::window().unwrap();
window.alert_with_message(s).unwrap();
}
macro_rules! console_log {
($($t:tt)*) => (log(&format_args!($($t)*).to_string(), false))
}
macro_rules! console_error {
($($t:tt)*) => (alert(&format_args!($($t)*).to_string()))
}
async fn fetch_raw_data(base_url: &Url, path: &String) -> Option<String> {
let client = Client::new();
let url = if path.starts_with("http://") || path.starts_with("https://") {
Url::parse(path)
} else {
base_url.join(path)
};
let url = match url {
Ok(e) => e,
Err(err) => {
alert(&format!("Could not build url {}: {}", path, err));
return None;
}
};
match client.get(url.clone()).send().await {
Ok(e) => match e.text().await {
Ok(e) => Some(e),
Err(err) => {
alert(&format!("Could not fetch from url {}: {}", url, err));
None
}
},
Err(err) => {
alert(&format!("Could not make request to {}: {}", url, err));
None
}
}
}
fn log_part_resolution(alias: PartAlias, result: Result<(), ResolutionError>) {
match result {
Ok(_) => {
console_log!("Part {} loaded", alias);
}
Err(err) => {
console_error!("Could not load part {}: {}", alias, err);
}
}
}
#[wasm_bindgen]
#[allow(clippy::await_holding_refcell_ref)]
pub async fn run(path: JsValue) -> JsValue {
panic::set_hook(Box::new(console_error_panic_hook::hook));
let web_window = web_sys::window().expect("No window exists.");
let web_document = web_window.document().expect("No document exists.");
let body = web_document.get_element_by_id("body").unwrap();
let canvas = web_document
.get_element_by_id("main_canvas")
.unwrap()
.dyn_into::<HtmlCanvasElement>()
.unwrap();
canvas.set_width(body.client_width() as u32);
canvas.set_height(body.client_height() as u32);
let event_loop = EventLoop::new().unwrap();
let builder = WindowBuilder::new()
.with_title("ldraw.rs demo")
.with_inner_size(winit::dpi::LogicalSize {
width: body.client_width() as u32,
height: body.client_height() as u32,
})
.with_canvas(Some(canvas));
let window = builder.build(&event_loop).unwrap();
let canvas = web_document
.get_element_by_id("main_canvas")
.unwrap()
.dyn_into::<HtmlCanvasElement>()
.unwrap();
let document_view = web_document
.get_element_by_id("document")
.unwrap()
.dyn_into::<HtmlTextAreaElement>()
.unwrap();
let mut location = Url::parse(&web_window.location().href().unwrap()).unwrap();
location.set_fragment(None);
let loader = Rc::new(HttpLoader::new(
Some(location.join("ldraw/").unwrap()),
Some(location.clone()),
));
let colors = match loader.load_colors().await {
Ok(e) => Rc::new(e),
Err(err) => {
console_error!("Could not open color definitions: {}", err);
return JsValue::undefined();
}
};
let main_window_id = window.id();
let window = Arc::new(window);
let app = match App::new(
Arc::clone(&window),
Rc::clone(&loader),
Rc::clone(&colors),
ANTIALIAS,
)
.await
{
Ok(v) => v,
Err(e) => {
console_error!("Could not initialize the app: {e}");
return JsValue::undefined();
}
};
let app = Rc::new(RefCell::new(app));
console_log!("Rendering context initialization done.");
let cache = Arc::new(RwLock::new(PartCache::default()));
app.borrow_mut().resize(winit::dpi::PhysicalSize {
width: canvas.width(),
height: canvas.height(),
});
let window = web_sys::window().unwrap();
let perf = window.performance().unwrap();
let start_time = perf.now();
{
let document_view = document_view.clone();
if path.is_string() {
let path = path.as_string().unwrap();
let document_text = match fetch_raw_data(&location, &path).await {
Some(v) => v,
None => {
return JsValue::undefined();
}
};
let document = match parse_multipart_document(
&mut BufReader::new(document_text.as_bytes()),
&colors,
)
.await
{
Ok(v) => v,
Err(err) => {
console_error!("Could not parse document: {}", err);
return JsValue::undefined();
}
};
if let Err(err) = app
.borrow_mut()
.set_document(Arc::clone(&cache), &document, &log_part_resolution)
.await
{
console_error!("Could not load model: {}", err);
}
cache
.write()
.unwrap()
.collect(CacheCollectionStrategy::Parts);
let subparts = web_document.get_element_by_id("subparts").unwrap();
subparts.set_inner_html("");
let body = web_document.create_element("option").unwrap();
body.set_attribute("value", "").unwrap();
body.set_inner_html("Base Model");
subparts.append_child(&body).unwrap();
for (id, name) in app.borrow().get_subparts() {
let subpart = web_document.create_element("option").unwrap();
subpart.set_attribute("value", &format!("{}", id)).unwrap();
subpart.set_inner_html(&format!("Subpart {} ({})", name, id));
subparts.append_child(&subpart).unwrap();
}
let web_document = web_document.clone();
let app = Rc::clone(&app);
let closure = Closure::wrap(Box::new(move |_event: web_sys::Event| {
let subparts = web_document.get_element_by_id("subparts").unwrap();
let subparts = JsCast::dyn_ref::<HtmlSelectElement>(&subparts).unwrap();
let value = subparts.value();
app.borrow_mut().set_render_target(if value.is_empty() {
None
} else {
Some(value.parse::<Uuid>().unwrap().into())
});
}) as Box<dyn FnMut(_)>);
subparts
.add_event_listener_with_callback("change", closure.as_ref().unchecked_ref())
.unwrap();
closure.forget();
document_view.set_value(&document_text);
}
}
let new_doc = Rc::new(RefCell::new(None));
{
let document_view = document_view.clone();
let new_doc = Rc::clone(&new_doc);
let colors = Rc::clone(&colors);
let closure = Closure::wrap(Box::new(move |_event: web_sys::Event| {
let document_view = document_view.clone();
let new_doc = Rc::clone(&new_doc);
let colors = Rc::clone(&colors);
spawn_local(async move {
let document_text = document_view.value();
let document = match parse_multipart_document(
&mut BufReader::new(document_text.as_bytes()),
&colors,
)
.await
{
Ok(v) => v,
Err(err) => {
console_error!("Could not parse document: {}", err);
return;
}
};
*new_doc.borrow_mut() = Some(document);
});
}) as Box<dyn FnMut(_)>);
let submit_button = web_document.get_element_by_id("submit").unwrap();
let submit_button = JsCast::dyn_ref::<HtmlButtonElement>(&submit_button).unwrap();
submit_button
.add_event_listener_with_callback("click", closure.as_ref().unchecked_ref())
.unwrap();
closure.forget();
}
{
let window = web_sys::window().unwrap();
let app = Rc::clone(&app);
let closure = Closure::wrap(Box::new(move |_event: web_sys::UiEvent| {
let app = &mut app.borrow_mut();
canvas.set_width(canvas.client_width() as _);
canvas.set_height(canvas.client_height() as _);
app.resize(winit::dpi::PhysicalSize {
width: canvas.client_width() as _,
height: canvas.client_height() as _,
});
}) as Box<dyn FnMut(_)>);
window
.add_event_listener_with_callback("resize", closure.as_ref().unchecked_ref())
.unwrap();
closure.forget();
}
{
let next_button = web_document.get_element_by_id("next-button").unwrap();
let next_button = JsCast::dyn_ref::<HtmlDivElement>(&next_button).unwrap();
let a = Rc::clone(&app);
let closure = EventListener::new(next_button, "click", move |_event| {
let window = web_sys::window().unwrap();
let perf = window.performance().unwrap();
a.borrow_mut()
.advance(((perf.now() - start_time) / 1000.0) as f32);
});
closure.forget();
}
{
let app = Rc::clone(&app);
let new_doc = Rc::clone(&new_doc);
let web_document = web_document.clone();
let cache = Arc::clone(&cache);
event_loop
.run(move |event, target| match event {
event::Event::AboutToWait => {
app.borrow().request_redraw();
}
event::Event::WindowEvent { event, window_id } if window_id == main_window_id => {
match event {
event::WindowEvent::RedrawRequested => {
let mut app_ = app.borrow_mut();
app_.animate(((perf.now() - start_time) / 1000.0) as f32);
match app_.render() {
Ok(duration) => {
let next_button =
web_document.get_element_by_id("next-button").unwrap();
let next_button =
JsCast::dyn_ref::<HtmlDivElement>(&next_button).unwrap();
if app_.state() == State::Step {
next_button.set_class_name("active");
} else {
next_button.set_class_name("");
}
let stats = web_document.get_element_by_id("stats").unwrap();
let stats = JsCast::dyn_ref::<HtmlDivElement>(&stats).unwrap();
stats.set_inner_html(&format!(
"Rendering backend: {}<br />{} msecs",
app_.adapter_info.backend.to_str(),
duration.as_millis(),
));
}
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
//app.resize(app.size);
}
Err(wgpu::SurfaceError::OutOfMemory) => {
target.exit();
}
Err(wgpu::SurfaceError::Timeout) => {
println!("Surface timeout");
}
Err(wgpu::SurfaceError::Other) => {
println!("Unrecognized surface error");
}
}
if new_doc.borrow().is_some() {
let document =
MultipartDocument::clone(new_doc.borrow().as_ref().unwrap());
*new_doc.borrow_mut() = None;
let app = Rc::clone(&app);
let cache = Arc::clone(&cache);
let web_document = web_document.clone();
spawn_local(async move {
if let Err(err) = app
.borrow_mut()
.set_document(
Arc::clone(&cache),
&document,
&log_part_resolution,
)
.await
{
console_error!("Could not reload model: {}", err);
};
cache
.write()
.unwrap()
.collect(CacheCollectionStrategy::Parts);
let subparts =
web_document.get_element_by_id("subparts").unwrap();
subparts.set_inner_html("");
let body = web_document.create_element("option").unwrap();
body.set_attribute("value", "").unwrap();
body.set_inner_html("Base Model");
subparts.append_child(&body).unwrap();
console_log!("{:?}", body);
for (id, name) in app.borrow().get_subparts() {
let subpart =
web_document.create_element("option").unwrap();
subpart.set_attribute("value", &format!("{}", id)).unwrap();
subpart
.set_inner_html(&format!("Subpart {} ({})", name, id));
subparts.append_child(&subpart).unwrap();
}
});
}
}
event::WindowEvent::CloseRequested => {}
event => {
if let Ok(mut app) = app.try_borrow_mut() {
app.handle_window_event(
event,
((perf.now() - start_time) / 1000.0) as f32,
);
}
}
}
}
_ => (),
})
.unwrap();
}
JsValue::undefined()
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/tools/baker/src/main.rs | tools/baker/src/main.rs | use std::{
env,
path::{Path, PathBuf},
sync::{Arc, RwLock},
};
use bincode::serialize;
use clap::{App, Arg};
use futures::{future::join_all, StreamExt};
use itertools::Itertools;
use ldraw::{
color::ColorCatalog,
library::{resolve_dependencies_multipart, CacheCollectionStrategy, LibraryLoader, PartCache},
parser::{parse_color_definitions, parse_multipart_document},
resolvers::local::LocalLoader,
};
use ldraw_ir::part::bake_part_from_multipart_document;
use tokio::{
fs::{self, File},
io::{AsyncWriteExt, BufReader, BufWriter},
task::spawn_blocking,
};
use tokio_stream::wrappers::ReadDirStream;
#[tokio::main]
async fn main() {
let matches = App::new("baker")
.about("Postprocess LDraw model files")
.arg(
Arg::with_name("ldraw_dir")
.long("ldraw-dir")
.value_name("PATH")
.takes_value(true)
.help("Path to LDraw directory"),
)
.arg(
Arg::with_name("files")
.multiple(true)
.takes_value(true)
.required(true)
.help("Files to process"),
)
.arg(
Arg::with_name("output_path")
.short("o")
.long("output-path")
.takes_value(true)
.help("Output path"),
)
.get_matches();
let ldrawdir = match matches.value_of("ldraw_dir") {
Some(v) => v.to_string(),
None => match env::var("LDRAWDIR") {
Ok(v) => v,
Err(_) => {
panic!("--ldraw-dir option or LDRAWDIR environment variable is required.");
}
},
};
let output_path = match matches.value_of("output_path") {
Some(v) => {
let path = Path::new(v);
if !path.is_dir() {
panic!("{} is not a proper output directory", v);
}
Some(path)
}
None => None,
};
let ldrawpath = PathBuf::from(&ldrawdir);
let colors = parse_color_definitions(&mut BufReader::new(
File::open(ldrawpath.join("LDConfig.ldr"))
.await
.expect("Could not load color definition."),
))
.await
.expect("Could not parse color definition");
let loader = LocalLoader::new(Some(ldrawpath), None);
let mut tasks = vec![];
let cache = Arc::new(RwLock::new(PartCache::new()));
if let Some(files) = matches.values_of("files") {
for file in files {
let path = PathBuf::from(&file);
if !fs::try_exists(&path).await.unwrap_or(false) {
panic!("Path {} does not exists.", file);
} else if path.is_dir() {
let mut dir = ReadDirStream::new(
fs::read_dir(&path)
.await
.expect("Could not read directory."),
);
while let Some(entry) = dir.next().await {
let entry = entry.unwrap();
let path = entry.path();
let ext = path.extension();
if ext.is_none() {
continue;
}
let ext = ext.unwrap().to_str().unwrap().to_string().to_lowercase();
if ext == "dat" || ext == "ldr" {
tasks.push(bake(
&loader,
&colors,
Arc::clone(&cache),
path,
&output_path,
));
}
}
} else {
tasks.push(bake(
&loader,
&colors,
Arc::clone(&cache),
path,
&output_path,
));
}
}
} else {
panic!("Required input files are missing.");
}
let cpus = num_cpus::get();
let tasks = tasks
.into_iter()
.chunks(cpus)
.into_iter()
.map(|chunk| chunk.collect())
.collect::<Vec<Vec<_>>>();
for items in tasks {
join_all(items).await;
}
let collected = cache
.write()
.unwrap()
.collect(CacheCollectionStrategy::PartsAndPrimitives);
println!("Collected {} entries.", collected);
}
async fn bake<L: LibraryLoader>(
loader: &L,
colors: &ColorCatalog,
cache: Arc<RwLock<PartCache>>,
path: PathBuf,
output_path: &Option<&Path>,
) {
println!("{}", path.to_str().unwrap());
let file = match File::open(path.clone()).await {
Ok(v) => v,
Err(err) => {
println!(
"Could not open document {}: {}",
path.to_str().unwrap(),
err
);
return;
}
};
let document = match parse_multipart_document(&mut BufReader::new(file), colors).await {
Ok(v) => v,
Err(err) => {
println!(
"Could not parse document {}: {}",
path.to_str().unwrap(),
err
);
return;
}
};
let resolution_result = resolve_dependencies_multipart(
&document,
Arc::clone(&cache),
colors,
loader,
&|alias, result| {
if let Err(err) = result {
println!("Could not open file {}: {}", alias, err);
}
},
)
.await;
let part = spawn_blocking(move || {
bake_part_from_multipart_document(&document, &resolution_result, false)
})
.await
.unwrap();
let outpath = match output_path {
Some(e) => e.to_path_buf().join(format!(
"{}.part",
path.file_name().unwrap().to_str().unwrap()
)),
None => {
let mut path_buf = path.to_path_buf();
path_buf.set_extension(match path.extension() {
Some(e) => format!("{}.part", e.to_str().unwrap()),
None => String::from("part"),
});
path_buf
}
};
match serialize(&part) {
Ok(serialized) => match File::create(&outpath).await {
Ok(file) => {
let mut writer = BufWriter::new(file);
writer.write_all(&serialized).await.unwrap();
writer.shutdown().await.unwrap();
}
Err(err) => {
println!("Could not create {}: {}", outpath.to_str().unwrap(), err);
}
},
Err(err) => {
println!("Could not bake part {}: {}", path.to_str().unwrap(), err);
}
};
cache
.write()
.unwrap()
.collect(CacheCollectionStrategy::Parts);
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/tools/ldr2img/src/main.rs | tools/ldr2img/src/main.rs | use std::{
collections::HashMap,
env,
path::{Path, PathBuf},
sync::{Arc, RwLock},
};
use clap::{App, Arg};
use ldraw::{
library::{resolve_dependencies_multipart, PartCache},
parser::{parse_color_definitions, parse_multipart_document},
resolvers::local::LocalLoader,
PartAlias,
};
use ldraw_ir::{model::Model, part::bake_part_from_multipart_document};
use ldraw_olr::{context::Context, ops::Ops};
use ldraw_renderer::part::{Part, PartQuerier};
use tokio::{fs::File, io::BufReader};
#[tokio::main]
async fn main() {
let matches = App::new("ldr2img")
.about("Render LDraw model into still image")
.arg(
Arg::with_name("ldraw_dir")
.long("ldraw-dir")
.value_name("PATH")
.takes_value(true)
.help("Path to LDraw directory"),
)
.arg(
Arg::with_name("output")
.short("o")
.takes_value(true)
.help("Output file name"),
)
.arg(
Arg::with_name("input")
.takes_value(true)
.required(true)
.index(1)
.help("Input file name"),
)
.arg(
Arg::with_name("size")
.short("s")
.default_value("1024")
.takes_value(true)
.help("Maximum width/height pixel size"),
)
.arg(
Arg::with_name("without-multisample")
.short("m")
.help("Number of samples"),
)
.get_matches();
let ldrawdir = match matches.value_of("ldraw_dir") {
Some(v) => v.to_string(),
None => match env::var("LDRAWDIR") {
Ok(v) => v,
Err(_) => {
panic!("--ldraw-dir option or LDRAWDIR environment variable is required.");
}
},
};
let ldraw_path = PathBuf::from(&ldrawdir);
let size = matches.value_of("size").unwrap().parse::<u32>().unwrap();
let sample_count = if matches.is_present("without-multisample") {
1
} else {
4
};
let mut context = Context::new(size, size, sample_count).await.unwrap();
let colors = parse_color_definitions(&mut BufReader::new(
File::open(ldraw_path.join("LDConfig.ldr")).await.unwrap(),
))
.await
.unwrap();
let input = matches.value_of("input").unwrap();
let output = matches.value_of("output").unwrap_or("image.png");
let document = parse_multipart_document(
&mut BufReader::new(File::open(&input).await.unwrap()),
&colors,
)
.await
.unwrap();
let input_path = PathBuf::from(input);
let loader = LocalLoader::new(
Some(ldraw_path),
Some(PathBuf::from(input_path.parent().unwrap())),
);
let cache = Arc::new(RwLock::new(PartCache::new()));
let resolution_result =
resolve_dependencies_multipart(&document, Arc::clone(&cache), &colors, &loader, &|_, _| {})
.await;
struct PartsPoolImpl(HashMap<PartAlias, Part>);
impl PartQuerier<PartAlias> for PartsPoolImpl {
fn get(&self, key: &PartAlias) -> Option<&Part> {
self.0.get(key)
}
}
let parts = document
.list_dependencies()
.into_iter()
.filter_map(|alias| {
resolution_result.query(&alias, true).map(|(part, local)| {
(
alias.clone(),
Part::new(
&bake_part_from_multipart_document(part, &resolution_result, local),
&context.device,
&colors,
),
)
})
})
.collect::<HashMap<_, _>>();
let parts = PartsPoolImpl(parts);
let model =
Model::from_ldraw_multipart_document(&document, &colors, Some((&loader, cache))).await;
let image = {
let ops = Ops::new(&mut context);
ops.render_model(&model, None, &parts, &colors).await
};
image.save(&Path::new(output)).unwrap();
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ir/src/lib.rs | ir/src/lib.rs | use std::{
cmp::Ordering,
fmt,
hash::{Hash, Hasher},
};
use ldraw::color::{ColorCatalog, ColorReference};
use serde::{
de::{Deserializer, Error as DeError, Unexpected, Visitor},
ser::Serializer,
Deserialize, Serialize,
};
pub mod constraints;
pub mod geometry;
pub mod model;
pub mod part;
#[derive(Clone, Debug)]
pub struct MeshGroupKey {
pub color_ref: ColorReference,
pub bfc: bool,
}
impl Serialize for MeshGroupKey {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if self.bfc {
serializer.serialize_str(&self.color_ref.code().to_string())
} else {
serializer.serialize_str(&format!("!{}", self.color_ref.code()))
}
}
}
impl<'de> Deserialize<'de> for MeshGroupKey {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct MeshGroupVisitor;
impl<'de> Visitor<'de> for MeshGroupVisitor {
type Value = MeshGroupKey;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(
"a string with number in it and optional exclamation mark preceding to it",
)
}
fn visit_str<E: DeError>(self, value: &str) -> Result<Self::Value, E> {
let (slice, bfc) = if let Some(stripped) = value.strip_prefix('!') {
(stripped, false)
} else {
(value, true)
};
match slice.parse::<u32>() {
Ok(v) => Ok(MeshGroupKey {
color_ref: ColorReference::Unknown(v),
bfc,
}),
Err(_) => Err(DeError::invalid_value(
Unexpected::Str(value),
&"a string with number in it and optional exclamation mark preceding to it",
)),
}
}
}
deserializer.deserialize_str(MeshGroupVisitor)
}
}
impl MeshGroupKey {
pub fn resolve_color(&mut self, colors: &ColorCatalog) {
self.color_ref.resolve_self(colors);
}
}
impl Hash for MeshGroupKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.color_ref.code().hash(state);
self.bfc.hash(state);
}
}
impl PartialOrd for MeshGroupKey {
fn partial_cmp(&self, other: &MeshGroupKey) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MeshGroupKey {
fn cmp(&self, other: &MeshGroupKey) -> Ordering {
let lhs_translucent = match &self.color_ref {
ColorReference::Color(c) => c.is_translucent(),
_ => false,
};
let rhs_translucent = match &other.color_ref {
ColorReference::Color(c) => c.is_translucent(),
_ => false,
};
match (lhs_translucent, rhs_translucent) {
(true, false) => return Ordering::Greater,
(false, true) => return Ordering::Less,
(_, _) => (),
};
match self.color_ref.code().cmp(&other.color_ref.code()) {
Ordering::Equal => self.bfc.cmp(&other.bfc),
e => e,
}
}
}
impl Eq for MeshGroupKey {}
impl PartialEq for MeshGroupKey {
fn eq(&self, other: &MeshGroupKey) -> bool {
self.color_ref.code() == other.color_ref.code() && self.bfc == other.bfc
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ir/src/geometry.rs | ir/src/geometry.rs | use ldraw::{Matrix4, Vector2, Vector3};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BoundingBox2 {
pub min: Vector2,
pub max: Vector2,
}
impl BoundingBox2 {
pub fn nil() -> Self {
BoundingBox2 {
min: Vector2::new(0.0, 0.0),
max: Vector2::new(0.0, 0.0),
}
}
pub fn new(a: &Vector2, b: &Vector2) -> Self {
let (min_x, max_x) = if a.x > b.x { (b.x, a.x) } else { (a.x, b.x) };
let (min_y, max_y) = if a.y > b.y { (b.y, a.y) } else { (a.y, b.y) };
Self {
min: Vector2::new(min_x, min_y),
max: Vector2::new(max_x, max_y),
}
}
pub fn new_xywh(x: f32, y: f32, w: f32, h: f32) -> Self {
Self {
min: Vector2::new(x, y),
max: Vector2::new(x + w, y + h),
}
}
pub fn len_x(&self) -> f32 {
self.max.x - self.min.x
}
pub fn len_y(&self) -> f32 {
self.max.y - self.min.y
}
pub fn is_null(&self) -> bool {
self.min.x == 0.0 && self.min.y == 0.0 && self.max.x == 0.0 && self.max.y == 0.0
}
pub fn update_point(&mut self, v: &Vector2) {
if self.is_null() {
self.min = *v;
self.max = *v;
} else {
if self.min.x > v.x {
self.min.x = v.x;
}
if self.min.y > v.y {
self.min.y = v.y;
}
if self.max.x < v.x {
self.max.x = v.x;
}
if self.max.y < v.y {
self.max.y = v.y;
}
}
}
pub fn update(&mut self, bb: &BoundingBox2) {
self.update_point(&bb.min);
self.update_point(&bb.max);
}
pub fn center(&self) -> Vector2 {
(self.min + self.max) * 0.5
}
pub fn points(&self) -> [Vector2; 4] {
[
Vector2::new(self.min.x, self.min.y),
Vector2::new(self.min.x, self.max.y),
Vector2::new(self.max.x, self.min.y),
Vector2::new(self.max.x, self.max.y),
]
}
pub fn intersects(&self, other: &Self) -> bool {
self.min.x < other.max.x
&& self.max.x > other.min.x
&& self.min.y < other.max.y
&& self.max.y > other.min.y
}
}
impl Default for BoundingBox2 {
fn default() -> Self {
Self::nil()
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BoundingBox3 {
pub min: Vector3,
pub max: Vector3,
null: bool,
}
impl BoundingBox3 {
pub fn nil() -> Self {
BoundingBox3 {
min: Vector3::new(0.0, 0.0, 0.0),
max: Vector3::new(0.0, 0.0, 0.0),
null: true,
}
}
pub fn new(a: &Vector3, b: &Vector3) -> Self {
let (min_x, max_x) = if a.x > b.x { (b.x, a.x) } else { (a.x, b.x) };
let (min_y, max_y) = if a.y > b.y { (b.y, a.y) } else { (a.y, b.y) };
let (min_z, max_z) = if a.z > b.z { (b.z, a.z) } else { (a.z, b.z) };
BoundingBox3 {
min: Vector3::new(min_x, min_y, min_z),
max: Vector3::new(max_x, max_y, max_z),
null: false,
}
}
pub fn transform(&self, matrix: &Matrix4) -> Self {
let mut bb = BoundingBox3::nil();
for vertex in self.points() {
let translated = matrix * vertex.extend(1.0);
bb.update_point(&translated.truncate())
}
bb
}
pub fn project(&self, matrix: &Matrix4) -> BoundingBox2 {
let mut bb = BoundingBox2::nil();
for vertex in self.points() {
let translated = matrix * vertex.extend(1.0);
bb.update_point(&Vector2::new(
translated.x / translated.w,
translated.y / translated.w,
));
}
bb
}
pub fn len_x(&self) -> f32 {
if self.null {
0.0
} else {
self.max.x - self.min.x
}
}
pub fn len_y(&self) -> f32 {
if self.null {
0.0
} else {
self.max.y - self.min.y
}
}
pub fn len_z(&self) -> f32 {
if self.null {
0.0
} else {
self.max.z - self.min.z
}
}
pub fn len(&self) -> f32 {
(self.len_x().powi(2) + self.len_y().powi(2) + self.len_z().powi(2)).sqrt()
}
pub fn is_null(&self) -> bool {
self.null
}
pub fn update_point(&mut self, v: &Vector3) {
if self.null {
self.min = *v;
self.max = *v;
self.null = false;
} else {
if self.min.x > v.x {
self.min.x = v.x;
}
if self.min.y > v.y {
self.min.y = v.y;
}
if self.min.z > v.z {
self.min.z = v.z;
}
if self.max.x < v.x {
self.max.x = v.x;
}
if self.max.y < v.y {
self.max.y = v.y;
}
if self.max.z < v.z {
self.max.z = v.z;
}
}
}
pub fn update(&mut self, bb: &BoundingBox3) {
self.update_point(&bb.min);
self.update_point(&bb.max);
}
pub fn center(&self) -> Vector3 {
if self.null {
Vector3::new(0.0, 0.0, 0.0)
} else {
(self.min + self.max) * 0.5
}
}
pub fn points(&self) -> [Vector3; 8] {
[
Vector3::new(self.min.x, self.min.y, self.min.z),
Vector3::new(self.min.x, self.min.y, self.max.z),
Vector3::new(self.min.x, self.max.y, self.min.z),
Vector3::new(self.min.x, self.max.y, self.max.z),
Vector3::new(self.max.x, self.min.y, self.min.z),
Vector3::new(self.max.x, self.min.y, self.max.z),
Vector3::new(self.max.x, self.max.y, self.min.z),
Vector3::new(self.max.x, self.max.y, self.max.z),
]
}
}
impl Default for BoundingBox3 {
fn default() -> Self {
Self::nil()
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ir/src/model.rs | ir/src/model.rs | use std::{
collections::{HashMap, HashSet},
fmt,
hash::Hash,
sync::{Arc, RwLock},
vec::Vec,
};
use cgmath::SquareMatrix;
use ldraw::{
color::{ColorCatalog, ColorReference},
document::{Document as LdrawDocument, MultipartDocument as LdrawMultipartDocument},
elements::{Command, Meta},
library::{resolve_dependencies, LibraryLoader, PartCache, ResolutionResult},
Matrix4, PartAlias, Vector3,
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
geometry::BoundingBox3,
part::{
bake_part_from_document, bake_part_from_multipart_document, Part, PartDimensionQuerier,
},
};
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Deserialize, Serialize)]
pub struct ObjectId(Uuid);
impl From<Uuid> for ObjectId {
fn from(value: Uuid) -> Self {
Self(value)
}
}
impl From<ObjectId> for Uuid {
fn from(value: ObjectId) -> Self {
value.0
}
}
impl fmt::Display for ObjectId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Deserialize, Serialize)]
pub struct GroupId(Uuid);
impl From<Uuid> for GroupId {
fn from(value: Uuid) -> Self {
Self(value)
}
}
impl From<GroupId> for Uuid {
fn from(value: GroupId) -> Self {
value.0
}
}
impl fmt::Display for GroupId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum ObjectInstance<P> {
Part(PartInstance<P>),
PartGroup(PartGroupInstance),
Step,
Annotation(Annotation),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Object<P> {
pub id: ObjectId,
pub data: ObjectInstance<P>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PartInstance<P> {
pub matrix: Matrix4,
pub color: ColorReference,
pub part: P,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PartGroupInstance {
pub matrix: Matrix4,
pub color: ColorReference,
pub group_id: GroupId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Annotation {
pub position: Vector3,
pub body: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ObjectGroup<P> {
pub id: GroupId,
pub name: String,
pub objects: Vec<Object<P>>,
pub pivot: Vector3,
}
impl<P> ObjectGroup<P> {
pub fn new(id: GroupId, name: String, pivot: Option<Vector3>) -> Self {
Self {
id,
name,
objects: Vec::new(),
pivot: pivot.unwrap_or_else(|| Vector3::new(0.0, 0.0, 0.0)),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Model<P: Clone + Eq + PartialEq + Hash> {
pub object_groups: HashMap<GroupId, ObjectGroup<P>>,
pub objects: Vec<Object<P>>,
pub embedded_parts: HashMap<P, Part>,
}
impl<P: Clone + Eq + PartialEq + Hash> Default for Model<P> {
fn default() -> Self {
Self {
object_groups: HashMap::new(),
objects: Vec::new(),
embedded_parts: HashMap::new(),
}
}
}
fn build_objects<P: Clone + Eq + PartialEq + Hash + From<PartAlias>>(
document: &LdrawDocument,
subparts: Option<&HashMap<P, GroupId>>,
) -> Vec<Object<P>> {
document
.commands
.iter()
.filter_map(|cmd| {
let data = match cmd {
Command::PartReference(r) => match subparts {
Some(subparts) => match subparts.get(&r.name.clone().into()) {
Some(e) => Some(ObjectInstance::PartGroup(PartGroupInstance {
matrix: r.matrix,
color: r.color.clone(),
group_id: *e,
})),
None => Some(ObjectInstance::Part(PartInstance {
matrix: r.matrix,
color: r.color.clone(),
part: r.name.clone().into(),
})),
},
None => Some(ObjectInstance::Part(PartInstance {
matrix: r.matrix,
color: r.color.clone(),
part: r.name.clone().into(),
})),
},
Command::Meta(Meta::Step) => Some(ObjectInstance::Step),
_ => None,
};
data.map(|v| Object {
id: Uuid::new_v4().into(),
data: v,
})
})
.collect::<Vec<_>>()
}
fn resolve_colors<P>(objects: &mut [Object<P>], colors: &ColorCatalog) {
for object in objects.iter_mut() {
match &mut object.data {
ObjectInstance::Part(ref mut p) => {
p.color.resolve_self(colors);
}
ObjectInstance::PartGroup(ref mut pg) => {
pg.color.resolve_self(colors);
}
_ => {}
}
}
}
fn extract_document_primitives<P: From<PartAlias>>(
document: &LdrawDocument,
) -> Option<(P, Part, Object<P>)> {
if document.has_primitives() {
let name = &document.name;
let prims = LdrawDocument {
name: name.clone(),
description: document.description.clone(),
author: document.author.clone(),
bfc: document.bfc.clone(),
headers: document.headers.clone(),
commands: document
.commands
.iter()
.filter_map(|e| match e {
Command::Line(_)
| Command::Triangle(_)
| Command::Quad(_)
| Command::OptionalLine(_) => Some(e.clone()),
_ => None,
})
.collect::<Vec<_>>(),
};
let prims = LdrawMultipartDocument {
body: prims,
subparts: HashMap::new(),
};
let part = bake_part_from_multipart_document(&prims, &ResolutionResult::default(), true);
let object = Object {
id: Uuid::new_v4().into(),
data: ObjectInstance::Part(PartInstance {
matrix: Matrix4::identity(),
color: ColorReference::Current,
part: PartAlias::from(name.clone()).into(),
}),
};
Some((PartAlias::from(name.clone()).into(), part, object))
} else {
None
}
}
impl<P: Eq + PartialEq + Hash + Clone + From<PartAlias>> Model<P> {
pub fn from_ldraw_multipart_document_sync(document: &LdrawMultipartDocument) -> Self {
let subparts = document
.subparts
.keys()
.map(|alias| (alias.clone().into(), Uuid::new_v4().into()))
.collect::<HashMap<_, _>>();
let mut embedded_parts: HashMap<P, Part> = HashMap::new();
let mut object_groups = HashMap::new();
for (alias, subpart) in document.subparts.iter() {
let converted_alias = alias.clone().into();
if !embedded_parts.contains_key(&converted_alias) {
let id = *subparts.get(&converted_alias).unwrap();
object_groups.insert(
id,
ObjectGroup {
id,
name: subpart.name.clone(),
objects: build_objects::<P>(subpart, Some(&subparts)),
pivot: Vector3::new(0.0, 0.0, 0.0),
},
);
}
}
let mut objects = build_objects::<P>(&document.body, Some(&subparts));
if let Some((alias, part, object)) = extract_document_primitives::<P>(&document.body) {
embedded_parts.insert(alias.clone(), part);
objects.push(object);
}
Model {
object_groups,
objects,
embedded_parts: HashMap::new(),
}
}
pub async fn from_ldraw_multipart_document<L: LibraryLoader>(
document: &LdrawMultipartDocument,
colors: &ColorCatalog,
inline_loader: Option<(&L, Arc<RwLock<PartCache>>)>,
) -> Self {
let subparts = document
.subparts
.keys()
.map(|alias| (alias.clone().into(), GroupId::from(Uuid::new_v4())))
.collect::<HashMap<_, _>>();
let mut embedded_parts: HashMap<P, Part> = HashMap::new();
if let Some((loader, cache)) = inline_loader {
for (alias, subpart) in document.subparts.iter() {
if subpart.has_primitives() {
let resolution_result = resolve_dependencies(
subpart,
Arc::clone(&cache),
colors,
loader,
&|_, _| {},
)
.await;
let part = bake_part_from_document(subpart, &resolution_result, true);
embedded_parts.insert(alias.clone().into(), part);
}
}
}
let mut object_groups = HashMap::new();
for (alias, subpart) in document.subparts.iter() {
let converted_alias = alias.clone().into();
if !embedded_parts.contains_key(&converted_alias) {
let id = *subparts.get(&converted_alias).unwrap();
object_groups.insert(
id,
ObjectGroup {
id,
name: subpart.name.clone(),
objects: build_objects::<P>(subpart, Some(&subparts)),
pivot: Vector3::new(0.0, 0.0, 0.0),
},
);
}
}
let mut objects = build_objects::<P>(&document.body, Some(&subparts));
if let Some((alias, part, object)) = extract_document_primitives::<P>(&document.body) {
embedded_parts.insert(alias.clone(), part);
objects.push(object);
}
Model {
object_groups,
objects,
embedded_parts,
}
}
pub fn from_ldraw_document(document: &LdrawDocument) -> Self {
let mut embedded_parts = HashMap::new();
let mut objects = build_objects(document, None);
if let Some((alias, part, object)) = extract_document_primitives::<P>(document) {
embedded_parts.insert(alias.clone(), part);
objects.push(object);
}
Model {
object_groups: HashMap::new(),
objects,
embedded_parts,
}
}
pub fn resolve_colors(&mut self, colors: &ColorCatalog) {
resolve_colors(&mut self.objects, colors);
for group in self.object_groups.values_mut() {
resolve_colors(&mut group.objects, colors);
}
}
fn build_dependencies(&self, deps: &mut HashSet<P>, objects: &[Object<P>]) {
for object in objects.iter() {
match &object.data {
ObjectInstance::Part(p) => {
if !deps.contains(&p.part) {
deps.insert(p.part.clone());
}
}
ObjectInstance::PartGroup(pg) => {
if let Some(pg) = self.object_groups.get(&pg.group_id) {
self.build_dependencies(deps, &pg.objects);
}
}
_ => {}
}
}
}
pub fn list_dependencies(&self) -> HashSet<P> {
let mut dependencies = HashSet::new();
self.build_dependencies(&mut dependencies, &self.objects);
dependencies
}
fn calculate_bounding_box_recursive(
&self,
bounding_box: &mut BoundingBox3,
matrix: Matrix4,
objects: &[Object<P>],
mut complete: bool,
querier: &impl PartDimensionQuerier<P>,
) -> bool {
for item in objects.iter() {
match &item.data {
ObjectInstance::Part(part) => {
if let Some(dim) = querier.query_part_dimension(&part.part) {
bounding_box.update(&dim.transform(&(matrix * part.matrix)));
} else {
complete = false;
}
}
ObjectInstance::PartGroup(pg) => {
if let Some(group) = self.object_groups.get(&pg.group_id) {
self.calculate_bounding_box_recursive(
bounding_box,
matrix * pg.matrix,
&group.objects,
complete,
querier,
);
}
}
_ => {}
}
}
complete
}
pub fn calculate_bounding_box(
&self,
group_id: Option<GroupId>,
querier: &impl PartDimensionQuerier<P>,
) -> Option<(BoundingBox3, bool)> {
let objects = if let Some(group_id) = group_id {
&self.object_groups.get(&group_id)?.objects
} else {
&self.objects
};
let matrix = Matrix4::identity();
let mut bounding_box = BoundingBox3::nil();
let complete = self.calculate_bounding_box_recursive(
&mut bounding_box,
matrix,
objects,
true,
querier,
);
Some((bounding_box, complete))
}
pub fn get_objects(
&self,
group_id: Option<GroupId>,
) -> Option<impl Iterator<Item = &Object<P>>> {
match group_id {
Some(group_id) => self
.object_groups
.get(&group_id)
.map(|groups| groups.objects.iter()),
None => Some(self.objects.iter()),
}
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ir/src/part.rs | ir/src/part.rs | use std::{
cell::RefCell, collections::HashMap, f32, fmt::Debug, ops::Deref, rc::Rc, sync::Arc, vec::Vec,
};
use cgmath::{AbsDiffEq, InnerSpace, Rad, SquareMatrix};
use kdtree::{distance::squared_euclidean, KdTree};
use ldraw::{
color::{ColorCatalog, ColorReference},
document::{Document, MultipartDocument},
elements::{BfcStatement, Command, Meta},
library::ResolutionResult,
Matrix4, Vector3, Winding,
};
use serde::{Deserialize, Serialize};
use crate::{geometry::BoundingBox3, MeshGroupKey};
const NORMAL_BLEND_THRESHOLD: Rad<f32> = Rad(f32::consts::FRAC_PI_6);
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct VertexBuffer(pub Vec<f32>);
impl VertexBuffer {
pub fn check_range(&self, range: &std::ops::Range<usize>) -> bool {
self.0.len() >= range.end
}
}
pub struct VertexBufferBuilder {
vertices: Vec<Vector3>,
index_table: KdTree<f32, u32, [f32; 3]>,
current_index: u32,
}
impl Default for VertexBufferBuilder {
fn default() -> Self {
Self {
vertices: Default::default(),
index_table: KdTree::new(3),
current_index: 0,
}
}
}
impl VertexBufferBuilder {
pub fn add(&mut self, vertex: Vector3) -> u32 {
let vertex_ref: &[f32; 3] = vertex.as_ref();
if let Ok(entries) = self.index_table.nearest(vertex_ref, 1, &squared_euclidean) {
if let Some((dist, index)) = entries.first() {
if dist < &f32::default_epsilon() {
return **index;
}
}
}
let index = self.current_index;
match self.index_table.add(*vertex_ref, index) {
Ok(_) => {
self.vertices.push(vertex);
self.current_index += 1;
index
}
Err(e) => {
panic!("Error adding vertex to vertex buffer: {vertex_ref:?} {e}");
}
}
}
pub fn add_all(&mut self, vertices: impl Iterator<Item = Vector3>) -> Vec<u32> {
let mut result = vec![];
for vertex in vertices {
result.push(self.add(vertex));
}
result
}
pub fn build(self) -> VertexBuffer {
let mut result = Vec::new();
for vertex in self.vertices.iter() {
let vertex: &[f32; 3] = vertex.as_ref();
result.extend(vertex);
}
VertexBuffer(result)
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct MeshBuffer {
pub vertex_indices: Vec<u32>,
pub normal_indices: Vec<u32>,
}
impl MeshBuffer {
pub fn len(&self) -> usize {
self.vertex_indices.len()
}
pub fn is_empty(&self) -> bool {
self.vertex_indices.is_empty()
}
pub fn is_valid(&self) -> bool {
self.vertex_indices.len() == self.normal_indices.len()
}
pub fn add(
&mut self,
vertex_buffer: &mut VertexBufferBuilder,
vertex: Vector3,
normal: Vector3,
) {
self.vertex_indices.push(vertex_buffer.add(vertex));
self.normal_indices.push(vertex_buffer.add(normal));
}
pub fn add_indices(&mut self, vertex_indices: Vec<u32>, normal_indices: Vec<u32>) {
self.vertex_indices.extend(vertex_indices);
self.normal_indices.extend(normal_indices);
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct EdgeBuffer {
pub vertex_indices: Vec<u32>,
pub colors: Vec<u32>,
}
impl EdgeBuffer {
pub fn add(
&mut self,
vertex_buffer: &mut VertexBufferBuilder,
vec: Vector3,
color: &ColorReference,
top: &ColorReference,
) {
self.vertex_indices.push(vertex_buffer.add(vec));
let code = if color.is_current() {
if let Some(c) = top.get_color() {
2 << 31 | c.code
} else {
2 << 30
}
} else if color.is_complement() {
if let Some(c) = top.get_color() {
c.code
} else {
2 << 29
}
} else if let Some(c) = color.get_color() {
2 << 31 | c.code
} else {
0
};
self.colors.push(code);
}
pub fn len(&self) -> usize {
self.vertex_indices.len()
}
pub fn is_empty(&self) -> bool {
self.vertex_indices.is_empty()
}
pub fn is_valid(&self) -> bool {
self.vertex_indices.len() == self.colors.len()
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct OptionalEdgeBuffer {
pub vertex_indices: Vec<u32>,
pub control_1_indices: Vec<u32>,
pub control_2_indices: Vec<u32>,
pub direction_indices: Vec<u32>,
pub colors: Vec<u32>,
}
impl OptionalEdgeBuffer {
#[allow(clippy::too_many_arguments)]
pub fn add(
&mut self,
vertex_buffer: &mut VertexBufferBuilder,
v1: Vector3,
v2: Vector3,
c1: Vector3,
c2: Vector3,
color: &ColorReference,
top: &ColorReference,
) {
let d = v2 - v1;
self.vertex_indices.push(vertex_buffer.add(v1));
self.vertex_indices.push(vertex_buffer.add(v2));
self.control_1_indices.push(vertex_buffer.add(c1));
self.control_1_indices.push(vertex_buffer.add(c1));
self.control_2_indices.push(vertex_buffer.add(c2));
self.control_2_indices.push(vertex_buffer.add(c2));
self.direction_indices.push(vertex_buffer.add(d));
self.direction_indices.push(vertex_buffer.add(d));
let code = if color.is_current() {
if let Some(c) = top.get_color() {
2 << 31 | c.code
} else {
2 << 30
}
} else if color.is_complement() {
if let Some(c) = top.get_color() {
c.code
} else {
2 << 29
}
} else if let Some(c) = color.get_color() {
2 << 31 | c.code
} else {
0
};
self.colors.push(code);
self.colors.push(code);
}
pub fn len(&self) -> usize {
self.vertex_indices.len()
}
pub fn is_empty(&self) -> bool {
self.vertex_indices.is_empty()
}
pub fn is_valid(&self) -> bool {
self.vertex_indices.len() == self.control_1_indices.len()
&& self.vertex_indices.len() == self.control_2_indices.len()
&& self.vertex_indices.len() == self.direction_indices.len()
&& self.vertex_indices.len() == self.colors.len()
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct PartBufferBundle {
pub vertex_buffer: VertexBuffer,
pub uncolored_mesh: MeshBuffer,
pub uncolored_without_bfc_mesh: MeshBuffer,
pub colored_meshes: HashMap<MeshGroupKey, MeshBuffer>,
pub edges: EdgeBuffer,
pub optional_edges: OptionalEdgeBuffer,
}
#[derive(Default)]
pub struct PartBufferBundleBuilder {
pub vertex_buffer_builder: VertexBufferBuilder,
uncolored_mesh: MeshBuffer,
uncolored_without_bfc_mesh: MeshBuffer,
colored_meshes: HashMap<MeshGroupKey, MeshBuffer>,
edges: EdgeBuffer,
optional_edges: OptionalEdgeBuffer,
}
impl PartBufferBundleBuilder {
fn query_mesh<'a>(&'a mut self, group: &MeshGroupKey) -> Option<&'a mut MeshBuffer> {
match (&group.color_ref, group.bfc) {
(ColorReference::Current | ColorReference::Complement, true) => {
Some(&mut self.uncolored_mesh)
}
(ColorReference::Current | ColorReference::Complement, false) => {
Some(&mut self.uncolored_without_bfc_mesh)
}
(ColorReference::Color(_), _) => {
Some(self.colored_meshes.entry(group.clone()).or_default())
}
_ => None,
}
}
pub fn build(self) -> PartBufferBundle {
PartBufferBundle {
vertex_buffer: self.vertex_buffer_builder.build(),
uncolored_mesh: self.uncolored_mesh,
uncolored_without_bfc_mesh: self.uncolored_without_bfc_mesh,
colored_meshes: self.colored_meshes,
edges: self.edges,
optional_edges: self.optional_edges,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PartMetadata {
pub name: String,
pub description: String,
pub author: String,
pub extras: HashMap<String, String>,
}
impl From<&Document> for PartMetadata {
fn from(document: &Document) -> PartMetadata {
PartMetadata {
name: document.name.clone(),
description: document.description.clone(),
author: document.author.clone(),
extras: HashMap::new(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Part {
pub metadata: PartMetadata,
pub geometry: PartBufferBundle,
pub bounding_box: BoundingBox3,
pub rotation_center: Vector3,
}
impl Part {
pub fn new(
metadata: PartMetadata,
geometry: PartBufferBundle,
bounding_box: BoundingBox3,
rotation_center: Vector3,
) -> Self {
Part {
metadata,
geometry,
bounding_box,
rotation_center,
}
}
// FIXME: deprecate this
pub fn resolve_colors(&mut self, colors: &ColorCatalog) {
let colored_meshes = std::mem::take(&mut self.geometry.colored_meshes);
self.geometry.colored_meshes = colored_meshes
.into_iter()
.map(|(k, v)| {
let color_ref = match k.color_ref {
ColorReference::Unresolved(v) => ColorReference::resolve(v, colors),
ColorReference::Unknown(v) => ColorReference::resolve(v, colors),
_ => k.color_ref.clone(),
};
(
MeshGroupKey {
color_ref,
bfc: k.bfc,
},
v,
)
})
.collect();
}
}
#[derive(Clone, Debug, PartialEq)]
struct FaceVertex {
position: Vector3,
normal: Vector3,
}
#[derive(Clone, Debug, PartialEq)]
enum FaceVertices {
Triangle([FaceVertex; 3]),
Quad([FaceVertex; 4]),
}
impl AbsDiffEq for FaceVertices {
type Epsilon = f32;
fn default_epsilon() -> Self::Epsilon {
f32::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
match (self, other) {
(FaceVertices::Triangle(lhs), FaceVertices::Triangle(rhs)) => {
lhs[0].position.abs_diff_eq(&rhs[0].position, epsilon)
&& lhs[1].position.abs_diff_eq(&rhs[1].position, epsilon)
&& lhs[2].position.abs_diff_eq(&rhs[2].position, epsilon)
}
(FaceVertices::Quad(lhs), FaceVertices::Quad(rhs)) => {
lhs[0].position.abs_diff_eq(&rhs[0].position, epsilon)
&& lhs[1].position.abs_diff_eq(&rhs[1].position, epsilon)
&& lhs[2].position.abs_diff_eq(&rhs[2].position, epsilon)
&& lhs[3].position.abs_diff_eq(&rhs[3].position, epsilon)
}
(_, _) => false,
}
}
}
const TRIANGLE_INDEX_ORDER: &[usize] = &[0, 1, 2];
const QUAD_INDEX_ORDER: &[usize] = &[0, 1, 2, 2, 3, 0];
struct FaceIterator<'a> {
face: &'a FaceVertices,
iterator: Box<dyn Iterator<Item = &'static usize>>,
}
impl<'a> Iterator for FaceIterator<'a> {
type Item = &'a FaceVertex;
fn next(&mut self) -> Option<Self::Item> {
match self.iterator.next() {
Some(e) => Some(match self.face {
FaceVertices::Triangle(v) => &v[*e],
FaceVertices::Quad(v) => &v[*e],
}),
None => None,
}
}
}
impl FaceVertices {
pub fn triangles(&self, reverse: bool) -> FaceIterator {
let order = match self {
FaceVertices::Triangle(_) => TRIANGLE_INDEX_ORDER,
FaceVertices::Quad(_) => QUAD_INDEX_ORDER,
};
let iterator: Box<dyn Iterator<Item = &'static usize>> = if reverse {
Box::new(order.iter().rev())
} else {
Box::new(order.iter())
};
FaceIterator {
face: self,
iterator,
}
}
pub fn query(&self, index: usize) -> &FaceVertex {
match self {
FaceVertices::Triangle(a) => &a[TRIANGLE_INDEX_ORDER[index]],
FaceVertices::Quad(a) => &a[QUAD_INDEX_ORDER[index]],
}
}
pub fn query_mut(&mut self, index: usize) -> &mut FaceVertex {
match self {
FaceVertices::Triangle(a) => a.get_mut(TRIANGLE_INDEX_ORDER[index]).unwrap(),
FaceVertices::Quad(a) => a.get_mut(QUAD_INDEX_ORDER[index]).unwrap(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
struct Face {
vertices: FaceVertices,
winding: Winding,
}
#[derive(Debug)]
struct Adjacency {
pub faces: Vec<(Rc<RefCell<Face>>, usize)>,
}
impl Adjacency {
pub fn new() -> Adjacency {
Adjacency { faces: Vec::new() }
}
pub fn add(&mut self, face: Rc<RefCell<Face>>, index: usize) {
self.faces.push((Rc::clone(&face), index));
}
}
fn calculate_normal(v1: &Vector3, v2: &Vector3, v3: &Vector3) -> Vector3 {
let normal = (v2 - v3).cross(v2 - v1).normalize();
if normal.x.is_nan() || normal.y.is_nan() || normal.z.is_nan() {
Vector3::new(0.0, 0.0, 0.0)
} else {
normal
}
}
#[derive(Debug)]
struct MeshBuilder {
pub faces: HashMap<MeshGroupKey, Vec<Rc<RefCell<Face>>>>,
adjacencies: Vec<Rc<RefCell<Adjacency>>>,
point_cloud: KdTree<f32, Rc<RefCell<Adjacency>>, [f32; 3]>,
}
impl MeshBuilder {
pub fn new() -> MeshBuilder {
MeshBuilder {
faces: HashMap::new(),
adjacencies: Vec::new(),
point_cloud: KdTree::new(3),
}
}
pub fn add(&mut self, group_key: &MeshGroupKey, face: Rc<RefCell<Face>>) {
let list = self.faces.entry(group_key.clone()).or_default();
list.push(face.clone());
for (index, vertex) in face.borrow().vertices.triangles(false).enumerate() {
let r: &[f32; 3] = vertex.position.as_ref();
let nearest = match self.point_cloud.iter_nearest_mut(r, &squared_euclidean) {
Ok(mut v) => match v.next() {
Some(vv) => {
if vv.0 < f32::default_epsilon() {
Some(vv.1)
} else {
None
}
}
None => None,
},
Err(_) => None,
};
match nearest {
Some(e) => {
e.borrow_mut().add(Rc::clone(&face), index);
}
None => {
let adjacency = Rc::new(RefCell::new(Adjacency::new()));
adjacency.borrow_mut().add(Rc::clone(&face), index);
self.adjacencies.push(Rc::clone(&adjacency));
self.point_cloud
.add(*vertex.position.as_ref(), adjacency)
.unwrap();
}
};
}
}
pub fn smooth_normals(&mut self) {
for adjacency in self.adjacencies.iter() {
let adjacency = adjacency.borrow_mut();
let length = adjacency.faces.len();
let mut flags = vec![false; length];
let mut marked = Vec::with_capacity(length);
loop {
let mut ops = 0;
for i in 0..length {
if !flags[i] {
marked.clear();
marked.push(i);
flags[i] = true;
let (face, index) = &adjacency.faces[i];
let base_normal = face.borrow().vertices.query(*index).normal;
let mut smoothed_normal = base_normal;
for (j, flag) in flags.iter_mut().enumerate() {
if i != j {
let (face, index) = &adjacency.faces[j];
let c_normal = face.borrow().vertices.query(*index).normal;
let angle = base_normal.angle(c_normal);
if angle.0 < f32::default_epsilon() {
*flag = true;
}
if angle < NORMAL_BLEND_THRESHOLD {
ops += 1;
*flag = true;
marked.push(j);
smoothed_normal += c_normal;
}
}
}
if !marked.is_empty() {
smoothed_normal /= marked.len() as f32;
}
for j in marked.iter() {
let (face, index) = &adjacency.faces[*j];
face.borrow_mut().vertices.query_mut(*index).normal = smoothed_normal;
}
}
}
if ops == 0 {
break;
}
}
}
}
pub fn bake(&self, builder: &mut PartBufferBundleBuilder, bounding_box: &mut BoundingBox3) {
let mut bounding_box_min = None;
let mut bounding_box_max = None;
for (group_key, faces) in self.faces.iter() {
let mut vertex_indices = vec![];
let mut normal_indices = vec![];
for face in faces.iter() {
for vertex in face.borrow().vertices.triangles(false) {
match bounding_box_min {
None => {
bounding_box_min = Some(vertex.position);
}
Some(ref mut e) => {
if e.x > vertex.position.x {
e.x = vertex.position.x;
}
if e.y > vertex.position.y {
e.y = vertex.position.y;
}
if e.z > vertex.position.z {
e.z = vertex.position.z;
}
}
}
match bounding_box_max {
None => {
bounding_box_max = Some(vertex.position);
}
Some(ref mut e) => {
if e.x < vertex.position.x {
e.x = vertex.position.x;
}
if e.y < vertex.position.y {
e.y = vertex.position.y;
}
if e.z < vertex.position.z {
e.z = vertex.position.z;
}
}
}
vertex_indices.push(builder.vertex_buffer_builder.add(vertex.position));
normal_indices.push(builder.vertex_buffer_builder.add(vertex.normal));
}
}
if let Some(mesh_buffer) = builder.query_mesh(group_key) {
mesh_buffer.add_indices(vertex_indices, normal_indices);
} else {
println!("Skipping unknown color group_key {:?}", group_key);
}
}
if let Some(bounding_box_min) = bounding_box_min {
if let Some(bounding_box_max) = bounding_box_max {
bounding_box.update_point(&bounding_box_min);
bounding_box.update_point(&bounding_box_max);
}
}
}
}
struct PartBaker<'a> {
resolutions: &'a ResolutionResult,
metadata: PartMetadata,
builder: PartBufferBundleBuilder,
mesh_builder: MeshBuilder,
color_stack: Vec<ColorReference>,
}
impl<'a> PartBaker<'a> {
pub fn traverse<M: Deref<Target = MultipartDocument>>(
&mut self,
document: &Document,
parent: M,
matrix: Matrix4,
cull: bool,
invert: bool,
local: bool,
) {
let mut local_cull = true;
let mut winding = Winding::Ccw;
let bfc_certified = document.bfc.is_certified().unwrap_or(true);
let mut invert_next = false;
if bfc_certified {
winding = match document.bfc.get_winding() {
Some(e) => e,
None => Winding::Ccw,
} ^ invert;
}
for cmd in document.commands.iter() {
match cmd {
Command::PartReference(cmd) => {
let matrix = matrix * cmd.matrix;
let invert_child = if cmd.matrix.determinant() < -f32::default_epsilon() {
invert == invert_next
} else {
invert != invert_next
};
let cull_next = if bfc_certified {
cull && local_cull
} else {
false
};
let color: ColorReference = match &cmd.color {
ColorReference::Current => self.color_stack.last().unwrap().clone(),
e => e.clone(),
};
if let Some(part) = parent.get_subpart(&cmd.name) {
self.color_stack.push(color);
self.traverse(part, &*parent, matrix, cull_next, invert_child, local);
self.color_stack.pop();
} else if let Some((document, local)) = self.resolutions.query(&cmd.name, local)
{
self.color_stack.push(color);
self.traverse(
&document.body,
Arc::clone(&document),
matrix,
cull_next,
invert_child,
local,
);
self.color_stack.pop();
}
invert_next = false;
}
Command::Line(cmd) => {
let top = self.color_stack.last().unwrap();
self.builder.edges.add(
&mut self.builder.vertex_buffer_builder,
(matrix * cmd.a).truncate(),
&cmd.color,
top,
);
self.builder.edges.add(
&mut self.builder.vertex_buffer_builder,
(matrix * cmd.b).truncate(),
&cmd.color,
top,
);
}
Command::OptionalLine(cmd) => {
let top = self.color_stack.last().unwrap();
self.builder.optional_edges.add(
&mut self.builder.vertex_buffer_builder,
(matrix * cmd.a).truncate(),
(matrix * cmd.b).truncate(),
(matrix * cmd.c).truncate(),
(matrix * cmd.d).truncate(),
&cmd.color,
top,
);
}
Command::Triangle(cmd) => {
let color = match &cmd.color {
ColorReference::Current => self.color_stack.last().unwrap(),
e => e,
};
let face = match winding {
Winding::Ccw => {
let v1 = (matrix * cmd.a).truncate();
let v2 = (matrix * cmd.b).truncate();
let v3 = (matrix * cmd.c).truncate();
let normal = calculate_normal(&v1, &v2, &v3);
Face {
vertices: FaceVertices::Triangle([
FaceVertex {
position: v1,
normal,
},
FaceVertex {
position: v2,
normal,
},
FaceVertex {
position: v3,
normal,
},
]),
winding: Winding::Ccw,
}
}
Winding::Cw => {
let v1 = (matrix * cmd.c).truncate();
let v2 = (matrix * cmd.b).truncate();
let v3 = (matrix * cmd.a).truncate();
let normal = calculate_normal(&v1, &v2, &v3);
Face {
vertices: FaceVertices::Triangle([
FaceVertex {
position: v1,
normal,
},
FaceVertex {
position: v2,
normal,
},
FaceVertex {
position: v3,
normal,
},
]),
winding: Winding::Cw,
}
}
};
let category = MeshGroupKey {
color_ref: color.clone(),
bfc: if bfc_certified {
cull && local_cull
} else {
false
},
};
self.mesh_builder
.add(&category, Rc::new(RefCell::new(face)));
}
Command::Quad(cmd) => {
let color = match &cmd.color {
ColorReference::Current => self.color_stack.last().unwrap(),
e => e,
};
let face = match winding {
Winding::Ccw => {
let v1 = (matrix * cmd.a).truncate();
let v2 = (matrix * cmd.b).truncate();
let v3 = (matrix * cmd.c).truncate();
let v4 = (matrix * cmd.d).truncate();
let normal = calculate_normal(&v1, &v2, &v3);
Face {
vertices: FaceVertices::Quad([
FaceVertex {
position: v1,
normal,
},
FaceVertex {
position: v2,
normal,
},
FaceVertex {
position: v3,
normal,
},
FaceVertex {
position: v4,
normal,
},
]),
winding: Winding::Ccw,
}
}
Winding::Cw => {
let v1 = (matrix * cmd.d).truncate();
let v2 = (matrix * cmd.c).truncate();
let v3 = (matrix * cmd.b).truncate();
let v4 = (matrix * cmd.a).truncate();
let normal = calculate_normal(&v1, &v2, &v3);
Face {
vertices: FaceVertices::Quad([
FaceVertex {
position: v1,
normal,
},
FaceVertex {
position: v2,
normal,
},
FaceVertex {
position: v3,
normal,
},
FaceVertex {
position: v4,
normal,
},
]),
winding: Winding::Cw,
}
}
};
let category = MeshGroupKey {
color_ref: color.clone(),
bfc: if bfc_certified {
cull && local_cull
} else {
false
},
};
self.mesh_builder
.add(&category, Rc::new(RefCell::new(face)));
}
Command::Meta(cmd) => {
if let Meta::Bfc(statement) = cmd {
match statement {
BfcStatement::InvertNext => {
invert_next = true;
}
BfcStatement::NoClip => {
local_cull = false;
}
BfcStatement::Clip(w) => {
local_cull = true;
if let Some(w) = w {
winding = w ^ invert;
}
}
BfcStatement::Winding(w) => {
winding = w ^ invert;
}
}
}
}
};
}
}
pub fn bake(mut self) -> Part {
let mut bounding_box = BoundingBox3::nil();
self.mesh_builder.smooth_normals();
self.mesh_builder.bake(&mut self.builder, &mut bounding_box);
Part::new(
self.metadata,
self.builder.build(),
bounding_box,
Vector3::new(0.0, 0.0, 0.0),
)
}
pub fn new(metadata: PartMetadata, resolutions: &'a ResolutionResult) -> Self {
let mut mb = PartBaker {
resolutions,
metadata,
builder: PartBufferBundleBuilder::default(),
mesh_builder: MeshBuilder::new(),
color_stack: Vec::new(),
};
mb.color_stack.push(ColorReference::Current);
mb
}
}
pub fn bake_part_from_multipart_document<D: Deref<Target = MultipartDocument>>(
document: D,
resolutions: &ResolutionResult,
local: bool,
) -> Part {
let mut baker = PartBaker::new(PartMetadata::from(&document.body), resolutions);
baker.traverse(
&document.body,
&*document,
Matrix4::identity(),
true,
false,
local,
);
baker.bake()
}
pub fn bake_part_from_document(
document: &Document,
resolutions: &ResolutionResult,
local: bool,
) -> Part {
let mut baker = PartBaker::new(document.into(), resolutions);
baker.traverse(
document,
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | true |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ir/src/constraints.rs | ir/src/constraints.rs | rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false | |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/olr/src/lib.rs | olr/src/lib.rs | pub mod context;
pub mod error;
pub mod ops;
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/olr/src/error.rs | olr/src/error.rs | use std::{
error::Error,
fmt::{Display, Formatter, Result as FmtResult},
};
#[derive(Debug)]
pub enum ContextCreationError {
NoAdapterFound,
RequestDeviceError(wgpu::RequestDeviceError),
}
impl Display for ContextCreationError {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
match self {
ContextCreationError::NoAdapterFound => {
write!(f, "No adapter found.")
}
ContextCreationError::RequestDeviceError(e) => {
write!(f, "Error requesting device: {}", e)
}
}
}
}
impl Error for ContextCreationError {
fn cause(&self) -> Option<&(dyn Error)> {
match *self {
ContextCreationError::NoAdapterFound => None,
ContextCreationError::RequestDeviceError(ref e) => Some(e),
}
}
}
impl From<wgpu::RequestDeviceError> for ContextCreationError {
fn from(e: wgpu::RequestDeviceError) -> Self {
Self::RequestDeviceError(e)
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/olr/src/context.rs | olr/src/context.rs | use image::RgbaImage;
use ldraw::Vector2;
use ldraw_ir::geometry::BoundingBox2;
use ldraw_renderer::{pipeline::RenderingPipelineManager, projection::Projection, Entity};
use crate::error::ContextCreationError;
pub struct Context {
pub width: u32,
pub height: u32,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub(super) pipelines: RenderingPipelineManager,
pub(super) projection: Entity<Projection>,
pub(super) framebuffer_texture: wgpu::Texture,
pub(super) framebuffer_texture_view: wgpu::TextureView,
pub(super) _multisampled_framebuffer_texture: Option<wgpu::Texture>,
pub(super) multisampled_framebuffer_texture_view: Option<wgpu::TextureView>,
pub(super) _depth_texture: wgpu::Texture,
pub(super) depth_texture_view: wgpu::TextureView,
output_buffer: wgpu::Buffer,
}
impl Context {
pub async fn new(
width: u32,
height: u32,
sample_count: u32,
) -> Result<Self, ContextCreationError> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
backend_options: Default::default(),
flags: wgpu::InstanceFlags::default(),
memory_budget_thresholds: Default::default(),
});
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptionsBase {
power_preference: wgpu::PowerPreference::default(),
force_fallback_adapter: false,
compatible_surface: None,
})
.await
.map_err(|_| ContextCreationError::NoAdapterFound)?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("Device Descriptor"),
required_features: wgpu::Features::POLYGON_MODE_LINE,
required_limits: wgpu::Limits::default(),
memory_hints: Default::default(),
trace: wgpu::Trace::Off,
})
.await?;
let framebuffer_format = wgpu::TextureFormat::Rgba8UnormSrgb;
let framebuffer_texture = device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: framebuffer_format,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::RENDER_ATTACHMENT,
label: Some("Render framebuffer"),
view_formats: &[],
});
let framebuffer_texture_view = framebuffer_texture.create_view(&Default::default());
let (multisampled_framebuffer_texture, multisampled_framebuffer_texture_view) =
if sample_count > 1 {
let texture = device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count,
dimension: wgpu::TextureDimension::D2,
format: framebuffer_format,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::RENDER_ATTACHMENT,
label: Some("Render framebuffer (w/o multisample)"),
view_formats: &[],
});
let view = texture.create_view(&Default::default());
(Some(texture), Some(view))
} else {
(None, None)
};
let pipelines =
RenderingPipelineManager::new(&device, &queue, framebuffer_format, sample_count);
let projection = Projection::new().into();
let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
label: Some("Depth buffer"),
view_formats: &[],
});
let depth_texture_view = depth_texture.create_view(&Default::default());
let output_buffer_size =
(std::mem::size_of::<u32>() as u32 * width * height) as wgpu::BufferAddress;
let output_buffer = device.create_buffer(&wgpu::BufferDescriptor {
size: output_buffer_size,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
label: Some("Output buffer"),
mapped_at_creation: false,
});
Ok(Self {
width,
height,
device,
queue,
pipelines,
projection,
framebuffer_texture,
framebuffer_texture_view,
_multisampled_framebuffer_texture: multisampled_framebuffer_texture,
multisampled_framebuffer_texture_view,
_depth_texture: depth_texture,
depth_texture_view,
output_buffer,
})
}
pub async fn finish(
&self,
mut encoder: wgpu::CommandEncoder,
bounds: Option<BoundingBox2>,
) -> RgbaImage {
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
aspect: wgpu::TextureAspect::All,
texture: &self.framebuffer_texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
},
wgpu::TexelCopyBufferInfo {
buffer: &self.output_buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(std::mem::size_of::<u32>() as u32 * self.width),
rows_per_image: Some(self.height),
},
},
wgpu::Extent3d {
width: self.width,
height: self.height,
depth_or_array_layers: 1,
},
);
self.queue.submit(Some(encoder.finish()));
let pixels = {
let buffer_slice = self.output_buffer.slice(..);
let (tx, rx) = futures_intrusive::channel::shared::oneshot_channel();
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
tx.send(result).unwrap();
});
self.device
.poll(wgpu::PollType::Wait)
.expect("Polling from GPU failed");
rx.receive().await.unwrap().unwrap();
buffer_slice.get_mapped_range()
};
let bounds = bounds
.unwrap_or_else(|| BoundingBox2::new(&Vector2::new(0.0, 0.0), &Vector2::new(1.0, 1.0)));
let x1 = (bounds.min.x * self.width as f32) as usize;
let y1 = (bounds.min.y * self.height as f32) as usize;
let x2 = (bounds.max.x * self.width as f32) as usize;
let y2 = (bounds.max.y * self.height as f32) as usize;
let cw = x2 - x1;
let ch = y2 - y1;
let mut pixels_rearranged: Vec<u8> = Vec::new();
for v in y1..y2 {
let s = 4 * v * self.width as usize + x1 * 4;
pixels_rearranged.extend_from_slice(&pixels[s..(s + (cw * 4))]);
}
drop(pixels);
self.output_buffer.unmap();
RgbaImage::from_raw(cw as _, ch as _, pixels_rearranged).unwrap()
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/olr/src/ops.rs | olr/src/ops.rs | use cgmath::SquareMatrix;
use image::RgbaImage;
use ldraw::{
color::{Color, ColorCatalog},
Matrix4, PartAlias, Point3,
};
use ldraw_ir::{
geometry::BoundingBox2,
model::{GroupId, Model},
};
use ldraw_renderer::{
display_list::DisplayList,
part::{Part, PartQuerier},
projection::{OrthographicCamera, ProjectionModifier, ViewBounds},
util::calculate_model_bounding_box,
};
use crate::context::Context;
pub struct Ops<'a> {
context: &'a mut Context,
encoder: wgpu::CommandEncoder,
}
impl<'a> Ops<'a> {
pub fn new(context: &'a mut Context) -> Self {
let encoder = context
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Command Encoder for Offscreen"),
});
Self { context, encoder }
}
pub async fn render_single_part(mut self, part: &Part, color: &Color) -> RgbaImage {
let camera = OrthographicCamera::new_isometric(
Point3::new(0.0, 0.0, 0.0),
ViewBounds::BoundingBox3(part.bounding_box.clone()),
);
self.context.projection.mutate_all(
camera
.update_projections((self.context.width, self.context.height).into())
.into_iter(),
);
self.context
.projection
.update(&self.context.device, &self.context.queue);
let (view, resolve_target) =
if let Some(t) = self.context.multisampled_framebuffer_texture_view.as_ref() {
(t, Some(&self.context.framebuffer_texture_view))
} else {
(&self.context.framebuffer_texture_view, None)
};
let mut render_pass = self
.encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Offscreen Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
resolve_target,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 1.0,
g: 1.0,
b: 1.0,
a: 0.0,
}),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.context.depth_texture_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
occlusion_query_set: None,
timestamp_writes: None,
})
.forget_lifetime();
self.context.pipelines.render_single_part(
&self.context.device,
&self.context.queue,
&mut render_pass,
&self.context.projection,
part,
Matrix4::identity(),
color,
);
drop(render_pass);
let bounds = camera
.view_bounds
.fraction(&self.context.projection.get_model_view_matrix());
self.finish(bounds).await
}
pub async fn render_model(
mut self,
model: &Model<PartAlias>,
group_id: Option<GroupId>,
parts: &impl PartQuerier<PartAlias>,
colors: &ColorCatalog,
) -> RgbaImage {
let bounding_box = calculate_model_bounding_box(model, group_id, parts);
let center = bounding_box.center();
let camera = OrthographicCamera::new_isometric(
Point3::new(center.x, center.y, center.z),
ViewBounds::BoundingBox3(bounding_box),
);
self.context.projection.mutate_all(
camera
.update_projections((self.context.width, self.context.height).into())
.into_iter(),
);
self.context
.projection
.update(&self.context.device, &self.context.queue);
let mut display_list = DisplayList::from_model(model, group_id, colors);
display_list.update(&self.context.device, &self.context.queue);
let (view, resolve_target) =
if let Some(t) = self.context.multisampled_framebuffer_texture_view.as_ref() {
(t, Some(&self.context.framebuffer_texture_view))
} else {
(&self.context.framebuffer_texture_view, None)
};
let mut render_pass = self
.encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Offscreen Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
resolve_target,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 1.0,
g: 1.0,
b: 1.0,
a: 0.0,
}),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.context.depth_texture_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
occlusion_query_set: None,
timestamp_writes: None,
})
.forget_lifetime();
self.context.pipelines.render(
&mut render_pass,
&self.context.projection,
parts,
&display_list,
);
drop(render_pass);
let bounds = camera
.view_bounds
.fraction(&self.context.projection.get_model_view_matrix());
self.finish(bounds).await
}
async fn finish(self, bounds: Option<BoundingBox2>) -> RgbaImage {
self.context.finish(self.encoder, bounds).await
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/lib.rs | ldraw/src/lib.rs | use std::cmp;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::{Hash, Hasher};
use std::ops::BitXor;
use cgmath::{
Matrix3 as Matrix3_, Matrix4 as Matrix4_, Point2 as Point2_, Point3 as Point3_,
Vector2 as Vector2_, Vector3 as Vector3_, Vector4 as Vector4_,
};
use serde::de::{Error as DeserializeError, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub mod color;
pub mod document;
pub mod elements;
pub mod error;
pub mod library;
pub mod parser;
pub mod resolvers;
pub mod writer;
pub type Matrix3 = Matrix3_<f32>;
pub type Matrix4 = Matrix4_<f32>;
pub type Vector2 = Vector2_<f32>;
pub type Vector3 = Vector3_<f32>;
pub type Vector4 = Vector4_<f32>;
pub type Point2 = Point2_<f32>;
pub type Point3 = Point3_<f32>;
#[derive(Clone, Debug)]
pub struct PartAlias {
pub normalized: String,
pub original: String,
}
impl PartAlias {
pub fn set(&mut self, alias: String) {
self.normalized = Self::normalize(&alias);
self.original = alias;
}
pub fn normalize(alias: &str) -> String {
alias.trim().to_lowercase().replace('\\', "/")
}
}
impl From<String> for PartAlias {
fn from(alias: String) -> PartAlias {
PartAlias {
normalized: Self::normalize(&alias),
original: alias,
}
}
}
impl From<&String> for PartAlias {
fn from(alias: &String) -> PartAlias {
PartAlias {
normalized: Self::normalize(alias),
original: alias.clone(),
}
}
}
impl From<&str> for PartAlias {
fn from(alias: &str) -> PartAlias {
let string = alias.to_string();
PartAlias {
normalized: Self::normalize(&string),
original: string,
}
}
}
impl Display for PartAlias {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
Display::fmt(&self.original, f)
}
}
struct StringVisitor;
impl<'a> Visitor<'a> for StringVisitor {
type Value = String;
fn expecting(&self, formatter: &mut Formatter) -> FmtResult {
write!(formatter, "a string")
}
fn visit_str<E: DeserializeError>(self, v: &str) -> Result<Self::Value, E> {
Ok(String::from(v))
}
}
impl Serialize for PartAlias {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.original.as_str())
}
}
impl<'a> Deserialize<'a> for PartAlias {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Ok(PartAlias::from(
&deserializer.deserialize_str(StringVisitor)?,
))
}
}
impl cmp::Eq for PartAlias {}
impl cmp::PartialEq for PartAlias {
fn eq(&self, other: &PartAlias) -> bool {
self.normalized.eq(&other.normalized)
}
}
impl Hash for PartAlias {
fn hash<H: Hasher>(&self, state: &mut H) {
self.normalized.hash(state)
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Winding {
Ccw,
Cw,
}
impl Winding {
pub fn invert(self) -> Self {
match self {
Winding::Ccw => Winding::Cw,
Winding::Cw => Winding::Ccw,
}
}
}
impl BitXor<bool> for Winding {
type Output = Self;
fn bitxor(self, rhs: bool) -> Self::Output {
match (self, rhs) {
(Winding::Ccw, false) => Winding::Ccw,
(Winding::Ccw, true) => Winding::Cw,
(Winding::Cw, false) => Winding::Cw,
(Winding::Cw, true) => Winding::Ccw,
}
}
}
impl BitXor<bool> for &Winding {
type Output = Winding;
fn bitxor(self, rhs: bool) -> Self::Output {
match (self, rhs) {
(Winding::Ccw, false) => Winding::Ccw,
(Winding::Ccw, true) => Winding::Cw,
(Winding::Cw, false) => Winding::Cw,
(Winding::Cw, true) => Winding::Ccw,
}
}
}
#[cfg(test)]
mod tests {
use crate::PartAlias;
#[test]
fn test_part_alias_directory_sep_normalization() {
let alias = PartAlias::from("test\\directory\\disc.dat".to_string());
assert_eq!(alias.normalized, "test/directory/disc.dat");
assert_eq!(alias.original, "test\\directory\\disc.dat");
}
#[test]
fn test_part_alias_case_normalization() {
let alias = PartAlias::from("Disc.dat".to_string());
assert_eq!(alias.normalized, "disc.dat");
assert_eq!(alias.original, "Disc.dat");
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/parser.rs | ldraw/src/parser.rs | use std::{collections::HashMap, marker::Unpin, str::Chars};
use cgmath::Matrix;
use futures::{stream::Enumerate, StreamExt};
use tokio::io::{AsyncBufRead, AsyncBufReadExt};
use tokio_stream::wrappers::LinesStream;
use crate::{
color::{
Color, ColorCatalog, ColorReference, CustomizedMaterial, Material, MaterialGlitter,
MaterialSpeckle, Rgba,
},
document::{BfcCertification, Document, MultipartDocument},
elements::{
BfcStatement, Command, Header, Line, Meta, OptionalLine, PartReference, Quad, Triangle,
},
error::{ColorDefinitionParseError, DocumentParseError, ParseError},
{Matrix4, PartAlias, Vector4, Winding},
};
#[derive(Debug, PartialEq)]
enum Line0 {
Header(Header),
Meta(Meta),
File(String),
Name(String),
Author(String),
BfcCertification(BfcCertification),
}
fn is_whitespace(ch: char) -> bool {
matches!(ch, ' ' | '\t' | '\r' | '\n')
}
fn next_token(iterator: &mut Chars, glob_remaining: bool) -> Result<String, ParseError> {
let mut buffer = String::new();
for v in iterator {
if !is_whitespace(v) {
buffer.push(v);
} else if !buffer.is_empty() {
if !glob_remaining {
break;
} else {
buffer.push(v);
}
}
}
match buffer.len() {
0 => Err(ParseError::EndOfLine),
_ => Ok(buffer.trim_end().to_string()),
}
}
fn next_token_u32(iterator: &mut Chars) -> Result<u32, ParseError> {
let token = next_token(iterator, false)?;
if token.starts_with("0x") {
let trimmed = token.chars().skip(2).collect::<String>();
return match u32::from_str_radix(trimmed.as_str(), 16) {
Ok(v) => Ok(v),
Err(_) => Err(ParseError::TypeMismatch("u32", token)),
};
}
match token.parse::<u32>() {
Ok(v) => Ok(v),
Err(_) => Err(ParseError::TypeMismatch("u32", token)),
}
}
fn next_token_f32(iterator: &mut Chars) -> Result<f32, ParseError> {
let token = next_token(iterator, false)?;
match token.parse::<f32>() {
Ok(v) => Ok(v),
Err(_) => Err(ParseError::TypeMismatch("f32", token)),
}
}
fn next_token_rgb(iterator: &mut Chars) -> Result<(u8, u8, u8), ParseError> {
match iterator.next() {
Some(v) => {
if v != '#' {
return Err(ParseError::InvalidToken(v.to_string()));
}
}
None => {
return Err(ParseError::EndOfLine);
}
}
let rs = iterator.take(2).collect::<String>();
let gs = iterator.take(2).collect::<String>();
let bs = iterator.take(2).collect::<String>();
let r = match u8::from_str_radix(rs.as_str(), 16) {
Ok(v) => v,
Err(_) => return Err(ParseError::TypeMismatch("u8", rs)),
};
let g = match u8::from_str_radix(gs.as_str(), 16) {
Ok(v) => v,
Err(_) => return Err(ParseError::TypeMismatch("u8", gs)),
};
let b = match u8::from_str_radix(bs.as_str(), 16) {
Ok(v) => v,
Err(_) => return Err(ParseError::TypeMismatch("u8", bs)),
};
Ok((r, g, b))
}
fn parse_bfc_statement(iterator: &mut Chars) -> Result<Line0, ParseError> {
let stmt = next_token(iterator, true)?;
match stmt.as_str() {
"NOCERTIFY" => Ok(Line0::BfcCertification(BfcCertification::NoCertify)),
"CERTIFY" | "CERTIFY CCW" => Ok(Line0::BfcCertification(BfcCertification::Certify(
Winding::Ccw,
))),
"CERTIFY CW" => Ok(Line0::BfcCertification(BfcCertification::Certify(
Winding::Cw,
))),
"CW" => Ok(Line0::Meta(Meta::Bfc(BfcStatement::Winding(Winding::Cw)))),
"CCW" => Ok(Line0::Meta(Meta::Bfc(BfcStatement::Winding(Winding::Ccw)))),
"CLIP" => Ok(Line0::Meta(Meta::Bfc(BfcStatement::Clip(None)))),
"CLIP CW" | "CW CLIP" => Ok(Line0::Meta(Meta::Bfc(BfcStatement::Clip(Some(
Winding::Cw,
))))),
"CLIP CCW" | "CCW CLIP" => Ok(Line0::Meta(Meta::Bfc(BfcStatement::Clip(Some(
Winding::Ccw,
))))),
"NOCLIP" => Ok(Line0::Meta(Meta::Bfc(BfcStatement::NoClip))),
"INVERTNEXT" => Ok(Line0::Meta(Meta::Bfc(BfcStatement::InvertNext))),
_ => Err(ParseError::InvalidBfcStatement(stmt)),
}
}
fn parse_line_0(iterator: &mut Chars) -> Result<Line0, ParseError> {
let text = match next_token(iterator, true) {
Ok(v) => v,
Err(ParseError::EndOfLine) => return Ok(Line0::Meta(Meta::Comment(String::new()))),
Err(e) => return Err(e),
};
let mut inner_iterator = text.chars();
let cmd = next_token(&mut inner_iterator, false)?;
if cmd.starts_with('!') {
let key: String = cmd.chars().skip(1).collect();
let value = next_token(&mut inner_iterator, true).unwrap_or_default();
return Ok(Line0::Header(Header(key, value)));
}
match cmd.as_str() {
"BFC" => parse_bfc_statement(&mut inner_iterator),
"Name:" => match next_token(&mut inner_iterator, true) {
Ok(msg) => Ok(Line0::Name(msg)),
Err(_) => Ok(Line0::Name(String::from(""))),
},
"Author:" => match next_token(&mut inner_iterator, true) {
Ok(msg) => Ok(Line0::Author(msg)),
Err(_) => Ok(Line0::Author(String::from(""))),
},
"FILE" => match next_token(&mut inner_iterator, true) {
Ok(msg) => Ok(Line0::File(msg)),
Err(e) => Err(e),
},
"STEP" => Ok(Line0::Meta(Meta::Step)),
"WRITE" => match next_token(&mut inner_iterator, true) {
Ok(msg) => Ok(Line0::Meta(Meta::Write(msg))),
Err(e) => Err(e),
},
"PRINT" => match next_token(&mut inner_iterator, true) {
Ok(msg) => Ok(Line0::Meta(Meta::Print(msg))),
Err(e) => Err(e),
},
"CLEAR" => Ok(Line0::Meta(Meta::Clear)),
"PAUSE" => Ok(Line0::Meta(Meta::Pause)),
"SAVE" => Ok(Line0::Meta(Meta::Save)),
_ => {
let comment = match text.strip_prefix("//") {
Some(e) => e.trim(),
None => &text,
};
Ok(Line0::Meta(Meta::Comment(comment.to_string())))
}
}
}
fn parse_line_1(colors: &ColorCatalog, iterator: &mut Chars) -> Result<PartReference, ParseError> {
let color = next_token_u32(iterator)?;
let x = next_token_f32(iterator)?;
let y = next_token_f32(iterator)?;
let z = next_token_f32(iterator)?;
let matrix = Matrix4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
x,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
y,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
z,
0.0,
0.0,
0.0,
1.0,
)
.transpose();
let name = next_token(iterator, true)?;
Ok(PartReference {
color: ColorReference::resolve(color, colors),
matrix,
name: PartAlias::from(name),
})
}
fn parse_line_2(colors: &ColorCatalog, iterator: &mut Chars) -> Result<Line, ParseError> {
let color = next_token_u32(iterator)?;
let a = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let b = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
Ok(Line {
color: ColorReference::resolve(color, colors),
a,
b,
})
}
fn parse_line_3(colors: &ColorCatalog, iterator: &mut Chars) -> Result<Triangle, ParseError> {
let color = next_token_u32(iterator)?;
let a = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let b = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let c = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
Ok(Triangle {
color: ColorReference::resolve(color, colors),
a,
b,
c,
})
}
fn parse_line_4(colors: &ColorCatalog, iterator: &mut Chars) -> Result<Quad, ParseError> {
let color = next_token_u32(iterator)?;
let a = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let b = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let c = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let d = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
Ok(Quad {
color: ColorReference::resolve(color, colors),
a,
b,
c,
d,
})
}
fn parse_line_5(colors: &ColorCatalog, iterator: &mut Chars) -> Result<OptionalLine, ParseError> {
let color = next_token_u32(iterator)?;
let a = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let b = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let c = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
let d = Vector4::new(
next_token_f32(iterator)?,
next_token_f32(iterator)?,
next_token_f32(iterator)?,
1.0,
);
Ok(OptionalLine {
color: ColorReference::resolve(color, colors),
a,
b,
c,
d,
})
}
async fn parse_inner<T: AsyncBufRead + Unpin>(
colors: &ColorCatalog,
iterator: &mut Enumerate<LinesStream<T>>,
multipart: bool,
) -> Result<(Document, Option<String>), DocumentParseError> {
let mut next: Option<String> = None;
let mut name = String::new();
let mut author = String::new();
let mut description = String::new();
let mut bfc = BfcCertification::NotApplicable;
let mut commands = Vec::new();
let mut headers = Vec::new();
'read_loop: while let Some((index, line_)) = iterator.next().await {
let line = match line_ {
Ok(v) => v,
Err(e) => {
return Err(DocumentParseError {
line: index + 1,
error: ParseError::from(e),
});
}
};
let mut it = line.chars();
match next_token(&mut it, false) {
Ok(token) => match token.as_str() {
"0" => match parse_line_0(&mut it) {
Ok(val) => match val {
Line0::BfcCertification(bfc_) => {
bfc = bfc_;
}
Line0::File(file_) => {
if multipart {
if !description.is_empty() {
next = Some(file_);
break 'read_loop;
}
} else {
return Err(DocumentParseError {
line: index + 1,
error: ParseError::MultipartDocument,
});
}
}
Line0::Name(name_) => {
name = name_;
}
Line0::Author(author_) => {
author = author_;
}
Line0::Meta(meta) => {
if let Meta::Comment(comment) = meta {
if description.is_empty() {
description = comment;
} else {
commands.push(Command::Meta(Meta::Comment(comment)));
}
} else {
commands.push(Command::Meta(meta));
}
}
Line0::Header(header) => {
headers.push(header);
}
},
Err(e) => {
return Err(DocumentParseError {
line: index + 1,
error: e,
});
}
},
"1" => match parse_line_1(colors, &mut it) {
Ok(val) => commands.push(Command::PartReference(val)),
Err(e) => {
return Err(DocumentParseError {
line: index + 1,
error: e,
});
}
},
"2" => match parse_line_2(colors, &mut it) {
Ok(val) => commands.push(Command::Line(val)),
Err(e) => {
return Err(DocumentParseError {
line: index + 1,
error: e,
});
}
},
"3" => match parse_line_3(colors, &mut it) {
Ok(val) => commands.push(Command::Triangle(val)),
Err(e) => {
return Err(DocumentParseError {
line: index + 1,
error: e,
});
}
},
"4" => match parse_line_4(colors, &mut it) {
Ok(val) => commands.push(Command::Quad(val)),
Err(e) => {
return Err(DocumentParseError {
line: index + 1,
error: e,
});
}
},
"5" => match parse_line_5(colors, &mut it) {
Ok(val) => commands.push(Command::OptionalLine(val)),
Err(e) => {
return Err(DocumentParseError {
line: index + 1,
error: e,
});
}
},
_ => {
return Err(DocumentParseError {
line: index + 1,
error: ParseError::UnexpectedCommand(token),
});
}
},
Err(ParseError::EndOfLine) => {}
Err(e) => {
return Err(DocumentParseError {
line: index + 1,
error: e,
});
}
}
}
Ok((
Document {
name,
description,
author,
bfc,
headers,
commands,
},
next,
))
}
pub async fn parse_single_document<T: AsyncBufRead + Unpin>(
reader: &mut T,
colors: &ColorCatalog,
) -> Result<Document, DocumentParseError> {
let mut it = LinesStream::new(reader.lines()).enumerate();
let (document, _) = parse_inner(colors, &mut it, false).await?;
Ok(document)
}
pub async fn parse_multipart_document<T: AsyncBufRead + Unpin>(
reader: &mut T,
colors: &ColorCatalog,
) -> Result<MultipartDocument, DocumentParseError> {
let mut it = LinesStream::new(reader.lines()).enumerate();
let (document, mut next) = parse_inner(colors, &mut it, true).await?;
let mut subparts = HashMap::new();
while next.is_some() {
let (part, next_) = parse_inner(colors, &mut it, true).await?;
subparts.insert(PartAlias::from(&next.unwrap()), part);
next = next_;
}
Ok(MultipartDocument {
body: document,
subparts,
})
}
fn parse_customized_material(
iterator: &mut Chars,
) -> Result<CustomizedMaterial, ColorDefinitionParseError> {
match next_token(iterator, false)?.as_str() {
"GLITTER" => {
let mut alpha = 255u8;
let mut luminance = 0u8;
let mut fraction = 0.0;
let mut vfraction = 0.0;
let mut size = 0u32;
let mut minsize = 0.0;
let mut maxsize = 0.0;
match next_token(iterator, false)?.as_str() {
"VALUE" => (),
e => {
return Err(ColorDefinitionParseError::ParseError(
ParseError::InvalidToken(e.to_string()),
));
}
};
let (vr, vg, vb) = next_token_rgb(iterator)?;
loop {
let token = match next_token(iterator, false) {
Ok(v) => v,
Err(ParseError::EndOfLine) => break,
Err(e) => return Err(ColorDefinitionParseError::ParseError(e)),
};
match token.as_str() {
"ALPHA" => {
alpha = next_token_u32(iterator)? as u8;
}
"LUMINANCE" => {
luminance = next_token_u32(iterator)? as u8;
}
"FRACTION" => {
fraction = next_token_f32(iterator)?;
}
"VFRACTION" => {
vfraction = next_token_f32(iterator)?;
}
"SIZE" => {
size = next_token_u32(iterator)?;
}
"MINSIZE" => {
minsize = next_token_f32(iterator)?;
}
"MAXSIZE" => {
maxsize = next_token_f32(iterator)?;
}
_ => {
return Err(ColorDefinitionParseError::ParseError(
ParseError::InvalidToken(token.clone()),
));
}
}
}
Ok(CustomizedMaterial::Glitter(MaterialGlitter {
value: Rgba::new(vr, vg, vb, alpha),
luminance,
fraction,
vfraction,
size,
minsize,
maxsize,
}))
}
"SPECKLE" => {
let mut alpha = 255u8;
let mut luminance = 0u8;
let mut fraction = 0.0;
let mut size = 0u32;
let mut minsize = 0.0;
let mut maxsize = 0.0;
match next_token(iterator, false)?.as_str() {
"VALUE" => (),
e => {
return Err(ColorDefinitionParseError::ParseError(
ParseError::InvalidToken(e.to_string()),
));
}
};
let (vr, vg, vb) = next_token_rgb(iterator)?;
loop {
let token = match next_token(iterator, false) {
Ok(v) => v,
Err(ParseError::EndOfLine) => break,
Err(e) => return Err(ColorDefinitionParseError::ParseError(e)),
};
match token.as_str() {
"ALPHA" => {
alpha = next_token_u32(iterator)? as u8;
}
"LUMINANCE" => {
luminance = next_token_u32(iterator)? as u8;
}
"FRACTION" => {
fraction = next_token_f32(iterator)?;
}
"SIZE" => {
size = next_token_u32(iterator)?;
}
"MINSIZE" => {
minsize = next_token_f32(iterator)?;
}
"MAXSIZE" => {
maxsize = next_token_f32(iterator)?;
}
_ => {
return Err(ColorDefinitionParseError::ParseError(
ParseError::InvalidToken(token.clone()),
));
}
}
}
Ok(CustomizedMaterial::Speckle(MaterialSpeckle {
value: Rgba::new(vr, vg, vb, alpha),
luminance,
fraction,
size,
minsize,
maxsize,
}))
}
e => Err(ColorDefinitionParseError::UnknownMaterial(e.to_string())),
}
}
pub async fn parse_color_definitions<T: AsyncBufRead + Unpin>(
reader: &mut T,
) -> Result<ColorCatalog, ColorDefinitionParseError> {
// Use an empty context here
let colors = ColorCatalog::new();
let document = parse_single_document(reader, &colors).await?;
let mut colors = ColorCatalog::new();
for Header(_, value) in document.headers.iter().filter(|s| s.0 == "COLOUR") {
let mut material = Material::Plastic;
let mut alpha = 255u8;
let mut luminance = 0u8;
let mut it = value.chars();
let name = next_token(&mut it, false)?;
match next_token(&mut it, false)?.as_str() {
"CODE" => (),
e => {
return Err(ColorDefinitionParseError::ParseError(
ParseError::InvalidToken(e.to_string()),
));
}
};
let code = next_token_u32(&mut it)?;
match next_token(&mut it, false)?.as_str() {
"VALUE" => (),
e => {
return Err(ColorDefinitionParseError::ParseError(
ParseError::InvalidToken(e.to_string()),
));
}
};
let (cr, cg, cb) = next_token_rgb(&mut it)?;
match next_token(&mut it, false)?.as_str() {
"EDGE" => (),
e => {
return Err(ColorDefinitionParseError::ParseError(
ParseError::InvalidToken(e.to_string()),
));
}
};
let (er, eg, eb) = next_token_rgb(&mut it)?;
loop {
let token = match next_token(&mut it, false) {
Ok(v) => v,
Err(ParseError::EndOfLine) => break,
Err(e) => return Err(ColorDefinitionParseError::ParseError(e)),
};
match token.as_str() {
"ALPHA" => {
alpha = next_token_u32(&mut it)? as u8;
}
"LUMINANCE" => {
luminance = next_token_u32(&mut it)? as u8;
}
"CHROME" => {
material = Material::Chrome;
}
"PEARLESCENT" => {
material = Material::Pearlescent;
}
"METAL" => {
material = Material::Metal;
}
"RUBBER" => {
material = Material::Rubber;
}
"MATTE_METALLIC" => {
material = Material::MatteMetallic;
}
"MATERIAL" => {
material = Material::Custom(parse_customized_material(&mut it)?);
}
_ => {
return Err(ColorDefinitionParseError::ParseError(
ParseError::InvalidToken(token.clone()),
));
}
}
}
colors.insert(
code,
Color {
code,
name,
color: Rgba::new(cr, cg, cb, alpha),
edge: Rgba::new(er, eg, eb, 255),
luminance,
material,
},
);
}
Ok(colors)
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_line_0_or_panic(input: &str) -> Line0 {
match parse_line_0(&mut input.chars()) {
Ok(line0) => line0,
Err(e) => {
panic!("cannot parse {}: {}", input, e);
}
}
}
#[test]
fn parse_line_0_parses_comment() {
let cases = [
("// This is a comment", "This is a comment"),
("This is also a comment", "This is also a comment"),
];
for (input, output) in cases {
let parsed = parse_line_0_or_panic(input);
match parsed {
Line0::Meta(Meta::Comment(comment)) => assert_eq!(comment, output),
_ => panic!("expected Line0::Meta(Meta::Comment(...)), got {:?}", parsed),
}
}
}
#[test]
fn parse_line_0_parses_offical_meta_commands_without_bfc() {
let cases = [
("STEP", Meta::Step),
(
"WRITE any length of string",
Meta::Write("any length of string".into()),
),
(
"PRINT also any length of string",
Meta::Print("also any length of string".into()),
),
("CLEAR", Meta::Clear),
("PAUSE", Meta::Pause),
("SAVE", Meta::Save),
];
for (input, output) in cases {
let parsed = parse_line_0_or_panic(input);
match parsed {
Line0::Meta(meta) => assert_eq!(meta, output),
_ => panic!("expected Line0::Meta(...), got {:?}", parsed),
}
}
}
#[test]
fn parse_line_0_parses_bfc_statements() {
let cases = [
("BFC CW", BfcStatement::Winding(Winding::Cw)),
("BFC CCW", BfcStatement::Winding(Winding::Ccw)),
("BFC CLIP", BfcStatement::Clip(None)),
("BFC CLIP CW", BfcStatement::Clip(Some(Winding::Cw))),
("BFC CLIP CCW", BfcStatement::Clip(Some(Winding::Ccw))),
("BFC CW CLIP", BfcStatement::Clip(Some(Winding::Cw))),
("BFC CCW CLIP", BfcStatement::Clip(Some(Winding::Ccw))),
("BFC NOCLIP", BfcStatement::NoClip),
("BFC INVERTNEXT", BfcStatement::InvertNext),
];
for (input, output) in cases {
let parsed = parse_line_0_or_panic(input);
match parsed {
Line0::Meta(Meta::Bfc(bfc)) => assert_eq!(bfc, output),
_ => panic!("expected Line0::Meta(Meta::Bfc(...)) got {:?}", parsed),
}
}
}
#[test]
fn parse_line_0_parses_bfc_certificates() {
let cases = [
("BFC NOCERTIFY", BfcCertification::NoCertify),
("BFC CERTIFY CW", BfcCertification::Certify(Winding::Cw)),
("BFC CERTIFY", BfcCertification::Certify(Winding::Ccw)),
("BFC CERTIFY CCW", BfcCertification::Certify(Winding::Ccw)),
];
for (input, output) in cases {
let parsed = parse_line_0_or_panic(input);
match parsed {
Line0::BfcCertification(certification) => assert_eq!(certification, output),
_ => panic!("expected Line0::BfsCertification(...), got {:?}", parsed),
}
}
}
#[test]
fn parse_line_0_parses_headers() {
let cases = [
(
"!LDRAW_ORG Part UPDATE 2006-01",
Header("LDRAW_ORG".into(), "Part UPDATE 2006-01".into()),
),
(
"!LICENSE Redistributable under CCAL version 2.: see CAreadme.txt",
Header(
"LICENSE".into(),
"Redistributable under CCAL version 2.: see CAreadme.txt".into(),
),
),
(
"!HELP Obviously there is no need for additional",
Header(
"HELP".into(),
"Obviously there is no need for additional".into(),
),
),
("!HELP", Header("HELP".into(), "".into())),
(
"!CATEGORY Animal",
Header("CATEGORY".into(), "Animal".into()),
),
(
"!KEYWORDS Sting, Poison, Adventurers, Egypt",
Header(
"KEYWORDS".into(),
"Sting, Poison, Adventurers, Egypt".into(),
),
),
("!CMDLINE -c1", Header("CMDLINE".into(), "-c1".into())),
(
"!HISTORY 2000-08-?? {Axel Poque} fixes to resolve L3P error messages",
Header(
"HISTORY".into(),
"2000-08-?? {Axel Poque} fixes to resolve L3P error messages".into(),
),
),
(
"!HISTORY 2002-04-25 [PTadmin] Official update 2002-02",
Header(
"HISTORY".into(),
"2002-04-25 [PTadmin] Official update 2002-02".into(),
),
),
];
for (input, output) in cases {
let parsed = parse_line_0_or_panic(input);
match parsed {
Line0::Header(header) => assert_eq!(header, output),
_ => panic!("expected Line0::Header(...), got {:?}", parsed),
}
}
}
#[test]
fn parse_line_0_parses_name_author() {
let name = "Name: 193a.dat";
let parsed_name = parse_line_0_or_panic(name);
assert_eq!(parsed_name, Line0::Name("193a.dat".into()));
let author = "Author: Chris Dee [cwdee]";
let parsed_author = parse_line_0_or_panic(author);
assert_eq!(parsed_author, Line0::Author("Chris Dee [cwdee]".into()));
}
#[test]
fn parse_line_0_parses_file() {
let file = "FILE main.ldr";
let parsed_file = parse_line_0_or_panic(file);
assert_eq!(parsed_file, Line0::File("main.ldr".into()));
}
#[test]
fn parse_customized_material_parses_glitter() {
let cases = [
("GLITTER VALUE #122334 FRACTION 0.3 VFRACTION 2.4 SIZE 1", MaterialGlitter {
value: Rgba::new(0x12, 0x23, 0x34, 255),
luminance: 0,
fraction: 0.3,
vfraction: 2.4,
size: 1,
minsize: 0.,
maxsize: 0.,
}),
("GLITTER VALUE #00DEAD LUMINANCE 128 FRACTION 0.5 VFRACTION 0.4 MINSIZE 2 MAXSIZE 3", MaterialGlitter {
value: Rgba::new(0x00, 0xde, 0xad, 255),
luminance: 128,
fraction: 0.5,
vfraction: 0.4,
size: 0,
minsize: 2.,
maxsize: 3.,
}),
("GLITTER VALUE #BEEF00 ALPHA 240 FRACTION 0.1 VFRACTION 0.12 SIZE 7", MaterialGlitter {
value: Rgba::new(0xbe, 0xef, 0x00, 240),
luminance: 0,
fraction: 0.1,
vfraction: 0.12,
size: 7,
minsize: 0.,
maxsize: 0.,
}),
("GLITTER VALUE #677889 ALPHA 5 LUMINANCE 10 FRACTION 1 VFRACTION 2 MINSIZE 1.1 MAXSIZE 4.3", MaterialGlitter {
value: Rgba::new(0x67, 0x78, 0x89, 5),
luminance: 10,
fraction: 1.,
vfraction: 2.,
size: 0,
minsize: 1.1,
maxsize: 4.3,
}),
];
for (input, output) in cases {
let parsed = parse_customized_material(&mut input.chars()).unwrap();
match parsed {
CustomizedMaterial::Glitter(glitter) => assert_eq!(glitter, output),
_ => panic!(
"expected CustomizedMaterial::Glitter(...), got: {:?}",
parsed
),
}
}
}
#[test]
fn parse_customized_material_parses_speckle() {
let cases = [
(
"SPECKLE VALUE #122334 FRACTION 0.3 SIZE 1",
MaterialSpeckle {
value: Rgba::new(0x12, 0x23, 0x34, 255),
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | true |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/document.rs | ldraw/src/document.rs | use std::{
collections::{HashMap, HashSet},
iter::Iterator,
vec::Vec,
};
use crate::{
elements::{Command, Header, Line, Meta, OptionalLine, PartReference, Quad, Triangle},
PartAlias, Winding,
};
#[derive(Clone, Debug, PartialEq)]
pub enum BfcCertification {
NotApplicable,
NoCertify,
Certify(Winding),
}
impl BfcCertification {
pub fn is_certified(&self) -> Option<bool> {
match self {
BfcCertification::Certify(_) => Some(true),
BfcCertification::NoCertify => Some(false),
BfcCertification::NotApplicable => None,
}
}
pub fn get_winding(&self) -> Option<Winding> {
match self {
BfcCertification::Certify(w) => Some(*w),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Document {
pub name: String,
pub description: String,
pub author: String,
pub bfc: BfcCertification,
pub headers: Vec<Header>,
pub commands: Vec<Command>,
}
impl Default for Document {
fn default() -> Self {
Document {
name: String::new(),
description: String::new(),
author: String::new(),
bfc: BfcCertification::NotApplicable,
headers: Vec::new(),
commands: Vec::new(),
}
}
}
fn traverse_dependencies(
document: &Document,
parent: Option<&MultipartDocument>,
list: &mut HashSet<PartAlias>,
) {
for part_ref in document.iter_refs() {
if let Some(parent) = parent {
if parent.subparts.contains_key(&part_ref.name) {
traverse_dependencies(
parent.subparts.get(&part_ref.name).unwrap(),
Some(parent),
list,
);
continue;
}
}
list.insert(part_ref.name.clone());
}
}
impl Document {
pub fn has_primitives(&self) -> bool {
for item in self.commands.iter() {
match item {
Command::Line(_)
| Command::Triangle(_)
| Command::Quad(_)
| Command::OptionalLine(_) => {
return true;
}
_ => (),
}
}
false
}
pub fn list_dependencies(&self) -> HashSet<PartAlias> {
let mut result = HashSet::new();
traverse_dependencies(self, None, &mut result);
result
}
}
macro_rules! define_iterator(
($fn:ident, $fn_mut:ident, $cmdval:path, $type:ty) => (
impl<'a> Document {
pub fn $fn(&'a self) -> impl Iterator<Item = &'a $type> {
self.commands.iter().filter_map(|value| match value {
$cmdval(m) => Some(m),
_ => None,
})
}
pub fn $fn_mut(&'a mut self) -> impl Iterator<Item = &'a mut $type> + 'a {
self.commands.iter_mut().filter_map(|value| match value {
$cmdval(m) => Some(m),
_ => None,
})
}
}
)
);
define_iterator!(iter_meta, iter_meta_mut, Command::Meta, Meta);
define_iterator!(
iter_refs,
iter_refs_mut,
Command::PartReference,
PartReference
);
define_iterator!(iter_lines, iter_lines_mut, Command::Line, Line);
define_iterator!(
iter_triangles,
iter_triangles_mut,
Command::Triangle,
Triangle
);
define_iterator!(iter_quads, iter_quads_mut, Command::Quad, Quad);
define_iterator!(
iter_optional_lines,
iter_optioanl_lines_mut,
Command::OptionalLine,
OptionalLine
);
#[derive(Clone, Debug, PartialEq)]
pub struct MultipartDocument {
pub body: Document,
pub subparts: HashMap<PartAlias, Document>,
}
impl MultipartDocument {
pub fn get_subpart(&self, alias: &PartAlias) -> Option<&Document> {
self.subparts.get(alias)
}
pub fn list_dependencies(&self) -> HashSet<PartAlias> {
let mut result = HashSet::new();
traverse_dependencies(&self.body, Some(self), &mut result);
result
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/error.rs | ldraw/src/error.rs | use std::{error::Error, fmt, io::Error as IoError};
#[cfg(any(target_arch = "wasm32", feature = "http"))]
use reqwest::Error as ReqwestError;
#[cfg(not(any(target_arch = "wasm32", feature = "http")))]
mod stub {
use super::{fmt, Error};
#[derive(Debug)]
pub struct ReqwestError;
impl fmt::Display for ReqwestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "")
}
}
impl Error for ReqwestError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
}
#[cfg(not(any(target_arch = "wasm32", feature = "http")))]
use stub::ReqwestError;
#[derive(Debug)]
pub enum ParseError {
TypeMismatch(&'static str, String),
IoError(Box<IoError>),
EndOfLine,
InvalidBfcStatement(String),
InvalidDocumentStructure,
UnexpectedCommand(String),
InvalidToken(String),
MultipartDocument,
}
impl From<IoError> for ParseError {
fn from(e: IoError) -> ParseError {
ParseError::IoError(Box::new(e))
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::TypeMismatch(type_, val) => {
write!(f, "Error reading value '{}' into {}", val, type_)
}
ParseError::IoError(err) => write!(f, "{}", err),
ParseError::EndOfLine => write!(f, "End of line"),
ParseError::InvalidBfcStatement(stmt) => write!(f, "Invalid BFC statement: {}", stmt),
ParseError::InvalidDocumentStructure => write!(f, "Invalid document structure."),
ParseError::UnexpectedCommand(cmd) => write!(f, "Unexpected command: {}", cmd),
ParseError::InvalidToken(token) => write!(f, "Invalid token: {}", token),
ParseError::MultipartDocument => write!(f, "Unexpected multipart document."),
}
}
}
impl Error for ParseError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ParseError::IoError(e) => Some(e),
_ => None,
}
}
}
#[derive(Debug)]
pub struct DocumentParseError {
pub line: usize,
pub error: ParseError,
}
impl From<DocumentParseError> for ColorDefinitionParseError {
fn from(e: DocumentParseError) -> ColorDefinitionParseError {
ColorDefinitionParseError::DocumentParseError(e)
}
}
impl fmt::Display for DocumentParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} (at line {})", self.error, self.line)
}
}
impl Error for DocumentParseError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.error)
}
}
#[derive(Debug)]
pub enum ColorDefinitionParseError {
ParseError(ParseError),
DocumentParseError(DocumentParseError),
UnknownMaterial(String),
}
impl From<ParseError> for ColorDefinitionParseError {
fn from(e: ParseError) -> ColorDefinitionParseError {
ColorDefinitionParseError::ParseError(e)
}
}
impl fmt::Display for ColorDefinitionParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ColorDefinitionParseError::ParseError(e) => write!(f, "{}", e),
ColorDefinitionParseError::DocumentParseError(e) => write!(f, "{}", e),
ColorDefinitionParseError::UnknownMaterial(e) => write!(f, "Unknown material: {}", e),
}
}
}
impl Error for ColorDefinitionParseError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ColorDefinitionParseError::ParseError(e) => Some(e),
ColorDefinitionParseError::DocumentParseError(e) => Some(e),
_ => None,
}
}
}
#[derive(Debug)]
pub enum SerializeError {
NoSerializable,
IoError(Box<IoError>),
}
impl From<IoError> for SerializeError {
fn from(e: IoError) -> SerializeError {
SerializeError::IoError(Box::new(e))
}
}
impl fmt::Display for SerializeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SerializeError::NoSerializable => write!(f, "Statement is not serializable."),
SerializeError::IoError(err) => write!(f, "{}", err),
}
}
}
impl Error for SerializeError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
SerializeError::IoError(e) => Some(e),
_ => None,
}
}
}
#[derive(Debug)]
pub enum ResolutionError {
NoLDrawDir,
FileNotFound,
IoError(Box<IoError>),
DocumentParseError(DocumentParseError),
ColorDefinitionParseError(ColorDefinitionParseError),
RemoteError(ReqwestError),
}
impl From<IoError> for ResolutionError {
fn from(e: IoError) -> ResolutionError {
ResolutionError::IoError(Box::new(e))
}
}
impl From<DocumentParseError> for ResolutionError {
fn from(e: DocumentParseError) -> ResolutionError {
ResolutionError::DocumentParseError(e)
}
}
impl From<ColorDefinitionParseError> for ResolutionError {
fn from(e: ColorDefinitionParseError) -> ResolutionError {
ResolutionError::ColorDefinitionParseError(e)
}
}
impl From<ReqwestError> for ResolutionError {
fn from(e: ReqwestError) -> ResolutionError {
ResolutionError::RemoteError(e)
}
}
impl fmt::Display for ResolutionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ResolutionError::NoLDrawDir => write!(f, "No LDraw library found."),
ResolutionError::FileNotFound => write!(f, "File not found."),
ResolutionError::IoError(err) => write!(f, "{}", err),
ResolutionError::DocumentParseError(err) => write!(f, "{}", err),
ResolutionError::ColorDefinitionParseError(err) => write!(f, "{}", err),
ResolutionError::RemoteError(err) => write!(f, "{}", err),
}
}
}
impl Error for ResolutionError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ResolutionError::IoError(e) => Some(e),
ResolutionError::DocumentParseError(e) => Some(e),
ResolutionError::ColorDefinitionParseError(e) => Some(e),
ResolutionError::RemoteError(e) => Some(e),
_ => None,
}
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/library.rs | ldraw/src/library.rs | use std::{
collections::{HashMap, HashSet},
ops::Deref,
sync::{Arc, RwLock},
};
use async_trait::async_trait;
use futures::future::join_all;
use serde::{Deserialize, Serialize};
use crate::{
color::ColorCatalog,
document::{Document, MultipartDocument},
error::ResolutionError,
PartAlias,
};
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Hash)]
pub enum PartKind {
Primitive,
Part,
}
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Hash)]
pub enum FileLocation {
Library(PartKind),
Local,
}
#[async_trait(?Send)]
pub trait DocumentLoader<T> {
async fn load_document(
&self,
locator: &T,
colors: &ColorCatalog,
) -> Result<MultipartDocument, ResolutionError>;
}
#[async_trait(?Send)]
pub trait LibraryLoader {
async fn load_colors(&self) -> Result<ColorCatalog, ResolutionError>;
async fn load_ref(
&self,
alias: PartAlias,
local: bool,
colors: &ColorCatalog,
) -> Result<(FileLocation, MultipartDocument), ResolutionError>;
}
#[derive(Debug, Default)]
pub struct PartCache {
primitives: HashMap<PartAlias, Arc<MultipartDocument>>,
parts: HashMap<PartAlias, Arc<MultipartDocument>>,
}
#[derive(Copy, Clone, Debug)]
pub enum CacheCollectionStrategy {
Parts,
Primitives,
PartsAndPrimitives,
}
impl Drop for PartCache {
fn drop(&mut self) {
self.collect(CacheCollectionStrategy::PartsAndPrimitives);
}
}
impl PartCache {
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, kind: PartKind, alias: PartAlias, document: Arc<MultipartDocument>) {
match kind {
PartKind::Part => self.parts.insert(alias, document),
PartKind::Primitive => self.primitives.insert(alias, document),
};
}
pub fn query(&self, alias: &PartAlias) -> Option<Arc<MultipartDocument>> {
match self.parts.get(alias) {
Some(part) => Some(Arc::clone(part)),
None => self.primitives.get(alias).cloned(),
}
}
fn collect_round(&mut self, collection_strategy: CacheCollectionStrategy) -> usize {
let prev_size = self.parts.len() + self.primitives.len();
match collection_strategy {
CacheCollectionStrategy::Parts => {
self.parts
.retain(|_, v| Arc::strong_count(v) > 1 || Arc::weak_count(v) > 0);
}
CacheCollectionStrategy::Primitives => {
self.primitives
.retain(|_, v| Arc::strong_count(v) > 1 || Arc::weak_count(v) > 0);
}
CacheCollectionStrategy::PartsAndPrimitives => {
self.parts
.retain(|_, v| Arc::strong_count(v) > 1 || Arc::weak_count(v) > 0);
self.primitives
.retain(|_, v| Arc::strong_count(v) > 1 || Arc::weak_count(v) > 0);
}
};
prev_size - self.parts.len() - self.primitives.len()
}
pub fn collect(&mut self, collection_strategy: CacheCollectionStrategy) -> usize {
let mut total_collected = 0;
loop {
let collected = self.collect_round(collection_strategy);
if collected == 0 {
break;
}
total_collected += collected;
}
total_collected
}
}
#[derive(Debug, Default)]
struct TransientDocumentCache {
documents: HashMap<PartAlias, Arc<MultipartDocument>>,
}
impl TransientDocumentCache {
pub fn register(&mut self, alias: PartAlias, document: Arc<MultipartDocument>) {
self.documents.insert(alias, document);
}
pub fn query(&self, alias: &PartAlias) -> Option<Arc<MultipartDocument>> {
self.documents.get(alias).cloned()
}
}
#[derive(Clone, Debug)]
pub enum ResolutionState {
Missing,
Pending,
Subpart,
Associated(Arc<MultipartDocument>),
}
struct DependencyResolver<'a, F, L> {
colors: &'a ColorCatalog,
cache: Arc<RwLock<PartCache>>,
local_cache: TransientDocumentCache,
on_update: &'a F,
loader: &'a L,
pub map: HashMap<PartAlias, ResolutionState>,
pub local_map: HashMap<PartAlias, ResolutionState>,
}
impl<'a, F: Fn(PartAlias, Result<(), ResolutionError>), L: LibraryLoader>
DependencyResolver<'a, F, L>
{
pub fn new(
colors: &'a ColorCatalog,
cache: Arc<RwLock<PartCache>>,
on_update: &'a F,
loader: &'a L,
) -> DependencyResolver<'a, F, L> {
DependencyResolver {
colors,
cache,
local_cache: TransientDocumentCache::default(),
on_update,
loader,
map: HashMap::new(),
local_map: HashMap::new(),
}
}
pub fn contains_state(&self, alias: &PartAlias, local: bool) -> bool {
if local {
self.local_map.contains_key(alias)
} else {
self.map.contains_key(alias)
}
}
pub fn put_state(&mut self, alias: PartAlias, local: bool, state: ResolutionState) {
if local {
self.local_map.insert(alias, state);
} else {
self.map.insert(alias, state);
}
}
pub fn clear_state(&mut self, alias: &PartAlias, local: bool) {
if local {
self.local_map.remove(alias);
} else {
self.map.remove(alias);
}
}
pub fn scan_dependencies(&mut self, document: &Document, local: bool) {
for r in document.iter_refs() {
let alias = &r.name;
if self.contains_state(alias, local) {
continue;
}
if local {
if let Some(cached) = self.local_cache.query(alias) {
self.scan_dependencies_with_parent(None, Arc::clone(&cached), true);
self.put_state(
alias.clone(),
true,
ResolutionState::Associated(Arc::clone(&cached)),
);
continue;
}
}
let cached = self.cache.read().unwrap().query(alias);
if let Some(cached) = cached {
self.scan_dependencies_with_parent(None, Arc::clone(&cached), false);
self.put_state(
alias.clone(),
false,
ResolutionState::Associated(Arc::clone(&cached)),
);
continue;
}
self.put_state(alias.clone(), local, ResolutionState::Pending);
}
}
pub fn scan_dependencies_with_parent<D: Deref<Target = MultipartDocument> + Clone>(
&mut self,
alias: Option<&PartAlias>,
parent: D,
local: bool,
) {
let document = match alias {
Some(e) => match parent.subparts.get(e) {
Some(e) => e,
None => return,
},
None => &parent.body,
};
for r in document.iter_refs() {
let alias = &r.name;
if self.contains_state(alias, local) {
continue;
}
if parent.subparts.contains_key(alias) {
self.put_state(alias.clone(), local, ResolutionState::Subpart);
self.scan_dependencies_with_parent(Some(alias), parent.clone(), local);
continue;
}
if local {
if let Some(cached) = self.local_cache.query(alias) {
self.scan_dependencies_with_parent(None, Arc::clone(&cached), true);
self.put_state(
alias.clone(),
true,
ResolutionState::Associated(Arc::clone(&cached)),
);
continue;
}
}
let cached = self.cache.read().unwrap().query(alias);
if let Some(cached) = cached {
self.scan_dependencies_with_parent(None, Arc::clone(&cached), false);
self.put_state(
alias.clone(),
false,
ResolutionState::Associated(Arc::clone(&cached)),
);
continue;
}
self.put_state(alias.clone(), local, ResolutionState::Pending);
}
}
pub async fn resolve_pending_dependencies(&mut self) -> bool {
let mut pending = self
.local_map
.iter()
.filter_map(|(k, v)| match v {
ResolutionState::Pending => Some((k.clone(), true)),
_ => None,
})
.collect::<Vec<_>>();
pending.extend(self.map.iter().filter_map(|(k, v)| match v {
ResolutionState::Pending => Some((k.clone(), false)),
_ => None,
}));
if pending.is_empty() {
return false;
}
let futs = pending
.iter()
.map(|(alias, local)| self.loader.load_ref(alias.clone(), *local, self.colors))
.collect::<Vec<_>>();
let result = join_all(futs).await;
for ((alias, mut local), result) in pending.iter().zip(result) {
let state = match result {
Ok((location, document)) => {
(self.on_update)(alias.clone(), Ok(()));
let document = Arc::new(document);
match location {
FileLocation::Library(kind) => {
if local {
self.clear_state(alias, true);
}
local = false;
self.cache.write().unwrap().register(
kind,
alias.clone(),
Arc::clone(&document),
);
}
FileLocation::Local => {
self.local_cache
.register(alias.clone(), Arc::clone(&document));
}
};
self.scan_dependencies_with_parent(None, Arc::clone(&document), local);
ResolutionState::Associated(document)
}
Err(err) => {
(self.on_update)(alias.clone(), Err(err));
ResolutionState::Missing
}
};
self.put_state(alias.clone(), local, state);
}
true
}
}
#[derive(Debug, Default)]
pub struct ResolutionResult {
library_entries: HashMap<PartAlias, Arc<MultipartDocument>>,
local_entries: HashMap<PartAlias, Arc<MultipartDocument>>,
}
impl ResolutionResult {
pub fn new() -> Self {
Self::default()
}
pub fn query(&self, alias: &PartAlias, local: bool) -> Option<(Arc<MultipartDocument>, bool)> {
if local {
let local_entry = self.local_entries.get(alias);
if let Some(e) = local_entry {
return Some((Arc::clone(e), true));
}
}
self.library_entries
.get(alias)
.map(|e| (Arc::clone(e), false))
}
pub fn list_dependencies(&self) -> HashSet<PartAlias> {
let mut result = HashSet::new();
result.extend(self.library_entries.keys().cloned());
result.extend(self.local_entries.keys().cloned());
result
}
}
pub async fn resolve_dependencies_multipart<F, L>(
document: &MultipartDocument,
cache: Arc<RwLock<PartCache>>,
colors: &ColorCatalog,
loader: &L,
on_update: &F,
) -> ResolutionResult
where
F: Fn(PartAlias, Result<(), ResolutionError>),
L: LibraryLoader,
{
let mut resolver = DependencyResolver::new(colors, cache, on_update, loader);
resolver.scan_dependencies_with_parent(None, document, true);
while resolver.resolve_pending_dependencies().await {}
ResolutionResult {
library_entries: resolver
.map
.into_iter()
.filter_map(|(k, v)| match v {
ResolutionState::Associated(e) => Some((k, e)),
_ => None,
})
.collect::<HashMap<_, _>>(),
local_entries: resolver
.local_map
.into_iter()
.filter_map(|(k, v)| match v {
ResolutionState::Associated(e) => Some((k, e)),
_ => None,
})
.collect::<HashMap<_, _>>(),
}
}
pub async fn resolve_dependencies<F, L>(
document: &Document,
cache: Arc<RwLock<PartCache>>,
colors: &ColorCatalog,
loader: &L,
on_update: &F,
) -> ResolutionResult
where
F: Fn(PartAlias, Result<(), ResolutionError>),
L: LibraryLoader,
{
let mut resolver = DependencyResolver::new(colors, cache, on_update, loader);
resolver.scan_dependencies(document, true);
while resolver.resolve_pending_dependencies().await {}
ResolutionResult {
library_entries: resolver
.map
.into_iter()
.filter_map(|(k, v)| match v {
ResolutionState::Associated(e) => Some((k, e)),
_ => None,
})
.collect::<HashMap<_, _>>(),
local_entries: resolver
.local_map
.into_iter()
.filter_map(|(k, v)| match v {
ResolutionState::Associated(e) => Some((k, e)),
_ => None,
})
.collect::<HashMap<_, _>>(),
}
}
#[cfg(test)]
mod tests {
use std::{collections::HashMap, sync::Arc};
use super::{PartCache, PartKind};
use crate::{
document::{BfcCertification, Document, MultipartDocument},
PartAlias,
};
#[test]
fn test_part_cache_query_existing() {
let document = MultipartDocument {
body: Document {
name: "Doc".to_string(),
author: "Author".to_string(),
description: "Description".to_string(),
bfc: BfcCertification::NoCertify,
headers: vec![],
commands: vec![],
},
subparts: HashMap::new(),
};
let mut cache = PartCache::new();
let existing_key = PartAlias::from("existing".to_string());
let document = Arc::new(document);
cache.register(PartKind::Primitive, existing_key.clone(), document.clone());
assert_eq!(cache.query(&existing_key).unwrap(), document);
}
#[test]
fn test_part_cache_query_missing() {
let cache = PartCache::new();
let missing_key = PartAlias::from("missing".to_string());
assert!(cache.query(&missing_key).is_none());
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/elements.rs | ldraw/src/elements.rs | use crate::color::ColorReference;
use crate::{Matrix4, PartAlias, Vector4, Winding};
#[derive(Clone, Debug, PartialEq)]
pub struct Header(pub String, pub String);
#[derive(Clone, Debug, PartialEq)]
pub enum BfcStatement {
Winding(Winding),
Clip(Option<Winding>),
NoClip,
InvertNext,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Meta {
Comment(String),
Step,
Write(String),
Print(String),
Clear,
Pause,
Save,
Bfc(BfcStatement),
}
#[derive(Clone, Debug, PartialEq)]
pub struct PartReference {
pub color: ColorReference,
pub matrix: Matrix4,
pub name: PartAlias,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Line {
pub color: ColorReference,
pub a: Vector4,
pub b: Vector4,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Triangle {
pub color: ColorReference,
pub a: Vector4,
pub b: Vector4,
pub c: Vector4,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Quad {
pub color: ColorReference,
pub a: Vector4,
pub b: Vector4,
pub c: Vector4,
pub d: Vector4,
}
#[derive(Clone, Debug, PartialEq)]
pub struct OptionalLine {
pub color: ColorReference,
pub a: Vector4,
pub b: Vector4,
pub c: Vector4,
pub d: Vector4,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Command {
Meta(Meta),
PartReference(PartReference),
Line(Line),
Triangle(Triangle),
Quad(Quad),
OptionalLine(OptionalLine),
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/writer.rs | ldraw/src/writer.rs | use std::fmt;
use async_trait::async_trait;
use cgmath::{Matrix, Vector4};
use tokio::io::{AsyncWrite, AsyncWriteExt};
use crate::color::ColorReference;
use crate::document::{BfcCertification, Document, MultipartDocument};
use crate::elements::{
BfcStatement, Command, Header, Line, Meta, OptionalLine, PartReference, Quad, Triangle,
};
use crate::error::SerializeError;
use crate::Winding;
fn serialize_vec3(vec: &Vector4<f32>) -> String {
format!("{} {} {}", vec.x, vec.y, vec.z)
}
impl fmt::Display for ColorReference {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let code = match self {
ColorReference::Unknown(code) => code,
ColorReference::Current => &16u32,
ColorReference::Complement => &24u32,
ColorReference::Color(color) => &color.code,
ColorReference::Unresolved(code) => code,
};
write!(f, "{}", code)
}
}
#[async_trait]
pub trait LDrawWriter {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError>;
}
#[async_trait]
impl LDrawWriter for Header {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
writer
.write_all(format!("0 !{} {}\n", self.0, self.1).as_bytes())
.await?;
Ok(())
}
}
#[async_trait]
impl LDrawWriter for BfcCertification {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
match self {
BfcCertification::NoCertify => writer.write_all(b"0 BFC NOCERTIFY\n").await?,
BfcCertification::Certify(Winding::Ccw) => {
writer.write_all(b"0 BFC CERTIFY CCW\n").await?
}
BfcCertification::Certify(Winding::Cw) => {
writer.write_all(b"0 BFC CERTIFY CW\n").await?
}
_ => return Err(SerializeError::NoSerializable),
};
Ok(())
}
}
#[async_trait]
impl LDrawWriter for BfcStatement {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
match self {
BfcStatement::Winding(Winding::Cw) => writer.write_all(b"0 BFC CW\n").await?,
BfcStatement::Winding(Winding::Ccw) => writer.write_all(b"0 BFC CCW\n").await?,
BfcStatement::Clip(None) => writer.write_all(b"0 BFC CLIP\n").await?,
BfcStatement::Clip(Some(Winding::Cw)) => writer.write_all(b"0 BFC CLIP CW\n").await?,
BfcStatement::Clip(Some(Winding::Ccw)) => writer.write_all(b"0 BFC CLIP CW\n").await?,
BfcStatement::NoClip => writer.write_all(b"0 BFC NOCLIP\n").await?,
BfcStatement::InvertNext => writer.write_all(b"0 BFC INVERTNEXT\n").await?,
};
Ok(())
}
}
#[async_trait]
impl LDrawWriter for Document {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
writer
.write_all(format!("0 {}\n", self.description).as_bytes())
.await?;
writer
.write_all(format!("0 Name: {}\n", self.name).as_bytes())
.await?;
writer
.write_all(format!("0 Author: {}\n", self.author).as_bytes())
.await?;
for header in &self.headers {
header.write(writer).await?;
}
writer.write_all(b"\n").await?;
match self.bfc.write(writer).await {
Ok(()) => {
writer.write_all(b"\n").await?;
}
Err(SerializeError::NoSerializable) => {}
Err(e) => return Err(e),
};
for command in &self.commands {
command.write(writer).await?;
}
writer.write_all(b"0\n\n").await?;
Ok(())
}
}
#[async_trait]
impl LDrawWriter for MultipartDocument {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
self.body.write(writer).await?;
for subpart in self.subparts.values() {
writer
.write_all(format!("0 FILE {}\n", subpart.name).as_bytes())
.await?;
subpart.write(writer).await?;
}
Ok(())
}
}
#[async_trait]
impl LDrawWriter for Meta {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
match self {
Meta::Comment(message) => {
for line in message.lines() {
writer
.write_all(format!("0 // {}\n", line).as_bytes())
.await?;
}
}
Meta::Step => {
writer.write_all(b"0 STEP\n").await?;
}
Meta::Write(message) => {
for line in message.lines() {
writer
.write_all(format!("0 WRITE {}\n", line).as_bytes())
.await?;
}
}
Meta::Print(message) => {
for line in message.lines() {
writer
.write_all(format!("0 PRINT {}\n", line).as_bytes())
.await?;
}
}
Meta::Clear => {
writer.write_all(b"0 CLEAR\n").await?;
}
Meta::Pause => {
writer.write_all(b"0 PAUSE\n").await?;
}
Meta::Save => {
writer.write_all(b"0 SAVE\n").await?;
}
Meta::Bfc(bfc) => {
bfc.write(writer).await?;
}
};
Ok(())
}
}
#[async_trait]
impl LDrawWriter for PartReference {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
let m = self.matrix.transpose();
writer
.write_all(
format!(
"1 {} {} {} {} {} {} {} {} {} {} {} {} {}\n",
self.color,
m.x.w,
m.y.w,
m.z.w,
m.x.x,
m.x.y,
m.x.z,
m.y.x,
m.y.y,
m.y.z,
m.z.x,
m.z.y,
m.z.z
)
.as_bytes(),
)
.await?;
Ok(())
}
}
#[async_trait]
impl LDrawWriter for Line {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
writer
.write_all(
format!(
"2 {} {} {}\n",
self.color,
serialize_vec3(&self.a),
serialize_vec3(&self.b)
)
.as_bytes(),
)
.await?;
Ok(())
}
}
#[async_trait]
impl LDrawWriter for Triangle {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
writer
.write_all(
format!(
"2 {} {} {} {}\n",
self.color,
serialize_vec3(&self.a),
serialize_vec3(&self.b),
serialize_vec3(&self.c)
)
.as_bytes(),
)
.await?;
Ok(())
}
}
#[async_trait]
impl LDrawWriter for Quad {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
writer
.write_all(
format!(
"2 {} {} {} {} {}\n",
self.color,
serialize_vec3(&self.a),
serialize_vec3(&self.b),
serialize_vec3(&self.c),
serialize_vec3(&self.d)
)
.as_bytes(),
)
.await?;
Ok(())
}
}
#[async_trait]
impl LDrawWriter for OptionalLine {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
writer
.write_all(
format!(
"2 {} {} {} {} {}\n",
self.color,
serialize_vec3(&self.a),
serialize_vec3(&self.b),
serialize_vec3(&self.c),
serialize_vec3(&self.d)
)
.as_bytes(),
)
.await?;
Ok(())
}
}
#[async_trait]
impl LDrawWriter for Command {
async fn write(
&self,
writer: &mut (dyn AsyncWrite + Unpin + Send),
) -> Result<(), SerializeError> {
match self {
Command::Meta(meta) => meta.write(writer).await,
Command::PartReference(ref_) => ref_.write(writer).await,
Command::Line(line) => line.write(writer).await,
Command::Triangle(triangle) => triangle.write(writer).await,
Command::Quad(quad) => quad.write(writer).await,
Command::OptionalLine(optional_line) => optional_line.write(writer).await,
}
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/color.rs | ldraw/src/color.rs | use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use serde::de::Deserializer;
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use crate::Vector4;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rgba {
value: [u8; 4],
}
impl Rgba {
pub fn new(r: u8, g: u8, b: u8, a: u8) -> Rgba {
Rgba {
value: [r, g, b, a],
}
}
pub fn from_value(value: u32) -> Rgba {
let r = ((value & 0x00ff_0000) >> 16) as u8;
let g = ((value & 0x0000_ff00) >> 8) as u8;
let b = (value & 0x0000_00ff) as u8;
let a = ((value & 0xff00_0000) >> 24) as u8;
Rgba {
value: [r, g, b, a],
}
}
pub fn red(self) -> u8 {
self.value[0]
}
pub fn green(self) -> u8 {
self.value[1]
}
pub fn blue(self) -> u8 {
self.value[2]
}
pub fn alpha(self) -> u8 {
self.value[3]
}
}
impl From<&Rgba> for Vector4 {
fn from(src: &Rgba) -> Vector4 {
Vector4::new(
f32::from(src.red()) / 255.0,
f32::from(src.green()) / 255.0,
f32::from(src.blue()) / 255.0,
f32::from(src.alpha()) / 255.0,
)
}
}
impl From<Rgba> for Vector4 {
fn from(src: Rgba) -> Vector4 {
Vector4::new(
f32::from(src.red()) / 255.0,
f32::from(src.green()) / 255.0,
f32::from(src.blue()) / 255.0,
f32::from(src.alpha()) / 255.0,
)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct MaterialGlitter {
pub value: Rgba,
pub luminance: u8,
pub fraction: f32,
pub vfraction: f32,
pub size: u32,
pub minsize: f32,
pub maxsize: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MaterialSpeckle {
pub value: Rgba,
pub luminance: u8,
pub fraction: f32,
pub size: u32,
pub minsize: f32,
pub maxsize: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub enum CustomizedMaterial {
Glitter(MaterialGlitter),
Speckle(MaterialSpeckle),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Material {
Plastic,
Chrome,
Pearlescent,
Rubber,
MatteMetallic,
Metal,
Custom(CustomizedMaterial),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Color {
pub code: u32,
pub name: String,
pub color: Rgba,
pub edge: Rgba,
pub luminance: u8,
pub material: Material,
}
impl Default for Color {
fn default() -> Self {
Color {
code: 0,
name: String::from("Black"),
color: Rgba::new(0x05, 0x13, 0x1d, 0xff),
edge: Rgba::new(0x59, 0x59, 0x59, 0xff),
luminance: 0x00,
material: Material::Plastic,
}
}
}
impl Color {
pub fn is_translucent(&self) -> bool {
self.color.alpha() < 255u8
}
}
pub type ColorCatalog = HashMap<u32, Color>;
#[derive(Clone, Debug)]
pub enum ColorReference {
Unknown(u32),
Current,
Complement,
Color(Color),
Unresolved(u32),
}
impl Eq for ColorReference {}
impl PartialEq for ColorReference {
fn eq(&self, other: &Self) -> bool {
self.code() == other.code()
}
}
impl Hash for ColorReference {
fn hash<H: Hasher>(&self, state: &mut H) {
self.code().hash(state)
}
}
impl ColorReference {
pub fn code(&self) -> u32 {
match self {
ColorReference::Unknown(c) => *c,
ColorReference::Current => 16,
ColorReference::Complement => 24,
ColorReference::Color(m) => m.code,
ColorReference::Unresolved(c) => *c,
}
}
pub fn is_current(&self) -> bool {
matches!(self, ColorReference::Current)
}
pub fn is_complement(&self) -> bool {
matches!(self, ColorReference::Complement)
}
pub fn is_color(&self) -> bool {
matches!(self, ColorReference::Color(_))
}
pub fn get_color(&self) -> Option<&Color> {
match self {
ColorReference::Color(m) => Some(m),
_ => None,
}
}
fn resolve_blended(code: u32, colors: &ColorCatalog) -> Option<Color> {
let code1 = code / 16;
let code2 = code % 16;
let color1 = match colors.get(&code1) {
Some(c) => c,
None => return None,
};
let color2 = match colors.get(&code2) {
Some(c) => c,
None => return None,
};
let new_color = Rgba::new(
color1.color.red() / 2 + color2.color.red() / 2,
color1.color.green() / 2 + color2.color.green() / 2,
color1.color.blue() / 2 + color2.color.blue() / 2,
255,
);
Some(Color {
code,
name: format!("Blended Color ({} and {})", code1, code2),
color: new_color,
edge: Rgba::from_value(0xff59_5959),
luminance: 0,
material: Material::Plastic,
})
}
fn resolve_rgb_4(code: u32) -> Color {
let red = (((code & 0xf00) >> 8) * 16) as u8;
let green = (((code & 0x0f0) >> 4) * 16) as u8;
let blue = ((code & 0x00f) * 16) as u8;
let edge_red = (((code & 0xf0_0000) >> 20) * 16) as u8;
let edge_green = (((code & 0x0f_0000) >> 16) * 16) as u8;
let edge_blue = (((code & 0x00_f000) >> 12) * 16) as u8;
Color {
code,
name: format!("RGB Color ({:03x})", code & 0xfff),
color: Rgba::new(red, green, blue, 255),
edge: Rgba::new(edge_red, edge_green, edge_blue, 255),
luminance: 0,
material: Material::Plastic,
}
}
fn resolve_rgb_2(code: u32) -> Color {
Color {
code,
name: format!("RGB Color ({:06x})", code & 0xff_ffff),
color: Rgba::from_value(0xff00_0000 | (code & 0xff_ffff)),
edge: Rgba::from_value(0xff59_5959),
luminance: 0,
material: Material::Plastic,
}
}
pub fn resolve(code: u32, colors: &ColorCatalog) -> ColorReference {
match code {
16 => return ColorReference::Current,
24 => return ColorReference::Complement,
_ => (),
}
if let Some(c) = colors.get(&code) {
return ColorReference::Color(c.clone());
}
if (256..=512).contains(&code) {
if let Some(c) = ColorReference::resolve_blended(code, colors) {
return ColorReference::Color(c);
}
}
if (code & 0xff00_0000) == 0x0200_0000 {
return ColorReference::Color(ColorReference::resolve_rgb_2(code));
} else if (code & 0xff00_0000) == 0x0400_0000 {
return ColorReference::Color(ColorReference::resolve_rgb_4(code));
}
ColorReference::Unknown(code)
}
pub fn resolve_self(&mut self, colors: &ColorCatalog) {
if let ColorReference::Unresolved(code) = self {
*self = ColorReference::resolve(*code, colors);
}
}
pub fn get_color_rgba(&self) -> Option<Vector4> {
match self {
ColorReference::Color(c) => Some(c.color.into()),
_ => None,
}
}
pub fn get_edge_color_rgba(&self) -> Option<Vector4> {
match self {
ColorReference::Color(m) => Some(m.edge.into()),
_ => None,
}
}
}
impl<'de> Deserialize<'de> for ColorReference {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
panic!("Deserializing ColorReference is not supported");
}
}
impl Serialize for ColorReference {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.code())
}
}
impl From<ColorReference> for u32 {
fn from(value: ColorReference) -> Self {
value.code()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct ColorCode(u32);
impl From<ColorReference> for ColorCode {
fn from(value: ColorReference) -> Self {
Self(value.code())
}
}
impl From<ColorCode> for u32 {
fn from(value: ColorCode) -> Self {
value.0
}
}
impl From<u32> for ColorCode {
fn from(value: u32) -> Self {
Self(value)
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/resolvers/local.rs | ldraw/src/resolvers/local.rs | use std::path::PathBuf;
use async_trait::async_trait;
use tokio::{
fs::{try_exists, File},
io::BufReader,
};
use crate::{
color::ColorCatalog,
document::MultipartDocument,
error::ResolutionError,
library::{DocumentLoader, FileLocation, LibraryLoader, PartKind},
parser::{parse_color_definitions, parse_multipart_document},
PartAlias,
};
pub struct LocalLoader {
ldrawdir: Option<PathBuf>,
cwd: Option<PathBuf>,
}
impl LocalLoader {
pub fn new(ldrawdir: Option<PathBuf>, cwd: Option<PathBuf>) -> Self {
LocalLoader { ldrawdir, cwd }
}
}
#[async_trait(?Send)]
impl DocumentLoader<PathBuf> for LocalLoader {
async fn load_document(
&self,
locator: &PathBuf,
colors: &ColorCatalog,
) -> Result<MultipartDocument, ResolutionError> {
if !try_exists(&locator).await? {
return Err(ResolutionError::FileNotFound);
}
Ok(
parse_multipart_document(&mut BufReader::new(File::open(locator).await?), colors)
.await?,
)
}
}
#[async_trait(?Send)]
impl LibraryLoader for LocalLoader {
async fn load_colors(&self) -> Result<ColorCatalog, ResolutionError> {
let ldrawdir = match self.ldrawdir.clone() {
Some(e) => e,
None => return Err(ResolutionError::NoLDrawDir),
};
let path = {
let mut path = ldrawdir.clone();
path.push("LDConfig.ldr");
path
};
if !try_exists(&path).await? {
return Err(ResolutionError::FileNotFound);
}
Ok(parse_color_definitions(&mut BufReader::new(File::open(&*path).await?)).await?)
}
async fn load_ref(
&self,
alias: PartAlias,
local: bool,
colors: &ColorCatalog,
) -> Result<(FileLocation, MultipartDocument), ResolutionError> {
let ldrawdir = match self.ldrawdir.clone() {
Some(e) => e,
None => return Err(ResolutionError::NoLDrawDir),
};
let cwd_path = self.cwd.as_ref().map(|v| {
let mut path = v.clone();
path.push(alias.normalized.clone());
path
});
let parts_path = {
let mut path = ldrawdir.clone();
path.push("parts");
path.push(alias.normalized.clone());
path
};
let p_path = {
let mut path = ldrawdir.clone();
path.push("p");
path.push(alias.normalized.clone());
path
};
let (kind, path) =
if local && cwd_path.is_some() && try_exists(&cwd_path.as_ref().unwrap()).await? {
(FileLocation::Local, cwd_path.as_ref().unwrap())
} else if try_exists(&parts_path).await? {
(FileLocation::Library(PartKind::Part), &parts_path)
} else if try_exists(&p_path).await? {
(FileLocation::Library(PartKind::Primitive), &p_path)
} else {
return Err(ResolutionError::FileNotFound);
};
let document =
parse_multipart_document(&mut BufReader::new(File::open(&**path).await?), colors)
.await?;
Ok((kind, document))
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/resolvers/http.rs | ldraw/src/resolvers/http.rs | use async_trait::async_trait;
use futures::join;
use reqwest::{Client, Error, Response, StatusCode, Url};
use tokio::io::BufReader;
use crate::{
color::ColorCatalog,
document::MultipartDocument,
error::ResolutionError,
library::{DocumentLoader, FileLocation, LibraryLoader, PartKind},
parser::{parse_color_definitions, parse_multipart_document},
PartAlias,
};
pub struct HttpLoader {
ldraw_url_base: Option<Url>,
document_url_base: Option<Url>,
client: Client,
}
impl HttpLoader {
pub fn new(ldraw_url_base: Option<Url>, document_url_base: Option<Url>) -> Self {
HttpLoader {
ldraw_url_base,
document_url_base,
client: Client::new(),
}
}
}
#[async_trait(?Send)]
impl DocumentLoader<String> for HttpLoader {
async fn load_document(
&self,
locator: &String,
colors: &ColorCatalog,
) -> Result<MultipartDocument, ResolutionError> {
let url = match Url::parse(locator) {
Ok(e) => e,
Err(_) => return Err(ResolutionError::FileNotFound),
};
let bytes = self.client.get(url).send().await?.bytes().await?;
Ok(parse_multipart_document(&mut BufReader::new(&*bytes), colors).await?)
}
}
#[async_trait(?Send)]
impl LibraryLoader for HttpLoader {
async fn load_colors(&self) -> Result<ColorCatalog, ResolutionError> {
let ldraw_url_base = self.ldraw_url_base.as_ref();
let ldraw_url_base = match ldraw_url_base {
Some(ref e) => e,
None => return Err(ResolutionError::NoLDrawDir),
};
let url = ldraw_url_base.join("LDConfig.ldr").unwrap();
let response = self.client.get(url).send().await?;
if response.status() == StatusCode::NOT_FOUND {
Err(ResolutionError::FileNotFound)
} else {
let bytes = response.bytes().await?;
Ok(parse_color_definitions(&mut BufReader::new(&*bytes)).await?)
}
}
async fn load_ref(
&self,
alias: PartAlias,
local: bool,
colors: &ColorCatalog,
) -> Result<(FileLocation, MultipartDocument), ResolutionError> {
let ldraw_url_base = self.ldraw_url_base.as_ref();
let ldraw_url_base = match ldraw_url_base {
Some(ref e) => e,
None => return Err(ResolutionError::NoLDrawDir),
};
let parts_url = ldraw_url_base
.join(&format!("parts/{}", alias.normalized))
.unwrap();
let p_url = ldraw_url_base
.join(&format!("p/{}", alias.normalized))
.unwrap();
let parts_fut = self.client.get(parts_url).send();
let p_fut = self.client.get(p_url).send();
let (location, res) = if local && self.document_url_base.is_some() {
let document_url_base = self.document_url_base.as_ref().unwrap();
let local_url = document_url_base.join(&alias.normalized).unwrap();
let local_fut = self.client.get(local_url).send();
let (local, parts, p) = join!(local_fut, parts_fut, p_fut);
if let Some(v) = select_response(local) {
(FileLocation::Local, v)
} else if let Some(v) = select_response(parts) {
(FileLocation::Library(PartKind::Part), v)
} else if let Some(v) = select_response(p) {
(FileLocation::Library(PartKind::Primitive), v)
} else {
return Err(ResolutionError::FileNotFound);
}
} else {
let (parts, p) = join!(parts_fut, p_fut);
if let Some(v) = select_response(parts) {
(FileLocation::Library(PartKind::Part), v)
} else if let Some(v) = select_response(p) {
(FileLocation::Library(PartKind::Primitive), v)
} else {
return Err(ResolutionError::FileNotFound);
}
};
let bytes = res.bytes().await?;
Ok((
location,
parse_multipart_document(&mut BufReader::new(&*bytes), colors).await?,
))
}
}
fn select_response(response: Result<Response, Error>) -> Option<Response> {
match response {
Ok(r) => {
if r.status() == StatusCode::OK {
Some(r)
} else {
None
}
}
Err(_) => None,
}
}
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
segfault87/ldraw.rs | https://github.com/segfault87/ldraw.rs/blob/50691a378e23210183a0ebbc84760d5cf5819b1b/ldraw/src/resolvers/mod.rs | ldraw/src/resolvers/mod.rs | #[cfg(any(target_arch = "wasm32", feature = "http"))]
pub mod http;
#[cfg(not(target_arch = "wasm32"))]
pub mod local;
| rust | MIT | 50691a378e23210183a0ebbc84760d5cf5819b1b | 2026-01-04T20:25:16.216619Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/lib.rs | crates/hwp-core/src/lib.rs | /// HWP Core Library
///
/// This library provides core functionality for parsing HWP files.
/// It accepts byte arrays as input to support cross-platform usage.
pub mod cfb;
pub mod decompress;
pub mod document;
pub mod error;
pub mod types;
pub mod viewer;
use ::cfb::CompoundFile;
use std::io::Cursor;
pub use cfb::CfbParser;
pub use decompress::{decompress_deflate, decompress_zlib};
pub use document::{
BinData, BinDataRecord, BodyText, BorderFill, Bullet, CharShape, DocInfo, DocumentProperties,
FaceName, FileHeader, HwpDocument, IdMappings, Numbering, ParaShape, Section,
SummaryInformation, TabDef,
};
pub use error::{CompressionFormat, HwpError};
pub use types::{
RecordHeader, BYTE, COLORREF, DWORD, HWPUNIT, HWPUNIT16, INT16, INT32, INT8, SHWPUNIT, UINT,
UINT16, UINT32, UINT8, WCHAR, WORD,
};
/// Main HWP parser structure
pub struct HwpParser {
// Placeholder for future implementation
}
impl HwpParser {
/// Create a new HWP parser
pub fn new() -> Self {
Self {}
}
/// Parse HWP file from byte array
///
/// # Arguments
/// * `data` - Byte array containing the HWP file data
///
/// # Returns
/// Parsed HWP document structure
pub fn parse(&self, data: &[u8]) -> Result<HwpDocument, HwpError> {
// Parse CFB structure
let mut cfb = CfbParser::parse(data)?;
// Parse required streams
let fileheader = self.parse_fileheader(&mut cfb)?;
let mut document = HwpDocument::new(fileheader.clone());
document.doc_info = self.parse_docinfo(&mut cfb, &fileheader)?;
document.body_text = self.parse_bodytext(&mut cfb, &fileheader, &document.doc_info)?;
document.bin_data = self.parse_bindata(&mut cfb, &document.doc_info)?;
// Parse optional streams
self.parse_optional_streams(&mut cfb, &fileheader, &mut document, data);
// Resolve derived display texts (e.g., AUTO_NUMBER in captions) for JSON/viewers.
document.resolve_display_texts();
Ok(document)
}
// ===== Required parsing methods =====
/// Parse FileHeader stream
fn parse_fileheader(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
) -> Result<FileHeader, HwpError> {
let fileheader_data = CfbParser::read_stream(cfb, "FileHeader")?;
FileHeader::parse(&fileheader_data).map_err(|e| error::HwpError::from(e))
}
/// Parse DocInfo stream
fn parse_docinfo(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
fileheader: &FileHeader,
) -> Result<DocInfo, HwpError> {
let docinfo_data = CfbParser::read_stream(cfb, "DocInfo")?;
DocInfo::parse(&docinfo_data, fileheader).map_err(|e| error::HwpError::from(e))
}
/// Parse BodyText storage
/// 구역 개수는 DocumentProperties의 area_count에서 가져옵니다 / Get section count from DocumentProperties.area_count
fn parse_bodytext(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
fileheader: &FileHeader,
doc_info: &DocInfo,
) -> Result<BodyText, HwpError> {
let section_count = doc_info
.document_properties
.as_ref()
.map(|props| props.area_count)
.unwrap_or(1); // 기본값은 1 / Default is 1
BodyText::parse(cfb, fileheader, section_count).map_err(|e| error::HwpError::from(e))
}
/// Parse BinData storage
/// 표 17의 bin_data_records를 사용하여 스트림을 찾습니다 (EMBEDDING/STORAGE 타입의 binary_data_id와 extension 사용)
/// Use bin_data_records from Table 17 to find streams (use binary_data_id and extension for EMBEDDING/STORAGE types)
fn parse_bindata(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
doc_info: &DocInfo,
) -> Result<BinData, HwpError> {
use crate::document::BinaryDataFormat;
BinData::parse(cfb, BinaryDataFormat::Base64, &doc_info.bin_data)
.map_err(|e| error::HwpError::from(e))
}
// ===== Optional parsing methods =====
/// Parse all optional streams (failures are logged but don't stop parsing)
fn parse_optional_streams(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
fileheader: &FileHeader,
document: &mut HwpDocument,
data: &[u8],
) {
self.parse_preview_text(cfb, document);
self.parse_preview_image(cfb, document);
self.parse_scripts(cfb, document);
self.parse_xml_template(cfb, fileheader, document);
self.parse_summary_information(cfb, document, data);
}
/// Parse PreviewText stream (optional)
/// 미리보기 텍스트 스트림 파싱 / Parse preview text stream
/// 스펙 문서 3.2.6: PrvText 스트림에는 미리보기 텍스트가 유니코드 문자열로 저장됩니다.
/// Spec 3.2.6: PrvText stream contains preview text stored as Unicode string.
fn parse_preview_text(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
document: &mut HwpDocument,
) {
if let Ok(prvtext_data) = CfbParser::read_stream(cfb, "PrvText") {
match crate::document::PreviewText::parse(&prvtext_data) {
Ok(preview_text) => {
document.preview_text = Some(preview_text);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse PrvText stream: {}", e);
}
}
}
}
/// Parse PreviewImage stream (optional)
/// 미리보기 이미지 스트림 파싱 / Parse preview image stream
/// 스펙 문서 3.2.7: PrvImage 스트림에는 미리보기 이미지가 BMP 또는 GIF 형식으로 저장됩니다.
/// Spec 3.2.7: PrvImage stream contains preview image stored as BMP or GIF format.
fn parse_preview_image(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
document: &mut HwpDocument,
) {
if let Ok(prvimage_data) = CfbParser::read_stream(cfb, "PrvImage") {
match crate::document::PreviewImage::parse(&prvimage_data, None) {
Ok(preview_image) => {
document.preview_image = Some(preview_image);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse PrvImage stream: {}", e);
}
}
}
}
/// Parse Scripts storage (optional)
/// 스크립트 스토리지 파싱 / Parse scripts storage
/// 스펙 문서 3.2.9: Scripts 스토리지에는 Script 코드가 저장됩니다.
/// Spec 3.2.9: Scripts storage contains Script code.
fn parse_scripts(&self, cfb: &mut CompoundFile<Cursor<&[u8]>>, document: &mut HwpDocument) {
match crate::document::Scripts::parse(cfb) {
Ok(scripts) => {
document.scripts = Some(scripts);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse Scripts storage: {}", e);
}
}
}
/// Parse XMLTemplate storage (optional)
/// XML 템플릿 스토리지 파싱 / Parse XML template storage
/// 스펙 문서 3.2.10: XMLTemplate 스토리지에는 XML Template 정보가 저장됩니다.
/// Spec 3.2.10: XMLTemplate storage contains XML Template information.
/// FileHeader의 document_flags Bit 5를 확인하여 XMLTemplate 스토리지 존재 여부 확인
/// Check FileHeader document_flags Bit 5 to determine if XMLTemplate storage exists
fn parse_xml_template(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
fileheader: &FileHeader,
document: &mut HwpDocument,
) {
if fileheader.has_xml_template() {
match crate::document::XmlTemplate::parse(cfb) {
Ok(xml_template) => {
// 모든 필드가 None이 아닌 경우에만 설정 / Only set if at least one field is not None
if xml_template.schema_name.is_some()
|| xml_template.schema.is_some()
|| xml_template.instance.is_some()
{
document.xml_template = Some(xml_template);
}
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse XMLTemplate storage: {}", e);
}
}
}
}
/// Parse SummaryInformation stream (optional)
/// 문서 요약 스트림 파싱 / Parse summary information stream
/// 스펙 문서 3.2.4: \005HwpSummaryInformation 스트림에는 문서 요약 정보가 MSDN Property Set 형식으로 저장됩니다.
/// Spec 3.2.4: \005HwpSummaryInformation stream contains document summary information stored in MSDN Property Set format.
/// 스트림 이름은 "\005HwpSummaryInformation" (바이트: 0x05 + "HwpSummaryInformation")
/// Stream name is "\005HwpSummaryInformation" (bytes: 0x05 + "HwpSummaryInformation")
fn parse_summary_information(
&self,
cfb: &mut CompoundFile<Cursor<&[u8]>>,
document: &mut HwpDocument,
data: &[u8],
) {
match Self::read_summary_information_stream(cfb, data) {
Ok(summary_bytes) => {
#[cfg(debug_assertions)]
{
eprintln!(
"Debug: Successfully read SummaryInformation stream, size: {} bytes",
summary_bytes.len()
);
if summary_bytes.len() >= 2 {
eprintln!(
"Debug: Byte order: 0x{:02X}{:02X}",
summary_bytes[0], summary_bytes[1]
);
}
}
match crate::document::SummaryInformation::parse(&summary_bytes) {
Ok(summary_information) => {
#[cfg(debug_assertions)]
eprintln!("Debug: Successfully parsed SummaryInformation");
document.summary_information = Some(summary_information);
}
Err(e) => {
#[cfg(debug_assertions)]
{
eprintln!("Warning: Failed to parse SummaryInformation stream: {}", e);
eprintln!(" Stream size: {} bytes", summary_bytes.len());
if summary_bytes.len() >= 40 {
eprintln!(" First 40 bytes: {:?}", &summary_bytes[..40]);
eprintln!(
" Byte order: 0x{:02X}{:02X}",
summary_bytes[0], summary_bytes[1]
);
eprintln!(
" Version: 0x{:02X}{:02X}",
summary_bytes[2], summary_bytes[3]
);
}
}
// 파싱 실패 시 None으로 유지 (raw_data 저장 안 함) / Keep None on parse failure (don't store raw_data)
}
}
}
Err(e) => {
#[cfg(debug_assertions)]
{
eprintln!("Warning: Failed to read SummaryInformation stream: {}", e);
eprintln!(" Tried: \\u{{0005}}HwpSummaryInformation, \\x05HwpSummaryInformation, HwpSummaryInformation");
}
// 스트림이 없으면 None으로 유지 (정상) / Keep None if stream doesn't exist (normal)
}
}
}
/// Try to read SummaryInformation stream with multiple name variations
/// 여러 가능한 스트림 이름 시도 / Try multiple possible stream names
/// CFB 라이브러리는 특수 문자를 포함한 스트림 이름을 처리할 수 있도록 바이트 배열로 변환 필요
/// CFB library may need byte array conversion for stream names with special characters
fn read_summary_information_stream(
cfb: &mut CompoundFile<Cursor<&[u8]>>,
data: &[u8],
) -> Result<Vec<u8>, HwpError> {
const STREAM_NAMES: &[&str] = &[
"\u{0005}HwpSummaryInformation",
"\x05HwpSummaryInformation",
"HwpSummaryInformation",
];
// Try string-based names first
for name in STREAM_NAMES {
match CfbParser::read_stream(cfb, name) {
Ok(stream_data) => return Ok(stream_data),
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Debug: Failed to read with {}: {}", name, e);
}
}
}
// If all string-based attempts fail, try parsing CFB bytes directly
// 모든 문자열 기반 시도가 실패하면 CFB 바이트를 직접 파싱 시도
#[cfg(debug_assertions)]
eprintln!("Debug: All string-based attempts failed, trying direct byte parsing for \\005HwpSummaryInformation");
let stream_name_bytes = b"\x05HwpSummaryInformation";
CfbParser::read_stream_by_bytes(data, stream_name_bytes)
}
/// Parse HWP file and return FileHeader as JSON
///
/// # Arguments
/// * `data` - Byte array containing the HWP file data
///
/// # Returns
/// FileHeader as JSON string
pub fn parse_fileheader_json(&self, data: &[u8]) -> Result<String, HwpError> {
// Parse CFB structure
let mut cfb = CfbParser::parse(data)?;
// Read and parse FileHeader
let fileheader_data = CfbParser::read_stream(&mut cfb, "FileHeader")?;
let fileheader =
FileHeader::parse(&fileheader_data).map_err(|e| error::HwpError::from(e))?;
// Convert to JSON
fileheader.to_json().map_err(|e| error::HwpError::from(e))
}
/// Parse HWP file and return SummaryInformation as JSON
///
/// # Arguments
/// * `data` - Byte array containing the HWP file data
///
/// # Returns
/// SummaryInformation as JSON string, or empty JSON object if not found
pub fn parse_summary_information_json(&self, data: &[u8]) -> Result<String, HwpError> {
// Parse CFB structure
let mut cfb = CfbParser::parse(data)?;
// Use the shared helper method to read the stream
match Self::read_summary_information_stream(&mut cfb, data) {
Ok(summary_bytes) => {
let summary_information =
crate::document::SummaryInformation::parse(&summary_bytes)
.map_err(|e| error::HwpError::from(e))?;
// Convert to JSON
serde_json::to_string_pretty(&summary_information).map_err(error::HwpError::from)
}
Err(_) => {
// 스트림이 없으면 빈 SummaryInformation을 JSON으로 반환
// If stream doesn't exist, return empty SummaryInformation as JSON
let empty_summary = crate::document::SummaryInformation::default();
serde_json::to_string_pretty(&empty_summary).map_err(error::HwpError::from)
}
}
}
}
impl Default for HwpParser {
fn default() -> Self {
Self::new()
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/cfb.rs | crates/hwp-core/src/cfb.rs | /// CFB (Compound File Binary) parsing module
///
/// This module handles parsing of CFB structures used in HWP files.
/// HWP 파일은 CFB 형식을 사용하여 여러 스토리지와 스트림을 포함합니다.
///
/// 스펙 문서 매핑: 표 2 - 파일 구조 (CFB 구조)
use crate::error::HwpError;
use cfb::CompoundFile;
use std::io::{Cursor, Read};
/// CFB parser for HWP files
/// HWP 파일용 CFB 파서
pub struct CfbParser;
impl CfbParser {
/// Parse CFB structure from byte array
/// 바이트 배열에서 CFB 구조를 파싱합니다.
///
/// # Arguments
/// * `data` - Byte array containing CFB file data / CFB 파일 데이터를 포함하는 바이트 배열
///
/// # Returns
/// Parsed CompoundFile structure / 파싱된 CompoundFile 구조체
pub fn parse(data: &[u8]) -> Result<CompoundFile<Cursor<&[u8]>>, HwpError> {
let cursor = Cursor::new(data);
CompoundFile::open(cursor).map_err(|e| HwpError::CfbParse(e.to_string()))
}
/// Read a stream from CFB structure (root level)
/// CFB 구조에서 스트림을 읽습니다 (루트 레벨).
///
/// # Arguments
/// * `cfb` - CompoundFile structure (mutable reference required) / CompoundFile 구조체 (가변 참조 필요)
/// * `stream_name` - Name of the stream to read / 읽을 스트림 이름
///
/// # Returns
/// Stream content as byte vector / 바이트 벡터로 된 스트림 내용
pub fn read_stream(
cfb: &mut CompoundFile<Cursor<&[u8]>>,
stream_name: &str,
) -> Result<Vec<u8>, HwpError> {
// Try to open stream with the given name
// 주어진 이름으로 스트림 열기 시도
match cfb.open_stream(stream_name) {
Ok(mut stream) => {
let mut buffer = Vec::new();
stream
.read_to_end(&mut buffer)
.map_err(|e| HwpError::stream_read_error(stream_name, e.to_string()))?;
Ok(buffer)
}
Err(_) => {
// If the stream name contains special characters (like \x05),
// cfb crate's open_stream may not handle it correctly.
// We need to parse CFB file bytes directly to find the stream.
// 스트림 이름에 특수 문자가 포함된 경우 (예: \x05),
// cfb crate의 open_stream이 이를 올바르게 처리하지 못할 수 있습니다.
// CFB 파일의 바이트를 직접 파싱하여 스트림을 찾아야 합니다.
Err(HwpError::stream_not_found(stream_name, "root"))
}
}
}
/// Read a stream by parsing CFB directory entries directly (for streams with special characters)
/// CFB 디렉토리 엔트리를 직접 파싱하여 스트림 읽기 (특수 문자가 포함된 스트림용)
///
/// # Arguments
/// * `data` - Original CFB file data / 원본 CFB 파일 데이터
/// * `stream_name_bytes` - Stream name as bytes (UTF-16LE encoded) / 바이트로 된 스트림 이름 (UTF-16LE 인코딩)
///
/// # Returns
/// Stream content as byte vector / 바이트 벡터로 된 스트림 내용
pub fn read_stream_by_bytes(
data: &[u8],
stream_name_bytes: &[u8],
) -> Result<Vec<u8>, HwpError> {
#[cfg(debug_assertions)]
eprintln!(
"Debug: read_stream_by_bytes called, data len: {}, stream_name: {:?}",
data.len(),
stream_name_bytes
);
if data.len() < 512 {
return Err(HwpError::CfbFileTooSmall {
expected: 512,
actual: data.len(),
});
}
// CFB Header structure (first 512 bytes)
// CFB 헤더 구조 (처음 512 바이트)
// Sector size is usually 512 bytes, but can be different
// 섹터 크기는 보통 512 바이트이지만 다를 수 있음
// Read sector size from header (offset 0x1E, 2 bytes)
// 헤더에서 섹터 크기 읽기 (오프셋 0x1E, 2 바이트)
let sector_size = if data.len() >= 0x20 {
let sector_size_shift = u16::from_le_bytes([data[0x1E], data[0x1F]]) as u32;
if sector_size_shift > 12 {
return Err(HwpError::InvalidSectorSize {
value: sector_size_shift,
});
}
1 << sector_size_shift // Usually 512 (2^9)
} else {
512 // Default
};
// Read directory sector location (offset 0x30, 4 bytes)
// 디렉토리 섹터 위치 읽기 (오프셋 0x30, 4 바이트)
let dir_sector = if data.len() >= 0x34 {
u32::from_le_bytes([data[0x30], data[0x31], data[0x32], data[0x33]])
} else {
return Err(HwpError::CfbFileTooSmall {
expected: 0x34,
actual: data.len(),
});
};
// Convert stream name to UTF-16LE bytes for comparison
// 스트림 이름을 UTF-16LE 바이트로 변환하여 비교
// CFB directory entries store names as UTF-16LE (2 bytes per character)
// CFB 디렉토리 엔트리는 이름을 UTF-16LE로 저장 (문자당 2 바이트)
// The name length field stores the UTF-16LE character count (including null terminator)
// 이름 길이 필드는 UTF-16LE 문자 개수를 저장 (null 종료 문자 포함)
let mut stream_name_utf16 = Vec::new();
for &b in stream_name_bytes {
stream_name_utf16.push(b);
stream_name_utf16.push(0); // UTF-16LE: each ASCII char is 2 bytes (low byte, high byte=0)
}
// Null terminator (2 bytes for UTF-16LE)
// 널 종료 문자 (UTF-16LE는 2 바이트)
stream_name_utf16.push(0);
stream_name_utf16.push(0);
// Expected name length in UTF-16LE characters (including null terminator)
// 예상되는 UTF-16LE 문자 개수 (null 종료 문자 포함)
let expected_name_length = (stream_name_utf16.len() / 2) as u16;
#[cfg(debug_assertions)]
eprintln!(
"Debug: Stream name UTF-16LE: {:?} (first 20 bytes)",
&stream_name_utf16[..20.min(stream_name_utf16.len())]
);
// Read directory entries
// 디렉토리 엔트리 읽기
// Each directory entry is 128 bytes
// 각 디렉토리 엔트리는 128 바이트
// Directory entries are stored in sectors
// 디렉토리 엔트리는 섹터에 저장됨
// CFB structure: Header (512 bytes) + Sectors
// CFB 구조: 헤더 (512 바이트) + 섹터들
// First sector starts at offset = sector_size (usually 512)
// 첫 번째 섹터는 오프셋 = sector_size (보통 512)부터 시작
// Directory sector number is 0-indexed, so:
// 디렉토리 섹터 번호는 0부터 시작하므로:
// dir_start = sector_size + (dir_sector * sector_size)
// But if dir_sector is -1 (ENDOFCHAIN), it means no directory
// 하지만 dir_sector가 -1 (ENDOFCHAIN)이면 디렉토리가 없음
let dir_entry_size = 128;
let dir_start = if dir_sector == 0xFFFFFFFF {
return Err(HwpError::InvalidDirectorySector {
reason: "ENDOFCHAIN marker found".to_string(),
});
} else {
(sector_size as usize) + (dir_sector as usize * sector_size as usize)
};
#[cfg(debug_assertions)]
eprintln!(
"Debug: dir_sector: {}, sector_size: {}, dir_start: {}",
dir_sector, sector_size, dir_start
);
if dir_start >= data.len() {
return Err(HwpError::InvalidDirectorySector {
reason: format!(
"Directory sector offset {} is beyond file size {}",
dir_start,
data.len()
),
});
}
#[cfg(debug_assertions)]
eprintln!(
"Debug: Searching directory entries, dir_start: {}, sector_size: {}",
dir_start, sector_size
);
// Search through directory entries (max 128 entries per sector)
// 디렉토리 엔트리 검색 (섹터당 최대 128 엔트리)
for i in 0..128 {
let entry_offset = dir_start + (i * dir_entry_size);
if entry_offset + dir_entry_size > data.len() {
break;
}
// Read entry name length (first 2 bytes, UTF-16LE character count)
// 엔트리 이름 길이 읽기 (처음 2 바이트, UTF-16LE 문자 개수)
let name_length =
u16::from_le_bytes([data[entry_offset], data[entry_offset + 1]]) as usize;
// Check if entry is empty (name_length == 0 or invalid)
// 엔트리가 비어있는지 확인 (name_length == 0 또는 유효하지 않음)
if name_length == 0 || name_length > 32 {
continue; // Skip empty or invalid entries
}
// Read entry name (UTF-16LE, up to 64 bytes = 32 characters)
// 엔트리 이름 읽기 (UTF-16LE, 최대 64 바이트 = 32 문자)
// Name is stored as UTF-16LE, so actual byte length is name_length * 2
// 이름은 UTF-16LE로 저장되므로 실제 바이트 길이는 name_length * 2
let name_byte_length = name_length * 2;
let name_start = entry_offset + 2; // Skip length field
let name_end = name_start + name_byte_length.min(64);
let entry_name_bytes = &data[name_start..name_end];
// Pad entry_name_bytes to 64 bytes for comparison
// 비교를 위해 entry_name_bytes를 64 바이트로 패딩
let mut entry_name = [0u8; 64];
entry_name[..entry_name_bytes.len().min(64)]
.copy_from_slice(&entry_name_bytes[..entry_name_bytes.len().min(64)]);
// Check entry type (offset 66 from entry start, 1 byte)
// 엔트리 타입 확인 (엔트리 시작부터 오프셋 66, 1 바이트)
let entry_type = data[entry_offset + 66];
// Check if entry name starts with our stream name (for debugging)
// 디버깅을 위해 엔트리 이름이 스트림 이름으로 시작하는지 확인
#[cfg(debug_assertions)]
if i < 20 || entry_type == 2 {
let name_str = String::from_utf16_lossy(
&entry_name_bytes
.chunks(2)
.take_while(|chunk| chunk.len() == 2 && (chunk[0] != 0 || chunk[1] != 0))
.map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
.collect::<Vec<_>>(),
);
eprintln!(
"Debug: Entry {} type: {}, name_length: {}, name: {:?} (bytes: {:?})",
i,
entry_type,
name_length,
name_str,
&entry_name_bytes[..20.min(entry_name_bytes.len())]
);
}
// Compare names byte-by-byte
// 바이트 단위로 이름 비교
// Compare the actual name bytes
// 실제 이름 바이트 비교
// Check if name length matches and bytes match
// 이름 길이가 일치하고 바이트가 일치하는지 확인
let name_matches = name_length == expected_name_length as usize
&& entry_name_bytes.len() >= stream_name_utf16.len()
&& entry_name_bytes[..stream_name_utf16.len()] == stream_name_utf16[..];
if name_matches {
#[cfg(debug_assertions)]
eprintln!(
"Debug: Found matching entry at index {} (type: {})",
i, entry_type
);
// Found matching entry, check if it's a stream (type = 2)
// 일치하는 엔트리를 찾았으므로 스트림인지 확인 (타입 = 2)
if entry_type != 2 {
#[cfg(debug_assertions)]
eprintln!(
"Debug: Entry is not a stream (type: {}), continuing...",
entry_type
);
// Not a stream
continue;
}
// Read starting sector (offset 116, 4 bytes)
// 시작 섹터 읽기 (오프셋 116, 4 바이트)
let start_sector = u32::from_le_bytes([
data[entry_offset + 116],
data[entry_offset + 117],
data[entry_offset + 118],
data[entry_offset + 119],
]);
// Read stream size (offset 120, 4 bytes for small streams, 8 bytes for large)
// 스트림 크기 읽기 (오프셋 120, 작은 스트림은 4 바이트, 큰 스트림은 8 바이트)
let stream_size = u32::from_le_bytes([
data[entry_offset + 120],
data[entry_offset + 121],
data[entry_offset + 122],
data[entry_offset + 123],
]) as usize;
if stream_size == 0 {
return Ok(Vec::new());
}
// Read stream data
// 스트림 데이터 읽기
let stream_start = (start_sector as usize + 1) * (sector_size as usize);
if stream_start + stream_size > data.len() {
return Err(HwpError::InvalidDirectorySector {
reason: format!(
"Stream data offset {} + size {} is beyond file size {}",
stream_start,
stream_size,
data.len()
),
});
}
return Ok(data[stream_start..stream_start + stream_size].to_vec());
}
}
Err(HwpError::stream_not_found(
String::from_utf8_lossy(stream_name_bytes),
"root (byte search)",
))
}
/// Read a stream from nested storage (e.g., BodyText/Section0)
/// 중첩된 스토리지에서 스트림을 읽습니다 (예: BodyText/Section0).
///
/// # Arguments
/// * `cfb` - CompoundFile structure (mutable reference required) / CompoundFile 구조체 (가변 참조 필요)
/// * `storage_name` - Name of the storage (e.g., "BodyText") / 스토리지 이름 (예: "BodyText")
/// * `stream_name` - Name of the stream within the storage (e.g., "Section0") / 스토리지 내 스트림 이름 (예: "Section0")
///
/// # Returns
/// Stream content as byte vector / 바이트 벡터로 된 스트림 내용
pub fn read_nested_stream(
cfb: &mut CompoundFile<Cursor<&[u8]>>,
storage_name: &str,
stream_name: &str,
) -> Result<Vec<u8>, HwpError> {
// First, try to open the storage and then the stream
// If open_storage is not available, fall back to path-based approach
// 먼저 스토리지를 열고 그 안에서 스트림을 열려고 시도합니다.
// open_storage를 사용할 수 없는 경우 경로 기반 접근 방식으로 폴백합니다.
let path = format!("{}/{}", storage_name, stream_name);
// Try path-based approach first (most CFB libraries support this)
// 먼저 경로 기반 접근 방식을 시도합니다 (대부분의 CFB 라이브러리가 이를 지원합니다).
match cfb.open_stream(&path) {
Ok(mut stream) => {
let mut buffer = Vec::new();
stream
.read_to_end(&mut buffer)
.map_err(|e| HwpError::stream_read_error(&path, e.to_string()))?;
Ok(buffer)
}
Err(_) => {
// Fallback: try with "Root Entry/" prefix (hwp.js style)
// 폴백: "Root Entry/" 접두사를 사용하여 시도합니다 (hwp.js 스타일).
let root_path = format!("Root Entry/{}/{}", storage_name, stream_name);
match cfb.open_stream(&root_path) {
Ok(mut stream) => {
let mut buffer = Vec::new();
stream
.read_to_end(&mut buffer)
.map_err(|e| HwpError::stream_read_error(&root_path, e.to_string()))?;
Ok(buffer)
}
Err(e) => Err(HwpError::stream_not_found(
format!("{}/{}", storage_name, stream_name),
format!("Tried '{}' and '{}', last error: {}", path, root_path, e),
)),
}
}
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/error.rs | crates/hwp-core/src/error.rs | /// Error types for HWP file parsing
///
/// This module defines all error types that can occur during HWP file parsing.
use thiserror::Error;
/// Main error type for HWP parsing operations
#[derive(Debug, Clone, Error)]
pub enum HwpError {
// ===== CFB related errors =====
/// Failed to parse CFB structure
#[error("Failed to parse CFB structure: {0}")]
CfbParse(String),
/// Stream not found in CFB structure
#[error("Stream not found: '{stream_name}' (path: {path})")]
StreamNotFound { stream_name: String, path: String },
/// Failed to read stream from CFB
#[error("Failed to read stream '{stream_name}': {reason}")]
StreamReadError { stream_name: String, reason: String },
/// CFB file is too small
#[error("CFB file too small: expected at least {expected} bytes, got {actual} bytes")]
CfbFileTooSmall { expected: usize, actual: usize },
/// Invalid directory sector in CFB
#[error("Invalid CFB directory sector: {reason}")]
InvalidDirectorySector { reason: String },
/// Invalid sector size in CFB header
#[error("Invalid sector size shift: {value} (must be <= 12)")]
InvalidSectorSize { value: u32 },
// ===== Decompression errors =====
/// Failed to decompress data
#[error("Failed to decompress {format} data: {reason}")]
DecompressError {
format: CompressionFormat,
reason: String,
},
// ===== Parsing errors =====
/// Insufficient data for parsing
#[error("Insufficient data for field '{field}': expected at least {expected} bytes, got {actual} bytes")]
InsufficientData {
field: String,
expected: usize,
actual: usize,
},
/// Unexpected value encountered during parsing
#[error("Unexpected value for field '{field}': expected '{expected}', got '{found}'")]
UnexpectedValue {
field: String,
expected: String,
found: String,
},
/// Failed to parse a record
#[error("Failed to parse record '{record_type}': {reason}")]
RecordParseError { record_type: String, reason: String },
/// Failed to parse record tree structure
#[error("Failed to parse record tree: {reason}")]
RecordTreeParseError { reason: String },
// ===== Document structure errors =====
/// Required stream is missing
#[error("Required stream missing: '{stream_name}'")]
RequiredStreamMissing { stream_name: String },
/// Unsupported document version
#[error("Unsupported document version: {version} (supported versions: {supported_versions})")]
UnsupportedVersion {
version: String,
supported_versions: String,
},
/// Invalid document signature
#[error("Invalid HWP document signature: expected 'HWP Document File', got '{found}'")]
InvalidSignature { found: String },
// ===== Other errors =====
/// IO error
#[error("IO error: {0}")]
Io(String),
/// Encoding/decoding error
#[error("Encoding error: {reason}")]
EncodingError { reason: String },
/// JSON serialization error
#[error("JSON serialization error: {0}")]
JsonError(String),
/// Internal error (unexpected situation)
#[error("Internal error: {message}")]
InternalError { message: String },
}
/// Compression format type
#[derive(Debug, Clone, Copy)]
pub enum CompressionFormat {
Zlib,
Deflate,
}
impl std::fmt::Display for CompressionFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CompressionFormat::Zlib => write!(f, "zlib"),
CompressionFormat::Deflate => write!(f, "deflate"),
}
}
}
/// Type alias for `Result<T, HwpError>`
///
/// Note: For better clarity in function signatures, consider using `Result<T, HwpError>` directly
/// to make the error type explicit. This type alias is kept for backward compatibility.
pub type HwpResult<T> = Result<T, HwpError>;
impl HwpError {
/// Create an `InsufficientData` error with field name
pub fn insufficient_data(field: impl Into<String>, expected: usize, actual: usize) -> Self {
Self::InsufficientData {
field: field.into(),
expected,
actual,
}
}
/// Create a `StreamNotFound` error
pub fn stream_not_found(stream_name: impl Into<String>, path: impl Into<String>) -> Self {
Self::StreamNotFound {
stream_name: stream_name.into(),
path: path.into(),
}
}
/// Create a `StreamReadError` error
pub fn stream_read_error(stream_name: impl Into<String>, reason: impl Into<String>) -> Self {
Self::StreamReadError {
stream_name: stream_name.into(),
reason: reason.into(),
}
}
/// Create a `RecordParseError` error
pub fn record_parse(record_type: impl Into<String>, reason: impl Into<String>) -> Self {
Self::RecordParseError {
record_type: record_type.into(),
reason: reason.into(),
}
}
/// Create a `DecompressError` error
pub fn decompress_error(format: CompressionFormat, reason: impl Into<String>) -> Self {
Self::DecompressError {
format,
reason: reason.into(),
}
}
}
/// Conversion from String to HwpError for backward compatibility
impl From<String> for HwpError {
fn from(s: String) -> Self {
HwpError::InternalError { message: s }
}
}
/// Conversion from &str to HwpError for backward compatibility
impl From<&str> for HwpError {
fn from(s: &str) -> Self {
HwpError::InternalError {
message: s.to_string(),
}
}
}
/// Conversion from std::io::Error to HwpError
impl From<std::io::Error> for HwpError {
fn from(err: std::io::Error) -> Self {
HwpError::Io(err.to_string())
}
}
/// Conversion from serde_json::Error to HwpError
impl From<serde_json::Error> for HwpError {
fn from(err: serde_json::Error) -> Self {
HwpError::JsonError(err.to_string())
}
}
/// Conversion from HwpError to String for NAPI and other integrations
/// This allows HwpError to be used with napi::Error::from_reason
impl From<HwpError> for String {
fn from(err: HwpError) -> Self {
err.to_string()
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/types.rs | crates/hwp-core/src/types.rs | /// HWP 5.0 자료형 정의
///
/// 표 1: 자료형에 따른 타입 정의
/// 스펙 문서와 1:1 매핑을 위해 모든 자료형을 명시적으로 정의합니다.
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// 소수점 2자리로 반올림하는 trait
pub trait RoundTo2dp {
/// 소수점 2자리로 반올림
fn round_to_2dp(self) -> f64;
}
impl RoundTo2dp for f64 {
fn round_to_2dp(self) -> f64 {
(self * 100.0).round() / 100.0
}
}
/// BYTE: 부호 없는 한 바이트(0~255)
pub type BYTE = u8;
/// WORD: 16비트 unsigned int
pub type WORD = u16;
/// DWORD: 32비트 unsigned long
pub type DWORD = u32;
/// WCHAR: 유니코드 기반 문자 (2바이트)
/// 한글의 내부 코드로 표현된 문자 한 글자
pub type WCHAR = u16;
/// HWPUNIT: 1/7200인치 단위 (unsigned)
/// 문자의 크기, 그림의 크기, 용지 여백 등 문서 구성 요소의 크기를 표현
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HWPUNIT(pub u32);
impl HWPUNIT {
/// 인치 단위로 변환
pub fn to_inches(self) -> f64 {
self.0 as f64 / 7200.0
}
/// 밀리미터 단위로 변환
pub fn to_mm(self) -> f64 {
self.to_inches() * 25.4
}
/// 인치 단위에서 생성
pub fn from_inches(inches: f64) -> Self {
Self((inches * 7200.0) as u32)
}
/// 밀리미터 단위에서 생성
pub fn from_mm(mm: f64) -> Self {
Self::from_inches(mm / 25.4)
}
/// 내부 값 반환
pub fn value(self) -> u32 {
self.0
}
}
impl From<u32> for HWPUNIT {
fn from(value: u32) -> Self {
Self(value)
}
}
impl From<HWPUNIT> for u32 {
fn from(value: HWPUNIT) -> Self {
value.0
}
}
/// SHWPUNIT: 1/7200인치 단위 (signed)
/// HWPUNIT의 부호 있는 버전
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SHWPUNIT(pub i32);
impl SHWPUNIT {
/// 인치 단위로 변환
pub fn to_inches(self) -> f64 {
self.0 as f64 / 7200.0
}
/// 밀리미터 단위로 변환
pub fn to_mm(self) -> f64 {
self.to_inches() * 25.4
}
/// 인치 단위에서 생성
pub fn from_inches(inches: f64) -> Self {
Self((inches * 7200.0) as i32)
}
/// 밀리미터 단위에서 생성
pub fn from_mm(mm: f64) -> Self {
Self::from_inches(mm / 25.4)
}
/// 내부 값 반환
pub fn value(self) -> i32 {
self.0
}
}
impl From<i32> for SHWPUNIT {
fn from(value: i32) -> Self {
Self(value)
}
}
impl From<SHWPUNIT> for i32 {
fn from(value: SHWPUNIT) -> Self {
value.0
}
}
/// HWPUNIT16 (i16)에 대한 변환 메서드 제공 / Conversion methods for HWPUNIT16 (i16)
pub trait Hwpunit16ToMm {
/// 밀리미터 단위로 변환 / Convert to millimeters
fn to_mm(self) -> f64;
}
impl Hwpunit16ToMm for i16 {
fn to_mm(self) -> f64 {
(self as f64 / 7200.0) * 25.4
}
}
/// COLORREF: BGR 형식 (0x00bbggrr)
/// 스펙 문서: RGB값(0x00bbggrr) - 실제로는 BGR 순서로 저장됨
/// Spec: RGB value (0x00bbggrr) - actually stored in BGR order
/// rr: red 1 byte (하위 바이트), gg: green 1 byte (중간 바이트), bb: blue 1 byte (상위 바이트)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct COLORREF(pub u32);
impl COLORREF {
/// RGB 값으로 생성
pub fn rgb(r: u8, g: u8, b: u8) -> Self {
Self((b as u32) << 16 | (g as u32) << 8 | r as u32)
}
/// Red 값 추출
pub fn r(self) -> u8 {
(self.0 & 0xFF) as u8
}
/// Green 값 추출
pub fn g(self) -> u8 {
((self.0 >> 8) & 0xFF) as u8
}
/// Blue 값 추출
pub fn b(self) -> u8 {
((self.0 >> 16) & 0xFF) as u8
}
/// 내부 값 반환
pub fn value(self) -> u32 {
self.0
}
}
impl From<u32> for COLORREF {
fn from(value: u32) -> Self {
Self(value)
}
}
impl From<COLORREF> for u32 {
fn from(value: COLORREF) -> Self {
value.0
}
}
// COLORREF를 RGB 형태로 JSON 직렬화 / Serialize COLORREF as RGB object in JSON
impl Serialize for COLORREF {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("COLORREF", 3)?;
state.serialize_field("r", &self.r())?;
state.serialize_field("g", &self.g())?;
state.serialize_field("b", &self.b())?;
state.end()
}
}
// JSON에서 RGB 형태로 역직렬화 / Deserialize COLORREF from RGB object in JSON
impl<'de> Deserialize<'de> for COLORREF {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{self, MapAccess, Visitor};
use std::fmt;
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
R,
G,
B,
}
struct COLORREFVisitor;
impl<'de> Visitor<'de> for COLORREFVisitor {
type Value = COLORREF;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct COLORREF with r, g, b fields")
}
fn visit_map<V>(self, mut map: V) -> Result<COLORREF, V::Error>
where
V: MapAccess<'de>,
{
let mut r = None;
let mut g = None;
let mut b = None;
while let Some(key) = map.next_key()? {
match key {
Field::R => {
if r.is_some() {
return Err(de::Error::duplicate_field("r"));
}
r = Some(map.next_value()?);
}
Field::G => {
if g.is_some() {
return Err(de::Error::duplicate_field("g"));
}
g = Some(map.next_value()?);
}
Field::B => {
if b.is_some() {
return Err(de::Error::duplicate_field("b"));
}
b = Some(map.next_value()?);
}
}
}
let r = r.ok_or_else(|| de::Error::missing_field("r"))?;
let g = g.ok_or_else(|| de::Error::missing_field("g"))?;
let b = b.ok_or_else(|| de::Error::missing_field("b"))?;
Ok(COLORREF::rgb(r, g, b))
}
}
deserializer.deserialize_map(COLORREFVisitor)
}
}
/// UINT8: unsigned int8
pub type UINT8 = u8;
/// UINT16: unsigned int16
pub type UINT16 = u16;
/// UINT32: unsigned int32
pub type UINT32 = u32;
/// UINT: UINT32와 동일
pub type UINT = UINT32;
/// INT8: signed int8
pub type INT8 = i8;
/// INT16: signed int16
pub type INT16 = i16;
/// INT32: signed int32
pub type INT32 = i32;
/// HWPUNIT16: INT16과 같음
pub type HWPUNIT16 = i16;
/// 레코드 헤더 파싱 결과 / Record header parsing result
///
/// 스펙 문서 매핑: 그림 45 - 레코드 구조 / Spec mapping: Figure 45 - Record structure
/// 레코드 헤더는 32비트로 구성되며 Tag ID (10 bits), Level (10 bits), Size (12 bits)를 포함합니다.
/// Record header is 32 bits consisting of Tag ID (10 bits), Level (10 bits), Size (12 bits).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecordHeader {
/// Tag ID (10 bits, 0x000-0x3FF)
pub tag_id: u16,
/// Level (10 bits)
pub level: u16,
/// Size (12 bits, 또는 확장 길이) / Size (12 bits, or extended length)
pub size: u32,
/// 확장 길이를 사용하는지 여부 (Size가 0xFFF인 경우) / Whether extended size is used (when Size is 0xFFF)
pub has_extended_size: bool,
}
impl RecordHeader {
/// 레코드 헤더를 파싱합니다. / Parse record header.
///
/// # Arguments
/// * `data` - 최소 4바이트의 데이터 (레코드 헤더) / At least 4 bytes of data (record header)
///
/// # Returns
/// 파싱된 RecordHeader와 다음 데이터 위치로 이동할 바이트 수 (헤더 크기) / Parsed RecordHeader and number of bytes to advance (header size)
pub fn parse(data: &[u8]) -> Result<(Self, usize), HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("RecordHeader", 4, data.len()));
}
// DWORD를 little-endian으로 읽기 / Read DWORD as little-endian
let header_value = DWORD::from_le_bytes([data[0], data[1], data[2], data[3]]);
// Tag ID: bits 0-9 (10 bits)
let tag_id = (header_value & 0x3FF) as u16;
// Level: bits 10-19 (10 bits)
let level = ((header_value >> 10) & 0x3FF) as u16;
// Size: bits 20-31 (12 bits)
let size = (header_value >> 20) & 0xFFF;
let (size, has_extended_size, header_size) = if size == 0xFFF {
// 확장 길이 사용: 다음 DWORD가 실제 길이 / Extended size: next DWORD is actual length
if data.len() < 8 {
return Err(HwpError::insufficient_data(
"RecordHeader (extended)",
8,
data.len(),
));
}
let extended_size = DWORD::from_le_bytes([data[4], data[5], data[6], data[7]]);
(extended_size, true, 8)
} else {
(size, false, 4)
};
Ok((
RecordHeader {
tag_id,
level,
size,
has_extended_size,
},
header_size,
))
}
}
/// UTF-16LE 바이트 배열을 String으로 디코딩 / Decode UTF-16LE byte array to String
pub fn decode_utf16le(bytes: &[u8]) -> Result<String, HwpError> {
use crate::error::HwpError;
if bytes.len() % 2 != 0 {
return Err(HwpError::EncodingError {
reason: "UTF-16LE bytes must be even length".to_string(),
});
}
let u16_chars: Vec<u16> = bytes
.chunks_exact(2)
.map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
.collect();
String::from_utf16(&u16_chars).map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode UTF-16LE string: {}", e),
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/decompress.rs | crates/hwp-core/src/decompress.rs | /// Decompression module for HWP files
///
/// This module handles zlib/deflate decompression used in HWP 5.0 files.
/// HWP files use raw deflate format (windowBits: -15) for DocInfo and BodyText streams.
use crate::error::{CompressionFormat, HwpError};
use flate2::read::{DeflateDecoder, ZlibDecoder};
use std::io::Read;
/// Decompress zlib-compressed data (with zlib header)
///
/// # Arguments
/// * `compressed_data` - Compressed byte array in zlib format (RFC 1950)
///
/// # Returns
/// Decompressed byte vector
pub fn decompress_zlib(compressed_data: &[u8]) -> Result<Vec<u8>, HwpError> {
let mut decoder = ZlibDecoder::new(compressed_data);
let mut decompressed = Vec::new();
decoder
.read_to_end(&mut decompressed)
.map_err(|e| HwpError::decompress_error(CompressionFormat::Zlib, e.to_string()))?;
Ok(decompressed)
}
/// Decompress raw deflate data (without zlib header, windowBits: -15)
///
/// HWP DocInfo and BodyText streams use raw deflate format.
/// This is equivalent to pako's inflate with windowBits: -15.
///
/// # Arguments
/// * `compressed_data` - Compressed byte array in raw deflate format
///
/// # Returns
/// Decompressed byte vector
pub fn decompress_deflate(compressed_data: &[u8]) -> Result<Vec<u8>, HwpError> {
let mut decoder = DeflateDecoder::new(compressed_data);
let mut decompressed = Vec::new();
decoder
.read_to_end(&mut decompressed)
.map_err(|e| HwpError::decompress_error(CompressionFormat::Deflate, e.to_string()))?;
Ok(decompressed)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/mod.rs | crates/hwp-core/src/viewer/mod.rs | /// Viewer module for converting HWP documents to various formats
/// HWP 문서를 다양한 형식으로 변환하는 뷰어 모듈
///
/// This module provides functionality to convert parsed HWP documents
/// into different output formats like Markdown, HTML, Canvas, PDF, etc.
/// 이 모듈은 파싱된 HWP 문서를 마크다운, HTML, Canvas, PDF 등 다양한 출력 형식으로 변환하는 기능을 제공합니다.
pub mod core;
pub mod markdown;
pub mod html;
#[allow(missing_docs)] // TODO: Implement Canvas viewer
pub mod canvas;
#[allow(missing_docs)] // TODO: Implement PDF viewer
pub mod pdf;
pub use markdown::{to_markdown, MarkdownOptions};
pub use html::{to_html, HtmlOptions};
pub use core::renderer::{DocumentParts, Renderer, TextStyles};
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/pdf/mod.rs | crates/hwp-core/src/viewer/pdf/mod.rs | //! PDF converter for HWP documents
//! HWP 문서를 PDF로 변환하는 모듈
//!
//! This module provides functionality to convert HWP documents to PDF format.
//! PDF output can be used for printing, archiving, or document distribution.
//! 이 모듈은 HWP 문서를 PDF 형식으로 변환하는 기능을 제공합니다.
//! PDF 출력은 인쇄, 보관, 문서 배포에 사용할 수 있습니다.
//!
//! # Status / 상태
//! This module is planned for future implementation.
//! 이 모듈은 향후 구현 예정입니다.
// TODO: Implement PDF viewer
// TODO: PDF 뷰어 구현
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/canvas/mod.rs | crates/hwp-core/src/viewer/canvas/mod.rs | //! Canvas converter for HWP documents
//! HWP 문서를 Canvas로 변환하는 모듈
//!
//! This module provides functionality to convert HWP documents to Canvas format.
//! Canvas output can be used for rendering in web browsers or exporting as images.
//! 이 모듈은 HWP 문서를 Canvas 형식으로 변환하는 기능을 제공합니다.
//! Canvas 출력은 웹 브라우저에서 렌더링하거나 이미지로 내보내는 데 사용할 수 있습니다.
//!
//! # Status / 상태
//! This module is planned for future implementation.
//! 이 모듈은 향후 구현 예정입니다.
// TODO: Implement Canvas viewer
// TODO: Canvas 뷰어 구현
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/page.rs | crates/hwp-core/src/viewer/html/page.rs | use crate::document::bodytext::ctrl_header::{CtrlHeaderData, PageNumberPosition};
use crate::document::HwpDocument;
use crate::types::RoundTo2dp;
use crate::{document::bodytext::PageDef, INT32};
/// 페이지 렌더링 모듈 / Page rendering module
/// 페이지를 HTML로 렌더링 / Render page to HTML
pub fn render_page(
page_number: usize,
content: &str,
tables: &[String],
page_def: Option<&PageDef>,
_first_segment_pos: Option<(INT32, INT32)>,
hcd_position: Option<(f64, f64)>,
page_number_position: Option<&CtrlHeaderData>,
page_start_number: u16,
document: &HwpDocument,
) -> String {
let width_mm = page_def
.map(|pd| pd.paper_width.to_mm().round_to_2dp())
.unwrap_or(210.0); // A4 기본값 / A4 default
let height_mm = page_def
.map(|pd| pd.paper_height.to_mm().round_to_2dp())
.unwrap_or(297.0); // A4 기본값 / A4 default
// hcD 위치: PageDef 여백을 직접 사용 / hcD position: use PageDef margins directly
let (left_mm, top_mm) = if let Some((left, top)) = hcd_position {
(left.round_to_2dp(), top.round_to_2dp())
} else {
// hcd_position이 없으면 PageDef 여백 사용 / Use PageDef margins if hcd_position not available
let left = page_def
.map(|pd| (pd.left_margin.to_mm() + pd.binding_margin.to_mm()).round_to_2dp())
.unwrap_or(20.0);
let top = page_def
.map(|pd| (pd.top_margin.to_mm() + pd.header_margin.to_mm()).round_to_2dp())
.unwrap_or(24.99);
(left, top)
};
// 일반 내용은 hcD > hcI 안에 배치 / Place regular content in hcD > hcI
let mut html = format!(
r#"<div class="hpa" style="width:{}mm;height:{}mm;">"#,
width_mm, height_mm
);
if !content.is_empty() {
html.push_str(&format!(
r#"<div class="hcD" style="left:{}mm;top:{}mm;"><div class="hcI">{}</div></div>"#,
left_mm, top_mm, content
));
}
// 테이블은 hpa 레벨에 직접 배치 / Place tables directly at hpa level
for table_html in tables {
html.push_str(table_html);
}
// 쪽번호 렌더링 / Render page number
if let Some(CtrlHeaderData::PageNumberPosition {
flags,
prefix,
suffix,
..
}) = page_number_position
{
if flags.position != PageNumberPosition::None {
let actual_page_number = (page_start_number as usize + page_number - 1).to_string();
// prefix/suffix에서 null 문자 제거 (null 문자는 빈 문자열로 처리) / Remove null characters from prefix/suffix (treat null as empty string)
let prefix_clean: String = prefix.chars().filter(|c| *c != '\0').collect();
let suffix_clean: String = suffix.chars().filter(|c| *c != '\0').collect();
let page_number_text =
format!("{}{}{}", prefix_clean, actual_page_number, suffix_clean);
// 페이지 크기 계산 / Calculate page size
let page_width_mm = page_def
.map(|pd| pd.paper_width.to_mm().round_to_2dp())
.unwrap_or(210.0);
let page_height_mm = page_def
.map(|pd| pd.paper_height.to_mm().round_to_2dp())
.unwrap_or(297.0);
// 쪽번호 위치 계산 (PageDef의 여백 정보 사용) / Calculate page number position (using PageDef margin information)
let (left_mm, top_mm) = match flags.position {
PageNumberPosition::BottomCenter => {
// 하단 중앙: 페이지 너비의 중앙, 하단 여백 기준 / Bottom center: center of page width, based on bottom margin
let left = (page_width_mm / 2.0).round_to_2dp();
let top = page_def
.map(|pd| {
// 페이지 높이 - 아래 여백 / Page height - bottom margin
(page_height_mm - pd.bottom_margin.to_mm()).round_to_2dp()
})
.unwrap_or_else(|| (page_height_mm - 10.0).round_to_2dp());
(left, top)
}
PageNumberPosition::BottomLeft => {
// 하단 왼쪽 / Bottom left
let left = page_def
.map(|pd| {
(pd.left_margin.to_mm() + pd.binding_margin.to_mm()).round_to_2dp()
})
.unwrap_or(20.0);
let top = page_def
.map(|pd| (page_height_mm - pd.bottom_margin.to_mm()).round_to_2dp())
.unwrap_or_else(|| (page_height_mm - 10.0).round_to_2dp());
(left, top)
}
PageNumberPosition::BottomRight => {
// 하단 오른쪽 / Bottom right
let left = page_def
.map(|pd| {
(page_width_mm - pd.right_margin.to_mm() - pd.binding_margin.to_mm())
.round_to_2dp()
})
.unwrap_or(190.0);
let top = page_def
.map(|pd| (page_height_mm - pd.bottom_margin.to_mm()).round_to_2dp())
.unwrap_or_else(|| (page_height_mm - 10.0).round_to_2dp());
(left, top)
}
PageNumberPosition::TopCenter => {
// 상단 중앙 / Top center
let left = (page_width_mm / 2.0).round_to_2dp();
let top = page_def
.map(|pd| pd.top_margin.to_mm().round_to_2dp())
.unwrap_or(10.0);
(left, top)
}
PageNumberPosition::TopLeft => {
// 상단 왼쪽 / Top left
let left = page_def
.map(|pd| {
(pd.left_margin.to_mm() + pd.binding_margin.to_mm()).round_to_2dp()
})
.unwrap_or(20.0);
let top = page_def
.map(|pd| pd.top_margin.to_mm().round_to_2dp())
.unwrap_or(10.0);
(left, top)
}
PageNumberPosition::TopRight => {
// 상단 오른쪽 / Top right
let left = page_def
.map(|pd| {
(page_width_mm - pd.right_margin.to_mm() - pd.binding_margin.to_mm())
.round_to_2dp()
})
.unwrap_or(190.0);
let top = page_def
.map(|pd| pd.top_margin.to_mm().round_to_2dp())
.unwrap_or(10.0);
(left, top)
}
_ => {
// 기타 위치는 기본값 사용 (하단 중앙) / Use default for other positions (bottom center)
let left = (page_width_mm / 2.0).round_to_2dp();
let top = page_def
.map(|pd| (page_height_mm - pd.bottom_margin.to_mm()).round_to_2dp())
.unwrap_or_else(|| (page_height_mm - 10.0).round_to_2dp());
(left, top)
}
};
// CharShape 정보로 텍스트 크기 계산 / Calculate text size from CharShape
// 원본 HTML에서 cs1 클래스를 사용하므로 shape_id 1 (0-based) 사용 / Use shape_id 1 (0-based) since original HTML uses cs1 class
let char_shape_id = 1;
let (width_mm, height_mm) = if char_shape_id < document.doc_info.char_shapes.len() {
if let Some(char_shape) = document.doc_info.char_shapes.get(char_shape_id) {
// 폰트 크기 계산 (base_size는 1/100 pt 단위) / Calculate font size (base_size is in 1/100 pt units)
let font_size_pt = char_shape.base_size as f64 / 100.0;
let font_size_mm = font_size_pt * 0.352778; // 1pt = 0.352778mm
// 텍스트 너비 계산: 문자 수 * 폰트 크기 * 평균 문자 폭 비율 (약 0.6) / Calculate text width: char count * font size * average char width ratio (approx 0.6)
let char_count = page_number_text.chars().count() as f64;
let text_width_mm = (char_count * font_size_mm * 0.6).round_to_2dp();
// 텍스트 높이 계산: 폰트 크기 * line-height (약 1.2) / Calculate text height: font size * line-height (approx 1.2)
let text_height_mm = (font_size_mm * 1.2).round_to_2dp();
(text_width_mm, text_height_mm)
} else {
// CharShape를 찾을 수 없는 경우 기본값 사용 / Use default if CharShape not found
(1.95, 3.53)
}
} else {
// CharShape ID가 범위를 벗어난 경우 기본값 사용 / Use default if CharShape ID out of range
(1.95, 3.53)
};
html.push_str(&format!(
r#"<div class="hpN" style="left:{}mm;top:{}mm;width:{}mm;height:{}mm;"><span class="hrt cs1">{}</span></div>"#,
left_mm, top_mm, width_mm, height_mm, page_number_text
));
}
}
html.push_str("</div>");
html
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/image.rs | crates/hwp-core/src/viewer/html/image.rs | /// 이미지 렌더링 모듈 / Image rendering module
use crate::types::INT32;
use crate::viewer::html::styles::{int32_to_mm, round_to_2dp};
/// 이미지를 HTML로 렌더링 / Render image to HTML
pub fn render_image(
image_url: &str,
left: INT32,
top: INT32,
width: INT32,
height: INT32,
) -> String {
let left_mm = round_to_2dp(int32_to_mm(left));
let top_mm = round_to_2dp(int32_to_mm(top));
let width_mm = round_to_2dp(int32_to_mm(width));
let height_mm = round_to_2dp(int32_to_mm(height));
format!(
r#"<div class="hsR" style="top:{}mm;left:{}mm;width:{}mm;height:{}mm;background-repeat:no-repeat;background-size:contain;background-image:url('{}');"></div>"#,
top_mm, left_mm, width_mm, height_mm, image_url
)
}
/// 이미지를 배경 이미지로 렌더링 (인라인 스타일 포함) / Render image as background image (with inline styles)
pub fn render_image_with_style(
image_url: &str,
left: INT32,
top: INT32,
width: INT32,
height: INT32,
margin_bottom: INT32,
margin_right: INT32,
) -> String {
let left_mm = round_to_2dp(int32_to_mm(left));
let top_mm = round_to_2dp(int32_to_mm(top));
let width_mm = round_to_2dp(int32_to_mm(width));
let height_mm = round_to_2dp(int32_to_mm(height));
let margin_bottom_mm = round_to_2dp(int32_to_mm(margin_bottom));
let margin_right_mm = round_to_2dp(int32_to_mm(margin_right));
format!(
r#"<div class="hsR" style="top:{}mm;left:{}mm;margin-bottom:{}mm;margin-right:{}mm;width:{}mm;height:{}mm;display:inline-block;position:relative;vertical-align:middle;background-repeat:no-repeat;background-size:contain;background-image:url('{}');"></div>"#,
top_mm, left_mm, margin_bottom_mm, margin_right_mm, width_mm, height_mm, image_url
)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/document.rs | crates/hwp-core/src/viewer/html/document.rs | use super::page;
use super::pagination::{PageBreakReason, PaginationContext};
use super::paragraph::{
render_paragraph, ParagraphPosition, ParagraphRenderContext, ParagraphRenderState,
};
use super::styles;
use super::styles::round_to_2dp;
use super::HtmlOptions;
use crate::document::bodytext::ctrl_header::{CtrlHeaderData, CtrlId};
use crate::document::bodytext::{PageDef, ParagraphRecord};
use crate::document::HwpDocument;
use crate::types::RoundTo2dp;
use crate::INT32;
/// 문서에서 첫 번째 PageDef 찾기 / Find first PageDef in document
fn find_page_def(document: &HwpDocument) -> Option<&PageDef> {
for section in &document.body_text.sections {
for paragraph in §ion.paragraphs {
for record in ¶graph.records {
// 직접 PageDef인 경우 / Direct PageDef
if let ParagraphRecord::PageDef { page_def } = record {
return Some(page_def);
}
// CtrlHeader의 children에서 PageDef 찾기 / Find PageDef in CtrlHeader's children
if let ParagraphRecord::CtrlHeader { children, .. } = record {
for child in children {
if let ParagraphRecord::PageDef { page_def } = child {
return Some(page_def);
}
}
}
}
}
}
None
}
/// 문서에서 첫 번째 PageNumberPosition 찾기 / Find first PageNumberPosition in document
fn find_page_number_position(document: &HwpDocument) -> Option<&CtrlHeaderData> {
for section in &document.body_text.sections {
for paragraph in §ion.paragraphs {
for record in ¶graph.records {
if let ParagraphRecord::CtrlHeader { header, .. } = record {
if header.ctrl_id == CtrlId::PAGE_NUMBER
|| header.ctrl_id == CtrlId::PAGE_NUMBER_POS
{
if let CtrlHeaderData::PageNumberPosition { .. } = &header.data {
return Some(&header.data);
}
}
}
}
}
}
None
}
/// Convert HWP document to HTML format
/// HWP 문서를 HTML 형식으로 변환
///
/// # Arguments / 매개변수
/// * `document` - The HWP document to convert / 변환할 HWP 문서
/// * `options` - HTML conversion options / HTML 변환 옵션
///
/// # Returns / 반환값
/// HTML string representation of the document / 문서의 HTML 문자열 표현
pub fn to_html(document: &HwpDocument, options: &HtmlOptions) -> String {
let mut html = String::new();
// HTML 문서 시작 / Start HTML document
html.push_str("<!DOCTYPE html>\n");
html.push_str("<html>\n");
html.push_str("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n");
html.push_str("\n");
html.push_str("<head>\n");
html.push_str(" <title></title>\n");
html.push_str(" <meta http_quiv=\"content-type\" content=\"text/html; charset=utf-8\">\n");
// CSS 스타일 생성 / Generate CSS styles
html.push_str(" <style>\n");
html.push_str(&styles::generate_css_styles(document));
html.push_str(" </style>\n");
html.push_str("</head>\n");
html.push_str("\n");
html.push_str("\n");
html.push_str("<body>\n");
// PageDef 찾기 / Find PageDef
let page_def = find_page_def(document);
// PageNumberPosition 찾기 / Find PageNumberPosition
let page_number_position = find_page_number_position(document);
// 페이지 시작 번호 가져오기 / Get page start number
let page_start_number = document
.doc_info
.document_properties
.as_ref()
.map(|p| p.page_start_number)
.unwrap_or(1);
// 페이지별로 렌더링 / Render by page
let mut page_number = 1;
let mut page_content = String::new();
let mut page_tables = Vec::new(); // 테이블을 별도로 저장 / Store tables separately
let mut first_segment_pos: Option<(INT32, INT32)> = None; // 첫 번째 LineSegment 위치 저장 / Store first LineSegment position
let mut hcd_position: Option<(f64, f64)> = None; // hcD 위치 저장 (mm 단위) / Store hcD position (in mm)
// 문서 레벨에서 table_counter 관리 (문서 전체에서 테이블 번호 연속 유지) / Manage table_counter at document level (maintain sequential table numbers across document)
let mut table_counter = document
.doc_info
.document_properties
.as_ref()
.map(|p| p.table_start_number as u32)
.unwrap_or(1);
// 문서 레벨에서 pattern_counter와 color_to_pattern 관리 (문서 전체에서 패턴 ID 공유) / Manage pattern_counter and color_to_pattern at document level (share pattern IDs across document)
use std::collections::HashMap;
let mut pattern_counter = 0;
let mut color_to_pattern: HashMap<u32, String> = HashMap::new();
// 페이지 높이 계산 (mm 단위) / Calculate page height (in mm)
let page_height_mm = page_def.map(|pd| pd.paper_height.to_mm()).unwrap_or(297.0);
let top_margin_mm = page_def.map(|pd| pd.top_margin.to_mm()).unwrap_or(24.99);
let bottom_margin_mm = page_def.map(|pd| pd.bottom_margin.to_mm()).unwrap_or(10.0);
let header_margin_mm = page_def.map(|pd| pd.header_margin.to_mm()).unwrap_or(0.0);
let footer_margin_mm = page_def.map(|pd| pd.footer_margin.to_mm()).unwrap_or(0.0);
// 실제 콘텐츠 영역 높이 / Actual content area height
let content_height_mm =
page_height_mm - top_margin_mm - bottom_margin_mm - header_margin_mm - footer_margin_mm;
// 페이지네이션 컨텍스트 초기화 / Initialize pagination context
let mut pagination_context = PaginationContext {
prev_vertical_mm: None,
current_max_vertical_mm: 0.0,
content_height_mm,
};
let mut current_page_def = page_def; // 현재 페이지의 PageDef 추적 / Track current page's PageDef
// 현재 페이지의 최대 vertical_position (mm 단위) / Maximum vertical_position of current page (in mm)
let mut current_max_vertical_mm = 0.0;
// 이전 문단의 마지막 vertical_position (mm 단위) / Last vertical_position of previous paragraph (in mm)
let mut prev_vertical_mm: Option<f64> = None;
let mut first_para_vertical_mm: Option<f64> = None; // 첫 번째 문단의 vertical_position (가설 O) / First paragraph's vertical_position (Hypothesis O)
// 각 문단의 vertical_position을 저장 (vert_rel_to: "para"일 때 참조 문단 찾기 위해) / Store each paragraph's vertical_position (to find reference paragraph when vert_rel_to: "para")
// 먼저 모든 문단의 vertical_position을 수집 / First collect all paragraphs' vertical_positions
let mut para_vertical_positions: Vec<f64> = Vec::new();
for section in &document.body_text.sections {
for paragraph in §ion.paragraphs {
let control_mask = ¶graph.para_header.control_mask;
let has_header_footer = control_mask.has_header_footer();
let has_footnote_endnote = control_mask.has_footnote_endnote();
if !has_header_footer && !has_footnote_endnote {
let vertical_mm = paragraph.records.iter().find_map(|record| {
if let ParagraphRecord::ParaLineSeg { segments } = record {
segments
.first()
.map(|seg| seg.vertical_position as f64 * 25.4 / 7200.0)
} else {
None
}
});
if let Some(vertical_mm) = vertical_mm {
para_vertical_positions.push(vertical_mm);
}
}
}
}
// 문단 인덱스 추적 (vertical_position이 있는 문단만 카운트) / Track paragraph index (only count paragraphs with vertical_position)
let mut para_index = 0;
for section in &document.body_text.sections {
for paragraph in §ion.paragraphs {
// 페이지네이션 컨텍스트는 아래에서 업데이트됨 / Pagination context will be updated below
// 1. 문단 페이지 나누기 확인 (렌더링 전) / Check paragraph page break (before rendering)
let para_result = super::pagination::check_paragraph_page_break(
paragraph,
&pagination_context,
current_page_def,
);
// LineSegment의 vertical_position 추출 (기존 로직 유지) / Extract vertical_position from LineSegment (keep existing logic)
let mut first_vertical_mm: Option<f64> = None;
for record in ¶graph.records {
if let ParagraphRecord::ParaLineSeg { segments } = record {
if let Some(first_segment) = segments.first() {
first_vertical_mm =
Some(first_segment.vertical_position as f64 * 25.4 / 7200.0);
}
break;
}
}
let has_page_break = para_result.has_page_break;
// 페이지 나누기가 있고 페이지 내용이 있으면 페이지 출력 (문단 렌더링 전) / Output page if page break and page content exists (before rendering paragraph)
if has_page_break && (!page_content.is_empty() || !page_tables.is_empty()) {
// PageDef 업데이트 (PageDefChange인 경우) / Update PageDef (if PageDefChange)
if para_result.reason == Some(PageBreakReason::PageDefChange) {
// 문단에서 PageDef 찾기 / Find PageDef in paragraph
for record in ¶graph.records {
if let ParagraphRecord::PageDef { page_def } = record {
current_page_def = Some(page_def);
break;
}
if let ParagraphRecord::CtrlHeader { children, .. } = record {
for child in children {
if let ParagraphRecord::PageDef { page_def } = child {
current_page_def = Some(page_def);
break;
}
}
}
}
}
// hcD 위치: PageDef 여백을 직접 사용 / hcD position: use PageDef margins directly
use crate::types::RoundTo2dp;
let hcd_pos = if let Some((left, top)) = hcd_position {
Some((left.round_to_2dp(), top.round_to_2dp()))
} else {
// hcd_position이 없으면 PageDef 여백 사용 / Use PageDef margins if hcd_position not available
let left = page_def
.map(|pd| {
(pd.left_margin.to_mm() + pd.binding_margin.to_mm()).round_to_2dp()
})
.unwrap_or(20.0);
let top = page_def
.map(|pd| (pd.top_margin.to_mm() + pd.header_margin.to_mm()).round_to_2dp())
.unwrap_or(24.99);
Some((left, top))
};
html.push_str(&page::render_page(
page_number,
&page_content,
&page_tables,
current_page_def,
first_segment_pos,
hcd_pos,
page_number_position,
page_start_number,
document,
));
page_number += 1;
page_content.clear();
page_tables.clear();
current_max_vertical_mm = 0.0;
pagination_context.current_max_vertical_mm = 0.0;
pagination_context.prev_vertical_mm = None;
first_segment_pos = None; // 새 페이지에서는 첫 번째 세그먼트 위치 리셋 / Reset first segment position for new page
hcd_position = None;
// 페이지네이션 발생 시 para_index와 para_vertical_positions 리셋 / Reset para_index and para_vertical_positions on pagination
para_index = 0;
para_vertical_positions.clear();
first_para_vertical_mm = None; // 새 페이지의 첫 번째 문단 추적을 위해 리셋 / Reset to track first paragraph of new page
}
// 문단 렌더링 (일반 본문 문단만) / Render paragraph (only regular body paragraphs)
let control_mask = ¶graph.para_header.control_mask;
let has_header_footer = control_mask.has_header_footer();
let has_footnote_endnote = control_mask.has_footnote_endnote();
if !has_header_footer && !has_footnote_endnote {
// 첫 번째 LineSegment 위치 저장 / Store first LineSegment position
// PageDef 여백을 직접 사용 / Use PageDef margins directly
if first_segment_pos.is_none() {
// hcD 위치는 left_margin + binding_margin, top_margin + header_margin을 직접 사용
// hcD position uses left_margin + binding_margin, top_margin + header_margin directly
let left_margin_mm = page_def
.map(|pd| {
(pd.left_margin.to_mm() + pd.binding_margin.to_mm()).round_to_2dp()
})
.unwrap_or(20.0);
let top_margin_mm = page_def
.map(|pd| (pd.top_margin.to_mm() + pd.header_margin.to_mm()).round_to_2dp())
.unwrap_or(24.99);
hcd_position = Some((left_margin_mm, top_margin_mm));
// LineSegment 위치 저장 (참고용) / Store LineSegment position (for reference)
for record in ¶graph.records {
if let ParagraphRecord::ParaLineSeg { segments } = record {
if let Some(first_segment) = segments.first() {
first_segment_pos = Some((
first_segment.column_start_position,
first_segment.vertical_position,
));
break;
}
}
}
}
// 첫 번째 문단의 vertical_position 추적 (가설 O) / Track first paragraph's vertical_position (Hypothesis O)
if first_para_vertical_mm.is_none() {
for record in ¶graph.records {
if let ParagraphRecord::ParaLineSeg { segments } = record {
if let Some(first_segment) = segments.first() {
first_para_vertical_mm =
Some(first_segment.vertical_position as f64 * 25.4 / 7200.0);
break;
}
}
}
}
// 현재 문단의 vertical_position 계산 / Calculate current paragraph's vertical_position
let current_para_vertical_mm = paragraph.records.iter().find_map(|record| {
if let ParagraphRecord::ParaLineSeg { segments } = record {
segments
.first()
.map(|seg| seg.vertical_position as f64 * 25.4 / 7200.0)
} else {
None
}
});
// 현재 문단 인덱스 (vertical_position이 있는 문단만 카운트) / Current paragraph index (only count paragraphs with vertical_position)
let current_para_index = if current_para_vertical_mm.is_some() {
Some(para_index)
} else {
None
};
let position = ParagraphPosition {
hcd_position,
page_def: current_page_def, // 현재 페이지의 PageDef 사용 / Use current page's PageDef
first_para_vertical_mm,
current_para_vertical_mm,
para_vertical_positions: ¶_vertical_positions, // 모든 문단의 vertical_position 전달 / Pass all paragraphs' vertical_positions
current_para_index, // 현재 문단 인덱스 전달 / Pass current paragraph index
};
let context = ParagraphRenderContext {
document,
options,
position,
};
let mut state = ParagraphRenderState {
table_counter: &mut table_counter, // 문서 레벨 table_counter 전달 / Pass document-level table_counter
pattern_counter: &mut pattern_counter, // 문서 레벨 pattern_counter 전달 / Pass document-level pattern_counter
color_to_pattern: &mut color_to_pattern, // 문서 레벨 color_to_pattern 전달 / Pass document-level color_to_pattern
};
// 2. 문단 렌더링 (내부에서 테이블/이미지 페이지네이션 체크) / Render paragraph (check table/image pagination inside)
let (para_html, table_htmls, obj_pagination_result) = render_paragraph(
paragraph,
&context,
&mut state,
&mut pagination_context, // 페이지네이션 컨텍스트 전달 / Pass pagination context
0, // 처음 렌더링이므로 건너뛸 테이블 없음 / No tables to skip on first render
);
// 3. 객체 페이지네이션 결과 처리 / Handle object pagination result
let has_obj_page_break = obj_pagination_result
.as_ref()
.map(|r| {
r.has_page_break && (!page_content.is_empty() || !page_tables.is_empty())
})
.unwrap_or(false);
if let Some(obj_result) = obj_pagination_result {
if obj_result.has_page_break
&& (!page_content.is_empty() || !page_tables.is_empty())
{
// 페이지 출력 / Output page
let hcd_pos = if let Some((left, top)) = hcd_position {
Some((left.round_to_2dp(), top.round_to_2dp()))
} else {
let left = page_def
.map(|pd| {
(pd.left_margin.to_mm() + pd.binding_margin.to_mm())
.round_to_2dp()
})
.unwrap_or(20.0);
let top = page_def
.map(|pd| {
(pd.top_margin.to_mm() + pd.header_margin.to_mm())
.round_to_2dp()
})
.unwrap_or(24.99);
Some((left, top))
};
html.push_str(&page::render_page(
page_number,
&page_content,
&page_tables,
page_def,
first_segment_pos,
hcd_pos,
page_number_position,
page_start_number,
document,
));
page_number += 1;
page_content.clear();
page_tables.clear();
current_max_vertical_mm = 0.0;
pagination_context.current_max_vertical_mm = 0.0;
pagination_context.prev_vertical_mm = None;
first_segment_pos = None;
hcd_position = None;
// 페이지네이션 발생 시 para_index와 para_vertical_positions 리셋 / Reset para_index and para_vertical_positions on pagination
para_index = 0;
para_vertical_positions.clear();
first_para_vertical_mm = None; // 새 페이지의 첫 번째 문단 추적을 위해 리셋 / Reset to track first paragraph of new page
// 페이지네이션 후 새 페이지의 첫 문단은 vertical_position이 0이어야 함 / After pagination, first paragraph of new page should have vertical_position 0
// 현재 문단의 vertical_position을 0으로 리셋 (새 페이지 시작) / Reset current paragraph's vertical_position to 0 (new page start)
// 새 페이지의 첫 번째 문단(현재 문단)의 vertical_position 추가 (0으로 리셋) / Add first paragraph's vertical_position of new page (reset to 0)
para_vertical_positions.push(0.0);
// 페이지네이션 후 같은 문단의 후속 테이블들을 새 페이지에 배치하기 위해 문단을 다시 렌더링
// Re-render paragraph to place subsequent tables on new page after pagination
if !table_htmls.is_empty() {
// 현재 문단의 vertical_position을 0으로 설정하여 새 페이지의 첫 문단으로 처리
// Set current paragraph's vertical_position to 0 to treat it as first paragraph of new page
let current_para_vertical_mm_for_next =
if current_para_vertical_mm.is_some() {
Some(0.0)
} else {
current_para_vertical_mm
};
let current_para_index_for_next = Some(0);
let position_next = ParagraphPosition {
hcd_position,
page_def: current_page_def,
first_para_vertical_mm: Some(0.0),
current_para_vertical_mm: current_para_vertical_mm_for_next,
para_vertical_positions: ¶_vertical_positions,
current_para_index: current_para_index_for_next,
};
let context_next = ParagraphRenderContext {
document,
options,
position: position_next,
};
let skip_tables_count = table_htmls.len(); // 이미 처리된 테이블 수 건너뛰기 / Skip already processed tables
let (_para_html_next, table_htmls_next, _obj_pagination_result_next) =
render_paragraph(
paragraph,
&context_next,
&mut state,
&mut pagination_context,
skip_tables_count,
);
// 후속 테이블들을 새 페이지에 추가
// Add subsequent tables to new page
for table_html in table_htmls_next {
page_tables.push(table_html);
}
}
}
}
// 현재 문단의 vertical_position을 para_vertical_positions에 추가 (페이지별로 관리) / Add current paragraph's vertical_position to para_vertical_positions (managed per page)
// 페이지네이션이 발생하지 않은 경우에만 추가 (페이지네이션 발생 시에는 이미 위에서 추가됨) / Only add if pagination did not occur (already added above if pagination occurred)
if !has_obj_page_break {
if let Some(vertical_mm) = current_para_vertical_mm {
para_vertical_positions.push(vertical_mm);
}
}
// 인덱스 증가 (vertical_position이 있는 문단만) / Increment index (only for paragraphs with vertical_position)
// 페이지네이션이 발생한 경우에는 인덱스를 증가시키지 않음 (이미 0으로 리셋됨) / Don't increment index if pagination occurred (already reset to 0)
if !has_obj_page_break && current_para_vertical_mm.is_some() {
para_index += 1;
}
if !para_html.is_empty() {
page_content.push_str(¶_html);
}
// 테이블은 hpa 레벨에 배치 (table.html 샘플 구조에 맞춤) / Tables are placed at hpa level (matching table.html sample structure)
// 페이지네이션 체크는 render_paragraph 내부에서 이미 수행되었으므로, 여기서는 바로 추가
// Pagination check is already performed in render_paragraph, so just add tables here
for table_html in table_htmls {
page_tables.push(table_html);
}
// vertical_position 업데이트 (문단의 모든 LineSegment 확인) / Update vertical_position (check all LineSegments in paragraph)
for record in ¶graph.records {
if let ParagraphRecord::ParaLineSeg { segments } = record {
for segment in segments {
let vertical_mm = segment.vertical_position as f64 * 25.4 / 7200.0;
if vertical_mm > current_max_vertical_mm {
current_max_vertical_mm = vertical_mm;
}
}
break;
}
}
// 첫 번째 세그먼트의 vertical_position을 prev_vertical_mm으로 저장 / Store first segment's vertical_position as prev_vertical_mm
if let Some(vertical) = first_vertical_mm {
prev_vertical_mm = Some(vertical);
}
// 페이지네이션 컨텍스트 업데이트 / Update pagination context
pagination_context.current_max_vertical_mm = current_max_vertical_mm;
pagination_context.prev_vertical_mm = prev_vertical_mm;
}
}
}
// 마지막 페이지 출력 / Output last page
if !page_content.is_empty() || !page_tables.is_empty() {
// hcD 위치: PageDef 여백을 직접 사용 / hcD position: use PageDef margins directly
let hcd_pos = if let Some((left, top)) = hcd_position {
Some((round_to_2dp(left), round_to_2dp(top)))
} else {
// hcd_position이 없으면 PageDef 여백 사용 / Use PageDef margins if hcd_position not available
let left = current_page_def
.map(|pd| round_to_2dp(pd.left_margin.to_mm() + pd.binding_margin.to_mm()))
.unwrap_or(20.0);
let top = current_page_def
.map(|pd| round_to_2dp(pd.top_margin.to_mm() + pd.header_margin.to_mm()))
.unwrap_or(24.99);
Some((left, top))
};
html.push_str(&page::render_page(
page_number,
&page_content,
&page_tables,
current_page_def,
first_segment_pos,
hcd_pos,
page_number_position,
page_start_number,
document,
));
}
html.push_str("</body>");
html.push('\n');
html.push('\n');
html.push_str("</html>");
html.push('\n');
html
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/styles.rs | crates/hwp-core/src/viewer/html/styles.rs | use crate::document::docinfo::para_shape::ParagraphAlignment;
/// CSS 스타일 생성 모듈 / CSS style generation module
/// noori_style.css 기반으로 CSS 생성
use crate::document::HwpDocument;
use crate::types::{COLORREF, INT32};
/// CSS 스타일 생성 / Generate CSS styles
/// 문서에 정의된 모든 스타일을 미리 생성하여 누락 방지 / Pre-generate all styles defined in document to prevent missing styles
pub fn generate_css_styles(document: &HwpDocument) -> String {
let mut css = String::new();
// 기본 스타일 (noori_style.css 기반) / Base styles (based on noori_style.css)
css.push_str(
"body {margin:0;padding-left:0;padding-right:0;padding-bottom:0;padding-top:2mm;}\n",
);
css.push_str(".hce {margin:0;padding:0;position:absolute;overflow:hidden;}\n");
css.push_str(".hme {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hhe {margin:0;padding:0;position:relative;}\n");
css.push_str(".hhi {display:inline-block;margin:0;padding:0;position:relative;background-size:contain;}\n");
css.push_str(".hls {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfS {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hcD {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hcI {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hcS {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfN {margin:0;padding:0;position:relative;}\n");
css.push_str(".hmB {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hmO {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hmT {margin:0;padding:0;position:absolute;}\n");
css.push_str(
".hpN {display:inline-block;margin:0;padding:0;position:relative;white-space:nowrap;}\n",
);
css.push_str(".htC {display:inline-block;margin:0;padding:0;position:relative;vertical-align:top;overflow:hidden;}\n");
css.push_str(".haN {display:inline-block;margin:0;padding:0;position:relative;}\n");
css.push_str(".hdu {margin:0;padding:0;position:relative;}\n");
css.push_str(".hdS {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hsC {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hsR {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hsG {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hsL {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hsT {margin:0;padding:0;position:absolute;overflow:hidden;}\n");
css.push_str(".hsE {margin:0;padding:0;position:absolute;overflow:hidden;}\n");
css.push_str(".hsA {margin:0;padding:0;position:absolute;overflow:hidden;}\n");
css.push_str(".hsP {margin:0;padding:0;position:absolute;overflow:hidden;}\n");
css.push_str(".hsV {margin:0;padding:0;position:absolute;overflow:hidden;}\n");
css.push_str(".hsO {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hsU {margin:0;padding:0;position:absolute;overflow:hidden;}\n");
css.push_str(".hpi {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hch {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hcG {margin:0;padding:0;position:absolute;}\n");
css.push_str(".heq {margin:0;padding:0;position:absolute;}\n");
css.push_str(".heG {margin:0;padding:0;position:absolute;}\n");
css.push_str(".htA {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hvi {margin:0;padding:0;position:absolute;}\n");
css.push_str(".htb {margin:0;padding:0;position:absolute;}\n");
css.push_str(".htG {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfJ {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfG {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfB {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfR {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfC {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfO {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfL {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfM {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hfE {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hpl {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hs {margin:0;padding:0;position:absolute;overflow:visible;}\n");
css.push_str(".hpa {position:relative;padding:0;overflow:hidden;margin-left:2mm;margin-right:0mm;margin-bottom:2mm;margin-top:0mm;border:1px black solid;box-shadow:1mm 1mm 0 #AAAAAA;}\n");
css.push_str(".hpa::after {content:'';position:absolute;margin:0;padding:0;left:0;right:0;top:0;bottom:0;background-color:white;z-index:-2;}\n");
css.push_str(".hrt {display:inline-block;margin:0;padding:0;position:relative;white-space:inherit;vertical-align:middle;line-height:1.1;}\n");
css.push_str(
".hco {display:inline-block;margin:0;padding:0;position:relative;white-space:inherit;}\n",
);
css.push_str(".hcc {margin:0;padding:0;position:absolute;}\n");
css.push_str(".hls {clear:both;}\n");
css.push_str("[onclick] {cursor:pointer;}\n");
// 모든 CharShape 스타일 생성 (cs0, cs1, cs2, ...) / Generate all CharShape styles (cs0, cs1, cs2, ...)
// 문서에 정의된 모든 char_shape를 미리 정의하여 누락 방지 / Pre-define all char_shapes in document to prevent missing styles
for (shape_id, char_shape) in document.doc_info.char_shapes.iter().enumerate() {
// Use 0-based shape_id for class name to match XSL/XML format (cs0, cs1, cs2, ...)
let class_name = format!("cs{}", shape_id);
css.push_str(&format!(".{} {{\n", class_name));
// 폰트 크기 / Font size
let size_pt = char_shape.base_size as f64 / 100.0;
css.push_str(&format!(" font-size:{}pt;", size_pt));
// 텍스트 색상 / Text color
let color = &char_shape.text_color;
css.push_str(&format!(
"color:rgb({},{},{});",
color.r(),
color.g(),
color.b()
));
// 폰트 패밀리 / Font family
// CharShape의 font_ids에서 한글 폰트 ID를 가져와서 face_names에서 폰트 이름 찾기
// Get Korean font ID from CharShape's font_ids and find font name from face_names
// HWP 파일의 font_id는 0-based indexing을 사용합니다 / HWP file uses 0-based indexing for font_id
let font_id = char_shape.font_ids.korean as usize;
let font_name = if font_id < document.doc_info.face_names.len() {
&document.doc_info.face_names[font_id].name
} else {
"함초롬바탕" // 기본값 / Default
};
css.push_str(&format!("font-family:\"{}\";", font_name));
// 속성 / Attributes
if char_shape.attributes.bold {
css.push_str("font-weight:bold;");
}
if char_shape.attributes.italic {
css.push_str("font-style:italic;");
}
// 자간 (letter-spacing) / Letter spacing
// 스펙 문서 표 33: letter_spacing은 -50%~50% 범위의 INT8 값
// Spec Table 33: letter_spacing is INT8 value in range -50%~50%
// CSS의 letter-spacing은 텍스트 전체에 적용되므로 하나의 값만 사용
// CSS letter-spacing applies to entire text, so use only one value
// 한글 우선, 없으면 다른 언어 중 0이 아닌 첫 번째 값 사용
// Prefer Korean, otherwise use first non-zero value from other languages
let letter_spacing = if char_shape.letter_spacing.korean != 0 {
char_shape.letter_spacing.korean
} else if char_shape.letter_spacing.english != 0 {
char_shape.letter_spacing.english
} else if char_shape.letter_spacing.chinese != 0 {
char_shape.letter_spacing.chinese
} else if char_shape.letter_spacing.japanese != 0 {
char_shape.letter_spacing.japanese
} else if char_shape.letter_spacing.other != 0 {
char_shape.letter_spacing.other
} else if char_shape.letter_spacing.symbol != 0 {
char_shape.letter_spacing.symbol
} else if char_shape.letter_spacing.user != 0 {
char_shape.letter_spacing.user
} else {
0
};
if letter_spacing != 0 {
// INT8 값을 %로 변환하여 em 단위로 적용 / Convert INT8 to % and apply as em unit
// 실제 HWP 파일에서는 값이 2배로 저장되어 있으므로 2로 나눔
// In actual HWP files, values are stored as 2x, so divide by 2
// 예: -5 → -2.5 → -0.025em (반올림하면 -0.03em), 2 → 1 → 0.01em
// Example: -5 → -2.5 → -0.025em (rounded to -0.03em), 2 → 1 → 0.01em
let letter_spacing_em = (letter_spacing as f64 / 2.0) / 100.0;
css.push_str(&format!("letter-spacing:{:.2}em;", letter_spacing_em));
}
css.push_str("\n}\n");
}
// 모든 ParaShape 스타일 생성 (ps0, ps1, ...) / Generate all ParaShape styles (ps0, ps1, ...)
// 문서에 정의된 모든 para_shape를 미리 정의하여 누락 방지 / Pre-define all para_shapes in document to prevent missing styles
for (idx, para_shape) in document.doc_info.para_shapes.iter().enumerate() {
let class_name = format!("ps{}", idx);
css.push_str(&format!(".{} {{\n", class_name));
// 정렬 / Alignment
match para_shape.attributes1.align {
ParagraphAlignment::Left => {
css.push_str(" text-align:left;");
}
ParagraphAlignment::Right => {
css.push_str(" text-align:right;");
}
ParagraphAlignment::Center => {
css.push_str(" text-align:center;");
}
ParagraphAlignment::Justify => {
css.push_str(" text-align:justify;");
}
_ => {
css.push_str(" text-align:justify;");
}
}
css.push_str("\n}\n");
}
// Print media query / Print media query
css.push_str("@media print {\n");
css.push_str(".hpa {margin:0;border:0 black none;box-shadow:none;}\n");
css.push_str("body {padding:0;}\n");
css.push_str("}\n");
css
}
/// INT32를 mm 단위로 변환 / Convert INT32 to millimeters
/// 값을 소수점 2자리로 반올림 / Round value to 2 decimal places
pub fn round_to_2dp(value: f64) -> f64 {
(value * 100.0).round() / 100.0
}
pub fn int32_to_mm(value: INT32) -> f64 {
// INT32는 1/7200인치 단위 (SHWPUNIT와 동일)
(value as f64 / 7200.0) * 25.4
}
/// mm를 INT32 단위로 변환 / Convert millimeters to INT32
pub fn mm_to_int32(value_mm: f64) -> INT32 {
// INT32는 1/7200인치 단위 (SHWPUNIT와 동일)
// 1 inch = 25.4 mm, 따라서 1 mm = 7200 / 25.4 INT32
((value_mm / 25.4) * 7200.0) as INT32
}
/// COLORREF를 RGB 문자열로 변환 / Convert COLORREF to RGB string
pub fn colorref_to_rgb(color: COLORREF) -> String {
format!("rgb({},{},{})", color.r(), color.g(), color.b())
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/text.rs | crates/hwp-core/src/viewer/html/text.rs | /// 텍스트 렌더링 모듈 / Text rendering module
use crate::document::{
bodytext::{CharShapeInfo, ParagraphRecord},
HwpDocument,
};
/// 텍스트를 HTML로 렌더링 / Render text to HTML
pub fn render_text(
text: &str,
char_shapes: &[CharShapeInfo],
document: &HwpDocument,
_css_prefix: &str,
) -> String {
if text.is_empty() {
return String::new();
}
let text_chars: Vec<char> = text.chars().collect();
let text_len = text_chars.len();
// CharShape 구간 계산 / Calculate CharShape segments
let mut segments: Vec<(usize, usize, Option<usize>)> = Vec::new();
// CharShape 정보를 position 기준으로 정렬 / Sort CharShape info by position
let mut sorted_shapes: Vec<_> = char_shapes.iter().collect();
sorted_shapes.sort_by_key(|shape| shape.position);
// 구간 정의 / Define segments
let mut positions = vec![0];
for shape_info in &sorted_shapes {
let pos = shape_info.position as usize;
if pos <= text_len {
positions.push(pos);
}
}
positions.push(text_len);
positions.sort();
positions.dedup();
// 각 구간에 대한 CharShape 찾기 / Find CharShape for each segment
for i in 0..positions.len() - 1 {
let start = positions[i];
let end = positions[i + 1];
// 이 구간에 해당하는 CharShape 찾기 / Find CharShape for this segment
let char_shape_id = sorted_shapes
.iter()
.rev()
.find(|shape| (shape.position as usize) <= start)
.map(|shape| shape.shape_id as usize);
segments.push((start, end, char_shape_id));
}
// 각 구간을 HTML로 렌더링 / Render each segment to HTML
let mut result = String::new();
for (start, end, char_shape_id_opt) in segments {
if start >= end {
continue;
}
let segment_text: String = text_chars[start..end].iter().collect();
if segment_text.is_empty() {
continue;
}
// CharShape 가져오기 / Get CharShape
// HWP 파일의 shape_id는 0-based indexing을 사용합니다 / HWP file uses 0-based indexing for shape_id
let char_shape_opt = char_shape_id_opt.and_then(|id| {
if id < document.doc_info.char_shapes.len() {
document.doc_info.char_shapes.get(id)
} else {
None
}
});
// 텍스트 스타일 적용 / Apply text styles
// 첫 공백과 마지막 공백을 로 변환 (HTML 태그 적용 전에 처리) / Convert leading and trailing spaces to (process before applying HTML tags)
let mut text_for_styling = segment_text.to_string();
// 첫 공백을 로 변환 / Convert leading space to
if text_for_styling.starts_with(' ') {
text_for_styling = text_for_styling.replacen(' ', " ", 1);
}
// 마지막 공백을 로 변환 / Convert trailing space to
if text_for_styling.ends_with(' ') {
text_for_styling.pop();
text_for_styling.push_str(" ");
}
if let Some(char_shape) = char_shape_opt {
// CharShape 클래스 적용 / Apply CharShape class (0-based indexing to match XSL/XML format)
let class_name = format!("cs{}", char_shape_id_opt.unwrap());
// 인라인 스타일 추가 / Add inline styles
let mut inline_style = String::new();
// 폰트 크기 / Font size
let size_pt = char_shape.base_size as f64 / 100.0;
inline_style.push_str(&format!("font-size:{}pt;", size_pt));
// 텍스트 색상 / Text color
let color = &char_shape.text_color;
inline_style.push_str(&format!(
"color:rgb({},{},{});",
color.r(),
color.g(),
color.b()
));
// 속성 / Attributes
// bold는 CSS의 font-weight:bold로 처리되므로 <strong> 태그 사용하지 않음
// Bold is handled by CSS font-weight:bold, so don't use <strong> tag
let mut styled_text = text_for_styling;
if char_shape.attributes.italic {
styled_text = format!("<em>{}</em>", styled_text);
}
if char_shape.attributes.underline_type > 0 {
styled_text = format!("<u>{}</u>", styled_text);
}
if char_shape.attributes.strikethrough > 0 {
styled_text = format!("<s>{}</s>", styled_text);
}
if char_shape.attributes.superscript {
styled_text = format!("<sup>{}</sup>", styled_text);
}
if char_shape.attributes.subscript {
styled_text = format!("<sub>{}</sub>", styled_text);
}
// .hrt span으로 래핑 / Wrap with .hrt span
if !inline_style.is_empty() {
result.push_str(&format!(
r#"<span class="hrt {}" style="{}">{}</span>"#,
class_name, inline_style, styled_text
));
} else {
result.push_str(&format!(
r#"<span class="hrt {}">{}</span>"#,
class_name, styled_text
));
}
} else {
// CharShape가 없는 경우 기본 스타일 / Default style when no CharShape
result.push_str(&format!(r#"<span class="hrt">{}</span>"#, text_for_styling));
}
}
result
}
/// 문단에서 텍스트와 CharShape 추출 / Extract text and CharShape from paragraph
pub fn extract_text_and_shapes(
paragraph: &crate::document::bodytext::Paragraph,
) -> (String, Vec<CharShapeInfo>) {
let mut text = String::new();
let mut char_shapes = Vec::new();
for record in ¶graph.records {
match record {
ParagraphRecord::ParaText {
text: para_text, ..
} => {
text.push_str(para_text);
}
ParagraphRecord::ParaCharShape { shapes } => {
char_shapes.extend(shapes.iter().cloned());
}
_ => {}
}
}
(text, char_shapes)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/options.rs | crates/hwp-core/src/viewer/html/options.rs | /// HTML 변환 옵션 / HTML conversion options
#[derive(Debug, Clone)]
pub struct HtmlOptions {
/// 이미지를 파일로 저장할 디렉토리 경로 (None이면 base64 데이터 URI로 임베드)
/// Optional directory path to save images as files. If None, images are embedded as base64 data URIs.
pub image_output_dir: Option<String>,
/// HTML 파일이 저장되는 디렉토리 경로 (이미지 상대 경로 계산에 사용)
/// Directory path where HTML file is saved (used for calculating relative image paths)
pub html_output_dir: Option<String>,
/// 버전 정보 포함 여부 / Whether to include version information
pub include_version: Option<bool>,
/// 페이지 정보 포함 여부 / Whether to include page information
pub include_page_info: Option<bool>,
/// CSS 클래스 접두사 (기본값: "" - noori.html 스타일)
/// CSS class prefix (default: "" - noori.html style)
pub css_class_prefix: String,
}
impl Default for HtmlOptions {
fn default() -> Self {
Self {
image_output_dir: None,
html_output_dir: None,
include_version: Some(true),
include_page_info: Some(false),
css_class_prefix: String::new(), // noori.html 스타일은 접두사 없음
}
}
}
impl HtmlOptions {
/// 이미지 출력 디렉토리 설정 / Set image output directory
pub fn with_image_output_dir(mut self, dir: Option<&str>) -> Self {
self.image_output_dir = dir.map(|s| s.to_string());
self
}
/// 버전 정보 포함 설정 / Set version information inclusion
pub fn with_include_version(mut self, include: Option<bool>) -> Self {
self.include_version = include;
self
}
/// 페이지 정보 포함 설정 / Set page information inclusion
pub fn with_include_page_info(mut self, include: Option<bool>) -> Self {
self.include_page_info = include;
self
}
/// CSS 클래스 접두사 설정 / Set CSS class prefix
pub fn with_css_class_prefix(mut self, prefix: &str) -> Self {
self.css_class_prefix = prefix.to_string();
self
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/mod.rs | crates/hwp-core/src/viewer/html/mod.rs | /// HTML converter for HWP documents
/// HWP 문서를 HTML로 변환하는 모듈
///
/// This module provides functionality to convert HWP documents to HTML format.
/// 이 모듈은 HWP 문서를 HTML 형식으로 변환하는 기능을 제공합니다.
///
/// noori.html 스타일의 정확한 레이아웃 HTML 뷰어
mod common;
mod ctrl_header;
mod document;
mod image;
mod line_segment;
mod options;
mod page;
mod pagination;
mod paragraph;
mod styles;
mod text;
// Re-export public API
pub use document::to_html;
pub use options::HtmlOptions;
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/common.rs | crates/hwp-core/src/viewer/html/common.rs | /// HTML 뷰어 공통 유틸리티 함수 / HTML viewer common utility functions
use crate::document::{BinDataRecord, HwpDocument};
use crate::{HwpError, WORD};
use base64::{engine::general_purpose::STANDARD, Engine as _};
use std::fs;
use std::path::Path;
/// Get file extension from BinData ID
/// BinData ID에서 파일 확장자 가져오기
pub fn get_extension_from_bindata_id(document: &HwpDocument, bindata_id: WORD) -> String {
for record in &document.doc_info.bin_data {
if let BinDataRecord::Embedding { embedding, .. } = record {
if embedding.binary_data_id == bindata_id {
return embedding.extension.clone();
}
}
}
"jpg".to_string()
}
/// Get MIME type from BinData ID
/// BinData ID에서 MIME 타입 가져오기
pub fn get_mime_type_from_bindata_id(document: &HwpDocument, bindata_id: WORD) -> String {
for record in &document.doc_info.bin_data {
if let BinDataRecord::Embedding { embedding, .. } = record {
if embedding.binary_data_id == bindata_id {
return match embedding.extension.to_lowercase().as_str() {
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
"gif" => "image/gif",
"bmp" => "image/bmp",
_ => "image/jpeg",
}
.to_string();
}
}
}
"image/jpeg".to_string()
}
/// Save image to file and return file path
/// 이미지를 파일로 저장하고 파일 경로 반환
pub fn save_image_to_file(
document: &HwpDocument,
bindata_id: crate::types::WORD,
base64_data: &str,
dir_path: &str,
) -> Result<String, HwpError> {
// base64 디코딩 / Decode base64
let image_data = STANDARD
.decode(base64_data)
.map_err(|e| HwpError::InternalError {
message: format!("Failed to decode base64: {}", e),
})?;
// 파일명 생성 / Generate filename
let extension = get_extension_from_bindata_id(document, bindata_id);
let file_name = format!("BIN{:04X}.{}", bindata_id, extension);
let file_path = Path::new(dir_path).join(&file_name);
// 디렉토리 생성 / Create directory
fs::create_dir_all(dir_path)
.map_err(|e| HwpError::Io(format!("Failed to create directory '{}': {}", dir_path, e)))?;
// 파일 저장 / Save file
fs::write(&file_path, &image_data).map_err(|e| {
HwpError::Io(format!(
"Failed to write file '{}': {}",
file_path.display(),
e
))
})?;
Ok(file_path.to_string_lossy().to_string())
}
/// Get image URL (file path or base64 data URI)
/// 이미지 URL 가져오기 (파일 경로 또는 base64 데이터 URI)
pub fn get_image_url(
document: &HwpDocument,
bindata_id: WORD,
image_output_dir: Option<&str>,
html_output_dir: Option<&str>,
) -> String {
// BinData에서 이미지 데이터 찾기 / Find image data from BinData
let base64_data = document
.bin_data
.items
.iter()
.find(|item| item.index == bindata_id)
.map(|item| item.data.as_str())
.unwrap_or("");
if base64_data.is_empty() {
return String::new();
}
match image_output_dir {
Some(dir_path) => {
// 이미지를 파일로 저장 / Save image as file
match save_image_to_file(document, bindata_id, base64_data, dir_path) {
Ok(file_path) => {
// HTML 출력 디렉토리가 있으면 상대 경로 계산 / Calculate relative path if HTML output directory is provided
if let Some(html_dir) = html_output_dir {
let image_path = Path::new(&file_path);
let html_path = Path::new(html_dir);
// 상대 경로 계산 / Calculate relative path
match pathdiff::diff_paths(image_path, html_path) {
Some(relative_path) => {
// 경로 구분자를 슬래시로 통일 / Normalize path separators to forward slashes
relative_path.to_string_lossy().replace('\\', "/")
}
None => {
// 상대 경로 계산 실패 시 파일명만 반환 / Return filename only if relative path calculation fails
image_path
.file_name()
.and_then(|n| n.to_str())
.map(|s| s.to_string())
.unwrap_or_else(|| file_path)
}
}
} else {
// HTML 출력 디렉토리가 없으면 파일명만 반환 / Return filename only if HTML output directory is not provided
let file_path_obj = Path::new(&file_path);
file_path_obj
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&file_path)
.to_string()
}
}
Err(_) => {
// 실패 시 base64로 폴백 / Fallback to base64 on failure
let mime_type = get_mime_type_from_bindata_id(document, bindata_id);
format!("data:{};base64,{}", mime_type, base64_data)
}
}
}
None => {
// base64 데이터 URI로 임베드 / Embed as base64 data URI
let mime_type = get_mime_type_from_bindata_id(document, bindata_id);
format!("data:{};base64,{}", mime_type, base64_data)
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/pagination.rs | crates/hwp-core/src/viewer/html/pagination.rs | /// 페이지네이션 모듈 / Pagination module
///
/// HTML 뷰어의 페이지 나누기 로직을 담당합니다.
/// Handles page break logic for HTML viewer.
use crate::document::bodytext::{ColumnDivideType, PageDef, ParagraphRecord};
use crate::document::Paragraph;
/// 페이지네이션 컨텍스트 / Pagination context
pub struct PaginationContext {
/// 이전 문단의 vertical_position (mm)
pub prev_vertical_mm: Option<f64>,
/// 현재 페이지의 최대 vertical_position (mm)
pub current_max_vertical_mm: f64,
/// 콘텐츠 영역 높이 (mm)
pub content_height_mm: f64,
}
/// 페이지네이션 결과 / Pagination result
pub struct PaginationResult {
/// 페이지 나누기 여부
pub has_page_break: bool,
/// 페이지 나누기 원인
pub reason: Option<PageBreakReason>,
}
/// 페이지 나누기 원인 / Page break reason
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageBreakReason {
/// 명시적 페이지 나누기 (column_divide_type)
Explicit,
/// PageDef 변경 (새 페이지 설정)
PageDefChange,
/// vertical_position 리셋
VerticalReset,
/// vertical_position 오버플로우
VerticalOverflow,
/// 테이블 오버플로우 (테이블이 페이지 높이를 초과)
TableOverflow,
/// 이미지/모양 객체 오버플로우 (객체가 페이지 높이를 초과)
ObjectOverflow,
}
/// 페이지 나누기 여부 확인 (문단) / Check if page break is needed (paragraph)
/// 모든 전략을 조합하여 확인: explicit > page_def_change > vertical_reset > vertical_overflow
/// Checks all strategies combined: explicit > page_def_change > vertical_reset > vertical_overflow
pub fn check_paragraph_page_break(
paragraph: &Paragraph,
context: &PaginationContext,
current_page_def: Option<&PageDef>,
) -> PaginationResult {
// 1. 첫 번째 LineSegment의 vertical_position 추출
let first_vertical_mm = extract_first_vertical_position(paragraph);
// 2. PageDef 변경 확인
let has_page_def_change = check_page_def_change(paragraph, current_page_def);
// 3. 모든 전략 확인 (우선순위: explicit > page_def_change > vertical_reset > vertical_overflow)
let has_explicit = check_explicit_page_break(paragraph);
let has_vertical_reset = check_vertical_reset(context.prev_vertical_mm, first_vertical_mm);
let has_vertical_overflow = check_vertical_overflow(
first_vertical_mm,
context.content_height_mm,
context.current_max_vertical_mm,
);
// 우선순위에 따라 첫 번째 true인 원인을 반환
if has_explicit {
PaginationResult {
has_page_break: true,
reason: Some(PageBreakReason::Explicit),
}
} else if has_page_def_change {
PaginationResult {
has_page_break: true,
reason: Some(PageBreakReason::PageDefChange),
}
} else if has_vertical_reset {
PaginationResult {
has_page_break: true,
reason: Some(PageBreakReason::VerticalReset),
}
} else if has_vertical_overflow {
PaginationResult {
has_page_break: true,
reason: Some(PageBreakReason::VerticalOverflow),
}
} else {
PaginationResult {
has_page_break: false,
reason: None,
}
}
}
/// 테이블 페이지 나누기 확인 / Check if table causes page break
/// 테이블의 top과 height를 받아서 페이지를 넘어가는지 확인
/// current_max_vertical_mm을 고려하여 테이블이 페이지를 넘어가는지 확인
pub fn check_table_page_break(
table_top_mm: f64,
table_height_mm: f64,
context: &PaginationContext,
) -> PaginationResult {
let table_bottom_mm = table_top_mm + table_height_mm;
// 테이블이 페이지를 넘어가는지 확인
// 1. 테이블의 bottom이 content_height_mm을 넘어가는 경우
// 2. 또는 테이블의 top이 current_max_vertical_mm보다 크고, 테이블의 bottom이 content_height_mm에 매우 가까운 경우 (95% 이상)
// Check if table overflows page
// 1. Table bottom exceeds content_height_mm
// 2. Or table top is greater than current_max_vertical_mm and table bottom is very close to content_height_mm (95% or more)
if table_bottom_mm > context.content_height_mm {
// 테이블이 페이지를 넘어가는 경우, current_max_vertical_mm이 0보다 크면 페이지네이션 발생
// If table overflows, pagination occurs if current_max_vertical_mm > 0
if context.current_max_vertical_mm > 0.0 {
PaginationResult {
has_page_break: true,
reason: Some(PageBreakReason::TableOverflow),
}
} else {
// 첫 페이지이지만 테이블이 페이지를 넘어가는 경우, 페이지네이션 발생
// Even on first page, if table overflows, pagination occurs
PaginationResult {
has_page_break: true,
reason: Some(PageBreakReason::TableOverflow),
}
}
} else if table_top_mm > context.current_max_vertical_mm
&& table_bottom_mm > context.content_height_mm
&& context.current_max_vertical_mm > 0.0
{
// 테이블이 페이지를 넘어가는 경우 (table_bottom_mm > content_height_mm)
// Table overflows page (table_bottom_mm > content_height_mm)
// 테이블의 top이 current_max_vertical_mm보다 크고, 테이블의 bottom이 content_height_mm을 넘어가는 경우
// If table top is greater than current_max_vertical_mm and table bottom exceeds content_height_mm
PaginationResult {
has_page_break: true,
reason: Some(PageBreakReason::TableOverflow),
}
} else {
PaginationResult {
has_page_break: false,
reason: None,
}
}
}
/// 이미지/모양 객체 페이지 나누기 확인 / Check if image/shape object causes page break
pub fn check_object_page_break(
object_top_mm: f64,
object_height_mm: f64,
context: &PaginationContext,
) -> PaginationResult {
let object_bottom_mm = object_top_mm + object_height_mm;
if object_bottom_mm > context.content_height_mm && context.current_max_vertical_mm > 0.0 {
PaginationResult {
has_page_break: true,
reason: Some(PageBreakReason::ObjectOverflow),
}
} else {
PaginationResult {
has_page_break: false,
reason: None,
}
}
}
/// 첫 번째 LineSegment의 vertical_position 추출 / Extract first LineSegment's vertical_position
fn extract_first_vertical_position(paragraph: &Paragraph) -> Option<f64> {
for record in ¶graph.records {
if let ParagraphRecord::ParaLineSeg { segments } = record {
if let Some(first_segment) = segments.first() {
return Some(first_segment.vertical_position as f64 * 25.4 / 7200.0);
}
}
}
None
}
/// 명시적 페이지 나누기 확인 / Check explicit page break
fn check_explicit_page_break(paragraph: &Paragraph) -> bool {
paragraph
.para_header
.column_divide_type
.iter()
.any(|t| matches!(t, ColumnDivideType::Page | ColumnDivideType::Section))
}
/// vertical_position 리셋 확인 / Check vertical_position reset
fn check_vertical_reset(prev_vertical_mm: Option<f64>, current_vertical_mm: Option<f64>) -> bool {
if let (Some(prev), Some(current)) = (prev_vertical_mm, current_vertical_mm) {
current < 0.1 || (prev > 0.1 && current < prev - 0.1)
} else if let Some(current) = current_vertical_mm {
current < 0.1 && prev_vertical_mm.is_some()
} else {
false
}
}
/// vertical_position 오버플로우 확인 / Check vertical_position overflow
fn check_vertical_overflow(
current_vertical_mm: Option<f64>,
content_height_mm: f64,
current_max_vertical_mm: f64,
) -> bool {
if let Some(current) = current_vertical_mm {
current > content_height_mm && current_max_vertical_mm > 0.0
} else {
false
}
}
/// PageDef 변경 확인 / Check if PageDef changed
fn check_page_def_change(paragraph: &Paragraph, current_page_def: Option<&PageDef>) -> bool {
// 문단의 레코드에서 PageDef 찾기 / Find PageDef in paragraph records
for record in ¶graph.records {
if let ParagraphRecord::PageDef { page_def } = record {
// PageDef가 있고, 현재 PageDef와 다르면 새 페이지 / If PageDef exists and differs from current, new page
// 포인터 비교로 변경 여부 확인 / Check change by pointer comparison
return current_page_def
.map(|pd| !std::ptr::eq(pd as *const _, page_def as *const _))
.unwrap_or(true);
}
// CtrlHeader의 children에서도 확인 / Also check in CtrlHeader's children
if let ParagraphRecord::CtrlHeader { children, .. } = record {
for child in children {
if let ParagraphRecord::PageDef { page_def } = child {
return current_page_def
.map(|pd| !std::ptr::eq(pd as *const _, page_def as *const _))
.unwrap_or(true);
}
}
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::bodytext::ParaHeader;
fn create_test_paragraph() -> Paragraph {
let mut para_header = ParaHeader::default();
para_header.para_shape_id = 0;
para_header.column_divide_type = vec![];
para_header.control_mask = crate::document::bodytext::ControlMask::new(0);
para_header.text_char_count = 0;
Paragraph {
para_header,
records: vec![],
}
}
#[test]
fn test_check_explicit_page_break() {
let mut para = create_test_paragraph();
para.para_header.column_divide_type = vec![ColumnDivideType::Page];
assert!(check_explicit_page_break(¶));
para.para_header.column_divide_type = vec![ColumnDivideType::Section];
assert!(check_explicit_page_break(¶));
para.para_header.column_divide_type = vec![];
assert!(!check_explicit_page_break(¶));
}
#[test]
fn test_check_vertical_reset() {
// prev가 있고 current가 0이면 리셋
assert!(check_vertical_reset(Some(10.0), Some(0.05)));
// prev가 있고 current가 prev보다 작으면 리셋
assert!(check_vertical_reset(Some(10.0), Some(9.8)));
// prev가 없고 current가 0이면 리셋 아님 (첫 문단)
assert!(!check_vertical_reset(None, Some(0.05)));
// prev가 있고 current가 prev보다 크면 리셋 아님
assert!(!check_vertical_reset(Some(10.0), Some(10.5)));
}
#[test]
fn test_check_vertical_overflow() {
let content_height = 250.0;
// current가 content_height를 초과하고 current_max가 있으면 오버플로우
assert!(check_vertical_overflow(Some(260.0), content_height, 10.0));
// current가 content_height를 초과하지만 current_max가 0이면 오버플로우 아님
assert!(!check_vertical_overflow(Some(260.0), content_height, 0.0));
// current가 content_height를 초과하지 않으면 오버플로우 아님
assert!(!check_vertical_overflow(Some(240.0), content_height, 10.0));
}
#[test]
fn test_check_table_page_break() {
let context = PaginationContext {
prev_vertical_mm: None,
current_max_vertical_mm: 10.0,
content_height_mm: 250.0,
};
// 테이블이 페이지를 넘어가면 페이지 나누기
let result = check_table_page_break(240.0, 20.0, &context);
assert!(result.has_page_break);
assert_eq!(result.reason, Some(PageBreakReason::TableOverflow));
// 테이블이 페이지를 넘어가지 않으면 페이지 나누기 아님
let result = check_table_page_break(240.0, 5.0, &context);
assert!(!result.has_page_break);
// current_max_vertical_mm이 0이면 페이지 나누기 아님
let context_empty = PaginationContext {
prev_vertical_mm: None,
current_max_vertical_mm: 0.0,
content_height_mm: 250.0,
};
let result = check_table_page_break(240.0, 20.0, &context_empty);
assert!(!result.has_page_break);
}
#[test]
fn test_check_object_page_break() {
let context = PaginationContext {
prev_vertical_mm: None,
current_max_vertical_mm: 10.0,
content_height_mm: 250.0,
};
// 객체가 페이지를 넘어가면 페이지 나누기
let result = check_object_page_break(240.0, 20.0, &context);
assert!(result.has_page_break);
assert_eq!(result.reason, Some(PageBreakReason::ObjectOverflow));
// 객체가 페이지를 넘어가지 않으면 페이지 나누기 아님
let result = check_object_page_break(240.0, 5.0, &context);
assert!(!result.has_page_break);
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/line_segment.rs | crates/hwp-core/src/viewer/html/line_segment.rs | use crate::document::bodytext::ctrl_header::VertRelTo;
/// 라인 세그먼트 렌더링 모듈 / Line segment rendering module
use crate::document::bodytext::{
control_char::{ControlChar, ControlCharPosition},
CharShapeInfo, LineSegmentInfo, PageDef, Table,
};
use crate::document::CtrlHeaderData;
use crate::viewer::html::ctrl_header::table::{CaptionData, TablePosition, TableRenderContext};
use crate::viewer::html::styles::{int32_to_mm, round_to_2dp};
use crate::viewer::HtmlOptions;
use crate::{HwpDocument, ParaShape};
use std::collections::HashMap;
/// 라인 세그먼트 렌더링 콘텐츠 / Line segment rendering content
pub struct LineSegmentContent<'a> {
pub segments: &'a [LineSegmentInfo],
pub text: &'a str,
pub char_shapes: &'a [CharShapeInfo],
pub control_char_positions: &'a [ControlCharPosition],
pub original_text_len: usize,
pub images: &'a [ImageInfo],
pub tables: &'a [TableInfo<'a>],
}
/// 라인 세그먼트 렌더링 컨텍스트 / Line segment rendering context
pub struct LineSegmentRenderContext<'a> {
pub document: &'a HwpDocument,
pub para_shape_class: &'a str,
pub options: &'a HtmlOptions,
pub para_shape_indent: Option<i32>,
pub hcd_position: Option<(f64, f64)>,
pub page_def: Option<&'a PageDef>,
}
/// 문서 레벨 렌더링 상태 / Document-level rendering state
pub struct DocumentRenderState<'a> {
pub table_counter_start: u32,
pub pattern_counter: &'a mut usize,
pub color_to_pattern: &'a mut HashMap<u32, String>,
}
/// 테이블 정보 구조체 / Table info struct
#[derive(Debug, Clone)]
pub struct TableInfo<'a> {
pub table: &'a Table,
pub ctrl_header: Option<&'a CtrlHeaderData>,
/// 문단 텍스트 내 컨트롤 문자(Shape/Table) 앵커 위치 (UTF-16 WCHAR 인덱스 기준)
/// Anchor position of the control char in paragraph text (UTF-16 WCHAR index)
pub anchor_char_pos: Option<usize>,
pub caption: Option<CaptionData<'a>>, // 캡션 데이터 / Caption data
}
/// 이미지 정보 구조체 / Image info struct
#[derive(Debug, Clone)]
pub struct ImageInfo {
pub width: u32,
pub height: u32,
pub url: String,
/// object_common 속성: 글자처럼 취급 여부 / object_common attribute: treat as letters
pub like_letters: bool,
/// object_common 속성: 줄 간격에 영향 여부 / object_common attribute: affect line spacing
pub affect_line_spacing: bool,
/// object_common 속성: 세로 기준 위치 / object_common attribute: vertical reference position
pub vert_rel_to: Option<VertRelTo>,
}
/// 라인 세그먼트를 HTML로 렌더링 / Render line segment to HTML
pub fn render_line_segment(
segment: &LineSegmentInfo,
content: &str,
para_shape_class: &str,
para_shape_indent: Option<i32>, // ParaShape의 indent 값 (옵션) / ParaShape indent value (optional)
para_shape: Option<&ParaShape>, // ParaShape 정보 (옵션) / ParaShape info (optional)
is_text_segment: bool, // 텍스트 세그먼트 여부 (테이블/이미지 like_letters 등은 false)
override_size_mm: Option<(f64, f64)>, // 비텍스트 세그먼트(이미지 등)에서 hls box 크기 override
) -> String {
let left_mm = round_to_2dp(int32_to_mm(segment.column_start_position));
let vertical_pos_mm = int32_to_mm(segment.vertical_position);
let (width_mm, height_mm) = if let Some((w, h)) = override_size_mm {
(round_to_2dp(w), round_to_2dp(h))
} else {
(
round_to_2dp(int32_to_mm(segment.segment_width)),
round_to_2dp(int32_to_mm(segment.line_height)),
)
};
let text_height_mm = round_to_2dp(int32_to_mm(segment.text_height));
let _line_spacing_mm = round_to_2dp(int32_to_mm(segment.line_spacing));
// baseline_distance_mm는 fixture 매칭 계산에서 직접 사용하지 않지만,
// 필요 시 디버깅을 위해 남겨둘 수 있습니다.
// NOTE (HWP 데이터 기반 + 스펙 기반 추론):
// - 스펙(표 44 bit8): use_line_grid=true 인 문단은 "편집 용지의 줄 격자"를 사용합니다.
// 이 경우 줄 높이는 격자에 의해 고정되며(=LineSegmentInfo.line_height가 의미를 갖는다고 보는 게 자연스럽고),
// baseline_distance는 "줄의 세로 위치에서 베이스라인까지 거리"(표 62)로서 CSS line-height 그 자체가 아닙니다.
//
// 따라서:
// - use_line_grid=false: 기존처럼 line-height=baseline_distance, top은 baseline 중심 보정
// - use_line_grid=true : line-height=line_height, top은 (line_height - text_height)/2 로 중앙 정렬
let use_line_grid = para_shape
.map(|ps| ps.attributes1.use_line_grid)
.unwrap_or(false);
let line_height_value = if is_text_segment {
if use_line_grid {
// 줄 격자 사용: "줄의 높이"를 사용
round_to_2dp(int32_to_mm(segment.line_height))
} else {
// 일반: baseline_distance를 사용
round_to_2dp(int32_to_mm(segment.baseline_distance))
}
} else {
height_mm
};
let top_mm = if is_text_segment {
if use_line_grid {
// 줄 격자 사용: 줄 높이 안에서 텍스트를 중앙 정렬
let offset_mm = (line_height_value - text_height_mm) / 2.0;
round_to_2dp(vertical_pos_mm + offset_mm)
} else {
// 일반: baseline 보정
let baseline_offset_mm = (line_height_value - text_height_mm) / 2.0;
round_to_2dp(vertical_pos_mm + baseline_offset_mm)
}
} else {
round_to_2dp(vertical_pos_mm)
};
let mut style = format!(
"line-height:{:.2}mm;white-space:nowrap;left:{:.2}mm;top:{:.2}mm;height:{:.2}mm;width:{:.2}mm;",
line_height_value, left_mm, top_mm, height_mm, width_mm
);
// padding-left 처리 (들여쓰기) / Handle padding-left (indentation)
if segment.tag.has_indentation {
// NOTE:
// HWP ParaShape의 `indent`는 첫 줄 들여쓰기(음수 가능; 내어쓰기/행잉 인덴트 표현)이고,
// `outdent`는 다음 줄(들여쓰기 적용 라인)의 오프셋으로 사용하는 값입니다.
// fixture(noori.html)에서 line_segment.tag.has_indentation=true인 라인은
// padding-left가 양수로 적용되는데, 이는 `indent`가 아니라 `outdent`에 해당합니다.
//
// 우선순위: ParaShape.outdent → (fallback) 전달받은 para_shape_indent
if let Some(ps) = para_shape {
let outdent_mm = round_to_2dp(int32_to_mm(ps.outdent));
style.push_str(&format!("padding-left:{:.2}mm;", outdent_mm));
} else if let Some(indent) = para_shape_indent {
let indent_mm = round_to_2dp(int32_to_mm(indent));
style.push_str(&format!("padding-left:{:.2}mm;", indent_mm));
}
}
format!(
r#"<div class="hls {}" style="{}">{}</div>"#,
para_shape_class, style, content
)
}
/// 라인 세그먼트를 HTML로 렌더링 (ParaShape indent 포함) / Render line segment to HTML (with ParaShape indent)
pub fn render_line_segment_with_indent(
segment: &LineSegmentInfo,
content: &str,
para_shape_class: &str,
para_shape_indent: Option<i32>,
) -> String {
render_line_segment(
segment,
content,
para_shape_class,
para_shape_indent,
None,
true,
None,
)
}
/// 라인 세그먼트 그룹을 HTML로 렌더링 / Render line segment group to HTML
pub fn render_line_segments(
segments: &[LineSegmentInfo],
text: &str,
char_shapes: &[CharShapeInfo],
document: &HwpDocument,
para_shape_class: &str,
) -> String {
// 이 함수는 레거시 호환성을 위해 유지되지만, 내부적으로는 독립적인 pattern_counter를 사용합니다.
// This function is kept for legacy compatibility but uses an independent pattern_counter internally.
use std::collections::HashMap;
let mut pattern_counter = 0;
let mut color_to_pattern: HashMap<u32, String> = HashMap::new();
let content = LineSegmentContent {
segments,
text,
char_shapes,
control_char_positions: &[],
original_text_len: text.chars().count(),
images: &[],
tables: &[],
};
let context = LineSegmentRenderContext {
document,
para_shape_class,
options: &HtmlOptions::default(),
para_shape_indent: None,
hcd_position: None,
page_def: None,
};
let mut state = DocumentRenderState {
table_counter_start: 1,
pattern_counter: &mut pattern_counter,
color_to_pattern: &mut color_to_pattern,
};
render_line_segments_with_content(&content, &context, &mut state)
}
/// 라인 세그먼트 그룹을 HTML로 렌더링 (이미지와 테이블 포함) / Render line segment group to HTML (with images and tables)
pub fn render_line_segments_with_content(
content: &LineSegmentContent,
context: &LineSegmentRenderContext,
state: &mut DocumentRenderState,
) -> String {
// 구조체에서 개별 값 추출 / Extract individual values from structs
let segments = content.segments;
let text = content.text;
let char_shapes = content.char_shapes;
let control_char_positions = content.control_char_positions;
let original_text_len = content.original_text_len;
let images = content.images;
let tables = content.tables;
let document = context.document;
let para_shape_class = context.para_shape_class;
let options = context.options;
let para_shape_indent = context.para_shape_indent;
let hcd_position = context.hcd_position;
let page_def = context.page_def;
let table_counter_start = state.table_counter_start;
// pattern_counter와 color_to_pattern은 이미 &mut이므로 직접 사용 / pattern_counter and color_to_pattern are already &mut, so use directly
let mut result = String::new();
// 원본 WCHAR 인덱스(original) -> cleaned_text 인덱스(cleaned) 매핑
// Map original WCHAR index -> cleaned_text index.
//
// control_char_positions.position은 "원본 WCHAR 인덱스" 기준입니다.
// text(여기 인자)는 제어 문자를 대부분 제거한 cleaned_text 입니다.
fn original_to_cleaned_index(pos: usize, control_chars: &[ControlCharPosition]) -> isize {
let mut delta: isize = 0; // cleaned = original + delta
for cc in control_chars.iter() {
if cc.position >= pos {
break;
}
let size = ControlChar::get_size_by_code(cc.code) as isize;
let contributes = if ControlChar::is_convertible(cc.code)
&& cc.code != ControlChar::PARA_BREAK
&& cc.code != ControlChar::LINE_BREAK
{
1
} else {
0
} as isize;
delta += contributes - size;
}
delta
}
fn slice_cleaned_by_original_range(
cleaned: &str,
control_chars: &[ControlCharPosition],
start_original: usize,
end_original: usize,
) -> String {
let start_delta = original_to_cleaned_index(start_original, control_chars);
let end_delta = original_to_cleaned_index(end_original, control_chars);
let start_cleaned = (start_original as isize + start_delta).max(0) as usize;
let end_cleaned = (end_original as isize + end_delta).max(0) as usize;
let cleaned_chars: Vec<char> = cleaned.chars().collect();
let s = start_cleaned.min(cleaned_chars.len());
let e = end_cleaned.min(cleaned_chars.len());
if s >= e {
return String::new();
}
cleaned_chars[s..e].iter().collect()
}
for segment in segments {
let mut content = String::new();
let mut override_size_mm: Option<(f64, f64)> = None;
// 이 세그먼트에 해당하는 텍스트 추출 (원본 WCHAR 인덱스 기준) / Extract text for this segment (based on original WCHAR indices)
let start_pos = segment.text_start_position as usize;
let end_pos = if let Some(next_segment) = segments
.iter()
.find(|s| s.text_start_position > segment.text_start_position)
{
next_segment.text_start_position as usize
} else {
original_text_len
};
let segment_text =
slice_cleaned_by_original_range(text, control_char_positions, start_pos, end_pos);
// 이 세그먼트에 해당하는 CharShape 필터링 / Filter CharShape for this segment
//
// IMPORTANT:
// CharShapeInfo.position은 "문단 전체 텍스트(원본 WCHAR) 기준" 인덱스입니다.
// 여기서는 원본(start_pos..end_pos) 범위를 기준으로 segment_char_shapes를 보정해야 합니다.
// position을 세그먼트 기준(0부터)으로 보정하지 않으면 스타일(csXX)이 누락되어
// `<span class="hrt">...</span>`로 떨어질 수 있습니다. (noori.html에서 재현)
//
// Strategy:
// - 세그먼트 시작 위치(start_pos)에 해당하는 CharShape가 있으면 그것을 0으로 이동
// - 없으면 start_pos 이전의 마지막 CharShape를 기본으로 0 위치에 추가
// - 세그먼트 범위 내 CharShape는 position -= start_pos 로 이동
let mut segment_char_shapes: Vec<CharShapeInfo> = Vec::new();
// 세그먼트 시작점에 정확히 CharShape 변화가 있는지 확인 / Check if there's a shape change exactly at start_pos
let has_shape_at_start = char_shapes
.iter()
.any(|shape| shape.position as usize == start_pos);
// start_pos 이전의 마지막 CharShape를 기본으로 포함 / Include the last shape before start_pos as the default
if !has_shape_at_start {
if let Some(prev_shape) = char_shapes
.iter()
.filter(|shape| (shape.position as usize) < start_pos)
.max_by_key(|shape| shape.position)
{
segment_char_shapes.push(CharShapeInfo {
position: 0,
shape_id: prev_shape.shape_id,
});
}
}
// 세그먼트 범위 내 CharShape를 보정해서 추가 / Add in-range shapes with adjusted positions
for shape in char_shapes.iter() {
let pos = shape.position as usize;
if pos >= start_pos && pos < end_pos {
segment_char_shapes.push(CharShapeInfo {
position: (pos - start_pos) as u32,
shape_id: shape.shape_id,
});
}
}
// position 기준 정렬 (render_text에서 다시 정렬하지만, 여기서도 정렬해두면 안정적) / Sort by position
segment_char_shapes.sort_by_key(|s| s.position);
// 세그먼트 인덱스 계산 / Calculate segment index
let segment_index = segments
.iter()
.position(|s| std::ptr::eq(s, segment))
.unwrap_or(0);
// 텍스트가 비어있는지 확인 / Check if text is empty
let is_text_empty = segment_text.trim().is_empty();
// is_empty_segment 플래그 확인 / Check is_empty_segment flag
let is_empty_segment = segment.tag.is_empty_segment;
// 빈 세그먼트 카운터 (is_empty_segment 플래그를 사용) / Empty segment counter (using is_empty_segment flag)
let mut empty_count = 0;
for (idx, seg) in segments.iter().enumerate() {
if idx >= segment_index {
break;
}
if seg.tag.is_empty_segment {
empty_count += 1;
}
}
// 이미지와 테이블 렌더링 / Render images and tables
//
// 정확도 최우선:
// - 테이블(like_letters=true)은 "빈 세그먼트 순서"가 아니라 ParaText control_char_positions(앵커) 기반으로
// 어떤 LineSegment에 속하는지 결정해서 딱 한 번만 렌더링합니다.
// - 이미지는 기존 empty_count 방식 유지 (향후 필요 시 동일 방식으로 개선 가능)
// 이 세그먼트 범위에 속하는 테이블 찾기 (앵커 기반; 원본 인덱스 기준) / Find tables for this segment (anchor-based; original indices)
let mut tables_for_segment: Vec<&TableInfo> = Vec::new();
for t in tables.iter() {
if let Some(anchor) = t.anchor_char_pos {
if anchor >= start_pos && anchor < end_pos {
tables_for_segment.push(t);
}
}
}
if !tables_for_segment.is_empty() {
// 테이블 렌더링 (앵커 기반) / Render tables (anchor-based)
use crate::viewer::html::ctrl_header::table::render_table;
for (idx_in_seg, table_info) in tables_for_segment.iter().enumerate() {
let current_table_number = table_counter_start + idx_in_seg as u32;
let segment_position =
Some((segment.column_start_position, segment.vertical_position));
let mut context = TableRenderContext {
document,
ctrl_header: table_info.ctrl_header,
page_def,
options,
table_number: Some(current_table_number),
pattern_counter: state.pattern_counter,
color_to_pattern: state.color_to_pattern,
};
let position = TablePosition {
hcd_position,
segment_position,
para_start_vertical_mm: None,
para_start_column_mm: None,
para_segment_width_mm: None,
first_para_vertical_mm: None,
};
let table_html = render_table(
table_info.table,
&mut context,
position,
table_info.caption.as_ref(),
);
content.push_str(&table_html);
}
} else if (is_empty_segment || is_text_empty)
&& !images.is_empty()
&& empty_count < images.len()
{
// 이미지 렌더링 (빈 세그먼트에 이미지) / Render images (images in empty segments)
let image = &images[empty_count];
use crate::viewer::html::image::render_image_with_style;
let image_html = render_image_with_style(
&image.url,
0,
0,
image.width as crate::types::INT32,
image.height as crate::types::INT32,
0,
0,
);
content.push_str(&image_html);
// IMPORTANT: 일부 파일(noori 'BIN0002.bmp')에서 LineSegment의 segment_width/line_height가 0에 가깝게 나와
// hls 박스가 0폭/작은 높이로 생성되며 이미지 중앙정렬이 깨집니다.
// fixture(noori.html) 기준으로는 이미지가 셀에 별도 배치되는 케이스가 있어
// hls width는 원래 segment_width(0일 수 있음)를 유지하고, height만 이미지 높이에 맞춥니다.
override_size_mm = Some((
round_to_2dp(int32_to_mm(segment.segment_width)),
round_to_2dp(int32_to_mm(image.height as crate::types::INT32)),
));
} else if !is_text_empty {
// 텍스트 렌더링 / Render text
use crate::viewer::html::text::render_text;
let rendered_text = render_text(&segment_text, &segment_char_shapes, document, "");
content.push_str(&rendered_text);
}
// 라인 세그먼트 렌더링 / Render line segment
// ParaShape 정보 가져오기 (para_shape_class에서 ID 추출) / Get ParaShape info (extract ID from para_shape_class)
let para_shape = if para_shape_class.starts_with("ps") {
if let Ok(para_shape_id) = para_shape_class[2..].parse::<usize>() {
if para_shape_id < document.doc_info.para_shapes.len() {
Some(&document.doc_info.para_shapes[para_shape_id])
} else {
None
}
} else {
None
}
} else {
None
};
result.push_str(&render_line_segment(
segment,
&content,
para_shape_class,
para_shape_indent,
para_shape,
// 텍스트 렌더링 경로일 때만 true. (이미지/테이블 like_letters를 배치한 세그먼트는 false)
!(!tables_for_segment.is_empty()
|| ((is_empty_segment || is_text_empty) && !images.is_empty())),
override_size_mm,
));
}
result
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/paragraph.rs | crates/hwp-core/src/viewer/html/paragraph.rs | use super::common;
use super::ctrl_header;
use super::line_segment::{
DocumentRenderState, ImageInfo, LineSegmentContent, LineSegmentRenderContext, TableInfo,
};
use super::pagination::{self, PaginationContext, PaginationResult};
use super::text;
use super::HtmlOptions;
use crate::document::bodytext::{
control_char::ControlChar,
ctrl_header::{CtrlHeaderData, VertRelTo},
PageDef, ParagraphRecord,
};
use crate::document::{HwpDocument, Paragraph};
use crate::viewer::html::ctrl_header::table::{render_table, TablePosition, TableRenderContext};
use crate::INT32;
use std::collections::HashMap;
/// 문단 위치 정보 / Paragraph position information
pub struct ParagraphPosition<'a> {
pub hcd_position: Option<(f64, f64)>,
pub page_def: Option<&'a PageDef>,
pub first_para_vertical_mm: Option<f64>,
pub current_para_vertical_mm: Option<f64>,
pub para_vertical_positions: &'a [f64],
pub current_para_index: Option<usize>,
}
/// 문단 렌더링 컨텍스트 / Paragraph rendering context
pub struct ParagraphRenderContext<'a> {
pub document: &'a HwpDocument,
pub options: &'a HtmlOptions,
pub position: ParagraphPosition<'a>,
}
/// 문단 렌더링 상태 / Paragraph rendering state
pub struct ParagraphRenderState<'a> {
pub table_counter: &'a mut u32,
pub pattern_counter: &'a mut usize,
pub color_to_pattern: &'a mut HashMap<u32, String>,
}
/// 문단을 HTML로 렌더링 / Render paragraph to HTML
/// 반환값: (문단 HTML, 테이블 HTML 리스트, 페이지네이션 결과) / Returns: (paragraph HTML, table HTML list, pagination result)
/// skip_tables_count: 페이지네이션 후 같은 문단을 다시 렌더링할 때 이미 처리된 테이블 수를 건너뛰기 위한 파라미터
/// skip_tables_count: Parameter to skip already processed tables when re-rendering paragraph after pagination
pub fn render_paragraph(
paragraph: &Paragraph,
context: &ParagraphRenderContext,
state: &mut ParagraphRenderState,
pagination_context: &mut PaginationContext,
skip_tables_count: usize,
) -> (String, Vec<String>, Option<PaginationResult>) {
// 구조체에서 개별 값 추출 / Extract individual values from structs
let document = context.document;
let options = context.options;
let hcd_position = context.position.hcd_position;
let page_def = context.position.page_def;
let first_para_vertical_mm = context.position.first_para_vertical_mm;
let current_para_vertical_mm = context.position.current_para_vertical_mm;
let para_vertical_positions = context.position.para_vertical_positions;
let current_para_index = context.position.current_para_index;
// table_counter, pattern_counter, color_to_pattern은 이미 &mut이므로 직접 사용 / table_counter, pattern_counter, color_to_pattern are already &mut, so use directly
let mut result = String::new();
// ParaShape 클래스 가져오기 / Get ParaShape class
let para_shape_id = paragraph.para_header.para_shape_id;
// HWP 파일의 para_shape_id는 0-based indexing을 사용합니다 / HWP file uses 0-based indexing for para_shape_id
let para_shape_class = if (para_shape_id as usize) < document.doc_info.para_shapes.len() {
format!("ps{}", para_shape_id)
} else {
String::new()
};
// 텍스트와 CharShape 추출 / Extract text and CharShape
let (text, char_shapes) = text::extract_text_and_shapes(paragraph);
// ParaText의 control_char_positions 수집 (원본 WCHAR 인덱스 기준) / Collect control_char_positions (based on original WCHAR indices)
let mut control_char_positions = Vec::new();
for record in ¶graph.records {
if let ParagraphRecord::ParaText {
control_char_positions: ccp,
..
} = record
{
control_char_positions = ccp.clone();
break;
}
}
// LineSegment 찾기 / Find LineSegment
let mut line_segments = Vec::new();
for record in ¶graph.records {
if let ParagraphRecord::ParaLineSeg { segments } = record {
line_segments = segments.clone();
break;
}
}
// 이미지와 테이블 수집 / Collect images and tables
let mut images = Vec::new();
let mut tables: Vec<TableInfo> = Vec::new();
// ParaText의 control_char_positions에서 SHAPE_OBJECT(표/그리기 개체) 앵커 위치 수집
// Collect SHAPE_OBJECT anchor positions from ParaText control_char_positions
let mut shape_object_anchor_positions: Vec<usize> = Vec::new();
for record in ¶graph.records {
if let ParagraphRecord::ParaText {
control_char_positions,
..
} = record
{
for pos in control_char_positions.iter() {
if pos.code == ControlChar::SHAPE_OBJECT {
shape_object_anchor_positions.push(pos.position);
}
}
}
}
let mut shape_object_anchor_cursor: usize = 0;
for record in ¶graph.records {
match record {
ParagraphRecord::ShapeComponent {
shape_component,
children,
} => {
// ShapeComponent의 children에서 이미지 찾기 / Find images in ShapeComponent's children
for child in children {
if let ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} = child
{
let bindata_id = shape_component_picture.picture_info.bindata_id;
let image_url = common::get_image_url(
document,
bindata_id,
options.image_output_dir.as_deref(),
options.html_output_dir.as_deref(),
);
if !image_url.is_empty() {
// shape_component.width/height를 직접 사용 / Use shape_component.width/height directly
images.push(ImageInfo {
width: shape_component.width,
height: shape_component.height,
url: image_url,
like_letters: false, // ShapeComponent에서 직접 온 이미지는 ctrl_header 정보 없음 / Images from ShapeComponent directly have no ctrl_header info
affect_line_spacing: false,
vert_rel_to: None,
});
}
}
}
}
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
let bindata_id = shape_component_picture.picture_info.bindata_id;
let image_url = common::get_image_url(
document,
bindata_id,
options.image_output_dir.as_deref(),
options.html_output_dir.as_deref(),
);
if !image_url.is_empty() {
// ShapeComponentPicture가 직접 올 때는 border_rectangle 사용 (부모 ShapeComponent가 없음)
// When ShapeComponentPicture comes directly, use border_rectangle (no parent ShapeComponent)
let width = (shape_component_picture.border_rectangle_x.right
- shape_component_picture.border_rectangle_x.left)
as u32;
let mut height = (shape_component_picture.border_rectangle_y.bottom
- shape_component_picture.border_rectangle_y.top)
as u32;
// border_rectangle_y의 top과 bottom이 같으면 crop_rectangle 사용
// If border_rectangle_y's top and bottom are the same, use crop_rectangle
if height == 0 {
height = (shape_component_picture.crop_rectangle.bottom
- shape_component_picture.crop_rectangle.top)
as u32;
}
images.push(ImageInfo {
width,
height,
url: image_url,
like_letters: false, // ShapeComponentPicture에서 직접 온 이미지는 ctrl_header 정보 없음 / Images from ShapeComponentPicture directly have no ctrl_header info
affect_line_spacing: false,
vert_rel_to: None,
});
}
}
ParagraphRecord::Table { table } => {
tables.push(TableInfo {
table: &table,
ctrl_header: None,
anchor_char_pos: None,
caption: None,
});
}
ParagraphRecord::CtrlHeader {
header,
children,
paragraphs,
..
} => {
// CtrlHeader 처리 / Process CtrlHeader
let ctrl_result = ctrl_header::process_ctrl_header(
&header,
&children,
¶graphs,
document,
options,
);
// SHAPE_OBJECT(11)는 "표/그리기 개체" 공통 제어문자이므로, ctrl_id가 "tbl "인 경우에만
// ParaText의 SHAPE_OBJECT 위치를 순서대로 매칭하여 anchor를 부여합니다.
if header.ctrl_id == "tbl " {
let anchor = shape_object_anchor_positions
.get(shape_object_anchor_cursor)
.copied();
shape_object_anchor_cursor = shape_object_anchor_cursor.saturating_add(1);
for t in ctrl_result.tables.iter() {
let mut tt = t.clone();
tt.anchor_char_pos = anchor;
tables.push(tt);
}
} else {
tables.extend(ctrl_result.tables);
}
images.extend(ctrl_result.images);
}
_ => {}
}
}
// 테이블 HTML 리스트 생성 / Create table HTML list
let mut table_htmls = Vec::new();
// inline_tables는 owned TableInfo를 저장 / inline_tables stores owned TableInfo
let mut inline_tables: Vec<TableInfo> = Vec::new(); // like_letters=true인 테이블들 / Tables with like_letters=true
// 문단의 첫 번째 LineSegment의 vertical_position 계산 (vert_rel_to: "para"일 때 사용) / Calculate first LineSegment's vertical_position (used when vert_rel_to: "para")
// current_para_vertical_mm이 전달되면 사용하고, 없으면 현재 문단의 첫 번째 LineSegment 사용
// If current_para_vertical_mm is provided, use it; otherwise use first LineSegment of current paragraph
// table_position 함수는 para_start_vertical_mm을 절대 위치(페이지 기준)로 기대하므로,
// 상대 위치일 때는 base_top을 더해서 절대 위치로 변환해야 함
// table_position function expects para_start_vertical_mm as absolute position (relative to page),
// so if it's relative position, add base_top to convert to absolute position
// base_top 계산 (나중에 사용) / Calculate base_top (used later)
let base_top_for_calc = if let Some((_, top)) = context.position.hcd_position {
top
} else if let Some(pd) = context.position.page_def {
pd.top_margin.to_mm() + pd.header_margin.to_mm()
} else {
24.99
};
let para_start_vertical_mm = if let Some(0) = current_para_index {
// 새 페이지의 첫 문단이므로 base_top을 사용 / First paragraph of new page, so use base_top
Some(base_top_for_calc)
} else {
// 상대 위치를 절대 위치로 변환 / Convert relative position to absolute position
let relative_mm = current_para_vertical_mm.or_else(|| {
line_segments
.first()
.map(|seg| seg.vertical_position as f64 * 25.4 / 7200.0)
});
relative_mm.map(|rel| rel + base_top_for_calc)
};
let para_start_column_mm = line_segments
.first()
.map(|seg| seg.column_start_position as f64 * 25.4 / 7200.0);
let para_segment_width_mm = line_segments
.first()
.map(|seg| seg.segment_width as f64 * 25.4 / 7200.0);
// base_top(mm): hcD의 top 위치. like_letters=false 테이블(=hpa 레벨로 빠지는 객체)의 vert_rel_to=para 계산에
// 페이지 기준(절대) y 좌표가 필요하므로, paragraph 기준 y(vertical_position)에 base_top을 더해 절대값으로 전달한다.
let base_top_mm = if let Some((_hcd_left, hcd_top)) = hcd_position {
hcd_top
} else if let Some(pd) = page_def {
pd.top_margin.to_mm() + pd.header_margin.to_mm()
} else {
24.99
};
// LineSegment가 있으면 사용 / Use LineSegment if available
if !line_segments.is_empty() {
// like_letters=true인 테이블과 false인 테이블 분리 / Separate tables with like_letters=true and false
let mut absolute_tables = Vec::new();
for table_info in tables.iter() {
let like_letters = table_info
.ctrl_header
.and_then(|h| match h {
CtrlHeaderData::ObjectCommon { attribute, .. } => Some(attribute.like_letters),
_ => None,
})
.unwrap_or(false);
if like_letters {
inline_tables.push(TableInfo {
table: table_info.table,
ctrl_header: table_info.ctrl_header,
anchor_char_pos: table_info.anchor_char_pos,
caption: table_info.caption.clone(),
});
} else {
absolute_tables.push(TableInfo {
table: table_info.table,
ctrl_header: table_info.ctrl_header,
anchor_char_pos: table_info.anchor_char_pos,
caption: table_info.caption.clone(),
});
}
}
// like_letters=true인 이미지와 false인 이미지 분리 / Separate images with like_letters=true and false
let mut inline_images = Vec::new();
let mut absolute_images = Vec::new();
for image_info in images.iter() {
if image_info.like_letters {
inline_images.push(image_info.clone());
} else {
absolute_images.push(image_info.clone());
}
}
// ParaShape indent 값 가져오기 / Get ParaShape indent value
// HWP 파일의 para_shape_id는 0-based indexing을 사용합니다 / HWP file uses 0-based indexing for para_shape_id
let para_shape_indent = if (para_shape_id as usize) < document.doc_info.para_shapes.len() {
Some(document.doc_info.para_shapes[para_shape_id as usize].indent)
} else {
None
};
// like_letters=true인 테이블을 line_segment에 포함 / Include tables with like_letters=true in line_segment
// inline_tables는 이미 TableInfo이므로 그대로 사용 / inline_tables is already TableInfo, so use as is
let inline_table_infos: Vec<TableInfo> = inline_tables
.iter()
.map(|table_info| TableInfo {
table: table_info.table,
ctrl_header: table_info.ctrl_header,
anchor_char_pos: table_info.anchor_char_pos,
caption: table_info.caption.clone(),
})
.collect();
// 테이블 번호 시작값: 현재 table_counter 사용 (문서 레벨에서 관리) / Table number start value: use current table_counter (managed at document level)
let table_counter_start = *state.table_counter;
let content = LineSegmentContent {
segments: &line_segments,
text: &text,
char_shapes: &char_shapes,
control_char_positions: &control_char_positions,
original_text_len: paragraph.para_header.text_char_count as usize,
images: &inline_images, // like_letters=true인 이미지만 line_segment에 포함 / Include only images with like_letters=true in line_segment
tables: inline_table_infos.as_slice(), // like_letters=true인 테이블 포함 / Include tables with like_letters=true
};
let context = LineSegmentRenderContext {
document,
para_shape_class: ¶_shape_class,
options,
para_shape_indent,
hcd_position,
page_def,
};
let mut line_segment_state = DocumentRenderState {
table_counter_start,
pattern_counter: state.pattern_counter,
color_to_pattern: state.color_to_pattern,
};
result.push_str(&super::line_segment::render_line_segments_with_content(
&content,
&context,
&mut line_segment_state,
));
// inline_tables의 개수만큼 table_counter 증가 (이미 line_segment에 포함되었으므로) / Increment table_counter by inline_tables count (already included in line_segment)
*state.table_counter += inline_table_infos.len() as u32;
// like_letters=true인 테이블은 이미 line_segment에 포함되었으므로 여기서는 처리하지 않음
// Tables with like_letters=true are already included in line_segment, so don't process them here
// like_letters=false인 이미지를 별도로 렌더링 (hpa 레벨에 배치) / Render images with like_letters=false separately (placed at hpa level)
for image_info in absolute_images.iter() {
use crate::viewer::html::image::render_image;
// vert_rel_to에 따라 위치 계산 / Calculate position based on vert_rel_to
let (left_mm, top_mm) = match image_info.vert_rel_to {
Some(VertRelTo::Para) => {
// para 기준: hcd_position 사용 / Use hcd_position for para reference
if let Some((hcd_left, hcd_top)) = hcd_position {
// offset_x, offset_y는 현재 image_info에 없으므로 0으로 설정
// offset_x, offset_y are not in image_info currently, so set to 0
(hcd_left, hcd_top)
} else {
// hcd_position이 없으면 para_start_vertical_mm 사용 / Use para_start_vertical_mm if hcd_position not available
(0.0, para_start_vertical_mm.unwrap_or(0.0))
}
}
Some(VertRelTo::Page) | Some(VertRelTo::Paper) | None => {
// page/paper 기준: 절대 위치 (현재는 0,0으로 설정, 나중에 object_common의 offset_x, offset_y 사용)
// page/paper reference: absolute position (currently set to 0,0, later use object_common's offset_x, offset_y)
(0.0, 0.0)
}
};
// 이미지 크기 계산 (mm 단위) / Calculate image size (in mm)
let height_mm = image_info.height as f64 * 25.4 / 7200.0;
// 페이지네이션 체크 (렌더링 직전) / Check pagination (before rendering)
let image_result =
pagination::check_object_page_break(top_mm, height_mm, pagination_context);
if image_result.has_page_break {
// 페이지네이션 결과 반환 (document.rs에서 처리) / Return pagination result (handled in document.rs)
return (result, table_htmls, Some(image_result));
}
let image_html = render_image(
&image_info.url,
(left_mm * 7200.0 / 25.4) as INT32,
(top_mm * 7200.0 / 25.4) as INT32,
image_info.width as INT32,
image_info.height as INT32,
);
result.push_str(&image_html);
}
// like_letters=false인 테이블을 별도로 렌더링 (hpa 레벨에 배치) / Render tables with like_letters=false separately (placed at hpa level)
// 페이지네이션 후 같은 문단을 다시 렌더링할 때 이미 처리된 테이블을 건너뛰기 / Skip already processed tables when re-rendering paragraph after pagination
for table_info in absolute_tables.iter().skip(skip_tables_count) {
// vert_rel_to: "para"일 때 다음 문단을 참조 / When vert_rel_to: "para", reference next paragraph
// vert_rel_to=para인 객체의 기준 문단은 "현재 문단"의 vertical_position입니다.
// para_start_vertical_mm은 이미 현재 문단의 vertical_position이므로 이를 직접 사용
// For vert_rel_to=para objects, the reference paragraph is the "current paragraph"'s vertical_position.
// para_start_vertical_mm is already the current paragraph's vertical_position, so use it directly
let ref_para_vertical_mm = para_start_vertical_mm;
// table_position 함수는 para_start_vertical_mm을 상대 위치로 기대하므로,
// 절대 위치로 변환하지 않고 상대 위치 그대로 전달
// table_position function expects para_start_vertical_mm as relative position,
// so pass relative position as-is without converting to absolute
let ref_para_vertical_for_table = ref_para_vertical_mm;
let first_para_vertical_for_table = first_para_vertical_mm;
// 테이블 크기 계산 (mm 단위) / Calculate table size (in mm)
// size 모듈은 pub(crate)이므로 같은 크레이트 내에서 접근 가능
// size module is pub(crate), so accessible within the same crate
use crate::viewer::html::ctrl_header::table;
use table::size::{content_size, htb_size, resolve_container_size};
let container_size = htb_size(table_info.ctrl_header);
let content_size = content_size(table_info.table, table_info.ctrl_header);
let resolved_size = resolve_container_size(container_size, content_size);
let height_mm = resolved_size.height;
// 테이블 위치 계산 (정확한 위치) / Calculate table position (exact position)
// table_position은 pub(crate)이므로 같은 크레이트 내에서 접근 가능
// table_position is pub(crate), so accessible within the same crate
use crate::viewer::html::ctrl_header::table::position::table_position;
let (_left_mm, top_mm) = table_position(
hcd_position,
page_def,
None, // like_letters=false인 테이블은 segment_position 없음 / No segment_position for like_letters=false tables
table_info.ctrl_header,
Some(resolved_size.width), // obj_outer_width_mm: 테이블 너비 사용 / Use table width
ref_para_vertical_for_table, // 상대 위치로 전달 / Pass as relative position
para_start_column_mm,
para_segment_width_mm,
first_para_vertical_for_table, // 상대 위치로 전달 / Pass as relative position
);
// 페이지네이션 체크 (렌더링 직전) / Check pagination (before rendering)
let table_result =
pagination::check_table_page_break(top_mm, height_mm, pagination_context);
// 페이지네이션이 발생하더라도 테이블을 렌더링하여 table_htmls에 포함시킴
// 이렇게 하면 페이지네이션 후 같은 문단을 다시 렌더링할 때 이미 처리된 테이블 수를 올바르게 계산할 수 있음
// Render table even if pagination occurs, so it's included in table_htmls
// This allows correct calculation of already processed tables when re-rendering paragraph after pagination
let mut context = TableRenderContext {
document,
ctrl_header: table_info.ctrl_header,
page_def,
options,
table_number: Some(*state.table_counter),
pattern_counter: state.pattern_counter,
color_to_pattern: state.color_to_pattern,
};
let position = TablePosition {
hcd_position,
segment_position: None, // like_letters=false인 테이블은 segment_position 없음 / No segment_position for like_letters=false tables
para_start_vertical_mm: ref_para_vertical_for_table, // 상대 위치로 전달 / Pass as relative position
para_start_column_mm,
para_segment_width_mm,
first_para_vertical_mm: first_para_vertical_for_table, // 상대 위치로 전달 / Pass as relative position
};
let table_html = render_table(
table_info.table,
&mut context,
position,
table_info.caption.as_ref(),
);
table_htmls.push(table_html);
*state.table_counter += 1; // table_counter 증가 / Increment table_counter
if table_result.has_page_break {
// 페이지네이션 결과 반환 (document.rs에서 처리) / Return pagination result (handled in document.rs)
return (result, table_htmls, Some(table_result));
}
}
} else if !text.is_empty() {
// LineSegment가 없으면 텍스트만 렌더링 / Render text only if no LineSegment
let rendered_text =
text::render_text(&text, &char_shapes, document, &options.css_class_prefix);
result.push_str(&format!(
r#"<div class="hls {}">{}</div>"#,
para_shape_class, rendered_text
));
}
(result, table_htmls, None)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/endnote.rs | crates/hwp-core/src/viewer/html/ctrl_header/endnote.rs | use crate::document::bodytext::ParagraphRecord;
use crate::document::{CtrlHeader, Paragraph};
use super::CtrlHeaderResult;
/// 미주 처리 / Process endnote
pub fn process_endnote<'a>(
_header: &'a CtrlHeader,
_children: &'a [ParagraphRecord],
_paragraphs: &[Paragraph],
) -> CtrlHeaderResult<'a> {
// TODO: 미주 처리 로직 추가 / Add endnote processing logic
CtrlHeaderResult::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/shape_object.rs | crates/hwp-core/src/viewer/html/ctrl_header/shape_object.rs | use super::CtrlHeaderResult;
use crate::document::bodytext::ctrl_header::VertRelTo;
use crate::document::bodytext::ParagraphRecord;
use crate::document::{CtrlHeader, CtrlHeaderData, Paragraph};
use crate::viewer::html::common;
use crate::viewer::html::line_segment::ImageInfo;
use crate::viewer::HtmlOptions;
use crate::HwpDocument;
/// 그리기 개체 처리 / Process shape object
pub fn process_shape_object<'a>(
header: &'a CtrlHeader,
children: &'a [ParagraphRecord],
paragraphs: &'a [Paragraph],
document: &'a HwpDocument,
options: &'a HtmlOptions,
) -> CtrlHeaderResult<'a> {
let mut result = CtrlHeaderResult::new();
// object_common 속성 추출 / Extract object_common attributes
let (like_letters, affect_line_spacing, vert_rel_to) = match &header.data {
CtrlHeaderData::ObjectCommon { attribute, .. } => (
attribute.like_letters,
attribute.affect_line_spacing,
Some(attribute.vert_rel_to),
),
_ => (false, false, None),
};
// children과 paragraphs에서 첫 번째 ShapeComponent 찾기 (크기 정보 추출용) / Find first ShapeComponent in children and paragraphs (for size extraction)
let mut initial_width = None;
let mut initial_height = None;
// children에서 찾기 / Search in children
for record in children {
if let ParagraphRecord::ShapeComponent {
shape_component, ..
} = record
{
initial_width = Some(shape_component.width);
initial_height = Some(shape_component.height);
break;
}
}
// children에서 찾지 못했으면 paragraphs에서 찾기 / If not found in children, search in paragraphs
if initial_width.is_none() {
for para in paragraphs {
for record in ¶.records {
match record {
ParagraphRecord::ShapeComponent {
shape_component, ..
} => {
initial_width = Some(shape_component.width);
initial_height = Some(shape_component.height);
break;
}
ParagraphRecord::CtrlHeader {
children: nested_children,
..
} => {
// 중첩된 CtrlHeader의 children에서도 찾기 / Also search in nested CtrlHeader's children
for nested_record in nested_children {
if let ParagraphRecord::ShapeComponent {
shape_component, ..
} = nested_record
{
initial_width = Some(shape_component.width);
initial_height = Some(shape_component.height);
break;
}
}
if initial_width.is_some() {
break;
}
}
_ => {}
}
}
if initial_width.is_some() {
break;
}
}
}
// children과 paragraphs에서 재귀적으로 이미지 수집 / Recursively collect images from children and paragraphs
// JSON 구조: CtrlHeader의 children에 ShapeComponent가 있고, 그 children에 ShapeComponentPicture가 있음
// JSON structure: CtrlHeader's children contains ShapeComponent, and its children contains ShapeComponentPicture
// 1. children이 있으면 children을 먼저 처리 (가장 일반적인 경우) / If children exists, process children first (most common case)
if !children.is_empty() {
collect_images_from_records(
children,
document,
options,
like_letters,
affect_line_spacing,
vert_rel_to,
initial_width, // parent_shape_component_width
initial_height, // parent_shape_component_height
&mut result.images,
);
} else if initial_width.is_some() && initial_height.is_some() {
// 2. children이 비어있고 paragraphs에 ShapeComponent가 있으면, paragraphs의 records에서 ShapeComponent를 찾아서 처리
// If children is empty and paragraphs has ShapeComponent, find ShapeComponent in paragraphs' records and process
for para in paragraphs {
// paragraphs의 records를 재귀적으로 탐색하여 이미지 수집
// Recursively search paragraphs' records to collect images
collect_images_from_records(
¶.records,
document,
options,
like_letters,
affect_line_spacing,
vert_rel_to,
initial_width,
initial_height,
&mut result.images,
);
}
}
result
}
/// ParagraphRecord 배열에서 재귀적으로 이미지 수집 / Recursively collect images from ParagraphRecord array
fn collect_images_from_records(
records: &[ParagraphRecord],
document: &HwpDocument,
options: &HtmlOptions,
like_letters: bool,
affect_line_spacing: bool,
vert_rel_to: Option<VertRelTo>,
parent_shape_component_width: Option<u32>,
parent_shape_component_height: Option<u32>,
images: &mut Vec<ImageInfo>,
) {
for record in records {
match record {
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
let bindata_id = shape_component_picture.picture_info.bindata_id;
let image_url = common::get_image_url(
document,
bindata_id,
options.image_output_dir.as_deref(),
options.html_output_dir.as_deref(),
);
if !image_url.is_empty() {
// shape_component.width/height를 우선 사용 / Prioritize shape_component.width/height
let width = parent_shape_component_width.unwrap_or(0);
let height = parent_shape_component_height.unwrap_or(0);
if width > 0 && height > 0 {
images.push(ImageInfo {
width,
height,
url: image_url,
like_letters,
affect_line_spacing,
vert_rel_to,
});
}
}
}
ParagraphRecord::ShapeComponent {
shape_component,
children,
} => {
// 재귀적으로 children에서 이미지 찾기 (shape_component.width/height 전달)
collect_images_from_records(
children,
document,
options,
like_letters,
affect_line_spacing,
vert_rel_to,
Some(shape_component.width),
Some(shape_component.height),
images,
);
}
ParagraphRecord::CtrlHeader { children, .. } => {
// 중첩된 CtrlHeader도 처리 (속성은 상위에서 상속, shape_component 크기는 유지)
// Process nested CtrlHeader (attributes inherited from parent, shape_component size maintained)
collect_images_from_records(
children,
document,
options,
like_letters,
affect_line_spacing,
vert_rel_to,
parent_shape_component_width,
parent_shape_component_height,
images,
);
}
_ => {}
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/footer.rs | crates/hwp-core/src/viewer/html/ctrl_header/footer.rs | use crate::document::bodytext::ParagraphRecord;
use crate::document::{CtrlHeader, Paragraph};
use super::CtrlHeaderResult;
/// 꼬리말 처리 / Process footer
pub fn process_footer<'a>(
_header: &'a CtrlHeader,
_children: &'a [ParagraphRecord],
_paragraphs: &[Paragraph],
) -> CtrlHeaderResult<'a> {
// TODO: 꼬리말 처리 로직 추가 / Add footer processing logic
CtrlHeaderResult::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/column_def.rs | crates/hwp-core/src/viewer/html/ctrl_header/column_def.rs | use super::CtrlHeaderResult;
use crate::document::bodytext::ParagraphRecord;
use crate::document::{CtrlHeader, Paragraph};
/// 단 정의 처리 / Process column definition
pub fn process_column_def<'a>(
_header: &'a CtrlHeader,
_children: &'a [ParagraphRecord],
_paragraphs: &[Paragraph],
) -> CtrlHeaderResult<'a> {
// TODO: 단 정의 처리 로직 추가 / Add column definition processing logic
CtrlHeaderResult::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/footnote.rs | crates/hwp-core/src/viewer/html/ctrl_header/footnote.rs | use crate::document::bodytext::ParagraphRecord;
use crate::document::{CtrlHeader, Paragraph};
use super::CtrlHeaderResult;
/// 각주 처리 / Process footnote
pub fn process_footnote<'a>(
_header: &'a CtrlHeader,
_children: &'a [ParagraphRecord],
_paragraphs: &[Paragraph],
) -> CtrlHeaderResult<'a> {
// TODO: 각주 처리 로직 추가 / Add footnote processing logic
CtrlHeaderResult::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/header.rs | crates/hwp-core/src/viewer/html/ctrl_header/header.rs | use crate::document::bodytext::ParagraphRecord;
use crate::document::{CtrlHeader, Paragraph};
use super::CtrlHeaderResult;
/// 머리말 처리 / Process header
pub fn process_header<'a>(
_header: &'a CtrlHeader,
_children: &'a [ParagraphRecord],
_paragraphs: &[Paragraph],
) -> CtrlHeaderResult<'a> {
// TODO: 머리말 처리 로직 추가 / Add header processing logic
CtrlHeaderResult::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/mod.rs | crates/hwp-core/src/viewer/html/ctrl_header/mod.rs | mod column_def;
mod endnote;
mod footer;
mod footnote;
mod header;
mod section_def;
/// CtrlHeader 처리 모듈 / CtrlHeader processing module
///
/// 각 ctrl_id 타입별로 독립적인 모듈로 처리합니다.
/// Each ctrl_id type is processed in its own independent module.
mod shape_object;
// table 모듈은 폴더로 분리되어 있음 / table module is separated into a folder
pub mod table;
use crate::document::{CtrlHeader, CtrlId, Paragraph, ParagraphRecord};
use crate::viewer::html::line_segment::{ImageInfo, TableInfo};
use crate::viewer::HtmlOptions;
use crate::HwpDocument;
/// CtrlHeader 처리 결과 / CtrlHeader processing result
#[derive(Debug, Default)]
pub struct CtrlHeaderResult<'a> {
/// 추출된 테이블들 / Extracted tables
pub tables: Vec<TableInfo<'a>>,
/// 추출된 이미지들 / Extracted images
pub images: Vec<ImageInfo>,
}
impl<'a> CtrlHeaderResult<'a> {
pub fn new() -> Self {
Self {
tables: Vec::new(),
images: Vec::new(),
}
}
}
/// CtrlHeader 처리 / Process CtrlHeader
///
/// ctrl_id에 따라 적절한 모듈의 처리 함수를 호출합니다.
/// Calls the appropriate module's processing function according to ctrl_id.
pub fn process_ctrl_header<'a>(
header: &'a CtrlHeader,
children: &'a [ParagraphRecord],
paragraphs: &'a [Paragraph],
document: &'a HwpDocument,
options: &'a HtmlOptions,
) -> CtrlHeaderResult<'a> {
match header.ctrl_id.as_str() {
CtrlId::TABLE => {
// 테이블 컨트롤 처리 / Process table control
table::process_table(header, children, paragraphs)
}
CtrlId::SHAPE_OBJECT => {
// 그리기 개체 처리 / Process shape object
shape_object::process_shape_object(header, children, paragraphs, document, options)
}
CtrlId::SECTION_DEF => {
// 구역 정의 처리 / Process section definition
section_def::process_section_def(header, children, paragraphs)
}
CtrlId::COLUMN_DEF => {
// 단 정의 처리 / Process column definition
column_def::process_column_def(header, children, paragraphs)
}
CtrlId::HEADER => {
// 머리말 처리 / Process header
header::process_header(header, children, paragraphs)
}
CtrlId::FOOTER => {
// 꼬리말 처리 / Process footer
footer::process_footer(header, children, paragraphs)
}
CtrlId::FOOTNOTE => {
// 각주 처리 / Process footnote
footnote::process_footnote(header, children, paragraphs)
}
CtrlId::ENDNOTE => {
// 미주 처리 / Process endnote
endnote::process_endnote(header, children, paragraphs)
}
_ => {
// 기타 CtrlHeader 처리 / Process other CtrlHeader types
CtrlHeaderResult::new()
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/section_def.rs | crates/hwp-core/src/viewer/html/ctrl_header/section_def.rs | use super::CtrlHeaderResult;
use crate::document::bodytext::ParagraphRecord;
use crate::document::{CtrlHeader, Paragraph};
/// 구역 정의 처리 / Process section definition
pub fn process_section_def<'a>(
_header: &'a CtrlHeader,
_children: &'a [ParagraphRecord],
_paragraphs: &[Paragraph],
) -> CtrlHeaderResult<'a> {
// TODO: 구역 정의 처리 로직 추가 / Add section definition processing logic
CtrlHeaderResult::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/svg.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/svg.rs | /// SVG 렌더링 모듈 / SVG rendering module
use crate::document::bodytext::Table;
use crate::HwpDocument;
use crate::viewer::html::ctrl_header::table::constants::BORDER_OFFSET_MM;
use crate::viewer::html::ctrl_header::table::geometry::{column_positions, row_positions};
use crate::viewer::html::ctrl_header::table::position::ViewBox;
use crate::viewer::html::ctrl_header::table::size::Size;
mod borders;
mod fills;
pub(crate) fn render_svg(
table: &Table,
document: &HwpDocument,
view_box: &ViewBox,
content: Size,
ctrl_header_height_mm: Option<f64>,
pattern_counter: &mut usize, // 문서 레벨 pattern_counter (문서 전체에서 패턴 ID 공유) / Document-level pattern_counter (share pattern IDs across document)
color_to_pattern: &mut std::collections::HashMap<u32, String>, // 문서 레벨 color_to_pattern (문서 전체에서 패턴 ID 공유) / Document-level color_to_pattern (share pattern IDs across document)
) -> String {
let (pattern_defs, fills) = fills::render_fills(
table,
document,
ctrl_header_height_mm,
pattern_counter,
color_to_pattern,
);
let mut cols = column_positions(table);
// 테이블의 오른쪽 끝을 명시적으로 추가 (가장 오른쪽 셀의 오른쪽 경계가 content.width와 일치하지 않을 수 있음)
// Explicitly add table's right edge (rightmost cell's right boundary may not match content.width)
if let Some(&last_col) = cols.last() {
if (last_col - content.width).abs() > 0.01 {
cols.push(content.width);
cols.sort_by(|a, b| a.partial_cmp(b).unwrap());
}
} else {
cols.push(content.width);
}
let rows = row_positions(table, content.height, document, ctrl_header_height_mm);
let vertical =
borders::render_vertical_borders(table, document, &cols, content, ctrl_header_height_mm);
let horizontal = borders::render_horizontal_borders(
table,
document,
&rows,
content,
BORDER_OFFSET_MM,
ctrl_header_height_mm,
);
format!(
r#"<svg class="hs" viewBox="{} {} {} {}" style="left:{}mm;top:{}mm;width:{}mm;height:{}mm;"><defs>{}</defs>{}</svg>"#,
view_box.left,
view_box.top,
view_box.width,
view_box.height,
view_box.left,
view_box.top,
view_box.width,
view_box.height,
pattern_defs,
format!("{fills}{vertical}{horizontal}")
)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/process.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/process.rs | use crate::document::bodytext::ctrl_header::{CaptionAlign, CtrlHeaderData};
use crate::document::bodytext::{
ControlChar, ControlCharPosition, LineSegmentInfo, ParaTextRun, Paragraph, ParagraphRecord,
};
use crate::document::CtrlHeader;
use crate::viewer::html::ctrl_header::CtrlHeaderResult;
use crate::viewer::html::line_segment::TableInfo;
use super::render::{CaptionData, CaptionInfo, CaptionParagraph, CaptionText};
/// 캡션 텍스트를 구조적으로 분해 / Parse caption text into structured components
///
/// 실제 HWP 데이터 구조:
/// - 텍스트: "표 오른쪽"
/// - AUTO_NUMBER 컨트롤 문자가 position 2에 있음
/// - 따라서: label="표", number는 AUTO_NUMBER에서 생성, body="오른쪽"
///
/// Actual HWP data structure:
/// - Text: "표 오른쪽"
/// - AUTO_NUMBER control character at position 2
/// - Therefore: label="표", number generated from AUTO_NUMBER, body="오른쪽"
fn parse_caption_text(
text: &str,
control_char_positions: &[ControlCharPosition],
table_number: Option<u32>,
auto_number_display_text: Option<&str>,
) -> CaptionText {
// AUTO_NUMBER 컨트롤 문자 위치 찾기 / Find AUTO_NUMBER control character position
let auto_number_pos = control_char_positions
.iter()
.find(|cp| cp.code == ControlChar::AUTO_NUMBER)
.map(|cp| cp.position);
if let Some(auto_pos) = auto_number_pos {
// AUTO_NUMBER가 있으면 그 위치를 기준으로 분리 / If AUTO_NUMBER exists, split based on its position
let label = text
.chars()
.take(auto_pos)
.collect::<String>()
.trim()
.to_string();
let body = text
.chars()
.skip(auto_pos + 1) // AUTO_NUMBER 컨트롤 문자 건너뛰기 / Skip AUTO_NUMBER control character
.collect::<String>()
.trim()
.to_string();
CaptionText {
label: if label.is_empty() {
"표".to_string()
} else {
label
},
number: auto_number_display_text
.map(|s| s.to_string())
.or_else(|| table_number.map(|n| n.to_string()))
.unwrap_or_default(),
body,
}
} else {
// AUTO_NUMBER가 없으면 기존 방식으로 파싱 / If no AUTO_NUMBER, parse using existing method
let trimmed = text.trim();
// "표"로 시작하는지 확인 / Check if starts with "표"
if trimmed.starts_with("표") {
// "표" + 공백 제거 / Remove "표" and space
let after_label = trimmed.strip_prefix("표 ").unwrap_or(trimmed);
// 숫자 추출 / Extract number
let number_end = after_label
.char_indices()
.find(|(_, c)| !c.is_ascii_digit() && !c.is_whitespace())
.map(|(i, _)| i)
.unwrap_or(after_label.len());
let number = if number_end > 0 {
after_label[..number_end].trim().to_string()
} else {
table_number.map(|n| n.to_string()).unwrap_or_default()
};
// 본문 추출 / Extract body
let body = if number_end < after_label.len() {
after_label[number_end..].trim().to_string()
} else {
String::new()
};
CaptionText {
label: "표".to_string(),
number,
body,
}
} else {
// "표"로 시작하지 않으면 전체를 본문으로 처리 / If doesn't start with "표", treat entire text as body
CaptionText {
label: String::new(),
number: auto_number_display_text
.map(|s| s.to_string())
.or_else(|| table_number.map(|n| n.to_string()))
.unwrap_or_default(),
body: trimmed.to_string(),
}
}
}
}
/// 테이블 컨트롤 처리 / Process table control
///
/// CtrlHeader에서 테이블을 추출하고 캡션을 수집합니다.
/// Extracts tables from CtrlHeader and collects captions.
pub fn process_table<'a>(
header: &'a CtrlHeader,
children: &'a [ParagraphRecord],
paragraphs: &'a [Paragraph],
) -> CtrlHeaderResult<'a> {
let mut result = CtrlHeaderResult::new();
// CtrlHeader 객체를 직접 전달 / Pass CtrlHeader object directly
let (ctrl_header, caption_info) = match &header.data {
CtrlHeaderData::ObjectCommon { caption, .. } => {
let info = caption.as_ref().map(|cap| {
CaptionInfo {
align: cap.align, // 캡션 정렬 방향 / Caption alignment direction
is_above: matches!(cap.align, CaptionAlign::Top),
gap: Some(cap.gap), // HWPUNIT16은 i16이므로 직접 사용 / HWPUNIT16 is i16, so use directly
height_mm: None, // 캡션 높이는 별도로 계산 필요 / Caption height needs separate calculation
width: Some(cap.width.into()), // 캡션 폭 / Caption width
include_margin: Some(cap.include_margin), // 마진 포함 여부 / Whether to include margin
last_width: Some(cap.last_width.into()), // 텍스트 최대 길이 / Maximum text length
vertical_align: cap.vertical_align, // 캡션 수직 정렬 전달 / Pass caption vertical alignment
}
});
(Some(&header.data), info)
}
_ => (None, None),
};
// 캡션 텍스트 추출: paragraphs 필드에서 모든 캡션 수집 / Extract caption text: collect all captions from paragraphs field
// 여러 paragraph를 하나의 캡션으로 묶기 위해 paragraph 그룹화 / Group paragraphs to combine multiple paragraphs into one caption
let mut caption_paragraph_groups: Vec<Vec<CaptionParagraph>> = Vec::new();
let mut caption_texts: Vec<CaptionText> = Vec::new();
let mut caption_char_shape_ids: Vec<Option<usize>> = Vec::new();
let mut caption_para_shape_ids: Vec<Option<usize>> = Vec::new();
// paragraphs 필드에서 모든 캡션 수집 / Collect all captions from paragraphs field
// 여러 paragraph를 하나의 캡션으로 묶기: 첫 번째 paragraph를 메인으로 사용하고, 연속된 paragraph들도 같은 캡션에 포함
// Group multiple paragraphs into one caption: use first paragraph as main, include consecutive paragraphs in same caption
let mut current_para_group: Vec<CaptionParagraph> = Vec::new();
for para in paragraphs {
let mut caption_text_opt: Option<String> = None;
let mut caption_control_chars: Vec<ControlCharPosition> = Vec::new();
let mut caption_auto_number_display_text_opt: Option<String> = None;
let mut caption_auto_number_position_opt: Option<usize> = None;
let mut caption_char_shape_id_opt: Option<usize> = None;
let mut caption_line_segments_vec: Vec<&LineSegmentInfo> = Vec::new();
// para_shape_id 추출 / Extract para_shape_id
let para_shape_id = para.para_header.para_shape_id as usize;
for record in ¶.records {
if let ParagraphRecord::ParaText {
text,
control_char_positions,
runs,
..
} = record
{
if !text.trim().is_empty() {
caption_text_opt = Some(text.clone());
caption_control_chars = control_char_positions.clone();
// AUTO_NUMBER 위치 찾기 / Find AUTO_NUMBER position
caption_auto_number_position_opt = control_char_positions
.iter()
.find(|cp| cp.code == ControlChar::AUTO_NUMBER)
.map(|cp| cp.position);
caption_auto_number_display_text_opt = runs.iter().find_map(|run| {
if let ParaTextRun::Control {
code, display_text, ..
} = run
{
if *code == ControlChar::AUTO_NUMBER {
return display_text.clone();
}
}
None
});
}
} else if let ParagraphRecord::ParaCharShape { shapes } = record {
// 첫 번째 char_shape_id 찾기 / Find first char_shape_id
if let Some(shape_info) = shapes.first() {
caption_char_shape_id_opt = Some(shape_info.shape_id as usize);
}
} else if let ParagraphRecord::ParaLineSeg { segments } = record {
// 모든 LineSegmentInfo 수집 / Collect all LineSegmentInfo
caption_line_segments_vec = segments.iter().collect();
}
}
if let Some(text) = caption_text_opt {
let has_auto_number = caption_auto_number_position_opt.is_some();
// CaptionParagraph 생성 / Create CaptionParagraph
let caption_para = CaptionParagraph {
original_text: text.clone(),
line_segments: caption_line_segments_vec,
control_char_positions: caption_control_chars.clone(),
auto_number_position: caption_auto_number_position_opt,
auto_number_display_text: caption_auto_number_display_text_opt.clone(),
char_shape_id: caption_char_shape_id_opt,
para_shape_id,
};
if has_auto_number {
// AUTO_NUMBER가 있는 paragraph: 새로운 캡션 그룹 시작 / Paragraph with AUTO_NUMBER: start new caption group
// 이전 그룹이 있으면 저장 / Save previous group if exists
if !current_para_group.is_empty() {
caption_paragraph_groups.push(current_para_group);
current_para_group = Vec::new();
}
// 캡션 텍스트를 구조적으로 분해 (control_char_positions 포함) / Parse caption text into structured components (including control_char_positions)
let parsed = parse_caption_text(
&text,
&caption_control_chars,
None,
caption_auto_number_display_text_opt.as_deref(),
);
caption_texts.push(parsed);
caption_char_shape_ids.push(caption_char_shape_id_opt);
caption_para_shape_ids.push(Some(para_shape_id));
}
// 현재 paragraph를 그룹에 추가 / Add current paragraph to group
current_para_group.push(caption_para);
} else if !current_para_group.is_empty() {
// 텍스트가 없는 paragraph: 현재 그룹 종료 / Paragraph without text: end current group
caption_paragraph_groups.push(current_para_group);
current_para_group = Vec::new();
}
}
// 마지막 그룹 저장 / Save last group
if !current_para_group.is_empty() {
caption_paragraph_groups.push(current_para_group);
}
// 먼저 children을 순회하여 필요한 모든 캡션을 caption_texts에 추가
// First, iterate through children to add all necessary captions to caption_texts
let mut caption_text: Option<CaptionText> = None;
let mut found_table = false;
for child in children.iter() {
if let ParagraphRecord::Table { .. } = child {
found_table = true;
// caption_text가 있으면 caption_texts에 추가 / If caption_text exists, add to caption_texts
if let Some(caption) = caption_text.take() {
caption_texts.push(caption);
}
} else if found_table {
// 테이블 다음에 오는 문단에서 텍스트 추출 / Extract text from paragraph after table
if let ParagraphRecord::ParaText {
text,
control_char_positions,
runs,
..
} = child
{
let auto_disp = runs.iter().find_map(|run| {
if let ParaTextRun::Control {
code, display_text, ..
} = run
{
if *code == ControlChar::AUTO_NUMBER {
return display_text.as_deref();
}
}
None
});
caption_text = Some(parse_caption_text(
text,
control_char_positions,
None,
auto_disp,
));
break;
} else if let ParagraphRecord::ListHeader { paragraphs, .. } = child {
// ListHeader의 paragraphs에서 텍스트 추출 / Extract text from ListHeader's paragraphs
for para in paragraphs {
for record in ¶.records {
if let ParagraphRecord::ParaText {
text,
control_char_positions,
runs,
..
} = record
{
let auto_disp = runs.iter().find_map(|run| {
if let ParaTextRun::Control {
code, display_text, ..
} = run
{
if *code == ControlChar::AUTO_NUMBER {
return display_text.as_deref();
}
}
None
});
caption_text = Some(parse_caption_text(
text,
control_char_positions,
None,
auto_disp,
));
break;
}
}
if caption_text.is_some() {
break;
}
}
if caption_text.is_some() {
break;
}
}
} else {
// 테이블 이전에 오는 문단에서 텍스트 추출 (첫 번째 테이블의 캡션) / Extract text from paragraph before table (caption for first table)
if let ParagraphRecord::ParaText {
text,
control_char_positions,
runs,
..
} = child
{
let auto_disp = runs.iter().find_map(|run| {
if let ParaTextRun::Control {
code, display_text, ..
} = run
{
if *code == ControlChar::AUTO_NUMBER {
return display_text.as_deref();
}
}
None
});
caption_text = Some(parse_caption_text(
text,
control_char_positions,
None,
auto_disp,
));
} else if let ParagraphRecord::ListHeader { paragraphs, .. } = child {
// ListHeader의 paragraphs에서 텍스트 추출 / Extract text from ListHeader's paragraphs
for para in paragraphs {
for record in ¶.records {
if let ParagraphRecord::ParaText {
text,
control_char_positions,
runs,
..
} = record
{
let auto_disp = runs.iter().find_map(|run| {
if let ParaTextRun::Control {
code, display_text, ..
} = run
{
if *code == ControlChar::AUTO_NUMBER {
return display_text.as_deref();
}
}
None
});
caption_text = Some(parse_caption_text(
text,
control_char_positions,
None,
auto_disp,
));
break;
}
}
if caption_text.is_some() {
break;
}
}
}
}
}
// 마지막 caption_text도 추가 / Add last caption_text as well
if let Some(caption) = caption_text {
caption_texts.push(caption);
}
// 이제 children을 다시 순회하여 테이블에 캡션 할당
// Now iterate through children again to assign captions to tables
let mut caption_index = 0;
for child in children.iter() {
if let ParagraphRecord::Table { table } = child {
// 캡션 텍스트 가져오기 / Get caption text
let current_caption = if caption_index < caption_texts.len() {
Some(caption_texts[caption_index].clone())
} else {
None
};
// 캡션 paragraph 그룹 가져오기 / Get caption paragraph group
let current_caption_paragraphs = if caption_index < caption_paragraph_groups.len() {
caption_paragraph_groups[caption_index].clone()
} else {
Vec::new()
};
// CaptionData 생성 / Create CaptionData
let caption_data = if let (Some(text), Some(info)) = (current_caption, caption_info) {
Some(CaptionData {
text,
info,
paragraphs: current_caption_paragraphs,
})
} else {
None
};
caption_index += 1;
result.tables.push(TableInfo {
table,
ctrl_header,
anchor_char_pos: None,
caption: caption_data,
});
}
}
result
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/geometry.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/geometry.rs | use crate::document::bodytext::{ParagraphRecord, Table, TableCell};
use crate::viewer::html::styles::{int32_to_mm, round_to_2dp};
use crate::HwpDocument;
/// 셀의 왼쪽 위치 계산 / Calculate cell left position
pub(crate) fn calculate_cell_left(table: &Table, cell: &TableCell) -> f64 {
// 해당 행의 셀들을 사용하여 정확한 열 위치 계산 / Use cells from the same row to calculate accurate column positions
// 이렇게 하면 각 행의 실제 열 구조를 반영할 수 있음 / This way we can reflect the actual column structure of each row
let row_address = cell.cell_attributes.row_address;
let target_col = cell.cell_attributes.col_address;
// 같은 행의 셀들을 찾아서 정렬 / Find and sort cells from the same row
let mut row_cells: Vec<_> = table
.cells
.iter()
.filter(|c| c.cell_attributes.row_address == row_address)
.collect();
row_cells.sort_by_key(|c| c.cell_attributes.col_address);
let mut left = 0.0;
// target_col 이전의 모든 열 너비를 누적 / Accumulate width of all columns before target_col
for row_cell in &row_cells {
if row_cell.cell_attributes.col_address < target_col {
left += row_cell.cell_attributes.width.to_mm();
} else {
break;
}
}
left
}
/// 셀의 위쪽 위치 계산 / Calculate cell top position
pub(crate) fn calculate_cell_top(
table: &Table,
cell: &TableCell,
ctrl_header_height_mm: Option<f64>,
) -> f64 {
let mut top = 0.0;
for row_idx in 0..(cell.cell_attributes.row_address as usize) {
top += get_row_height(table, row_idx, ctrl_header_height_mm);
}
top
}
/// 행 높이 가져오기 / Get row height
pub(crate) fn get_row_height(
table: &Table,
row_index: usize,
ctrl_header_height_mm: Option<f64>,
) -> f64 {
// 먼저 해당 행의 셀 height 속성을 확인 (가장 정확한 방법) / First check cell height attributes for this row (most accurate method)
let mut max_cell_height: f64 = 0.0;
if !table.cells.is_empty() {
for cell in &table.cells {
if cell.cell_attributes.row_address as usize == row_index
&& cell.cell_attributes.row_span == 1
{
let cell_height = cell.cell_attributes.height.to_mm();
max_cell_height = max_cell_height.max(cell_height);
}
}
}
// row_sizes가 있으면 사용 (셀 height보다 우선순위 낮음) / Use row_sizes if available (lower priority than cell height)
if !table.attributes.row_sizes.is_empty() && row_index < table.attributes.row_sizes.len() {
if let Some(&row_size) = table.attributes.row_sizes.get(row_index) {
// row_size가 0이거나 매우 작은 값(< 100)일 때는 셀 height 사용
// When row_size is 0 or very small (< 100), use cell height
if row_size >= 100 {
let row_height = (row_size as f64 / 7200.0) * 25.4;
// row_size와 셀 height 중 더 큰 값 사용 / Use larger of row_size and cell height
return max_cell_height.max(row_height);
}
}
}
// 셀 height가 있으면 사용 / Use cell height if available
if max_cell_height > 0.0 {
return max_cell_height;
}
// 셀 height도 없으면 CtrlHeader height를 행 개수로 나눈 값 사용 (fallback)
// If no cell height, use CtrlHeader height divided by row count (fallback)
if let Some(ctrl_height) = ctrl_header_height_mm {
if table.attributes.row_count > 0 {
return ctrl_height / table.attributes.row_count as f64;
}
}
0.0
}
/// 셀의 실제 높이 가져오기 (rowspan 고려) / Get cell height considering rowspan
pub(crate) fn get_cell_height(
table: &Table,
cell: &TableCell,
ctrl_header_height_mm: Option<f64>,
) -> f64 {
let row_address = cell.cell_attributes.row_address as usize;
let row_span = if cell.cell_attributes.row_span == 0 {
1
} else {
cell.cell_attributes.row_span as usize
};
// 셀의 height 속성은 실제 셀 높이가 아니라 내부 여백이나 다른 의미일 수 있음
// 실제 셀 높이는 행 높이를 사용해야 함
// Cell's height attribute may not be the actual cell height but internal margin or other meaning
// Actual cell height should use row height
let mut height = 0.0;
for i in 0..row_span {
let row_h = get_row_height(table, row_address + i, ctrl_header_height_mm);
height += row_h;
}
// 행 높이가 0이면 셀 속성의 높이를 사용 (fallback)
// Use cell attribute height if row height is 0 (fallback)
if height < 0.1 {
let cell_height_attr = cell.cell_attributes.height.to_mm();
if cell_height_attr > 0.1 {
height = cell_height_attr;
}
}
height
}
/// 열 경계선 위치 계산 / Calculate column boundary positions
pub(crate) fn column_positions(table: &Table) -> Vec<f64> {
// 모든 행의 셀들을 고려하여 모든 열 경계선 위치 계산 / Calculate all column boundary positions considering cells from all rows
// 각 셀의 왼쪽과 오른쪽 경계를 수집하여 고유한 위치만 추출 / Collect left and right boundaries of each cell and extract unique positions
// f64는 Hash와 Ord를 구현하지 않으므로 Vec을 사용하고 수동으로 중복 제거 / Use Vec and manually remove duplicates since f64 doesn't implement Hash or Ord
let mut boundary_positions = Vec::new();
boundary_positions.push(0.0); // 항상 0부터 시작 / Always start from 0
// 모든 셀의 왼쪽과 오른쪽 경계를 수집 / Collect left and right boundaries of all cells
for cell in &table.cells {
let cell_left = calculate_cell_left(table, cell);
let cell_width = cell.cell_attributes.width.to_mm();
let cell_right = cell_left + cell_width;
boundary_positions.push(cell_left);
boundary_positions.push(cell_right);
}
// 정렬 / Sort
boundary_positions.sort_by(|a, b| a.partial_cmp(b).unwrap());
// 중복 제거 (부동소수점 비교는 작은 오차를 허용) / Remove duplicates (floating point comparison allows small errors)
let mut unique_positions = Vec::new();
let epsilon = 0.01; // 0.01mm 이내는 같은 위치로 간주 / Positions within 0.01mm are considered the same
for &pos in &boundary_positions {
if unique_positions.is_empty() {
unique_positions.push(pos);
} else {
let last_pos = unique_positions.last().unwrap();
if (pos - *last_pos).abs() > epsilon {
unique_positions.push(pos);
}
}
}
unique_positions
}
/// 셀 마진을 mm 단위로 변환 / Convert cell margin to mm
fn cell_margin_to_mm(margin_hwpunit: i16) -> f64 {
round_to_2dp(int32_to_mm(margin_hwpunit as i32))
}
/// 행 경계선 위치 계산 (shape component 높이 고려) / Calculate row boundary positions (considering shape component height)
pub(crate) fn row_positions(
table: &Table,
_content_height: f64,
document: &HwpDocument,
ctrl_header_height_mm: Option<f64>,
) -> Vec<f64> {
let mut positions = vec![0.0];
let mut current_y = 0.0;
if table.attributes.row_count > 0 {
// object_common.height를 행 개수로 나눈 기본 행 높이 계산 / Calculate base row height from object_common.height divided by row count
let base_row_height_mm = if let Some(ctrl_height) = ctrl_header_height_mm {
if table.attributes.row_count > 0 {
ctrl_height / table.attributes.row_count as f64
} else {
0.0
}
} else {
0.0
};
let mut max_row_heights_with_shapes: std::collections::HashMap<usize, f64> =
std::collections::HashMap::new();
// 재귀적으로 모든 ShapeComponent의 높이를 찾는 헬퍼 함수 / Helper function to recursively find height of all ShapeComponents
fn find_shape_component_height(
children: &[ParagraphRecord],
shape_component_height: u32,
) -> Option<f64> {
let mut max_height_mm: Option<f64> = None;
let mut has_paraline_seg = false;
let mut paraline_seg_height_mm: Option<f64> = None;
let _ = shape_component_height;
// 먼저 children을 순회하여 ParaLineSeg와 다른 shape component들을 찾기 / First iterate through children to find ParaLineSeg and other shape components
for child in children {
match child {
// ShapeComponentPicture: shape_component.height 사용
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
let _ = shape_component_picture;
let height_hwpunit = shape_component_height as i32;
let height_mm = round_to_2dp(int32_to_mm(height_hwpunit));
if max_height_mm.is_none() || height_mm > max_height_mm.unwrap() {
max_height_mm = Some(height_mm);
}
}
// 중첩된 ShapeComponent: 재귀적으로 탐색
ParagraphRecord::ShapeComponent {
shape_component,
children: nested_children,
} => {
if let Some(height) =
find_shape_component_height(nested_children, shape_component.height)
{
if max_height_mm.is_none() || height > max_height_mm.unwrap() {
max_height_mm = Some(height);
}
}
}
// 다른 shape component 타입들: shape_component.height 사용
ParagraphRecord::ShapeComponentLine { .. }
| ParagraphRecord::ShapeComponentRectangle { .. }
| ParagraphRecord::ShapeComponentEllipse { .. }
| ParagraphRecord::ShapeComponentArc { .. }
| ParagraphRecord::ShapeComponentPolygon { .. }
| ParagraphRecord::ShapeComponentCurve { .. }
| ParagraphRecord::ShapeComponentOle { .. }
| ParagraphRecord::ShapeComponentContainer { .. }
| ParagraphRecord::ShapeComponentTextArt { .. }
| ParagraphRecord::ShapeComponentUnknown { .. } => {
// shape_component.height 사용 / Use shape_component.height
let height_mm = round_to_2dp(int32_to_mm(shape_component_height as i32));
if max_height_mm.is_none() || height_mm > max_height_mm.unwrap() {
max_height_mm = Some(height_mm);
}
}
// ParaLineSeg: line_height 합산하여 높이 계산 (나중에 shape_component.height와 비교)
// ParaLineSeg: calculate height by summing line_height (compare with shape_component.height later)
ParagraphRecord::ParaLineSeg { segments } => {
has_paraline_seg = true;
let total_height_hwpunit: i32 =
segments.iter().map(|seg| seg.line_height).sum();
let height_mm = round_to_2dp(int32_to_mm(total_height_hwpunit));
if paraline_seg_height_mm.is_none()
|| height_mm > paraline_seg_height_mm.unwrap()
{
paraline_seg_height_mm = Some(height_mm);
}
}
_ => {}
}
}
// ParaLineSeg가 있으면 shape_component.height와 비교하여 더 큰 값 사용
// If ParaLineSeg exists, compare with shape_component.height and use the larger value
if has_paraline_seg {
let shape_component_height_mm =
round_to_2dp(int32_to_mm(shape_component_height as i32));
let paraline_seg_height = paraline_seg_height_mm.unwrap_or(0.0);
// shape_component.height와 ParaLineSeg 높이 중 더 큰 값 사용 / Use the larger value between shape_component.height and ParaLineSeg height
let final_height = shape_component_height_mm.max(paraline_seg_height);
if max_height_mm.is_none() || final_height > max_height_mm.unwrap() {
max_height_mm = Some(final_height);
}
} else if max_height_mm.is_none() {
// ParaLineSeg가 없고 다른 shape component도 없으면 shape_component.height 사용
// If no ParaLineSeg and no other shape components, use shape_component.height
let height_mm = round_to_2dp(int32_to_mm(shape_component_height as i32));
max_height_mm = Some(height_mm);
}
max_height_mm
}
for cell in &table.cells {
if cell.cell_attributes.row_span == 1 {
let row_idx = cell.cell_attributes.row_address as usize;
// 먼저 실제 셀 높이를 가져옴 (cell.cell_attributes.height 우선) / First get actual cell height (cell.cell_attributes.height has priority)
let mut cell_height = cell.cell_attributes.height.to_mm();
// shape component가 있는 셀의 경우 shape 높이 + 마진을 고려 / For cells with shape components, consider shape height + margin
let mut max_shape_height_mm: Option<f64> = None;
for para in &cell.paragraphs {
// ShapeComponent의 children에서 모든 shape 높이 찾기 (재귀적으로) / Find all shape heights in ShapeComponent's children (recursively)
for record in ¶.records {
match record {
ParagraphRecord::ShapeComponent {
shape_component,
children,
} => {
if let Some(shape_height_mm) =
find_shape_component_height(children, shape_component.height)
{
if max_shape_height_mm.is_none()
|| shape_height_mm > max_shape_height_mm.unwrap()
{
max_shape_height_mm = Some(shape_height_mm);
}
}
break; // ShapeComponent는 하나만 있음 / Only one ShapeComponent per paragraph
}
// ParaLineSeg가 paragraph records에 직접 있는 경우도 처리 / Also handle ParaLineSeg directly in paragraph records
ParagraphRecord::ParaLineSeg { segments } => {
let total_height_hwpunit: i32 =
segments.iter().map(|seg| seg.line_height).sum();
let height_mm = round_to_2dp(int32_to_mm(total_height_hwpunit));
if max_shape_height_mm.is_none()
|| height_mm > max_shape_height_mm.unwrap()
{
max_shape_height_mm = Some(height_mm);
}
}
_ => {}
}
}
}
// shape component가 있으면 셀 높이 = shape 높이 + 마진 / If shape component exists, cell height = shape height + margin
if let Some(shape_height_mm) = max_shape_height_mm {
let top_margin_mm = cell_margin_to_mm(cell.cell_attributes.top_margin);
let bottom_margin_mm = cell_margin_to_mm(cell.cell_attributes.bottom_margin);
let shape_height_with_margin =
shape_height_mm + top_margin_mm + bottom_margin_mm;
// shape 높이 + 마진이 기존 셀 높이보다 크면 사용 / Use shape height + margin if larger than existing cell height
if shape_height_with_margin > cell_height {
cell_height = shape_height_with_margin;
}
}
// shape component가 없고 셀 높이가 매우 작으면 object_common.height를 베이스로 사용 (fallback)
// If no shape component and cell height is very small, use object_common.height as base (fallback)
if max_shape_height_mm.is_none() && cell_height < 0.1 && base_row_height_mm > 0.0 {
cell_height = base_row_height_mm;
}
let entry = max_row_heights_with_shapes.entry(row_idx).or_insert(0.0f64);
*entry = (*entry).max(cell_height);
}
}
for row_idx in 0..table.attributes.row_count as usize {
if let Some(&height) = max_row_heights_with_shapes.get(&row_idx) {
current_y += height;
} else if base_row_height_mm > 0.0 {
// max_row_heights_with_shapes에 없으면 object_common.height를 행 개수로 나눈 값 사용 / If not in max_row_heights_with_shapes, use object_common.height divided by row count
current_y += base_row_height_mm;
} else if let Some(&row_size) = table.attributes.row_sizes.get(row_idx) {
current_y += (row_size as f64 / 7200.0) * 25.4;
}
positions.push(current_y);
}
}
positions
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/render.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/render.rs | use crate::document::bodytext::ctrl_header::{CaptionAlign, CaptionVAlign, CtrlHeaderData};
use crate::document::bodytext::{
ControlChar, ControlCharPosition, LineSegmentInfo, PageDef, Table,
};
use crate::types::{Hwpunit16ToMm, HWPUNIT};
use crate::viewer::html::styles::{int32_to_mm, round_to_2dp};
use crate::viewer::HtmlOptions;
use crate::{HwpDocument, INT32};
use super::constants::SVG_PADDING_MM;
use super::position::{table_position, view_box};
use super::size::{content_size, htb_size, resolve_container_size};
use super::{cells, svg};
/// 캡션 정보 / Caption information
#[derive(Debug, Clone, Copy)]
pub struct CaptionInfo {
/// 캡션 정렬 방향 / Caption alignment direction
pub align: CaptionAlign,
/// 캡션 위치 (true = 위, false = 아래) / Caption position (true = above, false = below)
pub is_above: bool,
/// 캡션과 개체 사이 간격 (hwpunit) / Spacing between caption and object (hwpunit)
pub gap: Option<i16>,
/// 캡션 높이 (mm) / Caption height (mm)
pub height_mm: Option<f64>,
/// 캡션 폭(세로 방향일 때만 사용) / Caption width (only for vertical direction)
pub width: Option<u32>,
/// 캡션 폭에 마진을 포함할 지 여부 (가로 방향일 때만 사용) / Whether to include margin in caption width (only for horizontal direction)
pub include_margin: Option<bool>,
/// 텍스트의 최대 길이(=개체의 폭) / Maximum text length (= object width)
pub last_width: Option<u32>,
/// 캡션 수직 정렬 (조합 캡션 구분용) / Caption vertical alignment (for combination caption detection)
pub vertical_align: Option<CaptionVAlign>,
}
/// 캡션 텍스트 구조 / Caption text structure
#[derive(Debug, Clone)]
pub struct CaptionText {
/// 캡션 라벨 (예: "표") / Caption label (e.g., "표")
pub label: String,
/// 캡션 번호 (예: "1", "2") / Caption number (e.g., "1", "2")
pub number: String,
/// 캡션 본문 (예: "위 캡션", "왼쪽") / Caption body (e.g., "위 캡션", "왼쪽")
pub body: String,
}
/// 캡션 단일 paragraph 정보 / Caption single paragraph info
#[derive(Debug, Clone)]
pub struct CaptionParagraph<'a> {
/// 원본 텍스트 (control characters 제거된 cleaned 텍스트) / Original text (cleaned text with control characters removed)
pub original_text: String,
/// 모든 LineSegment를 저장 / Store all LineSegments
pub line_segments: Vec<&'a LineSegmentInfo>,
/// 컨트롤 문자 위치 (원본 WCHAR 인덱스 기준) / Control character positions (original WCHAR index)
pub control_char_positions: Vec<ControlCharPosition>,
/// AUTO_NUMBER 위치 (이 paragraph 내에서의 위치) / AUTO_NUMBER position (within this paragraph)
pub auto_number_position: Option<usize>,
/// AUTO_NUMBER 표시 텍스트 / AUTO_NUMBER display text
pub auto_number_display_text: Option<String>,
/// 첫 번째 char_shape_id / First char_shape_id
pub char_shape_id: Option<usize>,
/// para_shape_id / Para shape ID
pub para_shape_id: usize,
}
/// 캡션 데이터 구조체 / Caption data struct
/// 캡션과 관련된 모든 정보를 하나로 묶음 / Bundles all caption-related information
#[derive(Debug, Clone)]
pub struct CaptionData<'a> {
/// 첫 번째 paragraph에서 파싱한 텍스트 (label, number, body) / Parsed text from first paragraph (label, number, body)
pub text: CaptionText,
/// 캡션 정보 / Caption info
pub info: CaptionInfo,
/// 모든 캡션 paragraph 배열 / Array of all caption paragraphs
pub paragraphs: Vec<CaptionParagraph<'a>>,
}
/// 테이블 렌더링 컨텍스트 / Table rendering context
pub struct TableRenderContext<'a> {
pub document: &'a HwpDocument,
pub ctrl_header: Option<&'a CtrlHeaderData>,
pub page_def: Option<&'a PageDef>,
pub options: &'a HtmlOptions,
pub table_number: Option<u32>,
pub pattern_counter: &'a mut usize,
pub color_to_pattern: &'a mut std::collections::HashMap<u32, String>,
}
/// 테이블 위치 정보 / Table position information
#[derive(Debug, Clone, Copy)]
pub struct TablePosition {
pub hcd_position: Option<(f64, f64)>,
pub segment_position: Option<(INT32, INT32)>,
pub para_start_vertical_mm: Option<f64>,
pub para_start_column_mm: Option<f64>,
pub para_segment_width_mm: Option<f64>,
pub first_para_vertical_mm: Option<f64>,
}
/// 테이블을 HTML로 렌더링 / Render table to HTML
pub fn render_table(
table: &Table,
context: &mut TableRenderContext,
position: TablePosition,
caption: Option<&CaptionData>,
) -> String {
// 구조체에서 개별 값 추출 / Extract individual values from structs
let document = context.document;
let ctrl_header = context.ctrl_header;
let page_def = context.page_def;
let _options = context.options;
let table_number = context.table_number;
// pattern_counter와 color_to_pattern은 이미 &mut이므로 직접 사용 / pattern_counter and color_to_pattern are already &mut, so use directly
let hcd_position = position.hcd_position;
let segment_position = position.segment_position;
let para_start_vertical_mm = position.para_start_vertical_mm;
let para_start_column_mm = position.para_start_column_mm;
let para_segment_width_mm = position.para_segment_width_mm;
let first_para_vertical_mm = position.first_para_vertical_mm;
// 캡션 데이터에서 개별 필드 추출 / Extract individual fields from caption data
let caption_text = caption.as_ref().map(|c| &c.text);
let caption_info = caption.as_ref().map(|c| c.info);
let caption_paragraphs = caption.as_ref().map(|c| &c.paragraphs);
// 첫 번째 paragraph에서 기본 정보 추출 / Extract basic info from first paragraph
let caption_char_shape_id = caption_paragraphs
.and_then(|paras| paras.first())
.and_then(|p| p.char_shape_id);
let caption_para_shape_id = caption_paragraphs
.and_then(|paras| paras.first())
.map(|p| p.para_shape_id);
let caption_auto_number_position = caption_paragraphs
.and_then(|paras| paras.first())
.and_then(|p| p.auto_number_position);
let caption_auto_number_display_text = caption_paragraphs
.and_then(|paras| paras.first())
.and_then(|p| p.auto_number_display_text.clone());
if table.cells.is_empty() || table.attributes.row_count == 0 {
return r#"<div class="htb" style="left:0mm;width:0mm;top:0mm;height:0mm;"></div>"#
.to_string();
}
// CtrlHeader에서 필요한 정보 추출 / Extract necessary information from CtrlHeader
// CtrlHeader height를 mm로 변환 / Convert CtrlHeader height to mm
let ctrl_header_height_mm =
if let Some(CtrlHeaderData::ObjectCommon { height, .. }) = ctrl_header {
Some(height.to_mm())
} else {
None
};
let container_size = htb_size(ctrl_header);
let content_size = content_size(table, ctrl_header);
let resolved_size = resolve_container_size(container_size, content_size);
// margin 값 미리 계산 (SVG viewBox 계산에 필요) / Pre-calculate margin values (needed for SVG viewBox calculation)
let margin_left_mm = if let Some(CtrlHeaderData::ObjectCommon { margin, .. }) = ctrl_header {
margin.left.to_mm()
} else {
0.0
};
let margin_left_mm = round_to_2dp(margin_left_mm);
let margin_right_mm = if let Some(CtrlHeaderData::ObjectCommon { margin, .. }) = ctrl_header {
margin.right.to_mm()
} else {
0.0
};
let margin_right_mm = round_to_2dp(margin_right_mm);
// SVG viewBox는 실제 테이블 콘텐츠 크기를 기준으로 계산해야 함 (margin 제외)
// SVG viewBox should be calculated based on actual table content size (excluding margin)
// resolved_size.width는 margin을 포함할 수 있으므로, margin을 제외한 실제 테이블 width를 사용
// resolved_size.width may include margin, so use actual table width excluding margin
let svg_width = resolved_size.width - margin_left_mm - margin_right_mm;
let svg_height = content_size.height;
let view_box = view_box(svg_width, svg_height, SVG_PADDING_MM);
let svg = svg::render_svg(
table,
document,
&view_box,
content_size,
ctrl_header_height_mm,
context.pattern_counter, // 문서 레벨 pattern_counter 전달 / Pass document-level pattern_counter
context.color_to_pattern, // 문서 레벨 color_to_pattern 전달 / Pass document-level color_to_pattern
);
let cells_html = cells::render_cells(
table,
ctrl_header_height_mm,
document,
_options,
context.pattern_counter,
context.color_to_pattern,
);
let (mut left_mm, mut top_mm) = table_position(
hcd_position,
page_def,
segment_position,
ctrl_header,
Some(resolved_size.width),
para_start_vertical_mm,
para_start_column_mm,
para_segment_width_mm,
first_para_vertical_mm,
);
// htG 래퍼 생성 (캡션이 있거나 ctrl_header가 있는 경우) / Create htG wrapper (if caption exists or ctrl_header exists)
// 캡션 유무는 caption_info 존재 여부로 판단 / Determine caption existence by caption_info presence
let has_caption = caption_info.is_some();
// LineSegment(=글자처럼 취급/인라인) 테이블 처리
// - 일부 fixture(noori 등)에서는 htG 없이 htb만 존재하지만,
// - table-position 처럼 "캡션이 있는 인라인 테이블"은 htG 래퍼가 필요(캡션 블록이 htG 하위로 들어감)
// 따라서: LineSegment 내부라도 캡션이 있으면 htG를 생성한다.
let is_inline_table = segment_position.is_some();
let needs_htg = if is_inline_table {
has_caption
} else {
has_caption || ctrl_header.is_some()
};
// 인라인 테이블은 문단(line segment) 내부에서 상대 위치로 렌더링되므로,
// htG의 left/top은 0으로 고정해야 fixture와 일치한다.
if is_inline_table && needs_htg {
left_mm = 0.0;
top_mm = 0.0;
}
// margin 값 미리 계산 (margin_left_mm, margin_right_mm은 이미 위에서 계산됨) / Pre-calculate margin values (margin_left_mm, margin_right_mm already calculated above)
let margin_top_mm = if let Some(CtrlHeaderData::ObjectCommon { margin, .. }) = ctrl_header {
margin.top.to_mm()
} else {
0.0
};
let margin_top_mm = round_to_2dp(margin_top_mm);
let margin_bottom_mm = if let Some(CtrlHeaderData::ObjectCommon { margin, .. }) = ctrl_header {
margin.bottom.to_mm()
} else {
0.0
};
let margin_bottom_mm = round_to_2dp(margin_bottom_mm);
// resolved_size.height가 margin을 포함하지 않는 경우를 대비하여 명시적으로 계산
// Calculate explicitly in case resolved_size.height doesn't include margin
let resolved_height_with_margin = if container_size.height == 0.0 {
// container가 없으면 content.height + margin.top + margin.bottom
// If no container, use content.height + margin.top + margin.bottom
content_size.height + margin_top_mm + margin_bottom_mm
} else {
// container가 있으면 이미 margin이 포함되어 있음
// If container exists, margin is already included
resolved_size.height
};
// 캡션 정보 미리 계산 / Pre-calculate caption information
let is_caption_above = caption_info.map(|info| info.is_above).unwrap_or(false);
// 캡션 방향 확인 (가로/세로) / Check caption direction (horizontal/vertical)
// Top/Bottom: 가로 방향 (horizontal), Left/Right: 세로 방향 (vertical)
let caption_align = caption_info.map(|info| info.align);
let is_horizontal = matches!(
caption_align,
Some(CaptionAlign::Top) | Some(CaptionAlign::Bottom)
);
let is_vertical = matches!(
caption_align,
Some(CaptionAlign::Left) | Some(CaptionAlign::Right)
);
let is_left = matches!(caption_align, Some(CaptionAlign::Left));
let is_right = matches!(caption_align, Some(CaptionAlign::Right));
// 캡션 간격: gap 속성을 사용하여 계산 / Caption spacing: calculate using gap property
let caption_margin_mm = if let Some(info) = caption_info {
if let Some(gap_hwpunit) = info.gap {
// HWPUNIT16을 mm로 변환 / Convert HWPUNIT16 to mm
(gap_hwpunit as f64 / 7200.0) * 25.4
} else {
// gap이 없으면 기본값 사용 / Use default if gap not provided
if is_caption_above {
5.0
} else {
3.0
}
}
} else {
// 캡션 정보가 없으면 기본값 / Default if no caption info
if is_caption_above {
5.0
} else {
3.0
}
};
// 캡션 크기 미리 계산 (htb 위치 및 htG 크기 계산에 필요) / Pre-calculate caption size (needed for htb position and htG size calculation)
let (caption_width_mm, caption_height_mm) = if has_caption {
let width = if let Some(info) = caption_info {
if is_horizontal {
// 가로 방향(Top/Bottom): last_width만 사용, include_margin으로 마진 포함 여부 결정
// Horizontal direction: use last_width only, determine margin inclusion with include_margin
if let Some(last_width_hwpunit) = info.last_width {
let width_mm = HWPUNIT::from(last_width_hwpunit).to_mm();
if let Some(include_margin) = info.include_margin {
if include_margin {
// include_margin이 true이면 마진을 포함한 전체 폭 사용
// If include_margin is true, use full width including margin
width_mm
} else {
// include_margin이 false이면 last_width는 이미 마진을 제외한 값이므로 그대로 사용
// If include_margin is false, last_width is already without margin, so use as is
width_mm
}
} else {
// include_margin이 없으면 기본적으로 마진 제외한 값으로 간주
// If include_margin is not present, assume value without margin by default
width_mm
}
} else {
resolved_size.width - (margin_left_mm * 2.0)
}
} else {
// 세로 방향(Left/Right): width만 사용
// Vertical direction: use width only
if let Some(width_hwpunit) = info.width {
HWPUNIT::from(width_hwpunit).to_mm()
} else {
30.0 // 기본값: fixture에서 확인한 값 / Default: value from fixture
}
}
} else {
resolved_size.width - (margin_left_mm * 2.0)
};
let height = if is_vertical {
// 세로 방향: 테이블 높이와 같거나 더 큼 / Vertical direction: same or greater than table height
content_size.height
} else {
// 가로 방향: 모든 paragraph의 LineSegment를 고려하여 전체 높이 계산 / Horizontal direction: calculate total height considering all paragraphs' LineSegments
if let Some(paragraphs) = caption_paragraphs {
// 모든 paragraph의 LineSegment를 수집 / Collect LineSegments from all paragraphs
let mut all_segments = Vec::new();
let mut cumulative_text_len = 0;
for para in paragraphs.iter() {
for segment in para.line_segments.iter() {
all_segments.push((segment, cumulative_text_len));
}
// 다음 paragraph를 위해 누적 길이 업데이트 / Update cumulative length for next paragraph
cumulative_text_len += para.original_text.chars().count()
+ para
.control_char_positions
.iter()
.map(|cc| ControlChar::get_size_by_code(cc.code) as usize)
.sum::<usize>();
}
if all_segments.len() > 1 {
// 마지막 LineSegment의 vertical_position + line_height를 사용 / Use last segment's vertical_position + line_height
if let Some((last_segment, _)) = all_segments.last() {
let last_vertical_mm =
round_to_2dp(int32_to_mm(last_segment.vertical_position));
let last_line_height_mm =
round_to_2dp(int32_to_mm(last_segment.line_height));
round_to_2dp(last_vertical_mm + last_line_height_mm)
} else {
caption_info.and_then(|info| info.height_mm).unwrap_or(3.53)
}
} else if let Some((segment, _)) = all_segments.first() {
// 단일 LineSegment: line_height 사용 / Single LineSegment: use line_height
round_to_2dp(int32_to_mm(segment.line_height))
} else {
caption_info.and_then(|info| info.height_mm).unwrap_or(3.53)
}
} else {
// LineSegment 정보가 없으면 기본 높이 / Default height if no LineSegment info
caption_info.and_then(|info| info.height_mm).unwrap_or(3.53)
}
};
(round_to_2dp(width), round_to_2dp(height))
} else {
(0.0, 0.0)
};
// 캡션 렌더링 / Render caption
// 캡션 유무는 caption_info 존재 여부로 판단 / Determine caption existence by caption_info presence
let caption_html = if let Some(caption) = caption_text {
if !has_caption {
String::new()
} else {
// 분해된 캡션 텍스트 사용 / Use parsed caption text
let caption_label = if !caption.label.is_empty() {
caption.label.clone()
} else {
"표".to_string() // 기본값 / Default
};
let table_num_text = if !caption.number.is_empty() {
caption.number.clone()
} else {
table_number.map(|n| n.to_string()).unwrap_or_default()
};
let caption_body = caption.body.clone();
// 캡션 HTML 생성 / Generate caption HTML
let caption_base_left_mm =
if let Some(CtrlHeaderData::ObjectCommon { margin, .. }) = ctrl_header {
margin.left.to_mm()
} else {
0.0
};
// htb width 미리 계산 (캡션 위치 계산에 필요) / Pre-calculate htb width (needed for caption position calculation)
// resolved_size.width는 이미 margin.left + margin.right가 포함되어 있을 수 있으므로,
// resolved_size.width already may include margin.left + margin.right, so
// 실제 테이블 width는 resolved_size.width - margin.left - margin.right
// actual table width is resolved_size.width - margin.left - margin.right
let htb_width_mm_for_caption = resolved_size.width - margin_left_mm - margin_right_mm;
// 캡션 위치 계산 (left, top) / Calculate caption position (left, top)
let (mut caption_left_mm, mut caption_top_mm) = if is_vertical {
// 세로 방향 (Left/Right): 캡션이 세로로 배치됨 / Vertical direction: caption placed vertically
if is_left {
// 왼쪽 캡션: 캡션이 왼쪽에, 테이블이 오른쪽에 / Left caption: caption on left, table on right
(margin_left_mm, margin_top_mm)
} else if is_right {
// 오른쪽 캡션: 테이블이 왼쪽에, 캡션이 오른쪽에 / Right caption: table on left, caption on right
// 캡션 left = margin.left + htb width + gap
// Caption left = margin.left + htb width + gap
(
margin_left_mm + htb_width_mm_for_caption + caption_margin_mm,
margin_top_mm,
)
} else {
// 기본값 (발생하지 않아야 함) / Default (should not occur)
(margin_left_mm, margin_top_mm)
}
} else {
// 가로 방향 (Top/Bottom): 캡션이 가로로 배치됨 / Horizontal direction: caption placed horizontally
// include_margin이 true이면 left는 0mm (last_width가 마진을 포함한 전체 폭이므로)
// If include_margin is true, left should be 0mm (last_width includes full width with margin)
let left = if let Some(info) = caption_info {
if let Some(include_margin) = info.include_margin {
if include_margin {
// include_margin이 true이면 last_width가 마진을 포함한 전체 폭이므로 left는 0mm
// If include_margin is true, last_width includes full width with margin, so left is 0mm
0.0
} else {
caption_base_left_mm
}
} else {
caption_base_left_mm
}
} else {
caption_base_left_mm
};
let top = if is_caption_above {
// 위 캡션: htG 내부에서의 상대 위치는 margin.top
// Top caption: relative position within htG is margin.top
// Fixture 기준: 위 캡션은 htG 내부에서 top:10mm (margin.top 값)
// Based on fixture: top caption is at top:10mm within htG (margin.top value)
margin_top_mm
} else {
// 아래 캡션: htG 내부에서 htb 아래에 배치
// Bottom caption: placed below htb within htG
// Fixture 기준: 아래 캡션은 htG 내부에서 top:17.52mm = margin.top(10mm) + content.height(4.52mm) + gap(3mm)
// Based on fixture: bottom caption is at top:17.52mm = margin.top(10mm) + content.height(4.52mm) + gap(3mm)
// 아래 캡션이 있을 때 htb_top_mm은 margin_top_mm이므로, margin_top_mm + content_size.height + caption_margin_mm 사용
// When bottom caption exists, htb_top_mm equals margin_top_mm, so use margin_top_mm + content_size.height + caption_margin_mm
margin_top_mm + content_size.height + caption_margin_mm
};
(left, top)
};
// 캡션 위치를 mm 2자리까지 반올림 / Round caption position to 2 decimal places
caption_left_mm = round_to_2dp(caption_left_mm);
caption_top_mm = round_to_2dp(caption_top_mm);
// 캡션 문단의 첫 번째 char_shape_id 사용 / Use first char_shape_id from caption paragraph
let caption_char_shape_id_value = caption_char_shape_id.unwrap_or(0); // 기본값: 0 / Default: 0
let cs_class = format!("cs{}", caption_char_shape_id_value);
// 캡션 문단의 para_shape_id 사용 / Use para_shape_id from caption paragraph
// document.doc_info.para_shapes에서 실제 ParaShape를 확인하여 ID로 추출
// Extract ID by checking actual ParaShape from document.doc_info.para_shapes
let ps_class = if let Some(para_shape_id) = caption_para_shape_id {
// HWP 파일의 para_shape_id는 0-based indexing을 사용합니다 / HWP file uses 0-based indexing for para_shape_id
if para_shape_id < document.doc_info.para_shapes.len() {
format!("ps{}", para_shape_id)
} else {
String::new()
}
} else {
String::new()
};
// 세로 방향 캡션의 경우 hcI에 top 스타일 추가 / Add top style to hcI for vertical captions
let hci_style = if is_vertical {
// fixture에서 확인: 왼쪽/오른쪽 캡션은 hcI에 top:0.50mm 또는 top:0.99mm 추가
// From fixture: left/right captions have top:0.50mm or top:0.99mm in hcI
if is_right {
"style=\"top:0.99mm;\""
} else {
"style=\"top:0.50mm;\""
}
} else {
""
};
// 모든 paragraph의 LineSegment를 별도의 hls div로 렌더링 / Render each LineSegment from all paragraphs as separate hls div
let hls_divs = if let Some(paragraphs) = caption_paragraphs {
// 모든 paragraph의 LineSegment를 수집 / Collect LineSegments from all paragraphs
let mut all_segments_with_info = Vec::new();
let mut cumulative_text_len = 0;
for (para_idx, para) in paragraphs.iter().enumerate() {
if para.line_segments.is_empty() {
// LineSegment가 없으면 다음 paragraph로 / Skip if no LineSegments
cumulative_text_len += para.original_text.chars().count()
+ para
.control_char_positions
.iter()
.map(|cc| ControlChar::get_size_by_code(cc.code) as usize)
.sum::<usize>();
continue;
}
for segment in para.line_segments.iter() {
all_segments_with_info.push((segment, para_idx, para, cumulative_text_len));
}
// 다음 paragraph를 위해 누적 길이 업데이트 / Update cumulative length for next paragraph
cumulative_text_len += para.original_text.chars().count()
+ para
.control_char_positions
.iter()
.map(|cc| ControlChar::get_size_by_code(cc.code) as usize)
.sum::<usize>();
}
if all_segments_with_info.is_empty() {
// LineSegment가 없으면 fallback / Fallback if no LineSegments
let (line_height_mm, top_offset_mm, caption_hls_left_mm, caption_hls_width_mm) =
(2.79, -0.18, 0.0, caption_width_mm);
vec![format!(
r#"<div class="hls {ps_class}" style="line-height:{line_height_mm}mm;white-space:nowrap;left:{caption_hls_left_mm}mm;top:{top_offset_mm}mm;height:{caption_height_mm}mm;width:{caption_hls_width_mm}mm;"><span class="hrt {cs_class}">{caption_label} </span><div class="haN" style="left:0mm;top:0mm;height:{caption_height_mm}mm;"><span class="hrt {cs_class}">{table_num_text}</span></div><span class="hrt {cs_class}"> {caption_body}</span></div>"#,
ps_class = ps_class,
line_height_mm = line_height_mm,
top_offset_mm = top_offset_mm,
caption_hls_left_mm = caption_hls_left_mm,
caption_height_mm = caption_height_mm,
caption_hls_width_mm = caption_hls_width_mm,
cs_class = cs_class,
caption_label = caption_label,
table_num_text = table_num_text,
caption_body = caption_body
)]
} else {
// 각 LineSegment에 대해 텍스트 분할 및 렌더링 / Split text and render for each LineSegment
let mut hls_htmls = Vec::new();
// line_segment.rs의 함수와 동일한 로직 사용 / Use same logic as line_segment.rs
fn original_to_cleaned_index(
pos: usize,
control_chars: &[ControlCharPosition],
) -> isize {
let mut delta: isize = 0;
for cc in control_chars.iter() {
if cc.position >= pos {
break;
}
let size = ControlChar::get_size_by_code(cc.code) as isize;
let contributes = if ControlChar::is_convertible(cc.code)
&& cc.code != ControlChar::PARA_BREAK
&& cc.code != ControlChar::LINE_BREAK
{
1
} else {
0
} as isize;
delta += contributes - size;
}
delta
}
fn slice_cleaned_by_original_range(
cleaned: &str,
control_chars: &[ControlCharPosition],
start_original: usize,
end_original: usize,
) -> String {
let start_delta = original_to_cleaned_index(start_original, control_chars);
let end_delta = original_to_cleaned_index(end_original, control_chars);
let start_cleaned = (start_original as isize + start_delta).max(0) as usize;
let end_cleaned = (end_original as isize + end_delta).max(0) as usize;
let cleaned_chars: Vec<char> = cleaned.chars().collect();
let s = start_cleaned.min(cleaned_chars.len());
let e = end_cleaned.min(cleaned_chars.len());
if s >= e {
return String::new();
}
cleaned_chars[s..e].iter().collect()
}
for (global_idx, (segment, para_idx, para, para_cumulative_len)) in
all_segments_with_info.iter().enumerate()
{
let lh = round_to_2dp(int32_to_mm(segment.baseline_distance));
let text_height_mm = round_to_2dp(int32_to_mm(segment.text_height));
let top_off = round_to_2dp((lh - text_height_mm) / 2.0);
let left_mm = round_to_2dp(int32_to_mm(segment.column_start_position));
let width_mm = round_to_2dp(int32_to_mm(segment.segment_width));
// para_shape_id 가져오기 / Get para_shape_id
let para_ps_class =
if para.para_shape_id < document.doc_info.para_shapes.len() {
format!("ps{}", para.para_shape_id)
} else {
String::new()
};
// vertical_position을 mm로 변환 / Convert vertical_position to mm
// 첫 번째 LineSegment는 top_off만 사용, 이후는 vertical_position을 직접 사용
// First LineSegment uses only top_off, others use vertical_position directly
let segment_top_mm = if global_idx == 0 {
round_to_2dp(top_off)
} else {
// 이후 LineSegment는 vertical_position을 mm로 변환하여 사용
// Subsequent LineSegments use vertical_position converted to mm
round_to_2dp(int32_to_mm(segment.vertical_position))
};
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | true |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/mod.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/mod.rs | /// 테이블 컨트롤 처리 및 렌더링 모듈 / Table control processing and rendering module
///
/// 이 모듈은 실제 구현을 `render`와 `process` 서브모듈에 위임하고,
/// 외부에서는 동일한 API(`render_table`, `process_table`, `CaptionInfo`)만 노출합니다.
pub mod cells;
pub mod constants;
pub mod geometry;
pub mod position;
pub mod process;
pub mod render;
pub mod size;
pub mod svg;
pub use process::process_table;
pub use render::{render_table, CaptionData, TablePosition, TableRenderContext};
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/cells.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/cells.rs | use std::collections::HashMap;
use crate::document::bodytext::list_header::VerticalAlign;
use crate::document::bodytext::{LineSegmentInfo, ParagraphRecord, Table};
use crate::document::CtrlHeaderData;
use crate::viewer::html::line_segment::{
render_line_segments_with_content, DocumentRenderState, ImageInfo, LineSegmentContent,
LineSegmentRenderContext,
};
use crate::viewer::html::styles::{int32_to_mm, round_to_2dp};
use crate::viewer::html::{common, ctrl_header};
use crate::viewer::html::{image, text};
use crate::viewer::HtmlOptions;
use crate::{HwpDocument, INT32};
use super::geometry::{calculate_cell_left, get_cell_height, get_row_height};
/// 셀 마진을 mm 단위로 변환 / Convert cell margin to mm
fn cell_margin_to_mm(margin_hwpunit: i16) -> f64 {
round_to_2dp(int32_to_mm(margin_hwpunit as i32))
}
pub(crate) fn render_cells(
table: &Table,
ctrl_header_height_mm: Option<f64>,
document: &HwpDocument,
options: &HtmlOptions,
pattern_counter: &mut usize, // 문서 레벨 pattern_counter (문서 전체에서 패턴 ID 공유) / Document-level pattern_counter (share pattern IDs across document)
color_to_pattern: &mut HashMap<u32, String>, // 문서 레벨 color_to_pattern (문서 전체에서 패턴 ID 공유) / Document-level color_to_pattern (share pattern IDs across document)
) -> String {
// 각 행의 최대 셀 높이 계산 (실제 셀 높이만 사용) / Calculate max cell height for each row (use only actual cell height)
let mut max_row_heights: HashMap<usize, f64> = HashMap::new();
for cell in &table.cells {
let row_idx = cell.cell_attributes.row_address as usize;
let col_idx = cell.cell_attributes.col_address as usize;
// 실제 셀 높이 가져오기 / Get actual cell height
let mut cell_height = get_cell_height(table, cell, ctrl_header_height_mm);
// shape component 높이 찾기 (재귀적으로) / Find shape component height (recursively)
let mut max_shape_height_mm: Option<f64> = None;
// 재귀적으로 모든 ShapeComponent의 높이를 찾는 헬퍼 함수 / Helper function to recursively find height of all ShapeComponents
fn find_shape_component_height(
children: &[ParagraphRecord],
shape_component_height: u32,
) -> Option<f64> {
let mut max_height_mm: Option<f64> = None;
let mut has_paraline_seg = false;
let mut paraline_seg_height_mm: Option<f64> = None;
// 먼저 children을 순회하여 ParaLineSeg와 다른 shape component들을 찾기 / First iterate through children to find ParaLineSeg and other shape components
for child in children {
match child {
// ShapeComponentPicture: shape_component.height 사용
ParagraphRecord::ShapeComponentPicture { .. } => {
let height_hwpunit = shape_component_height as i32;
let height_mm = round_to_2dp(int32_to_mm(height_hwpunit));
if max_height_mm.is_none() || height_mm > max_height_mm.unwrap() {
max_height_mm = Some(height_mm);
}
}
// 중첩된 ShapeComponent: 재귀적으로 탐색
ParagraphRecord::ShapeComponent {
shape_component,
children: nested_children,
} => {
if let Some(height) =
find_shape_component_height(nested_children, shape_component.height)
{
if max_height_mm.is_none() || height > max_height_mm.unwrap() {
max_height_mm = Some(height);
}
}
}
// 다른 shape component 타입들: shape_component.height 사용
ParagraphRecord::ShapeComponentLine { .. }
| ParagraphRecord::ShapeComponentRectangle { .. }
| ParagraphRecord::ShapeComponentEllipse { .. }
| ParagraphRecord::ShapeComponentArc { .. }
| ParagraphRecord::ShapeComponentPolygon { .. }
| ParagraphRecord::ShapeComponentCurve { .. }
| ParagraphRecord::ShapeComponentOle { .. }
| ParagraphRecord::ShapeComponentContainer { .. }
| ParagraphRecord::ShapeComponentTextArt { .. }
| ParagraphRecord::ShapeComponentUnknown { .. } => {
// shape_component.height 사용 / Use shape_component.height
let height_mm = round_to_2dp(int32_to_mm(shape_component_height as i32));
if max_height_mm.is_none() || height_mm > max_height_mm.unwrap() {
max_height_mm = Some(height_mm);
}
}
// ParaLineSeg: line_height 합산하여 높이 계산 (나중에 shape_component.height와 비교)
// ParaLineSeg: calculate height by summing line_height (compare with shape_component.height later)
ParagraphRecord::ParaLineSeg { segments } => {
has_paraline_seg = true;
let total_height_hwpunit: i32 =
segments.iter().map(|seg| seg.line_height).sum();
let height_mm = round_to_2dp(int32_to_mm(total_height_hwpunit));
if paraline_seg_height_mm.is_none()
|| height_mm > paraline_seg_height_mm.unwrap()
{
paraline_seg_height_mm = Some(height_mm);
}
}
_ => {}
}
}
// ParaLineSeg가 있으면 shape_component.height와 비교하여 더 큰 값 사용
// If ParaLineSeg exists, compare with shape_component.height and use the larger value
if has_paraline_seg {
let shape_component_height_mm =
round_to_2dp(int32_to_mm(shape_component_height as i32));
let paraline_seg_height = paraline_seg_height_mm.unwrap_or(0.0);
// shape_component.height와 ParaLineSeg 높이 중 더 큰 값 사용 / Use the larger value between shape_component.height and ParaLineSeg height
let final_height = shape_component_height_mm.max(paraline_seg_height);
if max_height_mm.is_none() || final_height > max_height_mm.unwrap() {
max_height_mm = Some(final_height);
}
} else if max_height_mm.is_none() {
// ParaLineSeg가 없고 다른 shape component도 없으면 shape_component.height 사용
// If no ParaLineSeg and no other shape components, use shape_component.height
let height_mm = round_to_2dp(int32_to_mm(shape_component_height as i32));
max_height_mm = Some(height_mm);
}
max_height_mm
}
for para in &cell.paragraphs {
// ShapeComponent의 children에서 모든 shape 높이 찾기 (재귀적으로) / Find all shape heights in ShapeComponent's children (recursively)
for record in ¶.records {
match record {
ParagraphRecord::ShapeComponent {
shape_component,
children,
} => {
if let Some(shape_height_mm) =
find_shape_component_height(children, shape_component.height)
{
if max_shape_height_mm.is_none()
|| shape_height_mm > max_shape_height_mm.unwrap()
{
max_shape_height_mm = Some(shape_height_mm);
}
}
break; // ShapeComponent는 하나만 있음 / Only one ShapeComponent per paragraph
}
// ParaLineSeg가 paragraph records에 직접 있는 경우도 처리 / Also handle ParaLineSeg directly in paragraph records
ParagraphRecord::ParaLineSeg { segments } => {
let total_height_hwpunit: i32 =
segments.iter().map(|seg| seg.line_height).sum();
let height_mm = round_to_2dp(int32_to_mm(total_height_hwpunit));
if max_shape_height_mm.is_none() || height_mm > max_shape_height_mm.unwrap()
{
max_shape_height_mm = Some(height_mm);
}
}
_ => {}
}
}
}
// shape component 높이 + 마진이 셀 높이보다 크면 사용 / Use shape height + margin if larger than cell height
if let Some(shape_height_mm) = max_shape_height_mm {
let top_margin_mm = cell_margin_to_mm(cell.cell_attributes.top_margin);
let bottom_margin_mm = cell_margin_to_mm(cell.cell_attributes.bottom_margin);
let shape_height_with_margin = shape_height_mm + top_margin_mm + bottom_margin_mm;
if shape_height_with_margin > cell_height {
cell_height = shape_height_with_margin;
}
}
let entry = max_row_heights.entry(row_idx).or_insert(0.0f64);
*entry = (*entry).max(cell_height);
}
let mut cells_html = String::new();
for cell in &table.cells {
let cell_left = calculate_cell_left(table, cell);
// max_row_heights를 사용하여 cell_top 계산 (shape 높이 반영) / Calculate cell_top using max_row_heights (reflecting shape height)
let row_address = cell.cell_attributes.row_address as usize;
let mut cell_top = 0.0;
for row_idx in 0..row_address {
if let Some(&row_height) = max_row_heights.get(&row_idx) {
cell_top += row_height;
} else {
// max_row_heights에 없으면 기존 방식 사용 / Use existing method if not in max_row_heights
cell_top += get_row_height(table, row_idx, ctrl_header_height_mm);
}
}
let cell_width = cell.cell_attributes.width.to_mm();
// 같은 행의 모든 셀은 같은 높이를 가져야 함 (행의 최대 높이 사용, shape component 높이 포함) / All cells in the same row should have the same height (use row's max height, including shape component height)
let row_idx = cell.cell_attributes.row_address as usize;
let cell_height = if let Some(&row_max_height) = max_row_heights.get(&row_idx) {
// max_row_heights는 이미 shape component 높이를 포함하여 계산됨 / max_row_heights already includes shape component height
row_max_height
} else {
// max_row_heights가 없으면 실제 셀 높이 사용 (object_common.height는 fallback) / If max_row_heights not available, use actual cell height (object_common.height is fallback)
get_cell_height(table, cell, ctrl_header_height_mm)
};
// 셀 마진(mm) 계산은 렌더링 전반(특히 special-case)에서 필요하므로 먼저 계산합니다.
let left_margin_mm = cell_margin_to_mm(cell.cell_attributes.left_margin);
let right_margin_mm = cell_margin_to_mm(cell.cell_attributes.right_margin);
let top_margin_mm = cell_margin_to_mm(cell.cell_attributes.top_margin);
// 셀 내부 문단 렌더링 / Render paragraphs inside cell
let mut cell_content = String::new();
// fixture처럼 hce 바로 아래에 추가로 붙일 HTML(예: 이미지 hsR)을 모읍니다.
let mut cell_outside_html = String::new();
// 이미지-only 셀 보정용: 이미지가 크고(셀 높이에 근접) 텍스트가 없으면 hcI를 아래로 밀지 않음
let mut cell_has_text = false;
let mut image_only_max_height_mm: Option<f64> = None;
// hcI의 top 위치 계산을 위한 첫 번째 LineSegment 정보 저장 / Store first LineSegment info for hcI top position calculation
let mut first_line_segment: Option<&LineSegmentInfo> = None;
for para in &cell.paragraphs {
// ParaShape 클래스 가져오기 / Get ParaShape class
let para_shape_id = para.para_header.para_shape_id;
let para_shape_class = if (para_shape_id as usize) < document.doc_info.para_shapes.len()
{
format!("ps{}", para_shape_id)
} else {
String::new()
};
// 텍스트와 CharShape 추출 / Extract text and CharShape
let (text, char_shapes) = text::extract_text_and_shapes(para);
// LineSegment 찾기 / Find LineSegment
let mut line_segments = Vec::new();
for record in ¶.records {
if let ParagraphRecord::ParaLineSeg { segments } = record {
line_segments = segments.clone();
// 첫 번째 LineSegment 저장 (hcI top 계산용) / Store first LineSegment (for hcI top calculation)
if first_line_segment.is_none() && !segments.is_empty() {
first_line_segment = segments.first();
}
break;
}
}
// 이미지 수집 (셀 내부에서는 테이블은 렌더링하지 않음) / Collect images (tables are not rendered inside cells)
let mut images = Vec::new();
// para.records에서 직접 ShapeComponentPicture 찾기 (CtrlHeader 내부가 아닌 경우만) / Find ShapeComponentPicture directly in para.records (only if not inside CtrlHeader)
// CtrlHeader가 있는지 먼저 확인 / Check if CtrlHeader exists first
let has_ctrl_header = para
.records
.iter()
.any(|r| matches!(r, ParagraphRecord::CtrlHeader { .. }));
if !has_ctrl_header {
// CtrlHeader가 없을 때만 직접 처리 / Only process directly if no CtrlHeader
for record in ¶.records {
match record {
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
let bindata_id = shape_component_picture.picture_info.bindata_id;
let image_url = common::get_image_url(
document,
bindata_id,
options.image_output_dir.as_deref(),
options.html_output_dir.as_deref(),
);
if !image_url.is_empty() {
// ShapeComponentPicture가 직접 올 때는 border_rectangle 사용 (부모 ShapeComponent가 없음)
// When ShapeComponentPicture comes directly, use border_rectangle (no parent ShapeComponent)
let width_hwpunit =
shape_component_picture.border_rectangle_x.right
- shape_component_picture.border_rectangle_x.left;
let mut height_hwpunit =
(shape_component_picture.border_rectangle_y.bottom
- shape_component_picture.border_rectangle_y.top)
as i32;
// border_rectangle_y의 top과 bottom이 같으면 crop_rectangle 사용
// If border_rectangle_y's top and bottom are the same, use crop_rectangle
if height_hwpunit == 0 {
height_hwpunit = (shape_component_picture.crop_rectangle.bottom
- shape_component_picture.crop_rectangle.top)
as i32;
}
let width = width_hwpunit.max(0) as u32;
let height = height_hwpunit.max(0) as u32;
if width > 0 && height > 0 {
images.push(ImageInfo {
width,
height,
url: image_url,
like_letters: false, // 셀 내부 이미지는 ctrl_header 정보 없음 / Images inside cells have no ctrl_header info
affect_line_spacing: false,
vert_rel_to: None,
});
}
}
}
_ => {}
}
}
}
// 재귀적으로 ShapeComponentPicture를 찾는 헬퍼 함수 / Helper function to recursively find ShapeComponentPicture
fn collect_images_from_shape_component(
children: &[ParagraphRecord],
shape_component_width: u32,
shape_component_height: u32,
document: &HwpDocument,
options: &HtmlOptions,
images: &mut Vec<ImageInfo>,
) {
for child in children {
match child {
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
let bindata_id = shape_component_picture.picture_info.bindata_id;
let image_url = common::get_image_url(
document,
bindata_id,
options.image_output_dir.as_deref(),
options.html_output_dir.as_deref(),
);
if !image_url.is_empty() {
// shape_component.width/height를 직접 사용 / Use shape_component.width/height directly
if shape_component_width > 0 && shape_component_height > 0 {
images.push(ImageInfo {
width: shape_component_width,
height: shape_component_height,
url: image_url,
like_letters: false, // 셀 내부 이미지는 ctrl_header 정보 없음 / Images inside cells have no ctrl_header info
affect_line_spacing: false,
vert_rel_to: None,
});
}
}
}
ParagraphRecord::ShapeComponent {
shape_component,
children: nested_children,
} => {
// 중첩된 ShapeComponent 재귀적으로 탐색 / Recursively search nested ShapeComponent
collect_images_from_shape_component(
nested_children,
shape_component.width,
shape_component.height,
document,
options,
images,
);
}
ParagraphRecord::ShapeComponentLine { .. }
| ParagraphRecord::ShapeComponentRectangle { .. }
| ParagraphRecord::ShapeComponentEllipse { .. }
| ParagraphRecord::ShapeComponentArc { .. }
| ParagraphRecord::ShapeComponentPolygon { .. }
| ParagraphRecord::ShapeComponentCurve { .. }
| ParagraphRecord::ShapeComponentOle { .. }
| ParagraphRecord::ShapeComponentContainer { .. }
| ParagraphRecord::ShapeComponentTextArt { .. } => {
// 다른 shape component 타입들은 children이 없으므로 무시 / Other shape component types have no children, so ignore
}
_ => {}
}
}
}
for record in ¶.records {
match record {
ParagraphRecord::ShapeComponent {
shape_component,
children,
} => {
// ShapeComponent의 children에서 이미지 찾기 (재귀적으로) / Find images in ShapeComponent's children (recursively)
collect_images_from_shape_component(
children,
shape_component.width,
shape_component.height,
document,
options,
&mut images,
);
}
ParagraphRecord::CtrlHeader {
header,
children,
paragraphs: ctrl_paragraphs,
..
} => {
// CtrlHeader 처리 (그림 개체 등) / Process CtrlHeader (shape objects, etc.)
// process_ctrl_header를 호출하여 이미지 수집 (paragraph.rs와 동일한 방식) / Call process_ctrl_header to collect images (same way as paragraph.rs)
// children이 비어있으면 cell.paragraphs도 확인 / If children is empty, also check cell.paragraphs
let paragraphs_to_use =
if children.is_empty() && !cell.paragraphs.is_empty() {
&cell.paragraphs
} else {
ctrl_paragraphs
};
let ctrl_result = ctrl_header::process_ctrl_header(
header,
children,
paragraphs_to_use,
document,
options,
);
images.extend(ctrl_result.images);
}
_ => {}
}
}
// 이미지-only 셀 판단을 위해, 이 문단에서 수집된 이미지의 최대 높이를 기록합니다.
// (LineSegment 경로로 렌더링되는 경우에도 images는 존재할 수 있으므로 여기서 누적)
if !images.is_empty() {
for image in &images {
let h_mm = round_to_2dp(int32_to_mm(image.height as INT32));
image_only_max_height_mm = Some(
image_only_max_height_mm
.map(|cur| cur.max(h_mm))
.unwrap_or(h_mm),
);
}
}
// ParaShape indent 값 가져오기 / Get ParaShape indent value
let para_shape_indent =
if (para_shape_id as usize) < document.doc_info.para_shapes.len() {
Some(document.doc_info.para_shapes[para_shape_id as usize].indent)
} else {
None
};
// LineSegment가 있으면 사용 / Use LineSegment if available
if !line_segments.is_empty() {
// SPECIAL CASE (noori BIN0002 등):
// 텍스트가 없고 이미지가 있는데, LineSegment.segment_width가 0에 가까우면 hls width가 0으로 출력되어
// 이미지 정렬이 깨집니다. 이 경우에도 hce>hcD>hcI>hls 구조는 유지하되,
// hls 박스 width를 '셀의 콘텐츠 폭'으로 강제하고 이미지(hsR)를 그 안에서 가운데 배치합니다.
let has_only_images = text.trim().is_empty() && !images.is_empty();
let seg_width_mm = line_segments
.first()
.map(|s| round_to_2dp(int32_to_mm(s.segment_width)))
.unwrap_or(0.0);
if has_only_images && seg_width_mm.abs() < 0.01 {
// FIXTURE(noori.html) 구조 재현:
// - hcI에는 "빈 문단(hls width=0)"만 남김
// - 실제 이미지는 hce 바로 아래에 hsR로 배치(top/left는 cell margin + ObjectCommon offset)
//
// fixture 예:
// <div class="hcI"><div class="hls ... width:0mm;"></div></div>
// <div class="hsR" style="top:0.50mm;left:24.42mm;... background-image:url(...);"></div>
let image = &images[0];
let img_h_mm = round_to_2dp(int32_to_mm(image.height as INT32));
// 기본값: margin만 (offset 못 찾으면 0으로)
let mut obj_off_x_mm = 0.0;
let mut obj_off_y_mm = 0.0;
for record in ¶.records {
if let ParagraphRecord::CtrlHeader { header, .. } = record {
if let CtrlHeaderData::ObjectCommon {
offset_x, offset_y, ..
} = &header.data
{
obj_off_x_mm = round_to_2dp(int32_to_mm((*offset_x).into()));
obj_off_y_mm = round_to_2dp(int32_to_mm((*offset_y).into()));
break;
}
}
}
// 1) hcI 안에는 빈 hls만
cell_content.push_str(&format!(
r#"<div class="hls {}" style="line-height:{:.2}mm;white-space:nowrap;left:0mm;top:-0.18mm;height:3.53mm;width:0mm;"></div>"#,
para_shape_class, img_h_mm
));
// 2) 실제 이미지는 cell_outside_html로 (hce 바로 아래)
// 좌표는 fixture처럼: top = top_margin_mm + offset_y, left = left_margin_mm + offset_x
let abs_left_mm = round_to_2dp(left_margin_mm + obj_off_x_mm);
let abs_top_mm = round_to_2dp(top_margin_mm + obj_off_y_mm);
cell_outside_html.push_str(&format!(
r#"<div class="hsR" style="top:{:.2}mm;left:{:.2}mm;width:{:.2}mm;height:{:.2}mm;background-repeat:no-repeat;background-size:contain;background-image:url('{}');"></div>"#,
abs_top_mm,
abs_left_mm,
round_to_2dp(int32_to_mm(image.width as INT32)),
round_to_2dp(int32_to_mm(image.height as INT32)),
image.url
));
} else {
// ParaText의 control_char_positions 수집 (원본 WCHAR 인덱스 기준)
let mut control_char_positions = Vec::new();
for record in ¶.records {
if let ParagraphRecord::ParaText {
control_char_positions: ccp,
..
} = record
{
control_char_positions = ccp.clone();
break;
}
}
let content = LineSegmentContent {
segments: &line_segments,
text: &text,
char_shapes: &char_shapes,
control_char_positions: &control_char_positions,
original_text_len: para.para_header.text_char_count as usize,
images: &images,
tables: &[], // 셀 내부에서는 테이블 없음 / No tables inside cells
};
let context = LineSegmentRenderContext {
document,
para_shape_class: ¶_shape_class,
options,
para_shape_indent,
hcd_position: None, // hcd_position 없음 / No hcd_position
page_def: None, // page_def 없음 / No page_def
};
let mut state = DocumentRenderState {
table_counter_start: 0, // 셀 내부에서는 테이블 번호 사용 안 함 / table numbers not used inside cells
pattern_counter,
color_to_pattern,
};
cell_content.push_str(&render_line_segments_with_content(
&content, &context, &mut state,
));
if !text.is_empty() {
cell_has_text = true;
}
}
} else if !text.is_empty() {
// LineSegment가 없으면 텍스트만 렌더링 / Render text only if no LineSegment
let rendered_text =
text::render_text(&text, &char_shapes, document, &options.css_class_prefix);
cell_content.push_str(&format!(
r#"<div class="hls {}">{}</div>"#,
para_shape_class, rendered_text
));
cell_has_text = true;
} else if !images.is_empty() {
// LineSegment와 텍스트가 없지만 이미지가 있는 경우 / No LineSegment or text but images exist
// 이미지만 렌더링 / Render images only
for image in &images {
let image_html = image::render_image_with_style(
&image.url,
0,
0,
image.width as INT32,
image.height as INT32,
0,
0,
);
cell_content.push_str(&image_html);
let h_mm = round_to_2dp(int32_to_mm(image.height as INT32));
image_only_max_height_mm = Some(
image_only_max_height_mm
.map(|cur| cur.max(h_mm))
.unwrap_or(h_mm),
);
}
}
}
// (마진 값은 위에서 이미 계산됨)
let bottom_margin_mm = cell_margin_to_mm(cell.cell_attributes.bottom_margin);
// hcI의 top 위치 계산 / Calculate hcI top position
// NOTE: hcI는 "셀 안에서 컨텐츠 블록을 어디에 둘지"만 담당합니다(Top/Center/Bottom).
// 글자 baseline/line-height 보정은 LineSegment(hls) 쪽에서 처리합니다.
//
// IMPORTANT (fixture 기준):
// 셀 안에 줄이 여러 개(여러 para_line_seg)인 경우, 첫 줄 높이만으로 center를 계산하면
// fixture보다 과하게 내려가므로(예: 6.44mm), 전체 라인 블록 높이(첫 라인 시작~마지막 라인 끝)를 사용합니다.
let hci_top_mm = if let Some(segment) = first_line_segment {
// 기본: 단일 라인 높이 / Default: single line height
let mut content_height_mm = round_to_2dp(int32_to_mm(segment.line_height));
// 셀 내부 모든 para_line_seg를 스캔하여 전체 콘텐츠 높이 계산
// (min vertical_position ~ max(vertical_position + line_height))
let mut min_vp: Option<i32> = None;
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | true |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/constants.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/constants.rs | /// 테이블 렌더링 상수 / Table rendering constants
pub(crate) const SVG_PADDING_MM: f64 = 2.5;
pub(crate) const BORDER_COLOR: &str = "#000000";
pub(crate) const BORDER_WIDTH_MM: f64 = 0.12;
pub(crate) const BORDER_OFFSET_MM: f64 = 0.06;
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/position.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/position.rs | use crate::document::bodytext::ctrl_header::{CtrlHeaderData, HorzRelTo, VertRelTo};
use crate::document::bodytext::PageDef;
use crate::types::{RoundTo2dp, INT32};
use crate::viewer::html::styles::{int32_to_mm, round_to_2dp};
/// viewBox 데이터 / ViewBox data
#[derive(Clone, Copy)]
pub(crate) struct ViewBox {
pub left: f64,
pub top: f64,
pub width: f64,
pub height: f64,
}
/// SVG viewBox 계산 / Calculate SVG viewBox
pub(crate) fn view_box(htb_width: f64, htb_height: f64, padding: f64) -> ViewBox {
ViewBox {
left: round_to_2dp(-padding),
top: round_to_2dp(-padding),
width: round_to_2dp(htb_width + (padding * 2.0)),
height: round_to_2dp(htb_height + (padding * 2.0)),
}
}
/// 테이블 절대 위치 계산 / Calculate absolute table position
pub(crate) fn table_position(
hcd_position: Option<(f64, f64)>,
page_def: Option<&PageDef>,
segment_position: Option<(INT32, INT32)>,
ctrl_header: Option<&CtrlHeaderData>,
obj_outer_width_mm: Option<f64>,
para_start_vertical_mm: Option<f64>,
para_start_column_mm: Option<f64>,
para_segment_width_mm: Option<f64>,
first_para_vertical_mm: Option<f64>, // 첫 번째 문단의 vertical_position (가설 O) / First paragraph's vertical_position (Hypothesis O)
) -> (f64, f64) {
// CtrlHeader에서 필요한 정보 추출 / Extract necessary information from CtrlHeader
let (offset_x, offset_y, vert_rel_to, horz_rel_to, horz_relative) =
if let Some(CtrlHeaderData::ObjectCommon {
attribute,
offset_x,
offset_y,
..
}) = ctrl_header
{
(
Some(*offset_x),
Some(*offset_y),
Some(attribute.vert_rel_to),
Some(attribute.horz_rel_to),
Some(attribute.horz_relative),
)
} else {
(None, None, None, None, None)
};
let (base_left, base_top) = if let Some((left, top)) = hcd_position {
(left.round_to_2dp(), top.round_to_2dp())
} else if let Some(pd) = page_def {
let left = (pd.left_margin.to_mm() + pd.binding_margin.to_mm()).round_to_2dp();
let top = (pd.top_margin.to_mm() + pd.header_margin.to_mm()).round_to_2dp();
(left, top)
} else {
(20.0, 24.99)
};
if let Some((segment_col, segment_vert)) = segment_position {
// 레거시 코드처럼 vertical_position을 절대 위치로 직접 사용 / Use vertical_position as absolute position directly like legacy code
// vertical_position은 이미 페이지 기준 절대 위치이므로 base_pos를 더하지 않음 / vertical_position is already absolute position relative to page, so don't add base_pos
let segment_left_mm = int32_to_mm(segment_col);
let segment_top_mm = int32_to_mm(segment_vert);
(round_to_2dp(segment_left_mm), round_to_2dp(segment_top_mm))
} else {
// 종이(paper) 기준인 경우, 기준 원점은 용지 좌상단이므로 base_left/base_top을 적용하지 않는다.
// (page/hcD 기준은 본문 시작점이므로 base_left/base_top이 필요)
let base_top_for_obj = if matches!(vert_rel_to, Some(VertRelTo::Paper)) {
0.0
} else {
base_top
};
let base_left_for_obj = if matches!(horz_rel_to, Some(HorzRelTo::Paper)) {
0.0
} else {
base_left
};
let offset_left_mm = offset_x.map(|x| x.to_mm()).unwrap_or(0.0);
let para_left_mm = if matches!(horz_rel_to, Some(HorzRelTo::Para)) {
para_start_column_mm.unwrap_or(0.0)
} else {
0.0
};
let obj_w_mm = obj_outer_width_mm.unwrap_or(0.0);
// 기준 폭 계산 (right/center 정렬에 필요)
// - paper: 용지 폭
// - page/column: 본문(content) 폭
// - para: 현재 LineSeg의 segment_width
let mut ref_width_mm = match horz_rel_to {
Some(HorzRelTo::Paper) => page_def.map(|pd| pd.paper_width.to_mm()).unwrap_or(210.0),
Some(HorzRelTo::Para) => para_segment_width_mm.unwrap_or(0.0),
Some(HorzRelTo::Page) | Some(HorzRelTo::Column) | None => {
if let Some(pd) = page_def {
// content width = paper - (left+binding) - right
pd.paper_width.to_mm()
- (pd.left_margin.to_mm() + pd.binding_margin.to_mm())
- pd.right_margin.to_mm()
} else {
148.0
}
}
};
// ParaLineSeg.segment_width가 0인 케이스가 있어(빈 문단/앵커 문단),
// 이 경우에는 content width에서 para_left를 뺀 값으로 폴백한다.
if matches!(horz_rel_to, Some(HorzRelTo::Para)) && ref_width_mm <= 0.0 {
if let Some(pd) = page_def {
let content_w = pd.paper_width.to_mm()
- (pd.left_margin.to_mm() + pd.binding_margin.to_mm())
- pd.right_margin.to_mm();
// 문단 기준 폭은 "문단 시작(col_start)"을 좌우에서 모두 제외한 값으로 해석해야
// fixture(table-position)의 "문단 오른쪽/가운데" 케이스와 일치한다.
// 예) content_w(150) - 2*col_start(3.53) = 142.94mm
ref_width_mm = (content_w - (para_left_mm * 2.0)).max(0.0);
}
}
// horz_relative (Table 70): 0=left, 1=center, 2=right
// NOTE: fixture(table-position.html)의 "오른쪽부터 Nmm" 케이스는 right 기준 계산이 필요합니다.
let relative_mode = horz_relative.unwrap_or(0);
let left_mm = match relative_mode {
2 => {
// right aligned: (ref_right - offset_x - obj_width)
base_left_for_obj + para_left_mm + (ref_width_mm - offset_left_mm - obj_w_mm)
}
1 => {
// centered: (ref_center - obj_width/2) + offset_x
base_left_for_obj
+ para_left_mm
+ (ref_width_mm / 2.0 - obj_w_mm / 2.0)
+ offset_left_mm
}
_ => {
// left aligned
base_left_for_obj + para_left_mm + offset_left_mm
}
};
let offset_top_mm = if let (Some(VertRelTo::Para), Some(offset)) = (vert_rel_to, offset_y) {
let offset_mm = offset.to_mm();
if let Some(para_start) = para_start_vertical_mm {
// y 계산은 base_top 기준이어야 합니다. (base_left 사용은 버그)
para_start - base_top_for_obj
} else if let Some(first_para) = first_para_vertical_mm {
let first_para_relative_mm = first_para - base_top_for_obj;
first_para_relative_mm + offset_mm
} else {
offset_mm
}
} else {
offset_y.map(|y| y.to_mm()).unwrap_or(0.0)
};
let final_top_mm = base_top_for_obj + offset_top_mm;
(round_to_2dp(left_mm), round_to_2dp(final_top_mm))
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/size.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/size.rs | use std::collections::HashMap;
use crate::document::bodytext::ctrl_header::CtrlHeaderData;
use crate::document::bodytext::{ParagraphRecord, Table};
use crate::types::Hwpunit16ToMm;
use crate::viewer::html::styles::{int32_to_mm, round_to_2dp};
/// 셀 마진을 mm 단위로 변환 / Convert cell margin to mm
fn cell_margin_to_mm(margin_hwpunit: i16) -> f64 {
round_to_2dp(int32_to_mm(margin_hwpunit as i32))
}
/// 크기 데이터 / Size data
#[derive(Clone, Copy)]
pub(crate) struct Size {
pub width: f64,
pub height: f64,
}
/// CtrlHeader 기반 htb 컨테이너 크기 계산 / Calculate container size from CtrlHeader
pub(crate) fn htb_size(ctrl_header: Option<&CtrlHeaderData>) -> Size {
if let Some(CtrlHeaderData::ObjectCommon {
width,
height,
margin,
..
}) = ctrl_header
{
let w = width.to_mm() + margin.left.to_mm() + margin.right.to_mm();
let h = height.to_mm() + margin.top.to_mm() + margin.bottom.to_mm();
Size {
width: round_to_2dp(w),
height: round_to_2dp(h),
}
} else {
Size {
width: 0.0,
height: 0.0,
}
}
}
/// 셀 기반 콘텐츠 크기 계산 / Calculate content size from cells
pub(crate) fn content_size(table: &Table, ctrl_header: Option<&CtrlHeaderData>) -> Size {
let mut content_width = 0.0;
let mut content_height = 0.0;
if table.attributes.row_count > 0 && !table.attributes.row_sizes.is_empty() {
if let Some(CtrlHeaderData::ObjectCommon { height, .. }) = ctrl_header {
let ctrl_header_height_mm = height.to_mm();
// object_common.height를 행 개수로 나눈 기본 행 높이 계산 / Calculate base row height from object_common.height divided by row count
let base_row_height_mm = if table.attributes.row_count > 0 {
ctrl_header_height_mm / table.attributes.row_count as f64
} else {
0.0
};
// ctrl_header.height가 있어도, shape component가 있는 셀의 실제 높이를 확인하여 더 큰 값을 사용
// Even if ctrl_header.height exists, check actual cell heights with shape components and use the larger value
let mut max_row_heights_with_shapes: HashMap<usize, f64> = HashMap::new();
for cell in &table.cells {
if cell.cell_attributes.row_span == 1 {
let row_idx = cell.cell_attributes.row_address as usize;
// 먼저 실제 셀 높이를 가져옴 (cell.cell_attributes.height 우선) / First get actual cell height (cell.cell_attributes.height has priority)
let mut cell_height = cell.cell_attributes.height.to_mm();
// shape component가 있는 셀의 경우 shape 높이 + 마진을 고려 / For cells with shape components, consider shape height + margin
let mut max_shape_height_mm: Option<f64> = None;
// 재귀적으로 모든 ShapeComponent의 높이를 찾는 헬퍼 함수 / Helper function to recursively find height of all ShapeComponents
fn find_shape_component_height(
children: &[ParagraphRecord],
shape_component_height: u32,
) -> Option<f64> {
let mut max_height_mm: Option<f64> = None;
for child in children {
match child {
// ShapeComponentPicture: shape_component.height 사용
ParagraphRecord::ShapeComponentPicture { .. } => {
let height_hwpunit = shape_component_height as i32;
let height_mm = round_to_2dp(int32_to_mm(height_hwpunit));
if max_height_mm.is_none() || height_mm > max_height_mm.unwrap()
{
max_height_mm = Some(height_mm);
}
}
// 중첩된 ShapeComponent: 재귀적으로 탐색
ParagraphRecord::ShapeComponent {
shape_component,
children: nested_children,
} => {
if let Some(height) = find_shape_component_height(
nested_children,
shape_component.height,
) {
if max_height_mm.is_none()
|| height > max_height_mm.unwrap()
{
max_height_mm = Some(height);
}
}
}
// 다른 shape component 타입들: shape_component.height 사용
ParagraphRecord::ShapeComponentLine { .. }
| ParagraphRecord::ShapeComponentRectangle { .. }
| ParagraphRecord::ShapeComponentEllipse { .. }
| ParagraphRecord::ShapeComponentArc { .. }
| ParagraphRecord::ShapeComponentPolygon { .. }
| ParagraphRecord::ShapeComponentCurve { .. }
| ParagraphRecord::ShapeComponentOle { .. }
| ParagraphRecord::ShapeComponentContainer { .. }
| ParagraphRecord::ShapeComponentTextArt { .. }
| ParagraphRecord::ShapeComponentUnknown { .. } => {
// shape_component.height 사용 / Use shape_component.height
let height_mm =
round_to_2dp(int32_to_mm(shape_component_height as i32));
if max_height_mm.is_none() || height_mm > max_height_mm.unwrap()
{
max_height_mm = Some(height_mm);
}
}
// ParaLineSeg: line_height 합산하여 높이 계산
ParagraphRecord::ParaLineSeg { segments } => {
let total_height_hwpunit: i32 =
segments.iter().map(|seg| seg.line_height).sum();
let height_mm = round_to_2dp(int32_to_mm(total_height_hwpunit));
if max_height_mm.is_none() || height_mm > max_height_mm.unwrap()
{
max_height_mm = Some(height_mm);
}
}
_ => {}
}
}
max_height_mm
}
for para in &cell.paragraphs {
// ShapeComponent의 children에서 모든 shape 높이 찾기 (재귀적으로) / Find all shape heights in ShapeComponent's children (recursively)
for record in ¶.records {
match record {
ParagraphRecord::ShapeComponent {
shape_component,
children,
} => {
if let Some(shape_height_mm) = find_shape_component_height(
children,
shape_component.height,
) {
if max_shape_height_mm.is_none()
|| shape_height_mm > max_shape_height_mm.unwrap()
{
max_shape_height_mm = Some(shape_height_mm);
}
}
break; // ShapeComponent는 하나만 있음 / Only one ShapeComponent per paragraph
}
// ParaLineSeg가 paragraph records에 직접 있는 경우도 처리 / Also handle ParaLineSeg directly in paragraph records
ParagraphRecord::ParaLineSeg { segments } => {
let total_height_hwpunit: i32 =
segments.iter().map(|seg| seg.line_height).sum();
let height_mm = round_to_2dp(int32_to_mm(total_height_hwpunit));
if max_shape_height_mm.is_none()
|| height_mm > max_shape_height_mm.unwrap()
{
max_shape_height_mm = Some(height_mm);
}
}
_ => {}
}
}
}
// shape component가 있으면 셀 높이 = shape 높이 + 마진 / If shape component exists, cell height = shape height + margin
if let Some(shape_height_mm) = max_shape_height_mm {
let top_margin_mm = cell_margin_to_mm(cell.cell_attributes.top_margin);
let bottom_margin_mm =
cell_margin_to_mm(cell.cell_attributes.bottom_margin);
let shape_height_with_margin =
shape_height_mm + top_margin_mm + bottom_margin_mm;
// shape 높이 + 마진이 기존 셀 높이보다 크면 사용 / Use shape height + margin if larger than existing cell height
if shape_height_with_margin > cell_height {
cell_height = shape_height_with_margin;
}
}
// shape component가 없고 셀 높이가 매우 작으면 object_common.height를 베이스로 사용 (fallback)
// If no shape component and cell height is very small, use object_common.height as base (fallback)
if max_shape_height_mm.is_none()
&& cell_height < 0.1
&& base_row_height_mm > 0.0
{
cell_height = base_row_height_mm;
}
let entry = max_row_heights_with_shapes.entry(row_idx).or_insert(0.0f64);
*entry = (*entry).max(cell_height);
}
}
// 행 높이 합계 계산 / Calculate sum of row heights
let mut calculated_height = 0.0;
for row_idx in 0..table.attributes.row_count as usize {
if let Some(&height) = max_row_heights_with_shapes.get(&row_idx) {
calculated_height += height;
} else if base_row_height_mm > 0.0 {
// max_row_heights_with_shapes에 없으면 object_common.height를 행 개수로 나눈 값 사용 / If not in max_row_heights_with_shapes, use object_common.height divided by row count
calculated_height += base_row_height_mm;
} else if let Some(&row_size) = table.attributes.row_sizes.get(row_idx) {
let row_height = (row_size as f64 / 7200.0) * 25.4;
calculated_height += row_height;
}
}
// ctrl_header.height가 있으면 우선 사용 (이미 shape component 높이를 포함할 수 있음)
// If ctrl_header.height exists, use it preferentially (may already include shape component height)
// 계산된 높이는 참고용으로만 사용 (ctrl_header.height가 없거나 너무 작을 때만 사용)
// Calculated height is only for reference (use only if ctrl_header.height is missing or too small)
if calculated_height > ctrl_header_height_mm * 1.1 {
// 계산된 높이가 ctrl_header.height보다 10% 이상 크면 사용 (shape component가 추가된 경우)
// Use calculated height if it's more than 10% larger than ctrl_header.height (shape component added case)
content_height = calculated_height;
} else {
// 그렇지 않으면 ctrl_header.height 사용
// Otherwise use ctrl_header.height
content_height = ctrl_header_height_mm;
}
} else {
let mut max_row_heights: HashMap<usize, f64> = HashMap::new();
for cell in &table.cells {
if cell.cell_attributes.row_span == 1 {
let row_idx = cell.cell_attributes.row_address as usize;
let cell_height = cell.cell_attributes.height.to_mm();
let entry = max_row_heights.entry(row_idx).or_insert(0.0f64);
*entry = (*entry).max(cell_height);
}
}
for row_idx in 0..table.attributes.row_count as usize {
if let Some(&height) = max_row_heights.get(&row_idx) {
content_height += height;
} else if let Some(&row_size) = table.attributes.row_sizes.get(row_idx) {
let row_height = (row_size as f64 / 7200.0) * 25.4;
content_height += row_height;
}
}
}
}
for cell in &table.cells {
if cell.cell_attributes.row_address == 0 {
content_width += cell.cell_attributes.width.to_mm();
}
}
Size {
width: round_to_2dp(content_width),
height: round_to_2dp(content_height),
}
}
/// htb 컨테이너와 콘텐츠 크기 결합 / Combine container and content size
pub(crate) fn resolve_container_size(container: Size, content: Size) -> Size {
if container.width == 0.0 || container.height == 0.0 {
Size {
width: content.width,
height: content.height,
}
} else {
container
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/svg/borders.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/svg/borders.rs | use crate::document::bodytext::{Table, TableCell};
use crate::document::docinfo::border_fill::BorderLine;
use crate::viewer::html::styles::round_to_2dp;
use crate::{BorderFill, HwpDocument};
use crate::viewer::html::ctrl_header::table::geometry::{
calculate_cell_left, calculate_cell_top, get_cell_height,
};
use crate::viewer::html::ctrl_header::table::size::Size;
fn border_width_code_to_mm(code: u8) -> f64 {
match code {
0 => 0.10,
1 => 0.12,
2 => 0.15,
3 => 0.20,
4 => 0.25,
5 => 0.30,
6 => 0.40,
7 => 0.50,
8 => 0.60,
9 => 0.70,
10 => 1.00,
11 => 1.50,
12 => 2.00,
13 => 3.00,
14 => 4.00,
15 => 5.00,
_ => 0.12,
}
}
fn colorref_to_hex(c: u32) -> String {
// HWP COLORREF는 보통 0x00BBGGRR 형태
let r = (c & 0xFF) as u8;
let g = ((c >> 8) & 0xFF) as u8;
let b = ((c >> 16) & 0xFF) as u8;
format!("#{:02X}{:02X}{:02X}", r, g, b)
}
fn borderline_stroke_color(line: &BorderLine) -> String {
let stroke = colorref_to_hex(line.color.0);
stroke
}
fn borderline_base_width_mm(line: &BorderLine) -> f64 {
// 사용자 요청: 굵기(stroke-width)는 원 데이터(표 26) 기준 그대로 유지
border_width_code_to_mm(line.width)
}
fn render_border_paths(
x1: f64,
y1: f64,
x2: f64,
y2: f64,
is_vertical: bool,
line: &BorderLine,
) -> String {
// 레거시(hwpjs.js) 기준: line_type=0은 스타일을 리턴하지 않아 "선 없음" 취급.
// 따라서 line_type=0 또는 width=0이면 그리지 않는다.
if line.line_type == 0 || line.width == 0 {
let _ = (x1, y1, x2, y2, is_vertical);
return String::new();
}
// 사용자 요청: 굵기(stroke-width)는 그대로 유지하고,
// 색(stroke)과 “그려야 하는 선”만 맞춘다.
// 따라서 line_type에 따른 2중/3중선(다중 스트로크) 표현은 여기서는 하지 않는다.
let stroke = borderline_stroke_color(line);
let w = round_to_2dp(borderline_base_width_mm(line));
let (ax1, ay1, ax2, ay2) = if is_vertical {
(x1, y1, x2, y2)
} else {
(x1, y1, x2, y2)
};
format!(
r#"<path d="M{},{} L{},{}" style="stroke:{};stroke-linecap:butt;stroke-width:{};"></path>"#,
round_to_2dp(ax1),
round_to_2dp(ay1),
round_to_2dp(ax2),
round_to_2dp(ay2),
stroke,
w
)
}
fn get_border_fill<'a>(document: &'a HwpDocument, id: u16) -> Option<&'a BorderFill> {
if id == 0 {
return None;
}
let idx = (id as usize).checked_sub(1)?;
document.doc_info.border_fill.get(idx)
}
fn cell_border_fill_id(table: &Table, cell: &TableCell) -> u16 {
// 우선순위(추가 규칙):
// 1) TableZone.border_fill_id (있으면 셀 값을 덮어씀)
// 2) CellAttributes.border_fill_id
// 3) TableAttributes.border_fill_id
let row = cell.cell_attributes.row_address;
let col = cell.cell_attributes.col_address;
if !table.attributes.zones.is_empty() {
// 여러 zone이 겹치면 "나중에 나온 zone"이 우선(override)된다고 가정
for zone in table.attributes.zones.iter().rev() {
if zone.start_row <= row
&& row <= zone.end_row
&& zone.start_col <= col
&& col <= zone.end_col
&& zone.border_fill_id != 0
{
return zone.border_fill_id;
}
}
}
let id = cell.cell_attributes.border_fill_id;
if id != 0 {
id
} else {
table.attributes.border_fill_id
}
}
fn pick_thicker(a: BorderLine, b: BorderLine) -> BorderLine {
if border_width_code_to_mm(b.width) > border_width_code_to_mm(a.width) {
b
} else {
a
}
}
fn default_borderline(
table: &Table,
document: &HwpDocument,
side: usize, // 0:Left,1:Right,2:Top,3:Bottom
) -> Option<BorderLine> {
if table.attributes.border_fill_id == 0 {
return None;
}
get_border_fill(document, table.attributes.border_fill_id).map(|bf| bf.borders[side].clone())
}
fn vertical_segment_borderline(
table: &Table,
document: &HwpDocument,
col_x: f64,
y0: f64,
y1: f64,
ctrl_header_height_mm: Option<f64>,
is_left_edge: bool,
is_right_edge: bool,
) -> Option<BorderLine> {
let eps = 0.01;
// 바깥 테두리: table.border_fill_id가 있으면 그걸 우선, 없으면 셀 border_fill로 결정
if is_left_edge {
if let Some(line) = default_borderline(table, document, 0) {
return Some(line);
}
}
if is_right_edge {
if let Some(line) = default_borderline(table, document, 1) {
return Some(line);
}
}
// 경계선 우선순위(원본 HTML과 일치시키기 위한 규칙):
// - 내부선: "왼쪽 셀의 Right"를 우선, 없으면 "오른쪽 셀의 Left"
// - 왼쪽 외곽: "첫 열 셀의 Left"
// - 오른쪽 외곽: "마지막 열 셀의 Right"
let mut from_left_cell_right: Option<BorderLine> = None;
let mut from_right_cell_left: Option<BorderLine> = None;
// 셀 순서를 고정(행,열 오름차순)해서 “첫 셀 우선” 규칙이 안정적으로 동작하도록 함
let mut cells: Vec<&TableCell> = table.cells.iter().collect();
cells.sort_by_key(|c| (c.cell_attributes.row_address, c.cell_attributes.col_address));
for cell in cells {
let cell_left = calculate_cell_left(table, cell);
let cell_width = cell.cell_attributes.width.to_mm();
let cell_right = cell_left + cell_width;
let cell_top = calculate_cell_top(table, cell, ctrl_header_height_mm);
let cell_height = get_cell_height(table, cell, ctrl_header_height_mm);
let cell_bottom = cell_top + cell_height;
let overlaps_y = !(y1 <= cell_top + eps || y0 >= cell_bottom - eps);
if !overlaps_y {
continue;
}
let bf_id = cell_border_fill_id(table, cell);
let bf = match get_border_fill(document, bf_id) {
Some(v) => v,
None => continue,
};
// 왼쪽 셀의 Right: 여러 셀이 매칭되면 “첫 셀” 우선(원본/레거시 동작에 더 근접)
if (cell_right - col_x).abs() < eps {
let cand = bf.borders[1].clone();
if from_left_cell_right.is_none() {
from_left_cell_right = Some(cand);
}
}
// 오른쪽 셀의 Left: 여러 셀이 매칭되면 “첫 셀” 우선
if (cell_left - col_x).abs() < eps {
let cand = bf.borders[0].clone();
if from_right_cell_left.is_none() {
from_right_cell_left = Some(cand);
}
}
}
let chosen = if is_left_edge {
from_right_cell_left.or(from_left_cell_right)
} else if is_right_edge {
from_left_cell_right.or(from_right_cell_left)
} else {
from_left_cell_right.or(from_right_cell_left)
};
chosen
}
fn horizontal_segment_borderline(
table: &Table,
document: &HwpDocument,
row_positions: &[f64],
row_y: f64,
x0: f64,
x1: f64,
ctrl_header_height_mm: Option<f64>,
is_top_edge: bool,
is_bottom_edge: bool,
) -> Option<BorderLine> {
let eps = 0.01;
let _ = ctrl_header_height_mm; // row_positions 기반 계산을 사용
// 바깥 테두리: table.border_fill_id가 있으면 그걸 우선, 없으면 셀 border_fill로 결정
if is_top_edge {
if let Some(line) = default_borderline(table, document, 2) {
return Some(line);
}
}
if is_bottom_edge {
if let Some(line) = default_borderline(table, document, 3) {
return Some(line);
}
}
// 경계선 우선순위(원본 HTML과 일치시키기 위한 규칙):
// - 내부선: "위쪽 셀의 Bottom"을 우선, 없으면 "아래쪽 셀의 Top"
// - 위쪽 외곽: "첫 행 셀의 Top"
// - 아래쪽 외곽: "마지막 행 셀의 Bottom"
let mut from_upper_cell_bottom: Option<BorderLine> = None;
let mut from_lower_cell_top: Option<BorderLine> = None;
// 셀 순서를 고정(행,열 오름차순)해서 “첫 셀 우선” 규칙이 안정적으로 동작하도록 함
let mut cells: Vec<&TableCell> = table.cells.iter().collect();
cells.sort_by_key(|c| (c.cell_attributes.row_address, c.cell_attributes.col_address));
for cell in cells {
let row = cell.cell_attributes.row_address as usize;
let row_span = if cell.cell_attributes.row_span == 0 {
1usize
} else {
cell.cell_attributes.row_span as usize
};
if row_positions.len() <= row || row_positions.len() <= row + row_span {
continue;
}
let cell_top = row_positions[row];
let cell_bottom = row_positions[row + row_span];
let cell_left = calculate_cell_left(table, cell);
let cell_width = cell.cell_attributes.width.to_mm();
let cell_right = cell_left + cell_width;
let overlaps_x = !(x1 <= cell_left + eps || x0 >= cell_right - eps);
if !overlaps_x {
continue;
}
let bf_id = cell_border_fill_id(table, cell);
let bf = match get_border_fill(document, bf_id) {
Some(v) => v,
None => continue,
};
// 위쪽 셀의 Bottom: 여러 셀이 매칭되면 “첫 셀” 우선
if (cell_bottom - row_y).abs() < eps {
let cand = bf.borders[3].clone();
if from_upper_cell_bottom.is_none() {
from_upper_cell_bottom = Some(cand);
}
}
// 아래쪽 셀의 Top: 여러 셀이 매칭되면 “첫 셀” 우선
if (cell_top - row_y).abs() < eps {
let cand = bf.borders[2].clone();
if from_lower_cell_top.is_none() {
from_lower_cell_top = Some(cand);
}
}
}
let chosen = if is_top_edge {
from_lower_cell_top.or(from_upper_cell_bottom)
} else if is_bottom_edge {
from_upper_cell_bottom.or(from_lower_cell_top)
} else {
from_upper_cell_bottom.or(from_lower_cell_top)
};
chosen
}
/// 수직 경계선 렌더링 / Render vertical borders
pub(crate) fn render_vertical_borders(
table: &Table,
document: &HwpDocument,
column_positions: &[f64],
content: Size,
ctrl_header_height_mm: Option<f64>,
) -> String {
let mut svg_paths = String::new();
let epsilon = 0.01; // 부동소수점 비교를 위한 작은 오차 / Small epsilon for floating point comparison
let is_suspect_image_or_caption_table =
table.attributes.row_count as usize >= 6 && table.cells.len() >= 12;
let mut h11_logged_count = 0usize;
for &col_x in column_positions {
let is_left_edge = (col_x - 0.0).abs() < epsilon;
let is_right_edge = (col_x - content.width).abs() < epsilon;
// 레거시/fixture 정합:
// 좌/우 외곽선은 “항상 전체 높이”로 그려야 한다.
// (부동소수점 오차로 covered_ranges가 생기거나, 셀 병합/커버 계산 때문에
// 외곽선이 위/아래로 끊기는 현상이 발생할 수 있음)
if is_left_edge || is_right_edge {
if let Some(line) = vertical_segment_borderline(
table,
document,
col_x,
0.0,
content.height,
ctrl_header_height_mm,
is_left_edge,
is_right_edge,
) {
svg_paths.push_str(&render_border_paths(
col_x,
0.0,
col_x,
content.height,
true,
&line,
));
}
continue;
}
let mut covered_ranges = Vec::new();
for cell in &table.cells {
let cell_left = calculate_cell_left(table, cell);
let cell_width = cell.cell_attributes.width.to_mm();
let cell_right = cell_left + cell_width;
let cell_top = calculate_cell_top(table, cell, ctrl_header_height_mm);
let cell_height = get_cell_height(table, cell, ctrl_header_height_mm);
// 셀이 해당 열 위치를 가로지르는 경우 (셀의 오른쪽 경계가 정확히 그 위치인 경우는 제외)
// Cell crosses the column position (excluding when cell's right boundary is exactly at that position)
if cell_left < col_x && cell_right > col_x {
covered_ranges.push((cell_top, cell_top + cell_height));
}
}
covered_ranges.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
let mut segments = Vec::new();
let mut current_y = 0.0;
for (cover_start, cover_end) in &covered_ranges {
if current_y < *cover_start {
segments.push((current_y, *cover_start));
}
current_y = current_y.max(*cover_end);
}
if current_y < content.height {
segments.push((current_y, content.height));
}
if segments.is_empty() {
// 덮인 범위가 없으면 전체 높이에 걸쳐 경계선을 그림
// If no covered ranges, draw border across full height
if let Some(line) = vertical_segment_borderline(
table,
document,
col_x,
0.0,
content.height,
ctrl_header_height_mm,
is_left_edge,
is_right_edge,
) {
svg_paths.push_str(&render_border_paths(
col_x,
0.0,
col_x,
content.height,
true,
&line,
));
}
} else if segments.len() == 1 && segments[0].0 == 0.0 && segments[0].1 == content.height {
if let Some(line) = vertical_segment_borderline(
table,
document,
col_x,
0.0,
content.height,
ctrl_header_height_mm,
is_left_edge,
is_right_edge,
) {
svg_paths.push_str(&render_border_paths(
col_x,
0.0,
col_x,
content.height,
true,
&line,
));
}
} else {
for (y_start, y_end) in segments {
if let Some(line) = vertical_segment_borderline(
table,
document,
col_x,
y_start,
y_end,
ctrl_header_height_mm,
is_left_edge,
is_right_edge,
) {
svg_paths.push_str(&render_border_paths(
col_x, y_start, col_x, y_end, true, &line,
));
}
}
}
}
svg_paths
}
/// 수평 경계선 렌더링 / Render horizontal borders
pub(crate) fn render_horizontal_borders(
table: &Table,
document: &HwpDocument,
row_positions: &[f64],
content: Size,
border_offset: f64,
ctrl_header_height_mm: Option<f64>,
) -> String {
let mut svg_paths = String::new();
let _ = ctrl_header_height_mm; // row_positions 기반 계산을 사용
for &row_y in row_positions {
let is_top_edge = (row_y - 0.0).abs() < 0.01;
let is_bottom_edge = (row_y - content.height).abs() < 0.01;
let mut covered_ranges = Vec::new();
for cell in &table.cells {
let row = cell.cell_attributes.row_address as usize;
let row_span = if cell.cell_attributes.row_span == 0 {
1usize
} else {
cell.cell_attributes.row_span as usize
};
if row_positions.len() <= row || row_positions.len() <= row + row_span {
continue;
}
let cell_top = row_positions[row];
let cell_bottom = row_positions[row + row_span];
let cell_left = calculate_cell_left(table, cell);
let cell_width = cell.cell_attributes.width.to_mm();
if cell_top < row_y && cell_bottom > row_y {
covered_ranges.push((cell_left, cell_left + cell_width));
}
}
covered_ranges.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
let mut segments = Vec::new();
let mut current_x = 0.0;
for (cover_start, cover_end) in &covered_ranges {
if current_x < *cover_start {
segments.push((current_x, *cover_start));
}
current_x = current_x.max(*cover_end);
}
if current_x < content.width {
segments.push((current_x, content.width));
}
if segments.is_empty() {
continue;
} else if segments.len() == 1 && segments[0].0 == 0.0 && segments[0].1 == content.width {
let line_opt = horizontal_segment_borderline(
table,
document,
row_positions,
row_y,
0.0,
content.width,
ctrl_header_height_mm,
is_top_edge,
is_bottom_edge,
);
if let Some(line) = line_opt {
svg_paths.push_str(&render_border_paths(
-border_offset,
row_y,
content.width + border_offset,
row_y,
false,
&line,
));
}
} else {
for (x_start, x_end) in segments {
let line_opt = horizontal_segment_borderline(
table,
document,
row_positions,
row_y,
x_start,
x_end,
ctrl_header_height_mm,
is_top_edge,
is_bottom_edge,
);
if let Some(line) = line_opt {
svg_paths.push_str(&render_border_paths(
x_start - border_offset,
row_y,
x_end + border_offset,
row_y,
false,
&line,
));
}
}
}
}
// 테이블 하단 테두리 추가 / Add table bottom border
// row_positions는 행의 시작 위치만 포함하므로, 항상 content.height 위치에 하단 테두리를 그려야 함
// row_positions only contains row start positions, so we must always draw bottom border at content.height
if let Some(line) = horizontal_segment_borderline(
table,
document,
row_positions,
content.height,
0.0,
content.width,
ctrl_header_height_mm,
false,
true,
) {
svg_paths.push_str(&render_border_paths(
-border_offset,
content.height,
content.width + border_offset,
content.height,
false,
&line,
));
}
svg_paths
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/html/ctrl_header/table/svg/fills.rs | crates/hwp-core/src/viewer/html/ctrl_header/table/svg/fills.rs | use crate::document::bodytext::Table;
use crate::document::FillInfo;
use crate::HwpDocument;
use crate::viewer::html::styles::round_to_2dp;
use crate::viewer::html::ctrl_header::table::geometry::{
calculate_cell_left, calculate_cell_top, get_cell_height,
};
use std::collections::HashMap;
/// 배경 패턴 및 면 채우기 생성 / Build background patterns and fills
pub(crate) fn render_fills(
table: &Table,
document: &HwpDocument,
ctrl_header_height_mm: Option<f64>,
pattern_counter: &mut usize, // 문서 레벨 pattern_counter (문서 전체에서 패턴 ID 공유) / Document-level pattern_counter (share pattern IDs across document)
color_to_pattern: &mut HashMap<u32, String>, // 문서 레벨 color_to_pattern (문서 전체에서 패턴 ID 공유) / Document-level color_to_pattern (share pattern IDs across document)
) -> (String, String) {
let mut svg_paths = String::new();
let mut pattern_defs = String::new();
for (cell_idx, cell) in table.cells.iter().enumerate() {
let cell_left = calculate_cell_left(table, cell);
let cell_top = calculate_cell_top(table, cell, ctrl_header_height_mm);
let cell_width = cell.cell_attributes.width.to_mm();
let cell_height = get_cell_height(table, cell, ctrl_header_height_mm);
// 셀의 border_fill_id를 사용하거나, 0이면 테이블의 기본 border_fill_id 사용
// Use cell's border_fill_id, or table's default border_fill_id if 0
let border_fill_id_to_use = if cell.cell_attributes.border_fill_id > 0 {
cell.cell_attributes.border_fill_id
} else {
table.attributes.border_fill_id
};
if border_fill_id_to_use > 0 {
let border_fill_id = border_fill_id_to_use as usize;
// border_fill_id는 1-based이므로 배열 인덱스는 border_fill_id - 1
// border_fill_id is 1-based, so array index is border_fill_id - 1
if border_fill_id > 0 && border_fill_id <= document.doc_info.border_fill.len() {
let border_fill = &document.doc_info.border_fill[border_fill_id - 1];
if let FillInfo::Solid(solid) = &border_fill.fill {
let color_value = solid.background_color.0;
// COLORREF가 0이 아니고 (투명하지 않고) 색상이 있는 경우
// If COLORREF is not 0 (not transparent) and has color
if color_value != 0 {
// 같은 색상이면 기존 패턴 재사용 / Reuse existing pattern for same color
let is_new_pattern = !color_to_pattern.contains_key(&color_value);
let pattern_id = if is_new_pattern {
let id = format!("w_{:02}", *pattern_counter);
*pattern_counter += 1;
let color = &solid.background_color;
pattern_defs.push_str(&format!(
r#"<pattern id="{}" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="10" height="10" fill="rgb({},{},{})" /></pattern>"#,
id, color.r(), color.g(), color.b()
));
color_to_pattern.insert(color_value, id.clone());
id
} else {
color_to_pattern.get(&color_value).unwrap().clone()
};
svg_paths.push_str(&format!(
r#"<path fill="url(#{})" d="M{},{}L{},{}L{},{}L{},{}L{},{}Z "></path>"#,
pattern_id,
round_to_2dp(cell_left),
round_to_2dp(cell_top),
round_to_2dp(cell_left + cell_width),
round_to_2dp(cell_top),
round_to_2dp(cell_left + cell_width),
round_to_2dp(cell_top + cell_height),
round_to_2dp(cell_left),
round_to_2dp(cell_top + cell_height),
round_to_2dp(cell_left),
round_to_2dp(cell_top)
));
}
}
}
}
}
(pattern_defs, svg_paths)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/core/renderer.rs | crates/hwp-core/src/viewer/core/renderer.rs | /// Renderer trait for different output formats
/// 다양한 출력 형식을 위한 렌더러 트레이트
///
/// 각 뷰어(HTML, Markdown, PDF, Image 등)는 이 트레이트를 구현하여
/// HWP 문서를 해당 형식으로 변환합니다.
///
/// Each viewer (HTML, Markdown, PDF, Image, etc.) implements this trait
/// to convert HWP documents to that format.
use crate::document::{bodytext::Table, HwpDocument};
/// Text styling information
/// 텍스트 스타일 정보
#[derive(Debug, Clone, Default)]
pub struct TextStyles {
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub strikethrough: bool,
pub superscript: bool,
pub subscript: bool,
pub font_family: Option<String>,
pub font_size: Option<f32>,
pub color: Option<String>,
pub background_color: Option<String>,
}
/// Document parts for rendering
/// 렌더링을 위한 문서 부분들
#[derive(Debug, Clone, Default)]
pub struct DocumentParts {
pub headers: Vec<String>,
pub body_lines: Vec<String>,
pub footers: Vec<String>,
pub footnotes: Vec<String>,
pub endnotes: Vec<String>,
}
/// Renderer trait for converting HWP documents to various formats
/// HWP 문서를 다양한 형식으로 변환하는 렌더러 트레이트
pub trait Renderer {
/// Renderer-specific options type
/// 렌더러별 옵션 타입
type Options: Clone;
// ===== Text Styling =====
/// Render plain text with optional styles
/// 스타일이 적용된 일반 텍스트 렌더링
fn render_text(&self, text: &str, styles: &TextStyles) -> String;
/// Render bold text
/// 굵은 텍스트 렌더링
fn render_bold(&self, text: &str) -> String;
/// Render italic text
/// 기울임 텍스트 렌더링
fn render_italic(&self, text: &str) -> String;
/// Render underlined text
/// 밑줄 텍스트 렌더링
fn render_underline(&self, text: &str) -> String;
/// Render strikethrough text
/// 취소선 텍스트 렌더링
fn render_strikethrough(&self, text: &str) -> String;
/// Render superscript text
/// 위첨자 텍스트 렌더링
fn render_superscript(&self, text: &str) -> String;
/// Render subscript text
/// 아래첨자 텍스트 렌더링
fn render_subscript(&self, text: &str) -> String;
// ===== Structure Elements =====
/// Render a paragraph
/// 문단 렌더링
fn render_paragraph(&self, content: &str) -> String;
/// Render a table
/// 테이블 렌더링
fn render_table(
&self,
table: &Table,
document: &HwpDocument,
options: &Self::Options,
) -> String;
/// Render an image
/// 이미지 렌더링
fn render_image(
&self,
image_id: u16,
document: &HwpDocument,
options: &Self::Options,
) -> Option<String>;
/// Render a page break
/// 페이지 구분선 렌더링
fn render_page_break(&self) -> String;
// ===== Document Structure =====
/// Render the complete document
/// 전체 문서 렌더링
fn render_document(
&self,
parts: &DocumentParts,
document: &HwpDocument,
options: &Self::Options,
) -> String;
/// Render document header (title, version, etc.)
/// 문서 헤더 렌더링 (제목, 버전 등)
fn render_document_header(
&self,
document: &HwpDocument,
options: &Self::Options,
) -> String;
/// Render document footer (footnotes, endnotes, etc.)
/// 문서 푸터 렌더링 (각주, 미주 등)
fn render_document_footer(
&self,
parts: &DocumentParts,
options: &Self::Options,
) -> String;
// ===== Special Elements =====
/// Render a footnote reference link
/// 각주 참조 링크 렌더링
fn render_footnote_ref(&self, id: u32, number: &str, options: &Self::Options) -> String;
/// Render an endnote reference link
/// 미주 참조 링크 렌더링
fn render_endnote_ref(&self, id: u32, number: &str, options: &Self::Options) -> String;
/// Render a footnote back link
/// 각주 돌아가기 링크 렌더링
fn render_footnote_back(&self, ref_id: &str, options: &Self::Options) -> String;
/// Render an endnote back link
/// 미주 돌아가기 링크 렌더링
fn render_endnote_back(&self, ref_id: &str, options: &Self::Options) -> String;
/// Render outline number
/// 개요 번호 렌더링
fn render_outline_number(&self, level: u8, number: u32, content: &str) -> String;
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/core/bodytext.rs | crates/hwp-core/src/viewer/core/bodytext.rs | /// Common bodytext processing logic
/// 공통 본문 처리 로직
///
/// 모든 뷰어에서 공통으로 사용되는 본문 처리 로직을 제공합니다.
/// 출력 형식은 Renderer 트레이트를 통해 처리됩니다.
///
/// Provides common bodytext processing logic used by all viewers.
/// Output format is handled through the Renderer trait.
use crate::document::{ColumnDivideType, CtrlHeader, HwpDocument, Paragraph, ParagraphRecord};
use crate::viewer::core::renderer::{DocumentParts, Renderer};
use crate::viewer::markdown::utils::OutlineNumberTracker;
use crate::viewer::{html, html::HtmlOptions, MarkdownOptions};
/// Render paragraph using viewer-specific functions
/// 뷰어별 함수를 사용하여 문단 렌더링
///
/// 이 함수는 타입별로 기존 뷰어 함수를 호출하여 글자 모양, 개요 번호 등
/// 복잡한 처리를 기존 로직으로 처리합니다.
///
/// This function calls existing viewer functions by type to handle complex
/// processing like character shapes, outline numbers, etc. with existing logic.
///
/// tracker는 문서 전체에 걸쳐 상태를 유지해야 하므로 외부에서 전달받습니다.
/// tracker maintains state across the entire document, so it's passed from outside.
fn render_paragraph_with_viewer<R: Renderer>(
paragraph: &Paragraph,
document: &HwpDocument,
renderer: &R,
options: &R::Options,
tracker: &mut dyn TrackerRef,
) -> String
where
R::Options: 'static,
{
// 타입 체크를 통해 기존 뷰어 함수 호출 / Call existing viewer functions through type checking
// HTML 렌더러인 경우 - 새로운 HTML 뷰어는 process_paragraph를 사용 / If HTML renderer - new HTML viewer uses process_paragraph
// HTML 뷰어는 to_html() 함수에서 직접 처리하므로 여기서는 기본 처리 사용
// HTML viewer is handled directly in to_html() function, so use default processing here
// Markdown 렌더러인 경우 / If Markdown renderer
if std::any::TypeId::of::<R::Options>()
== std::any::TypeId::of::<crate::viewer::markdown::MarkdownOptions>()
{
use crate::viewer::markdown::document::bodytext::paragraph::convert_paragraph_to_markdown;
// 안전하게 타입 캐스팅 / Safely cast type
unsafe {
let md_options =
&*(options as *const R::Options as *const crate::viewer::markdown::MarkdownOptions);
let md_tracker = tracker.as_markdown_tracker_mut();
return convert_paragraph_to_markdown(paragraph, document, md_options, md_tracker);
}
}
// 기본: 공통 paragraph 처리 사용 / Default: Use common paragraph processing
use crate::viewer::core::paragraph::process_paragraph;
process_paragraph(paragraph, document, renderer, options)
}
/// Trait for outline number tracker reference
/// 개요 번호 추적기 참조를 위한 트레이트
trait TrackerRef {
/// Get mutable reference to HTML tracker
/// HTML 추적기의 가변 참조 가져오기
/// Note: 새로운 HTML 뷰어는 OutlineNumberTracker를 사용하지 않음
/// Note: New HTML viewer does not use OutlineNumberTracker
unsafe fn as_html_tracker_mut(&mut self) -> &mut ();
/// Get mutable reference to Markdown tracker
/// Markdown 추적기의 가변 참조 가져오기
unsafe fn as_markdown_tracker_mut(&mut self) -> &mut OutlineNumberTracker;
}
/// Enum to hold tracker by renderer type
/// 렌더러 타입별 추적기를 보관하는 열거형
enum Tracker {
/// HTML 뷰어는 더 이상 OutlineNumberTracker를 사용하지 않음
/// HTML viewer no longer uses OutlineNumberTracker
Html(()),
Markdown(OutlineNumberTracker),
}
impl TrackerRef for Tracker {
unsafe fn as_html_tracker_mut(&mut self) -> &mut () {
match self {
Tracker::Html(_) => {
// 새로운 HTML 뷰어는 tracker를 사용하지 않음
// New HTML viewer does not use tracker
std::hint::unreachable_unchecked()
}
_ => std::hint::unreachable_unchecked(),
}
}
unsafe fn as_markdown_tracker_mut(&mut self) -> &mut OutlineNumberTracker {
match self {
Tracker::Markdown(tracker) => tracker,
_ => std::hint::unreachable_unchecked(),
}
}
}
/// Process bodytext and return document parts
/// 본문을 처리하고 문서 부분들을 반환
pub fn process_bodytext<R: Renderer>(
document: &HwpDocument,
renderer: &R,
options: &R::Options,
) -> DocumentParts
where
R::Options: 'static,
{
let mut parts = DocumentParts::default();
// 각주/미주 번호 추적기 / Footnote/endnote number tracker
let mut footnote_counter = 1u32;
let mut endnote_counter = 1u32;
// 개요 번호 추적기 생성 (렌더러별로 다름) / Create outline number tracker (varies by renderer)
// 문서 전체에 걸쳐 상태를 유지해야 하므로 한 번만 생성 / Created only once to maintain state across entire document
// 새로운 HTML 뷰어는 tracker를 사용하지 않음 / New HTML viewer does not use tracker
let mut tracker: Tracker = if std::any::TypeId::of::<R::Options>()
== std::any::TypeId::of::<HtmlOptions>()
{
Tracker::Html(())
} else if std::any::TypeId::of::<R::Options>() == std::any::TypeId::of::<MarkdownOptions>() {
Tracker::Markdown(OutlineNumberTracker::new())
} else {
// 기본 렌더러는 tracker가 필요 없을 수 있음 / Default renderer may not need tracker
// 하지만 일단 Markdown tracker를 사용 (나중에 필요시 수정) / But use Markdown tracker for now (modify later if needed)
Tracker::Markdown(OutlineNumberTracker::new())
};
// Convert body text / 본문 텍스트를 변환
for section in &document.body_text.sections {
for paragraph in §ion.paragraphs {
// control_mask를 사용하여 빠른 필터링 (최적화) / Use control_mask for quick filtering (optimization)
let control_mask = ¶graph.para_header.control_mask;
// control_mask로 머리말/꼬리말/각주/미주가 있는지 빠르게 확인 / Quickly check if header/footer/footnote/endnote exists using control_mask
let has_header_footer = control_mask.has_header_footer();
let has_footnote_endnote = control_mask.has_footnote_endnote();
// 머리말/꼬리말/각주/미주 컨트롤 처리 / Process header/footer/footnote/endnote controls
if has_header_footer || has_footnote_endnote {
for record in ¶graph.records {
if let ParagraphRecord::CtrlHeader {
header,
children,
paragraphs: ctrl_paragraphs,
} = record
{
use crate::document::CtrlId;
if header.ctrl_id.as_str() == CtrlId::HEADER {
// 머리말 처리 / Process header
process_header(
header,
children,
ctrl_paragraphs,
document,
renderer,
options,
&mut parts,
&mut tracker,
);
} else if header.ctrl_id.as_str() == CtrlId::FOOTER {
// 꼬리말 처리 / Process footer
process_footer(
header,
children,
ctrl_paragraphs,
document,
renderer,
options,
&mut parts,
&mut tracker,
);
} else if header.ctrl_id.as_str() == CtrlId::FOOTNOTE {
// 각주 처리 / Process footnote
let footnote_id = footnote_counter;
footnote_counter += 1;
process_footnote(
footnote_id,
header,
children,
ctrl_paragraphs,
document,
renderer,
options,
&mut parts,
&mut tracker,
);
} else if header.ctrl_id.as_str() == CtrlId::ENDNOTE {
// 미주 처리 / Process endnote
let endnote_id = endnote_counter;
endnote_counter += 1;
process_endnote(
endnote_id,
header,
children,
ctrl_paragraphs,
document,
renderer,
options,
&mut parts,
&mut tracker,
);
}
// 테이블은 paragraph.rs에서 처리 / Table is processed in paragraph.rs
}
}
}
// 일반 본문 문단 처리 (컨트롤이 없는 경우) / Process regular body paragraph (when no controls)
if !has_header_footer && !has_footnote_endnote {
// 페이지 나누기 확인 / Check for page break
let has_page_break = paragraph
.para_header
.column_divide_type
.iter()
.any(|t| matches!(t, ColumnDivideType::Page | ColumnDivideType::Section));
if has_page_break && !parts.body_lines.is_empty() {
let last_line = parts.body_lines.last().map(String::as_str).unwrap_or("");
// 페이지 구분선이 이미 있는지 확인 (렌더러별로 다름) / Check if page break already exists (varies by renderer)
if !last_line.is_empty() && !is_page_break_line(last_line, renderer) {
parts.body_lines.push(renderer.render_page_break());
}
}
// 문단 처리 / Process paragraph
let para_content = render_paragraph_with_viewer(
paragraph,
document,
renderer,
options,
&mut tracker,
);
if !para_content.is_empty() {
parts.body_lines.push(para_content);
}
}
}
}
parts
}
/// Check if a line is a page break line (renderer-specific)
/// 페이지 구분선인지 확인 (렌더러별)
fn is_page_break_line<R: Renderer>(line: &str, _renderer: &R) -> bool {
// HTML: <hr
// Markdown: ---
line.contains("<hr") || line == "---"
}
/// Process header
/// 머리말 처리
fn process_header<R: Renderer>(
_header: &CtrlHeader,
children: &[ParagraphRecord],
ctrl_paragraphs: &[Paragraph],
document: &HwpDocument,
renderer: &R,
options: &R::Options,
parts: &mut DocumentParts,
tracker: &mut dyn TrackerRef,
) where
R::Options: 'static,
{
// LIST_HEADER가 있으면 children에서 처리, 없으면 paragraphs에서 처리
// If LIST_HEADER exists, process from children, otherwise from paragraphs
let mut found_list_header = false;
for child_record in children {
if let ParagraphRecord::ListHeader { paragraphs, .. } = child_record {
found_list_header = true;
// LIST_HEADER 내부의 문단 처리 / Process paragraphs inside LIST_HEADER
// 기존 뷰어 함수를 직접 호출 (글자 모양, 개요 번호 등 복잡한 처리를 위해)
// Call existing viewer functions directly (for complex processing like character shapes, outline numbers, etc.)
for para in paragraphs {
let para_content =
render_paragraph_with_viewer(para, document, renderer, options, tracker);
if !para_content.is_empty() {
parts.headers.push(para_content);
}
}
}
}
// LIST_HEADER가 없으면 paragraphs 처리 / If no LIST_HEADER, process paragraphs
if !found_list_header {
for para in ctrl_paragraphs {
let para_content =
render_paragraph_with_viewer(para, document, renderer, options, tracker);
if !para_content.is_empty() {
parts.headers.push(para_content);
}
}
}
}
/// Process footer
/// 꼬리말 처리
fn process_footer<R: Renderer>(
_header: &CtrlHeader,
children: &[ParagraphRecord],
ctrl_paragraphs: &[Paragraph],
document: &HwpDocument,
renderer: &R,
options: &R::Options,
parts: &mut DocumentParts,
tracker: &mut dyn TrackerRef,
) where
R::Options: 'static,
{
// LIST_HEADER가 있으면 children에서 처리, 없으면 paragraphs에서 처리
// If LIST_HEADER exists, process from children, otherwise from paragraphs
let mut found_list_header = false;
for child_record in children {
if let ParagraphRecord::ListHeader { paragraphs, .. } = child_record {
found_list_header = true;
// LIST_HEADER 내부의 문단 처리 / Process paragraphs inside LIST_HEADER
for para in paragraphs {
let para_content =
render_paragraph_with_viewer(para, document, renderer, options, tracker);
if !para_content.is_empty() {
parts.footers.push(para_content);
}
}
}
}
// LIST_HEADER가 없으면 paragraphs 처리 / If no LIST_HEADER, process paragraphs
if !found_list_header {
for para in ctrl_paragraphs {
let para_content =
render_paragraph_with_viewer(para, document, renderer, options, tracker);
if !para_content.is_empty() {
parts.footers.push(para_content);
}
}
}
}
/// Process footnote
/// 각주 처리
fn process_footnote<R: Renderer>(
footnote_id: u32,
_header: &CtrlHeader,
_children: &[ParagraphRecord],
ctrl_paragraphs: &[Paragraph],
document: &HwpDocument,
renderer: &R,
options: &R::Options,
parts: &mut DocumentParts,
tracker: &mut dyn TrackerRef,
) where
R::Options: 'static,
{
// 각주 번호 형식 (TODO: FootnoteShape에서 가져오기)
// Footnote number format (TODO: Get from FootnoteShape)
let footnote_number = format!("{}", footnote_id);
// 본문에 각주 참조 링크 삽입 / Insert footnote reference link in body
if !parts.body_lines.is_empty() {
let last_idx = parts.body_lines.len() - 1;
let last_line = &mut parts.body_lines[last_idx];
// 렌더러별로 각주 참조 링크 추가 방법이 다름
// Method to add footnote reference link varies by renderer
let footnote_ref = renderer.render_footnote_ref(footnote_id, &footnote_number, options);
*last_line = append_to_last_paragraph(last_line, &footnote_ref, renderer);
} else {
// 본문이 비어있으면 새 문단으로 추가 / Add as new paragraph if body is empty
let footnote_ref = renderer.render_footnote_ref(footnote_id, &footnote_number, options);
parts
.body_lines
.push(renderer.render_paragraph(&footnote_ref));
}
// 각주 내용 수집 / Collect footnote content
for para in ctrl_paragraphs {
let para_content = render_paragraph_with_viewer(para, document, renderer, options, tracker);
if !para_content.is_empty() {
let footnote_ref_id = format!("footnote-{}-ref", footnote_id);
let footnote_back = renderer.render_footnote_back(&footnote_ref_id, options);
let footnote_id_str = format!("footnote-{}", footnote_id);
// 렌더러별 각주 컨테이너 형식 (HTML: <div>, Markdown: 일반 텍스트)
// Footnote container format by renderer (HTML: <div>, Markdown: plain text)
let footnote_container = format_footnote_container(
&footnote_id_str,
&footnote_back,
¶_content,
renderer,
options,
);
parts.footnotes.push(footnote_container);
}
}
}
/// Process endnote
/// 미주 처리
fn process_endnote<R: Renderer>(
endnote_id: u32,
_header: &CtrlHeader,
_children: &[ParagraphRecord],
ctrl_paragraphs: &[Paragraph],
document: &HwpDocument,
renderer: &R,
options: &R::Options,
parts: &mut DocumentParts,
tracker: &mut dyn TrackerRef,
) where
R::Options: 'static,
{
// 미주 번호 형식 (TODO: FootnoteShape에서 가져오기)
// Endnote number format (TODO: Get from FootnoteShape)
let endnote_number = format!("{}", endnote_id);
// 본문에 미주 참조 링크 삽입 / Insert endnote reference link in body
if !parts.body_lines.is_empty() {
let last_idx = parts.body_lines.len() - 1;
let last_line = &mut parts.body_lines[last_idx];
let endnote_ref = renderer.render_endnote_ref(endnote_id, &endnote_number, options);
*last_line = append_to_last_paragraph(last_line, &endnote_ref, renderer);
} else {
// 본문이 비어있으면 새 문단으로 추가 / Add as new paragraph if body is empty
let endnote_ref = renderer.render_endnote_ref(endnote_id, &endnote_number, options);
parts
.body_lines
.push(renderer.render_paragraph(&endnote_ref));
}
// 미주 내용 수집 / Collect endnote content
for para in ctrl_paragraphs {
let para_content = render_paragraph_with_viewer(para, document, renderer, options, tracker);
if !para_content.is_empty() {
let endnote_ref_id = format!("endnote-{}-ref", endnote_id);
let endnote_back = renderer.render_endnote_back(&endnote_ref_id, options);
let endnote_id_str = format!("endnote-{}", endnote_id);
parts.endnotes.push(format_endnote_container(
&endnote_id_str,
&endnote_back,
¶_content,
renderer,
options,
));
}
}
}
/// Append content to last paragraph (renderer-specific)
/// 마지막 문단에 내용 추가 (렌더러별)
fn append_to_last_paragraph<R: Renderer>(last_line: &str, content: &str, _renderer: &R) -> String {
// HTML: </p> 태그 앞에 추가
// Markdown: 문단 끝에 추가
if last_line.contains("</p>") {
last_line.replace("</p>", &format!(" {}</p>", content))
} else {
format!("{} {}", last_line, content)
}
}
/// Format footnote container (renderer-specific)
/// 각주 컨테이너 포맷 (렌더러별)
fn format_footnote_container<R: Renderer>(
id: &str,
back_link: &str,
content: &str,
_renderer: &R,
options: &R::Options,
) -> String
where
R::Options: 'static,
{
// 타입 체크를 통해 렌더러별 포맷 적용 / Apply renderer-specific format through type checking
// HTML 렌더러인 경우 / If HTML renderer
if std::any::TypeId::of::<R::Options>() == std::any::TypeId::of::<HtmlOptions>() {
unsafe {
let html_options = &*(options as *const R::Options as *const html::HtmlOptions);
return format!(
r#" <div id="{}" class="{}footnote">"#,
id, html_options.css_class_prefix
) + &format!(r#" {}"#, back_link)
+ content
+ " </div>";
}
}
// Markdown 렌더러인 경우 / If Markdown renderer
if std::any::TypeId::of::<R::Options>() == std::any::TypeId::of::<MarkdownOptions>() {
// 마크다운에서는 각주를 [^1]: 형식으로 표시
// In markdown, footnotes are shown as [^1]:
return format!("{}{}", back_link, content);
}
// 기본: 일반 텍스트 / Default: plain text
format!("{} {}", back_link, content)
}
/// Format endnote container (renderer-specific)
/// 미주 컨테이너 포맷 (렌더러별)
fn format_endnote_container<R: Renderer>(
id: &str,
back_link: &str,
content: &str,
_renderer: &R,
options: &R::Options,
) -> String
where
R::Options: 'static,
{
// 타입 체크를 통해 렌더러별 포맷 적용 / Apply renderer-specific format through type checking
// HTML 렌더러인 경우 / If HTML renderer
if std::any::TypeId::of::<R::Options>() == std::any::TypeId::of::<HtmlOptions>() {
unsafe {
let html_options = &*(options as *const R::Options as *const html::HtmlOptions);
return format!(
r#" <div id="{}" class="{}endnote">"#,
id, html_options.css_class_prefix
) + &format!(r#" {}"#, back_link)
+ content
+ " </div>";
}
}
// Markdown 렌더러인 경우 / If Markdown renderer
if std::any::TypeId::of::<R::Options>() == std::any::TypeId::of::<MarkdownOptions>() {
// 마크다운에서는 미주를 [^1]: 형식으로 표시
// In markdown, endnotes are shown as [^1]:
return format!("{}{}", back_link, content);
}
// 기본: 일반 텍스트 / Default: plain text
format!("{} {}", back_link, content)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/core/mod.rs | crates/hwp-core/src/viewer/core/mod.rs | /// Core viewer module - 공통 로직
/// Core viewer module - Common logic
///
/// 이 모듈은 모든 뷰어(HTML, Markdown, PDF, Image 등)에서 공통으로 사용되는
/// 로직을 제공합니다. 출력 형식만 다른 렌더러 패턴을 사용합니다.
///
/// This module provides common logic used by all viewers (HTML, Markdown, PDF, Image, etc.).
/// Uses a renderer pattern where only the output format differs.
pub mod bodytext;
mod paragraph;
pub mod renderer;
pub use bodytext::process_bodytext;
pub use paragraph::process_paragraph;
pub use renderer::{DocumentParts, Renderer, TextStyles};
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/core/paragraph.rs | crates/hwp-core/src/viewer/core/paragraph.rs | /// Common paragraph processing logic
/// 공통 문단 처리 로직
///
/// 모든 뷰어에서 공통으로 사용되는 문단 처리 로직을 제공합니다.
/// 출력 형식은 Renderer 트레이트를 통해 처리됩니다.
///
/// Provides common paragraph processing logic used by all viewers.
/// Output format is handled through the Renderer trait.
use crate::document::{HwpDocument, Paragraph, ParagraphRecord};
use crate::viewer::core::renderer::Renderer;
use crate::viewer::markdown::collect::collect_text_and_images_from_paragraph;
/// Process a paragraph and return rendered content
/// 문단을 처리하고 렌더링된 내용을 반환
pub fn process_paragraph<R: Renderer>(
paragraph: &Paragraph,
document: &HwpDocument,
renderer: &R,
options: &R::Options,
) -> String {
if paragraph.records.is_empty() {
return String::new();
}
let mut parts = Vec::new();
let mut text_parts = Vec::new(); // 같은 문단 내의 텍스트 레코드들을 모음
// TODO: 글자 모양 정보 수집 및 적용 (렌더러별로 다름)
// Character shape information collection and application (varies by renderer)
// Process all records in order / 모든 레코드를 순서대로 처리
for record in ¶graph.records {
match record {
ParagraphRecord::ParaText {
text,
control_char_positions: _,
..
} => {
// ParaText 처리 / Process ParaText
// TODO: 글자 모양 적용 로직 구현 (렌더러별로 다름)
// Character shape application logic (varies by renderer)
// 현재는 간단히 텍스트만 사용
// For now, just use text
let text_content = text.to_string();
text_parts.push(text_content);
}
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
// 이미지 처리 / Process image
if let Some(image_content) = renderer.render_image(
shape_component_picture.picture_info.bindata_id,
document,
options,
) {
parts.push(image_content);
}
}
ParagraphRecord::Table { table } => {
// 테이블 처리 / Process table
let table_content = renderer.render_table(table, document, options);
if !table_content.is_empty() {
parts.push(table_content);
}
}
ParagraphRecord::CtrlHeader {
header,
children,
paragraphs: ctrl_paragraphs,
..
} => {
// 컨트롤 헤더 처리 / Process control header
process_ctrl_header(
header,
children,
ctrl_paragraphs,
document,
renderer,
options,
&mut parts,
);
}
_ => {
// 기타 레코드는 무시 / Ignore other records
}
}
}
// 같은 문단 내의 텍스트를 합침 / Combine text in the same paragraph
if !text_parts.is_empty() {
let combined_text = text_parts.join("");
// TODO: 개요 번호 처리 (렌더러별로 다름)
// Outline number processing (varies by renderer)
parts.push(renderer.render_paragraph(&combined_text));
}
// HTML로 결합 / Combine into output
if parts.is_empty() {
return String::new();
}
if parts.len() == 1 {
return parts[0].clone();
}
parts.join("")
}
/// Process CtrlHeader
/// 컨트롤 헤더 처리
fn process_ctrl_header<R: Renderer>(
header: &crate::document::CtrlHeader,
children: &[ParagraphRecord],
ctrl_paragraphs: &[Paragraph],
document: &HwpDocument,
renderer: &R,
options: &R::Options,
parts: &mut Vec<String>,
) {
use crate::document::CtrlId;
// 표 셀 내부의 텍스트와 이미지를 수집하여 셀 내부 문단인지 확인
// Collect text and images from paragraphs in Table.cells to check if they are cell content
let mut table_cell_texts: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut table_cell_image_ids: std::collections::HashSet<u16> = std::collections::HashSet::new();
let mut table_cell_para_ids: std::collections::HashSet<u32> = std::collections::HashSet::new();
let mut table_opt: Option<&crate::document::bodytext::Table> = None;
let is_table_control = header.ctrl_id.as_str() == CtrlId::TABLE;
// 먼저 TABLE을 찾아서 table_opt에 저장 / First find TABLE and store in table_opt
for child in children {
if let ParagraphRecord::Table { table } = child {
table_opt = Some(table);
break;
}
}
if let Some(table) = table_opt {
for cell in &table.cells {
for para in &cell.paragraphs {
if para.para_header.instance_id != 0 {
table_cell_para_ids.insert(para.para_header.instance_id);
}
collect_text_and_images_from_paragraph(
para,
&mut table_cell_texts,
&mut table_cell_image_ids,
);
}
}
}
// 컨트롤 헤더의 자식 레코드들을 순회하며 처리 / Iterate through control header's child records
for child in children {
match child {
ParagraphRecord::Table { table } => {
// 표 변환 / Convert table
let table_content = renderer.render_table(table, document, options);
if !table_content.is_empty() {
parts.push(table_content);
}
}
_ => {
// 기타 레코드는 무시 / Ignore other records
}
}
}
// CTRL_HEADER 내부의 직접 문단 처리 / Process direct paragraphs inside CTRL_HEADER
for para in ctrl_paragraphs {
// 표 셀 내부의 문단인지 확인 / Check if paragraph is inside table cell
let is_table_cell = if is_table_control && table_opt.is_some() {
// 먼저 instance_id로 확인 (가장 정확, 0이 아닌 경우만)
let is_table_cell_by_id = !table_cell_para_ids.is_empty()
&& para.para_header.instance_id != 0
&& table_cell_para_ids.contains(¶.para_header.instance_id);
if is_table_cell_by_id {
true
} else {
// 재귀적으로 문단에서 텍스트와 이미지를 수집하여 표 셀 내부인지 확인
let mut para_texts = std::collections::HashSet::new();
let mut para_image_ids = std::collections::HashSet::new();
collect_text_and_images_from_paragraph(para, &mut para_texts, &mut para_image_ids);
(!para_texts.is_empty()
&& para_texts
.iter()
.any(|text| table_cell_texts.contains(text)))
|| (!para_image_ids.is_empty()
&& para_image_ids
.iter()
.any(|id| table_cell_image_ids.contains(id)))
}
} else {
false
};
// 표 셀 내부가 아닌 경우에만 처리 / Only process if not inside table cell
if !is_table_cell {
let para_content = process_paragraph(para, document, renderer, options);
if !para_content.is_empty() {
parts.push(para_content);
}
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/renderer.rs | crates/hwp-core/src/viewer/markdown/renderer.rs | /// Markdown Renderer implementation
/// Markdown 렌더러 구현
use crate::document::{bodytext::Table, HwpDocument};
use crate::viewer::core::renderer::{DocumentParts, Renderer, TextStyles};
/// Markdown Renderer
pub struct MarkdownRenderer;
impl Renderer for MarkdownRenderer {
type Options = crate::viewer::markdown::MarkdownOptions;
// ===== Text Styling =====
fn render_text(&self, text: &str, _styles: &TextStyles) -> String {
// TODO: 스타일 적용 (마크다운에서는 제한적)
text.to_string()
}
fn render_bold(&self, text: &str) -> String {
format!("**{}**", text)
}
fn render_italic(&self, text: &str) -> String {
format!("*{}*", text)
}
fn render_underline(&self, text: &str) -> String {
// 마크다운에서는 밑줄을 직접 지원하지 않으므로 HTML 태그 사용
// Markdown doesn't directly support underline, so use HTML tag
format!("<u>{}</u>", text)
}
fn render_strikethrough(&self, text: &str) -> String {
format!("~~{}~~", text)
}
fn render_superscript(&self, text: &str) -> String {
// 마크다운에서는 위첨자를 직접 지원하지 않으므로 HTML 태그 사용
// Markdown doesn't directly support superscript, so use HTML tag
format!("<sup>{}</sup>", text)
}
fn render_subscript(&self, text: &str) -> String {
// 마크다운에서는 아래첨자를 직접 지원하지 않으므로 HTML 태그 사용
// Markdown doesn't directly support subscript, so use HTML tag
format!("<sub>{}</sub>", text)
}
// ===== Structure Elements =====
fn render_paragraph(&self, content: &str) -> String {
// 마크다운에서는 문단이 빈 줄로 구분되므로 그냥 텍스트 반환
// In markdown, paragraphs are separated by blank lines, so just return text
content.to_string()
}
fn render_table(
&self,
table: &Table,
document: &HwpDocument,
options: &Self::Options,
) -> String {
// 기존 테이블 변환 함수 사용
use crate::viewer::markdown::document::bodytext::table::convert_table_to_markdown;
use crate::viewer::markdown::utils::OutlineNumberTracker;
let mut tracker = OutlineNumberTracker::new();
convert_table_to_markdown(table, document, options, &mut tracker)
}
fn render_image(
&self,
image_id: u16,
document: &HwpDocument,
options: &Self::Options,
) -> Option<String> {
// bindata_id로 직접 이미지 렌더링 / Render image directly by bindata_id
use crate::viewer::markdown::common::format_image_markdown;
// BinData에서 이미지 데이터 가져오기 / Get image data from BinData
if let Some(bin_item) = document
.bin_data
.items
.iter()
.find(|item| item.index == image_id)
{
let image_markdown = format_image_markdown(
document,
image_id,
&bin_item.data,
options.image_output_dir.as_deref(),
);
if !image_markdown.is_empty() {
return Some(image_markdown);
}
}
None
}
fn render_page_break(&self) -> String {
"---\n".to_string()
}
// ===== Document Structure =====
fn render_document(
&self,
_parts: &DocumentParts,
document: &HwpDocument,
options: &Self::Options,
) -> String {
// 기존 to_markdown 함수의 로직 사용
use crate::viewer::markdown::to_markdown;
to_markdown(document, options)
}
fn render_document_header(
&self,
document: &HwpDocument,
options: &Self::Options,
) -> String {
let mut md = String::new();
md.push_str("# HWP 문서\n");
md.push_str("\n");
if options.include_version != Some(false) {
use crate::viewer::markdown::document::fileheader::format_version;
md.push_str(&format!("**버전**: {}\n", format_version(document)));
md.push_str("\n");
}
md
}
fn render_document_footer(
&self,
parts: &DocumentParts,
_options: &Self::Options,
) -> String {
let mut md = String::new();
if !parts.footnotes.is_empty() {
md.push_str("## 각주\n");
md.push_str("\n");
for footnote in &parts.footnotes {
md.push_str(footnote);
md.push_str("\n");
}
}
if !parts.endnotes.is_empty() {
md.push_str("## 미주\n");
md.push_str("\n");
for endnote in &parts.endnotes {
md.push_str(endnote);
md.push_str("\n");
}
}
md
}
// ===== Special Elements =====
fn render_footnote_ref(&self, id: u32, number: &str, _options: &Self::Options) -> String {
// 마크다운에서는 각주 참조를 [^1] 형식으로 표시
// In markdown, footnote references are shown as [^1]
format!("[^{}]", number)
}
fn render_endnote_ref(&self, id: u32, number: &str, _options: &Self::Options) -> String {
// 마크다운에서는 미주 참조를 [^1] 형식으로 표시
// In markdown, endnote references are shown as [^1]
format!("[^{}]", number)
}
fn render_footnote_back(&self, _ref_id: &str, _options: &Self::Options) -> String {
// 마크다운에서는 각주 돌아가기 링크를 지원하지 않음
// Markdown doesn't support footnote back links
String::new()
}
fn render_endnote_back(&self, _ref_id: &str, _options: &Self::Options) -> String {
// 마크다운에서는 미주 돌아가기 링크를 지원하지 않음
// Markdown doesn't support endnote back links
String::new()
}
fn render_outline_number(&self, _level: u8, _number: u32, content: &str) -> String {
// TODO: 개요 번호 형식 적용
content.to_string()
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/collect.rs | crates/hwp-core/src/viewer/markdown/collect.rs | /// Functions for collecting text and images from paragraphs
/// 문단에서 텍스트와 이미지를 수집하는 함수들
use crate::document::ParagraphRecord;
/// 재귀적으로 paragraph에서 텍스트와 이미지 ID를 수집
/// Recursively collect text and image IDs from paragraph
pub fn collect_text_and_images_from_paragraph(
para: &crate::document::bodytext::Paragraph,
table_cell_texts: &mut std::collections::HashSet<String>,
table_cell_image_ids: &mut std::collections::HashSet<u16>,
) {
for record in ¶.records {
match record {
ParagraphRecord::ParaText { text, .. } => {
if !text.trim().is_empty() {
table_cell_texts.insert(text.trim().to_string());
}
}
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
// 이미지 ID 수집 / Collect image ID
table_cell_image_ids.insert(shape_component_picture.picture_info.bindata_id);
}
ParagraphRecord::CtrlHeader {
children,
paragraphs: ctrl_paragraphs,
..
} => {
// CTRL_HEADER 내부의 paragraphs도 재귀적으로 확인 / Recursively check paragraphs inside CTRL_HEADER
for ctrl_para in ctrl_paragraphs {
collect_text_and_images_from_paragraph(
ctrl_para,
table_cell_texts,
table_cell_image_ids,
);
}
// CTRL_HEADER의 children도 재귀적으로 확인 / Recursively check children of CTRL_HEADER
for child in children {
match child {
ParagraphRecord::ShapeComponent { children, .. } => {
// SHAPE_COMPONENT의 children 확인 / Check SHAPE_COMPONENT's children
for shape_child in children {
match shape_child {
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
table_cell_image_ids.insert(
shape_component_picture.picture_info.bindata_id,
);
}
ParagraphRecord::ListHeader { paragraphs, .. } => {
// LIST_HEADER의 paragraphs도 확인 / Check LIST_HEADER's paragraphs
for list_para in paragraphs {
collect_text_and_images_from_paragraph(
list_para,
table_cell_texts,
table_cell_image_ids,
);
}
}
_ => {}
}
}
}
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
table_cell_image_ids
.insert(shape_component_picture.picture_info.bindata_id);
}
_ => {}
}
}
}
_ => {}
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/utils.rs | crates/hwp-core/src/viewer/markdown/utils.rs | /// Utility functions for Markdown conversion
/// 마크다운 변환을 위한 유틸리티 함수들
use crate::document::{HeaderShapeType, HwpDocument};
/// 개요 번호 추적 구조체 / Outline number tracking structure
/// 각 레벨별로 번호를 추적하여 개요 번호를 생성
/// Tracks numbers per level to generate outline numbers
#[derive(Debug, Clone)]
pub(crate) struct OutlineNumberTracker {
/// 각 레벨별 번호 카운터 (인덱스는 레벨-1) / Number counter per level (index is level-1)
counters: [u32; 7],
}
impl OutlineNumberTracker {
/// 새로운 추적기 생성 / Create new tracker
pub(crate) fn new() -> Self {
Self { counters: [0; 7] }
}
/// 개요 레벨의 번호를 증가시키고 반환 / Increment and return number for outline level
pub(crate) fn get_and_increment(&mut self, level: u8) -> u32 {
// 레벨 8 이상은 번호를 사용하지 않음 / Levels 8 and above don't use numbers
// 카운터도 증가시키지 않음 / Don't increment counters either
if level >= 8 {
return 0;
}
let level_index = (level - 1) as usize;
if level_index < 7 {
// 현재 레벨의 카운터가 0이 아니면 같은 레벨이 연속으로 나오는 것
// If current level counter is not 0, it means the same level is continuing
let is_same_level = self.counters[level_index] > 0;
if is_same_level {
// 같은 레벨이 연속으로 나올 때: 현재 레벨만 증가, 하위 레벨만 초기화
// When same level continues: only increment current level, reset only lower levels
for i in (level_index + 1)..7 {
self.counters[i] = 0;
}
self.counters[level_index] += 1;
} else {
// 상위 레벨로 이동하거나 새로운 레벨: 현재 레벨과 하위 레벨 모두 초기화
// Moving to higher level or new level: reset current level and lower levels
for i in level_index..7 {
self.counters[i] = 0;
}
self.counters[level_index] = 1;
}
self.counters[level_index]
} else {
0
}
}
}
/// 버전 번호를 읽기 쉬운 문자열로 변환
/// Convert version number to readable string
pub(crate) fn format_version(document: &HwpDocument) -> String {
let version = document.file_header.version;
let major = (version >> 24) & 0xFF;
let minor = (version >> 16) & 0xFF;
let patch = (version >> 8) & 0xFF;
let build = version & 0xFF;
format!("{}.{:02}.{:02}.{:02}", major, minor, patch, build)
}
/// 문서에서 첫 번째 PageDef 정보 추출 / Extract first PageDef information from document
pub(crate) fn extract_page_info(
document: &HwpDocument,
) -> Option<&crate::document::bodytext::PageDef> {
use crate::document::ParagraphRecord;
for section in &document.body_text.sections {
for paragraph in §ion.paragraphs {
for record in ¶graph.records {
if let ParagraphRecord::PageDef { page_def } = record {
return Some(page_def);
}
}
}
}
None
}
/// Check if a part is a text part (not a block element)
/// part가 텍스트인지 확인 (블록 요소가 아님)
pub(crate) fn is_text_part(part: &str) -> bool {
!is_block_element(part)
}
/// Check if a part is a block element (image, table, etc.)
/// part가 블록 요소인지 확인 (이미지, 표 등)
pub(crate) fn is_block_element(part: &str) -> bool {
part.starts_with("![이미지]")
|| part.starts_with("|") // 테이블 / table
|| part.starts_with("---") // 페이지 구분선 / page break
// 개요 번호는 블록 요소가 아님 / Outline numbers are not block elements
}
/// Check if control header should be processed for markdown
/// 컨트롤 헤더가 마크다운 변환에서 처리되어야 하는지 확인
pub(crate) fn should_process_control_header(header: &crate::document::CtrlHeader) -> bool {
use crate::document::CtrlId;
match header.ctrl_id.as_str() {
// 마크다운으로 표현 가능한 컨트롤만 처리 / Only process controls that can be expressed in markdown
CtrlId::TABLE => true,
CtrlId::SHAPE_OBJECT => true, // 이미지는 자식 레코드에서 처리 / Images are processed from child records
CtrlId::HEADER => true, // 머리말 처리 / Process header
CtrlId::FOOTER => true, // 꼬리말 처리 / Process footer
CtrlId::FOOTNOTE => false, // 각주는 convert_bodytext_to_markdown에서 처리 / Footnotes are processed in convert_bodytext_to_markdown
CtrlId::ENDNOTE => false, // 미주는 convert_bodytext_to_markdown에서 처리 / Endnotes are processed in convert_bodytext_to_markdown
CtrlId::COLUMN_DEF => false, // 마크다운으로 표현 불가 / Cannot be expressed in markdown
CtrlId::PAGE_NUMBER | CtrlId::PAGE_NUMBER_POS => false, // 마크다운으로 표현 불가 / Cannot be expressed in markdown
_ => false, // 기타 컨트롤도 마크다운으로 표현 불가 / Other controls also cannot be expressed in markdown
}
}
/// 한글 개요 번호 형식 생성 / Generate Korean outline number format
/// 레벨에 따라 다른 번호 형식 사용 / Use different number format based on level
fn format_outline_number(level: u8, number: u32) -> String {
match level {
1 => format!("{}.", number), // 1.
2 => format!("{}.", number_to_hangul(number)), // 가.
3 => format!("{})", number), // 1)
4 => format!("{})", number_to_hangul(number)), // 가)
5 => format!("({})", number), // (1)
6 => format!("({})", number_to_hangul(number)), // (가)
7 => format!("{}", number_to_circled(number)), // ①
_ => format!("{}.", number), // 기본값 / default
}
}
/// 숫자를 한글 자모로 변환 / Convert number to Korean syllable
/// 1 -> 가, 2 -> 나, 3 -> 다, ... / 1 -> 가, 2 -> 나, 3 -> 다, ...
fn number_to_hangul(number: u32) -> String {
// 한글 자모 배열 (가, 나, 다, 라, 마, 바, 사, 아, 자, 차, 카, 타, 파, 하)
// Korean syllable array (가, 나, 다, 라, 마, 바, 사, 아, 자, 차, 카, 타, 파, 하)
const HANGUL_SYLLABLES: [char; 14] = [
'가', '나', '다', '라', '마', '바', '사', '아', '자', '차', '카', '타', '파', '하',
];
if number == 0 {
return String::new();
}
let index = ((number - 1) % 14) as usize;
HANGUL_SYLLABLES[index].to_string()
}
/// 숫자를 원 숫자로 변환 / Convert number to circled number
/// 1 -> ①, 2 -> ②, 3 -> ③, ... / 1 -> ①, 2 -> ②, 3 -> ③, ...
fn number_to_circled(number: u32) -> String {
if number == 0 || number > 20 {
return format!("{}", number);
}
// 원 숫자 유니코드 범위: 0x2460-0x2473 (①-⑳)
// Circled number Unicode range: 0x2460-0x2473 (①-⑳)
let code = 0x2460 + number - 1;
char::from_u32(code).unwrap_or(' ').to_string()
}
/// format_string이 번호를 사용하지 않는지 확인
/// Check if format_string indicates no numbering should be used
fn is_format_string_empty_or_null(format_string: &str) -> bool {
// 빈 문자열("")은 기본 형식 사용하므로 false 반환 (번호 표시)
// Empty string ("") uses default format, so return false (show number)
if format_string.is_empty() {
return false;
}
// null 문자(\u0000)만 포함하거나 모든 문자가 null 문자인 경우만 번호 없음
// Only null character (\u0000) or all characters are null means no number
// UTF-16LE로 디코딩된 null 문자는 단일 바이트 0 또는 "\u{0000}" 문자열로 나타날 수 있음
// Null character decoded from UTF-16LE may appear as single byte 0 or "\u{0000}" string
// 모든 문자가 null 문자인지 확인 (가장 안전한 방법)
// Check if all characters are null (safest method)
if format_string.chars().all(|c| c == '\u{0000}') {
return true;
}
// UTF-8 바이트가 모두 0인지 확인 (null 문자만 포함)
// Check if all UTF-8 bytes are 0 (only null characters)
if format_string.as_bytes().iter().all(|&b| b == 0) {
return true;
}
// 단일 null 문자인지 확인
// Check if it's a single null character
if format_string.len() == 1 {
// 문자로 확인
// Check as character
if format_string.chars().next() == Some('\u{0000}') {
return true;
}
// UTF-8 바이트로 확인
// Check as UTF-8 byte
if format_string.as_bytes()[0] == 0 {
return true;
}
}
false
}
/// 개요 레벨이면 텍스트 앞에 개요 번호를 추가
/// Add outline number prefix to text if it's an outline level
pub(crate) fn convert_to_outline_with_number(
text: &str,
para_header: &crate::document::bodytext::ParaHeader,
document: &HwpDocument,
tracker: &mut OutlineNumberTracker,
) -> String {
// ParaShape 찾기 (para_shape_id는 인덱스) / Find ParaShape (para_shape_id is index)
let para_shape_id = para_header.para_shape_id as usize;
if let Some(para_shape) = document.doc_info.para_shapes.get(para_shape_id) {
// 개요 타입이면 개요 번호 추가 / If outline type, add outline number
if para_shape.attributes1.header_shape_type == HeaderShapeType::Outline {
// paragraph_level + 1 = 실제 레벨 (0=레벨1, 1=레벨2, 2=레벨3, ...)
// paragraph_level + 1 = actual level (0=level1, 1=level2, 2=level3, ...)
let base_level = para_shape.attributes1.paragraph_level + 1;
// paragraph_level이 6이고 line_spacing이 7 이상이면 실제 레벨은 para_style_id를 사용하여 결정
// If paragraph_level is 6 and line_spacing is 7 or higher, determine actual level using para_style_id
let level = if base_level == 7 {
// paragraph_level이 6이면 base_level은 7 / If paragraph_level is 6, base_level is 7
// line_spacing이 7 이상이면 확장 레벨 (8-10) / If line_spacing >= 7, extended level (8-10)
// para_style_id를 사용하여 스타일 이름에서 레벨 추출
// Use para_style_id to extract level from style name
if let Some(line_spacing) = para_shape.line_spacing {
if line_spacing >= 7 && line_spacing <= 10 {
// para_style_id로 스타일 찾기 / Find style by para_style_id
if let Some(style) = document
.doc_info
.styles
.get(para_header.para_style_id as usize)
{
// 스타일 이름에서 레벨 추출 (예: "개요 8" -> 8, "개요 9" -> 9, "개요 10" -> 10)
// Extract level from style name (e.g., "개요 8" -> 8, "개요 9" -> 9, "개요 10" -> 10)
if style.local_name.starts_with("개요 ") {
if let Ok(style_level) = style.local_name[3..].trim().parse::<u8>()
{
if style_level >= 8 && style_level <= 10 {
style_level
} else {
// 스타일 레벨이 범위를 벗어나면 line_spacing 기반 계산
// If style level is out of range, calculate based on line_spacing
(line_spacing + 1) as u8
}
} else {
// 스타일 이름 파싱 실패 시 line_spacing 기반 계산
// If style name parsing fails, calculate based on line_spacing
(line_spacing + 1) as u8
}
} else {
// 스타일 이름이 "개요 "로 시작하지 않으면 line_spacing 기반 계산
// If style name doesn't start with "개요 ", calculate based on line_spacing
(line_spacing + 1) as u8
}
} else {
// 스타일을 찾을 수 없으면 line_spacing 기반 계산
// If style cannot be found, calculate based on line_spacing
(line_spacing + 1) as u8
}
} else {
base_level
}
} else {
base_level
}
} else {
base_level
};
// numbering_id로 numbering 정보 찾기 / Find numbering info by numbering_id
let numbering_id = para_shape.number_bullet_id as usize;
// 레벨 8-10인 경우 extended_levels의 format_string 확인
// For levels 8-10, check format_string from extended_levels
if level >= 8 {
if let Some(numbering) = document.doc_info.numbering.get(numbering_id) {
// 레벨 8은 extended_levels[0], 레벨 9는 extended_levels[1], 레벨 10은 extended_levels[2]
// Level 8 is extended_levels[0], level 9 is extended_levels[1], level 10 is extended_levels[2]
let extended_index = (level - 8) as usize;
// extended_levels 배열 범위 확인
// Check extended_levels array bounds
if extended_index < numbering.extended_levels.len() {
if let Some(extended_level) = numbering.extended_levels.get(extended_index)
{
// format_string이 null 문자만 포함하면 번호 없이 텍스트만 반환
// If format_string contains only null character, return text only without number
if is_format_string_empty_or_null(&extended_level.format_string) {
return text.to_string();
}
}
} else {
// extended_levels 배열 범위를 벗어나면 넘버링 없이 텍스트만 반환
// If extended_levels array index is out of bounds, return text only without number
return text.to_string();
}
// extended_levels가 없으면 번호 생성 (기본 동작)
// If extended_levels don't exist, generate number (default behavior)
} else {
// numbering이 없으면 넘버링 없이 텍스트만 반환 (레벨 8 이상은 numbering이 필요)
// If numbering doesn't exist, return text only without number (levels 8+ require numbering)
return text.to_string();
}
}
// 레벨 1-7인 경우 format_string 확인 (빈 문자열이면 기본 형식 사용)
// For levels 1-7, check format_string (empty string uses default format)
if let Some(numbering) = document.doc_info.numbering.get(numbering_id) {
let level_index = (level - 1) as usize;
if let Some(level_info) = numbering.levels.get(level_index) {
// format_string이 null 문자만 포함하면 번호 없이 텍스트만 반환
// If format_string contains only null character, return text only without number
// 빈 문자열("")은 기본 형식 사용 (번호 표시)
// Empty string ("") uses default format (show number)
if is_format_string_empty_or_null(&level_info.format_string) {
return text.to_string();
}
}
}
// format_string이 있으면 번호 생성 / Generate number if format_string exists
let number = tracker.get_and_increment(level);
let outline_number = format_outline_number(level, number);
return format!("{} {}", outline_number, text);
}
}
text.to_string()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/mod.rs | crates/hwp-core/src/viewer/markdown/mod.rs | /// Markdown converter for HWP documents
/// HWP 문서를 마크다운으로 변환하는 모듈
///
/// This module provides functionality to convert HWP documents to Markdown format.
/// 이 모듈은 HWP 문서를 마크다운 형식으로 변환하는 기능을 제공합니다.
///
/// 구조는 HWPTAG 기준으로 나뉘어 있습니다:
/// Structure is organized by HWPTAG:
/// - document: 문서 레벨 변환 (bodytext, docinfo, fileheader 등) / Document-level conversion (bodytext, docinfo, fileheader, etc.)
/// - bodytext: 본문 텍스트 관련 (para_text, paragraph, list_header, table, shape_component, shape_component_picture)
/// - docinfo: 문서 정보
/// - fileheader: 파일 헤더
/// - ctrl_header: CTRL_HEADER (HWPTAG_BEGIN + 55) - CtrlId별로 세분화
/// - utils: 유틸리티 함수들 / Utility functions
/// - collect: 텍스트/이미지 수집 함수들 / Text/image collection functions
pub mod collect;
mod common;
mod ctrl_header;
pub mod document;
mod renderer;
pub mod utils;
use crate::document::HwpDocument;
pub use ctrl_header::convert_control_to_markdown;
pub use document::bodytext::convert_paragraph_to_markdown;
pub use document::bodytext::convert_table_to_markdown;
pub use renderer::MarkdownRenderer;
/// Markdown 변환 옵션 / Markdown conversion options
#[derive(Debug, Clone)]
pub struct MarkdownOptions {
/// 이미지를 파일로 저장할 디렉토리 경로 (None이면 base64 데이터 URI로 임베드)
/// Optional directory path to save images as files. If None, images are embedded as base64 data URIs.
pub image_output_dir: Option<String>,
/// HTML 태그 사용 여부 (Some(true)인 경우 테이블 등 개행 불가 영역에 <br> 태그 사용)
/// Whether to use HTML tags (if Some(true), use <br> tags in areas where line breaks are not possible, such as tables)
pub use_html: Option<bool>,
/// 버전 정보 포함 여부 / Whether to include version information
pub include_version: Option<bool>,
/// 페이지 정보 포함 여부 / Whether to include page information
pub include_page_info: Option<bool>,
}
impl MarkdownOptions {
/// 이미지 출력 디렉토리 설정 / Set image output directory
pub fn with_image_output_dir(mut self, dir: Option<&str>) -> Self {
self.image_output_dir = dir.map(|s| s.to_string());
self
}
/// HTML 태그 사용 설정 / Set HTML tag usage
pub fn with_use_html(mut self, use_html: Option<bool>) -> Self {
self.use_html = use_html;
self
}
/// 버전 정보 포함 설정 / Set version information inclusion
pub fn with_include_version(mut self, include: Option<bool>) -> Self {
self.include_version = include;
self
}
/// 페이지 정보 포함 설정 / Set page information inclusion
pub fn with_include_page_info(mut self, include: Option<bool>) -> Self {
self.include_page_info = include;
self
}
}
/// Convert HWP document to Markdown format
/// HWP 문서를 마크다운 형식으로 변환
///
/// # Arguments / 매개변수
/// * `document` - The HWP document to convert / 변환할 HWP 문서
/// * `options` - Markdown conversion options / 마크다운 변환 옵션
///
/// # Returns / 반환값
/// Markdown string representation of the document / 문서의 마크다운 문자열 표현
pub fn to_markdown(document: &HwpDocument, options: &MarkdownOptions) -> String {
let mut lines = Vec::new();
// Add document title with version info / 문서 제목과 버전 정보 추가
lines.push("# HWP 문서".to_string());
lines.push(String::new());
// 버전 정보 추가 / Add version information
if options.include_version != Some(false) {
lines.push(format!("**버전**: {}", document::format_version(document)));
lines.push(String::new());
}
// 페이지 정보 추가 / Add page information
if options.include_page_info == Some(true) {
if let Some(page_def) = document::extract_page_info(document) {
let paper_width_mm = page_def.paper_width.to_mm();
let paper_height_mm = page_def.paper_height.to_mm();
let left_margin_mm = page_def.left_margin.to_mm();
let right_margin_mm = page_def.right_margin.to_mm();
let top_margin_mm = page_def.top_margin.to_mm();
let bottom_margin_mm = page_def.bottom_margin.to_mm();
lines.push(format!(
"**용지 크기**: {:.2}mm x {:.2}mm",
paper_width_mm, paper_height_mm
));
lines.push(format!(
"**용지 방향**: {:?}",
page_def.attributes.paper_direction
));
lines.push(format!(
"**여백**: 좌 {:.2}mm / 우 {:.2}mm / 상 {:.2}mm / 하 {:.2}mm",
left_margin_mm, right_margin_mm, top_margin_mm, bottom_margin_mm
));
lines.push(String::new());
}
}
// Convert body text to markdown using common logic / 공통 로직을 사용하여 본문 텍스트를 마크다운으로 변환
use crate::viewer::core::bodytext::process_bodytext;
use crate::viewer::markdown::renderer::MarkdownRenderer;
let renderer = MarkdownRenderer;
let parts = process_bodytext(document, &renderer, options);
// 머리말, 본문, 꼬리말, 각주, 미주 순서로 결합 / Combine in order: headers, body, footers, footnotes, endnotes
if !parts.headers.is_empty() {
lines.extend(parts.headers.clone());
lines.push(String::new());
}
lines.extend(parts.body_lines.clone());
if !parts.footers.is_empty() {
if !lines.is_empty() && !lines.last().unwrap().is_empty() {
lines.push(String::new());
}
lines.extend(parts.footers.clone());
}
if !parts.footnotes.is_empty() {
if !lines.is_empty() && !lines.last().unwrap().is_empty() {
lines.push(String::new());
}
// 각주 섹션 헤더 추가 / Add footnote section header
lines.push("## 각주".to_string());
lines.push(String::new());
lines.extend(parts.footnotes.clone());
}
if !parts.endnotes.is_empty() {
if !lines.is_empty() && !lines.last().unwrap().is_empty() {
lines.push(String::new());
}
// 미주 섹션 헤더 추가 / Add endnote section header
lines.push("## 미주".to_string());
lines.push(String::new());
lines.extend(parts.endnotes.clone());
}
// 문단 사이에 빈 줄을 추가하여 마크다운에서 각 문단이 구분되도록 함
// Add blank lines between paragraphs so each paragraph is distinguished in markdown
lines.join("\n\n")
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/common.rs | crates/hwp-core/src/viewer/markdown/common.rs | /// 공통 유틸리티 함수 / Common utility functions
///
/// 마크다운 변환에 사용되는 공통 함수들을 제공합니다.
/// Provides common functions used in markdown conversion.
use crate::document::{BinDataRecord, HwpDocument};
use crate::error::HwpError;
use base64::{engine::general_purpose::STANDARD, Engine as _};
use std::fs;
use std::path::Path;
/// Get MIME type from BinData ID using bin_data_records
/// bin_data_records를 사용하여 BinData ID에서 MIME 타입 가져오기
pub(crate) fn get_mime_type_from_bindata_id(
document: &HwpDocument,
bindata_id: crate::types::WORD,
) -> String {
// bin_data_records에서 EMBEDDING 타입의 extension 찾기 / Find extension from EMBEDDING type in bin_data_records
for record in &document.doc_info.bin_data {
if let BinDataRecord::Embedding { embedding, .. } = record {
if embedding.binary_data_id == bindata_id {
return match embedding.extension.to_lowercase().as_str() {
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
"gif" => "image/gif",
"bmp" => "image/bmp",
_ => "image/jpeg", // 기본값 / default
}
.to_string();
}
}
}
// 기본값 / default
"image/jpeg".to_string()
}
/// Get file extension from BinData ID using bin_data_records
/// bin_data_records를 사용하여 BinData ID에서 파일 확장자 가져오기
pub(crate) fn get_extension_from_bindata_id(
document: &HwpDocument,
bindata_id: crate::types::WORD,
) -> String {
// bin_data_records에서 EMBEDDING 타입의 extension 찾기 / Find extension from EMBEDDING type in bin_data_records
for record in &document.doc_info.bin_data {
if let BinDataRecord::Embedding { embedding, .. } = record {
if embedding.binary_data_id == bindata_id {
return embedding.extension.clone();
}
}
}
// 기본값 / default
"jpg".to_string()
}
/// Format image markdown - either as base64 data URI or file path
/// 이미지 마크다운 포맷 - base64 데이터 URI 또는 파일 경로
pub(crate) fn format_image_markdown(
document: &HwpDocument,
bindata_id: crate::types::WORD,
base64_data: &str,
image_output_dir: Option<&str>,
) -> String {
match image_output_dir {
Some(dir_path) => {
// 이미지를 파일로 저장하고 파일 경로를 마크다운에 포함 / Save image as file and include file path in markdown
match save_image_to_file(document, bindata_id, base64_data, dir_path) {
Ok(file_path) => {
// 상대 경로로 변환 (images/ 디렉토리 포함) / Convert to relative path (include images/ directory)
let file_path_obj = Path::new(&file_path);
let file_name = file_path_obj
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&file_path);
// images/ 디렉토리 경로 포함 / Include images/ directory path
format!("", file_name)
}
Err(e) => {
eprintln!("Failed to save image: {}", e);
// 실패 시 base64로 폴백 / Fallback to base64 on failure
let mime_type = get_mime_type_from_bindata_id(document, bindata_id);
format!("", mime_type, base64_data)
}
}
}
None => {
// base64 데이터 URI로 임베드 / Embed as base64 data URI
let mime_type = get_mime_type_from_bindata_id(document, bindata_id);
format!("", mime_type, base64_data)
}
}
}
/// Save image to file from base64 data
/// base64 데이터에서 이미지를 파일로 저장
fn save_image_to_file(
document: &HwpDocument,
bindata_id: crate::types::WORD,
base64_data: &str,
dir_path: &str,
) -> Result<String, HwpError> {
// base64 디코딩 / Decode base64
let image_data = STANDARD
.decode(base64_data)
.map_err(|e| HwpError::InternalError {
message: format!("Failed to decode base64: {}", e),
})?;
// 파일명 생성 / Generate filename
let extension = get_extension_from_bindata_id(document, bindata_id);
let file_name = format!("BIN{:04X}.{}", bindata_id, extension);
let file_path = Path::new(dir_path).join(&file_name);
// 디렉토리 생성 / Create directory
fs::create_dir_all(dir_path)
.map_err(|e| HwpError::Io(format!("Failed to create directory '{}': {}", dir_path, e)))?;
// 파일 저장 / Save file
fs::write(&file_path, &image_data).map_err(|e| {
HwpError::Io(format!(
"Failed to write file '{}': {}",
file_path.display(),
e
))
})?;
Ok(file_path.to_string_lossy().to_string())
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/endnote.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/endnote.rs | /// ENDNOTE CtrlId conversion to Markdown
/// ENDNOTE CtrlId를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 127 - 개체 이외의 컨트롤과 컨트롤 ID, ENDNOTE ("en ")
/// Spec mapping: Table 127 - Controls other than objects and Control IDs, ENDNOTE ("en ")
/// Convert ENDNOTE CtrlId to markdown
/// ENDNOTE CtrlId를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `header` - 컨트롤 헤더 / Control header
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_endnote_ctrl_to_markdown(
_header: &crate::document::CtrlHeader,
) -> String {
// 미주 제목 / Endnote title
// 실제 내용은 자식 레코드에서 처리됨 / Actual content is processed from child records
"## 미주".to_string()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/shape_object.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/shape_object.rs | /// SHAPE_OBJECT CtrlId conversion to Markdown
/// SHAPE_OBJECT CtrlId를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 127 - 개체 컨트롤 ID, SHAPE_OBJECT ("gso ")
/// Spec mapping: Table 127 - Object Control IDs, SHAPE_OBJECT ("gso ")
use crate::document::CtrlHeader;
/// Convert SHAPE_OBJECT CtrlId to markdown
/// SHAPE_OBJECT CtrlId를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `header` - 컨트롤 헤더 / Control header
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_shape_object_ctrl_to_markdown(_header: &CtrlHeader) -> String {
// 그리기 개체 메타데이터는 마크다운 뷰어에서 불필요하므로 빈 문자열 반환
// 실제 이미지나 내용은 자식 레코드에서 처리됨
// Shape object metadata is not needed in markdown viewer, so return empty string
// Actual images or content are processed from child records
String::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/footer.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/footer.rs | /// FOOTER CtrlId conversion to Markdown
/// FOOTER CtrlId를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 127 - 개체 이외의 컨트롤과 컨트롤 ID, FOOTER ("foot")
/// Spec mapping: Table 127 - Controls other than objects and Control IDs, FOOTER ("foot")
/// Convert FOOTER CtrlId to markdown
/// FOOTER CtrlId를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `header` - 컨트롤 헤더 / Control header
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_footer_ctrl_to_markdown(_header: &crate::document::CtrlHeader) -> String {
// 꼬리말 제목 / Footer title
// 실제 내용은 자식 레코드에서 처리됨 / Actual content is processed from child records
"## 꼬리말".to_string()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/column_def.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/column_def.rs | /// COLUMN_DEF CtrlId conversion to Markdown
/// COLUMN_DEF CtrlId를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 127 - 개체 이외의 컨트롤과 컨트롤 ID, COLUMN_DEF ("cold")
/// Spec mapping: Table 127 - Controls other than objects and Control IDs, COLUMN_DEF ("cold")
/// Convert COLUMN_DEF CtrlId to markdown
/// COLUMN_DEF CtrlId를 마크다운으로 변환
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_column_def_ctrl_to_markdown() -> String {
// 단 정의는 마크다운 뷰어에서 불필요하므로 빈 문자열 반환
// Column definition is not needed in markdown viewer, so return empty string
String::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/table.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/table.rs | /// TABLE CtrlId conversion to Markdown
/// TABLE CtrlId를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 127 - 개체 컨트롤 ID, TABLE ("tbl ")
/// Spec mapping: Table 127 - Object Control IDs, TABLE ("tbl ")
use crate::document::{CtrlHeader, CtrlHeaderData};
/// Convert TABLE CtrlId to markdown
/// TABLE CtrlId를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `header` - 컨트롤 헤더 / Control header
/// * `has_table` - 표가 이미 추출되었는지 여부 / Whether table was already extracted
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_table_ctrl_to_markdown(header: &CtrlHeader, has_table: bool) -> String {
// 표 (Table) / Table
// 표가 이미 추출되었다면 메시지를 출력하지 않음 / Don't output message if table was already extracted
if has_table {
return String::new();
}
let mut md = String::from("**표**");
if let CtrlHeaderData::ObjectCommon { description, .. } = &header.data {
if let Some(desc) = description {
if !desc.trim().is_empty() {
md.push_str(&format!(": {}", desc.trim()));
}
}
}
md.push_str("\n\n*[표 내용은 추출되지 않았습니다]*");
md
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/footnote.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/footnote.rs | /// FOOTNOTE CtrlId conversion to Markdown
/// FOOTNOTE CtrlId를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 127 - 개체 이외의 컨트롤과 컨트롤 ID, FOOTNOTE ("fn ")
/// Spec mapping: Table 127 - Controls other than objects and Control IDs, FOOTNOTE ("fn ")
/// Convert FOOTNOTE CtrlId to markdown
/// FOOTNOTE CtrlId를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `header` - 컨트롤 헤더 / Control header
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_footnote_ctrl_to_markdown(
_header: &crate::document::CtrlHeader,
) -> String {
// 각주 제목 / Footnote title
// 실제 내용은 자식 레코드에서 처리됨 / Actual content is processed from child records
"## 각주".to_string()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/header.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/header.rs | /// HEADER CtrlId conversion to Markdown
/// HEADER CtrlId를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 127 - 개체 이외의 컨트롤과 컨트롤 ID, HEADER ("head")
/// Spec mapping: Table 127 - Controls other than objects and Control IDs, HEADER ("head")
/// Convert HEADER CtrlId to markdown
/// HEADER CtrlId를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `header` - 컨트롤 헤더 / Control header
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_header_ctrl_to_markdown(
_header: &crate::document::CtrlHeader,
) -> String {
// 머리말 제목 / Header title
// 실제 내용은 자식 레코드에서 처리됨 / Actual content is processed from child records
"## 머리말".to_string()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/mod.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/mod.rs | /// CtrlHeader conversion to Markdown
/// CtrlHeader를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 57 - 본문의 데이터 레코드, CTRL_HEADER (HWPTAG_BEGIN + 55)
/// Spec mapping: Table 57 - BodyText data records, CTRL_HEADER (HWPTAG_BEGIN + 55)
mod column_def;
mod endnote;
mod footer;
mod footnote;
mod header;
mod page_number;
mod shape_object;
mod table;
use crate::document::{CtrlHeader, CtrlId};
use column_def::convert_column_def_ctrl_to_markdown;
use endnote::convert_endnote_ctrl_to_markdown;
use footer::convert_footer_ctrl_to_markdown;
use footnote::convert_footnote_ctrl_to_markdown;
use header::convert_header_ctrl_to_markdown;
use page_number::convert_page_number_ctrl_to_markdown;
use shape_object::convert_shape_object_ctrl_to_markdown;
use table::convert_table_ctrl_to_markdown;
/// Convert control header to markdown
/// 컨트롤 헤더를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `header` - 컨트롤 헤더 / Control header
/// * `has_table` - 표가 이미 추출되었는지 여부 / Whether table was already extracted
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub fn convert_control_to_markdown(header: &CtrlHeader, has_table: bool) -> String {
match header.ctrl_id.as_str() {
CtrlId::TABLE => convert_table_ctrl_to_markdown(header, has_table),
CtrlId::SHAPE_OBJECT => convert_shape_object_ctrl_to_markdown(header),
CtrlId::HEADER => convert_header_ctrl_to_markdown(header),
CtrlId::FOOTER => convert_footer_ctrl_to_markdown(header),
CtrlId::FOOTNOTE => convert_footnote_ctrl_to_markdown(header),
CtrlId::ENDNOTE => convert_endnote_ctrl_to_markdown(header),
CtrlId::COLUMN_DEF => convert_column_def_ctrl_to_markdown(),
CtrlId::PAGE_NUMBER | CtrlId::PAGE_NUMBER_POS => {
convert_page_number_ctrl_to_markdown(header)
}
_ => {
// 기타 컨트롤은 마크다운으로 표현할 수 없으므로 빈 문자열 반환
// Other controls cannot be expressed in markdown, so return empty string
String::new()
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/ctrl_header/page_number.rs | crates/hwp-core/src/viewer/markdown/ctrl_header/page_number.rs | /// PAGE_NUMBER CtrlId conversion to Markdown
/// PAGE_NUMBER CtrlId를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 127 - 개체 이외의 컨트롤과 컨트롤 ID, PAGE_NUMBER ("pgno") / PAGE_NUMBER_POS ("pgnp")
/// Spec mapping: Table 127 - Controls other than objects and Control IDs, PAGE_NUMBER ("pgno") / PAGE_NUMBER_POS ("pgnp")
use crate::document::CtrlHeader;
/// Convert PAGE_NUMBER or PAGE_NUMBER_POS CtrlId to markdown
/// PAGE_NUMBER 또는 PAGE_NUMBER_POS CtrlId를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `header` - 컨트롤 헤더 / Control header
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_page_number_ctrl_to_markdown(_header: &CtrlHeader) -> String {
// 쪽 번호 위치는 마크다운으로 표현할 수 없으므로 빈 문자열 반환
// Page number position cannot be expressed in markdown, so return empty string
String::new()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/docinfo.rs | crates/hwp-core/src/viewer/markdown/document/docinfo.rs | /// DocInfo conversion to Markdown
/// 문서 정보를 마크다운으로 변환하는 모듈
use crate::document::{HwpDocument, ParagraphRecord};
/// 문서에서 첫 번째 PageDef 정보 추출 / Extract first PageDef information from document
pub fn extract_page_info(document: &HwpDocument) -> Option<&crate::document::bodytext::PageDef> {
for section in &document.body_text.sections {
for paragraph in §ion.paragraphs {
for record in ¶graph.records {
if let ParagraphRecord::PageDef { page_def } = record {
return Some(page_def);
}
}
}
}
None
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/mod.rs | crates/hwp-core/src/viewer/markdown/document/mod.rs | /// Document-level markdown conversion
/// 문서 레벨의 마크다운 변환
///
/// HWP 문서의 각 부분(bodytext, docinfo, fileheader 등)을 마크다운으로 변환하는 모듈
/// Module for converting each part of HWP document (bodytext, docinfo, fileheader, etc.) to markdown
pub mod bodytext;
mod docinfo;
pub mod fileheader;
pub use bodytext::convert_bodytext_to_markdown;
pub use docinfo::extract_page_info;
pub use fileheader::format_version;
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/fileheader.rs | crates/hwp-core/src/viewer/markdown/document/fileheader.rs | /// FileHeader conversion to Markdown
/// 파일 헤더를 마크다운으로 변환하는 모듈
use crate::document::HwpDocument;
/// 버전 번호를 읽기 쉬운 문자열로 변환
/// Convert version number to readable string
pub fn format_version(document: &HwpDocument) -> String {
let version = document.file_header.version;
let major = (version >> 24) & 0xFF;
let minor = (version >> 16) & 0xFF;
let patch = (version >> 8) & 0xFF;
let build = version & 0xFF;
format!("{}.{:02}.{:02}.{:02}", major, minor, patch, build)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/bodytext/table.rs | crates/hwp-core/src/viewer/markdown/document/bodytext/table.rs | /// Table conversion to Markdown
/// 테이블을 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 57 - 본문의 데이터 레코드, TABLE (HWPTAG_BEGIN + 61)
/// Spec mapping: Table 57 - BodyText data records, TABLE (HWPTAG_BEGIN + 61)
use crate::document::{bodytext::Table, HwpDocument, ParagraphRecord};
/// Convert table to markdown format
/// 테이블을 마크다운 형식으로 변환
pub fn convert_table_to_markdown(
table: &Table,
document: &HwpDocument,
options: &crate::viewer::markdown::MarkdownOptions,
tracker: &mut crate::viewer::markdown::utils::OutlineNumberTracker,
) -> String {
let row_count = table.attributes.row_count as usize;
let col_count = table.attributes.col_count as usize;
if row_count == 0 || col_count == 0 {
return format!("\n\n[Table: {}x{}]\n\n", row_count, col_count);
}
// 셀이 비어있어도 표 형식으로 출력 / Output table format even if cells are empty
if table.cells.is_empty() {
// 빈 표 형식으로 출력 / Output empty table format
let mut lines = Vec::new();
lines.push(String::new());
let empty_row: Vec<String> = (0..col_count).map(|_| " ".to_string()).collect();
lines.push(format!("| {} |", empty_row.join(" | ")));
lines.push(format!(
"|{}|",
(0..col_count).map(|_| "---").collect::<Vec<_>>().join("|")
));
for _ in 1..row_count {
lines.push(format!("| {} |", empty_row.join(" | ")));
}
lines.push(String::new());
return lines.join("\n");
}
// 2D 배열로 셀 정렬 (행/열 위치 기준) / Arrange cells in 2D array (by row/column position)
// row_address와 col_address는 1부터 시작하므로 0-based 인덱스로 변환 필요
// row_address and col_address start from 1, so need to convert to 0-based index
let mut grid: Vec<Vec<Option<String>>> = vec![vec![None; col_count]; row_count];
// row_address와 col_address의 최소값 찾기 (일반적으로 1부터 시작하지만 확인 필요)
// Find minimum values of row_address and col_address (usually start from 1, but need to verify)
let min_row = table
.cells
.iter()
.map(|c| c.cell_attributes.row_address)
.min()
.unwrap_or(1);
let min_col = table
.cells
.iter()
.map(|c| c.cell_attributes.col_address)
.min()
.unwrap_or(1);
// row_address가 모두 같다면, 셀의 순서를 사용하여 행을 구분
// If all row_address values are the same, use cell order to distinguish rows
let all_same_row = table
.cells
.iter()
.all(|c| c.cell_attributes.row_address == min_row);
// 셀을 row_address, col_address 순서로 정렬 / Sort cells by row_address, then col_address
let mut sorted_cells: Vec<_> = table.cells.iter().enumerate().collect();
sorted_cells.sort_by_key(|(_, cell)| {
(
cell.cell_attributes.row_address,
cell.cell_attributes.col_address,
)
});
// row_address가 모두 같다면, 셀의 순서를 사용하여 행을 구분
// If all row_address are the same, use cell order to distinguish rows
if all_same_row {
// 셀을 원래 순서대로 처리하되, col_address가 0으로 돌아가면 새 행으로 간주
// Process cells in original order, but consider it a new row when col_address returns to 0
let mut row_index = 0;
let mut last_col = u16::MAX;
for (_original_idx, cell) in sorted_cells {
let col = (cell.cell_attributes.col_address.saturating_sub(min_col)) as usize;
// col_address가 이전보다 작거나 같으면 새 행으로 간주
// If col_address is less than or equal to previous, consider it a new row
if cell.cell_attributes.col_address <= last_col && last_col != u16::MAX {
row_index += 1;
if row_index >= row_count {
row_index = row_count - 1;
}
}
last_col = cell.cell_attributes.col_address;
let row = row_index;
if col < col_count {
fill_cell_content(
&mut grid, cell, row, col, row_count, col_count, document, options, tracker,
);
}
}
} else {
// row_address가 다르면 정상적으로 사용
// If row_address differ, use them normally
for cell in &table.cells {
let row = (cell.cell_attributes.row_address.saturating_sub(min_row)) as usize;
let col = (cell.cell_attributes.col_address.saturating_sub(min_col)) as usize;
if row < row_count && col < col_count {
fill_cell_content(
&mut grid, cell, row, col, row_count, col_count, document, options, tracker,
);
}
}
}
// 마크다운 표 형식으로 변환 / Convert to markdown table format
let mut lines = Vec::new();
lines.push(String::new()); // 빈 줄 추가 / Add empty line
// 모든 행을 순서대로 출력 / Output all rows in order
for row_idx in 0..row_count {
let row_data: Vec<String> = (0..col_count)
.map(|col| {
grid[row_idx][col]
.as_ref()
.map(|s| s.clone())
.unwrap_or_else(|| " ".to_string())
})
.collect();
lines.push(format!("| {} |", row_data.join(" | ")));
// 첫 번째 행 다음에 구분선 추가 / Add separator line after first row
if row_idx == 0 {
lines.push(format!(
"|{}|",
(0..col_count).map(|_| "---").collect::<Vec<_>>().join("|")
));
}
}
lines.push(String::new()); // 빈 줄 추가 / Add empty line
lines.join("\n")
}
/// Fill cell content and handle cell merging
/// 셀 내용을 채우고 셀 병합을 처리
fn fill_cell_content(
grid: &mut [Vec<Option<String>>],
cell: &crate::document::bodytext::TableCell,
row: usize,
col: usize,
row_count: usize,
col_count: usize,
document: &HwpDocument,
options: &crate::viewer::markdown::MarkdownOptions,
tracker: &mut crate::viewer::markdown::utils::OutlineNumberTracker,
) {
// 셀 내용을 텍스트와 이미지로 변환 / Convert cell content to text and images
let mut cell_parts = Vec::new();
let mut has_image = false;
// 먼저 이미지가 있는지 확인 / First check if image exists
for para in &cell.paragraphs {
for rec in ¶.records {
if matches!(rec, ParagraphRecord::ShapeComponentPicture { .. }) {
has_image = true;
break;
}
}
if has_image {
break;
}
}
// 셀 내부의 문단들을 마크다운으로 변환 / Convert paragraphs inside cell to markdown
for (idx, para) in cell.paragraphs.iter().enumerate() {
// 테이블 셀 내부에서는 PARA_BREAK를 직접 처리해야 함
// In table cells, we need to handle PARA_BREAK directly
// 문단 내의 모든 ParaText 레코드를 먼저 수집하여 함께 처리
// First collect all ParaText records in the paragraph to process together
let mut para_text_records = Vec::new();
let mut has_non_text_records = false;
for record in ¶.records {
match record {
ParagraphRecord::ParaText {
text,
control_char_positions,
..
} => {
para_text_records.push((text, control_char_positions));
}
_ => {
has_non_text_records = true;
}
}
}
// ParaText 레코드가 있으면 직접 처리 / If ParaText records exist, process directly
if !para_text_records.is_empty() {
let mut para_text_result = String::new();
for (text, control_char_positions) in para_text_records {
// PARA_BREAK나 LINE_BREAK를 직접 처리 / Handle PARA_BREAK or LINE_BREAK directly
let has_breaks = control_char_positions.iter().any(|pos| {
use crate::document::bodytext::ControlChar;
pos.code == ControlChar::PARA_BREAK || pos.code == ControlChar::LINE_BREAK
});
if !has_breaks {
// 제어 문자가 없으면 텍스트만 추가 / If no control characters, just add text
para_text_result.push_str(text);
continue;
}
let mut last_char_pos = 0;
// control_positions를 정렬하여 순서대로 처리 / Sort control_positions to process in order
let mut sorted_positions: Vec<_> = control_char_positions
.iter()
.filter(|pos| {
use crate::document::bodytext::ControlChar;
pos.code == ControlChar::PARA_BREAK || pos.code == ControlChar::LINE_BREAK
})
.collect();
sorted_positions.sort_by_key(|pos| pos.position);
for pos in sorted_positions {
// position은 문자 인덱스이므로, 그 위치까지의 텍스트를 문자 단위로 추가
// position is character index, so add text up to that position by character
let text_len = text.chars().count();
if pos.position > last_char_pos && pos.position <= text_len {
// 문자 단위로 텍스트 추출 / Extract text by character
let text_before: String = text
.chars()
.skip(last_char_pos)
.take(pos.position - last_char_pos)
.collect();
// trim() 없이 그대로 추가 (정확한 위치 유지) / Add as-is without trim (maintain exact position)
para_text_result.push_str(&text_before);
}
// PARA_BREAK나 LINE_BREAK 위치에 <br> 추가 / Add <br> at PARA_BREAK or LINE_BREAK position
if options.use_html == Some(true) {
para_text_result.push_str("<br>");
} else {
para_text_result.push(' ');
}
// 제어 문자 다음 위치 / Position after control character
// position이 텍스트 끝이면 더 이상 텍스트가 없으므로 text_len으로 설정
// If position is at end of text, set to text_len as there's no more text
last_char_pos = if pos.position >= text_len {
text_len
} else {
pos.position + 1
};
}
// 마지막 부분의 텍스트 추가 (last_char_pos가 텍스트 길이보다 작을 때만)
// Add remaining text (only if last_char_pos is less than text length)
let text_len = text.chars().count();
if last_char_pos < text_len {
let text_after: String = text.chars().skip(last_char_pos).collect();
// trim() 없이 그대로 추가 / Add as-is without trim
para_text_result.push_str(&text_after);
}
}
if !para_text_result.trim().is_empty() {
cell_parts.push(para_text_result);
}
}
// ParaText가 아닌 레코드(이미지 등)가 있으면 직접 처리
// Process non-ParaText records (images, etc.) directly if they exist
if has_non_text_records {
for record in ¶.records {
match record {
ParagraphRecord::ParaText { .. } => {
// ParaText는 이미 처리했으므로 건너뜀 / Skip ParaText as it's already processed
continue;
}
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
// ShapeComponentPicture 변환 / Convert ShapeComponentPicture
if let Some(image_md) =
crate::viewer::markdown::document::bodytext::shape_component_picture::convert_shape_component_picture_to_markdown(
shape_component_picture,
document,
options.image_output_dir.as_deref(),
)
{
cell_parts.push(image_md);
has_image = true;
}
}
ParagraphRecord::ShapeComponent {
shape_component: _,
children,
} => {
// SHAPE_COMPONENT의 children을 재귀적으로 처리 / Recursively process SHAPE_COMPONENT's children
let shape_parts =
crate::viewer::markdown::document::bodytext::shape_component::convert_shape_component_children_to_markdown(
children,
document,
options.image_output_dir.as_deref(),
tracker,
);
for shape_part in shape_parts {
if shape_part.contains("![이미지]") {
has_image = true;
}
cell_parts.push(shape_part);
}
}
_ => {
// 기타 레코드는 서식 정보이므로 건너뜀 / Other records are formatting info, skip
}
}
}
}
// 마지막 문단이 아니면 문단 사이 공백 추가
// If not last paragraph, add space between paragraphs
if idx < cell.paragraphs.len() - 1 {
cell_parts.push(" ".to_string());
}
}
// 셀 내용을 하나의 문자열로 결합 / Combine cell parts into a single string
// 표 셀 내부에서는 개행을 공백으로 변환 (마크다운 표는 한 줄로 표시)
// In table cells, convert line breaks to spaces (markdown tables are displayed in one line)
let cell_text = cell_parts.join("");
// 마크다운 표에서 파이프 문자 이스케이프 처리 / Escape pipe characters in markdown table
let cell_content = if cell_text.is_empty() {
" ".to_string() // 빈 셀은 공백으로 표시 / Empty cell shows as space
} else {
cell_text.replace('|', "\\|") // 파이프 문자 이스케이프 / Escape pipe character
};
// 셀에 이미 내용이 있으면 덮어쓰지 않음 (병합 셀 처리)
// Don't overwrite if cell already has content (handle merged cells)
if grid[row][col].is_none() {
grid[row][col] = Some(cell_content);
// 셀 병합 처리: col_span과 row_span에 따라 병합된 셀을 빈 셀로 채움
// Handle cell merging: fill merged cells with empty cells based on col_span and row_span
let col_span = cell.cell_attributes.col_span as usize;
let row_span = cell.cell_attributes.row_span as usize;
// 병합된 열을 빈 셀로 채움 (마크다운에서는 병합을 직접 표현할 수 없으므로 빈 셀로 처리)
// Fill merged columns with empty cells (markdown doesn't support cell merging directly)
for c in (col + 1)..(col + col_span).min(col_count) {
if grid[row][c].is_none() {
grid[row][c] = Some(" ".to_string());
}
}
// 병합된 행을 빈 셀로 채움
// Fill merged rows with empty cells
for r in (row + 1)..(row + row_span).min(row_count) {
for c in col..(col + col_span).min(col_count) {
if grid[r][c].is_none() {
grid[r][c] = Some(" ".to_string());
}
}
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/bodytext/shape_component_picture.rs | crates/hwp-core/src/viewer/markdown/document/bodytext/shape_component_picture.rs | /// ShapeComponentPicture conversion to Markdown
/// ShapeComponentPicture를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 57 - 본문의 데이터 레코드, SHAPE_COMPONENT_PICTURE
/// Spec mapping: Table 57 - BodyText data records, SHAPE_COMPONENT_PICTURE
use crate::document::{bodytext::ShapeComponentPicture, HwpDocument};
use crate::viewer::markdown::common::format_image_markdown;
/// Convert ShapeComponentPicture to markdown
/// ShapeComponentPicture를 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `shape_component_picture` - 그림 개체 / Picture shape component
/// * `document` - HWP 문서 / HWP document
/// * `image_output_dir` - 이미지 출력 디렉토리 (선택) / Image output directory (optional)
///
/// # Returns / 반환값
/// 마크다운 문자열 / Markdown string
pub(crate) fn convert_shape_component_picture_to_markdown(
shape_component_picture: &ShapeComponentPicture,
document: &HwpDocument,
image_output_dir: Option<&str>,
) -> Option<String> {
// 그림 개체를 마크다운 이미지로 변환 / Convert picture shape component to markdown image
let bindata_id = shape_component_picture.picture_info.bindata_id;
// BinData에서 해당 이미지 찾기 / Find image in BinData
if let Some(bin_item) = document
.bin_data
.items
.iter()
.find(|item| item.index == bindata_id)
{
let image_markdown =
format_image_markdown(document, bindata_id, &bin_item.data, image_output_dir);
if !image_markdown.is_empty() {
return Some(image_markdown);
}
}
None
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/bodytext/mod.rs | crates/hwp-core/src/viewer/markdown/document/bodytext/mod.rs | /// BodyText conversion to Markdown
/// 본문 텍스트를 마크다운으로 변환하는 모듈
///
/// HWP 문서의 본문 텍스트(bodytext) 관련 레코드들을 마크다운으로 변환하는 모듈
/// Module for converting BodyText-related records in HWP documents to markdown
mod list_header;
mod para_text;
pub mod paragraph;
mod shape_component;
pub mod shape_component_picture;
pub mod table;
use crate::document::{ColumnDivideType, HwpDocument, ParagraphRecord};
use crate::viewer::markdown::MarkdownOptions;
pub use paragraph::convert_paragraph_to_markdown;
pub use table::convert_table_to_markdown;
/// Convert body text to markdown
/// 본문 텍스트를 마크다운으로 변환
pub fn convert_bodytext_to_markdown(
document: &HwpDocument,
options: &MarkdownOptions,
) -> (
Vec<String>, // headers
Vec<String>, // body_lines
Vec<String>, // footers
Vec<String>, // footnotes
Vec<String>, // endnotes
) {
// 머리말, 본문, 꼬리말, 각주, 미주를 분리하여 수집 / Collect headers, body, footers, footnotes, and endnotes separately
let mut headers = Vec::new();
let mut body_lines = Vec::new();
let mut footers = Vec::new();
let mut footnotes = Vec::new();
let mut endnotes = Vec::new();
// 개요 번호 추적기 생성 / Create outline number tracker
let mut outline_tracker = crate::viewer::markdown::utils::OutlineNumberTracker::new();
// Convert body text to markdown / 본문 텍스트를 마크다운으로 변환
for section in &document.body_text.sections {
for paragraph in §ion.paragraphs {
// control_mask를 사용하여 빠른 필터링 (최적화) / Use control_mask for quick filtering (optimization)
let control_mask = ¶graph.para_header.control_mask;
// control_mask로 머리말/꼬리말/각주/미주가 있는지 빠르게 확인 / Quickly check if header/footer/footnote/endnote exists using control_mask
// 주의: control_mask는 머리말/꼬리말을 구분하지 못하고, 각주/미주도 구분하지 못함
// Note: control_mask cannot distinguish header/footer or footnote/endnote
let has_header_footer = control_mask.has_header_footer();
let has_footnote_endnote = control_mask.has_footnote_endnote();
// 머리말/꼬리말/각주/미주 컨트롤 처리 / Process header/footer/footnote/endnote controls
// 하나의 문단에 여러 개의 컨트롤이 있을 수 있으므로 break 없이 모두 처리
// Multiple controls can exist in one paragraph, so process all without break
// control_mask로 필터링하여 불필요한 순회 방지 / Filter with control_mask to avoid unnecessary iteration
if has_header_footer || has_footnote_endnote {
for record in ¶graph.records {
if let ParagraphRecord::CtrlHeader {
header,
children,
paragraphs: ctrl_paragraphs,
} = record
{
use crate::document::CtrlId;
if header.ctrl_id.as_str() == CtrlId::HEADER {
// 머리말 문단 처리 / Process header paragraph
// 파서에서 이미 ParaText를 제거하고, LIST_HEADER가 있으면 paragraphs는 비어있음
// Parser already removed ParaText, and if LIST_HEADER exists, paragraphs is empty
// LIST_HEADER가 있으면 children에서 처리, 없으면 paragraphs에서 처리
// If LIST_HEADER exists, process from children, otherwise from paragraphs
let mut found_list_header = false;
for child_record in children {
if let ParagraphRecord::ListHeader { paragraphs, .. } = child_record
{
found_list_header = true;
// LIST_HEADER 내부의 문단 처리 / Process paragraphs inside LIST_HEADER
for para in paragraphs {
let para_md = paragraph::convert_paragraph_to_markdown(
para,
document,
options,
&mut outline_tracker,
);
if !para_md.is_empty() {
headers.push(para_md);
}
}
}
}
// LIST_HEADER가 없으면 paragraphs 처리 (각주/미주 등)
// If no LIST_HEADER, process paragraphs (for footnotes/endnotes, etc.)
if !found_list_header {
for para in ctrl_paragraphs {
let para_md = paragraph::convert_paragraph_to_markdown(
para,
document,
options,
&mut outline_tracker,
);
if !para_md.is_empty() {
headers.push(para_md);
}
}
}
} else if header.ctrl_id.as_str() == CtrlId::FOOTER {
// 꼬리말 문단 처리 / Process footer paragraph
// 파서에서 이미 ParaText를 제거하고, LIST_HEADER가 있으면 paragraphs는 비어있음
// Parser already removed ParaText, and if LIST_HEADER exists, paragraphs is empty
// LIST_HEADER가 있으면 children에서 처리, 없으면 paragraphs에서 처리
// If LIST_HEADER exists, process from children, otherwise from paragraphs
let mut found_list_header = false;
for child_record in children {
if let ParagraphRecord::ListHeader { paragraphs, .. } = child_record
{
found_list_header = true;
// LIST_HEADER 내부의 문단 처리 / Process paragraphs inside LIST_HEADER
for para in paragraphs {
let para_md = paragraph::convert_paragraph_to_markdown(
para,
document,
options,
&mut outline_tracker,
);
if !para_md.is_empty() {
footers.push(para_md);
}
}
}
}
// LIST_HEADER가 없으면 paragraphs 처리 (각주/미주 등)
// If no LIST_HEADER, process paragraphs (for footnotes/endnotes, etc.)
if !found_list_header {
for para in ctrl_paragraphs {
let para_md = paragraph::convert_paragraph_to_markdown(
para,
document,
options,
&mut outline_tracker,
);
if !para_md.is_empty() {
footers.push(para_md);
}
}
}
} else if header.ctrl_id.as_str() == CtrlId::FOOTNOTE {
// 각주 문단 처리 / Process footnote paragraph
// hwplib 방식: LIST_HEADER는 문단 리스트 헤더 정보만 포함하고,
// 실제 텍스트는 ParagraphList(paragraphs)에 있음
// hwplib approach: LIST_HEADER only contains paragraph list header info,
// actual text is in ParagraphList (paragraphs)
for para in ctrl_paragraphs {
let para_md = paragraph::convert_paragraph_to_markdown(
para,
document,
options,
&mut outline_tracker,
);
if !para_md.is_empty() {
footnotes.push(para_md);
}
}
// LIST_HEADER는 건너뜀 (자동 번호 템플릿, 실제 텍스트 아님)
// Skip LIST_HEADER (auto-number template, not actual text)
} else if header.ctrl_id.as_str() == CtrlId::ENDNOTE {
// 미주 문단 처리 / Process endnote paragraph
// hwplib 방식: LIST_HEADER는 문단 리스트 헤더 정보만 포함하고,
// 실제 텍스트는 ParagraphList(paragraphs)에 있음
// hwplib approach: LIST_HEADER only contains paragraph list header info,
// actual text is in ParagraphList (paragraphs)
for para in ctrl_paragraphs {
let para_md = paragraph::convert_paragraph_to_markdown(
para,
document,
options,
&mut outline_tracker,
);
if !para_md.is_empty() {
endnotes.push(para_md);
}
}
// LIST_HEADER는 건너뜀 (자동 번호 템플릿, 실제 텍스트 아님)
// Skip LIST_HEADER (auto-number template, not actual text)
}
}
}
}
// 일반 본문 문단 처리 (컨트롤이 없는 경우) / Process regular body paragraph (when no controls)
// control_mask로 일반 문단인지 확인 / Check if regular paragraph using control_mask
if !has_header_footer && !has_footnote_endnote {
// 일반 본문 문단 처리 / Process regular body paragraph
// Check if we need to add page break / 페이지 나누기가 필요한지 확인
let has_page_break = paragraph
.para_header
.column_divide_type
.iter()
.any(|t| matches!(t, ColumnDivideType::Page | ColumnDivideType::Section));
if has_page_break && !body_lines.is_empty() {
// Only add page break if we have content before / 이전에 내용이 있을 때만 페이지 구분선 추가
let last_line = body_lines.last().map(String::as_str).unwrap_or("");
if !last_line.is_empty() && last_line != "---" {
body_lines.push("---".to_string());
body_lines.push(String::new());
}
}
// Convert paragraph to markdown (includes text and controls) / 문단을 마크다운으로 변환 (텍스트와 컨트롤 포함)
let markdown = paragraph::convert_paragraph_to_markdown(
paragraph,
document,
options,
&mut outline_tracker,
);
if !markdown.is_empty() {
body_lines.push(markdown);
}
}
}
}
(headers, body_lines, footers, footnotes, endnotes)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/bodytext/shape_component.rs | crates/hwp-core/src/viewer/markdown/document/bodytext/shape_component.rs | /// ShapeComponent conversion to Markdown
/// ShapeComponent를 마크다운으로 변환하는 모듈
///
/// 스펙 문서 매핑: 표 57 - 본문의 데이터 레코드, SHAPE_COMPONENT (HWPTAG_BEGIN + 60)
/// Spec mapping: Table 57 - BodyText data records, SHAPE_COMPONENT (HWPTAG_BEGIN + 60)
use crate::document::{HwpDocument, ParagraphRecord};
use crate::viewer::markdown::document::bodytext::shape_component_picture::convert_shape_component_picture_to_markdown;
/// Convert ShapeComponent children to markdown
/// ShapeComponent의 자식들을 마크다운으로 변환
///
/// # Arguments / 매개변수
/// * `children` - ShapeComponent의 자식 레코드들 / Child records of ShapeComponent
/// * `document` - HWP 문서 / HWP document
/// * `image_output_dir` - 이미지 출력 디렉토리 (선택) / Image output directory (optional)
/// * `tracker` - 개요 번호 추적기 / Outline number tracker
///
/// # Returns / 반환값
/// 마크다운 문자열 리스트 / List of markdown strings
pub(crate) fn convert_shape_component_children_to_markdown(
children: &[ParagraphRecord],
document: &HwpDocument,
image_output_dir: Option<&str>,
tracker: &mut crate::viewer::markdown::utils::OutlineNumberTracker,
) -> Vec<String> {
use crate::viewer::markdown::document::bodytext::paragraph::convert_paragraph_to_markdown;
use crate::viewer::markdown::MarkdownOptions;
let mut parts = Vec::new();
let options = MarkdownOptions {
image_output_dir: image_output_dir.map(|s| s.to_string()),
use_html: None,
include_version: None,
include_page_info: None,
};
// SHAPE_COMPONENT의 children을 재귀적으로 처리 / Recursively process SHAPE_COMPONENT's children
// SHAPE_COMPONENT_PICTURE는 SHAPE_COMPONENT의 자식으로 올 수 있음
// SHAPE_COMPONENT_PICTURE can be a child of SHAPE_COMPONENT
// LIST_HEADER는 글상자 텍스트를 포함할 수 있음 (SHAPE_COMPONENT 내부의 글상자)
// LIST_HEADER can contain textbox text (textbox inside SHAPE_COMPONENT)
for child in children {
match child {
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
// 그림 개체를 마크다운 이미지로 변환 / Convert picture shape component to markdown image
if let Some(image_md) = convert_shape_component_picture_to_markdown(
shape_component_picture,
document,
image_output_dir,
) {
parts.push(image_md);
}
}
ParagraphRecord::ListHeader { paragraphs, .. } => {
// LIST_HEADER의 paragraphs 처리 (글상자 텍스트) / Process LIST_HEADER's paragraphs (textbox text)
// SHAPE_COMPONENT 내부의 LIST_HEADER는 글상자 텍스트를 포함할 수 있음
// LIST_HEADER inside SHAPE_COMPONENT can contain textbox text
for para in paragraphs {
let para_md = convert_paragraph_to_markdown(para, document, &options, tracker);
if !para_md.is_empty() {
parts.push(para_md);
}
}
}
_ => {
// 기타 children은 무시 / Ignore other children
}
}
}
parts
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.