visualbasic 0.2.1

Parse and inspect Visual Basic 6 compiled binaries
Documentation
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
//! VB6 form property stream decoder.
//!
//! Decodes the property opcode+value streams in form binary data.
//! Each property is looked up by control type and opcode index in
//! build-time generated tables from `data/vb6_control_properties.csv`.
//!
//! The serialization format is determined by the descriptor flags in
//! MSVBVM60.DLL, traced through the compiler's `WritePropertyStream`
//! function (VB6.EXE `sub_457E57`).

use std::fmt;

use crate::{
    VbProject,
    util::{read_i16_le, read_u16_le, read_u32_le},
    vb::formdata::FormControlType,
    vb::guitable::GuiObjectType,
};

/// Magic value at the start of every StdDataFormat persistence blob.
///
/// This is the first DWORD of the StdDataFormat CLSID
/// `{6B263850-900B-11D0-9484-00A0C91110ED}`, written verbatim as the
/// header signature.
const STD_DATA_FORMAT_MAGIC: u32 = 0x6B263850;

/// VB6 data format type constants (`DataFormatTypeConstants`).
///
/// Determines how the StdDataFormat object applies formatting to
/// data-bound control values. Maps to the `Type` property of the
/// `StdDataFormat` COM object from MSSTDFMT.DLL.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataFormatType {
    /// General format — no special formatting applied.
    General = 0,
    /// Number format — uses the format string for numeric display.
    Number = 1,
    /// Currency format.
    Currency = 2,
    /// Short date format.
    ShortDate = 3,
    /// Long date format.
    LongDate = 4,
    /// Custom format — fully user-defined via the format string.
    /// When this type is active, TrueValue/FalseValue/NullValue
    /// VARIANT entries are also serialized.
    Custom = 5,
}

impl DataFormatType {
    /// Converts a raw u32 to a `DataFormatType`.
    pub fn from_u32(v: u32) -> Option<Self> {
        match v {
            0 => Some(Self::General),
            1 => Some(Self::Number),
            2 => Some(Self::Currency),
            3 => Some(Self::ShortDate),
            4 => Some(Self::LongDate),
            5 => Some(Self::Custom),
            _ => None,
        }
    }
}

impl fmt::Display for DataFormatType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::General => write!(f, "General"),
            Self::Number => write!(f, "Number"),
            Self::Currency => write!(f, "Currency"),
            Self::ShortDate => write!(f, "ShortDate"),
            Self::LongDate => write!(f, "LongDate"),
            Self::Custom => write!(f, "Custom"),
        }
    }
}

/// Decoded StdDataFormat COM object from a form binary property stream.
///
/// The VB6 compiler serializes `DataFormat` properties (ser_type 0x16)
/// by calling `IPersistStream::Save` (IID `{00000109-...}`) on the
/// StdDataFormat COM object from MSSTDFMT.DLL.
///
/// # Binary Layout (reverse engineered from MSSTDFMT.DLL v6.01.9839)
///
/// The persistence format was traced through the COM delegation chain:
/// `IPersistStream::Save` thunk → `StdDataFormat_PersistSave_Wrapper`
/// → main vtable dispatch → `StdDataFormat_SaveToStream` (0x24dd240c).
///
/// ```text
/// HEADER (0x28 = 40 bytes):
///   +0x00  u32  magic           = 0x6B263850 (CLSID first DWORD, "P8&k")
///   +0x04  u32  version         = 0x60000 | 0x60001 | 0x60002
///   +0x08  u32  format_type     = DataFormatTypeConstants (0-5)
///   +0x0C  u32  reserved1       = 0 (zeroed by constructor)
///   +0x10  u32  reserved2       = 0
///   +0x14  u32  fmt_str_len     = format string length (UTF-16 chars)
///   +0x18  u32  has_custom      = 0 or 1 (1 only when type==Custom)
///   +0x1C  u32  true_val_len    = TrueValue BSTR char count
///   +0x20  u32  false_val_len   = FalseValue BSTR char count
///   +0x24  u32  null_val_len    = NullValue BSTR char count
///
/// FORMAT STRING (variable):
///   [fmt_str_len * 2 bytes]     UTF-16LE format string (e.g., "##,###.00")
///
/// CUSTOM VALUES (only when has_custom != 0):
///   For TrueValue, FalseValue, NullValue:
///     [16 bytes]                VARIANT header (VT at byte 0)
///     If VT == 8 (VT_BSTR):    [len * 2 bytes] BSTR character data
///
/// TRAILER (version-dependent):
///   If version >= 0x60001:      [4 bytes] u32 FirstDayOfWeek
///   If version >= 0x60002:      [4 bytes] u32 FirstWeekOfYear
/// ```
///
/// # Version History
///
/// - `0x60000`: Original format — header + format string + custom values only.
/// - `0x60001`: Adds FirstDayOfWeek trailer field.
/// - `0x60002`: Adds FirstWeekOfYear trailer field (current/most common).
#[derive(Debug, Clone)]
pub struct StdDataFormat {
    /// Persistence format version (0x60000, 0x60001, or 0x60002).
    pub version: u32,
    /// Format type determining how data-bound values are displayed.
    pub format_type: DataFormatType,
    /// Format string (e.g., `"##,###.00"` for Number, `"yyyy-mm-dd"` for dates).
    /// Empty for General type or when no custom format string is set.
    pub format: String,
    /// Whether custom TrueValue/FalseValue/NullValue entries are present.
    /// Only true when `format_type == Custom`.
    pub has_custom_values: bool,
    /// FirstDayOfWeek setting. Present when version >= 0x60001.
    /// Maps to VB6 `vbDayOfWeek` constants (0=system, 1=Sunday..7=Saturday).
    pub first_day_of_week: Option<u32>,
    /// FirstWeekOfYear setting. Present when version >= 0x60002.
    /// Maps to VB6 `vbFirstWeekOfYear` constants.
    pub first_week_of_year: Option<u32>,
    /// Total blob size in bytes consumed from the property stream.
    pub blob_size: u32,
}

/// Property value type encoding for the form binary format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropType {
    /// 1-byte value (booleans, enums, flags).
    Byte,
    /// 2-byte signed integer.
    Int16,
    /// 4-byte value (Long, Color, Single).
    Long,
    /// Variable-length ASCII string: `[u16_le byte_length][string + null]`.
    Str,
    /// Variable-length UTF-16 string (Tag/Connect encoding): `[u16_le char_count][char_count * 2 bytes UTF-16LE]`.
    ///
    /// Used by properties with serialization type 0x0D (Tag, Connect, DatabaseName,
    /// RecordSource). Written by compiler `sub_427270` which calls
    /// `SysStringLen` then writes `char_count(2) + data(char_count * 2)`.
    /// No null terminator.
    TagStr,
    /// 16-byte ControlSize: 8 x i16 (ClientLeft/Top/Width/Height + unused).
    Size16,
    /// 11-byte font descriptor.
    Font,
    /// Picture: 4-byte size then data. `0xFFFFFFFF` = default.
    Picture,
    /// Two consecutive Long values (8 bytes): Left + Top callback pair.
    ///
    /// When a child control's Left property has the callback bit (B2 bit 1)
    /// set, the compiler writes 4 bytes of Left value followed by 4 bytes
    /// of Top value from the callback. This encodes position as 8 bytes.
    LongPair,
    /// StdDataFormat COM object serialized via IPersistStream::Save.
    ///
    /// The compiler (VB6.EXE `WritePropertyStream` case 0x16) calls
    /// `IPersistStream::Save(stream, FALSE)` on the StdDataFormat object
    /// from MSSTDFMT.DLL. The persistence format is:
    ///
    /// - 0x28-byte header: magic(4) + version(4) + type(4) + reserved(8) +
    ///   fmt_str_len(4) + has_custom(4) + 3x custom_len(12)
    /// - Format string: `fmt_str_len * 2` bytes UTF-16LE
    /// - If has_custom: 3x VARIANT entries (0x10 each) + optional BSTRs
    /// - Trailer: `first_day_of_week(4)` (if version >= 0x60001) +
    ///   `first_week_of_year(4)` (if version >= 0x60002)
    ///
    /// Reverse engineered from `StdDataFormat_SaveToStream` and
    /// `StdDataFormat_LoadFromStream` in MSSTDFMT.DLL v6.01.9839.
    DataFormat,
    /// Flag-only: opcode is emitted with NO value data following.
    ///
    /// Used for font sub-properties (FontSize, FontBold, FontItalic,
    /// FontStrikethru, FontUnderline) where the descriptor flags have
    /// bits 16-17 both clear. The opcode marks the property as non-default,
    /// but the actual value is embedded in the Font blob (PropType::Font).
    /// Discovered via compiler tracing: `sub_457E57` in VB6.EXE checks
    /// `(flags & 0x10000) != 0 || (flags & 0x20000) != 0` before retrieving
    /// and writing a value. When both bits are clear, only the opcode byte
    /// is written to the stream.
    Flag,
}

impl PropType {
    /// Returns the fixed byte size, or `None` for variable-length types.
    pub fn fixed_size(&self) -> Option<usize> {
        match self {
            Self::Flag => Some(0),
            Self::Byte => Some(1),
            Self::LongPair => Some(8), // Left + Top callback
            Self::Int16 => Some(2),
            Self::Long => Some(4),
            Self::Size16 => Some(16),
            Self::Font => None,       // 11 base + variable nameLen callback
            Self::DataFormat => None, // StdDataFormat IPersistStream blob
            Self::Str | Self::TagStr | Self::Picture => None,
        }
    }
}

/// Returns the property name and type for a form binary property opcode.
///
/// Property opcodes are **context-dependent** — the same index means different
/// properties for different control types.
///
/// Returns `None` for unknown opcodes.
///
/// Source: `data/vb6_control_properties.csv`, verified against MSVBVM60.DLL descriptor tables.
/// All 22 control types (1038 entries) traced from runtime property pointer tables.
pub fn property_info(ctype: FormControlType, opcode: u8) -> Option<(&'static str, PropType)> {
    generated::lookup_property(ctype.to_u8(), opcode).map(|desc| (desc.name, desc.prop_type))
}

/// Returns the full property descriptor for a form binary property opcode.
///
/// Unlike [`property_info`] which returns only `(name, PropType)`, this
/// provides the serialization type and callback byte count from the
/// MSVBVM60.DLL descriptor metadata.
pub fn property_descriptor(
    ctype: FormControlType,
    opcode: u8,
) -> Option<&'static generated::PropertyDesc> {
    generated::lookup_property(ctype.to_u8(), opcode)
}

/// Control position pair (Left + Top) from callback data.
///
/// When a child control's Left property has the callback bit (B2 bit 1)
/// set in the descriptor flags, the compiler writes 4 bytes of Left
/// followed by 4 bytes of Top from the `vtable+0x34` callback.
///
/// # Binary Layout (8 bytes)
///
/// ```text
/// +0x00  u32  left   Twips coordinate
/// +0x04  u32  top    Twips coordinate
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ControlPosition {
    /// Left coordinate in twips.
    pub left: u32,
    /// Top coordinate in twips.
    pub top: u32,
}

impl ControlPosition {
    /// Parses a position pair from raw bytes.
    /// Returns the parsed value and bytes consumed, or `None` if too short.
    pub fn parse(data: &[u8]) -> Option<(Self, usize)> {
        if data.len() < 8 {
            return None;
        }
        Some((
            Self {
                left: read_u32_le(data, 0).ok()?,
                top: read_u32_le(data, 4).ok()?,
            },
            8,
        ))
    }
}

impl fmt::Display for ControlPosition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{},{}", self.left, self.top)
    }
}

/// Client area rectangle from callback data (ClientLeft/Top/Width/Height).
///
/// Written by the form's `vtable+0x34` callback when the ClientLeft
/// descriptor has 12 callback bytes (B2 bit 1 set, 12B trailing data).
///
/// # Binary Layout (16 bytes)
///
/// ```text
/// +0x00  u32  left    Client area left in twips
/// +0x04  u32  top     Client area top in twips (from callback)
/// +0x08  u32  width   Client area width in twips (from callback)
/// +0x0C  u32  height  Client area height in twips (from callback)
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClientRect {
    /// Client area left in twips.
    pub left: u32,
    /// Client area top in twips.
    pub top: u32,
    /// Client area width in twips.
    pub width: u32,
    /// Client area height in twips.
    pub height: u32,
}

impl ClientRect {
    /// Parses a client rectangle from raw bytes.
    /// Returns the parsed value and bytes consumed, or `None` if too short.
    pub fn parse(data: &[u8]) -> Option<(Self, usize)> {
        if data.len() < 16 {
            return None;
        }
        Some((
            Self {
                left: read_u32_le(data, 0).ok()?,
                top: read_u32_le(data, 4).ok()?,
                width: read_u32_le(data, 8).ok()?,
                height: read_u32_le(data, 12).ok()?,
            },
            16,
        ))
    }
}

impl fmt::Display for ClientRect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{},{},{},{}",
            self.left, self.top, self.width, self.height
        )
    }
}

/// Font descriptor from a form binary property stream.
///
/// The VB6 compiler writes font properties as an 11-byte fixed header
/// followed by a variable-length ASCII font name (from the `vtable+0x34`
/// callback, where the name length is byte 10 of the header).
///
/// # Binary Layout (11 + name_len bytes)
///
/// ```text
/// +0x00  u16  charset         Font character set
/// +0x02  u8   pitch_family    Pitch and font family
/// +0x03  u8   flags           Font flags (italic=0x02, underline=0x04, strikeout=0x08)
/// +0x04  u16  weight          Font weight (400=Normal, 700=Bold)
/// +0x06  u32  size_raw        Font size in 1/10000 pt units
/// +0x0A  u8   name_len        Length of trailing font name (ASCII, no null)
/// +0x0B  [name_len bytes]     Font family name (e.g., "MS Sans Serif")
/// ```
#[derive(Debug, Clone)]
pub struct FontDescriptor {
    /// Font size in points (raw value / 10000).
    pub size_pt: u32,
    /// Whether the font is bold (weight >= 700).
    pub bold: bool,
    /// Font weight (400=Normal, 700=Bold, etc.).
    pub weight: u16,
    /// Font family name (e.g., "MS Sans Serif").
    pub name: String,
}

impl FontDescriptor {
    /// Parses a font descriptor from raw bytes.
    /// Returns the parsed value and bytes consumed, or `None` if too short.
    pub fn parse(data: &[u8]) -> Option<(Self, usize)> {
        if data.len() < 11 {
            return None;
        }
        let weight = read_u16_le(data, 4).ok()?;
        let raw_size = read_u32_le(data, 6).ok()?;
        let name_len = (*data.get(10)?) as usize;
        let mut consumed: usize = 11;
        let name = if name_len > 0 {
            let end = consumed.checked_add(name_len)?;
            if end <= data.len() {
                let s = String::from_utf8_lossy(data.get(consumed..end)?).into_owned();
                consumed = end;
                s
            } else {
                String::new()
            }
        } else {
            String::new()
        };
        Some((
            Self {
                size_pt: raw_size.checked_div(10000).unwrap_or(0),
                bold: weight >= 700,
                weight,
                name,
            },
            consumed,
        ))
    }
}

impl fmt::Display for FontDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let b = if self.bold { " Bold" } else { "" };
        write!(f, "({}pt{b}, \"{}\")", self.size_pt, self.name)
    }
}

/// Embedded picture/icon data from a form binary property stream.
///
/// Pictures are serialized with a 4-byte size prefix. The size field
/// includes all overhead (OLE type header + inner data). A sentinel
/// value of `0xFFFFFFFF` indicates the default picture.
///
/// # Binary Layout
///
/// ```text
/// +0x00  u32  size   Total picture data size (or 0xFFFFFFFF for default)
/// +0x04  [size bytes] Picture data (OLE header + BMP/ICO/etc.)
/// ```
#[derive(Debug, Clone)]
pub struct PictureData {
    /// Total picture data size in bytes.
    pub size: u32,
    /// Whether the picture contains a BMP ("BM" magic at offset +8).
    pub is_bmp: bool,
    /// Whether this is the default picture sentinel (0xFFFFFFFF).
    pub is_default: bool,
    /// Embedded picture bytes, excluding the 4-byte size prefix.
    ///
    /// Empty when [`is_default`](Self::is_default) is `true`.
    pub bytes: Vec<u8>,
}

impl PictureData {
    /// Parses picture data from raw bytes.
    /// Returns the parsed value and bytes consumed, or `None` if too short.
    pub fn parse(data: &[u8]) -> Option<(Self, usize)> {
        if data.len() < 4 {
            return None;
        }
        let size = read_u32_le(data, 0).ok()?;
        if size == 0xFFFFFFFF {
            return Some((
                Self {
                    size: 0,
                    is_bmp: false,
                    is_default: true,
                    bytes: Vec::new(),
                },
                4,
            ));
        }
        let total = size as usize;
        let consumed = 4usize.checked_add(total)?;
        if consumed > data.len() {
            return None;
        }
        // OLE header is 8 bytes, BMP magic at data start (offset 12 from blob start)
        let bmp_off: usize = 12;
        let is_bmp =
            data.get(bmp_off) == Some(&b'B') && data.get(bmp_off.checked_add(1)?) == Some(&b'M');
        Some((
            Self {
                size,
                is_bmp,
                is_default: false,
                bytes: data.get(4..consumed)?.to_vec(),
            },
            consumed,
        ))
    }

    /// Returns the embedded BMP/ICO bytes, excluding the size prefix.
    ///
    /// Returns `None` for the default-picture sentinel.
    pub fn bytes(&self) -> Option<&[u8]> {
        if self.is_default {
            None
        } else {
            Some(&self.bytes)
        }
    }
}

impl fmt::Display for PictureData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_default {
            write!(f, "default")
        } else if self.is_bmp {
            write!(f, "(BMP, {}B)", self.size)
        } else {
            write!(f, "({}B)", self.size)
        }
    }
}

impl StdDataFormat {
    /// Parses a StdDataFormat IPersistStream blob from raw bytes.
    /// Returns the parsed value and bytes consumed, or `None` if invalid.
    pub fn parse(data: &[u8]) -> Option<(Self, usize)> {
        if data.len() < 0x28 {
            return None;
        }
        if read_u32_le(data, 0).ok()? != STD_DATA_FORMAT_MAGIC {
            return None;
        }
        let version = read_u32_le(data, 4).ok()?;
        let format_type = read_u32_le(data, 8).ok()?;
        let fmt_str_len = read_u32_le(data, 0x14).ok()? as usize;
        let has_custom = read_u32_le(data, 0x18).ok()?;
        let true_val_len = read_u32_le(data, 0x1C).ok()? as usize;
        let false_val_len = read_u32_le(data, 0x20).ok()? as usize;
        let null_val_len = read_u32_le(data, 0x24).ok()? as usize;

        let mut off: usize = 0x28;

        // Format string (UTF-16LE)
        let fmt_byte_len = fmt_str_len.checked_mul(2)?;
        let fmt_end = off.checked_add(fmt_byte_len)?;
        let format = if fmt_str_len > 0 && fmt_end <= data.len() {
            let utf16: Vec<u16> = (0..fmt_str_len)
                .map(|j| {
                    let pos = off.checked_add(j.checked_mul(2)?)?;
                    read_u16_le(data, pos).ok()
                })
                .collect::<Option<Vec<_>>>()?;
            off = fmt_end;
            String::from_utf16_lossy(&utf16)
        } else {
            off = fmt_end;
            String::new()
        };

        // Custom values (3x VARIANT + optional BSTRs)
        if has_custom != 0 {
            // TrueValue: 0x10 header + (len * 2) bytes
            off = off
                .checked_add(0x10)?
                .checked_add(true_val_len.checked_mul(2)?)?;
            off = off
                .checked_add(0x10)?
                .checked_add(false_val_len.checked_mul(2)?)?;
            off = off
                .checked_add(0x10)?
                .checked_add(null_val_len.checked_mul(2)?)?;
        }

        // Trailer (version-dependent)
        let first_day_of_week =
            if version >= 0x60001 && off.checked_add(4).map(|e| e <= data.len()).unwrap_or(false) {
                let v = read_u32_le(data, off).ok()?;
                off = off.checked_add(4)?;
                Some(v)
            } else {
                None
            };
        let first_week_of_year =
            if version >= 0x60002 && off.checked_add(4).map(|e| e <= data.len()).unwrap_or(false) {
                let v = read_u32_le(data, off).ok()?;
                off = off.checked_add(4)?;
                Some(v)
            } else {
                None
            };

        Some((
            Self {
                version,
                format_type: DataFormatType::from_u32(format_type)
                    .unwrap_or(DataFormatType::General),
                format,
                has_custom_values: has_custom != 0,
                first_day_of_week,
                first_week_of_year,
                blob_size: off as u32,
            },
            off,
        ))
    }
}

impl fmt::Display for StdDataFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.format.is_empty() {
            write!(f, "({}, {}B)", self.format_type, self.blob_size)
        } else {
            write!(
                f,
                "({}, \"{}\", {}B)",
                self.format_type, self.format, self.blob_size
            )
        }
    }
}

/// Parses a VB6 ASCII string from a property stream.
///
/// Format: `[u16_le byte_length][string_bytes][null_terminator]`.
/// Used by ser_types 1, 18, 26, and 33 (Name, String, DataMember).
fn parse_ascii_str(data: &[u8]) -> Option<(String, usize)> {
    if data.len() < 2 {
        return None;
    }
    let len = read_u16_le(data, 0).ok()? as usize;
    let end = 2usize.checked_add(len)?;
    if end >= data.len() {
        return None;
    }
    let s = String::from_utf8_lossy(data.get(2..end)?).into_owned();
    Some((s, end.checked_add(1)?)) // +1 null terminator
}

/// Parses a VB6 UTF-16LE string from a property stream.
///
/// Format: `[u16_le char_count][char_count * 2 bytes UTF-16LE]`.
/// Written by compiler `sub_427270`. No null terminator.
/// Used by ser_type 13 (Tag, Connect, DatabaseName, RecordSource).
fn parse_utf16_str(data: &[u8]) -> Option<(String, usize)> {
    if data.len() < 2 {
        return None;
    }
    let char_count = read_u16_le(data, 0).ok()? as usize;
    let byte_len = char_count.checked_mul(2)?;
    let total = 2usize.checked_add(byte_len)?;
    if total > data.len() {
        return None;
    }
    let utf16: Vec<u16> = (0..char_count)
        .map(|j| {
            let pos = 2usize.checked_add(j.checked_mul(2)?)?;
            read_u16_le(data, pos).ok()
        })
        .collect::<Option<Vec<_>>>()?;
    let s = String::from_utf16_lossy(&utf16);
    Some((s, total))
}

/// A decoded property value from a form binary property stream.
#[derive(Debug, Clone)]
pub enum PropertyValue {
    /// Flag-only — opcode emitted with no value data.
    Flag,
    /// Boolean/enum byte (1 byte).
    Byte(u8),
    /// 16-bit signed integer.
    Int16(i16),
    /// 32-bit integer.
    Long(u32),
    /// OLE color value.
    Color(u32),
    /// ASCII string.
    Str(String),
    /// UTF-16 string (Tag, Connect, DatabaseName, etc.).
    TagStr(String),
    /// Position pair: Left + Top from callback.
    Position(ControlPosition),
    /// Client rectangle from callback.
    ClientRect(ClientRect),
    /// Font descriptor.
    Font(FontDescriptor),
    /// Embedded picture/icon data.
    Picture(PictureData),
    /// StdDataFormat COM object (from MSSTDFMT.DLL).
    DataFormat(StdDataFormat),
}

impl PropertyValue {
    /// Returns the stable persistence string for this value's discriminator.
    ///
    /// These strings are part of the public API contract and are suitable
    /// for database storage: `"Flag"`, `"Byte"`, `"Int16"`, `"Long"`,
    /// `"Color"`, `"Str"`, `"TagStr"`, `"Position"`, `"ClientRect"`,
    /// `"Font"`, `"Picture"`, and `"DataFormat"`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Flag => "Flag",
            Self::Byte(_) => "Byte",
            Self::Int16(_) => "Int16",
            Self::Long(_) => "Long",
            Self::Color(_) => "Color",
            Self::Str(_) => "Str",
            Self::TagStr(_) => "TagStr",
            Self::Position(_) => "Position",
            Self::ClientRect(_) => "ClientRect",
            Self::Font(_) => "Font",
            Self::Picture(_) => "Picture",
            Self::DataFormat(_) => "DataFormat",
        }
    }

    /// Returns the embedded BMP/ICO bytes for [`PropertyValue::Picture`].
    ///
    /// Returns `None` for non-picture values and for the default-picture
    /// sentinel.
    pub fn picture_bytes(&self) -> Option<&[u8]> {
        match self {
            Self::Picture(pic) => pic.bytes(),
            _ => None,
        }
    }

    /// Formats this value with [`Display`](fmt::Display), truncated to a
    /// maximum number of Unicode scalar values.
    ///
    /// Truncation happens only at character boundaries. No suffix is added,
    /// so the returned string length is at most `limit` characters.
    pub fn display_truncated(&self, limit: usize) -> String {
        let rendered = self.to_string();
        if rendered.chars().count() <= limit {
            return rendered;
        }
        rendered.chars().take(limit).collect()
    }
}

impl fmt::Display for PropertyValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Flag => Ok(()),
            Self::Byte(v) => write!(f, "{v}"),
            Self::Int16(v) => write!(f, "{v}"),
            Self::Long(v) => write!(f, "{v}"),
            Self::Color(v) => write!(f, "#{v:06X}"),
            Self::Str(s) | Self::TagStr(s) => {
                write!(f, "\"")?;
                for ch in s.chars() {
                    if ch.is_control() {
                        write!(f, "\\x{:02X}", ch as u32)?;
                    } else {
                        write!(f, "{ch}")?;
                    }
                }
                write!(f, "\"")
            }
            Self::Position(p) => write!(f, "{p}"),
            Self::ClientRect(r) => write!(f, "{r}"),
            Self::Font(font) => write!(f, "{font}"),
            Self::Picture(pic) => write!(f, "{pic}"),
            Self::DataFormat(df) => write!(f, "{df}"),
        }
    }
}

/// A single decoded property from a form binary stream.
#[derive(Debug, Clone)]
pub struct Property {
    /// Property name (e.g., "Caption", "BackColor").
    pub name: &'static str,
    /// Decoded value.
    pub value: PropertyValue,
    /// Byte offset of this property's value within the property stream.
    pub offset: usize,
}

/// Iterator over decoded properties in a form binary property stream.
///
/// Created by [`FormControlRecord::properties`](crate::vb::formdata::FormControlRecord::properties) or
/// [`FormDataParser::form_properties_decoded`](crate::vb::formdata::FormDataParser::form_properties_decoded).
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct PropertyIter<'a> {
    data: &'a [u8],
    pos: usize,
    ctype: FormControlType,
}

impl<'a> PropertyIter<'a> {
    /// Creates a new property iterator over the given raw property stream.
    pub fn new(data: &'a [u8], ctype: FormControlType) -> Self {
        Self {
            data,
            pos: 0,
            ctype,
        }
    }

    /// Decodes a single property value based on ser_type and callback_bytes.
    /// Returns `None` if the stream is truncated.
    fn decode_value(&mut self, ser_type: u8, callback_bytes: i8) -> Option<PropertyValue> {
        let d = self.data;
        let p = self.pos;
        let rest = d.get(p..)?;
        match ser_type {
            0 => Some(PropertyValue::Flag),

            // ASCII string (Name, String, DataMember)
            1 | 18 | 26 | 33 => {
                let (s, consumed) = parse_ascii_str(rest)?;
                self.pos = self.pos.checked_add(consumed)?;
                Some(PropertyValue::Str(s))
            }

            // Int16
            2 | 17 => {
                let v = read_i16_le(d, p).ok()?;
                self.pos = self.pos.checked_add(2)?;
                Some(PropertyValue::Int16(v))
            }

            // Long
            3 => {
                let v = read_u32_le(d, p).ok()?;
                self.pos = self.pos.checked_add(4)?;
                Some(PropertyValue::Long(v))
            }

            // Byte
            4 => {
                let v = *rest.first()?;
                self.pos = self.pos.checked_add(1)?;
                Some(PropertyValue::Byte(v))
            }

            // OLE_COLOR
            5 => {
                let v = read_u32_le(d, p).ok()?;
                self.pos = self.pos.checked_add(4)?;
                Some(PropertyValue::Color(v))
            }

            // Enum/Byte + optional callback trailing data
            6 => {
                let v = *rest.first()?;
                self.pos = self.pos.checked_add(1)?;
                if callback_bytes > 0 {
                    let skip = callback_bytes as usize;
                    let new_pos = self.pos.checked_add(skip)?;
                    if new_pos <= d.len() {
                        self.pos = new_pos;
                    }
                }
                Some(PropertyValue::Byte(v))
            }

            // Single/Currency/Twips Y/H (4 bytes, displayed as Long)
            7 | 10 | 11 => {
                let v = read_u32_le(d, p).ok()?;
                self.pos = self.pos.checked_add(4)?;
                Some(PropertyValue::Long(v))
            }

            // Twips X/W (4 bytes + optional callback for Position/ClientRect)
            8 | 9 => match callback_bytes {
                4 => {
                    let (pos, consumed) = ControlPosition::parse(rest)?;
                    self.pos = self.pos.checked_add(consumed)?;
                    Some(PropertyValue::Position(pos))
                }
                12 => {
                    let (rect, consumed) = ClientRect::parse(rest)?;
                    self.pos = self.pos.checked_add(consumed)?;
                    Some(PropertyValue::ClientRect(rect))
                }
                _ => {
                    let v = read_u32_le(d, p).ok()?;
                    self.pos = self.pos.checked_add(4)?;
                    Some(PropertyValue::Long(v))
                }
            },

            // UTF-16LE string (Tag, Connect, DatabaseName, RecordSource)
            13 => {
                let (s, consumed) = parse_utf16_str(rest)?;
                self.pos = self.pos.checked_add(consumed)?;
                Some(PropertyValue::TagStr(s))
            }

            // Font descriptor (11B header + variable name callback)
            20 => {
                let (font, consumed) = FontDescriptor::parse(rest)?;
                self.pos = self.pos.checked_add(consumed)?;
                Some(PropertyValue::Font(font))
            }

            // Picture / Icon
            21 => {
                let (pic, consumed) = PictureData::parse(rest)?;
                self.pos = self.pos.checked_add(consumed)?;
                Some(PropertyValue::Picture(pic))
            }

            // StdDataFormat IPersistStream blob
            22 => {
                let (df, consumed) = StdDataFormat::parse(rest)?;
                self.pos = self.pos.checked_add(consumed)?;
                Some(PropertyValue::DataFormat(df))
            }

            // Unknown ser_type — treat as flag
            _ => Some(PropertyValue::Flag),
        }
    }
}

impl<'a> Iterator for PropertyIter<'a> {
    type Item = Property;

    fn next(&mut self) -> Option<Property> {
        let opcode = *self.data.get(self.pos)?;
        if opcode == 0xFF {
            return None;
        }

        let opcode_offset = self.pos;

        // Known property — decode via ser_type dispatch
        if let Some(desc) = property_descriptor(self.ctype, opcode) {
            self.pos = self.pos.checked_add(1)?; // consume opcode byte
            let value_offset = self.pos;

            if desc.prop_type == PropType::Flag {
                return Some(Property {
                    name: desc.name,
                    value: PropertyValue::Flag,
                    offset: opcode_offset,
                });
            }

            let value = self.decode_value(desc.ser_type, desc.callback_bytes)?;
            return Some(Property {
                name: desc.name,
                value,
                offset: value_offset,
            });
        }

        // Unknown opcode — try lookahead to skip flag-like unknowns
        self.pos = self.pos.checked_add(1)?;
        if let Some(&next) = self.data.get(self.pos)
            && (next == 0xFF || property_info(self.ctype, next).is_some())
        {
            let unknown_name: &'static str = Box::leak(format!("?0x{opcode:02X}").into_boxed_str());
            return Some(Property {
                name: unknown_name,
                value: PropertyValue::Flag,
                offset: opcode_offset,
            });
        }
        None
    }
}

/// Determines the correct [`FormControlType`] for a form-level property stream.
///
/// The GUI entry type doesn't always match the actual form content in OCX files
/// (e.g., PropertyPage form data stored under UserControl GUI entries). This
/// function examines the stream content and project metadata to resolve the
/// correct type deterministically.
pub fn decode_form_type(
    gui_type: GuiObjectType,
    form_props: &[u8],
    project: &VbProject<'_>,
) -> FormControlType {
    match gui_type {
        GuiObjectType::PropertyPage => FormControlType::PropertyPage,
        GuiObjectType::UserControl => {
            // Check if this is actually a PropertyPage by matching the form
            // Name against project objects. The compiler writes using the
            // object's own TypeInfo, which may differ from the GUI entry.
            if form_props.len() > 3 && form_props.first() == Some(&0x00) {
                let Ok(nlen) = read_u16_le(form_props, 1) else {
                    return FormControlType::UserControl;
                };
                let nlen = nlen as usize;
                let Some(name_end) = 3usize.checked_add(nlen) else {
                    return FormControlType::UserControl;
                };
                if let Some(form_name) = form_props.get(3..name_end) {
                    let Ok(objects) = project.objects() else {
                        return FormControlType::UserControl;
                    };
                    for other_obj in objects {
                        if let Ok(other_obj) = other_obj
                            && let Ok(n) = other_obj.name_bytes()
                            && n == form_name
                        {
                            let Ok(otype) = other_obj.descriptor().object_type_raw() else {
                                break;
                            };
                            // Designer objects (flag 0x02) that aren't UserControl
                            // (flag 0x20) are PropertyPages
                            if otype & 0x02 != 0 && otype & 0x20 == 0 {
                                return FormControlType::PropertyPage;
                            }
                            break;
                        }
                    }
                }
            }
            FormControlType::UserControl
        }
        // Form and MDIForm gui types. UserDocument also uses Form gui type
        // in practice — the Form table handles it correctly since the property
        // streams overlap at common indices. The UserDocument table has additional
        // document-specific properties at indices 76+ (ScrollBars, Viewport, etc.)
        // that are only emitted for real UserDocument streams.
        _ => FormControlType::Form,
    }
}

/// Build-time generated property lookup tables.
/// Source: `data/vb6_control_properties.csv`.
pub(crate) mod generated {
    include!(concat!(env!("OUT_DIR"), "/property_generated.rs"));
}