/* NEW BSD LICENSE {{{ Copyright (c) 2010, 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 = alias alias Define the alias for a command. コマンドに別名(エイリアス|alias)をつける。 1.0.0 anekos new BSD License (Please read the source code comments of this plugin) 修正BSDライセンス (ソースコードのコメントを参照してください) http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/alias.js 2.3 2.3 : Define the alias with for the command . ]]> : コマンド という別名をつけます。 ]]> ; // }}} // INFO {{{ let INFO = <> anekos New BSD License :alias :alias newCommandName oldCommandName

Define the alias with newCommandName for the command oldCommandName.

alias examples for .vimperatorrc

If you input directly these commands in vimperator commandline, remove the ":lazy".

:command! -nargs=+ lazy autocmd VimperatorEnter .* <args> :lazy alias newName oldCommandName
anekos New BSD License :alias :alias newCommandName oldCommandName

コマンド oldCommandNamenewCommandName という別名をつけます。

alias examples for .vimperatorrc

If you input directly these commands in vimperator commandline, remove the ":lazy".

:command! -nargs=+ lazy autocmd VimperatorEnter .* <args> :lazy alias newName oldCommandName
; // }}} (function () { commands.addUserCommand( ['alias'], 'Define the alias for a command.', function (args) { let [newName, oldName] = args; let cmd = commands.get(oldName); if (!cmd) return liberator.echoerr('Not found command with: ' + oldName); cmd.specs.push(newName); // XXX 必要でない気もする。実際コマンドの検索には要らない。 Command.prototype.init.call(cmd, cmd.specs, cmd.description, cmd.action); }, { completer: function (context, args) { if (args.completeArg == 1) return completion.command(context); } }, true ); })(); // vim:sw=2 ts=2 et si fdm=marker: id='n72' href='#n72'>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
// PLUGIN_INFO//{{{
var PLUGIN_INFO =
<VimperatorPlugin>
    <name>{NAME}</name>
    <description>browser act scenario semi-automatic.</description>
    <author mail="konbu.komuro@gmail.com" homepage="http://d.hatena.ne.jp/hogelog/">hogelog</author>
    <version>0.0.6</version>
    <minVersion>2.0a2</minVersion>
    <updateURL>http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/scenario-actor.js</updateURL>
    <detail><![CDATA[
== Usage ==
browser act scenario semi-automatic.

== Needs Library ==
- _libly.js(ver.0.1.17)
  @see http://coderepos.org/share/browser/lang/javascript/vimperator-plugins/trunk/_libly.js

== SETTING ==
Scenario list is loaded by script under RUNTIME_PATH/plugin/scenario,
and liberator.globalVariables.userScenario.
liberator.globalVariables.userScenario can be set
by .vimperatorrc (or _vimperatorrc) using inline JavaScript.
>||
// hatena sample
javascript <<EOM
liberator.globalVariables.userScenario = {
    DOMContentLoaded: [
    { // good by hatena keyword
        pattern: 'http://d.hatena.ne.jp/keyword/',
        action: [
            {sleep: 1000},
            {follow: '//a[contains(@href,"http://ja.wikipedia.org/wiki")]'},
        ],
    },
    { // auto paging hatena in 5 seconds
        pattern: 'hatena.ne.jp',
        action: {and: [
            {sleep: 5000},
            {follow: '//a[@rel="prev"]'},
        ]}
    },
    { // recent vector site is confusing
        pattern: 'http://www.vector.co.jp/soft/',
        action: {or: [
            {follow: ['//a[not(starts-with(@href,"http")) and contains(@href,"/soft/dl/")]', liberator.NEW_TAB]},
            {follow: '//a[not(starts-with(@href,"http")) and contains(@href,"/download/file/")]'},
        ]}
    },
    ],
    load: [
    { // auto hatena star
        pattern: 'hatena.ne.jp/',
        action:
            {follow: '//img[@class="hatena-star-add-button"]'},
    },
    ],
};
EOM
||<
Action expressions like
>||
action: {and: [
    {sleep: 5000},
    {follow: '//a[@rel="prev"]'},
]}
||<
is syntax-sugar of
>||
action: [{and: [
    {sleep: [5000]},
    {follow: ['//a[@rel="prev"]']},
]}]
||<
and action expressions are quoted by {begin: ...}.
== TODO ==
- write more examples.
- add more functions.
- fix bugs.
- a lot.
     ]]></detail>
</VimperatorPlugin>;
//}}}
(function() {

const debugMode = true;
const VariablesName = 'ScenarioActorVariables';
const VariablesLabelID = 'ScenarioActorVariablesLabelID';

let SCENARIO_DIR = liberator.globalVariables.scenarioDir || 'scenario';

var libly = liberator.plugins.libly;
var $U = libly.$U;
var logger = $U.getLogger('scenario-actor');

function ScenarioActor () { //{{{
    let variables = storage.newMap('scenarioactor', true);

    function ScenarioContext(event) { //{{{
        let triggeredEvent = event;
        let win = (event.target.contentDocument||event.target).defaultView;
        let self = {
            glet: function (name, value) {
                if((typeof name)!='string') throw [name, value];
                variables.set(name, self.eval(value));
                return value;
            },
            gvar: function (name) {
                if((typeof name)!='string') throw [name, value];
                return variables.get(name);
            },
            begin: function () {
                let lastValue;
                for(let i=0,len=arguments.length;i<len;++i) {
                    lastValue = self.eval(arguments[i]);
                }
                return lastValue;
            },
            and: function () {
                let lastValue;
                for(let i=0,len=arguments.length;i<len;++i) {
                    if(!(lastValue = self.eval(arguments[i]))) break;
                }
                return lastValue;
            },
            or: function () {
                let lastValue;
                for(let i=0,len=arguments.length;i<len;++i) {
                    if(lastValue = self.eval(arguments[i])) break;
                }
                return lastValue;
            },
            loop: function (cond, exp) {
                let mainThread = services.get('threadManager').mainThread;
                let f = function() {
                    if(!self.eval(cond)) return;
                    self.eval(exp);
                    mainThread.processNextEvent(true);
                    f();
                };
                setTimeout(f, 1);
            },
            get: function (dst, prop) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst, prop];

                return edst[prop];
            },
            set: function (dst, src, prop) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst, src, prop];

                edst[prop] = self.eval(src);
                return edst[prop];
            },
            xpath: function (xpath) {
                if((typeof xpath)!='string'||!win.document) throw [name, value];
                return buffer.evaluateXPath(xpath, win.document).snapshotItem(0);
            },
            value: function (dst, src) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst, src];

                if(src!=undefined) { // set
                    edst.value = self.eval(src);
                }
                return edst.value;
            },
            click: function (dst) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst];
                edst.click();
                return edst;
            },
            follow: function(dst, where) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst, where];
                buffer.followLink(edst, where?where:liberator.CURRENT_TAB)
                return edst;
            },
            remove: function (dst) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst];
                edst.parentNode.removeChild(edst);
                return edst;
            },
            saveLink: function (dst, skipPrompt) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst, skipPrompt];
                buffer.saveLink(edst, skipPrompt);
                return edst;
            },
            innerText: function (dst, src) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst, src];

                if(src==undefined) { // get
                    return edst.innerText;
                }
                let esrc = self.eval(src);
                edst.innerText = esrc;
                return esrc;
            },
            innerHTML: function (dst, src) {
                let edst = self.eval({xpath: self.eval(dst)});
                if(!edst) throw [dst, src];

                if(src==undefined) { // get
                    return edst.innerHTML;
                }
                let esrc = self.eval(src);
                edst.innerHTML = esrc;
                return esrc;
            },
            url: function() {
                if(!win.document) throw [];
                return win.document.location.href;
            },
            prompt: function(message, init) {
                if(!win) throw [message, init];
                return win.prompt(message||'', init||'');
            },
            sleep: function(delay) {
                return liberator.sleep(delay);
            },
            close: function() {
                if(!win) throw [];
                return win.close();
            },
            jseval: function() {
                let f = arguments[0];
                let args = Array.prototype.slice.call(arguments);
                args.shift();
                if(typeof f!='function') throw [f].concat(args);
                return f.apply(this, args);
            },
            showVariables: function (names) {
                if(!win.document) throw [names];
                actor.showVariables(win.document, names);
            },
            eval: function(exp) {
                switch(typeof exp) {
                    default:
                    case 'bolean':
                    case 'number':
                    case 'string':
                    case 'function':
                        return exp;
                    case 'object':
                        for(let sym in exp) {
                            let args = exp[sym];
                            if(debugMode) logger.log('{'+sym+': '+args+'}');
                            try {
                                if(args instanceof Array) {
                                    return self[sym].apply(this, args);
                                }
                                return self[sym](args);
                            } catch(args if args instanceof Array) {
                                let msg = '{'+sym+': ['+args.join(',')+']}';
                                liberator.reportError(msg);
                                return false;
                            }
                        }
                }
            },
        };
        return self;
    } //}}}

    function createLabel(doc, labelID) {
        let label;
        if(!(label = doc.getElementById(labelID))) {
            label = doc.createElement('pre');
            label.id = VariablesLabelID;
            label.style.position = 'absolute';
            label.style.top = '0px';
            label.style.left = '0px';
            label.style.margin = '0px';
            label.style.padding = '0px';
            label.style.fontSize = '80%';
            label.style.border = '1px solid #ccc';
            label.style.backgroundColor = '#fff';
            label.style.textAlign = 'left';
            label.style.zIndex = '100';
            doc.body.appendChild(label);
        }
        return label;
    }
    function urlmatcher(url) {
        return function(scenario) {
            if(scenario.pattern) {
                let pattern = scenario.pattern;
                switch(typeof pattern) {
                    case 'string':
                        if(url.indexOf(pattern)==-1) return false;
                        break;
                    case 'object':
                        if(!pattern.test(url)) return false;
                        break;
                }
            }
            if(scenario.ignore) {
                let ignore = scenario.ignore;
                switch(typeof ignore) {
                    case 'string':
                        if(url.indexOf(ignore)!=-1) return false;
                        break;
                    case 'object':
                        if(ignore.test(url)) return false;
                        break;
                }
            }
            return true;
        }
    }

    let self = {
        enabled: true,
        readScenarioDirectory: function(name, fun) {
            io.getRuntimeDirectories(SCENARIO_DIR).forEach(function(dir) {
                $U.readDirectory(dir.path, name, fun);
            });
        },
        loadLocalScenario: function(name) {
            if(!name) name = '\.js$';

            if(liberator.globalVariables.userScenario)
                loadedScenarioList.push(liberator.globalVariables.userScenario);
            self.readScenarioDirectory(name, function(file) {
                logger.log('load scenario '+file.path);
                io.source(file.path);
            });
            loadedScenarioList.forEach(function(list) {
                for(let event in list) {
                    self.addListener(event, list[event]);
                }
            });
        },
        showVariables: function(doc, names) {
            if(!doc)
                doc = window.content.document;
            if(!names) {
                names = [name for([name, value] in variables)];
            }

            let label = createLabel(doc, VariablesLabelID);
            label.innerHTML = [arg+': '+variables.get(arg) for each(arg in names)].join("\n");
        },
        clear: function () {
            variables.clear();
        },
        addListener: function (eventType, scenarioList) {
            if(!scenarioList || scenarioList.length==0) return scenarioList;

            getBrowser().addEventListener(eventType,
                    function (event) {
                        if (!self.enabled)
                            return;
                        let context = ScenarioContext(event);
                        let url = context.url();
                        if(!url) return false;
                        let matchfun = urlmatcher(url);
                        scenarioList.forEach(function(scenario) {
                            if(matchfun(scenario)) {
                                context.eval({begin: scenario.action});
                            }
                        });
                    },
                    true);
        },
    };
    return self;
}; //}}}

let actor = plugins.scenarioActor = ScenarioActor();

let loadedScenarioList = plugins.scenarioActor.loadedScenarioList = [];

actor.enabled = !/^(?:false|0)$/i.test(liberator.globalVariables.scenario_actor_enabled);

actor.loadLocalScenario();

commands.addUserCommand(['scenarioclear'], 'clear scenario-actor variables',
        actor.clear,
        {
            argCount: '0',
        });
commands.addUserCommand(['scenariovars'], 'show scenario-actor variables',
        function(args) {
            actor.showVariables(window.content.document);
        },
        {
            argCount: '0',
        });
commands.addUserCommand(['scenarioload'], 'load local scenario',
        function(args) {
            if(args.length) {
                args.forEach(actor.loadLocalScenario);
            } else {
                actor.loadLocalScenario();
            }
        },
        {
            argCount: '*',
            completer: function (context, args) {
                let completions = [];
                actor.readScenarioDirectory(name, function(file) {
                    completions.push([file.leafName, '']);
                });
                context.completions = completions;
            }
        });
commands.addUserCommand(['scenario'], 'turn on/off scenario-actor',
        function(args) {
            if (args.length) {
                switch (args[0].toLowerCase()) {
                    case 'on':
                        actor.enabled = true;
                        break;
                    case 'off':
                        actor.enabled = false;
                        break;
                    default:
                        liberator.echoerr('Invalid argument: ' + args[0]);
                        return;
                }
            } else {
                actor.enabled = !actor.enabled;
            }
            liberator.echo('scenario-actor was ' + (actor.enabled ? 'enabled' : 'disabled'));
        },
        {
            argCount: '*',
            completer: function (context, args) {
                context.completions = [['on', 'enable scenario-actor'], ['off', 'disable scenario-actor']];
            }
        });
})();
// vim: set fdm=marker sw=4 ts=4 et: