"""Convert VRML files to X3D and HTML using X3DOM.
It includes utilities for parsing VRML, updating color spaces, managing
resources, and handling 3D transformations. The module also supports caching
and embedding resources for efficient processing.
"""
from __future__ import annotations
import http.client
import os
import re
import string
import urllib.error
import urllib.parse
import urllib.request
from typing import TYPE_CHECKING
from DisplayCAL import colormath
from DisplayCAL import localization as lang
from DisplayCAL.config import get_data_path
from DisplayCAL.defaultpaths import CACHE as CACHEPATH
from DisplayCAL.log import safe_print as _safe_print
from DisplayCAL.meta import DOMAIN
from DisplayCAL.options import DEBUG
from DisplayCAL.util_io import GzipFileProper
from DisplayCAL.util_str import StrList, create_replace_function
if TYPE_CHECKING:
from DisplayCAL.worker import Worker
class VRMLParseError(Exception):
"""Exception raised for errors in the VRML parsing process."""
class Tag:
"""X3D Tag.
Args:
tagname (str): The name of the tag.
**attributes: Optional attributes for the tag.
"""
def __init__(self, tagname: str, **attributes) -> None:
self.parent = None
self.tagname = tagname
self.children = []
self.attributes = attributes
def __str__(self) -> str:
"""Return a string representation of the tag."""
return self.markup()
def markup(self, allow_empty_element_tag: bool = False, x3dom: bool = False) -> str:
"""Return the X3D markup for this tag.
Args:
allow_empty_element_tag (bool): If True, allows the tag to be
self-closing. Defaults to False.
x3dom (bool): If True, generates X3DOM compatible markup.
Defaults to False.
Returns:
str: The X3D markup for this tag.
"""
markup = [f"<{self.tagname}"]
attrs = []
for key in self.attributes:
value = self.attributes[key]
value = (
value.strip()
.replace("<", "<")
.replace(">", ">")
.replace("&", "&")
.replace("'", "'")
)
if value in ("FALSE", "TRUE"):
value = value.lower()
attrs.append(f"{key}='{value}'")
if attrs:
markup.append(" " + " ".join(attrs))
if not allow_empty_element_tag:
markup.append(">")
if self.children:
if allow_empty_element_tag:
markup.append(">")
markup.append("\n")
for child in self.children:
markup.extend(
f"\t{line}\n"
for line in child.markup(
allow_empty_element_tag, x3dom
).splitlines()
)
if not allow_empty_element_tag or self.children:
# Not XML, or XML with children
markup.append(f"{self.tagname}>\n")
else:
# XML, no children
markup.append("/>")
if (
self.tagname == "Material"
and float(self.attributes.get("transparency", "0").strip())
not in (0.0, 1.0)
and x3dom
):
# Fix z-fighting in X3DOM renderer
markup.append("")
return "".join(markup)
def append_child(self, child: Tag) -> None:
"""Append a child tag to this tag.
Args:
child (Tag): The child tag to append.
"""
child.parent = self
self.children.append(child)
@classmethod
def ensure_cache_directory(cls, cache_dir: str) -> None:
"""Ensure the cache directory exists.
Args:
cache_dir (str): The path to the cache directory.
"""
if not os.path.isdir(cache_dir):
_safe_print("Creating cache directory:", cache_dir)
os.makedirs(cache_dir)
@classmethod
def get_resource_from_cache(cls, force: bool, cachefilename: str) -> str:
"""Get resource from cache if available.
Args:
force (bool): If True, forces re-download of the resource.
cachefilename (str): The path to the cached file.
Returns:
str: The content of the cached file if it exists, otherwise an
empty string.
"""
body = ""
if not force and os.path.isfile(cachefilename):
_safe_print("Using cached file:", cachefilename)
with open(cachefilename, "rb") as cachefile:
body = cachefile.read()
return body
@classmethod
def request_url_content(cls, url: str) -> bytes:
"""Request content from a URL.
Args:
url (str): The URL to fetch content from.
Returns:
bytes: The content of the URL if successful, otherwise an empty
byte string.
"""
body = b""
for url_ in [url, url.replace("https://", "http://")]:
_safe_print("Requesting:", url_)
try:
response = urllib.request.urlopen(url_) # noqa: S310
except (
OSError,
urllib.error.URLError,
http.client.HTTPException,
) as exception:
_safe_print(exception)
else:
body = response.read()
response.close()
break
return body
@classmethod
def get_local_resources(cls, basename: str) -> None | bytes:
"""Get local resources.
Args:
basename (str): The name of the resource file to fetch.
Returns:
None | bytes: The content of the resource file if found,
otherwise None.
"""
url = get_data_path(f"x3d-viewer/{basename}")
if not url:
_safe_print("Error: Resource not found:", basename)
return None
with open(url, "rb") as resource_file:
return resource_file.read()
@classmethod
def get_resource(
cls, url: str, source: bool = True, force: bool = False, cache: bool = True
) -> None | str:
"""Collect resources.
Args:
url (str): The URL of the resource to fetch.
source (bool): If True, returns the resource content,
otherwise returns the file path.
force (bool): If True, forces fetching the resource even if
it is already cached.
cache (bool): If True, caches the resource locally.
Returns:
None | str: The content of the resource if source is True,
or the file path if source is False. Returns None if the
resource could not be fetched or is empty.
"""
baseurl, basename = os.path.split(url)
# Strip protocol
cache_uri = re.sub(r"^\w+://", "", baseurl)
# Strip www
cache_uri = re.sub(r"^(?:www\.)?", "", cache_uri)
# domain.com -> com.domain
domain, path = cache_uri.split("/", 1)
cache_uri = "/".join([".".join(reversed(domain.split("."))), path])
# com.domain/path -> com.domain.path
cache_uri = re.sub(r"^([^/]+)/", "\\1.", cache_uri)
cache_dir = os.path.join(CACHEPATH, os.path.join(*cache_uri.split("/")))
cls.ensure_cache_directory(cache_dir)
cachefilename = os.path.join(cache_dir, basename)
body = cls.get_resource_from_cache(force, cachefilename)
if not body.strip():
body = cls.request_url_content(url)
if not body.strip():
# Fallback to local copy
body = cls.get_local_resources(basename)
if body.strip():
if cache and (force or not os.path.isfile(cachefilename)):
with open(cachefilename, "wb") as cachefile:
cachefile.write(body)
if source and not basename.endswith(".swf"):
if basename.endswith(".css"):
return f""
if basename.endswith(".js"):
return f"