office-automation 0.3.2

Windows CLI tool that automates PowerPoint and Excel via COM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Variant newtype over `windows::Win32::System::Variant::VARIANT`.
//!
//! Provides ergonomic conversions for COM automation values.

use windows::core::BSTR;
use windows::Win32::System::Com::{IDispatch, SAFEARRAY};
use windows::Win32::System::Ole::{
    SafeArrayAccessData, SafeArrayGetDim, SafeArrayGetElement, SafeArrayGetLBound,
    SafeArrayGetUBound, SafeArrayUnaccessData,
};
use windows::Win32::System::Variant::*;

use crate::error::{OaError, OaResult};

// VARENUM constants for SAFEARRAY element type detection.
const VT_ARRAY: u16 = 0x2000;
const VT_R8: u16 = 5;
const VT_VARIANT: u16 = 12;
// VARENUM tags that mean "no value" for chart data (GOTCHA #43).
const VT_EMPTY_TAG: u16 = 0;
const VT_NULL_TAG: u16 = 1;
const VT_BSTR_TAG: u16 = 8;
const VT_ERROR_TAG: u16 = 10;

/// A value extracted from a SAFEARRAY element (Range.Value2 or Series.Values).
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum CellValue {
    F64(f64),
    I32(i32),
    Str(String),
    Empty,
}

#[allow(dead_code)]
impl CellValue {
    /// Convert to f64, treating empty/string as 0.0 (matches Python's chart behavior).
    pub fn to_f64(&self) -> f64 {
        match self {
            CellValue::F64(v) => *v,
            CellValue::I32(v) => *v as f64,
            CellValue::Str(s) => s.parse::<f64>().unwrap_or(0.0),
            CellValue::Empty => 0.0,
        }
    }
}

/// A wrapper around COM VARIANT that provides ergonomic Rust conversions.
///
/// VARIANT itself doesn't implement Debug, so we implement it manually.
#[derive(Clone)]
pub struct Variant(pub VARIANT);

impl Variant {
    /// Create an empty variant (VT_EMPTY).
    pub fn empty() -> Self {
        Self(VARIANT::default())
    }

    /// Check if this variant is empty (VT_EMPTY).
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Get the variant type tag.
    pub fn vt(&self) -> u16 {
        // SAFETY: reading the type discriminant from the union.
        // VARIANT -> VARIANT_0 (union) -> VARIANT_0_0 (ManuallyDrop) -> vt (VARENUM)
        unsafe { self.0.Anonymous.Anonymous.vt.0 }
    }

    /// Try to extract an i32 value.
    pub fn as_i32(&self) -> OaResult<i32> {
        i32::try_from(&self.0).map_err(OaError::Com)
    }

    /// Try to extract an f64 value.
    pub fn as_f64(&self) -> OaResult<f64> {
        f64::try_from(&self.0).map_err(OaError::Com)
    }

    /// Try to extract a string value (from BSTR).
    pub fn as_string(&self) -> OaResult<String> {
        let bstr = BSTR::try_from(&self.0).map_err(OaError::Com)?;
        Ok(bstr.to_string())
    }

    /// Try to extract a bool value.
    pub fn as_bool(&self) -> OaResult<bool> {
        bool::try_from(&self.0).map_err(OaError::Com)
    }

    /// Try to extract an IDispatch COM object.
    pub fn as_dispatch(&self) -> OaResult<IDispatch> {
        IDispatch::try_from(&self.0).map_err(OaError::Com)
    }

    /// Try to coerce to a numeric value (i32 or f64 → f64).
    #[allow(dead_code)]
    pub fn as_numeric(&self) -> OaResult<f64> {
        // Try f64 first, then i32
        if let Ok(v) = self.as_f64() {
            return Ok(v);
        }
        if let Ok(v) = self.as_i32() {
            return Ok(v as f64);
        }
        Err(OaError::Other(format!("Cannot convert variant (vt={}) to numeric", self.vt())))
    }

    /// Get the inner VARIANT reference for passing to COM calls.
    #[allow(dead_code)]
    pub fn inner(&self) -> &VARIANT {
        &self.0
    }

    /// Get a mutable reference to the inner VARIANT.
    #[allow(dead_code)]
    pub fn inner_mut(&mut self) -> &mut VARIANT {
        &mut self.0
    }

    /// Consume and return the inner VARIANT.
    pub fn into_inner(self) -> VARIANT {
        self.0
    }

    /// Check if this variant contains a SAFEARRAY.
    pub fn is_array(&self) -> bool {
        self.vt() & VT_ARRAY != 0
    }

    /// Extract a 1D SAFEARRAY of f64 values (VT_ARRAY|VT_R8).
    ///
    /// Used for `Series.Values` which returns chart data points as doubles.
    /// Uses `SafeArrayAccessData` for zero-copy pointer access.
    pub fn as_f64_array(&self) -> OaResult<Vec<f64>> {
        unsafe {
            let psa = self.safearray_ptr()?;
            let dims = SafeArrayGetDim(psa);
            if dims != 1 {
                return Err(OaError::Other(format!("Expected 1D SAFEARRAY, got {dims}D")));
            }

            let lb = SafeArrayGetLBound(psa, 1).map_err(OaError::Com)?;
            let ub = SafeArrayGetUBound(psa, 1).map_err(OaError::Com)?;
            let count = (ub - lb + 1) as usize;
            if count == 0 {
                return Ok(vec![]);
            }

            let mut data_ptr: *mut std::ffi::c_void = std::ptr::null_mut();
            SafeArrayAccessData(psa, &mut data_ptr).map_err(OaError::Com)?;

            // Scope guard: always call UnaccessData even if we panic/error
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                let f64_ptr = data_ptr as *const f64;
                let slice = std::slice::from_raw_parts(f64_ptr, count);
                slice.to_vec()
            }));

            SafeArrayUnaccessData(psa).map_err(OaError::Com)?;

            result.map_err(|_| OaError::Other("Panic while reading SAFEARRAY data".into()))
        }
    }

    /// Extract a flat `Vec<Option<f64>>` from a numeric VARIANT — scalar or array.
    ///
    /// Handles scalars, `VT_ARRAY|VT_R8` and 1D/2D `VT_ARRAY|VT_VARIANT` (Range.Value2),
    /// flattened row-by-row, and preserves "no value":
    /// blank cells (VT_EMPTY/VT_NULL), error cells (`#N/A`, VT_ERROR) and
    /// non-numeric text become `None`; a real `0` is `Some(0.0)`.
    ///
    /// Used by the chart pipeline so a blank Excel cell produces *no* chart point
    /// instead of a zero-height bar (GOTCHA #43). Not used by OLE/table code.
    pub fn as_flat_opt_f64_vec(&self) -> OaResult<Vec<Option<f64>>> {
        if !self.is_array() {
            return Ok(vec![variant_to_opt_f64(&self.0)]);
        }

        let elem_vt = self.vt() & 0x0FFF;

        if elem_vt == VT_R8 {
            // A raw f64 array cannot express blanks — every element is a value.
            return Ok(self.as_f64_array()?.into_iter().map(Some).collect());
        }

        if elem_vt == VT_VARIANT {
            unsafe {
                let psa = self.safearray_ptr()?;
                let dims = SafeArrayGetDim(psa);
                return match dims {
                    1 => self.read_variant_array_1d_opt(psa),
                    2 => self.read_variant_array_2d_opt(psa),
                    _ => Err(OaError::Other(format!("Unsupported {dims}D SAFEARRAY"))),
                };
            }
        }

        Err(OaError::Other(format!("Unsupported SAFEARRAY element type: VT={elem_vt}")))
    }

    /// Read 1D SAFEARRAY of VARIANTs, preserving blanks as `None`.
    unsafe fn read_variant_array_1d_opt(&self, psa: *const SAFEARRAY) -> OaResult<Vec<Option<f64>>> {
        let lb = unsafe { SafeArrayGetLBound(psa, 1).map_err(OaError::Com)? };
        let ub = unsafe { SafeArrayGetUBound(psa, 1).map_err(OaError::Com)? };
        let mut values = Vec::with_capacity((ub - lb + 1) as usize);

        for i in lb..=ub {
            let val = unsafe { self.get_variant_element(psa, &[i])? };
            values.push(variant_to_opt_f64(&val));
        }
        Ok(values)
    }

    /// Read 2D SAFEARRAY of VARIANTs row-by-row, preserving blanks as `None`.
    unsafe fn read_variant_array_2d_opt(&self, psa: *const SAFEARRAY) -> OaResult<Vec<Option<f64>>> {
        let row_lb = unsafe { SafeArrayGetLBound(psa, 1).map_err(OaError::Com)? };
        let row_ub = unsafe { SafeArrayGetUBound(psa, 1).map_err(OaError::Com)? };
        let col_lb = unsafe { SafeArrayGetLBound(psa, 2).map_err(OaError::Com)? };
        let col_ub = unsafe { SafeArrayGetUBound(psa, 2).map_err(OaError::Com)? };

        let rows = (row_ub - row_lb + 1) as usize;
        let cols = (col_ub - col_lb + 1) as usize;
        let mut values = Vec::with_capacity(rows * cols);

        for r in row_lb..=row_ub {
            for c in col_lb..=col_ub {
                let val = unsafe { self.get_variant_element(psa, &[r, c])? };
                values.push(variant_to_opt_f64(&val));
            }
        }
        Ok(values)
    }

    /// Get a single VARIANT element from a SAFEARRAY by indices.
    ///
    /// SafeArrayGetElement copies the element — caller owns the result.
    unsafe fn get_variant_element(&self, psa: *const SAFEARRAY, indices: &[i32]) -> OaResult<VARIANT> {
        let mut element = VARIANT::default();
        unsafe {
            SafeArrayGetElement(
                psa,
                indices.as_ptr(),
                &mut element as *mut VARIANT as *mut std::ffi::c_void,
            )
            .map_err(OaError::Com)?;
        }
        Ok(element)
    }

    /// Get the SAFEARRAY pointer from this VARIANT.
    ///
    /// The VARIANT owns the SAFEARRAY — do NOT call SafeArrayDestroy on it.
    unsafe fn safearray_ptr(&self) -> OaResult<*const SAFEARRAY> {
        let psa = unsafe { self.0.Anonymous.Anonymous.Anonymous.parray };
        if psa.is_null() {
            return Err(OaError::Other("SAFEARRAY pointer is null".into()));
        }
        Ok(psa as *const SAFEARRAY)
    }
}

// --- From implementations ---

impl From<i32> for Variant {
    fn from(v: i32) -> Self {
        Self(VARIANT::from(v))
    }
}

impl From<f64> for Variant {
    fn from(v: f64) -> Self {
        Self(VARIANT::from(v))
    }
}

impl From<bool> for Variant {
    fn from(v: bool) -> Self {
        Self(VARIANT::from(v))
    }
}

impl From<&str> for Variant {
    fn from(v: &str) -> Self {
        Self(VARIANT::from(BSTR::from(v)))
    }
}

impl From<String> for Variant {
    fn from(v: String) -> Self {
        Self(VARIANT::from(BSTR::from(v.as_str())))
    }
}

impl From<BSTR> for Variant {
    fn from(v: BSTR) -> Self {
        Self(VARIANT::from(v))
    }
}

impl From<IDispatch> for Variant {
    fn from(v: IDispatch) -> Self {
        Self(VARIANT::from(v))
    }
}

impl From<VARIANT> for Variant {
    fn from(v: VARIANT) -> Self {
        Self(v)
    }
}


/// Convert a raw VARIANT element to `Option<f64>`, preserving "no value".
///
/// GOTCHA #43: the raw type tag must be inspected FIRST. `f64::try_from(&VARIANT)`
/// is `VariantToDouble`, which happily coerces VT_EMPTY to `0.0`, so a blank cell
/// and a real zero are indistinguishable after coercion.
///
/// - VT_EMPTY / VT_NULL / VT_ERROR (`#N/A`, `#DIV/0!`) → `None`
/// - VT_BSTR: `""`/whitespace → `None`; numeric text (optionally `%`) → `Some`; else `None`
/// - anything else → numeric coercion → `Some`, or `None` if not coercible
fn variant_to_opt_f64(v: &VARIANT) -> Option<f64> {
    // SAFETY: reading the discriminant of the VARIANT union.
    let vt = unsafe { v.Anonymous.Anonymous.vt.0 };

    match vt {
        VT_EMPTY_TAG | VT_NULL_TAG | VT_ERROR_TAG => return None,
        VT_BSTR_TAG => {
            let text = BSTR::try_from(v).map(|b| b.to_string()).unwrap_or_default();
            return parse_numeric_text(&text);
        }
        _ => {}
    }

    if let Ok(val) = f64::try_from(v) {
        return Some(val);
    }
    if let Ok(val) = i32::try_from(v) {
        return Some(val as f64);
    }
    None
}

/// Parse a cell's text as a number for chart data. `"12%"` → `0.12`, `""` → `None`.
fn parse_numeric_text(text: &str) -> Option<f64> {
    let s = text.trim();
    if s.is_empty() {
        return None;
    }
    if let Some(pct) = s.strip_suffix('%') {
        return pct.trim().parse::<f64>().ok().map(|n| n / 100.0);
    }
    s.parse::<f64>().ok()
}

impl Default for Variant {
    fn default() -> Self {
        Self::empty()
    }
}

impl std::fmt::Debug for Variant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Variant")
            .field("vt", &self.vt())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_variant() {
        let v = Variant::empty();
        assert!(v.is_empty());
    }

    #[test]
    fn test_i32_round_trip() {
        let v = Variant::from(42i32);
        assert_eq!(v.as_i32().unwrap(), 42);
    }

    #[test]
    fn test_f64_round_trip() {
        let v = Variant::from(3.14f64);
        assert!((v.as_f64().unwrap() - 3.14).abs() < f64::EPSILON);
    }

    #[test]
    fn test_bool_round_trip() {
        let v_true = Variant::from(true);
        let v_false = Variant::from(false);
        assert!(v_true.as_bool().unwrap());
        assert!(!v_false.as_bool().unwrap());
    }

    #[test]
    fn test_string_round_trip() {
        let v = Variant::from("hello world");
        assert_eq!(v.as_string().unwrap(), "hello world");
    }

    #[test]
    fn test_string_from_owned() {
        let v = Variant::from("test string".to_string());
        assert_eq!(v.as_string().unwrap(), "test string");
    }

    #[test]
    fn test_numeric_from_i32() {
        let v = Variant::from(10i32);
        assert!((v.as_numeric().unwrap() - 10.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_numeric_from_f64() {
        let v = Variant::from(2.5f64);
        assert!((v.as_numeric().unwrap() - 2.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_empty_coerces_to_zero() {
        // COM's VariantToDouble coerces VT_EMPTY to 0.0 — this is correct behavior.
        let v = Variant::empty();
        assert!((v.as_numeric().unwrap() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_default_is_empty() {
        let v = Variant::default();
        assert!(v.is_empty());
    }

    #[test]
    fn test_negative_i32() {
        let v = Variant::from(-1i32);
        assert_eq!(v.as_i32().unwrap(), -1);
    }

    #[test]
    fn test_zero_values() {
        let vi = Variant::from(0i32);
        let vf = Variant::from(0.0f64);
        assert_eq!(vi.as_i32().unwrap(), 0);
        assert!((vf.as_f64().unwrap()).abs() < f64::EPSILON);
    }

    #[test]
    fn test_empty_string() {
        let v = Variant::from("");
        assert_eq!(v.as_string().unwrap(), "");
    }

    #[test]
    fn test_unicode_string() {
        let v = Variant::from("日本語テスト");
        assert_eq!(v.as_string().unwrap(), "日本語テスト");
    }

    // --- CellValue tests ---

    #[test]
    fn test_cell_value_f64() {
        assert!((CellValue::F64(3.14).to_f64() - 3.14).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cell_value_i32() {
        assert!((CellValue::I32(42).to_f64() - 42.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cell_value_str_numeric() {
        assert!((CellValue::Str("2.5".into()).to_f64() - 2.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cell_value_str_non_numeric() {
        assert!((CellValue::Str("N/A".into()).to_f64() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cell_value_empty() {
        assert!((CellValue::Empty.to_f64() - 0.0).abs() < f64::EPSILON);
    }

    // --- is_array tests ---

    #[test]
    fn test_is_array_false_for_scalars() {
        assert!(!Variant::from(1i32).is_array());
        assert!(!Variant::from(1.0f64).is_array());
        assert!(!Variant::from("hello").is_array());
        assert!(!Variant::empty().is_array());
    }

    // --- as_flat_opt_f64_vec / variant_to_opt_f64 tests (GOTCHA #43) ---

    #[test]
    fn test_opt_empty_is_none() {
        assert_eq!(Variant::empty().as_flat_opt_f64_vec().unwrap(), vec![None]);
    }

    #[test]
    fn test_opt_zero_is_some_zero() {
        assert_eq!(Variant::from(0.0f64).as_flat_opt_f64_vec().unwrap(), vec![Some(0.0)]);
        assert_eq!(Variant::from(0i32).as_flat_opt_f64_vec().unwrap(), vec![Some(0.0)]);
    }

    #[test]
    fn test_opt_numeric() {
        assert_eq!(Variant::from(0.25f64).as_flat_opt_f64_vec().unwrap(), vec![Some(0.25)]);
        assert_eq!(Variant::from(3i32).as_flat_opt_f64_vec().unwrap(), vec![Some(3.0)]);
        assert_eq!(Variant::from(-7i32).as_flat_opt_f64_vec().unwrap(), vec![Some(-7.0)]);
    }

    #[test]
    fn test_opt_text_blank_is_none() {
        assert_eq!(Variant::from("").as_flat_opt_f64_vec().unwrap(), vec![None]);
        assert_eq!(Variant::from("   ").as_flat_opt_f64_vec().unwrap(), vec![None]);
    }

    #[test]
    fn test_opt_text_non_numeric_is_none() {
        assert_eq!(Variant::from("N/A").as_flat_opt_f64_vec().unwrap(), vec![None]);
        assert_eq!(Variant::from("n/a").as_flat_opt_f64_vec().unwrap(), vec![None]);
    }

    #[test]
    fn test_opt_text_numeric_parses() {
        assert_eq!(Variant::from("2.5").as_flat_opt_f64_vec().unwrap(), vec![Some(2.5)]);
        assert_eq!(Variant::from("12%").as_flat_opt_f64_vec().unwrap(), vec![Some(0.12)]);
        assert_eq!(Variant::from(" 0 ").as_flat_opt_f64_vec().unwrap(), vec![Some(0.0)]);
    }

    #[test]
    fn test_parse_numeric_text() {
        assert_eq!(parse_numeric_text(""), None);
        assert_eq!(parse_numeric_text("abc"), None);
        assert_eq!(parse_numeric_text("0"), Some(0.0));
        assert_eq!(parse_numeric_text("-1.5"), Some(-1.5));
        assert_eq!(parse_numeric_text("50 %"), Some(0.5));
    }

}