pub mod gldf;
pub use gldf::*;
pub mod editable;
pub use editable::{EditableGldf, EditableGldfStats};
pub mod fix;
pub use fix::fix_legacy_content_types;
pub mod validation;
pub use validation::{ValidationError, ValidationLevel, ValidationResult};
pub mod dialux_compat;
pub mod operations;
pub mod mapping;
pub use mapping::{
get_first_l3d_with_ldt, get_l3d_files_with_ldt, get_l3d_ldt_mappings, get_variant_emitter_data,
EmitterRenderData, L3dLdtMapping, L3dWithLdt, MountingInfo, MountingType, VariantEmitterData,
};
#[cfg(feature = "eulumdat")]
pub mod convert;
#[cfg(feature = "eulumdat")]
pub use convert::{ldt_metadata, ldt_metadata_to_gldf, ldt_to_gldf, tm33_to_gldf, LdtMetadata};
#[cfg(feature = "eulumdat")]
pub mod photometry;
#[cfg(feature = "eulumdat")]
pub use photometry::{
export_photometry, patch_ldt_for_variant, patch_photometry_for_variant,
resolve_variant_photometries, PhotometryExportFormat, VariantPhotometryResolution,
};
pub mod export;
pub mod ifc;
pub use ifc::{
ifc_to_gldf,
import_ifc,
GldfGenerator,
GldfToIfc,
IfcImporter,
ImportedLightSource,
ImportedLuminaire,
ImportedProperties,
ImportedVariant,
LightEmissionSourceEnum,
LightFixtureTypeEnum,
StepWriter,
};
pub mod plugin;
pub use plugin::{Plugin, PluginManager, PluginManifest};
pub mod ral;
pub mod i18n;
#[cfg(feature = "l3d")]
pub mod l3d_mtl_sync;
#[cfg(feature = "l3d")]
pub mod l3d_leo;
#[cfg(feature = "l3d")]
pub use l3d_leo::{extract_leos, LeoFootprint, LeoShape};
#[cfg(test)]
mod tests;
use anyhow::{Context, Result};
use regex::Regex;
use serde_json::from_str as serde_from_str;
use std::fs::File as StdFile;
use std::io::{Read, Write};
use std::path::Path;
use std::path::PathBuf;
use zip::ZipArchive;
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum GldfSchemaVersion {
Rc3,
#[default]
Rc4,
}
fn downconvert_rc4_to_rc3(xml: &str) -> String {
xml
.replace(
"RatedChromaticityCoordinateValues",
"RatedChromacityCoordinateValues",
)
.replace("Fluorescent Triphosphor", "Flourescent Triphosphor")
.replace("Fluorescent Halophosphate", "Flourescent Halophosphate")
}
impl GldfProduct {
pub fn detach(&mut self) -> anyhow::Result<()> {
Ok(())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct BufFile {
pub name: Option<String>,
pub content: Option<Vec<u8>>,
pub file_id: Option<String>,
pub path: Option<String>,
}
pub struct FileBufGldf {
pub files: Vec<BufFile>,
pub gldf: GldfProduct,
}
impl GldfProduct {
pub fn load_gldf_file_str(&self, path: String) -> anyhow::Result<String> {
let zipfile = StdFile::open(Path::new(&self.path))?;
let mut zip = ZipArchive::new(zipfile)?;
let mut some_str = String::new();
let mut some_file = zip.by_name(&path)?;
some_file.read_to_string(&mut some_str)?;
Ok(some_str)
}
pub fn load_gldf_file(&self, path: String) -> anyhow::Result<Vec<u8>> {
let zipfile = StdFile::open(Path::new(&self.path))?;
let mut zip = ZipArchive::new(zipfile)?;
let mut file_buf = Vec::new();
let mut some_file = zip.by_name(&path)?;
some_file.read_to_end(&mut file_buf)?;
Ok(file_buf)
}
pub fn get_xml_str_from_gldf(path: PathBuf) -> anyhow::Result<String> {
let zipfile = StdFile::open(path)?;
let mut zip = ZipArchive::new(zipfile)?;
let mut xmlfile = zip.by_name("product.xml")?;
let mut xml_str = String::new();
xmlfile.read_to_string(&mut xml_str)?;
Ok(xml_str)
}
pub fn remove_bom(s: &str) -> String {
if let Some(stripped) = s.strip_prefix("\u{FEFF}") {
stripped.to_string()
} else {
s.to_string()
}
}
pub fn sanitize_xml_str(xml_str: &str) -> String {
let cleaned_str = Self::remove_bom(xml_str);
let re = Regex::new(r"<Root .*?>").unwrap();
let cleaned = re.replace_all(&cleaned_str, "<Root>").to_string();
cleaned
.replace("Flourescent Triphosphor", "Fluorescent Triphosphor")
.replace("Flourescent Halophosphate", "Fluorescent Halophosphate")
}
pub fn from_xml(xml_str: &str) -> anyhow::Result<GldfProduct> {
let my_xml_str = Self::sanitize_xml_str(xml_str);
let result: GldfProduct = quick_xml::de::from_str(&my_xml_str)
.map_err(|e| anyhow::anyhow!("XML parsing error: {}", e))?;
Ok(result)
}
pub fn load_gldf(path: &str) -> anyhow::Result<GldfProduct> {
let path_buf = Path::new(path).to_path_buf();
let xml_str = GldfProduct::get_xml_str_from_gldf(path_buf)
.map_err(anyhow::Error::msg)
.context("Failed to parse XML string")?;
let mut loaded: GldfProduct = GldfProduct::from_xml(&xml_str)?;
loaded.path = path.to_string();
Ok(loaded)
}
pub fn load_gldf_from_buf_all(gldf_buf: Vec<u8>) -> anyhow::Result<FileBufGldf> {
let zip_buf = std::io::Cursor::new(gldf_buf);
let mut zip = ZipArchive::new(zip_buf).context("Failed to open GLDF as ZIP archive")?;
let mut file_bufs: Vec<BufFile> = Vec::new();
let mut xmlfile = zip
.by_name("product.xml")
.context("product.xml not found in GLDF archive")?;
let mut xml_str = String::new();
xmlfile
.read_to_string(&mut xml_str)
.context("Failed to read product.xml")?;
let loaded: GldfProduct =
GldfProduct::from_xml(&xml_str).context("Failed to parse product.xml")?;
drop(xmlfile);
let mut path_to_file_id: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for file_def in &loaded.general_definitions.files.file {
if file_def.type_attr == "url" {
continue;
}
let zip_path = crate::editable::EditableGldf::get_zip_path_for_file(
&file_def.content_type,
&file_def.file_name,
);
path_to_file_id.insert(zip_path, file_def.id.clone());
}
for i in 0..zip.len() {
if let Ok(mut file) = zip.by_index(i) {
if file.is_file() {
let mut buf: Vec<u8> = Vec::new();
let zip_name = file.name().to_string();
if file.read_to_end(&mut buf).is_ok() {
let file_id = path_to_file_id.get(&zip_name).cloned();
let buf_file = BufFile {
name: Some(zip_name.clone()),
content: Some(buf),
file_id,
path: Some(zip_name),
};
file_bufs.push(buf_file);
}
}
}
}
let file_buf = FileBufGldf {
files: file_bufs,
gldf: loaded,
};
Ok(file_buf)
}
pub fn load_gldf_from_buf(file_buf: Vec<u8>) -> anyhow::Result<GldfProduct> {
let zip_buf = std::io::Cursor::new(file_buf);
let mut zip = ZipArchive::new(zip_buf).context("Failed to open GLDF as ZIP archive")?;
let mut xmlfile = zip
.by_name("product.xml")
.context("product.xml not found in GLDF archive")?;
let mut xml_str = String::new();
xmlfile
.read_to_string(&mut xml_str)
.context("Failed to read product.xml")?;
let loaded: GldfProduct =
GldfProduct::from_xml(&xml_str).context("Failed to parse product.xml")?;
Ok(loaded)
}
pub fn to_buf(&self) -> anyhow::Result<Vec<u8>> {
if self.path.is_empty() {
return Err(anyhow::anyhow!(
"to_buf requires a path-loaded GldfProduct (load_gldf), \
not a buffer-loaded one; nowhere to source the LDC/image \
entries from"
));
}
let source = StdFile::open(&self.path)
.with_context(|| format!("open source gldf: {}", self.path))?;
let mut src_zip = ZipArchive::new(source)
.with_context(|| format!("open source gldf as zip: {}", self.path))?;
let schema = match self.header.format_version.pre_release {
Some(3) => GldfSchemaVersion::Rc3,
_ => GldfSchemaVersion::Rc4,
};
let xml_str = self
.to_xml_with_schema(schema)
.context("serialize patched product.xml")?;
let mut out_buf: Vec<u8> = Vec::with_capacity(
std::fs::metadata(&self.path)
.map(|m| m.len() as usize)
.unwrap_or(0)
.max(8 * 1024),
);
{
let cursor = std::io::Cursor::new(&mut out_buf);
let mut writer = zip::ZipWriter::new(cursor);
for i in 0..src_zip.len() {
let entry = src_zip
.by_index(i)
.with_context(|| format!("read source zip entry {i}"))?;
if entry.name() == "product.xml" {
continue;
}
writer
.raw_copy_file(entry)
.context("raw-copy zip entry to output")?;
}
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated);
writer
.start_file("product.xml", opts)
.context("start product.xml entry")?;
writer
.write_all(xml_str.as_bytes())
.context("write patched product.xml bytes")?;
writer.finish().context("finish zip writer")?;
}
Ok(out_buf)
}
pub fn save_gldf(&self, path: &str) -> anyhow::Result<()> {
let buf = self.to_buf()?;
let dest = Path::new(path);
let parent = dest.parent().unwrap_or_else(|| Path::new("."));
let tmp_name = format!(
"{}.tmp.{}",
dest.file_name().and_then(|n| n.to_str()).unwrap_or("gldf"),
std::process::id()
);
let tmp = parent.join(tmp_name);
std::fs::write(&tmp, &buf)
.with_context(|| format!("write temp gldf: {}", tmp.display()))?;
std::fs::rename(&tmp, dest)
.with_context(|| format!("rename {} -> {}", tmp.display(), dest.display()))?;
Ok(())
}
pub fn to_json(&self) -> anyhow::Result<String> {
let json_str = serde_json::to_string(&self)?;
Ok(json_str)
}
pub fn to_pretty_json(&self) -> anyhow::Result<String> {
let json_str =
serde_json::to_string_pretty(&self).context("Failed to serialize to JSON")?;
Ok(json_str)
}
pub fn from_json(json_str: &str) -> anyhow::Result<GldfProduct> {
let j_loaded: GldfProduct = serde_from_str(json_str)?;
Ok(j_loaded)
}
pub fn from_json_file(path: PathBuf) -> anyhow::Result<GldfProduct> {
let mut json_file = StdFile::open(&path)
.with_context(|| format!("Failed to open JSON file: {:?}", path))?;
let mut json_str = String::new();
json_file
.read_to_string(&mut json_str)
.context("Failed to read JSON file")?;
GldfProduct::from_json(&json_str).context("Failed to parse JSON content")
}
pub fn to_xml(&self) -> anyhow::Result<String> {
self.to_xml_with_schema(GldfSchemaVersion::Rc4)
}
pub fn to_xml_with_schema(&self, version: GldfSchemaVersion) -> anyhow::Result<String> {
let xml_str = quick_xml::se::to_string(&self)?;
let xml_str = match version {
GldfSchemaVersion::Rc4 => xml_str,
GldfSchemaVersion::Rc3 => downconvert_rc4_to_rc3(&xml_str),
};
Ok(format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}",
xml_str
))
}
pub fn get_phot_files(&self) -> anyhow::Result<Vec<&File>> {
let mut result: Vec<&File> = Vec::new();
for f in self.general_definitions.files.file.iter() {
let content_type = &f.content_type;
if content_type.starts_with("ldc") {
result.push(f)
}
}
Ok(result.to_owned())
}
pub fn get_image_def_files(&self) -> Result<Vec<&File>> {
let mut result: Vec<&File> = Vec::new();
for f in self.general_definitions.files.file.iter() {
let content_type = &f.content_type;
if content_type.starts_with("image") {
result.push(f)
}
}
Ok(result.to_owned())
}
pub fn get_image_zip_files(&self) -> anyhow::Result<Vec<&File>> {
let mut result: Vec<&File> = Vec::new();
for f in self.general_definitions.files.file.iter() {
let content_type = &f.content_type;
if content_type.starts_with("image") {
result.push(f)
}
}
Ok(result.to_owned())
}
#[cfg(feature = "http")]
pub async fn get_ldc_by_id(&self, file_id: String) -> Result<String, anyhow::Error> {
let mut result: String = "".to_owned();
for f in self.general_definitions.files.file.iter() {
if f.id == file_id {
let mut ldc_path = "ldc/".to_owned();
let file_name = f.file_name.to_owned();
if f.type_attr == "url" {
let tmp = fetch_text_from_url(&file_name).await?;
result.push_str(tmp.as_str());
} else {
ldc_path.push_str(&file_name);
result.push_str(&self.load_gldf_file_str(ldc_path)?);
}
}
}
Ok(result)
}
#[cfg(not(feature = "http"))]
pub fn get_ldc_by_id(&self, file_id: String) -> Result<String, anyhow::Error> {
let mut result: String = "".to_owned();
for f in self.general_definitions.files.file.iter() {
if f.id == file_id {
if f.type_attr == "url" {
return Err(anyhow::anyhow!(
"URL file type not supported without http feature"
));
}
let mut ldc_path = "ldc/".to_owned();
ldc_path.push_str(&f.file_name);
result.push_str(&self.load_gldf_file_str(ldc_path)?);
}
}
Ok(result)
}
pub fn get_all_file_definitions(&self) -> anyhow::Result<Vec<File>> {
let mut result: Vec<File> = Vec::new();
for f in self.general_definitions.files.file.iter() {
result.push(f.to_owned());
}
Ok(result)
}
pub fn get_url_file_definitions(&self) -> anyhow::Result<Vec<File>> {
let mut result: Vec<File> = Vec::new();
for f in self.general_definitions.files.file.iter() {
if f.content_type == "url" {
result.push(f.to_owned());
}
}
Ok(result)
}
}
#[cfg(feature = "http")]
pub async fn fetch_text_from_url(url: &str) -> Result<String, reqwest::Error> {
let response = reqwest::get(url).await?;
let text = response.text().await?;
Ok(text)
}
#[cfg(feature = "http")]
pub async fn fetch_content_from_url(url: &str) -> Result<Vec<u8>, reqwest::Error> {
let response = reqwest::get(url).await?;
let content = response.bytes().await?;
Ok(content.to_vec())
}