拖拽打开

鼠标拖拽功能。仅支持拖拽[文本]、[链接]和[图片]

  1. // ==UserScript==
  2. // @name DragOpen
  3. // @name:zh-CN 拖拽打开
  4. // @namespace ASH
  5. // @description drag open
  6. // @description:zh-CN 鼠标拖拽功能。仅支持拖拽[文本]、[链接]和[图片]
  7. // @version 1.00
  8. // @include *
  9. // @match *
  10. // @noframes
  11. // @run-at document-end
  12. // @grant GM_addStyle
  13. // @grant GM_openInTab
  14. // @grant GM_setValue
  15. // @grant GM_getValue
  16. // @grant GM.setValue
  17. // @grant GM.getValue
  18. // @grant GM_setClipboard
  19. // @grant GM_download
  20. // @grant GM_addValueChangeListener
  21. // @grant GM_notification
  22. // @grant window.close
  23. // @grant GM_getResourceText
  24. // @grant GM_xmlhttpRequest
  25. // @license GPL-3.0
  26. // ==/UserScript==
  27. /* jshint esversion: 6 */
  28.  
  29. //===============================================================
  30. //Thanks: Robbendebiene's project Gesturefy
  31. // https://github.com/Robbendebiene/Gesturefy [GPL-3.0]
  32. //For: canvas line style & GestureHandler
  33.  
  34. //===============================================================
  35. //Thanks: Jim Lin's userscript 有道划词翻译
  36. // https://greasyfork.org/zh-CN/scripts/15844 [License MIT]
  37. //For: 划词翻译
  38.  
  39. //===============================================================
  40. //Thanks: 黄盐's userscript mouseplus
  41. // https://greasyfork.org/zh-CN/scripts/35466-mouseplus
  42.  
  43.  
  44.  
  45. (function() {
  46. 'use strict';
  47. //==========①=========================
  48. let storage = {
  49. get: function(name, defaultValue) {
  50. return GM_getValue(name, defaultValue);
  51. },
  52. set: function(name, data) {
  53. return GM_setValue(name, data);
  54. }
  55. },
  56. runtime = {
  57. sendMessage: function(data){
  58. return Promise.resolve(this.processMessage(data));
  59. },
  60. processMessage: function(data){
  61. switch (data.subject) {
  62. case 'dragChange':
  63. try {
  64. let actionName = '',
  65. typeAndData = getDragFn(data.data);
  66. if(typeAndData[1].alias)
  67. actionName = typeAndData[1].alias;
  68. else
  69. actionName = local[typeAndData[0]][typeAndData[1].name][cfg.language];
  70. return {action:actionName};
  71. } catch(e) {}
  72. break;
  73. case 'dragEnd':
  74. try {
  75. let action = getDragFn(data.data)[1];
  76. Fn[action.name](action.arg, data.data);
  77. } catch(e) {
  78. // console.log(e);
  79. }
  80. break;
  81. default:
  82. break;
  83. }
  84. },
  85. captureGesture:false
  86. },
  87. _cfg = {
  88. Gesture: {
  89. mouseButton: 2,
  90. suppressionKey: "",
  91. distanceThreshold: 10,
  92. distanceSensitivity: 10,
  93. Timeout: {
  94. active: false,
  95. duration: 1
  96. }
  97. },
  98. Hinter: {
  99. // background : 'ff0',
  100. background : '4b4b4b',
  101. fontSize: 40,
  102. lineColor: '8074d990',
  103. minLineWidth: 1,
  104. maxLineWidth: 10,
  105. lineGrowth: 0.6,
  106. funNotDefine: ' (◔ ‸◔)?'
  107. },
  108. Drag: {
  109. linktextAslink: true,
  110. dragInTextarea: true
  111. },
  112. directions: 4,
  113. language: "zh",
  114. text: { // dragText
  115. "1": {name:"copyText", arg:[]},
  116. "2": {name:"copyText", arg:[]},
  117. "4": {name:"copyText", arg:[]},
  118. "0": {
  119. name:"searchText",
  120. arg:["https://www.baidu.com/s?wd=", true, true]
  121. }
  122. },
  123. link: { // drag link
  124. "1": {name:"copyLink", arg:[]},
  125. "2": {name:"copyLink", arg:[]},
  126. "4": {name:"copyLink", arg:[]},
  127. "24": {name:"copyLink", arg:[]},
  128. "42": {name:"copyLink", arg:[]},
  129. "6": {name:"openLink", arg:[]},
  130. "0": {name:"openLinkInBack", arg:[]}
  131. },
  132. image: { // drag image
  133. "8": {name:"saveImg", arg:[]},
  134. "3": {name:"selectImg", arg:[]},
  135. "6": {
  136. name:"searchImg",
  137. arg:['https://image.baidu.com/n/pc_search?queryImageUrl=U-R-L&uptype=urlsearch', true, true]
  138. },
  139. "2": {name:"copyImgURL", arg:[]},
  140. "4": {name:"selectImg", arg:[]}
  141. },
  142. },
  143. cfg = storage.get('cfg',_cfg),
  144. Fn = {
  145. userDefine: function(argumentArr, data){
  146. try {
  147. new Function("mpArray", "mpData", mpUnescape(argumentArr[0]))(data);
  148. } catch(e) {
  149. console.log(e);
  150. }
  151. },
  152. stopLoading: function() {
  153. window.stop();
  154. },
  155. reload: function() {
  156. history.go(0);
  157. //window.location.reload();
  158. },
  159. reloadNoCache: function() {
  160. window.location.reload(true);
  161. },
  162. close: function() {
  163. window.close();
  164. },
  165. back: function() {
  166. history.back();
  167. },
  168. forward: function() {
  169. history.forward();
  170. },
  171. toTop: function() {
  172. document.documentElement.scrollTo(0, 0);
  173. },
  174. toBottom: function() {
  175. document.documentElement.scrollTo(0, 9999999);
  176. },
  177. reopenTab: function() {
  178. //GreasyMonkdy:
  179. // GM_openInTab(GM_getValue('latestTab'),false);
  180. //TamperMonkey:
  181. GM_openInTab(GM_getValue('latestTab', 'about:blank'), {
  182. active: true
  183. });
  184. },
  185. URLLevelUp: function() {
  186. //当前网址的层次结构向上一层
  187. if (window.location.href[window.location.href.length - 1] === "/")
  188. window.location.href = "../";
  189. else
  190. window.location.href = "./";
  191. },
  192. //clone curren tab ,background
  193. cloneTab: function() {
  194. GM_openInTab(location.href, {
  195. active: false
  196. });
  197. },
  198. //open new blank tab
  199. openBlankTab: function() {
  200. GM_openInTab('about:blank', {
  201. active: true
  202. });
  203. },
  204. //view source
  205. viewSource: function() {
  206. GM_openInTab('view-source:'+location.href, {
  207. active: true
  208. });
  209. },
  210. fkVip: function(argumentArr) {
  211. GM_openInTab(argumentArr[0]+location.href, {active:true});
  212. },
  213. closeOtherTabs: function() {
  214. GM_setValue('closeAll', Date());
  215. },
  216. translateSelect: function() {
  217. window.document.body.addEventListener('mouseup', translate, false);
  218. var context = new AudioContext();
  219. function translate(e) {
  220. var previous = document.querySelector('.youdaoPopup');
  221. if (previous) {
  222. document.body.removeChild(previous);
  223. }
  224. var selectObj = document.getSelection();
  225. if (selectObj.anchorNode.nodeType == 3) {
  226. var word = selectObj.toString();
  227. if (word == '') {
  228. return;
  229. }
  230. word = word.replace('-\n', '');
  231. word = word.replace('\n', ' ');
  232. var ts = new Date().getTime();
  233. var x = e.clientX;
  234. var y = e.clientY;
  235. translate(word, ts);
  236. }
  237. function popup(x, y, result) {
  238. var youdaoWindow = document.createElement('div');
  239. youdaoWindow.classList.toggle('youdaoPopup');
  240. var dict = JSON.parse(result);
  241. var query = dict.query;
  242. var errorCode = dict.errorCode;
  243. if (dict.basic) {
  244. word();
  245. } else {
  246. sentence();
  247. }
  248. youdaoWindow.style.cssText = `z-index:999999;display:block;position:fixed;color:black;text-align:left;word-wrap:break-word;background:lightBlue;border-radius:5px;box-shadow:0 0 5px 0;opacity:1;width:200px;left:${x+10}px;padding:5px`;
  249. if (x + 200 + 10 >= window.innerWidth) {
  250. youdaoWindow.style.left = parseInt(youdaoWindow.style.left) - 200 + 'px';
  251. }
  252. if (y + youdaoWindow.offsetHeight + 10 >= window.innerHeight) {
  253. youdaoWindow.style.bottom = '20px';
  254. } else {
  255. youdaoWindow.style.top = y + 10 + 'px';
  256. }
  257. document.body.appendChild(youdaoWindow);
  258. function word() {
  259. var basic = dict.basic;
  260. var header = document.createElement('p');
  261. var span = document.createElement('span');
  262. span.innerHTML = query;
  263. header.appendChild(span);
  264. var phonetic = basic.phonetic;
  265. if (phonetic) {
  266. var phoneticNode = document.createElement('span');
  267. phoneticNode.innerHTML = '[' + phonetic + ']';
  268. phoneticNode.style.cursor = 'pointer';
  269. header.appendChild(phoneticNode);
  270. phoneticNode.addEventListener('mouseup', function(e) {
  271. e.stopPropagation();
  272. }, false);
  273. var soundUrl = 'https://dict.youdao.com/dictvoice?type=2&audio={}'.replace('{}', query);
  274. var promise = new Promise(function() {
  275. GM_xmlhttpRequest({
  276. method: 'GET',
  277. url: soundUrl,
  278. responseType: 'arraybuffer',
  279. onload: function(res) {
  280. try {
  281. context.decodeAudioData(res.response, function(buffer) {
  282. phoneticNode.addEventListener('mouseup', function() {
  283. var source = context.createBufferSource();
  284. source.buffer = buffer;
  285. source.connect(context.destination);
  286. source.start(0);
  287. }, false);
  288. header.appendChild(document.createTextNode('✓'));
  289. });
  290. } catch (e) {}
  291. }
  292. });
  293. });
  294. promise.then();
  295. }
  296. header.style.color = 'darkBlue';
  297. header.style.margin = '0';
  298. header.style.padding = '0';
  299. span.style.color = 'black';
  300. youdaoWindow.appendChild(header);
  301. var hr = document.createElement('hr');
  302. hr.style.margin = '0';
  303. hr.style.padding = '0';
  304. youdaoWindow.appendChild(hr);
  305. var ul = document.createElement('ul');
  306. ul.style.margin = '0';
  307. ul.style.padding = '0';
  308. basic.explains.map(function(trans) {
  309. var li = document.createElement('li');
  310. li.style.listStyle = 'none';
  311. li.style.margin = '0';
  312. li.style.padding = '0';
  313. li.appendChild(document.createTextNode(trans));
  314. ul.appendChild(li);
  315. });
  316. youdaoWindow.appendChild(ul);
  317. }
  318. function sentence() {
  319. var ul = document.createElement('ul');
  320. ul.style.margin = '0';
  321. ul.style.padding = '0';
  322. dict.translation.map(function(trans) {
  323. var li = document.createElement('li');
  324. li.style.listStyle = 'none';
  325. li.style.margin = '0';
  326. li.style.padding = '0';
  327. li.appendChild(document.createTextNode(trans));
  328. ul.appendChild(li);
  329. });
  330. youdaoWindow.appendChild(ul);
  331. }
  332. }
  333. function translate(word, ts) {
  334. var reqUrl = 'http://fanyi.youdao.com/openapi.do?type=data&doctype=json&version=1.1&relatedUrl=' +
  335. escape('http://fanyi.youdao.com/#') +
  336. '&keyfrom=fanyiweb&key=null&translate=on' +
  337. '&q={}'.replace('{}', word) +
  338. '&ts={}'.replace('{}', ts);
  339. GM_xmlhttpRequest({
  340. method: 'GET',
  341. url: reqUrl,
  342. onload: function(res) {
  343. popup(x, y, res.response);
  344. }
  345. });
  346. }
  347. }
  348. },
  349. contentEditable: function(argumentArr, data){
  350. data.target.self.setAttribute('contenteditable', 'true');
  351. data.target.self.setAttribute('data-mp', '1');
  352. },
  353. /*
  354. //not torking
  355. zoomIn: function(){
  356. setTimeout(zoomer, 200);
  357. function zoomer(evt){
  358. let a, b,isZoom = true;
  359. a = document.elementFromPoint(evt.clientX,evt.clientY).style.zoom=cfg.zoom;
  360. a.setAttribute('data-zoom', 'true');
  361. [].every.forEach(document.querySelectorAll('*[data-zoom=true]'), function(item){
  362. if (item !== a) item.style.zoom = null;
  363. });
  364. }
  365. },*/
  366.  
  367. searchText: function(argumentArr, data) {
  368. GM_openInTab(argumentArr[0] + encodeURIComponent(data.textSelection),
  369. {
  370. active: argumentArr[1] != "false",
  371. insert: argumentArr[2] != "false",
  372. setParent: true //makes the browser re-focus the current tab on close.
  373. });
  374. },
  375. copyText: function(argumentArr, data) {
  376. GM_setClipboard(data.textSelection, "text");
  377. },
  378. openLink: function(argumentArr, data) {
  379. //TamperMonkey
  380. GM_openInTab(getLink(data), {
  381. active: true
  382. });
  383. },
  384. openLinkInBack: function(argumentArr, data) {
  385. //TamperMonkey
  386. GM_openInTab(getLink(data), {
  387. active: false
  388. });
  389. },
  390. copyLink: function(argumentArr, data) {
  391. GM_setClipboard(getLink(data), "text");
  392. },
  393. copyLinkText: function(argumentArr, data) {
  394. GM_setClipboard(data.target.textContent || data.textSelection, "text");
  395. },
  396. saveImg: function(argumentArr, data) {
  397. //TamperMonkey
  398. let name = data.target.src.split('/').pop();
  399. GM_download(data.target.src, name);
  400. //method 2
  401. /*
  402. let a = document.createElement('a');
  403. a.href = dObj.img; a.setAttribute('download', dObj.img.split('/').pop());
  404. document.documentElement.appendChild(a);
  405. a.click();
  406. a.parentElement.remove(a);
  407. */
  408. /* //jQuery:
  409. $("<a>").attr("href", actionFn.request.selimg).attr("download", actionFn.request.selimg.split('/').pop()).appendTo("body");
  410. a[0].click();
  411. a.remove();
  412. */
  413. },
  414. searchImg: function(argumentArr, data) {
  415. //TamperMonkey
  416. GM_openInTab(argumentArr[0].replace(/U-R-L/, data.target.src), {
  417. active: argumentArr[1] != "false",
  418. insert: argumentArr[2] != "false",
  419. setParent: true //not working
  420. });
  421. },
  422. selectImg: function(argumentArr, data) {
  423. // it may not working on some browsers [develping standard]
  424. //TamperMonkey
  425. document.execCommand('selectAll');
  426. let sel = document.getSelection();
  427. sel.collapse(data.target.self, 0);
  428. sel.modify("extend", "forward", "character");
  429. },
  430. //not working:
  431. copyImage: function(e) {
  432. let canvas = canvasDrawTheImage(e);
  433. // get image as blob
  434. canvas.canvas.toBlob((blob) => {
  435. GM_setClipboard(blob, {
  436. type: canvas.type,
  437. mimetype: canvas.mime
  438. });
  439. }, canvas.mime);
  440. },
  441. image2DataURL: function(e) {
  442. //canvas绘制图片,由于浏览器的安全考虑:
  443. //如果在使用canvas绘图的过程中,使用到了外域的图片资源,那么在toDataURL()时会抛出安全异常:
  444. let canvas = canvasDrawTheImage(e).canvas;
  445. let dataURL = canvas.toDataURL();
  446. GM_setClipboard(dataURL, "text");
  447. },
  448. copyImgURL: function(argumentArr, data) {
  449. //TamperMonkey
  450. GM_setClipboard(data.target.src, "text");
  451. },
  452. openImgNewTab: function(argumentArr, data) {
  453. //TamperMonkey
  454. GM_openInTab(data.target.src, {
  455. active: true
  456. });
  457. },
  458. setting: function() {
  459. if (document.getElementById('MPsetting')) {
  460. return;
  461. }else Ui.init();
  462. }
  463. },
  464. local = {
  465. gesture:{
  466. stopLoading: {zh:'停止加载', en:'StopLoading'},
  467. reload: {zh:'刷新', en:'Refresh'},
  468. reloadNoCache: {zh:'清缓存刷新', en:'Refresh Without Cache'},
  469. close: {zh:'关闭', en:'Close'},
  470. back: {zh:'后退', en:'Back'},
  471. forward: {zh:'前进', en:'Forward'},
  472. toTop: {zh:'到顶部', en:'Scroll to Top'},
  473. toBottom: {zh:'到底部', en:'Scroll to Bottom'},
  474. reopenTab: {zh:'打开最近关闭窗口', en:'Reopen Latest Closed Window'},
  475. setting: {zh:'设置', en:'Settings'},
  476. URLLevelUp: {zh:'网址向上一层', en:'URL hierarchy up'},
  477. cloneTab: {zh:'克隆标签页', en:'Duplicate This Tab'},
  478. openBlankTab: {zh:'打开空白页', en:'Open New Blank Tab'},
  479. viewSource: {zh:'看网页源代码', en:'View Source'},
  480. fkVip: {zh:'破解VIP视频', en:'Crack to Watch VIP Video'},
  481. closeOtherTabs: {zh:'关闭其他标签', en:'Close Other Tabs'},
  482. translateSelect: {zh:'开启划词翻译', en:'Turn on Select And Translate'},
  483. //开发者功能
  484. contentEditable: {zh:'元素内容可编辑', en:'Element Content Editable'},
  485. userDefine: {zh:'自定义', en:'User Define'}
  486. },
  487. //drag text
  488. text: {
  489. searchText: {zh:'搜索选中文本', en:'Search Selected Text'},
  490. copyText: {zh:'复制选中文本', en:'Copy Selected Text'},
  491. userDefine: {zh:'自定义', en:'User Define'}
  492. },
  493. //drag link
  494. link:{
  495. openLink: {zh:'打开链接', en:'Open Link'},
  496. openLinkInBack: {zh:'后台打开', en:'Open Link In back'},
  497. copyLink: {zh:'复制链接', en:'Copy Link'},
  498. copyLinkText: {zh:'复制链接文字', en:'Copy Link Text'},
  499. userDefine: {zh:'自定义', en:'User Define'}
  500. },
  501. //drag image
  502. image:{
  503. saveImg: {zh:'保存图片', en:'Save Image'},
  504. searchImg: {zh:'搜索图片', en:'Search Image'},
  505. // copyImage: {zh:'复制图片', en:'Copy Image to ClickBoard'},
  506. copyImgURL: {zh:'复制图片链接', en:'Copy ImageURL'},
  507. openImgNewTab: {zh:'新标签打开图片', en:'Open Image in New Tab'},
  508. // image2DataURL: {zh:'复制图片为DataURL',en:'Copy Image as DataURL'},
  509. selectImg: {zh:'选中图片', en:'Select This Image'},
  510. userDefine: {zh:'自定义', en:'User Define'}
  511. }
  512. };
  513.  
  514. //========②supported functions=======
  515. function getLink(data){
  516. if(data.link)
  517. return data.link.href;
  518. else if(data.target.src)
  519. return data.target.src;
  520. else return data.textSelection;
  521. }
  522.  
  523. //--> check if string is an url
  524. function isURL (string) {
  525. try {
  526. new URL(string);
  527. }
  528. catch (e) {
  529. return false;
  530. }
  531. return true;
  532. }
  533.  
  534. //--> checks if the current window is framed or not
  535. function inIframe () {
  536. try {
  537. return window.self !== window.top;
  538. }
  539. catch (e) {
  540. return true;
  541. }
  542. }
  543.  
  544. //--> returns all available data of the given target
  545. //--> this data is used by some background actions
  546. function getTargetData(target) {
  547. let data = {};
  548.  
  549. data.target = {
  550. src: target.currentSrc || target.src || null,
  551. title: target.title || null,
  552. alt: target.alt || null,
  553. textContent: target.textContent.trim(),
  554. nodeName: target.nodeName,
  555. self: target
  556. };
  557.  
  558. let link = getClosestLink(target);
  559. if (link) {
  560. data.link = {
  561. href: link.href || null,
  562. title: link.title || null,
  563. textContent: link.textContent.trim()
  564. };
  565. }
  566.  
  567. data.textSelection = getTextSelection();
  568.  
  569. return data;
  570. }
  571.  
  572. //--> returns the selected text, if no text is selected it will return an empty string
  573. //--> inspired by https://stackoverflow.com/a/5379408/3771196
  574. function getTextSelection () {
  575. // get input/textfield text selection
  576. if (document.activeElement &&
  577. typeof document.activeElement.selectionStart === 'number' &&
  578. typeof document.activeElement.selectionEnd === 'number') {
  579. return document.activeElement.value.slice(
  580. document.activeElement.selectionStart,
  581. document.activeElement.selectionEnd
  582. );
  583. }
  584. // get normal text selection
  585. return window.getSelection().toString();
  586. }
  587.  
  588. //--> calculates and returns the distance
  589. //--> between to points
  590. function getDistance(x1, y1, x2, y2) {
  591. return Math.hypot(x2 - x1, y2 - y1);
  592. }
  593.  
  594. //--> returns the closest hierarchical link node or null of given element
  595. function getClosestLink (node) {
  596. // bubble up the hierarchy from the target element
  597. while (node !== null && node.nodeName.toLowerCase() !== "a" && node.nodeName.toLowerCase() !== "area")
  598. node = node.parentElement;
  599. return node;
  600. }
  601. function getDirection(x, y, cx, cy){
  602. /*=================
  603. | |
  604. | 1↖ 2↑ 3↗ |
  605. | |
  606. | 4← 5 6→ |
  607. | |
  608. | 7↙ 8↓ 9↘ |
  609. | |
  610. |=================*/
  611. let d, t;
  612. if(cfg.directions == 4){ //4 directions
  613. if (Math.abs(cx - x) < Math.abs(cy - y)) {
  614. d = cy > y ? "8" : "2";
  615. } else {
  616. d = cx > x ? "6" : "4";
  617. }
  618. }else{ //8 directions
  619. t = (cy-y)/(cx-x);
  620. if (-0.4142<= t && t < 0.4142) d = cx > x ? '6' : "4";
  621. else if(2.4142 <= t || t< -2.4142) d = cy > y ? '8' : '2';
  622. else if(0.4142 <= t && t < 2.4142) d = cx > x ? '9' : '1';
  623. else d = cy > y ? '7' : '3';
  624. }
  625. return d;
  626. }
  627. // data: data.data
  628. function getDragFn(data){
  629. // let
  630. if(data.target.nodeName === "IMG")
  631. return ['image',cfg.image[data.gesture]];
  632. else if(data.link || data.target.nodeName === "A" || isURL(data.textSelection))
  633. return ['link', cfg.link[data.gesture] ? cfg.link[data.gesture] : cfg.link[0]];
  634. else
  635. return ['text', cfg.text[data.gesture]];
  636. }
  637.  
  638. function mpEscape(str){
  639. if(!str) return;
  640. return str.replace(/"/g, "&quot;").replace(/'/g, "&apos;");
  641. }
  642. function mpUnescape(str){
  643. if(!str) return;
  644. return str.replace(/&quot;/g,'"').replace(/&apos;/g, "'");
  645. }
  646.  
  647. //========③Hinter====================
  648. const Hinter = (function(){
  649. let modul = {};
  650.  
  651. modul.enable = function enable(){
  652. GestureHandler
  653. .on("start", addCanvas)
  654. .on("update", updateTrack)
  655. .on("change", updateHint)
  656. .on("abort", reset)
  657. .on("end", reset);
  658. };
  659.  
  660. modul.applySettings = function applySettings(Config){
  661. background = Config.Hinter.background;
  662. fontSize = Config.Hinter.fontSize;
  663. lineColor = Config.Hinter.lineColor;
  664. minLineWidth = Config.Hinter.minLineWidth;
  665. maxLineWidth = Config.Hinter.maxLineWidth;
  666. lineGrowth = Config.Hinter.lineGrowth;
  667. funNotDefine = Config.Hinter.funNotDefine;
  668. updateHintLayer();
  669. };
  670.  
  671. //private methods & value
  672. let
  673. background = 'ff0',
  674. fontSize = 40,
  675. lineColor = '0074d990',
  676. minLineWidth = 1,
  677. maxLineWidth = 10,
  678. lineGrowth = 0.6,
  679. funNotDefine = ' (◔ ‸◔)?';
  680. let canvas = null,
  681. tip = null,
  682. ctx = null,
  683. hasCanvas = false;
  684.  
  685. function updateHintLayer(){
  686. canvas = tip = ctx = hasCanvas = null;
  687. createCanvaTips();
  688. }
  689. function createCanvaTips(){
  690. //create <canvas>
  691. canvas = document.createElement("canvas");
  692. canvas.id = 'MPcanvas';
  693. ctx = canvas.getContext("2d");
  694. //create tips<div>
  695. tip = document.createElement('div');
  696. tip.id = 'MPtips';
  697. tip.style.cssText = `background:#${background} !important; font-size: ${fontSize}px !important;`;
  698. }
  699. //<canvas> & tip<div> is ready, when mousemove or drag, append to show track & tips
  700. function addCanvas(e) {
  701. if(!canvas || !tip) createCanvaTips();
  702. document.documentElement.appendChild(tip); //append tip <div>
  703. document.documentElement.appendChild(canvas); //append <canvas>
  704. canvas.width = window.innerWidth; //set canvas attribute to clear content
  705. canvas.height = window.innerHeight;
  706. ctx.lineCap = "round";
  707. ctx.lineJoin = "round";
  708. if(lineColor.length>6) canvas.style.opacity = parseInt(lineColor.slice(6),16)/255;
  709. canvas.style.opacity = 0.3;
  710. ctx.lineWidth = minLineWidth;
  711. ctx.strokeStyle = '#' + lineColor.slice(0,6); //like delicious link color//line color
  712. hasCanvas = true;
  713. //allow drop
  714. tip.addEventListener('dragover', ()=>event.preventDefault(), false);
  715. canvas.addEventListener('dragover', ()=>event.preventDefault(), false);
  716. }
  717. //remove <canvas> and tips<div>,set flags to false
  718. function reset() {
  719. if (hasCanvas) {
  720. document.documentElement.removeChild(canvas);
  721. tip.innerHTML = '';
  722. document.documentElement.removeChild(tip);
  723. }
  724. hasCanvas = false;
  725. }
  726. //show Tips
  727. function updateHint(gesture,fnName){
  728. tip.innerHTML = gesture.join("") + '<br/>' + (fnName ? fnName : funNotDefine);
  729. }
  730. function updateTrack(x,y){
  731. if (hasCanvas) {
  732. ctx.lineWidth = Math.min(maxLineWidth, ctx.lineWidth += lineGrowth);
  733. ctx.lineTo(x, y);
  734. ctx.stroke();
  735. ctx.closePath();
  736. ctx.beginPath();
  737. ctx.moveTo(x, y);
  738. }
  739. }
  740. // due to modul pattern: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
  741. return modul;
  742. })();
  743.  
  744. //========④GesturedHadler============
  745. //--> GestureHandler "singleton" class using the modul pattern
  746. //--> the handler behaves different depending on whether it's injected in a frame or not
  747. //--> frame: detects gesture start, move, end and sends an indication message
  748. //--> main page: detects whole gesture including frame indication messages and reports it to the background script
  749. //--> provides 4 events: on start, update, change and end
  750. //--> on default the handler is disabled and must be enabled via enable()
  751. //--> REQUIRES: contentCommons.js
  752. const GestureHandler = (function() {
  753. // public variables and methods
  754. let modul = {};
  755.  
  756. //-->Add callbacks to the given events
  757. modul.on = function on(event, callback) {
  758. // if event does not exist or function already applied skip it
  759. if (event in events && !events[event].includes(callback))
  760. events[event].push(callback);
  761. return this;
  762. };
  763.  
  764. //-->applies necessary settings
  765. modul.applySettings = function applySettings(Settings) {
  766. mouseButton = Number(Settings.Gesture.mouseButton);
  767. suppressionKey = Settings.Gesture.suppressionKey;
  768. distanceSensitivity = Settings.Gesture.distanceSensitivity;
  769. distanceThreshold = Settings.Gesture.distanceThreshold;
  770. timeoutActive = Settings.Gesture.Timeout.active;
  771. timeoutDuration = Settings.Gesture.Timeout.duration;
  772. };
  773.  
  774. //-->Add the event listeners
  775. modul.enable = function enable() {
  776. if (inIframe()) {
  777. window.addEventListener('mousedown', handleFrameMousedown, true);
  778. window.addEventListener('mousemove', handleFrameMousemove, true);
  779. window.addEventListener('mouseup', handleFrameMouseup, true);
  780. window.addEventListener('dragstart', handleDragstart, true);
  781. } else {
  782. // chrome.runtime.onMessage.addListener(handleMessage);
  783. window.addEventListener('mousedown', handleMousedown, true);
  784. }
  785. };
  786.  
  787. //-->Remove the event listeners and resets the handler
  788. modul.disable = function disable() {
  789. if (inIframe()) {
  790. window.removeEventListener('mousedown', handleFrameMousedown, true);
  791. window.removeEventListener('mousemove', handleFrameMousemove, true);
  792. window.removeEventListener('mouseup', handleFrameMouseup, true);
  793. window.removeEventListener('dragstart', handleDragstart, true);
  794. } else {
  795. // chrome.runtime.onMessage.removeListener(handleMessage);
  796. window.removeEventListener('mousedown', handleMousedown, true);
  797. window.removeEventListener('mousemove', handleMousemove, true);
  798. window.removeEventListener('mouseup', handleMouseup, true);
  799. window.removeEventListener('contextmenu', handleContextmenu, true);
  800. window.removeEventListener('mouseout', handleMouseout, true);
  801. window.removeEventListener('dragstart', handleDragstart, true);
  802. // reset gesture array, internal state and target data
  803. directions = [];
  804. state = "passive";
  805. targetData = {};
  806. }
  807. };
  808.  
  809. // private variables and methods
  810.  
  811. // setting properties
  812. let mouseButton = 2,
  813. dragButton = 1,//MP
  814. suppressionKey = "",
  815. distanceThreshold = 10,
  816. distanceSensitivity = 10,
  817. timeoutActive = false,
  818. timeoutDuration = 1;
  819.  
  820. // contains all gesture direction letters
  821. let directions = [];
  822.  
  823. // internal state: passive, pending, active
  824. let state = "passive";
  825.  
  826. // holds reference point to current point
  827. let referencePoint = {
  828. x: 0,
  829. y: 0
  830. };
  831.  
  832. // contains the timeout identifier
  833. let timeout = null;
  834.  
  835. // contains relevant data of the target element
  836. let targetData = {};
  837.  
  838. // holds all event callbacks added by on()
  839. let events = {
  840. 'start': [],
  841. 'update': [],
  842. 'change': [],
  843. 'abort': [],
  844. 'end': []
  845. };
  846.  
  847. //-->initializes the gesture to the "pending" state, where it's unclear if the user is starting a gesture or not
  848. //-->requires the current x and y coordinates
  849. function init(x, y) {
  850. // set the initial point
  851. referencePoint.x = x;
  852. referencePoint.y = y;
  853.  
  854. // change internal state
  855. state = "pending";
  856.  
  857. // add gesture detection listeners
  858. window.addEventListener('mousemove', handleMousemove, true);
  859. window.addEventListener('dragstart', handleDragstart, true);
  860. window.addEventListener('drag', handleDrag, true);//MP
  861. window.addEventListener('dragend', handleDragend, true);//MP
  862. window.addEventListener('contextmenu', handleContextmenu, true);
  863. window.addEventListener('mouseup', handleMouseup, true);
  864. window.addEventListener('mouseout', handleMouseout, true);
  865. }
  866.  
  867. //-->Indicates the gesture start and should only be called once untill gesture end
  868. function start() {
  869. // dispatch all binded functions with the current x and y coordinates as parameter on start
  870. events['start'].forEach((callback) => callback(referencePoint.x, referencePoint.y));
  871.  
  872. // change internal state
  873. state = "active";
  874. }
  875.  
  876. //-->Indicates the gesture change and should be called every time the cursor position changes
  877. //-->requires the current x and y coordinates
  878. function update(x, y, dragMark) {
  879. // dispatch all binded functions with the current x and y coordinates as parameter on update
  880. events['update'].forEach((callback) => callback(x, y));
  881.  
  882. // handle timeout
  883. if (timeoutActive) {
  884. // clear previous timeout if existing
  885. if (timeout) window.clearTimeout(timeout);
  886. timeout = window.setTimeout(() => {
  887. // dispatch all binded functions on abort
  888. events['abort'].forEach((callback) => callback());
  889. state = "expired";
  890. // clear directions
  891. directions = [];
  892. }, timeoutDuration * 1000);
  893. }
  894.  
  895. let direction = getDirection(referencePoint.x, referencePoint.y, x, y);
  896.  
  897. if (directions[directions.length - 1] !== direction) {
  898. // add new direction to gesture list
  899. directions.push(direction);
  900.  
  901. // send message to background on gesture change
  902. let message = runtime.sendMessage({
  903. // subject: "gestureChange",
  904. subject: dragMark ? "dragChange" : "gestureChange",//MP
  905. data: Object.assign(//MP
  906. targetData, {
  907. gesture: directions.join("")
  908. })
  909. });
  910. // on response (also fires on no response) dispatch all binded functions with the directions array and the action as parameter
  911. message.then((response) => {
  912. let action = response ? response.action : null;
  913. events['change'].forEach((callback) => callback(directions, action));
  914. });
  915. }
  916.  
  917. // set new reference point
  918. referencePoint.x = x;
  919. referencePoint.y = y;
  920. }
  921.  
  922. //-->Indicates the gesture end and should be called to terminate the gesture
  923. function end(dragMark) {
  924. // dispatch all binded functions on end
  925. events['end'].forEach((callback) => callback(directions));
  926.  
  927. // send directions and target data to background if directions is not empty
  928. if (directions.length) runtime.sendMessage({
  929. // subject: "gestureEnd",
  930. subject: dragMark ? "dragEnd" : "gestureEnd",
  931. data: Object.assign(
  932. targetData, {
  933. gesture: directions.join("")
  934. }
  935. )
  936. });
  937.  
  938. // reset gesture handler
  939. reset();
  940. }
  941.  
  942. //-->Resets the handler to its initial state
  943. function reset() {
  944. // remove gesture detection listeners
  945. window.removeEventListener('mousemove', handleMousemove, true);
  946. window.removeEventListener('mouseup', handleMouseup, true);
  947. window.removeEventListener('contextmenu', handleContextmenu, true);
  948. window.removeEventListener('mouseout', handleMouseout, true);
  949. window.removeEventListener('dragstart', handleDragstart, true);
  950. window.removeEventListener('drag', handleDrag, true);//MP
  951. window.removeEventListener('dragend', handleDragend, true);//MP
  952.  
  953. // reset gesture array, internal state and target data
  954. directions = [];
  955. state = "passive";
  956. targetData = {};
  957.  
  958. if (timeout) {
  959. window.clearTimeout(timeout);
  960. timeout = null;
  961. }
  962. }
  963.  
  964. //-->Handles iframe/background messages which will update the gesture
  965. function handleMessage(message, sender, sendResponse) {
  966.  
  967. switch (message.subject) {
  968. case "gestureFrameMousedown":
  969. // init gesture
  970. init(
  971. Math.round(message.data.screenX / window.devicePixelRatio - window.mozInnerScreenX),
  972. Math.round(message.data.screenY / window.devicePixelRatio - window.mozInnerScreenY)
  973. );
  974. // save target data
  975. targetData = message.data;
  976. break;
  977.  
  978. case "gestureFrameMousemove":
  979. // calculate distance between the current point and the reference point
  980. let distance = getDistance(referencePoint.x, referencePoint.y,
  981. Math.round(message.data.screenX / window.devicePixelRatio - window.mozInnerScreenX),
  982. Math.round(message.data.screenY / window.devicePixelRatio - window.mozInnerScreenY)
  983. );
  984. // induce gesture
  985. if (state === "pending" && distance > distanceThreshold)
  986. start();
  987. // update gesture && mousebutton fix: right click on frames is sometimes captured by both event listeners which leads to problems
  988. else if (state === "active" && distance > distanceSensitivity && mouseButton !== 2) update(
  989. Math.round(message.data.screenX / window.devicePixelRatio - window.mozInnerScreenX),
  990. Math.round(message.data.screenY / window.devicePixelRatio - window.mozInnerScreenY)
  991. );
  992. break;
  993.  
  994. case "gestureFrameMouseup":
  995. if (state === "active" || state === "expired") end();
  996. else if (state === "pending") reset();
  997. break;
  998. }
  999. }
  1000.  
  1001. //-->Handles mousedown which will add the mousemove listener
  1002. function handleMousedown(event) {
  1003. // on mouse button and no supression key
  1004. if (event.isTrusted && (event.buttons === mouseButton || event.buttons === dragButton) && (!suppressionKey || (suppressionKey in event && !event[suppressionKey]))) {//MP
  1005. // init gesture
  1006. init(event.clientX, event.clientY);
  1007.  
  1008. // save target to global variable if exisiting
  1009. if (typeof TARGET !== 'undefined') TARGET = event.target;
  1010.  
  1011. // get and save target data
  1012. targetData = getTargetData(event.target);
  1013.  
  1014. // prevent and middle click scroll
  1015. if (mouseButton === 4) event.preventDefault();
  1016. }
  1017. }
  1018.  
  1019. //-->Handles mousemove which will either start the gesture or update it
  1020. function handleMousemove(event) {
  1021. if (event.isTrusted && event.buttons === mouseButton) {
  1022. // calculate distance between the current point and the reference point
  1023. let distance = getDistance(referencePoint.x, referencePoint.y, event.clientX, event.clientY);
  1024.  
  1025. // induce gesture
  1026. if (state === "pending" && distance > distanceThreshold)
  1027. start();
  1028.  
  1029. // update gesture
  1030. else if (state === "active" && distance > distanceSensitivity)
  1031. update(event.clientX, event.clientY);
  1032.  
  1033. // prevent text selection
  1034. if (mouseButton === 1) window.getSelection().removeAllRanges();
  1035. }
  1036. }
  1037.  
  1038. //-->Handles context menu popup and removes all added listeners
  1039. function handleContextmenu(event) {
  1040. if (event.isTrusted && mouseButton === 2) {
  1041. if (state === "active" || state === "expired") {
  1042. // prevent context menu
  1043. event.preventDefault();
  1044. end();
  1045. }
  1046. // reset if state is pending
  1047. else if (state === "pending")
  1048. reset();
  1049. }
  1050. }
  1051.  
  1052. //-->Handles mouseup and removes all added listeners
  1053. function handleMouseup(event) {
  1054. // only call on left and middle mouse click to terminate gesture
  1055. if (event.isTrusted && ((event.button === 0 && mouseButton === 1) || (event.button === 1 && mouseButton === 4))) {
  1056. if (state === "active" || state === "expired")
  1057. end();
  1058. // reset if state is pending
  1059. else if (state === "pending")
  1060. reset();
  1061. }
  1062. }
  1063.  
  1064. //-->Handles mouse out and removes all added listeners
  1065. function handleMouseout(event) {
  1066. // only call if cursor left the browser window
  1067. if (event.isTrusted && event.relatedTarget === null) {
  1068. if (state === "active" || state === "expired")
  1069. end();
  1070. // reset if state is pending
  1071. else if (state === "pending")
  1072. reset();
  1073. }
  1074. }
  1075.  
  1076. //-->Handles dragstart and prevents it if needed
  1077. function handleDragstart(event) {
  1078. // prevent drag if mouse button and no supression key is pressed
  1079. if (event.isTrusted && event.buttons === mouseButton && (!suppressionKey || (suppressionKey in event && !event[suppressionKey])))
  1080. event.preventDefault();
  1081. }
  1082.  
  1083. //-->Handles drag MP
  1084. function handleDrag(event) {
  1085. // prevent drag if mouse button and no supression key is pressed
  1086. if (event.isTrusted && event.buttons === dragButton && (!suppressionKey || (suppressionKey in event && !event[suppressionKey]))){
  1087. let distance = getDistance(referencePoint.x, referencePoint.y, event.clientX, event.clientY);
  1088.  
  1089. // induce gesture
  1090. if (state === "pending" && distance > distanceThreshold)
  1091. start();
  1092.  
  1093. // update gesture
  1094. else if (state === "active" && distance > distanceSensitivity)
  1095. update(event.clientX, event.clientY, 'dragMark');
  1096. }
  1097. }
  1098.  
  1099. //-->Handles dragsend MP
  1100. function handleDragend(event) {
  1101. if (event.isTrusted && ((event.button === 0 && mouseButton === 1) || (event.button === 1 && mouseButton === 4) || event.button === 0 && dragButton === 1)) {//MP
  1102. // if (event.isTrusted && ((event.button === 0 && gestureHandler.mouseButton === 1) || (event.button === 1 && gestureHandler.mouseButton === 4))) {
  1103. if (state === "active" || state === "expired")
  1104. end("dragMark");
  1105. // reset if state is pending
  1106. else if (state === "pending")
  1107. reset();
  1108. }
  1109. }
  1110.  
  1111. //-->Handles mousedown for frames; send message with target data and position
  1112. function handleFrameMousedown(event) {
  1113. // on mouse button and no supression key
  1114. if (event.isTrusted && event.buttons === mouseButton && (!suppressionKey || (suppressionKey in event && !event[suppressionKey]))) {
  1115. runtime.sendMessage({
  1116. subject: "gestureFrameMousedown",
  1117. data: Object.assign(
  1118. getTargetData(event.target), {
  1119. screenX: event.screenX,
  1120. screenY: event.screenY,
  1121. }
  1122. )
  1123. });
  1124. // save target to global variable if exisiting
  1125. if (typeof TARGET !== 'undefined') TARGET = event.target;
  1126. // prevent middle click scroll
  1127. if (mouseButton === 4) event.preventDefault();
  1128. }
  1129. }
  1130.  
  1131. //-->Handles mousemove for frames; send message with position
  1132. function handleFrameMousemove(event) {
  1133. // on mouse button and no supression key
  1134. if (event.isTrusted && event.buttons === mouseButton && (!suppressionKey || (suppressionKey in event && !event[suppressionKey]))) {
  1135. runtime.sendMessage({
  1136. subject: "gestureFrameMousemove",
  1137. data: {
  1138. screenX: event.screenX,
  1139. screenY: event.screenY
  1140. }
  1141. });
  1142. // prevent text selection
  1143. if (mouseButton === 1) window.getSelection().removeAllRanges();
  1144. }
  1145. }
  1146.  
  1147. //--> Handles mouseup for frames
  1148. function handleFrameMouseup(event) {
  1149. // only call on left, right and middle mouse click to terminate or reset gesture
  1150. if (event.isTrusted && ((event.button === 0 && mouseButton === 1) || (event.button === 1 && mouseButton === 4) || (event.button === 2 && mouseButton === 2)))
  1151. runtime.sendMessage({
  1152. subject: "gestureFrameMouseup",
  1153. data: {}
  1154. });
  1155. }
  1156.  
  1157. // due to modul pattern: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
  1158. return modul;
  1159. })();
  1160.  
  1161. //========⑤Setting===================
  1162. const Ui = (function(){
  1163. let modul = {};
  1164. modul.init = function (){
  1165. addStyle(CSS, 'MPmanageStyle');
  1166.  
  1167. let node = document.createElement('div');
  1168. node.id = 'MPsetting';
  1169. node.innerHTML = menuHTML;
  1170. document.body.appendChild(node);
  1171.  
  1172. //#mg1
  1173. q('#mg1')[0].innerHTML = gestureAndDragHTML;
  1174. //#mg2
  1175. q('#mg2')[0].innerHTML = makeFunsList();
  1176. each(['gesture', 'text', 'link', 'image'],(item)=>{
  1177. q('#mg2')[0].innerHTML += makeDefinedFunsList(item);
  1178. });
  1179. //#mg3
  1180. q('#mg3')[0].innerHTML = aboutHTML;
  1181.  
  1182. //addEventListener
  1183. listen(q('#MPsetting')[0], 'click', click);
  1184. each(q('#mg1 input[type=text], #mg2 span[name="alias"]'),item=>{
  1185. listen(item, 'blur', updateConfigUi);
  1186. });
  1187. each(q('#MPsetting select, #MPsetting input[type=checkbox]'),item=>{
  1188. listen(item, 'change', updateConfigUi);
  1189. });
  1190. //show functions,hide others
  1191. q('li[name=mg2]')[0].click();
  1192. };
  1193.  
  1194. modul.captureGesture = function(gestureStr, operation){
  1195. try {
  1196. if(operation === "recorddingGesture"){
  1197. q('#recorddingGesture')[0].textContent = gestureStr;
  1198. return;
  1199. }
  1200. if(operation !== "cancelGesture") q('[data-flag=captureGesture]')[0].value = gestureStr;
  1201. document.body.removeChild(q('#MPMask')[0]);
  1202. runtime.captureGesture = false;
  1203. attr(q('#MPsetting')[0], "style", " ");
  1204. let tmp = q('[data-flag=captureGesture]')[0];
  1205. attr(tmp, "data-flag", " ");
  1206. updateFns(tmp.parentElement);
  1207. } catch(e) {
  1208. // console.log(e);
  1209. }
  1210. };
  1211.  
  1212. let
  1213. fnLocal = {
  1214. arg: {
  1215. userDefine:{
  1216. description:{zh:['自定义功能代码'], en:['User Define Function Code']},
  1217. arg:['textarea']
  1218. },
  1219. searchText:{
  1220. description:{zh:['搜索引擎', '后台打开', '右边插入'], en:['SearchingEnging', 'Load In Background', 'Insert After Current Tab']},
  1221. arg:['select:searchEnging', 'checkbox', 'checkbox']
  1222. },
  1223. searchImg:{
  1224. description:{zh:['图片搜索引擎', '后台打开', '右边插入'], en:['Image SearchingEnging', 'Load In Background', 'Insert After Current Tab']},
  1225. arg:['select:imgSearchEnging', 'checkbox', 'checkbox']
  1226. },
  1227. fkVip:{
  1228. description:{zh:['视频解析接口'], en:['Videos Parser API']},
  1229. arg:['select:vipAPI']
  1230. }
  1231. },
  1232. FunsListTitle: {
  1233. gesture: {zh:'手势', en:'Gesture'},
  1234. text: {zh:'拖拽文本', en:'Drag Text'},
  1235. link: {zh:'拖拽链接', en:'Drag Link'},
  1236. image: {zh:'拖拽图片', en:'Drag Image'}
  1237. },
  1238. addFunction: {zh:'增加一个功能', en:'Add Function'}
  1239. },
  1240. CSS = `
  1241. #MPsetting{z-index:999997!important;background:white!important;width:100%!important;height:100%!important;color:#032E58!important;font-family:"微软雅黑"!important;position:fixed!important;top:0!important;left:0!important;}
  1242. #MPmenu *,
  1243. .MPcontent *{border-radius:3px!important;font-size:16px!important;}
  1244. #MPlogo svg{background:white!important;box-shadow:inset 0 0 25px 15px #A2B7D2!important;width:80px!important;height:100px!important;margin:0!important;padding:0!important;}
  1245. #MPmenu{z-index:999999!important;height:100%!important;width:100px!important;background:#A2B7D2!important;color:white!important;text-align:center!important;}
  1246. #MPmenu li{list-style-type:none!important;border-top:1px dashed white!important;margin:10px 15px!important;cursor:pointer;}
  1247. .MPselected,#MPmenu li:hover{background:white!important;color:#A2B7D2!important;}
  1248. #MPmenu li span{display:block!important;width:40px!important;height:40px!important;font-size:35px!important;font-weight:bold!important;padding:0 15px!important;}
  1249. #MPmenu b{display:block!important;width:70px!important;text-align:center!important;margin-top:10px!important;}
  1250. .MPcontent{height:94%!important;width:100%!important;overflow-y:scroll!important;position:absolute!important;left:100px!important;top:0!important;z-index:999998!important;padding:20px!important;}
  1251. .MPcontent h1{display:block!important;width:800px!important;font-size:20px!important;float:left!important;top:0!important;left:90px!important;padding:3px 10px!important;margin:0 5px!important;border-left:5px solid #A2B7D2!important;background:#A2B7D259!important;}
  1252. .MPcontent > li{list-style-type:none!important;width:800px!important;height:auto!important;padding:10px 5px 0px 5px!important;margin:5px 20px!important;float:left!important;border-bottom:1px dashed #00000020!important;}
  1253. .MPcontent > li:hover{box-shadow:inset 1px 1px 1px 3px #A2B7D240!important;}
  1254. #mg1 >li span:nth-child(2),#mg2>li>input{max-height:28px!important;float:right!important;}
  1255. #mg1 input[type="text"],#mg1 select,#mg2 input[readonly="readonly"]{width:250px!important;height:26px!important;margin:0 10px!important;text-align:center!important;border:0!important;background:#0000000C!important;font-size:20px!important;}
  1256. .MPcontent input[type="checkbox"]{width:0!important;}
  1257. #FunsList{width:800px!important;border:0!important;overflow:hidden!important;}
  1258. .FunsListHide{height: 34px!important;border: 0!important;margin: 0!important;padding: 0!important;}
  1259. .FunsListShow{height:auto!important;}
  1260. #FunsList>li{display:inline-block!important;width:300px!important;height:30px!important;margin:5px!important;text-align:left!important;}
  1261. span.tag:before{color:white!important;background:#555555!important;margin:0!important;border:0!important;padding:3px!important;border-radius:4px 0 0 4px!important;font-size:14px!important;white-space:nowrap!important;font-weight:bold!important;}
  1262. span.tag{color:white!important;margin:0!important;border:0!important;padding:1px 7px 3px 0!important;border-radius:4px!important;}
  1263.  
  1264. #mg2 b{margin-left:30px;padding:0 20px;background:#0000000C!important;}
  1265. #mg2 div.fnArgument{display:none;padding-top:20px!important;height:auto;}
  1266. #mg2 div.fnArgument textarea{width:100%;height:200px;}
  1267. #mg2 div.fnArgument span{width:auto;height:auto;}
  1268. #mg2 .yellow{background:#FFB400!important;}
  1269. #mg2 .yellow:before{content:"${fnLocal.FunsListTitle.gesture[cfg.language]}";}
  1270. #mg2 .blue:before{content:"${fnLocal.FunsListTitle.link[cfg.language]}";}
  1271. #mg2 .blue{background:#1182C2!important;}
  1272. #mg2 .green:before{content:"${fnLocal.FunsListTitle.text[cfg.language]}";}
  1273. #mg2 .green{background:#4DC71F!important;}
  1274. #mg2 .darkcyan:before{content:"${fnLocal.FunsListTitle.image[cfg.language]}";}
  1275. #mg2 .darkcyan{background:#B10DC9!important;}
  1276. #mg2 > li[data-type=gesture]>span:first-child{background:#FFB40030!important;color:#FFB400!important;}
  1277. #mg2 > li[data-type=text]>span:first-child{background:#4DC71F30!important;color:#4DC71F!important;}
  1278. #mg2 > li[data-type=link]>span:first-child{background:#1182C230!important;color:#1182C2!important;}
  1279. #mg2 > li[data-type=image]>span:first-child{background:#B10DC930!important;color:#B10DC9!important;}
  1280. #mg1 > li span:first-child,#mg2>li>span:first-child{text-align:left!important;font-size:16px!important;font-weight:bold!important;padding:2px 6px!important;width:auto!important;height:24px!important;float:left!important;border-left:5px solid!important;margin-right:20px!important;}
  1281. #mg2>li>span{margin-bottom:10px!important;}
  1282. #mg2>li>input {font-family: MParrow;}
  1283.  
  1284. #mg2 div input[type=text],#mg2 div select{background:#0000000c;padding:5px;margin:10px 5px;border: 0;}
  1285. #mg2 div input{width:80%;}
  1286. #mg2 div select{width:15%;}
  1287. #mg2 div label{margin:3px 0;}
  1288.  
  1289.  
  1290. #mg3 *{height: auto;font-size: 30px!important;text-decoration: none;font-weight: bolder;padding: 20px; color:#3A3B74!important}
  1291.  
  1292. /*label 作为开关*/
  1293. label.switchOn{background:#3A3B7420!important;display:inline-block!important;color:#3A3B74!important;font-weight:bolder!important;min-width:40px!important;height:24px!important;padding:2px 5px!important;border-left:15px solid #3A3B74!important;border-radius:5px!important;}
  1294. label.switchOff{background:#33333370!important;display:inline-block!important;color:#333333a0!important;text-decoration:line-through!important;min-width:40px!important;height:24px!important;padding:2px 5px!important;border-right:15px solid #333333!important;border-radius:5px!important;}
  1295. input[type=checkbox].switch{width:0px!important;}
  1296.  
  1297. #MPMask{z-index:9999999;position:fixed;top:0;left:0;}
  1298. #recorddingGesture{position: fixed;width: 100%;top: 100%;margin-top: -50%;text-align: center;color: white;font-size: 40px;font-family: MParrow;word-wrap:break-word;}
  1299. `,
  1300. uiLocal = {
  1301. //gesture
  1302. gestureUi: {zh:'手势配置', en:'Gesture Config'},
  1303. mouseButton: {zh:'手势按键', en:'Gesture mouse button'},
  1304. leftButton: {zh:'左键', en:'Left Key'},
  1305. middleButton: {zh:'中键', en:'MIddle Key'},
  1306. rightButton: {zh:'右键', en:'Right Key'},
  1307. mouseButtonTitle: {zh:'触发鼠标手势的按键', en:'The mouse button which will trigger the gesture.'},
  1308.  
  1309. suppressionKey: {zh:'手势禁用键', en:'Gesture suppression key'},
  1310. suppressionKeyTitle: {zh:'按下禁用键,暂时禁用手势', en:'Disables the mouse gesture if the key is pressed.'},
  1311. distanceThreshold: {zh:'手势距离阈值', en:'Gesture distance threshold'},
  1312. distanceThresholdTitle: {zh:'激活鼠标手势的最短距离', en:'The minimum mouse distance until the Gesture gets activated.'},
  1313. distanceSensitivity: {zh:'手势灵敏度', en:'Gesture sensitivity'},
  1314. distanceSensitivityTitle: {zh:'认定为新方向的最短距离。这也影响轨迹平滑度', en:'The minimum mouse distance until a new direction gets recognized. This will also impact the trace smoothness.'},
  1315. timeout: {zh:'手势超时', en:'Gesture timeout'},
  1316. timeoutTitle: {zh:'鼠标不动指定时间后,取消手势', en:'Cancels the gesture after the mouse has not been moved for the specified time.'},
  1317. directions: {zh:'手势方向数', en:'Gesture directions'},
  1318. directionsTitle: {zh:'手势识别的方向个数', en:'Gesture diffrent directions.'},
  1319. language: {zh:'语言', en:'Language'},
  1320. languageTitle: {zh:'设定使用语言', en:'Set the language for using.'},
  1321. //hint
  1322. hintUi: {zh:'提示配置', en:'Hint Config'},
  1323. background: {zh:'提示背景颜色', en:'Hint background'},
  1324. backgroundTitle: {zh:'提示的文字的背景颜色', en:'Hint text background color'},
  1325. fontSize: {zh:'提示字体', en:'Hint font size'},
  1326. fontSizeTitle: {zh:'提示文字的字体大小,单位:"&quot;px"&quot;', en:'Hint text font size,unit:"&quot;px"&quot;'},
  1327. lineColor: {zh:'轨迹颜色', en:'Track line color'},
  1328. lineColorTitle: {zh:'显示轨迹的颜色,十六进制,可以使3/6/8位', en:'track line color, hex, 3/6/8 bit'},
  1329. minLineWidth: {zh:'最小宽度', en:'Track minimum width'},
  1330. minLineWidthTitle: {zh:'轨迹的最小宽度,单位:&quot;px"&quot;', en:'Track minimum width,unit:&quot;px"&quot;'},
  1331. maxLineWidth: {zh:'最大宽度', en:'Track maximum width'},
  1332. maxLineWidthTitle: {zh:'轨迹的最大宽度,单位:&quot;px"&quot;', en:'Track maximum width,unit:&quot;px&quot;'},
  1333. lineGrowth: {zh:'增长速度', en:'Track growth speed'},
  1334. lineGrowthTitle: {zh:'轨迹的增长速度,单位:&quot;px&quot;', en:'Track growth speed,unit:&quot;px&quot;'},
  1335. funNotDefine: {zh:'未定义提示', en:'Gesture not found hint'},
  1336. funNotDefineTitle: {zh:'手势或者功能未定义时的提示信息', en:'If gesture not found, hint this'},
  1337. //drag
  1338. dragSetting: {zh:'拖拽配置', en:'Drag Config'},
  1339. linktextAslink: {zh:'链接优先', en:'Link priority'},
  1340. linktextAslinkTitle: {zh:'链接文字识别为链接', en:'Text link drag as link'},
  1341. dragInTextarea: {zh:'文本框拖拽', en:'Enable drag in textarea'},
  1342. dragInTextareaTitle: {zh:'文本框中选中文字并且拖拽时候,使用拖拽的功能', en:'Enable drag in textarea or input'}
  1343. },
  1344.  
  1345. menuHTML = `
  1346. <div id="MPmenu">
  1347. <span id="MPlogo">
  1348. <svg width="80px" height="100px" viewbox="0 0 200 200">
  1349. <path d="M135 13 l13 13h-7v20h20v-7l13 13l-13 13v-7h-20v20h7l-13 13 l-13 -13h7v-20h-20v7l-13-13l13-13v7h20v-20h-7z" style="fill:#0074d9;stroke:none;"></path>
  1350. <path d="M0 190L20 10c3,-8 8,-4 10,0L100 130L160 80c8,-8 17,-8 20,0L200 180c-2 20 -24 20 -30 0L160 120L110 163c-6 6 -19 10 -25 0L30 40L10 195c-3 5 -8 5 -10 0z" style="stroke:none;fill:#0074d9;"></path>
  1351. </svg>
  1352. </span>
  1353. <li name="mg1"> <span>◧</span> <b>Config</b> </li>
  1354. <li name="mg2"> <span>↯</span> <b>Gesture</b> </li>
  1355. <li name="mg3"> <span>❓</span> <b>About</b> </li>
  1356. <li name="close"> <span>?</span> <b>Close</b> </li>
  1357. </div>
  1358. <div id="mg1" class="MPcontent">mg1</div>
  1359. <div id="mg2" class="MPcontent">mg2</div>
  1360. <div id="mg3" class="MPcontent">mg3</div>
  1361. `,
  1362. gestureAndDragHTML =
  1363. //======gestureAndDragHTML======
  1364. `
  1365. <h1>${uiLocal.gestureUi[cfg.language]}</h1>
  1366. <!-- 因为启用了左键作为拖拽,所以按钮选项要禁用
  1367. <li>
  1368. <span title="${uiLocal.mouseButtonTitle[cfg.language]}">${uiLocal.mouseButton[cfg.language]}</span>
  1369. <span>
  1370. <select name="mouseButton">
  1371. <option value="0" ${sel(cfg.Gesture.mouseButton, 0)}>${uiLocal.leftButton[cfg.language]}</option>
  1372. <option value="1" ${sel(cfg.Gesture.mouseButton, 1)}>${uiLocal.middleButton[cfg.language]}</option>
  1373. <option value="2" ${sel(cfg.Gesture.mouseButton, 2)}>${uiLocal.rightButton[cfg.language]}</option>
  1374. </select>
  1375. </span>
  1376. </li>
  1377. -->
  1378. <li>
  1379. <span title="${uiLocal.suppressionKeyTitle[cfg.language]}">${uiLocal.suppressionKey[cfg.language]}</span>
  1380. <span>
  1381. <select name="suppressionKey">
  1382. <option value="" ${sel(cfg.Gesture.suppressionKey, '')}>&nbsp;</option>
  1383. <option value="altKey" ${sel(cfg.Gesture.suppressionKey, 'altKey')}>Alt</option>
  1384. <option value="ctrlKey" ${sel(cfg.Gesture.suppressionKey, 'ctrlKey')}>Ctrl</option>
  1385. <option value="shiftKey" ${sel(cfg.Gesture.suppressionKey, 'shiftKey')}>Shift</option>
  1386. </select>
  1387. </span>
  1388. </li>
  1389. <li>
  1390. <span title="${uiLocal.distanceThresholdTitle[cfg.language]}">${uiLocal.distanceThreshold[cfg.language]}</span>
  1391. <span>
  1392. <input type="text" name="distanceThreshold" value="${cfg.Gesture.distanceThreshold}" data-mark="number">
  1393. </span>
  1394. </li>
  1395. <li>
  1396. <span title="${uiLocal.distanceSensitivityTitle[cfg.language]}">${uiLocal.distanceSensitivity[cfg.language]}</span>
  1397. <span>
  1398. <input type="text" name="distanceSensitivity" value="${cfg.Gesture.distanceSensitivity}" data-mark="number">
  1399. </span>
  1400. </li>
  1401. <li>
  1402. <span title="${uiLocal.timeoutTitle[cfg.language]}">${uiLocal.timeout[cfg.language]}</span>
  1403. <span>
  1404. <input type="text" name="timeout" value="${cfg.Gesture.Timeout.duration}" data-mark="number">
  1405. </span>
  1406. </li>
  1407. <li>
  1408. <span title="${uiLocal.directionsTitle[cfg.language]}">${uiLocal.directions[cfg.language]}</span>
  1409. <span>
  1410. <select name="directions">
  1411. <option value="4" ${sel(cfg.directions, 4)}> 4 </option>
  1412. <option value="8" ${sel(cfg.directions, 8)}> 8 </option>
  1413. </select>
  1414. </span>
  1415. </li>
  1416. <li>
  1417. <span title="${uiLocal.languageTitle[cfg.language]}">${uiLocal.language[cfg.language]}</span>
  1418. <span>
  1419. <select name="language">
  1420. <option value="zh" ${sel(cfg.language, 'zh')}>中文</option>
  1421. <option value="en" ${sel(cfg.language, 'en')}>English</option>
  1422. </select>
  1423. </span>
  1424. </li>
  1425. <h1>${uiLocal.hintUi[cfg.language]}</h1>
  1426. <li>
  1427. <span title="${uiLocal.backgroundTitle[cfg.language]}">${uiLocal.background[cfg.language]}</span>
  1428. <span>
  1429. <input type="text" name="background" value="${cfg.Hinter.background}" style="background:#${cfg.Hinter.background} !important;">
  1430. </span>
  1431. </li>
  1432. <li>
  1433. <span title="${uiLocal.fontSizeTitle[cfg.language]}">${uiLocal.fontSize[cfg.language]}</span>
  1434. <span>
  1435. <input type="text" name="fontSize" value="${cfg.Hinter.fontSize}" data-mark="number">
  1436. </span>
  1437. </li>
  1438. <li>
  1439. <span title="${uiLocal.lineColorTitle[cfg.language]}">${uiLocal.lineColor[cfg.language]}</span>
  1440. <span>
  1441. <input type="text" name="lineColor" value="${cfg.Hinter.lineColor}" style="background:#${cfg.Hinter.lineColor} !important;">
  1442. </span>
  1443. </li>
  1444. <li>
  1445. <span title="${uiLocal.minLineWidthTitle[cfg.language]}">${uiLocal.minLineWidth[cfg.language]}</span>
  1446. <span>
  1447. <input type="text" name="minLineWidth" value="${cfg.Hinter.minLineWidth}">
  1448. </span>
  1449. </li>
  1450. <li>
  1451. <span title="${uiLocal.maxLineWidthTitle[cfg.language]}">${uiLocal.maxLineWidth[cfg.language]}</span>
  1452. <span>
  1453. <input type="text" name="maxLineWidth" value="${cfg.Hinter.maxLineWidth}">
  1454. </span>
  1455. </li>
  1456. <li>
  1457. <span title="${uiLocal.lineGrowthTitle[cfg.language]}">${uiLocal.lineGrowth[cfg.language]}</span>
  1458. <span>
  1459. <input type="text" name="lineGrowth" value="${cfg.Hinter.lineGrowth}">
  1460. </span>
  1461. </li>
  1462. <li>
  1463. <span title="${uiLocal.funNotDefineTitle[cfg.language]}">${uiLocal.funNotDefine[cfg.language]}</span>
  1464. <span>
  1465. <input type="text" name="funNotDefine" value="${cfg.Hinter.funNotDefine}">
  1466. </span>
  1467. </li>
  1468.  
  1469. <h1>${uiLocal.dragSetting[cfg.language]}</h1>
  1470. <li>
  1471. <span title="${uiLocal.linktextAslinkTitle[cfg.language]}">${uiLocal.linktextAslink[cfg.language]}</span>
  1472. <span>
  1473. <input type="checkbox" id="linktextAslink" name="linktextAslink" checked="" class="switch">
  1474. <label for="linktextAslink" class="switchOn"></label>
  1475. </span>
  1476. </li>
  1477. <!-- 使用抑制键代替
  1478. <li>
  1479. <span title="${uiLocal.dragInTextareaTitle[cfg.language]}">${uiLocal.dragInTextarea[cfg.language]}</span>
  1480. <span>
  1481. <input type="checkbox" id="dragInTextarea" name="dragInTextarea" checked="" class="switch">
  1482. <label for="dragInTextarea" class="switchOn"></label>
  1483. </span>
  1484. </li>
  1485. -->
  1486. `,
  1487.  
  1488. //=======gestureAndDragHTML End=========
  1489. aboutHTML = `
  1490. <pre style="font-size:1.2em !important;">
  1491. About userDefine function:
  1492. there are one argument(Object:mpData) provided in userDefine function.
  1493. mpData is a object like this:
  1494. {
  1495. gesture:"646", //gesture code of last mouse gesure
  1496. link:{ //optional, the target is link/image link...
  1497. href: "https://www.baidu.com/",
  1498. title: null, textContent: ""
  1499. }
  1500. target:{
  1501. src: "https://www.baidu.com/img/baidu_jgylogo3.gif", //target element arrtibute: src
  1502. title: "到百度首页", //target element arrtibute: title
  1503. alt: "到百度首页", //target element arrtibute: alt
  1504. textContent: "", //target element's text content
  1505. nodeName: "IMG", //target element's node name
  1506. self:{} //target element itself
  1507. }
  1508. textSelection:""
  1509. }
  1510. So, code in textarea shuold be <em>function body.</em>
  1511. And, you can add some not frequently used function as "userDefine" function to MP
  1512. </pre>
  1513. <a href="https://github.com/woolition/greasyforks/blob/master/mouseGesture/HY-MouseGesture.md" >(● ̄(エ) ̄●)づ <br>Click Me to More(点我看更多介绍)! </a>
  1514. `,
  1515. options = {
  1516. imgSearchEnging: { // image searching
  1517. BaiduImage: "https://image.baidu.com/n/pc_search?queryImageUrl=U-R-L&uptype=urlsearch",
  1518. GoogleImage: "https://www.google.com/searchbyimage?image_url=U-R-L",
  1519. TinEye: "http://www.tineye.com/search?url=U-R-L"
  1520. },
  1521. searchEnging: { // text searching
  1522. google: "http://www.google.com/search?q=",
  1523. baidu: "http://www.baidu.com/s?wd=",
  1524. yandex: "http://www.yandex.com/yandsearch?text=",
  1525. Bing: "http://www.bing.com/search?q=",
  1526. yahoo: "http://search.yahoo.com/search?p=",
  1527. wiki: "http://en.wikipedia.org/w/index.php?search=",
  1528. taobao: "http://s.taobao.com/search?q=",
  1529. amazon: "http://www.amazon.com/s/&field-keywords=",
  1530. sogou: "https://www.sogou.com/web?query=",
  1531. s360: "http://www.haosou.com/s?q="
  1532. },
  1533. vipAPI:{
  1534. 疯狂: "http://goudidiao.com/?url=",
  1535. 噗噗: "http://pupudy.com/play?make=url&id="
  1536. }
  1537. };
  1538.  
  1539.  
  1540. function q(cssSelector){
  1541. return document.querySelectorAll(cssSelector);
  1542. }
  1543. function attr(element,attributeName, attributeValue){
  1544. try {
  1545. if(attributeValue) element.setAttribute(attributeName, attributeValue);
  1546. else return element.getAttribute(attributeName);
  1547. } catch(e) {}
  1548. }
  1549. function each(elementCollect,func){
  1550. try{
  1551. Array.prototype.forEach.call(elementCollect, (item)=>{func(item);});
  1552. }catch(e){}
  1553. }
  1554. function listen(element, eventType, func){
  1555. element.addEventListener(eventType, func, false);
  1556. }
  1557. function sel(val1, val2){
  1558. return val1 == val2 ? 'selected="selected"' : '';
  1559. }
  1560. function click(evt){
  1561. function getName(evt){
  1562. if(evt.target.getAttribute('name')){
  1563. return evt.target.getAttribute('name');
  1564. }else {
  1565. if(evt.target.parentElement.getAttribute('name'))
  1566. return evt.target.parentElement.getAttribute('name');
  1567. else
  1568. return evt.target.parentElement.parentElement.getAttribute('name');
  1569. }
  1570. }
  1571. let named = getName(evt);
  1572. switch (named) {
  1573. case 'mg1':
  1574. case 'mg2':
  1575. case 'mg3':
  1576. each(q('.MPcontent'),(item)=>{
  1577. attr(item, 'style', 'display:none;');
  1578. });
  1579. attr(q('#'+named)[0], 'style', 'display:block;');
  1580. each(q('#MPmenu li'),item=>{
  1581. attr(item, 'class', ' ');
  1582. });
  1583. attr(q('[name='+named+']')[0], 'class', 'MPselected');
  1584. break;
  1585. case 'close':
  1586. q('body')[0].removeChild(q('#MPsetting')[0]);
  1587. break;
  1588. case 'addFunction':
  1589. toggleFunsList();
  1590. break;
  1591. case 'addFunctionLi':
  1592. clickToMakeEle();
  1593. break;
  1594. case 'alias':
  1595. attr(evt.target, 'contentEditable', "true");
  1596. break;
  1597. case 'toggleArgument':
  1598. if(evt.target.textContent === "▼"){
  1599. evt.target.textContent = "▲";
  1600. try{attr(evt.target.parentElement.lastChild,"style","display:block;");}
  1601. catch(e){}
  1602. }else {
  1603. evt.target.textContent = "▼";
  1604. try{attr(evt.target.parentElement.lastChild,"style"," ");}
  1605. catch(e){}
  1606. }
  1607. break;
  1608. case 'clearGesture':
  1609. case 'cancelGesture':
  1610. modul.captureGesture("", named);
  1611. break;
  1612. default:
  1613. if(cfg.hasOwnProperty(attr(evt.target, 'data-mark')))
  1614. addMask();
  1615. break;
  1616. }
  1617. }
  1618. function arg2html(argument, type, trk){
  1619. let html ="",
  1620. argu, i,rand, trackTxt, name,
  1621. argValue = [],
  1622. agrDetail = [],
  1623. description,
  1624. selectName;
  1625. if(typeof argument === "object")
  1626. argu = argument;
  1627. else
  1628. argu = JSON.parse(argument);
  1629. trackTxt = trk || '';
  1630. name = argu.name;
  1631. html += `<span>${name}</span><span name="alias">${argu.alias ? argu.alias : local[type][name][cfg.language]}</span><b style="visibility:${argu.arg.length ? "visible" : "hidden"};" name="toggleArgument">▼</b><input type="text" name="${name}" value="${trackTxt}" data-mark="${type}" readonly="readonly"><br/><div class="fnArgument">`;
  1632. if(argu.arg.length > 0){
  1633. argValue = trackTxt ? argu.arg : [];
  1634. agrDetail = fnLocal.arg[name].arg;
  1635. description = fnLocal.arg[name].description[cfg.language];
  1636. for(i in agrDetail){
  1637. rand = Math.floor(Math.random()*1000);
  1638. switch (agrDetail[i].slice(0,5)) {
  1639. case 'texta':
  1640. html += `<span><textarea>${mpUnescape(argValue[i])}</textarea><i></i></span>`;
  1641. break;
  1642. case 'input':
  1643. html += '<span><input type="text"><i></i></span>';
  1644. break;
  1645. case 'check':
  1646. html += `<span><input type="checkbox" id="${name + rand}" value=${argValue[i] || false} ${argValue[i] ? "checked" : ''} class="switch" name="fnCheckbox"><label for="${name + rand}" ${argValue[i] ? 'class="switchOn"' : 'class="switchOff"'}>${description[i]}</label></span>`;
  1647. break;
  1648. case 'selec':
  1649. selectName = agrDetail[i].split(':').pop();
  1650. html += `<span><input type="text" value=${argValue[i] || ''}><select name="fnSelect">`;
  1651. for (let k in options[selectName]){
  1652. html += `<option value=${options[selectName][k]}>${k}</option>`;
  1653. }
  1654. html += '</select></span>';
  1655. break;
  1656. default:
  1657. html = `<span style="visibility:hidden;"></span>`;
  1658. break;
  1659. }
  1660. }
  1661. }
  1662. return html + "</div>";
  1663. }
  1664. function makeFunsList(){
  1665. let color = ['yellow', 'green', 'blue', 'darkcyan'],
  1666. html = '',
  1667. arg = null;
  1668. each(['gesture', 'text', 'link', 'image'], (type)=>{
  1669. each(Object.keys(local[type]), (fnName)=>{
  1670. if(fnLocal.arg.hasOwnProperty(fnName))
  1671. arg = Object.assign({name:fnName},fnLocal.arg[fnName]);
  1672. else
  1673. arg = {name:fnName,arg:[]};
  1674. html += `<li data-type="${type}" data-arg='${JSON.stringify(arg)}' title="${local[type][fnName][cfg.language]}" name="addFunctionLi">
  1675. <span class="tag ${color[['gesture', 'text', 'link', 'image'].indexOf(type)]}">
  1676. <!--<span>${fnLocal.FunsListTitle[type][cfg.language]}</span>-->
  1677. <!--<span>-->${fnName}<!--</span>-->
  1678. </span>
  1679. </li>`;
  1680. });
  1681. });
  1682. html = `<fieldset id="FunsList" class="FunsListHide">
  1683. <h1 name="addFunction">${fnLocal.addFunction[cfg.language]} </h1><br/>
  1684. ${html}
  1685. </fieldset>`;
  1686. return html;
  1687. }
  1688. function makeDefinedFunsList(type){
  1689. let html ='';
  1690. each(Object.keys(cfg[type]), item=>{
  1691. try {
  1692. html += `<li data-arg='${JSON.stringify(cfg[type][item])}' data-type='${type}'>${arg2html(cfg[type][item], type, item)}`;
  1693. } catch(e) {}
  1694. });
  1695. return html;
  1696. }
  1697. function clickToMakeEle(){
  1698. let tarEle = event.target.tagName === 'LI' ? event.target : (event.target.parentNode.tagName === "LI" ? event.target.parentNode : event.target.parentNode.parentNode);
  1699. let ele = document.createElement('li');
  1700. ele.setAttribute('data-arg', tarEle.dataset.arg);
  1701. ele.setAttribute('data-type', tarEle.dataset.type);
  1702. ele.innerHTML = arg2html(tarEle.dataset.arg, tarEle.dataset.type);
  1703. document.getElementById('mg2').insertBefore(ele, document.querySelector(`#mg2>li`));
  1704. listen(ele.childNodes[2].childNodes[0], 'blur', updateConfigUi);
  1705. //函数列表收缩, 回滚到顶部
  1706. toggleFunsList();
  1707. document.documentElement.scrollTo(0, 0);
  1708. }
  1709. function updateFns(ele){
  1710. // check Conflict
  1711. if(Object.keys(cfg[ele.dataset.type]).indexOf(ele.childNodes[3].value) > -1){
  1712. if(JSON.parse(ele.dataset.arg).name !== cfg[ele.dataset.type][ele.childNodes[3].value].name){
  1713. attr(ele, "style", "background:red!important;");
  1714. alert("Gesture Conflict (手势冲突) !!!");
  1715. return;
  1716. }
  1717. }
  1718. // setting gesture not null
  1719. if(JSON.parse(ele.dataset.arg).name === "setting" && !ele.childNodes[3].value){
  1720. attr(ele, "style", "background:red!important;");
  1721. alert("Setting Gesture Cannot Set Null (设置手势不能为空) !!!");
  1722. return;
  1723. }
  1724. attr(ele, "style", " ");
  1725.  
  1726. let typeObject = {};
  1727. each(q(`#mg2>li[data-type=${ele.dataset.type}]`), element=>updateItem(element));
  1728. function updateItem(item){
  1729. let childrens, trk, argValue=[], name, dataArgObject, alias, argumentNodes;
  1730. trk = item.childNodes[3].value;
  1731. alias = item.childNodes[1].textContent;
  1732. //if mouse track is not empty , update Fns
  1733. if(trk !== ''){
  1734. childrens = item.childNodes[5].childNodes;
  1735. dataArgObject = JSON.parse(item.dataset.arg);
  1736. each(childrens, item=>{
  1737. if(item.firstElementChild.value && item.firstElementChild.value !== "undefined"){
  1738. // console.log(item.firstElementChild.nodeName);
  1739. // console.log('updateItem..');
  1740. if(item.firstElementChild.nodeName === "TEXTAREA")
  1741. argValue.push(mpEscape(item.firstElementChild.value));
  1742. else
  1743. argValue.push(item.firstElementChild.value);
  1744. } else{
  1745. argValue.push(' ');
  1746. }
  1747. });
  1748. typeObject[trk] = {name: dataArgObject.name, arg: argValue, alias:alias};
  1749. }
  1750. }
  1751. // console.log(typeObject);
  1752. cfg[ele.dataset.type] = typeObject;
  1753. storage.set('cfg', cfg);
  1754. }
  1755. function updateConfigUi(e){
  1756. let name = attr(e.target, 'name');
  1757. switch (name) {
  1758. case 'mouseButton':
  1759. case 'suppressionKey':
  1760. cfg.Gesture[name] = e.target.value;
  1761. break;
  1762. case 'distanceThreshold':
  1763. case 'distanceSensitivity':
  1764. case 'timeout':
  1765. cfg.Gesture[name] = parseInt(e.target.value);
  1766. break;
  1767. case 'directions':
  1768. case 'language':
  1769. cfg[name] = e.target.value;
  1770. break;
  1771. case 'background':
  1772. case 'lineColor':
  1773. cfg.Hinter[name] = e.target.value;
  1774. attr(e.target, 'style', `background: #${e.target.value} !important;`);
  1775. break;
  1776. case 'fontSize':
  1777. case 'minLineWidth':
  1778. case 'maxLineWidth':
  1779. case 'lineGrowth':
  1780. cfg.Hinter[name] = parseFloat(parseFloat(e.target.value).toFixed(2));
  1781. break;
  1782. case 'funNotDefine':
  1783. cfg.Hinter[name] = e.target.value;
  1784. break;
  1785. case 'linktextAslink':
  1786. case 'dragInTextarea':
  1787. cfg.Drag[name] = e.target.checked;
  1788. onOff(e, e.target.checked);
  1789. break;
  1790. default:
  1791. if(name === "alias")
  1792. updateFns(e.target.parentElement);
  1793. else if(name === "fnCheckbox" || name==="fnSelect"){
  1794. formChange();
  1795. }
  1796. return;
  1797. }
  1798. storage.set('cfg', cfg);
  1799. }
  1800. function formChange(){
  1801. if(event.target.type === 'checkbox'){
  1802. event.target.value = event.target.checked;
  1803. onOff(event, event.target.checked);
  1804. updateFns(event.target.parentElement.parentElement.parentElement);
  1805. }
  1806. if(event.target.tagName === 'SELECT'){
  1807. event.target.previousElementSibling.value = event.target.value;
  1808. updateFns(event.target.parentElement.parentElement.parentElement);
  1809. }
  1810. }
  1811. function onOff(e, check) {
  1812. if (check) {
  1813. attr(e.target.nextElementSibling, 'class', 'switchOn');
  1814. } else {
  1815. attr(e.target.nextElementSibling, 'class', 'switchOff');
  1816. }
  1817. }
  1818. function addMask(){
  1819. let
  1820. w=window.innerWidth,
  1821. h=window.innerHeight,
  1822. px = 0.1*w,
  1823. string=`
  1824. <svg height="${h}" width="${w}" style="background:#00000080">
  1825. <path id="record" d="
  1826. M${50}, ${50+px} v-${px} h${px}
  1827. M${w-px-50},${50} h${px} v${px}
  1828. M${w-50}, ${h-px-50} v${px} h-${px}
  1829. M${50+px}, ${h-50} h-${px} v-${px}"
  1830. style="stroke:#fff;stroke-width:${w/50};fill:none;"></path>
  1831. <text name="clearGesture" x="100" y="${h-100}" style="font-size:${Math.floor(w/20)}px;stroke:none;fill:white;cursor:pointer;">Clear</text>
  1832. <text name="cancelGesture" x="${w-100-w/6}" y="${h-100}" style="font-size:${Math.floor(w/20)}px;stroke:none;fill:white;cursor:pointer;">Cancle</text>
  1833. </svg>`;
  1834. let mask = document.createElement('div');
  1835. mask.id = "MPMask";
  1836. mask.innerHTML = string + '<div id="recorddingGesture"></div>';
  1837. document.body.appendChild(mask);
  1838. each(q('text[name=clearGesture], text[name=cancelGesture]'), item=>listen(item,"click",click));
  1839.  
  1840. attr(q('#MPsetting')[0], "style", "z-index:9999998 !important;");
  1841. attr(event.target, "data-flag", "captureGesture");
  1842. runtime.captureGesture = true;
  1843. }
  1844. function toggleFunsList(){
  1845. let a = q('#FunsList')[0];
  1846. if(attr(a, 'class') === "FunsListHide"){
  1847. attr(a, 'class', 'FunsListShow');
  1848. }else{
  1849. attr(a, 'class', 'FunsListHide');
  1850. }
  1851. }
  1852.  
  1853.  
  1854. return modul;
  1855. })();
  1856.  
  1857. //========⑥Run===================
  1858.  
  1859. //this addStyle is better than GM_addStyle,but not working in CSP tabs
  1860. // function addStyle(cssStr,id='MPStyle'){
  1861. // try {
  1862. // let node = document.createElement('style');
  1863. // node.id = id;
  1864. // node.textContent = cssStr;
  1865. // document.querySelector(':root').appendChild(node);
  1866. // } catch(e){}
  1867. // }
  1868. function addStyle(cssStr,id='MPStyle'){
  1869. GM_addStyle(cssStr);
  1870. }
  1871. addStyle(`
  1872. @font-face {
  1873. font-family: 'MParrow';
  1874. src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAQdAAoAAAAABPAAAQAAAAAAAAAAAAAAAAAAAAAECAAAABVPUy8yAAABYAAAAEQAAABgUc1dNGNtYXAAAAHEAAAARgAAAGAAcgFDZ2x5ZgAAAiAAAADwAAABNKukdSxoZWFkAAAA9AAAADQAAAA2DKcEFmhoZWEAAAEoAAAAHQAAACQEKQIaaG10eAAAAaQAAAAfAAAAJBGtAZVsb2NhAAACDAAAABQAAAAUATIBfm1heHAAAAFIAAAAFQAAACAACwAKbmFtZQAAAxAAAADnAAABe0DXvWtwb3N0AAAD+AAAABAAAAAgAAMAAXjaY2BkYGAA4gfLE97F89t8ZeBkYgCBq07amiD6mu+MRAaB/3cZXzFuAnI5GMDSAEgbC5142mNgZGBgYgACPSApwCDA+IqBkQEVcAIAGeEBSQAAAHjaY2BkYGDgBEIQzQAlkQAAAjsAFgAAAHjaY2Bm/MY4gYGVgYPRhzGNgYHBHUp/ZZBkaGFgYGJg5WSAAUYGJBCQ5poCpAwZLBkf/H/AoMeEpIaRAcpjAAAVNgmoeNpjYmBgYPzCYAbE3lBagImBQQzM/srgA6IBjAwITgB42i2KywmAQBQD57l+e9gCvAoieLd/7ShmnwZCmDBA4WslaLlMkdyzekdv0LFzSuaNQ9Kj+/ebUfNf0iv2YfA7Mb+pBQmvAAAAAAAAABQAJgA6AEwAXgByAIYAmnjaVY8hT8NAGIa/N0tzLJlgbY4LYmI0zekvTTmBuHomcGT9DXMkpD8Bwd+AhIo1wa8CVYfF4DCgm8wV7m6Gqc+8eZ7nI9AlRejwSCdERvAkYqHEQxljarv6zWIau0sEuv79xAtewy4tjJLpPH2q2rZqvtH3GAc6YiWaswlroQfPKLsaVzYe93ZXu90pneML94ElWRuWS/nhILO7qt2uG/K+M7f5OWxQsBJcLAtc9P04YLHeOu2xL1McJayMAtlx74W34YngW7n25tCe5VLoIp/nuAnxzz4eMwrO/zzDScZGG2xK393V74G7q/8AczlNtXjadY7BasJAEIb/mKgVSumh3ucBoiQetHjpod6K4MlLi7CROSzEBDaB0EfoC/hEvoLv0990G0Rwhtn99p9/hwHwiCMCXCLAsD0v0eP94DnEuNMjjDruY8rOHw/ofqcziEZUnvDhuccfn55D+v/1CC8d9/GFb88DPOO83hjnykbetuoqWxaSTpPkmmWlez1k6mQeyyxJF7HYwtbW5OI0V1OpHzHBGhsYOGaJBrJ7/TlhiS2USgVLtYAg5WoJ854uWLGzZx2QtR7BHDHPGbspFi1b/rGoWQY5347OnGU4UW82mfwCMzM4HQB42mNgZkAGjAxoAAAAjgAFSExQRAEARkMJAAAAUGF3J1oAAAAA) format('woff');
  1875. }
  1876. #MPcanvas{position:fixed;top:0;left:0;z-index:10000000;}
  1877. #MPtips{all:initial!important;position:fixed!important;z-index:9999996!important;top:50%!important;left:50%!important;transform:translate(-50%,-50%)!important;font-family:MParrow,"Arial",sans-serif!important;color:white!important;white-space:nowrap!important;line-height:normal!important;text-shadow:1px 1px 5px rgba(0,0,0,0.8)!important;text-align:center!important;padding:25px 20px 20px 20px!important;border-radius:5px!important;font-weight:bold!important; }
  1878. `);
  1879. //===========update any time=========
  1880. GM_addValueChangeListener('cfg', ()=>{
  1881. GestureHandler.applySettings(cfg);
  1882. Hinter.applySettings(cfg);
  1883. });
  1884. //when close a tab, save it's url, in order to reopen it: reopenTab
  1885. window.addEventListener('unload', function() {
  1886. GM_setValue('latestTab', window.location.href);
  1887. }, false);
  1888. //used in func: closeOtherTabs
  1889. if(!GM_getValue('closeAll','')) GM_setValue('closeAll', Date());
  1890. GM_addValueChangeListener('closeAll',function(name, old_value, new_value, remote){if(remote)window.close();});
  1891. //===========update any time end=========
  1892. GestureHandler.applySettings(cfg);
  1893. Hinter.applySettings(cfg);
  1894. GestureHandler.enable();
  1895. Hinter.enable();
  1896. })();