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",
];
const AHK_VERSION: &str = "2.0.19";
const NOT_WINDOWS: &str = "this is a name of Windows, and this desktop is not Windows.";
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_SCRIPT_HWND: &str =
"this runtime has no window of its own: it is a script that runs and ends.";
const NO_SCREEN_DPI: &str = "this desktop does not know the scale of the output.";
const NO_TRAY_ICON: &str = "this runtime has no tray icon.";
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>> {
let name = spelled(name)?;
match kind_of(&name)? {
Kind::Known => Some(Ok(known_value(&name, rt))),
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 => 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 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 => 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 })?;
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 => 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"
| "cursor"
| "defaultmousespeed"
| "detecthiddentext"
| "detecthiddenwindows"
| "fileencoding"
| "keydelay"
| "keydelayplay"
| "keyduration"
| "keydurationplay"
| "listlines"
| "menumaskkey"
| "mousedelay"
| "mousedelayplay"
| "regview"
| "sendlevel"
| "sendmode"
| "storecapslockmode"
| "titlematchmode"
| "titlematchmodespeed"
| "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" | "screendpi"
| "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" => 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" => Value::Text(AHK_VERSION.to_string()),
"is64bitos" => Value::Int((core::mem::size_of::<usize>() == 8) as i64),
"ptrsize" => Value::Int(core::mem::size_of::<usize>() as i64),
"iscompiled" | "iscritical" | "ispaused" | "issuspended" => Value::Int(0),
"tickcount" => Value::Int(rt.now_ms() 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" | "scriptdir" => match rt.initial_working_dir() {
Some(directory) => Ok(Value::Text(directory.to_string())),
None => Err(reason(NO_INITIAL_WORKING_DIR)),
},
"scriptname" | "scriptfullpath" | "icontip" => Ok(Value::Text("*".to_string())),
"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)),
_ => Err(reason(NO_SUCH_MACHINE_NAME)),
}
}
fn machine_refusal(name: &str) -> Option<&'static str> {
Some(match name {
"windir" | "programfiles" => NOT_WINDOWS,
"ahkpath" => NO_AHK_PATH,
"scripthwnd" => NO_SCRIPT_HWND,
"screendpi" => NO_SCREEN_DPI,
"iconfile" | "iconnumber" | "traymenu" => NO_TRAY_ICON,
_ => 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,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::date::NO_DATE;
use crate::desktop::{
Clipboard, 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.19.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 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.19".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();
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()));
assert!(reason("a_cursor").contains("shape of the cursor"));
}
#[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_some());
assert!(refusal_of("ScriptHwnd").is_some());
}
#[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:?}"
);
}
}