use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;
use crate::runtime::{Runtime, RuntimeError, RuntimeFailure, Value};
pub(crate) fn names() -> Vec<&'static str> {
vec![
"id",
"isalive",
"threads",
"main",
"task",
"terminated",
"exit",
"post",
"send",
]
}
pub(crate) fn the_main_thread() -> Value {
crate::classes::object("realthread")
}
pub(crate) fn property(
_class: &str,
name: &str,
_this: &Value,
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
if !_class.eq_ignore_ascii_case("realthread") {
return None;
}
match name.to_lowercase().as_str() {
"isalive" => Some(Ok(Value::Int(1))),
"id" => match rt.desktop().the_current_thread_id() {
Ok(id) => Some(Ok(Value::Int(id))),
Err(reason) => Some(Err(RuntimeFailure::Error(RuntimeError {
message: reason,
line,
}))),
},
"threads" => {
let items = vec![the_main_thread()];
Some(crate::classes::array::construct(&items, rt, line))
}
"main" => Some(Ok(the_main_thread())),
"task" | "terminated" => Some(Err(RuntimeFailure::Error(RuntimeError {
message: "the only real thread of this run is the main one, and it is not a worker: it has no task of its own".to_string(),
line,
}))),
_ => None,
}
}
pub(crate) fn call(
_class: &str,
method: &str,
_this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
if !_class.eq_ignore_ascii_case("realthread") {
return None;
}
match method.to_lowercase().as_str() {
"exit" => {
let code = arguments.first().and_then(|value| value.to_number()).unwrap_or(0.0) as i32;
rt.exit_with(code);
Some(Ok(Value::Int(code as i64)))
}
"post" | "send" => Some(Err(RuntimeFailure::Error(RuntimeError {
message: "this tree runs the script on one real thread and has no queue to post to: Post and Send are not carried".to_string(),
line,
}))),
_ => None,
}
}