-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpane.ts
2188 lines (1902 loc) · 80.9 KB
/
pane.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) 2022, Metron, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import { appendChild, arrayAllEqual, arrayRemoveFirst, arrayRemoveLast, arraySortStable, Consumer, Disposer, DisposerGroup, DisposerGroupMap, equal, FireableListenable, FireableNotifier, IMMEDIATE, ImmutableSet, Interval2D, isDefined, isNonNullish, isNullish, isNumber, LinkedSet, mapAdd, mapRequire, mapSetIfAbsent, newImmutableSet, NOOP, NotifierBasic, Nullable, Point2D, Predicate, ReadableRef, Ref, RefBasic, requireNonNullish, run, Runnable, Size2D, StringTuple, Supplier } from '@metsci/gleam-util';
import { ChildlessLayout } from '../layouts/childlessLayout';
import { BorderPainter } from '../painters/borderPainter';
import { FillPainter } from '../painters/fillPainter';
import { attachCanvasResizeListener, attachSubtreeRestyleListener, CET_L01, ColorTablePopulator, COLOR_TABLE_INVERTER, createDomPeer, currentDpr, DomPeer, drawingBufferBounds, getModifiers, getMouseLoc_PX, GL, glScissor, glViewport, isDomPeer, isStyleProp, isUnboundStyleProp, MAGMA, ModifierSet, PeerType, setCssClassPresent, ShaderProgram, ShaderSource } from '../support';
import { ArrayWithZIndices, attachEventListener, isfn, isobj } from '../util';
import { mergePreSortedLists, NotifierTree } from '../util/notifierTree';
import { BufferInfo, BufferInit, BufferMeta, Context, TextureInfo, TextureInit, TextureMeta } from './context';
import { Layout } from './layout';
import { Painter } from './painter';
const { max, min } = Math;
export class PaneMouseEvent {
constructor(
readonly dpr: number,
readonly loc_PX: Point2D,
readonly modifiers: ModifierSet,
readonly button: Nullable<number> = null,
readonly pressCount: number = 0,
readonly wheelSteps: number = 0,
) {
}
}
export class PaneKeyEvent {
constructor(
readonly dpr: number,
readonly key: string,
readonly keysDown: ImmutableSet<string>,
) {
}
}
export function findPaneById( id: string ): Nullable<Pane> {
return ( document.getElementById( id ) as any )?.pane ?? null;
}
export function* findPanes( rootPane: Pane, selectors: string ): Iterable<Pane> {
for ( const element of rootPane.peer.querySelectorAll( selectors ) ) {
const pane = ( element as any ).pane;
if ( pane ) {
yield pane;
}
}
}
export function findFirstPane( basePane: Pane, selectors: string ): Nullable<Pane> {
for ( const pane of findPanes( basePane, selectors ) ) {
return pane;
}
return null;
}
export interface PaintFn {
( context: Context ): void;
}
export interface InputHandler {
getHoverHandler?( evMove: PaneMouseEvent ): Nullable<HoverHandler>;
getDragHandler?( evGrab: PaneMouseEvent ): Nullable<DragHandler>;
getWheelHandler?( evWheel: PaneMouseEvent ): Nullable<WheelHandler>;
getKeyHandler?( evGrab: PaneMouseEvent ): Nullable<KeyHandler>;
}
export function maskedInputHandler( inputHandler: InputHandler, mask: Predicate<PaneMouseEvent> ): InputHandler {
return {
getHoverHandler( evMove: PaneMouseEvent ): Nullable<HoverHandler> {
if ( inputHandler.getHoverHandler && mask( evMove ) ) {
return inputHandler.getHoverHandler( evMove );
}
return null;
},
getDragHandler( evGrab: PaneMouseEvent ): Nullable<DragHandler> {
if ( inputHandler.getDragHandler && mask( evGrab ) ) {
return inputHandler.getDragHandler( evGrab );
}
return null;
},
getWheelHandler( evWheel: PaneMouseEvent ): Nullable<WheelHandler> {
if ( inputHandler.getWheelHandler && mask( evWheel ) ) {
return inputHandler.getWheelHandler( evWheel );
}
return null;
},
getKeyHandler( evGrab: PaneMouseEvent ): Nullable<KeyHandler> {
if ( inputHandler.getKeyHandler && mask( evGrab ) ) {
return inputHandler.getKeyHandler( evGrab );
}
return null;
},
};
}
export interface HoverHandler {
/**
* A sequence of handlers with the same `target` are considered a single
* continuous hover. `handleHover` is called when such a sequence starts,
* and `handleUnhover` is called when the sequence ends. `target` objects
* are checked for equality according to `ValueObject` semantics.
*/
readonly target: unknown;
getMouseCursorClasses?( ): ReadonlyArray<string>;
handleHover?( ): void;
handleMove?( evMove: PaneMouseEvent ): void;
handleUnhover?( ): void;
}
export interface DragHandler extends HoverHandler {
handleGrab?( ): void;
handleDrag?( evDrag: PaneMouseEvent ): void;
handleUngrab?( evUngrab: PaneMouseEvent ): void;
}
export interface WheelHandler {
/**
* Passed to input spectators. The wheel is treated as separate from
* hover/drag and focus, and there are no begin/end wheel notifications
* analogous to hover/unhover, grab/ungrab, and focus/unfocus.
*/
readonly target: unknown;
handleWheel?( evWheel: PaneMouseEvent ): void;
}
export interface KeyHandler {
/**
* A sequence of handlers with the same `target` are considered a single
* continuous focus. `handleFocus` is called when such a sequence starts,
* and `handleUnfocus` is called when the sequence ends. `target` objects
* are checked for equality according to `ValueObject` semantics.
*/
readonly target: unknown;
handleFocus?( ): void;
handleKeyPress?( evPress: PaneKeyEvent ): void;
handleKeyRelease?( evRelease: PaneKeyEvent ): void;
handleUnfocus?( ): void;
}
const NOOP_TARGET: unknown = Object.freeze( [ 'NOOP' ] );
const NOOP_HOVER_HANDLER: HoverHandler = Object.freeze( { target: NOOP_TARGET } );
const NOOP_DRAG_HANDLER: DragHandler = Object.freeze( { target: NOOP_TARGET } );
const NOOP_KEY_HANDLER: KeyHandler = Object.freeze( { target: NOOP_TARGET } );
const NOOP_WHEEL_HANDLER: WheelHandler = Object.freeze( { target: NOOP_TARGET } );
export interface InputSpectator {
handleHover?( target: unknown, evEnter: PaneMouseEvent ): void;
handleMove?( target: unknown, evHover: PaneMouseEvent ): void;
handleUnhover?( target: unknown, evExit: PaneMouseEvent ): void;
handleGrab?( target: unknown, evGrab: PaneMouseEvent ): void;
handleDrag?( target: unknown, evDrag: PaneMouseEvent ): void;
handleUngrab?( target: unknown, evUngrab: PaneMouseEvent ): void;
handleWheel?( target: unknown, evWheel: PaneMouseEvent ): void;
handleFocus?( target: unknown ): void;
handleKeyPress?( target: unknown, evPress: PaneKeyEvent ): void;
handleKeyRelease?( target: unknown, evRelease: PaneKeyEvent ): void;
handleUnfocus?( target: unknown ): void;
}
export function createHoverAndFocusRefs( pane: Pane ): [ ReadableRef<unknown>, ReadableRef<unknown> ] {
const hoverTargetRef = new RefBasic<unknown>( undefined, equal );
const focusTargetRef = new RefBasic<unknown>( undefined, equal );
attachHoverAndFocusRefs( pane, hoverTargetRef, focusTargetRef );
return [ hoverTargetRef, focusTargetRef ];
}
export function attachHoverAndFocusRefs( pane: Pane, hoverTargetRef: Ref<unknown>, focusTargetRef: Ref<unknown> ): Disposer {
const disposers = new DisposerGroup( );
disposers.add( attachHoverRef( pane, hoverTargetRef ) );
disposers.add( attachFocusRef( pane, focusTargetRef ) );
return disposers;
}
export function attachHoverRef( pane: Pane, hoverTargetRef: Ref<unknown> ): Disposer {
return pane.inputSpectators.add( {
handleHover: target => hoverTargetRef.set( true, target ),
handleUnhover: ( ) => hoverTargetRef.set( true, undefined ),
} );
}
export function attachFocusRef( pane: Pane, focusTargetRef: Ref<unknown> ): Disposer {
return pane.inputSpectators.add( {
handleFocus: target => focusTargetRef.set( false, target ),
handleUnfocus: ( ) => focusTargetRef.set( false, undefined ),
} );
}
export const PANE_SYMBOL = Symbol( '@@__GLEAM_PANE__@@' );
export function isPane( obj: any ): obj is Pane {
return !!( obj && typeof obj === 'object' && obj[ PANE_SYMBOL ] );
}
export class Pane {
readonly [ PANE_SYMBOL ] = true;
readonly peer = createDomPeer( 'gleam-pane', this, PeerType.PANE );
/**
* CSS props to be consulted by this pane's parent layout when deciding
* where to place this pane.
*/
readonly siteInParentPeer = createDomPeer( 'site-in-parent', this, PeerType.SITE );
readonly siteInParentStyle = window.getComputedStyle( this.siteInParentPeer );
readonly siteInParentOverrides: { [ key: string ]: Supplier<unknown> | undefined } = {};
readonly layout: Layout;
consumesInputEvents: boolean;
protected parent: Pane | null;
protected readonly children: LinkedSet<Pane>;
/**
* Actions to be run the next time a `Context` is current.
*/
protected readonly pendingContextActions: Array<Consumer<Context>>;
/**
* Includes `PaintFn` instances for both painters and child-panes.
*/
protected readonly paintFns: ArrayWithZIndices<PaintFn>;
protected readonly paintFnsByPainter: Map<Painter,PaintFn>;
protected readonly paintFnsByPane: Map<Pane,PaintFn>;
/**
* Includes handlers added via `addInputHandler()` and child panes added
* via `addPane()`.
*/
protected readonly inputHandlers: ArrayWithZIndices<InputHandler>;
protected readonly disposersByCssClass: DisposerGroupMap<string>;
protected readonly disposersByPainter: DisposerGroupMap<Painter>;
protected readonly disposersByInputHandler: DisposerGroupMap<InputHandler>;
protected readonly disposersByInputSpectator: DisposerGroupMap<InputSpectator>;
protected readonly disposersByChild: DisposerGroupMap<Pane>;
protected visible: boolean;
protected prefSize_PX: Size2D;
protected viewport_PX: Interval2D;
protected scissor_PX: Interval2D;
readonly prefSizeReady: FireableNotifier<void>;
readonly layoutReady: NotifierTree<void>;
readonly inputSpectators: InputSpectatorTree;
/**
* Defined iff this pane is a top-level pane that is currently attached
* to a canvas. See `Pane.getCanvas()`.
*/
protected canvas: HTMLCanvasElement | undefined;
/**
* See also `Pane.getCanvas()`.
*/
readonly canvasChanged: NotifierTree<void>;
readonly background: FillPainter;
readonly border: BorderPainter;
constructor( layout: Layout = new ChildlessLayout( ) ) {
this.disposersByCssClass = new DisposerGroupMap( );
this.disposersByPainter = new DisposerGroupMap( );
this.disposersByInputHandler = new DisposerGroupMap( );
this.disposersByInputSpectator = new DisposerGroupMap( );
this.disposersByChild = new DisposerGroupMap( );
// TODO: Make this.layout mutable
appendChild( this.peer, this.siteInParentPeer );
appendChild( this.peer, layout.peer );
this.layout = layout;
this.consumesInputEvents = false;
this.parent = null;
this.children = new LinkedSet( );
this.pendingContextActions = new Array( );
this.paintFns = new ArrayWithZIndices( );
this.paintFnsByPainter = new Map( );
this.paintFnsByPane = new Map( );
this.inputHandlers = new ArrayWithZIndices( );
this.visible = true;
this.prefSize_PX = Size2D.ZERO;
this.viewport_PX = Interval2D.ZERO;
this.scissor_PX = this.viewport_PX;
this.prefSizeReady = new NotifierBasic( undefined );
this.layoutReady = new NotifierTree( undefined );
this.inputSpectators = new InputSpectatorTree( );
this.canvas = undefined;
this.canvasChanged = new NotifierTree( undefined );
this.background = new FillPainter( );
this.background.peer.classList.add( 'background' );
this.addPainter( this.background, -1e6 );
this.border = new BorderPainter( );
this.addPainter( this.border, +1e6 );
const debugPickFill = new FillPainter( );
debugPickFill.peer.classList.add( 'inspect-highlight' );
this.addPainter( debugPickFill, Number.POSITIVE_INFINITY );
const debugPickBorder = new BorderPainter( );
debugPickBorder.peer.classList.add( 'inspect-highlight' );
this.addPainter( debugPickBorder, Number.POSITIVE_INFINITY );
}
addCssClass( className: string ): Disposer {
const disposers = this.disposersByCssClass.get( className );
if ( !this.peer.classList.contains( className ) ) {
this.peer.classList.add( className );
disposers.add( ( ) => {
this.peer.classList.remove( className );
} );
}
return disposers;
}
removeCssClass( className: string ): void {
this.disposersByCssClass.disposeFor( className );
}
getParent( ): Pane | null {
return this.parent;
}
addPainter( painter: Painter, zIndex: number = 0 ): Disposer {
const disposers = this.disposersByPainter.get( painter );
disposers.add( appendChild( this.peer, painter.peer ) );
const paintFn = ( context: Context ): void => {
if ( painter.visible.v ) {
const gl = context.gl;
gl.enable( GL.SCISSOR_TEST );
glScissor( gl, this.scissor_PX );
glViewport( gl, this.viewport_PX );
painter.paint( context, this.viewport_PX );
}
};
disposers.add( mapAdd( this.paintFnsByPainter, painter, paintFn ) );
disposers.add( this.paintFns.add( paintFn, zIndex ) );
return disposers;
}
getPainters( ): Iterable<Painter> {
return this.paintFnsByPainter.keys( );
}
removePainter( painter: Painter ): void {
this.disposersByPainter.disposeFor( painter );
}
removeAllPainters( ): void {
this.disposersByPainter.dispose( );
}
hasPainter( painter: Painter ): boolean {
return this.paintFnsByPainter.has( painter );
}
getPainterZIndex( painter: Painter ): number {
const paintFn = mapRequire( this.paintFnsByPainter, painter );
return this.paintFns.getZIndex( paintFn );
}
setPainterZIndex( painter: Painter, zIndex: number ): void {
this.appendPainterToZIndex( painter, zIndex );
}
prependPainterToZIndex( painter: Painter, zIndex: number ): void {
const paintFn = mapRequire( this.paintFnsByPainter, painter );
this.paintFns.prependToZIndex( paintFn, zIndex );
}
appendPainterToZIndex( painter: Painter, zIndex: number ): void {
const paintFn = mapRequire( this.paintFnsByPainter, painter );
this.paintFns.appendToZIndex( paintFn, zIndex );
}
addInputHandler( inputHandler: InputHandler, zIndex: number = 0 ): Disposer {
return this.inputHandlers.add( inputHandler, zIndex );
}
removeInputHandler( inputHandler: InputHandler ): void {
this.disposersByInputHandler.disposeFor( inputHandler );
}
removeAllInputHandlers( ): void {
this.disposersByInputHandler.dispose( );
}
hasInputHandler( inputHandler: InputHandler ): boolean {
return this.inputHandlers.has( inputHandler );
}
getInputHandlerZIndex( inputHandler: InputHandler ): number {
return this.inputHandlers.getZIndex( inputHandler );
}
setInputHandlerZIndex( inputHandler: InputHandler, zIndex: number ): void {
this.appendInputHandlerToZIndex( inputHandler, zIndex );
}
prependInputHandlerToZIndex( inputHandler: InputHandler, zIndex: number ): void {
this.inputHandlers.prependToZIndex( inputHandler, zIndex );
}
appendInputHandlerToZIndex( inputHandler: InputHandler, zIndex: number ): void {
this.inputHandlers.appendToZIndex( inputHandler, zIndex );
}
addPane( child: Pane, zIndex: number = 0 ): Disposer {
const disposers = this.disposersByChild.get( child );
child.parent = this;
disposers.add( ( ) => {
child.parent = null;
} );
this.children.addLast( child );
disposers.add( ( ) => {
this.children.delete( child );
} );
// Move context actions as high up the tree as possible, so they run
// even if child gets detached from the tree before the next render
this.getRootPane( ).pendingContextActions.push( ...child.pendingContextActions );
child.pendingContextActions.length = 0;
disposers.add( appendChild( this.peer, child.peer ) );
const paintFn = ( context: Context ): void => {
child.paint( context );
};
disposers.add( mapAdd( this.paintFnsByPane, child, paintFn ) );
disposers.add( this.paintFns.add( paintFn, zIndex ) );
disposers.add( this.inputHandlers.add( child, zIndex ) );
child.layoutReady.setParent( this.layoutReady );
disposers.add( ( ) => {
child.layoutReady.setParent( null );
} );
child.inputSpectators.setParent( this.inputSpectators );
disposers.add( ( ) => {
child.inputSpectators.setParent( null );
} );
child.canvasChanged.setParent( this.canvasChanged );
disposers.add( ( ) => {
child.canvasChanged.setParent( null );
} );
return disposers;
}
removePane( child: Pane ): void {
this.disposersByChild.disposeFor( child );
}
removeAllPanes( ): void {
this.disposersByChild.dispose( );
}
hasPane( pane: Pane ): boolean {
return this.paintFnsByPane.has( pane );
}
getPaneZIndex( pane: Pane ): number {
const paintFn = mapRequire( this.paintFnsByPane, pane );
return this.paintFns.getZIndex( paintFn );
}
setPaneZIndex( pane: Pane, zIndex: number ): void {
this.appendPaneToZIndex( pane, zIndex );
}
prependPaneToZIndex( pane: Pane, zIndex: number ): void {
const paintFn = mapRequire( this.paintFnsByPane, pane );
this.paintFns.prependToZIndex( paintFn, zIndex );
this.inputHandlers.prependToZIndex( pane, zIndex );
}
appendPaneToZIndex( pane: Pane, zIndex: number ): void {
const paintFn = mapRequire( this.paintFnsByPane, pane );
this.paintFns.appendToZIndex( paintFn, zIndex );
this.inputHandlers.appendToZIndex( pane, zIndex );
}
// TODO: Maybe replace with an enum like VISIBLE, BLANK, ABSENT
isVisible( ): boolean {
return this.visible;
}
setVisible( visible: boolean ): void {
this.visible = visible;
}
getPrefSize_PX( ): Size2D {
return this.prefSize_PX;
}
getViewport_PX( ): Interval2D {
return this.viewport_PX;
}
getScissor_PX( ): Interval2D {
return this.scissor_PX;
}
/**
* **WARNING:** This method updates the mutable state of this pane and
* its descendants, but doesn't render to the display. This may leave
* the pane states out of sync with what's visible on the screen.
*
* Recursively layout this pane and its descendants to fit the specified
* bounds.
*
* This method is rarely used. In most cases, it is sufficient to do the
* layout just before rendering. However, there are cases where you want
* to change a setting, then (without rendering) check how the layout
* has changed.
*/
_doLayout( bounds?: Interval2D ): void {
bounds = bounds ?? this.getViewport_PX( );
this.prepForLayout( );
this.updatePrefSizes( );
this.updateBounds( bounds, bounds );
}
/**
* Recursively layout and paint this pane and its descendants to fill
* the supplied context. This method is only intended to be called on
* the top-level pane within a canvas.
*/
render( context: Context ): void {
// Pending actions
while ( true ) {
const contextAction = this.pendingContextActions.shift( );
if ( contextAction === undefined ) {
break;
}
contextAction( context );
}
// Prep
this.prepForLayout( );
// Pref sizes
this.updatePrefSizes( );
this.prefSizeReady.fire( );
// Layout and paint
const bounds = drawingBufferBounds( context.gl );
if ( bounds !== null ) {
this.updateBounds( bounds, bounds );
this.layoutReady.fire( undefined );
this.paint( context );
}
}
/**
* Enqueues the given action to run the next time a context is current.
* Handy when non-rendering code needs to make sure a GL resource gets
* disposed.
*/
doLaterWithContext( contextAction: Consumer<Context> ): void {
// Add it as high up the tree as possible, so the thing still runs even
// if this Pane gets detached from the tree before the next render
this.getRootPane( ).pendingContextActions.push( contextAction );
}
enableColorTables( colorTables: Iterable<Readonly<[string,ColorTablePopulator]>> ): void {
this.doLaterWithContext( context => {
for ( const [ key, value ] of colorTables ) {
context.putColorTable( key, value );
}
} );
}
getRootPane( ): Pane {
let pane: Pane = this;
while ( true ) {
if ( pane.parent === null ) {
return pane;
}
pane = pane.parent;
}
}
/**
* Convenience method for application code that needs to access the part
* of the DOM that contains a pane.
*
* See also `Pane.canvasChanged`.
*/
getCanvas( ): HTMLCanvasElement | undefined {
return this.getRootPane( ).canvas;
}
/**
* Intended for internal use only.
*/
_setCanvas( canvas: HTMLCanvasElement ): Disposer {
if ( this.canvas ) {
throw new Error( 'Canvas is already set' );
}
else {
this.canvas = canvas;
this.canvasChanged.fire( undefined );
return ( ) => {
if ( this.canvas === canvas ) {
this.canvas = undefined;
this.canvasChanged.fire( undefined );
}
};
}
}
protected prepForLayout( ): void {
// Child panes
for ( const child of this.children ) {
child.prepForLayout( );
}
// This pane
if ( this.visible && this.layout.prepFns !== undefined ) {
for ( const prepFn of this.layout.prepFns ) {
prepFn( this.children );
}
}
}
protected updatePrefSizes( ): void {
// Child panes
for ( const child of this.children ) {
child.updatePrefSizes( );
}
// This pane
if ( this.visible && this.layout.computePrefSize_PX !== undefined ) {
this.prefSize_PX = this.layout.computePrefSize_PX( this.children );
}
else {
this.prefSize_PX = Size2D.ZERO;
}
}
protected updateBounds( viewport_PX: Interval2D, scissor_PX: Interval2D ): void {
// This pane
this.viewport_PX = viewport_PX;
this.scissor_PX = scissor_PX;
// Child panes
const childViewports_PX = this.layout.computeChildViewports_PX( this.viewport_PX, this.children );
for ( const child of this.children ) {
const childViewport_PX = ( childViewports_PX.get( child ) ?? Interval2D.ZERO ).round( );
const childScissor_PX = ( childViewport_PX.intersection( this.scissor_PX ) ?? Interval2D.ZERO );
child.updateBounds( childViewport_PX, childScissor_PX );
}
}
protected paint( context: Context ): void {
if ( this.visible && this.scissor_PX.w > 0 && this.scissor_PX.h > 0 ) {
for ( const paintFn of this.paintFns ) {
paintFn( context );
}
}
}
getHoverHandler( evMove: PaneMouseEvent ): Nullable<HoverHandler> {
if ( this.visible && this.scissor_PX.containsPoint( evMove.loc_PX ) ) {
for ( const inputHandler of this.inputHandlers.inReverse ) {
const result = inputHandler.getHoverHandler?.( evMove );
if ( isNonNullish( result ) ) {
return result;
}
}
if ( this.consumesInputEvents ) {
return NOOP_HOVER_HANDLER;
}
}
return null;
}
getDragHandler( evGrab: PaneMouseEvent ): Nullable<DragHandler> {
if ( this.visible && this.scissor_PX.containsPoint( evGrab.loc_PX ) ) {
for ( const inputHandler of this.inputHandlers.inReverse ) {
const result = inputHandler.getDragHandler?.( evGrab );
if ( isNonNullish( result ) ) {
return result;
}
}
if ( this.consumesInputEvents ) {
return NOOP_DRAG_HANDLER;
}
}
return null;
}
getWheelHandler( evGrabOrWheel: PaneMouseEvent ): Nullable<WheelHandler> {
if ( this.visible && this.scissor_PX.containsPoint( evGrabOrWheel.loc_PX ) ) {
for ( const inputHandler of this.inputHandlers.inReverse ) {
const result = inputHandler.getWheelHandler?.( evGrabOrWheel );
if ( isNonNullish( result ) ) {
return result;
}
}
if ( this.consumesInputEvents ) {
return NOOP_WHEEL_HANDLER;
}
}
return null;
}
getKeyHandler( evGrab: PaneMouseEvent ): Nullable<KeyHandler> {
if ( this.visible && this.scissor_PX.containsPoint( evGrab.loc_PX ) ) {
for ( const inputHandler of this.inputHandlers.inReverse ) {
const result = inputHandler.getKeyHandler?.( evGrab );
if ( isNonNullish( result ) ) {
return result;
}
}
if ( this.consumesInputEvents ) {
return NOOP_KEY_HANDLER;
}
}
return null;
}
getPaneToInspect( evMove: PaneMouseEvent ): Nullable<Pane> {
if ( this.visible && this.scissor_PX.containsPoint( evMove.loc_PX ) ) {
for ( const inputHandler of this.inputHandlers.inReverse ) {
if ( isPane( inputHandler ) ) {
const pane = inputHandler.getPaneToInspect( evMove );
if ( isNonNullish( pane ) ) {
return pane;
}
}
else {
const hoverHandler = inputHandler.getHoverHandler?.( evMove );
if ( isNonNullish( hoverHandler ) ) {
return this;
}
}
}
return this;
}
return null;
}
}
/**
* Attach a listener that will run after layouts and before subsequent paints. The listener
* will remove itself after it has run the given number of times, or immediately upon key
* press, mouse press, or wheel.
*
* Useful at application startup, when the browser's reported window size can fluctuate for
* a few frames (e.g. if the application was opened in a bg tab while the fg tab had docked
* devtools), and there are application state variables (especially axis bounds) that need
* to be initialized based on the pixel sizes of onscreen components.
*/
export function onFirstFewLayouts( pane: Pane, numTimes: number, listener: Runnable ): Disposer {
const disposers = new DisposerGroup( );
let timesRemaining = numTimes;
if ( timesRemaining > 0 ) {
// Tear down after we've run the listener the specified number of times
disposers.add( pane.layoutReady.addListener( { order: +1e6 }, ( ) => {
listener( );
timesRemaining--;
if ( timesRemaining <= 0 ) {
disposers.dispose( );
}
} ) );
// Tear down immediately on user interaction
disposers.add( pane.inputSpectators.add( {
handleGrab: ( ) => disposers.dispose( ),
handleWheel: ( ) => disposers.dispose( ),
handleKeyPress: ( ) => disposers.dispose( ),
} ) );
}
return disposers;
}
interface ProgramCacheEntry {
prog: ShaderProgram<StringTuple,StringTuple>;
lastAccessFrameNum: number;
}
interface TextureCacheEntry {
inputs: ReadonlyArray<unknown>;
info: TextureInfo<TextureMeta>;
lastAccessFrameNum: number;
}
interface BufferCacheEntry {
inputs: ReadonlyArray<unknown>;
info: BufferInfo<BufferMeta>;
lastAccessFrameNum: number;
}
class ContextImpl implements Context {
frameNum: number;
wnd: Window;
canvas: HTMLCanvasElement;
gl: WebGLRenderingContext;
glIncarnation: { n: number };
protected nextObjectNum: number;
protected readonly objectKeys: WeakMap<object,string>;
protected readonly colorTables: Map<string,ColorTablePopulator>;
protected readonly colorTableFallback: ColorTablePopulator;
protected readonly programCache: Map<ShaderSource<StringTuple,StringTuple>,ProgramCacheEntry>;
protected readonly textureCache: Map<string,TextureCacheEntry>;
protected readonly bufferCache: Map<string,BufferCacheEntry>;
protected programCacheLastPruneFrameNum: number;
protected textureCacheLastPruneFrameNum: number;
protected bufferCacheLastPruneFrameNum: number;
constructor( wndInit: Window, canvasInit: HTMLCanvasElement, glInit: WebGLRenderingContext ) {
this.frameNum = 0;
this.wnd = wndInit;
this.canvas = canvasInit;
this.gl = glInit;
this.glIncarnation = { n: 0 };
this.nextObjectNum = 0;
this.objectKeys = new WeakMap( );
this.colorTables = new Map( [ CET_L01, MAGMA ] );
this.colorTableFallback = CET_L01[ 1 ];
this.programCache = new Map( );
this.textureCache = new Map( );
this.bufferCache = new Map( );
this.programCacheLastPruneFrameNum = this.frameNum;
this.textureCacheLastPruneFrameNum = this.frameNum;
this.bufferCacheLastPruneFrameNum = this.frameNum;
}
startNewIncarnation( wnd: Window, canvas: HTMLCanvasElement, gl: WebGLRenderingContext ): void {
this.wnd = wnd;
this.canvas = canvas;
this.gl = gl;
this.glIncarnation = { n: this.glIncarnation.n + 1 };
this.programCache.clear( );
this.textureCache.clear( );
this.bufferCache.clear( );
this.programCacheLastPruneFrameNum = this.frameNum;
this.textureCacheLastPruneFrameNum = this.frameNum;
this.bufferCacheLastPruneFrameNum = this.frameNum;
}
getObjectKey( obj: object ): string {
return mapSetIfAbsent( this.objectKeys, obj, ( ) => `#${this.nextObjectNum++}#` );
}
getProgram<U extends StringTuple, A extends StringTuple>( source: ShaderSource<U,A> ): ShaderProgram<U,A> {
this.pruneProgramCache( );
const en = mapSetIfAbsent( this.programCache, source, ( ) => {
return {
prog: new ShaderProgram( source ),
lastAccessFrameNum: -1,
};
} );
en.lastAccessFrameNum = this.frameNum;
en.prog.prepare( this.gl, this.glIncarnation );
return en.prog as ShaderProgram<U,A>;
}
protected pruneProgramCache( ): void {
if ( this.frameNum > this.programCacheLastPruneFrameNum ) {
// Identify entries ready to be disposed
const entriesToDispose = new Array<[ ShaderSource<StringTuple,StringTuple>, ShaderProgram<StringTuple,StringTuple> ]>( );
for ( const [ source, { prog, lastAccessFrameNum } ] of this.programCache ) {
if ( lastAccessFrameNum < this.frameNum - 1 ) {
entriesToDispose.push( [ source, prog ] );
}
}
// Try not to do more than `disposeLimit` disposes on a single frame,
// but never leave more than `deferLimit` waiting to be disposed
const disposeLimit = 1;
const deferLimit = 10;
const numToDispose = max( min( disposeLimit, entriesToDispose.length ), entriesToDispose.length - deferLimit );
for ( const [ source, prog ] of entriesToDispose.slice( 0, numToDispose ) ) {
prog.dispose( this.gl, this.glIncarnation );
this.programCache.delete( source );
}
// Don't prune again until next frame
this.programCacheLastPruneFrameNum = this.frameNum;
}
}
getTexture<M extends TextureMeta>( key: string, inputs: ReadonlyArray<unknown>, init: TextureInit<M> ): TextureInfo<M> {
this.pruneTextureCache( );
let en = this.textureCache.get( key );
if ( !en || !arrayAllEqual( inputs, en.inputs, equal ) ) {
const texture = this.gl.createTexture( );
this.gl.bindTexture( GL.TEXTURE_2D, texture );
const meta = init( this.gl, GL.TEXTURE_2D );
en = { inputs, info: { meta, texture }, lastAccessFrameNum: -1 };
this.textureCache.set( key, en );
}
en.lastAccessFrameNum = this.frameNum;
// See the `Context.getTexture()` doc comment for why this cast is acceptable
return en.info as TextureInfo<M>;
}
protected pruneTextureCache( ): void {
if ( this.frameNum > this.textureCacheLastPruneFrameNum ) {
// Identify entries ready to be disposed
const entriesToDispose = new Array<[ string, Nullable<WebGLTexture> ]>( );
for ( const [ key, { info, lastAccessFrameNum } ] of this.textureCache ) {
if ( lastAccessFrameNum < this.frameNum - 1 ) {
entriesToDispose.push( [ key, info.texture ] );
}
}
// Try not to do more than `disposeLimit` disposes on a single frame,
// but never leave more than `deferLimit` waiting to be disposed
const disposeLimit = 1;
const deferLimit = 10;
const numToDispose = max( min( disposeLimit, entriesToDispose.length ), entriesToDispose.length - deferLimit );
for ( const [ key, texture ] of entriesToDispose.slice( 0, numToDispose ) ) {
this.gl.deleteTexture( texture );
this.textureCache.delete( key );
}
// Don't prune again until next frame
this.textureCacheLastPruneFrameNum = this.frameNum;
}
}
getBuffer<M extends BufferMeta>( key: string, inputs: ReadonlyArray<unknown>, init: BufferInit<M> ): BufferInfo<M> {
this.pruneBufferCache( );
let en = this.bufferCache.get( key );
if ( !en || !arrayAllEqual( inputs, en.inputs, equal ) ) {
const buffer = this.gl.createBuffer( );
this.gl.bindBuffer( GL.ARRAY_BUFFER, buffer );
const meta = init( this.gl, GL.ARRAY_BUFFER );
en = { inputs, info: { meta, buffer }, lastAccessFrameNum: -1 };
this.bufferCache.set( key, en );
}
en.lastAccessFrameNum = this.frameNum;
// See the `Context.getBuffer()` doc comment for why this cast is acceptable
return en.info as BufferInfo<M>;
}
protected pruneBufferCache( ): void {
if ( this.frameNum > this.bufferCacheLastPruneFrameNum ) {
// Identify entries ready to be disposed
const entriesToDispose = new Array<[ string, Nullable<WebGLBuffer> ]>( );
for ( const [ key, { info, lastAccessFrameNum } ] of this.bufferCache ) {
if ( lastAccessFrameNum < this.frameNum - 1 ) {
entriesToDispose.push( [ key, info.buffer ] );
}
}
// Try not to do more than `disposeLimit` disposes on a single frame,
// but never leave more than `deferLimit` waiting to be disposed
const disposeLimit = 1;
const deferLimit = 10;
const numToDispose = max( min( disposeLimit, entriesToDispose.length ), entriesToDispose.length - deferLimit );
for ( const [ key, buffer ] of entriesToDispose.slice( 0, numToDispose ) ) {
this.gl.deleteBuffer( buffer );
this.bufferCache.delete( key );
}
// Don't prune again until next frame
this.bufferCacheLastPruneFrameNum = this.frameNum;
}