Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@

### Changes
- [improvements] עברית: מנגנון עדכון מובנה עם הורדה ישירה ללא פתיחת דפדפן חיצוני, כתיבה אטומית לקובץ ‎.part, מדדי מהירות ו-ETA ואימות SHA-256 בזמן הורדה | en: Browserless in-app updater with direct streaming download, atomic .part file handling, live speed/ETA, and streaming SHA-256 verification
- [security] עברית: אימות כותרת PE ‏(MZ), גודל מינימלי ותקינות קובץ לפני הפעלת המתקין | en: Validate PE (MZ) header, minimum file size, and installer integrity before execution
- [improvements] עברית: אימות כותרת PE ‏(MZ), גודל מינימלי ותקינות קובץ לפני הפעלת המתקין | en: Validate PE (MZ) header, minimum file size, and installer integrity before execution
- [features] עברית: סריקה עמוקה של כוננים חיצוניים ותיקיות מתקינים נפוצות, השוואת SemVer והמלצה על גרסה חדשה | en: Deep external-drive and common installer-folder discovery with SemVer comparison and newest-candidate recommendation
- [improvements] עברית: הפעלה מנותקת של המתקין וסגירה מסודרת של התוכנה לשחרור נעילות קבצים | en: Detached installer execution and clean application shutdown to release binary locks
- [tests] עברית: הוספת 11 בדיקות יחידה ורגרסיה למנוע העדכון, אימות PE, SHA-256 וגישור IPC | en: Added 11 unit and regression tests for updater engine, PE validation, SHA-256, and IPC bridge contracts
- [improvements] עברית: הוספת 11 בדיקות יחידה ורגרסיה למנוע העדכון, אימות PE, SHA-256 וגישור IPC | en: Added 11 unit and regression tests for updater engine, PE validation, SHA-256, and IPC bridge contracts
- [fixes] עברית: תיקון אתחול ContextualInspector והעברת setFlows לאחר יצירת inspector, לתיקון יצירת מסמכים וייבוא DOCX ב-Issue #28 | en: Fix ContextualInspector initialization order and call setFlows after inspector creation, resolving document creation and DOCX import failures in Issue #28

---
Expand Down
Binary file added crates/tok-pdf/assets/icc/a2b.bin
Binary file not shown.
Binary file added crates/tok-pdf/assets/icc/b2a.bin
Binary file not shown.
152 changes: 152 additions & 0 deletions crates/tok-pdf/assets/icc/gen_icc_luts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""
Generates the two colour-transform tags embedded in every ICC profile that the
PDF engine writes (`crates/tok-pdf/src/color.rs`):

* a2b.bin - `mft2` (lut16Type) tag data: CMYK -> Lab (PCS), 9^4 grid
* b2a.bin - `mft2` (lut16Type) tag data: Lab -> CMYK, 9^3 grid

The model is a generic, deterministic, subtractive approximation (it is NOT a
characterisation of a real press condition such as FOGRA39). Run this script
to regenerate the files; the output is byte-for-byte reproducible.

python3 gen_icc_luts.py <output directory>
"""
import struct
import sys
from pathlib import Path

A2B_GRID = 9
B2A_GRID = 9

# D50 reference white
XN, YN, ZN = 0.9642, 1.0, 0.8249


def srgb_to_linear(v):
return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4


def linear_to_srgb(v):
v = min(max(v, 0.0), 1.0)
return 12.92 * v if v <= 0.0031308 else 1.055 * (v ** (1 / 2.4)) - 0.055


def rgb_to_xyz_d50(r, g, b):
rl, gl, bl = srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b)
# sRGB (D65) -> XYZ, then Bradford adaptation to D50 (combined matrix, as in the sRGB D50 profile)
x = 0.4360747 * rl + 0.3850649 * gl + 0.1430804 * bl
y = 0.2225045 * rl + 0.7168786 * gl + 0.0606169 * bl
z = 0.0139322 * rl + 0.0971045 * gl + 0.7141733 * bl
return x, y, z


def xyz_d50_to_rgb(x, y, z):
rl = 3.1338561 * x - 1.6168667 * y - 0.4906146 * z
gl = -0.9787684 * x + 1.9161415 * y + 0.0334540 * z
bl = 0.0719453 * x - 0.2289914 * y + 1.4052427 * z
return linear_to_srgb(rl), linear_to_srgb(gl), linear_to_srgb(bl)


def f(t):
return t ** (1 / 3) if t > 216 / 24389 else (24389 / 27 * t + 16) / 116


def finv(t):
return t ** 3 if t ** 3 > 216 / 24389 else (116 * t - 16) / (24389 / 27)


def xyz_to_lab(x, y, z):
fx, fy, fz = f(x / XN), f(y / YN), f(z / ZN)
return 116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)


def lab_to_xyz(l, a, b):
fy = (l + 16) / 116
fx, fz = fy + a / 500, fy - b / 200
return XN * finv(fx), YN * finv(fy), ZN * finv(fz)


def cmyk_to_rgb(c, m, y, k):
return (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k)


def rgb_to_cmyk(r, g, b):
r, g, b = (min(max(v, 0.0), 1.0) for v in (r, g, b))
k = 1 - max(r, g, b)
if k >= 1 - 1e-9:
return 0.0, 0.0, 0.0, 1.0
d = 1 - k
return (1 - r - k) / d, (1 - g - k) / d, (1 - b - k) / d, k


def u16(v):
return int(min(max(round(v), 0), 65535))


# ICC v2 legacy 16-bit Lab encoding
def enc_l(l):
return u16(l * 65280 / 100)


def enc_ab(a):
return u16((a + 128) * 256)


def dec_l(v):
return v * 100 / 65280


def dec_ab(v):
return v / 256 - 128


def lut16(in_ch, out_ch, grid, clut):
"""Assembles an `mft2` tag: identity matrix, 2-entry identity input/output tables."""
out = bytearray()
out += b"mft2" + bytes(4)
out += bytes([in_ch, out_ch, grid, 0])
for i in range(9):
out += struct.pack(">i", 0x00010000 if i % 4 == 0 else 0)
out += struct.pack(">HH", 2, 2)
for _ in range(in_ch):
out += struct.pack(">HH", 0, 65535)
out += b"".join(struct.pack(">H", v) for v in clut)
for _ in range(out_ch):
out += struct.pack(">HH", 0, 65535)
return bytes(out)


def build_a2b():
clut = []
n = A2B_GRID - 1
for ci in range(A2B_GRID):
for mi in range(A2B_GRID):
for yi in range(A2B_GRID):
for ki in range(A2B_GRID):
r, g, b = cmyk_to_rgb(ci / n, mi / n, yi / n, ki / n)
l, a, bb = xyz_to_lab(*rgb_to_xyz_d50(r, g, b))
clut += [enc_l(l), enc_ab(a), enc_ab(bb)]
return lut16(4, 3, A2B_GRID, clut)


def build_b2a():
clut = []
n = B2A_GRID - 1
for li in range(B2A_GRID):
for ai in range(B2A_GRID):
for bi in range(B2A_GRID):
l = dec_l(li / n * 65280)
a = dec_ab(ai / n * 65280)
b = dec_ab(bi / n * 65280)
r, g, bl = xyz_d50_to_rgb(*lab_to_xyz(l, a, b))
c, m, y, k = rgb_to_cmyk(r, g, bl)
clut += [u16(c * 65535), u16(m * 65535), u16(y * 65535), u16(k * 65535)]
return lut16(3, 4, B2A_GRID, clut)


if __name__ == "__main__":
out_dir = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "a2b.bin").write_bytes(build_a2b())
(out_dir / "b2a.bin").write_bytes(build_b2a())
106 changes: 74 additions & 32 deletions crates/tok-pdf/src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,35 +262,39 @@ impl ColorManagementEngine {
}
}

/// Generates a valid ISO 15076-1 binary ICC v2.4 `prtr` `CMYK -> Lab` Output Profile
/// for embedding in the PDF/X `DestOutputProfile` stream (`N = 4`).
/// Generates a binary ICC v2.4 `prtr` `CMYK -> Lab` Output Profile for embedding in the
/// PDF/X `DestOutputProfile` stream (`N = 4`).
///
/// The profile carries real colour transforms (`A2B0..2` and `B2A0..2`, both `lut16Type`) so
/// that colour-managed viewers can build a transform from it. They come from a generic
/// subtractive model (see `assets/icc/gen_icc_luts.py`), not from a measured press condition,
/// and the description says so.
pub fn generate_icc_profile_bytes(profile: IccProfileId) -> Vec<u8> {
let desc_str = profile.info();
// CMYK -> Lab and Lab -> CMYK `lut16Type` tag data.
const A2B_LUT: &[u8] = include_bytes!("../assets/icc/a2b.bin");
const B2A_LUT: &[u8] = include_bytes!("../assets/icc/b2a.bin");

let desc_str = format!("TypesetOK approximation of {}", profile.info());
let cprt_str = "Copyright TypesetOK Pre-Press Color Engine (ISO 15076-1)";

// Build `desc` tag (type 'desc')
// Build `desc` tag (type 'desc', textDescriptionType)
let mut desc_tag = Vec::new();
desc_tag.extend_from_slice(b"desc");
desc_tag.extend_from_slice(&[0u8; 4]);
let ascii_len = (desc_str.len() + 1) as u32;
desc_tag.extend_from_slice(&ascii_len.to_be_bytes());
desc_tag.extend_from_slice(desc_str.as_bytes());
desc_tag.push(0);
// Unicode & ScriptCode placeholders (67 bytes per ICC v2 spec)
desc_tag.extend_from_slice(&[0u8; 67]);
while desc_tag.len() % 4 != 0 {
desc_tag.push(0);
}
// Unicode language code + count (4 + 4), ScriptCode code + count + 67-byte buffer
// (2 + 1 + 67): 78 bytes, as the ICC v2 specification requires.
desc_tag.extend_from_slice(&[0u8; 78]);

// Build `cprt` tag (type 'text')
let mut cprt_tag = Vec::new();
cprt_tag.extend_from_slice(b"text");
cprt_tag.extend_from_slice(&[0u8; 4]);
cprt_tag.extend_from_slice(cprt_str.as_bytes());
cprt_tag.push(0);
while cprt_tag.len() % 4 != 0 {
cprt_tag.push(0);
}

// Build `wtpt` tag (type 'XYZ ', D50 standard illuminant: X=0.9642, Y=1.0000, Z=0.8249)
let mut wtpt_tag = Vec::with_capacity(20);
Expand All @@ -300,13 +304,32 @@ impl ColorManagementEngine {
wtpt_tag.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // 1.0000 in s15Fixed16
wtpt_tag.extend_from_slice(&0x0000_D32Du32.to_be_bytes()); // 0.8249 in s15Fixed16

// Distinct data blocks, stored in this order. Every block starts on a 4-byte boundary.
let blocks: [&[u8]; 5] = [&desc_tag, &cprt_tag, &wtpt_tag, A2B_LUT, B2A_LUT];
// Tag table: signature and the block it points at. The three rendering intents of each
// transform share one block.
let tags: [(&[u8; 4], usize); 9] = [
(b"desc", 0),
(b"cprt", 1),
(b"wtpt", 2),
(b"A2B0", 3),
(b"A2B1", 3),
(b"A2B2", 3),
(b"B2A0", 4),
(b"B2A1", 4),
(b"B2A2", 4),
];

let header_size = 128u32;
let tag_count = 3u32;
let tag_count = tags.len() as u32;
let tag_table_size = 4 + tag_count * 12;
let desc_offset = header_size + tag_table_size;
let cprt_offset = desc_offset + desc_tag.len() as u32;
let wtpt_offset = cprt_offset + cprt_tag.len() as u32;
let total_size = wtpt_offset + wtpt_tag.len() as u32;
let mut offsets = [0u32; 5];
let mut cursor = header_size + tag_table_size;
for (offset, block) in offsets.iter_mut().zip(blocks.iter()) {
*offset = cursor;
cursor += (block.len() as u32 + 3) & !3;
}
let total_size = cursor;

let mut icc = Vec::with_capacity(total_size as usize);

Expand Down Expand Up @@ -338,23 +361,18 @@ impl ColorManagementEngine {

// Tag Table
icc.extend_from_slice(&tag_count.to_be_bytes());
// Tag 1: 'desc'
icc.extend_from_slice(b"desc");
icc.extend_from_slice(&desc_offset.to_be_bytes());
icc.extend_from_slice(&(desc_tag.len() as u32).to_be_bytes());
// Tag 2: 'cprt'
icc.extend_from_slice(b"cprt");
icc.extend_from_slice(&cprt_offset.to_be_bytes());
icc.extend_from_slice(&(cprt_tag.len() as u32).to_be_bytes());
// Tag 3: 'wtpt'
icc.extend_from_slice(b"wtpt");
icc.extend_from_slice(&wtpt_offset.to_be_bytes());
icc.extend_from_slice(&(wtpt_tag.len() as u32).to_be_bytes());
for &(signature, block_index) in &tags {
icc.extend_from_slice(signature);
icc.extend_from_slice(&offsets[block_index].to_be_bytes());
icc.extend_from_slice(&(blocks[block_index].len() as u32).to_be_bytes());
}

// Tag Data
icc.extend_from_slice(&desc_tag);
icc.extend_from_slice(&cprt_tag);
icc.extend_from_slice(&wtpt_tag);
for block in blocks {
icc.extend_from_slice(block);
let padding = (4 - block.len() % 4) % 4;
icc.extend_from_slice(&[0u8; 3][..padding]);
}

icc
}
Expand Down Expand Up @@ -436,5 +454,29 @@ mod tests {
assert_eq!(&icc_bytes[12..16], b"prtr");
assert_eq!(&icc_bytes[16..20], b"CMYK");
assert_eq!(&icc_bytes[36..40], b"acsp");

// The profile must be structurally consistent and carry both colour transforms.
let be32 = |at: usize| u32::from_be_bytes(icc_bytes[at..at + 4].try_into().unwrap());
assert_eq!(be32(0) as usize, icc_bytes.len(), "profile size field");
let tag_count = be32(128) as usize;
assert_eq!(tag_count, 9);
let mut signatures = Vec::new();
for i in 0..tag_count {
let entry = 132 + i * 12;
let (offset, size) = (be32(entry + 4) as usize, be32(entry + 8) as usize);
assert_eq!(offset % 4, 0, "tag data must be 4-byte aligned");
assert!(
offset + size <= icc_bytes.len(),
"tag data inside the profile"
);
signatures.push(icc_bytes[entry..entry + 4].to_vec());
if icc_bytes[entry..entry + 4] == *b"A2B0" {
assert_eq!(&icc_bytes[offset..offset + 4], b"mft2");
assert_eq!(icc_bytes[offset + 8], 4, "A2B0 has 4 input channels (CMYK)");
assert_eq!(icc_bytes[offset + 9], 3, "A2B0 has 3 output channels (Lab)");
}
}
assert!(signatures.iter().any(|s| s == b"A2B0"));
assert!(signatures.iter().any(|s| s == b"B2A0"));
}
}
Loading
Loading