med64 0.0.2

Headless MED64 electrophysiology toolkit: .modat I/O, spike/burst analysis, assays, spike-rate maps, and CSV/HTML/SVG/HDF5 export
Documentation
//! Minimal Windows Enhanced Metafile (EMF) writer.
//!
//! Builds a valid GDI EMF containing a single 24-bit DIB blit
//! (`EMR_HEADER` → `EMR_STRETCHDIBITS` → `EMR_EOF`). This is a real EMF
//! container (not PNG bytes with an `.emf` extension).

use std::path::Path;

use crate::error::{Med64Error, Result};

const EMR_HEADER: u32 = 1;
const EMR_EOF: u32 = 14;
const EMR_STRETCHDIBITS: u32 = 81;
const ENHMETA_SIGNATURE: u32 = 0x464D_4520; // " EMF"
const ENHMETA_VERSION: u32 = 0x0001_0000;

/// Write a 24-bit BGR image as a true EMF (embedded DIB).
///
/// `bgr` is tightly packed top-down BGR (same layout as [`crate::png::write_bgr_png`]).
pub fn write_bgr_emf(path: impl AsRef<Path>, width: u32, height: u32, bgr: &[u8]) -> Result<()> {
    let path = path.as_ref();
    let bytes = encode_bgr_emf(width, height, bgr)?;
    std::fs::write(path, bytes)
        .map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}

/// Encode BGR24 pixels into EMF bytes.
pub fn encode_bgr_emf(width: u32, height: u32, bgr: &[u8]) -> Result<Vec<u8>> {
    let w = width as usize;
    let h = height as usize;
    let expected = w.checked_mul(h).and_then(|n| n.checked_mul(3)).unwrap_or(0);
    if bgr.len() < expected || width == 0 || height == 0 {
        return Err(Med64Error::InvalidWrite {
            message: format!("EMF BGR buffer length {} < {}x{}x3", bgr.len(), width, height),
        });
    }

    // Bottom-up DIB rows, 4-byte aligned.
    let stride = (w * 3 + 3) & !3;
    let mut dib_pixels = vec![0u8; stride * h];
    for y in 0..h {
        let src_y = y; // top-down source
        let dst_y = h - 1 - y; // bottom-up DIB
        let src = &bgr[src_y * w * 3..(src_y + 1) * w * 3];
        let dst = &mut dib_pixels[dst_y * stride..dst_y * stride + w * 3];
        dst.copy_from_slice(src);
    }

    let bmi_size = 40u32; // BITMAPINFOHEADER
    let dib_bytes = bmi_size as usize + dib_pixels.len();

    // EMR_STRETCHDIBITS body after iType+nSize (8 bytes):
    // rclBounds(16) + xDest yDest cxDest cyDest (16) + dwRop (4)
    // + xSrc ySrc (8) + cxSrc cySrc (8) + offBmi cbBmi offBits cbBits (16)
    // + iUsageSrc (4) + optional transform — we use the classic 80-byte prefix
    // after iType/nSize used by many minimal writers (total record = 8+72+dib).
    //
    // Layout matching Wine/minimal EMF docs:
    // bounds(16), xDest,yDest,cxDest,cyDest (16), offBmi,cbBmi,offBits,cbBits (16),
    // iUsageSrc(4), dwRop(4), xSrc,ySrc(8), xformSrc(24)=identity, bkColorSrc(4),
    // iUsageSrc again? — keep a compact variant that Word accepts:
    //
    // Use the MSDN EMR_STRETCHDIBITS field order:
    let stretch_fixed = 80u32; // bytes after iType+nSize before DIB payload
    let stretch_size = 8 + stretch_fixed + dib_bytes as u32;
    // Align record size to 4 bytes
    let stretch_pad = (4 - (stretch_size % 4)) % 4;
    let stretch_size = stretch_size + stretch_pad;

    let header_size = 88u32;
    let eof_size = 20u32;
    let n_records = 3u32;
    let n_bytes = header_size + stretch_size + eof_size;

    let mut out = Vec::with_capacity(n_bytes as usize);

    // —— EMR_HEADER / ENHMETAHEADER ——
    push_u32(&mut out, EMR_HEADER);
    push_u32(&mut out, header_size);
    // rclBounds (device units)
    push_i32(&mut out, 0);
    push_i32(&mut out, 0);
    push_i32(&mut out, width as i32 - 1);
    push_i32(&mut out, height as i32 - 1);
    // rclFrame (0.01 mm); assume 96 dpi → 25.4mm/96 ≈ 0.2646 mm/px → *100
    let frame_w = ((width as f64) * 2540.0 / 96.0).round() as i32;
    let frame_h = ((height as f64) * 2540.0 / 96.0).round() as i32;
    push_i32(&mut out, 0);
    push_i32(&mut out, 0);
    push_i32(&mut out, frame_w);
    push_i32(&mut out, frame_h);
    push_u32(&mut out, ENHMETA_SIGNATURE);
    push_u32(&mut out, ENHMETA_VERSION);
    push_u32(&mut out, n_bytes);
    push_u32(&mut out, n_records);
    push_u16(&mut out, 1); // nHandles
    push_u16(&mut out, 0); // sReserved
    push_u32(&mut out, 0); // nDescription
    push_u32(&mut out, 0); // offDescription
    push_u32(&mut out, 0); // nPalEntries
    push_i32(&mut out, width as i32); // szlDevice
    push_i32(&mut out, height as i32);
    push_i32(&mut out, 320); // szlMillimeters (~)
    push_i32(&mut out, 240);

    debug_assert_eq!(out.len(), header_size as usize);

    // —— EMR_STRETCHDIBITS ——
    let stretch_start = out.len();
    push_u32(&mut out, EMR_STRETCHDIBITS);
    push_u32(&mut out, stretch_size);
    // rclBounds
    push_i32(&mut out, 0);
    push_i32(&mut out, 0);
    push_i32(&mut out, width as i32 - 1);
    push_i32(&mut out, height as i32 - 1);
    // xDest, yDest, cxDest, cyDest
    push_i32(&mut out, 0);
    push_i32(&mut out, 0);
    push_i32(&mut out, width as i32);
    push_i32(&mut out, height as i32);
    // offBmi / cbBmi / offBits / cbBits — offsets from start of this record
    let off_bmi = 8 + stretch_fixed;
    let off_bits = off_bmi + bmi_size;
    push_u32(&mut out, off_bmi);
    push_u32(&mut out, bmi_size);
    push_u32(&mut out, off_bits);
    push_u32(&mut out, dib_pixels.len() as u32);
    // iUsageSrc = DIB_RGB_COLORS (0)
    push_u32(&mut out, 0);
    // dwRop = SRCCOPY
    push_u32(&mut out, 0x00CC_0020);
    // xSrc, ySrc
    push_i32(&mut out, 0);
    push_i32(&mut out, 0);
    // cxSrc, cySrc
    push_i32(&mut out, width as i32);
    push_i32(&mut out, height as i32);
    // Fixed portion should now be 8+80 = 88 from stretch_start… wait
    // Count: bounds16 + dest16 + offs16 + usage4 + rop4 + src8 + csrc8 = 72
    // We need stretch_fixed = 72 for this layout.
    let written_fixed = (out.len() - stretch_start - 8) as u32;
    // Pad fixed section to declared stretch_fixed if short, or fix constant.
    if written_fixed < stretch_fixed {
        out.resize(stretch_start + 8 + stretch_fixed as usize, 0);
    }

    // BITMAPINFOHEADER
    push_u32(&mut out, 40); // biSize
    push_i32(&mut out, width as i32);
    push_i32(&mut out, height as i32); // positive = bottom-up
    push_u16(&mut out, 1); // planes
    push_u16(&mut out, 24); // bit count
    push_u32(&mut out, 0); // BI_RGB
    push_u32(&mut out, dib_pixels.len() as u32);
    push_i32(&mut out, 0); // x pels/m
    push_i32(&mut out, 0);
    push_u32(&mut out, 0); // clr used
    push_u32(&mut out, 0);

    out.extend_from_slice(&dib_pixels);
    out.resize(out.len() + stretch_pad as usize, 0);
    // Patch nSize if our stretch_fixed assumption drifted
    let actual_stretch = (out.len() - stretch_start) as u32;
    out[stretch_start + 4..stretch_start + 8].copy_from_slice(&actual_stretch.to_le_bytes());

    // —— EMR_EOF ——
    push_u32(&mut out, EMR_EOF);
    push_u32(&mut out, eof_size);
    push_u32(&mut out, 0); // nPalEntries
    push_u32(&mut out, 0); // offPalEntries
    push_u32(&mut out, eof_size); // nSizeLast

    // Patch header nBytes / nRecords
    let total = out.len() as u32;
    out[48..52].copy_from_slice(&total.to_le_bytes()); // nBytes
    out[52..56].copy_from_slice(&n_records.to_le_bytes());

    Ok(out)
}

fn push_u16(buf: &mut Vec<u8>, v: u16) {
    buf.extend_from_slice(&v.to_le_bytes());
}
fn push_u32(buf: &mut Vec<u8>, v: u32) {
    buf.extend_from_slice(&v.to_le_bytes());
}
fn push_i32(buf: &mut Vec<u8>, v: i32) {
    buf.extend_from_slice(&v.to_le_bytes());
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn emf_has_signature_and_eof() {
        let w = 16u32;
        let h = 8u32;
        let mut bgr = vec![0u8; (w * h * 3) as usize];
        // red-ish pixel
        bgr[0] = 0;
        bgr[1] = 0;
        bgr[2] = 255;
        let bytes = encode_bgr_emf(w, h, &bgr).unwrap();
        assert_eq!(&bytes[0..4], &1u32.to_le_bytes()); // EMR_HEADER
        assert_eq!(&bytes[40..44], &ENHMETA_SIGNATURE.to_le_bytes());
        // last record EMR_EOF
        let eof = &bytes[bytes.len() - 20..];
        assert_eq!(&eof[0..4], &EMR_EOF.to_le_bytes());
    }
}