// ==UserScript==
// @name           Tab Preview
// @namespace      http://www.xuldev.org/
// @description    Displays a real-time thumbnail preview when hovering mouse on a tab.
// @include        main
// @compatibility  Firefox 3.0, 3.5, 3.6b4
// @author         Gomita
// @version        1.0.20080201
// @homepage       http://www.xuldev.org/misc/ucjs.php
// ==/UserScript==

var ucjsTabPreview = {

	PREVIEW_WIDTH: 250,	// width of preview in pixels
	PREVIEW_HEIGHT: 180,	// height of preview in pixels
	UPDATE_INTERVAL: 50,	// interval to refresh preview in milliseconds

	_updateTimer: null,

	init: function() {
		var overlay = 
			<overlay xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
			         xmlns:html="http://www.w3.org/1999/xhtml">
				<popupset id="mainPopupSet">
					<tooltip id="TabPreviewTooltip" noautohide="true" orient="vertical"
					         onpopupshowing="ucjsTabPreview.showPreview();"
					         onpopuphiding="ucjsTabPreview.cancelTimer();">
						<label style="text-align: center;" />
						<hbox flex="1">
							<html:canvas id="TabPreviewCanvas" width={this.PREVIEW_WIDTH} height={this.PREVIEW_HEIGHT}
							             style="display: block; border: 1px solid ThreeDLightShadow; padding: 3px;" />
						</hbox>
					</tooltip>
				</popupset>
			</overlay>;
		overlay = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + encodeURI(overlay.toXMLString());
		document.loadOverlay(overlay, null);
		getBrowser().mStrip.tooltip = "TabPreviewTooltip";
	},

	showPreview: function() {
		var tn = document.tooltipNode;
		if (!tn || tn.localName != "tab")
			return;
		document.getElementById("TabPreviewTooltip").firstChild.value = tn.label;
		var canvas = document.getElementById("TabPreviewCanvas");
		var win = gBrowser.getBrowserForTab(tn).contentWindow;
		var isBlank = win.location.href == "about:blank";
		canvas.parentNode.style.display = isBlank ? "none" : "block";
		if (!isBlank) {
			var w = win.innerWidth;
			var z = canvas.width / w;
			var h = canvas.height / z;
			var ctx = canvas.getContext("2d");
			ctx.clearRect(0, 0, canvas.width, canvas.height);
			ctx.save();
			ctx.scale(z, z);
			ctx.drawWindow(win, win.scrollX, win.scrollY, w + win.scrollX, h + win.scrollY, "rgb(255,255,255)");
			ctx.restore();
		}
		if (this.UPDATE_INTERVAL > 0) {
			var callback = function(self) { self.showPreview(); };
			this._updateTimer = window.setTimeout(callback, this.UPDATE_INTERVAL, this);
		}
	},

	cancelTimer: function() {
		if (this._updateTimer) {
			window.clearTimeout(this._updateTimer);
			this._updateTimer = null;
		}
	}

};

ucjsTabPreview.init();
window.addEventListener("unload", function() { ucjsTabPreview.cancelTimer(); }, false);

