aboutsummaryrefslogtreecommitdiffstats
path: root/applauncher.js
blob: ae28700bf9e2fe5256db9563588047bbe1d22bf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
var PLUGIN_INFO =
<VimperatorPlugin>
  <name>AppLauncher</name>
  <name lang='ja'>アプリケーションランチャー</name>
  <description>Launch defined application</description>
  <description lang='ja'>アプリケーションを起動します</description>
  <version>0.12</version>
  <author>pekepeke</author>
  <minVersion>2.0pre</minVersion>
  <maxVersion>2.0pre</maxVersion>
  <updateURL>http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/applauncher.js</updateURL>
  <detail lang='ja'><![CDATA[
  == Commands ==
    :applaunch [name]:
    :runapp [name]:
      [name] で指定されたアプリケーションを起動します
  == .vimperatorrc example ==
    >||
    js <<EOM
    liberator.globalVariables.applauncher_list = [
      [ 'name', 'application path', ['arguments', '%URL%', '%SEL%']],
      [ 'Internet Explorer', 'C:\\Program Files\\Internet Explorer\\iexplore.exe', '%URL%'],
      [ 'Internet Explorer(Search)', 'C:\\Program Files\\Internet Explorer\\iexplore.exe', '%SEL%'],
    ];
    liberator.globalVariables.applauncher_charset = 'Shift_JIS';
    EOM
    ||<
    %URL% は実行時に選択中のリンクURLもしくは開いているページのURLに置き換えられます
    %SEL% は選択中の文字列に置き換えられます
    %TITLE% はページのタイトルに置き換えられます
    引数を複数指定する場合は配列形式で指定してください
    applauncher_charset を指定すると渡される文字列が指定の文字セットに変換されます
  ]]></detail>
</VimperatorPlugin>

liberator.plugins.AppLauncher = (function(){
  const UConv = Cc['@mozilla.org/intl/scriptableunicodeconverter'].getService(Ci.nsIScriptableUnicodeConverter);
  const AppName = 'AppLauncher';

  var global = liberator.globalVariables;
  var settings = global.applauncher_list || [];
  var defaultCharset = global.applauncher_charset;
  if (!settings || settings.length <= 0) return;
  var completer = settings.map( function([name, app, args]) [name, args ? app + ' ' + args.toString(): app] );

  var Class = function() function(){ this.initialize.apply(this, arguments); };
  var AppLauncher = new Class();

  AppLauncher.prototype = {
    initialize: function(){
      this.buildMenu();
      this.registerCommand();
    },
    registerCommand: function(){
      var self = this;
      commands.addUserCommand(['applaunch', 'runapp'], 'Run Defined Application',
        function(arg){
          arg = (typeof arg.string == 'undefined' ? arg : arg.string);
          self.launch(arg);
        }, {
          completer: function( context, arg, special){
            var filter = context.filter;
            context.title = [ 'Name', 'Description'];
            if (!filter){
              context.completions = completer;
              return;
            }
            filter = filter.toLowerCase();
            context.completions = completer.filter( function(el) el[0].toLowerCase().indexOf(filter) == 0);
          }
        });
    },
    buildMenu: function(){
      var self = this;
      var menu = document.getElementById('contentAreaContextMenu')
                         .appendChild(document.createElement('menu'));
      menu.setAttribute('id', AppName + 'Context');
      menu.setAttribute('label', AppName);
      menu.setAttribute('accesskey', 'L');

      var menupopup = menu.appendChild(document.createElement('menupopup'));
      menupopup.setAttribute('id', AppName + 'ContextMenu');
      for (let i=0, l=settings.length; i<l; i++){
        let [name, app, args] = settings[i];
        let menuitem = menupopup.appendChild(document.createElement('menuitem'));
        menuitem.setAttribute('id', AppName + i);
        menuitem.setAttribute('label', name + '\u3092\u8D77\u52D5');
        menuitem.addEventListener('command', function() self.launch(name), false);
      }
    },
    variables: {
      __noSuchMethod__: function(name) name,
      URL: function() gContextMenu && gContextMenu.onLink ? gContextMenu.getLinkURL() : buffer.URL,
      SEL: function(){
        var selection = window.content.window.getSelection();
        var sel = '';
        for (// Last Change: 21-Jan-2010. Jan 2008
var PLUGIN_INFO =
<VimperatorPlugin>
    <name>{NAME}</name>
    <description>Direct Post to Social Bookmarks</description>
    <author mail="trapezoid.g@gmail.com" homepage="http://unsigned.g.hatena.ne.jp/Trapezoid">Trapezoid</author>
    <version>0.15</version>
    <license>GPL</license>
    <minVersion>2.0pre</minVersion>
    <maxVersion>2.2</maxVersion>
    <updateURL>http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/direct_bookmark.js</updateURL>
    <detail><![CDATA[
Social Bookmark direct add script for Vimperator 2.2
for Migemo search: require XUL/Migemo Extension

== Parts ==
- http://d.hatena.ne.jp/fls/20080309/p1
- Pagerization (c) id:ofk
- AutoPagerize (c) id:swdyh
- direct_delb.js id:mattn
- JSDeferred id:cho45


== Variables ==
=== g:direct_sbm_use_services_by_tag ===
>||
      Use social bookmark services to extract tags
          'h': Hatena Bookmark
          'd': del.icio.us
          'l': livedoor clip
          'p':
:direct_sbm_use_services_by_tag = "hdl" ||< === g:direct_sbm_use_services_by_post === >|| Use social bookmark services to post 'h': Hatena Bookmark 'd': del.icio.us 'l': livedoor clip 'g': Google Bookmarks 'p': Places (Firefox bookmarks) Usage: let g:direct_sbm_use_services_by_post = "hdl" ||< === g:direct_sbm_echo_type === >|| Post message type 'simple' : single line, no posted services description 'multiline' : multi line, display services description 'none' : hide post message ||< === g:direct_sbm_is_normalize === >|| Use normalize permalink ||< === g:direct_sbm_is_use_migemo === >|| Use Migemo completion ||< == Commands == === :btags === >|| Extract tags from social bookmarks for completion ||< === :sbm === >|| Post a current page to social bookmarks Arguments -s,-service: default:"hdl" Specify target SBM services to post ||< === :bentry === >|| Goto Bookmark Entry Page ||< === :bicon === >|| Show Bookmark Count as Icon ||< ]]></detail> </VimperatorPlugin>; (function(){ var evalFunc = window.eval; try { var sandbox = new Components.utils.Sandbox(window); if (Components.utils.evalInSandbox("true", sandbox) === true) { evalFunc = function(text) { return Components.utils.evalInSandbox(text, sandbox); } } } catch(e) { liberator.log('warning: direct_bookmark.js is working with unsafe sandbox.'); } var useServicesByPost = liberator.globalVariables.direct_sbm_use_services_by_post || 'hdl'; var useServicesByTag = liberator.globalVariables.direct_sbm_use_services_by_tag || 'hdl'; var echoType = liberator.globalVariables.direct_sbm_echo_type || 'multiline'; var isNormalize = typeof liberator.globalVariables.direct_sbm_is_normalize == 'undefined' ? true : evalFunc(liberator.globalVariables.direct_sbm_is_normalize); var isUseMigemo = typeof liberator.globalVariables.direct_sbm_is_use_migemo == 'undefined' ? true : evalFunc(liberator.globalVariables.direct_sbm_is_use_migemo); var XMigemoCore; try{ XMigemoCore = Components.classes['@piro.sakura.ne.jp/xmigemo/factory;1'] .getService(Components.interfaces.pIXMigemoFactory) .getService("ja"); } catch(ex if ex instanceof TypeError){} function Deferred () this instanceof Deferred ? this.init(this) : new Deferred(); Deferred.prototype = { init : function () { this._next = null; this.callback = { ok: function (x) x, ng: function (x) { throw x } }; return this; }, next : function (fun) this._post("ok", fun), error : function (fun) this._post("ng", fun), call : function (val) this._fire("ok", val), fail : function (err) this._fire("ng", err), cancel : function () { (this.canceller || function () {})(); return this.init(); }, _post : function (okng, fun) { this._next = new Deferred(); this._next.callback[okng] = fun; return this._next; }, _fire : function (okng, value) { var self = this, next = "ok"; try { value = self.callback[okng].call(self, value); } catch (e) { next = "ng"; value = e; } if (value instanceof Deferred) { value._next = self._next; } else if (self._next) { self._next._fire(next, value); } return this; } }; Deferred.next = function (fun) { var d = new Deferred(); var id = setTimeout(function () { clearTimeout(id); d.call() }, 0); if (fun) d.callback.ok = fun; d.canceller = function () { try { clearTimeout(id) } catch (e) {} }; return d; }; function http (opts) { var d = Deferred(); var req = new XMLHttpRequest(); req.open(opts.method, opts.url, true, opts.user || null, opts.password || null); if (opts.headers) { for (var k in opts.headers) if (opts.headers.hasOwnProperty(k)) { req.setRequestHeader(k, opts.headers[k]); } } req.onreadystatechange = function () { if (req.readyState == 4) d.call(req); }; req.send(opts.data || null); d.xhr = req; return d; } http.get = function (url) http({method:"get", url:url}); http.post = function (url, data) http({method:"post", url:url, data:data, headers:{"Content-Type":"application/x-www-form-urlencoded"}}); Deferred.Deferred = Deferred; Deferred.http = http; function WSSEUtils(aUserName, aPassword){ this._init(aUserName, aPassword); } WSSEUtils.prototype = { get userName() this._userName, get noce() this._nonce, get created() this._created, get passwordDigest() this._passwordDigest, getWSSEHeader: function(){ var result = [ 'UsernameToken Username="' + this._userName + '", ', 'PasswordDigest="' + this._passwordDigest + '=", ', 'Nonce="' + this._nonce + '", ', 'Created="' + this._created + '"' ].join(""); return result; }, _init: function(aUserName, aPassword){ var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator); var seed = (new Date()).toUTCString() + uuidGenerator.generateUUID().toString(); this._userName = aUserName; this._nonce = this._getSha1Digest(seed, true); this._created = this._getISO8601String((new Date())); this._passwordDigest = this._getSha1Digest(this._getSha1Digest(seed, false) + this._created + aPassword, true); }, _getSha1Digest: function(aString, aBase64){ var cryptoHash = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash); cryptoHash.init(Ci.nsICryptoHash.SHA1); var inputStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream); inputStream.setData(aString, aString.length); cryptoHash.updateFromStream(inputStream, -1); return cryptoHash.finish(aBase64); }, _getISO8601String: function(aDate){ var result = [ zeropad(aDate.getUTCFullYear(), 4), "-", zeropad(aDate.getUTCMonth() + 1, 2), "-", zeropad(aDate.getUTCDate(), 2), "T", zeropad(aDate.getUTCHours(), 2), ":", zeropad(aDate.getUTCMinutes(), 2), ":", zeropad(aDate.getUTCSeconds(), 2), "Z" ].join(""); return result; function zeropad(s, l){ s = String(s); while(s.length < l){ s = "0" + s; } return s; } } }; // copied from AutoPagerize (c) id:swdyh function getElementsByXPath(xpath, node){ node = node || document; var nodesSnapshot = (node.ownerDocument || node).evaluate(xpath, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var data = []; for(var i = 0, l = nodesSnapshot.snapshotLength; i < l; data.push(nodesSnapshot.snapshotItem(i++))); return (data.length > 0) ? data : null; } function getFirstElementByXPath(xpath, node){ node = node || document; var result = (node.ownerDocument || node).evaluate(xpath, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); return result.singleNodeValue ? result.singleNodeValue : null; } // copied from http://d.hatena.ne.jp/odz/20060901/1157165797 id:odz function parseHTML(text) { var createHTMLDocument = function() { var xsl = (new DOMParser()).parseFromString( ['<?xml version="1.0"?>', '<stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform">', '<output method="html"/>', '</stylesheet>'].join("\n"), "text/xml"); var xsltp = new XSLTProcessor(); xsltp.importStylesheet(xsl); var doc = xsltp