aboutsummaryrefslogtreecommitdiffstats
path: root/shuppoppo.js
AgeCommit message (Collapse)Author
2008-09-05 * shuppoppo! shuppoppo!drry
git-svn-id: http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk@18896 d0d07461-0603-4401-acd4-de1884942a52
2008-07-20slコマンドとbeep時にslを走らせるteramako
git-svn-id: http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk@16046 d0d07461-0603-4401-acd4-de1884942a52
n47' href='#n47'>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
/**
 * gmperator - Vimperator plugin for Greasemonkey
 * For Vimperator 0.6pre
 * @author teramako teramako@gmail.com
 * @version 0.3a
 *
 * ---------------------------
 * Usage:
 * ---------------------------
 * {{{
 *
 * :gmli[st] {filter}                -> show user scripts matches {filter}
 * :gmli[st]!                        -> show all user scripts
 * :gmli[st] full                    -> same as :gmli[st]!
 *
 * :gmlo[ad] {name|filename}         -> load the user script to the current page
 *                                      but, don't dispatch load event
 *                                      so maybe you should edit the scripts before load
 * :gmlo[ad]! {name|filename}        -> force load the user script
 *
 * :gmset!                           -> toggle enable/disable Greasemonkey
 * :gmset! {filename}                -> toogle enable/disable the script
 * :gmset {filename} {options}
 *   {options}:
 *       -n[ame] {value}              -> change name to {value}
 *       -i[nclude] {expr[,expr,...]} -> change includes to expr list ("," demiliter)
 *       -e[xclude] {expr[,expr,...]} -> change excludes to expr list ("," demiliter)
 *
 * Caution:
 * The change is permanent, not only the session.
 * And cannot get back.
 *
 * ex)
 * :gmset! {filename} -n fooScriptName -i http://*,https://* -e http://example.com/*
 *   toggle enable or disable,
 *   name to "fooScriptName",
 *   includes to "http://*" and "https://*",
 *   and excludes to "http://example.com/*"
 *
 * }}}
 * ---------------------------
 * For plugin developer:
 * ---------------------------
 * {{{
 *
 * 1). can access to the sandbox of Greasemonkey !!!
 * 2). can register commands which execute
 *     when the user script is executed on the URI
 *     @see liberator.plugins.gmperator.addAutoCommand
 *
 * liberator.plugins.gmperator => (
 *   allItem           :  return object of key   : {panalID},
 *                                         value : {GmContainer}
 *                              {panelID}   => @see gBrowser.mTags[].linkedPanel
 *   currentPanel
 *   currentContainer  :  return the current {GmContainer} object
 *   currentSandbox    :  return the current sandbox object
 *   gmScripts         :  return array of {userScripts}
 *                              {userScripts} => (
 *                                  filename   : {String}
 *                                  name       : {String}
 *                                  namespace  : {String}
 *                                  description: {String}
 *                                  enabled    : {Boolean}
 *                                  includes   : {String[]}
 *                                  encludes   : {String[]}
 *                              )
 *  addAutoCommand    : function( uri, script, cmd )
 *                      If both of uri and script is match
 *
 * )
 * }}}
 */
(function(){

const Cc = Components.classes;
const Ci = Components.interfaces;
const gmID = '@greasemonkey.mozdev.org/greasemonkey-service;1';
if (!Cc[gmID]) {
    log('Greasemonkey is not installed');
    return;
}
if(!liberator.plugins) liberator.plugins = {};


liberator.plugins.gmperator = (function(){ //{{{
    // -----------------------
    // PUBLIC section
    // -----------------------
    // {{{
    var manager =  {
        register: function (uri,sandbox,script){
            var panelID = getPanelID(sandbox.window);
            var gmCon;
            if (containers[panelID]){
                gmCon = containers[panelID];
            } else {
                gmCon = new GmContainer(uri,sandbox);
                containers[panelID] = gmCon;
                this.__defineGetter__(panelID,function(){return gmCon;});
                log('gmpeartor: redisted: '+ panelID + ' - ' + uri);
            }
            gmCon.sandbox = sandbox;
            gmCon.addScript(script);
            gmCon.uri = uri;
            autocommands.trigger('GMInjectedScript',uri+'\n'+script.filename);
        },
        get gmScripts(){
            return getScripts();
        },
        get allItem(){
            return containers;
        },
        get currentPanel(){
            return getBrowser().mCurrentTab.linkedPanel;
        },
        get currentContainer(){
            return containers[this.currentPanel] || null;
        },
        get currentSandbox(){
            var id = this.currentPanel;
            return containers[id] ? containers[id].sandbox : null;
        },
        getSandboxFromWindow: function(win){
            for each(var c in containers){
                if(c.sandbox.window == win) return sandbox;
            }
            return null;
        },
        getContainersFromURI: function(uri){
            var list = [];
            for each(var c in containers){
                if (c.uri == uri) list.push(c);
            }
            return list.length > 0 ? list : null;
        },
        addAutoCommand: function(uri, script, cmd){
            var reg = uri+'.*\n'+script+'\.user\.js';
            autocommands.add('GMInjectedScript', reg, cmd);
        },
        removeAutoCommand: function(uri, script){
            var reg = uri+'.*\n'+script+'\.user\.js';
            autocommands.remove('GMInjectedScript', reg);
        },
    };
    // }}}
    // -----------------------
    // PRIVATE section
    // -----------------------
    // {{{
    var containers = {};
    var gmSvc = Cc[gmID].getService().wrappedJSObject;

    function appendCode(target,name,func){
        var original = target[name];
        target[name] = function(){
            var tmp = original.apply(target,arguments);
            func.apply(this,arguments);
            return tmp;
        };
    }
    appendCode(gmSvc, 'evalInSandbox', function(code,uri,sandbox,script){
        liberator.plugins.gmperator.register(uri,sandbox,script);
    });
    function getPanelID(win){
        var tabs = getBrowser().mTabs;
        for (var i=0; tabs.length; i++){
            var tab = tabs.item(i);
            if (tab.linkedBrowser.contentWindow == win){
                return tab.linkedPanel;
            }
        }
        liberator.log(win + 'is no found');
    }
    function updateGmContainerList(e){
        var t = e.target;
        if (t && t.localName == 'tab' && t.linkedPanel){
            delete containers[t.linkedPanel];
            delete plugins.gmperator[t.linkedPanel];
        }
    }
    getBrowser().mTabContainer.addEventListener('TabClose',updateGmContainerList,false);
    // }}}
    return manager;
})(); //}}}

// ---------------------------
// User Command
// ---------------------------
commands.addUserCommand(['gmli[st]','lsgm'], 'list Greasemonkey scripts', //{{{
    function(arg,special){
        var str = '';
        var scripts = getScripts();
        var reg;
        var table, tr;
        if (special || arg == 'full'){
            reg = new RegExp('.*');
        } else if( arg ){
            reg = new RegExp(arg,'i');
        }
        if (reg){
            for each(var s in scripts){
                if ( reg.test(s.name) || reg.test(s.filename) ) {
                    str += scriptToString(s) + '\n\n';
                }
            }
        } else {
            table = <table/>;
            for each(var script in scripts){
                tr = <tr/>;
                if (script.enabled){
                    tr.* += <td><span style="font-weight:bold;">{script.name}</span></td>;
                } else {
                    tr.* += <td>{script.name}</td>;
                }
                tr.* += <td>({script.filename})</td>;
                table.* += tr;
            }
            str += table.toSource();
        }
        echo(str,true);
        function scriptToString(script){
            var table = <table>
                <caption class="hl-Title" style="text-align:left">{script.name}</caption>
            </table>;
            ['FileName', 'NameSpace', 'Description',
             'Includes', 'Excludes', 'Enabled'].forEach(function(prop){
                var tr = <tr>
                    <th style="font-weight:bold;text-align:left;vertical-align:top">{prop}</th>
                </tr>;
                var contents = script[prop.toLowerCase()];
                if (typeof contents == "string"){
                    tr.* += <>{contents}</>;
                } else {
                    contents.forEach(function(c,i,a){
                        tr.* += <>{c}</>;
                        if (a[i+1]) tr.* += <br/>;
                    });
                }
                table.* += tr;
            });
            return table.toSource();
        }
    }
); //}}}
commands.addUserCommand(['gmlo[ad]'], 'load Greasemonkey scripts', //{{{
    function(arg, special){
        if (!arg) {
            echoerr('Usage: :gmlo[ad][!] {name|filename}');
            return;
        }
        var scripts = getScripts();
        var script;
        for (var i=0; i<scripts.length; i++){
            if (scripts[i].filename == arg || scripts[i].name == arg){
                script = scripts[i];
                break;
            }
        }
        if (!script) {
            echoerr('no such a user script');
            return;
        } else if (plugins.gmperator.currentContainer.hasScript(script.filename) && !special){
            echoerr(script.filename + ' is already loaded!');
            return;
        } else {
            echo('loading: ' +script.filename);
        }
        try {
            var href = buffer.URL;
            var unsafewin = window.content.document.defaultView.wrappedJSObject;
            GM_BrowserUI.gmSvc.wrappedJSObject.injectScripts([script],href,unsafewin,window);
        } catch(e){
            log(e);
            echoerr(e);
        }
        /*
        // do you have idea how to dispatch load event to only the script ?
        window.setTimeout(function(){
            var loadEvent = document.createEvent('Event');
            loadEvent.initEvent('load',true,true, window.content.document,1);
            window.content.document.dispatchEvent(loadEvent);
        },100);
        */
    },{
        completer: function(filter){
            return scriptsCompleter(filter,true);
        }
    }
); //}}}
commands.addUserCommand(['gmset'], 'change settings for Greasemonkey scripts', //{{{
    function(arg, special){
        var res = commands.parseArgs(arg, this.args);
        if (!res) {
            if (special) GM_setEnabled(!GM_getEnabled()); // toggle enable/disable Greasemonkey
            return;
        }
        var filename = res.args[0];
        var config = new Config();
        config.load();
        var script;
        for (var i=0; i<config.scripts.length; i++){
            if (config.scripts[i].filename == filename){
                script = config.scripts[i];
                break;
            }
        }
        if (!script) return;
        if (special){ // toggle enable/disable the script if {filename} is exist
            script.enabled = !script.enabled;
        }
        if (res.opts.length > 0){
            script.name     = commands.getOption(res.opts, '-name',    script.name);
            script.includes = commands.getOption(res.opts, '-include', script.includes);
            script.excludes = commands.getOption(res.opts, '-exclude', script.excludes);
        }
        config.save();
    },{
        args: [
            [['-name','-n'],    commands.OPTION_STRING],
            [['-include','-i'], commands.OPTION_LIST],
            [['-exclude','-e'], commands.OPTION_LIST]
        ],
        shortHelp: 'change settings for Greasemonkey scripts',
        help: [
            'toggle enable/disable with "!", if <code>{filename}</code> is exist, if not toggle Greasemonkey',
            '<dl><dt><code>-n</code><br/><code>-name</code></dt><dd>change the name</dd>',
            '<dt><code>-i</code><br/><code>-include</code></dt><dd>change the includes list ("," delimiter)</dd>',
            '<dt><code>-e</code><br/><code>-exclude</code></dt><dd>change the excludes list ("," delimiter)</dd></dl>',
            'Caution: the change is permanent, not the only session.<br/>And cannot get back.'
        ].join(''),
        completer: function(filter){
            return scriptsCompleter(filter, false);
        }
    }
); //}}}

// ---------------------------
// Utils
// ---------------------------
/** Grasemonkey sandbox container {{{
 * @param {String} uri
 * @param {Sandbox} sandbox
 * @param {Array} scripts
 */
function GmContainer(uri,sandbox){
    this.uri = uri;
    this.sandbox = sandbox;
    this.scripts = [];
}
GmContainer.prototype = {
    addScript :  function(script){
        if (this.hasScript(script)) return false;

        return this.scripts.push(script);
    },
    hasScript : function(script){
        var filename;
        switch( typeof(script) ){
            case 'object': filename = script.filename; break;
            case 'string': filename = script; break;
            default: return null;
        }
        return this.scripts.some(function(s){ return s.filename == filename; });
    }
} // }}}
function getScripts(){ //{{{
    var config = new Config();
    config.load();
    return config.scripts;
} //}}}
function scriptsCompleter(filter,flag){ //{{{
    var candidates = [];
    var scripts = getScripts();
    var isAll = false;
    if (!filter) isAll=true;
    if (flag){
        for each(var s in scripts){
            if (isAll || s.name.toLowerCase().indexOf(filter) == 0 ||
                s.filename.indexOf(filter) == 0)
            {
                candidates.push([s.name, s.description]);
                candidates.push([s.filename, s.description]);
            }
        }
    } else {
        for each(var s in scripts){
            if (isAll || s.filename.indexOf(filter) == 0)
            {
                candidates.push([s.filename, s.description]);
            }
        }
    }
    return [0,candidates];
} //}}}

})();

// vim: fdm=marker sw=4 ts=4 et: