vb6runtime 0.2.0

VB6 runtime library - value system, type conversions, and standard library implementations
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
//! # `GetSetting` Function
//!
//! Returns a registry key setting value from the Windows registry.
//!
//! ## Syntax
//!
//! ```vb
//! GetSetting(appname, section, key[, default])
//! ```
//!
//! ## Parameters
//!
//! - `appname` (Required): `String` expression containing the name of the application or project whose key setting is requested. On Windows, this is a subkey under `HKEY_CURRENT_USER\Software\VB and VBA Program Settings`.
//! - `section` (Required): `String` expression containing the name of the section where the key setting is found.
//! - `key` (Required): `String` expression containing the name of the key setting to return.
//! - `default` (Optional): Expression containing the value to return if no value is set in the key setting. If omitted, default is assumed to be a zero-length string ("").
//!
//! ## Return Value
//!
//! Returns a String containing the value of the specified registry key. If the key doesn't exist and no default is provided, returns an empty string.
//!
//! ## Remarks
//!
//! The `GetSetting` function retrieves settings from the Windows registry that were previously saved using the `SaveSetting` statement. The settings are stored in the application's subkey under:
//!
//! `HKEY_CURRENT_USER\Software\VB and VBA Program Settings\appname\section`
//!
//! - If the registry key doesn't exist, `GetSetting` returns the default value (or "" if no default specified)
//! - `GetSetting` only works with the `HKEY_CURRENT_USER` registry hive
//! - For more advanced registry access, use Windows API functions like `RegOpenKeyEx` and `RegQueryValueEx`
//! - The `appname`, `section`, and `key` parameters are case-insensitive
//! - `GetSetting` is designed to work with `SaveSetting`, `DeleteSetting`, and `GetAllSettings`
//! - On non-Windows platforms, behavior may vary or be unsupported
//!
//! ## Typical Uses
//!
//! 1. **Application Configuration**: Retrieve user preferences and application settings
//! 2. **User Preferences**: Load window positions, sizes, and UI state
//! 3. **Recent Files**: Get most recently used files or paths
//! 4. **Database Connections**: Retrieve connection strings and server names
//! 5. **Feature Toggles**: Load feature flags and experimental settings
//! 6. **Localization**: Get language and regional preferences
//!
//! ## Basic Usage Examples
//!
//! ```vb
//! ' Example 1: Get a simple setting with default
//! Dim userName As String
//! userName = GetSetting("MyApp", "User", "Name", "Guest")
//!
//! ' Example 2: Get window position
//! Dim formLeft As String
//! formLeft = GetSetting("MyApp", "Window", "Left", "0")
//!
//! ' Example 3: Get setting without default
//! Dim lastFile As String
//! lastFile = GetSetting("MyApp", "Recent", "File1")
//!
//! ' Example 4: Get database connection
//! Dim connString As String
//! connString = GetSetting("MyApp", "Database", "ConnectionString", "")
//! ```
//!
//! ## Common Patterns
//!
//! ```vb
//! ' Pattern 1: Load form position and size
//! Private Sub Form_Load()
//!     Me.Left = CLng(GetSetting("MyApp", "MainForm", "Left", "0"))
//!     Me.Top = CLng(GetSetting("MyApp", "MainForm", "Top", "0"))
//!     Me.Width = CLng(GetSetting("MyApp", "MainForm", "Width", "6000"))
//!     Me.Height = CLng(GetSetting("MyApp", "MainForm", "Height", "4500"))
//! End Sub
//!
//! ' Pattern 2: Check if setting exists
//! Function SettingExists(app As String, section As String, key As String) As Boolean
//!     Dim marker As String
//!     marker = String$(10, "X")
//!     SettingExists = (GetSetting(app, section, key, marker) <> marker)
//! End Function
//!
//! ' Pattern 3: Get with type conversion
//! Dim showTips As Boolean
//! showTips = CBool(GetSetting("MyApp", "Options", "ShowTips", "True"))
//!
//! ' Pattern 4: Get recent file list
//! Dim i As Integer
//! Dim recentFiles() As String
//! ReDim recentFiles(1 To 10)
//! For i = 1 To 10
//!     recentFiles(i) = GetSetting("MyApp", "Recent", "File" & i, "")
//!     If recentFiles(i) = "" Then Exit For
//! Next i
//!
//! ' Pattern 5: Get connection info
//! Dim server As String, database As String
//! server = GetSetting("MyApp", "Database", "Server", "localhost")
//! database = GetSetting("MyApp", "Database", "Name", "MyDB")
//!
//! ' Pattern 6: Get user preference with validation
//! Dim fontSize As Integer
//! fontSize = CInt(GetSetting("MyApp", "UI", "FontSize", "10"))
//! If fontSize < 8 Or fontSize > 72 Then fontSize = 10
//!
//! ' Pattern 7: Get setting in With block
//! With Form1
//!     .BackColor = CLng(GetSetting("MyApp", "Colors", "Background", "16777215"))
//! End With
//!
//! ' Pattern 8: Conditional loading
//! If GetSetting("MyApp", "Options", "AutoSave", "False") = "True" Then
//!     EnableAutoSave
//! End If
//!
//! ' Pattern 9: Get multiple related settings
//! Dim smtp As String, port As String, useTLS As String
//! smtp = GetSetting("MyApp", "Email", "SMTPServer", "smtp.gmail.com")
//! port = GetSetting("MyApp", "Email", "Port", "587")
//! useTLS = GetSetting("MyApp", "Email", "UseTLS", "True")
//!
//! ' Pattern 10: Safe retrieval with error handling
//! On Error Resume Next
//! Dim value As String
//! value = GetSetting("MyApp", "Config", "Setting", "DefaultValue")
//! If Err.Number <> 0 Then
//!     value = "DefaultValue"
//!     Err.Clear
//! End If
//! On Error GoTo 0
//! ```
//!
//! ## Advanced Usage Examples
//!
//! ```vb
//! ' Example 1: Settings manager class
//! Public Class AppSettings
//!     Private Const APP_NAME As String = "MyApplication"
//!     
//!     Public Function GetStringSetting(section As String, key As String, _
//!                                      Optional defaultValue As String = "") As String
//!         GetStringSetting = GetSetting(APP_NAME, section, key, defaultValue)
//!     End Function
//!     
//!     Public Function GetIntegerSetting(section As String, key As String, _
//!                                       Optional defaultValue As Integer = 0) As Integer
//!         Dim value As String
//!         value = GetSetting(APP_NAME, section, key, CStr(defaultValue))
//!         On Error Resume Next
//!         GetIntegerSetting = CInt(value)
//!         If Err.Number <> 0 Then GetIntegerSetting = defaultValue
//!     End Function
//!     
//!     Public Function GetBooleanSetting(section As String, key As String, _
//!                                       Optional defaultValue As Boolean = False) As Boolean
//!         Dim value As String
//!         value = GetSetting(APP_NAME, section, key, CStr(defaultValue))
//!         GetBooleanSetting = CBool(value)
//!     End Function
//! End Class
//!
//! ' Example 2: Application configuration loader
//! Private Sub LoadApplicationConfig()
//!     Dim config As New Collection
//!     
//!     config.Add GetSetting("MyApp", "Paths", "Data", App.Path & "\Data"), "DataPath"
//!     config.Add GetSetting("MyApp", "Paths", "Export", App.Path & "\Export"), "ExportPath"
//!     config.Add GetSetting("MyApp", "Paths", "Temp", Environ$("TEMP")), "TempPath"
//!     
//!     config.Add GetSetting("MyApp", "Database", "Server", "localhost"), "DBServer"
//!     config.Add GetSetting("MyApp", "Database", "Name", "AppDB"), "DBName"
//!     
//!     config.Add GetSetting("MyApp", "Options", "AutoBackup", "True"), "AutoBackup"
//!     config.Add GetSetting("MyApp", "Options", "BackupInterval", "60"), "BackupInterval"
//!     
//!     Set g_AppConfig = config
//! End Sub
//!
//! ' Example 3: Multi-user profile system
//! Public Function LoadUserProfile(userName As String) As UserProfile
//!     Dim profile As New UserProfile
//!     Dim section As String
//!     
//!     section = "User_" & userName
//!     
//!     With profile
//!         .FullName = GetSetting("MyApp", section, "FullName", userName)
//!         .Email = GetSetting("MyApp", section, "Email", "")
//!         .Role = GetSetting("MyApp", section, "Role", "User")
//!         .Theme = GetSetting("MyApp", section, "Theme", "Default")
//!         .Language = GetSetting("MyApp", section, "Language", "en-US")
//!         .LastLogin = GetSetting("MyApp", section, "LastLogin", "")
//!     End With
//!     
//!     LoadUserProfile = profile
//! End Function
//!
//! ' Example 4: MRU (Most Recently Used) manager
//! Public Class MRUManager
//!     Private Const MAX_MRU As Integer = 10
//!     Private Const APP_NAME As String = "MyApp"
//!     Private Const SECTION As String = "MRU"
//!     
//!     Public Function GetMRUList() As Collection
//!         Dim mruList As New Collection
//!         Dim i As Integer
//!         Dim item As String
//!         
//!         For i = 1 To MAX_MRU
//!             item = GetSetting(APP_NAME, SECTION, "Item" & i, "")
//!             If Len(item) > 0 Then
//!                 mruList.Add item
//!             Else
//!                 Exit For
//!             End If
//!         Next i
//!         
//!         Set GetMRUList = mruList
//!     End Function
//!     
//!     Public Sub AddMRUItem(filePath As String)
//!         Dim mruList As Collection
//!         Dim i As Integer
//!         Dim item As String
//!         
//!         Set mruList = GetMRUList()
//!         
//!         ' Remove if already exists
//!         For i = 1 To mruList.Count
//!             If StrComp(mruList(i), filePath, vbTextCompare) = 0 Then
//!                 mruList.Remove i
//!                 Exit For
//!             End If
//!         Next i
//!         
//!         ' Add to top
//!         mruList.Add filePath, , 1
//!         
//!         ' Save back
//!         For i = 1 To mruList.Count
//!             If i > MAX_MRU Then Exit For
//!             SaveSetting APP_NAME, SECTION, "Item" & i, mruList(i)
//!         Next i
//!     End Sub
//! End Class
//! ```
//!
//! ## Error Handling
//!
//! `GetSetting` generally doesn't raise errors, but returns the default value if the setting doesn't exist:
//!
//! - **No Error**: If the registry key doesn't exist, returns default (or "" if no default)
//! - **No Error**: If appname, section, or key is empty, returns default value
//! - **Type Mismatch**: Can occur when converting returned String to another type (e.g., `CInt`)
//! - **Registry Access**: On systems where registry access is restricted, may return defaults
//!
//! ```vb
//! ' Safe retrieval with type conversion
//! On Error Resume Next
//! Dim timeout As Integer
//! timeout = CInt(GetSetting("MyApp", "Network", "Timeout", "30"))
//! If Err.Number <> 0 Then
//!     timeout = 30
//!     Err.Clear
//! End If
//! On Error GoTo 0
//! ```
//!
//! ## Performance Considerations
//!
//! - **Registry Access**: Each call accesses the Windows registry, which is slower than memory access
//! - **Caching**: Consider caching frequently used settings in memory
//! - **Startup Time**: Loading many settings at startup can slow application initialization
//! - **Batch Loading**: Use `GetAllSettings` to retrieve all settings in a section at once for better performance
//!
//! ## Best Practices
//!
//! 1. **Use Defaults**: Always provide sensible default values
//! 2. **Validate Values**: Validate retrieved settings before using them
//! 3. **Cache Settings**: Load settings once and cache them for the session
//! 4. **Consistent Naming**: Use consistent naming conventions for `appname`, `section`, and `key`
//! 5. **Error Handling**: Use error handling when converting string values to other types
//! 6. **Cleanup**: Use `DeleteSetting` to remove obsolete settings
//! 7. **Documentation**: Document all registry keys used by your application
//!
//! ## Comparison with Other Registry Functions
//!
//! | Function | Purpose | Returns |
//! |----------|---------|---------|
//! | `GetSetting` | Get single registry value | `String` |
//! | `GetAllSettings` | Get all values in a section | `Variant` array |
//! | `SaveSetting` | Save registry value | N/A (statement) |
//! | `DeleteSetting` | Delete registry key/section | N/A (statement) |
//!
//! ## Platform Compatibility
//!
//! - **Windows**: Full support, uses `HKEY_CURRENT_USER` registry hive
//! - **Other Platforms**: May use alternative storage mechanisms or be unsupported
//! - **Registry Location**: `HKEY_CURRENT_USER\Software\VB and VBA Program Settings\appname\section\key`
//!
//! ## Limitations
//!
//! - Only accesses `HKEY_CURRENT_USER` hive (use Windows API for other hives)
//! - Returns `String` type only (requires conversion for other types)
//! - No direct way to check if a key exists (use unique default value trick)
//! - Limited to VB's registry structure (use Windows API for custom locations)
//! - No support for `REG_BINARY` or other complex registry types
//! - Settings are user-specific, not machine-wide
//!
//! ## Related Functions
//!
//! - `GetAllSettings`: Returns all key settings and their values from a registry section
//! - `SaveSetting`: Saves or creates an application entry in the Windows registry
//! - `DeleteSetting`: Deletes a section or key setting from the Windows registry
//! - `Environ`: Returns the string associated with an environment variable
//! - `Command`: Returns the argument portion of the command line
//! - `App.Path`: Returns the path where the application executable is located

use crate::error::VBResult;
use crate::state::settings;
use crate::value::{VBString, VBVariant};

/// Returns the value stored for `(appname, section, key)` under the VB6
/// settings store, or `default` when no value is stored.
///
/// The three path components are matched case-insensitively, mirroring the
/// Windows registry. `default` defaults to the empty string when the argument
/// is `Empty` (omitted). `Null` arguments raise error 94 (invalid use of
/// `Null`); object and array arguments raise error 13 (type mismatch).
pub fn get_setting(
    appname: &VBString,
    section: &VBString,
    key: &VBString,
    default: Option<&VBString>,
) -> VBResult<VBVariant> {
    let value = settings::get(appname.as_str(), section.as_str(), key.as_str())
        .unwrap_or_else(|| default.map(|d| d.as_str().to_owned()).unwrap_or_default());
    Ok(VBVariant::from_string(value))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::settings as settings_state;
    use crate::state::test_support::with_temp_settings_store;

    fn string(value: &str) -> VBVariant {
        VBVariant::from_string(value)
    }

    #[test]
    fn returns_the_stored_value() {
        with_temp_settings_store(|_| {
            settings_state::set("MyApp", "Window", "Left", "150").unwrap();
            assert_eq!(
                get_setting(
                    &VBString::from("MyApp"),
                    &VBString::from("Window"),
                    &VBString::from("Left"),
                    Some(&VBString::from("0")),
                )
                .unwrap(),
                string("150")
            );
        });
    }

    #[test]
    fn returns_default_when_the_key_is_missing() {
        with_temp_settings_store(|_| {
            assert_eq!(
                get_setting(
                    &VBString::from("MyApp"),
                    &VBString::from("Window"),
                    &VBString::from("Missing"),
                    Some(&VBString::from("42")),
                )
                .unwrap(),
                string("42")
            );
        });
    }

    #[test]
    fn omitted_default_returns_an_empty_string() {
        with_temp_settings_store(|_| {
            assert_eq!(
                get_setting(
                    &VBString::from("MyApp"),
                    &VBString::from("Window"),
                    &VBString::from("Missing"),
                    None,
                )
                .unwrap(),
                string("")
            );
        });
    }

    #[test]
    fn lookup_is_case_insensitive() {
        with_temp_settings_store(|_| {
            settings_state::set("MyApp", "Startup", "Left", "150").unwrap();
            assert_eq!(
                get_setting(
                    &VBString::from("myapp"),
                    &VBString::from("startup"),
                    &VBString::from("LEFT"),
                    Some(&VBString::from("0"))
                )
                .unwrap(),
                string("150")
            );
        });
    }

    #[test]
    fn empty_arguments_return_the_default() {
        with_temp_settings_store(|_| {
            for (appname, section, key) in [
                ("", "Section", "Key"),
                ("App", "", "Key"),
                ("App", "Section", ""),
            ] {
                assert_eq!(
                    get_setting(
                        &VBString::from(appname),
                        &VBString::from(section),
                        &VBString::from(key),
                        Some(&VBString::from("fallback")),
                    )
                    .unwrap(),
                    string("fallback")
                );
            }
        });
    }

    #[test]
    fn values_survive_a_reload_from_disk() {
        with_temp_settings_store(|_| {
            settings_state::set("MyApp", "Startup", "Left", "150").unwrap();
            settings_state::reset();
            assert_eq!(
                get_setting(
                    &VBString::from("MyApp"),
                    &VBString::from("Startup"),
                    &VBString::from("Left"),
                    Some(&VBString::from("0"))
                )
                .unwrap(),
                string("150")
            );
        });
    }
}