-
Notifications
You must be signed in to change notification settings - Fork 118
/
gestures.js
826 lines (661 loc) · 23.6 KB
/
gestures.js
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
/**
* Handles gesture recognition and inertial scrolling.
*/
function initializeTerminalGestures() {
const DEBUG = false;
// Determines the decay rate of the inertial scroll
// velocity.
// If 0.1, at the end of a second,
// the inertial scroll velocity is 1/10th of what it
// was at the beginning of the second.
const INERTIAL_SCROLL_DECAY_FACTOR = 0.1;
// Minimum lines/second for speed to trigger
// inertial scrolling.
const MIN_INERTIAL_SCROLL_START_SPEED_X = 40;
const MIN_INERTIAL_SCROLL_START_SPEED_Y = 15;
// While inertial scrolling, if the inertial scroll speed
// drops below this many lines per second, inertial scrolling
// stops.
const MIN_INERTIAL_SCROLL_CONTINUE_SPEED_X = 5;
const MIN_INERTIAL_SCROLL_CONTINUE_SPEED_Y = 3;
// Maximum number of lines/second we can scroll
const MAX_INERTIAL_SCROLL_SPEED = 2000;
// When we start inertial scrolling, scroll this many times faster
// than how fast we were scrolling with the user's finger/pointer
// on the screen.
const INITIAL_INERTIAL_SCROLL_VEL_MULTIPLIER = 1.4;
// Minimum number of characters a cursor must move to trigger a
//(non-arrow-)key press.
const HORIZ_KEYBOARD_KEYPRESS_CHARS = 7;
// If input is currently interpreted as a horizontal gesture,
// SNAP_BREAKAWAY_HORIZ_CHARS is the number of characters the
// pointer needs to move to switch the gesture to a vertical gesture.
const SNAP_BREAKAWAY_HORIZ_CHARS = 6;
const SNAP_BREAKAWAY_VERT_CHARS = 4;
// We don't know how long wheel gestures actually take, but we can
// guess. In seconds.
const MOUSE_WHEEL_GESTURE_EST_D_TIME = 0.6;
// Multiplies the number of lines by which mouse wheel gestures scroll.
const MOUSE_WHEEL_SENSITIVITY = 1;
// Maximum estimated mouse wheel gesture speed in lines/second.
const MOUSE_WHEEL_GESTURE_MAX_SPEED = 80;
// Discard wheel events that happen within this number of seconds after
// the previous.
const MIN_TIME_BETWEEN_WHEEL_GESTURES = 0.0;
// Minimum number of lines a single mouse wheel gesture can scroll.
const MOUSE_WHEEL_MIN_LINES = 1;
const MOUSE_WHEEL_INERTIAL_SCROLL_ENABLED = true;
// Things that should only be done once: Useful for
// debugging if we want to run this script multiple times
// in the same instance of a-Shell.
if (!window.gestures_) {
window.gestures_ = {};
// User-settable preferences
// Can be overridden after loading this script.
gestures_.preferences = {
swipeLeft: {
// At present, one-finger swipes are always arrow keys
2: '\x1b', // Two-finger left swipe: ESC
},
swipeRight: {
2: '\t', // Two-finger right swipe: tab
// TODO: \n doesn't act as expected:
// 3: '\n', // Three-finger right swipe: Enter
},
// True iff inertial "scrolling" can also trigger keypresses
// associated with gestures.
inertialScroll: {
allowNonarrowKeys: false,
},
};
// Debug view
window.gestures_.gestureStatus = document.createElement("div");
term_.document_.body.appendChild(gestures_.gestureStatus);
gestures_.gestureStatus.classList.add("gestureStatus");
// Events
gestures_.gesturePtrDown = () => {};
gestures_.gesturePtrMove = () => {};
gestures_.gesturePtrUp = () => {};
gestures_.gestureMouseWheel = () => {};
const targetElem = window.term_.scrollPort_.screen_;
targetElem.addEventListener('pointerdown', (evt) =>
gestures_.gesturePtrDown(evt));
targetElem.addEventListener('pointermove', (evt) =>
gestures_.gesturePtrMove(evt));
targetElem.addEventListener('pointerleave', (evt) =>
gestures_.gesturePtrUp(evt));
targetElem.addEventListener('pointerup', (evt) =>
gestures_.gesturePtrUp(evt));
window.term_.document_.body.addEventListener('keydown', (evt) =>
gestures_.handleKeyEvent(evt));
// Have listeners inside and outside the terminal iframe:
// We want to intercept the wheel event.
document.body.addEventListener('wheel', (evt) =>
gestures_.gestureMouseWheel(evt));
window.term_.document_.body.addEventListener('wheel', (evt) =>
gestures_.gestureMouseWheel(evt));
}
// When debugging (if another, older instance of gestures.js
// has already been run) ensure that we don't attempt to access
// properties of `undefined`.
gestures_.preferences.inertialScroll = gestures_.preferences.inertialScroll || {};
let gestureStatus = gestures_.gestureStatus;
// Style the debug output region.
gestureStatus.style = `
position: fixed;
right: 0;
bottom: 0;
z-index: 999;
max-width: 100px;
box-shadow: 0px 0px 4px rgba(200, 100, 100, 0.6);
border-top-left-radius: 5px;
background-color: rgba(255, 255, 255, 0.9);
padding: 3px;
color: black;
opacity: 0.5;
display: none;
font-family: monospace;
`;
// If we're not debugging, showDebugMsg shouldn't do anything.
let showDebugMsg = () => {};
// Debugging? Show the debug information window.
if (DEBUG) {
gestureStatus.style.display = "block";
gestureStatus.innerText = "...";
showDebugMsg = (text) => {
window.webkit.messageHandlers.aShell.postMessage('showDebugMsg:' + text);
gestureStatus.innerText = text;
};
}
// Attempts to determine whether `less` or `man` are currently running.
// Returns true if it thinks less or man is.
const isLessRunning = () => {
return window.commandRunning.search(new RegExp("(^less|^man|^perldoc|.*[|]\\s*less)")) == 0;
};
// Commands like less and vim generally use an alternate screen
// to display content.
// Sometimes, term_ is using the alternate screen with no command running.
const isUsingAlternateScreen = () => {
return ((!term_.isPrimaryScreen()) && (window.commandRunning.length > 0));
};
const moveCursor = (dx, dy) => {
let escPrefix = term_.keyboard.applicationCursor ? "\x1bO" : "\x1b[";
for (let i = 0; i <= Math.abs(dx) - 1; i++) {
term_.io.sendString(dx < 0 ? escPrefix + "D" : escPrefix + "C");
}
for (let i = 0; i <= Math.abs(dy) - 1; i++) {
term_.io.sendString(dy > 0 ? escPrefix + "B" : escPrefix + "A");
}
};
/// Returns the { width: px, height: px } size of a character in the terminal.
const getCharSize = () => {
return term_.scrollPort_.characterSize;
};
let origTouchFn = term_.scrollPort_.onTouch;
let disableTouchFn = undefined;
/// Temporarily turn off hterm's touch scrolling.
/// Does nothing if touch scrolling has already been disabled
/// by this method.
const disableHtermTouchScrolling = () => {
if (term_.scrollPort_.onTouch !== disableTouchFn) {
origTouchFn = term_.scrollPort_.onTouch;
term_.scrollPort_.onTouch = (evt) => {
origTouchFn(evt);
evt.preventDefault();
};
disableTouchFn = term_.scrollPort_.onTouch;
}
};
const enableHtermTouchScrolling = () => {
term_.scrollPort_.onTouch = origTouchFn;
};
// Returns true iff the last line is
//within a few lines of the cisible region.
const isLastLineNearVisible = () => {
const errorMargin = 4;
const scrollPort = term_.getScrollPort();
return term_.getRowCount() <= scrollPort.getTopRowIndex() + scrollPort.visibleRowCount + errorMargin;
};
/// Tracks the velocity of a given
//pointer.
class VelocityTracker {
constructor(ptrId) {
this.targetId_ = ptrId;
this.lastTime_ = (new Date()).getTime();
this.lastPosition_ = null;
this.velocity_ = [0, 0];
}
getVelocity() {
return this.velocity_;
}
handleEvt(evt) {
if (evt.pointerId != this.targetId_) {
return;
}
const nowTime = (new Date()).getTime();
let velocity = this.velocity_;
if (this.lastPosition_) {
const dx = (evt.pageX - this.lastPosition_[0]) / getCharSize().width;
const dy = (evt.pageY - this.lastPosition_[1]) / getCharSize().height;
const dt = (nowTime - this.lastTime_) / 1000;
// Too small of a time difference -> inaccurate velocities.
if (dt < 0.02) {
return;
}
// Average the current estimated
// velocity and the last for
// smoother changes in velocity.
velocity[0] += dx / dt;
velocity[1] += dy / dt;
velocity[0] /= 2;
velocity[1] /= 2;
}
this.lastTime_ = nowTime;
this.lastPosition_ = [ evt.pageX, evt.pageY ];
}
}
class Gesture {
/// [carryoverMomentum]: Any inertial scroll momentum (with mass=1)
/// remaining just before the start of this gesture. Copied during
/// initialization.
constructor(carryoverMomentum) {
// Last positions at which pointer
// data was eaten by an action.
this.ptrLastHandledPositions_ = {};
// VelocityTrackers for pointers
this.ptrVelocities_ = {};
// Set of pointer IDs that are currently
// 'down'.
this.ptrsDown_ = {};
this.ptrCount_ = 0;
// Number of unhandled characters in x and y directions
// by this.
this.bufferedDx_ = 0;
this.bufferedDy_ = 0;
// The gesture hasn't caused scrolling.
this.isScrollGesture_ = false;
// Maximum value of ptrsDown_
// during this gesture.
this.maxPtrCount_ = 0;
this.origMomentum_ = [carryoverMomentum[0], carryoverMomentum[1]];
this.gestureStartTime_ = (new Date()).getTime();
this.isHorizontal_ = Math.abs(this.origMomentum_[0]) > 0;
this.isVertical_ = Math.abs(this.origMomentum_[1]) > 0;
}
getPtrDownCount() {
return this.ptrCount_;
}
onPointerDown(evt) {
const ptrId = evt.pointerId;
// Do nothing if we're already tracking
// the pointer.
if (this.ptrsDown_[ptrId] != undefined) {
return;
}
this.ptrCount_++;
this.maxPtrCount_ = Math.max(this.ptrCount_, this.maxPtrCount_);
const velocityTracker = new VelocityTracker(ptrId);
velocityTracker.handleEvt(evt);
this.ptrLastHandledPositions_[ptrId] = [ evt.pageX, evt.pageY ];
this.ptrVelocities_[ptrId] = velocityTracker;
this.ptrsDown_[ptrId] = true;
}
onPointerMove(evt) {
const charWidth = getCharSize().width;
const charHeight = getCharSize().height;
const ptrId = evt.pointerId;
// Don't handle pointers that aren't down (e.g. mouse
// cursors).
if (!this.ptrsDown_[ptrId]) {
return;
}
// Use this event to update the tracked velocity.
this.ptrVelocities_[ptrId].handleEvt(evt);
let lastPos = this.ptrLastHandledPositions_[ptrId];
let dx = (evt.pageX - lastPos[0]) / charWidth;
let dy = (evt.pageY - lastPos[1]) / charHeight;
this.bufferedDx_ += dx / this.ptrCount_;
this.bufferedDy_ += dy / this.ptrCount_;
// Only act on the input when we've moved at least
// a character in either x or y (so that we have enough input to act on.
if (!this.shouldBufferDx_(this.bufferedDx_)) {
showDebugMsg("Horiz:" + dx);
this.handleHorizontal_(this.bufferedDx_, evt);
this.bufferedDx_ = 0;
}
if (Math.abs(this.bufferedDy_) > 0.5) {
showDebugMsg("Disabled hterm scrolling.");
// hterm's built-in touch scrolling can take effect
// after the user attemtpts to scroll less than a line.
// Don't do built-in touch scrolling.
disableHtermTouchScrolling();
}
if (!this.shouldBufferDy_(this.bufferedDy_)) {
showDebugMsg("Vert:" + dy);
this.handleVertical_(this.bufferedDy_, evt);
this.bufferedDy_ = 0;
}
lastPos[0] = evt.pageX;
lastPos[1] = evt.pageY;
}
onPointerUp(evt, startInertialScroll) {
const ptrId = evt.pointerId;
// If the pointer isn't down, discard
// the event.
if (!this.ptrsDown_[ptrId]) {
return;
}
const velocityTracker = this.ptrVelocities_[ptrId];
this.ptrCount_ --;
this.ptrsDown_[ptrId] = false;
velocityTracker.handleEvt(evt);
const velocity = velocityTracker.getVelocity();
const vx = velocity[0];
const vy = velocity[1];
const nowTime = (new Date()).getTime();
const dt = (nowTime - this.gestureStartTime_) / 1000;
this.startInertialScroll_(vx, vy, dt, startInertialScroll);
}
/// Decide whether to start inertial scrolling.
/// [vy] is the gesture's end velocity and [dt]
/// is the time it took to complete the gesture.
/// Returns true iff inertial scrolling was started.
startInertialScroll_(vx, vy, dt, startInertialScroll) {
if (!this.isHorizontal_) {
vx = 0;
}
if (!this.isVertical_) {
vy = 0;
}
if (this.ptrCount_ == 0) {
let carryoverX = this.origMomentum_[0] * Math.pow( INERTIAL_SCROLL_DECAY_FACTOR, dt);
let carryoverY = this.origMomentum_[1] * Math.pow(INERTIAL_SCROLL_DECAY_FACTOR, dt);
if (Math.sign(carryoverX) != Math.sign(vx)) {
carryoverX = 0;
}
if (Math.sign(carryoverY) != Math.sign(vy)) {
carryoverY = 0;
}
vx *= INITIAL_INERTIAL_SCROLL_VEL_MULTIPLIER;
vy *= INITIAL_INERTIAL_SCROLL_VEL_MULTIPLIER;
vx += carryoverX;
vy += carryoverY;
const isReasonableStartingVel =
Math.abs(vx) >= MIN_INERTIAL_SCROLL_START_SPEED_X
|| Math.abs(vy) >= MIN_INERTIAL_SCROLL_START_SPEED_Y;
if (isReasonableStartingVel) {
startInertialScroll(this, vx, vy);
return true;
}
}
return false;
}
/// Handle inertial scrolling.
/// [dx] and [dy] both have units of
/// characters and must have magnitude
/// at least one.
onInertialScrollUpdate(dx, dy) {
this.bufferedDx_ += dx;
this.bufferedDy_ += dy;
if (!this.shouldBufferDy_(this.bufferedDy_)) {
this.handleVertical_(this.bufferedDy_);
this.bufferedDy_ = 0;
}
if (!this.shouldBufferDx_(this.bufferedDx_)) {
// Only trigger nonarrowkey strokes if explicitly requested.
const allowNonarrowKeys = gestures_.preferences.inertialScroll.allowNonarrowKeys;
if (!this.isKeyboardGesture_ || allowNonarrowKeys) {
this.handleHorizontal_(this.bufferedDx_);
}
this.bufferedDx_ = 0;
}
}
/// Returns true iff we should keep
/// inertial scrolling if the current
/// inertial scroll velocity is
/// [vx, vy] in characters.
shouldKeepInertialScrolling(vx, vy) {
const vyIsEnough = (Math.abs(vy) >= MIN_INERTIAL_SCROLL_CONTINUE_SPEED_Y);
const vxIsEnough = (Math.abs(vx) >= MIN_INERTIAL_SCROLL_CONTINUE_SPEED_X);
return vxIsEnough || vyIsEnough;
}
// Returns true if the given [dx] shouldn't
// be handled, but rather, buffered.
shouldBufferDx_(dx) {
if (this.isVertical_ && !this.isHorizontal_) {
return Math.abs(dx) < SNAP_BREAKAWAY_HORIZ_CHARS;
}
if (this.maxPtrCount_ > 1) {
return Math.abs(dx) < HORIZ_KEYBOARD_KEYPRESS_CHARS;
}
return Math.abs(dx) < 1;
}
// Returns true if the given dy should be buffered,
// rather than handled.
shouldBufferDy_(dy) {
if (this.isHorizontal_ && !this.isVertical_) {
return Math.abs(dy) < SNAP_BREAKAWAY_VERT_CHARS;
}
return Math.abs(dy) < 1;
}
/// [dx] is in units of characters
/// and must have magnitude \geq 1
handleHorizontal_(dx) {
if (!isLastLineNearVisible()) {
return;
}
if (!this.isHorizontal_ && this.isVertical_) {
// If we're breaking away from a snap...
this.isVertical_ = false;
// Only move one char
dx = Math.sign(dx);
}
this.isHorizontal_ = true;
// Snap to a horizontal gesture.
if (!this.isVertical_) {
this.bufferedDy_ = 0;
}
if (this.maxPtrCount_ >= 2) {
// Stop scrolling, start keyboard gestures.
this.isKeyboardGesture_ = true;
this.isScrollGesture_ = false;
let key = null;
if (dx >= HORIZ_KEYBOARD_KEYPRESS_CHARS) {
key = gestures_.preferences.swipeRight[this.maxPtrCount_] || key;
} else if (dx <= -HORIZ_KEYBOARD_KEYPRESS_CHARS) {
key = gestures_.preferences.swipeLeft[this.maxPtrCount_] || key;
}
if (key) {
term_.io.sendString(key);
}
} else if (!isLessRunning()) {
// Horizontal gestures: Don't move cursor if in `man'
moveCursor(dx, 0);
}
term_.scrollEnd();
return this;
}
/// [dy] is in units of characters
/// and must have magnitude \geq 1.
handleVertical_(dy) {
if (!this.isVertical_ && this.isHorizontal_) {
// If we're breaking away from a snap,
// switch from horizontal to vertical.
this.isHorizontal_ = false;
// Only move one char when breaking away.
dy = Math.sign(dy);
}
this.isScrollGesture_ = true;
this.isVertical_ = true;
// We count arrow key gestures as ``scroll gestures''.
if (this.isKeyboardGesture_) {
this.isScrollGesture_ = false;
return;
}
// If not handling horizontal gestures,
// snap to a vertical gesture.
if (!this.isHorizontal_) {
this.bufferedDx_ = 0;
}
// Vertical gestures: Move cursor if in vim/less/man
if (isUsingAlternateScreen() || this.maxPtrCount_ == 2) {
// In less, cursor movement scrolls content,
// so invert the cursor movement direction for
// more natural scrolling.
if (isLessRunning()) {
moveCursor(0, -dy);
} else {
moveCursor(0, dy);
}
term_.scrollEnd();
} else {
// Otherwise, scroll.
for (let i = 1; i <= Math.abs(dy); i++) {
if (dy > 0) {
term_.scrollLineUp();
} else {
term_.scrollLineDown();
}
}
}
return this;
};
}
// Inertial scroll state.
let momentum = [0, 0];
let momentumLoopRunning = false;
// Start inertial scrolling with the initial velocity
// <vx, vy>. At present, vx is unused.
const startInertialScroll = (gesture, vx, vy) => {
let momentumLoop;
let lastT = (new Date()).getTime();
// Updates the "momentum" of the viewport in a loop.
momentumLoop = () => {
const p = momentum;
const nowT = (new Date()).getTime();
const dt = (nowT - lastT) / 1000.0;
const decay = Math.pow(INERTIAL_SCROLL_DECAY_FACTOR, dt);
showDebugMsg("P: <" + p[0] + ", " + p[1] + ">");
p[0] *= decay;
p[1] *= decay;
// If we're still scrolling fast enough, continue
// updating the momentum
if (gesture.shouldKeepInertialScrolling(p[0], p[1])) {
gesture.onInertialScrollUpdate(p[0] * dt, p[1] * dt);
momentumLoopRunning = true;
lastT = nowT;
requestAnimationFrame(momentumLoop);
} else {
p[0] = 0;
p[1] = 0;
momentumLoopRunning = false;
}
};
/// Returns v iff |v| is within (-MAX_INERTIAL_SCROLL_SPEED, MAX_INERTIAL_SCROLL_SPEED)
/// Otherwise, returns the maximum inertial scroll speed in the
/// direction of v.
const getClampedVelocity = (v) => {
if (Math.abs(v) > MAX_INERTIAL_SCROLL_SPEED) {
return Math.sign(v) * MAX_INERTIAL_SCROLL_SPEED;
}
return v;
};
// Clamp <vx, vy> because some programs break if given to much input/sec
vy = getClampedVelocity(vy);
vx = getClampedVelocity(vx);
momentum = [vx, vy];
if (!momentumLoopRunning) {
momentumLoop();
}
};
// Saves the terminal's onTouch function
// so we can use it to stop the terminal's
// default touchscreen scrolling.
let origTermTouchFn;
let currentGesture;
gestures_.gesturePtrDown = (evt) => {
showDebugMsg("Down@" + evt.pageX + "," + evt.pageY);
// Only interpret touch events as gestures
if (evt.pointerType != "touch") {
return;
}
try {
// If the user has selected something, exit. Let them continue
// the selection.
const selection = term_.document_.getSelection();
if (!selection.isCollapsed) {
evt.preventDefault(); // iOS: prevent WKWebView from scrolling too.
return;
}
// If the start of a new gesture (we may have lost
// the end of the previous):
if (evt.isPrimary || !currentGesture) {
currentGesture = new Gesture(momentum);
}
momentum = [ 0, 0 ];
currentGesture.onPointerDown(evt);
} catch(e) {
if (DEBUG) {
alert(e);
}
}
};
gestures_.gesturePtrMove = (evt) => {
// Currently being moved by the user: Make sure we aren't inertial
// scrolling.
momentum = [0, 0];
if (!currentGesture) {
return;
}
evt.preventDefault();
// Don't scroll the main window.
document.scrollingElement.scrollTop = 0;
try {
currentGesture.onPointerMove(evt);
} catch(e) {
if (DEBUG) {
alert(e);
}
}
};
gestures_.gesturePtrUp = (evt) => {
showDebugMsg(" Up @" + evt.pageX + "," + evt.pageY);
if (!currentGesture) {
return;
}
try {
currentGesture.onPointerUp(evt, startInertialScroll);
if (currentGesture.getPtrDownCount() == 0) {
currentGesture = undefined;
enableHtermTouchScrolling();
}
} catch(e) {
if (DEBUG) {
alert(e);
}
}
};
let lastWheelTime = (new Date()).getTime();
gestures_.gestureMouseWheel = (evt) => {
evt.preventDefault();
if (!currentGesture) {
// Not a horizontal gesture.
momentum[0] = 0;
currentGesture = new Gesture(momentum);
momentum = [ 0, 0 ];
}
const lineHeight = getCharSize().height;
const nowTime = (new Date()).getTime();
try {
// Inevert the scroll direction to match the system.
let dy = -evt.deltaY;
// Don't scroll the main window.
document.scrollingElement.scrollTop = 0;
// We don't really know how long the gesture took,
// but let's guess:
let dt = MOUSE_WHEEL_GESTURE_EST_D_TIME;
let actualDt = (nowTime - lastWheelTime) / 1000;
if (actualDt < MIN_TIME_BETWEEN_WHEEL_GESTURES) {
return;
}
// If the actual time between this and the last scroll gestures
// is less than our estimate, use the actual time as our estimate.
if (actualDt < dt) {
dt = actualDt;
}
// Scroll events deltaY can be specified in units other than
// lines. See
// https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
if (evt.deltaMode == WheelEvent.DOM_DELTA_PIXEL) {
dy /= lineHeight;
} else if (evt.deltaMode == WheelEvent.DOM_DELTA_PAGE) {
dy *= term_.screenSize.height / MOUSE_WHEEL_SENSITIVITY;
}
dy *= MOUSE_WHEEL_SENSITIVITY;
if (Math.abs(dy) < MOUSE_WHEEL_MIN_LINES) {
dy = Math.sign(dy) * MOUSE_WHEEL_MIN_LINES;
}
showDebugMsg("Wheel: " + dy);
currentGesture.handleVertical_(dy);
// Estimate a velocity and try to start inertial scrolling.
let estimatedVy = dy / dt;
// Bound the estimated velocity.
if (Math.abs(estimatedVy) > MOUSE_WHEEL_GESTURE_MAX_SPEED) {
estimatedVy = Math.sign(estimatedVy) * MOUSE_WHEEL_GESTURE_MAX_SPEED;
}
if (MOUSE_WHEEL_INERTIAL_SCROLL_ENABLED) {
currentGesture.startInertialScroll_(0, estimatedVy, dt, startInertialScroll);
}
currentGesture = undefined;
} catch(e) {
if (DEBUG) {
alert(e);
}
}
lastWheelTime = nowTime;
};
// Stop inertial scrolling if the user presses a key:
gestures_.handleKeyEvent = (evt) => {
momentum = [0, 0];
};
}