Files
palemoon27/browser/modules/WindowsPreviewPerTab.jsm
roytam1 573e7dd316 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1220564 - Remove legacy generator comprehensions. (r=Waldo) (762c83b25f)
- Bug 1220564 - Update and remove obsolete jit-tests. (r=Waldo) (cd56eda223)
- Bug 1220564 - Update and remove obsolete JS reftests. (r=Waldo) (3a36a4f4e5)
- Bug 1139736 - Part 1: map settings "network.debugging.enabled" to preference. r=fabrice (594fc01429)
- Bug 1210740 - Expose tracking protection setting to Gaia, r=fabrice (38daca12a0)
- Bug 1163956 - Modify updatePath to fixed char array. r=gsvelto (56fec01263)
- Bug 1229620 - Replace #ifdefs in b2g/ code by AppConstants r=timdream (7cc5dce39d)
- Bug 1214515 - PersistentDataBlock b2g component implementation. r=gerard-majax (eadc3d53ca)
- Bug 1220564 - Update chrome code uses of genexprs and legacy comprehensions. (r=billm) (0dea4b39fd)
- Bug 1234738 - Emit ALIASEDVAR ops or block-scoped lexicals right below global level. (r=jorendorff) (7c8eb66a00)
- Bug 1221144 - Part 1: Make static scope objects a separate class hierarchy from the runtime ScopeObjects. r=shu. (1c74551384)
- Bug 1237564 - Fix minor bug with a lexical declaration shadowing a non-configurable global. r=shu (fcb3040151)
- Bug 1237501. Actually create a baseline IC for a JSNative accessor property get that's unshadowed on a DOM proxy. We apparently failed to ever do this. r=jandem (e2e4222197)
- Bug 1234663: SharedStubs: Use correct fallbackstubspace to keep stubs# , r=jandm (591fbcd885)
- Bug 1234414 - Consider the initial values at block entry to be within block note bounds. (r=jorendorff) (321a016320)
- Bug 1214059: Baseline: Enable switch to debug mode at function entry, r=jandem (b803a7206d)
- Bug 1233179 - Allow bytecode emitter to access module environment before module declarations are instantiated r=shu (e6d23fc2af)
- Bug 1220564 - Remove legacy array comprehensions. (r=Waldo) (73973ac52e)
- Bug 1228976 - Remove array comprehensions from Places .r=mak (10274eaaef)
- Bug 1239753 - FirefoxProfileMigrator is broken after generator expression removal. r=gijs (da1fbf8ca7)
- Bug 1229519: Fix toolkit/components/thumbnails to pass eslint checks. r=rhelmer (2a710ab167)
- Bug 1041537 - Prevent ContentSearch from leaking the browser if it's still processing a message while the test suite shuts down r=adw (b62ad37cdd)
- Bug 1204361 - New Tab Page doesn't honor my "x" clicks on Suggested Tiles; instead of removing the tile, it swaps in a very similar one. [r=emtwo] (3260d90a44)
- Bug 1119442 - Update hang ui, remove drop down options and replace with simpler 'just fix it' button interface. r=mconley (29046ca45c)
- Bug 1233470 - make browser/modules eslintable, r=Mossop (aeb556ba66)
- Bug 1236875 - Fix BytecodeEmitter::atBodyLevel() for modules r=efaust (2fca7e49f2)
- Bug 1221144 - Part 2: Rename static scope classes away from "ScopeObject". r=shu. (dc2f110ef2)
- Bug 1221144 - Part 3: Rename variables, arguments, and fields that point to static scopes away from names that indicate objects, like "scopeObj" and "blockObj". r=shu. (33d1504d55)
- Bug 1221144 - Part 4: Rename a few functions about scopes away from names that indicate objects, like js::CloneNestedScopeObject. r=shu. (9551101431)
- Bug 1221144 - Part 5: Delete class js::BlockObject. r=shu. (5b4746c5a5)
- Bug 1221144 - Part 6: Introduce StaticModuleScope. Pretty silly so far. Bindings are still stored in the script. r=shu. (b90c20e255)
- Bug 1221144 - Part 7: Introduce StaticFunctionScope, same story. r=shu. (eb39a2359b)
- Bug 1221144 - Part 8: Change C++ type of static scopes everywhere from JSObject* to StaticScope*. r=shu. (f1edf54510)
- Bug 1221144 - Part 9: A few more JSObject* -> StaticScope* changes. r=shu. (000d52709b)
- Bug 1221144 - Part 10: Delete an obsolete comment. r=shu. (f0655f736b)
- Bug 1221144 - Part 12: Remove StaticScopeIter<>::IsStaticScope. r=shu. (9653f2c544)
- Bug 1221144 - Part 13: Change DumpStaticScopeChain to include a function scope when available, on the theory that more information is better. r=shu. (7dd24064c8)
- Bug 1221144 - Part 14: Handlify scope arguments to methods around FunctionBox creation. r=shu. (902020bf08)
- Fix busted test checked in with bug 1221144. r=red. (9d8ff7f3be)
- Bug 1235590 - Allow redeclaring block-scoped functions and warn about deprecation for now. (r=jorendorff) (1e8a6ca2bb)
- Bug 1245321 - Merge the object and regexp lists in script data. r=jorendorff. (4f429f9d7b)
- Bug 1230633 - User is unable to enable full devtools/developer mode r=me (a9ee457fec)
- backout Bug 1221144 for perf regression (0c24810d37)
- Bug 1207490 - Part 11: Remove use of expression closure from browser/modules/DirectoryLinksProvider.jsm. r=Gijs (f7f844130a)
- Bug 1240245 - Disable data collection for new-tab page r=jaws (a7a40f394b)
- Bug 526620 - Intelligently invalidate other tabs' previews on resize, flushing their layout when necessary. r=jimm (30ce73281d)
- Bug 1122356 - Remove use of expression closures from WindowsPreviewPerTab.jsm. r=dao (bb3fde452e)
- Bug 1207490 - Part 15: Remove use of expression closure from browser/modules/WindowsPreviewPerTab.jsm. r=Gijs (3904885596)
- Bug 1233925 - Treat functions with rest more like functions with lazy arguments. r=nbp (7e6ec266e1)
- Bug 1243397 - Ensure enough ballast space in LiveRange::FallibleNew. r=h4writer (d36353ed01)
- Bug 1229636 - Remove new tab first time use message. r=gijs (57a1df93cf)
- Bug 1245154 - Ensure enough ballast space in LiveBundle::FallibleNew. r=h4writer (46863982c0)
- Bug 1245176 - Ensure enough ballast space in BacktrackingAllocator::reifyAllocations. r=h4writer (289d71a6cb)
- Bug 1231024 - Fix printing of live bundle information in regalloc spew, r=jonco. (fb4449119f)
- Bug 1244215 part 1 - Store frame header size in the frame descriptor. r=nbp (e666793f3c)
- Bug 1234425 - Skip accessor IC frames in GetPcScript. r=h4writer (5981b361ad)
- Bug 1244215 part 2 - Get rid of unwound frames and clean up a lot of code in this area. r=nbp (96de454424)
- Bug 1244215 part 3 - Remove lazy link frames, they're no longer necessary. r=nbp (32637085a0)
- Bug 1225041 - Implement ES6 Annex B.3.5. (r=jorendorff) (718e230725)
- Bug 1224310 - Suggested tiles requires two blocks to stop showing in newtab [r=marcosc] (53aed2c8a8)
- Bug 912337 - Update docs on Debugger.DebuggeeWouldRun. (r=jimb) (f4a88f0f93)
- Bug 1236316 - Suppress GC in ActivationEntryMonitor constructors; should fix a ton of dt oranges. r=fitzgen (122a436137)
- Bug 1238575 - Fix shell evalInWorker() to wait for thread if it exitsearly r=terrence (dd0ef6414a)
- Bug 1243706 - Release PerformanceStats/PerformanceWatcher;r=Felipe (1a36dce39e)
- Bug 912337 - Tests. (r=jimb) (463a89f8fc)
- Bug 912337 - Update existing tests. (r=jimb) (bf57c020a9)
- Bug 912337 - Make a pref to toggle whether DebuggeeWouldRun is a warning or an error. (r=jimb) (3fd12fe0c3)
- Bug 912337 - Make DebuggeeWouldRun report filename and lineno. (r=me) (56ace0f5e4)
- Bug 1232685 - Prevent forcing illegal return values in derived class constructors. (r=shu, a=kwierso) (f15c51b1fd)
- Bug 1243754 - IonMonkey: Use 'delete' to destroy the ion script instead of 'free', r=jandem (74df94e3a2)
2023-09-04 16:37:44 +08:00

743 lines
25 KiB
JavaScript

/* vim: se cin sw=2 ts=2 et filetype=javascript :
* 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/. */
/*
* This module implements the front end behavior for AeroPeek. Starting in
* Windows Vista, the taskbar began showing live thumbnail previews of windows
* when the user hovered over the window icon in the taskbar. Starting with
* Windows 7, the taskbar allows an application to expose its tabbed interface
* in the taskbar by showing thumbnail previews rather than the default window
* preview. Additionally, when a user hovers over a thumbnail (tab or window),
* they are shown a live preview of the window (or tab + its containing window).
*
* In Windows 7, a title, icon, close button and optional toolbar are shown for
* each preview. This feature does not make use of the toolbar. For window
* previews, the title is the window title and the icon the window icon. For
* tab previews, the title is the page title and the page's favicon. In both
* cases, the close button "does the right thing."
*
* The primary objects behind this feature are nsITaskbarTabPreview and
* nsITaskbarPreviewController. Each preview has a controller. The controller
* responds to the user's interactions on the taskbar and provides the required
* data to the preview for determining the size of the tab and thumbnail. The
* PreviewController class implements this interface. The preview will request
* the controller to provide a thumbnail or preview when the user interacts with
* the taskbar. To reduce the overhead of drawing the tab area, the controller
* implementation caches the tab's contents in a <canvas> element. If no
* previews or thumbnails have been requested for some time, the controller will
* discard its cached tab contents.
*
* Screen real estate is limited so when there are too many thumbnails to fit
* on the screen, the taskbar stops displaying thumbnails and instead displays
* just the title, icon and close button in a similar fashion to previous
* versions of the taskbar. If there are still too many previews to fit on the
* screen, the taskbar resorts to a scroll up and scroll down button pair to let
* the user scroll through the list of tabs. Since this is undoubtedly
* inconvenient for users with many tabs, the AeroPeek objects turns off all of
* the tab previews. This tells the taskbar to revert to one preview per window.
* If the number of tabs falls below this magic threshold, the preview-per-tab
* behavior returns. There is no reliable way to determine when the scroll
* buttons appear on the taskbar, so a magic pref-controlled number determines
* when this threshold has been crossed.
*/
this.EXPORTED_SYMBOLS = ["AeroPeek"];
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
// Pref to enable/disable preview-per-tab
const TOGGLE_PREF_NAME = "browser.taskbar.previews.enable";
// Pref to determine the magic auto-disable threshold
const DISABLE_THRESHOLD_PREF_NAME = "browser.taskbar.previews.max";
// Pref to control the time in seconds that tab contents live in the cache
const CACHE_EXPIRATION_TIME_PREF_NAME = "browser.taskbar.previews.cachetime";
const WINTASKBAR_CONTRACTID = "@mozilla.org/windows-taskbar;1";
////////////////////////////////////////////////////////////////////////////////
//// Various utility properties
XPCOMUtils.defineLazyServiceGetter(this, "ioSvc",
"@mozilla.org/network/io-service;1",
"nsIIOService");
XPCOMUtils.defineLazyServiceGetter(this, "imgTools",
"@mozilla.org/image/tools;1",
"imgITools");
XPCOMUtils.defineLazyServiceGetter(this, "faviconSvc",
"@mozilla.org/browser/favicon-service;1",
"nsIFaviconService");
// nsIURI -> imgIContainer
function _imageFromURI(uri, privateMode, callback) {
let channel = ioSvc.newChannelFromURI(uri);
try {
channel.QueryInterface(Ci.nsIPrivateBrowsingChannel);
channel.setPrivate(privateMode);
} catch (e) {
// Ignore channels which do not support nsIPrivateBrowsingChannel
}
NetUtil.asyncFetch(channel, function(inputStream, resultCode) {
if (!Components.isSuccessCode(resultCode))
return;
try {
let out_img = { value: null };
imgTools.decodeImageData(inputStream, channel.contentType, out_img);
callback(out_img.value);
} catch (e) {
// We failed, so use the default favicon (only if this wasn't the default
// favicon).
let defaultURI = faviconSvc.defaultFavicon;
if (!defaultURI.equals(uri))
_imageFromURI(defaultURI, callback);
}
});
}
// string? -> imgIContainer
function getFaviconAsImage(iconurl, privateMode, callback) {
if (iconurl)
_imageFromURI(NetUtil.newURI(iconurl), privateMode, callback);
else
_imageFromURI(faviconSvc.defaultFavicon, privateMode, callback);
}
// Snaps the given rectangle to be pixel-aligned at the given scale
function snapRectAtScale(r, scale) {
let x = Math.floor(r.x * scale);
let y = Math.floor(r.y * scale);
let width = Math.ceil((r.x + r.width) * scale) - x;
let height = Math.ceil((r.y + r.height) * scale) - y;
r.x = x / scale;
r.y = y / scale;
r.width = width / scale;
r.height = height / scale;
}
////////////////////////////////////////////////////////////////////////////////
//// PreviewController
/*
* This class manages the behavior of the preview.
*
* To give greater performance when drawing, the dirty areas of the content
* window are tracked and drawn on demand into a canvas of the same size.
* This provides a great increase in responsiveness when drawing a preview
* for unchanged (or even only slightly changed) tabs.
*
* @param win
* The TabWindow (see below) that owns the preview that this controls
* @param tab
* The <tab> that this preview is associated with
*/
function PreviewController(win, tab) {
this.win = win;
this.tab = tab;
this.linkedBrowser = tab.linkedBrowser;
this.preview = this.win.createTabPreview(this);
this.linkedBrowser.addEventListener("MozAfterPaint", this, false);
this.linkedBrowser.addEventListener("resize", this, false);
this.tab.addEventListener("TabAttrModified", this, false);
XPCOMUtils.defineLazyGetter(this, "canvasPreview", function () {
let canvas = this.win.win.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
canvas.mozOpaque = true;
return canvas;
});
XPCOMUtils.defineLazyGetter(this, "dirtyRegion",
function () {
let dirtyRegion = Cc["@mozilla.org/gfx/region;1"]
.createInstance(Ci.nsIScriptableRegion);
dirtyRegion.init();
return dirtyRegion;
});
XPCOMUtils.defineLazyGetter(this, "winutils",
function () {
let win = tab.linkedBrowser.contentWindow;
return win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
});
}
PreviewController.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsITaskbarPreviewController,
Ci.nsIDOMEventListener]),
destroy: function () {
this.tab.removeEventListener("TabAttrModified", this, false);
this.linkedBrowser.removeEventListener("resize", this, false);
this.linkedBrowser.removeEventListener("MozAfterPaint", this, false);
// Break cycles, otherwise we end up leaking the window with everything
// attached to it.
delete this.win;
delete this.preview;
delete this.dirtyRegion;
},
get wrappedJSObject() {
return this;
},
get dirtyRects() {
let rectstream = this.dirtyRegion.getRects();
if (!rectstream)
return [];
let rects = [];
for (let i = 0; i < rectstream.length; i+= 4) {
let r = {x: rectstream[i],
y: rectstream[i+1],
width: rectstream[i+2],
height: rectstream[i+3]};
rects.push(r);
}
return rects;
},
// Resizes the canvasPreview to 0x0, essentially freeing its memory.
// updateCanvasPreview() will detect the size mismatch as a resize event
// the next time it is called.
resetCanvasPreview: function () {
this.resizeCanvasPreview(0, 0);
},
resizeCanvasPreview: function (width, height) {
this.canvasPreview.width = width;
this.canvasPreview.height = height;
},
get wasResizedSinceLastPreview () {
let bx = this.linkedBrowser.boxObject;
return bx.width != this.canvasPreview.width ||
bx.height != this.canvasPreview.height;
},
get zoom() {
// Note that winutils.fullZoom accounts for "quantization" of the zoom factor
// from nsIMarkupDocumentViewer due to conversion through appUnits.
// We do -not- want screenPixelsPerCSSPixel here, because that would -also-
// incorporate any scaling that is applied due to hi-dpi resolution options.
return this.winutils.fullZoom;
},
// Updates the controller's canvas with the parts of the <browser> that need
// to be redrawn.
updateCanvasPreview: function () {
let win = this.linkedBrowser.contentWindow;
let bx = this.linkedBrowser.boxObject;
// If we resized then we need to flush layout so that the previews are up
// to date. Layout flushing for resizes is deferred for background tabs so
// we may need to force it. (bug 526620)
let flushLayout = this.wasResizedSinceLastPreview;
// Check for resize
if (flushLayout) {
// Invalidate the entire area and repaint
this.onTabPaint({left:0, top:0, right:win.innerWidth, bottom:win.innerHeight});
this.resizeCanvasPreview(bx.width, bx.height);
}
// Draw dirty regions
let ctx = this.canvasPreview.getContext("2d");
let scale = this.zoom;
let flags = this.canvasPreviewFlags;
if (flushLayout)
flags &= ~Ci.nsIDOMCanvasRenderingContext2D.DRAWWINDOW_DO_NOT_FLUSH;
// The dirty region may include parts that are offscreen so we clip to the
// canvas area.
this.dirtyRegion.intersectRect(0, 0, win.innerWidth, win.innerHeight);
this.dirtyRects.forEach(function (r) {
// We need to snap the rectangle to be pixel aligned in the destination
// coordinate space. Otherwise natively themed widgets might not draw.
snapRectAtScale(r, scale);
let x = r.x;
let y = r.y;
let width = r.width;
let height = r.height;
ctx.save();
ctx.scale(scale, scale);
ctx.translate(x, y);
ctx.drawWindow(win, x, y, width, height, "white", flags);
ctx.restore();
});
this.dirtyRegion.setToRect(0,0,0,0);
// If we're updating the canvas, then we're in the middle of a peek so
// don't discard the cache of previews.
AeroPeek.resetCacheTimer();
},
onTabPaint: function (rect) {
let x = Math.floor(rect.left),
y = Math.floor(rect.top),
width = Math.ceil(rect.right) - x,
height = Math.ceil(rect.bottom) - y;
this.dirtyRegion.unionRect(x, y, width, height);
},
updateTitleAndTooltip: function () {
let title = this.win.tabbrowser.getWindowTitleForBrowser(this.linkedBrowser);
this.preview.title = title;
this.preview.tooltip = title;
},
//////////////////////////////////////////////////////////////////////////////
//// nsITaskbarPreviewController
get width() {
return this.win.width;
},
get height() {
return this.win.height;
},
get thumbnailAspectRatio() {
let boxObject = this.tab.linkedBrowser.boxObject;
// Avoid returning 0
let tabWidth = boxObject.width || 1;
// Avoid divide by 0
let tabHeight = boxObject.height || 1;
return tabWidth / tabHeight;
},
drawPreview: function (ctx) {
this.win.tabbrowser.previewTab(this.tab, () => this.previewTabCallback(ctx));
// We must avoid having the frame drawn around the window. See bug 520807
return false;
},
previewTabCallback: function (ctx) {
// This will extract the resolution-scale component of the scaling we need,
// which should be applied to both chrome and content;
// the page zoom component is applied (to content only) within updateCanvasPreview.
let scale = this.winutils.screenPixelsPerCSSPixel / this.winutils.fullZoom;
ctx.save();
ctx.scale(scale, scale);
let width = this.win.width;
let height = this.win.height;
// Draw our toplevel window
ctx.drawWindow(this.win.win, 0, 0, width, height, "transparent");
// XXX (jfkthame): Pending tabs don't seem to draw with the proper scaling
// unless we use this block of code; but doing this for "normal" (loaded) tabs
// results in blurry rendering on hidpi systems, so we avoid it if possible.
// I don't understand why pending and loaded tabs behave differently here...
// (see bug 857061).
if (this.tab.hasAttribute("pending")) {
// Compositor, where art thou?
// Draw the tab content on top of the toplevel window
this.updateCanvasPreview();
let boxObject = this.linkedBrowser.boxObject;
ctx.translate(boxObject.x, boxObject.y);
ctx.drawImage(this.canvasPreview, 0, 0);
}
ctx.restore();
},
drawThumbnail: function (ctx, width, height) {
this.updateCanvasPreview();
let scale = width/this.linkedBrowser.boxObject.width;
ctx.scale(scale, scale);
ctx.drawImage(this.canvasPreview, 0, 0);
// Don't draw a frame around the thumbnail
return false;
},
onClose: function () {
this.win.tabbrowser.removeTab(this.tab);
},
onActivate: function () {
this.win.tabbrowser.selectedTab = this.tab;
// Accept activation - this will restore the browser window
// if it's minimized
return true;
},
//// nsIDOMEventListener
handleEvent: function (evt) {
switch (evt.type) {
case "MozAfterPaint":
if (evt.originalTarget === this.linkedBrowser.contentWindow) {
let clientRects = evt.clientRects;
let length = clientRects.length;
for (let i = 0; i < length; i++) {
let r = clientRects.item(i);
this.onTabPaint(r);
}
}
let preview = this.preview;
if (preview.visible)
preview.invalidate();
break;
case "TabAttrModified":
this.updateTitleAndTooltip();
break;
case "resize":
// We need to invalidate our window's other tabs' previews since layout
// due to resizing is delayed for background tabs. Note that this
// resize may not be the first after the main window has been resized -
// the user may be switching to our tab which forces the resize.
this.win.previews.forEach(function (p) {
let controller = p.controller.wrappedJSObject;
if (controller.wasResizedSinceLastPreview) {
controller.resetCanvasPreview();
if (p.visible) p.invalidate();
}
});
break;
}
}
};
XPCOMUtils.defineLazyGetter(PreviewController.prototype, "canvasPreviewFlags",
function () { let canvasInterface = Ci.nsIDOMCanvasRenderingContext2D;
return canvasInterface.DRAWWINDOW_DRAW_VIEW
| canvasInterface.DRAWWINDOW_DRAW_CARET
| canvasInterface.DRAWWINDOW_ASYNC_DECODE_IMAGES
| canvasInterface.DRAWWINDOW_DO_NOT_FLUSH;
});
////////////////////////////////////////////////////////////////////////////////
//// TabWindow
/*
* This class monitors a browser window for changes to its tabs
*
* @param win
* The nsIDOMWindow browser window
*/
function TabWindow(win) {
this.win = win;
this.tabbrowser = win.gBrowser;
this.previews = new Map();
for (let i = 0; i < this.tabEvents.length; i++)
this.tabbrowser.tabContainer.addEventListener(this.tabEvents[i], this, false);
this.tabbrowser.addTabsProgressListener(this);
AeroPeek.windows.push(this);
let tabs = this.tabbrowser.tabs;
for (let i = 0; i < tabs.length; i++)
this.newTab(tabs[i]);
this.updateTabOrdering();
AeroPeek.checkPreviewCount();
}
TabWindow.prototype = {
_enabled: false,
tabEvents: ["TabOpen", "TabClose", "TabSelect", "TabMove"],
destroy: function () {
this._destroying = true;
let tabs = this.tabbrowser.tabs;
this.tabbrowser.removeTabsProgressListener(this);
for (let i = 0; i < this.tabEvents.length; i++)
this.tabbrowser.tabContainer.removeEventListener(this.tabEvents[i], this, false);
for (let i = 0; i < tabs.length; i++)
this.removeTab(tabs[i]);
let idx = AeroPeek.windows.indexOf(this.win.gTaskbarTabGroup);
AeroPeek.windows.splice(idx, 1);
AeroPeek.checkPreviewCount();
},
get width () {
return this.win.innerWidth;
},
get height () {
return this.win.innerHeight;
},
// Invoked when the given tab is added to this window
newTab: function (tab) {
let controller = new PreviewController(this, tab);
// It's OK to add the preview now while the favicon still loads.
this.previews.set(tab, controller.preview);
AeroPeek.addPreview(controller.preview);
// updateTitleAndTooltip relies on having controller.preview which is lazily resolved.
// Now that we've updated this.previews, it will resolve successfully.
controller.updateTitleAndTooltip();
},
createTabPreview: function (controller) {
let docShell = this.win
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell);
let preview = AeroPeek.taskbar.createTaskbarTabPreview(docShell, controller);
preview.visible = AeroPeek.enabled;
preview.active = this.tabbrowser.selectedTab == controller.tab;
// Grab the default favicon
getFaviconAsImage(null, PrivateBrowsingUtils.isWindowPrivate(this.win), function (img) {
// It is possible that we've already gotten the real favicon, so make sure
// we have not set one before setting this default one.
if (!preview.icon)
preview.icon = img;
});
return preview;
},
// Invoked when the given tab is closed
removeTab: function (tab) {
let preview = this.previewFromTab(tab);
preview.active = false;
preview.visible = false;
preview.move(null);
preview.controller.wrappedJSObject.destroy();
// We don't want to splice from the array if the tabs aren't being removed
// from the tab bar as well (as is the case when the window closes).
this.previews.delete(tab);
AeroPeek.removePreview(preview);
},
get enabled () {
return this._enabled;
},
set enabled (enable) {
this._enabled = enable;
// Because making a tab visible requires that the tab it is next to be
// visible, it is far simpler to unset the 'next' tab and recreate them all
// at once.
for (let [tab, preview] of this.previews) {
preview.move(null);
preview.visible = enable;
}
this.updateTabOrdering();
},
previewFromTab: function (tab) {
return this.previews.get(tab);
},
updateTabOrdering: function () {
let previews = this.previews;
let tabs = this.tabbrowser.tabs;
// Previews are internally stored using a map, so we need to iterate the
// tabbrowser's array of tabs to retrieve previews in the same order.
let inorder = [];
for (let t of tabs) {
if (previews.has(t)) {
inorder.push(previews.get(t));
}
}
// Since the internal taskbar array has not yet been updated we must force
// on it the sorting order of our local array. To do so we must walk
// the local array backwards, otherwise we would send move requests in the
// wrong order. See bug 522610 for details.
for (let i = inorder.length - 1; i >= 0; i--) {
inorder[i].move(inorder[i + 1] || null);
}
},
//// nsIDOMEventListener
handleEvent: function (evt) {
let tab = evt.originalTarget;
switch (evt.type) {
case "TabOpen":
this.newTab(tab);
this.updateTabOrdering();
break;
case "TabClose":
this.removeTab(tab);
this.updateTabOrdering();
break;
case "TabSelect":
this.previewFromTab(tab).active = true;
break;
case "TabMove":
this.updateTabOrdering();
break;
}
},
//// Browser progress listener
onLinkIconAvailable: function (aBrowser, aIconURL) {
let self = this;
getFaviconAsImage(aIconURL, PrivateBrowsingUtils.isWindowPrivate(this.win), function (img) {
let index = self.tabbrowser.browsers.indexOf(aBrowser);
// Only add it if we've found the index. The tab could have closed!
if (index != -1) {
let tab = self.tabbrowser.tabs[index];
self.previews.get(tab).icon = img;
}
});
}
}
////////////////////////////////////////////////////////////////////////////////
//// AeroPeek
/*
* This object acts as global storage and external interface for this feature.
* It maintains the values of the prefs.
*/
this.AeroPeek = {
available: false,
// Does the pref say we're enabled?
_prefenabled: true,
_enabled: true,
// nsITaskbarTabPreview array
previews: [],
// TabWindow array
windows: [],
// nsIWinTaskbar service
taskbar: null,
// Maximum number of previews
maxpreviews: 20,
// Length of time in seconds that previews are cached
cacheLifespan: 20,
initialize: function () {
if (!(WINTASKBAR_CONTRACTID in Cc))
return;
this.taskbar = Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar);
this.available = this.taskbar.available;
if (!this.available)
return;
this.prefs.addObserver(TOGGLE_PREF_NAME, this, false);
this.prefs.addObserver(DISABLE_THRESHOLD_PREF_NAME, this, false);
this.prefs.addObserver(CACHE_EXPIRATION_TIME_PREF_NAME, this, false);
this.cacheLifespan = this.prefs.getIntPref(CACHE_EXPIRATION_TIME_PREF_NAME);
this.maxpreviews = this.prefs.getIntPref(DISABLE_THRESHOLD_PREF_NAME);
this.enabled = this._prefenabled = this.prefs.getBoolPref(TOGGLE_PREF_NAME);
},
destroy: function destroy() {
this._enabled = false;
this.prefs.removeObserver(TOGGLE_PREF_NAME, this);
this.prefs.removeObserver(DISABLE_THRESHOLD_PREF_NAME, this);
this.prefs.removeObserver(CACHE_EXPIRATION_TIME_PREF_NAME, this);
if (this.cacheTimer)
this.cacheTimer.cancel();
},
get enabled() {
return this._enabled;
},
set enabled(enable) {
if (this._enabled == enable)
return;
this._enabled = enable;
this.windows.forEach(function (win) {
win.enabled = enable;
});
},
addPreview: function (preview) {
this.previews.push(preview);
this.checkPreviewCount();
},
removePreview: function (preview) {
let idx = this.previews.indexOf(preview);
this.previews.splice(idx, 1);
this.checkPreviewCount();
},
checkPreviewCount: function () {
if (this.previews.length > this.maxpreviews)
this.enabled = false;
else
this.enabled = this._prefenabled;
},
onOpenWindow: function (win) {
// This occurs when the taskbar service is not available (xp, vista)
if (!this.available)
return;
win.gTaskbarTabGroup = new TabWindow(win);
},
onCloseWindow: function (win) {
// This occurs when the taskbar service is not available (xp, vista)
if (!this.available)
return;
win.gTaskbarTabGroup.destroy();
delete win.gTaskbarTabGroup;
if (this.windows.length == 0)
this.destroy();
},
resetCacheTimer: function () {
this.cacheTimer.cancel();
this.cacheTimer.init(this, 1000*this.cacheLifespan, Ci.nsITimer.TYPE_ONE_SHOT);
},
//// nsIObserver
observe: function (aSubject, aTopic, aData) {
switch (aTopic) {
case "nsPref:changed":
if (aData == CACHE_EXPIRATION_TIME_PREF_NAME)
break;
if (aData == TOGGLE_PREF_NAME)
this._prefenabled = this.prefs.getBoolPref(TOGGLE_PREF_NAME);
else if (aData == DISABLE_THRESHOLD_PREF_NAME)
this.maxpreviews = this.prefs.getIntPref(DISABLE_THRESHOLD_PREF_NAME);
// Might need to enable/disable ourselves
this.checkPreviewCount();
break;
case "timer-callback":
this.previews.forEach(function (preview) {
let controller = preview.controller.wrappedJSObject;
controller.resetCanvasPreview();
});
break;
}
}
};
XPCOMUtils.defineLazyGetter(AeroPeek, "cacheTimer", () =>
Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer)
);
XPCOMUtils.defineLazyServiceGetter(AeroPeek, "prefs",
"@mozilla.org/preferences-service;1",
"nsIPrefBranch");
AeroPeek.initialize();