/* * ==VimperatorPlugin== * @name highlight.js * @description Factory for the object to highlight specified element[s]. this set in plugins.highlighterFactory. * @description-ja 指定した要素をハイライトするオブジェクトを返す Factory 。 plugins.highlighterFactory に構築される。 * @author janus_wel * @version 0.11 * @minversion 2.0pre 2008/10/16 * ==/VimperatorPlugin== * * LICENSE * New BSD License * * USAGE * plugins.highlighterFactory() return the object to highlight element[s]. * arguments is object that have below properties. * color: color name that define by css or RGB format ( #xxxxxx ), * opacity: opacity for -moz-opacity property in css. * interval: interval to blink ( unit: msec ). if 0 specified, not blink. * * returned object has 3 methods. * set: setter that accept object have above properties. * highlight: method to highlight specified element. * unhighlightAll: unhighlight all. * * highlight is implement by "div" element that have style "position: absolute;". * it has class name "vimp_plugin_highlightelement", so you should use buffer.evaluateXPath * with query that like '//div[contains(concat(" ", @class, " "), " vimp_plugin_highlightelement ")]' * when you want to process elements to highlight. * * EXAMPLE * let h = plugins.highlighterFactory({ * color: '#0080ff', * opacity: 0.7, * interval: 0, * ); * h.highlight(content.document.getElementsByTagName('A')); * h.unhighlightAll(); * * TODO * need valid English. * */ ( function () { const fixedStyle = [ 'position: absolute;', 'display: block;', 'z-index: 2147483647;', ].join(''); // class definition function Highlighter() { this._initialize.apply(this, arguments); } Highlighter.prototype = { _initialize: function (args) { if (args) this.set(args); this.highlightList = []; }, set: function (args) { this.color = args.color; this.opacity = args.opacity; this.interval = args.interval; this._prepareTemplate(); return this; }, _prepareTemplate: function () { let div = window.document.createElement('div'); div.className = 'vimp_plugin_highlightelement'; let style = fixedStyle + [ 'background-color: ' + this.color + ';', '-moz-opacity: ' + this.opacity + ';' ].join(''); div.setAttribute('style', style); this._highlightTemplate = div; }, highlight: function (element) { if (!this._isDisplay(element)) return; let doc = element.ownerDocument; // TODO: highlight XUL elements if (!doc.body) return; let scrollX = doc.defaultView.scrollX; let scrollY = doc.defaultView.scrollY; let rects = element.getClientRects(); for (let i=0, l=rects.length ; i 0) { div.intervalId = setInterval( function () { let d = div.style.display; div.style.display = (d === 'block' ? 'none' : 'block'); }, this.interval ); } else { div.intervalId = undefined; } return div; }, }; if (!plugins.highlighterFactory) { plugins.highlighterFactory = function () { let h = new Highlighter(); return h.set.apply(h, arguments); } } } )(); // vim: set sw=4 ts=4 et; 3 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
// ==VimperatorPlugin==
// @name           Auto Detect Link
// @description-ja (次|前)っぽいページへのリンクを探してジャンプ
// @license        Creative Commons 2.1 (Attribution + Share Alike)
// @version        1.1.0
// ==/VimperatorPlugin==
//
//  Usage:
//    デフォルトの設定では、"]]" "[[" を上書きします。
//    ]]    次っぽいページへ
//    [[    前っぽいページへ
//
//  Setting:
//    liberator.globalVariables.autoDetectLink
//      nextPatterns:
//      backPatterns:
//        (次|前)のパターンの配列。
//        要素は、
//          ・リンク文字列に対する(正規表現|文字列)
//          ・リンクに対する関数のリスト
//      nextMappings:
//      backPatterns:
//        (次|前)移動のマッピング(Array)
//      useNextHistory:
//      useBackHistory:
//        履歴を併用。
//        履歴がある場合はそっちを優先します。
//      useSuccPattern:
//        doc_01.html のときは、 doc_02.html を次と見なす…ようなパターン。
//        ファイル名に当たる部分の、数字列あるいは一文字のアルファベットが対象です。
//        (つながっているアルファベットは無視されます。)
//          doc_02.html => doc_03.html
//          doc_a.html => doc_b.html
//      force:
//        (次|前)っぽいURIを捏造してそこに移動します。
//      useAutoPagerize:
//        AutoPagerize のキャッシュを利用します。
//        (ただし、"次" へのリンクにしか使われません)
//
//    example:
//      :js liberator.globalVariables.autoDetectLink = {nextPatterns: [/next/, /次/]}
//
//  Function:
//    (次|前)へのリンクを検出する。
//    liberator.plugins.autoDetectLink.detect(next, setting)
//      next:     次のリンクを探すときは、true。
//      setting:  設定を一時的に上書きする。省略可。
//      return:   リンクのURIなどを含んだオブジェクト
//        uri:     アドレス。
//        text:    リンクテキストなど
//        frame:   リンクの存在するフレームの Window オブジェクト
//        element: リンクの要素
//
//    (次|前)へのリンクに移動。
//    liberator.plugins.autoDetectLink.go(next, setting)
//      引数は detect と同じ。
//
//    example:
//      履歴を使用しないで、前のリンクを探す。
//        liberator.plugins.autoDetectLink.detect(false, {useBackHistory: false});
//
// Note:
//    単純なリンクと、フォームのボタンを検出できます。
//
// License:
//    http://creativecommons.org/licenses/by-sa/2.1/jp/
//    http://creativecommons.org/licenses/by-sa/2.1/jp/deed.en_CA
//
// TODO:
//    input / form
//    history


(function () { try{
  liberator.log('auto_detect_link.js loading');

  ////////////////////////////////////////////////////////////////
  // default setting
  ////////////////////////////////////////////////////////////////

  let defaultSetting = {
    nextPatterns: [
      /NEXT/, /next/, /Next/, 
      /^次(へ|の)/, /つぎへ/, /つづく/, /続/, /次/, /つぎ/, /next/i, /進む/,
      /^>$/, />>/, />/
    ],
    backPatterns: [
      /back/i, /back/i, /BACK/, /PREV/, 
      /^前(へ|の)/, /前/, /戻る/, /^<$/, /<</, /</
    ],
    nextMappings: [']]'],
    backMappings: ['[['],
    useSuccPattern: true,
    useNextHistory: false,
    useBackHistory: false,
    //clickButton: true,
    force: false,
    useAutoPagerize: true,
  }

  ////////////////////////////////////////////////////////////////
  // setting
  ////////////////////////////////////////////////////////////////

  let _gv;

  // 評価を遅延するために関数にしておく
  function gv () {
    if (_gv) 
      return _gv;

    if (liberator.globalVariables) {
      if (!liberator.globalVariables.autoDetectLink)
        liberator.globalVariables.autoDetectLink = {};
      _gv = liberator.globalVariables.autoDetectLink;
    }

    for (let key in defaultSetting) {
      if (_gv[key] == undefined)
        _gv[key] = defaultSetting[key];
    }

    return _gv;
  }

  const APPREF = 'greasemonkey.scriptvals.http://swdyh.yu.to//AutoPagerize.cacheInfo';
  let ap_cache = eval(Application.prefs.getValue(APPREF, null));

  for each (let cache in ap_cache) {
    cache.info = cache.info.filter(function(i) { return ('url' in i) })
    cache.info.sort(function(a, b) { return (b.url.length - a.url.length) })
  }


  ////////////////////////////////////////////////////////////////
  // functions
  ////////////////////////////////////////////////////////////////

  // Array#find
  function find (ary, f) {
    let func = (typeof f == 'function') ? f : function (v) v == f;
    for (var i = 0; i < ary.length; i++) {
      if (func(ary[i])) {
        return ary[i];
      }
    }
    return null;
  }


  // 要素をクリックする
  function clickElement (elem) {
    liberator.log('click: ' + elem);
    var e = content.document.createEvent('MouseEvents');
    e.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null); 
    elem.dispatchEvent( e ); 
  }


  // 開いたURIなどの表示
  function displayOpened (link) {
    let msg = 'open: ' + link.type + ' <' + link.text + '> ' + link.uri;
    setTimeout(function () liberator.echo(msg), 1000);
    liberator.log(msg);
  }


  // リンクを開く
  function open (link) {
    liberator.log(link);
    if (link.element) {
      clickElement(link.element);
    } else if (link.uri) {
      link.frame.location.href = link.uri
    }
    displayOpened(link);
  }


  // 元の文字列、詰め込む文字、長さ
  function padChar (s, c, n) {
    return s.replace(new RegExp('^(.{0,'+(n-1)+'})$'), function(s)padChar(c+s,c,n));
  }


  // (次|前)の数字文字列リストを取得
  function succNumber (n, next) {
    let m = (parseInt(n.replace(/^0*(.)/,'$1')||0) + (next ? 1 : -1)).toString();
    let result = [m];
    if (m.length < n.length)
      result.unshift(padChar(m.toString(), '0', n.length));
    return result;
  }


  // (次|前)の文字列リストを取得
  function succString (s, next) {
    let result = [], d = next ? 1 : -1;
    let c = String.fromCharCode(s.charCodeAt(0) + d);
    if (('a' <= c && c <= 'z') || 'A' <= c && c <= 'Z')
      result.push(c);
    return result;
  }


  // (次|前)のURIリストを取得
  function succURI (uri, next) {
    let urim = uri.match(/^(.+\/)([^\/]+)$/);
    if (!urim)
      return [];
    let [_, dir, file] = urim, result = [];
    // succ number
    let (dm, succs, file = file, left = '', temp = []) {
      while (file && (dm = file.match(/\d+/))) {
        let [rcontext, lcontext, lmatch] = [RegExp.rightContext, RegExp.leftContext, RegExp.lastMatch];
        left += lcontext;
        succs = succNumber(lmatch, next);
        for each (let succ in succs) {
          temp.push(dir + left + succ + rcontext);
        }
        left += lmatch;
        file = rcontext;
      }
      result = result.concat(temp.reverse());
    }
    liberator.log(result);
    // succ string
    let (dm, succs, file = file, left = '', temp = []) {
      while (file && (dm = file.match(/(^|[^a-zA-Z])([a-zA-Z])([^a-zA-Z]|$)/))) {
        let [rcontext, lcontext] = [RegExp.rightContext, RegExp.leftContext];
        left += lcontext + dm[1];
        succs = succString(dm[2], next);
        for each (let succ in succs) {
          temp.push(dir + left + succ + dm[3] + rcontext);
        }
        left += dm[1];
        file = dm[3] + rcontext;
      }
      result = result.concat(temp.reverse());
    }
    return result;
  }


  // パターンマッチング
  function match (pattern, link) {
    if (pattern instanceof Function)
      return pattern(link);
    if (!link.text)
      return;
    if (pattern instanceof RegExp)
      return pattern.test(link.text);
    return link.text.toLowerCase().indexOf(pattern.toString().toLowerCase()) >= 0;
  }


  // 要素が表示されているか?
  function isVisible (element) {
    try {
      let st = content.document.defaultView.getComputedStyle(element, null);
      return !(st.display && st.display.match(/none/)) && (!element.parentNode || isVisible(element.parentNode))
    } catch (e) {
      return true;
    }
  }


  // リンクのフィルタ
  function linkElementFilter (elem) {
    return isVisible(elem) && elem.href && !elem.href.match(/@/) && elem.href.match(/^((https?|file|ftp):\/\/|javascript:)/) && elem.textContent;
  }


  // 全てのリンクを取得
  // 再帰的にフレーム内のも取得する
  function getAllLinks (content) {
    var result = [];
    // Anchor
    for each (let it in content.document.links) {
      if (linkElementFilter(it))
        result.push({
          type: 'link',
          frame: content,
          uri: it.href,
          text: it.textContent,
          element: it
        });
    }
    // Form
    for each (let input in content.document.getElementsByTagName('input')) {
      (function (input) {
        result.push({
          type: 'input',
          frame: content, 
          uri: input.form && input.form.action, 
          text: input.value,
          click: input.click,
          element: input,
          });
      })(input);
    }
    // Frame
    if (content.frames) {
      for (let i = 0; i < content.frames.length; i++) {
        result = result.concat(getAllLinks(content.frames[i]));
      }
    }
    return result;
  }


  // 上書きした設定を返す。
  function getCurrentSetting (setting) {
    if (!setting)
      setting = {};
    for (let n in gv()) {
      if (setting[n] == undefined)
        setting[n] = gv()[n];
    }
    return setting;
  }


  // 相対アドレスから絶対アドレスに変換するんじゃないの?
  function toAbsPath (path) {
    with (content.document.createElement('a'))
      return (href = path) && href;
  }

  // AutoPagerize のデータからマッチする物を取得
  function getAutopagerizeNext () {
    if (!ap_cache)
      return;

    let info = (function () {
      let uri = buffer.URL;
      for each (let cache in ap_cache) {
        for each (let info in cache.info) {
          if (uri.match(info.url))
            return info;
        }
      }
    })();

    if (!info)
      return;

    let doc = content.document;
    let result = doc.evaluate(info.nextLink, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    if (result.singleNodeValue)
      return result.singleNodeValue;
  }


  ////////////////////////////////////////////////////////////////
  // main
  ////////////////////////////////////////////////////////////////

  // リンクを探す
  function detect (next, setting) {
    try {
      setting = getCurrentSetting(setting);

      // TODO
      if (setting.useAutoPagerize) {
        let apnext = getAutopagerizeNext();
        if (apnext) {
          return {
            type: 'aplink',
            frame: content,
            uri: apnext.href || apnext.action || apnext.value,
            text: apnext.textContent,
            element: apnext
          };
        }
      }

      patterns = next ? setting.nextPatterns : setting.backPatterns;

      let uri = window.content.location.href;
      let links = getAllLinks(window.content);

      // keywords
      if (1) {
        for each (let pattern in patterns) {
          let link = find(links, function (link) match(pattern, link));
          if (link)
            return link;
        }
      }

      // succ
      let succs = succURI(uri, next);
      if (setting.useSuccPattern) {
        for each (succ in succs) {
          let link = find(links, function (link) (link.uri && (link.uri.indexOf(succ) >= 0)));
          if (link)
            return link;
        }
      }

      // force
      if (setting.force && succs.length) 
        return {
          type: 'force',
          uri: succs[0],
          text: '-force-',
          frame: window.content,
        };

    } catch (e) {
      liberator.log(e);
      liberator.echoerr(e);
    }
  }


  // 猫又
  function go (next, setting) {
    setting = getCurrentSetting(setting);

    if ((next && setting.useNextHistory) || (!next && setting.useBackHistory)) {
      next ? BrowserForward() : BrowserBack();
      displayOpened({uri: 'history', text: next ? 'next' : 'back'});
      return;
    }

    let link = detect(next, setting);
    if (link)
      open(link);
  }


  // 外部から使用可能にする。
  if (liberator.plugins)
    liberator.plugins.autoDetectLink = {detect: detect, go: go};


  ////////////////////////////////////////////////////////////////
  // Mappings
  ////////////////////////////////////////////////////////////////

  if (gv().nextMappings.length) {
    liberator.mappings.addUserMap(
      [liberator.modes.NORMAL], 
      gv().nextMappings,
      'Go next',
      function () go(true)
    );
  }


  if (gv().backMappings.length) {
    liberator.mappings.addUserMap(
      [liberator.modes.NORMAL], 
      gv().backMappings,
      'Go back',
      function () go(false)
    );
  }


  liberator.log('auto_detect_link.js loaded');

}catch(e){liberator.log(e)}
})();