-
Notifications
You must be signed in to change notification settings - Fork 208
/
MapFeatureInfoTool.ts
326 lines (277 loc) · 12.2 KB
/
MapFeatureInfoTool.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module MapLayersFormats
*/
import {
BeButtonEvent,
EventHandled,
HitDetail,
IModelApp,
LocateFilterStatus,
LocateResponse,
MapFeatureInfo,
MapLayerInfoFromTileTree,
MapLayerScaleRangeVisibility,
MapTileTreeScaleRangeVisibility,
PrimitiveTool,
ToolAssistance,
ToolAssistanceImage,
ToolAssistanceInputMethod,
ToolAssistanceInstruction,
ToolAssistanceSection,
Viewport,
} from "@itwin/core-frontend";
import { BeEvent } from "@itwin/core-bentley";
import { ImageMapLayerSettings, MapImageryProps, MapImagerySettings, MapLayerProps } from "@itwin/core-common";
import { MapFeatureInfoDecorator } from "./MapFeatureInfoDecorator";
import { mapInfoIcon } from "../Icons/MapInfoIcon";
/**
* Data provided every time [[MapFeatureInfoTool]] retrieves feature information.
* @see [[MapFeatureInfoToolData]]
* @beta
*/
export interface MapFeatureInfoToolData {
hit: HitDetail;
mapInfo?: MapFeatureInfo;
}
class ActiveMapLayerState {
private _activeMapLayers: MapLayerInfoFromTileTree[]|undefined;
public get activeMapLayers() {return this._activeMapLayers;}
public set activeMapLayers(active: MapLayerInfoFromTileTree[]|undefined) {
this._activeMapLayers = active;
this.isVisible = true;
this.isInRange = true;
this.existsInDisplayStyle = true;
}
public isVisible: boolean = true;
public isInRange: boolean = true;
public existsInDisplayStyle: boolean = true;
public get hasMapLayers() { return (this.activeMapLayers && this.activeMapLayers.length > 0);}
public updateWithImagerySettings(imagery: MapImageryProps) {
const result = {exists: false, hidden: false};
this.existsInDisplayStyle = false;
this.isVisible = false;
if (this.hasMapLayers) {
const oldMls = this._activeMapLayers![0]; // consider only first layer for now
let newMls: MapLayerProps|undefined;
if (oldMls.isBaseLayer) {
if (typeof (imagery.backgroundBase) !== "number") {
newMls = imagery.backgroundBase;
}
} else if (oldMls.index?.isOverlay && imagery.overlayLayers && imagery.overlayLayers.length > oldMls.index.index) {
newMls = imagery.overlayLayers[oldMls.index.index];
} else if ((oldMls.index !== undefined) && imagery.backgroundLayers && imagery.backgroundLayers.length > oldMls.index.index) {
newMls = imagery.backgroundLayers[oldMls.index.index];
}
// We want to make sure that newMls and OldMls are the same (but ignoring the 'visible' flag).
// by using the serialized JSON object
let tmpNewMls = newMls;
if (newMls && newMls.visible !== oldMls.settings.visible) {
tmpNewMls = {...newMls, visible: oldMls.settings.visible};
}
const newJson = tmpNewMls ? JSON.stringify(tmpNewMls) : "";
const oldJson = JSON.stringify(oldMls.settings.toJSON());
if (newJson === oldJson ) {
// We consider newMls and OldMls to be the same mapLayer instance.
this.existsInDisplayStyle = true;
this.isVisible = newMls!.visible ? true : false;
}
}
return result;
}
public updateWithScaleRangeVisibility(layerIndexes: MapLayerScaleRangeVisibility[]) {
if (this.hasMapLayers) {
const currentMls = this.activeMapLayers![0]; // consider only first layer for now
for (const scaleRangeVisibility of layerIndexes) {
if (currentMls.index?.index === scaleRangeVisibility.index) {
this.isInRange = scaleRangeVisibility.visibility === MapTileTreeScaleRangeVisibility.Visible || scaleRangeVisibility.visibility === MapTileTreeScaleRangeVisibility.Partial;
}
}
}
}
}
/** Tools that allow extracting feature information from map-layers.
* Simulate feature highlight by drawing overlay decorations. It also
* fire an event that provide further feature information meant to be displayed in a UI / Widget.
* @see [[MapFeatureInfoToolData]]
* @beta
*/
export class MapFeatureInfoTool extends PrimitiveTool {
public readonly onInfoReady = new BeEvent<(data: MapFeatureInfoToolData) => void>();
public readonly onInfoCleared = new BeEvent();
public static override toolId = "MapFeatureInfoTool";
public static override iconSpec = mapInfoIcon.dataUri;
private _decorator: MapFeatureInfoDecorator = new MapFeatureInfoDecorator();
private _layerSettingsCache = new Map<string, MapLayerInfoFromTileTree[]>();
private _state: ActiveMapLayerState = new ActiveMapLayerState();
private readonly _detachListeners: VoidFunction[] = [];
private _detachOnMapImageryChanged: VoidFunction|undefined;
public override requireWriteableTarget(): boolean {
return false;
}
/** @internal */
protected setupAndPromptForNextAction(): void {
this.showPrompt();
}
private updateDecorator(vp: Viewport) {
if (this._state.existsInDisplayStyle) {
if (this._state.isInRange) {
this._decorator.hidden = !this._state.isVisible;
}
} else {
// Flush existing decorations until a new selection is made
this.onInfoCleared.raiseEvent();
this._decorator.clearData();
}
vp.invalidateDecorations();
}
public override async onPostInstall() {
await super.onPostInstall();
this.setupAndPromptForNextAction();
this.initLocateElements();
IModelApp.locateManager.options.allowDecorations = true;
this._layerSettingsCache.clear();
// Listen of display style configuration changes, that way we don't have to restart the tool to be up to date.
const vp = this.targetView;
if (vp) {
const mapImageryChangeHandler = (newImagery: Readonly<MapImagerySettings>) => {
if (this._state.hasMapLayers) {
this._state.updateWithImagerySettings(newImagery.toJSON());
this.updateDecorator(vp);
}
this._layerSettingsCache.clear();
};
this._detachListeners.push(vp.onChangeView.addListener((viewport, _previousViewState) => {
// When a saved view is loaded, 'onMapImageryChanged' events are no longer handled, we have to re-attach.
if (this._detachOnMapImageryChanged) {
this._detachOnMapImageryChanged();
}
this._detachOnMapImageryChanged = viewport.displayStyle.settings.onMapImageryChanged.addListener(mapImageryChangeHandler);
if (this._state.hasMapLayers) {
this._state.updateWithImagerySettings({
backgroundBase: viewport.displayStyle.backgroundMapBase.toJSON(),
backgroundLayers: viewport.displayStyle.getMapLayers(false).map((value) => value.toJSON()),
overlayLayers: viewport.displayStyle.getMapLayers(true).map((value) => value.toJSON()),
});
this.updateDecorator(vp);
}
this._layerSettingsCache.clear();
}));
this._detachOnMapImageryChanged = vp.displayStyle.settings.onMapImageryChanged.addListener(mapImageryChangeHandler);
// Every time a layer goes out of range it, its associated decoration should be hidden (and restore if enter again the range)
this._detachListeners.push(vp.onMapLayerScaleRangeVisibilityChanged.addListener(((layerIndexes: MapLayerScaleRangeVisibility[]) => {
if (this._state.hasMapLayers) {
this._state.updateWithScaleRangeVisibility(layerIndexes);
if (this._state.existsInDisplayStyle && this._state.isVisible) {
this._decorator.hidden = !this._state.isInRange;
vp.invalidateDecorations();
}
}
this._layerSettingsCache.clear();
})));
}
IModelApp.viewManager.addDecorator(this._decorator);
}
public override async onCleanup() {
this._detachListeners.forEach((f) => f());
this._detachListeners.length = 0;
if (this._detachOnMapImageryChanged) {
this._detachOnMapImageryChanged();
}
IModelApp.viewManager.dropDecorator(this._decorator);
}
/**
* Get map layer information from a hit.
* @param hit The hit to get info from.
* @returns Returns a list of [[MapLayerInfoFromTileTree]]s.
* @internal
*/
private getMapLayerInfoFromHit(hit: HitDetail) {
let mapLayerFromHit: MapLayerInfoFromTileTree[] = [];
const fromCache = this._layerSettingsCache.get(hit.sourceId);
if (fromCache) {
mapLayerFromHit = fromCache;
} else if (this.targetView) {
mapLayerFromHit = this.targetView?.mapLayerFromHit(hit).filter(((info) => info.settings instanceof ImageMapLayerSettings && info.provider?.supportsMapFeatureInfo));
this._layerSettingsCache.set(hit.sourceId, mapLayerFromHit);
}
return mapLayerFromHit;
}
public override async getToolTip(hit: HitDetail): Promise<HTMLElement | string> {
const infos = this.getMapLayerInfoFromHit(hit);
if (infos.length > 0) {
const names = infos.map((info) => info.settings.name);
return `Layer${names.length > 1 ? "s" : ""}: ${names.join(", ")}`;
}
return "";
}
public override async filterHit(hit: HitDetail, _out?: LocateResponse): Promise<LocateFilterStatus> {
return this.getMapLayerInfoFromHit(hit).length > 0 ? LocateFilterStatus.Accept : LocateFilterStatus.Reject;
}
public override async onDataButtonDown(
ev: BeButtonEvent,
): Promise<EventHandled> {
const hit = await IModelApp.locateManager.doLocate(
new LocateResponse(),
true,
ev.point,
ev.viewport,
ev.inputSource,
);
if (hit !== undefined) {
let mapInfo: MapFeatureInfo | undefined;
const mapLayersHit = this.getMapLayerInfoFromHit(hit);
if (mapLayersHit.length > 0) {
this._state.activeMapLayers = mapLayersHit;
IModelApp.toolAdmin.setCursor("wait");
try {
const aperture = (hit.viewport.pixelsFromInches(IModelApp.locateManager.apertureInches) / 2.0) + 1.5;
const pixelRadius = Math.floor(aperture + 0.5);
mapInfo = await hit.viewport.getMapFeatureInfo(hit, {tolerance: pixelRadius});
if (mapInfo) {
this._decorator.setData({ hit, mapInfo });
} else {
IModelApp.toolAdmin.setCursor(undefined);
}
} catch {
IModelApp.toolAdmin.setCursor(undefined);
}
}
this.onInfoReady.raiseEvent({ hit, mapInfo });
return EventHandled.Yes;
}
return EventHandled.No;
}
public override async onResetButtonUp(
_ev: BeButtonEvent,
): Promise<EventHandled> {
this._state.activeMapLayers = undefined;
/* Common reset behavior for primitive tools is calling onReinitialize to restart or exitTool to terminate. */
await this.onReinitialize();
return EventHandled.No;
}
public override async onRestartTool() {
const tool = new MapFeatureInfoTool();
if (!(await tool.run()))
return this.exitTool();
}
/** @internal */
protected showPrompt(): void {
const promptEnterPoint = IModelApp.localization.getLocalizedString("mapLayersFormats:tools.MapFeatureInfoTool.Prompts.EnterPoint");
const promptClickIdentify= IModelApp.localization.getLocalizedString("mapLayersFormats:tools.MapFeatureInfoTool.Prompts.clickToIdentify");
const promptClickClear = IModelApp.localization.getLocalizedString("mapLayersFormats:tools.MapFeatureInfoTool.Prompts.clickToClear");
// Mouse Instructions
const mouseInstructions: ToolAssistanceInstruction[] = [];
mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.LeftClick, promptClickIdentify, false, ToolAssistanceInputMethod.Mouse));
mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.RightClick, promptClickClear, false, ToolAssistanceInputMethod.Mouse));
const sections: ToolAssistanceSection[] = [];
sections.push(ToolAssistance.createSection(mouseInstructions, ToolAssistance.inputsLabel));
// Main Instruction
const mainInstruction = ToolAssistance.createInstruction(this.iconSpec, promptEnterPoint);
const instructions = ToolAssistance.createInstructions(mainInstruction, sections);
IModelApp.notifications.setToolAssistance(instructions);
}
}