use core::fmt::Write as _;
use crate::json::Object;
use crate::runtime::Value;
#[cfg(feature = "std")]
pub(crate) fn is_asked() -> bool {
static THE_ANSWER: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*THE_ANSWER.get_or_init(|| std::env::var_os("AHK_TRACE_JSONL").is_some())
}
#[cfg(not(feature = "std"))]
pub(crate) fn is_asked() -> bool {
false
}
#[cfg(feature = "std")]
pub(crate) fn the_vars_are_asked() -> bool {
static THE_ANSWER: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
is_asked() && *THE_ANSWER.get_or_init(|| std::env::var_os("AHK_TRACE_VARS").is_some())
}
#[cfg(not(feature = "std"))]
pub(crate) fn the_vars_are_asked() -> bool {
false
}
pub(crate) fn dll_call(target: &str, args: &[Value], result: Option<&Value>) {
if !is_asked() {
return;
}
let mut object = Object::new(96);
object.text("kind", "dllcall");
object.text("fn", target);
object.field("args", |out| {
out.push('[');
for (index, argument) in args.iter().enumerate() {
if index > 0 {
out.push(',');
}
match argument {
Value::Int(number) => {
let _ = write!(out, "{number}");
}
Value::Float(number) if number.is_finite() => {
let _ = write!(out, "{number}");
}
Value::Text(text) => crate::json::write_text(out, text),
Value::Reference(reference) => {
crate::json::write_text(out, &reference.name);
}
other => crate::json::write_text(out, &other.to_text()),
}
}
out.push(']');
});
object.field("result", |out| match result {
Some(Value::Int(number)) => {
let _ = write!(out, "{number}");
}
Some(Value::Float(number)) if number.is_finite() => {
let _ = write!(out, "{number}");
}
_ => out.push_str("null"),
});
write(&object.finish());
}
pub(crate) fn gui_message(hwnd: i64, msg: i64, wparam: i64, lparam: i64) {
if !is_asked() {
return;
}
let mut object = Object::new(96);
object.text("kind", "gui_message");
object.number("hwnd", hwnd);
object.number("msg", msg);
object.number("wparam", wparam);
object.number("lparam", lparam);
write(&object.finish());
}
pub(crate) fn timer(name: &str, period: i64) {
if !is_asked() {
return;
}
let mut object = Object::new(64);
object.text("kind", "timer");
object.text("name", name);
object.number("period", period);
write(&object.finish());
}
pub(crate) fn variable(name: &str, value: &str) {
if !the_vars_are_asked() {
return;
}
let mut object = Object::new(64);
object.text("kind", "var");
object.text("name", name);
object.text("value", value);
write(&object.finish());
}
#[cfg(feature = "std")]
fn write(line: &str) {
writer::write(line);
}
#[cfg(not(feature = "std"))]
fn write(_line: &str) {}
#[cfg(feature = "std")]
mod writer {
use std::cell::RefCell;
use std::fs::{File, OpenOptions};
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
thread_local! {
static THE_FILE: RefCell<Option<File>> = const { RefCell::new(None) };
}
static THE_LOCK: Mutex<()> = Mutex::new(());
static THE_FILE_WAS_MADE: AtomicBool = AtomicBool::new(false);
static THE_FAILURE_WAS_SAID: AtomicBool = AtomicBool::new(false);
fn the_path() -> Option<&'static PathBuf> {
static THE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
THE_PATH
.get_or_init(|| std::env::var_os("AHK_TRACE_JSONL").map(PathBuf::from))
.as_ref()
}
pub(super) fn write(line: &str) {
let Some(path) = the_path() else {
return;
};
let Ok(_lock) = THE_LOCK.lock() else {
return;
};
THE_FILE.with(|held| {
let mut held = held.borrow_mut();
if held.is_none() {
let Some(file) = the_file_is_opened(path) else {
return;
};
*held = Some(file);
}
let Some(file) = held.as_mut() else {
return;
};
let _ = file.write_all(line.as_bytes());
let _ = file.write_all(b"\n");
let _ = file.flush();
});
}
fn the_file_is_opened(path: &Path) -> Option<File> {
let mut options = OpenOptions::new();
options.write(true).create(true);
if THE_FILE_WAS_MADE.swap(true, Ordering::SeqCst) {
options.append(true);
} else {
options.truncate(true);
}
match options.open(path) {
Ok(file) => Some(file),
Err(error) => {
if !THE_FAILURE_WAS_SAID.swap(true, Ordering::SeqCst) {
eprintln!("the trace of the run could not be written: {error}");
}
None
}
}
}
}