vb6parse 1.0.1

vb6parse is a library for parsing and analyzing VB6 code, from projects, to controls, to modules, and forms.
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
//! Defines the `Color` enum and related functionality for handling colors
//! in VB6 forms and controls.
//!
//! This module includes predefined VB6 colors as constants, as well as methods
//! for parsing and formatting colors in the VB6 hex format.
//!
//! In VB6, colors are represented as 24-bit RGB values stored in a special
//! format as '&H00BBGGRR&' for RGB colors and '&H800000II&' for system colors,
//! where 'II' is the index of the system color.
//!
//!! # Example
//! ```rust
//! use vb6parse::language::Color;
//! let color = Color::from_hex("&H00FF0000&")
//!     .expect("Failed to parse color");
//! assert_eq!(color, Color::RGB { red: 0x00, green: 0x00, blue: 0xFF });
//! assert_eq!(color.to_vb_string(), "&H00FF0000&");
//! ```

use crate::errors::{ErrorKind, FormError};

use std::fmt::Display;

/// `Colors` are 24 bits with 8 bits for red, green, and blue.
///
/// `Colors` are stored and used within VB6 as text formatted as '&H00BBGGRR&'.
/// If, instead, the value begins with '&H80' such as in '&H80000000&', then
/// the color is a system color. and the value is not the elements of the color,
/// but rather the index of a system color.
#[derive(Debug, PartialEq, Clone, Eq, serde::Serialize, Copy, Hash)]
pub enum Color {
    /// A color represented by red, green, and blue values.
    /// The values are 8 bits each.
    /// The values are stored in the order of red, green, blue.
    /// This is the same as calling `Color::new(red, green, blue)`.
    RGB {
        /// The red value.
        red: u8,
        /// The green value.
        green: u8,
        /// The blue value.
        blue: u8,
    },
    /// A system color represented by an index.
    /// The index is the index of the system color.
    /// This is the same as calling `Color::system(index)`.
    System {
        /// The system color index.
        index: u8,
    },
}

impl Display for Color {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut predefined = false;
        let mut vb_color_name = "";

        if let Some((name, _)) = PREDEFINED_COLORS.iter().find(|(_, color)| color == self) {
            predefined = true;
            vb_color_name = name;
        }

        match self {
            Color::RGB { red, green, blue } if predefined => {
                write!(
                    f,
                    "{vb_color_name} RGB({red}, {green}, {blue}) - {}",
                    self.to_vb_string()
                )
            }
            Color::System { index } if predefined => {
                write!(
                    f,
                    "{vb_color_name} System({}) - {}",
                    index,
                    self.to_vb_string()
                )
            }
            Color::RGB { red, green, blue } => {
                write!(f, "RGB({red}, {green}, {blue}) = {}", self.to_vb_string())
            }
            Color::System { index } => {
                write!(f, "System({}) = {}", index, self.to_vb_string())
            }
        }
    }
}

impl Color {
    /// Converts the `Color` to a VB6 formatted string.
    ///
    /// # Returns
    ///
    /// A string formatted as '&H00BBGGRR&' for RGB colors
    /// or '&H800000II&' for system colors.
    #[must_use]
    pub fn to_vb_string(&self) -> String {
        match self {
            Color::RGB { red, green, blue } => {
                format!("&H00{blue:02X}{green:02X}{red:02X}&")
            }
            Color::System { index } => {
                format!("&H80{index:06X}&")
            }
        }
    }
}

/// A list of predefined VB6 colors.
/// Each entry is a tuple of the VB6 color name and the corresponding `Color`.
/// This includes both RGB colors and system colors.
pub const PREDEFINED_COLORS: [(&str, Color); 24] = [
    ("vbBlack", VB_BLACK),
    ("vbWhite", VB_WHITE),
    ("vbRed", VB_RED),
    ("vbGreen", VB_GREEN),
    ("vbBlue", VB_BLUE),
    ("vbYellow", VB_YELLOW),
    ("vbMagenta", VB_MAGENTA),
    ("vbCyan", VB_CYAN),
    ("vbScrollBars", VB_SCROLL_BARS),
    ("vbDesktop", VB_DESKTOP),
    ("vbActiveTitleBar", VB_ACTIVE_TITLE_BAR),
    ("vbInactiveTitleBar", VB_INACTIVE_TITLE_BAR),
    ("vbMenuBar", VB_MENU_BAR),
    ("vbWindowBackground", VB_WINDOW_BACKGROUND),
    ("vbWindowFrame", VB_WINDOW_FRAME),
    ("vbMenuText", VB_MENU_TEXT),
    ("vbWindowText", VB_WINDOW_TEXT),
    ("vbTitleBarText", VB_TITLE_BAR_TEXT),
    ("vbActiveBorder", VB_ACTIVE_BORDER),
    ("vbInactiveBorder", VB_INACTIVE_BORDER),
    ("vbApplicationWorkspace", VB_APPLICATION_WORKSPACE),
    ("vbHighlight", VB_HIGHLIGHT),
    ("vbHighlightText", VB_HIGHLIGHT_TEXT),
    ("vbButtonFace", VB_BUTTON_FACE),
];

/// A `Color` with red, green, and blue values of 0x00.
/// This is the same as calling `Color::new(0x00, 0x00, 0x00)`.
/// This corresponds to the VB6 color constant `vbBlack`.
pub const VB_BLACK: Color = Color::RGB {
    red: 0x00,
    green: 0x00,
    blue: 0x00,
};

/// A `Color` with red, green, and blue values of 0xFF.
/// This is the same as calling `Color::new(0xFF, 0xFF, 0xFF)`.
/// This corresponds to the VB6 color constant `vbWhite`.
pub const VB_WHITE: Color = Color::RGB {
    red: 0xFF,
    green: 0xFF,
    blue: 0xFF,
};

/// A `Color` with a red value of 0xFF and a green and blue value of 0x00.
/// This is the same as calling `Color::new(0xFF, 0x00, 0x00)`.
/// This corresponds to the VB6 color constant `vbRed`.
pub const VB_RED: Color = Color::RGB {
    red: 0xFF,
    green: 0x00,
    blue: 0x00,
};

/// A `Color` with a red value of 0x00 and a green value of
/// 0xFF and a blue value of 0x00.
///
/// This is the same as calling `Color::new(0x00, 0xFF, 0x00)`.
/// This corresponds to the VB6 color constant `vbGreen`.
pub const VB_GREEN: Color = Color::RGB {
    red: 0x00,
    green: 0xFF,
    blue: 0x00,
};

/// A `Color` with red and green values of 0x00 and a blue value of 0xFF.
///
/// This is the same as calling `Color::new(0x00, 0x00, 0xFF)`.
/// This corresponds to the VB6 color constant `vbBlue`.
pub const VB_BLUE: Color = Color::RGB {
    red: 0x00,
    green: 0x00,
    blue: 0xFF,
};

/// A `Color` with a red and green value of 0xFF and a blue value of 0x00.
///
/// This is the same as calling `Color::new(0xFF, 0xFF, 0x00)`.
/// This corresponds to the VB6 color constant `vbYellow`.
pub const VB_YELLOW: Color = Color::RGB {
    red: 0xFF,
    green: 0xFF,
    blue: 0x00,
};

/// A `Color` with a red and blue value of 0xFF and a green value of 0x00.
///
/// This is the same as calling `Color::new(0xFF, 0x00, 0xFF)`.
/// This corresponds to the VB6 color constant `vbMagenta`.
pub const VB_MAGENTA: Color = Color::RGB {
    red: 0xFF,
    green: 0x00,
    blue: 0xFF,
};

/// A `Color` with a red value of 0x00 and a green and blue value of 0xFF.
///
/// This is the same as calling `Color::new(0x00, 0xFF, 0xFF)`.
/// This corresponds to the VB6 color constant `vbCyan`.
pub const VB_CYAN: Color = Color::RGB {
    red: 0x00,
    green: 0xFF,
    blue: 0xFF,
};

/// Scrollbar color
pub const VB_SCROLL_BARS: Color = Color::System { index: 0x00 };

/// Desktop color
pub const VB_DESKTOP: Color = Color::System { index: 0x01 };

/// Color of the title bar for the active window
pub const VB_ACTIVE_TITLE_BAR: Color = Color::System { index: 0x02 };

/// Color of the title bar for the inactive window
pub const VB_INACTIVE_TITLE_BAR: Color = Color::System { index: 0x03 };

/// Menu background color
pub const VB_MENU_BAR: Color = Color::System { index: 0x04 };

/// Window background color
pub const VB_WINDOW_BACKGROUND: Color = Color::System { index: 0x05 };

/// Window frame color
pub const VB_WINDOW_FRAME: Color = Color::System { index: 0x06 };

/// Color of text on menus
pub const VB_MENU_TEXT: Color = Color::System { index: 0x07 };

/// Color of text in windows
pub const VB_WINDOW_TEXT: Color = Color::System { index: 0x08 };

/// Color of text in caption, size box, and scroll arrow
pub const VB_TITLE_BAR_TEXT: Color = Color::System { index: 0x09 };

/// Border color of active window
pub const VB_ACTIVE_BORDER: Color = Color::System { index: 0x0A };

/// Border color of inactive window
pub const VB_INACTIVE_BORDER: Color = Color::System { index: 0x0B };

/// Background color of multiple document interface (MDI) applications
pub const VB_APPLICATION_WORKSPACE: Color = Color::System { index: 0x0C };

/// Background color of items selected in a control
pub const VB_HIGHLIGHT: Color = Color::System { index: 0x0D };

/// Text color of items selected in a control
pub const VB_HIGHLIGHT_TEXT: Color = Color::System { index: 0x0E };

/// Color of shading on the face of command buttons
pub const VB_BUTTON_FACE: Color = Color::System { index: 0x0F };

/// Color of shading on the face of command buttons
pub const VB_3D_FACE: Color = Color::System { index: 0x0F };

/// Lightest shadow color for 3-D display elements
pub const VB_3D_SHADOW: Color = Color::System { index: 0x10 };

/// Color of shading on the edge of command buttons
pub const VB_BUTTON_SHADOW: Color = Color::System { index: 0x10 };

/// Grayed (disabled) text
pub const VB_GRAY_TEXT: Color = Color::System { index: 0x11 };

/// Text color on push buttons
pub const VB_BUTTON_TEXT: Color = Color::System { index: 0x12 };

/// Color of text in an inactive caption
pub const VB_INACTIVE_CAPTION_TEXT: Color = Color::System { index: 0x13 };

/// Highlight color for 3-D display elements
pub const VB_3D_HIGHLIGHT: Color = Color::System { index: 0x14 };

/// Darkest shadow color for 3-D display elements.
pub const VB_3D_DK_SHADOW: Color = Color::System { index: 0x15 };

/// Second lightest 3-D color after vb3DHighlight
pub const VB_3D_LIGHT: Color = Color::System { index: 0x16 };

/// Color of text in tool tips
pub const VB_INFO_TEXT: Color = Color::System { index: 0x17 };

/// Color of text in tool tips
pub const VB_MSG_BOX: Color = Color::System { index: 0x17 };

/// Background color of tool tips
pub const VB_INFO_BACKGROUND: Color = Color::System { index: 0x18 };

/// Background color of tool tips
pub const VB_MSG_BOX_TEXT: Color = Color::System { index: 0x18 };

impl Color {
    /// Creates a new `Color`.
    ///
    /// # Arguments
    ///
    /// * `red` - The red value.
    /// * `green` - The green value.
    /// * `blue` - The blue value.
    ///
    /// # Returns
    ///
    /// A new RGB `Color`.
    #[must_use]
    pub fn new(red: u8, green: u8, blue: u8) -> Self {
        Color::RGB { red, green, blue }
    }

    /// Creates a new `Color` that represents a system color.
    /// The index is the index of the system color.
    /// This is the same as calling `Color::System { index }`.
    ///
    /// # Arguments
    /// * `index` - The index of the system color.
    ///
    /// # Returns
    ///
    /// A new system `Color`.
    #[must_use]
    pub fn system(index: u8) -> Self {
        Color::System { index }
    }

    /// Creates a new `Color` with an RGB value.
    /// This is the same as calling `Color::new(red, green, blue)`.
    ///
    /// # Arguments
    ///
    /// * `red` - The red value.
    /// * `green` - The green value.
    /// * `blue` - The blue value.
    ///
    /// # Returns
    ///
    /// A new RGB `Color`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use assert_matches::assert_matches;
    ///
    ///
    /// use vb6parse::language::Color;
    ///
    /// let color = Color::rgb(0xFF, 0x33, 0x12);
    ///
    /// assert_matches!(color, Color::RGB { .. } );
    /// assert_eq!(color, Color::RGB { red: 0xFF, green: 0x33, blue: 0x12 });
    /// ```
    #[must_use]
    pub fn rgb(red: u8, green: u8, blue: u8) -> Self {
        Color::RGB { red, green, blue }
    }

    /// Parses a `Color`.
    ///
    /// The color is represented as a 24-bit RGB value.
    /// The red, green, and blue values are each 8-bits.
    /// This is stored and used in VB6 as a formatted hex text value &H00BBGGRR&.
    ///
    /// # Arguments
    ///
    /// * `input` - The input to parse.
    ///
    /// # Errors
    ///
    /// If the input is not a valid hex color of either a
    /// '&H00BBGGRR&' or '&H800000II&' format, then a `ErrorKind::Form(FormError::HexColorParseError)` is returned.
    ///
    /// The '&H00BBGGRR&' format is a 24-bit RGB color in the order of blue, green, red.
    /// where each element is in hex format.
    ///
    /// The '&H800000II&' format is a system color with the index value of 'II'.
    /// Again, where 'II' is in hex format.
    ///
    /// # Returns
    ///
    /// The `Color`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # fn main() -> Result<(), vb6parse::errors::ErrorKind> {
    ///     use assert_matches::assert_matches;
    ///
    ///     use vb6parse::language::Color;
    ///
    ///     // Of course, VB6 being as it is...
    ///     // the color is stored in a 'special' order.
    ///     // blue, green, red
    ///     let mut input = "&H00BBCCFF&";
    ///     let color = Color::from_hex(&input)?;
    ///
    ///     assert_matches!(color, Color::RGB { .. } );
    ///     assert_eq!(color, Color::RGB { red: 0xFF, green: 0xCC, blue: 0xBB });
    ///     # Ok(())
    /// # }
    /// ```
    pub fn from_hex(input: &str) -> Result<Color, ErrorKind> {
        let kind_ascii = &input[2..4];

        let kind = u8::from_str_radix(kind_ascii, 16)
            .map_err(|_| ErrorKind::Form(FormError::HexColorParseError))?;

        if kind == 0x80 {
            // System color
            let index = u8::from_str_radix(&input[8..10], 16)
                .map_err(|_| ErrorKind::Form(FormError::HexColorParseError))?;
            return Ok(Color::system(index));
        } else if kind != 0x00 {
            return Err(ErrorKind::Form(FormError::HexColorParseError));
        }

        let blue_ascii = &input[4..6];
        let green_ascii = &input[6..8];
        let red_ascii = &input[8..10];

        let blue = u8::from_str_radix(blue_ascii, 16)
            .map_err(|_| ErrorKind::Form(FormError::HexColorParseError))?;
        let green = u8::from_str_radix(green_ascii, 16)
            .map_err(|_| ErrorKind::Form(FormError::HexColorParseError))?;
        let red = u8::from_str_radix(red_ascii, 16)
            .map_err(|_| ErrorKind::Form(FormError::HexColorParseError))?;

        Ok(Color::new(red, green, blue))
    }
}