-
Notifications
You must be signed in to change notification settings - Fork 216
/
Copy pathPresentationManagerDetail.ts
654 lines (589 loc) · 24.2 KB
/
PresentationManagerDetail.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import * as hash from "object-hash";
import * as path from "path";
import { IModelDb, IModelJsNative, IpcHost } from "@itwin/core-backend";
import { BeEvent, Logger } from "@itwin/core-bentley";
import { UnitSystemKey } from "@itwin/core-quantity";
import {
Content,
ContentDescriptorRequestOptions,
ContentFlags,
ContentRequestOptions,
ContentSourcesRequestOptions,
deepReplaceNullsToUndefined,
DefaultContentDisplayTypes,
Descriptor,
DescriptorOverrides,
DiagnosticsOptions,
DiagnosticsScopeLogs,
DisplayLabelRequestOptions,
DisplayLabelsRequestOptions,
DisplayValueGroup,
DistinctValuesRequestOptions,
FilterByInstancePathsHierarchyRequestOptions,
FilterByTextHierarchyRequestOptions,
FormatsMap,
HierarchyLevel,
HierarchyLevelDescriptorRequestOptions,
HierarchyRequestOptions,
InstanceKey,
Item,
ItemJSON,
Key,
KeySet,
LabelDefinition,
Node,
NodeKey,
NodePathElement,
NodePathFilteringData,
Paged,
PagedResponse,
PresentationIpcEvents,
Prioritized,
Ruleset,
RulesetVariable,
SelectClassInfo,
UpdateInfo,
WithCancelEvent,
} from "@itwin/presentation-common";
import { PresentationBackendLoggerCategory } from "./BackendLoggerCategory";
import {
createDefaultNativePlatform,
NativePlatformDefinition,
NativePlatformRequestTypes,
NativePlatformResponse,
NativePresentationDefaultUnitFormats,
NativePresentationKeySetJSON,
NativePresentationUnitSystem,
PresentationNativePlatformResponseError,
} from "./NativePlatform";
import { HierarchyCacheConfig, HierarchyCacheMode, PresentationManagerProps } from "./PresentationManager";
import { RulesetManager, RulesetManagerImpl } from "./RulesetManager";
import { BackendDiagnosticsAttribute, BackendDiagnosticsOptions, combineDiagnosticsOptions, getElementKey, reportDiagnostics } from "./Utils";
/** @internal */
export class PresentationManagerDetail implements Disposable {
private _disposed: boolean;
private _nativePlatform: NativePlatformDefinition | undefined;
private _onManagerUsed: (() => void) | undefined;
private _diagnosticsOptions: BackendDiagnosticsOptions | undefined;
public rulesets: RulesetManager;
public activeUnitSystem: UnitSystemKey | undefined;
constructor(params: PresentationManagerProps) {
this._disposed = false;
this._nativePlatform =
params.addon ??
createNativePlatform(
params.id ?? "",
params.workerThreadsCount ?? 2,
IpcHost.isValid ? ipcUpdatesHandler : noopUpdatesHandler,
params.caching,
params.defaultFormats,
params.useMmap,
);
setupRulesets(this._nativePlatform, params.supplementalRulesetDirectories ?? [], params.rulesetDirectories ?? []);
this.activeUnitSystem = params.defaultUnitSystem;
this._onManagerUsed = undefined;
this.rulesets = new RulesetManagerImpl(() => this.getNativePlatform());
this._diagnosticsOptions = params.diagnostics;
}
public [Symbol.dispose](): void {
if (this._disposed) {
return;
}
this.getNativePlatform()[Symbol.dispose]();
this._nativePlatform = undefined;
this._disposed = true;
}
public getNativePlatform(): NativePlatformDefinition {
if (this._disposed) {
throw new Error("Attempting to use Presentation manager after disposal");
}
return this._nativePlatform!;
}
public setOnManagerUsedHandler(handler: () => void) {
this._onManagerUsed = handler;
}
public async getNodes(
requestOptions: WithCancelEvent<Prioritized<Paged<HierarchyRequestOptions<IModelDb, NodeKey, RulesetVariable>>>> & BackendDiagnosticsAttribute,
): Promise<string> {
const { rulesetOrId, parentKey, ...strippedOptions } = requestOptions;
const params = {
requestId: parentKey ? NativePlatformRequestTypes.GetChildren : NativePlatformRequestTypes.GetRootNodes,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
nodeKey: parentKey,
};
return this.request(params);
}
public async getNodesCount(
requestOptions: WithCancelEvent<Prioritized<HierarchyRequestOptions<IModelDb, NodeKey, RulesetVariable>>> & BackendDiagnosticsAttribute,
): Promise<number> {
const { rulesetOrId, parentKey, ...strippedOptions } = requestOptions;
const params = {
requestId: parentKey ? NativePlatformRequestTypes.GetChildrenCount : NativePlatformRequestTypes.GetRootNodesCount,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
nodeKey: parentKey,
};
return JSON.parse(await this.request(params));
}
public async getNodesDescriptor(
requestOptions: WithCancelEvent<Prioritized<HierarchyLevelDescriptorRequestOptions<IModelDb, NodeKey, RulesetVariable>>> & BackendDiagnosticsAttribute,
): Promise<string> {
const { rulesetOrId, parentKey, ...strippedOptions } = requestOptions;
const params = {
requestId: NativePlatformRequestTypes.GetNodesDescriptor,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
nodeKey: parentKey,
};
return this.request(params);
}
public async getNodePaths(
requestOptions: WithCancelEvent<Prioritized<FilterByInstancePathsHierarchyRequestOptions<IModelDb, RulesetVariable>>> & BackendDiagnosticsAttribute,
): Promise<NodePathElement[]> {
const { rulesetOrId, instancePaths, ...strippedOptions } = requestOptions;
const params = {
requestId: NativePlatformRequestTypes.GetNodePaths,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
paths: instancePaths,
};
const paths: NodePathElement[] = deepReplaceNullsToUndefined(JSON.parse(await this.request(params)));
paths.forEach(fixNodePathElementFromAddon);
return paths;
}
public async getFilteredNodePaths(
requestOptions: WithCancelEvent<Prioritized<FilterByTextHierarchyRequestOptions<IModelDb, RulesetVariable>>> & BackendDiagnosticsAttribute,
): Promise<NodePathElement[]> {
const { rulesetOrId, ...strippedOptions } = requestOptions;
const params = {
requestId: NativePlatformRequestTypes.GetFilteredNodePaths,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
};
const paths: NodePathElement[] = deepReplaceNullsToUndefined(JSON.parse(await this.request(params)));
paths.forEach(fixNodePathElementFromAddon);
return paths;
}
public async getContentDescriptor(requestOptions: WithCancelEvent<Prioritized<ContentDescriptorRequestOptions<IModelDb, KeySet>>>): Promise<string> {
const { rulesetOrId, contentFlags, ...strippedOptions } = requestOptions;
const params = {
requestId: NativePlatformRequestTypes.GetContentDescriptor,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
contentFlags: contentFlags ?? ContentFlags.DescriptorOnly, // only set "descriptor only" flag if there are no flags provided
keys: getKeysForContentRequest(requestOptions.keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)),
};
return this.request(params);
}
public async getContentSources(
requestOptions: WithCancelEvent<Prioritized<ContentSourcesRequestOptions<IModelDb>>> & BackendDiagnosticsAttribute,
): Promise<SelectClassInfo[]> {
const params = {
requestId: NativePlatformRequestTypes.GetContentSources,
rulesetId: "ElementProperties",
...requestOptions,
};
const reviver = (key: string, value: any) => {
return key === "" ? SelectClassInfo.listFromCompressedJSON(value.sources, value.classesMap) : value;
};
return deepReplaceNullsToUndefined(JSON.parse(await this.request(params), reviver));
}
public async getContentSetSize(
requestOptions: WithCancelEvent<Prioritized<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>> &
BackendDiagnosticsAttribute,
): Promise<number> {
const { rulesetOrId, descriptor, ...strippedOptions } = requestOptions;
const params = {
requestId: NativePlatformRequestTypes.GetContentSetSize,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
keys: getKeysForContentRequest(requestOptions.keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)),
descriptorOverrides: createContentDescriptorOverrides(descriptor),
};
return JSON.parse(await this.request(params));
}
public async getContentSet(
requestOptions: WithCancelEvent<Prioritized<Paged<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>>> &
BackendDiagnosticsAttribute,
): Promise<Item[]> {
const { rulesetOrId, descriptor, ...strippedOptions } = requestOptions;
const params = {
requestId: NativePlatformRequestTypes.GetContentSet,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
keys: getKeysForContentRequest(requestOptions.keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)),
descriptorOverrides: createContentDescriptorOverrides(descriptor),
};
return JSON.parse(await this.request(params))
.map((json: ItemJSON) => Item.fromJSON(deepReplaceNullsToUndefined(json)))
.filter((item: Item | undefined): item is Item => !!item);
}
public async getContent(
requestOptions: WithCancelEvent<Prioritized<Paged<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>>> &
BackendDiagnosticsAttribute,
): Promise<Content | undefined> {
const { rulesetOrId, descriptor, ...strippedOptions } = requestOptions;
const params = {
requestId: NativePlatformRequestTypes.GetContent,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptions,
keys: getKeysForContentRequest(requestOptions.keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)),
descriptorOverrides: createContentDescriptorOverrides(descriptor),
};
return Content.fromJSON(deepReplaceNullsToUndefined(JSON.parse(await this.request(params))));
}
public async getPagedDistinctValues(
requestOptions: WithCancelEvent<Prioritized<DistinctValuesRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>> &
BackendDiagnosticsAttribute,
): Promise<PagedResponse<DisplayValueGroup>> {
const { rulesetOrId, ...strippedOptions } = requestOptions;
const { descriptor, keys, ...strippedOptionsNoDescriptorAndKeys } = strippedOptions;
const params = {
requestId: NativePlatformRequestTypes.GetPagedDistinctValues,
rulesetId: this.registerRuleset(rulesetOrId),
...strippedOptionsNoDescriptorAndKeys,
keys: getKeysForContentRequest(keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)),
descriptorOverrides: createContentDescriptorOverrides(descriptor),
};
return deepReplaceNullsToUndefined(JSON.parse(await this.request(params)));
}
public async getDisplayLabelDefinition(
requestOptions: WithCancelEvent<Prioritized<DisplayLabelRequestOptions<IModelDb, InstanceKey>>> & BackendDiagnosticsAttribute,
): Promise<LabelDefinition> {
const params = {
requestId: NativePlatformRequestTypes.GetDisplayLabel,
...requestOptions,
};
return deepReplaceNullsToUndefined(JSON.parse(await this.request(params)));
}
public async getDisplayLabelDefinitions(
requestOptions: WithCancelEvent<Prioritized<Paged<DisplayLabelsRequestOptions<IModelDb, InstanceKey>>>> & BackendDiagnosticsAttribute,
): Promise<LabelDefinition[]> {
const concreteKeys = requestOptions.keys
.map((k) => {
if (k.className === "BisCore:Element") {
return getElementKey(requestOptions.imodel, k.id);
}
return k;
})
.filter<InstanceKey>((k): k is InstanceKey => !!k);
const contentRequestOptions: ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet> = {
...requestOptions,
rulesetOrId: "RulesDrivenECPresentationManager_RulesetId_DisplayLabel",
descriptor: {
displayType: DefaultContentDisplayTypes.List,
contentFlags: ContentFlags.ShowLabels | ContentFlags.NoFields,
},
keys: new KeySet(concreteKeys),
};
const content = await this.getContent(contentRequestOptions);
return concreteKeys.map((key) => {
const item = content ? content.contentSet.find((it) => it.primaryKeys.length > 0 && InstanceKey.compare(it.primaryKeys[0], key) === 0) : undefined;
if (!item) {
return { displayValue: "", rawValue: "", typeName: "" };
}
return item.label;
});
}
/** Registers given ruleset and replaces the ruleset with its ID in the resulting object */
public registerRuleset(rulesetOrId: Ruleset | string): string {
if (typeof rulesetOrId === "object") {
const rulesetWithNativeId = { ...rulesetOrId, id: this.getRulesetId(rulesetOrId) };
return this.rulesets.add(rulesetWithNativeId).id;
}
return rulesetOrId;
}
/** @internal */
public getRulesetId(rulesetOrId: Ruleset | string): string {
return getRulesetIdObject(rulesetOrId).uniqueId;
}
public async request(params: RequestParams): Promise<string> {
this._onManagerUsed?.();
const { requestId, imodel, unitSystem, diagnostics: requestDiagnostics, cancelEvent, ...strippedParams } = params;
const imodelAddon = this.getNativePlatform().getImodelAddon(imodel);
const response = await withOptionalDiagnostics([this._diagnosticsOptions, requestDiagnostics], async (diagnosticsOptions) => {
const nativeRequestParams: any = {
requestId,
params: {
unitSystem: toOptionalNativeUnitSystem(unitSystem ?? this.activeUnitSystem),
...strippedParams,
...(diagnosticsOptions ? { diagnostics: diagnosticsOptions } : undefined),
},
};
return this.getNativePlatform().handleRequest(imodelAddon, JSON.stringify(nativeRequestParams), cancelEvent);
});
return response.result;
}
}
async function withOptionalDiagnostics(
diagnosticsOptions: Array<BackendDiagnosticsOptions | undefined>,
nativePlatformRequestHandler: (combinedDiagnosticsOptions: DiagnosticsOptions | undefined) => Promise<NativePlatformResponse<string>>,
): Promise<NativePlatformResponse<string>> {
const contexts = diagnosticsOptions.map((d) => d?.requestContextSupplier?.());
const combinedOptions = combineDiagnosticsOptions(...diagnosticsOptions);
let responseDiagnostics: DiagnosticsScopeLogs | undefined;
try {
const response = await nativePlatformRequestHandler(combinedOptions);
responseDiagnostics = response.diagnostics;
return response;
} catch (e) {
if (e instanceof PresentationNativePlatformResponseError) {
responseDiagnostics = e.diagnostics;
}
throw e;
} finally {
if (responseDiagnostics) {
const diagnostics = { logs: [responseDiagnostics] };
diagnosticsOptions.forEach((options, i) => {
options && reportDiagnostics(diagnostics, options, contexts[i]);
});
}
}
}
interface RequestParams {
diagnostics?: BackendDiagnosticsOptions;
requestId: string;
imodel: IModelDb;
unitSystem?: UnitSystemKey;
cancelEvent?: BeEvent<() => void>;
}
function setupRulesets(nativePlatform: NativePlatformDefinition, supplementalRulesetDirectories: string[], primaryRulesetDirectories: string[]): void {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const elementPropertiesRuleset: Ruleset = require("./primary-presentation-rules/ElementProperties.PresentationRuleSet.json");
nativePlatform.addRuleset(JSON.stringify(elementPropertiesRuleset));
// eslint-disable-next-line @typescript-eslint/no-require-imports
const bisSupplementalRuleset: Ruleset = require("./supplemental-presentation-rules/BisCore.PresentationRuleSet.json");
nativePlatform.registerSupplementalRuleset(JSON.stringify(bisSupplementalRuleset));
// eslint-disable-next-line @typescript-eslint/no-require-imports
const funcSupplementalRuleset: Ruleset = require("./supplemental-presentation-rules/Functional.PresentationRuleSet.json");
nativePlatform.registerSupplementalRuleset(JSON.stringify(funcSupplementalRuleset));
nativePlatform.setupSupplementalRulesetDirectories(collateAssetDirectories(supplementalRulesetDirectories));
nativePlatform.setupRulesetDirectories(collateAssetDirectories(primaryRulesetDirectories));
}
interface RulesetIdObject {
uniqueId: string;
parts: {
id: string;
hash?: string;
};
}
/** @internal */
export function getRulesetIdObject(rulesetOrId: Ruleset | string): RulesetIdObject {
if (typeof rulesetOrId === "object") {
if (IpcHost.isValid) {
// in case of native apps we don't want to enforce ruleset id uniqueness as ruleset variables
// are stored on a backend and creating new id will lose those variables
return {
uniqueId: rulesetOrId.id,
parts: { id: rulesetOrId.id },
};
}
const hashedId = hash.MD5(rulesetOrId);
return {
uniqueId: `${rulesetOrId.id}-${hashedId}`,
parts: {
id: rulesetOrId.id,
hash: hashedId,
},
};
}
return { uniqueId: rulesetOrId, parts: { id: rulesetOrId } };
}
/** @internal */
export function getKeysForContentRequest(
keys: Readonly<KeySet>,
classInstanceKeysProcessor?: (keys: Map<string, Set<string>>) => void,
): NativePresentationKeySetJSON {
const result: NativePresentationKeySetJSON = {
instanceKeys: [],
nodeKeys: [],
};
const classInstancesMap = new Map<string, Set<string>>();
keys.forEach((key) => {
if (Key.isNodeKey(key)) {
result.nodeKeys.push(key);
}
if (Key.isInstanceKey(key)) {
addInstanceKey(classInstancesMap, key);
}
});
if (classInstanceKeysProcessor) {
classInstanceKeysProcessor(classInstancesMap);
}
for (const entry of classInstancesMap) {
if (entry[1].size > 0) {
result.instanceKeys.push([entry["0"], [...entry[1]]]);
}
}
return result;
}
/** @internal */
export function bisElementInstanceKeysProcessor(imodel: IModelDb, classInstancesMap: Map<string, Set<string>>) {
const elementClassName = "BisCore:Element";
const elementIds = classInstancesMap.get(elementClassName);
if (elementIds) {
const deleteElementIds = new Array<string>();
elementIds.forEach((elementId) => {
const concreteKey = getElementKey(imodel, elementId);
if (concreteKey && concreteKey.className !== elementClassName) {
deleteElementIds.push(elementId);
addInstanceKey(classInstancesMap, { className: concreteKey.className, id: elementId });
}
});
for (const id of deleteElementIds) {
elementIds.delete(id);
}
}
}
function addInstanceKey(classInstancesMap: Map<string, Set<string>>, key: InstanceKey): void {
let set = classInstancesMap.get(key.className);
// istanbul ignore else
if (!set) {
set = new Set();
classInstancesMap.set(key.className, set);
}
set.add(key.id);
}
function createNativePlatform(
id: string,
workerThreadsCount: number,
updateCallback: (updateInfo: UpdateInfo | undefined) => void,
caching: PresentationManagerProps["caching"],
defaultFormats: FormatsMap | undefined,
useMmap: boolean | number | undefined,
): NativePlatformDefinition {
return new (createDefaultNativePlatform({
id,
taskAllocationsMap: { [Number.MAX_SAFE_INTEGER]: workerThreadsCount },
updateCallback,
cacheConfig: createCacheConfig(caching?.hierarchies),
contentCacheSize: caching?.content?.size,
workerConnectionCacheSize: caching?.workerConnectionCacheSize,
defaultFormats: toNativeUnitFormatsMap(defaultFormats),
useMmap,
}))();
function createCacheConfig(config?: HierarchyCacheConfig): IModelJsNative.ECPresentationHierarchyCacheConfig {
switch (config?.mode) {
case HierarchyCacheMode.Disk:
return { ...config, directory: normalizeDirectory(config.directory) };
case HierarchyCacheMode.Hybrid:
return {
...config,
disk: config.disk ? { ...config.disk, directory: normalizeDirectory(config.disk.directory) } : undefined,
};
case HierarchyCacheMode.Memory:
return config;
default:
return { mode: HierarchyCacheMode.Disk, directory: "" };
}
}
function normalizeDirectory(directory?: string): string {
return directory ? path.resolve(directory) : "";
}
function toNativeUnitFormatsMap(map: FormatsMap | undefined): NativePresentationDefaultUnitFormats | undefined {
if (!map) {
return undefined;
}
const nativeFormatsMap: NativePresentationDefaultUnitFormats = {};
Object.entries(map).forEach(([phenomenon, formats]) => {
nativeFormatsMap[phenomenon] = (Array.isArray(formats) ? formats : [formats]).map((unitSystemsFormat) => ({
unitSystems: unitSystemsFormat.unitSystems.map(toNativeUnitSystem),
format: unitSystemsFormat.format,
}));
});
return nativeFormatsMap;
}
}
function toOptionalNativeUnitSystem(unitSystem: UnitSystemKey | undefined): NativePresentationUnitSystem | undefined {
return unitSystem ? toNativeUnitSystem(unitSystem) : undefined;
}
function toNativeUnitSystem(unitSystem: UnitSystemKey): NativePresentationUnitSystem {
switch (unitSystem) {
case "imperial":
return NativePresentationUnitSystem.BritishImperial;
case "metric":
return NativePresentationUnitSystem.Metric;
case "usCustomary":
return NativePresentationUnitSystem.UsCustomary;
case "usSurvey":
return NativePresentationUnitSystem.UsSurvey;
}
}
function collateAssetDirectories(dirs: string[]): string[] {
return [...new Set(dirs)];
}
const createContentDescriptorOverrides = (descriptorOrOverrides: Descriptor | DescriptorOverrides): DescriptorOverrides => {
if (descriptorOrOverrides instanceof Descriptor) {
return descriptorOrOverrides.createDescriptorOverrides();
}
return descriptorOrOverrides;
};
function parseUpdateInfo(info: UpdateInfo | undefined) {
if (info === undefined) {
return undefined;
}
const parsedInfo: UpdateInfo = {};
for (const fileName in info) {
// istanbul ignore if
if (!info.hasOwnProperty(fileName)) {
continue;
}
const imodelDb = IModelDb.findByFilename(fileName);
if (!imodelDb) {
Logger.logError(PresentationBackendLoggerCategory.PresentationManager, `Update records IModelDb not found with path ${fileName}`);
continue;
}
parsedInfo[imodelDb.getRpcProps().key] = info[fileName];
}
return Object.keys(parsedInfo).length > 0 ? parsedInfo : undefined;
}
/** @internal */
export function ipcUpdatesHandler(info: UpdateInfo | undefined) {
const parsed = parseUpdateInfo(info);
if (parsed) {
IpcHost.send(PresentationIpcEvents.Update, parsed);
}
}
/** @internal */
// istanbul ignore next
export function noopUpdatesHandler(_info: UpdateInfo | undefined) {}
/** @internal */
export function parseHierarchyLevelFromString(serializedHierarchyLevel: string): HierarchyLevel {
const hl: HierarchyLevel = deepReplaceNullsToUndefined(JSON.parse(serializedHierarchyLevel));
hl.nodes.forEach(fixNodeFromAddon);
return hl;
}
function fixNodePathElementFromAddon(npe: NodePathElement & { filteringData?: NodePathFilteringData | AddonNodePathFilteringData }): NodePathElement {
fixNodeFromAddon(npe.node);
npe.children.forEach(fixNodePathElementFromAddon);
// istanbul ignore next
if (npe.filteringData && isAddonNodePathFilteringData(npe.filteringData)) {
npe.filteringData = {
matchesCount: npe.filteringData.occurances,
childMatchesCount: npe.filteringData.childrenOccurances,
};
}
return npe;
}
interface AddonNodePathFilteringData {
childrenOccurances: number;
occurances: number;
}
function isAddonNodePathFilteringData(filteringData: NodePathFilteringData | AddonNodePathFilteringData): filteringData is AddonNodePathFilteringData {
return "occurances" in filteringData;
}
function fixNodeFromAddon(node: Node & { labelDefinition?: LabelDefinition }): Node {
// FIXME: this is a temporary workaround until the addon starts serializing node labels
// under the "label" property
// istanbul ignore next
if (node.labelDefinition) {
node.label = node.labelDefinition;
delete node.labelDefinition;
}
return node;
}