use alloc::format;
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;
use crate::ast::Node;
use crate::desktop::WindowAnswer;
use crate::keys;
use crate::runtime::{Route, Runtime, RuntimeError, RuntimeFailure, Value};
pub const DEVICE_VARIABLE: &str = "AHK_HOTKEY_DEVICE";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Hotkey,
Hotstring,
State,
}
#[derive(Debug, Clone)]
pub struct Hotkey {
pub name: String,
pub function: String,
pub enabled: bool,
pub kind: Kind,
pub line: u32,
pub object: Option<Value>,
pub shared: Rc<RefCell<Shared>>,
pub condition: Option<Condition>,
pub takes_name: bool,
pub body: Option<Vec<Node>>,
}
pub struct Shape {
pub kind: Kind,
pub name: String,
pub function: String,
pub takes_name: bool,
pub options: String,
pub object: Option<Value>,
}
#[derive(Debug, Default)]
pub struct Shared {
pub prior: Option<(String, u64)>,
pub current: Option<(String, u64)>,
pub condition: Option<Condition>,
}
#[derive(Debug, Clone)]
pub enum Condition {
Function(String),
WindowActive(String),
WindowExists(String),
WindowNotActive(String),
WindowNotExist(String),
Expression { node: Node, text: String },
}
pub(crate) fn the_text_of_a_condition(condition: &Condition) -> String {
match condition {
Condition::Function(name) => name.clone(),
Condition::WindowActive(title) => format!("WinActive(\"{}\")", title),
Condition::WindowExists(title) => format!("WinExist(\"{}\")", title),
Condition::WindowNotActive(title) => format!("!WinActive(\"{}\")", title),
Condition::WindowNotExist(title) => format!("!WinExist(\"{}\")", title),
Condition::Expression { text, .. } => text.clone(),
}
}
#[derive(Debug, Clone)]
pub struct Spec {
pub modifiers: Vec<String>,
pub key: String,
pub code: u16,
pub up: bool,
pub tilde: bool,
pub custom: bool,
}
pub fn parse(spec: &str) -> Result<Spec, String> {
let mut modifiers: Vec<String> = Vec::new();
let mut tilde = false;
let mut custom = false;
let mut rest = spec;
let mut marks: Vec<char> = Vec::new();
while let Some(first) = rest.chars().next() {
match first {
'~' if modifiers.is_empty() && !tilde => {
tilde = true;
rest = &rest[1..];
}
'*' if modifiers.is_empty() && !custom => {
custom = true;
rest = &rest[1..];
}
'$' if modifiers.is_empty() => {
rest = &rest[1..];
}
'<' | '>' => {
marks.push(first);
rest = &rest[1..];
}
'^' | '!' | '+' | '#' => {
marks.push(first);
rest = &rest[1..];
}
_ => break,
}
}
for (index, mark) in marks.iter().enumerate() {
if !matches!(mark, '^' | '!' | '+' | '#') {
continue;
}
let left = index > 0 && marks[index - 1] == '<';
let right = index + 1 < marks.len() && marks[index + 1] == '>';
for name in sides(*mark, left, right) {
modifiers.push(name);
}
}
let mut up = false;
if rest.len() > 3 && rest[rest.len() - 3..].eq_ignore_ascii_case(" up") {
up = true;
rest = &rest[..rest.len() - 3];
}
if rest.is_empty() {
let Some(modifier) = modifiers.pop() else {
return Err("Invalid key name.".to_string());
};
if modifiers.is_empty() {
let code =
keys::resolve_name(&modifier).map_err(|_| "Invalid key name.".to_string())?;
return Ok(Spec {
modifiers,
key: modifier,
code,
up,
tilde,
custom,
});
}
return Err("Invalid key name.".to_string());
}
if rest.contains(' ') {
return Err("Invalid hotkey.".to_string());
}
let code = keys::resolve_name(rest).map_err(|_| "Invalid key name.".to_string())?;
Ok(Spec {
modifiers,
key: rest.to_string(),
code,
up,
tilde,
custom,
})
}
fn sides(marker: char, left: bool, right: bool) -> Vec<String> {
let (name, right_name) = match marker {
'^' => ("ctrl", "rctrl"),
'!' => ("alt", "ralt"),
'+' => ("shift", "rshift"),
_ => ("win", "rwin"),
};
match (left, right) {
(true, true) => vec![name.to_string(), right_name.to_string()],
(true, false) => vec![name.to_string()],
(false, true) => vec![right_name.to_string()],
(false, false) => vec![name.to_string()],
}
}
pub fn hotstring_text(name: &str) -> Option<String> {
let mut chars = name.chars();
let first = chars.next()?;
let last = name.chars().last()?;
if first != last || first.is_alphanumeric() || name.chars().count() < 3 {
return None;
}
let inner: String = name
.chars()
.skip(1)
.take(name.chars().count() - 2)
.collect();
Some(inner)
}
pub(crate) fn run_fired(rt: &mut Runtime<'_>) -> Result<(), RuntimeFailure> {
if !rt.hotkeys().iter().any(|entry| entry.kind != Kind::State) {
return Ok(());
}
let fired = match rt.desktop().fired_hotkey() {
Ok(Some(name)) => name,
Ok(None) => return Ok(()),
Err(reason) => return Err(fail(&reason, 0)),
};
let Some(entry) = rt
.hotkeys()
.iter()
.find(|entry| entry.matches(&fired))
.cloned()
else {
return Ok(());
};
if !entry.enabled {
return Ok(());
}
if !condition_holds(rt, &entry)? {
return Ok(());
}
{
let mut shared = entry.shared.borrow_mut();
shared.prior = shared.current.clone();
shared.current = Some((entry.name.clone(), rt.now_ms()));
}
if let Some(body) = &entry.body {
rt.run_the_body_of_a_hotkey(body)?;
return Ok(());
}
if entry.takes_name {
rt.call_named(
&entry.function,
&[Value::Text(fired)],
entry.line,
Route::Written,
)?;
} else {
rt.call_function_by_name(&entry.function, entry.line)?;
}
Ok(())
}
pub(crate) fn register_the_hotkey_of_the_v1(
rt: &mut Runtime<'_>,
name: &str,
body: Vec<Node>,
line: u32,
condition: Option<Condition>,
) -> Result<(), RuntimeFailure> {
rt.desktop()
.register_hotkey(name)
.map_err(|reason| fail(&reason, line))?;
let shared = shared_of(rt);
rt.hotkeys().push(Hotkey {
name: name.to_string(),
function: String::new(),
enabled: true,
kind: Kind::Hotkey,
line,
object: None,
shared,
condition,
takes_name: false,
body: Some(body),
});
Ok(())
}
pub(crate) fn register_the_hotkey_of_the_v2(
rt: &mut Runtime<'_>,
name: &str,
body: Vec<Node>,
line: u32,
condition: Option<Condition>,
) -> Result<(), RuntimeFailure> {
if let Err(reason) = rt.desktop().register_hotkey(name) {
rt.note(format!(
"the hotkey {name} is not watched on this desktop: {reason}"
));
return Ok(());
}
let shared = shared_of(rt);
rt.hotkeys().push(Hotkey {
name: name.to_string(),
function: String::new(),
enabled: true,
kind: Kind::Hotkey,
line,
object: None,
shared,
condition,
takes_name: false,
body: Some(body),
});
Ok(())
}
impl Hotkey {
fn matches(&self, fired: &str) -> bool {
match self.kind {
Kind::Hotstring => match hotstring_text(&self.name) {
Some(text) => text.eq_ignore_ascii_case(fired),
None => false,
},
_ => self.name == fired,
}
}
}
fn condition_holds(rt: &mut Runtime<'_>, entry: &Hotkey) -> Result<bool, RuntimeFailure> {
let Some(condition) = entry.condition.clone() else {
return Ok(true);
};
let mode = crate::settings::title_match_mode();
match condition {
Condition::Function(name) => {
let value = rt.call_named(&name, &[], entry.line, Route::Written)?;
Ok(value.truthy())
}
Condition::Expression { node, .. } => rt.the_truth_of_the_expression(&node),
Condition::WindowActive(title) => match rt.desktop().window_active(&title, mode) {
Ok(WindowAnswer::Active) => Ok(true),
Ok(WindowAnswer::NotActive) | Ok(WindowAnswer::Absent) => Ok(false),
Ok(WindowAnswer::Unknown(reason)) => Err(fail(&reason, entry.line)),
Err(reason) => Err(fail(&reason, entry.line)),
},
Condition::WindowExists(title) => match rt.desktop().window_exists(&title, mode) {
Ok(WindowAnswer::Active) | Ok(WindowAnswer::NotActive) => Ok(true),
Ok(WindowAnswer::Absent) => Ok(false),
Ok(WindowAnswer::Unknown(reason)) => Err(fail(&reason, entry.line)),
Err(reason) => Err(fail(&reason, entry.line)),
},
Condition::WindowNotActive(title) => match rt.desktop().window_active(&title, mode) {
Ok(WindowAnswer::Active) => Ok(false),
Ok(WindowAnswer::NotActive) | Ok(WindowAnswer::Absent) => Ok(true),
Ok(WindowAnswer::Unknown(reason)) => Err(fail(&reason, entry.line)),
Err(reason) => Err(fail(&reason, entry.line)),
},
Condition::WindowNotExist(title) => match rt.desktop().window_exists(&title, mode) {
Ok(WindowAnswer::Active) | Ok(WindowAnswer::NotActive) => Ok(false),
Ok(WindowAnswer::Absent) => Ok(true),
Ok(WindowAnswer::Unknown(reason)) => Err(fail(&reason, entry.line)),
Err(reason) => Err(fail(&reason, entry.line)),
},
}
}
pub(crate) fn register(
rt: &mut Runtime<'_>,
shape: Shape,
line: u32,
) -> Result<(), RuntimeFailure> {
let Shape {
kind,
name,
function,
takes_name,
options,
object,
} = shape;
match kind {
Kind::Hotkey => {
parse(&name).map_err(|reason| fail(&reason, line))?;
}
Kind::Hotstring => {
if hotstring_text(&name).is_none() {
return Err(fail("Parameter #1 of Hotstring is invalid.", line));
}
}
Kind::State => {}
}
check_options(&options, line)?;
let mut enabled = true;
for option in options.split_whitespace() {
match option.to_lowercase().as_str() {
"off" => enabled = false,
"toggle" => enabled = !enabled,
_ => {}
}
}
if enabled {
rt.desktop()
.register_hotkey(&name)
.map_err(|reason| fail(&reason, line))?;
}
let shared = shared_of(rt);
let condition = shared.borrow_mut().condition.take();
rt.hotkeys().push(Hotkey {
name: name.clone(),
function: function.clone(),
enabled,
kind,
line,
object,
shared,
condition,
takes_name,
body: None,
});
Ok(())
}
pub(crate) fn the_condition_of_the_script(rt: &mut Runtime<'_>) -> Option<Condition> {
shared_of(rt).borrow().condition.clone()
}
fn shared_of(rt: &mut Runtime<'_>) -> Rc<RefCell<Shared>> {
if let Some(entry) = rt.hotkeys().iter().find(|entry| entry.kind == Kind::State) {
return entry.shared.clone();
}
let shared = Rc::new(RefCell::new(Shared::default()));
rt.hotkeys().push(Hotkey {
name: String::new(),
function: String::new(),
enabled: false,
kind: Kind::State,
line: 0,
object: None,
shared: shared.clone(),
condition: None,
takes_name: false,
body: None,
});
shared
}
fn shared_state(rt: &mut Runtime<'_>) -> Option<Rc<RefCell<Shared>>> {
rt.hotkeys()
.iter()
.find(|entry| entry.kind == Kind::State)
.map(|entry| entry.shared.clone())
}
pub(crate) fn check_options(options: &str, line: u32) -> Result<(), RuntimeFailure> {
for option in options.split_whitespace() {
let lowered = option.to_lowercase();
if lowered == "on" || lowered == "off" || lowered == "toggle" {
continue;
}
let mut rest = lowered.as_str();
while !rest.is_empty() {
let letter = rest.chars().next().unwrap_or(' ');
rest = &rest[letter.len_utf8()..];
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
rest = &rest[digits.len()..];
let known = match letter {
'b' | 'i' | 'p' | 's' => true,
't' => !digits.is_empty(),
_ => false,
};
if !known {
return Err(fail("Parameter #3 of Hotkey is invalid.", line));
}
}
}
Ok(())
}
pub(crate) fn action_of(value: &Value, line: u32) -> Result<(String, bool), RuntimeFailure> {
let Value::Object(object) = value else {
return Err(fail("Parameter #2 of Hotkey is invalid.", line));
};
let object = object.borrow();
if object.class != "func" {
return Err(fail("Parameter #2 of Hotkey is invalid.", line));
}
let builtin = object
.value_of("builtin")
.and_then(|value| value.to_number())
.unwrap_or(0.0);
if builtin != 0.0 {
return Err(fail("Invalid callback function.", line));
}
let max = object
.value_of("maxparams")
.and_then(|value| value.to_number())
.unwrap_or(0.0);
if max > 1.0 {
return Err(fail("Invalid callback function.", line));
}
let name = object
.value_of("name")
.map(|value| value.to_text())
.unwrap_or_default();
Ok((name, max >= 1.0))
}
pub(crate) fn hotstring_action_of(
value: &Value,
line: u32,
) -> Result<(String, bool), RuntimeFailure> {
match value {
Value::Text(text) => Ok((text.clone(), false)),
Value::Int(number) => Ok((number.to_string(), false)),
other => action_of(other, line),
}
}
pub fn hotkey(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let name = text_argument(values.first(), "Parameter #1 of Hotkey is invalid.", line)?;
let Some(action) = values.get(1).cloned() else {
return Err(RuntimeError {
message: "Nonexistent hotkey.".to_string(),
line,
});
};
let options = match values.get(2) {
Some(value) => value.to_text(),
None => String::new(),
};
if let Value::Text(word) = &action {
match word.to_lowercase().as_str() {
"on" | "off" | "toggle" => {
return toggle(rt, &name, word, line);
}
_ => {}
}
}
let (function, takes_name) =
action_of(&action, line).map_err(|failure| as_error(failure, line))?;
let shape = Shape {
kind: Kind::Hotkey,
name,
function,
takes_name,
options,
object: None,
};
register(rt, shape, line).map_err(|failure| as_error(failure, line))?;
Ok(Value::Text(String::new()))
}
fn toggle(rt: &mut Runtime<'_>, name: &str, word: &str, line: u32) -> Result<Value, RuntimeError> {
let lowered = word.to_lowercase();
let Some(entry) = rt
.hotkeys()
.iter()
.find(|entry| entry.name == name)
.cloned()
else {
return Err(RuntimeError {
message: "Nonexistent hotkey.".to_string(),
line,
});
};
let on = match lowered.as_str() {
"on" => true,
"off" => false,
_ => !entry.enabled,
};
set_enabled(rt, &entry, on).map_err(|failure| as_error(failure, line))?;
Ok(Value::Text(String::new()))
}
pub(crate) fn set_enabled(
rt: &mut Runtime<'_>,
entry: &Hotkey,
on: bool,
) -> Result<(), RuntimeFailure> {
if entry.enabled == on {
return Ok(());
}
if on {
rt.desktop()
.register_hotkey(&entry.name)
.map_err(|reason| fail(&reason, entry.line))?;
} else {
rt.desktop()
.unregister_hotkey(&entry.name)
.map_err(|reason| fail(&reason, entry.line))?;
}
for hotkey in rt.hotkeys().iter_mut() {
if hotkey.kind == entry.kind && hotkey.name == entry.name {
hotkey.enabled = on;
}
}
Ok(())
}
pub fn hotstring(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let text = match values.first() {
Some(Value::Text(text)) => text.clone(),
Some(_) => {
return Err(RuntimeError {
message:
"Parameter #1 of Hotstring requires a String, but received something else."
.to_string(),
line,
});
}
None => {
return Err(RuntimeError {
message: "Parameter #1 of Hotstring is invalid.".to_string(),
line,
});
}
};
if hotstring_text(&text).is_none() {
return Err(RuntimeError {
message: "Parameter #1 of Hotstring is invalid.".to_string(),
line,
});
}
let options = match values.get(2) {
Some(value) => value.to_text(),
None => String::new(),
};
let (function, takes_name) = match values.get(1) {
Some(action) => {
hotstring_action_of(action, line).map_err(|failure| as_error(failure, line))?
}
None => (String::new(), false),
};
let shape = Shape {
kind: Kind::Hotstring,
name: text,
function,
takes_name,
options,
object: None,
};
register(rt, shape, line).map_err(|failure| as_error(failure, line))?;
Ok(Value::Text(String::new()))
}
pub fn hotif(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
let shared = shared_of(rt);
match values.first() {
None => {
shared.borrow_mut().condition = None;
}
Some(value) => {
let Value::Object(object) = value else {
return Err(RuntimeError {
message: "Parameter #1 must match an existing #HotIf expression.".to_string(),
line,
});
};
let object = object.borrow();
if object.class != "func" {
return Err(RuntimeError {
message: "Parameter #1 must match an existing #HotIf expression.".to_string(),
line,
});
}
let name = object
.value_of("name")
.map(|value| value.to_text())
.unwrap_or_default();
shared.borrow_mut().condition = Some(Condition::Function(name));
}
}
Ok(Value::Text(String::new()))
}
pub fn hotif_window(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
variant: u8,
) -> Result<Value, RuntimeError> {
let title = text_argument(
values.first(),
"Parameter #1 must match an existing #HotIf expression.",
line,
)?;
let condition = match variant {
0 => Condition::WindowActive(title),
1 => Condition::WindowExists(title),
2 => Condition::WindowNotActive(title),
_ => Condition::WindowNotExist(title),
};
let shared = shared_of(rt);
shared.borrow_mut().condition = Some(condition);
Ok(Value::Text(String::new()))
}
pub fn get_key_state(
rt: &mut Runtime<'_>,
values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
if values.len() > 2 {
return Err(RuntimeError {
message: "Parameter #2 of GetKeyState is invalid.".to_string(),
line,
});
}
let mode = values
.get(1)
.map(|value| value.to_text())
.unwrap_or_default();
let mode = mode.trim();
if !mode.is_empty() && !mode.eq_ignore_ascii_case("T") && !mode.eq_ignore_ascii_case("P") {
return Err(RuntimeError {
message: "Parameter #2 of GetKeyState is invalid.".to_string(),
line,
});
}
let name = text_argument(
values.first(),
"Parameter #1 of GetKeyState is invalid.",
line,
)?;
if keys::resolve_name(&name).is_err() {
return Err(RuntimeError {
message: "Parameter #1 of GetKeyState is invalid.".to_string(),
line,
});
}
if let Some(lock) = the_lock_of(&name) {
if mode.eq_ignore_ascii_case("T") {
return match rt.desktop().lock_light(lock) {
Ok(Some(on)) => Ok(Value::Int(on as i64)),
Ok(None) => Ok(Value::Int(0)),
Err(reason) => Err(RuntimeError {
message: reason,
line,
}),
};
}
return Ok(Value::Int(0));
}
match rt.desktop().key_is_down(&name) {
Ok(down) => Ok(Value::Int(down as i64)),
Err(reason) => Err(RuntimeError {
message: reason,
line,
}),
}
}
pub fn key_history(
_rt: &mut Runtime<'_>,
_values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
Err(RuntimeError {
message:
"this desktop cannot show the history of the keys: it has no window to show it in."
.to_string(),
line,
})
}
pub fn list_hotkeys(
_rt: &mut Runtime<'_>,
_values: &[Value],
line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
Err(RuntimeError {
message:
"this desktop cannot show the list of the hotkeys: it has no window to show it in."
.to_string(),
line,
})
}
pub fn install_hook(
_rt: &mut Runtime<'_>,
_values: &[Value],
_line: u32,
_variant: u8,
) -> Result<Value, RuntimeError> {
Ok(Value::Text(String::new()))
}
pub fn variable(name: &str, rt: &mut Runtime<'_>) -> Option<Result<Value, RuntimeError>> {
let spelled = name.to_lowercase();
let name = spelled.strip_prefix("a_").unwrap_or(spelled.as_str());
let value = match name {
"hotkeyinterval" => Value::Int(2000),
"hotkeymodifiertimeout" => Value::Int(50),
"maxhotkeysperinterval" => Value::Int(70),
"priorhotkey" => match shared_state(rt) {
Some(shared) => match &shared.borrow().prior {
Some((name, _)) => Value::Text(name.clone()),
None => Value::Text(String::new()),
},
None => Value::Text(String::new()),
},
"priorkey" => Value::Text(String::new()),
"thishotkey" => match shared_state(rt) {
Some(shared) => match &shared.borrow().current {
Some((name, _)) => Value::Text(name.clone()),
None => Value::Text(String::new()),
},
None => Value::Text(String::new()),
},
"timesincepriorhotkey" => match shared_state(rt) {
Some(shared) => {
let shared = shared.borrow();
match &shared.prior {
Some((_, when)) => Value::Int(rt.now_ms() as i64 - *when as i64),
None => Value::Text(String::new()),
}
}
None => Value::Text(String::new()),
},
"timesincethishotkey" => match shared_state(rt) {
Some(shared) => {
let shared = shared.borrow();
match &shared.current {
Some((_, when)) => Value::Int(rt.now_ms() as i64 - *when as i64),
None => Value::Text(String::new()),
}
}
None => Value::Text(String::new()),
},
_ => return None,
};
Some(Ok(value))
}
fn text_argument(value: Option<&Value>, message: &str, line: u32) -> Result<String, RuntimeError> {
match value {
Some(Value::Text(text)) => Ok(text.clone()),
_ => Err(RuntimeError {
message: message.to_string(),
line,
}),
}
}
fn fail(message: &str, line: u32) -> RuntimeFailure {
RuntimeFailure::Error(RuntimeError {
message: message.to_string(),
line,
})
}
fn as_error(failure: RuntimeFailure, line: u32) -> RuntimeError {
match failure {
RuntimeFailure::Error(error) => error,
RuntimeFailure::Detailed(error, _) => error,
_ => RuntimeError {
message: "the hotkey could not be registered.".to_string(),
line,
},
}
}
fn the_lock_of(name: &str) -> Option<&'static str> {
match name.trim().to_lowercase().as_str() {
"capslock" => Some("CapsLock"),
"numlock" => Some("NumLock"),
"scrolllock" => Some("ScrollLock"),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::desktop::{
Clipboard, Com, Desktop, Dialogs, Files, Hotkeys, Keyboard, Machine, Native, Network,
Pictures, Pointer, Processes, Screen, Sound, Timers, TitleMatch, WindowAnswer, Windows,
};
use crate::runtime::Clock;
use alloc::string::String;
use alloc::vec::Vec;
use core::time::Duration;
struct Fake {
fired: bool,
registered: Vec<String>,
down: Vec<String>,
}
impl Fake {
fn new() -> Self {
Fake {
fired: false,
registered: Vec::new(),
down: Vec::new(),
}
}
}
impl Keyboard for Fake {
fn type_text(&mut self, text: &str) -> Result<String, String> {
Ok(text.to_string())
}
fn press_key(&mut self, name: &str, _modifiers: &[String]) -> Result<String, String> {
Ok(name.to_string())
}
fn key_is_down(&mut self, name: &str) -> Result<bool, String> {
Ok(self.down.iter().any(|key| key == name))
}
}
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,
_w: i64,
_h: i64,
_filename: &str,
) -> Result<String, String> {
Ok(String::new())
}
fn pixel(&mut self, _x: i64, _y: i64) -> Result<String, String> {
Ok("#000000".to_string())
}
}
impl Processes for Fake {
fn run(&mut self, _command: &str, _window: &str) -> Result<(i32, String, String), String> {
Ok((0, String::new(), String::new()))
}
}
impl Windows for Fake {
fn window_active(
&mut self,
_title: &str,
_mode: TitleMatch,
) -> Result<WindowAnswer, String> {
Ok(WindowAnswer::Absent)
}
fn window_exists(
&mut self,
_title: &str,
_mode: TitleMatch,
) -> Result<WindowAnswer, String> {
Ok(WindowAnswer::Absent)
}
}
impl Files for Fake {}
impl Clipboard for Fake {}
impl Timers for Fake {}
impl Hotkeys for Fake {
fn register_hotkey(&mut self, name: &str) -> Result<String, String> {
self.registered.push(name.to_string());
Ok(name.to_string())
}
fn unregister_hotkey(&mut self, name: &str) -> Result<String, String> {
Ok(name.to_string())
}
fn hotkeys(&mut self) -> Result<Vec<String>, String> {
Ok(self.registered.clone())
}
fn fired_hotkey(&mut self) -> Result<Option<String>, String> {
if self.fired {
return Ok(None);
}
self.fired = true;
Ok(self.registered.first().cloned())
}
}
impl Native for Fake {}
impl Com for 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 {}
struct TheClock;
impl Clock for TheClock {
fn now_ms(&self) -> u64 {
0
}
fn sleep_ms(&mut self, _millis: u64) {}
}
#[test]
fn the_modifiers_are_read_from_the_front() {
let spec = parse("^!a").unwrap();
assert_eq!(spec.modifiers, vec!["ctrl".to_string(), "alt".to_string()]);
assert_eq!(spec.key, "a");
assert_eq!(spec.code, 30);
assert!(!spec.up);
}
#[test]
fn the_shift_and_the_windows_key_are_read() {
assert_eq!(
parse("^+a").unwrap().modifiers,
vec!["ctrl".to_string(), "shift".to_string()]
);
assert_eq!(parse("#a").unwrap().modifiers, vec!["win".to_string()]);
}
#[test]
fn the_sides_of_the_modifiers_are_read() {
assert_eq!(parse("<^a").unwrap().modifiers, vec!["ctrl".to_string()]);
assert_eq!(parse("^>a").unwrap().modifiers, vec!["rctrl".to_string()]);
assert_eq!(
parse("<^>a").unwrap().modifiers,
vec!["ctrl".to_string(), "rctrl".to_string()]
);
}
#[test]
fn the_prefixes_are_read() {
let spec = parse("~^a").unwrap();
assert!(spec.tilde);
assert!(!spec.custom);
let spec = parse("*^a").unwrap();
assert!(spec.custom);
assert!(!spec.tilde);
}
#[test]
fn the_up_suffix_is_read() {
let spec = parse("a Up").unwrap();
assert!(spec.up);
assert_eq!(spec.key, "a");
let spec = parse("^a Up").unwrap();
assert!(spec.up);
assert_eq!(spec.modifiers, vec!["ctrl".to_string()]);
}
#[test]
fn the_down_suffix_is_refused() {
assert_eq!(parse("a Down").unwrap_err(), "Invalid hotkey.");
}
#[test]
fn a_name_that_is_not_a_key_is_refused() {
assert_eq!(parse("Foo").unwrap_err(), "Invalid key name.");
assert_eq!(parse("").unwrap_err(), "Invalid key name.");
}
#[test]
fn two_keys_are_refused() {
assert_eq!(parse("a b").unwrap_err(), "Invalid hotkey.");
}
#[test]
fn a_lone_modifier_is_the_key() {
let spec = parse("^").unwrap();
assert_eq!(spec.key, "ctrl");
assert_eq!(spec.code, 29);
}
#[test]
fn the_options_are_read() {
assert!(check_options("B", 1).is_ok());
assert!(check_options("S", 1).is_ok());
assert!(check_options("P", 1).is_ok());
assert!(check_options("I", 1).is_ok());
assert!(check_options("T2", 1).is_ok());
assert!(check_options("On", 1).is_ok());
assert!(check_options("Off", 1).is_ok());
assert!(check_options("Toggle", 1).is_ok());
assert!(check_options("SS", 1).is_ok());
}
#[test]
fn an_option_that_v2_does_not_know_is_refused() {
let failure = check_options("X", 1).unwrap_err();
let RuntimeFailure::Error(error) = failure else {
panic!("the failure is not an error");
};
assert_eq!(error.message, "Parameter #3 of Hotkey is invalid.");
}
#[test]
fn the_text_of_a_hotstring_is_read() {
assert_eq!(hotstring_text(":btw:"), Some("btw".to_string()));
assert_eq!(hotstring_text("abc"), None);
assert_eq!(hotstring_text("~a~"), Some("a".to_string()));
assert_eq!(hotstring_text("(a)"), None);
}
#[test]
fn the_name_of_a_hotstring_is_checked_before_its_action() {
let script = "Hotstring(\"btw\", \"b\")\n";
let statements = crate::parse(script).expect("the script parses");
let mut desktop = Fake::new();
let mut clock = TheClock;
let report =
Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
assert!(!report.ok, "the script was expected to fail");
assert_eq!(
report.error.unwrap(),
"Parameter #1 of Hotstring is invalid."
);
}
#[test]
fn the_action_of_a_hotstring_may_be_a_text() {
let script = "Callback(hk) {\n MsgBox hk\n}\nHotstring(\":btw:\", \"Callback\")\n";
let statements = crate::parse(script).expect("the script parses");
let mut desktop = Fake::new();
let mut clock = TheClock;
let report =
Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
assert!(report.ok, "the script failed: {:?}", report.error);
assert_eq!(desktop.registered, vec![":btw:".to_string()]);
}
#[test]
fn the_hotkey_that_was_pressed_runs_its_function() {
let script = "Callback(hk) {\n MsgBox hk\n}\nHotkey(\"^a\", Callback)\n";
let statements = crate::parse(script).expect("the script parses");
let mut desktop = Fake::new();
let mut clock = TheClock;
let report =
Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
assert!(report.ok, "the script failed: {:?}", report.error);
assert_eq!(desktop.registered, vec!["^a".to_string()]);
assert_eq!(report.output, vec!["^a".to_string()]);
}
#[test]
fn a_script_with_no_hotkey_asks_nothing() {
let script = "MsgBox \"hello\"\n";
let statements = crate::parse(script).expect("the script parses");
let mut desktop = Fake::new();
let mut clock = TheClock;
let report =
Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
assert!(report.ok, "the script failed: {:?}", report.error);
assert!(desktop.registered.is_empty());
}
#[test]
fn a_hotkey_of_a_window_that_is_not_there_does_not_run() {
let script =
"Callback(hk) {\n MsgBox hk\n}\nHotIfWinExist \"Steam\"\nHotkey(\"^a\", Callback)\n";
let statements = crate::parse(script).expect("the script parses");
let mut desktop = Fake::new();
let mut clock = TheClock;
let report =
Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
assert!(report.ok, "the script failed: {:?}", report.error);
assert_eq!(desktop.registered, vec!["^a".to_string()]);
assert!(
report.output.is_empty(),
"the hotkey ran: {:?}",
report.output
);
}
#[test]
fn a_hotkey_of_a_window_that_is_not_active_runs() {
let script = "Callback(hk) {\n MsgBox hk\n}\nHotIfWinNotActive \"Steam\"\nHotkey(\"^a\", Callback)\n";
let statements = crate::parse(script).expect("the script parses");
let mut desktop = Fake::new();
let mut clock = TheClock;
let report =
Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10)).run(&statements);
assert!(report.ok, "the script failed: {:?}", report.error);
assert_eq!(report.output, vec!["^a".to_string()]);
}
#[test]
fn the_numbers_of_the_hotkeys_are_the_ones_of_v2() {
let mut desktop = Fake::new();
let mut clock = TheClock;
let mut rt = Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10));
assert_eq!(
variable("hotkeyinterval", &mut rt).unwrap().unwrap(),
Value::Int(2000)
);
assert_eq!(
variable("maxhotkeysperinterval", &mut rt).unwrap().unwrap(),
Value::Int(70)
);
assert_eq!(
variable("hotkeymodifiertimeout", &mut rt).unwrap().unwrap(),
Value::Int(50)
);
}
#[test]
fn the_variables_carry_the_state_of_the_hotkeys() {
let mut desktop = Fake::new();
let mut clock = TheClock;
let mut rt = Runtime::with_clock(&mut desktop, &mut clock, Duration::from_secs(10));
assert_eq!(
variable("thishotkey", &mut rt).unwrap().unwrap(),
Value::Text(String::new())
);
assert_eq!(
variable("priorhotkey", &mut rt).unwrap().unwrap(),
Value::Text(String::new())
);
assert_eq!(
variable("timesincepriorhotkey", &mut rt).unwrap().unwrap(),
Value::Text(String::new())
);
let shared = shared_of(&mut rt);
shared.borrow_mut().current = Some(("^a".to_string(), 0));
shared.borrow_mut().prior = Some(("a".to_string(), 0));
assert_eq!(
variable("thishotkey", &mut rt).unwrap().unwrap(),
Value::Text("^a".to_string())
);
assert_eq!(
variable("priorhotkey", &mut rt).unwrap().unwrap(),
Value::Text("a".to_string())
);
assert_eq!(
variable("timesincethishotkey", &mut rt).unwrap().unwrap(),
Value::Int(0)
);
}
}