// ==UserScript==
// @name         Mouse Gestures (with Wheel Gesture and Rocker Gesture)
// @namespace    http://www.xuldev.org/
// @description  轻量级鼠标手势执行命令.
// @include      main
// @author       Gomita
// @version      1.0.20080201
// @homepage     http://www.xuldev.org/misc/ucjs.php
// ==/UserScript==

var ucjsMouseGestures = {

	// about:config
	enableWheelGestures: true,	// 滚轮手势 (Scroll wheel with holding right-click)
	enableRockerGestures: true,	// 摇杆手势 (Left-click with holding right-click and vice versa)

	_lastX: 0,
	_lastY: 0,
	_directionChain: "",
	_isMac: false,	// for Mac

	init: function()
	{
		this._isMac = navigator.platform.indexOf("Mac") == 0;
		gBrowser.mPanelContainer.addEventListener("mousedown", this, false);
		gBrowser.mPanelContainer.addEventListener("mousemove", this, false);
		gBrowser.mPanelContainer.addEventListener("mouseup", this, false);
		gBrowser.mPanelContainer.addEventListener("contextmenu", this, true);
		if (this.enableRockerGestures)
			gBrowser.mPanelContainer.addEventListener("draggesture", this, true);
		if (this.enableWheelGestures)
			gBrowser.mPanelContainer.addEventListener("DOMMouseScroll", this, false);
	},

	uninit: function()
	{
		gBrowser.mPanelContainer.removeEventListener("mousedown", this, false);
		gBrowser.mPanelContainer.removeEventListener("mousemove", this, false);
		gBrowser.mPanelContainer.removeEventListener("mouseup", this, false);
		gBrowser.mPanelContainer.removeEventListener("contextmenu", this, true);
		if (this.enableRockerGestures)
			gBrowser.mPanelContainer.removeEventListener("draggesture", this, true);
		if (this.enableWheelGestures)
			gBrowser.mPanelContainer.removeEventListener("DOMMouseScroll", this, false);
	},

	_isMouseDownL: false,
	_isMouseDownR: false,
	_suppressContext: false,
	_shouldFireContext: false,	// for Linux

	handleEvent: function(event)
	{
		switch (event.type) {
			case "mousedown":
				if (event.button == 2) {
					this._isMouseDownR = true;
					this._suppressContext = false;
					this._startGesture(event);
					if (this.enableRockerGestures && this._isMouseDownL) {
						this._isMouseDownR = false;
						this._suppressContext = true;
						this._directionChain = "L>R";
						this._stopGesture(event);
					}
				}
				else if (this.enableRockerGestures && event.button == 0) {
					this._isMouseDownL = true;
					if (this._isMouseDownR) {
						this._isMouseDownL = false;
						this._suppressContext = true;
						this._directionChain = "L<R";
						this._stopGesture(event);
					}
				}
				break;
			case "mousemove":
				if (this._isMouseDownR) {
					this._progressGesture(event);
				}
				break;
			case "mouseup":
				if ((this._isMouseDownR && event.button == 2) ||
				    (this._isMouseDownR && this._isMac && event.button == 0 && event.ctrlKey)) {
					this._isMouseDownR = false;
					if (this._directionChain)
						this._suppressContext = true;
					this._stopGesture(event);
					if (this._shouldFireContext) {
						this._shouldFireContext = false;
						this._displayContextMenu(event);
					}
				}
				else if (this.enableRockerGestures && event.button == 0 && this._isMouseDownL) {
					this._isMouseDownL = false;
				}
				break;
			case "contextmenu":
				if (this._suppressContext || this._isMouseDownR) {
					this._suppressContext = false;
					event.preventDefault();
					event.stopPropagation();
					if (this._isMouseDownR) {
						this._shouldFireContext = true;
					}
				}
				break;
			case "DOMMouseScroll":
				if (this.enableWheelGestures && this._isMouseDownR) {
					event.preventDefault();
					event.stopPropagation();
					this._suppressContext = true;
					this._directionChain = "W" + (event.detail > 0 ? "+" : "-");
					this._stopGesture(event);
				}
				break;
			case "draggesture":
				this._isMouseDownL = false;
				break;
		}
	},

	_displayContextMenu: function(event)
	{
		var evt = event.originalTarget.ownerDocument.createEvent("MouseEvents");
		evt.initMouseEvent(
			"contextmenu", true, true, event.originalTarget.defaultView, 0,
			event.screenX, event.screenY, event.clientX, event.clientY,
			false, false, false, false, 2, null
		);
		event.originalTarget.dispatchEvent(evt);
	},

	_startGesture: function(event)
	{
		this._lastX = event.screenX;
		this._lastY = event.screenY;
		this._directionChain = "";
	},

	_progressGesture: function(event)
	{
		var x = event.screenX;
		var y = event.screenY;
		var distanceX = Math.abs(x - this._lastX);
		var distanceY = Math.abs(y - this._lastY);
		// minimal movement where the gesture is recognized
		const tolerance = 10;
		if (distanceX < tolerance && distanceY < tolerance)
			return;
		// determine current direction
		var direction;
		if (distanceX > distanceY)
			direction = x < this._lastX ? "L" : "R";
		else
			direction = y < this._lastY ? "U" : "D";
		// compare to last direction 开始比较鼠标的方向
		var lastDirection = this._directionChain.charAt(this._directionChain.length - 1);
		if (direction != lastDirection) {
			this._directionChain += direction;
			XULBrowserWindow.statusTextField.label = "\uFEFF\u9F20\u6807\u624B\u52BF:" + this._directionChain;
		}
		// save current position 记录鼠标的坐标
		this._lastX = x;
		this._lastY = y;
	},

	_stopGesture: function(event)
	{
		try {
			if (this._directionChain)
				this._performAction(event);
			XULBrowserWindow.statusTextField.label = "";
		}
		catch(ex) {
			XULBrowserWindow.statusTextField.label = ex;
		}
		this._directionChain = "";
	},

//－－－－－－－－－－－－自定义函数－－－－－－－－－－－－－//
//链接
	getLinkURL: function(aNode)
	{
		if (!aNode)
			aNode = this.sourceNode;
		while (aNode) {
			if ((aNode instanceof HTMLAnchorElement || aNode instanceof HTMLAreaElement) && aNode.href)
				return aNode.href;
			aNode = aNode.parentNode;
		}
		return null;
	},

	getLocaleString: function(aStringKey, aReplacements)
	{
		if (!this._stringBundle) {
			const kBundleURI = "chrome://firegestures/locale/firegestures.properties";
			var bundleSvc = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
			this._stringBundle = bundleSvc.createBundle(kBundleURI);
		}
		try {
			if (!aReplacements)
				return this._stringBundle.GetStringFromName(aStringKey);
			else
				return this._stringBundle.formatStringFromName(aStringKey, aReplacements, aReplacements.length);
		}
		catch(ex) {
			return aStringKey;
		}
	},

//链接数字递增或递减
	goNumericURL: function(aIncrement)
	{
		var url = gBrowser.currentURI.spec;
		if (!url.match(/(\d+)(\D*)$/))
			throw "No numeric value in URL";
		var num = RegExp.$1;
		var digit = (num.charAt(0) == "0") ? num.length : null;
		num = parseInt(num, 10) + aIncrement;
		if (num < 0)
			throw "Cannot decrement number in URL anymore";
		num = num.toString();
		digit = digit - num.length;
		for (var i = 0; i < digit; i++)
			num = "0" + num;
		loadURI(RegExp.leftContext + num + RegExp.$2);
	},

//打开选中的所有URL/搜索所选文本：
	get focusedWindow()
	{
		var win = document.commandDispatcher.focusedWindow;
		if (win == window)
			win = window.content;
		return win;
	},

	getSelectedText: function()
	{
		return this.focusedWindow.getSelection().toString();
	},

	openURLsInSelection: function()
	{
		var sel = this.getSelectedText();
		if (!sel)
			throw "No selection";
		var flag = 0;
		sel = sel.split("\n");
		sel.forEach(function(str) {
			str = str.match(/([\w\+\-\=\$;:\?\.%,!#~\*\/@&]{8,})/);
			if (!str || str[1].indexOf(".") < 0)
				return;
			if (str[1].split("/").length < 3 && str[1].split(".").length < 3)
				return;
			str = str[1];
			if (str.indexOf("ttp://") == 0 || str.indexOf("ttps://") == 0)
				str = "h" + str;
			var tab = gBrowser.loadOneTab(str, null, null, null, true, false);
			gBrowser.moveTabTo(tab, gBrowser.mCurrentTab._tPos + ++flag);
		});
		if (!flag)
			BrowserSearch.loadSearch(sel, true);
	},

//向上一级
	goUpperLevel: function()
	{
		var uri = gBrowser.currentURI;
		if (uri.path == "/")
			return;
		var pathList = uri.path.split("/");
		if (!pathList.pop())
			pathList.pop();
		loadURI(uri.prePath + pathList.join("/") + "/");
	},
		
	gatherLinkURLsInSelection: function()
	{
		var win = this.focusedWindow;
		var sel = win.getSelection();
		if (!sel || sel.isCollapsed)
			return null;
		var doc = win.document;
		var ret = [];
		for (var i = 0; i < sel.rangeCount; i++) {
			var range = sel.getRangeAt(i);
			var fragment = range.cloneContents();
			var treeWalker = fragment.ownerDocument.createTreeWalker(fragment, NodeFilter.SHOW_ELEMENT, null, true);
			while (treeWalker.nextNode()) {
				var node = treeWalker.currentNode;
				if ((node instanceof HTMLAnchorElement || node instanceof HTMLAreaElement) && node.href) {
					try {
						this.checkURL(node.href, doc, Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT);
						ret.push(node.href);
					}
					catch(ex) {
					}
				}
			}
		}
		return ret;
	},

	getLinkText: function(aNode)
	{
		if (!aNode)
			aNode = this.sourceNode;
		var text = gatherTextUnder(aNode);
		if (!text || !text.match(/\S/)) {
			text = aNode.getAttribute("title");
			if (!text || !text.match(/\S/)) {
				text = aNode.getAttribute("alt");
				if (!text || !text.match(/\S/)) {
					text = this.getLinkURL(aNode);
				}
			}
		}
		return text;
	},

//帧

		

//图像
	getImageURL: function(aNode)
	{
		if (!aNode)
			aNode = this.sourceNode;
		if (aNode instanceof HTMLImageElement && aNode.src)
			return aNode.src;
		else if (aNode instanceof HTMLCanvasElement)
			return aNode.toDataURL();
		return null;
	},

//弹出菜单型
//其他
	onDirectionChanged: function(event, aDirection)
	{
		var command = this._gestureMappings.getCommandForDirection(aDirection);
		var name = command ? " (" + command.name + ")" : "";
		this.setStatusText(this.getLocaleString("GESTURE") + ": " + aDirection + name);
	},

	onMouseGesture: function(event, aDirection)
	{
		try {
			var command = this._gestureMappings.getCommandForDirection(aDirection);
			if (!command)
				throw null;
			if (command.type == this._gestureMappings.TYPE_SCRIPT)
				(new Function("event", command.value))(event);
			else
				this._performAction(event, command.value);
		}
		catch(ex) {
			this.setStatusText(
				ex ? 
				this.getLocaleString("GESTURE_FAILED")  + ": " + aDirection + " (" + ex + ")" :
				this.getLocaleString("GESTURE_UNKNOWN") + ": " + aDirection
			);
		}
		this.clearStatusText(3000);
	},

	setStatusText: function(aText)
	{
		this._statusTextField.label = aText;
	},

	clearStatusText: function(aMillisec)
	{
		if (this._clearStatusTimer) {
			window.clearTimeout(this._clearStatusTimer);
			this._clearStatusTimer = null;
		}
		var text = this._statusTextField.label;
		var callback = function(self) {
			self._clearStatusTimer = null;
			if (self._statusTextField.label == text)
				self.setStatusText("");
		};
		this._clearStatusTimer = window.setTimeout(callback, aMillisec, this);
	},


//－－－－－－－－－－－－－自定义函数－－－－－－－－－－－－//
	_performAction: function(event)
	{
		// 映射. 支持自定义
		switch (this._directionChain) {
//MouseGesTures默认鼠标手势
//导航：
			// 后退
			case "L": document.getElementById("Browser:Back").doCommand(); break;
			// 前进
			case "R": document.getElementById("Browser:Forward").doCommand(); break;
			// 刷新
			case "UD": document.getElementById("Browser:Reload").doCommand(); break;
			// 刷新（跳过缓存）
			case "UDU": document.getElementById("Browser:ReloadSkipCache").doCommand(); break;
			// 主页
			case "": document.getElementById("Browser:Home").doCommand(); break;
			// 停止
			case "": document.getElementById("Browser:Stop").doCommand(); break;
			//向上一级
			case "DU":
			this.goUpperLevel();break;
			//URL中的数字递增
			case "RURU":
			this.goNumericURL(+1);break;
            //URL中的数字递减
            case "RDRD":
			this.goNumericURL(-1);break;

//窗口
			// 新建窗口
			case "DRU": document.getElementById("cmd_newNavigator").doCommand(); break;
			// 关闭窗口
			case "URD": document.getElementById("cmd_closeWindow").doCommand(); break;
			// 最小化窗口
			case "RUD": window.minimize(); break;
			// 最大化/恢复窗口大小
			case "RDU": window.windowState == 1 ? window.restore() : window.maximize(); break;
			//最小化窗口
			case "RUD" :
			window.minimize();break;
			// 全屏
			case "": document.getElementById("View:FullScreen").doCommand(); break;

//标签页：
			// 新建标签页
			case "LR": document.getElementById("cmd_newNavigatorTab").doCommand(); break;
			// 关闭标签页
			case "DR": document.getElementById("cmd_close").doCommand(); break;
			 //关闭标签页 / 关闭窗口
			case "LRL":
			BrowserCloseTabOrWindow();break;
			//重新载入全部标签页
			case "RLR":
			gBrowser.reloadAllTabs(gBrowser.mCurrentTab);break;
			//复制标签页.
			case "":
			openNewTabWith(gBrowser.currentURI.spec, null, null, null, false);break;
			// 撤销关闭标签页
			case "RL": document.getElementById("History:UndoCloseTab").doCommand(); break;
			// Undo Close Tab (If you are using Tab Mix Plus's Session Manager, use this instead.)
			// case "DL":
			//gBrowser.undoRemoveTab(); break;
			// 上一个标签页
			case "L<R":
			case "W-":
			case "UL": gBrowser.mTabContainer.advanceSelectedTab(-1, true); break;
			// 下一个标签页
			case "L>R":
			case "W+":
			case "UR": gBrowser.mTabContainer.advanceSelectedTab(+1, true); break;
			//关闭其他标签页.
			case "":
			var browser = getBrowser(); browser.removeAllTabsBut(browser.mCurrentTab);break;
			//关闭左边标签页
			case "":
			var tabs = gBrowser.mTabContainer.childNodes;
for (var i = tabs.length - 1; tabs[i] != gBrowser.mCurrentTab; i--){}
for (i--; i >=0 ; i--){
    gBrowser.removeTab(tabs[i]);
}break;
             //关闭右边标签页
             case "":
             var tabs = gBrowser.mTabContainer.childNodes;
for (var i = tabs.length - 1; tabs[i] != gBrowser.selectedTab; i--)
{
    gBrowser.removeTab(tabs[i]);
}break;

//页面
            //缩放 - 放大
            case "":
document.getElementById("cmd_fullZoomEnlarge").doCommand(); break;
			//缩放 - 缩小
			case "":
document.getElementById("cmd_fullZoomReduce").doCommand(); break;
			//缩放 - 重置
			case "":
document.getElementById("cmd_fullZoomReset").doCommand(); break;
			// 滚动到顶部
			case "LU": goDoCommand("cmd_scrollTop"); break;
			// 滚动到底部
			case "LD": goDoCommand("cmd_scrollBottom"); break;
			// 向上翻页
			case "U": goDoCommand("cmd_scrollPageUp"); break;
			// 向下翻页
			case "D": goDoCommand("cmd_scrollPageDown"); break;
			// 文字大小-缩小
			case "LRD": document.getElementById("cmd_textZoomReduce").doCommand(); break;
			// 文字大小-放大
			case "LRU": document.getElementById("cmd_textZoomEnlarge").doCommand(); break;
			// 文字大小-正常
			case "LDRU": document.getElementById("View:FullScreen").doCommand(); break;
			//当前页加为书签
			case "":
document.getElementById("Browser:AddBookmarkAs").doCommand(); 	break;
			//页面另存为…
			case "":
document.getElementById("Browser:SavePage").doCommand(); break;
			//查看页面源代码
			case "":
document.getElementById("View:FullScreen").doCommand(); break;
			//查看页面信息
			case "":
document.getElementById("View:PageInfo").doCommand(); break;
			//打印预览
			case "":
document.getElementById("cmd_printPreview").doCommand(); break;
			//打印…
			case "":
document.getElementById("cmd_print").doCommand(); break;

//帧：
             //查看帧信息
             case "": BrowserPageInfo(globalSrcEvent.originalTarget.ownerDocument);
break;
              //查看帧源代码
              case "":                  BrowserViewSourceOfDocument(globalSrcEvent.originalTarget.ownerDocument);break;

//链接
             //在新窗口中打开
             case "":
             var linkURL = this.getLinkURL();
			if (!linkURL)
			throw this.getLocaleString("\uFEFF\u624B\u52BF\u8D77\u70B9\u4E0D\u662F\u94FE\u63A5");
			if ("nodePrincipal" in this.sourceNode.ownerDocument)
			openNewWindowWith(linkURL, this.sourceNode.ownerDocument, null, false);
			else
			openNewWindowWith(linkURL, this.sourceNode.ownerDocument.location.href, null, false);break;

//图像

//选择项目
              //搜索所选文本
			  case "":
BrowserSearch.loadSearch(getBrowserSelection(), true);break;
			  //打开选中的所有链接
              case "RU": 
			  var linkURLs = this.gatherLinkURLsInSelection();
				if (!linkURLs || linkURLs.length == 0)
				throw "No valid links in selection";
				var doc = this.sourceNode.ownerDocument;
				var referer = makeURI(doc.location.href);
				var charset = window.content.document.characterSet;
				linkURLs.forEach(function(aURL) {
				gBrowser.loadOneTab(aURL, referer, charset, null, true, false);
});break;

//工具
			 // 下载
			case "": document.getElementById("Tools:Downloads").doCommand(); break;
			// 附加组件
			case "": document.getElementById("Tools:Addons").doCommand(); break;
			// 清除隐私数据
			case "": document.getElementById("Tools:Sanitize").doCommand(); break;
			//错误控制台
			case "":
			toJavaScriptConsole();break;
			//打开/关闭书签侧边栏
             case "":
             toggleSidebar("viewBookmarksSidebar");break;
			//显示/隐藏历史侧边栏
			case "":
			toggleSidebar("viewHistorySidebar");break;
			//打开/关闭 查找栏
			case "":
			if ("isFindBarVisible" in gFindBar)
    gFindBar.isFindBarVisible() ? gFindBar.closeFindBar() : gFindBar.onFindCmd();
else
    gFindBar.hidden ? gFindBar.onFindCommand() : gFindBar.close();break;

//弹出菜单型：
            //
            
//混合功能型：
            //
            
//用户脚本 ：
           // 
           //用IE查看当前网页
			case "":
			const IE_PATH = "C:\\Program Files\\Internet Explorer\\iexplore.exe";

var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
file.initWithPath(IE_PATH);
if (!file.exists()) {
  alert("File does not exist: " + IE_PATH);
  return;
}
var process  = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
try {
  var args = [window.content.location.href];
  process.init(file);
  process.run(false, args, args.length);
}
catch (ex) {
  alert("Failed to execute: " + IE_PATH);
} break; 
           //复制网页标题和URL到剪贴板
               case "":
               const AS_HTML = false;

function htmlEscape(s) {
  s = s.replace(/&/g, "&amp;");
  s = s.replace(/>/g, "&gt;");
  s = s.replace(/</g, "&lt;");
  s = s.replace(/"/g, "&quot;");
  return s;
}
var url = window.content.location.href;
var title = window.content.document.title;
var txt = AS_HTML ? 
  '<a href="' + htmlEscape(url) + '">' + htmlEscape(title) + '</a>' : 
  title + "\n" + url;
var clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"]
           .getService(Ci.nsIClipboardHelper);
clipboard.copyString(txt);break; 
           //Firefox选项
           case "":
           openPreferences();break; 
                
			//[安装Tab Mix Plus后] 冻结标签页
            case "":
gBrowser.freezeTab(gBrowser.mCurrentTab);break; 
            //[安装Tab Mix Plus后] 锁定标签
            case "":
            gBrowser.lockTab(gBrowser.mCurrentTab);break; 
            //[安装Tab Mix Plus后] 保护标签
            case "":
gBrowser.protectTab(gBrowser.mCurrentTab);break; 
			//开启/关闭导航工具栏
             case "":
             var toolbar = document.getElementById("nav-bar");
toolbar.collapsed = !toolbar.collapsed;
document.persist(toolbar.id, "collapsed");break;
            //开启/关闭标签工具栏
            case "":
             function tbtoggle (thisBTN)
{thisBTN.checked = !thisBTN.checked;
        if ( thisBTN.checked )
        {gBrowser.setStripVisibilityTo(false);
        gBrowser.mPrefs.setBoolPref("browser.tabs.forceHide", true);}
        else
        {gBrowser.setStripVisibilityTo(true);
        gBrowser.mPrefs.setBoolPref("browser.tabs.forceHide", false);}}
tbtoggle(this);break;
//开启/关闭状态栏
              case "":
goToggleToolbar('status-bar','toggle_taskbar');break;
             //[安装stylsh扩展后]开启/关闭stylsh侧边栏
             case "":
stylishBrowserOverlay.openSidebar();break;
			 //定位到最左边标签页
              case "":
              gBrowser.selectedTab = gBrowser.mTabContainer.firstChild;break;
              //定位到最右边标签页
               case "":
               gBrowser.selectedTab =
gBrowser.tabContainer.childNodes[gBrowser.tabContainer.childNodes.length-1];break;
			   //在当前标签页右边新建标签页
              case "":
              var x = gBrowser.mCurrentTab._tPos + 1;
gBrowser.moveTabTo(gBrowser.selectedTab = gBrowser.addTab("about:blank"), x);break;
             //在新窗口打开about:config
             case "":
             toOpenWindowByType('pref:pref', 'About:config');break;
            //重新载入左边所有标签页
            case "":
            var browsers = gBrowser.browsers;
var i = gBrowser.mCurrentTab._tPos - 1;
var l = -1;

for(; i > l; i--)
try { browsers[i].reload(); } catch(err){};break;
           //重新载入右边所有标签页
            case "":
            var browsers = gBrowser.browsers;
var i = gBrowser.mCurrentTab._tPos + 1;
var l = browsers.length;

for(; i < l; i++)
try { browsers[i].reload(); } catch(err){};break;
           //重新载入其它标签页
           case "":
           var browsers = gBrowser.browsers;
var i = 0;
var l = browsers.length;
var x = gBrowser.mCurrentTab._tPos;

for(; i < l; i++)
if(i != x) try { browsers[i].reload(); } catch(err){};break;
           //显示/隐藏书签工具栏
           case "":
           var bmToolbar = document.getElementById("PersonalToolbar");
bmToolbar.collapsed = !bmToolbar.collapsed;break;
           //显示/隐藏菜单
           case "":
           var menubar = document.getElementById("toolbar-menubar");
menubar.collapsed = !menubar.collapsed;break;
           //显示隐藏标题栏
           //隐藏标题栏时自定义了窗口大小
           case "":
           function hideChrome() {
document.getElementById("main-window").setAttribute('hidechrome','true');
window.moveTo(1, 112);
window.resizeTo(1008, 662);
}

function showChrome() {
document.getElementById("main-window").removeAttribute('hidechrome');
window.maximize();
window.restore();
window.maximize();
}

function toggleChrome() {
var isFullScreen = document.getElementById("main-window").getAttribute('hidechrome');
if (isFullScreen) {
showChrome();
} else {
hideChrome();
}
}

toggleChrome();break;
              //打开单个链接
           case "":
           const URL = "chrome://sessionpage/content/SessionPage.xul";
const IN_NEW_TAB = true;
const IN_BACKGROUND = false;

if (IN_NEW_TAB)
  gBrowser.loadOneTab(URL, null, null, null, IN_BACKGROUND, false);
else
  gBrowser.loadURI(URL);break;
            //下一页
           //安装GM的next page脚本后生效
           case "":
           try { var node = FireGestures.sourceNode; } catch (e) {}
while (node && node.nodeName != "BODY")
  node = node.parentNode;
if (!node) node = getBrowser().contentDocument;
var e = document.createEvent("KeyboardEvent");
e.initKeyEvent("keydown", true, true, window, false, false, false, false, 39, 0);
node.dispatchEvent(e);break;
           //上一页
           //安装GM的next page脚本后生效
           case "":
           try { var node = FireGestures.sourceNode; } catch (e) {}
while (node && node.nodeName != "BODY")
  node = node.parentNode;
if (!node) node = getBrowser().contentDocument;
var e = document.createEvent("KeyboardEvent");
e.initKeyEvent("keydown", true, true, window, false, false, false, false, 37, 0);
node.dispatchEvent(e);break;
           //关闭全部标签页并退出Firefox
           case "":
           var ctab = gBrowser.addTab("about:blank");
	gBrowser.removeAllTabsBut(ctab);
	if(gBrowser.tabContainer.childNodes.length > 1)
		gBrowser.removeTab(ctab);
javascript:window.open('','_parent','');window.close();break;
           //关闭全部标签页
            case "":
            var ctab = gBrowser.addTab("about:blank");
	gBrowser.removeAllTabsBut(ctab);
	if(gBrowser.tabContainer.childNodes.length > 1)
		gBrowser.removeTab(ctab);break;
           //查看当前网页Cookies
            case "": 
            alert(content.document.cookie);break;
                //[Secure Login扩展]Secure Login登陆
            case "": 
            secureLogin.login();break;
           //划词释义
           case "": 
           function openAndReuseOneTabPerURL(url) {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);
  var browserEnumerator = wm.getEnumerator("navigator:browser");

  // Check each browser instance for our URL
  var found = false;
  while (!found && browserEnumerator.hasMoreElements()) {
    var browserInstance = browserEnumerator.getNext().getBrowser();

    // Check each tab of this browser instance
    var numTabs = browserInstance.tabContainer.childNodes.length;
    for(var index=0; index<numTabs; index++) {
      var currentBrowser = browserInstance.getBrowserAtIndex(index);
      if (currentBrowser.currentURI.spec.indexOf(url) == 0) {

        // The URL is already opened. Select this tab.
        browserInstance.selectedTab = browserInstance.tabContainer.childNodes[index];

        // Focus *this* browser
        browserInstance.focus();
        found = true;
        var defhistory = window._content.document.getElementById("link").toString();
        defhistory = defhistory.slice(url.length,defhistory.length);
        window._content.document.location.href = url+defhistory+","+sel;
        break;
      }
    }
  }

  // Our URL isn't open. Open it now.
  if (!found) {
    var recentWindow = wm.getMostRecentWindow("navigator:browser");
    if (recentWindow) {
      // Use an existing browser window
      recentWindow.delayedOpenTab(url+sel, null, null, null, null);
    }
    else {
      // No browser windows are open, so open a new one.
      window.open(url+sel);
    }
  }
}

//Strips all punctuation out of given string
function cleanUp(str){
  //Convert to string and lowercase
  str = str.toString().toLowerCase();
  var cleanstr = "";
    //Check if each character is alphanumeric or " "
    for (var i=0; i<=str.length; i++){
       if(str.charAt(i) >='a' && str.charAt(i) <='z' || str.charAt(i) == ' '){
         cleanstr += str.charAt(i);
       }
     }
  return(cleanstr);
}
//Set URL
var url = "http://vdict.com/";

//Get highlighted text
var sel = cleanUp(window._content.getSelection()) + ",1,0,0.html";

openAndReuseOneTabPerURL(url);break;
           //翻译选定文字,无选定则翻译全文
           case "": 
           var t = content.getSelection().toString();
if(t) {gBrowser.selectedTab = gBrowser.addTab("http://translate.google.cn/translate_t?hl=zh-CN#auto|zh-CN|"+t);}
else {gBrowser.selectedTab = gBrowser.addTab("http://translate.google.cn/translate?u="+content.location);} break;
           //增强型前进
           //没前进翻到下一页,需要配合油猴子的那个下一页脚本一起使用
           case "": 
           var nav = gBrowser.webNavigation;
if (nav.canGoForward)
  nav.goForward();
else
try { var node = FireGestures.sourceNode; } catch (e) {}
while (node && node.nodeName != "BODY")
  node = node.parentNode;
if (!node) node = getBrowser().contentDocument;
var e = document.createEvent("KeyboardEvent");
e.initKeyEvent("keydown", true, true, window, false, false, false, false, 39, 0);
node.dispatchEvent(e);break;
           //增强型后退
           //没后退关闭本页
           case "": 
           var nav = gBrowser.webNavigation;
if (nav.canGoBack)
  nav.goBack();
else
  gBrowser.removeCurrentTab();break;
                //重启Firefox
           case "":
// Derived from chrome://mozapps/content/extensions/extensions.js

const nsIAppStartup = Components.interfaces.nsIAppStartup;

// Notify all windows that an application quit has been requested.
var os = Components.classes["@mozilla.org/observer-service;1"]
                   .getService(Components.interfaces.nsIObserverService);
var cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"]
                           .createInstance(Components.interfaces.nsISupportsPRBool);
os.notifyObservers(cancelQuit, "quit-application-requested", null);

// Something aborted the quit process. 
if (cancelQuit.data)
  return;

// Notify all windows that an application quit has been granted.
os.notifyObservers(null, "quit-application-granted", null);

// Enumerate all windows and call shutdown handlers
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var windows = wm.getEnumerator(null);
while (windows.hasMoreElements()) {
  var win = windows.getNext();
  if (("tryToClose" in win) && !win.tryToClose())
    return;
}
Components.classes["@mozilla.org/toolkit/app-startup;1"].getService(nsIAppStartup)
          .quit(nsIAppStartup.eRestart | nsIAppStartup.eAttemptQuit);break;

                //粘贴并搜索
           //自行判断剪贴板内容是链接还是文本，链接粘贴到地址栏并打开，文本则粘贴宾用当前搜索引擎搜索
           case "":
           var str = readFromClipboard();
if(!str) return;
if (/^file:\/{3}|^data:.+|^(?!java script:)\S*?(([\w-]\.)+\w{2,7}|localhost([:\/]|$))\S*$/.test(str)) {
    gBrowser.loadOneTab(str);
}
else{
    BrowserSearch.loadSearch(str, true);
}break;
                //[Drag&Dropzone Searching扩展]开启/关闭Drag&Dropzone Searching
            case "": 
            DenDZones_ToggleDenD();break;
                //清空搜索栏关键字
           case "": 
document.getElementById("searchbar").value = "";break;
                //复制选中的文本到剪贴板
           case "":
(function(){
function getSelectString(){
function getWindow(){
var focusedWindow = document.commandDispatcher.focusedWindow;
if (!focusedWindow || focusedWindow == window) return window.content;
else return focusedWindow;
}
var targetWindow = getWindow();
var sel = Components.lookupMethod(targetWindow, 'getSelection').call(targetWindow);
//インプット/テキストエリアもね
if (sel && !sel.toString()) {
var node = document.commandDispatcher.focusedElement;
if (node && (node.type == "text" || node.type == "textarea") && 'selectionStart' in node && node.selectionStart != node.selectionEnd) {
var offsetStart = Math.min(node.selectionStart, node.selectionEnd);
var offsetEnd = Math.max(node.selectionStart, node.selectionEnd);
return node.value.substr(offsetStart, offsetEnd-offsetStart);
}
}
return sel ? sel.toString() : "";
}
Components.classes["@mozilla.org/widget/clipboardhelper;1"]
.getService(Components.interfaces.nsIClipboardHelper).copyString(getSelectString());
})();break; 
                //粘贴并转到（将剪贴板里的URL粘贴到地址栏里，后台新建标签打开链接。）
                     case "LDR": 
                     var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
  if (!clip) alert("No clipboard!");
  var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
  if (!trans) alert("Clipboard not transferable!");
  trans.addDataFlavor("text/unicode");
  clip.getData(trans, clip.kGlobalClipboard);
  var data = {}, dataLen = {};
  try {
    trans.getTransferData("text/unicode", data, dataLen);
  }
  catch(err) {
    alert("Clipboard is empty!");
  }
  if (data) {
     data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
     var url = data.data.substring(0, dataLen.value / 2);
     if (gURLBar) gURLBar.value = url;
     tab = getBrowser().addTab(gURLBar.value);break;
}
                //搜索栏清除关键字并获得焦点
                     case "DRUL": 
                   var searchbar = document.getElementById('searchbar');
	if (searchbar) {
		if (searchbar.mTextbox) searchbar.mTextbox.value = "";
                searchbar.value = "";
		var evt = document.createEvent("Events");
		evt.initEvent("oninput", true, true);
		searchbar.dispatchEvent(evt);
		searchbar.focus();
	}break;
                       
                       //地址栏清除链接并获得焦点
                       case "URDL": 
                       var urlbar = document.getElementById('urlbar');
	if (urlbar) {
		urlbar.value = "";
		urlbar.focus();
	}break;
	           //[弹出菜单] 搜索所选文本用...
                //安装ConQuery Search扩展后弹出搜索引擎菜单搜索生效
					case "":
					cqrShowHotmenu("yes", mgOldX,  mgOldY, window._content.document.getSelection())
					break; 
                //开启/关闭Google Talk侧边栏
                 case "": 
                 var sidebar_box = document.getElementById('sidebar-box');
var sidebar_title = document.getElementById('sidebar-title');

if(sidebar_box.hidden) {
    if(sidebar_title.value!="Google Talk"){  // 这个判断是垃圾代码，应该去掉
        openWebPanel("Google Talk","http://talkgadget.google.com/talkgadget/popout");
    }
}
else {
    if(sidebar_title.value=="Google Talk"){
        toggleSidebar();
    }
    else {  //当前侧栏打开不是Google Talk，切到Google Talk
        openWebPanel("Google Talk","http://talkgadget.google.com/talkgadget/popout");
    }
} break;
                //转到上一级
                case "": 
                var uri = gBrowser.currentURI;
if (uri.path == "/")
    return;
var pathList = uri.path.split("/");
if (!pathList.pop())
    pathList.pop();
loadURI(uri.prePath + pathList.join("/") + "/");break;
                //清空搜索栏关键字
                case "": 
                document.getElementById("searchbar").value = "";break;
                //\

                 //未知的手势
			default: throw "\uFEFF\u672A\u77E5\u7684\u9F20\u6807\u624B\u52BF\uFF1A" + this._directionChain;
		}
	}
};
// エントリポイント
ucjsMouseGestures.init();
window.addEventListener("unload", function(){ ucjsMouseGestures.uninit(); }, false);
