-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAtributoService.cs
More file actions
639 lines (550 loc) · 26.8 KB
/
Copy pathAtributoService.cs
File metadata and controls
639 lines (550 loc) · 26.8 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Autodesk.Navisworks.Api;
using Autodesk.Navisworks.Api.ComApi;
using ComApi = Autodesk.Navisworks.Api.Interop.ComApi;
namespace AutisAnalytics.NavisworksAtributos
{
/// <summary>
/// Modelo de um atributo customizado que será persistido no Navisworks.
/// </summary>
public class AtributoCustom
{
public string Categoria { get; set; }
public string Nome { get; set; }
public string Valor { get; set; }
public string Tipo { get; set; } // "string" | "double" | "int" | "bool"
public AtributoCustom(string categoria, string nome, string valor, string tipo = "string")
{
Categoria = categoria;
Nome = nome;
Valor = valor;
Tipo = tipo;
}
}
/// <summary>
/// Lê e grava atributos customizados via COM API do Navisworks 2026.
///
/// ADAPTAÇÃO NW 2026:
/// - Namespace mudou para Autodesk.Navisworks.Api.Interop.ComApi
/// - InwOaPathArray removido → usar ToInwOaPath(ModelItem) por item
/// - SetCustomProperties removido → usar InwNodeAttributesColl via nós do path
/// - nwEUserDataType removido → valor é inferido pelo COM runtime
/// - InwOaCategoryVec/InwOaCategory removidos → usar InwOaPropertyAttribute
/// - ComApiBridge movido para Autodesk.Navisworks.Api.ComApi namespace
/// </summary>
public static class AtributoService
{
private const string CATEGORIA_PADRAO = AutisSchema.CategoriaPrincipal;
// ─────────────────────────────────────────────────────────────────────
// LEITURA — Managed API (sem alterações)
// ─────────────────────────────────────────────────────────────────────
public static List<AtributoCustom> LerPropriedades(ModelItem item)
{
var resultado = new List<AtributoCustom>();
if (item == null) return resultado;
foreach (var categoria in item.PropertyCategories)
foreach (var prop in categoria.Properties)
resultado.Add(new AtributoCustom(
categoria.DisplayName ?? categoria.Name,
prop.DisplayName ?? prop.Name,
FormatarValor(prop.Value),
ObterTipo(prop.Value)));
return resultado;
}
public static List<string> LerSetsSalvos(
ModelItem item,
IEnumerable<string> nomesSetsValidos = null,
string nomeCategoria = null)
{
var resultado = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (item == null)
return resultado.ToList();
var nomesValidos = new HashSet<string>(
(nomesSetsValidos ?? Enumerable.Empty<string>())
.Where(nome => !string.IsNullOrWhiteSpace(nome))
.Select(nome => nome.Trim()),
StringComparer.OrdinalIgnoreCase);
foreach (var categoria in item.PropertyCategories)
{
var nomeCat = categoria.DisplayName ?? categoria.Name ?? "";
if (!ObterCategoriasRelacionadas(nomeCategoria ?? CATEGORIA_PADRAO)
.Contains(nomeCat, StringComparer.OrdinalIgnoreCase))
continue;
foreach (var prop in categoria.Properties)
{
var nomeProp = (prop.DisplayName ?? prop.Name ?? "").Trim();
var valorProp = FormatarValor(prop.Value)?.Trim() ?? "";
if (EhPropriedadeDeSets(nomeProp))
{
foreach (var nomeSet in SepararListaSets(valorProp))
{
if (nomesValidos.Count == 0 || nomesValidos.Contains(nomeSet))
resultado.Add(nomeSet);
}
continue;
}
// Suporte para formato legado: um set por propriedade.
if (nomesValidos.Count > 0 &&
nomesValidos.Contains(nomeProp) &&
string.Equals(valorProp, nomeProp, StringComparison.OrdinalIgnoreCase))
{
resultado.Add(nomeProp);
}
}
}
return resultado
.OrderBy(nome => nome, StringComparer.OrdinalIgnoreCase)
.ToList();
}
// ─────────────────────────────────────────────────────────────────────
// ESCRITA — COM API adaptada para NW 2026
// ─────────────────────────────────────────────────────────────────────
/// <summary>
/// Grava atributos nos elementos selecionados usando a mesma abordagem do eT.ools:
/// state.BeginEdit → guiNode.SetUserDefined() → state.EndEdit
/// </summary>
public static (int sucesso, int erros, string mensagem) GravarAtributos(
ModelItemCollection itens,
List<AtributoCustom> atributos,
string nomeCategoria = null,
Dictionary<ModelItem, List<SetAssignment>> setsPorItem = null)
{
if (itens == null || itens.Count == 0) return (0, 0, "No elements selected.");
bool temAtributos = atributos != null && atributos.Count > 0;
bool temSets = setsPorItem != null && setsPorItem.Values.Any(sets => sets != null && sets.Count > 0);
if (!temAtributos && !temSets) return (0, 0, "No attributes or sets to write.");
atributos = atributos ?? new List<AtributoCustom>();
var categoria = string.IsNullOrWhiteSpace(nomeCategoria)
? CATEGORIA_PADRAO
: nomeCategoria.Trim();
var internalName = categoria.Replace(" ", "_") + "_Internal";
ComApi.InwOpState10 oState = null;
bool editStarted = false;
try
{
oState = (ComApi.InwOpState10)ComBridgeHelper.ObterEstado();
oState.BeginEdit("autis_gravar");
editStarted = true;
int sucesso = 0, erros = 0;
string ultimoErro = null;
foreach (ModelItem item in itens)
{
try
{
// Converter para seleção/path (mesmo padrão do eT.ools)
var itemColl = new ModelItemCollection();
itemColl.Add(item);
var sel = ComApiBridge.ToInwOpSelection(itemColl);
var paths = sel.Paths();
var path = (ComApi.InwOaPath3)(dynamic)paths.Last();
// Obter GUI property node
var guiNode = (ComApi.InwGUIPropertyNode2)oState.GetGUIPropertyNode(path, true);
// Remover a categoria atual e categorias legadas antes de recriar.
RemoverCategoriasRelacionadas(guiNode, categoria);
// Criar InwOaPropertyVec com as propriedades
var propVec = (ComApi.InwOaPropertyVec)(dynamic)oState.ObjectFactory(
ComApi.nwEObjectType.eObjectType_nwOaPropertyVec);
var nomesInternosUsados = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
int propriedadesAdicionadas = 0;
foreach (var atr in atributos)
{
if (string.IsNullOrWhiteSpace(atr?.Nome)) continue;
AdicionarPropriedade(oState, propVec, atr.Nome, ConverterValor(atr), nomesInternosUsados);
propriedadesAdicionadas++;
}
if (setsPorItem != null &&
setsPorItem.TryGetValue(item, out var setsDoItem) &&
setsDoItem != null)
{
var nomesSets = setsDoItem
.Where(setInfo => !string.IsNullOrWhiteSpace(setInfo?.Nome))
.Select(setInfo => setInfo.Nome.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(nome => nome, StringComparer.OrdinalIgnoreCase)
.ToList();
if (nomesSets.Count > 0)
{
AdicionarPropriedade(
oState,
propVec,
AutisSchema.PropriedadeSets,
string.Join(" | ", nomesSets),
nomesInternosUsados);
propriedadesAdicionadas++;
}
}
if (propriedadesAdicionadas == 0)
continue;
// Gravar! (mesma chamada do eT.ools)
guiNode.SetUserDefined(0, categoria, internalName, propVec);
sucesso++;
}
catch (Exception ex)
{
erros++;
ultimoErro = ex.Message;
System.Diagnostics.Debug.WriteLine($"[Autis] Erro no item: {ex.Message}\n{ex.StackTrace}");
}
}
var msg = $"Saved: {sucesso} element(s). Errors: {erros}.";
if (erros > 0 && ultimoErro != null)
msg += $"\n\nLast error: {ultimoErro}";
return (sucesso, erros, msg);
}
catch (Exception ex)
{
return (0, itens.Count, $"Error accessing COM API: {ex.Message}");
}
finally
{
if (editStarted)
{
try { oState.EndEdit(); }
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Autis] Erro ao finalizar edicao COM: {ex.Message}");
}
}
}
}
public static (int sucesso, int erros, string mensagem) ExcluirAtributos(
ModelItemCollection itens,
string nomeCategoria = null)
{
if (itens == null || itens.Count == 0) return (0, 0, "No elements selected.");
var categoria = string.IsNullOrWhiteSpace(nomeCategoria)
? CATEGORIA_PADRAO
: nomeCategoria.Trim();
ComApi.InwOpState10 oState = null;
bool editStarted = false;
try
{
oState = (ComApi.InwOpState10)ComBridgeHelper.ObterEstado();
oState.BeginEdit("autis_excluir");
editStarted = true;
int removidos = 0, naoEncontrados = 0, erros = 0;
string ultimoErro = null;
foreach (ModelItem item in itens)
{
try
{
var itemColl = new ModelItemCollection();
itemColl.Add(item);
var sel = ComApiBridge.ToInwOpSelection(itemColl);
var paths = sel.Paths();
var path = (ComApi.InwOaPath3)(dynamic)paths.Last();
var guiNode = (ComApi.InwGUIPropertyNode2)oState.GetGUIPropertyNode(path, true);
if (RemoverCategoriasRelacionadas(guiNode, categoria))
removidos++;
else
naoEncontrados++;
}
catch (Exception ex)
{
erros++;
ultimoErro = ex.Message;
System.Diagnostics.Debug.WriteLine($"[Autis] Erro ao excluir no item: {ex.Message}\n{ex.StackTrace}");
}
}
var msg = $"Removed: {removidos} element(s). Not found: {naoEncontrados}. Errors: {erros}.";
if (erros > 0 && ultimoErro != null)
msg += $"\n\nLast error: {ultimoErro}";
return (removidos, erros, msg);
}
catch (Exception ex)
{
return (0, itens.Count, $"Error accessing COM API: {ex.Message}");
}
finally
{
if (editStarted)
{
try { oState.EndEdit(); }
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Autis] Erro ao finalizar exclusao COM: {ex.Message}");
}
}
}
}
private static void AdicionarPropriedade(ComApi.InwOpState10 oState,
ComApi.InwOaPropertyVec propVec, string nome, object valor,
HashSet<string> nomesInternosUsados)
{
var prop = (ComApi.InwOaProperty)(dynamic)oState.ObjectFactory(
ComApi.nwEObjectType.eObjectType_nwOaProperty);
prop.name = CriarNomeInternoPropriedade(nome, nomesInternosUsados);
prop.UserName = nome;
prop.value = valor ?? "";
propVec.Properties().Add(prop);
}
private static string CriarNomeInternoPropriedade(string nome,
HashSet<string> nomesInternosUsados)
{
if (nomesInternosUsados == null)
nomesInternosUsados = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrWhiteSpace(nome))
nome = "prop";
var baseName = new string(nome
.Select(c => char.IsLetterOrDigit(c) ? c : '_')
.ToArray())
.Trim('_');
if (string.IsNullOrWhiteSpace(baseName))
baseName = "prop";
string candidate = baseName + "_prop";
int suffix = 2;
while (!nomesInternosUsados.Add(candidate))
candidate = $"{baseName}_{suffix++}_prop";
return candidate;
}
private static bool RemoverCategoriasRelacionadas(
ComApi.InwGUIPropertyNode2 guiNode,
string nomeCategoriaPrincipal)
{
bool removeuAlguma = false;
foreach (var nomeCategoria in ObterCategoriasRelacionadas(nomeCategoriaPrincipal))
{
if (RemoverCategoriaExistente(guiNode, nomeCategoria))
removeuAlguma = true;
}
return removeuAlguma;
}
private static IEnumerable<string> ObterCategoriasRelacionadas(string nomeCategoriaPrincipal)
{
var nomes = new List<string>();
if (!string.IsNullOrWhiteSpace(nomeCategoriaPrincipal))
nomes.Add(nomeCategoriaPrincipal.Trim());
nomes.AddRange(AutisSchema.CategoriasLegadas);
return nomes
.Where(nome => !string.IsNullOrWhiteSpace(nome))
.Distinct(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Remove categoria user-defined existente pelo DisplayName (evita duplicação).
/// Mesmo padrão do eT.ools DeleteEToolsCategory.
/// </summary>
private static bool RemoverCategoriaExistente(ComApi.InwGUIPropertyNode2 guiNode, string nomeCategoria)
{
int idx = 1;
foreach (ComApi.InwGUIAttribute2 attr in guiNode.GUIAttributes())
{
try
{
if (attr.UserDefined && attr.ClassUserName == nomeCategoria)
{
guiNode.RemoveUserDefined(idx);
return true; // Removeu — sai (só pode ter 1 com esse nome)
}
if (attr.UserDefined) idx++;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(
$"[Autis] Erro ao remover categoria '{nomeCategoria}': {ex.Message}");
}
}
return false;
}
/// <summary>
/// Converte o valor do atributo para o tipo COM adequado.
/// </summary>
private static object ConverterValor(AtributoCustom atr)
{
switch (atr.Tipo?.ToLower())
{
case "double":
case "float":
if (double.TryParse(atr.Valor?.Replace(",", "."),
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double dv))
return dv;
return atr.Valor ?? "";
case "int":
if (int.TryParse(atr.Valor, out int iv))
return iv;
return atr.Valor ?? "";
case "bool":
bool bv;
if (!bool.TryParse(atr.Valor, out bv))
bv = atr.Valor?.ToLower() == "yes" || atr.Valor?.ToLower() == "true";
return bv;
default:
return atr.Valor ?? "";
}
}
// ─────────────────────────────────────────────────────────────────────
// Helpers de formatação (leitura)
// ─────────────────────────────────────────────────────────────────────
private static string FormatarValor(VariantData valor)
{
if (valor == null) return "";
switch (valor.DataType)
{
case VariantDataType.Double: return valor.ToDouble().ToString("G");
case VariantDataType.Int32: return valor.ToInt32().ToString();
case VariantDataType.Boolean: return valor.ToBoolean() ? "True" : "False";
case VariantDataType.DisplayString: return valor.ToDisplayString();
case VariantDataType.IdentifierString: return valor.ToIdentifierString();
default: return valor.ToString();
}
}
private static string ObterTipo(VariantData valor)
{
if (valor == null) return "string";
switch (valor.DataType)
{
case VariantDataType.Double: return "double";
case VariantDataType.Int32: return "int";
case VariantDataType.Boolean: return "bool";
default: return "string";
}
}
private static IEnumerable<string> SepararListaSets(string texto)
{
return (texto ?? "")
.Split(new[] { '|', ';', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(parte => parte.Trim())
.Where(parte => !string.IsNullOrWhiteSpace(parte));
}
private static bool EhPropriedadeDeSets(string nomePropriedade)
{
if (string.IsNullOrWhiteSpace(nomePropriedade))
return false;
if (string.Equals(nomePropriedade, AutisSchema.PropriedadeSets, StringComparison.OrdinalIgnoreCase))
return true;
return AutisSchema.PropriedadesSetsLegadas
.Any(nome => string.Equals(nome, nomePropriedade, StringComparison.OrdinalIgnoreCase));
}
}
// ─────────────────────────────────────────────────────────────────────────
/// <summary>
/// Descobre e invoca o ComApiBridge em runtime, sem depender do namespace
/// exato da DLL — que mudou do NW 2025 para o NW 2026.
///
/// Ordem de tentativa:
/// 1. Autodesk.Navisworks.Api.ComApi.ComApiBridge (NW 2026 — namespace real)
/// 2. Autodesk.Navisworks.ComApi.ComApiBridge (NW 2026 — alternativo)
///
/// Se nenhum for encontrado, lança InvalidOperationException descritiva.
/// </summary>
// ─────────────────────────────────────────────────────────────────────────
internal static class ComBridgeHelper
{
// Candidatos de namespace, por ordem de prioridade (NW 2026 primeiro)
private static readonly string[] BRIDGE_CANDIDATES = new[]
{
"Autodesk.Navisworks.Api.ComApi.ComApiBridge", // NW 2026 (namespace real)
"Autodesk.Navisworks.ComApi.ComApiBridge", // NW 2026 (alternativo)
};
private static Type _bridgeType; // cacheado após primeira descoberta
private static object _lockObj = new object();
// ── Descoberta do tipo ────────────────────────────────────────────────
private static Type ObterTipoBridge()
{
if (_bridgeType != null) return _bridgeType;
lock (_lockObj)
{
if (_bridgeType != null) return _bridgeType;
// Varre todos os assemblies já carregados no AppDomain
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var candidato in BRIDGE_CANDIDATES)
{
try
{
var tipo = asm.GetType(candidato);
if (tipo != null)
{
_bridgeType = tipo;
System.Diagnostics.Debug.WriteLine(
$"[Autis] ComApiBridge encontrado: {candidato} em {asm.GetName().Name}");
return _bridgeType;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(
$"[Autis] Falha ao inspecionar assembly '{asm.GetName().Name}' para '{candidato}': {ex.Message}");
}
}
}
// Não achou nos assemblies carregados — tenta forçar o carregamento
_bridgeType = TentarCarregarDllComApi();
if (_bridgeType == null)
throw new InvalidOperationException(
"ComApiBridge not found in any loaded assembly.\n\n" +
"Check:\n" +
" 1. Autodesk.Navisworks.ComApi.dll is referenced in the .csproj\n" +
" 2. The NavisworksDir path points to the correct NW 2026 installation\n" +
$" Candidates tried:\n - {string.Join("\n - ", BRIDGE_CANDIDATES)}");
return _bridgeType;
}
}
private static Type TentarCarregarDllComApi()
{
var dllsNome = new[] { "Autodesk.Navisworks.ComApi", "Autodesk.Navisworks.Api.ComApi" };
foreach (var nome in dllsNome)
{
try
{
var asm = Assembly.Load(nome);
foreach (var candidato in BRIDGE_CANDIDATES)
{
var tipo = asm?.GetType(candidato);
if (tipo != null) return tipo;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(
$"[Autis] Falha ao carregar assembly '{nome}': {ex.Message}");
}
}
return null;
}
// ── API pública ───────────────────────────────────────────────────────
/// <summary>
/// Equivalente a: ComApiBridge.State
/// Retorna o InwOpState do documento ativo.
/// </summary>
public static ComApi.InwOpState ObterEstado()
{
var bridge = ObterTipoBridge();
var prop = bridge.GetProperty("State",
BindingFlags.Public | BindingFlags.Static);
if (prop == null)
throw new InvalidOperationException(
"Property 'State' not found in ComApiBridge.");
var state = prop.GetValue(null) as ComApi.InwOpState;
if (state == null)
throw new InvalidOperationException(
"ComApiBridge.State retornou null — nenhum documento ativo?");
return state;
}
/// <summary>
/// NW 2026: ComApiBridge.ToInwOaPath(ModelItem) — converte um ModelItem para InwOaPath.
/// (ToInwOaPathArray foi removido; agora é um item por vez)
/// </summary>
public static ComApi.InwOaPath ObterPath(ModelItem item)
{
var bridge = ObterTipoBridge();
MethodInfo metodo = bridge.GetMethod("ToInwOaPath",
BindingFlags.Public | BindingFlags.Static,
null,
new[] { typeof(ModelItem) },
null);
if (metodo == null)
throw new InvalidOperationException(
"Method 'ToInwOaPath(ModelItem)' not found in ComApiBridge.\n" +
"Check that Autodesk.Navisworks.ComApi.dll is compatible with NW 2026.");
var path = metodo.Invoke(null, new object[] { item }) as ComApi.InwOaPath;
if (path == null)
throw new InvalidOperationException(
"ToInwOaPath retornou null para o item fornecido.");
return path;
}
}
}