use core::ffi::c_void;
use core::mem::size_of;
use crate::{Host, WindowHandle, sys};
#[must_use]
pub const fn rgb(red: u8, green: u8, blue: u8) -> u32 {
(red as u32) << 16 | (green as u32) << 8 | blue as u32
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Image {
width: u32,
height: u32,
pixels: Vec<u32>,
}
impl Image {
#[must_use]
pub fn new(width: u32, height: u32) -> Self {
let len = (width as usize)
.checked_mul(height as usize)
.expect("image too large");
Self {
width,
height,
pixels: vec![0; len],
}
}
#[must_use]
pub fn width(&self) -> u32 {
self.width
}
#[must_use]
pub fn height(&self) -> u32 {
self.height
}
#[must_use]
pub fn pixels(&self) -> &[u32] {
&self.pixels
}
pub fn pixels_mut(&mut self) -> &mut [u32] {
&mut self.pixels
}
pub fn fill(&mut self, color: u32) {
self.pixels.fill(color);
}
#[must_use]
pub fn scaled(&self, factor: u32) -> Self {
assert!(factor > 0, "scale factor must be at least 1");
let mut out = Self::new(self.width * factor, self.height * factor);
let (w, f) = (self.width as usize, factor as usize);
let out_w = out.width as usize;
for (y, row) in self.pixels.chunks_exact(w.max(1)).enumerate() {
let start = y * f * out_w;
for (x, &pixel) in row.iter().enumerate() {
out.pixels[start + x * f..start + (x + 1) * f].fill(pixel);
}
for copy in 1..f {
out.pixels
.copy_within(start..start + out_w, start + copy * out_w);
}
}
out
}
}
#[derive(Debug)]
pub struct Canvas {
hdc: *mut c_void,
bitmap: *mut c_void,
width: u32,
height: u32,
}
impl Canvas {
#[must_use]
pub fn width(&self) -> u32 {
self.width
}
#[must_use]
pub fn height(&self) -> u32 {
self.height
}
pub fn draw(&self, image: &Image) {
self.draw_at(image, 0, 0);
}
pub fn draw_at(&self, image: &Image, x: i32, y: i32) {
if image.width == 0 || image.height == 0 {
return;
}
let info = sys::BitmapInfoHeader {
size: size_of::<sys::BitmapInfoHeader>() as u32,
width: image.width as i32,
height: -(image.height as i32),
planes: 1,
bit_count: 32,
compression: 0,
size_image: 0,
x_pels_per_meter: 0,
y_pels_per_meter: 0,
colors_used: 0,
colors_important: 0,
};
unsafe {
sys::SetDIBitsToDevice(
self.hdc,
x,
y,
image.width,
image.height,
0,
0,
0,
image.height,
image.pixels.as_ptr().cast(),
&info,
sys::DIB_RGB_COLORS,
);
}
}
#[must_use]
pub fn hdc(&self) -> *mut c_void {
self.hdc
}
#[must_use]
pub fn bitmap(&self) -> *mut c_void {
self.bitmap
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Update {
Default,
Redraw,
Area {
left: i32,
top: i32,
right: i32,
bottom: i32,
},
Skip,
}
impl Update {
pub(crate) fn reply(self) -> String {
match self {
Self::Default => "-1".to_owned(),
Self::Redraw => "1".to_owned(),
Self::Area {
left,
top,
right,
bottom,
} => format!("1 {left} {top} {right} {bottom}"),
Self::Skip => "0".to_owned(),
}
}
}
pub trait IntoUpdate {
fn into_update(self) -> Update;
}
impl IntoUpdate for Update {
fn into_update(self) -> Update {
self
}
}
impl IntoUpdate for () {
fn into_update(self) -> Update {
Update::Redraw
}
}
#[derive(Debug)]
pub struct Draw {
data: String,
canvas: Canvas,
main_window: WindowHandle,
active_window: WindowHandle,
host: &'static Host,
}
impl Draw {
#[must_use]
pub fn data(&self) -> &str {
&self.data
}
#[must_use]
pub fn canvas(&self) -> &Canvas {
&self.canvas
}
#[must_use]
pub fn main_window(&self) -> WindowHandle {
self.main_window
}
#[must_use]
pub fn active_window(&self) -> WindowHandle {
self.active_window
}
#[must_use]
pub fn host(&self) -> &'static Host {
self.host
}
}
#[must_use]
pub fn draw_command(window: &str, export: &str, data: &str) -> String {
let path = crate::dll_path();
let command = format!("drawdll -n {window} \"{path}\" {export}");
if data.is_empty() {
command
} else {
format!("{command} {data}")
}
}
#[derive(Debug, PartialEq, Eq)]
struct Request<'a> {
hdc: usize,
bitmap: usize,
data: &'a str,
}
fn parse_request(text: &str) -> Option<Request<'_>> {
let rest = text.strip_prefix("hdc:")?;
let (hdc, rest) = rest.split_once(' ')?;
let rest = rest.strip_prefix("hbm:")?;
let (bitmap, data) = match rest.split_once(' ') {
Some((bitmap, rest)) => (bitmap, rest.strip_prefix("data:")?),
None => (rest, ""),
};
Some(Request {
hdc: parse_handle(hdc)?,
bitmap: parse_handle(bitmap)?,
data,
})
}
fn parse_handle(text: &str) -> Option<usize> {
let digits = text
.strip_prefix("0x")
.or_else(|| text.strip_prefix("0X"))
.unwrap_or(text);
usize::from_str_radix(digits, 16).ok().filter(|&h| h != 0)
}
pub(crate) fn prepare(
text: &str,
main_window: WindowHandle,
active_window: WindowHandle,
host: &'static Host,
) -> Option<Draw> {
let request = parse_request(text)?;
let mut bitmap = sys::Bitmap {
bm_type: 0,
bm_width: 0,
bm_height: 0,
bm_width_bytes: 0,
bm_planes: 0,
bm_bits_pixel: 0,
bm_bits: core::ptr::null_mut(),
};
let written = unsafe {
sys::GetObjectW(
request.bitmap as *mut c_void,
size_of::<sys::Bitmap>() as i32,
(&raw mut bitmap).cast(),
)
};
if written == 0 || bitmap.bm_width <= 0 || bitmap.bm_height <= 0 {
return None;
}
Some(Draw {
data: request.data.to_owned(),
canvas: Canvas {
hdc: request.hdc as *mut c_void,
bitmap: request.bitmap as *mut c_void,
width: bitmap.bm_width as u32,
height: bitmap.bm_height as u32,
},
main_window,
active_window,
host,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rgb_packs_channels() {
assert_eq!(rgb(0x12, 0x34, 0x56), 0x0012_3456);
assert_eq!(rgb(0, 0, 0), 0);
assert_eq!(rgb(255, 255, 255), 0x00FF_FFFF);
}
#[test]
fn parses_what_mirc_sends() {
assert_eq!(
parse_request("hdc:0xC4011991 hbm:0xF005160B data:hello world"),
Some(Request {
hdc: 0xC401_1991,
bitmap: 0xF005_160B,
data: "hello world"
})
);
assert_eq!(
parse_request("hdc:0x1A hbm:0x2B data:"),
Some(Request {
hdc: 0x1A,
bitmap: 0x2B,
data: ""
})
);
assert_eq!(
parse_request("hdc:0x1A hbm:0x2B"),
Some(Request {
hdc: 0x1A,
bitmap: 0x2B,
data: ""
})
);
assert_eq!(
parse_request("hdc:0x1 hbm:0x2 data:hdc:0x3 hbm:0x4 data:x")
.map(|r| (r.hdc, r.bitmap, r.data)),
Some((1, 2, "hdc:0x3 hbm:0x4 data:x"))
);
}
#[test]
fn rejects_calls_that_did_not_come_from_drawdll() {
assert_eq!(parse_request(""), None);
assert_eq!(parse_request("just some text"), None);
assert_eq!(parse_request("hdc:0x1 data:oops"), None);
assert_eq!(parse_request("hdc:zz hbm:0x2 data:"), None);
assert_eq!(parse_request("hdc:0x0 hbm:0x2 data:"), None);
}
#[test]
fn replies_in_the_format_mirc_documents() {
assert_eq!(Update::Default.reply(), "-1");
assert_eq!(Update::Redraw.reply(), "1");
assert_eq!(Update::Skip.reply(), "0");
assert_eq!(
Update::Area {
left: 1,
top: 2,
right: 30,
bottom: 40
}
.reply(),
"1 1 2 30 40"
);
assert_eq!(().into_update(), Update::Redraw);
}
#[test]
fn images_scale_without_smoothing() {
let mut image = Image::new(2, 2);
image.pixels_mut().copy_from_slice(&[1, 2, 3, 4]);
let big = image.scaled(3);
assert_eq!((big.width(), big.height()), (6, 6));
let rows: Vec<&[u32]> = big.pixels().chunks(6).collect();
assert_eq!(rows[0], [1, 1, 1, 2, 2, 2]);
assert_eq!(rows[2], [1, 1, 1, 2, 2, 2]);
assert_eq!(rows[3], [3, 3, 3, 4, 4, 4]);
assert_eq!(rows[5], [3, 3, 3, 4, 4, 4]);
assert_eq!(image.scaled(1), image);
}
#[test]
fn empty_images_are_fine() {
let image = Image::new(0, 5);
assert!(image.pixels().is_empty());
assert_eq!(image.scaled(2).width(), 0);
}
mod gdi {
use super::super::*;
#[link(name = "gdi32")]
unsafe extern "system" {
fn CreateCompatibleDC(hdc: *mut c_void) -> *mut c_void;
fn CreateCompatibleBitmap(hdc: *mut c_void, w: i32, h: i32) -> *mut c_void;
fn SelectObject(hdc: *mut c_void, object: *mut c_void) -> *mut c_void;
fn GetPixel(hdc: *mut c_void, x: i32, y: i32) -> u32;
fn DeleteObject(object: *mut c_void) -> i32;
fn DeleteDC(hdc: *mut c_void) -> i32;
}
#[link(name = "user32")]
unsafe extern "system" {
fn GetDC(hwnd: *mut c_void) -> *mut c_void;
fn ReleaseDC(hwnd: *mut c_void, hdc: *mut c_void) -> i32;
}
fn colorref(rgb: u32) -> u32 {
(rgb & 0xFF) << 16 | (rgb & 0xFF00) | (rgb >> 16) & 0xFF
}
#[test]
fn draws_into_a_memory_dc_the_way_mirc_provides_one() {
unsafe {
let screen = GetDC(core::ptr::null_mut());
let hdc = CreateCompatibleDC(screen);
let bitmap = CreateCompatibleBitmap(screen, 8, 6);
let old = SelectObject(hdc, bitmap);
let handles = format!("hdc:{:#X} hbm:{:#X} data:x", hdc as usize, bitmap as usize);
let draw = prepare(
&handles,
WindowHandle::from_raw(core::ptr::null_mut()),
WindowHandle::from_raw(core::ptr::null_mut()),
crate::host(),
)
.expect("prepare");
assert_eq!(draw.data(), "x");
let canvas = draw.canvas();
assert_eq!((canvas.width(), canvas.height()), (8, 6));
let mut image = Image::new(4, 3);
image.fill(rgb(1, 2, 3));
image.pixels_mut()[0] = rgb(200, 100, 50); image.pixels_mut()[11] = rgb(9, 8, 7); canvas.draw_at(&image, 2, 1);
assert_eq!(GetPixel(hdc, 2, 1), colorref(rgb(200, 100, 50)));
assert_eq!(GetPixel(hdc, 5, 3), colorref(rgb(9, 8, 7)));
assert_eq!(GetPixel(hdc, 3, 2), colorref(rgb(1, 2, 3)));
SelectObject(hdc, old);
DeleteObject(bitmap);
DeleteDC(hdc);
ReleaseDC(core::ptr::null_mut(), screen);
}
}
}
}