use crate::wmf::converter::{
svg::{device_context::BlitDestRect, node::Node, util::url_string, Fill},
*,
};
#[derive(Clone, Debug, snafu::prelude::Snafu)]
pub enum TernaryRasterOperationError {
#[snafu(display("no brush specified: {cause}"))]
NoBrush { cause: String },
#[snafu(display("no source bitmap specified: {cause}"))]
NoSource { cause: String },
}
#[derive(PartialEq)]
struct BrushOnlyRopKey {
rect: [i32; 4],
fill: String,
clip_id: Option<String>,
clip_rect: Option<[i32; 4]>,
}
#[derive(Default)]
pub struct BrushOnlyRopSequence {
state: Option<BrushOnlyRopSequenceState>,
suppressed_elements: Vec<usize>,
vector_masks: Vec<(usize, Node, String, [i32; 4])>,
bitmap_masks: Vec<(usize, String, [i32; 4])>,
}
enum BrushOnlyRopSequenceState {
AwaitDpa {
key: BrushOnlyRopKey,
expected_element_count: usize,
},
AwaitFinalPatInvert {
key: BrushOnlyRopKey,
expected_element_count: usize,
mask_definition_index: Option<usize>,
mask_rect: [i32; 4],
},
AwaitFinalVectorInvert {
key: BrushOnlyRopKey,
expected_element_count: usize,
mask: Node,
},
}
impl BrushOnlyRopSequence {
fn observe(
&mut self,
operation: TernaryRasterOperation,
key: BrushOnlyRopKey,
element_count: usize,
mask_definition_index: Option<usize>,
) -> bool {
let state = std::mem::take(&mut self.state);
match (state, operation) {
(
Some(BrushOnlyRopSequenceState::AwaitFinalVectorInvert {
key: previous_key,
expected_element_count,
mask,
}),
TernaryRasterOperation::PATINVERT,
) if key == previous_key && element_count == expected_element_count => {
self.suppressed_elements.push(element_count - 2);
self.vector_masks.push((
element_count - 1,
mask,
previous_key.fill,
previous_key.rect,
));
true
}
(
Some(BrushOnlyRopSequenceState::AwaitDpa {
key: previous_key,
expected_element_count,
}),
TernaryRasterOperation::DPA,
) if element_count == expected_element_count
&& key.clip_id == previous_key.clip_id
&& key.clip_rect == previous_key.clip_rect =>
{
let mask_definition_index =
mask_definition_index.filter(|_| key.rect[2] > 0 && key.rect[3] > 0);
self.state = Some(BrushOnlyRopSequenceState::AwaitFinalPatInvert {
key: previous_key,
expected_element_count: element_count + 1,
mask_definition_index,
mask_rect: key.rect,
});
false
}
(
Some(BrushOnlyRopSequenceState::AwaitFinalPatInvert {
key: previous_key,
expected_element_count,
mask_definition_index,
mask_rect,
}),
TernaryRasterOperation::PATINVERT,
) if key == previous_key && element_count == expected_element_count => {
if mask_definition_index.is_some() {
self.suppressed_elements.push(element_count - 2);
self.bitmap_masks
.push((element_count - 1, previous_key.fill, mask_rect));
}
true
}
(_, TernaryRasterOperation::PATINVERT) => {
self.state = Some(BrushOnlyRopSequenceState::AwaitDpa {
key,
expected_element_count: element_count + 1,
});
false
}
_ => false,
}
}
pub fn observe_vector_mask(
&mut self,
mask: &Node,
brush: &Brush,
draw_mode: Option<BinaryRasterOperation>,
bounds: [i32; 4],
clip: (Option<&str>, Option<&Rect>),
element_count: usize,
) {
let Some(BrushOnlyRopSequenceState::AwaitDpa {
key,
expected_element_count,
}) = self.state.take()
else {
return;
};
let (clip_id, clip_rect) = clip;
let clip_rect = clip_rect.map(|r| {
[
i32::from(r.left),
i32::from(r.top),
i32::from(r.right),
i32::from(r.bottom),
]
});
let [x, y, width, height] = key.rect;
if expected_element_count != element_count
|| draw_mode != Some(BinaryRasterOperation::R2_MASKPEN)
|| !Self::brush_is_monochrome_mask(Some(brush))
|| mask.attr("stroke") != Some("none")
|| !key.fill.starts_with('#')
|| key.clip_id.as_deref() != clip_id
|| key.clip_rect != clip_rect
|| width <= 0
|| height <= 0
|| bounds[0] < x
|| bounds[1] < y
|| i64::from(bounds[2]) > i64::from(x) + i64::from(width)
|| i64::from(bounds[3]) > i64::from(y) + i64::from(height)
{
return;
}
self.state = Some(BrushOnlyRopSequenceState::AwaitFinalVectorInvert {
key,
expected_element_count: element_count + 1,
mask: mask.clone(),
});
}
pub fn finish(
self,
mut definitions: Vec<Node>,
mut elements: Vec<Node>,
) -> (Vec<Node>, Vec<Node>) {
let bitmap_masks: Vec<_> = self
.bitmap_masks
.into_iter()
.map(|(index, color, rect)| {
let mask = elements[index]
.clone()
.set("id", format!("rop_bitmap_source{index}"));
let paint = elements[index - 1].clone().set("fill", &color);
(index, mask, color, rect, Some(paint))
})
.collect();
for (kind, (index, mask, color, [x, y, width, height], paint)) in self
.vector_masks
.into_iter()
.map(|(index, mask, color, rect)| ("vector", (index, mask, color, rect, None)))
.chain(bitmap_masks.into_iter().map(|mask| ("bitmap", mask)))
{
let filter_id = format!("rop_{kind}_inverse{}", definitions.len());
let mask_id = format!("rop_{kind}_mask{}", definitions.len());
let transfer = Node::new("feComponentTransfer")
.add(
Node::new("feFuncR")
.set("type", "table")
.set("tableValues", "1 0"),
)
.add(
Node::new("feFuncG")
.set("type", "table")
.set("tableValues", "1 0"),
)
.add(
Node::new("feFuncB")
.set("type", "table")
.set("tableValues", "1 0"),
);
definitions.push(
Node::new("filter")
.set("id", &filter_id)
.set("color-interpolation-filters", "sRGB")
.add(transfer),
);
definitions.push(
Node::new("mask")
.set("id", &mask_id)
.set("maskUnits", "userSpaceOnUse")
.set("mask-type", "luminance")
.set("x", x)
.set("y", y)
.set("width", width)
.set("height", height)
.add(mask.set("filter", url_string(format!("#{filter_id}").as_str()))),
);
let mask_url = url_string(format!("#{mask_id}").as_str());
if let Some(paint) = paint {
let black = elements[index].clone().set("fill", "black");
elements[index] = Node::new("svg")
.set("x", x)
.set("y", y)
.set("width", width)
.set("height", height)
.set("viewBox", format!("{x} {y} {width} {height}"))
.set("mask", &mask_url)
.add(black)
.add(paint);
} else {
elements[index] = elements[index]
.clone()
.set("fill", color)
.set("mask", &mask_url);
}
}
let elements = elements
.into_iter()
.enumerate()
.filter_map(|(index, node)| {
self.suppressed_elements
.binary_search(&index)
.is_err()
.then_some(node)
})
.collect();
(definitions, elements)
}
fn brush_is_monochrome_mask(brush: Option<&Brush>) -> bool {
let Some(Brush::DIBPatternPT {
color_usage: ColorUsage::DIB_RGB_COLORS,
brush_hatch,
}) = brush
else {
return false;
};
if !matches!(
brush_hatch.dib_header_info.bit_count(),
BitCount::BI_BITCOUNT_1
) {
return false;
}
let colors = match &brush_hatch.colors {
Colors::RGBQuad(colors) if colors.len() == 2 => [
[colors[0].red, colors[0].green, colors[0].blue],
[colors[1].red, colors[1].green, colors[1].blue],
],
Colors::RGBTriple(colors) if colors.len() == 2 => [
[colors[0].red, colors[0].green, colors[0].blue],
[colors[1].red, colors[1].green, colors[1].blue],
],
_ => return false,
};
matches!(
colors,
[[0, 0, 0], [255, 255, 255]] | [[255, 255, 255], [0, 0, 0]]
)
}
fn clear_if_unrelated(&mut self, operation: TernaryRasterOperation) {
if !matches!(
operation,
TernaryRasterOperation::PATINVERT | TernaryRasterOperation::DPA
) {
self.state = None;
}
}
}
pub struct TernaryRasterOperator {
operation: TernaryRasterOperation,
rect: BlitDestRect,
brush: Option<Brush>,
source: Option<Source>,
source_rect: Option<BitmapSourceRect>,
source_bottom_up: bool,
clip_id: Option<String>,
clip_rect: Option<[i32; 4]>,
}
#[derive(Clone, Copy)]
struct BitmapSourceRect {
x: i16,
y: i16,
width: i16,
height: i16,
}
enum Source {
Bitmap16(Bitmap16),
Bitmap(DeviceIndependentBitmap),
}
impl TernaryRasterOperator {
pub fn new(operation: TernaryRasterOperation, rect: BlitDestRect) -> Self {
Self {
operation,
rect,
brush: None,
source: None,
source_rect: None,
source_bottom_up: false,
clip_id: None,
clip_rect: None,
}
}
fn normalized_rect(&self) -> (i32, i32, i32, i32, Option<String>) {
let BlitDestRect {
x,
y,
width,
height,
flip_x,
flip_y,
} = self.rect;
let mut parts = Vec::new();
if flip_x {
parts.push(format!("translate({},0) scale(-1,1)", 2 * x + width));
}
if flip_y {
parts.push(format!("translate(0,{}) scale(1,-1)", 2 * y + height));
}
let transform = (!parts.is_empty()).then(|| parts.join(" "));
(x, y, width, height, transform)
}
pub(super) fn image_node(rect: BlitDestRect, data_url: String) -> Node {
let (x, y, width, height, transform) =
Self::new(TernaryRasterOperation::SRCCOPY, rect).normalized_rect();
let image = Node::new("image")
.set("x", x)
.set("y", y)
.set("width", width)
.set("height", height)
.set("preserveAspectRatio", "none")
.set("href", data_url);
match transform {
Some(transform) => image.set("transform", transform),
None => image,
}
}
pub fn brush(mut self, brush: Brush) -> Self {
self.brush = brush.into();
self
}
pub fn clip(mut self, clip_id: Option<&str>, clip_rect: Option<&Rect>) -> Self {
self.clip_id = clip_id.map(str::to_owned);
self.clip_rect = clip_rect.map(|rect| {
[
i32::from(rect.left),
i32::from(rect.top),
i32::from(rect.right),
i32::from(rect.bottom),
]
});
self
}
pub fn source_bitmap16(mut self, source: Bitmap16) -> Self {
self.source = Source::Bitmap16(source).into();
self
}
pub fn source_bitmap(mut self, source: DeviceIndependentBitmap) -> Self {
self.source = Source::Bitmap(source).into();
self
}
pub fn source_rectangle(mut self, x: i16, y: i16, width: i16, height: i16) -> Self {
self.source_rect = Some(BitmapSourceRect {
x,
y,
width,
height,
});
self
}
pub fn bottom_up_source(mut self) -> Self {
self.source_bottom_up = true;
self
}
fn bitmap_node(&self, bitmap: Bitmap, dimensions: (usize, usize)) -> Option<Node> {
let (x, y, width, height, transform) = self.normalized_rect();
let Some(source) = self.source_rect else {
let image = Node::new("image")
.set("x", x)
.set("y", y)
.set("width", width)
.set("height", height)
.set("preserveAspectRatio", "none")
.set("href", bitmap.as_data_url());
return Some(match transform {
Some(transform) => image.set("transform", transform),
None => image,
});
};
if source.width == 0 || source.height == 0 || dimensions.0 == 0 || dimensions.1 == 0 {
return None;
}
if source.x == 0
&& source.y == 0
&& usize::try_from(source.width).ok() == Some(dimensions.0)
&& usize::try_from(source.height).ok() == Some(dimensions.1)
{
let image = Node::new("image")
.set("x", x)
.set("y", y)
.set("width", width)
.set("height", height)
.set("preserveAspectRatio", "none")
.set("href", bitmap.as_data_url());
return Some(match transform {
Some(transform) => image.set("transform", transform),
None => image,
});
}
let sx = i64::from(source.x);
let sw = i64::from(source.width);
let sh = i64::from(source.height);
let sy = if self.source_bottom_up {
i64::try_from(dimensions.1).ok()? - i64::from(source.y) - sh
} else {
i64::from(source.y)
};
let mut image = Node::new("image")
.set("x", 0)
.set("y", 0)
.set("width", dimensions.0)
.set("height", dimensions.1)
.set("preserveAspectRatio", "none")
.set("href", bitmap.as_data_url());
let mut source_transforms = Vec::new();
if sw < 0 {
source_transforms.push(format!("translate({},0) scale(-1,1)", 2 * sx + sw));
}
if sh < 0 {
source_transforms.push(format!("translate(0,{}) scale(1,-1)", 2 * sy + sh));
}
if !source_transforms.is_empty() {
image = image.set("transform", source_transforms.join(" "));
}
let viewport = Node::new("svg")
.set("x", x)
.set("y", y)
.set("width", width)
.set("height", height)
.set(
"viewBox",
format!(
"{} {} {} {}",
sx.min(sx + sw),
sy.min(sy + sh),
sw.abs(),
sh.abs()
),
)
.set("preserveAspectRatio", "none")
.set("overflow", "hidden")
.add(image);
Some(match transform {
Some(transform) => Node::new("g").set("transform", transform).add(viewport),
None => viewport,
})
}
fn source_bitmap_node(&mut self) -> Option<Node> {
let dib = match self.source.take()? {
Source::Bitmap16(data) => DeviceIndependentBitmap::from(data),
Source::Bitmap(data) => data,
};
let dimensions = (dib.dib_header_info.width(), dib.dib_header_info.height());
self.bitmap_node(Bitmap::from(dib), dimensions)
}
pub fn run(
mut self,
definitions: &mut Vec<Node>,
brush_only_rop_sequence: &mut BrushOnlyRopSequence,
element_count: usize,
) -> Result<Option<Node>, TernaryRasterOperationError> {
brush_only_rop_sequence.clear_if_unrelated(self.operation);
if self.operation.use_selected_brush() && self.brush.is_none() {
return Err(TernaryRasterOperationError::NoBrush {
cause: format!(
"TernaryRasterOperation {:?} cannot access brush.",
self.operation,
),
});
}
if self.operation.use_source() && self.source.is_none() {
return Err(TernaryRasterOperationError::NoSource {
cause: format!(
"TernaryRasterOperation {:?} cannot access source bitmap.",
self.operation,
),
});
}
let result: Node = match self.operation {
TernaryRasterOperation::BLACKNESS => Node::new("rect")
.set("x", self.rect.x)
.set("y", self.rect.y)
.set("width", self.rect.width)
.set("height", self.rect.height)
.set("stroke", "none")
.set("fill", "black"),
TernaryRasterOperation::SRCCOPY => {
let Some(image) = self.source_bitmap_node() else {
return Ok(None);
};
image
}
TernaryRasterOperation::PATCOPY => {
let fill = match Fill::from(self.brush.clone().unwrap()) {
Fill::Pattern { pattern } => {
let id = Self::issue_id(definitions);
definitions.push(pattern.set("id", id.as_str()));
url_string(format!("#{id}").as_str())
}
Fill::Value { value } => value,
};
Node::new("rect")
.set("x", self.rect.x)
.set("y", self.rect.y)
.set("width", self.rect.width)
.set("height", self.rect.height)
.set("fill", fill.as_str())
}
TernaryRasterOperation::WHITENESS => Node::new("rect")
.set("x", self.rect.x)
.set("y", self.rect.y)
.set("width", self.rect.width)
.set("height", self.rect.height)
.set("stroke", "none")
.set("fill", "white"),
operation if operation.use_selected_brush() && !operation.use_source() => {
info!(
?operation,
"approximating brush-only TernaryRasterOperation as PATCOPY"
);
let is_mask = BrushOnlyRopSequence::brush_is_monochrome_mask(self.brush.as_ref());
let mut mask_definition_index = None;
let fill = match Fill::from(self.brush.clone().unwrap()) {
Fill::Pattern { pattern } => {
let id = Self::issue_id(definitions);
if is_mask {
mask_definition_index = Some(definitions.len());
}
definitions.push(pattern.set("id", id.as_str()));
url_string(format!("#{id}").as_str())
}
Fill::Value { value } => value,
};
let key = BrushOnlyRopKey {
rect: [self.rect.x, self.rect.y, self.rect.width, self.rect.height],
fill: fill.clone(),
clip_id: self.clip_id,
clip_rect: self.clip_rect,
};
if brush_only_rop_sequence.observe(
operation,
key,
element_count,
mask_definition_index,
) {
return Ok(None);
}
Node::new("rect")
.set("x", self.rect.x)
.set("y", self.rect.y)
.set("width", self.rect.width)
.set("height", self.rect.height)
.set("fill", fill.as_str())
}
operation if operation.use_source() => {
info!(
?operation,
"approximating source TernaryRasterOperation as SRCCOPY"
);
let Some(image) = self.source_bitmap_node() else {
return Ok(None);
};
image
}
operation => {
info!(?operation, "TernaryRasterOperation is not implemented");
return Ok(None);
}
};
Ok(Some(result))
}
#[inline]
fn issue_id(definitions: &[Node]) -> String {
format!("rop_pat{}", definitions.len())
}
}
impl From<ColorRef> for RGBQuad {
fn from(v: ColorRef) -> Self {
let ColorRef {
red,
green,
blue,
reserved,
} = v;
Self {
red,
green,
blue,
reserved,
}
}
}