use std::borrow::Cow;
use crate::trap::types::decode_mac_roman;
pub const DIALOG_RECORD_SIZE: u32 = 256;
pub const DIALOG_WINDOW_KIND_OFFSET: u32 = 108;
pub const DIALOG_GO_AWAY_FLAG_OFFSET: u32 = 112;
pub const DIALOG_ITEMS_OFFSET: u32 = 156;
pub const DIALOG_TEXT_HANDLE_OFFSET: u32 = 160;
pub const DIALOG_EDIT_FIELD_OFFSET: u32 = 164;
pub const DIALOG_EDIT_OPEN_OFFSET: u32 = 166;
pub const DIALOG_DEFAULT_ITEM_OFFSET: u32 = 168;
pub const DIALOG_RESOURCE_ID_OFFSET: u32 = 170;
pub const DIALOG_INITIAL_EDIT_FIELD: i16 = -1;
pub const DIALOG_INITIAL_EDIT_OPEN: i16 = 0;
pub const DIALOG_INITIAL_DEFAULT_ITEM: i16 = 1;
pub const DIALOG_CANCEL_ITEM_OFFSET: u32 = 172;
pub const DIALOG_ALERT_HIT_OFFSET: u32 = 174;
pub const DIALOG_STANDARD_ALERT_OUTPUT_OFFSET: u32 = 176;
pub const DIALOG_STANDARD_ALERT_STACK_OFFSET: u32 = 180;
pub const DIALOG_WINDOW_KIND: u16 = 2;
#[allow(dead_code)]
pub const DIALOG_DISPATCH_NEW_COLOR_DIALOG: u16 = 0x0000;
pub const DIALOG_DISPATCH_GET_STD_FILTER_PROC: u16 = 0x0003;
pub const DIALOG_DISPATCH_SET_DIALOG_DEFAULT_ITEM: u16 = 0x0004;
pub const DIALOG_DISPATCH_SET_DIALOG_CANCEL_ITEM: u16 = 0x0005;
pub const DIALOG_DISPATCH_SET_DIALOG_TRACKS_CURSOR: u16 = 0x0006;
pub const DIALOG_DISPATCH_NEW_FEATURES_DIALOG: u16 = 0x000C;
pub const DEFAULT_BUTTON_OUTLINE_THICKNESS: i16 = 3;
pub const DEFAULT_BUTTON_OUTLINE_INSET: i16 = 4;
pub const DIALOG_DBOX_FRAME_MARGIN: i16 = 8;
pub const EDIT_TEXT_FRAME_OUTSET: i16 = 3;
pub const DIALOG_TEXT_LEFT_INSET: i16 = 1;
pub const APPEND_DITL_OVERLAY: i16 = 0;
pub const APPEND_DITL_RIGHT: i16 = 1;
pub const APPEND_DITL_BOTTOM: i16 = 2;
pub const DIALOG_ITEM_DISABLED_FLAG: u8 = 0x80;
pub const DIALOG_ITEM_USER_ITEM: u8 = 0;
pub const DIALOG_ITEM_BUTTON: u8 = 4;
pub const DIALOG_ITEM_CHECKBOX: u8 = 5;
pub const DIALOG_ITEM_RADIO: u8 = 6;
pub const DIALOG_ITEM_RESOURCE_CONTROL: u8 = 7;
pub const DIALOG_ITEM_STATIC_TEXT: u8 = 8;
pub const DIALOG_ITEM_EDIT_TEXT: u8 = 16;
pub const DIALOG_ITEM_ICON: u8 = 32;
pub const DIALOG_ITEM_PICTURE: u8 = 64;
pub const ALERT_TYPE_STOP: u16 = 0;
pub const ALERT_TYPE_NOTE: u16 = 1;
pub const ALERT_TYPE_CAUTION: u16 = 2;
#[allow(dead_code)]
pub const ALERT_TYPE_PLAIN: u16 = 3;
#[allow(dead_code)]
pub const ALERT_BUTTON_OK: i16 = 1;
#[allow(dead_code)]
pub const ALERT_BUTTON_CANCEL: i16 = 2;
#[allow(dead_code)]
pub const ALERT_BUTTON_OTHER: i16 = 3;
#[allow(dead_code)]
pub const ALERT_BUTTON_HELP: i16 = 4;
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DialogItemKind {
UserItem,
Button,
Checkbox,
RadioButton,
ResourceControl,
StaticText,
EditText,
Icon,
Picture,
Unknown(u8),
}
#[allow(dead_code)]
impl DialogItemKind {
pub const fn from_raw_type(raw: u8) -> Self {
match raw & 0x7F {
DIALOG_ITEM_USER_ITEM => Self::UserItem,
DIALOG_ITEM_BUTTON => Self::Button,
DIALOG_ITEM_CHECKBOX => Self::Checkbox,
DIALOG_ITEM_RADIO => Self::RadioButton,
DIALOG_ITEM_RESOURCE_CONTROL => Self::ResourceControl,
DIALOG_ITEM_STATIC_TEXT => Self::StaticText,
DIALOG_ITEM_EDIT_TEXT => Self::EditText,
DIALOG_ITEM_ICON => Self::Icon,
DIALOG_ITEM_PICTURE => Self::Picture,
other => Self::Unknown(other),
}
}
pub const fn raw_base_type(self) -> u8 {
match self {
Self::UserItem => DIALOG_ITEM_USER_ITEM,
Self::Button => DIALOG_ITEM_BUTTON,
Self::Checkbox => DIALOG_ITEM_CHECKBOX,
Self::RadioButton => DIALOG_ITEM_RADIO,
Self::ResourceControl => DIALOG_ITEM_RESOURCE_CONTROL,
Self::StaticText => DIALOG_ITEM_STATIC_TEXT,
Self::EditText => DIALOG_ITEM_EDIT_TEXT,
Self::Icon => DIALOG_ITEM_ICON,
Self::Picture => DIALOG_ITEM_PICTURE,
Self::Unknown(raw) => raw,
}
}
pub const fn is_control(self) -> bool {
matches!(
self,
Self::Button | Self::Checkbox | Self::RadioButton | Self::ResourceControl
)
}
pub const fn is_user_item(self) -> bool {
matches!(self, Self::UserItem)
}
pub const fn is_button(self) -> bool {
matches!(self, Self::Button)
}
pub const fn is_checkbox(self) -> bool {
matches!(self, Self::Checkbox)
}
pub const fn is_radio(self) -> bool {
matches!(self, Self::RadioButton)
}
pub const fn is_resource_control(self) -> bool {
matches!(self, Self::ResourceControl)
}
pub const fn is_static_text(self) -> bool {
matches!(self, Self::StaticText)
}
pub const fn is_edit_text(self) -> bool {
matches!(self, Self::EditText)
}
pub const fn is_icon(self) -> bool {
matches!(self, Self::Icon)
}
pub const fn is_picture(self) -> bool {
matches!(self, Self::Picture)
}
pub const fn is_text(self) -> bool {
matches!(self, Self::StaticText | Self::EditText)
}
pub const fn has_text_or_title(self) -> bool {
matches!(
self,
Self::StaticText
| Self::EditText
| Self::Button
| Self::Checkbox
| Self::RadioButton
)
}
pub const fn is_resource(self) -> bool {
matches!(self, Self::ResourceControl | Self::Icon | Self::Picture)
}
pub const fn resource_type(self) -> Option<[u8; 4]> {
match self {
Self::ResourceControl => Some(*b"CNTL"),
Self::Icon => Some(*b"ICON"),
Self::Picture => Some(*b"PICT"),
_ => None,
}
}
pub const fn resource_type_u32(self) -> Option<u32> {
match self.resource_type() {
Some(bytes) => Some(u32::from_be_bytes(bytes)),
None => None,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DialogItemRecord {
pub item_offset: usize,
pub item_type: u8,
pub rect: (i16, i16, i16, i16),
pub handle: u32,
pub payload: Vec<u8>,
}
#[allow(dead_code)]
impl DialogItemRecord {
pub fn is_enabled(&self) -> bool {
is_dialog_item_enabled(self.item_type)
}
pub fn is_disabled(&self) -> bool {
is_dialog_item_disabled(self.item_type)
}
pub fn kind(&self) -> DialogItemKind {
DialogItemKind::from_raw_type(self.item_type)
}
pub fn is_control(&self) -> bool {
is_dialog_item_control(self.item_type)
}
pub fn is_user_item(&self) -> bool {
is_dialog_item_user_item(self.item_type)
}
pub fn is_button(&self) -> bool {
is_dialog_item_button(self.item_type)
}
pub fn is_checkbox(&self) -> bool {
is_dialog_item_checkbox(self.item_type)
}
pub fn is_radio(&self) -> bool {
is_dialog_item_radio(self.item_type)
}
pub fn is_resource_control(&self) -> bool {
is_dialog_item_resource_control(self.item_type)
}
pub fn is_static_text(&self) -> bool {
is_dialog_item_static_text(self.item_type)
}
pub fn is_edit_text(&self) -> bool {
is_dialog_item_edit_text(self.item_type)
}
pub fn is_icon(&self) -> bool {
is_dialog_item_icon(self.item_type)
}
pub fn is_picture(&self) -> bool {
is_dialog_item_picture(self.item_type)
}
pub fn is_text(&self) -> bool {
is_dialog_item_text(self.item_type)
}
pub fn has_text_or_title(&self) -> bool {
is_dialog_item_text_or_title(self.item_type)
}
pub fn text_payload(&self) -> Option<&[u8]> {
if self.has_text_or_title() {
Some(&self.payload)
} else {
None
}
}
pub fn text(&self) -> String {
self.text_payload()
.map(decode_mac_roman)
.unwrap_or_default()
}
pub fn is_resource(&self) -> bool {
is_dialog_item_resource(self.item_type)
}
pub fn resource_type(&self) -> Option<[u8; 4]> {
dialog_item_resource_type(self.item_type)
}
pub fn resource_type_u32(&self) -> Option<u32> {
dialog_item_resource_type_u32(self.item_type)
}
pub fn resource_id(&self) -> Option<i16> {
if self.is_resource() && self.payload.len() >= 2 {
Some(i16::from_be_bytes([self.payload[0], self.payload[1]]))
} else {
None
}
}
pub fn is_hidden(&self) -> bool {
is_dialog_item_rect_hidden(self.rect)
}
pub fn offset_rect(&mut self, v_delta: i16, h_delta: i16) {
self.rect = offset_rect(self.rect, v_delta, h_delta);
}
pub fn enclosing_rect(&self) -> (i16, i16, i16, i16) {
dialog_item_enclosing_rect(self.item_type, self.rect)
}
}
#[inline]
fn read_be_i16(bytes: &[u8], offset: usize) -> Option<i16> {
let slice = bytes.get(offset..offset.checked_add(2)?)?;
Some(i16::from_be_bytes([slice[0], slice[1]]))
}
#[inline]
fn read_be_u32(bytes: &[u8], offset: usize) -> Option<u32> {
let slice = bytes.get(offset..offset.checked_add(4)?)?;
Some(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
}
pub fn ditl_item_payload_len(base_type: u8, data_len_byte: u8, remaining: usize) -> Option<usize> {
if is_dialog_item_resource(base_type) {
if remaining < 2 {
return None;
}
if data_len_byte >= 2 {
Some(usize::from(data_len_byte))
} else {
Some(2)
}
} else {
Some(usize::from(data_len_byte))
}
}
pub fn ditl_item_record_len_at(bytes: &[u8], record_offset: usize) -> Option<usize> {
if record_offset.checked_add(14)? > bytes.len() {
return None;
}
let item_type = *bytes.get(record_offset.checked_add(12)?)?;
let data_len_byte = *bytes.get(record_offset.checked_add(13)?)?;
let base_type = dialog_item_base_type(item_type);
let payload_offset = record_offset.checked_add(14)?;
let remaining = bytes.len().saturating_sub(payload_offset);
let payload_len = ditl_item_payload_len(base_type, data_len_byte, remaining)?;
let padded = (payload_len + 1) & !1;
if padded > remaining {
return None;
}
Some(14 + padded)
}
pub fn ditl_total_used_len(bytes: &[u8]) -> usize {
if bytes.len() < 2 {
return bytes.len();
}
let Some(count_minus_one) = read_be_i16(bytes, 0) else {
return bytes.len();
};
let count = if count_minus_one < 0 {
0
} else {
match usize::try_from(count_minus_one)
.ok()
.and_then(|c| c.checked_add(1))
{
Some(c) => c,
None => return bytes.len(),
}
};
let mut offset = 2usize;
for _ in 0..count {
let Some(record_len) = ditl_item_record_len_at(bytes, offset) else {
break;
};
offset = offset.saturating_add(record_len);
}
offset
}
pub fn parse_ditl_items(bytes: &[u8]) -> Option<Vec<DialogItemRecord>> {
let count_minus_one = read_be_i16(bytes, 0)?;
let count = if count_minus_one < 0 {
0
} else {
match usize::try_from(count_minus_one)
.ok()
.and_then(|c| c.checked_add(1))
{
Some(c) => c,
None => return None,
}
};
let mut offset = 2usize;
let mut items = Vec::with_capacity(count);
for _ in 0..count {
if offset + 14 > bytes.len() {
break;
}
let Some(handle) = read_be_u32(bytes, offset) else {
break;
};
let Some(top) = read_be_i16(bytes, offset + 4) else {
break;
};
let Some(left) = read_be_i16(bytes, offset + 6) else {
break;
};
let Some(bottom) = read_be_i16(bytes, offset + 8) else {
break;
};
let Some(right) = read_be_i16(bytes, offset + 10) else {
break;
};
let item_type = bytes[offset + 12];
let data_len_byte = bytes[offset + 13];
let base_type = dialog_item_base_type(item_type);
let payload_start = offset + 14;
let remaining = bytes.len().saturating_sub(payload_start);
let Some(payload_len) = ditl_item_payload_len(base_type, data_len_byte, remaining) else {
break;
};
let padded = (payload_len + 1) & !1;
if padded > remaining {
break;
}
let payload = bytes[payload_start..payload_start + payload_len].to_vec();
items.push(DialogItemRecord {
item_offset: offset,
item_type,
rect: (top, left, bottom, right),
handle,
payload,
});
offset = payload_start + padded;
}
Some(items)
}
pub fn position_dialog_bounds(
bounds: (i16, i16, i16, i16),
position: u16,
screen_width: i32,
screen_height: i32,
) -> (i16, i16, i16, i16) {
let centered = matches!(
position,
0x280a | 0x300a | 0x380a | 0xa80a | 0xb00a | 0xb80a
);
if !centered {
return bounds;
}
let height = i32::from(bounds.2) - i32::from(bounds.0);
let width = i32::from(bounds.3) - i32::from(bounds.1);
let top = (screen_height - height).max(0) / 2;
let left = (screen_width - width).max(0) / 2;
(
top.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
left.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
(top + height).clamp(i16::MIN as i32, i16::MAX as i32) as i16,
(left + width).clamp(i16::MIN as i32, i16::MAX as i32) as i16,
)
}
pub const DIALOG_ITEM_HIDDEN_OFFSET: i16 = 16384;
pub const DIALOG_ITEM_HIDDEN_THRESHOLD: i16 = 8192;
pub fn offset_rect(rect: (i16, i16, i16, i16), v_delta: i16, h_delta: i16) -> (i16, i16, i16, i16) {
(
rect.0.saturating_add(v_delta),
rect.1.saturating_add(h_delta),
rect.2.saturating_add(v_delta),
rect.3.saturating_add(h_delta),
)
}
pub fn dialog_rect_to_global(
bounds: (i16, i16, i16, i16),
rect: (i16, i16, i16, i16),
) -> (i16, i16, i16, i16) {
(
bounds.0.saturating_add(rect.0),
bounds.1.saturating_add(rect.1),
bounds.0.saturating_add(rect.2),
bounds.1.saturating_add(rect.3),
)
}
#[allow(dead_code)]
pub fn dialog_rect_to_local(
bounds: (i16, i16, i16, i16),
rect: (i16, i16, i16, i16),
) -> (i16, i16, i16, i16) {
(
rect.0.saturating_sub(bounds.0),
rect.1.saturating_sub(bounds.1),
rect.2.saturating_sub(bounds.0),
rect.3.saturating_sub(bounds.1),
)
}
#[inline]
pub const fn global_to_dialog_local_point(
bounds: (i16, i16, i16, i16),
screen_v: i16,
screen_h: i16,
) -> (i16, i16) {
(
screen_v.saturating_sub(bounds.0),
screen_h.saturating_sub(bounds.1),
)
}
#[allow(dead_code)]
#[inline]
pub const fn dialog_local_to_global_point(
bounds: (i16, i16, i16, i16),
local_v: i16,
local_h: i16,
) -> (i16, i16) {
(
bounds.0.saturating_add(local_v),
bounds.1.saturating_add(local_h),
)
}
pub fn rect_contains_point(rect: (i16, i16, i16, i16), v: i16, h: i16) -> bool {
v >= rect.0 && v < rect.2 && h >= rect.1 && h < rect.3
}
#[allow(dead_code)]
pub fn inset_rect(rect: (i16, i16, i16, i16), v_delta: i16, h_delta: i16) -> (i16, i16, i16, i16) {
(
rect.0.saturating_add(v_delta),
rect.1.saturating_add(h_delta),
rect.2.saturating_sub(v_delta),
rect.3.saturating_sub(h_delta),
)
}
pub fn outset_rect(rect: (i16, i16, i16, i16), v_delta: i16, h_delta: i16) -> (i16, i16, i16, i16) {
(
rect.0.saturating_sub(v_delta),
rect.1.saturating_sub(h_delta),
rect.2.saturating_add(v_delta),
rect.3.saturating_add(h_delta),
)
}
pub fn dialog_dbox_frame_rect(content_bounds: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
outset_rect(
content_bounds,
DIALOG_DBOX_FRAME_MARGIN,
DIALOG_DBOX_FRAME_MARGIN,
)
}
pub fn edit_text_frame_rect(item_rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
outset_rect(item_rect, EDIT_TEXT_FRAME_OUTSET, EDIT_TEXT_FRAME_OUTSET)
}
pub fn dialog_text_rect(item_rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
(
item_rect.0,
item_rect.1.saturating_add(DIALOG_TEXT_LEFT_INSET),
item_rect.2,
item_rect.3,
)
}
pub const fn dialog_item_base_type(raw_type: u8) -> u8 {
raw_type & !DIALOG_ITEM_DISABLED_FLAG
}
#[inline]
pub const fn is_dialog_item_disabled(raw_type: u8) -> bool {
(raw_type & DIALOG_ITEM_DISABLED_FLAG) != 0
}
#[inline]
pub const fn is_dialog_item_enabled(raw_type: u8) -> bool {
(raw_type & DIALOG_ITEM_DISABLED_FLAG) == 0
}
pub fn dialog_target_for_event<F>(
what: u16,
message: u32,
is_dialog: F,
front_dialog: Option<u32>,
) -> Option<u32>
where
F: FnOnce(u32) -> bool,
{
match what {
EVENT_UPDATE | EVENT_ACTIVATE => {
if is_dialog(message) {
Some(message)
} else {
None
}
}
_ => front_dialog,
}
}
pub fn is_dialog_item_rect_hidden(rect: (i16, i16, i16, i16)) -> bool {
rect.1 > DIALOG_ITEM_HIDDEN_THRESHOLD
}
pub fn hide_dialog_item_rect(rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
(
rect.0,
rect.1.wrapping_add(DIALOG_ITEM_HIDDEN_OFFSET),
rect.2,
rect.3.wrapping_add(DIALOG_ITEM_HIDDEN_OFFSET),
)
}
pub fn show_dialog_item_rect(rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
(
rect.0,
rect.1.wrapping_sub(DIALOG_ITEM_HIDDEN_OFFSET),
rect.2,
rect.3.wrapping_sub(DIALOG_ITEM_HIDDEN_OFFSET),
)
}
pub fn dialog_item_enclosing_rect(
item_type: u8,
rect: (i16, i16, i16, i16),
) -> (i16, i16, i16, i16) {
if is_dialog_item_edit_text(item_type) {
(
rect.0.saturating_sub(3),
rect.1.saturating_sub(3),
rect.2.saturating_add(3),
rect.3.saturating_add(3),
)
} else {
rect
}
}
pub fn find_dialog_item_at_local_point<'a>(
rects: impl IntoIterator<Item = &'a (i16, i16, i16, i16)>,
pt_v: i16,
pt_h: i16,
) -> Option<usize> {
for (idx, &rect) in rects.into_iter().enumerate() {
if rect_contains_point(rect, pt_v, pt_h) {
return Some(idx);
}
}
None
}
pub fn find_dialog_item_hit<I, F>(
items: I,
local_v: i16,
local_h: i16,
enabled_only: bool,
mut control_part_hit: F,
) -> Option<usize>
where
I: IntoIterator<Item = ((i16, i16, i16, i16), u8)>,
F: FnMut(usize) -> bool,
{
for (idx, (rect, raw_type)) in items.into_iter().enumerate() {
if enabled_only && is_dialog_item_disabled(raw_type) {
continue;
}
if !rect_contains_point(rect, local_v, local_h) {
continue;
}
if is_dialog_item_control(raw_type) && !control_part_hit(idx) {
continue;
}
return Some(idx);
}
None
}
#[allow(dead_code)]
pub fn find_dialog_item_at_global_point<I, F>(
bounds: (i16, i16, i16, i16),
screen_v: i16,
screen_h: i16,
items: I,
enabled_only: bool,
control_part_hit: F,
) -> Option<usize>
where
I: IntoIterator<Item = ((i16, i16, i16, i16), u8)>,
F: FnMut(usize) -> bool,
{
let (local_v, local_h) = global_to_dialog_local_point(bounds, screen_v, screen_h);
find_dialog_item_hit(items, local_v, local_h, enabled_only, control_part_hit)
}
pub fn offset_ditl_bytes(
bytes: &mut [u8],
item_offsets: impl IntoIterator<Item = usize>,
dv: i16,
dh: i16,
) {
if dv == 0 && dh == 0 {
return;
}
for item_offset in item_offsets {
for (coordinate_offset, delta) in [(4usize, dv), (6, dh), (8, dv), (10, dh)] {
let Some(start) = item_offset.checked_add(coordinate_offset) else {
continue;
};
let Some(pair) = bytes.get(start..start.saturating_add(2)) else {
continue;
};
let value = i16::from_be_bytes([pair[0], pair[1]]).saturating_add(delta);
if let Some(destination) = bytes.get_mut(start..start.saturating_add(2)) {
destination.copy_from_slice(&value.to_be_bytes());
}
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DialogTemplate {
pub bounds: (i16, i16, i16, i16),
pub proc_id: i16,
pub visible: bool,
pub go_away: bool,
pub ref_con: u32,
pub items_id: i16,
pub title: Vec<u8>,
pub position: u16,
}
impl DialogTemplate {
pub fn title_string(&self) -> String {
decode_mac_roman(&self.title)
}
}
pub fn parse_dialog_template(bytes: &[u8]) -> Option<DialogTemplate> {
if bytes.len() < 20 {
return None;
}
let bounds = (
i16::from_be_bytes(bytes.get(0..2)?.try_into().ok()?),
i16::from_be_bytes(bytes.get(2..4)?.try_into().ok()?),
i16::from_be_bytes(bytes.get(4..6)?.try_into().ok()?),
i16::from_be_bytes(bytes.get(6..8)?.try_into().ok()?),
);
let proc_id = i16::from_be_bytes(bytes.get(8..10)?.try_into().ok()?);
let visible = *bytes.get(10)? != 0;
let go_away = bytes.get(12).copied().unwrap_or(0) != 0;
let ref_con = bytes
.get(14..18)
.and_then(|slice| slice.try_into().ok())
.map(u32::from_be_bytes)
.unwrap_or(0);
let items_id = i16::from_be_bytes(bytes.get(18..20)?.try_into().ok()?);
let title_len = usize::from(bytes.get(20).copied().unwrap_or(0));
let title_start = 21.min(bytes.len());
let title_end = 21usize.saturating_add(title_len).min(bytes.len());
let title = bytes.get(title_start..title_end).unwrap_or(&[]).to_vec();
let nominal_title_end = 21usize.saturating_add(title_len);
let position_offset = (nominal_title_end + 1) & !1;
let position = bytes
.get(position_offset..position_offset.saturating_add(2))
.and_then(|value| value.try_into().ok())
.map(u16::from_be_bytes)
.unwrap_or(0);
Some(DialogTemplate {
bounds,
proc_id,
visible,
go_away,
ref_con,
items_id,
title,
position,
})
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AlertTemplate {
pub bounds: (i16, i16, i16, i16),
pub items_id: i16,
pub stages: u16,
pub position: u16,
}
pub fn parse_alert_template(bytes: &[u8]) -> Option<AlertTemplate> {
if bytes.len() < 8 {
return None;
}
let bounds = (
i16::from_be_bytes(bytes.get(0..2)?.try_into().ok()?),
i16::from_be_bytes(bytes.get(2..4)?.try_into().ok()?),
i16::from_be_bytes(bytes.get(4..6)?.try_into().ok()?),
i16::from_be_bytes(bytes.get(6..8)?.try_into().ok()?),
);
let items_id = bytes
.get(8..10)
.and_then(|slice| slice.try_into().ok())
.map(i16::from_be_bytes)
.unwrap_or(0);
let stages = bytes
.get(10..12)
.and_then(|slice| slice.try_into().ok())
.map(u16::from_be_bytes)
.unwrap_or(0);
let position = bytes
.get(12..14)
.and_then(|slice| slice.try_into().ok())
.map(u16::from_be_bytes)
.unwrap_or(0);
Some(AlertTemplate {
bounds,
items_id,
stages,
position,
})
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AlertStageInfo {
pub stage_index: u16,
pub stage_nibble: u8,
pub box_drawn: bool,
pub default_item: i16,
pub sound_number: u8,
}
pub fn alert_stage_info(stages: u16, stage_counter: u16) -> AlertStageInfo {
let stage_index = stage_counter.min(3);
let stage_nibble = ((stages >> (stage_index * 4)) & 0x0F) as u8;
let box_drawn = (stage_nibble & 0x04) != 0;
let default_item = if (stage_nibble & 0x08) == 0 { 1 } else { 2 };
let sound_number = stage_nibble & 0x03;
AlertStageInfo {
stage_index,
stage_nibble,
box_drawn,
default_item,
sound_number,
}
}
pub fn apply_param_text<'a>(text: &'a [u8], slots: &[impl AsRef<[u8]>]) -> Cow<'a, [u8]> {
if !text.contains(&b'^') {
return Cow::Borrowed(text);
}
let mut expanded = Vec::with_capacity(text.len());
let mut offset = 0;
while offset < text.len() {
if text[offset] == b'^' {
if let Some(index) = text
.get(offset + 1)
.copied()
.filter(u8::is_ascii_digit)
.map(|b| usize::from(b - b'0'))
.filter(|&idx| idx < slots.len())
{
expanded.extend_from_slice(slots[index].as_ref());
offset += 2;
continue;
}
}
expanded.push(text[offset]);
offset += 1;
}
Cow::Owned(expanded)
}
pub fn apply_param_text_str<'a, S: AsRef<[u8]>>(text: &'a str, slots: &[S]) -> Cow<'a, str> {
if !text.contains('^') {
return Cow::Borrowed(text);
}
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '^' {
if let Some(&next) = chars.peek() {
if let Some(digit) = next.to_digit(10) {
let idx = digit as usize;
if idx < slots.len() {
chars.next();
out.push_str(&decode_mac_roman(slots[idx].as_ref()));
continue;
}
}
}
}
out.push(ch);
}
Cow::Owned(out)
}
pub const KEY_RETURN: u8 = 0x24;
pub const KEY_NUMPAD_ENTER: u8 = 0x4C;
pub const KEY_ESCAPE: u8 = 0x35;
pub const KEY_TAB: u8 = 0x30;
pub const KEY_PERIOD: u8 = 0x2F;
pub const CHAR_RETURN: u8 = 0x0D;
pub const CHAR_ENTER: u8 = 0x03;
pub const CHAR_ESCAPE: u8 = 0x1B;
pub const CHAR_TAB: u8 = 0x09;
pub const CHAR_PERIOD: u8 = b'.';
pub const MODIFIER_CMD_KEY: u16 = 0x0100;
pub const EVENT_NULL: u16 = 0;
pub const EVENT_MOUSE_DOWN: u16 = 1;
#[allow(dead_code)]
pub const EVENT_MOUSE_UP: u16 = 2;
pub const EVENT_KEY_DOWN: u16 = 3;
#[allow(dead_code)]
pub const EVENT_KEY_UP: u16 = 4;
pub const EVENT_AUTO_KEY: u16 = 5;
pub const EVENT_UPDATE: u16 = 6;
#[allow(dead_code)]
pub const EVENT_DISK: u16 = 7;
pub const EVENT_ACTIVATE: u16 = 8;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DialogFilterDecision {
TriggerDefaultButton,
TriggerCancelButton,
AdvanceEditTextFocus,
Unhandled,
}
pub const fn is_dialog_default_key(char_code: u8, key_code: u8) -> bool {
matches!(char_code, CHAR_RETURN | CHAR_ENTER)
|| matches!(key_code, KEY_RETURN | KEY_NUMPAD_ENTER)
}
pub const fn is_dialog_cancel_key(char_code: u8, key_code: u8, modifiers: u16) -> bool {
char_code == CHAR_ESCAPE
|| key_code == KEY_ESCAPE
|| ((modifiers & MODIFIER_CMD_KEY) != 0
&& (char_code == CHAR_PERIOD || key_code == KEY_PERIOD))
}
pub const fn is_dialog_tab_key(char_code: u8, key_code: u8) -> bool {
char_code == CHAR_TAB || key_code == KEY_TAB
}
pub fn evaluate_modal_dialog_key(
event_what: u16,
message: u32,
modifiers: u16,
) -> DialogFilterDecision {
if !matches!(event_what, EVENT_KEY_DOWN | EVENT_AUTO_KEY) {
return DialogFilterDecision::Unhandled;
}
let char_code = (message & 0xFF) as u8;
let key_code = ((message >> 8) & 0xFF) as u8;
if is_dialog_default_key(char_code, key_code) {
DialogFilterDecision::TriggerDefaultButton
} else if is_dialog_cancel_key(char_code, key_code, modifiers) {
DialogFilterDecision::TriggerCancelButton
} else if is_dialog_tab_key(char_code, key_code) {
DialogFilterDecision::AdvanceEditTextFocus
} else {
DialogFilterDecision::Unhandled
}
}
pub fn find_next_edit_text_item(
item_types: impl IntoIterator<Item = u8>,
current_edit_item_1_indexed: usize,
) -> Option<usize> {
let types: Vec<u8> = item_types.into_iter().collect();
if types.is_empty() {
return None;
}
let start = current_edit_item_1_indexed;
for offset in 0..types.len() {
let idx = (start + offset) % types.len();
let base_type = dialog_item_base_type(types[idx]);
if base_type == DIALOG_ITEM_EDIT_TEXT {
return Some(idx + 1);
}
}
None
}
#[allow(dead_code)]
pub fn find_next_edit_text_in_items(
items: &[DialogItemRecord],
current_edit_item_1_indexed: usize,
) -> Option<usize> {
find_next_edit_text_item(
items.iter().map(|item| item.item_type),
current_edit_item_1_indexed,
)
}
#[allow(dead_code)]
pub fn clamp_dialog_item_text_len(len: usize) -> u8 {
len.min(255) as u8
}
pub fn clamp_dialog_item_text_bytes(text_bytes: &[u8]) -> &[u8] {
let len = text_bytes.len().min(255);
&text_bytes[..len]
}
#[allow(dead_code)]
pub fn clamp_dialog_item_text_str(text: &str) -> &str {
if text.len() <= 255 {
return text;
}
let mut boundary = 255;
while boundary > 0 && !text.is_char_boundary(boundary) {
boundary -= 1;
}
&text[..boundary]
}
pub fn encode_dialog_item_pstring(text_bytes: &[u8]) -> (u8, &[u8]) {
let clamped = clamp_dialog_item_text_bytes(text_bytes);
(clamped.len() as u8, clamped)
}
#[allow(dead_code)]
pub fn format_dialog_item_pstring(text_bytes: &[u8]) -> Vec<u8> {
let clamped = clamp_dialog_item_text_bytes(text_bytes);
let mut result = Vec::with_capacity(1 + clamped.len());
result.push(clamped.len() as u8);
result.extend_from_slice(clamped);
result
}
#[allow(dead_code)]
pub fn decode_dialog_item_pstring(bytes: &[u8]) -> Option<&[u8]> {
let &len = bytes.first()?;
let end = 1 + len as usize;
if bytes.len() >= end {
Some(&bytes[1..end])
} else {
None
}
}
#[allow(dead_code)]
pub fn decode_dialog_item_pstring_to_string(bytes: &[u8]) -> Option<String> {
decode_dialog_item_pstring(bytes).map(decode_mac_roman)
}
#[allow(dead_code)]
pub fn prepare_set_dialog_item_text(text_bytes: &[u8]) -> (&[u8], String) {
let clamped = clamp_dialog_item_text_bytes(text_bytes);
let decoded = decode_mac_roman(clamped);
(clamped, decoded)
}
#[allow(dead_code)]
pub fn prepare_get_dialog_item_text(text_bytes: &[u8]) -> (u8, &[u8]) {
encode_dialog_item_pstring(text_bytes)
}
pub fn extract_dialog_item_text_bytes<'a>(
base_type: u8,
handle_bytes: Option<&'a [u8]>,
fallback_payload: &'a [u8],
) -> &'a [u8] {
if let Some(bytes) = handle_bytes {
bytes
} else if is_dialog_item_text_or_title(base_type) {
fallback_payload
} else {
&[]
}
}
#[allow(dead_code)]
pub fn extract_dialog_item_text_string(
base_type: u8,
handle_bytes: Option<&[u8]>,
fallback_payload: &[u8],
) -> String {
decode_mac_roman(extract_dialog_item_text_bytes(
base_type,
handle_bytes,
fallback_payload,
))
}
pub fn get_item_at_1_indexed<T>(items: &[T], item_number_1_indexed: usize) -> Option<&T> {
item_number_1_indexed
.checked_sub(1)
.and_then(|idx| items.get(idx))
}
#[allow(dead_code)]
pub fn get_item_at_1_indexed_mut<T>(
items: &mut [T],
item_number_1_indexed: usize,
) -> Option<&mut T> {
item_number_1_indexed
.checked_sub(1)
.and_then(|idx| items.get_mut(idx))
}
pub const fn is_dialog_item_control(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_control()
}
pub const fn is_dialog_item_user_item(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_user_item()
}
pub const fn is_dialog_item_button(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_button()
}
pub const fn is_dialog_item_checkbox(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_checkbox()
}
pub const fn is_dialog_item_radio(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_radio()
}
pub const fn is_dialog_item_resource_control(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_resource_control()
}
pub const fn is_dialog_item_static_text(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_static_text()
}
pub const fn is_dialog_item_edit_text(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_edit_text()
}
pub const fn is_dialog_item_icon(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_icon()
}
pub const fn is_dialog_item_picture(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_picture()
}
pub const fn is_dialog_item_text(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_text()
}
pub const fn is_dialog_item_text_or_title(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).has_text_or_title()
}
pub const fn is_dialog_item_resource(raw_type: u8) -> bool {
DialogItemKind::from_raw_type(raw_type).is_resource()
}
pub const fn dialog_item_resource_type(raw_type: u8) -> Option<[u8; 4]> {
DialogItemKind::from_raw_type(raw_type).resource_type()
}
pub const fn dialog_item_resource_type_u32(raw_type: u8) -> Option<u32> {
DialogItemKind::from_raw_type(raw_type).resource_type_u32()
}
pub const DIALOG_ICON_SIZE: i16 = 32;
#[allow(dead_code)]
pub const DIALOG_SMALL_ICON_SIZE: i16 = 16;
#[allow(dead_code)]
#[inline]
pub const fn dialog_icon_rect(
item_rect: (i16, i16, i16, i16),
icon_width: i16,
icon_height: i16,
) -> (i16, i16, i16, i16) {
let (top, left, bottom, right) = item_rect;
let rect_w = right - left;
let rect_h = bottom - top;
let offset_x = (rect_w - icon_width) / 2;
let offset_y = (rect_h - icon_height) / 2;
let start_x = left + offset_x;
let start_y = top + offset_y;
(start_y, start_x, start_y + icon_height, start_x + icon_width)
}
#[allow(dead_code)]
#[inline]
pub const fn dialog_standard_icon_rect(item_rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
dialog_icon_rect(item_rect, DIALOG_ICON_SIZE, DIALOG_ICON_SIZE)
}
pub const fn is_dialog_item_disposable_text(raw_type: u8) -> bool {
is_dialog_item_text(raw_type)
}
pub const fn is_dialog_item_disposable_control(raw_type: u8) -> bool {
is_dialog_item_control(raw_type)
}
pub fn dialog_item_control_proc_id(item_type: u8) -> Option<i16> {
match dialog_item_base_type(item_type) {
DIALOG_ITEM_BUTTON => Some(0),
DIALOG_ITEM_CHECKBOX => Some(1),
DIALOG_ITEM_RADIO => Some(2),
_ => None,
}
}
#[allow(dead_code)]
pub fn alert_icon_id(alert_type: u16) -> Option<i16> {
match alert_type {
ALERT_TYPE_STOP => Some(0),
ALERT_TYPE_NOTE => Some(1),
ALERT_TYPE_CAUTION => Some(2),
_ => None,
}
}
pub fn next_alert_stage(current_stage: u16) -> u16 {
((current_stage as u32) + 1).min(3) as u16
}
#[inline]
pub fn normalize_selection_bounds(start: usize, end: usize, max_len: usize) -> (usize, usize) {
let s = start.min(max_len);
let e = end.min(max_len);
if s <= e {
(s, e)
} else {
(e, s)
}
}
pub fn normalize_dialog_item_selection(
start_sel: i16,
end_sel: i16,
text_len: usize,
) -> (u16, u16) {
let text_len = text_len.min(i16::MAX as usize);
if start_sel == 0 && (end_sel == -1 || end_sel == i16::MAX) {
(0, text_len as u16)
} else {
let (s, e) = normalize_selection_bounds(
start_sel.max(0) as usize,
end_sel.max(0) as usize,
text_len,
);
(s as u16, e as u16)
}
}
pub fn default_button_outline_geometry(
button_rect: (i16, i16, i16, i16),
) -> ((i16, i16, i16, i16), i16) {
let outer = (
button_rect.0.saturating_sub(DEFAULT_BUTTON_OUTLINE_INSET),
button_rect.1.saturating_sub(DEFAULT_BUTTON_OUTLINE_INSET),
button_rect.2.saturating_add(DEFAULT_BUTTON_OUTLINE_INSET),
button_rect.3.saturating_add(DEFAULT_BUTTON_OUTLINE_INSET),
);
let height = outer.2.saturating_sub(outer.0);
let oval = (height / 2 - 4).max(4);
(outer, oval)
}
pub fn is_dialog_cancel_button_title(title: &[u8]) -> bool {
title.eq_ignore_ascii_case(b"cancel")
}
#[allow(dead_code)]
pub fn is_dialog_cancel_button_title_str(title: &str) -> bool {
title.eq_ignore_ascii_case("cancel")
}
pub fn find_dialog_cancel_item_index<I, T>(items: I) -> Option<u16>
where
I: IntoIterator<Item = (u8, T)>,
T: AsRef<[u8]>,
{
items
.into_iter()
.enumerate()
.find_map(|(idx, (raw_type, title))| {
let is_enabled_button =
is_dialog_item_enabled(raw_type) && is_dialog_item_button(raw_type);
if is_enabled_button && is_dialog_cancel_button_title(title.as_ref()) {
u16::try_from(idx + 1).ok()
} else {
None
}
})
}
pub fn resolve_dialog_cancel_item<I, T>(configured_cancel: Option<i16>, items: I) -> i16
where
I: IntoIterator<Item = (u8, T)>,
T: AsRef<[u8]>,
{
if let Some(item) = configured_cancel {
if item > 0 {
return item;
}
}
find_dialog_cancel_item_index(items)
.map(|idx| idx as i16)
.unwrap_or(0)
}
pub fn resolve_modal_dialog_cancel_item<I, T>(configured_cancel: Option<i16>, items: I) -> i16
where
I: IntoIterator<Item = (u8, T)>,
T: AsRef<[u8]>,
{
let item = resolve_dialog_cancel_item(configured_cancel, items);
if item > 0 {
item
} else {
ALERT_BUTTON_CANCEL
}
}
pub fn resolve_dialog_default_item(configured_default: Option<i16>, item_count: usize) -> i16 {
if let Some(item) = configured_default {
if item > 0 {
return item;
}
}
if item_count >= 1 {
ALERT_BUTTON_OK
} else {
0
}
}
#[allow(dead_code)]
#[inline]
pub const fn is_dialog_default_button(item_no: i16, default_item: i16) -> bool {
item_no > 0 && item_no == default_item
}
#[allow(dead_code)]
#[inline]
pub const fn is_dialog_cancel_button(item_no: i16, cancel_item: i16) -> bool {
item_no > 0 && item_no == cancel_item
}
pub fn append_ditl_offset_delta<F>(
method: i16,
dialog_height: i16,
dialog_width: i16,
item_origin_lookup: F,
) -> (i16, i16)
where
F: FnOnce(usize) -> Option<(i16, i16)>,
{
match method {
APPEND_DITL_OVERLAY => (0, 0),
APPEND_DITL_RIGHT => (0, dialog_width),
APPEND_DITL_BOTTOM => (dialog_height, 0),
relative_item if relative_item < 0 => {
let item_no = usize::from(relative_item.unsigned_abs());
item_origin_lookup(item_no).unwrap_or((0, 0))
}
_ => (0, 0),
}
}
pub fn shorten_ditl_counts(current_count: usize, remove_count: usize) -> (usize, i16) {
let remove = remove_count.min(current_count);
let retained = current_count.saturating_sub(remove);
let count_minus_one = if retained == 0 {
-1
} else {
retained.saturating_sub(1).min(i16::MAX as usize) as i16
};
(retained, count_minus_one)
}
pub fn rects_intersect(a: (i16, i16, i16, i16), b: (i16, i16, i16, i16)) -> bool {
a.0 < b.2 && a.2 > b.0 && a.1 < b.3 && a.3 > b.1
}
pub fn dialog_item_intersects_bounds(
bounds: (i16, i16, i16, i16),
item_rect: (i16, i16, i16, i16),
) -> bool {
rects_intersect(dialog_rect_to_global(bounds, item_rect), bounds)
}
pub fn is_dialog_game_managed<I>(bounds: (i16, i16, i16, i16), items: I) -> bool
where
I: IntoIterator<Item = (u8, (i16, i16, i16, i16))>,
{
let mut has_visible_item = false;
for (item_type, item_rect) in items {
if !dialog_item_intersects_bounds(bounds, item_rect) {
continue;
}
has_visible_item = true;
if !is_dialog_item_user_item(item_type) {
return false;
}
}
has_visible_item
}
pub fn is_dialog_event(
what: u16,
message: u32,
where_v: i16,
where_h: i16,
target_dialog: Option<u32>,
dialog_bounds: Option<(i16, i16, i16, i16)>,
) -> bool {
let Some(dialog_ptr) = target_dialog else {
return false;
};
match what {
EVENT_UPDATE | EVENT_ACTIVATE => message == dialog_ptr,
EVENT_MOUSE_DOWN => {
dialog_bounds.is_some_and(|bounds| rect_contains_point(bounds, where_v, where_h))
}
_ => true,
}
}
pub fn is_dialog_edit_text_character(character: u8) -> bool {
matches!(character, 0x08 | 0x20..=0x7E)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DialogSelectAction {
NoAction,
Update { dialog: u32 },
Activate { dialog: u32 },
Idle { dialog: u32, edit_item: i16 },
ItemHit {
dialog: u32,
item_no: i16,
is_edit_text: bool,
is_resource_control: bool,
},
DisabledItemHit { dialog: u32, item_no: i16 },
KeyStroke {
dialog: u32,
edit_item: i16,
character: u8,
},
}
#[allow(dead_code)]
impl DialogSelectAction {
#[inline]
pub const fn is_handled(self) -> bool {
matches!(self, Self::ItemHit { .. } | Self::KeyStroke { .. })
}
#[inline]
pub const fn should_set_dialog_ptr(self) -> bool {
matches!(
self,
Self::Update { .. }
| Self::Activate { .. }
| Self::ItemHit { .. }
| Self::KeyStroke { .. }
)
}
#[inline]
pub const fn target_dialog(self) -> Option<u32> {
match self {
Self::NoAction => None,
Self::Update { dialog }
| Self::Activate { dialog }
| Self::Idle { dialog, .. }
| Self::ItemHit { dialog, .. }
| Self::DisabledItemHit { dialog, .. }
| Self::KeyStroke { dialog, .. } => Some(dialog),
}
}
#[inline]
pub const fn item_hit(self) -> Option<i16> {
match self {
Self::ItemHit { item_no, .. } => Some(item_no),
Self::KeyStroke { edit_item, .. } => Some(edit_item),
_ => None,
}
}
}
pub fn evaluate_dialog_select<F>(
what: u16,
message: u32,
where_v: i16,
where_h: i16,
target_dialog: Option<u32>,
dialog_bounds: Option<(i16, i16, i16, i16)>,
active_edit_item: Option<(i16, u8)>,
hit_test: F,
) -> DialogSelectAction
where
F: FnOnce(i16, i16) -> Option<(i16, u8)>,
{
let Some(dialog) = target_dialog else {
return DialogSelectAction::NoAction;
};
match what {
EVENT_UPDATE if message == dialog => DialogSelectAction::Update { dialog },
EVENT_ACTIVATE if message == dialog => DialogSelectAction::Activate { dialog },
EVENT_NULL => {
if let Some((edit_item, raw_type)) = active_edit_item {
if edit_item > 0
&& is_dialog_item_enabled(raw_type)
&& is_dialog_item_edit_text(raw_type)
{
return DialogSelectAction::Idle { dialog, edit_item };
}
}
DialogSelectAction::NoAction
}
EVENT_MOUSE_DOWN => {
let Some(bounds) = dialog_bounds else {
return DialogSelectAction::NoAction;
};
if !rect_contains_point(bounds, where_v, where_h) {
return DialogSelectAction::NoAction;
}
if let Some((item_no, raw_type)) = hit_test(where_v, where_h) {
if item_no > 0 {
if is_dialog_item_enabled(raw_type) {
return DialogSelectAction::ItemHit {
dialog,
item_no,
is_edit_text: is_dialog_item_edit_text(raw_type),
is_resource_control: is_dialog_item_resource_control(raw_type),
};
} else {
return DialogSelectAction::DisabledItemHit { dialog, item_no };
}
}
}
DialogSelectAction::NoAction
}
EVENT_KEY_DOWN | EVENT_AUTO_KEY => {
if let Some((edit_item, raw_type)) = active_edit_item {
if edit_item > 0
&& is_dialog_item_enabled(raw_type)
&& is_dialog_item_edit_text(raw_type)
{
let character = (message & 0xFF) as u8;
if is_dialog_edit_text_character(character) {
return DialogSelectAction::KeyStroke {
dialog,
edit_item,
character,
};
}
}
}
DialogSelectAction::NoAction
}
_ => DialogSelectAction::NoAction,
}
}
pub fn textedit_key_result(
existing: &[u8],
sel_start: usize,
sel_end: usize,
key: u8,
) -> (Vec<u8>, usize) {
let text_len = existing.len();
let s = sel_start.min(text_len);
let e = sel_end.min(text_len);
let (s, e) = if s > e { (e, s) } else { (s, e) };
if key == 0x08 {
if s != e {
let mut merged = Vec::with_capacity(text_len - (e - s));
merged.extend_from_slice(&existing[..s]);
merged.extend_from_slice(&existing[e..]);
return (merged, s);
}
if s > 0 {
let mut merged = Vec::with_capacity(text_len - 1);
merged.extend_from_slice(&existing[..s - 1]);
merged.extend_from_slice(&existing[s..]);
return (merged, s - 1);
}
return (existing.to_vec(), s);
}
let mut merged = Vec::with_capacity(s + 1 + text_len.saturating_sub(e));
merged.extend_from_slice(&existing[..s]);
merged.push(key);
merged.extend_from_slice(&existing[e..]);
(merged, s + 1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn item_kind_decoding_and_properties() {
assert_eq!(DialogItemKind::from_raw_type(4), DialogItemKind::Button);
assert_eq!(
DialogItemKind::from_raw_type(4 | DIALOG_ITEM_DISABLED_FLAG),
DialogItemKind::Button
);
assert!(DialogItemKind::Button.is_control());
assert!(!DialogItemKind::Button.is_text());
assert_eq!(DialogItemKind::from_raw_type(8), DialogItemKind::StaticText);
assert!(DialogItemKind::StaticText.is_text());
assert!(!DialogItemKind::StaticText.is_control());
assert_eq!(DialogItemKind::from_raw_type(16), DialogItemKind::EditText);
assert_eq!(DialogItemKind::from_raw_type(32), DialogItemKind::Icon);
assert_eq!(DialogItemKind::from_raw_type(64), DialogItemKind::Picture);
assert_eq!(DialogItemKind::from_raw_type(0), DialogItemKind::UserItem);
assert_eq!(
DialogItemKind::from_raw_type(99),
DialogItemKind::Unknown(99)
);
}
#[test]
fn parse_ditl_items_round_trip() {
let mut data = Vec::new();
data.extend_from_slice(&0i16.to_be_bytes());
data.extend_from_slice(&0u32.to_be_bytes());
data.extend_from_slice(&10i16.to_be_bytes());
data.extend_from_slice(&20i16.to_be_bytes());
data.extend_from_slice(&30i16.to_be_bytes());
data.extend_from_slice(&40i16.to_be_bytes());
data.push(DIALOG_ITEM_BUTTON);
data.push(2);
data.extend_from_slice(b"OK");
let items = parse_ditl_items(&data).expect("valid DITL");
assert_eq!(items.len(), 1);
assert_eq!(items[0].rect, (10, 20, 30, 40));
assert_eq!(items[0].kind(), DialogItemKind::Button);
assert!(items[0].is_enabled());
assert_eq!(items[0].text(), "OK");
}
#[test]
fn position_dialog_centering() {
let bounds = (0, 0, 100, 200);
let centered = position_dialog_bounds(bounds, 0x280a, 640, 480);
assert_eq!(centered, (190, 220, 290, 420));
let uncentered = position_dialog_bounds(bounds, 0x0000, 640, 480);
assert_eq!(uncentered, bounds);
}
#[test]
fn parse_ditl_items_empty_and_truncated() {
let mut empty_data = Vec::new();
empty_data.extend_from_slice(&(-1i16).to_be_bytes());
let empty_items = parse_ditl_items(&empty_data).expect("valid empty DITL");
assert!(empty_items.is_empty());
assert_eq!(ditl_total_used_len(&empty_data), 2);
let mut data = Vec::new();
data.extend_from_slice(&1i16.to_be_bytes()); data.extend_from_slice(&0u32.to_be_bytes());
data.extend_from_slice(&[0, 1, 0, 2, 0, 11, 0, 42]);
data.push(DIALOG_ITEM_BUTTON);
data.push(2);
data.extend_from_slice(b"OK");
data.extend_from_slice(&0u32.to_be_bytes());
data.extend_from_slice(&[0, 12, 0, 2, 0, 22, 0, 72]);
data.push(DIALOG_ITEM_STATIC_TEXT);
data.push(6);
data.extend_from_slice(b"Bad");
let items = parse_ditl_items(&data).expect("parses valid items before truncated one");
assert_eq!(items.len(), 1);
assert_eq!(items[0].text(), "OK");
}
#[test]
fn parse_ditl_items_resource_ids_and_record_lengths() {
let mut data = Vec::new();
data.extend_from_slice(&1i16.to_be_bytes()); data.extend_from_slice(&0u32.to_be_bytes());
data.extend_from_slice(&[0, 1, 0, 2, 0, 11, 0, 42]);
data.push(DIALOG_ITEM_RESOURCE_CONTROL);
data.push(0); data.extend_from_slice(&128i16.to_be_bytes());
data.extend_from_slice(&0u32.to_be_bytes());
data.extend_from_slice(&[0, 12, 0, 2, 0, 28, 0, 34]);
data.push(DIALOG_ITEM_ICON);
data.push(2); data.extend_from_slice(&(-42i16).to_be_bytes());
let len1 = ditl_item_record_len_at(&data, 2).expect("record 1 len");
assert_eq!(len1, 16);
let len2 = ditl_item_record_len_at(&data, 2 + len1).expect("record 2 len");
assert_eq!(len2, 16);
assert_eq!(ditl_total_used_len(&data), 2 + len1 + len2);
let items = parse_ditl_items(&data).expect("valid items");
assert_eq!(items.len(), 2);
assert_eq!(items[0].kind(), DialogItemKind::ResourceControl);
assert_eq!(items[0].resource_id(), Some(128));
assert_eq!(items[1].kind(), DialogItemKind::Icon);
assert_eq!(items[1].resource_id(), Some(-42));
}
#[test]
fn dialog_item_rect_geometry_and_visibility() {
let initial_rect = (10, 20, 30, 80);
let offset = offset_rect(initial_rect, 5, -10);
assert_eq!(offset, (15, 10, 35, 70));
let bounds = (100, 200, 300, 500);
let global = dialog_rect_to_global(bounds, initial_rect);
assert_eq!(global, (110, 220, 130, 280));
let local = dialog_rect_to_local(bounds, global);
assert_eq!(local, initial_rect);
assert!(!is_dialog_item_rect_hidden(initial_rect));
let hidden = hide_dialog_item_rect(initial_rect);
assert_eq!(hidden, (10, 16404, 30, 16464));
assert!(is_dialog_item_rect_hidden(hidden));
let shown = show_dialog_item_rect(hidden);
assert_eq!(shown, initial_rect);
assert_eq!(
dialog_item_enclosing_rect(DIALOG_ITEM_BUTTON, initial_rect),
initial_rect
);
assert_eq!(
dialog_item_enclosing_rect(DIALOG_ITEM_EDIT_TEXT, initial_rect),
(7, 17, 33, 83)
);
let mut record = DialogItemRecord {
item_offset: 2,
item_type: DIALOG_ITEM_EDIT_TEXT,
rect: initial_rect,
handle: 0,
payload: vec![],
};
assert!(!record.is_hidden());
assert_eq!(record.enclosing_rect(), (7, 17, 33, 83));
record.offset_rect(10, 20);
assert_eq!(record.rect, (20, 40, 40, 100));
}
#[test]
fn dialog_item_point_hit_testing_and_ditl_byte_offsetting() {
let rect1 = (10, 20, 30, 50);
let rect2 = (30, 20, 50, 50);
let rects = [rect1, rect2];
assert!(rect_contains_point(rect1, 10, 20));
assert!(rect_contains_point(rect1, 29, 49));
assert!(!rect_contains_point(rect1, 30, 20));
assert!(!rect_contains_point(rect1, 10, 50));
assert_eq!(find_dialog_item_at_local_point(&rects, 15, 25), Some(0));
assert_eq!(find_dialog_item_at_local_point(&rects, 35, 25), Some(1));
assert_eq!(find_dialog_item_at_local_point(&rects, 5, 5), None);
let mut data = Vec::new();
data.extend_from_slice(&0i16.to_be_bytes()); data.extend_from_slice(&0u32.to_be_bytes()); data.extend_from_slice(&10i16.to_be_bytes()); data.extend_from_slice(&20i16.to_be_bytes()); data.extend_from_slice(&30i16.to_be_bytes()); data.extend_from_slice(&40i16.to_be_bytes()); data.push(DIALOG_ITEM_BUTTON);
data.push(0);
offset_ditl_bytes(&mut data, [2], 5, 10);
assert_eq!(i16::from_be_bytes([data[6], data[7]]), 15);
assert_eq!(i16::from_be_bytes([data[8], data[9]]), 30);
assert_eq!(i16::from_be_bytes([data[10], data[11]]), 35);
assert_eq!(i16::from_be_bytes([data[12], data[13]]), 50);
}
#[test]
fn dialog_template_parsing_and_positioning() {
let mut dlog22 = Vec::new();
dlog22.extend_from_slice(&228i16.to_be_bytes()); dlog22.extend_from_slice(&198i16.to_be_bytes()); dlog22.extend_from_slice(&372i16.to_be_bytes()); dlog22.extend_from_slice(&455i16.to_be_bytes()); dlog22.extend_from_slice(&2i16.to_be_bytes()); dlog22.push(1); dlog22.push(0); dlog22.push(0); dlog22.push(0); dlog22.extend_from_slice(&0u32.to_be_bytes()); dlog22.extend_from_slice(&1013i16.to_be_bytes()); dlog22.push(0); dlog22.push(0);
let template = parse_dialog_template(&dlog22).expect("valid 22-byte dlog");
assert_eq!(template.bounds, (228, 198, 372, 455));
assert_eq!(template.proc_id, 2);
assert!(template.visible);
assert!(!template.go_away);
assert_eq!(template.ref_con, 0);
assert_eq!(template.items_id, 1013);
assert_eq!(template.title, b"");
assert_eq!(template.title_string(), "");
assert_eq!(template.position, 0);
let mut dlog24 = dlog22.clone();
dlog24.extend_from_slice(&0x280Au16.to_be_bytes());
let template = parse_dialog_template(&dlog24).expect("valid 24-byte dlog");
assert_eq!(template.position, 0x280A);
let mut dlog_odd = Vec::new();
dlog_odd.extend_from_slice(&10i16.to_be_bytes());
dlog_odd.extend_from_slice(&20i16.to_be_bytes());
dlog_odd.extend_from_slice(&110i16.to_be_bytes());
dlog_odd.extend_from_slice(&220i16.to_be_bytes());
dlog_odd.extend_from_slice(&1i16.to_be_bytes());
dlog_odd.push(1); dlog_odd.push(0);
dlog_odd.push(1); dlog_odd.push(0);
dlog_odd.extend_from_slice(&42u32.to_be_bytes());
dlog_odd.extend_from_slice(&701i16.to_be_bytes());
dlog_odd.push(3); dlog_odd.extend_from_slice(b"Odd");
dlog_odd.extend_from_slice(&0x300Au16.to_be_bytes());
let template = parse_dialog_template(&dlog_odd).expect("valid odd title dlog");
assert_eq!(template.title_string(), "Odd");
assert_eq!(template.items_id, 701);
assert_eq!(template.position, 0x300A);
assert!(template.go_away);
let mut dlog_even = Vec::new();
dlog_even.extend_from_slice(&11i16.to_be_bytes());
dlog_even.extend_from_slice(&21i16.to_be_bytes());
dlog_even.extend_from_slice(&111i16.to_be_bytes());
dlog_even.extend_from_slice(&221i16.to_be_bytes());
dlog_even.extend_from_slice(&1i16.to_be_bytes());
dlog_even.push(1);
dlog_even.push(0);
dlog_even.push(0);
dlog_even.push(0);
dlog_even.extend_from_slice(&0u32.to_be_bytes());
dlog_even.extend_from_slice(&702i16.to_be_bytes());
dlog_even.push(4); dlog_even.extend_from_slice(b"Even");
dlog_even.push(0); dlog_even.extend_from_slice(&0x700Au16.to_be_bytes());
let template = parse_dialog_template(&dlog_even).expect("valid even title dlog");
assert_eq!(template.title_string(), "Even");
assert_eq!(template.items_id, 702);
assert_eq!(template.position, 0x700A);
assert!(parse_dialog_template(&[0u8; 19]).is_none());
}
#[test]
fn alert_template_parsing_and_stages() {
let mut alrt12 = Vec::new();
alrt12.extend_from_slice(&10i16.to_be_bytes());
alrt12.extend_from_slice(&20i16.to_be_bytes());
alrt12.extend_from_slice(&90i16.to_be_bytes());
alrt12.extend_from_slice(&220i16.to_be_bytes());
alrt12.extend_from_slice(&123i16.to_be_bytes()); alrt12.extend_from_slice(&0x0008u16.to_be_bytes());
let alert = parse_alert_template(&alrt12).expect("valid 12-byte alrt");
assert_eq!(alert.bounds, (10, 20, 90, 220));
assert_eq!(alert.items_id, 123);
assert_eq!(alert.stages, 0x0008);
assert_eq!(alert.position, 0);
let mut alrt14 = Vec::new();
alrt14.extend_from_slice(&0i16.to_be_bytes());
alrt14.extend_from_slice(&0i16.to_be_bytes());
alrt14.extend_from_slice(&80i16.to_be_bytes());
alrt14.extend_from_slice(&200i16.to_be_bytes());
alrt14.extend_from_slice(&(-321i16).to_be_bytes()); alrt14.extend_from_slice(&0xF721u16.to_be_bytes()); alrt14.extend_from_slice(&0xB00Au16.to_be_bytes());
let alert = parse_alert_template(&alrt14).expect("valid 14-byte alrt");
assert_eq!(alert.items_id, -321);
assert_eq!(alert.stages, 0xF721);
assert_eq!(alert.position, 0xB00A);
let s0 = alert_stage_info(0xF721, 0);
assert_eq!(s0.stage_index, 0);
assert_eq!(s0.stage_nibble, 1);
assert!(!s0.box_drawn);
assert_eq!(s0.default_item, 1);
assert_eq!(s0.sound_number, 1);
let s1 = alert_stage_info(0xF721, 1);
assert_eq!(s1.stage_index, 1);
assert_eq!(s1.stage_nibble, 2);
assert!(!s1.box_drawn);
assert_eq!(s1.default_item, 1);
assert_eq!(s1.sound_number, 2);
let s2 = alert_stage_info(0xF721, 2);
assert_eq!(s2.stage_index, 2);
assert_eq!(s2.stage_nibble, 7);
assert!(s2.box_drawn);
assert_eq!(s2.default_item, 1);
assert_eq!(s2.sound_number, 3);
let s3 = alert_stage_info(0xF721, 3);
assert_eq!(s3.stage_index, 3);
assert_eq!(s3.stage_nibble, 0xF);
assert!(s3.box_drawn);
assert_eq!(s3.default_item, 2);
assert_eq!(s3.sound_number, 3);
let s_clamped = alert_stage_info(0xF721, 10);
assert_eq!(s_clamped, s3);
assert!(parse_alert_template(&[0u8; 7]).is_none());
}
#[test]
fn param_text_byte_and_str_substitution() {
let params: [Vec<u8>; 4] = [
b"first".to_vec(),
Vec::new(),
b"third".to_vec(),
b"fourth".to_vec(),
];
assert_eq!(
apply_param_text(b"^0/^1/^2/^3", ¶ms).as_ref(),
b"first//third/fourth"
);
assert_eq!(
apply_param_text(b"^^0 ^9 trailing^", ¶ms).as_ref(),
b"^first ^9 trailing^"
);
assert!(matches!(
apply_param_text(b"plain", ¶ms),
Cow::Borrowed(_)
));
let str_params: [Vec<u8>; 4] = [
b"MS UserKey".to_vec(),
b"42".to_vec(),
Vec::new(),
Vec::new(),
];
assert_eq!(
apply_param_text_str("Unable to open the \"^0\" file.", &str_params),
"Unable to open the \"MS UserKey\" file."
);
assert_eq!(apply_param_text_str("count: ^1", &str_params), "count: 42");
assert_eq!(
apply_param_text_str("plain text without placeholders", &str_params),
"plain text without placeholders"
);
assert_eq!(
apply_param_text_str("^0 ^1 ^2 ^3", &str_params),
"MS UserKey 42 "
);
assert_eq!(
apply_param_text_str("^A literal caret", &str_params),
"^A literal caret"
);
assert_eq!(apply_param_text_str("trailing^", &str_params), "trailing^");
assert_eq!(apply_param_text_str("^^0", &str_params), "^MS UserKey");
assert_eq!(apply_param_text_str("", &str_params), "");
}
#[test]
fn modal_dialog_keyboard_navigation_and_filter_evaluation() {
assert!(is_dialog_default_key(CHAR_RETURN, 0));
assert!(is_dialog_default_key(0, KEY_RETURN));
assert!(is_dialog_default_key(CHAR_ENTER, 0));
assert!(is_dialog_default_key(0, KEY_NUMPAD_ENTER));
assert!(!is_dialog_default_key(b'a', 0));
assert!(is_dialog_cancel_key(CHAR_ESCAPE, 0, 0));
assert!(is_dialog_cancel_key(0, KEY_ESCAPE, 0));
assert!(is_dialog_cancel_key(CHAR_PERIOD, 0, MODIFIER_CMD_KEY));
assert!(is_dialog_cancel_key(0, KEY_PERIOD, MODIFIER_CMD_KEY));
assert!(!is_dialog_cancel_key(CHAR_PERIOD, 0, 0));
assert!(is_dialog_tab_key(CHAR_TAB, 0));
assert!(is_dialog_tab_key(0, KEY_TAB));
assert!(!is_dialog_tab_key(b' ', 0));
let return_msg = (u32::from(KEY_RETURN) << 8) | u32::from(CHAR_RETURN);
assert_eq!(
evaluate_modal_dialog_key(EVENT_KEY_DOWN, return_msg, 0),
DialogFilterDecision::TriggerDefaultButton
);
assert_eq!(
evaluate_modal_dialog_key(EVENT_AUTO_KEY, return_msg, 0),
DialogFilterDecision::TriggerDefaultButton
);
let esc_msg = (u32::from(KEY_ESCAPE) << 8) | u32::from(CHAR_ESCAPE);
assert_eq!(
evaluate_modal_dialog_key(EVENT_KEY_DOWN, esc_msg, 0),
DialogFilterDecision::TriggerCancelButton
);
let cmd_period_msg = (u32::from(KEY_PERIOD) << 8) | u32::from(CHAR_PERIOD);
assert_eq!(
evaluate_modal_dialog_key(EVENT_KEY_DOWN, cmd_period_msg, MODIFIER_CMD_KEY),
DialogFilterDecision::TriggerCancelButton
);
assert_eq!(
evaluate_modal_dialog_key(EVENT_KEY_DOWN, cmd_period_msg, 0),
DialogFilterDecision::Unhandled
);
let tab_msg = (u32::from(KEY_TAB) << 8) | u32::from(CHAR_TAB);
assert_eq!(
evaluate_modal_dialog_key(EVENT_KEY_DOWN, tab_msg, 0),
DialogFilterDecision::AdvanceEditTextFocus
);
assert_eq!(
evaluate_modal_dialog_key(1, return_msg, 0),
DialogFilterDecision::Unhandled
);
}
#[test]
fn find_next_edit_text_item_cycling() {
assert_eq!(find_next_edit_text_item([], 0), None);
assert_eq!(
find_next_edit_text_item([DIALOG_ITEM_BUTTON, DIALOG_ITEM_STATIC_TEXT], 0),
None
);
let single = [
DIALOG_ITEM_BUTTON,
DIALOG_ITEM_EDIT_TEXT,
DIALOG_ITEM_STATIC_TEXT,
];
assert_eq!(find_next_edit_text_item(single, 0), Some(2));
assert_eq!(find_next_edit_text_item(single, 1), Some(2));
assert_eq!(find_next_edit_text_item(single, 2), Some(2));
assert_eq!(find_next_edit_text_item(single, 3), Some(2));
let multiple = [
DIALOG_ITEM_BUTTON, DIALOG_ITEM_EDIT_TEXT, DIALOG_ITEM_STATIC_TEXT, DIALOG_ITEM_EDIT_TEXT, ];
assert_eq!(find_next_edit_text_item(multiple, 0), Some(2));
assert_eq!(find_next_edit_text_item(multiple, 1), Some(2));
assert_eq!(find_next_edit_text_item(multiple, 2), Some(4));
assert_eq!(find_next_edit_text_item(multiple, 3), Some(4));
assert_eq!(find_next_edit_text_item(multiple, 4), Some(2));
let disabled_edit = [
DIALOG_ITEM_BUTTON,
DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG,
];
assert_eq!(find_next_edit_text_item(disabled_edit, 0), Some(2));
let item_records = [
DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_BUTTON,
rect: (0, 0, 0, 0),
handle: 0,
payload: vec![],
},
DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_EDIT_TEXT,
rect: (0, 0, 0, 0),
handle: 0,
payload: vec![],
},
];
assert_eq!(find_next_edit_text_in_items(&item_records, 0), Some(2));
assert_eq!(find_next_edit_text_in_items(&item_records, 2), Some(2));
}
#[test]
fn dialog_item_text_and_query_operations() {
assert_eq!(clamp_dialog_item_text_len(10), 10);
assert_eq!(clamp_dialog_item_text_len(300), 255);
let short_bytes = b"Hello world";
assert_eq!(clamp_dialog_item_text_bytes(short_bytes), short_bytes);
let long_bytes = vec![b'A'; 300];
let clamped = clamp_dialog_item_text_bytes(&long_bytes);
assert_eq!(clamped.len(), 255);
assert_eq!(clamped, &long_bytes[..255]);
let (len, text) = encode_dialog_item_pstring(b"Test");
assert_eq!(len, 4);
assert_eq!(text, b"Test");
let mut pstr = vec![4];
pstr.extend_from_slice(b"Test");
assert_eq!(decode_dialog_item_pstring(&pstr), Some(&b"Test"[..]));
assert_eq!(decode_dialog_item_pstring(&[]), None);
assert_eq!(decode_dialog_item_pstring(&[10, 1, 2]), None);
let mut items = vec!["First", "Second", "Third"];
assert_eq!(get_item_at_1_indexed(&items, 0), None);
assert_eq!(get_item_at_1_indexed(&items, 1), Some(&"First"));
assert_eq!(get_item_at_1_indexed(&items, 2), Some(&"Second"));
assert_eq!(get_item_at_1_indexed(&items, 3), Some(&"Third"));
assert_eq!(get_item_at_1_indexed(&items, 4), None);
*get_item_at_1_indexed_mut(&mut items, 2).unwrap() = "Modified";
assert_eq!(items[1], "Modified");
assert_eq!(get_item_at_1_indexed_mut(&mut items, 0), None);
assert_eq!(get_item_at_1_indexed_mut(&mut items, 99), None);
assert!(is_dialog_item_control(DIALOG_ITEM_BUTTON));
assert!(is_dialog_item_control(
DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG
));
assert!(is_dialog_item_control(DIALOG_ITEM_CHECKBOX));
assert!(is_dialog_item_control(DIALOG_ITEM_RADIO));
assert!(is_dialog_item_control(DIALOG_ITEM_RESOURCE_CONTROL));
assert!(!is_dialog_item_control(DIALOG_ITEM_STATIC_TEXT));
assert!(!is_dialog_item_control(DIALOG_ITEM_EDIT_TEXT));
assert!(!is_dialog_item_control(DIALOG_ITEM_ICON));
assert!(is_dialog_item_text(DIALOG_ITEM_STATIC_TEXT));
assert!(is_dialog_item_text(DIALOG_ITEM_EDIT_TEXT));
assert!(is_dialog_item_text(
DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG
));
assert!(!is_dialog_item_text(DIALOG_ITEM_BUTTON));
assert!(!is_dialog_item_text(DIALOG_ITEM_ICON));
assert!(is_dialog_item_text_or_title(DIALOG_ITEM_STATIC_TEXT));
assert!(is_dialog_item_text_or_title(DIALOG_ITEM_EDIT_TEXT));
assert!(is_dialog_item_text_or_title(DIALOG_ITEM_BUTTON));
assert!(is_dialog_item_text_or_title(DIALOG_ITEM_CHECKBOX));
assert!(is_dialog_item_text_or_title(DIALOG_ITEM_RADIO));
assert!(!is_dialog_item_text_or_title(DIALOG_ITEM_RESOURCE_CONTROL));
assert!(!is_dialog_item_text_or_title(DIALOG_ITEM_ICON));
assert!(!is_dialog_item_text_or_title(DIALOG_ITEM_PICTURE));
assert!(!is_dialog_item_text_or_title(DIALOG_ITEM_USER_ITEM));
let short_str = "Dialog item text";
assert_eq!(clamp_dialog_item_text_str(short_str), short_str);
let long_str = "a".repeat(300);
let clamped_str = clamp_dialog_item_text_str(&long_str);
assert_eq!(clamped_str.len(), 255);
let pstr_formatted = format_dialog_item_pstring(b"Sample");
assert_eq!(pstr_formatted[0], 6);
assert_eq!(&pstr_formatted[1..], b"Sample");
assert_eq!(
decode_dialog_item_pstring_to_string(&pstr_formatted),
Some("Sample".to_string())
);
let (set_bytes, set_string) = prepare_set_dialog_item_text(b"Config");
assert_eq!(set_bytes, b"Config");
assert_eq!(set_string, "Config");
let (get_len, get_bytes) = prepare_get_dialog_item_text(b"Result");
assert_eq!(get_len, 6);
assert_eq!(get_bytes, b"Result");
let payload = b"Default text";
let handle_override = b"Active handle text";
assert_eq!(
extract_dialog_item_text_bytes(DIALOG_ITEM_EDIT_TEXT, Some(handle_override), payload),
handle_override
);
assert_eq!(
extract_dialog_item_text_bytes(DIALOG_ITEM_EDIT_TEXT, None, payload),
payload
);
assert_eq!(
extract_dialog_item_text_bytes(DIALOG_ITEM_BUTTON, None, b"Cancel"),
b"Cancel"
);
assert_eq!(
extract_dialog_item_text_bytes(DIALOG_ITEM_ICON, None, &[0x00, 0x80]),
b""
);
assert_eq!(
extract_dialog_item_text_string(DIALOG_ITEM_STATIC_TEXT, None, b"Info"),
"Info"
);
let text_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_STATIC_TEXT,
rect: (0, 0, 10, 50),
handle: 0,
payload: b"Hello".to_vec(),
};
assert!(text_record.has_text_or_title());
assert_eq!(text_record.text_payload(), Some(&b"Hello"[..]));
assert_eq!(text_record.text(), "Hello");
let icon_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_ICON,
rect: (0, 0, 32, 32),
handle: 0,
payload: vec![0x00, 0x80],
};
assert!(!icon_record.has_text_or_title());
assert_eq!(icon_record.text_payload(), None);
assert_eq!(icon_record.text(), "");
assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_BUTTON), Some(0));
assert_eq!(
dialog_item_control_proc_id(DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG),
Some(0)
);
assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_CHECKBOX), Some(1));
assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_RADIO), Some(2));
assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_STATIC_TEXT), None);
assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_ICON), None);
}
#[test]
fn dialog_item_resource_mapping_and_geometry() {
assert!(is_dialog_item_resource(DIALOG_ITEM_RESOURCE_CONTROL));
assert!(is_dialog_item_resource(DIALOG_ITEM_ICON));
assert!(is_dialog_item_resource(DIALOG_ITEM_PICTURE));
assert!(is_dialog_item_resource(
DIALOG_ITEM_RESOURCE_CONTROL | DIALOG_ITEM_DISABLED_FLAG
));
assert!(is_dialog_item_resource(
DIALOG_ITEM_ICON | DIALOG_ITEM_DISABLED_FLAG
));
assert!(is_dialog_item_resource(
DIALOG_ITEM_PICTURE | DIALOG_ITEM_DISABLED_FLAG
));
assert!(!is_dialog_item_resource(DIALOG_ITEM_USER_ITEM));
assert!(!is_dialog_item_resource(DIALOG_ITEM_BUTTON));
assert!(!is_dialog_item_resource(DIALOG_ITEM_CHECKBOX));
assert!(!is_dialog_item_resource(DIALOG_ITEM_RADIO));
assert!(!is_dialog_item_resource(DIALOG_ITEM_STATIC_TEXT));
assert!(!is_dialog_item_resource(DIALOG_ITEM_EDIT_TEXT));
assert!(!is_dialog_item_resource(99));
assert_eq!(
dialog_item_resource_type(DIALOG_ITEM_RESOURCE_CONTROL),
Some(*b"CNTL")
);
assert_eq!(
dialog_item_resource_type(DIALOG_ITEM_RESOURCE_CONTROL | DIALOG_ITEM_DISABLED_FLAG),
Some(*b"CNTL")
);
assert_eq!(dialog_item_resource_type(DIALOG_ITEM_ICON), Some(*b"ICON"));
assert_eq!(
dialog_item_resource_type(DIALOG_ITEM_ICON | DIALOG_ITEM_DISABLED_FLAG),
Some(*b"ICON")
);
assert_eq!(
dialog_item_resource_type(DIALOG_ITEM_PICTURE),
Some(*b"PICT")
);
assert_eq!(
dialog_item_resource_type(DIALOG_ITEM_PICTURE | DIALOG_ITEM_DISABLED_FLAG),
Some(*b"PICT")
);
assert_eq!(dialog_item_resource_type(DIALOG_ITEM_STATIC_TEXT), None);
assert_eq!(dialog_item_resource_type(DIALOG_ITEM_BUTTON), None);
assert_eq!(
dialog_item_resource_type_u32(DIALOG_ITEM_RESOURCE_CONTROL),
Some(u32::from_be_bytes(*b"CNTL"))
);
assert_eq!(
dialog_item_resource_type_u32(DIALOG_ITEM_ICON),
Some(u32::from_be_bytes(*b"ICON"))
);
assert_eq!(
dialog_item_resource_type_u32(DIALOG_ITEM_PICTURE),
Some(u32::from_be_bytes(*b"PICT"))
);
assert_eq!(
dialog_item_resource_type_u32(DIALOG_ITEM_STATIC_TEXT),
None
);
let res_control_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_RESOURCE_CONTROL,
rect: (10, 10, 30, 80),
handle: 0,
payload: 128i16.to_be_bytes().to_vec(),
};
assert!(res_control_record.is_resource());
assert_eq!(res_control_record.resource_type(), Some(*b"CNTL"));
assert_eq!(
res_control_record.resource_type_u32(),
Some(u32::from_be_bytes(*b"CNTL"))
);
assert_eq!(res_control_record.resource_id(), Some(128));
let icon_record = DialogItemRecord {
item_offset: 16,
item_type: DIALOG_ITEM_ICON | DIALOG_ITEM_DISABLED_FLAG,
rect: (20, 20, 52, 52),
handle: 0,
payload: (-42i16).to_be_bytes().to_vec(),
};
assert!(icon_record.is_resource());
assert_eq!(icon_record.resource_type(), Some(*b"ICON"));
assert_eq!(
icon_record.resource_type_u32(),
Some(u32::from_be_bytes(*b"ICON"))
);
assert_eq!(icon_record.resource_id(), Some(-42));
let pict_record = DialogItemRecord {
item_offset: 32,
item_type: DIALOG_ITEM_PICTURE,
rect: (0, 0, 100, 100),
handle: 0,
payload: 1024i16.to_be_bytes().to_vec(),
};
assert!(pict_record.is_resource());
assert_eq!(pict_record.resource_type(), Some(*b"PICT"));
assert_eq!(
pict_record.resource_type_u32(),
Some(u32::from_be_bytes(*b"PICT"))
);
assert_eq!(pict_record.resource_id(), Some(1024));
let short_icon_record = DialogItemRecord {
item_offset: 48,
item_type: DIALOG_ITEM_ICON,
rect: (0, 0, 32, 32),
handle: 0,
payload: vec![1],
};
assert!(short_icon_record.is_resource());
assert_eq!(short_icon_record.resource_id(), None);
let text_record = DialogItemRecord {
item_offset: 64,
item_type: DIALOG_ITEM_STATIC_TEXT,
rect: (0, 0, 16, 100),
handle: 0,
payload: b"OK".to_vec(),
};
assert!(!text_record.is_resource());
assert_eq!(text_record.resource_type(), None);
assert_eq!(text_record.resource_type_u32(), None);
assert_eq!(text_record.resource_id(), None);
assert_eq!(DIALOG_ICON_SIZE, 32);
assert_eq!(DIALOG_SMALL_ICON_SIZE, 16);
assert_eq!(
dialog_standard_icon_rect((10, 20, 42, 52)),
(10, 20, 42, 52)
);
assert_eq!(
dialog_standard_icon_rect((0, 0, 40, 50)),
(4, 9, 36, 41)
);
assert_eq!(
dialog_icon_rect(
(10, 10, 30, 30),
DIALOG_SMALL_ICON_SIZE,
DIALOG_SMALL_ICON_SIZE
),
(12, 12, 28, 28)
);
}
#[test]
fn dialog_selection_normalization_and_alert_helpers() {
assert_eq!(normalize_dialog_item_selection(0, -1, 10), (0, 10));
assert_eq!(normalize_dialog_item_selection(0, i16::MAX, 10), (0, 10));
assert_eq!(normalize_dialog_item_selection(0, -1, 0), (0, 0));
assert_eq!(normalize_dialog_item_selection(2, 5, 10), (2, 5));
assert_eq!(normalize_dialog_item_selection(0, 0, 10), (0, 0));
assert_eq!(normalize_dialog_item_selection(10, 10, 10), (10, 10));
assert_eq!(normalize_dialog_item_selection(-5, 20, 10), (0, 10));
assert_eq!(normalize_dialog_item_selection(15, 20, 10), (10, 10));
assert_eq!(normalize_dialog_item_selection(7, 3, 10), (3, 7));
assert_eq!(normalize_dialog_item_selection(12, -2, 10), (0, 10));
assert_eq!(alert_icon_id(ALERT_TYPE_STOP), Some(0));
assert_eq!(alert_icon_id(ALERT_TYPE_NOTE), Some(1));
assert_eq!(alert_icon_id(ALERT_TYPE_CAUTION), Some(2));
assert_eq!(alert_icon_id(ALERT_TYPE_PLAIN), None);
assert_eq!(alert_icon_id(999), None);
assert_eq!(ALERT_BUTTON_OK, 1);
assert_eq!(ALERT_BUTTON_CANCEL, 2);
assert_eq!(ALERT_BUTTON_OTHER, 3);
assert_eq!(ALERT_BUTTON_HELP, 4);
assert_eq!(next_alert_stage(0), 1);
assert_eq!(next_alert_stage(1), 2);
assert_eq!(next_alert_stage(2), 3);
assert_eq!(next_alert_stage(3), 3);
assert_eq!(next_alert_stage(10), 3);
assert!(is_dialog_item_disposable_text(DIALOG_ITEM_STATIC_TEXT));
assert!(is_dialog_item_disposable_text(DIALOG_ITEM_EDIT_TEXT));
assert!(is_dialog_item_disposable_text(
DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG
));
assert!(!is_dialog_item_disposable_text(DIALOG_ITEM_BUTTON));
assert!(!is_dialog_item_disposable_text(DIALOG_ITEM_ICON));
assert!(is_dialog_item_disposable_control(DIALOG_ITEM_BUTTON));
assert!(is_dialog_item_disposable_control(DIALOG_ITEM_CHECKBOX));
assert!(is_dialog_item_disposable_control(DIALOG_ITEM_RADIO));
assert!(is_dialog_item_disposable_control(
DIALOG_ITEM_RESOURCE_CONTROL
));
assert!(is_dialog_item_disposable_control(
DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG
));
assert!(!is_dialog_item_disposable_control(DIALOG_ITEM_STATIC_TEXT));
assert!(!is_dialog_item_disposable_control(DIALOG_ITEM_ICON));
}
#[test]
fn dialog_dispatch_button_geometry_and_cancel_detection() {
assert_eq!(DIALOG_WINDOW_KIND_OFFSET, 108);
assert_eq!(DIALOG_WINDOW_KIND, 2);
assert_eq!(DIALOG_GO_AWAY_FLAG_OFFSET, 112);
assert_eq!(DIALOG_DISPATCH_NEW_COLOR_DIALOG, 0x0000);
assert_eq!(DIALOG_DISPATCH_GET_STD_FILTER_PROC, 0x0003);
assert_eq!(DIALOG_DISPATCH_SET_DIALOG_DEFAULT_ITEM, 0x0004);
assert_eq!(DIALOG_DISPATCH_SET_DIALOG_CANCEL_ITEM, 0x0005);
assert_eq!(DIALOG_DISPATCH_SET_DIALOG_TRACKS_CURSOR, 0x0006);
assert_eq!(DIALOG_DISPATCH_NEW_FEATURES_DIALOG, 0x000C);
assert_eq!(DEFAULT_BUTTON_OUTLINE_THICKNESS, 3);
assert_eq!(DEFAULT_BUTTON_OUTLINE_INSET, 4);
let button_rect = (50, 100, 70, 160);
let (outer, oval) = default_button_outline_geometry(button_rect);
assert_eq!(outer, (46, 96, 74, 164));
assert_eq!(oval, 10);
assert!(is_dialog_cancel_button_title(b"Cancel"));
assert!(is_dialog_cancel_button_title(b"cancel"));
assert!(is_dialog_cancel_button_title(b"CANCEL"));
assert!(!is_dialog_cancel_button_title(b"OK"));
assert!(!is_dialog_cancel_button_title(b""));
assert!(is_dialog_cancel_button_title_str("Cancel"));
assert!(is_dialog_cancel_button_title_str("cancel"));
assert!(!is_dialog_cancel_button_title_str("Dismiss"));
let items: Vec<(u8, &str)> = vec![
(DIALOG_ITEM_BUTTON, "OK"),
(DIALOG_ITEM_BUTTON, "Cancel"),
(DIALOG_ITEM_STATIC_TEXT, "Cancel"),
];
assert_eq!(
find_dialog_cancel_item_index(items.iter().copied()),
Some(2)
);
let items_disabled: Vec<(u8, &str)> = vec![
(DIALOG_ITEM_BUTTON, "OK"),
(DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG, "Cancel"),
];
assert_eq!(
find_dialog_cancel_item_index(items_disabled.iter().copied()),
None
);
let items_no_cancel: Vec<(u8, &str)> =
vec![(DIALOG_ITEM_BUTTON, "OK"), (DIALOG_ITEM_BUTTON, "Help")];
assert_eq!(
find_dialog_cancel_item_index(items_no_cancel.iter().copied()),
None
);
assert_eq!(
resolve_dialog_cancel_item(Some(3), items.iter().copied()),
3
);
assert_eq!(
resolve_dialog_cancel_item(Some(0), items.iter().copied()),
2
);
assert_eq!(
resolve_dialog_cancel_item(None, items.iter().copied()),
2
);
assert_eq!(
resolve_dialog_cancel_item(None, items_no_cancel.iter().copied()),
0
);
assert_eq!(
resolve_modal_dialog_cancel_item(Some(4), items.iter().copied()),
4
);
assert_eq!(
resolve_modal_dialog_cancel_item(None, items.iter().copied()),
2
);
assert_eq!(
resolve_modal_dialog_cancel_item(None, items_no_cancel.iter().copied()),
ALERT_BUTTON_CANCEL
);
assert_eq!(resolve_dialog_default_item(Some(3), 5), 3);
assert_eq!(resolve_dialog_default_item(Some(0), 5), 1);
assert_eq!(resolve_dialog_default_item(None, 5), 1);
assert_eq!(resolve_dialog_default_item(None, 0), 0);
assert!(is_dialog_default_button(1, 1));
assert!(!is_dialog_default_button(2, 1));
assert!(!is_dialog_default_button(0, 0));
assert!(!is_dialog_default_button(-1, -1));
assert!(is_dialog_cancel_button(2, 2));
assert!(!is_dialog_cancel_button(1, 2));
assert!(!is_dialog_cancel_button(0, 0));
assert!(!is_dialog_cancel_button(-1, -1));
}
#[test]
fn append_and_shorten_ditl_operations_and_game_managed_check() {
assert_eq!(APPEND_DITL_OVERLAY, 0);
assert_eq!(APPEND_DITL_RIGHT, 1);
assert_eq!(APPEND_DITL_BOTTOM, 2);
let height = 200;
let width = 300;
let item_origins = [(20, 30), (50, 60)];
assert_eq!(
append_ditl_offset_delta(APPEND_DITL_OVERLAY, height, width, |_| None),
(0, 0)
);
assert_eq!(
append_ditl_offset_delta(APPEND_DITL_RIGHT, height, width, |_| None),
(0, 300)
);
assert_eq!(
append_ditl_offset_delta(APPEND_DITL_BOTTOM, height, width, |_| None),
(200, 0)
);
assert_eq!(
append_ditl_offset_delta(-1, height, width, |idx| item_origins.get(idx - 1).copied()),
(20, 30)
);
assert_eq!(
append_ditl_offset_delta(-2, height, width, |idx| item_origins.get(idx - 1).copied()),
(50, 60)
);
assert_eq!(
append_ditl_offset_delta(-3, height, width, |idx| item_origins.get(idx - 1).copied()),
(0, 0)
);
assert_eq!(shorten_ditl_counts(10, 3), (7, 6));
assert_eq!(shorten_ditl_counts(5, 5), (0, -1));
assert_eq!(shorten_ditl_counts(5, 10), (0, -1));
assert_eq!(shorten_ditl_counts(0, 2), (0, -1));
let r1 = (10, 10, 50, 50);
let r2 = (20, 20, 60, 60);
let r3 = (60, 60, 100, 100);
let r4 = (50, 50, 100, 100);
assert!(rects_intersect(r1, r2));
assert!(!rects_intersect(r1, r3));
assert!(!rects_intersect(r1, r4));
let bounds = (100, 100, 300, 400);
assert!(dialog_item_intersects_bounds(bounds, (10, 10, 50, 50)));
assert!(!dialog_item_intersects_bounds(bounds, (300, 10, 350, 50)));
let all_user = vec![
(DIALOG_ITEM_USER_ITEM, (10, 10, 50, 50)),
(DIALOG_ITEM_USER_ITEM, (60, 60, 100, 100)),
];
assert!(is_dialog_game_managed(bounds, all_user));
let with_button = vec![
(DIALOG_ITEM_USER_ITEM, (10, 10, 50, 50)),
(DIALOG_ITEM_BUTTON, (60, 60, 100, 100)),
];
assert!(!is_dialog_game_managed(bounds, with_button));
let button_offscreen = vec![
(DIALOG_ITEM_USER_ITEM, (10, 10, 50, 50)),
(DIALOG_ITEM_BUTTON, (300, 300, 350, 350)),
];
assert!(is_dialog_game_managed(bounds, button_offscreen));
let empty: Vec<(u8, (i16, i16, i16, i16))> = vec![];
assert!(!is_dialog_game_managed(bounds, empty));
}
#[test]
fn dialog_event_classification_and_textedit_key_processing() {
let dialog = 0x2000;
let bounds = (50, 50, 200, 300);
assert!(!is_dialog_event(
EVENT_UPDATE,
dialog,
0,
0,
None,
Some(bounds)
));
assert!(!is_dialog_event(
EVENT_MOUSE_DOWN,
0,
100,
100,
None,
Some(bounds)
));
assert!(is_dialog_event(
EVENT_UPDATE,
dialog,
0,
0,
Some(dialog),
Some(bounds)
));
assert!(!is_dialog_event(
EVENT_UPDATE,
0x9999,
0,
0,
Some(dialog),
Some(bounds)
));
assert!(is_dialog_event(
EVENT_ACTIVATE,
dialog,
0,
0,
Some(dialog),
Some(bounds)
));
assert!(!is_dialog_event(
EVENT_ACTIVATE,
0x1111,
0,
0,
Some(dialog),
Some(bounds)
));
assert!(is_dialog_event(
EVENT_MOUSE_DOWN,
0,
100,
100,
Some(dialog),
Some(bounds)
));
assert!(!is_dialog_event(
EVENT_MOUSE_DOWN,
0,
10,
10,
Some(dialog),
Some(bounds)
));
assert!(!is_dialog_event(
EVENT_MOUSE_DOWN,
0,
100,
100,
Some(dialog),
None
));
assert!(is_dialog_event(
EVENT_KEY_DOWN,
b'a' as u32,
0,
0,
Some(dialog),
Some(bounds)
));
assert!(is_dialog_event(
EVENT_AUTO_KEY,
b'a' as u32,
0,
0,
Some(dialog),
Some(bounds)
));
assert!(is_dialog_event(
EVENT_NULL,
0,
0,
0,
Some(dialog),
Some(bounds)
));
assert!(is_dialog_edit_text_character(0x08)); assert!(is_dialog_edit_text_character(b' ')); assert!(is_dialog_edit_text_character(b'A'));
assert!(is_dialog_edit_text_character(b'~')); assert!(!is_dialog_edit_text_character(0x00)); assert!(!is_dialog_edit_text_character(0x0D)); assert!(!is_dialog_edit_text_character(0x1B)); assert!(!is_dialog_edit_text_character(0x7F)); assert!(!is_dialog_edit_text_character(0x80));
let initial = b"Hello World";
let (res, caret) = textedit_key_result(initial, 5, 5, b',');
assert_eq!(res, b"Hello, World");
assert_eq!(caret, 6);
let (res, caret) = textedit_key_result(initial, 5, 11, b'!');
assert_eq!(res, b"Hello!");
assert_eq!(caret, 6);
let (res, caret) = textedit_key_result(initial, 11, 5, b'!');
assert_eq!(res, b"Hello!");
assert_eq!(caret, 6);
let (res, caret) = textedit_key_result(initial, 5, 5, 0x08);
assert_eq!(res, b"Hell World");
assert_eq!(caret, 4);
let (res, caret) = textedit_key_result(initial, 0, 5, 0x08);
assert_eq!(res, b" World");
assert_eq!(caret, 0);
let (res, caret) = textedit_key_result(initial, 0, 0, 0x08);
assert_eq!(res, b"Hello World");
assert_eq!(caret, 0);
}
#[test]
fn dialog_target_routing_and_frame_geometry() {
let front = Some(0x1000);
let dialog_window = 0x2000;
let other_window = 0x3000;
let is_dialog = |ptr| ptr == dialog_window;
assert_eq!(
dialog_target_for_event(EVENT_UPDATE, dialog_window, is_dialog, front),
Some(dialog_window)
);
assert_eq!(
dialog_target_for_event(EVENT_UPDATE, other_window, is_dialog, front),
None
);
assert_eq!(
dialog_target_for_event(EVENT_ACTIVATE, dialog_window, is_dialog, front),
Some(dialog_window)
);
assert_eq!(
dialog_target_for_event(EVENT_ACTIVATE, other_window, is_dialog, front),
None
);
assert_eq!(
dialog_target_for_event(EVENT_MOUSE_DOWN, other_window, is_dialog, front),
front
);
assert_eq!(
dialog_target_for_event(EVENT_KEY_DOWN, other_window, is_dialog, front),
front
);
assert_eq!(
dialog_target_for_event(EVENT_AUTO_KEY, other_window, is_dialog, front),
front
);
assert_eq!(
dialog_target_for_event(EVENT_NULL, other_window, is_dialog, front),
front
);
let base = (10, 20, 100, 200);
assert_eq!(inset_rect(base, 2, 5), (12, 25, 98, 195));
assert_eq!(outset_rect(base, 3, 4), (7, 16, 103, 204));
assert_eq!(
dialog_dbox_frame_rect((50, 60, 150, 260)),
(42, 52, 158, 268)
);
assert_eq!(edit_text_frame_rect((10, 20, 30, 80)), (7, 17, 33, 83));
assert_eq!(dialog_text_rect((10, 20, 30, 80)), (10, 21, 30, 80));
assert_eq!(
dialog_item_base_type(DIALOG_ITEM_USER_ITEM),
DIALOG_ITEM_USER_ITEM
);
assert_eq!(
dialog_item_base_type(DIALOG_ITEM_BUTTON),
DIALOG_ITEM_BUTTON
);
assert_eq!(
dialog_item_base_type(DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG),
DIALOG_ITEM_BUTTON
);
assert_eq!(
dialog_item_base_type(DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG),
DIALOG_ITEM_EDIT_TEXT
);
assert_eq!(
dialog_item_base_type(DIALOG_ITEM_PICTURE | DIALOG_ITEM_DISABLED_FLAG),
DIALOG_ITEM_PICTURE
);
}
#[test]
fn dialog_record_initial_state_and_offsets() {
assert_eq!(DIALOG_INITIAL_EDIT_FIELD, -1);
assert_eq!(DIALOG_INITIAL_EDIT_FIELD as u16, 0xFFFF);
assert_eq!(DIALOG_INITIAL_EDIT_OPEN, 0);
assert_eq!(DIALOG_INITIAL_DEFAULT_ITEM, 1);
assert_eq!(DIALOG_ITEMS_OFFSET, 156);
assert_eq!(DIALOG_TEXT_HANDLE_OFFSET, 160);
assert_eq!(DIALOG_EDIT_FIELD_OFFSET, 164);
assert_eq!(DIALOG_EDIT_OPEN_OFFSET, 166);
assert_eq!(DIALOG_DEFAULT_ITEM_OFFSET, 168);
assert_eq!(DIALOG_RESOURCE_ID_OFFSET, 170);
assert_eq!(DIALOG_CANCEL_ITEM_OFFSET, 172);
assert_eq!(DIALOG_ALERT_HIT_OFFSET, 174);
assert_eq!(DIALOG_STANDARD_ALERT_OUTPUT_OFFSET, 176);
assert_eq!(DIALOG_STANDARD_ALERT_STACK_OFFSET, 180);
assert_eq!(DIALOG_RECORD_SIZE, 256);
}
#[test]
fn dialog_item_disabled_and_enabled_predicates() {
assert!(is_dialog_item_enabled(DIALOG_ITEM_BUTTON));
assert!(is_dialog_item_enabled(DIALOG_ITEM_EDIT_TEXT));
assert!(is_dialog_item_enabled(DIALOG_ITEM_USER_ITEM));
assert!(!is_dialog_item_disabled(DIALOG_ITEM_BUTTON));
assert!(!is_dialog_item_disabled(DIALOG_ITEM_EDIT_TEXT));
let disabled_btn = DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG;
assert!(is_dialog_item_disabled(disabled_btn));
assert!(!is_dialog_item_enabled(disabled_btn));
let disabled_text = DIALOG_ITEM_STATIC_TEXT | DIALOG_ITEM_DISABLED_FLAG;
assert!(is_dialog_item_disabled(disabled_text));
assert!(!is_dialog_item_enabled(disabled_text));
let record_enabled = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_BUTTON,
rect: (10, 10, 30, 80),
handle: 0,
payload: vec![],
};
assert!(record_enabled.is_enabled());
assert!(!record_enabled.is_disabled());
let record_disabled = DialogItemRecord {
item_offset: 0,
item_type: disabled_btn,
rect: (10, 10, 30, 80),
handle: 0,
payload: vec![],
};
assert!(record_disabled.is_disabled());
assert!(!record_disabled.is_enabled());
}
#[test]
fn dialog_point_conversions_and_bounds() {
let bounds = (50, 100, 250, 300);
let screen_pt = (75, 160);
let local_pt = global_to_dialog_local_point(bounds, screen_pt.0, screen_pt.1);
assert_eq!(local_pt, (25, 60));
let converted_back = dialog_local_to_global_point(bounds, local_pt.0, local_pt.1);
assert_eq!(converted_back, screen_pt);
assert_eq!(
global_to_dialog_local_point((100, 100, 200, 200), i16::MIN, i16::MIN),
(i16::MIN, i16::MIN)
);
assert_eq!(
dialog_local_to_global_point((100, 100, 200, 200), i16::MAX, i16::MAX),
(i16::MAX, i16::MAX)
);
}
#[test]
fn dialog_item_hit_testing() {
assert_eq!(find_dialog_item_hit([], 10, 10, false, |_| true), None);
let items = [
(
(10, 10, 50, 100),
DIALOG_ITEM_STATIC_TEXT | DIALOG_ITEM_DISABLED_FLAG,
),
((20, 20, 40, 80), DIALOG_ITEM_BUTTON),
((60, 10, 90, 100), DIALOG_ITEM_RESOURCE_CONTROL),
];
assert_eq!(
find_dialog_item_hit(items, 25, 25, false, |_| true),
Some(0)
);
assert_eq!(find_dialog_item_hit(items, 25, 25, true, |_| true), Some(1));
assert_eq!(find_dialog_item_hit(items, 5, 5, true, |_| true), None);
assert_eq!(
find_dialog_item_hit(items, 70, 50, true, |_idx| false),
None
);
assert_eq!(
find_dialog_item_hit(items, 70, 50, true, |idx| idx == 2),
Some(2)
);
let dialog_bounds = (100, 200, 300, 400);
assert_eq!(
find_dialog_item_at_global_point(dialog_bounds, 125, 225, items, true, |_| true,),
Some(1)
);
}
#[test]
fn normalize_selection_bounds_behavior() {
assert_eq!(normalize_selection_bounds(2, 5, 10), (2, 5));
assert_eq!(normalize_selection_bounds(5, 2, 10), (2, 5));
assert_eq!(normalize_selection_bounds(0, 0, 10), (0, 0));
assert_eq!(normalize_selection_bounds(10, 10, 10), (10, 10));
assert_eq!(normalize_selection_bounds(5, 20, 10), (5, 10));
assert_eq!(normalize_selection_bounds(25, 30, 10), (10, 10));
assert_eq!(normalize_selection_bounds(30, 5, 10), (5, 10));
}
#[test]
fn item_kind_predicates_and_record_methods() {
let test_cases: [(
u8,
DialogItemKind,
bool,
bool,
bool,
bool,
bool,
bool,
bool,
bool,
bool,
bool,
bool,
); 9] = [
(
DIALOG_ITEM_USER_ITEM,
DialogItemKind::UserItem,
true,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
),
(
DIALOG_ITEM_BUTTON,
DialogItemKind::Button,
false,
true,
false,
false,
false,
true,
false,
false,
false,
false,
false,
),
(
DIALOG_ITEM_CHECKBOX,
DialogItemKind::Checkbox,
false,
false,
true,
false,
false,
true,
false,
false,
false,
false,
false,
),
(
DIALOG_ITEM_RADIO,
DialogItemKind::RadioButton,
false,
false,
false,
true,
false,
true,
false,
false,
false,
false,
false,
),
(
DIALOG_ITEM_RESOURCE_CONTROL,
DialogItemKind::ResourceControl,
false,
false,
false,
false,
true,
true,
false,
false,
false,
false,
false,
),
(
DIALOG_ITEM_STATIC_TEXT,
DialogItemKind::StaticText,
false,
false,
false,
false,
false,
false,
true,
false,
true,
false,
false,
),
(
DIALOG_ITEM_EDIT_TEXT,
DialogItemKind::EditText,
false,
false,
false,
false,
false,
false,
false,
true,
true,
false,
false,
),
(
DIALOG_ITEM_ICON,
DialogItemKind::Icon,
false,
false,
false,
false,
false,
false,
false,
false,
false,
true,
false,
),
(
DIALOG_ITEM_PICTURE,
DialogItemKind::Picture,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
true,
),
];
for (
raw,
kind,
is_user,
is_btn,
is_chk,
is_rad,
is_res_ctrl,
is_ctrl,
is_stat,
is_edit,
is_text,
is_icon,
is_pict,
) in test_cases
{
for flag in [0, DIALOG_ITEM_DISABLED_FLAG] {
let r = raw | flag;
assert_eq!(is_dialog_item_user_item(r), is_user);
assert_eq!(is_dialog_item_button(r), is_btn);
assert_eq!(is_dialog_item_checkbox(r), is_chk);
assert_eq!(is_dialog_item_radio(r), is_rad);
assert_eq!(is_dialog_item_resource_control(r), is_res_ctrl);
assert_eq!(is_dialog_item_control(r), is_ctrl);
assert_eq!(is_dialog_item_static_text(r), is_stat);
assert_eq!(is_dialog_item_edit_text(r), is_edit);
assert_eq!(is_dialog_item_text(r), is_text);
assert_eq!(is_dialog_item_icon(r), is_icon);
assert_eq!(is_dialog_item_picture(r), is_pict);
let record = DialogItemRecord {
item_offset: 0,
item_type: r,
rect: (0, 0, 10, 10),
handle: 0,
payload: Vec::new(),
};
assert_eq!(record.is_user_item(), is_user);
assert_eq!(record.is_button(), is_btn);
assert_eq!(record.is_checkbox(), is_chk);
assert_eq!(record.is_radio(), is_rad);
assert_eq!(record.is_resource_control(), is_res_ctrl);
assert_eq!(record.is_control(), is_ctrl);
assert_eq!(record.is_static_text(), is_stat);
assert_eq!(record.is_edit_text(), is_edit);
assert_eq!(record.is_text(), is_text);
assert_eq!(record.is_icon(), is_icon);
assert_eq!(record.is_picture(), is_pict);
}
assert_eq!(kind.is_user_item(), is_user);
assert_eq!(kind.is_button(), is_btn);
assert_eq!(kind.is_checkbox(), is_chk);
assert_eq!(kind.is_radio(), is_rad);
assert_eq!(kind.is_resource_control(), is_res_ctrl);
assert_eq!(kind.is_control(), is_ctrl);
assert_eq!(kind.is_static_text(), is_stat);
assert_eq!(kind.is_edit_text(), is_edit);
assert_eq!(kind.is_text(), is_text);
assert_eq!(kind.is_icon(), is_icon);
assert_eq!(kind.is_picture(), is_pict);
}
}
#[test]
fn dialog_select_action_and_evaluation() {
let dialog = 0x2000;
let bounds = (10, 20, 110, 120);
let no_act = DialogSelectAction::NoAction;
assert!(!no_act.is_handled());
assert!(!no_act.should_set_dialog_ptr());
assert_eq!(no_act.target_dialog(), None);
assert_eq!(no_act.item_hit(), None);
let update_act = DialogSelectAction::Update { dialog };
assert!(!update_act.is_handled());
assert!(update_act.should_set_dialog_ptr());
assert_eq!(update_act.target_dialog(), Some(dialog));
assert_eq!(update_act.item_hit(), None);
let activate_act = DialogSelectAction::Activate { dialog };
assert!(!activate_act.is_handled());
assert!(activate_act.should_set_dialog_ptr());
assert_eq!(activate_act.target_dialog(), Some(dialog));
assert_eq!(activate_act.item_hit(), None);
let idle_act = DialogSelectAction::Idle {
dialog,
edit_item: 1,
};
assert!(!idle_act.is_handled());
assert!(!idle_act.should_set_dialog_ptr());
assert_eq!(idle_act.target_dialog(), Some(dialog));
assert_eq!(idle_act.item_hit(), None);
let hit_act = DialogSelectAction::ItemHit {
dialog,
item_no: 3,
is_edit_text: false,
is_resource_control: false,
};
assert!(hit_act.is_handled());
assert!(hit_act.should_set_dialog_ptr());
assert_eq!(hit_act.target_dialog(), Some(dialog));
assert_eq!(hit_act.item_hit(), Some(3));
let dis_act = DialogSelectAction::DisabledItemHit {
dialog,
item_no: 4,
};
assert!(!dis_act.is_handled());
assert!(!dis_act.should_set_dialog_ptr());
assert_eq!(dis_act.target_dialog(), Some(dialog));
assert_eq!(dis_act.item_hit(), None);
let key_act = DialogSelectAction::KeyStroke {
dialog,
edit_item: 2,
character: b'Z',
};
assert!(key_act.is_handled());
assert!(key_act.should_set_dialog_ptr());
assert_eq!(key_act.target_dialog(), Some(dialog));
assert_eq!(key_act.item_hit(), Some(2));
assert_eq!(
evaluate_dialog_select(
EVENT_NULL,
0,
0,
0,
None,
Some(bounds),
None,
|_, _| None,
),
DialogSelectAction::NoAction
);
assert_eq!(
evaluate_dialog_select(
EVENT_UPDATE,
dialog,
0,
0,
Some(dialog),
Some(bounds),
None,
|_, _| None,
),
DialogSelectAction::Update { dialog }
);
assert_eq!(
evaluate_dialog_select(
EVENT_UPDATE,
0x9999,
0,
0,
Some(dialog),
Some(bounds),
None,
|_, _| None,
),
DialogSelectAction::NoAction
);
assert_eq!(
evaluate_dialog_select(
EVENT_ACTIVATE,
dialog,
0,
0,
Some(dialog),
Some(bounds),
None,
|_, _| None,
),
DialogSelectAction::Activate { dialog }
);
assert_eq!(
evaluate_dialog_select(
EVENT_NULL,
0,
0,
0,
Some(dialog),
Some(bounds),
Some((2, DIALOG_ITEM_EDIT_TEXT)),
|_, _| None,
),
DialogSelectAction::Idle {
dialog,
edit_item: 2
}
);
assert_eq!(
evaluate_dialog_select(
EVENT_NULL,
0,
0,
0,
Some(dialog),
Some(bounds),
Some((2, DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG)),
|_, _| None,
),
DialogSelectAction::NoAction
);
assert_eq!(
evaluate_dialog_select(
EVENT_NULL,
0,
0,
0,
Some(dialog),
Some(bounds),
Some((1, DIALOG_ITEM_BUTTON)),
|_, _| None,
),
DialogSelectAction::NoAction
);
assert_eq!(
evaluate_dialog_select(
EVENT_MOUSE_DOWN,
0,
5,
5,
Some(dialog),
Some(bounds),
None,
|_, _| Some((1, DIALOG_ITEM_BUTTON)),
),
DialogSelectAction::NoAction
);
assert_eq!(
evaluate_dialog_select(
EVENT_MOUSE_DOWN,
0,
50,
50,
Some(dialog),
Some(bounds),
None,
|_, _| Some((1, DIALOG_ITEM_BUTTON)),
),
DialogSelectAction::ItemHit {
dialog,
item_no: 1,
is_edit_text: false,
is_resource_control: false,
}
);
assert_eq!(
evaluate_dialog_select(
EVENT_MOUSE_DOWN,
0,
50,
50,
Some(dialog),
Some(bounds),
None,
|_, _| Some((2, DIALOG_ITEM_EDIT_TEXT)),
),
DialogSelectAction::ItemHit {
dialog,
item_no: 2,
is_edit_text: true,
is_resource_control: false,
}
);
assert_eq!(
evaluate_dialog_select(
EVENT_MOUSE_DOWN,
0,
50,
50,
Some(dialog),
Some(bounds),
None,
|_, _| Some((3, DIALOG_ITEM_RESOURCE_CONTROL)),
),
DialogSelectAction::ItemHit {
dialog,
item_no: 3,
is_edit_text: false,
is_resource_control: true,
}
);
assert_eq!(
evaluate_dialog_select(
EVENT_MOUSE_DOWN,
0,
50,
50,
Some(dialog),
Some(bounds),
None,
|_, _| Some((4, DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG)),
),
DialogSelectAction::DisabledItemHit { dialog, item_no: 4 }
);
assert_eq!(
evaluate_dialog_select(
EVENT_MOUSE_DOWN,
0,
50,
50,
Some(dialog),
Some(bounds),
None,
|_, _| None,
),
DialogSelectAction::NoAction
);
assert_eq!(
evaluate_dialog_select(
EVENT_KEY_DOWN,
b'A' as u32,
0,
0,
Some(dialog),
Some(bounds),
Some((2, DIALOG_ITEM_EDIT_TEXT)),
|_, _| None,
),
DialogSelectAction::KeyStroke {
dialog,
edit_item: 2,
character: b'A',
}
);
assert_eq!(
evaluate_dialog_select(
EVENT_AUTO_KEY,
0x08,
0,
0,
Some(dialog),
Some(bounds),
Some((2, DIALOG_ITEM_EDIT_TEXT)),
|_, _| None,
),
DialogSelectAction::KeyStroke {
dialog,
edit_item: 2,
character: 0x08,
}
);
assert_eq!(
evaluate_dialog_select(
EVENT_KEY_DOWN,
b'A' as u32,
0,
0,
Some(dialog),
Some(bounds),
None,
|_, _| None,
),
DialogSelectAction::NoAction
);
}
}