/* {{{ Copyright (c) 2008-2009, anekos. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ################################################################################### # http://sourceforge.jp/projects/opensource/wiki/licenses%2Fnew_BSD_license # に参考になる日本語訳がありますが、有効なのは上記英文となります。 ################################################################################### }}} */ // PLUGIN_INFO {{{ let PLUGIN_INFO = Stella すてら Show video informations on the status line. ステータスラインに動画の再生時間などを表示する。 0.16 anekos new BSD License (Please read the source code comments of this plugin) 修正BSDライセンス (ソースコードのコメントを参照してください) 2.0pre 2.0pre http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/stella.js : set to the specified volume. :stmu[te]: turn on/off mute. :stre[peat]: turn on/off mute. :stco[mment]: turn on/off comment visible. :stse[ek] : seek to specified position. TIMECODE formats - :stseek 1:30 # 1分30秒 - :stseek 1.5 # 1.5分。90秒 - :stseek 90 # 90秒 :stse[ek]! : seek to the specified position from current position at relatively. :stfe[tch]: fetch and save the video. :stla[rge]: enlarge video screen. :stfu[llscreen]: turn on/off fullscreen. ]]> : 指定の音量にする。 0から100の数字で指定する。 :stmu[te]: ミュートのOn/Offを切り替える。 :stre[peat]: リピートモードのOn/Offを切り替える。 :stco[mment]: コメントのOn/Offを切り替える。 :stse[ek] : 指定の秒数までシークする。 TIMECODE は以下の様に指定できる。 - :stseek 1:30 # 1分30秒 - :stseek 1.5 # 1.5分。90秒 - :stseek 90 # 90秒 :stse[ek]! : 現在の位置から TIMECODE 分移動する。 :stfe[tch]: 動画をファイルとして保存する。 :stla[rge]: 画面を大きくする/戻す。 :stfu[llscreen]: フルスクリーン表示のOn/Offを切り替える。 == Link == http://d.hatena.ne.jp/nokturnalmortum/20081213/1229168832 ]]> ; // }}} /* {{{ TODO ・Icons ・Other video hosting websites ・auto fullscreen ・動的な command の追加削除 (nice rabbit!) ・ツールチップみたいな物で、マウスオー馬したときに動画情報を得られるようにしておく。 ・外から呼ぶべきでない関数(プライベート)をわかりやすくしたい ・argCount の指定が適当なのを修正 (動的な userCommand と平行でうまくできそう?) ・実際のプレイヤーが表示されるまで待機できようにしたい(未表示に時にフルスクリーン化すると…) ・コメント欄でリンクされている動画も関連動画として扱いたい -> "その3=>sm666" みたいなやつ -> リンクはともかくタイトルの取得がムツカシー ・isValid とは別にプレイヤーの準備が出来ているか?などをチェックできる関数があるほうがいいかも -> isValid ってなまえはどうなの? -> isReady とか ・パネルなどの要素にクラス名をつける MEMO ・prototype での定義順: 単純な値 initialize finalize (get|set)ter メソッド ・関数やプロパティは基本的にアルファベット順にならべる。 Refs: http://yuichis.homeip.net/nicodai.user.html http://coderepos.org/share/browser/lang/javascript/vimperator-plugins/trunk/nicontroller.js http://coderepos.org/share/browser/lang/javascript/vimperator-plugins/trunk/youtubeamp.js Thanks: 参考にさせてもらった人々。THANKS!! janus_wel 氏 http://d.hatena.ne.jp/janus_wel/ ゆういち 氏 http://yuichis.homeip.net/nicodai.user.html }}} */ (function () { /********************************************************************************* * Const {{{ *********************************************************************************/ const ID_PREFIX = 'anekos-stela-'; const InVimperator = !!(liberator && modules && modules.liberator); const DOUBLE_CLICK_INTERVAL = 300; // }}} /********************************************************************************* * Utils {{{ *********************************************************************************/ const U = { bindr: function (_this, f) function () f.apply(_this, arguments), capitalize: function (s) s.replace(/^[a-z]/, String.toUpperCase).replace(/-[a-z]/, function (s) s.slice(1).toUpperCase()), currentURL: function () content.document.location.href, download: function (url, filepath, ext, title) { let dm = Cc["@mozilla.org/download-manager;1"].getService(Ci.nsIDownloadManager); let wbp = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Ci.nsIWebBrowserPersist); let file; if (filepath) { file = io.getFile(io.expandPath(filepath)); } else { file = dm.userDownloadsDirectory; } if (file.isDirectory() && title) file.appendRelativePath(U.fixFilename(title) + ext); if (file.exists()) return liberator.echoerr('The file already exists! -> ' + file.path); file = makeFileURI(file); let dl = dm.addDownload(0, U.makeURL(url, null, null), file, title, null, null, null, null, wbp); wbp.progressListener = dl; wbp.persistFlags |= wbp.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION; wbp.saveURI(U.makeURL(url), null, null, null, null, file); return true; }, fixDoubleClick: function (obj, click, dblClick) { let clicked = 0; let original = {click: obj[click], dblClick: obj[dblClick]}; obj[click] = function () { let self = this, args = arguments; let _clicked = ++clicked; setTimeout(function () { if (_clicked == clicked--) original.click.apply(self, args); else clic
/**
 * The MIT License
 *
 * Copyright (c) 2010 Adam Abrons and Misko Hevery http://getangular.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
(function(window) {

  var filename = /^(.*\/)angular-bootstrap.js(#.*)?$/,
      scripts = document.getElementsByTagName("SCRIPT"),
      serverPath,
      match,
      globalVars = {};

  for(var j = 0; j < scripts.length; j++) {
    match = (scripts[j].src || "").match(filename);
    if (match) {
      serverPath = match[1];
    }
  }

  function key(prop) {
    return "ng-clobber_" + prop;
  }

  window.angularClobberTest = function(file) {
    var varKey, prop,
        clobbered = [];

    for (prop in window) {
      varKey = key(prop);

      if (prop === 'event') { //skip special variables which keep on changing
        continue;
      }
      else if (!globalVars.hasOwnProperty(varKey)) {
        //console.log('new global variable found: ', prop);
        try {
          globalVars[varKey] = window[prop];
        } catch(e) {} //ignore properties that throw exception when accessed (common in FF)
      } else if (globalVars[varKey] !== window[prop] && !isActuallyNaN(window[prop])) {
        clobbered.push(prop);
        console.error("Global variable clobbered by script " + file + "! Variable name: " + prop);
        globalVars[varKey] = window[prop];
      }
    }

    for (varKey in globalVars) {
      prop = varKey.substr(11);
      if (clobbered.indexOf(prop) == -1 &&
          prop != 'event' &&
          !isActuallyNaN(globalVars[varKey]) &&
          globalVars[varKey] !== window[prop]) {

        delete globalVars[varKey];
        console.warn("Global variable unexpectedly deleted in script " + file + "! " +
                     "Variable name: " + prop);
      }
    }

    function isActuallyNaN(val) {
      return isNaN(val) && (typeof val === 'number');
    }
  };

  function addScripts(){
    var prop, i;

    // initialize the window property cache
    for (prop in window) {
      try {
        globalVars[key(prop)] = window[prop];
      } catch(e) {} //ignore properties that throw exception when accessed (common in FF)
    }

    // load the js scripts
    for (i in Array.prototype.slice.call(arguments, 0)) {
      file = arguments[i];
      document.write('<script type="text/javascript" src="' + serverPath + file + '" ' +
                             'onload="angularClobberTest(\'' + file + '\')"></script>');
    }
  }

  function addCss(file) {
    document.write('<link rel="stylesheet" type="text/css" href="' +
                      serverPath + '../css/' + file  + '"/>');
  }

  addCss('angular.css');

  addScripts('Angular.js',
             'JSON.js',
             'Compiler.js',
             'Scope.js',
             'Injector.js',
             'jqLite.js',
             'parser.js',
             'Resource.js',
             'Browser.js',
             'sanitizer.js',
             'AngularPublic.js',

             // Extension points

             'service/cookieStore.js',
             'service/cookies.js',
             'service/defer.js',
             'service/document.js',
             'service/exceptionHandler.js',
             'service/hover.js',
             'service/invalidWidgets.js',
             'service/location.js',
             'service/log.js',
             'service/resource.js',
             'service/route.js',
             'service/updateView.js',
             'service/window.js',
             'service/xhr.bulk.js',
             'service/xhr.cache.js',
             'service/xhr.error.js',
             'service/xhr.js',

             'apis.js',
             'filters.js',
             'formatters.js',
             'validators.js',
             'directives.js',
             'markups.js',
             'widgets.js');


  function onLoadListener(){
    // empty the cache to prevent mem leaks
    globalVars = {};

    //angular-ie-compat.js needs to be pregenerated for development with IE<8
    if (msie<8) addScript('../angular-ie-compat.js');

    angularInit(angularJsConfig(document), document);
  }

  if (window.addEventListener){
    window.addEventListener('load', onLoadListener, false);
  } else if (window.attachEvent){
    window.attachEvent('onload', onLoadListener);
  }

})(window);

d+)/)) (m && m[1]), get muted () this.player.ext_isMute(), set muted (value) (this.player.ext_setMute(value), value), get player () U.getElementByIdEx('flvplayer'), get playerContainer () U.getElementByIdEx('flvplayer_container'), get relatedIDs () { if (this.__rid_last_url == U.currentURL()) return this.__rid_cache || []; this.__rid_last_url = U.currentURL(); let videos = []; let uri = 'http://www.nicovideo.jp/api/getrelation?sort=p&order=d&video=' + this.id; let xhr = new XMLHttpRequest(); xhr.open('GET', uri, false); xhr.send(null); let xml = xhr.responseXML; let v, vs = xml.evaluate('//video', xml, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); while (v = vs.iterateNext()) { let [cs, video] = [v.childNodes, {}]; for each (let c in cs) if (c.nodeName != '#text') video[c.nodeName] = c.textContent; videos.push(new RelatedID(video.url.replace(/^.+?\/watch\//, ''), video.title)); } return this.__rid_cache = videos; }, get relatedTags() { let nodes = content.document.getElementsByClassName('nicopedia'); return [new RelatedTag(it.textContent) for each (it in nodes) if (it.rel == 'tag')]; }, get repeating () this.player.ext_isRepeat(), set repeating (value) (this.player.ext_setRepeat(value), value), get large () this.player.ext_getVideoSize() === NicoPlayer.SIZE_LARGE, set large (value) { this.player.ext_setVideoSize(value ? NicoPlayer.SIZE_LARGE : NicoPlayer.SIZE_NORMAL); return this.large; }, get state () { switch (this.player.ext_getStatus()) { case 'end': return Player.ST_ENDED; case 'playing': return Player.ST_PLAYING; case 'paused': return Player.ST_PAUSED; case 'buffering': default: return Player.ST_OTHER; } }, get title () content.document.title.replace(/\s*\u2010\s*\u30CB\u30B3\u30CB\u30B3\u52D5\u753B(.+)$/, ''), get totalTime () parseInt(this.player.ext_getTotalTime()), get volume () parseInt(this.player.ext_getVolume()), set volume (value) (this.player.ext_setVolume(value), this.volume), fetch: function (filepath) { let onComplete = U.bindr(this, function (xhr) { let res = xhr.responseText; let info = {}; res.split(/&/).forEach(function (it) let ([n, v] = it.split(/=/)) (info[n] = v)); U.download(decodeURIComponent(info.url), filepath, this.fileExtension, this.title); }); U.httpRequest('http://www.nicovideo.jp/api/getflv?v=' + this.id, null, onComplete); }, makeURL: function (value, type) { switch (type) { case Player.URL_ID: return 'http://www.nicovideo.jp/watch/' + value; case Player.URL_TAG: return 'http://www.nicovideo.jp/tag/' + encodeURIComponent(value); case Player.URL_SEARCH: return 'http://www.nicovideo.jp/search/' + encodeURIComponent(value); } return value; }, pause: function () this.player.ext_play(false), play: function () this.player.ext_play(true), playOrPause: function () { if (this.is(Player.ST_PLAYING)) { this.pause(); } else { let base = this.currentTime; setTimeout(U.bindr(this, function () (base === this.currentTime ? this.playEx() : this.pause())), 100); } }, say: function (message) { liberator.log('stsay'); this.sendComment(message); }, // みかんせいじん // test -> http://www.nicovideo.jp/watch/sm2586636 // 自分のコメントが見れないので、うれしくないかも。 sendComment: function (message, command, vpos) { let self = this; // コメント連打を防止 { let now = new Date(); let last = this.__last_comment_time; if (last && (now.getTime() - last.getTime()) < 5000) return U.raise('Shurrup!!'); this.__last_comment_time = now; } function getThumbInfo () { liberator.log('getThumbInfo'); if (self.cachedInfo.block_no !== undefined) return; let xhr = U.httpRequest(self.baseURL + 'api/getthumbinfo/' + self.id); let xml = xhr.responseXML; let cn = xml.getElementsByTagName('comment_num')[0]; self.cachedInfo.block_no = cn.textContent.replace(/..$/, ''); } function getFLV () { liberator.log('getFLV'); if (self.cachedInfo.flvInfo !== undefined) return; let xhr = U.httpRequest(self.baseURL + 'api/getflv?v=' + self.id); let res = xhr.responseText; self.cachedInfo.flvInfo = U.parseParameter(res); } function getPostkey () { liberator.log('getPostkey'); let info = self.cachedInfo; if (info.postkey !== undefined) return; let url = U.fromTemplate( '--base--api/getpostkey?thread=--thread_id--&block_no=--block_no--', { base: self.baseURL, thread_id: info.flvInfo.thread_id, block_no: info.block_no } ); liberator.log(url); let xhr = U.httpRequest(url); let res = xhr.responseText; info.postkey = res.replace(/^.*=/, ''); } function getComments () { liberator.log('getComments'); let info = self.cachedInfo; if (info.ticket !== undefined) return; let tmpl = ''; let xhr = U.httpRequest(info.flvInfo.ms, U.fromTemplate(tmpl, info.flvInfo)); let xml = xhr.responseXML; let r = xml.evaluate('//packet/thread', xml, null, 9, null, 7, null).singleNodeValue; info.ticket = r.getAttribute('ticket'); } function sendChat () { liberator.log('sendChat'); let info = self.cachedInfo; let tmpl = '--body--'; let args = { __proto__: info.flvInfo, ticket: info.ticket, postkey: info.postkey, // 0 秒コメントはうざいらしいので勝手に自重する vpos: Math.max(100, parseInt(vpos || (self.player.ext_getPlayheadTime() * 100), 10)), body: message }; liberator.log(args); let data = U.fromTemplate(tmpl, args); let xhr = U.httpRequest(info.flvInfo.ms, data); liberator.log(xhr.responseText); } liberator.log('sendcommnet'); getThumbInfo(); getFLV(); getPostkey(); getComments(); sendChat(); } }; // }}} /********************************************************************************* * ContextMenu {{{ *********************************************************************************/ const ContextMenuVolume = []; for (let i = 0; i <= 100; i += 10) ContextMenuVolume.push({name: 'setVolume', label: i + '%', attributes: {volume: i}}); const ContextMenuTree = [ 'play', 'pause', 'comment', 'repeat', 'fullscreen', 'fetch', { name: 'volume-root', label: 'Volume', id: ID_PREFIX + 'volume-menupopup', sub: ContextMenuVolume }, { name: 'relations-root', label: 'Relations', id: ID_PREFIX + 'relations-menupopup', sub: [] } ]; function buildContextMenu (setting) { function append (parent, menu) { if (typeof menu == 'string') menu = {name: menu}; if (menu instanceof Array) return menu.forEach(function (it) append(parent, it)); if (!menu.label) menu.label = U.capitalize(menu.name); let (elem) { if (menu.sub) { let _menu = document.createElement('menu'); let _menupopup = elem = document.createElement('menupopup'); _menu.setAttribute('label', menu.label); _menu.appendChild(_menupopup); parent.appendChild(_menu); append(_menupopup, menu.sub); } else { elem = document.createElement('menuitem'); elem.setAttribute('label', menu.label); parent.appendChild(elem); } menu.id && elem.setAttribute('id', menu.id); for (let [name, value] in Iterator(menu.attributes || {})) elem.setAttribute(name, value); setting.onAppend.call(setting, elem, menu); } } let root = document.createElement('menupopup'); root.id = setting.id; append(root, setting.tree); setting.set.setAttribute('context', root.id); setting.parent.appendChild(root); return root; } // }}} /********************************************************************************* * Event {{{ *********************************************************************************/ function WebProgressListener (listeners) { let self = this; for (let [name, listener] in Iterator(listeners)) this[name] = listener; getBrowser().addProgressListener(this); // これは必要? window.addEventListener('unload', U.bindr(this.uninstall), false); } WebProgressListener.prototype = { onStatusChange: function (webProgress, request, stateFlags, staus) undefined, onProgressChange: function (webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) undefined, onLocationChange: function (webProgress, request, location) undefined, onStateChange: function (webProgress, request, status, message) undefined, onSecurityChange: function (webProgress, request, state) undefined, uninstall: function () getBrowser().removeProgressListener(this) }; // }}} /********************************************************************************* * Stella {{{ *********************************************************************************/ function Stella () { this.initialize.apply(this, arguments); } Stella.MAIN_PANEL_ID = ID_PREFIX + 'main-panel', Stella.MAIN_MENU_ID = ID_PREFIX + 'main-menu', Stella.VOLUME_MENU_ID = ID_PREFIX + 'volume-menu', Stella.prototype = { // new 時に呼ばれる initialize: function () { let self = this; this.players = { niconico: new NicoPlayer(), youtube: new YouTubePlayer() }; this.createStatusPanel(); this.onLocationChange(); this.__onResize = window.addEventListener('resize', U.bindr(this, this.onResize), false); this.progressListener = new WebProgressListener({onLocationChange: U.bindr(this, this.onLocationChange)}); }, // もちろん、勝手に呼ばれたりはしない。 finalize: function () { this.removeStatusPanel(); this.disable(); this.progressListener.uninstall(); for each (let player in this.players) player.finalize(); window.removeEventListener('resize', this.__onResize, false); }, get hidden () (this.panel.hidden), set hidden (v) (this.panel.hidden = v), get isValid () (this.where), get player () this.players[this.where], get statusBar () document.getElementById('status-bar'), get statusBarVisible () !this.statusBar.getAttribute('moz-collapsed', false), set statusBarVisible (value) (this.statusBar.setAttribute('moz-collapsed', !value), value), get where () { for (let [name, player] in Iterator(this.players)) if (player.isValid) return name; }, addUserCommands: function () { let self = this; function add (cmdName, funcS, funcB) { commands.addUserCommand( ['st' + cmdName], cmdName.replace(/[\[\]]+/g, '') + ' - Stella', (funcS instanceof Function) ? funcS : function (arg, bang) { if (!self.isValid) U.raise('Stella: Current page is not supported'); let p = self.player; let func = bang ? funcB : funcS; if (p.has(func, 'rwt')) p.toggle(func); else if (p.has(func, 'rw')) p[func] = arg[0]; else if (p.has(func, 'x')) p[func].apply(p, arg); else U.raise('Stella: The function is not supported in this page.'); self.update(); }, {argCount: '*', bang: !!funcB}, true ); } add('pl[ay]', 'playOrPause', 'play'); add('pa[use]', 'pause'); add('mu[te]', 'muted'); add('re[peat]', 'repeating'); add('co[mment]', 'comment'); add('vo[lume]', 'volume', 'turnUpDownVolume'); add('se[ek]', 'seek', 'seekRelative'); add('fe[tch]', 'fetch'); add('la[rge]', 'large'); add('fu[llscreen]', 'fullscreen'); if (U.s2b(liberator.globalVariables.stella_use_nico_comment, false)) add('sa[y]', 'say'); commands.addUserCommand( ['strel[ations]'], 'relations - Stella', function (args) { let arg = args.string; let url = self.player.has('makeURL', 'x') ? makeRelationURL(self.player, arg) : arg; liberator.open(url, args.bang ? liberator.NEW_TAB : liberator.CURRENT_TAB); }, { argCount: '*', bang: true, completer: function (context, args) { if (!self.isValid) U.raise('Stella: Current page is not supported'); if (!self.player.has('relations', 'r')) return; context.title = ['Tag/ID', 'Description']; context.completions = self.player.relations.map(function (rel) rel.completionItem); }, }, true ); }, createStatusPanel: function () { let self = this; function setEvents (name, elem) { ['click', 'popupshowing'].forEach(function (eventName) { let onEvent = self['on' + U.capitalize(name) + U.capitalize(eventName)]; onEvent && elem.addEventListener(eventName, function (event) { if (eventName != 'click' || event.button == 0) { onEvent.apply(self, arguments); self.update(); } }, false); }); } function createLabel (store, name, l, r) { let label = store[name] = document.createElement('label'); label.setAttribute('value', '-'); label.style.marginLeft = (l || 0) + 'px'; label.style.marginRight = (r || 0) + 'px'; label.__defineGetter__('text', function () this.getAttribute('value')); label.__defineSetter__('text', function (v) this.setAttribute('value', v)); setEvents(name, label); } let panel = this.panel = document.createElement('statusbarpanel'); panel.setAttribute('id', Stella.MAIN_PANEL_ID); let hbox = document.createElement('hbox'); hbox.setAttribute('align', 'center'); let icon = this.icon = document.createElement('image'); icon.setAttribute('class', 'statusbarpanel-iconic'); icon.style.marginRight = '4px'; setEvents('icon', icon); icon.addEventListener('dblclick', U.bindr(this, this.onIconDblClick), false); let labels = this.labels = {}; let toggles = this.toggles = {}; createLabel(labels, 'main', 2, 2); createLabel(labels, 'volume', 0, 2); for each (let player in this.players) { for (let func in player.functions) { if (player.has(func, 't')) (func in labels) || createLabel(toggles, func); } } panel.appendChild(hbox); hbox.appendChild(icon); [hbox.appendChild(label) for each (label in labels)]; [hbox.appendChild(toggle) for each (toggle in toggles)]; let menu = this.mainMenu = buildContextMenu({ id: Stella.MAIN_MENU_ID, parent: panel, set: hbox, tree: ContextMenuTree, onAppend: function (elem, menu) setEvents(U.capitalize(menu.name), elem) }); let stbar = document.getElementById('status-bar'); stbar.insertBefore(panel, document.getElementById('liberator-statusline').nextSibling); let relmenu = document.getElementById('anekos-stela-relations-menupopup'); }, disable: function () { this.hidden = true; if (this.timerHandle) { clearInterval(this.timerHandle); this.timerHandle = null; } }, enable: function () { this.hidden = false; this.icon.setAttribute('src', this.player.icon); for (let name in this.toggles) { this.toggles[name].hidden = !this.player.has(name, 't'); } if (!this.timerHandle) { this.timerHandle = setInterval(U.bindr(this, this.update), 500); } }, removeStatusPanel: function () { let e = this.panel || document.getElementById(this.panelId); if (e && e.parentNode) e.parentNode.removeChild(e); }, update: function () { this.labels.main.text = this.player.statusText; this.labels.volume.text = this.player.volume; for (let name in this.toggles) { this.toggles[name].text = (this.player[name] ? String.toUpperCase : U.id)(name[0]); } }, onCommentClick: function () (this.player.toggle('comment')), onFetchClick: function () this.player.fetch(), // フルスクリーン時にステータスバーを隠さないようにする onFullScreen: function () { if (window.fullScreen) { this.__statusBarVisible = this.statusBarVisible; this.statusBarVisible = true; } else { if (this.__statusBarVisible !== undefined) this.statusBarVisible = this.__statusBarVisible; } }, onFullscreenClick: function () this.player.toggle('fullscreen'), onIconClick: function () this.player.playOrPause(), onIconDblClick: function () this.player.toggle('fullscreen'), onLocationChange: function () { if (this.__valid !== this.isValid) { (this.__valid = this.isValid) ? this.enable() : this.disable(); } }, onMainClick: function (event) { if (event.button) return; if (!(this.player && this.player.has('currentTime', 'rw', 'totalTime', 'r'))) return; let rect = event.target.getBoundingClientRect(); let x = event.screenX; let per = (x - rect.left) / (rect.right - rect.left); this.player.currentTime = this.player.totalTime * per; }, onMutedClick: function (event) this.player.toggle('muted'), onPauseClick: function () this.player.pause(), onPlayClick: function () this.player.play(), onRepeatClick: function () this.player.toggle('repeating'), onRelationsRootPopupshowing: function () { let self = this; function clickEvent (cmd) function () liberator.open(makeRelationURL(self.player, cmd)); if (!this.player) return; let relmenu = document.getElementById('anekos-stela-relations-menupopup'); let rels = this.player.relations; while (relmenu.firstChild) relmenu.removeChild(relmenu.firstChild); rels.forEach(function (rel) { let elem = document.createElement('menuitem'); let prefix = rel instanceof RelatedID ? 'ID: ' : rel instanceof RelatedTag ? 'Tag: ' : ''; elem.setAttribute('label', prefix + rel.description); elem.addEventListener('click', clickEvent(rel.command), false); relmenu.appendChild(elem); }, this); }, onResize: function () { if (this.__fullScreen !== window.fullScreen) { this.__fullScreen = window.fullScreen; this.onFullScreen(this.__fullScreen); } }, onSetVolumeClick: function (event) (this.player.volume = event.target.getAttribute('volume')) }; U.fixDoubleClick(Stella.prototype, 'onIconClick', 'onIconDblClick'); // }}} /********************************************************************************* * Functions {{{ *********************************************************************************/ function makeRelationURL (player, command) { if (!player.has('makeURL', 'x')) U.raise('Mysterious Error! makeURL has been not implmented.'); if (command.match(/^[#\uff03]/)) return player.makeURL(command.slice(1), Player.URL_ID); if (command.match(/^[:\uff1a]/)) return player.makeURL(command.slice(1), Player.URL_TAG); if (command.indexOf('http://') == -1) return player.makeURL(encodeURIComponent(command), Player.URL_TAG); return command; } // }}} /********************************************************************************* * Install {{{ *********************************************************************************/ if (InVimperator) { let estella = liberator.globalVariables.stella; let install = function () { let stella = liberator.globalVariables.stella = new Stella(); stella.addUserCommands(); liberator.log('Stella: installed.'); }; // すでにインストール済みの場合は、一度ファイナライズする // (デバッグ時に前のパネルが残ってしまうため) if (estella) { liberator.log(estella) estella.finalize(); install(); } else { window.addEventListener( 'DOMContentLoaded', function () { window.removeEventListener('DOMContentLoaded', arguments.callee, false); install(); }, false ); } } else { /* do something */ } // }}} })(); // vim:sw=2 ts=2 et si fdm=marker: