This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 305
/
BrowserElementScrolling.js
758 lines (633 loc) · 25.1 KB
/
BrowserElementScrolling.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
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 sts=2 et: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
const ContentPanning = {
// Are we listening to touch or mouse events?
watchedEventsType: '',
// Are mouse events being delivered to this content along with touch
// events, in violation of spec?
hybridEvents: false,
init: function cp_init() {
var events;
try {
content.document.createEvent('TouchEvent');
events = ['touchstart', 'touchend', 'touchmove'];
this.watchedEventsType = 'touch';
#ifdef MOZ_WIDGET_GONK
// The gonk widget backend does not deliver mouse events per
// spec. Third-party content isn't exposed to this behavior,
// but that behavior creates some extra work for us here.
let appInfo = Cc["@mozilla.org/xre/app-info;1"];
let isParentProcess =
!appInfo || appInfo.getService(Ci.nsIXULRuntime)
.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
this.hybridEvents = isParentProcess;
#endif
} catch(e) {
// Touch events aren't supported, so fall back on mouse.
events = ['mousedown', 'mouseup', 'mousemove'];
this.watchedEventsType = 'mouse';
}
events.forEach(function(type) {
addEventListener(type, ContentPanning, false);
});
addMessageListener("Viewport:Change", this._recvViewportChange.bind(this));
addMessageListener("Gesture:DoubleTap", this._recvDoubleTap.bind(this));
},
handleEvent: function cp_handleEvent(evt) {
if (evt.defaultPrevented)
return;
switch (evt.type) {
case 'mousedown':
case 'touchstart':
this.onTouchStart(evt);
break;
case 'mousemove':
case 'touchmove':
this.onTouchMove(evt);
break;
case 'mouseup':
case 'touchend':
this.onTouchEnd(evt);
break;
case 'click':
evt.stopPropagation();
evt.preventDefault();
let target = evt.target;
let view = target.ownerDocument ? target.ownerDocument.defaultView
: target;
view.removeEventListener('click', this, true, true);
break;
}
},
position: new Point(0 , 0),
findPrimaryPointer: function cp_findPrimaryPointer(touches) {
if (!('primaryPointerId' in this))
return null;
for (let i = 0; i < touches.length; i++) {
if (touches[i].identifier === this.primaryPointerId) {
return touches[i];
}
}
return null;
},
onTouchStart: function cp_onTouchStart(evt) {
let screenX, screenY;
if (this.watchedEventsType == 'touch') {
if ('primaryPointerId' in this) {
return;
}
let firstTouch = evt.changedTouches[0];
this.primaryPointerId = firstTouch.identifier;
this.pointerDownTarget = firstTouch.target;
screenX = firstTouch.screenX;
screenY = firstTouch.screenY;
} else {
this.pointerDownTarget = evt.target;
screenX = evt.screenX;
screenY = evt.screenY;
}
this.dragging = true;
this.panning = false;
let oldTarget = this.target;
[this.target, this.scrollCallback] = this.getPannable(this.pointerDownTarget);
// If we found a target, that means we have found a scrollable subframe. In
// this case, and if we are using async panning and zooming on the parent
// frame, inform the pan/zoom controller that it should not attempt to
// handle any touch events it gets until the next batch (meaning the next
// time we get a touch end).
if (this.target != null && this._asyncPanZoomForViewportFrame) {
this.detectingScrolling = true;
var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
os.notifyObservers(docShell, 'detect-scrollable-subframe', null);
}
// If we have a pointer down target and we're not async
// pan/zooming, we may need to fill in for EventStateManager in
// setting the active state on the target element. Set a timer to
// ensure the pointer-down target is active. (If it's already
// active, the timer is a no-op.)
if (this.pointerDownTarget !== null && !this.detectingScrolling) {
// If there's no possibility this is a drag/pan, activate now.
// Otherwise wait a little bit to see if the gesture isn't a
// tap.
if (this.target === null) {
this.notify(this._activationTimer);
} else {
this._activationTimer.initWithCallback(this,
this._activationDelayMs,
Ci.nsITimer.TYPE_ONE_SHOT);
}
}
// If there is a pan animation running (from a previous pan gesture) and
// the user touch back the screen, stop this animation immediatly and
// prevent the possible click action if the touch happens on the same
// target.
this.preventNextClick = false;
if (KineticPanning.active) {
KineticPanning.stop();
if (oldTarget && oldTarget == this.target)
this.preventNextClick = true;
}
this.position.set(screenX, screenY);
KineticPanning.record(new Point(0, 0), evt.timeStamp);
},
onTouchEnd: function cp_onTouchEnd(evt) {
let touch = null;
if (!this.dragging ||
(this.watchedEventsType == 'touch' &&
!(touch = this.findPrimaryPointer(evt.changedTouches)))) {
return;
}
// !isPan() and evt.detail should always give the same answer here
// since they use the same heuristics, but use the native gecko
// computation when possible.
//
// NB: when we're using touch events, then !KineticPanning.isPan()
// => this.panning, so we'll never attempt to block the click
// event. That's OK however, because we won't fire a synthetic
// click when we're using touch events and this touch series
// wasn't a "tap" gesture.
let click = (this.watchedEventsType == 'mouse') ?
evt.detail : !KineticPanning.isPan();
// Additionally, if we're seeing non-compliant hybrid events, a
// "real" click will be generated if we started and ended on the
// same element.
if (this.hybridEvents) {
let target =
content.document.elementFromPoint(touch.clientX, touch.clientY);
click |= (target === this.pointerDownTarget);
}
if (this.target && click && (this.panning || this.preventNextClick)) {
let target = this.target;
let view = target.ownerDocument ? target.ownerDocument.defaultView
: target;
view.addEventListener('click', this, true, true);
}
this._resetActive();
this.dragging = false;
this.detectingScrolling = false;
delete this.primaryPointerId;
this._activationTimer.cancel();
if (this.panning) {
KineticPanning.start(this);
}
},
// True when there's an async pan-zoom controll watching the
// outermost scrollable frame, and we're waiting to see whether
// we're going to take over from it and synchronously scroll an
// inner scrollable frame.
detectingScrolling: false,
onTouchMove: function cp_onTouchMove(evt) {
if (!this.dragging)
return;
let screenX, screenY;
if (this.watchedEventsType == 'touch') {
let primaryTouch = this.findPrimaryPointer(evt.changedTouches);
if (evt.touches.length > 1 || !primaryTouch)
return;
screenX = primaryTouch.screenX;
screenY = primaryTouch.screenY;
} else {
screenX = evt.screenX;
screenY = evt.screenY;
}
let current = this.position;
let delta = new Point(screenX - current.x, screenY - current.y);
current.set(screenX, screenY);
KineticPanning.record(delta, evt.timeStamp);
// There's no possibility of us panning anything.
if (!this.scrollCallback) {
return;
}
let isPan = KineticPanning.isPan();
if (this.detectingScrolling) {
this.detectingScrolling = false;
// Stop async-pan-zooming if the user is panning the subframe.
if (isPan) {
// We're going to drive synchronously scrolling an inner frame.
Services.obs.notifyObservers(docShell, 'cancel-default-pan-zoom', null);
} else {
// Let AsyncPanZoomController handle the scrolling gesture.
this.scrollCallback = null;
return;
}
}
this.scrollCallback(delta.scale(-1));
// If a pan action happens, cancel the active state of the
// current target.
if (!this.panning && isPan) {
this.panning = true;
this._resetActive();
this._activationTimer.cancel();
}
if (this.panning) {
evt.stopPropagation();
evt.preventDefault();
}
},
// nsITimerCallback
notify: function cp_notify(timer) {
this._setActive(this.pointerDownTarget);
},
onKineticBegin: function cp_onKineticBegin(evt) {
},
onKineticPan: function cp_onKineticPan(delta) {
return !this.scrollCallback(delta);
},
onKineticEnd: function cp_onKineticEnd() {
if (!this.dragging)
this.scrollCallback = null;
},
getPannable: function cp_getPannable(node) {
let pannableNode = this._findPannable(node);
if (pannableNode) {
return [pannableNode, this._generateCallback(pannableNode)];
}
return [null, null];
},
_findPannable: function cp_findPannable(node) {
if (!(node instanceof Ci.nsIDOMHTMLElement) || node.tagName == 'HTML') {
return null;
}
let nodeContent = node.ownerDocument.defaultView;
while (!(node instanceof Ci.nsIDOMHTMLBodyElement)) {
let style = nodeContent.getComputedStyle(node, null);
let overflow = [style.getPropertyValue('overflow'),
style.getPropertyValue('overflow-x'),
style.getPropertyValue('overflow-y')];
let rect = node.getBoundingClientRect();
let isAuto = (overflow.indexOf('auto') != -1 &&
(rect.height < node.scrollHeight ||
rect.width < node.scrollWidth));
let isScroll = (overflow.indexOf('scroll') != -1);
let isScrollableTextarea = (node.tagName == 'TEXTAREA' &&
(node.scrollHeight > node.clientHeight ||
node.scrollWidth > node.clientWidth ||
('scrollLeftMax' in node && node.scrollLeftMax > 0) ||
('scrollTopMax' in node && node.scrollTopMax > 0)));
if (isScroll || isAuto || isScrollableTextarea) {
return node;
}
node = node.parentNode;
}
if (ContentPanning._asyncPanZoomForViewportFrame &&
nodeContent === content) {
// The parent context is asynchronously panning and zooming our
// root scrollable frame, so don't use our synchronous fallback.
return null;
}
if (nodeContent.scrollMaxX || nodeContent.scrollMaxY) {
return nodeContent;
}
return null;
},
_generateCallback: function cp_generateCallback(content) {
let firstScroll = true;
let target;
let isScrolling = false;
let oldX, oldY, newX, newY;
let win, doc, htmlNode, bodyNode;
function doScroll(node, delta) {
if (node instanceof Ci.nsIDOMHTMLElement) {
oldX = node.scrollLeft, oldY = node.scrollTop;
node.scrollLeft += delta.x;
node.scrollTop += delta.y;
newX = node.scrollLeft, newY = node.scrollTop;
return (newX != oldX || newY != oldY);
} else if (node instanceof Ci.nsIDOMWindow) {
win = node;
doc = win.document;
// "overflow:hidden" on either the <html> or the <body> node should
// prevent the user from scrolling the root viewport.
if (doc instanceof Ci.nsIDOMHTMLDocument) {
htmlNode = doc.documentElement;
bodyNode = doc.body;
if (win.getComputedStyle(htmlNode, null).overflowX == "hidden" ||
win.getComputedStyle(bodyNode, null).overflowX == "hidden") {
delta.x = 0;
}
if (win.getComputedStyle(htmlNode, null).overflowY == "hidden" ||
win.getComputedStyle(bodyNode, null).overflowY == "hidden") {
delta.y = 0;
}
}
oldX = node.scrollX, oldY = node.scrollY;
node.scrollBy(delta.x, delta.y);
newX = node.scrollX, newY = node.scrollY;
return (newX != oldX || newY != oldY);
}
// If we get here, |node| isn't an HTML element and it's not a window,
// but findPannable apparently thought it was scrollable... What is it?
return false;
};
function scroll(delta) {
for (target = content; target;
target = ContentPanning._findPannable(target.parentNode)) {
isScrolling = doScroll(target, delta);
if (isScrolling || !firstScroll) {
break;
}
}
if (isScrolling) {
if (firstScroll) {
content = target; // set scrolling target to the first scrolling region
}
firstScroll = false; // lockdown the scrolling target after a success scrolling
}
return isScrolling;
}
return scroll;
},
get _domUtils() {
delete this._domUtils;
return this._domUtils = Cc['@mozilla.org/inspector/dom-utils;1']
.getService(Ci.inIDOMUtils);
},
get _activationTimer() {
delete this._activationTimer;
return this._activationTimer = Cc["@mozilla.org/timer;1"]
.createInstance(Ci.nsITimer);
},
get _activationDelayMs() {
let delay = Services.prefs.getIntPref('ui.touch_activation.delay_ms');
delete this._activationDelayMs;
return this._activationDelayMs = delay;
},
_resetActive: function cp_resetActive() {
let elt = this.target || this.pointerDownTarget;
let root = elt.ownerDocument || elt.document;
this._setActive(root.documentElement);
},
_setActive: function cp_setActive(elt) {
const kStateActive = 0x00000001;
this._domUtils.setContentState(elt, kStateActive);
},
get _asyncPanZoomForViewportFrame() {
return docShell.asyncPanZoomEnabled;
},
_recvViewportChange: function(data) {
let metrics = data.json;
this._viewport = new Rect(metrics.x, metrics.y,
metrics.viewport.width,
metrics.viewport.height);
this._cssCompositedRect = new Rect(metrics.x, metrics.y,
metrics.cssCompositedRect.width,
metrics.cssCompositedRect.height);
this._cssPageRect = new Rect(metrics.cssPageRect.x,
metrics.cssPageRect.y,
metrics.cssPageRect.width,
metrics.cssPageRect.height);
},
_recvDoubleTap: function(data) {
let data = data.json;
// We haven't received a metrics update yet; don't do anything.
if (this._viewport == null) {
return;
}
let win = content;
let element = ElementTouchHelper.anyElementFromPoint(win, data.x, data.y);
if (!element) {
this._zoomOut();
return;
}
while (element && !this._shouldZoomToElement(element))
element = element.parentNode;
if (!element) {
this._zoomOut();
} else {
const margin = 15;
let rect = ElementTouchHelper.getBoundingContentRect(element);
let cssPageRect = this._cssPageRect;
let viewport = this._viewport;
let bRect = new Rect(Math.max(cssPageRect.x, rect.x - margin),
rect.y,
rect.w + 2 * margin,
rect.h);
// constrict the rect to the screen's right edge
bRect.width = Math.min(bRect.width, cssPageRect.right - bRect.x);
// if the rect is already taking up most of the visible area and is stretching the
// width of the page, then we want to zoom out instead.
if (this._isRectZoomedIn(bRect, this._cssCompositedRect)) {
this._zoomOut();
return;
}
rect.x = Math.round(bRect.x);
rect.y = Math.round(bRect.y);
rect.w = Math.round(bRect.width);
rect.h = Math.round(bRect.height);
// if the block we're zooming to is really tall, and the user double-tapped
// more than a screenful of height from the top of it, then adjust the y-coordinate
// so that we center the actual point the user double-tapped upon. this prevents
// flying to the top of a page when double-tapping to zoom in (bug 761721).
// the 1.2 multiplier is just a little fuzz to compensate for bRect including horizontal
// margins but not vertical ones.
let cssTapY = viewport.y + data.y;
if ((bRect.height > rect.h) && (cssTapY > rect.y + (rect.h * 1.2))) {
rect.y = cssTapY - (rect.h / 2);
}
var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
os.notifyObservers(docShell, 'browser-zoom-to-rect', JSON.stringify(rect));
}
},
_shouldZoomToElement: function(aElement) {
let win = aElement.ownerDocument.defaultView;
if (win.getComputedStyle(aElement, null).display == "inline")
return false;
if (aElement instanceof Ci.nsIDOMHTMLLIElement)
return false;
if (aElement instanceof Ci.nsIDOMHTMLQuoteElement)
return false;
return true;
},
_zoomOut: function() {
let rect = new Rect(0, 0, 0, 0);
var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
os.notifyObservers(docShell, 'browser-zoom-to-rect', JSON.stringify(rect));
},
_isRectZoomedIn: function(aRect, aViewport) {
// This function checks to see if the area of the rect visible in the
// viewport (i.e. the "overlapArea" variable below) is approximately
// the max area of the rect we can show.
let vRect = new Rect(aViewport.x, aViewport.y, aViewport.width, aViewport.height);
let overlap = vRect.intersect(aRect);
let overlapArea = overlap.width * overlap.height;
let availHeight = Math.min(aRect.width * vRect.height / vRect.width, aRect.height);
let showing = overlapArea / (aRect.width * availHeight);
let ratioW = (aRect.width / vRect.width);
let ratioH = (aRect.height / vRect.height);
return (showing > 0.9 && (ratioW > 0.9 || ratioH > 0.9));
}
};
ContentPanning.init();
// Min/max velocity of kinetic panning. This is in pixels/millisecond.
const kMinVelocity = 0.4;
const kMaxVelocity = 6;
// Constants that affect the "friction" of the scroll pane.
const kExponentialC = 1000;
const kPolynomialC = 100 / 1000000;
// How often do we change the position of the scroll pane?
// Too often and panning may jerk near the end.
// Too little and panning will be choppy. In milliseconds.
const kUpdateInterval = 16;
// The numbers of momentums to use for calculating the velocity of the pan.
// Those are taken from the end of the action
const kSamples = 5;
const KineticPanning = {
_position: new Point(0, 0),
_velocity: new Point(0, 0),
_acceleration: new Point(0, 0),
get active() {
return this.target !== null;
},
target: null,
start: function kp_start(target) {
this.target = target;
// Calculate the initial velocity of the movement based on user input
let momentums = this.momentums.slice(-kSamples);
let distance = new Point(0, 0);
momentums.forEach(function(momentum) {
distance.add(momentum.dx, momentum.dy);
});
let elapsed = momentums[momentums.length - 1].time - momentums[0].time;
function clampFromZero(x, min, max) {
if (x >= 0)
return Math.max(min, Math.min(max, x));
return Math.min(-min, Math.max(-max, x));
}
let velocityX = clampFromZero(distance.x / elapsed, 0, kMaxVelocity);
let velocityY = clampFromZero(distance.y / elapsed, 0, kMaxVelocity);
let velocity = this._velocity;
velocity.set(Math.abs(velocityX) < kMinVelocity ? 0 : velocityX,
Math.abs(velocityY) < kMinVelocity ? 0 : velocityY);
this.momentums = [];
// Set acceleration vector to opposite signs of velocity
function sign(x) {
return x ? (x > 0 ? 1 : -1) : 0;
}
this._acceleration.set(velocity.clone().map(sign).scale(-kPolynomialC));
// Reset the position
this._position.set(0, 0);
this._startAnimation();
this.target.onKineticBegin();
},
stop: function kp_stop() {
if (!this.target)
return;
this.momentums = [];
this.distance.set(0, 0);
this.target.onKineticEnd();
this.target = null;
},
momentums: [],
record: function kp_record(delta, timestamp) {
this.momentums.push({ 'time': timestamp, 'dx' : delta.x, 'dy' : delta.y });
this.distance.add(delta.x, delta.y);
},
get threshold() {
let dpi = content.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils)
.displayDPI;
let threshold = Services.prefs.getIntPref('ui.dragThresholdX') / 240 * dpi;
delete this.threshold;
return this.threshold = threshold;
},
distance: new Point(0, 0),
isPan: function cp_isPan() {
return (Math.abs(this.distance.x) > this.threshold ||
Math.abs(this.distance.y) > this.threshold);
},
_startAnimation: function kp_startAnimation() {
let c = kExponentialC;
function getNextPosition(position, v, a, t) {
// Important traits for this function:
// p(t=0) is 0
// p'(t=0) is v0
//
// We use exponential to get a smoother stop, but by itself exponential
// is too smooth at the end. Adding a polynomial with the appropriate
// weight helps to balance
position.set(v.x * Math.exp(-t / c) * -c + a.x * t * t + v.x * c,
v.y * Math.exp(-t / c) * -c + a.y * t * t + v.y * c);
}
let startTime = content.mozAnimationStartTime;
let elapsedTime = 0, targetedTime = 0, averageTime = 0;
let velocity = this._velocity;
let acceleration = this._acceleration;
let position = this._position;
let nextPosition = new Point(0, 0);
let delta = new Point(0, 0);
let callback = (function(timestamp) {
if (!this.target)
return;
// To make animation end fast enough but to keep smoothness, average the
// ideal time frame (smooth animation) with the actual time lapse
// (end fast enough).
// Animation will never take longer than 2 times the ideal length of time.
elapsedTime = timestamp - startTime;
targetedTime += kUpdateInterval;
averageTime = (targetedTime + elapsedTime) / 2;
// Calculate new position.
getNextPosition(nextPosition, velocity, acceleration, averageTime);
delta.set(Math.round(nextPosition.x - position.x),
Math.round(nextPosition.y - position.y));
// Test to see if movement is finished for each component.
if (delta.x * acceleration.x > 0)
delta.x = position.x = velocity.x = acceleration.x = 0;
if (delta.y * acceleration.y > 0)
delta.y = position.y = velocity.y = acceleration.y = 0;
if (velocity.equals(0, 0) || delta.equals(0, 0)) {
this.stop();
return;
}
position.add(delta);
if (this.target.onKineticPan(delta.scale(-1))) {
this.stop();
return;
}
content.mozRequestAnimationFrame(callback);
}).bind(this);
content.mozRequestAnimationFrame(callback);
}
};
const ElementTouchHelper = {
anyElementFromPoint: function(aWindow, aX, aY) {
let cwu = aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
let elem = cwu.elementFromPoint(aX, aY, true, true);
let HTMLIFrameElement = Ci.nsIDOMHTMLIFrameElement;
let HTMLFrameElement = Ci.nsIDOMHTMLFrameElement;
while (elem && (elem instanceof HTMLIFrameElement || elem instanceof HTMLFrameElement)) {
let rect = elem.getBoundingClientRect();
aX -= rect.left;
aY -= rect.top;
cwu = elem.contentDocument.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
elem = cwu.elementFromPoint(aX, aY, true, true);
}
return elem;
},
getBoundingContentRect: function(aElement) {
if (!aElement)
return {x: 0, y: 0, w: 0, h: 0};
let document = aElement.ownerDocument;
while (document.defaultView.frameElement)
document = document.defaultView.frameElement.ownerDocument;
let cwu = document.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
let scrollX = {}, scrollY = {};
cwu.getScrollXY(false, scrollX, scrollY);
let r = aElement.getBoundingClientRect();
// step out of iframes and frames, offsetting scroll values
for (let frame = aElement.ownerDocument.defaultView; frame.frameElement && frame != content; frame = frame.parent) {
// adjust client coordinates' origin to be top left of iframe viewport
let rect = frame.frameElement.getBoundingClientRect();
let left = frame.getComputedStyle(frame.frameElement, "").borderLeftWidth;
let top = frame.getComputedStyle(frame.frameElement, "").borderTopWidth;
scrollX.value += rect.left + parseInt(left);
scrollY.value += rect.top + parseInt(top);
}
return {x: r.left + scrollX.value,
y: r.top + scrollY.value,
w: r.width,
h: r.height };
}
};