use crate::desktop::TitleMatch;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
const THE_NAMES: [&str; 4] = ["ahk_class", "ahk_exe", "ahk_id", "ahk_pid"];
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WindowCriteria {
pub title: String,
pub class: Option<String>,
pub exe: Option<String>,
pub id: Option<String>,
pub pid: Option<String>,
}
impl WindowCriteria {
pub fn parse(text: &str) -> WindowCriteria {
let mut criteria = WindowCriteria::default();
let found = the_criteria_of(text);
let first = match found.first() {
Some((at, _)) => *at,
None => {
criteria.title = text.to_string();
return criteria;
}
};
let mut title_end = first;
if title_end > 0 && text.as_bytes()[title_end - 1] == b' ' {
title_end -= 1;
}
criteria.title = text[..title_end].to_string();
for (number, (at, name)) in found.iter().enumerate() {
let start = at + name.len();
let mut end = match found.get(number + 1) {
Some((next, _)) => *next,
None => text.len(),
};
if number + 1 < found.len() {
while end > start && text.as_bytes()[end - 1].is_ascii_whitespace() {
end -= 1;
}
}
let value = text[start..end].trim_start().to_string();
match *name {
"ahk_class" => criteria.class = Some(value),
"ahk_exe" => criteria.exe = Some(value),
"ahk_id" => criteria.id = Some(value),
"ahk_pid" => criteria.pid = Some(value),
_ => {}
}
}
criteria
}
pub fn matches(
&self,
title: &str,
class: &str,
exe: &str,
id: i64,
pid: i64,
mode: TitleMatch,
) -> Result<bool, String> {
if let Some(wanted) = &self.class {
if wanted.is_empty() || wanted != class {
return Ok(false);
}
}
if let Some(wanted) = &self.exe {
if wanted.is_empty() || !wanted.eq_ignore_ascii_case(exe) {
return Ok(false);
}
}
if let Some(wanted) = &self.id {
match the_number_of(wanted) {
Some(number) if number == id => {}
_ => return Ok(false),
}
}
if let Some(wanted) = &self.pid {
match the_number_of(wanted) {
Some(number) if number == pid => {}
_ => return Ok(false),
}
}
if self.title.is_empty() {
return Ok(true);
}
mode.matches(title, &self.title)
}
}
fn the_criteria_of(text: &str) -> Vec<(usize, &'static str)> {
let mut found = Vec::new();
for (at, _) in text.char_indices() {
if at != 0 && text.as_bytes()[at - 1] != b' ' {
continue;
}
for name in THE_NAMES {
if text[at..].len() >= name.len()
&& text[at..at + name.len()].eq_ignore_ascii_case(name)
{
found.push((at, name));
break;
}
}
}
found
}
fn the_number_of(text: &str) -> Option<i64> {
let text = text.trim();
if text.is_empty() {
return None;
}
if let Some(hex) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
return i64::from_str_radix(hex, 16).ok();
}
text.parse::<i64>().ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn um_texto_sem_criterio_e_o_titulo() {
let criteria = WindowCriteria::parse("the title of the window");
assert_eq!(criteria.title, "the title of the window");
assert_eq!(criteria.class, None);
assert_eq!(criteria.exe, None);
assert_eq!(criteria.id, None);
assert_eq!(criteria.pid, None);
}
#[test]
fn a_classe_e_lida_e_o_titulo_e_o_que_sobra() {
let criteria = WindowCriteria::parse("ahk_class Notepad");
assert_eq!(criteria.class.as_deref(), Some("Notepad"));
assert_eq!(criteria.title, "");
}
#[test]
fn o_espaco_entre_o_nome_e_o_valor_pode_faltar() {
let criteria = WindowCriteria::parse("ahk_classNotepad");
assert_eq!(criteria.class.as_deref(), Some("Notepad"));
assert_eq!(criteria.title, "");
}
#[test]
fn o_valor_do_criterio_tem_os_espacos_do_titulo() {
let criteria = WindowCriteria::parse("ahk_class ahk Test Class");
assert_eq!(criteria.class.as_deref(), Some("ahk Test Class"));
assert_eq!(criteria.title, "");
}
#[test]
fn o_valor_para_onde_o_criterio_que_vem_depois_comeca() {
let criteria = WindowCriteria::parse("ahk_class ahk Test Class ahk_pid 42");
assert_eq!(criteria.class.as_deref(), Some("ahk Test Class"));
assert_eq!(criteria.pid.as_deref(), Some("42"));
}
#[test]
fn o_titulo_que_esta_antes_do_criterio_e_ido() {
let criteria = WindowCriteria::parse("the title ahk_class Notepad");
assert_eq!(criteria.class.as_deref(), Some("Notepad"));
assert_eq!(criteria.title, "the title");
}
#[test]
fn o_espaco_que_separa_o_titulo_do_criterio_e_do_titulo() {
let criteria = WindowCriteria::parse("the title ahk_class Notepad");
assert_eq!(criteria.title, "the title ");
}
#[test]
fn o_nome_do_criterio_e_lido_sem_a_caixa() {
let criteria = WindowCriteria::parse("AHK_CLASS Notepad");
assert_eq!(criteria.class.as_deref(), Some("Notepad"));
assert_eq!(criteria.title, "");
}
#[test]
fn o_nome_do_criterio_precisa_de_uma_palavra_antes() {
let criteria = WindowCriteria::parse("xxahk_class Notepad");
assert_eq!(criteria.class, None);
assert_eq!(criteria.title, "xxahk_class Notepad");
}
#[test]
fn um_numero_que_nao_e_numero_nao_casa_com_nenhuma_janela() {
let criteria = WindowCriteria::parse("ahk_id abc");
assert!(!criteria
.matches("the title", "Notepad", "notepad.exe", 1, 2, TitleMatch::Exact)
.unwrap());
}
#[test]
fn o_executavel_e_lido() {
let criteria = WindowCriteria::parse("ahk_exe notepad.exe");
assert_eq!(criteria.exe.as_deref(), Some("notepad.exe"));
assert_eq!(criteria.title, "");
}
#[test]
fn o_identificador_e_lido_em_decimal_e_em_hexadecimal() {
assert_eq!(
the_number_of(WindowCriteria::parse("ahk_id 4331538").id.as_deref().unwrap()),
Some(4331538)
);
assert_eq!(
the_number_of(WindowCriteria::parse("ahk_id 0x421812").id.as_deref().unwrap()),
Some(4331538)
);
assert_eq!(
the_number_of(WindowCriteria::parse("ahk_id 0X421812").id.as_deref().unwrap()),
Some(4331538)
);
}
#[test]
fn o_processo_e_lido() {
let criteria = WindowCriteria::parse("ahk_pid 32808");
assert_eq!(the_number_of(criteria.pid.as_deref().unwrap()), Some(32808));
}
#[test]
fn o_espaco_que_fica_no_fim_do_texto_e_do_valor() {
let criteria = WindowCriteria::parse("ahk_class Notepad ");
assert_eq!(criteria.class.as_deref(), Some("Notepad "));
}
#[test]
fn um_criterio_sem_valor_nao_nomeia_nenhuma_janela() {
let criteria = WindowCriteria::parse("ahk_class");
assert!(!criteria
.matches("the title", "Notepad", "notepad.exe", 1, 2, TitleMatch::Exact)
.unwrap());
let criteria = WindowCriteria::parse("ahk_exe");
assert!(!criteria
.matches("the title", "Notepad", "notepad.exe", 1, 2, TitleMatch::Exact)
.unwrap());
}
#[test]
fn dois_criterios_da_mesma_especie_o_ultimo_e_o_que_conta() {
let criteria = WindowCriteria::parse("ahk_class zzz ahk_class Notepad");
assert_eq!(criteria.class.as_deref(), Some("Notepad"));
}
#[test]
fn a_classe_compara_a_caixa() {
let criteria = WindowCriteria::parse("ahk_class Notepad");
assert!(criteria
.matches("the title", "Notepad", "notepad.exe", 1, 2, TitleMatch::Exact)
.unwrap());
assert!(!criteria
.matches("the title", "notepad", "notepad.exe", 1, 2, TitleMatch::Exact)
.unwrap());
}
#[test]
fn o_executavel_compara_sem_a_caixa() {
let criteria = WindowCriteria::parse("ahk_exe NOTEPAD.EXE");
assert!(criteria
.matches("the title", "Notepad", "notepad.exe", 1, 2, TitleMatch::Exact)
.unwrap());
}
#[test]
fn o_identificador_e_o_processo_sao_perguntados() {
let criteria = WindowCriteria::parse("ahk_id 7 ahk_pid 9");
assert!(criteria
.matches("the title", "Notepad", "notepad.exe", 7, 9, TitleMatch::Exact)
.unwrap());
assert!(!criteria
.matches("the title", "Notepad", "notepad.exe", 7, 8, TitleMatch::Exact)
.unwrap());
}
#[test]
fn um_texto_so_de_criterios_nao_e_um_titulo() {
let criteria = WindowCriteria::parse("ahk_class Notepad");
assert!(criteria
.matches("any title", "Notepad", "notepad.exe", 1, 2, TitleMatch::Starts)
.unwrap());
}
}