aboutsummaryrefslogtreecommitdiffstats
path: root/applauncher.js
blob: 1c28882587a4d938d15538d7387c5b93f6436684 (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>https://github.com/vimpr/vimperator-plugins/raw/master/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){
            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 (let i=0, l=selection.rangeCount; i<l; i++) sel+=selection.getRangeAt(i).toString();
        return sel;
      },
      TITLE: function() buffer.title
    },
    launch: function(appName){
      var self = this;
      appName = appName.replace(/\\+/g, '');                // fix commandline input ' ' -> '\ '
      settings.some( function([name, app, args]){
        args = args instanceof Array ? args : args ? [args] : [];
        args = args.map( function( val ) val.replace(/%([A-Z]+)%/g, function( _, name ) self.variables[name]()) );
        if (defaultCharset){
          UConv.charset = defaultCharset;
          args = args.map( function( val ) UConv.ConvertFromUnicode(val) );
        }
        if (appName == name){
          io.run(app, args);
          return true;
        }
        return false;
      });
    }
  }
  return new AppLauncher();
})();
">(name, value); default: alert('unknown pref type'); } }, }; const tagssvc = Cc["@mozilla.org/browser/tagging-service;1"]. getService(Ci.nsITaggingService); const IOService = Cc["@mozilla.org/network/io-service;1"]. getService(Ci.nsIIOService); const myURI = IOService.newURI("http://www.mozilla.com", null, null); const bookmarks = Cc["@mozilla.org/browser/nav-bookmarks-service;1"]. getService(Ci.nsINavBookmarksService); const history = Cc["@mozilla.org/browser/nav-history-service;1"]. getService(Ci.nsINavHistoryService); let [folderId, folderGUID] = [prefs.get('folderId', false), prefs.get('folderGUID', false)]; if (!(folderGUID && folderId && (folderId == bookmarks.getItemIdForGUID(folderGUID)))) { folderId = bookmarks.createFolder(bookmarks.toolbarFolder, FOLDER_NAME, bookmarks.DEFAULT_INDEX); prefs.set('folderId', folderId); prefs.set('folderGUID', bookmarks.getItemGUID(folderId)); } /* // Get an array of tags for a URI let myTags = tagssvc.getTagsForURI(myURI, {}); // Get an array of URIs for a tag let taggedURIs = tagssvc.getURIsForTag("mozilla"); // Get an array of all tags let arrayOfAllTags = tagssvc.allTags; // Remove tags from a URI tagssvc.untagURI(myURI, ["mozilla", "firefox"]); */ function openURI (uri) { if (window.content.document.location.href == 'about:blank') { window.loadURI(uri); } else { if ('delayedOpenTab' in window) window.delayedOpenTab(uri, null); else window.getBrowser().addTab(uri, null); } } function makeURI (uri) { return IOService.newURI(uri, null, null); } function addEntry (doc, tags) { var loc = doc.location.href; var title = doc.title || loc; var uri = makeURI(loc); var bkmk = bookmarks.insertBookmark(folderId, uri, bookmarks.DEFAULT_INDEX, title); tags.push(RCL_TAG); tagssvc.tagURI(uri, tags); return title; } function splitBySpaces (str) { return [it for each (it in str.split(/\s+/)) if (/\w/.test(it))]; } function RCL_Bookmarks () { try { let query = history.getNewQuery(); query.setFolders([folderId], 1); let result = []; let qres = history.executeQueries([query], 1, history.getNewQueryOptions()); let folderNode = qres.root; let closeOriginally = !folderNode.containerOpen; if (closeOriginally) folderNode.containerOpen = true; for (let i = 0; i < folderNode.childCount; ++i) { let node = folderNode.getChild(i); if (PlacesUtils.nodeIsBookmark(node)) { let it = {id: node.itemId, title: node.title, URI: node.uri }; result.push(it); } } if (closeOriginally) folderNode.containerOpen = false; return liberator.globalVariables.readcatlater_reverse ? result.reverse() : result; } catch (e) { liberator.log(e); } } function completer (context, arg) { context.compare = void 'meow'; context.title = ['URL', 'Title']; context.filters = [CompletionContext.Filter.textDescription]; context.completions = RCL_Bookmarks(). filter(function (it) it.id). map(function (it) [it.URI, bookmarks.getItemTitle(it.id)]). reverse(); } function removeItems (uri) { if (typeof uri === 'number') { bookmarks.removeItem(uri); return true; } if (typeof uri === 'object') { bookmarks.removeItem(uri.id); return true; } var removed = false; for each (let id in bookmarks.getBookmarkIdsForURI(makeURI(uri), {})) if (id && (folderId == bookmarks.getFolderIdForItem(id))) { removed = true; bookmarks.removeItem(id); } return removed; } /******************************************************************************** * Add Command ********************************************************************************/ commands.addUserCommand( ['readcatlater', 'rcl'], 'read cat later', function (args) { var res = addEntry(window.content.document, splitBySpaces(args.string)); if (res) liberator.echo('"' + buffer.title + '" was added'); else liberator.echo("this URI already exists!?"); }, {}, true ); commands.addUserCommand( ['readcatnow', 'rcn'], 'read cat now', function (arg) { let opennum = arg['-number']; if (opennum) { let us = RCL_Bookmarks(arg.literalArg).splice(0, opennum).map(function (it) it); liberator.open(us.map(function (it) it.URI), liberator.NEW_BACKGROUND_TAB); if (!arg.bang) { us.forEach(removeItems); liberator.echo(us.length + ' items were removed.'); } } else { let uri = arg.string; openURI(uri); if (!arg.bang && removeItems(uri)) liberator.echo('"' + uri + '" was removed.'); } }, { literal: 0, options: [ [['-number', '-n'], commands.OPTION_INT] ], completer: completer }, true ); commands.addUserCommand( ['deletecatnow', 'dcn'], 'delete cat now', function (arg) { let uri = arg.string; if (removeItems(uri)) liberator.echo('"' + uri + '" was removed.'); }, { completer: completer }, true ); })();