use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use crate::runtime::{Runtime, RuntimeError, Value};
const NO_MENU: &str = "Target menu not found.";
const THE_FIRST_HANDLE: u64 = 0x1_0000;
pub(crate) struct TheItem {
pub(crate) name: String,
pub(crate) callback: String,
pub(crate) submenu: String,
pub(crate) checked: bool,
pub(crate) enabled: bool,
}
pub(crate) struct TheMenu {
pub(crate) name: String,
pub(crate) handle: u64,
pub(crate) machine: Option<u64>,
pub(crate) items: Vec<TheItem>,
pub(crate) default: Option<String>,
}
fn the_menus<'a>(rt: &'a mut Runtime<'_>) -> &'a mut Vec<TheMenu> {
rt.the_menus_of_the_v1()
}
fn the_menu_of_the_name<'a>(rt: &'a mut Runtime<'_>, name: &str) -> &'a mut TheMenu {
let wanted = name.to_lowercase();
let found = {
let menus = the_menus(rt);
menus
.iter()
.position(|menu| menu.name.to_lowercase() == wanted)
};
if let Some(index) = found {
return &mut the_menus(rt)[index];
}
let machine = rt.desktop().menu_create().ok();
let menus = the_menus(rt);
let handle = machine.unwrap_or(THE_FIRST_HANDLE + menus.len() as u64);
menus.push(TheMenu {
name: name.to_string(),
handle,
machine,
items: Vec::new(),
default: None,
});
let last = menus.len() - 1;
&mut menus[last]
}
fn the_menu_that_is_there<'a>(rt: &'a mut Runtime<'_>, name: &str) -> Option<&'a mut TheMenu> {
let wanted = name.to_lowercase();
let menus = the_menus(rt);
menus
.iter_mut()
.find(|menu| menu.name.to_lowercase() == wanted)
}
pub(crate) fn the_machine_menu_of(rt: &mut Runtime<'_>, name: &str) -> Option<u64> {
the_menu_that_is_there(rt, name).and_then(|menu| menu.machine)
}
fn the_failure_of_a_menu_that_is_not_there(line: u32) -> RuntimeError {
RuntimeError {
message: NO_MENU.to_string(),
line,
}
}
fn the_item<'a>(menu: &'a mut TheMenu, item: &str) -> Option<&'a mut TheItem> {
menu.items
.iter_mut()
.find(|held| held.name.eq_ignore_ascii_case(item))
}
fn the_callback_and_the_submenu(callback: &str) -> (String, String) {
let trimmed = callback.trim();
match trimmed.strip_prefix(':') {
Some(name) => (String::new(), name.trim().to_string()),
None => (trimmed.to_string(), String::new()),
}
}
fn the_callback_of_the_item(item: &str, callback: &str) -> String {
if callback.trim().is_empty() && !item.trim().is_empty() {
return item.trim().to_string();
}
callback.trim().to_string()
}
pub(crate) fn add_item(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
callback: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let (callback, submenu) = the_callback_and_the_submenu(callback);
let callback = if submenu.is_empty() {
the_callback_of_the_item(item, &callback)
} else {
callback
};
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
let held = if item.is_empty() {
None
} else {
the_item(menu, item)
};
match held {
Some(held) => {
held.callback = callback.clone();
held.submenu = submenu.clone();
}
None => menu.items.push(TheItem {
name: item.to_string(),
callback: callback.clone(),
submenu: submenu.clone(),
checked: false,
enabled: true,
}),
}
if let Some(machine) = machine {
let _ = rt.desktop().menu_update(machine, item, &callback);
if !submenu.is_empty() {
let child = {
let child = the_menu_of_the_name(rt, &submenu);
child.machine
};
if let Some(child) = child {
let _answer = rt.desktop().menu_set_submenu(machine, item, child);
#[cfg(feature = "std")]
if std::env::var_os("AHK_DEBUG_CALLBACK").is_some() {
eprintln!("the menu of the item {item:?} is {:?}", _answer);
}
}
}
}
let _ = line;
Ok(Value::Text(String::new()))
}
pub(crate) fn insert_item(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
callback: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let (callback, submenu) = the_callback_and_the_submenu(callback);
let callback = if submenu.is_empty() {
the_callback_of_the_item(item, &callback)
} else {
callback
};
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
let held = TheItem {
name: item.to_string(),
callback: callback.clone(),
submenu: submenu.clone(),
checked: false,
enabled: true,
};
let at = menu.items.len().saturating_sub(1);
menu.items.insert(at, held);
if let Some(machine) = machine {
let _ = rt.desktop().menu_insert(machine, item, &callback);
if !submenu.is_empty() {
let child = {
let child = the_menu_of_the_name(rt, &submenu);
child.machine
};
if let Some(child) = child {
let _ = rt.desktop().menu_set_submenu(machine, item, child);
}
}
}
let _ = line;
Ok(Value::Text(String::new()))
}
pub(crate) fn delete_item(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
let before = menu.items.len();
menu.items
.retain(|held| !held.name.eq_ignore_ascii_case(item));
if menu.items.len() == before {
return Err(the_failure_of_a_menu_that_is_not_there(line));
}
if let Some(machine) = machine {
let _ = rt.desktop().menu_delete(machine, item);
}
Ok(Value::Text(String::new()))
}
pub(crate) fn delete_all(
rt: &mut Runtime<'_>,
name: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
if menu.items.is_empty() {
return Err(the_failure_of_a_menu_that_is_not_there(line));
}
menu.items.clear();
menu.default = None;
if let Some(machine) = machine {
let _ = rt.desktop().menu_delete_all(machine);
}
let _ = line;
Ok(Value::Text(String::new()))
}
pub(crate) fn delete_the_menu(
rt: &mut Runtime<'_>,
name: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let found = the_menu_that_is_there(rt, name).is_some();
if !found {
return Err(the_failure_of_a_menu_that_is_not_there(line));
}
let wanted = name.to_lowercase();
let holders: Vec<(u64, Vec<String>)> = {
let menus = the_menus(rt);
menus
.iter()
.filter(|menu| !menu.name.to_lowercase().eq_ignore_ascii_case(&wanted))
.filter_map(|menu| {
let machine = menu.machine?;
let items: Vec<String> = menu
.items
.iter()
.filter(|item| item.submenu.eq_ignore_ascii_case(&wanted))
.map(|item| item.name.clone())
.collect();
if items.is_empty() {
None
} else {
Some((machine, items))
}
})
.collect()
};
for (machine, items) in holders {
for item in items {
let _ = rt.desktop().menu_delete(machine, &item);
let menus = the_menus(rt);
if let Some(menu) = menus
.iter_mut()
.find(|menu| menu.machine == Some(machine))
{
menu.items.retain(|held| !held.name.eq_ignore_ascii_case(&item));
}
}
}
let machine = the_menu_that_is_there(rt, name).and_then(|menu| menu.machine);
if let Some(machine) = machine {
rt.desktop()
.menu_delete_the_menu(machine)
.map_err(|reason| RuntimeError {
message: reason,
line,
})?;
}
let menus = the_menus(rt);
menus.retain(|menu| !menu.name.eq_ignore_ascii_case(&wanted));
Ok(Value::Text(String::new()))
}
pub(crate) fn set_enabled(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
on: bool,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
let Some(held) = the_item(menu, item) else {
return Err(the_failure_of_a_menu_that_is_not_there(line));
};
held.enabled = on;
if let Some(machine) = machine {
let _ = rt.desktop().menu_enable(machine, item, on);
}
Ok(Value::Text(String::new()))
}
pub(crate) fn toggle_enabled(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
let Some(held) = the_item(menu, item) else {
return Err(the_failure_of_a_menu_that_is_not_there(line));
};
held.enabled = !held.enabled;
let on = held.enabled;
if let Some(machine) = machine {
let _ = rt.desktop().menu_enable(machine, item, on);
}
Ok(Value::Text(String::new()))
}
pub(crate) fn set_checked(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
checked: bool,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
let Some(held) = the_item(menu, item) else {
return Err(the_failure_of_a_menu_that_is_not_there(line));
};
held.checked = checked;
if let Some(machine) = machine {
let _ = rt.desktop().menu_check(machine, item, checked);
}
Ok(Value::Text(String::new()))
}
pub(crate) fn toggle_checked(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
let Some(held) = the_item(menu, item) else {
return Err(the_failure_of_a_menu_that_is_not_there(line));
};
held.checked = !held.checked;
let checked = held.checked;
if let Some(machine) = machine {
let _ = rt.desktop().menu_check(machine, item, checked);
}
Ok(Value::Text(String::new()))
}
pub(crate) fn set_default(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
if the_item(menu, item).is_none() {
return Err(the_failure_of_a_menu_that_is_not_there(line));
}
menu.default = Some(item.to_string());
Ok(Value::Text(String::new()))
}
pub(crate) fn no_default(
rt: &mut Runtime<'_>,
name: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
menu.default = None;
let _ = line;
Ok(Value::Text(String::new()))
}
pub(crate) fn rename_item(
rt: &mut Runtime<'_>,
name: &str,
old: &str,
new: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
let Some(held) = the_item(menu, old) else {
return Err(the_failure_of_a_menu_that_is_not_there(line));
};
held.name = new.to_string();
if let Some(machine) = machine {
let _ = rt.desktop().menu_rename(machine, old, new);
}
Ok(Value::Text(String::new()))
}
pub(crate) fn set_icon(
rt: &mut Runtime<'_>,
name: &str,
item: &str,
icon: &str,
number: i64,
line: u32,
) -> Result<Value, RuntimeError> {
let menu = the_menu_of_the_name(rt, name);
let machine = menu.machine;
if the_item(menu, item).is_none() {
return Err(the_failure_of_a_menu_that_is_not_there(line));
}
if let Some(machine) = machine {
let canonical = if icon.trim().is_empty() {
String::new()
} else {
rt.desktop()
.canonical_path(icon.trim())
.unwrap_or_else(|_| icon.trim().to_string())
};
rt.desktop()
.menu_set_icon(machine, item, &canonical, number)
.map_err(|reason| RuntimeError {
message: reason,
line,
})?;
}
Ok(Value::Text(String::new()))
}
pub(crate) fn show(
rt: &mut Runtime<'_>,
name: &str,
x: &str,
y: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let Some(machine) = the_machine_menu_of(rt, name) else {
return Err(the_failure_of_a_menu_that_is_not_there(line));
};
let place = (x.trim().parse::<i32>().ok(), y.trim().parse::<i32>().ok());
let chosen = rt
.the_menu_of_the_script_is_shown(machine, place.0, place.1)
.map_err(|reason| RuntimeError {
message: reason,
line,
})?;
if let Some(callback) = chosen {
if !callback.trim().is_empty() {
rt.the_callback_of_a_menu_is_waiting(callback);
}
}
Ok(Value::Text(String::new()))
}
pub(crate) fn the_handle_of(
rt: &mut Runtime<'_>,
name: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let _ = line;
let Some(menu) = the_menu_that_is_there(rt, name) else {
return Ok(Value::Int(0));
};
let machine = menu.machine;
let handle = menu.handle;
if let Some(machine) = machine {
if let Ok(real) = rt.desktop().menu_handle(machine) {
return Ok(Value::Int(real));
}
}
Ok(Value::Int(handle as i64))
}
pub(crate) fn the_name_of(
rt: &mut Runtime<'_>,
handle: &str,
line: u32,
) -> Result<Value, RuntimeError> {
let _ = line;
let wanted = handle.trim();
let mut names: Vec<(u64, String)> = Vec::new();
{
let menus = the_menus(rt);
for menu in menus.iter() {
names.push((menu.handle, menu.name.clone()));
}
}
for (number, name) in names {
if wanted == number.to_string() {
return Ok(Value::Text(name));
}
}
let menus = the_menus(rt);
let machines: Vec<(u64, String)> = menus
.iter()
.filter_map(|menu| menu.machine.map(|machine| (machine, menu.name.clone())))
.collect();
for (machine, name) in machines {
if let Ok(real) = rt.desktop().menu_handle(machine) {
if wanted == real.to_string() {
return Ok(Value::Text(name));
}
}
}
Ok(Value::Text(String::new()))
}
pub(crate) fn the_items_of_the_menu(rt: &mut Runtime<'_>, name: &str) -> String {
let menus = the_menus(rt);
the_items_of_the_menu_in(menus, name)
}
fn the_items_of_the_menu_in(menus: &[TheMenu], name: &str) -> String {
let Some(menu) = menus
.iter()
.find(|menu| menu.name.eq_ignore_ascii_case(name))
else {
return String::from("[]");
};
let mut json = String::from("[");
for (index, item) in menu.items.iter().enumerate() {
if index > 0 {
json.push(',');
}
json.push('[');
json.push_str(&the_json_text(&item.name));
json.push_str(&format!(",{},{}", item.checked, item.enabled));
if !item.callback.is_empty() || !item.submenu.is_empty() {
json.push(',');
json.push_str(&the_json_text(&item.callback));
}
if !item.submenu.is_empty() {
json.push(',');
json.push_str(&the_items_of_the_menu_in(menus, &item.submenu));
}
json.push(']');
}
json.push(']');
json
}
pub(crate) fn the_menus_that_have_the_submenu(rt: &mut Runtime<'_>, name: &str) -> Vec<String> {
let menus = the_menus(rt);
let mut names: Vec<String> = Vec::new();
let mut pending: Vec<String> = alloc::vec![name.to_string()];
while let Some(wanted) = pending.pop() {
for menu in menus.iter() {
let holds = menu
.items
.iter()
.any(|item| item.submenu.eq_ignore_ascii_case(&wanted));
if !holds {
continue;
}
if names
.iter()
.any(|other: &String| other.eq_ignore_ascii_case(&menu.name))
{
continue;
}
names.push(menu.name.clone());
pending.push(menu.name.clone());
}
}
names
}
fn the_json_text(text: &str) -> String {
let mut out = String::from("\"");
for character in text.chars() {
match character {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
other => out.push(other),
}
}
out.push('"');
out
}