use alloc::format;
use alloc::string::ToString;
use alloc::string::String;
use crate::ast::AssignOp;
use crate::runtime::{Runtime, RuntimeError, Value};
pub const THE_RUNTIME_OWNS: &[&str] = &[
"index",
"linefile",
"linenumber",
"loopfield",
"loopfileattrib",
"loopfiledir",
"loopfileext",
"loopfilefullpath",
"loopfilename",
"loopfilepath",
"loopfileshortname",
"loopfileshortpath",
"loopfilesize",
"loopfilesizekb",
"loopfilesizemb",
"loopfiletimeaccessed",
"loopfiletimecreated",
"loopfiletimemodified",
"loopreadline",
"loopregkey",
"loopregname",
"loopregtimemodified",
"loopregtype",
"thisfunc",
];
pub const AHK_VERSION: &str = "2.0.31";
pub(crate) const NO_SHORT_NAMES_OF_THE_FILES: &str =
"the short names of the files are a thing of Windows, and this desktop is not Windows.";
const NO_SUCH_FOLDER: &str = "the machine has no such folder.";
const NO_DESKTOP_COMMON: &str =
"the machine has no desktop for everybody: the desktop of the session is the one of the user.";
const NO_PROGRAMS: &str = "the machine has no programs folder: the start menu of the user is the folder of the applications.";
const NO_PROGRAMS_COMMON: &str = "the machine has no programs folder for everybody: the start menu is the folder of the applications.";
const NO_AHK_PATH: &str = "this runtime is not AutoHotkey, and it has no path of an executable.";
const NO_SCREEN_DPI: &str = "this desktop does not know the scale of the output.";
const NO_INITIAL_WORKING_DIR: &str =
"this runtime does not keep the directory where the run started.";
pub(crate) fn read_only(name: &str, op: AssignOp) -> String {
match op {
AssignOp::Set => {
format!(
"This built-in variable cannot be used as an output variable.\n Specifically: {name}"
)
}
_ => {
format!("This built-in variable cannot be assigned a value.\n Specifically: {name}")
}
}
}
const WRITABLE: &[&str] = &[
"clipboard",
"workingdir",
"eventinfo",
"hotkeyinterval",
"hotkeymodifiertimeout",
"iconhidden",
"icontip",
"lasterror",
"maxhotkeysperinterval",
"scriptname",
"allowmainwindow",
"controldelay",
"coordmodecaret",
"coordmodemenu",
"coordmodemouse",
"coordmodepixel",
"coordmodetooltip",
"defaultmousespeed",
"detecthiddentext",
"detecthiddenwindows",
"fileencoding",
"keydelay",
"keydelayplay",
"keyduration",
"keydurationplay",
"listlines",
"menumaskkey",
"mousedelay",
"mousedelayplay",
"regview",
"sendlevel",
"sendmode",
"storecapslockmode",
"titlematchmode",
"titlematchmodespeed",
"windelay",
"index",
];
pub(crate) fn is_read_only(name: &str) -> bool {
let Some(spelled) = spelled(name) else {
return false;
};
is_built_in(name) && !WRITABLE.contains(&spelled.as_str())
}
const NO_SUCH_MACHINE_NAME: &str = "this runtime does not carry this name of the machine.";
pub(crate) fn lookup(name: &str, rt: &mut Runtime) -> Option<Result<Value, RuntimeError>> {
if rt.dialect().carries_the_variable_of_the_extension(name) {
return Some(the_extension_value(name, rt));
}
let name = spelled(name)?;
match kind_of(&name)? {
Kind::Known => Some(Ok(known_value(&name, rt))),
Kind::State if name == "cursor" => Some(match rt.desktop().cursor_shape() {
Ok(shape) => Ok(Value::Text(shape)),
Err(message) => Err(reason(&message)),
}),
Kind::State => Some(match crate::settings::value_of(&name) {
Some(Ok(value)) => Ok(value),
Some(Err(why)) => Err(reason(why)),
None => Err(reason(crate::settings::NO_STATE)),
}),
Kind::Date => Some(crate::date::variable_value(&name, rt)),
Kind::Machine => Some(machine_value(&name, rt)),
Kind::Clipboard => Some(match rt.desktop().clipboard_read() {
Ok(text) => Ok(Value::Text(text)),
Err(message) => Err(reason(&message)),
}),
Kind::Hotkey => crate::hotkeys::variable(&name, rt),
Kind::Screen if name == "screendpi" => Some(match rt.desktop().screen_dpi() {
Ok(dots) => Ok(Value::Int(dots)),
Err(message) => Err(reason(&message)),
}),
Kind::Screen => Some(match rt.desktop().screen_size() {
Ok((width, height)) => Ok(Value::Int(if name == "screenwidth" {
width
} else {
height
})),
Err(message) => Err(reason(&message)),
}),
}
}
pub(crate) fn spelled(name: &str) -> Option<String> {
let mut letters = name.chars();
if !letters.next()?.eq_ignore_ascii_case(&'a') || !letters.next()?.eq_ignore_ascii_case(&'_') {
return None;
}
let lower = name.to_lowercase();
lower.strip_prefix("a_").map(|rest| rest.to_string())
}
fn in_the_table(name: &str) -> String {
let lower = name.to_lowercase();
lower
.strip_prefix("a_")
.unwrap_or(lower.as_str())
.to_string()
}
pub(crate) fn write(
name: &str,
op: AssignOp,
value: &Value,
line: u32,
rt: &mut Runtime,
) -> Option<Result<Value, RuntimeError>> {
if is_read_only(name) {
return Some(Err(reason(&read_only(name, op))));
}
match spelled(name).as_deref() {
Some("clipboard") => Some(write_to_the_clipboard(op, value, line, rt)),
Some("workingdir") => Some(write_the_working_directory(op, value, line, rt)),
_ => None,
}
}
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Written {
Any,
Number,
Unsigned,
Flag,
Strict { lowest: i64, highest: i64 },
}
pub(crate) fn the_kind_of_the_write(name: &str) -> Option<Written> {
let name = spelled(name)?;
Some(match name.as_str() {
"scriptname" | "icontip" | "hotkeymodifiertimeout" => Written::Any,
"eventinfo" => Written::Number,
"lasterror" => Written::Unsigned,
"iconhidden" => Written::Flag,
"hotkeyinterval" => Written::Strict {
lowest: 0,
highest: 2147483647,
},
"maxhotkeysperinterval" => Written::Strict {
lowest: 1,
highest: 2147483647,
},
_ => return None,
})
}
pub(crate) fn the_written_value(
kind: Written,
value: &Value,
line: u32,
) -> Result<Value, RuntimeError> {
Ok(match kind {
Written::Any => value.clone(),
Written::Number => Value::Int(value.to_number_lenient() as i64),
Written::Unsigned => Value::Int(value.to_number_lenient() as i64 as u32 as i64),
Written::Flag => Value::Int(value.truthy() as i64),
Written::Strict { lowest, highest } => {
let number = value.to_number_strict().map_err(|_| RuntimeError {
message: crate::runtime::expected_number(value),
line,
})? as i64;
if number < lowest || number > highest {
return Err(RuntimeError {
message: crate::settings::INVALID_VALUE.to_string(),
line,
});
}
Value::Int(number)
}
})
}
fn write_the_working_directory(
op: AssignOp,
value: &Value,
line: u32,
rt: &mut Runtime,
) -> Result<Value, RuntimeError> {
match op {
AssignOp::Set => {}
_ => {
return Err(RuntimeError {
message: "the working directory is set with the assignment, and the other operators do not make a path of it.".into(),
line,
})
}
}
let path = value.to_text();
rt.desktop()
.set_working_directory(&path)
.map_err(|why| reason(&why))?;
Ok(Value::Text(path))
}
fn write_to_the_clipboard(
op: AssignOp,
value: &Value,
line: u32,
rt: &mut Runtime,
) -> Result<Value, RuntimeError> {
match op {
AssignOp::Set => {
if let Value::Object(object) = value {
if object.borrow().class == "clipboardall" {
if let Some(bytes) = crate::classes::clipboard::the_bytes(value) {
rt.desktop().clipboard_write_all(&bytes).map_err(|message| {
RuntimeError { message, line }
})?;
return read_the_clipboard(rt, line).map(Value::Text);
}
}
}
put_on_the_clipboard(rt, &value.to_text(), line)
}
AssignOp::Concat => {
let current = read_the_clipboard(rt, line)?;
put_on_the_clipboard(rt, &format!("{current}{}", value.to_text()), line)
}
_ => {
let current = read_the_clipboard(rt, line)?;
Err(RuntimeError {
message: crate::runtime::expected_number(&Value::Text(current)),
line,
})
}
}
}
fn read_the_clipboard(rt: &mut Runtime, line: u32) -> Result<String, RuntimeError> {
rt.desktop()
.clipboard_read()
.map_err(|message| RuntimeError { message, line })
}
fn put_on_the_clipboard(rt: &mut Runtime, text: &str, line: u32) -> Result<Value, RuntimeError> {
rt.desktop()
.clipboard_write(text)
.map_err(|message| RuntimeError { message, line })?;
if let Some(name) = rt.the_clipboard_watcher().map(str::to_string) {
rt.call_a_function_for_a_built_in(&name, &[Value::Int(1)], line)?;
}
Ok(Value::Text(text.to_string()))
}
pub fn is_built_in(name: &str) -> bool {
let Some(rest) = spelled(name) else {
return false;
};
kind_of(&rest).is_some() || THE_RUNTIME_OWNS.contains(&rest.as_str())
}
pub fn refusal_of(name: &str) -> Option<&'static str> {
let name = in_the_table(name);
match kind_of(&name)? {
Kind::Known | Kind::Date | Kind::Hotkey | Kind::Screen | Kind::Clipboard => None,
Kind::State if name == "cursor" => None,
Kind::State => match crate::settings::value_of(&name) {
Some(Ok(_)) => None,
Some(Err(why)) => Some(why),
None => Some(crate::settings::NO_STATE),
},
Kind::Machine => machine_refusal(&name),
}
}
pub fn carries(name: &str) -> bool {
let name = in_the_table(name);
kind_of(&name).is_some() || THE_RUNTIME_OWNS.contains(&name.as_str())
}
fn kind_of(name: &str) -> Option<Kind> {
match name {
"ahkversion" | "is64bitos" | "ptrsize" | "iscompiled" | "iscritical" | "ispaused"
| "issuspended" | "tickcount" | "endchar" | "space" | "tab" => Some(Kind::Known),
"allowmainwindow"
| "controldelay"
| "coordmodecaret"
| "coordmodemenu"
| "coordmodemouse"
| "coordmodepixel"
| "coordmodetooltip"
| "defaultmousespeed"
| "detecthiddentext"
| "detecthiddenwindows"
| "fileencoding"
| "keydelay"
| "keydelayplay"
| "keyduration"
| "keydurationplay"
| "listlines"
| "menumaskkey"
| "mousedelay"
| "mousedelayplay"
| "regview"
| "sendlevel"
| "sendmode"
| "storecapslockmode"
| "titlematchmode"
| "titlematchmodespeed"
| "cursor"
| "windelay" => Some(Kind::State),
"dd" | "ddd" | "dddd" | "hour" | "mday" | "min" | "mm" | "mmm" | "mmmm" | "mon"
| "msec" | "now" | "nowutc" | "sec" | "wday" | "yday" | "year" | "yweek" | "yyyy" => {
Some(Kind::Date)
}
"ahkpath" | "appdata" | "appdatacommon" | "computername" | "comspec" | "desktop"
| "desktopcommon" | "eventinfo" | "iconfile" | "iconhidden" | "iconnumber" | "icontip"
| "initialworkingdir" | "isadmin" | "language" | "lasterror" | "mydocuments"
| "osversion" | "programfiles" | "programs" | "programscommon" | "scriptdir"
| "scriptfullpath" | "scripthwnd" | "scriptname" | "startmenu" | "startmenucommon"
| "startup" | "startupcommon" | "temp" | "timeidle" | "timeidlekeyboard"
| "timeidlemouse" | "timeidlephysical" | "traymenu" | "username" | "windir"
| "workingdir" => Some(Kind::Machine),
"clipboard" => Some(Kind::Clipboard),
"screenheight" | "screenwidth" | "screendpi" => Some(Kind::Screen),
"hotkeyinterval"
| "hotkeymodifiertimeout"
| "maxhotkeysperinterval"
| "priorhotkey"
| "priorkey"
| "thishotkey"
| "timesincepriorhotkey"
| "timesincethishotkey" => Some(Kind::Hotkey),
_ => None,
}
}
#[derive(Clone, Copy, PartialEq)]
enum Kind {
Known,
State,
Date,
Machine,
Clipboard,
Hotkey,
Screen,
}
fn known_value(name: &str, rt: &Runtime) -> Value {
match name {
"ahkversion" => {
let (a, b, c, d) = rt.dialect().version();
if d == 0 {
Value::Text(alloc::format!("{a}.{b}.{c}"))
} else {
Value::Text(alloc::format!("{a}.{b}.{c}.{d:02}"))
}
}
"is64bitos" => Value::Int((core::mem::size_of::<usize>() == 8) as i64),
"ptrsize" => Value::Int(core::mem::size_of::<usize>() as i64),
"iscompiled" => Value::Int(0),
"iscritical" => {
if rt.dialect().is_the_v1() {
Value::Int(if rt.is_critical() { 16 } else { 0 })
} else {
Value::Int(0)
}
}
"issuspended" => Value::Int(rt.is_suspended() as i64),
"ispaused" => Value::Int(rt.is_paused() as i64),
"tickcount" => Value::Int(rt.tick_count() as i64),
"endchar" => Value::Text("\r".to_string()),
"space" => Value::Text(" ".to_string()),
"tab" => Value::Text("\t".to_string()),
_ => Value::Text(String::new()),
}
}
fn machine_value(name: &str, rt: &mut Runtime) -> Result<Value, RuntimeError> {
if let Some(why) = machine_refusal(name) {
return Err(reason(why));
}
match name {
"username" => text(rt.desktop().user_name()),
"computername" => text(rt.desktop().computer_name()),
"comspec" => text(rt.desktop().shell()),
"osversion" => text(rt.desktop().os_version()),
"language" => text(rt.desktop().language()),
"isadmin" => rt
.desktop()
.is_admin()
.map(|yes| Value::Int(yes as i64))
.map_err(|why| reason(&why)),
"initialworkingdir" => match rt.initial_working_dir() {
Some(directory) => Ok(Value::Text(directory.to_string())),
None => Err(reason(NO_INITIAL_WORKING_DIR)),
},
"scriptdir" => match rt.script_path() {
Some(path) => Ok(Value::Text(
crate::builtins::split_the_path(path)[1].clone(),
)),
None => match rt.initial_working_dir() {
Some(directory) => Ok(Value::Text(directory.to_string())),
None => Err(reason(NO_INITIAL_WORKING_DIR)),
},
},
"scriptname" => match rt.script_path() {
Some(path) => Ok(Value::Text(
crate::builtins::split_the_path(path)[0].clone(),
)),
None => Ok(Value::Text("*".to_string())),
},
"scriptfullpath" => match rt.script_path() {
Some(path) => Ok(Value::Text(path.to_string())),
None => Ok(Value::Text("*".to_string())),
},
"icontip" => Ok(Value::Text("*".to_string())),
"scripthwnd" => rt
.desktop()
.script_window()
.map(Value::Int)
.map_err(|why| reason(&why)),
"windir" => text(rt.desktop().windows_directory()),
"programfiles" => text(rt.desktop().program_files()),
"appdata" | "appdatacommon" | "desktop" | "desktopcommon" | "startmenu"
| "startmenucommon" | "programs" | "programscommon" | "startup" | "startupcommon"
| "mydocuments" | "temp" => folder(rt, name),
"timeidle" | "timeidlephysical" | "timeidlekeyboard" | "timeidlemouse" => idle(rt, name),
"workingdir" => text(rt.desktop().working_directory()),
"eventinfo" => Ok(Value::Int(0)),
"lasterror" => Ok(Value::Int(0)),
"iconhidden" => Ok(Value::Int(1)),
"iconfile" => Ok(Value::Text(
rt.the_icon_of_the_script()
.map(|(file, _)| file.clone())
.unwrap_or_default(),
)),
"iconnumber" => Ok(Value::Int(
rt.the_icon_of_the_script()
.map(|(_, number)| *number)
.unwrap_or(0),
)),
"traymenu" => Ok(rt.the_tray_menu(0)),
"ahkpath" => rt
.desktop()
.executable()
.map(Value::Text)
.map_err(|_| reason(NO_AHK_PATH)),
_ => Err(reason(NO_SUCH_MACHINE_NAME)),
}
}
fn machine_refusal(name: &str) -> Option<&'static str> {
Some(match name {
"screendpi" => NO_SCREEN_DPI,
_ => return None,
})
}
fn text(answer: Result<String, String>) -> Result<Value, RuntimeError> {
answer.map(Value::Text).map_err(|why| reason(&why))
}
fn folder(rt: &mut Runtime, name: &str) -> Result<Value, RuntimeError> {
let folders = rt.desktop().folders().map_err(|why| reason(&why))?;
let path = match name {
"appdata" => folders.app_data.clone(),
"appdatacommon" => folders.app_data_common.clone(),
"desktop" => folders.desktop.clone(),
"desktopcommon" => folders.desktop_common.clone(),
"startmenu" => folders.start_menu.clone(),
"startmenucommon" => folders.start_menu_common.clone(),
"programs" => folders.programs.clone(),
"programscommon" => folders.programs_common.clone(),
"startup" => folders.startup.clone(),
"startupcommon" => folders.startup_common.clone(),
"mydocuments" => folders.my_documents.clone(),
"temp" => folders.temp.clone(),
_ => None,
};
match path {
Some(path) => Ok(Value::Text(path)),
None => Err(reason(no_folder(name))),
}
}
fn no_folder(name: &str) -> &'static str {
match name {
"desktopcommon" => NO_DESKTOP_COMMON,
"programs" => NO_PROGRAMS,
"programscommon" => NO_PROGRAMS_COMMON,
_ => NO_SUCH_FOLDER,
}
}
fn idle(rt: &mut Runtime, name: &str) -> Result<Value, RuntimeError> {
let idle = rt.desktop().idle_times().map_err(|why| reason(&why))?;
let millis = match name {
"timeidle" => idle.any,
"timeidlephysical" => idle.physical,
"timeidlekeyboard" => idle.keyboard,
"timeidlemouse" => idle.mouse,
_ => 0,
};
Ok(Value::Int(millis as i64))
}
fn reason(message: &str) -> RuntimeError {
RuntimeError {
message: message.to_string(),
line: 0,
}
}
fn the_extension_value(name: &str, rt: &mut Runtime) -> Result<Value, RuntimeError> {
let lowered = name.to_lowercase();
let bare = lowered
.strip_prefix("a_")
.unwrap_or(lowered.strip_prefix('a').unwrap_or(lowered.as_str()));
match bare {
"realthread" => Ok(crate::classes::realthread::the_main_thread()),
"hotif" => Ok(Value::Text(rt.the_hotif().unwrap_or_default())),
"timers" => {
let timers = rt.the_timers();
let mut items = Vec::new();
for (function, period, last) in timers {
items.push(crate::classes::timer::the_timer(&function, period, last));
}
match crate::classes::array::construct(&items, rt, 0) {
Ok(array) => Ok(array),
Err(failure) => Err(RuntimeError {
message: crate::runtime::the_message_of(&failure),
line: 0,
}),
}
}
"nowms" | "nowutcms" => match rt.wall_clock() {
Some(clock) => {
let date = if bare == "nowms" {
&clock.local
} else {
&clock.utc
};
Ok(Value::Text(alloc::format!(
"{}.{:02}",
crate::date::the_number_text(date),
date.millisecond / 10
)))
}
None => Err(reason(crate::date::NO_DATE)),
},
"dirseparator" => Ok(Value::Text(if cfg!(windows) {
"\\".to_string()
} else {
"/".to_string()
})),
"newline" => Ok(Value::Text("\n".to_string())),
"true" => Ok(Value::Int(1)),
"false" => Ok(Value::Int(0)),
"thread" => Ok(rt.the_current_thread()),
"keybdhookinstalled" | "mousehookinstalled" => Ok(Value::Int(0)),
"loopregvalue" => Ok(Value::Unset),
"defaulthotstringcasesensitive" => Ok(Value::Int(0)),
"defaulthotstringconformtocase" => Ok(Value::Int(1)),
"defaulthotstringdetectwheninsideword" => Ok(Value::Int(0)),
"defaulthotstringdobackspace" => Ok(Value::Int(1)),
"defaulthotstringdoreset" => Ok(Value::Int(0)),
"defaulthotstringendcharrequired" => Ok(Value::Int(1)),
"defaulthotstringendchars" => Ok(Value::Text("-()[]{}:;'\"/\\,.?!\r\n \t".to_string())),
"defaulthotstringkeydelay" => Ok(Value::Int(0)),
"defaulthotstringnomouse" => Ok(Value::Int(0)),
"defaulthotstringomitendchar" => Ok(Value::Int(0)),
"defaulthotstringpriority" => Ok(Value::Int(0)),
"defaulthotstringsendmode" => Ok(Value::Text("Input".to_string())),
"defaulthotstringsendraw" => Ok(Value::Int(0)),
"clipboardtimeout" => Ok(Value::Int(1000)),
"hotiftimeout" => Ok(Value::Int(250)),
"maxthreads" => Ok(Value::Int(10)),
"maxthreadsbuffer" => Ok(Value::Int(0)),
"maxthreadsperhotkey" => Ok(Value::Int(1)),
"peekfrequency" => Ok(Value::Int(0)),
"persistent" => Ok(Value::Int(rt.the_script_is_persistent() as i64)),
"winactivateforce" => Ok(Value::Int(0)),
"notrayicon" => Ok(Value::Int(1)),
"osarch" | "processarch" => Ok(Value::Text(arch_name().to_string())),
"ostype" => Ok(Value::Text(if cfg!(windows) {
"WINDOWS".to_string()
} else if cfg!(target_os = "macos") {
"OSX".to_string()
} else if cfg!(target_os = "linux") {
"LINUX".to_string()
} else {
"UNKNOWN".to_string()
})),
"ksversion" => Ok(Value::Text(env!("CARGO_PKG_VERSION").to_string())),
"kscorepath" => rt
.desktop()
.executable()
.map(Value::Text)
.map_err(|why| reason(&why)),
"guitheme" => Ok(Value::Text(if cfg!(windows) {
"System".to_string()
} else {
"Classic".to_string()
})),
_ => Err(reason(crate::dialect::NOT_CARRIED_YET)),
}
}
fn arch_name() -> &'static str {
if cfg!(target_arch = "x86_64") {
"X64"
} else if cfg!(target_arch = "aarch64") {
"ARM64"
} else if cfg!(target_arch = "x86") {
"X86"
} else if cfg!(target_arch = "arm") {
"ARM"
} else {
"UNKNOWN"
}
}
use alloc::vec::Vec;
#[cfg(test)]
mod tests {
use super::*;
use crate::date::NO_DATE;
use crate::desktop::{
Clipboard, Com, Desktop, Dialogs, Files, Hotkeys, Keyboard, Machine, Native, Network,
Pictures, Pointer, Processes, Screen, Sound, Timers, Windows,
};
use crate::runtime::Clock;
use alloc::string::String;
use core::time::Duration;
const SURFACE: &str = include_str!("../reference/ahk-v2.0.31.surface.tsv");
#[derive(Debug)]
struct Fake;
impl Desktop for Fake {}
impl Pictures for Fake {}
impl Network for Fake {}
impl Sound for Fake {}
impl Machine for Fake {}
impl Dialogs for Fake {}
impl Files for Fake {}
impl Clipboard for Fake {}
impl Timers for Fake {}
impl Hotkeys for Fake {}
impl Windows for Fake {}
impl Native for Fake {}
impl Com for Fake {}
impl Keyboard for Fake {
fn type_text(&mut self, _text: &str) -> Result<String, String> {
Ok(String::new())
}
fn press_key(&mut self, _name: &str, _modifiers: &[String]) -> Result<String, String> {
Ok(String::new())
}
}
impl Pointer for Fake {
fn click(
&mut self,
_x: i64,
_y: i64,
_button: &str,
_count: u32,
) -> Result<String, String> {
Ok(String::new())
}
}
impl Screen for Fake {
fn capture(
&mut self,
_x: i64,
_y: i64,
_width: i64,
_height: i64,
_filename: &str,
) -> Result<String, String> {
Ok(String::new())
}
fn pixel(&mut self, _x: i64, _y: i64) -> Result<String, String> {
Ok(String::new())
}
}
impl Processes for Fake {
fn run(&mut self, _command: &str, _window: &str) -> Result<(i32, String, String), String> {
Ok((0, String::new(), String::new()))
}
}
#[derive(Debug)]
struct TheClock;
impl Clock for TheClock {
fn now_ms(&self) -> u64 {
1234
}
fn sleep_ms(&mut self, _millis: u64) {}
}
fn answer(name: &str) -> Option<Result<Value, RuntimeError>> {
let mut desktop = Fake;
let mut clock = TheClock;
let mut rt = Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10));
lookup(name, &mut rt)
}
fn value(name: &str) -> Value {
match answer(name) {
Some(Ok(value)) => value,
Some(Err(_)) => panic!("{name} answered with a reason instead of a value"),
None => panic!("{name} is not a built-in variable"),
}
}
fn reason(name: &str) -> String {
match answer(name) {
Some(Err(error)) => error.message,
Some(Ok(value)) => panic!("{name} answered {value:?} instead of a reason"),
None => panic!("{name} is not a built-in variable"),
}
}
fn surface_variables() -> Vec<String> {
SURFACE
.lines()
.filter(|line| !line.starts_with('#'))
.filter_map(|line| {
let fields: Vec<&str> = line.split('\t').collect();
if fields.first() == Some(&"variable") {
fields.get(2).map(|name| name.to_lowercase())
} else {
None
}
})
.collect()
}
#[test]
fn the_surface_has_one_hundred_and_thirty_one_variables() {
assert_eq!(surface_variables().len(), 131);
}
#[test]
fn a_script_that_asks_for_the_version_is_told_the_version_of_the_dialect() {
assert_eq!(value("a_ahkversion"), Value::Text("2.0.31".into()));
}
#[test]
fn a_script_that_asks_for_the_size_of_a_pointer_is_told_the_size_of_a_pointer() {
let size = core::mem::size_of::<usize>() as i64;
assert_eq!(value("a_ptrsize"), Value::Int(size));
assert_eq!(value("a_is64bitos"), Value::Int((size == 8) as i64));
}
#[test]
fn a_script_that_asks_whether_the_program_is_compiled_is_told_it_is_not() {
assert_eq!(value("a_iscompiled"), Value::Int(0));
}
#[test]
fn a_script_that_asks_whether_the_runtime_is_critical_paused_or_suspended_is_told_it_is_not() {
assert_eq!(value("a_iscritical"), Value::Int(0));
assert_eq!(value("a_ispaused"), Value::Int(0));
assert_eq!(value("a_issuspended"), Value::Int(0));
}
#[test]
fn a_script_that_asks_for_the_tick_count_is_told_the_milliseconds_of_the_clock() {
assert_eq!(value("a_tickcount"), Value::Int(1234));
}
#[test]
fn a_script_that_asks_for_the_end_of_a_line_is_told_the_carriage_return() {
assert_eq!(value("a_endchar"), Value::Text("\r".into()));
}
#[test]
fn a_script_that_asks_for_the_space_and_the_tab_is_told_them() {
assert_eq!(value("a_space"), Value::Text(" ".into()));
assert_eq!(value("a_tab"), Value::Text("\t".into()));
}
#[test]
fn the_name_of_a_built_in_variable_does_not_matter() {
assert_eq!(value("A_AhkVersion"), value("a_ahkversion"));
assert_eq!(value("a_AHKVERSION"), value("a_ahkversion"));
}
#[test]
fn a_script_that_asks_for_the_date_is_told_the_clock_does_not_know_it() {
assert_eq!(reason("a_now"), NO_DATE);
assert_eq!(reason("a_nowutc"), NO_DATE);
assert_eq!(reason("a_msec"), NO_DATE);
assert_eq!(reason("a_year"), NO_DATE);
}
#[test]
fn a_script_that_asks_for_the_machine_is_told_what_the_desktop_cannot_answer() {
assert_eq!(
reason("a_computername"),
"this desktop cannot say the name of the computer"
);
assert_eq!(
reason("a_username"),
"this desktop cannot say the name of the user"
);
}
#[test]
fn a_script_that_asks_for_the_size_of_the_screen_is_told_by_the_desktop() {
assert_eq!(
reason("a_screenwidth"),
"this desktop cannot tell how big the screen is"
);
assert_eq!(
reason("a_screenheight"),
"this desktop cannot tell how big the screen is"
);
}
#[test]
fn a_script_that_asks_for_a_hotkey_is_answered_by_the_hotkey_system() {
assert_eq!(value("a_hotkeyinterval"), Value::Int(2000));
assert_eq!(value("a_maxhotkeysperinterval"), Value::Int(70));
assert_eq!(value("a_hotkeymodifiertimeout"), Value::Int(50));
assert_eq!(value("a_thishotkey"), Value::Text(String::new()));
assert_eq!(value("a_priorkey"), Value::Text(String::new()));
}
#[test]
fn a_script_that_asks_for_a_setting_is_answered_with_the_setting() {
let _turn = crate::settings::Turn::take();
crate::settings::put_the_state_back();
assert_eq!(value("a_coordmodemouse"), Value::Text("Client".to_string()));
assert_eq!(value("a_sendmode"), Value::Text("Input".to_string()));
assert_eq!(value("a_keydelay"), Value::Int(10));
assert_eq!(value("a_coordmodecaret"), Value::Text("Client".to_string()));
assert_eq!(value("a_controldelay"), Value::Int(20));
assert_eq!(value("a_regview"), Value::Text("Default".to_string()));
}
#[test]
fn the_shape_of_the_cursor_is_the_desktop_s_answer() {
assert!(refusal_of("a_cursor").is_none());
assert!(refusal_of("A_Cursor").is_none());
assert_eq!(
reason("a_cursor"),
"this desktop cannot tell the shape of the cursor"
);
}
#[test]
fn the_window_of_the_script_is_the_desktop_s_answer() {
assert!(refusal_of("a_scripthwnd").is_none());
assert!(refusal_of("A_ScriptHwnd").is_none());
assert_eq!(
reason("a_scripthwnd"),
"this desktop has no window of the script"
);
}
#[test]
fn a_name_without_the_prefix_is_not_a_built_in_variable() {
assert!(answer("isadmin").is_none());
assert!(answer("clipboard").is_none());
assert!(answer("now").is_none());
assert!(!is_built_in("isadmin"));
assert!(!is_built_in("clipboard"));
}
#[test]
fn the_table_carries_the_names_without_the_prefix() {
assert!(carries("clipboard"));
assert!(carries("Clipboard"));
assert!(carries("A_Clipboard"));
assert!(refusal_of("A_ScriptHwnd").is_none());
assert!(refusal_of("ScriptHwnd").is_none());
assert!(refusal_of("A_Cursor").is_none());
}
#[test]
fn the_variables_the_runtime_writes_where_it_runs_are_not_answered_here() {
assert!(answer("a_index").is_none());
assert!(answer("a_loopfilename").is_none());
assert!(answer("a_thisfunc").is_none());
}
#[test]
fn every_variable_of_the_surface_is_answered_or_is_the_runtime_s_own() {
let lost: Vec<String> = surface_variables()
.into_iter()
.filter(|name| !THE_RUNTIME_OWNS.contains(&name.as_str()))
.map(|name| format!("a_{name}"))
.filter(|name| answer(name).is_none())
.collect();
assert!(
lost.is_empty(),
"these variables of v2 are not answered: {lost:?}"
);
}
}