Skip to main content

excel_api/
excel_call.rs

1//! Narrow Excel12v callback capability and the M8 call catalogue.
2
3use core::{
4    ffi::{c_char, c_int, c_void},
5    fmt, ptr,
6};
7use std::sync::atomic::{AtomicUsize, Ordering};
8
9use excel_api_sys::{LPXLOPER12, XLOPER12, XLOPER12Value};
10
11use crate::excel_owned::ExcelReleaseBackend;
12use crate::{
13    CommandRegistration, ExcelOwnedValue, ExcelReleaseError, ExcelReleasePolicy, ExcelString,
14    FunctionRegistration, LifecycleContext, RegistrationError,
15};
16
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18/// Capability required by one typed Excel C API descriptor.
19pub enum CallPermission {
20    /// Genuine open/close lifecycle callback.
21    Lifecycle,
22    /// Ordinary worksheet-function callback.
23    Worksheet,
24    /// MTR-safe worksheet-function callback.
25    ThreadSafe,
26    /// Registered macro command callback.
27    Macro,
28}
29
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31/// Whether Excel must supply a result root for a call.
32pub enum ResultRoot {
33    /// The call has no result root.
34    None,
35    /// The call writes one `XLOPER12` result root.
36    Required,
37}
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40/// Verified contract metadata for one narrowly exposed Excel C API call.
41pub struct ExcelCallDescriptor {
42    /// SDK operation name.
43    pub name: &'static str,
44    /// Exact Excel12v function identifier.
45    pub function: i32,
46    /// Callback capabilities from which this call is documented as legal.
47    pub permissions: &'static [CallPermission],
48    /// Whether the call writes a result root.
49    pub result: ResultRoot,
50    /// Exactly-once release policy for an Excel-owned result.
51    pub release: ExcelReleasePolicy,
52    /// Whether Microsoft documents this operation as MTR-safe.
53    pub thread_safe: bool,
54    /// Minimum accepted argument count.
55    pub minimum_arguments: usize,
56    /// Maximum accepted argument count.
57    pub maximum_arguments: usize,
58}
59
60/// Descriptor for lifecycle-only `xlGetName`.
61pub const XL_GET_NAME: ExcelCallDescriptor = ExcelCallDescriptor {
62    name: "xlGetName",
63    function: excel_api_sys::xlGetName,
64    permissions: &[CallPermission::Lifecycle],
65    result: ResultRoot::Required,
66    release: ExcelReleasePolicy::XlFreeRequired,
67    thread_safe: false,
68    minimum_arguments: 0,
69    maximum_arguments: 0,
70};
71/// Descriptor for lifecycle-only `xlfRegister`.
72pub const XLF_REGISTER: ExcelCallDescriptor = ExcelCallDescriptor {
73    name: "xlfRegister",
74    function: excel_api_sys::xlfRegister,
75    permissions: &[CallPermission::Lifecycle],
76    result: ResultRoot::Required,
77    release: ExcelReleasePolicy::XlFreeRequired,
78    thread_safe: false,
79    minimum_arguments: 10,
80    maximum_arguments: 255,
81};
82/// Descriptor for lifecycle-only `xlfUnregister`.
83pub const XLF_UNREGISTER: ExcelCallDescriptor = ExcelCallDescriptor {
84    name: "xlfUnregister",
85    function: excel_api_sys::xlfUnregister,
86    permissions: &[CallPermission::Lifecycle],
87    result: ResultRoot::Required,
88    release: ExcelReleasePolicy::XlFreeRequired,
89    thread_safe: false,
90    minimum_arguments: 1,
91    maximum_arguments: 1,
92};
93/// Descriptor for lifecycle-only `xlfSetName`.
94pub const XLF_SET_NAME: ExcelCallDescriptor = ExcelCallDescriptor {
95    name: "xlfSetName",
96    function: excel_api_sys::xlfSetName,
97    permissions: &[CallPermission::Lifecycle],
98    result: ResultRoot::Required,
99    release: ExcelReleasePolicy::XlFreeRequired,
100    thread_safe: false,
101    minimum_arguments: 1,
102    maximum_arguments: 2,
103};
104/// Descriptor for the Excel-owned-result cleanup operation `xlFree`.
105pub const XL_FREE: ExcelCallDescriptor = ExcelCallDescriptor {
106    name: "xlFree",
107    function: excel_api_sys::xlFree,
108    permissions: &[CallPermission::ThreadSafe],
109    result: ResultRoot::None,
110    release: ExcelReleasePolicy::NoReleaseRequired,
111    thread_safe: true,
112    minimum_arguments: 1,
113    maximum_arguments: 255,
114};
115/// Descriptor for lifecycle-only event registration.
116pub const XL_EVENT_REGISTER: ExcelCallDescriptor = ExcelCallDescriptor {
117    name: "xlEventRegister",
118    function: excel_api_sys::xlEventRegister,
119    permissions: &[CallPermission::Lifecycle],
120    result: ResultRoot::Required,
121    release: ExcelReleasePolicy::NoReleaseRequired,
122    thread_safe: false,
123    minimum_arguments: 2,
124    maximum_arguments: 2,
125};
126/// Polls the Excel cancellation/break request. This is not a calculation-state query.
127pub const XL_ABORT: ExcelCallDescriptor = ExcelCallDescriptor {
128    name: "xlAbort",
129    function: excel_api_sys::xlAbort,
130    permissions: &[
131        CallPermission::Worksheet,
132        CallPermission::ThreadSafe,
133        CallPermission::Macro,
134    ],
135    result: ResultRoot::Required,
136    release: ExcelReleasePolicy::NoReleaseRequired,
137    thread_safe: true,
138    minimum_arguments: 0,
139    maximum_arguments: 1,
140};
141/// Resolves a sheet name (or the active/front sheet when omitted) to its internal ID.
142pub const XL_SHEET_ID: ExcelCallDescriptor = ExcelCallDescriptor {
143    name: "xlSheetId",
144    function: excel_api_sys::xlSheetId,
145    permissions: &[
146        CallPermission::Worksheet,
147        CallPermission::ThreadSafe,
148        CallPermission::Macro,
149    ],
150    result: ResultRoot::Required,
151    release: ExcelReleasePolicy::NoReleaseRequired,
152    thread_safe: true,
153    minimum_arguments: 0,
154    maximum_arguments: 1,
155};
156/// Resolves an internal/external reference to its sheet name.
157pub const XL_SHEET_NM: ExcelCallDescriptor = ExcelCallDescriptor {
158    name: "xlSheetNm",
159    function: excel_api_sys::xlSheetNm,
160    permissions: &[
161        CallPermission::Worksheet,
162        CallPermission::ThreadSafe,
163        CallPermission::Macro,
164    ],
165    result: ResultRoot::Required,
166    release: ExcelReleasePolicy::XlFreeRequired,
167    thread_safe: true,
168    minimum_arguments: 1,
169    maximum_arguments: 1,
170};
171/// Returns information about the caller of a worksheet function or macro.
172pub const XLF_CALLER: ExcelCallDescriptor = ExcelCallDescriptor {
173    name: "xlfCaller",
174    function: excel_api_sys::xlfCaller,
175    permissions: &[CallPermission::Worksheet, CallPermission::Macro],
176    result: ResultRoot::Required,
177    release: ExcelReleasePolicy::XlFreeRequired,
178    thread_safe: false,
179    minimum_arguments: 0,
180    maximum_arguments: 0,
181};
182/// Converts a C API value to an explicitly requested Excel root type.
183pub const XL_COERCE: ExcelCallDescriptor = ExcelCallDescriptor {
184    name: "xlCoerce",
185    function: excel_api_sys::xlCoerce,
186    permissions: &[
187        CallPermission::Worksheet,
188        CallPermission::ThreadSafe,
189        CallPermission::Macro,
190    ],
191    result: ResultRoot::Required,
192    release: ExcelReleasePolicy::XlFreeRequired,
193    thread_safe: true,
194    minimum_arguments: 1,
195    maximum_arguments: 2,
196};
197
198/// Experimental M17 research call used only to obtain Excel's own serial clock.
199#[cfg(feature = "xlcontime-research")]
200#[doc(hidden)]
201pub const XLF_NOW: ExcelCallDescriptor = ExcelCallDescriptor {
202    name: "xlfNow",
203    function: excel_api_sys::xlfNow,
204    permissions: &[CallPermission::Lifecycle, CallPermission::Macro],
205    result: ResultRoot::Required,
206    release: ExcelReleasePolicy::NoReleaseRequired,
207    thread_safe: false,
208    minimum_arguments: 0,
209    maximum_arguments: 0,
210};
211
212/// Experimental M17 compatibility probe. This is not a production dispatcher API.
213#[cfg(feature = "xlcontime-research")]
214#[doc(hidden)]
215pub const XLC_ON_TIME: ExcelCallDescriptor = ExcelCallDescriptor {
216    name: "xlcOnTime",
217    function: excel_api_sys::xlcOnTime,
218    permissions: &[CallPermission::Lifecycle, CallPermission::Macro],
219    result: ResultRoot::Required,
220    release: ExcelReleasePolicy::NoReleaseRequired,
221    thread_safe: false,
222    minimum_arguments: 2,
223    maximum_arguments: 4,
224};
225
226/// Controls whether an `xlAbort` poll retains or clears a pending break.
227///
228/// `PreservePendingBreak` is represented by an omitted argument in
229/// [`crate::WorksheetContext::is_cancellation_requested`], or by an explicit
230/// TRUE in [`crate::WorksheetContext::is_cancellation_requested_with`]. `ClearPendingBreak`
231/// is explicit FALSE. The returned Boolean reports a user break request only;
232/// it never reports Excel's general calculation progress or state.
233#[derive(Clone, Copy, Debug, Eq, PartialEq)]
234pub enum AbortCheckMode {
235    /// Preserve a pending user break request by omitting the argument or passing TRUE.
236    PreservePendingBreak,
237    /// Clear a pending user break request by passing FALSE.
238    ClearPendingBreak,
239}
240
241/// The Excel root type requested from [`XL_COERCE`].
242#[derive(Clone, Copy, Debug, Eq, PartialEq)]
243pub enum CoerceTarget {
244    /// Coerce to an Excel number.
245    Number,
246    /// Coerce to an Excel text result.
247    Text,
248    /// Coerce to an Excel Boolean.
249    Boolean,
250    /// Coerce to an Excel error root.
251    Error,
252}
253
254/// Immediate result root observed from the experimental `xlcOnTime` call.
255#[cfg(feature = "xlcontime-research")]
256#[doc(hidden)]
257#[derive(Clone, Copy, Debug, PartialEq)]
258pub enum ExperimentalOnTimeValue {
259    Boolean(bool),
260    ExcelError(i32),
261    Other(u32),
262}
263
264/// Preserves both the raw Excel12v return code and the immediate result root.
265#[cfg(feature = "xlcontime-research")]
266#[doc(hidden)]
267#[derive(Clone, Copy, Debug, PartialEq)]
268pub struct ExperimentalOnTimeOutcome {
269    pub return_code: ExcelReturnCode,
270    pub value: ExperimentalOnTimeValue,
271}
272
273#[cfg(feature = "xlcontime-research")]
274impl ExperimentalOnTimeOutcome {
275    pub const fn accepted(self) -> bool {
276        self.return_code.is_success()
277            && matches!(self.value, ExperimentalOnTimeValue::Boolean(true))
278    }
279}
280
281impl CoerceTarget {
282    const fn xltype(self) -> i32 {
283        match self {
284            Self::Number => excel_api_sys::xltypeNum as i32,
285            Self::Text => excel_api_sys::xltypeStr as i32,
286            Self::Boolean => excel_api_sys::xltypeBool as i32,
287            Self::Error => excel_api_sys::xltypeErr as i32,
288        }
289    }
290}
291
292/// Exact Excel C API return code, including any documented bit flags.
293#[derive(Clone, Copy, Debug, Eq, PartialEq)]
294pub struct ExcelReturnCode(pub i32);
295
296impl ExcelReturnCode {
297    /// Returns whether this is exactly `xlretSuccess`.
298    pub const fn is_success(self) -> bool {
299        self.0 == excel_api_sys::xlretSuccess
300    }
301    /// Returns whether this bit-combined code includes `flag`.
302    pub const fn has(self, flag: i32) -> bool {
303        self.0 & flag != 0
304    }
305}
306
307impl fmt::Display for ExcelReturnCode {
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        write!(f, "{}", self.0)
310    }
311}
312
313#[derive(Clone, Debug, Eq, PartialEq)]
314/// Failure of descriptor validation, typed invocation, or result handling.
315pub enum ExcelCallError {
316    /// No linked Excel12v callback entry point is available.
317    BackendUnavailable,
318    /// The descriptor does not permit the supplied argument count.
319    InvalidArgumentCount {
320        /// Descriptor operation name.
321        function: &'static str,
322        /// Supplied count.
323        count: usize,
324    },
325    /// The actual typed context lacks this operation's capability.
326    IllegalContext {
327        /// Descriptor operation name.
328        function: &'static str,
329        /// Capability represented by the attempted context.
330        context: CallPermission,
331    },
332    /// Excel returned an exact non-success result code.
333    ExcelFailure {
334        /// Descriptor operation name.
335        function: &'static str,
336        /// Exact raw result code.
337        code: ExcelReturnCode,
338    },
339    /// A result root's tag did not match the documented contract.
340    MalformedResult {
341        /// Descriptor operation name.
342        function: &'static str,
343        /// Documented result kind.
344        expected: &'static str,
345        /// Observed result kind.
346        actual: &'static str,
347    },
348    /// Excel supplied a module name with invalid UTF-16.
349    InvalidModuleNameUtf16,
350    /// An experimental Excel serial time was non-finite.
351    InvalidExcelSerialTime,
352    /// Deep copying an Excel-owned result failed.
353    ResultConversion(crate::ExcelOwnedConversionError),
354    /// Releasing an Excel-owned result failed.
355    ResultRelease(crate::ExcelReleaseError),
356    /// A registration descriptor was invalid.
357    Registration(RegistrationError),
358}
359
360impl fmt::Display for ExcelCallError {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        match self {
363            Self::BackendUnavailable => f.write_str("Excel12v callback backend is unavailable"),
364            Self::InvalidArgumentCount { function, count } => {
365                write!(f, "{function} does not accept {count} arguments")
366            }
367            Self::IllegalContext { function, context } => {
368                write!(
369                    f,
370                    "{function} is not legal in the {context:?} callback context"
371                )
372            }
373            Self::ExcelFailure { function, code } => {
374                write!(f, "{function} returned Excel C API code {code}")
375            }
376            Self::MalformedResult {
377                function,
378                expected,
379                actual,
380            } => write!(f, "{function} returned {actual}, expected {expected}"),
381            Self::InvalidModuleNameUtf16 => f.write_str("module name is not valid UTF-16"),
382            Self::InvalidExcelSerialTime => f.write_str("Excel serial date/time must be finite"),
383            Self::ResultConversion(error) => write!(f, "{error}"),
384            Self::ResultRelease(error) => write!(f, "{error}"),
385            Self::Registration(error) => write!(f, "registration descriptor is invalid: {error}"),
386        }
387    }
388}
389impl std::error::Error for ExcelCallError {
390    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
391        match self {
392            Self::ResultConversion(error) => Some(error),
393            Self::ResultRelease(error) => Some(error),
394            Self::Registration(error) => Some(error),
395            _ => None,
396        }
397    }
398}
399
400pub(crate) trait ExcelCallBackend: Send + Sync {
401    fn link(&self) -> Result<(), ExcelCallError>;
402    fn unlink(&self);
403    fn is_linked(&self) -> bool;
404
405    /// # Safety
406    /// All argument pointers must remain valid and uniquely mutable where Excel permits mutation;
407    /// `result` must be null only for calls documented without a result. The caller must be in an
408    /// active Excel callback on a legal thread, and this backend must remain linked for the call.
409    unsafe fn excel12v_raw(
410        &self,
411        function: i32,
412        result: *mut XLOPER12,
413        count: c_int,
414        arguments: *mut LPXLOPER12,
415    ) -> i32;
416}
417
418#[derive(Default)]
419/// Production backend that resolves and invokes Excel's `Excel12v` entry point.
420pub struct SdkExcel12vBackend {
421    entry: AtomicUsize,
422}
423
424impl fmt::Debug for SdkExcel12vBackend {
425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426        f.debug_struct("SdkExcel12vBackend")
427            .field("linked", &self.is_linked())
428            .finish()
429    }
430}
431
432impl SdkExcel12vBackend {
433    /// Creates an unlinked backend with no cached host entry point.
434    pub const fn new() -> Self {
435        Self {
436            entry: AtomicUsize::new(0),
437        }
438    }
439
440    /// Caches an Excel12v entry point if no entry point is cached yet.
441    pub fn set_entry_point(&self, entry: excel_api_sys::Excel12EntryPtFn) {
442        if self.entry.load(Ordering::Acquire) == 0 {
443            self.entry.store(entry as usize, Ordering::Release);
444        }
445    }
446
447    #[cfg(windows)]
448    fn resolve_host_entry() -> Option<usize> {
449        #[link(name = "kernel32")]
450        unsafe extern "system" {
451            fn GetModuleHandleW(name: *const u16) -> *mut c_void;
452            fn GetProcAddress(module: *mut c_void, name: *const c_char) -> *mut c_void;
453        }
454        // SAFETY: null requests the current process executable; the symbol name is NUL-terminated.
455        let module = unsafe { GetModuleHandleW(ptr::null()) };
456        if module.is_null() {
457            return None;
458        }
459        // SAFETY: `module` is the live host module returned above.
460        let address = unsafe { GetProcAddress(module, c"MdCallBack12".as_ptr()) };
461        (!address.is_null()).then_some(address as usize)
462    }
463
464    #[cfg(not(windows))]
465    fn resolve_host_entry() -> Option<usize> {
466        None
467    }
468}
469
470impl ExcelCallBackend for SdkExcel12vBackend {
471    fn link(&self) -> Result<(), ExcelCallError> {
472        if self.is_linked() {
473            return Ok(());
474        }
475        let entry = Self::resolve_host_entry().ok_or(ExcelCallError::BackendUnavailable)?;
476        let _ = self
477            .entry
478            .compare_exchange(0, entry, Ordering::AcqRel, Ordering::Acquire);
479        Ok(())
480    }
481
482    fn unlink(&self) {
483        self.entry.store(0, Ordering::Release);
484    }
485    fn is_linked(&self) -> bool {
486        self.entry.load(Ordering::Acquire) != 0
487    }
488
489    unsafe fn excel12v_raw(
490        &self,
491        function: i32,
492        result: *mut XLOPER12,
493        count: c_int,
494        arguments: *mut LPXLOPER12,
495    ) -> i32 {
496        let address = self.entry.load(Ordering::Acquire);
497        if address == 0 {
498            return excel_api_sys::xlretFailed;
499        }
500        // SAFETY: a nonzero address is installed only from MdCallBack12 or SetExcel12EntryPt.
501        let callback: excel_api_sys::Excel12EntryPtFn = unsafe { core::mem::transmute(address) };
502        // SAFETY: forwarded from this method's contract while the atomic keeps the entry installed.
503        unsafe { callback(function, count, arguments, result) }
504    }
505}
506
507pub(crate) struct CallCapability<'call> {
508    backend: &'call dyn ExcelCallBackend,
509}
510
511impl fmt::Debug for CallCapability<'_> {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        f.debug_struct("CallCapability")
514            .field("linked", &self.backend.is_linked())
515            .finish()
516    }
517}
518
519impl<'call> CallCapability<'call> {
520    pub(crate) const fn new(backend: &'call dyn ExcelCallBackend) -> Self {
521        Self { backend }
522    }
523
524    fn call(
525        &'call self,
526        permission: CallPermission,
527        descriptor: ExcelCallDescriptor,
528        arguments: &mut [LPXLOPER12],
529    ) -> Result<Option<ExcelOwnedValue<'call>>, ExcelCallError> {
530        if !descriptor.permissions.contains(&permission) {
531            return Err(ExcelCallError::IllegalContext {
532                function: descriptor.name,
533                context: permission,
534            });
535        }
536        if arguments.len() < descriptor.minimum_arguments
537            || arguments.len() > descriptor.maximum_arguments
538        {
539            return Err(ExcelCallError::InvalidArgumentCount {
540                function: descriptor.name,
541                count: arguments.len(),
542            });
543        }
544        let count =
545            c_int::try_from(arguments.len()).map_err(|_| ExcelCallError::InvalidArgumentCount {
546                function: descriptor.name,
547                count: arguments.len(),
548            })?;
549        if !self.backend.is_linked() {
550            return Err(ExcelCallError::BackendUnavailable);
551        }
552        let mut root: XLOPER12 = XLOPER12 {
553            val: XLOPER12Value { w: 0 },
554            xltype: excel_api_sys::xltypeNil,
555        };
556        let result = if descriptor.result == ResultRoot::Required {
557            &mut root
558        } else {
559            ptr::null_mut()
560        };
561        // SAFETY: roots and the mutable pointer vector remain stable through the synchronous call.
562        let raw = unsafe {
563            self.backend
564                .excel12v_raw(descriptor.function, result, count, arguments.as_mut_ptr())
565        };
566        let code = ExcelReturnCode(raw);
567        if !code.is_success() {
568            crate::diagnostics::emit(crate::DiagnosticEvent::new(
569                crate::DiagnosticCode::ExcelCall,
570                crate::DiagnosticSeverity::Error,
571                code.0,
572            ));
573            return Err(ExcelCallError::ExcelFailure {
574                function: descriptor.name,
575                code,
576            });
577        }
578        if descriptor.result == ResultRoot::None {
579            return Ok(None);
580        }
581        // SAFETY: successful Excel12v initialized this root; descriptor metadata supplies release policy.
582        Ok(Some(unsafe {
583            ExcelOwnedValue::from_call_result(root, descriptor.release, self)
584        }))
585    }
586
587    fn cancellation_requested(
588        &'call self,
589        permission: CallPermission,
590        mode: Option<AbortCheckMode>,
591    ) -> Result<bool, ExcelCallError> {
592        if !XL_ABORT.permissions.contains(&permission) {
593            return Err(ExcelCallError::IllegalContext {
594                function: XL_ABORT.name,
595                context: permission,
596            });
597        }
598        let mut retain = XLOPER12 {
599            val: XLOPER12Value { xbool: 1 },
600            xltype: excel_api_sys::xltypeBool,
601        };
602        if matches!(mode, Some(AbortCheckMode::ClearPendingBreak)) {
603            retain.val = XLOPER12Value { xbool: 0 };
604        }
605        let mut arguments = mode
606            .map(|_| vec![&mut retain as *mut XLOPER12])
607            .unwrap_or_default();
608        if !self.backend.is_linked() {
609            return Err(ExcelCallError::BackendUnavailable);
610        }
611        let mut root = XLOPER12 {
612            val: XLOPER12Value { w: 0 },
613            xltype: excel_api_sys::xltypeNil,
614        };
615        // SAFETY: `root` and the optional Boolean argument remain initialized,
616        // uniquely mutable, and live for this synchronous documented call.
617        let raw = unsafe {
618            self.backend.excel12v_raw(
619                XL_ABORT.function,
620                &mut root,
621                arguments.len() as c_int,
622                arguments.as_mut_ptr(),
623            )
624        };
625        let code = ExcelReturnCode(raw);
626        if !code.is_success() {
627            crate::diagnostics::emit(crate::DiagnosticEvent::new(
628                crate::DiagnosticCode::ExcelCall,
629                crate::DiagnosticSeverity::Error,
630                code.0,
631            ));
632            return Err(ExcelCallError::ExcelFailure {
633                function: XL_ABORT.name,
634                code,
635            });
636        }
637        if root.xltype != excel_api_sys::xltypeBool {
638            return Err(ExcelCallError::MalformedResult {
639                function: XL_ABORT.name,
640                expected: "Boolean cancellation flag",
641                actual: "non-Boolean result",
642            });
643        }
644        // `xlAbort` returns an immediate Boolean; its descriptor records that
645        // no Excel-owned auxiliary allocation is expected, so no owner/xlFree
646        // obligation is created.
647        // SAFETY: the successful call's descriptor requires an immediate
648        // `xltypeBool` result, which initializes this union member.
649        Ok(unsafe { root.val.xbool != 0 })
650    }
651
652    #[cfg(feature = "xlcontime-research")]
653    fn experimental_excel_serial_now(
654        &'call self,
655        permission: CallPermission,
656    ) -> Result<f64, ExcelCallError> {
657        let mut arguments = [];
658        let owner = self
659            .call(permission, XLF_NOW, &mut arguments)?
660            .expect("descriptor requires a result");
661        let root = owner.raw_root();
662        if root.xltype & excel_api_sys::XLTYPE_MASK != excel_api_sys::xltypeNum {
663            return Err(ExcelCallError::MalformedResult {
664                function: XLF_NOW.name,
665                expected: "Excel serial date/time number",
666                actual: "non-number result",
667            });
668        }
669        // SAFETY: the base tag was checked above and the immediate scalar has
670        // no Excel-owned auxiliary allocation.
671        let serial = unsafe { root.val.num };
672        if serial.is_finite() {
673            Ok(serial)
674        } else {
675            Err(ExcelCallError::MalformedResult {
676                function: XLF_NOW.name,
677                expected: "finite Excel serial date/time number",
678                actual: "non-finite number",
679            })
680        }
681    }
682
683    #[cfg(feature = "xlcontime-research")]
684    fn experimental_on_time(
685        &'call self,
686        permission: CallPermission,
687        earliest: f64,
688        command: &str,
689        latest: Option<f64>,
690        cancel: bool,
691    ) -> Result<ExperimentalOnTimeOutcome, ExcelCallError> {
692        if !XLC_ON_TIME.permissions.contains(&permission) {
693            return Err(ExcelCallError::IllegalContext {
694                function: XLC_ON_TIME.name,
695                context: permission,
696            });
697        }
698        if !earliest.is_finite() || latest.is_some_and(|value| !value.is_finite()) {
699            return Err(ExcelCallError::InvalidExcelSerialTime);
700        }
701        let mut command_storage = counted(command).map_err(ExcelCallError::Registration)?;
702        let mut earliest_root = XLOPER12 {
703            val: XLOPER12Value { num: earliest },
704            xltype: excel_api_sys::xltypeNum,
705        };
706        let mut command_root = XLOPER12 {
707            val: XLOPER12Value {
708                str: command_storage.as_mut_ptr(),
709            },
710            xltype: excel_api_sys::xltypeStr,
711        };
712        let mut latest_root = XLOPER12 {
713            val: XLOPER12Value {
714                num: latest.unwrap_or_default(),
715            },
716            xltype: if latest.is_some() {
717                excel_api_sys::xltypeNum
718            } else {
719                excel_api_sys::xltypeMissing
720            },
721        };
722        let mut cancel_root = XLOPER12 {
723            val: XLOPER12Value { xbool: 0 },
724            xltype: excel_api_sys::xltypeBool,
725        };
726        let mut arguments = vec![
727            &mut earliest_root as LPXLOPER12,
728            &mut command_root as LPXLOPER12,
729        ];
730        if cancel {
731            arguments.push(&mut latest_root);
732            arguments.push(&mut cancel_root);
733        } else if latest.is_some() {
734            arguments.push(&mut latest_root);
735        }
736        if !self.backend.is_linked() {
737            return Err(ExcelCallError::BackendUnavailable);
738        }
739        let mut root = XLOPER12 {
740            val: XLOPER12Value { w: 0 },
741            xltype: excel_api_sys::xltypeNil,
742        };
743        // SAFETY: every scalar/string root and the counted string backing it
744        // remain stable and live through this synchronous Excel12v call.
745        let raw = unsafe {
746            self.backend.excel12v_raw(
747                XLC_ON_TIME.function,
748                &mut root,
749                arguments.len() as c_int,
750                arguments.as_mut_ptr(),
751            )
752        };
753        let base = root.xltype & excel_api_sys::XLTYPE_MASK;
754        let value = match base {
755            excel_api_sys::xltypeBool => {
756                // SAFETY: the checked Boolean tag selects this union member.
757                ExperimentalOnTimeValue::Boolean(unsafe { root.val.xbool } != 0)
758            }
759            excel_api_sys::xltypeErr => {
760                // SAFETY: the checked error tag selects this union member.
761                ExperimentalOnTimeValue::ExcelError(unsafe { root.val.err })
762            }
763            other => ExperimentalOnTimeValue::Other(other),
764        };
765        Ok(ExperimentalOnTimeOutcome {
766            return_code: ExcelReturnCode(raw),
767            value,
768        })
769    }
770}
771
772impl ExcelReleaseBackend for CallCapability<'_> {
773    fn xl_free(&self, value: *mut XLOPER12) -> Result<(), ExcelReleaseError> {
774        if !self.backend.is_linked() {
775            return Err(ExcelReleaseError::BackendUnavailable);
776        }
777        let mut arguments = [value];
778        // SAFETY: ExcelOwnedValue provides its unique live top-level C-API result root; xlFree has no result.
779        let code = unsafe {
780            self.backend.excel12v_raw(
781                excel_api_sys::xlFree,
782                ptr::null_mut(),
783                1,
784                arguments.as_mut_ptr(),
785            )
786        };
787        if code == excel_api_sys::xlretSuccess {
788            Ok(())
789        } else if code & excel_api_sys::xlretNotThreadSafe != 0 {
790            Err(ExcelReleaseError::NotThreadSafe)
791        } else {
792            Err(ExcelReleaseError::ExcelCallFailure { code })
793        }
794    }
795}
796
797fn counted(text: &str) -> Result<Box<[u16]>, RegistrationError> {
798    let units: Vec<u16> = text.encode_utf16().collect();
799    if units.len() > excel_api_sys::EXCEL12_MAX_STRING_CODE_UNITS {
800        return Err(RegistrationError::StringTooLong);
801    }
802    let mut storage = Vec::with_capacity(units.len() + 1);
803    storage.push(units.len() as u16);
804    storage.extend(units);
805    Ok(storage.into_boxed_slice())
806}
807
808struct CallArguments {
809    strings: Vec<Box<[u16]>>,
810    roots: Vec<XLOPER12>,
811}
812
813impl CallArguments {
814    fn registration(
815        module: &ExcelString,
816        registration: &FunctionRegistration,
817    ) -> Result<Self, ExcelCallError> {
818        registration
819            .validate()
820            .map_err(ExcelCallError::Registration)?;
821        let module_text = String::from_utf16(module.as_utf16())
822            .map_err(|_| ExcelCallError::InvalidModuleNameUtf16)?;
823        let type_text = registration
824            .type_text()
825            .map_err(ExcelCallError::Registration)?;
826        let argument_text = registration.argument_names.join(",");
827        let mut values = vec![
828            module_text,
829            registration.rust_symbol.into(),
830            type_text,
831            registration.excel_name.into(),
832            argument_text,
833            registration.category.unwrap_or("Rust").into(),
834            String::new(),
835            String::new(),
836            registration.description.unwrap_or("").into(),
837        ];
838        values.extend(
839            registration
840                .argument_descriptions
841                .iter()
842                .map(|value| (*value).to_owned()),
843        );
844        let mut strings = Vec::with_capacity(values.len());
845        for value in values {
846            strings.push(counted(&value).map_err(ExcelCallError::Registration)?);
847        }
848        let mut roots: Vec<XLOPER12> = strings
849            .iter_mut()
850            .map(|value| XLOPER12 {
851                val: XLOPER12Value {
852                    str: value.as_mut_ptr(),
853                },
854                xltype: excel_api_sys::xltypeStr,
855            })
856            .collect();
857        roots.insert(
858            5,
859            XLOPER12 {
860                val: XLOPER12Value { num: 1.0 },
861                xltype: excel_api_sys::xltypeNum,
862            },
863        );
864        Ok(Self { strings, roots })
865    }
866
867    fn command_registration(
868        module: &ExcelString,
869        registration: &CommandRegistration,
870    ) -> Result<Self, ExcelCallError> {
871        registration
872            .validate()
873            .map_err(ExcelCallError::Registration)?;
874        let module_text = String::from_utf16(module.as_utf16())
875            .map_err(|_| ExcelCallError::InvalidModuleNameUtf16)?;
876        let values = vec![
877            module_text,
878            registration.rust_symbol.into(),
879            registration.type_text().into(),
880            registration.excel_name.into(),
881            String::new(),
882            registration.shortcut.unwrap_or("").into(),
883            String::new(),
884            registration.description.unwrap_or("").into(),
885        ];
886        let mut strings = Vec::with_capacity(values.len());
887        for value in values {
888            strings.push(counted(&value).map_err(ExcelCallError::Registration)?);
889        }
890        let mut roots: Vec<XLOPER12> = strings
891            .iter_mut()
892            .map(|value| XLOPER12 {
893                val: XLOPER12Value {
894                    str: value.as_mut_ptr(),
895                },
896                xltype: excel_api_sys::xltypeStr,
897            })
898            .collect();
899        // `pxMacroType = 2` is the documented command registration form.
900        roots.insert(
901            5,
902            XLOPER12 {
903                val: XLOPER12Value { num: 2.0 },
904                xltype: excel_api_sys::xltypeNum,
905            },
906        );
907        Ok(Self { strings, roots })
908    }
909
910    fn pointers(&mut self) -> Vec<LPXLOPER12> {
911        let _keep_alive = &self.strings;
912        self.roots
913            .iter_mut()
914            .map(|root| root as *mut XLOPER12)
915            .collect()
916    }
917
918    fn one_string(value: &str) -> Result<Self, ExcelCallError> {
919        let mut strings = vec![counted(value).map_err(ExcelCallError::Registration)?];
920        let roots = vec![XLOPER12 {
921            val: XLOPER12Value {
922                str: strings[0].as_mut_ptr(),
923            },
924            xltype: excel_api_sys::xltypeStr,
925        }];
926        Ok(Self { strings, roots })
927    }
928
929    fn event(procedure: &str, event: i32) -> Result<Self, ExcelCallError> {
930        let mut strings = vec![counted(procedure).map_err(ExcelCallError::Registration)?];
931        let roots = vec![
932            XLOPER12 {
933                val: XLOPER12Value {
934                    str: strings[0].as_mut_ptr(),
935                },
936                xltype: excel_api_sys::xltypeStr,
937            },
938            XLOPER12 {
939                val: XLOPER12Value { w: event },
940                xltype: excel_api_sys::xltypeInt,
941            },
942        ];
943        Ok(Self { strings, roots })
944    }
945}
946
947impl LifecycleContext<'_> {
948    pub(crate) fn register_event(
949        &self,
950        procedure: &str,
951        event: i32,
952    ) -> Result<i32, ExcelCallError> {
953        let mut storage = CallArguments::event(procedure, event)?;
954        let mut arguments = storage.pointers();
955        let owner = self
956            .capability()
957            .call(CallPermission::Lifecycle, XL_EVENT_REGISTER, &mut arguments)?
958            .expect("descriptor requires a result");
959        let root = owner.raw_root();
960        if root.xltype & excel_api_sys::XLTYPE_MASK != excel_api_sys::xltypeInt {
961            return Err(ExcelCallError::MalformedResult {
962                function: XL_EVENT_REGISTER.name,
963                expected: "positive integer event registration ID",
964                actual: "non-integer result",
965            });
966        }
967        // SAFETY: guarded by the integer tag.
968        let id = unsafe { root.val.w };
969        if id > 0 {
970            Ok(id)
971        } else {
972            Err(ExcelCallError::MalformedResult {
973                function: XL_EVENT_REGISTER.name,
974                expected: "positive integer event registration ID",
975                actual: "non-positive integer",
976            })
977        }
978    }
979
980    pub(crate) fn get_module_name(&self) -> Result<ExcelString, ExcelCallError> {
981        let mut arguments = [];
982        let owner = self
983            .capability()
984            .call(CallPermission::Lifecycle, XL_GET_NAME, &mut arguments)?
985            .expect("descriptor requires a result");
986        let value = owner
987            .into_owned_value(&crate::ConversionLimits::default())
988            .map_err(ExcelCallError::ResultConversion)?;
989        match value {
990            crate::ExcelValue::Text(text) => Ok(text),
991            other => Err(ExcelCallError::MalformedResult {
992                function: XL_GET_NAME.name,
993                expected: "text",
994                actual: other.kind_name(),
995            }),
996        }
997    }
998
999    pub(crate) fn register(
1000        &self,
1001        module: &ExcelString,
1002        registration: &FunctionRegistration,
1003    ) -> Result<f64, ExcelCallError> {
1004        let mut storage = CallArguments::registration(module, registration)?;
1005        let mut arguments = storage.pointers();
1006        let owner = self
1007            .capability()
1008            .call(CallPermission::Lifecycle, XLF_REGISTER, &mut arguments)?
1009            .expect("descriptor requires a result");
1010        let value = owner
1011            .into_owned_value(&crate::ConversionLimits::default())
1012            .map_err(ExcelCallError::ResultConversion)?;
1013        match value {
1014            crate::ExcelValue::Number(id) if id.is_finite() => Ok(id),
1015            other => Err(ExcelCallError::MalformedResult {
1016                function: XLF_REGISTER.name,
1017                expected: "finite registration ID",
1018                actual: other.kind_name(),
1019            }),
1020        }
1021    }
1022
1023    pub(crate) fn register_command(
1024        &self,
1025        module: &ExcelString,
1026        registration: &CommandRegistration,
1027    ) -> Result<f64, ExcelCallError> {
1028        let mut storage = CallArguments::command_registration(module, registration)?;
1029        let mut arguments = storage.pointers();
1030        let owner = self
1031            .capability()
1032            .call(CallPermission::Lifecycle, XLF_REGISTER, &mut arguments)?
1033            .expect("descriptor requires a result");
1034        let value = owner
1035            .into_owned_value(&crate::ConversionLimits::default())
1036            .map_err(ExcelCallError::ResultConversion)?;
1037        match value {
1038            crate::ExcelValue::Number(id) if id.is_finite() => Ok(id),
1039            other => Err(ExcelCallError::MalformedResult {
1040                function: XLF_REGISTER.name,
1041                expected: "finite command registration ID",
1042                actual: other.kind_name(),
1043            }),
1044        }
1045    }
1046
1047    pub(crate) fn unregister(&self, registration_id: f64) -> Result<(), ExcelCallError> {
1048        let mut id = XLOPER12 {
1049            val: XLOPER12Value {
1050                num: registration_id,
1051            },
1052            xltype: excel_api_sys::xltypeNum,
1053        };
1054        let mut arguments = [&mut id as *mut XLOPER12];
1055        let owner = self
1056            .capability()
1057            .call(CallPermission::Lifecycle, XLF_UNREGISTER, &mut arguments)?
1058            .expect("descriptor requires a result");
1059        owner.release().map_err(ExcelCallError::ResultRelease)
1060    }
1061
1062    pub(crate) fn delete_defined_name(&self, name: &str) -> Result<(), ExcelCallError> {
1063        let mut storage = CallArguments::one_string(name)?;
1064        let mut arguments = storage.pointers();
1065        let owner = self
1066            .capability()
1067            .call(CallPermission::Lifecycle, XLF_SET_NAME, &mut arguments)?
1068            .expect("descriptor requires a result");
1069        owner.release().map_err(ExcelCallError::ResultRelease)
1070    }
1071}
1072
1073macro_rules! sheet_context {
1074    ($type:ty, $permission:expr) => {
1075        impl<'call> $type {
1076            /// Returns the internal ID of Excel's active/front sheet.
1077            ///
1078            /// This is deliberately not named "current": the zero-argument
1079            /// `xlSheetId` contract identifies the active/front sheet.
1080            pub fn active_sheet_id(&self) -> Result<u64, ExcelCallError> {
1081                let mut arguments = [];
1082                let owner = self
1083                    .capability()
1084                    .call($permission, XL_SHEET_ID, &mut arguments)?
1085                    .expect("descriptor requires a result");
1086                let root = owner.raw_root();
1087                if root.xltype != excel_api_sys::xltypeRef {
1088                    return Err(ExcelCallError::MalformedResult {
1089                        function: XL_SHEET_ID.name,
1090                        expected: "external reference containing a sheet ID",
1091                        actual: "non-reference result",
1092                    });
1093                }
1094                // SAFETY: `xlSheetId` documents the `mref.idSheet` member for
1095                // its successful `xltypeRef` result; `owner` remains live here.
1096                Ok(unsafe { root.val.mref.idSheet as u64 })
1097            }
1098
1099            /// Returns the name of the *current* sheet, not the active sheet.
1100            pub fn current_sheet_name(&self) -> Result<ExcelString, ExcelCallError> {
1101                let mut current = XLOPER12 {
1102                    val: XLOPER12Value {
1103                        mref: excel_api_sys::XLOPER12MRef {
1104                            lpmref: core::ptr::null_mut(),
1105                            idSheet: 0,
1106                        },
1107                    },
1108                    xltype: excel_api_sys::xltypeRef,
1109                };
1110                let mut arguments = [&mut current as *mut XLOPER12];
1111                let owner = self
1112                    .capability()
1113                    .call($permission, XL_SHEET_NM, &mut arguments)?
1114                    .expect("descriptor requires a result");
1115                let value = owner
1116                    .into_owned_value(&crate::ConversionLimits::default())
1117                    .map_err(ExcelCallError::ResultConversion)?;
1118                match value {
1119                    crate::ExcelValue::Text(name) => Ok(name),
1120                    other => Err(ExcelCallError::MalformedResult {
1121                        function: XL_SHEET_NM.name,
1122                        expected: "sheet name text",
1123                        actual: other.kind_name(),
1124                    }),
1125                }
1126            }
1127        }
1128    };
1129}
1130
1131sheet_context!(crate::WorksheetContext<'call>, CallPermission::Worksheet);
1132sheet_context!(crate::ThreadSafeContext<'call>, CallPermission::ThreadSafe);
1133sheet_context!(crate::MacroContext<'call>, CallPermission::Macro);
1134
1135macro_rules! abort_context {
1136    ($type:ty, $permission:expr) => {
1137        impl<'call> $type {
1138            /// Poll whether Excel has received a user cancellation/break request.
1139            /// This zero-argument form preserves a pending break request.
1140            pub fn is_cancellation_requested(&self) -> Result<bool, ExcelCallError> {
1141                self.capability().cancellation_requested($permission, None)
1142            }
1143
1144            /// Poll cancellation while explicitly preserving or clearing a pending break.
1145            pub fn is_cancellation_requested_with(
1146                &self,
1147                mode: AbortCheckMode,
1148            ) -> Result<bool, ExcelCallError> {
1149                self.capability()
1150                    .cancellation_requested($permission, Some(mode))
1151            }
1152        }
1153    };
1154}
1155
1156abort_context!(crate::WorksheetContext<'call>, CallPermission::Worksheet);
1157abort_context!(crate::ThreadSafeContext<'call>, CallPermission::ThreadSafe);
1158abort_context!(crate::MacroContext<'call>, CallPermission::Macro);
1159
1160macro_rules! caller_context {
1161    ($type:ty, $permission:expr) => {
1162        impl<'call> $type {
1163            /// Returns Excel's caller value with its Excel-owned result lifetime.
1164            pub fn caller(&self) -> Result<ExcelOwnedValue<'call>, ExcelCallError> {
1165                let mut arguments = [];
1166                self.capability()
1167                    .call($permission, XLF_CALLER, &mut arguments)?
1168                    .ok_or(ExcelCallError::MalformedResult {
1169                        function: XLF_CALLER.name,
1170                        expected: "caller value",
1171                        actual: "missing result",
1172                    })
1173            }
1174        }
1175    };
1176}
1177
1178caller_context!(crate::WorksheetContext<'call>, CallPermission::Worksheet);
1179caller_context!(crate::MacroContext<'call>, CallPermission::Macro);
1180
1181macro_rules! coerce_context {
1182    ($type:ty, $permission:expr) => {
1183        impl<'call> $type {
1184            /// Converts an Excel-owned callback result to a requested root type.
1185            ///
1186            /// The source remains owned by the caller and is not consumed or
1187            /// released by `xlCoerce`; the returned root has its own `xlFree`
1188            /// obligation encoded in [`ExcelOwnedValue`].
1189            pub fn coerce(
1190                &self,
1191                source: &ExcelOwnedValue<'call>,
1192                target: CoerceTarget,
1193            ) -> Result<ExcelOwnedValue<'call>, ExcelCallError> {
1194                let mut source_root = *source.raw_root();
1195                let mut requested = XLOPER12 {
1196                    val: XLOPER12Value { w: target.xltype() },
1197                    xltype: excel_api_sys::xltypeInt,
1198                };
1199                let mut arguments = [
1200                    &mut source_root as *mut XLOPER12,
1201                    &mut requested as *mut XLOPER12,
1202                ];
1203                self.capability()
1204                    .call($permission, XL_COERCE, &mut arguments)?
1205                    .ok_or(ExcelCallError::MalformedResult {
1206                        function: XL_COERCE.name,
1207                        expected: "coerced value",
1208                        actual: "missing result",
1209                    })
1210            }
1211        }
1212    };
1213}
1214
1215coerce_context!(crate::WorksheetContext<'call>, CallPermission::Worksheet);
1216coerce_context!(crate::ThreadSafeContext<'call>, CallPermission::ThreadSafe);
1217coerce_context!(crate::MacroContext<'call>, CallPermission::Macro);
1218
1219#[cfg(feature = "xlcontime-research")]
1220impl crate::MacroContext<'_> {
1221    /// Experimental: returns the current date/time in Excel's own serial representation.
1222    #[doc(hidden)]
1223    pub fn experimental_excel_serial_now(&self) -> Result<f64, ExcelCallError> {
1224        self.capability()
1225            .experimental_excel_serial_now(CallPermission::Macro)
1226    }
1227
1228    /// Experimental two-argument `xlcOnTime` scheduling probe.
1229    #[doc(hidden)]
1230    pub fn experimental_schedule_on_time(
1231        &self,
1232        earliest: f64,
1233        command: &str,
1234    ) -> Result<ExperimentalOnTimeOutcome, ExcelCallError> {
1235        self.capability().experimental_on_time(
1236            CallPermission::Macro,
1237            earliest,
1238            command,
1239            None,
1240            false,
1241        )
1242    }
1243
1244    /// Experimental three-argument scheduling probe with a latest time.
1245    #[doc(hidden)]
1246    pub fn experimental_schedule_on_time_with_latest(
1247        &self,
1248        earliest: f64,
1249        command: &str,
1250        latest: f64,
1251    ) -> Result<ExperimentalOnTimeOutcome, ExcelCallError> {
1252        self.capability().experimental_on_time(
1253            CallPermission::Macro,
1254            earliest,
1255            command,
1256            Some(latest),
1257            false,
1258        )
1259    }
1260
1261    /// Experimental four-argument cancellation probe (`missing`, `FALSE`).
1262    #[doc(hidden)]
1263    pub fn experimental_cancel_on_time(
1264        &self,
1265        earliest: f64,
1266        command: &str,
1267    ) -> Result<ExperimentalOnTimeOutcome, ExcelCallError> {
1268        self.capability()
1269            .experimental_on_time(CallPermission::Macro, earliest, command, None, true)
1270    }
1271}
1272
1273#[cfg(feature = "xlcontime-research")]
1274impl crate::LifecycleContext<'_> {
1275    /// Experimental lifecycle-time clock probe used only by the isolated harness.
1276    #[doc(hidden)]
1277    pub fn experimental_excel_serial_now(&self) -> Result<f64, ExcelCallError> {
1278        self.capability()
1279            .experimental_excel_serial_now(CallPermission::Lifecycle)
1280    }
1281
1282    /// Experimental lifecycle-time two-argument scheduling probe.
1283    #[doc(hidden)]
1284    pub fn experimental_schedule_on_time(
1285        &self,
1286        earliest: f64,
1287        command: &str,
1288    ) -> Result<ExperimentalOnTimeOutcome, ExcelCallError> {
1289        self.capability().experimental_on_time(
1290            CallPermission::Lifecycle,
1291            earliest,
1292            command,
1293            None,
1294            false,
1295        )
1296    }
1297
1298    /// Experimental lifecycle-time scheduling probe with a latest time.
1299    #[doc(hidden)]
1300    pub fn experimental_schedule_on_time_with_latest(
1301        &self,
1302        earliest: f64,
1303        command: &str,
1304        latest: f64,
1305    ) -> Result<ExperimentalOnTimeOutcome, ExcelCallError> {
1306        self.capability().experimental_on_time(
1307            CallPermission::Lifecycle,
1308            earliest,
1309            command,
1310            Some(latest),
1311            false,
1312        )
1313    }
1314
1315    /// Experimental close-time cancellation probe. Its modern legality is a
1316    /// live-validation question and is not a stable lifecycle capability.
1317    #[doc(hidden)]
1318    pub fn experimental_cancel_on_time(
1319        &self,
1320        earliest: f64,
1321        command: &str,
1322    ) -> Result<ExperimentalOnTimeOutcome, ExcelCallError> {
1323        self.capability().experimental_on_time(
1324            CallPermission::Lifecycle,
1325            earliest,
1326            command,
1327            None,
1328            true,
1329        )
1330    }
1331}
1332
1333#[cfg(test)]
1334pub(crate) mod test_support {
1335    use super::*;
1336    pub(crate) struct UnavailableBackend;
1337    impl ExcelCallBackend for UnavailableBackend {
1338        fn link(&self) -> Result<(), ExcelCallError> {
1339            Err(ExcelCallError::BackendUnavailable)
1340        }
1341        fn unlink(&self) {}
1342        fn is_linked(&self) -> bool {
1343            false
1344        }
1345        unsafe fn excel12v_raw(
1346            &self,
1347            _: i32,
1348            _: *mut XLOPER12,
1349            _: c_int,
1350            _: *mut LPXLOPER12,
1351        ) -> i32 {
1352            excel_api_sys::xlretFailed
1353        }
1354    }
1355}
1356
1357#[cfg(test)]
1358mod tests {
1359    use super::*;
1360    use std::sync::Mutex;
1361
1362    #[cfg(feature = "xlcontime-research")]
1363    #[derive(Clone, Debug, PartialEq)]
1364    struct OnTimeTrace {
1365        function: i32,
1366        tags: Vec<u32>,
1367        numbers: Vec<f64>,
1368        text: Option<String>,
1369        boolean: Option<i32>,
1370    }
1371
1372    #[cfg(feature = "xlcontime-research")]
1373    struct OnTimeBackend {
1374        calls: Mutex<Vec<OnTimeTrace>>,
1375        code: Mutex<i32>,
1376        result_tag: Mutex<u32>,
1377        result_value: Mutex<i32>,
1378    }
1379
1380    #[cfg(feature = "xlcontime-research")]
1381    impl Default for OnTimeBackend {
1382        fn default() -> Self {
1383            Self {
1384                calls: Mutex::new(Vec::new()),
1385                code: Mutex::new(excel_api_sys::xlretSuccess),
1386                result_tag: Mutex::new(excel_api_sys::xltypeBool),
1387                result_value: Mutex::new(1),
1388            }
1389        }
1390    }
1391
1392    #[cfg(feature = "xlcontime-research")]
1393    impl ExcelCallBackend for OnTimeBackend {
1394        fn link(&self) -> Result<(), ExcelCallError> {
1395            Ok(())
1396        }
1397        fn unlink(&self) {}
1398        fn is_linked(&self) -> bool {
1399            true
1400        }
1401        unsafe fn excel12v_raw(
1402            &self,
1403            function: i32,
1404            result: *mut XLOPER12,
1405            count: c_int,
1406            arguments: *mut LPXLOPER12,
1407        ) -> i32 {
1408            if function == excel_api_sys::xlfNow {
1409                self.calls.lock().unwrap().push(OnTimeTrace {
1410                    function,
1411                    tags: Vec::new(),
1412                    numbers: Vec::new(),
1413                    text: None,
1414                    boolean: None,
1415                });
1416                // SAFETY: the typed xlfNow wrapper supplies a live result root.
1417                unsafe {
1418                    (*result).val = XLOPER12Value { num: 45_678.25 };
1419                    (*result).xltype = excel_api_sys::xltypeNum;
1420                }
1421                return *self.code.lock().unwrap();
1422            }
1423            // SAFETY: the typed wrapper supplies exactly `count` live pointers.
1424            let arguments = unsafe { core::slice::from_raw_parts(arguments, count as usize) };
1425            let mut tags = Vec::with_capacity(arguments.len());
1426            let mut numbers = Vec::new();
1427            let mut text = None;
1428            let mut boolean = None;
1429            for argument in arguments {
1430                // SAFETY: guaranteed by the typed wrapper contract above.
1431                let argument = unsafe { &**argument };
1432                tags.push(argument.xltype);
1433                match argument.xltype & excel_api_sys::XLTYPE_MASK {
1434                    excel_api_sys::xltypeNum => {
1435                        // SAFETY: the numeric tag selects this member.
1436                        numbers.push(unsafe { argument.val.num });
1437                    }
1438                    excel_api_sys::xltypeStr => {
1439                        // SAFETY: the counted string pointer is live for this call.
1440                        let pointer = unsafe { argument.val.str };
1441                        // SAFETY: counted strings contain a readable length prefix.
1442                        let length = usize::from(unsafe { *pointer });
1443                        // SAFETY: the backing contains prefix plus `length` units.
1444                        let units = unsafe { core::slice::from_raw_parts(pointer.add(1), length) };
1445                        text = Some(String::from_utf16(units).unwrap());
1446                    }
1447                    excel_api_sys::xltypeBool => {
1448                        // SAFETY: the Boolean tag selects this member.
1449                        boolean = Some(unsafe { argument.val.xbool });
1450                    }
1451                    _ => {}
1452                }
1453            }
1454            self.calls.lock().unwrap().push(OnTimeTrace {
1455                function,
1456                tags,
1457                numbers,
1458                text,
1459                boolean,
1460            });
1461            let tag = *self.result_tag.lock().unwrap();
1462            let value = *self.result_value.lock().unwrap();
1463            // SAFETY: the typed wrapper supplies a live result root and this
1464            // mock initializes the union member selected by `tag`.
1465            unsafe {
1466                (*result).xltype = tag;
1467                (*result).val = if tag == excel_api_sys::xltypeErr {
1468                    XLOPER12Value { err: value }
1469                } else {
1470                    XLOPER12Value { xbool: value }
1471                };
1472            }
1473            *self.code.lock().unwrap()
1474        }
1475    }
1476
1477    #[derive(Default)]
1478    struct AbortBackend {
1479        calls: Mutex<Vec<(i32, usize, Option<i32>)>>,
1480        result: Mutex<bool>,
1481        code: Mutex<i32>,
1482    }
1483
1484    impl ExcelCallBackend for AbortBackend {
1485        fn link(&self) -> Result<(), ExcelCallError> {
1486            Ok(())
1487        }
1488        fn unlink(&self) {}
1489        fn is_linked(&self) -> bool {
1490            true
1491        }
1492        unsafe fn excel12v_raw(
1493            &self,
1494            function: i32,
1495            result: *mut XLOPER12,
1496            count: c_int,
1497            arguments: *mut LPXLOPER12,
1498        ) -> i32 {
1499            let retain = if count == 1 {
1500                // SAFETY: test calls supply one initialized Boolean root.
1501                Some(unsafe { (**arguments).val.xbool })
1502            } else {
1503                None
1504            };
1505            self.calls
1506                .lock()
1507                .unwrap()
1508                .push((function, count as usize, retain));
1509            // SAFETY: this test backend initializes the documented Boolean result root.
1510            unsafe {
1511                (*result).val = XLOPER12Value {
1512                    xbool: i32::from(*self.result.lock().unwrap()),
1513                };
1514                (*result).xltype = excel_api_sys::xltypeBool;
1515            }
1516            *self.code.lock().unwrap()
1517        }
1518    }
1519
1520    #[test]
1521    fn abort_descriptor_and_zero_retain_clear_forms_are_exact() {
1522        assert_eq!(XL_ABORT.function, excel_api_sys::xlAbort);
1523        assert_eq!(XL_ABORT.minimum_arguments, 0);
1524        assert_eq!(XL_ABORT.maximum_arguments, 1);
1525        assert_eq!(XL_ABORT.release, ExcelReleasePolicy::NoReleaseRequired);
1526        assert_eq!(
1527            XL_ABORT.permissions,
1528            &[
1529                CallPermission::Worksheet,
1530                CallPermission::ThreadSafe,
1531                CallPermission::Macro,
1532            ]
1533        );
1534        let backend = AbortBackend::default();
1535        *backend.result.lock().unwrap() = true;
1536        let capability = CallCapability::new(&backend);
1537        let context = crate::WorksheetContext::new(&capability);
1538        assert!(context.is_cancellation_requested().unwrap());
1539        assert!(
1540            context
1541                .is_cancellation_requested_with(AbortCheckMode::PreservePendingBreak)
1542                .unwrap()
1543        );
1544        assert!(
1545            context
1546                .is_cancellation_requested_with(AbortCheckMode::ClearPendingBreak)
1547                .unwrap()
1548        );
1549        assert_eq!(
1550            *backend.calls.lock().unwrap(),
1551            vec![
1552                (excel_api_sys::xlAbort, 0, None),
1553                (excel_api_sys::xlAbort, 1, Some(1)),
1554                (excel_api_sys::xlAbort, 1, Some(0)),
1555            ]
1556        );
1557    }
1558
1559    #[test]
1560    fn abort_is_available_to_verified_contexts_and_preserves_return_codes() {
1561        let backend = AbortBackend::default();
1562        let capability = CallCapability::new(&backend);
1563        assert!(
1564            !crate::ThreadSafeContext::new(&capability)
1565                .is_cancellation_requested()
1566                .unwrap()
1567        );
1568        assert!(
1569            !crate::MacroContext::new(&capability)
1570                .is_cancellation_requested()
1571                .unwrap()
1572        );
1573        *backend.code.lock().unwrap() = excel_api_sys::xlretAbort | excel_api_sys::xlretUncalced;
1574        assert_eq!(
1575            crate::WorksheetContext::new(&capability).is_cancellation_requested(),
1576            Err(ExcelCallError::ExcelFailure {
1577                function: "xlAbort",
1578                code: ExcelReturnCode(excel_api_sys::xlretAbort | excel_api_sys::xlretUncalced),
1579            })
1580        );
1581        assert_eq!(
1582            capability.cancellation_requested(CallPermission::Lifecycle, None),
1583            Err(ExcelCallError::IllegalContext {
1584                function: "xlAbort",
1585                context: CallPermission::Lifecycle,
1586            })
1587        );
1588        // Only xlAbort appears in the mock trace: its immediate Boolean root
1589        // creates no ExcelOwnedValue and therefore no xlFree call.
1590        assert_eq!(backend.calls.lock().unwrap().len(), 3);
1591    }
1592
1593    #[test]
1594    fn selected_m11_descriptors_preserve_sdk_ids_and_contracts() {
1595        assert_eq!(XL_COERCE.function, excel_api_sys::xlCoerce);
1596        assert_eq!(XL_COERCE.minimum_arguments, 1);
1597        assert_eq!(XL_COERCE.maximum_arguments, 2);
1598        assert_eq!(XL_COERCE.release, ExcelReleasePolicy::XlFreeRequired);
1599        assert_eq!(XL_SHEET_ID.function, excel_api_sys::xlSheetId);
1600        assert_eq!(XL_SHEET_ID.minimum_arguments, 0);
1601        assert_eq!(XL_SHEET_ID.release, ExcelReleasePolicy::NoReleaseRequired);
1602        assert_eq!(XL_SHEET_NM.function, excel_api_sys::xlSheetNm);
1603        assert_eq!(XL_SHEET_NM.minimum_arguments, 1);
1604        assert_eq!(XL_SHEET_NM.release, ExcelReleasePolicy::XlFreeRequired);
1605        assert_eq!(XLF_CALLER.function, excel_api_sys::xlfCaller);
1606        assert_eq!(
1607            XLF_CALLER.permissions,
1608            &[CallPermission::Worksheet, CallPermission::Macro]
1609        );
1610        let caller_is_thread_safe = XLF_CALLER.thread_safe;
1611        assert!(!caller_is_thread_safe);
1612    }
1613
1614    #[cfg(feature = "xlcontime-research")]
1615    #[test]
1616    fn experimental_on_time_forms_preserve_exact_ids_roots_and_arguments() {
1617        assert_eq!(XLF_NOW.function, 74);
1618        assert_eq!(XLC_ON_TIME.function, 32_916);
1619        assert_eq!(XLC_ON_TIME.function, 0x8094);
1620        assert_eq!(XLC_ON_TIME.minimum_arguments, 2);
1621        assert_eq!(XLC_ON_TIME.maximum_arguments, 4);
1622        assert_eq!(XLC_ON_TIME.release, ExcelReleasePolicy::NoReleaseRequired);
1623
1624        let backend = OnTimeBackend::default();
1625        let capability = CallCapability::new(&backend);
1626        let macro_context = crate::MacroContext::new(&capability);
1627        assert_eq!(
1628            macro_context.experimental_excel_serial_now().unwrap(),
1629            45_678.25
1630        );
1631        let two = macro_context
1632            .experimental_schedule_on_time(45_678.5, "RUST.ONTIME.CALLBACK")
1633            .unwrap();
1634        assert!(two.accepted());
1635        let three = macro_context
1636            .experimental_schedule_on_time_with_latest(45_678.6, "RUST.ONTIME.CALLBACK", 45_678.7)
1637            .unwrap();
1638        assert!(three.accepted());
1639        let four = macro_context
1640            .experimental_cancel_on_time(45_678.5, "RUST.ONTIME.CALLBACK")
1641            .unwrap();
1642        assert!(four.accepted());
1643
1644        let calls = backend.calls.lock().unwrap();
1645        assert_eq!(calls[0].function, excel_api_sys::xlfNow);
1646        assert_eq!(calls[1].function, excel_api_sys::xlcOnTime);
1647        assert_eq!(
1648            calls[1].tags,
1649            [excel_api_sys::xltypeNum, excel_api_sys::xltypeStr]
1650        );
1651        assert_eq!(calls[1].numbers, [45_678.5]);
1652        assert_eq!(calls[1].text.as_deref(), Some("RUST.ONTIME.CALLBACK"));
1653        assert_eq!(
1654            calls[2].tags,
1655            [
1656                excel_api_sys::xltypeNum,
1657                excel_api_sys::xltypeStr,
1658                excel_api_sys::xltypeNum,
1659            ]
1660        );
1661        assert_eq!(calls[2].numbers, [45_678.6, 45_678.7]);
1662        assert_eq!(
1663            calls[3].tags,
1664            [
1665                excel_api_sys::xltypeNum,
1666                excel_api_sys::xltypeStr,
1667                excel_api_sys::xltypeMissing,
1668                excel_api_sys::xltypeBool,
1669            ]
1670        );
1671        assert_eq!(calls[3].boolean, Some(0));
1672        assert!(
1673            !calls
1674                .iter()
1675                .any(|call| call.function == excel_api_sys::xlFree)
1676        );
1677    }
1678
1679    #[cfg(feature = "xlcontime-research")]
1680    #[test]
1681    fn experimental_on_time_preserves_raw_code_error_root_and_context_boundary() {
1682        let backend = OnTimeBackend::default();
1683        *backend.code.lock().unwrap() = excel_api_sys::xlretAbort | excel_api_sys::xlretUncalced;
1684        *backend.result_tag.lock().unwrap() = excel_api_sys::xltypeErr;
1685        *backend.result_value.lock().unwrap() = excel_api_sys::xlerrValue;
1686        let capability = CallCapability::new(&backend);
1687        let outcome = crate::MacroContext::new(&capability)
1688            .experimental_cancel_on_time(45_678.5, "RUST.ONTIME.CALLBACK")
1689            .unwrap();
1690        assert_eq!(
1691            outcome,
1692            ExperimentalOnTimeOutcome {
1693                return_code: ExcelReturnCode(
1694                    excel_api_sys::xlretAbort | excel_api_sys::xlretUncalced
1695                ),
1696                value: ExperimentalOnTimeValue::ExcelError(excel_api_sys::xlerrValue),
1697            }
1698        );
1699        assert!(!outcome.accepted());
1700        assert_eq!(
1701            capability.experimental_on_time(
1702                CallPermission::Worksheet,
1703                45_678.5,
1704                "RUST.ONTIME.CALLBACK",
1705                None,
1706                false,
1707            ),
1708            Err(ExcelCallError::IllegalContext {
1709                function: "xlcOnTime",
1710                context: CallPermission::Worksheet,
1711            })
1712        );
1713    }
1714}