use core::ffi::c_void;
use core::ptr;
use std::sync::OnceLock;
use crate::{Encoding, Version, sys};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct WindowHandle(*mut c_void);
unsafe impl Send for WindowHandle {}
unsafe impl Sync for WindowHandle {}
impl WindowHandle {
pub const fn from_raw(hwnd: *mut c_void) -> Self {
Self(hwnd)
}
pub const fn as_raw(self) -> *mut c_void {
self.0
}
pub fn is_null(self) -> bool {
self.0.is_null()
}
pub fn is_current_thread(self) -> bool {
unsafe {
sys::GetWindowThreadProcessId(self.0, ptr::null_mut()) == sys::GetCurrentThreadId()
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Client {
Mirc,
AdiIrc,
}
impl Client {
pub fn of_window(window: WindowHandle) -> Self {
let mut class = [0u16; 16];
let len =
unsafe { sys::GetClassNameW(window.as_raw(), class.as_mut_ptr(), class.len() as i32) };
Self::from_class(&class[..len.max(0) as usize])
}
fn from_class(class: &[u16]) -> Self {
let is = |name: &str| class.iter().copied().eq(name.encode_utf16());
if is("mIRC") || is("mIRC32") {
Self::Mirc
} else {
Self::AdiIrc
}
}
}
#[derive(Clone, Debug)]
pub struct Host {
client: Client,
version: Version,
beta: u32,
main_window: WindowHandle,
encoding: Encoding,
capacity: usize,
keep_loaded: bool,
}
impl Host {
pub fn client(&self) -> Client {
self.client
}
pub fn version(&self) -> Version {
self.version
}
pub fn beta(&self) -> u32 {
self.beta
}
pub fn main_window(&self) -> WindowHandle {
self.main_window
}
pub fn unicode(&self) -> bool {
self.encoding == Encoding::Utf16
}
pub fn encoding(&self) -> Encoding {
self.encoding
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn keep_loaded(&self) -> bool {
self.keep_loaded
}
}
pub const fn buffer_capacity(version: Version, reported_bytes: Option<u32>) -> usize {
const DOCUMENTED: usize = 900;
const LINE_LIMIT: usize = 4151;
const EXTENDED: usize = 4200;
let reported = match reported_bytes {
Some(bytes) if bytes > 0 => Some(bytes as usize),
_ => None,
};
if version.major() > 7 || (version.major() == 7 && version.minor() >= 84) {
match reported {
Some(bytes) => bytes,
None => EXTENDED,
}
} else if version.major() == 7 && version.minor() >= 64 {
match reported {
Some(bytes) => bytes / 2,
None => EXTENDED,
}
} else if version.major() == 7 && version.minor() >= 53 {
EXTENDED
} else if version.major() == 7 || (version.major() == 6 && version.minor() >= 32) {
LINE_LIMIT
} else {
DOCUMENTED
}
}
fn legacy_version() -> Version {
host_file_version()
.filter(|&v| v >= Version::V5_6 && v < Version::V5_8)
.unwrap_or(Version::V5_6)
}
fn host_file_version() -> Option<Version> {
parse_version(&host_version_string("FileVersion")?)
}
fn host_version_string(key: &str) -> Option<String> {
let resource = unsafe {
let module = sys::GetModuleHandleW(ptr::null());
let found = sys::FindResourceW(
module,
sys::VS_VERSION_INFO as *const u16,
sys::RT_VERSION as *const u16,
);
if module.is_null() || found.is_null() {
return None;
}
let data = sys::LockResource(sys::LoadResource(module, found));
let len = sys::SizeofResource(module, found) as usize;
if data.is_null() {
return None;
}
core::slice::from_raw_parts(data.cast::<u8>(), len)
};
version_resource_string(resource, key)
}
fn version_resource_string(resource: &[u8], key: &str) -> Option<String> {
let key: Vec<u8> = key
.encode_utf16()
.chain([0])
.flat_map(u16::to_le_bytes)
.collect();
let at = resource.windows(key.len()).position(|w| w == key)?;
let value = (at + key.len() + 3) & !3;
let units: Vec<u16> = resource
.get(value..)?
.chunks_exact(2)
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.take_while(|&u| u != 0)
.collect();
Some(String::from_utf16_lossy(&units))
}
fn parse_version(text: &str) -> Option<Version> {
let (major, minor) = text.trim().split_once('.')?;
let minor: String = minor.chars().take_while(char::is_ascii_digit).collect();
if minor.is_empty() || minor.len() > 2 {
return None;
}
let padded = if minor.len() == 1 {
format!("{minor}0")
} else {
minor
};
Some(Version::new(major.parse().ok()?, padded.parse().ok()?))
}
static HOST: OnceLock<Host> = OnceLock::new();
pub fn host() -> &'static Host {
HOST.get_or_init(|| Host::legacy(None))
}
pub(crate) fn init_legacy(main_window: WindowHandle) -> &'static Host {
let _ = HOST.set(Host::legacy(Some(main_window)));
host()
}
pub(crate) unsafe fn init(
info: *mut sys::LoadInfo,
keep_loaded: bool,
unicode: bool,
) -> &'static Host {
if !info.is_null() {
let host = unsafe { Host::from_load_info(info, keep_loaded, unicode) };
let _ = HOST.set(host);
}
host()
}
impl Host {
fn legacy(main_window: Option<WindowHandle>) -> Self {
let main_window = main_window.unwrap_or(WindowHandle(ptr::null_mut()));
Self {
client: Client::of_window(main_window),
version: legacy_version(),
beta: 0,
main_window,
encoding: Encoding::Ansi,
capacity: buffer_capacity(Version::V5_6, None),
keep_loaded: false,
}
}
unsafe fn from_load_info(info: *mut sys::LoadInfo, keep_loaded: bool, unicode: bool) -> Self {
let (raw_version, hwnd) = unsafe {
(&raw mut (*info).m_keep).write(keep_loaded.into());
(
(&raw const (*info).m_version).read(),
(&raw const (*info).m_hwnd).read(),
)
};
let version = Version::from_raw(raw_version);
let encoding = if version >= Version::V7_0 {
unsafe { (&raw mut (*info).m_unicode).write(unicode.into()) };
if unicode {
Encoding::Utf16
} else {
Encoding::Utf8
}
} else {
Encoding::Ansi
};
let beta =
(version >= Version::V7_51).then(|| unsafe { (&raw const (*info).m_beta).read() });
let bytes =
(version >= Version::V7_64).then(|| unsafe { (&raw const (*info).m_bytes).read() });
Self {
client: Client::of_window(WindowHandle(hwnd)),
version,
beta: beta.unwrap_or(0),
main_window: WindowHandle(hwnd),
encoding,
capacity: buffer_capacity(version, bytes),
keep_loaded,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const fn v(major: u16, minor: u16) -> Version {
Version::new(major, minor)
}
#[test]
fn capacity_by_version() {
assert_eq!(buffer_capacity(Version::V5_6, None), 900);
assert_eq!(buffer_capacity(v(5, 80), None), 900);
assert_eq!(buffer_capacity(v(6, 3), None), 900);
assert_eq!(buffer_capacity(v(6, 31), None), 900);
assert_eq!(buffer_capacity(v(6, 32), None), 4151);
assert_eq!(buffer_capacity(v(7, 0), None), 4151);
assert_eq!(buffer_capacity(v(7, 52), None), 4151);
assert_eq!(buffer_capacity(v(7, 53), None), 4200);
assert_eq!(buffer_capacity(v(7, 63), None), 4200);
}
#[test]
fn capacity_from_mbytes() {
assert_eq!(buffer_capacity(v(7, 64), Some(20480)), 10240);
assert_eq!(buffer_capacity(v(7, 83), Some(20480)), 10240);
assert_eq!(buffer_capacity(v(7, 84), Some(10240)), 10240);
assert_eq!(buffer_capacity(v(7, 85), Some(10240)), 10240);
assert_eq!(buffer_capacity(v(8, 0), Some(16384)), 16384);
}
#[test]
fn capacity_ignores_missing_mbytes() {
assert_eq!(buffer_capacity(v(7, 85), Some(0)), 4200);
assert_eq!(buffer_capacity(v(7, 70), None), 4200);
}
#[test]
fn reads_modern_loadinfo() {
let mut info = sys::LoadInfo {
m_version: Version::new(7, 85).to_raw(),
m_hwnd: ptr::null_mut(),
m_keep: 1,
m_unicode: 0,
m_beta: 0,
m_bytes: 10240,
};
let host = unsafe { Host::from_load_info(&mut info, false, true) };
assert_eq!(info.m_keep, 0);
assert_eq!(info.m_unicode, 1);
assert_eq!(host.version(), v(7, 85));
assert_eq!(host.beta(), 0);
assert!(host.unicode());
assert_eq!(host.encoding(), Encoding::Utf16);
assert_eq!(host.capacity(), 10240);
assert!(!host.keep_loaded());
}
#[test]
fn ansi_mode_on_mirc_7_is_utf8() {
let mut info = sys::LoadInfo {
m_version: Version::new(7, 42).to_raw(),
m_hwnd: ptr::null_mut(),
m_keep: 1,
m_unicode: 0,
m_beta: 0,
m_bytes: 0,
};
let host = unsafe { Host::from_load_info(&mut info, true, false) };
assert_eq!(info.m_unicode, 0);
assert_eq!(host.encoding(), Encoding::Utf8);
assert_eq!(host.capacity(), 4151);
}
#[test]
fn touches_only_the_12_byte_prefix_on_mirc_6() {
#[repr(C)]
struct Mirc6LoadInfo {
version: u32,
hwnd: *mut c_void,
keep: i32,
beyond: [u32; 3],
}
let mut info = Mirc6LoadInfo {
version: 3 << 16, hwnd: ptr::null_mut(),
keep: 1,
beyond: [0xDEAD_BEEF; 3],
};
let host = unsafe { Host::from_load_info((&raw mut info).cast(), false, true) };
assert_eq!(host.version(), v(6, 3));
assert_eq!(host.encoding(), Encoding::Ansi);
assert_eq!(host.capacity(), 900);
assert_eq!(info.keep, 0);
assert_eq!(info.beyond, [0xDEAD_BEEF; 3]);
}
}
#[cfg(test)]
mod legacy_tests {
use super::*;
#[test]
fn hosts_without_loaddll_are_conservative_mirc_5_6() {
let host = Host::legacy(None);
assert_eq!(host.version(), Version::V5_6);
assert_eq!(host.encoding(), Encoding::Ansi);
assert_eq!(host.capacity(), 900);
assert!(!host.keep_loaded());
assert!(!host.unicode());
assert_eq!(host.beta(), 0);
assert!(host.main_window().is_null());
}
}
#[cfg(test)]
mod file_version_tests {
use super::*;
fn utf16(text: &str) -> Vec<u8> {
text.encode_utf16().flat_map(u16::to_le_bytes).collect()
}
fn string_entry(key: &str, value: &str) -> Vec<u8> {
let mut entry = vec![0u8; 6]; entry.extend(utf16(key));
entry.extend([0, 0]);
while entry.len() % 4 != 0 {
entry.push(0);
}
entry.extend(utf16(value));
entry.extend([0, 0]);
entry
}
#[test]
fn finds_file_version_among_other_strings() {
let mut resource = string_entry("CompanyName", "mIRC Co. Ltd.");
while resource.len() % 4 != 0 {
resource.push(0);
}
resource.extend(string_entry("FileVersion", "5.61"));
assert_eq!(
version_resource_string(&resource, "FileVersion").as_deref(),
Some("5.61")
);
assert_eq!(
version_resource_string(&resource, "CompanyName").as_deref(),
Some("mIRC Co. Ltd.")
);
assert_eq!(
version_resource_string(&string_entry("ProductName", "mIRC"), "FileVersion"),
None
);
}
#[test]
fn parses_mirc_style_versions() {
assert_eq!(parse_version("5.6"), Some(Version::new(5, 60)));
assert_eq!(parse_version("5.61"), Some(Version::new(5, 61)));
assert_eq!(parse_version("5.7"), Some(Version::new(5, 70)));
assert_eq!(parse_version("5.71"), Some(Version::new(5, 71)));
assert_eq!(parse_version("7.85 beta"), Some(Version::new(7, 85)));
assert_eq!(parse_version("5"), None);
assert_eq!(parse_version("5.678"), None);
}
#[test]
fn test_runner_is_not_a_legacy_host() {
assert_eq!(legacy_version(), Version::V5_6);
}
}
#[cfg(test)]
mod client_tests {
use super::*;
fn utf16(text: &str) -> Vec<u16> {
text.encode_utf16().collect()
}
#[test]
fn mirc_window_classes_are_mirc_and_anything_else_is_adiirc() {
assert_eq!(Client::from_class(&utf16("mIRC")), Client::Mirc);
assert_eq!(Client::from_class(&utf16("mIRC32")), Client::Mirc);
assert_eq!(Client::from_class(&utf16("mirc")), Client::AdiIrc);
assert_eq!(Client::from_class(&utf16("mIRC_Channel")), Client::AdiIrc);
assert_eq!(
Client::from_class(&utf16("WindowsForms10.Window.8.app.0.141b42a_r6_ad1")),
Client::AdiIrc
);
}
}