use std::borrow::Cow;
use crate::mac_roman::encode_mac_roman_lossy;
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;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DialogRecordInitEvaluation {
items_handle: u32,
}
impl DialogRecordInitEvaluation {
pub const fn new(items_handle: u32) -> Self {
Self { items_handle }
}
pub const fn window_kind(&self) -> u16 {
DIALOG_WINDOW_KIND
}
pub const fn items_handle(&self) -> u32 {
self.items_handle
}
#[allow(dead_code)]
pub const fn text_handle(&self) -> u32 {
0
}
pub const fn edit_field(&self) -> i16 {
DIALOG_INITIAL_EDIT_FIELD
}
pub const fn edit_open(&self) -> i16 {
DIALOG_INITIAL_EDIT_OPEN
}
pub const fn default_item(&self) -> i16 {
DIALOG_INITIAL_DEFAULT_ITEM
}
}
pub const fn evaluate_dialog_record_init(items_handle: u32) -> DialogRecordInitEvaluation {
DialogRecordInitEvaluation::new(items_handle)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DialogStoragePolicy {
AllocateNew,
CallerSupplied(u32),
}
#[allow(dead_code)]
impl DialogStoragePolicy {
#[inline]
pub const fn is_caller_supplied(&self) -> bool {
matches!(self, Self::CallerSupplied(_))
}
#[inline]
pub const fn is_allocate_new(&self) -> bool {
matches!(self, Self::AllocateNew)
}
#[inline]
pub const fn caller_storage(&self) -> Option<u32> {
match self {
Self::CallerSupplied(ptr) => Some(*ptr),
Self::AllocateNew => None,
}
}
}
#[inline]
pub const fn evaluate_dialog_storage_policy(storage: u32) -> DialogStoragePolicy {
if storage != 0 {
DialogStoragePolicy::CallerSupplied(storage)
} else {
DialogStoragePolicy::AllocateNew
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NewDialogParameters {
storage: u32,
bounds_ptr: u32,
title_ptr: u32,
visible: bool,
proc_id: i16,
behind: u32,
go_away: bool,
ref_con: u32,
items: u32,
is_color: bool,
}
#[allow(dead_code)]
impl NewDialogParameters {
#[allow(clippy::too_many_arguments)]
#[inline]
pub const fn new(
storage: u32,
bounds_ptr: u32,
title_ptr: u32,
visible: bool,
proc_id: i16,
behind: u32,
go_away: bool,
ref_con: u32,
items: u32,
is_color: bool,
) -> Self {
Self {
storage,
bounds_ptr,
title_ptr,
visible,
proc_id,
behind,
go_away,
ref_con,
items,
is_color,
}
}
#[inline]
pub const fn storage(&self) -> u32 {
self.storage
}
#[inline]
pub const fn storage_policy(&self) -> DialogStoragePolicy {
evaluate_dialog_storage_policy(self.storage)
}
#[inline]
pub const fn bounds_ptr(&self) -> u32 {
self.bounds_ptr
}
#[inline]
pub const fn title_ptr(&self) -> u32 {
self.title_ptr
}
#[inline]
pub const fn is_visible(&self) -> bool {
self.visible
}
#[inline]
pub const fn proc_id(&self) -> i16 {
self.proc_id
}
#[inline]
pub const fn behind(&self) -> u32 {
self.behind
}
#[inline]
pub const fn go_away(&self) -> bool {
self.go_away
}
#[inline]
pub const fn ref_con(&self) -> u32 {
self.ref_con
}
#[inline]
pub const fn items(&self) -> u32 {
self.items
}
#[inline]
pub const fn is_color(&self) -> bool {
self.is_color
}
#[inline]
pub const fn has_title(&self) -> bool {
self.title_ptr != 0
}
#[inline]
pub const fn has_items(&self) -> bool {
self.items != 0
}
}
#[allow(clippy::too_many_arguments)]
#[inline]
pub const fn evaluate_new_dialog_parameters(
storage: u32,
bounds_ptr: u32,
title_ptr: u32,
visible: bool,
proc_id: i16,
behind: u32,
go_away: bool,
ref_con: u32,
items: u32,
is_color: bool,
) -> Result<NewDialogParameters, i16> {
if bounds_ptr == 0 {
return Err(DIALOG_PARAM_ERR);
}
Ok(NewDialogParameters {
storage,
bounds_ptr,
title_ptr,
visible,
proc_id,
behind,
go_away,
ref_con,
items,
is_color,
})
}
#[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 DIALOG_NO_ERR: i16 = 0;
pub const DIALOG_PARAM_ERR: i16 = -50;
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 DITL_ITEM_HANDLE_OFFSET: u32 = 0;
pub const DITL_ITEM_RECT_OFFSET: u32 = 4;
pub const DITL_ITEM_TYPE_OFFSET: u32 = 12;
#[allow(dead_code)]
pub const DITL_ITEM_DATA_LEN_OFFSET: u32 = 13;
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 has_user_proc(&self) -> bool {
self.is_user_item() && self.handle != 0
}
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 set_text(&mut self, text: &str) {
if self.has_text_or_title() {
self.payload = encode_mac_roman_lossy(text);
}
}
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)
}
pub fn evaluate_hide(&self) -> Option<DialogItemVisibilityChange> {
evaluate_hide_dialog_item(self.item_type, self.rect)
}
pub fn evaluate_show(
&self,
original_rect: Option<(i16, i16, i16, i16)>,
) -> Option<DialogItemVisibilityChange> {
evaluate_show_dialog_item(self.item_type, self.rect, original_rect)
}
pub fn header(&self) -> DialogItemHeader {
DialogItemHeader {
item_type: u16::from(self.item_type),
handle: self.handle,
rect: self.rect,
}
}
pub fn update_header(&mut self, item_type: u8, handle: u32, rect: (i16, i16, i16, i16)) {
self.item_type = item_type;
self.handle = handle;
self.rect = rect;
}
pub fn select_text(&self, start_sel: i16, end_sel: i16) -> Option<(u16, u16)> {
if !self.is_edit_text() {
return None;
}
let text_len = self.text_payload().map(|p| p.len()).unwrap_or(0);
Some(normalize_dialog_item_selection(start_sel, end_sel, text_len))
}
pub fn evaluate_select_text(&self, start_sel: i16, end_sel: i16) -> Option<(u16, u16)> {
self.select_text(start_sel, end_sel)
}
}
#[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
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DialogItemVisibilityChange {
pub new_rect: (i16, i16, i16, i16),
pub enclosing_rect: (i16, i16, i16, i16),
}
pub fn evaluate_hide_dialog_item(
item_type: u8,
current_rect: (i16, i16, i16, i16),
) -> Option<DialogItemVisibilityChange> {
if is_dialog_item_rect_hidden(current_rect) {
None
} else {
Some(DialogItemVisibilityChange {
new_rect: hide_dialog_item_rect(current_rect),
enclosing_rect: dialog_item_enclosing_rect(item_type, current_rect),
})
}
}
pub fn evaluate_show_dialog_item(
item_type: u8,
current_rect: (i16, i16, i16, i16),
original_rect: Option<(i16, i16, i16, i16)>,
) -> Option<DialogItemVisibilityChange> {
if !is_dialog_item_rect_hidden(current_rect) {
None
} else {
let restored_rect = match original_rect {
Some(orig) if !is_dialog_item_rect_hidden(orig) => orig,
_ => show_dialog_item_rect(current_rect),
};
Some(DialogItemVisibilityChange {
new_rect: restored_rect,
enclosing_rect: dialog_item_enclosing_rect(item_type, restored_rect),
})
}
}
#[allow(dead_code)]
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 evaluate_find_dialog_item<I, F>(
items: I,
local_v: i16,
local_h: i16,
control_part_hit: F,
) -> i16
where
I: IntoIterator<Item = ((i16, i16, i16, i16), u8)>,
F: FnMut(usize) -> bool,
{
find_dialog_item_hit(items, local_v, local_h, false, control_part_hit)
.map_or(-1, |idx| idx as i16)
}
#[allow(dead_code)]
pub fn evaluate_find_dialog_item_rects<'a, I>(rects: I, local_v: i16, local_h: i16) -> i16
where
I: IntoIterator<Item = &'a (i16, i16, i16, i16)>,
{
find_dialog_item_at_local_point(rects, local_v, local_h).map_or(-1, |idx| idx as i16)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FindDialogItemQuery {
dialog_ptr: u32,
pt_v: i16,
pt_h: i16,
}
impl FindDialogItemQuery {
pub const fn new(dialog_ptr: u32, pt_v: i16, pt_h: i16) -> Self {
Self {
dialog_ptr,
pt_v,
pt_h,
}
}
pub const fn dialog_ptr(&self) -> u32 {
self.dialog_ptr
}
pub const fn pt_v(&self) -> i16 {
self.pt_v
}
pub const fn pt_h(&self) -> i16 {
self.pt_h
}
#[allow(dead_code)]
pub const fn point(&self) -> (i16, i16) {
(self.pt_v, self.pt_h)
}
#[allow(dead_code)]
pub const fn packed_point(&self) -> u32 {
((self.pt_v as u16 as u32) << 16) | (self.pt_h as u16 as u32)
}
}
pub const fn evaluate_find_dialog_item_query(
dialog_ptr: u32,
pt_v: i16,
pt_h: i16,
) -> Option<FindDialogItemQuery> {
if dialog_ptr == 0 {
None
} else {
Some(FindDialogItemQuery::new(dialog_ptr, pt_v, pt_h))
}
}
pub const fn evaluate_find_dialog_item_packed(
dialog_ptr: u32,
point: u32,
) -> Option<FindDialogItemQuery> {
let v = (point >> 16) as u16 as i16;
let h = point as u16 as i16;
evaluate_find_dialog_item_query(dialog_ptr, v, h)
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct DialogItemHeader {
pub item_type: u16,
pub handle: u32,
pub rect: (i16, i16, i16, i16),
}
impl DialogItemHeader {
pub const ZERO: Self = Self {
item_type: 0,
handle: 0,
rect: (0, 0, 0, 0),
};
pub fn new(item_type: u16, handle: u32, rect: (i16, i16, i16, i16)) -> Self {
Self {
item_type,
handle,
rect,
}
}
}
pub fn evaluate_get_dialog_item<T>(
items: &[T],
item_number: usize,
header_extractor: impl FnOnce(&T) -> DialogItemHeader,
) -> DialogItemHeader {
get_item_at_1_indexed(items, item_number).map_or(DialogItemHeader::ZERO, header_extractor)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GetDialogItemQuery {
dialog_ptr: u32,
item_number: usize,
}
#[allow(dead_code)]
impl GetDialogItemQuery {
#[inline]
pub const fn new(dialog_ptr: u32, item_number: usize) -> Self {
Self {
dialog_ptr,
item_number,
}
}
#[inline]
pub const fn dialog_ptr(&self) -> u32 {
self.dialog_ptr
}
#[inline]
pub const fn item_number(&self) -> usize {
self.item_number
}
#[inline]
pub const fn item_no(&self) -> i16 {
self.item_number as i16
}
}
#[inline]
pub const fn evaluate_get_dialog_item_query(
dialog_ptr: u32,
item_number: usize,
) -> Option<GetDialogItemQuery> {
if dialog_ptr == 0 || item_number == 0 {
return None;
}
Some(GetDialogItemQuery {
dialog_ptr,
item_number,
})
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SetDialogItemParameters {
dialog_ptr: u32,
item_number: usize,
item_type: u8,
item_handle: u32,
rect: (i16, i16, i16, i16),
}
#[allow(dead_code)]
impl SetDialogItemParameters {
#[inline]
pub const fn new(
dialog_ptr: u32,
item_number: usize,
item_type: u8,
item_handle: u32,
rect: (i16, i16, i16, i16),
) -> Self {
Self {
dialog_ptr,
item_number,
item_type,
item_handle,
rect,
}
}
#[inline]
pub const fn dialog_ptr(&self) -> u32 {
self.dialog_ptr
}
#[inline]
pub const fn item_number(&self) -> usize {
self.item_number
}
#[inline]
pub const fn item_no(&self) -> i16 {
self.item_number as i16
}
#[inline]
pub const fn item_type(&self) -> u8 {
self.item_type
}
#[inline]
pub const fn base_type(&self) -> u8 {
dialog_item_base_type(self.item_type)
}
#[inline]
pub const fn is_enabled(&self) -> bool {
is_dialog_item_enabled(self.item_type)
}
#[inline]
pub const fn item_handle(&self) -> u32 {
self.item_handle
}
#[inline]
pub const fn rect(&self) -> (i16, i16, i16, i16) {
self.rect
}
}
#[inline]
pub const fn evaluate_set_dialog_item_parameters(
dialog_ptr: u32,
item_number: usize,
item_type: u16,
item_handle: u32,
rect: (i16, i16, i16, i16),
) -> Option<SetDialogItemParameters> {
if dialog_ptr == 0 || item_number == 0 {
return None;
}
Some(SetDialogItemParameters {
dialog_ptr,
item_number,
item_type: item_type as u8,
item_handle,
rect,
})
}
pub fn evaluate_get_dialog_item_as_control(
item_type: u8,
handle: u32,
) -> Result<u32, i16> {
if is_dialog_item_control(item_type) && handle != 0 {
Ok(handle)
} else {
Err(DIALOG_PARAM_ERR)
}
}
pub fn evaluate_set_dialog_default_item(dialog_ptr: u32, _new_item: i16) -> Result<i16, i16> {
if dialog_ptr == 0 {
Err(DIALOG_PARAM_ERR)
} else {
Ok(DIALOG_NO_ERR)
}
}
pub fn evaluate_set_dialog_cancel_item(dialog_ptr: u32, _new_item: i16) -> Result<i16, i16> {
if dialog_ptr == 0 {
Err(DIALOG_PARAM_ERR)
} else {
Ok(DIALOG_NO_ERR)
}
}
pub fn evaluate_set_dialog_tracks_cursor(_dialog_ptr: u32, _tracks: bool) -> Result<i16, i16> {
Ok(DIALOG_NO_ERR)
}
pub fn evaluate_get_std_filter_proc(out_proc: u32, can_write: bool) -> Result<i16, i16> {
if out_proc == 0 || !can_write {
Err(DIALOG_PARAM_ERR)
} else {
Ok(DIALOG_NO_ERR)
}
}
pub fn evaluate_count_ditl(ditl_count_word: Option<u16>, record_count: usize) -> u16 {
if let Some(word) = ditl_count_word {
let count = word.wrapping_add(1);
if count != 0 {
return count;
}
}
record_count.min(u16::MAX as usize) as u16
}
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());
}
}
}
}
#[allow(dead_code)]
pub const DITL_ITEM_HEADER_SIZE: usize = 13;
#[allow(dead_code)]
pub fn write_ditl_item_header_bytes(
bytes: &mut [u8],
offset: usize,
handle: u32,
rect: (i16, i16, i16, i16),
item_type: u8,
) -> bool {
let Some(end) = offset.checked_add(DITL_ITEM_HEADER_SIZE) else {
return false;
};
let Some(slice) = bytes.get_mut(offset..end) else {
return false;
};
slice[0..4].copy_from_slice(&handle.to_be_bytes());
slice[4..6].copy_from_slice(&rect.0.to_be_bytes());
slice[6..8].copy_from_slice(&rect.1.to_be_bytes());
slice[8..10].copy_from_slice(&rect.2.to_be_bytes());
slice[10..12].copy_from_slice(&rect.3.to_be_bytes());
slice[12] = item_type;
true
}
#[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 const ALERT_SUPPRESSED_RESULT: i16 = -1;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AlertStageEvaluation {
stage_index: u16,
stage_nibble: u8,
box_drawn: bool,
default_item: i16,
sound_number: u8,
next_stage: u16,
}
#[allow(dead_code)]
impl AlertStageEvaluation {
#[inline]
pub const fn new(
stage_index: u16,
stage_nibble: u8,
box_drawn: bool,
default_item: i16,
sound_number: u8,
next_stage: u16,
) -> Self {
Self {
stage_index,
stage_nibble,
box_drawn,
default_item,
sound_number,
next_stage,
}
}
#[inline]
pub const fn stage_index(&self) -> u16 {
self.stage_index
}
#[inline]
pub const fn stage_nibble(&self) -> u8 {
self.stage_nibble
}
#[inline]
pub const fn box_drawn(&self) -> bool {
self.box_drawn
}
#[inline]
pub const fn default_item(&self) -> i16 {
self.default_item
}
#[inline]
pub const fn effective_default_item(&self) -> Option<i16> {
if self.box_drawn {
Some(self.default_item)
} else {
None
}
}
#[inline]
pub const fn sound_number(&self) -> u8 {
self.sound_number
}
#[inline]
pub const fn has_sound(&self) -> bool {
self.sound_number != 0
}
#[inline]
pub const fn next_stage(&self) -> u16 {
self.next_stage
}
#[inline]
pub const fn suppressed_result(&self) -> i16 {
ALERT_SUPPRESSED_RESULT
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AlertInvocationEvaluation {
alert_id: i16,
stage: AlertStageEvaluation,
}
#[allow(dead_code)]
impl AlertInvocationEvaluation {
#[inline]
pub const fn new(alert_id: i16, stage: AlertStageEvaluation) -> Self {
Self { alert_id, stage }
}
#[inline]
pub const fn alert_id(&self) -> i16 {
self.alert_id
}
#[inline]
pub const fn stage(&self) -> &AlertStageEvaluation {
&self.stage
}
#[inline]
pub const fn next_stage(&self) -> u16 {
self.stage.next_stage()
}
#[inline]
pub const fn anumber(&self) -> u16 {
self.alert_id as u16
}
#[inline]
pub const fn default_item(&self) -> Option<i16> {
self.stage.effective_default_item()
}
#[inline]
pub const fn sound_number(&self) -> u8 {
self.stage.sound_number()
}
#[inline]
pub const fn has_sound(&self) -> bool {
self.stage.has_sound()
}
#[inline]
pub const fn is_suppressed(&self) -> bool {
!self.stage.box_drawn()
}
#[inline]
pub const fn suppressed_result(&self) -> i16 {
self.stage.suppressed_result()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ErrorSoundEvaluation {
sound_proc: u32,
}
#[allow(dead_code)]
impl ErrorSoundEvaluation {
#[inline]
pub const fn new(sound_proc: u32) -> Self {
Self { sound_proc }
}
#[inline]
pub const fn sound_proc(&self) -> u32 {
self.sound_proc
}
#[inline]
pub const fn is_silent(&self) -> bool {
self.sound_proc == 0
}
}
#[inline]
pub fn evaluate_alert_stage(stages: u16, current_stage: u16) -> AlertStageEvaluation {
let info = alert_stage_info(stages, current_stage);
let next_stage = next_alert_stage(current_stage);
AlertStageEvaluation::new(
info.stage_index,
info.stage_nibble,
info.box_drawn,
info.default_item,
info.sound_number,
next_stage,
)
}
#[inline]
pub fn evaluate_alert_invocation(
alert_id: i16,
stages: u16,
current_stage: u16,
) -> AlertInvocationEvaluation {
let stage = evaluate_alert_stage(stages, current_stage);
AlertInvocationEvaluation::new(alert_id, stage)
}
#[inline]
pub const fn evaluate_error_sound(sound_proc: u32) -> ErrorSoundEvaluation {
ErrorSoundEvaluation::new(sound_proc)
}
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 PARAM_TEXT_SLOT_COUNT: usize = 4;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ParamTextEvaluation {
slots: [Option<Vec<u8>>; PARAM_TEXT_SLOT_COUNT],
}
impl ParamTextEvaluation {
pub const fn new(slots: [Option<Vec<u8>>; PARAM_TEXT_SLOT_COUNT]) -> Self {
Self { slots }
}
pub fn slot(&self, index: usize) -> Option<&[u8]> {
self.slots.get(index).and_then(|opt| opt.as_deref())
}
#[allow(dead_code)]
pub fn has_update(&self, index: usize) -> bool {
self.slots.get(index).is_some_and(Option::is_some)
}
pub fn apply_to(&self, target: &mut [Vec<u8>; PARAM_TEXT_SLOT_COUNT]) {
for (index, slot_opt) in self.slots.iter().enumerate() {
if let Some(bytes) = slot_opt {
target[index] = bytes.clone();
}
}
}
#[allow(dead_code)]
pub fn merged_with(
&self,
current: &[Vec<u8>; PARAM_TEXT_SLOT_COUNT],
) -> [Vec<u8>; PARAM_TEXT_SLOT_COUNT] {
let mut result = current.clone();
self.apply_to(&mut result);
result
}
pub fn decoded_strings(
&self,
current: &[Vec<u8>; PARAM_TEXT_SLOT_COUNT],
) -> [String; PARAM_TEXT_SLOT_COUNT] {
let merged = self.merged_with(current);
[
decode_mac_roman(&merged[0]),
decode_mac_roman(&merged[1]),
decode_mac_roman(&merged[2]),
decode_mac_roman(&merged[3]),
]
}
}
pub fn evaluate_param_text(
slots: [Option<&[u8]>; PARAM_TEXT_SLOT_COUNT],
) -> ParamTextEvaluation {
let mut evaluated = [None, None, None, None];
for (i, opt) in slots.into_iter().enumerate() {
if let Some(bytes) = opt {
let clamped = if bytes.len() > 255 {
bytes[..255].to_vec()
} else {
bytes.to_vec()
};
evaluated[i] = Some(clamped);
}
}
ParamTextEvaluation::new(evaluated)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InitDialogsEvaluation {
resume_proc: u32,
}
impl InitDialogsEvaluation {
pub const fn resume_proc(&self) -> u32 {
self.resume_proc
}
pub const fn initial_alert_stage(&self) -> i16 {
0
}
pub const fn da_beeper(&self) -> u32 {
0
}
pub const fn da_strings_count(&self) -> usize {
PARAM_TEXT_SLOT_COUNT
}
}
pub const fn evaluate_init_dialogs(resume_proc: u32) -> InitDialogsEvaluation {
InitDialogsEvaluation { resume_proc }
}
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)
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GetDialogItemTextEvaluation {
pub item_handle: u32,
pub text_out_ptr: u32,
pub len: u8,
pub text: Vec<u8>,
}
#[allow(dead_code)]
impl GetDialogItemTextEvaluation {
pub fn item_handle(&self) -> u32 {
self.item_handle
}
pub fn text_out_ptr(&self) -> u32 {
self.text_out_ptr
}
pub fn len(&self) -> u8 {
self.len
}
pub fn text(&self) -> &[u8] {
&self.text
}
pub fn decoded_text(&self) -> String {
decode_mac_roman(&self.text)
}
pub fn pstring_bytes(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(usize::from(self.len) + 1);
out.push(self.len);
out.extend_from_slice(&self.text);
out
}
}
pub fn evaluate_get_dialog_item_text(
item_handle: u32,
text_out_ptr: u32,
source_bytes: &[u8],
) -> Option<GetDialogItemTextEvaluation> {
if text_out_ptr == 0 {
None
} else {
let (len, text) = prepare_get_dialog_item_text(source_bytes);
Some(GetDialogItemTextEvaluation {
item_handle,
text_out_ptr,
len,
text: text.to_vec(),
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SetDialogItemTextEvaluation {
pub item_handle: u32,
pub text_ptr: u32,
pub bytes: Vec<u8>,
pub text: String,
}
#[allow(dead_code)]
impl SetDialogItemTextEvaluation {
pub fn item_handle(&self) -> u32 {
self.item_handle
}
pub fn text_ptr(&self) -> u32 {
self.text_ptr
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
pub fn byte_len(&self) -> usize {
self.bytes.len()
}
pub fn text(&self) -> &str {
&self.text
}
}
pub fn evaluate_set_dialog_item_text(
item_handle: u32,
text_ptr: u32,
raw_text: &[u8],
) -> Option<SetDialogItemTextEvaluation> {
if text_ptr == 0 {
None
} else {
let (bytes, text) = prepare_set_dialog_item_text(raw_text);
Some(SetDialogItemTextEvaluation {
item_handle,
text_ptr,
bytes: bytes.to_vec(),
text,
})
}
}
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)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SelectDialogItemTextEvaluation {
pub edit_field: u16,
pub sel_start: u16,
pub sel_end: u16,
}
#[allow(dead_code)]
impl SelectDialogItemTextEvaluation {
pub fn selection_range(&self) -> (u16, u16) {
(self.sel_start, self.sel_end)
}
}
pub fn evaluate_select_dialog_item_text(
dialog_ptr: u32,
item_number: usize,
is_edit_text: bool,
start_sel: i16,
end_sel: i16,
text_len: usize,
) -> Option<SelectDialogItemTextEvaluation> {
if dialog_ptr == 0 || item_number == 0 || !is_edit_text {
return None;
}
let edit_field = (item_number - 1).min(i16::MAX as usize) as u16;
let (sel_start, sel_end) = normalize_dialog_item_selection(start_sel, end_sel, text_len);
Some(SelectDialogItemTextEvaluation {
edit_field,
sel_start,
sel_end,
})
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DialogTearDownEvaluation {
pub dialog_ptr: u32,
pub dispose_record: bool,
}
#[allow(dead_code)]
impl DialogTearDownEvaluation {
pub fn is_dispose(&self) -> bool {
self.dispose_record
}
pub fn is_close(&self) -> bool {
!self.dispose_record
}
}
pub fn evaluate_close_or_dispose_dialog(
dialog_ptr: u32,
is_dispose: bool,
) -> Option<DialogTearDownEvaluation> {
if dialog_ptr == 0 {
None
} else {
Some(DialogTearDownEvaluation {
dialog_ptr,
dispose_record: is_dispose,
})
}
}
pub fn evaluate_close_dialog(dialog_ptr: u32) -> Option<DialogTearDownEvaluation> {
evaluate_close_or_dispose_dialog(dialog_ptr, false)
}
pub fn evaluate_dispose_dialog(dialog_ptr: u32) -> Option<DialogTearDownEvaluation> {
evaluate_close_or_dispose_dialog(dialog_ptr, true)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DrawDialogEvaluation {
pub dialog_ptr: u32,
}
#[allow(dead_code)]
impl DrawDialogEvaluation {
pub fn dialog_ptr(&self) -> u32 {
self.dialog_ptr
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UpdateDialogEvaluation {
pub dialog_ptr: u32,
pub update_rgn: u32,
}
#[allow(dead_code)]
impl UpdateDialogEvaluation {
pub fn dialog_ptr(&self) -> u32 {
self.dialog_ptr
}
pub fn update_rgn(&self) -> u32 {
self.update_rgn
}
pub fn as_draw_dialog(&self) -> DrawDialogEvaluation {
DrawDialogEvaluation {
dialog_ptr: self.dialog_ptr,
}
}
}
#[inline]
pub fn evaluate_draw_dialog(dialog_ptr: u32) -> Option<DrawDialogEvaluation> {
if dialog_ptr == 0 {
None
} else {
Some(DrawDialogEvaluation { dialog_ptr })
}
}
#[inline]
pub fn evaluate_update_dialog(dialog_ptr: u32, update_rgn: u32) -> Option<UpdateDialogEvaluation> {
if dialog_ptr == 0 || update_rgn == 0 {
None
} else {
Some(UpdateDialogEvaluation {
dialog_ptr,
update_rgn,
})
}
}
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 dialog_effective_update_rect(
bounds: (i16, i16, i16, i16),
update_rect: (i16, i16, i16, i16),
) -> (i16, i16, i16, i16) {
if rects_intersect(update_rect, bounds) {
update_rect
} else {
dialog_rect_to_global(bounds, update_rect)
}
}
pub fn dialog_item_intersects_draw_area(
bounds: (i16, i16, i16, i16),
item_rect: (i16, i16, i16, i16),
update_rect: Option<(i16, i16, i16, i16)>,
) -> bool {
if !dialog_item_intersects_bounds(bounds, item_rect) {
return false;
}
match update_rect {
Some(rect) => {
let global_rect = dialog_rect_to_global(bounds, item_rect);
let effective_rect = dialog_effective_update_rect(bounds, rect);
rects_intersect(global_rect, effective_rect)
}
None => true,
}
}
pub fn evaluate_dialog_user_item_numbers<I>(
items: I,
bounds: (i16, i16, i16, i16),
update_rect: Option<(i16, i16, i16, i16)>,
) -> Vec<usize>
where
I: IntoIterator<Item = (bool, (i16, i16, i16, i16))>,
{
items
.into_iter()
.enumerate()
.filter_map(|(index, (has_user_proc, item_rect))| {
if has_user_proc && dialog_item_intersects_draw_area(bounds, item_rect, update_rect) {
Some(index + 1)
} else {
None
}
})
.collect()
}
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
);
}
#[test]
fn dialog_item_visibility_transitions_and_find_dialog_item() {
let visible_btn_rect = (10, 20, 30, 80);
let hidden_btn_rect = (
10,
20 + DIALOG_ITEM_HIDDEN_OFFSET,
30,
80 + DIALOG_ITEM_HIDDEN_OFFSET,
);
let visible_edit_rect = (40, 50, 60, 150);
let hidden_edit_rect = (
40,
50 + DIALOG_ITEM_HIDDEN_OFFSET,
60,
150 + DIALOG_ITEM_HIDDEN_OFFSET,
);
let hide_btn = evaluate_hide_dialog_item(DIALOG_ITEM_BUTTON, visible_btn_rect);
assert_eq!(
hide_btn,
Some(DialogItemVisibilityChange {
new_rect: hidden_btn_rect,
enclosing_rect: visible_btn_rect,
})
);
assert_eq!(
evaluate_hide_dialog_item(DIALOG_ITEM_BUTTON, hidden_btn_rect),
None
);
let hide_edit = evaluate_hide_dialog_item(DIALOG_ITEM_EDIT_TEXT, visible_edit_rect);
assert_eq!(
hide_edit,
Some(DialogItemVisibilityChange {
new_rect: hidden_edit_rect,
enclosing_rect: (37, 47, 63, 153),
})
);
assert_eq!(
evaluate_show_dialog_item(DIALOG_ITEM_BUTTON, visible_btn_rect, None),
None
);
let show_btn = evaluate_show_dialog_item(DIALOG_ITEM_BUTTON, hidden_btn_rect, None);
assert_eq!(
show_btn,
Some(DialogItemVisibilityChange {
new_rect: visible_btn_rect,
enclosing_rect: visible_btn_rect,
})
);
let show_btn_orig = evaluate_show_dialog_item(
DIALOG_ITEM_BUTTON,
hidden_btn_rect,
Some(visible_btn_rect),
);
assert_eq!(
show_btn_orig,
Some(DialogItemVisibilityChange {
new_rect: visible_btn_rect,
enclosing_rect: visible_btn_rect,
})
);
let show_edit = evaluate_show_dialog_item(DIALOG_ITEM_EDIT_TEXT, hidden_edit_rect, None);
assert_eq!(
show_edit,
Some(DialogItemVisibilityChange {
new_rect: visible_edit_rect,
enclosing_rect: (37, 47, 63, 153),
})
);
let btn_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_BUTTON,
rect: visible_btn_rect,
handle: 0,
payload: Vec::new(),
};
assert!(!btn_record.is_hidden());
assert_eq!(btn_record.evaluate_hide(), hide_btn);
assert_eq!(btn_record.evaluate_show(None), None);
let mut hidden_record = btn_record;
hidden_record.rect = hidden_btn_rect;
assert!(hidden_record.is_hidden());
assert_eq!(hidden_record.evaluate_hide(), None);
assert_eq!(hidden_record.evaluate_show(None), show_btn);
let rects = [
(10, 10, 40, 60), (50, 10, 70, 100), (10, 16404, 30, 16464), ];
assert_eq!(evaluate_find_dialog_item_rects(&rects, 25, 25), 0);
assert_eq!(evaluate_find_dialog_item_rects(&rects, 60, 25), 1);
assert_eq!(evaluate_find_dialog_item_rects(&rects, 20, 20), 0);
assert_eq!(evaluate_find_dialog_item_rects(&rects, 200, 200), -1);
let empty: [(i16, i16, i16, i16); 0] = [];
assert_eq!(evaluate_find_dialog_item_rects(&empty, 10, 10), -1);
let ditl_items = [
((10, 10, 150, 250), DIALOG_ITEM_RESOURCE_CONTROL),
((40, 30, 60, 110), DIALOG_ITEM_BUTTON),
((160, 10, 180, 100), DIALOG_ITEM_STATIC_TEXT | DIALOG_ITEM_DISABLED_FLAG),
];
let hit_test = |v, h| {
evaluate_find_dialog_item(ditl_items, v, h, |idx| {
idx != 0
})
};
assert_eq!(hit_test(50, 70), 1);
assert_eq!(hit_test(120, 200), -1);
assert_eq!(hit_test(170, 50), 2);
assert_eq!(hit_test(300, 300), -1);
}
#[test]
fn dialog_item_header_query_update_and_control_evaluation() {
assert_eq!(
DialogItemHeader::ZERO,
DialogItemHeader {
item_type: 0,
handle: 0,
rect: (0, 0, 0, 0),
}
);
let header = DialogItemHeader::new(4, 0x12345678, (10, 20, 30, 40));
assert_eq!(header.item_type, 4);
assert_eq!(header.handle, 0x12345678);
assert_eq!(header.rect, (10, 20, 30, 40));
let mut record = DialogItemRecord {
item_offset: 2,
item_type: DIALOG_ITEM_BUTTON,
rect: (10, 20, 30, 40),
handle: 0x1000,
payload: b"OK".to_vec(),
};
assert_eq!(
record.header(),
DialogItemHeader {
item_type: DIALOG_ITEM_BUTTON as u16,
handle: 0x1000,
rect: (10, 20, 30, 40),
}
);
record.update_header(DIALOG_ITEM_CHECKBOX, 0x2000, (50, 60, 70, 80));
assert_eq!(record.item_type, DIALOG_ITEM_CHECKBOX);
assert_eq!(record.handle, 0x2000);
assert_eq!(record.rect, (50, 60, 70, 80));
assert_eq!(
record.header(),
DialogItemHeader {
item_type: DIALOG_ITEM_CHECKBOX as u16,
handle: 0x2000,
rect: (50, 60, 70, 80),
}
);
let records = [record];
assert_eq!(
evaluate_get_dialog_item(&records, 1, |r| r.header()),
records[0].header()
);
assert_eq!(
evaluate_get_dialog_item(&records, 0, |r| r.header()),
DialogItemHeader::ZERO
);
assert_eq!(
evaluate_get_dialog_item(&records, 2, |r| r.header()),
DialogItemHeader::ZERO
);
assert_eq!(
evaluate_get_dialog_item_as_control(DIALOG_ITEM_BUTTON, 0x3000),
Ok(0x3000)
);
assert_eq!(
evaluate_get_dialog_item_as_control(DIALOG_ITEM_RESOURCE_CONTROL, 0x4000),
Ok(0x4000)
);
assert_eq!(
evaluate_get_dialog_item_as_control(DIALOG_ITEM_BUTTON, 0),
Err(-50)
);
assert_eq!(
evaluate_get_dialog_item_as_control(DIALOG_ITEM_STATIC_TEXT, 0x3000),
Err(-50)
);
assert_eq!(
evaluate_get_dialog_item_as_control(DIALOG_ITEM_USER_ITEM, 0x3000),
Err(-50)
);
let mut buf = vec![0u8; 32];
let written = write_ditl_item_header_bytes(
&mut buf,
4,
0xAABBCCDD,
(11, 22, 33, 44),
DIALOG_ITEM_RADIO,
);
assert!(written);
assert_eq!(&buf[4..8], &0xAABBCCDDu32.to_be_bytes());
assert_eq!(&buf[8..10], &11i16.to_be_bytes());
assert_eq!(&buf[10..12], &22i16.to_be_bytes());
assert_eq!(&buf[12..14], &33i16.to_be_bytes());
assert_eq!(&buf[14..16], &44i16.to_be_bytes());
assert_eq!(buf[16], DIALOG_ITEM_RADIO);
let mut small_buf = [0u8; 10];
assert!(!write_ditl_item_header_bytes(
&mut small_buf,
0,
0,
(0, 0, 0, 0),
0
));
}
#[test]
fn dialog_dispatch_extension_routines_and_count_ditl_evaluation() {
assert_eq!(evaluate_set_dialog_default_item(0x1000, 1), Ok(DIALOG_NO_ERR));
assert_eq!(evaluate_set_dialog_default_item(0x1000, -1), Ok(DIALOG_NO_ERR));
assert_eq!(evaluate_set_dialog_default_item(0, 1), Err(DIALOG_PARAM_ERR));
assert_eq!(evaluate_set_dialog_cancel_item(0x1000, 2), Ok(DIALOG_NO_ERR));
assert_eq!(evaluate_set_dialog_cancel_item(0x1000, 0), Ok(DIALOG_NO_ERR));
assert_eq!(evaluate_set_dialog_cancel_item(0, 2), Err(DIALOG_PARAM_ERR));
assert_eq!(evaluate_set_dialog_tracks_cursor(0x1000, true), Ok(DIALOG_NO_ERR));
assert_eq!(evaluate_set_dialog_tracks_cursor(0, false), Ok(DIALOG_NO_ERR));
assert_eq!(evaluate_get_std_filter_proc(0x2000, true), Ok(DIALOG_NO_ERR));
assert_eq!(evaluate_get_std_filter_proc(0, true), Err(DIALOG_PARAM_ERR));
assert_eq!(evaluate_get_std_filter_proc(0x2000, false), Err(DIALOG_PARAM_ERR));
assert_eq!(evaluate_get_std_filter_proc(0, false), Err(DIALOG_PARAM_ERR));
assert_eq!(evaluate_count_ditl(Some(0), 10), 1);
assert_eq!(evaluate_count_ditl(Some(1), 10), 2);
assert_eq!(evaluate_count_ditl(Some(4), 0), 5);
assert_eq!(evaluate_count_ditl(Some(u16::MAX), 0), 0);
assert_eq!(evaluate_count_ditl(Some(u16::MAX), 3), 3);
assert_eq!(evaluate_count_ditl(None, 0), 0);
assert_eq!(evaluate_count_ditl(None, 7), 7);
}
#[test]
fn select_dialog_item_text_evaluation() {
assert_eq!(
evaluate_select_dialog_item_text(0, 1, true, 0, 5, 10),
None
);
assert_eq!(
evaluate_select_dialog_item_text(0x1000, 0, true, 0, 5, 10),
None
);
assert_eq!(
evaluate_select_dialog_item_text(0x1000, 1, false, 0, 5, 10),
None
);
let eval = evaluate_select_dialog_item_text(0x1000, 1, true, 2, 5, 10).unwrap();
assert_eq!(eval.edit_field, 0);
assert_eq!(eval.sel_start, 2);
assert_eq!(eval.sel_end, 5);
assert_eq!(eval.selection_range(), (2, 5));
let eval_item3 = evaluate_select_dialog_item_text(0x1000, 3, true, 1, 4, 10).unwrap();
assert_eq!(eval_item3.edit_field, 2);
assert_eq!(eval_item3.sel_start, 1);
assert_eq!(eval_item3.sel_end, 4);
let eval_all1 = evaluate_select_dialog_item_text(0x1000, 2, true, 0, -1, 15).unwrap();
assert_eq!(eval_all1.edit_field, 1);
assert_eq!(eval_all1.selection_range(), (0, 15));
let eval_all2 = evaluate_select_dialog_item_text(0x1000, 2, true, 0, i16::MAX, 15).unwrap();
assert_eq!(eval_all2.selection_range(), (0, 15));
let eval_empty = evaluate_select_dialog_item_text(0x1000, 1, true, 0, -1, 0).unwrap();
assert_eq!(eval_empty.selection_range(), (0, 0));
let eval_clamped = evaluate_select_dialog_item_text(0x1000, 1, true, -10, 50, 12).unwrap();
assert_eq!(eval_clamped.selection_range(), (0, 12));
let eval_swapped = evaluate_select_dialog_item_text(0x1000, 1, true, 8, 3, 12).unwrap();
assert_eq!(eval_swapped.selection_range(), (3, 8));
let edit_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_EDIT_TEXT,
rect: (0, 0, 20, 100),
handle: 0,
payload: b"Hello World".to_vec(),
};
assert_eq!(edit_record.select_text(0, -1), Some((0, 11)));
assert_eq!(edit_record.evaluate_select_text(2, 7), Some((2, 7)));
let button_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_BUTTON,
rect: (0, 0, 20, 100),
handle: 0,
payload: b"OK".to_vec(),
};
assert_eq!(button_record.select_text(0, -1), None);
assert_eq!(button_record.evaluate_select_text(0, 1), None);
}
#[test]
fn dialog_teardown_evaluation() {
assert_eq!(evaluate_close_or_dispose_dialog(0, false), None);
assert_eq!(evaluate_close_or_dispose_dialog(0, true), None);
assert_eq!(evaluate_close_dialog(0), None);
assert_eq!(evaluate_dispose_dialog(0), None);
let close_eval = evaluate_close_dialog(0x1000).unwrap();
assert_eq!(close_eval.dialog_ptr, 0x1000);
assert!(!close_eval.dispose_record);
assert!(close_eval.is_close());
assert!(!close_eval.is_dispose());
let dispose_eval = evaluate_dispose_dialog(0x2000).unwrap();
assert_eq!(dispose_eval.dialog_ptr, 0x2000);
assert!(dispose_eval.dispose_record);
assert!(dispose_eval.is_dispose());
assert!(!dispose_eval.is_close());
assert_eq!(
evaluate_close_or_dispose_dialog(0x1000, false),
Some(close_eval)
);
assert_eq!(
evaluate_close_or_dispose_dialog(0x2000, true),
Some(dispose_eval)
);
}
#[test]
fn draw_and_update_dialog_evaluation() {
assert_eq!(evaluate_draw_dialog(0), None);
let draw_eval = evaluate_draw_dialog(0x5000).unwrap();
assert_eq!(draw_eval.dialog_ptr, 0x5000);
assert_eq!(draw_eval.dialog_ptr(), 0x5000);
assert_eq!(evaluate_update_dialog(0, 0x1000), None);
assert_eq!(evaluate_update_dialog(0x5000, 0), None);
assert_eq!(evaluate_update_dialog(0, 0), None);
let update_eval = evaluate_update_dialog(0x5000, 0x2000).unwrap();
assert_eq!(update_eval.dialog_ptr, 0x5000);
assert_eq!(update_eval.dialog_ptr(), 0x5000);
assert_eq!(update_eval.update_rgn, 0x2000);
assert_eq!(update_eval.update_rgn(), 0x2000);
assert_eq!(update_eval.as_draw_dialog(), draw_eval);
let user_with_proc = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_USER_ITEM,
rect: (10, 10, 50, 50),
handle: 0x4000,
payload: Vec::new(),
};
assert!(user_with_proc.has_user_proc());
let user_without_proc = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_USER_ITEM,
rect: (10, 10, 50, 50),
handle: 0,
payload: Vec::new(),
};
assert!(!user_without_proc.has_user_proc());
let button_with_proc = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_BUTTON,
rect: (10, 10, 50, 50),
handle: 0x4000,
payload: Vec::new(),
};
assert!(!button_with_proc.has_user_proc());
let bounds = (100, 100, 300, 400);
let intersecting = (150, 150, 250, 250);
assert_eq!(dialog_effective_update_rect(bounds, intersecting), intersecting);
let local_rect = (10, 10, 50, 50);
assert_eq!(
dialog_effective_update_rect(bounds, local_rect),
(110, 110, 150, 150)
);
let in_bounds_item_rect = (10, 10, 50, 50); assert!(dialog_item_intersects_draw_area(bounds, in_bounds_item_rect, None));
assert!(dialog_item_intersects_draw_area(
bounds,
in_bounds_item_rect,
Some((100, 100, 200, 200))
));
assert!(!dialog_item_intersects_draw_area(
bounds,
in_bounds_item_rect,
Some((200, 200, 300, 300))
));
let offscreen_item_rect = (500, 500, 550, 550);
assert!(!dialog_item_intersects_draw_area(bounds, offscreen_item_rect, None));
assert!(!dialog_item_intersects_draw_area(
bounds,
offscreen_item_rect,
Some((100, 100, 200, 200))
));
let items = vec![
(user_with_proc.has_user_proc(), user_with_proc.rect),
(button_with_proc.has_user_proc(), button_with_proc.rect),
(user_without_proc.has_user_proc(), user_without_proc.rect),
(true, (500, 500, 550, 550)), (true, (60, 60, 100, 100)), ];
assert_eq!(
evaluate_dialog_user_item_numbers(items.clone(), bounds, None),
vec![1, 5]
);
assert_eq!(
evaluate_dialog_user_item_numbers(
items.clone(),
bounds,
Some((100, 100, 155, 155)) ),
vec![1]
);
assert_eq!(
evaluate_dialog_user_item_numbers(
items.clone(),
bounds,
Some((155, 155, 250, 250)) ),
vec![5]
);
assert_eq!(
evaluate_dialog_user_item_numbers(
items,
bounds,
Some((250, 250, 300, 300)) ),
Vec::<usize>::new()
);
}
#[test]
fn get_and_set_dialog_item_text_evaluation() {
assert_eq!(evaluate_get_dialog_item_text(0x1000, 0, b"Hello"), None);
let get_eval = evaluate_get_dialog_item_text(0x1000, 0x2000, b"Hello").unwrap();
assert_eq!(get_eval.item_handle(), 0x1000);
assert_eq!(get_eval.text_out_ptr(), 0x2000);
assert_eq!(get_eval.len(), 5);
assert_eq!(get_eval.text(), b"Hello");
assert_eq!(get_eval.decoded_text(), "Hello");
assert_eq!(get_eval.pstring_bytes(), b"\x05Hello");
let empty_get = evaluate_get_dialog_item_text(0x1000, 0x2000, b"").unwrap();
assert_eq!(empty_get.len(), 0);
assert_eq!(empty_get.text(), b"");
assert_eq!(empty_get.pstring_bytes(), vec![0]);
let long_bytes = vec![b'A'; 300];
let clamped_get = evaluate_get_dialog_item_text(0x1000, 0x2000, &long_bytes).unwrap();
assert_eq!(clamped_get.len(), 255);
assert_eq!(clamped_get.text().len(), 255);
assert_eq!(clamped_get.pstring_bytes().len(), 256);
assert_eq!(evaluate_set_dialog_item_text(0x1000, 0, b"Submit"), None);
let set_eval = evaluate_set_dialog_item_text(0x1000, 0x3000, b"Submit").unwrap();
assert_eq!(set_eval.item_handle(), 0x1000);
assert_eq!(set_eval.text_ptr(), 0x3000);
assert_eq!(set_eval.bytes(), b"Submit");
assert_eq!(set_eval.byte_len(), 6);
assert_eq!(set_eval.text(), "Submit");
let long_raw = vec![b'Z'; 300];
let clamped_set = evaluate_set_dialog_item_text(0x1000, 0x3000, &long_raw).unwrap();
assert_eq!(clamped_set.byte_len(), 255);
assert_eq!(clamped_set.bytes().len(), 255);
let mut edit_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_EDIT_TEXT,
rect: (10, 10, 30, 100),
handle: 0,
payload: b"Original".to_vec(),
};
edit_record.set_text("Modified");
assert_eq!(edit_record.text(), "Modified");
let mut button_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_BUTTON,
rect: (10, 10, 30, 100),
handle: 0,
payload: b"OK".to_vec(),
};
button_record.set_text("Cancel");
assert_eq!(button_record.text(), "Cancel");
let mut icon_record = DialogItemRecord {
item_offset: 0,
item_type: DIALOG_ITEM_ICON,
rect: (10, 10, 42, 42),
handle: 0,
payload: vec![0, 128], };
icon_record.set_text("NotText");
assert_eq!(icon_record.payload, vec![0, 128]);
}
#[test]
fn param_text_and_init_dialogs_evaluation() {
let init_null = evaluate_init_dialogs(0);
assert_eq!(init_null.resume_proc(), 0);
assert_eq!(init_null.initial_alert_stage(), 0);
assert_eq!(init_null.da_beeper(), 0);
assert_eq!(init_null.da_strings_count(), 4);
let init_custom = evaluate_init_dialogs(0x0012_3456);
assert_eq!(init_custom.resume_proc(), 0x0012_3456);
assert_eq!(init_custom.initial_alert_stage(), 0);
assert_eq!(init_custom.da_beeper(), 0);
assert_eq!(init_custom.da_strings_count(), 4);
let all_nil = evaluate_param_text([None, None, None, None]);
for i in 0..4 {
assert!(!all_nil.has_update(i));
assert_eq!(all_nil.slot(i), None);
}
let initial_slots = [
b"apple".to_vec(),
b"banana".to_vec(),
b"cherry".to_vec(),
b"date".to_vec(),
];
assert_eq!(all_nil.merged_with(&initial_slots), initial_slots);
let mut target = initial_slots.clone();
all_nil.apply_to(&mut target);
assert_eq!(target, initial_slots);
let selective = evaluate_param_text([Some(b"avocado"), None, Some(b"cantaloupe"), None]);
assert!(selective.has_update(0));
assert!(!selective.has_update(1));
assert!(selective.has_update(2));
assert!(!selective.has_update(3));
assert_eq!(selective.slot(0), Some(b"avocado".as_slice()));
assert_eq!(selective.slot(1), None);
assert_eq!(selective.slot(2), Some(b"cantaloupe".as_slice()));
assert_eq!(selective.slot(3), None);
let merged = selective.merged_with(&initial_slots);
assert_eq!(merged[0], b"avocado");
assert_eq!(merged[1], b"banana");
assert_eq!(merged[2], b"cantaloupe");
assert_eq!(merged[3], b"date");
let mut target = initial_slots.clone();
selective.apply_to(&mut target);
assert_eq!(target, merged);
let decoded = selective.decoded_strings(&initial_slots);
assert_eq!(
decoded,
[
"avocado".to_string(),
"banana".to_string(),
"cantaloupe".to_string(),
"date".to_string()
]
);
let long_bytes = vec![b'X'; 300];
let clamped = evaluate_param_text([Some(&long_bytes), None, None, None]);
assert_eq!(clamped.slot(0).unwrap().len(), 255);
assert_eq!(clamped.slot(0).unwrap(), &vec![b'X'; 255][..]);
}
#[test]
fn find_dialog_item_and_dialog_record_init_evaluation() {
let init = evaluate_dialog_record_init(0x1234_5678);
assert_eq!(init.window_kind(), 2);
assert_eq!(init.items_handle(), 0x1234_5678);
assert_eq!(init.text_handle(), 0);
assert_eq!(init.edit_field(), -1);
assert_eq!(init.edit_open(), 0);
assert_eq!(init.default_item(), 1);
assert_eq!(evaluate_find_dialog_item_query(0, 10, 20), None);
assert_eq!(evaluate_find_dialog_item_packed(0, 0x000A_0014), None);
let query = evaluate_find_dialog_item_query(0x1000, 15, 25).unwrap();
assert_eq!(query.dialog_ptr(), 0x1000);
assert_eq!(query.pt_v(), 15);
assert_eq!(query.pt_h(), 25);
assert_eq!(query.point(), (15, 25));
assert_eq!(query.packed_point(), 0x000F_0019);
let packed_query = evaluate_find_dialog_item_packed(0x2000, 0x000F_0019).unwrap();
assert_eq!(packed_query.dialog_ptr(), 0x2000);
assert_eq!(packed_query.pt_v(), 15);
assert_eq!(packed_query.pt_h(), 25);
assert_eq!(packed_query.point(), (15, 25));
let neg_query = evaluate_find_dialog_item_query(0x3000, -10, -20).unwrap();
assert_eq!(neg_query.pt_v(), -10);
assert_eq!(neg_query.pt_h(), -20);
let from_packed_neg =
evaluate_find_dialog_item_packed(0x3000, neg_query.packed_point()).unwrap();
assert_eq!(from_packed_neg.pt_v(), -10);
assert_eq!(from_packed_neg.pt_h(), -20);
}
#[test]
fn alert_stage_and_sound_evaluation() {
let stages = 0xF721;
let eval0 = evaluate_alert_stage(stages, 0);
assert_eq!(eval0.stage_index(), 0);
assert_eq!(eval0.stage_nibble(), 0x01);
assert!(!eval0.box_drawn());
assert_eq!(eval0.default_item(), 1);
assert_eq!(eval0.effective_default_item(), None);
assert_eq!(eval0.sound_number(), 1);
assert!(eval0.has_sound());
assert_eq!(eval0.next_stage(), 1);
assert_eq!(eval0.suppressed_result(), ALERT_SUPPRESSED_RESULT);
let eval1 = evaluate_alert_stage(stages, 1);
assert_eq!(eval1.stage_index(), 1);
assert_eq!(eval1.stage_nibble(), 0x02);
assert!(!eval1.box_drawn());
assert_eq!(eval1.default_item(), 1);
assert_eq!(eval1.effective_default_item(), None);
assert_eq!(eval1.sound_number(), 2);
assert!(eval1.has_sound());
assert_eq!(eval1.next_stage(), 2);
let eval2 = evaluate_alert_stage(stages, 2);
assert_eq!(eval2.stage_index(), 2);
assert_eq!(eval2.stage_nibble(), 0x07);
assert!(eval2.box_drawn());
assert_eq!(eval2.default_item(), 1);
assert_eq!(eval2.effective_default_item(), Some(1));
assert_eq!(eval2.sound_number(), 3);
assert!(eval2.has_sound());
assert_eq!(eval2.next_stage(), 3);
let eval3 = evaluate_alert_stage(stages, 3);
assert_eq!(eval3.stage_index(), 3);
assert_eq!(eval3.stage_nibble(), 0x0F);
assert!(eval3.box_drawn());
assert_eq!(eval3.default_item(), 2);
assert_eq!(eval3.effective_default_item(), Some(2));
assert_eq!(eval3.sound_number(), 3);
assert!(eval3.has_sound());
assert_eq!(eval3.next_stage(), 3);
let eval_clamped = evaluate_alert_stage(stages, 99);
assert_eq!(eval_clamped.stage_index(), 3);
assert_eq!(eval_clamped.next_stage(), 3);
let silent_eval = evaluate_alert_stage(0x0004, 0);
assert_eq!(silent_eval.sound_number(), 0);
assert!(!silent_eval.has_sound());
assert!(silent_eval.box_drawn());
assert_eq!(silent_eval.effective_default_item(), Some(1));
let inv_drawn = evaluate_alert_invocation(128, stages, 2);
assert_eq!(inv_drawn.alert_id(), 128);
assert_eq!(inv_drawn.anumber(), 128);
assert_eq!(inv_drawn.next_stage(), 3);
assert!(!inv_drawn.is_suppressed());
assert_eq!(inv_drawn.default_item(), Some(1));
assert_eq!(inv_drawn.sound_number(), 3);
assert!(inv_drawn.has_sound());
assert_eq!(inv_drawn.suppressed_result(), -1);
let inv_suppressed = evaluate_alert_invocation(-300, stages, 0);
assert_eq!(inv_suppressed.alert_id(), -300);
assert_eq!(inv_suppressed.anumber(), (-300i16) as u16);
assert_eq!(inv_suppressed.next_stage(), 1);
assert!(inv_suppressed.is_suppressed());
assert_eq!(inv_suppressed.default_item(), None);
assert_eq!(inv_suppressed.sound_number(), 1);
assert!(inv_suppressed.has_sound());
assert_eq!(inv_suppressed.suppressed_result(), -1);
let err_sound = evaluate_error_sound(0x00AB_CDEF);
assert_eq!(err_sound.sound_proc(), 0x00AB_CDEF);
assert!(!err_sound.is_silent());
let err_silent = evaluate_error_sound(0);
assert_eq!(err_silent.sound_proc(), 0);
assert!(err_silent.is_silent());
}
#[test]
fn new_dialog_parameters_and_storage_policy_evaluation() {
let alloc_policy = evaluate_dialog_storage_policy(0);
assert_eq!(alloc_policy, DialogStoragePolicy::AllocateNew);
assert!(!alloc_policy.is_caller_supplied());
assert!(alloc_policy.is_allocate_new());
assert_eq!(alloc_policy.caller_storage(), None);
let caller_policy = evaluate_dialog_storage_policy(0x0012_3456);
assert_eq!(caller_policy, DialogStoragePolicy::CallerSupplied(0x0012_3456));
assert!(caller_policy.is_caller_supplied());
assert!(!caller_policy.is_allocate_new());
assert_eq!(caller_policy.caller_storage(), Some(0x0012_3456));
let err = evaluate_new_dialog_parameters(
0, 0, 0x1000, true, 1, 0xFFFF_FFFF, false, 0x2000, 0x3000, false,
);
assert_eq!(err, Err(DIALOG_PARAM_ERR));
let params = evaluate_new_dialog_parameters(
0x0001_0000,
0x0002_0000,
0x0003_0000,
true,
16,
0xFFFF_FFFF,
true,
0xCAFE_BABE,
0x0004_0000,
true,
)
.expect("valid bounds should succeed");
assert_eq!(params.storage(), 0x0001_0000);
assert_eq!(params.storage_policy(), DialogStoragePolicy::CallerSupplied(0x0001_0000));
assert_eq!(params.bounds_ptr(), 0x0002_0000);
assert_eq!(params.title_ptr(), 0x0003_0000);
assert!(params.is_visible());
assert_eq!(params.proc_id(), 16);
assert_eq!(params.behind(), 0xFFFF_FFFF);
assert!(params.go_away());
assert_eq!(params.ref_con(), 0xCAFE_BABE);
assert_eq!(params.items(), 0x0004_0000);
assert!(params.is_color());
assert!(params.has_title());
assert!(params.has_items());
let minimal_params = evaluate_new_dialog_parameters(
0,
0x0002_0000,
0,
false,
0,
0,
false,
0,
0,
false,
)
.expect("minimal parameters should succeed");
assert_eq!(minimal_params.storage(), 0);
assert_eq!(minimal_params.storage_policy(), DialogStoragePolicy::AllocateNew);
assert!(!minimal_params.is_visible());
assert_eq!(minimal_params.proc_id(), 0);
assert_eq!(minimal_params.behind(), 0);
assert!(!minimal_params.go_away());
assert_eq!(minimal_params.ref_con(), 0);
assert_eq!(minimal_params.items(), 0);
assert!(!minimal_params.is_color());
assert!(!minimal_params.has_title());
assert!(!minimal_params.has_items());
}
#[test]
fn get_and_set_dialog_item_query_and_parameters_evaluation() {
assert_eq!(DITL_ITEM_HANDLE_OFFSET, 0);
assert_eq!(DITL_ITEM_RECT_OFFSET, 4);
assert_eq!(DITL_ITEM_TYPE_OFFSET, 12);
assert_eq!(DITL_ITEM_DATA_LEN_OFFSET, 13);
assert_eq!(evaluate_get_dialog_item_query(0, 1), None);
assert_eq!(evaluate_get_dialog_item_query(0x1000, 0), None);
let query = evaluate_get_dialog_item_query(0x0001_2340, 3)
.expect("valid query parameters should succeed");
assert_eq!(query.dialog_ptr(), 0x0001_2340);
assert_eq!(query.item_number(), 3);
assert_eq!(query.item_no(), 3);
assert_eq!(
evaluate_set_dialog_item_parameters(0, 1, 4, 0x2000, (10, 20, 30, 40)),
None
);
assert_eq!(
evaluate_set_dialog_item_parameters(0x1000, 0, 4, 0x2000, (10, 20, 30, 40)),
None
);
let enabled_btn = evaluate_set_dialog_item_parameters(
0x0005_6780,
2,
DIALOG_ITEM_BUTTON as u16,
0x000A_BC00,
(50, 60, 70, 80),
)
.expect("valid set parameters should succeed");
assert_eq!(enabled_btn.dialog_ptr(), 0x0005_6780);
assert_eq!(enabled_btn.item_number(), 2);
assert_eq!(enabled_btn.item_no(), 2);
assert_eq!(enabled_btn.item_type(), DIALOG_ITEM_BUTTON);
assert_eq!(enabled_btn.base_type(), DIALOG_ITEM_BUTTON);
assert!(enabled_btn.is_enabled());
assert_eq!(enabled_btn.item_handle(), 0x000A_BC00);
assert_eq!(enabled_btn.rect(), (50, 60, 70, 80));
let disabled_user = evaluate_set_dialog_item_parameters(
0x0005_6780,
5,
(DIALOG_ITEM_USER_ITEM | DIALOG_ITEM_DISABLED_FLAG) as u16,
0x000D_EF00,
(100, 110, 120, 130),
)
.expect("valid disabled item parameters should succeed");
assert_eq!(disabled_user.item_number(), 5);
assert_eq!(disabled_user.base_type(), DIALOG_ITEM_USER_ITEM);
assert!(!disabled_user.is_enabled());
assert_eq!(disabled_user.item_handle(), 0x000D_EF00);
assert_eq!(disabled_user.rect(), (100, 110, 120, 130));
}
}