-
Notifications
You must be signed in to change notification settings - Fork 212
/
ToolAdmin.ts
1998 lines (1649 loc) · 75.2 KB
/
ToolAdmin.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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Tools
*/
import { AbandonedError, assert, BeEvent, BeTimePoint, IModelStatus, Logger } from "@itwin/core-bentley";
import { Matrix3d, Point2d, Point3d, Transform, Vector3d, XAndY } from "@itwin/core-geometry";
import { Easing, GeometryStreamProps, NpcCenter } from "@itwin/core-common";
import { DialogItemValue, DialogPropertyItem, DialogPropertySyncItem } from "@itwin/appui-abstract";
import { AccuSnap, TentativeOrAccuSnap } from "../AccuSnap";
import { LocateOptions } from "../ElementLocateManager";
import { FrontendLoggerCategory } from "../common/FrontendLoggerCategory";
import { HitDetail } from "../HitDetail";
import { IModelApp } from "../IModelApp";
import { linePlaneIntersect } from "../LinePlaneIntersect";
import { MessageBoxIconType, MessageBoxType } from "../NotificationManager";
import { CanvasDecoration } from "../render/CanvasDecoration";
import { IconSprites } from "../Sprites";
import { OnViewExtentsError, ViewChangeOptions } from "../ViewAnimation";
import { DecorateContext, DynamicsContext } from "../ViewContext";
import { ScreenViewport, Viewport } from "../Viewport";
import { ViewStatus } from "../ViewStatus";
import { PrimitiveTool } from "./PrimitiveTool";
import {
BeButton, BeButtonEvent, BeButtonState, BeModifierKeys, BeTouchEvent, BeWheelEvent, CoordinateLockOverrides, CoordSource, EventHandled,
InputCollector, InputSource, InteractiveTool, Tool,
} from "./Tool";
import { ToolSettings } from "./ToolSettings";
import { ViewTool } from "./ViewTool";
/**
* @public
* @extensions
*/
export enum StartOrResume { Start = 1, Resume = 2 }
/**
* @public
* @extensions
*/
export enum ManipulatorToolEvent { Start = 1, Stop = 2, Suspend = 3, Unsuspend = 4 }
const enum MouseButton { Left = 0, Middle = 1, Right = 2 } // eslint-disable-line no-restricted-syntax
/** Maintains the state of tool settings properties for the current session.
* @see [[ToolAdmin.toolSettingsState]] to access the state for the current session.
* @public
*/
export class ToolSettingsState {
/** Retrieve saved tool settings DialogItemValue by property name. */
public getInitialToolSettingValue(toolId: string, propertyName: string): DialogItemValue | undefined {
const key = `${toolId}:${propertyName}`;
const savedValue = window.sessionStorage.getItem(key);
if (null !== savedValue) {
return JSON.parse(savedValue) as DialogItemValue;
}
return undefined;
}
/** Retrieve an array of DialogPropertyItem with the values latest values that were used in the session. */
public getInitialToolSettingValues(toolId: string, propertyNames: string[]): DialogPropertyItem[] | undefined {
const initializedProperties: DialogPropertyItem[] = [];
let propertyValue: DialogItemValue | undefined;
propertyNames.forEach((propertyName: string) => {
propertyValue = this.getInitialToolSettingValue(toolId, propertyName);
if (propertyValue)
initializedProperties.push({ value: propertyValue, propertyName });
});
return initializedProperties.length ? initializedProperties : undefined;
}
/** Save single tool settings value to session storage. */
public saveToolSettingProperty(toolId: string, item: DialogPropertyItem): void {
const key = `${toolId}:${item.propertyName}`;
const objectAsString = JSON.stringify(item.value);
window.sessionStorage.setItem(key, objectAsString);
}
/** Save an array of tool settings values to session storage */
public saveToolSettingProperties(toolId: string, tsProps: DialogPropertyItem[]): void {
tsProps.forEach((item: DialogPropertyItem) => this.saveToolSettingProperty(toolId, item));
}
}
/** @internal */
export class ToolState {
public coordLockOvr = CoordinateLockOverrides.None;
public locateCircleOn = false;
public setFrom(other: ToolState) {
this.coordLockOvr = other.coordLockOvr;
this.locateCircleOn = other.locateCircleOn;
}
public clone(): ToolState {
const val = new ToolState();
val.setFrom(this);
return val;
}
}
/** @internal */
export class SuspendedToolState {
private readonly _toolState: ToolState;
private readonly _accuSnapState: AccuSnap.ToolState;
private readonly _locateOptions: LocateOptions;
private readonly _viewCursor?: string;
private _inDynamics: boolean;
private _shuttingDown = false;
constructor() {
const { toolAdmin, viewManager, accuSnap, locateManager } = IModelApp;
toolAdmin.setIncompatibleViewportCursor(true); // Don't save this
this._toolState = toolAdmin.toolState.clone();
this._accuSnapState = accuSnap.toolState.clone();
this._locateOptions = locateManager.options.clone();
this._viewCursor = viewManager.cursor;
this._inDynamics = viewManager.inDynamicsMode;
if (this._inDynamics)
viewManager.endDynamicsMode();
}
public stop() {
if (this._shuttingDown)
return;
const { toolAdmin, viewManager, accuSnap, locateManager } = IModelApp;
toolAdmin.setIncompatibleViewportCursor(true); // Don't restore this
toolAdmin.toolState.setFrom(this._toolState);
accuSnap.toolState.setFrom(this._accuSnapState);
locateManager.options.setFrom(this._locateOptions);
viewManager.setViewCursor(this._viewCursor);
if (this._inDynamics)
viewManager.beginDynamicsMode();
else
viewManager.endDynamicsMode();
}
}
/** @internal */
export class CurrentInputState {
private readonly _rawPoint: Point3d = new Point3d();
private readonly _point: Point3d = new Point3d();
private readonly _viewPoint: Point3d = new Point3d();
public qualifiers = BeModifierKeys.None;
public viewport?: ScreenViewport;
public button: BeButtonState[] = [new BeButtonState(), new BeButtonState(), new BeButtonState()];
public lastButton: BeButton = BeButton.Data;
public inputSource: InputSource = InputSource.Unknown;
public lastMotion = new Point2d();
public lastWheelEvent?: BeWheelEvent;
public lastTouchStart?: BeTouchEvent;
public touchTapTimer?: number;
public touchTapCount?: number;
public get rawPoint() { return this._rawPoint; }
public set rawPoint(pt: Point3d) { this._rawPoint.setFrom(pt); }
public get point() { return this._point; }
public set point(pt: Point3d) { this._point.setFrom(pt); }
public get viewPoint() { return this._viewPoint; }
public set viewPoint(pt: Point3d) { this._viewPoint.setFrom(pt); }
public get isShiftDown() { return 0 !== (this.qualifiers & BeModifierKeys.Shift); }
public get isControlDown() { return 0 !== (this.qualifiers & BeModifierKeys.Control); }
public get isAltDown() { return 0 !== (this.qualifiers & BeModifierKeys.Alt); }
public isDragging(button: BeButton) { return this.button[button].isDragging; }
public onStartDrag(button: BeButton) { this.button[button].isDragging = true; }
public onInstallTool() {
this.clearKeyQualifiers();
this.lastWheelEvent = undefined;
this.lastTouchStart = this.touchTapTimer = this.touchTapCount = undefined;
}
public clearKeyQualifiers() { this.qualifiers = BeModifierKeys.None; }
public clearViewport(vp: Viewport) {
if (vp === this.viewport)
this.viewport = undefined;
}
private isAnyDragging() { return this.button.some((button) => button.isDragging); }
private setKeyQualifier(qual: BeModifierKeys, down: boolean) {
this.qualifiers = down ? (this.qualifiers | qual) : (this.qualifiers & (~qual));
}
public setKeyQualifiers(ev: MouseEvent | KeyboardEvent | TouchEvent): void {
this.setKeyQualifier(BeModifierKeys.Shift, ev.shiftKey);
this.setKeyQualifier(BeModifierKeys.Control, ev.ctrlKey);
this.setKeyQualifier(BeModifierKeys.Alt, ev.altKey);
}
public onMotion(pt2d: XAndY) {
this.lastMotion.x = pt2d.x;
this.lastMotion.y = pt2d.y;
}
public changeButtonToDownPoint(ev: BeButtonEvent) {
ev.point = this.button[ev.button].downUorPt;
ev.rawPoint = this.button[ev.button].downRawPt;
if (ev.viewport)
ev.viewPoint = ev.viewport.worldToView(ev.rawPoint);
}
public updateDownPoint(ev: BeButtonEvent) { this.button[ev.button].downUorPt = ev.point; }
public onButtonDown(button: BeButton) {
const viewPt = this.viewport!.worldToView(this.button[button].downRawPt);
const center = this.viewport!.npcToView(NpcCenter);
viewPt.z = center.z;
const now = Date.now();
const isDoubleClick = ((now - this.button[button].downTime) < ToolSettings.doubleClickTimeout.milliseconds) && (viewPt.distance(this.viewPoint) < this.viewport!.pixelsFromInches(ToolSettings.doubleClickToleranceInches));
this.button[button].init(this.point, this.rawPoint, now, true, isDoubleClick, false, this.inputSource);
this.lastButton = button;
}
public onButtonUp(button: BeButton) {
this.button[button].isDown = false;
this.button[button].isDragging = false;
this.lastButton = button;
}
public toEvent(ev: BeButtonEvent, useSnap: boolean) {
let coordsFrom = CoordSource.User;
const point = this.point.clone();
let viewport = this.viewport;
if (useSnap) {
const snap = TentativeOrAccuSnap.getCurrentSnap(false);
if (snap) {
coordsFrom = snap.isHot ? CoordSource.ElemSnap : CoordSource.User;
point.setFrom(snap.isPointAdjusted ? snap.adjustedPoint : snap.getPoint()); // NOTE: adjustedPoint can be set by adjustSnapPoint even when not hot...
viewport = snap.viewport;
} else if (IModelApp.tentativePoint.isActive) {
coordsFrom = CoordSource.TentativePoint;
point.setFrom(IModelApp.tentativePoint.getPoint());
viewport = IModelApp.tentativePoint.viewport;
}
}
const buttonState = this.button[this.lastButton];
ev.init({
point, rawPoint: this.rawPoint, viewPoint: this.viewPoint, viewport, coordsFrom,
keyModifiers: this.qualifiers, button: this.lastButton, isDown: buttonState.isDown,
isDoubleClick: buttonState.isDoubleClick, isDragging: buttonState.isDragging,
inputSource: this.inputSource,
});
}
public adjustLastDataPoint(ev: BeButtonEvent) {
const state = this.button[BeButton.Data];
state.downUorPt = ev.point;
state.downRawPt = ev.point;
this.viewport = ev.viewport;
}
public toEventFromLastDataPoint(ev: BeButtonEvent) {
const state = this.button[BeButton.Data];
const point = state.downUorPt;
const rawPoint = state.downRawPt;
const viewPoint = this.viewport ? this.viewport.worldToView(rawPoint) : Point3d.create(); // BeButtonEvent is invalid when viewport is undefined
ev.init({
point, rawPoint, viewPoint, viewport: this.viewport!, coordsFrom: CoordSource.User,
keyModifiers: this.qualifiers, button: BeButton.Data, isDown: state.isDown,
isDoubleClick: state.isDoubleClick, isDragging: state.isDragging, inputSource: state.inputSource,
});
}
public fromPoint(vp: ScreenViewport, pt: XAndY, source: InputSource) {
this.viewport = vp;
this._viewPoint.x = pt.x;
this._viewPoint.y = pt.y;
this._viewPoint.z = vp.npcToView(NpcCenter).z;
vp.viewToWorld(this._viewPoint, this._rawPoint);
this.point = this._rawPoint;
this.inputSource = source;
}
public fromButton(vp: ScreenViewport, pt: XAndY, source: InputSource, applyLocks: boolean) {
this.fromPoint(vp, pt, source);
// NOTE: Using the hit point on the element is preferable to ignoring a snap that is not "hot" completely
if (TentativeOrAccuSnap.getCurrentSnap(false)) {
if (applyLocks)
IModelApp.toolAdmin.adjustSnapPoint();
return;
}
IModelApp.toolAdmin.adjustPoint(this._point, vp, true, applyLocks);
}
public isStartDrag(button: BeButton): boolean {
// First make sure we aren't already dragging any button
if (this.isAnyDragging())
return false;
const state = this.button[button];
if (!state.isDown)
return false;
if ((Date.now() - state.downTime) <= ToolSettings.startDragDelay.milliseconds)
return false;
const viewPt = this.viewport!.worldToView(state.downRawPt);
const deltaX = Math.abs(this._viewPoint.x - viewPt.x);
const deltaY = Math.abs(this._viewPoint.y - viewPt.y);
return ((deltaX + deltaY) > this.viewport!.pixelsFromInches(ToolSettings.startDragDistanceInches));
}
}
/** A ToolEvent combines an HTML Event and a Viewport. It is stored in a queue for processing by the ToolAdmin.eventLoop. */
interface ToolEvent {
ev: Event;
vp?: ScreenViewport; // Viewport is optional - keyboard events aren't associated with a Viewport.
}
/** Controls the operation of [[Tool]]s, administering the current [[ViewTool]], [[PrimitiveTool]], and [[IdleTool]] and forwarding events to the appropriate tool.
* @see [[IModelApp.toolAdmin]] to access the session's `ToolAdmin`.
* @public
* @extensions
*/
export class ToolAdmin {
public markupView?: ScreenViewport;
/** @internal */
public readonly currentInputState = new CurrentInputState();
/** @internal */
public readonly toolState = new ToolState();
/** Maintains the state of tool settings properties for the current session. */
public readonly toolSettingsState = new ToolSettingsState();
private _canvasDecoration?: CanvasDecoration;
private _suspendedByViewTool?: SuspendedToolState;
private _suspendedByInputCollector?: SuspendedToolState;
private _viewTool?: ViewTool;
private _primitiveTool?: PrimitiveTool;
private _idleTool?: InteractiveTool;
private _inputCollector?: InputCollector;
private _saveCursor?: string;
private _saveLocateCircle = false;
private _defaultToolId = "Select";
private _defaultToolArgs?: any[];
private _lastHandledMotionTime?: BeTimePoint;
private _mouseMoveOverTimeout?: NodeJS.Timeout;
/** The name of the [[PrimitiveTool]] to use as the default tool. Defaults to "Select", referring to [[SelectionTool]].
* @see [[startDefaultTool]] to activate the default tool.
* @see [[defaultToolArgs]] to supply arguments when starting the tool.
*/
public get defaultToolId(): string {
return this._defaultToolId;
}
public set defaultToolId(toolId: string) {
this._defaultToolId = toolId;
}
/** The arguments supplied to the default [[Tool]]'s [[Tool.run]] method from [[startDefaultTool]].
* @see [[defaultToolId]] to configure the default tool.
*/
public get defaultToolArgs(): any[] | undefined {
return this._defaultToolArgs;
}
public set defaultToolArgs(args: any[] | undefined) {
this._defaultToolArgs = args;
}
/** Apply operations such as transform, copy or delete to all members of an assembly. */
public assemblyLock = false;
/** If Grid Lock is on, project data points to grid. */
public gridLock = false;
/** If ACS Snap Lock is on, project snap points to the ACS plane. */
public acsPlaneSnapLock = false;
/** If ACS Plane Lock is on, standard view rotations are relative to the ACS instead of global. */
public acsContextLock = false;
/** Options for how uncaught exceptions should be handled by [[ToolAdmin.exceptionHandler]]. */
public static exceptionOptions = {
/** Log exception to Logger. */
log: true,
/** Show an alert box explaining that a problem happened. */
alertBox: true,
/** Include the "gory details" (e.g. stack trace) in the alert box. */
details: true,
/** break into debugger (only works if debugger is already opened) */
launchDebugger: true,
};
/** A function that catches otherwise-uncaught exceptions occurring inside ToolAdmin.eventLoop.
* To customize the behavior of this function, modify [[ToolAdmin.exceptionOptions]].
* To replace it within your own handler, simply assign to it, e.g.:
* ```ts
* ToolAdmin.exceptionHandler = (exception: any): Promise<any> => {
* ... your implementation here
* }
* ```
*/
public static async exceptionHandler(exception: any): Promise<any> {
const opts = ToolAdmin.exceptionOptions;
const msg: string = undefined !== exception.stack ? exception.stack : exception.toString();
if (opts.log)
Logger.logError(`${FrontendLoggerCategory.Package}.unhandledException`, msg);
if (opts.launchDebugger) // this does nothing if the debugger window is not already opened
debugger; // eslint-disable-line no-debugger
if (!opts.alertBox)
return;
let out = `<h2>${IModelApp.localization.getLocalizedString("iModelJs:Errors.ReloadPage")}</h2>`;
if (opts.details) {
out += `<h3>${IModelApp.localization.getLocalizedString("iModelJs:Errors.Details")}</h3><h4>`;
msg.split("\n").forEach((line) => out += `${line}<br>`);
out += "</h4>";
}
const div = document.createElement("div");
div.innerHTML = out;
return IModelApp.notifications.openMessageBox(MessageBoxType.MediumAlert, div, MessageBoxIconType.Critical);
}
private static readonly _removals: VoidFunction[] = [];
/** The registered handler method that will update the UI with any property value changes.
* @internal
*/
private _toolSettingsChangeHandler: ((toolId: string, syncProperties: DialogPropertySyncItem[]) => void) | undefined = undefined;
/** Returns the handler registered by the UI layer that allows it to display property changes made by the active Tool. */
public get toolSettingsChangeHandler() { return this._toolSettingsChangeHandler; }
public set toolSettingsChangeHandler(handler: ((toolId: string, syncProperties: DialogPropertySyncItem[]) => void) | undefined) {
this._toolSettingsChangeHandler = handler;
}
/** The registered handler method that will inform the UI to reload tool setting with properties from active tool.
* @internal
*/
private _reloadToolSettingsHandler: (() => void) | undefined = undefined;
/** Returns the handler registered by the UI layer that allows it to display property changes made by the active Tool. */
public get reloadToolSettingsHandler() { return this._reloadToolSettingsHandler; }
public set reloadToolSettingsHandler(handler: (() => void) | undefined) {
this._reloadToolSettingsHandler = handler;
}
/** The registered handler method that will trigger UI Sync processing.
* @internal
*/
private _toolSyncUiEventDispatcher: ((syncEventId: string, useImmediateDispatch?: boolean) => void) | undefined = undefined;
/** Returns the handler registered by the UI layer that will trigger UiSyncEvent processing that informs UI component to refresh their state. */
public get toolSyncUiEventDispatcher() { return this._toolSyncUiEventDispatcher; }
public set toolSyncUiEventDispatcher(handler: ((syncEventId: string, useImmediateDispatch?: boolean) => void) | undefined) {
this._toolSyncUiEventDispatcher = handler;
}
/** Handler for keyboard events. */
private static _keyEventHandler = (ev: KeyboardEvent) => {
if (!ev.repeat) // we don't want repeated keyboard events. If we keep them they interfere with replacing mouse motion events, since they come as a stream.
ToolAdmin.addEvent(ev);
};
/** @internal */
public onInitialized() {
if (typeof document === "undefined")
return; // if document isn't defined, we're probably running in a test environment. At any rate, we can't have interactive tools.
this._idleTool = IModelApp.tools.create("Idle") as InteractiveTool;
["keydown", "keyup"].forEach((type) => {
document.addEventListener(type, ToolAdmin._keyEventHandler as EventListener, false);
ToolAdmin._removals.push(() => document.removeEventListener(type, ToolAdmin._keyEventHandler as EventListener, false));
});
ToolAdmin._removals.push(() => window.onfocus = null);
}
/** @internal */
public onShutDown() {
this.clearMotionPromises();
this._idleTool = undefined;
IconSprites.emptyAll(); // clear cache of icon sprites
ToolAdmin._removals.forEach((remove) => remove());
ToolAdmin._removals.length = 0;
}
/** Get the ScreenViewport where the cursor is currently, if any. */
public get cursorView(): ScreenViewport | undefined { return this.currentInputState.viewport; }
/** Called from ViewManager.dropViewport to prevent tools from continuing to operate on the dropped viewport.
* @internal
*/
public forgetViewport(vp: ScreenViewport): void {
// Ignore pending motion promises on fulfillment.
this.clearMotionPromises();
// make sure tools don't think the cursor is still in this viewport.
this.onMouseLeave(vp);
// Remove any events associated with this viewport.
ToolAdmin._toolEvents = ToolAdmin._toolEvents.filter((ev) => ev.vp !== vp);
}
private getMousePosition(event: ToolEvent): XAndY {
return event.vp!.mousePosFromEvent(event.ev as MouseEvent);
}
private getMouseMovement(event: ToolEvent): XAndY {
return event.vp!.mouseMovementFromEvent(event.ev as MouseEvent);
}
private getMouseButton(button: number) {
switch (button) {
case MouseButton.Middle: return BeButton.Middle;
case MouseButton.Right: return BeButton.Reset;
default: return BeButton.Data;
}
}
private async onMouseButton(event: ToolEvent, isDown: boolean): Promise<any> {
const ev = event.ev as MouseEvent;
const vp = event.vp!;
const pos = this.getMousePosition(event);
const button = this.getMouseButton(ev.button);
this.currentInputState.setKeyQualifiers(ev);
return isDown ? this.onButtonDown(vp, pos, button, InputSource.Mouse) : this.onButtonUp(vp, pos, button, InputSource.Mouse);
}
private async onWheel(event: ToolEvent): Promise<EventHandled> {
const ev = event.ev as WheelEvent;
const vp = event.vp!;
if (this.filterViewport(vp))
return EventHandled.Yes;
const current = this.currentInputState;
current.setKeyQualifiers(ev);
if (ev.deltaY === 0)
return EventHandled.No;
let delta: number;
switch (ev.deltaMode) {
case ev.DOM_DELTA_LINE:
delta = -ev.deltaY * ToolSettings.wheelLineFactor; // 40
break;
case ev.DOM_DELTA_PAGE:
delta = -ev.deltaY * ToolSettings.wheelPageFactor; // 120;
break;
default: // DOM_DELTA_PIXEL:
delta = -ev.deltaY;
break;
}
const pt2d = this.getMousePosition(event);
vp.setAnimator();
current.fromButton(vp, pt2d, InputSource.Mouse, true);
const wheelEvent = new BeWheelEvent();
wheelEvent.wheelDelta = delta;
current.toEvent(wheelEvent, true);
const overlayHit = this.pickCanvasDecoration(wheelEvent);
if (undefined !== overlayHit && undefined !== overlayHit.onWheel && overlayHit.onWheel(wheelEvent))
return EventHandled.Yes;
const tool = this.activeTool;
if (undefined === tool || EventHandled.Yes !== await tool.onMouseWheel(wheelEvent) && vp !== this.markupView)
return this.idleTool.onMouseWheel(wheelEvent);
return EventHandled.Yes;
}
private async sendTapEvent(touchEv: BeTouchEvent): Promise<EventHandled> {
touchEv.viewport!.setAnimator();
const overlayHit = this.pickCanvasDecoration(touchEv);
if (undefined !== overlayHit && undefined !== overlayHit.onMouseButton && overlayHit.onMouseButton(touchEv))
return EventHandled.Yes;
if (await IModelApp.accuSnap.onTouchTap(touchEv))
return EventHandled.Yes;
const tool = this.activeTool;
if (undefined !== tool && EventHandled.Yes === await tool.onTouchTap(touchEv))
return EventHandled.Yes;
return this.idleTool.onTouchTap(touchEv);
}
private async doubleTapTimeout(): Promise<void> {
const current = this.currentInputState;
if (undefined === current.touchTapTimer)
return;
const touchEv = current.lastTouchStart;
const numTouches = (undefined !== current.lastTouchStart ? current.lastTouchStart.touchCount : 0);
const numTaps = (undefined !== current.touchTapCount ? current.touchTapCount : 0);
current.touchTapTimer = current.touchTapCount = current.lastTouchStart = undefined;
if (undefined === touchEv || 0 > numTouches || 0 > numTaps)
return;
touchEv.tapCount = numTaps;
await this.sendTapEvent(touchEv);
}
private async onTouch(event: ToolEvent): Promise<void> {
const touchEvent = event.ev as TouchEvent;
const vp = event.vp!;
if (this.filterViewport(vp))
return;
const ev = new BeTouchEvent({ touchEvent });
const current = this.currentInputState;
const pos = BeTouchEvent.getTouchListCentroid(0 !== touchEvent.targetTouches.length ? touchEvent.targetTouches : touchEvent.changedTouches, vp);
switch (touchEvent.type) {
case "touchstart":
if (touchEvent.changedTouches.length === touchEvent.targetTouches.length)
vp.setAnimator(); // Clear viewport animator on start of new touch input (first contact point added)...
current.setKeyQualifiers(touchEvent);
break;
case "touchend":
current.setKeyQualifiers(touchEvent);
break;
}
current.fromButton(vp, undefined !== pos ? pos : Point2d.createZero(), InputSource.Touch, true);
current.toEvent(ev, false);
const tool = this.activeTool;
switch (touchEvent.type) {
case "touchstart": {
current.lastTouchStart = ev;
IModelApp.accuSnap.onTouchStart(ev);
if (undefined !== tool)
await tool.onTouchStart(ev);
return;
}
case "touchend": {
IModelApp.accuSnap.onTouchEnd(ev);
if (undefined !== tool) {
await tool.onTouchEnd(ev);
if (0 === ev.touchCount)
await tool.onTouchComplete(ev);
}
if (undefined === current.lastTouchStart)
return;
if (ev.touchEvent.timeStamp - current.lastTouchStart.touchEvent.timeStamp > (2.0 * ToolSettings.doubleTapTimeout.milliseconds))
return; // Too much time has passed from touchstart to be considered a tap...
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < ev.touchEvent.changedTouches.length; i++) {
const currTouch = ev.touchEvent.changedTouches[i];
const startTouch = BeTouchEvent.findTouchById(current.lastTouchStart.touchEvent.targetTouches, currTouch.identifier);
if (undefined !== startTouch) {
const currPt = BeTouchEvent.getTouchPosition(currTouch, vp);
const startPt = BeTouchEvent.getTouchPosition(startTouch, vp);
if (currPt.distance(startPt) < vp.pixelsFromInches(ToolSettings.touchMoveDistanceInches))
continue; // Hasn't moved appreciably....
}
current.lastTouchStart = undefined; // Not a tap...
return;
}
if (0 !== ev.touchCount || undefined === current.lastTouchStart)
return;
// All fingers off, defer processing tap until we've waited long enough to detect double tap...
if (undefined === current.touchTapTimer) {
current.touchTapTimer = Date.now();
current.touchTapCount = 1;
// eslint-disable-next-line @typescript-eslint/unbound-method
await ToolSettings.doubleTapTimeout.executeAfter(this.doubleTapTimeout, this);
} else if (undefined !== current.touchTapCount) {
current.touchTapCount++;
}
return;
}
case "touchcancel": {
current.lastTouchStart = undefined;
IModelApp.accuSnap.onTouchCancel(ev);
if (undefined !== tool)
await tool.onTouchCancel(ev);
return;
}
case "touchmove": {
if (!IModelApp.accuSnap.onTouchMove(ev) && undefined !== tool)
await tool.onTouchMove(ev);
if (undefined === current.lastTouchStart)
return;
if (ev.touchEvent.timeStamp - current.lastTouchStart.touchEvent.timeStamp < ToolSettings.touchMoveDelay.milliseconds)
return;
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < ev.touchEvent.changedTouches.length; ++i) {
const currTouch = ev.touchEvent.changedTouches[i];
const startTouch = BeTouchEvent.findTouchById(current.lastTouchStart.touchEvent.targetTouches, currTouch.identifier);
if (undefined === startTouch)
continue;
const currPt = BeTouchEvent.getTouchPosition(currTouch, vp);
const startPt = BeTouchEvent.getTouchPosition(startTouch, vp);
if (currPt.distance(startPt) < vp.pixelsFromInches(ToolSettings.touchMoveDistanceInches))
continue; // Hasn't moved appreciably....
const touchStart = current.lastTouchStart;
current.lastTouchStart = undefined;
if (IModelApp.accuSnap.onTouchMoveStart(ev, touchStart))
return;
if (undefined === tool || EventHandled.Yes !== await tool.onTouchMoveStart(ev, touchStart))
await this.idleTool.onTouchMoveStart(ev, touchStart);
return;
}
return;
}
}
}
/** A first-in-first-out queue of ToolEvents. */
private static _toolEvents: ToolEvent[] = [];
private static tryReplace(ev: Event, vp?: ScreenViewport): boolean {
if (ToolAdmin._toolEvents.length < 1)
return false;
const last = ToolAdmin._toolEvents[ToolAdmin._toolEvents.length - 1];
const lastType = last.ev.type;
if (lastType !== ev.type || (lastType !== "mousemove" && lastType !== "touchmove"))
return false; // only mousemove and touchmove can replace previous
last.ev = ev; // sequential moves are not important. Replace the previous one with this one.
last.vp = vp;
return true;
}
/** @internal */
private static getNextEvent(): ToolEvent | undefined {
if (ToolAdmin._toolEvents.length > 1) // if there is more than one event, we're going to need another animation frame to process it.
IModelApp.requestNextAnimation();
return ToolAdmin._toolEvents.shift(); // pull first event from the queue
}
/** Called from HTML event listeners. Events are processed in the order they're received in ToolAdmin.eventLoop
* @internal
*/
public static addEvent(ev: Event, vp?: ScreenViewport): void {
if (!ToolAdmin.tryReplace(ev, vp)) // see if this event replaces the last event in the queue
this._toolEvents.push({ ev, vp }); // otherwise put it at the end of the queue.
IModelApp.requestNextAnimation(); // wake up event loop, if
}
/** Process the next event in the event queue, if any. */
private async processNextEvent(): Promise<any> {
const event = ToolAdmin.getNextEvent(); // pull first event from the queue
if (undefined === event)
return; // nothing in queue
switch (event.ev.type) {
case "mousedown": return this.onMouseButton(event, true);
case "mouseup": return this.onMouseButton(event, false);
case "mousemove": return this.onMouseMove(event);
case "mouseover": return this.onMouseEnter(event);
case "mouseout": return this.onMouseLeave(event.vp!);
case "wheel": return this.onWheel(event);
case "keydown": return this.onKeyTransition(event, true);
case "keyup": return this.onKeyTransition(event, false);
case "touchstart": return this.onTouch(event);
case "touchend": return this.onTouch(event);
case "touchcancel": return this.onTouch(event);
case "touchmove": return this.onTouch(event);
}
}
private _processingEvent = false;
/**
* Process a single event, plus timer events. Don't start work on new events if the previous one has not finished.
* @internal
*/
public async processEvent(): Promise<void> {
if (this._processingEvent)
return; // we're still working on the previous event.
try {
this._processingEvent = true; // we can't allow any further event processing until the current event completes.
await this.processNextEvent();
} catch (exception) {
await ToolAdmin.exceptionHandler(exception); // we don't attempt to exit here
} finally {
this._processingEvent = false; // this event is now finished. Allow processing next time through.
}
}
/** The idleTool handles events that are not otherwise processed. */
public get idleTool(): InteractiveTool {
assert(undefined !== this._idleTool);
return this._idleTool;
}
public set idleTool(idleTool: InteractiveTool) {
this._idleTool = idleTool;
}
/** Return true to filter (ignore) events to the given viewport */
protected filterViewport(vp: ScreenViewport) {
if (undefined === vp || vp.isDisposed)
return true;
const tool = this.activeTool;
return (undefined !== tool ? !tool.isCompatibleViewport(vp, false) : false);
}
/** @internal */
public async onInstallTool(tool: InteractiveTool): Promise<boolean> {
this.currentInputState.onInstallTool();
return tool.onInstall();
}
/** @internal */
public async onPostInstallTool(tool: InteractiveTool) { return tool.onPostInstall(); }
public get viewTool(): ViewTool | undefined { return this._viewTool; }
public get primitiveTool(): PrimitiveTool | undefined { return this._primitiveTool; }
/** The currently active InteractiveTool. May be ViewTool, InputCollector, PrimitiveTool, undefined - in that priority order. */
public get activeTool(): InteractiveTool | undefined {
return this._viewTool ? this._viewTool : (this._inputCollector ? this._inputCollector : this._primitiveTool); // NOTE: Viewing tools suspend input collectors as well as primitives
}
/** The current tool. May be ViewTool, InputCollector, PrimitiveTool, or IdleTool - in that priority order. */
public get currentTool(): InteractiveTool { return this.activeTool ? this.activeTool : this.idleTool; }
/** Ask the current tool to provide tooltip contents for the supplied HitDetail. */
public async getToolTip(hit: HitDetail): Promise<HTMLElement | string> { return this.currentTool.getToolTip(hit); }
/**
* Event raised whenever the active tool changes. This includes PrimitiveTool, ViewTool, and InputCollector.
* @param newTool The newly activated tool
*/
public readonly activeToolChanged = new BeEvent<(tool: Tool, start: StartOrResume) => void>();
/**
* Event raised by tools that support edit manipulators like the SelectTool.
* @param tool The current tool
*/
public readonly manipulatorToolEvent = new BeEvent<(tool: Tool, event: ManipulatorToolEvent) => void>();
private async onMouseEnter(event: ToolEvent): Promise<void> {
const vp = event.vp!;
const current = this.currentInputState;
current.viewport = vp;
// Detect if drag was active and button was released outside the view...
const tool = this.activeTool;
if (undefined === tool)
return;
const buttonMask = (event.ev as MouseEvent).buttons;
let cancelDrag = false;
current.button.forEach((button, buttonNum) => {
if (button.isDragging && !(buttonMask & (1 << buttonNum))) {
button.isDragging = button.isDown = false;
cancelDrag = true;
}
});
if (cancelDrag)
await tool.onReinitialize();
}
/** @internal */
public onMouseLeave(vp: ScreenViewport): void {
if (this._mouseMoveOverTimeout !== undefined)
clearTimeout(this._mouseMoveOverTimeout);
IModelApp.accuSnap.clear();
this.currentInputState.clearViewport(vp);
this.setCanvasDecoration(vp);
vp.invalidateDecorations(); // stop drawing locate circle...
}
/** @internal */
public updateDynamics(ev?: BeButtonEvent, useLastData?: boolean, adjustPoint?: boolean): void {
if (undefined === this.activeTool)
return;
if (undefined === ev) {
ev = new BeButtonEvent();
if (useLastData)
this.fillEventFromLastDataButton(ev);
else
this.fillEventFromCursorLocation(ev);
// NOTE: Do not call adjustPoint when snapped, refer to CurrentInputState.fromButton
if (adjustPoint && undefined !== ev.viewport && undefined === TentativeOrAccuSnap.getCurrentSnap(false))
this.adjustPoint(ev.point, ev.viewport);
}
if (undefined === ev.viewport)
return;
// Support tools requesting async information in onMouseMotion for use in decorate or onDynamicFrame...
const toolPromise = this._toolMotionPromise = this.activeTool.onMouseMotion(ev);
const tool = this.activeTool;
const vp = ev.viewport;
const motion = ev;
toolPromise.then(() => {
if (undefined === this._toolMotionPromise)
return; // Only early return if canceled, result from a previous motion is preferable to showing nothing...
// Update decorations when dynamics are inactive...
if (!IModelApp.viewManager.inDynamicsMode) {
vp.invalidateDecorations();
return;
}
// Update dynamics and decorations only after motion...
const context = new DynamicsContext(vp);
tool.onDynamicFrame(motion, context);
context.changeDynamics();
}).catch((_) => { });
}
public async sendEndDragEvent(ev: BeButtonEvent): Promise<any> {
let tool = this.activeTool;
if (undefined !== tool) {
if (!tool.isValidLocation(ev, true))
tool = undefined;
else if (tool.receivedDownEvent)
tool.receivedDownEvent = false;
else
tool = undefined;
}
// Don't send tool end drag event if it didn't get the start drag event
if (undefined === tool || EventHandled.Yes !== await tool.onMouseEndDrag(ev))
return this.idleTool.onMouseEndDrag(ev);
}
private setCanvasDecoration(vp: ScreenViewport, dec?: CanvasDecoration, ev?: BeButtonEvent) {
if (dec === this._canvasDecoration)
return;
if (this._canvasDecoration && this._canvasDecoration.onMouseLeave)
this._canvasDecoration.onMouseLeave();
this._canvasDecoration = dec;
if (ev && dec && dec.onMouseEnter)
dec.onMouseEnter(ev);
vp.canvas.style.cursor = dec ? (dec.decorationCursor ? dec.decorationCursor : "pointer") : IModelApp.viewManager.cursor;
vp.invalidateDecorations();
}
private pickCanvasDecoration(ev: BeButtonEvent) {
const vp = ev.viewport!;
const decoration = (undefined === this.viewTool) ? vp.pickCanvasDecoration(ev.viewPoint) : undefined;
this.setCanvasDecoration(vp, decoration, ev);
return decoration;
}
/** Current request for locate/snap */
private _snapMotionPromise?: Promise<boolean>;
/** Current request for active tool motion event */
private _toolMotionPromise?: Promise<void>;
private clearMotionPromises(): void {
this._snapMotionPromise = this._toolMotionPromise = undefined;
}
private async forceOnMotionSnap(ev: BeButtonEvent): Promise<boolean> {
// Make sure that we fire the motion snap event correctly
this._lastHandledMotionTime = undefined;
return this.onMotionSnap(ev);
}
private async onMotionSnap(ev: BeButtonEvent): Promise<boolean> {
try {
await this.onMotionSnapOrSkip(ev);
return true;
} catch (error) {
if (error instanceof AbandonedError)
return false; // expected, not a problem. Just ignore this motion and return.