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
use crate::errors::{SageError, SageResult};
use std::{collections::HashMap, marker::PhantomData, rc::Rc};
use windows::{core::*, Win32::System::Com::*, Win32::System::Variant::*};
/// Instance COM sûre avec gestion automatique du cycle de vie.
///
/// Cette instance reste liée au thread STA qui a initialisé COM et ne doit
/// pas être partagée entre threads.
pub struct ComInstance {
#[allow(dead_code)] // Sera utilisé dans les futures versions
unknown: IUnknown,
dispatch: Option<IDispatch>,
initialized_com: bool,
_sta_marker: PhantomData<Rc<()>>,
}
#[derive(Debug, Clone)]
pub enum MemberType {
Method,
#[allow(dead_code)] // Sera utilisé dans les futures versions
PropertyGet,
#[allow(dead_code)] // Sera utilisé dans les futures versions
PropertyPut,
#[allow(dead_code)] // Sera utilisé dans les futures versions
PropertyPutRef,
}
#[derive(Debug, Clone)]
pub struct MemberInfo {
pub id: i32,
pub name: String,
pub member_type: MemberType,
pub param_count: Option<u32>,
pub return_type: Option<String>,
}
impl ComInstance {
/// Crée une nouvelle instance COM en initialisant automatiquement COM si nécessaire
pub fn new(clsid: &str) -> SageResult<Self> {
unsafe {
// Initialiser COM
let com_result = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
let initialized_com = com_result.is_ok();
// Parser le CLSID
let guid = Self::parse_clsid(clsid)?;
// Créer l'instance
let unknown: IUnknown =
CoCreateInstance(&guid, None, CLSCTX_INPROC_SERVER).map_err(|e| {
if initialized_com {
CoUninitialize();
}
SageError::from(e)
})?;
// Tenter d'obtenir IDispatch pour l'automation
let dispatch = unknown.cast::<IDispatch>().ok();
Ok(ComInstance {
unknown,
dispatch,
initialized_com,
_sta_marker: PhantomData,
})
}
}
/// Crée une instance à partir d'un IUnknown existant
#[allow(dead_code)] // Sera utilisé dans les futures versions
pub fn from_unknown(unknown: IUnknown) -> Self {
let dispatch = unknown.cast::<IDispatch>().ok();
ComInstance {
unknown,
dispatch,
initialized_com: false, // N'a pas initialisé COM
_sta_marker: PhantomData,
}
}
/// Obtient l'interface IDispatch pour l'automation
pub fn dispatch(&self) -> SageResult<&IDispatch> {
self.dispatch.as_ref().ok_or_else(|| {
SageError::InternalError("Interface IDispatch non disponible".to_string())
})
}
/// Obtient l'interface IUnknown
#[allow(dead_code)] // Sera utilisé dans les futures versions
pub fn unknown(&self) -> &IUnknown {
&self.unknown
}
/// Vérifie si l'instance supporte l'automation
pub fn supports_automation(&self) -> bool {
self.dispatch.is_some()
}
/// Parse un CLSID string en GUID
fn parse_clsid(clsid_str: &str) -> SageResult<GUID> {
let clsid_formatted = if clsid_str.starts_with('{') {
clsid_str.to_string()
} else {
format!("{{{}}}", clsid_str)
};
let clsid_wide: Vec<u16> = clsid_formatted
.encode_utf16()
.chain(std::iter::once(0))
.collect();
unsafe { CLSIDFromString(PCWSTR(clsid_wide.as_ptr())).map_err(SageError::from) }
}
/// Obtient les informations de type de l'objet COM
pub fn get_type_info(&self) -> SageResult<String> {
let dispatch = self.dispatch()?;
unsafe {
let type_info_count = dispatch.GetTypeInfoCount()?;
if type_info_count == 0 {
return Ok("Aucune information de type disponible".to_string());
}
let type_info = dispatch.GetTypeInfo(0, 0)?;
let mut names = BSTR::default();
let mut doc_string = BSTR::default();
type_info.GetDocumentation(
-1, // MEMBERID_NIL
Some(&mut names as *mut BSTR),
Some(&mut doc_string as *mut BSTR),
std::ptr::null_mut(),
None,
)?;
Ok(format!("Nom: {}, Description: {}", names, doc_string))
}
}
/// Obtient l'interface ITypeInfo brute pour introspection avancée
#[allow(dead_code)] // Sera utilisé dans les futures versions
fn get_type_info_raw(&self) -> SageResult<ITypeInfo> {
let dispatch = self.dispatch()?;
unsafe {
let type_info_count = dispatch.GetTypeInfoCount()?;
if type_info_count == 0 {
return Err(SageError::InternalError(
"Aucune information de type disponible".to_string(),
));
}
dispatch.GetTypeInfo(0, 0).map_err(SageError::from)
}
}
/// Liste les méthodes disponibles
pub fn list_methods(&self) -> SageResult<Vec<(i32, String)>> {
let dispatch = self.dispatch()?;
let mut methods = Vec::new();
unsafe {
let type_info_count = dispatch.GetTypeInfoCount()?;
if type_info_count > 0 {
let type_info = dispatch.GetTypeInfo(0, 0)?;
// Essayer de récupérer les méthodes par ID
for method_id in 1..=50 {
// Limite arbitraire
let mut names = BSTR::default();
if type_info
.GetDocumentation(
method_id,
Some(&mut names as *mut BSTR),
None,
std::ptr::null_mut(),
None,
)
.is_ok()
{
methods.push((method_id, names.to_string()));
}
}
}
}
Ok(methods)
}
/// Liste toutes les méthodes et propriétés avec leur type (version intelligente)
pub fn list_members(&self) -> SageResult<Vec<MemberInfo>> {
// Utiliser la découverte basique puis analyser intelligemment
let basic_methods = self.list_methods()?;
let mut members = Vec::new();
for (id, name) in basic_methods {
// Analyser le nom et ID pour déterminer le type réel
let member_type = Self::classify_member_by_name(&name, id);
// Estimer le nombre de paramètres basé sur le nom
let param_count = Self::estimate_parameter_count(&name, &member_type);
// Deviner le type de retour basé sur le nom
let return_type = Self::guess_return_type(&name, &member_type);
members.push(MemberInfo {
id,
name,
member_type,
param_count,
return_type,
});
}
Ok(members)
}
/// Classifie un membre basé sur son nom et des heuristiques COM Sage
fn classify_member_by_name(name: &str, _id: i32) -> MemberType {
// Propriétés évidentes : Factory*
if name.starts_with("Factory") {
return MemberType::PropertyGet;
}
// Propriétés communes dans les objets Sage COM
let property_names = [
"Name",
"Version",
"Database",
"User",
"Server",
"Path",
"Description",
"Type",
"Count",
"Value",
"Status",
"State",
"Mode",
"Level",
"Index",
"Size",
"IsOpen",
"Application",
"Parent",
"Collection",
"Handle",
"ID",
"Code",
"Reference",
];
// Vérification exacte des noms de propriétés
if property_names.contains(&name) {
return MemberType::PropertyGet;
}
// Méthodes évidentes : verbes d'action
let method_verbs = [
"Open",
"Close",
"Create",
"Delete",
"Add",
"Remove",
"Update",
"Save",
"Load",
"Connect",
"Disconnect",
"Execute",
"Run",
"Start",
"Stop",
"Cancel",
"Reset",
"Clear",
"Refresh",
"Reload",
"Import",
"Export",
"Print",
"Preview",
"Validate",
"Check",
"Test",
"Initialize",
"Finalize",
"Process",
"Calculate",
"Search",
"Find",
"Locate",
"Get",
"Set",
"Move",
"Copy",
"Paste",
"Cut",
"Undo",
"Redo",
"Backup",
"Restore",
"Synchronize",
"Synchro",
"ReadFrom",
"List",
"ExistNumero",
"Read",
"Query",
];
// Si le nom commence par un verbe d'action
if method_verbs.iter().any(|&verb| name.starts_with(verb)) {
return MemberType::Method;
}
// Pattern CamelCase sans verbe d'action = probablement propriété
if name.chars().next().unwrap_or('a').is_uppercase()
&& !name.contains('(')
&& !name.contains("Method")
{
// Exceptions : certains noms qui ressemblent à des propriétés mais sont des méthodes
let method_exceptions = ["DatabaseInfo", "ReadFrom", "WriteTo", "ToString"];
if !method_exceptions.contains(&name) {
return MemberType::PropertyGet;
}
}
// Par défaut : méthode
MemberType::Method
}
/// Estime le nombre de paramètres basé sur le nom et type
fn estimate_parameter_count(name: &str, member_type: &MemberType) -> Option<u32> {
match member_type {
MemberType::PropertyGet => Some(0), // Les getters n'ont pas de paramètres
MemberType::PropertyPut | MemberType::PropertyPutRef => Some(1), // Les setters ont 1 paramètre
MemberType::Method => {
// Estimation basée sur le nom de méthode
match name {
"IsOpen" | "Close" | "Create" | "Save" | "Clear" | "Refresh" => Some(0),
"Open" | "Delete" | "Add" | "Remove" => Some(1),
"Update" | "Copy" | "Move" => Some(2),
_ => None, // Paramètres inconnus
}
}
}
}
/// Devine le type de retour basé sur le nom et type
fn guess_return_type(name: &str, member_type: &MemberType) -> Option<String> {
match member_type {
MemberType::PropertyGet => {
if name.starts_with("Factory") {
Some("Object".to_string()) // Les Factory retournent des objets
} else if name.starts_with("Is") || name.ends_with("ed") {
Some("Boolean".to_string()) // Les propriétés booléennes
} else if name.contains("Count") || name.contains("Size") {
Some("Integer".to_string()) // Les propriétés numériques
} else if name == "Name" || name == "Description" || name == "Path" {
Some("String".to_string()) // Les propriétés texte
} else {
Some("Variant".to_string()) // Type générique
}
}
MemberType::PropertyPut | MemberType::PropertyPutRef => {
Some("void".to_string()) // Les setters ne retournent rien
}
MemberType::Method => {
match name {
"IsOpen" => Some("Boolean".to_string()),
"Open" | "Close" | "Create" | "Save" | "Delete" => Some("void".to_string()),
"DatabaseInfo" => Some("String".to_string()),
_ => Some("Variant".to_string()), // Type générique pour les méthodes
}
}
}
}
/// Filtre uniquement les méthodes
pub fn list_methods_only(&self) -> SageResult<Vec<MemberInfo>> {
let members = self.list_members()?;
Ok(members
.into_iter()
.filter(|m| matches!(m.member_type, MemberType::Method))
.collect())
}
/// Filtre uniquement les propriétés
pub fn list_properties(&self) -> SageResult<Vec<MemberInfo>> {
let members = self.list_members()?;
Ok(members
.into_iter()
.filter(|m| {
matches!(
m.member_type,
MemberType::PropertyGet | MemberType::PropertyPut | MemberType::PropertyPutRef
)
})
.collect())
}
/// Groupe les propriétés par nom (Get/Put/PutRef ensemble)
pub fn group_properties(&self) -> SageResult<HashMap<String, Vec<MemberInfo>>> {
let properties = self.list_properties()?;
let mut grouped = HashMap::new();
for prop in properties {
grouped
.entry(prop.name.clone())
.or_insert_with(Vec::new)
.push(prop);
}
Ok(grouped)
}
/// Convertit le VARTYPE en nom de type lisible
#[allow(dead_code)] // Sera utilisé dans les futures versions
fn get_type_name(vt: VARENUM) -> Option<String> {
let type_name = match vt {
VT_EMPTY => "void",
VT_NULL => "null",
VT_I2 => "short",
VT_I4 => "long",
VT_R4 => "float",
VT_R8 => "double",
VT_CY => "currency",
VT_DATE => "date",
VT_BSTR => "string",
VT_DISPATCH => "object",
VT_ERROR => "error",
VT_BOOL => "bool",
VT_VARIANT => "variant",
VT_UNKNOWN => "unknown",
VT_DECIMAL => "decimal",
VT_UI1 => "byte",
VT_UI2 => "ushort",
VT_UI4 => "ulong",
VT_I8 => "longlong",
VT_UI8 => "ulonglong",
VT_HRESULT => "hresult",
VT_PTR => "pointer",
VT_SAFEARRAY => "array",
_ => return None,
};
Some(type_name.to_string())
}
/// Crée une nouvelle instance ComInstance à partir d'un IDispatch existant
pub fn from_dispatch(dispatch: IDispatch) -> Self {
// IDispatch hérite d'IUnknown, donc on peut faire un cast sûr
let unknown = dispatch.cast::<IUnknown>().unwrap_or_else(|_| {
// Si le cast échoue pour une raison quelconque, utiliser transmute
// C'est sûr car IDispatch hérite d'IUnknown
unsafe { std::mem::transmute_copy::<IDispatch, IUnknown>(&dispatch) }
});
ComInstance {
unknown,
dispatch: Some(dispatch),
initialized_com: false, // N'a pas initialisé COM car l'objet existe déjà
_sta_marker: PhantomData,
}
}
/// Explore les propriétés d'un objet COM imbriqué - CORRIGÉ v0.1.3
pub fn explore_nested_object(dispatch: IDispatch) -> SageResult<()> {
let instance = Self::from_dispatch(dispatch);
println!("🔍 Exploration de l'objet imbriqué...");
// Essayer d'obtenir les informations de type
match instance.get_type_info() {
Ok(info) => println!("📋 {}", info),
Err(_) => println!("⚠️ Informations de type non disponibles pour l'objet imbriqué"),
}
// Lister les méthodes et propriétés disponibles
match instance.list_methods_only() {
Ok(methods) => {
if !methods.is_empty() {
println!("🔧 Méthodes disponibles ({}):", methods.len());
for method in methods.iter().take(10) {
println!(" - {}", method.name);
}
if methods.len() > 10 {
println!(" ... et {} autres", methods.len() - 10);
}
} else {
println!("🔧 Aucune méthode détectée");
}
}
Err(_) => println!("⚠️ Impossible de lister les méthodes de l'objet imbriqué"),
}
match instance.group_properties() {
Ok(properties) => {
if !properties.is_empty() {
println!("📋 Propriétés disponibles ({}):", properties.len());
for (name, _) in properties.iter().take(10) {
println!(" - {}", name);
}
if properties.len() > 10 {
println!(" ... et {} autres", properties.len() - 10);
}
} else {
println!("📋 Aucune propriété détectée");
}
}
Err(_) => println!("⚠️ Impossible de lister les propriétés de l'objet imbriqué"),
}
Ok(())
}
}
impl Drop for ComInstance {
fn drop(&mut self) {
// Libérer COM si on l'a initialisé
if self.initialized_com {
unsafe {
CoUninitialize();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_clsid_parsing() {
// Test avec et sans accolades
let result1 = ComInstance::parse_clsid("309DE0FB-9FB8-4F4E-8295-CC60C60DAA33");
let result2 = ComInstance::parse_clsid("{309DE0FB-9FB8-4F4E-8295-CC60C60DAA33}");
assert!(result1.is_ok());
assert!(result2.is_ok());
}
}