use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use crate::desktop::ThreadValue;
use crate::runtime::{Callback, Runtime, RuntimeError, RuntimeFailure, Value};
fn the_name_of_the_callback(value: Option<&Value>) -> Option<String> {
let value = value?;
if let Value::Object(object) = value {
let object = object.borrow();
if object.class == "func" {
let name = object.value_of("name").map(|name| name.to_text())?;
if !name.is_empty() {
return Some(name);
}
}
return None;
}
None
}
pub(crate) fn names() -> Vec<&'static str> {
vec![
"id",
"isalive",
"threads",
"main",
"task",
"terminated",
"exit",
"post",
"send",
"create",
"result",
"exitcode",
"wait",
"error",
]
}
pub(crate) fn the_main_thread() -> Value {
crate::classes::object("realthread")
}
const WORKER_ID: &str = "\u{1}realthread worker";
const WORKER_TASK: &str = "\u{1}realthread task";
pub(crate) fn the_worker_thread(id: u64, task: &str) -> Value {
crate::classes::object_with(
"realthread",
vec![
(WORKER_ID, Value::Int(id as i64)),
(WORKER_TASK, Value::Text(task.to_string())),
],
)
}
fn the_worker_id(this: &Value) -> Option<u64> {
if let Value::Object(object) = this {
if let Some(Value::Int(id)) = object.borrow().value_of(WORKER_ID) {
return Some(id as u64);
}
}
None
}
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;
}
if let Some(id) = the_worker_id(this) {
return Some(the_worker_property(id, name, this, rt, line));
}
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 mut items = vec![the_main_thread()];
if let Ok(workers) = rt.desktop().worker_thread_list() {
for (id, task) in workers {
items.push(the_worker_thread(id, &task));
}
}
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,
}
}
fn the_worker_property(
id: u64,
name: &str,
this: &Value,
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let lowered = name.to_lowercase();
if lowered == "task" {
let task = match this {
Value::Object(object) => object
.borrow()
.value_of(WORKER_TASK)
.unwrap_or(Value::Text(String::new())),
_ => Value::Text(String::new()),
};
return Ok(task);
}
let state = rt.desktop().worker_thread_state(id).map_err(|reason| {
RuntimeFailure::Error(RuntimeError {
message: reason,
line,
})
})?;
let answer = match lowered.as_str() {
"isalive" => Value::Int(i64::from(state.alive)),
"terminated" => Value::Int(i64::from(state.terminated)),
"exitcode" => Value::Int(state.exit_code),
"id" => Value::Int(id as i64),
"result" => match state.result {
Some(answer) => answer.to_value(),
None => Value::Unset,
},
"error" => match state.error {
Some(error) => Value::Text(error),
None => Value::Text(String::new()),
},
_ => {
return Err(RuntimeFailure::Error(RuntimeError {
message: format!(
"This value of type \"RealThread\" has no property named {name:?}."
),
line,
}))
}
};
Ok(answer)
}
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" => {
let name = match the_name_of_the_callback(arguments.first()) {
Some(name) => name,
None => {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: crate::runtime::wants_a_reference(
1,
"Post",
"a Func",
arguments.first().unwrap_or(&Value::Int(0)),
),
line,
})))
}
};
rt.post_callback(Callback { name, line });
Some(Ok(Value::Int(1)))
}
"send" => {
let name = match the_name_of_the_callback(arguments.first()) {
Some(name) => name,
None => {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: crate::runtime::wants_a_reference(
1,
"Send",
"a Func",
arguments.first().unwrap_or(&Value::Int(0)),
),
line,
})))
}
};
Some(rt.call_named(&name, &[], line, crate::runtime::Route::Written))
}
"create" => {
let name = match the_name_of_the_callback(arguments.first()) {
Some(name) => name,
None => {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: crate::runtime::wants_a_reference(
1,
"Create",
"a Func",
arguments.first().unwrap_or(&Value::Int(0)),
),
line,
})))
}
};
let args: Vec<ThreadValue> =
arguments.iter().skip(1).map(ThreadValue::of_value).collect();
let source = rt.the_source();
let dialect = rt.the_dialect_name();
let globals = rt.the_globals_as_thread_values();
#[cfg(feature = "std")]
let shared = Some(rt.share_the_globals());
#[cfg(not(feature = "std"))]
let shared = None;
let created =
rt.desktop()
.create_worker_thread(&source, dialect, &name, args, globals, shared);
Some(match created {
Ok(id) => Ok(the_worker_thread(id, &name)),
Err(reason) => Err(RuntimeFailure::Error(RuntimeError {
message: reason,
line,
})),
})
}
"wait" => {
#[cfg_attr(not(feature = "std"), allow(unused_variables))]
let Some(id) = the_worker_id(this) else {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: "the main thread cannot be waited for: it is the one that runs"
.to_string(),
line,
})));
};
let timeout_ms = arguments.first().and_then(|v| v.to_number()).unwrap_or(-1.0);
#[cfg(feature = "std")]
{
let start = std::time::Instant::now();
loop {
let state = match rt.desktop().worker_thread_state(id) {
Ok(state) => state,
Err(reason) => {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: reason,
line,
})))
}
};
if state.terminated {
return Some(Ok(Value::Int(1)));
}
if timeout_ms >= 0.0
&& start.elapsed().as_millis() as f64 >= timeout_ms
{
return Some(Ok(Value::Int(0)));
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
#[cfg(not(feature = "std"))]
{
let _ = timeout_ms;
Some(Err(RuntimeFailure::Error(RuntimeError {
message: "the wait of a worker needs the std of the tree".to_string(),
line,
})))
}
}
_ => None,
}
}