1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
8 * A class that manages updating the browser with zoom changes.
12 * Constructs a ZoomManager
13 * @param {!Viewport} viewport A Viewport for which to manage zoom.
14 * @param {Function} setBrowserZoomFunction A function that sets the browser
15 * zoom to the provided value.
16 * @param {number} defaultZoom The default browser zoom level.
18 constructor(viewport, setBrowserZoomFunction, defaultZoom) {
19 this.viewport_ = viewport;
20 this.setBrowserZoomFunction_ = setBrowserZoomFunction;
21 this.browserZoom_ = defaultZoom;
22 this.changingBrowserZoom_ = null;
26 * Invoked when a browser-initiated zoom-level change occurs.
27 * @param {number} newZoom the zoom level to zoom to.
29 onBrowserZoomChange(newZoom) {
30 // If we are changing the browser zoom level, ignore any browser zoom level
31 // change events. Either, the change occurred before our update and will be
32 // overwritten, or the change being reported is the change we are making,
33 // which we have already handled.
34 if (this.changingBrowserZoom_)
37 if (this.floatingPointEquals(this.browserZoom_, newZoom))
40 this.browserZoom_ = newZoom;
41 this.viewport_.setZoom(newZoom);
45 * Invoked when an extension-initiated zoom-level change occurs.
48 // If we are already changing the browser zoom level in response to a
49 // previous extension-initiated zoom-level change, ignore this zoom change.
50 // Once the browser zoom level is changed, we check whether the extension's
51 // zoom level matches the most recently sent zoom level.
52 if (this.changingBrowserZoom_)
55 let zoom = this.viewport_.zoom;
56 if (this.floatingPointEquals(this.browserZoom_, zoom))
59 this.changingBrowserZoom_ = this.setBrowserZoomFunction_(zoom).then(
61 this.browserZoom_ = zoom;
62 this.changingBrowserZoom_ = null;
64 // The extension's zoom level may have changed while the browser zoom
65 // change was in progress. We call back into onPdfZoomChange to ensure the
66 // browser zoom is up to date.
67 this.onPdfZoomChange();
72 * Returns whether two numbers are approximately equal.
73 * @param {number} a The first number.
74 * @param {number} b The second number.
76 floatingPointEquals(a, b) {
77 let MIN_ZOOM_DELTA = 0.01;
78 // If the zoom level is close enough to the current zoom level, don't
79 // change it. This avoids us getting into an infinite loop of zoom changes
80 // due to floating point error.
81 return Math.abs(a - b) <= MIN_ZOOM_DELTA;