aboutsummaryrefslogtreecommitdiffstats
path: root/stylechanger.js
blob: f76fef7f980856bb9204de78f139753476b32aa8 (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
/* NEW BSD LICENSE {{{
Copyright (c) 2010-2011, 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       #
# に参考になる日本語訳がありますが、有効なのは上記英文となります。                #
###################################################################################

}}} */

// INFO {{{
let INFO = xml`
  <plugin name="跳.jp" version="1.0.2"
          href="http://vimpr.github.com/"
          summary="跳ねます"
          lang="ja"
          xmlns="http://vimperator.org/namespaces/liberator">
    <author email="anekos@snca.net">anekos</author>
    <license>New BSD License</license>
    <project name="Vimperator" minVersion="3.0"/>
    <p></p>
    <item>
      <tags>:in-nantoka</tags>
      <spec>:in-nantoka <oa>URL</oa></spec>
      <description><p>
        Copy to clipboard.
      </p></description>
    </item>
  </plugin>
`;
// }}}


(function () {
  function getc (url, callback) {
    function toResult (html) {
      return [html, html.match(/**
 * ==VimperatorPlugin==
 * @name           stylesheet changer
 * @description    enable to apply user stylesheets like Stylish
 * @description-ja Stylishの様にユーザスタイルシートの適用を可能にします
 * @author         teramako teramako@gmail.com
 * @url            http://coderepos.org/share/wiki/VimperatorPlugin/stylechanger.js
 * @license        MPL 1.1/GPL 2.0/LGPL 2.1
 * @version        0.3c
 * ==/VimperatorPlugin==
 *
 * Usage:
 *
 * :hi[ghlight] [groupName]             -> list all or specified group temporary-style(s)
 * :hi[ghlight] clear [groupName}       -> clear all or specified group temporary-styles
 * :hi[ghlight] {groupName} {style...}  -> define style as {groupName}
 *
 * :altcolo[rschema]                -> list available site alternative styles (`*'-marked is current style)
 * :altcolo[rschema] {altStyleName} -> switch to the style
 *
 * :colo[rschema]                -> list available user stylesheets (`*'-marked are loaded styles)
 * :colo[rschema] {styleName}    -> enable the style
 * :colo[rschema]! {styleName}   -> disable the style
 *
 *     {styleName}               -> the name taked away from a CSS-file-name '.css' suffix
 *      CSS-file are put in "~/vimperator/colors" directory
 *
 * `colors[chema]' command is similar to Stylish
 *
 * Example:
 *
 * auto load settings
 *    let g:styles = "style, name"
 *
 */

(function(){

liberator.plugins.styleSheetsManger = (function(){
	var sss = Components.classes['@mozilla.org/content/style-sheet-service;1'].getService(Components.interfaces.nsIStyleSheetService);
	var ios = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService);
	var CSSDataPrefix = 'data:text/css,';
	function init() {
		if (globalVariables.styles) globalVariables.styles.split(/\s*,\s*/).forEach(manager.load);
	}
	function getCSSFiles() {
		var files = [];
		io.getRuntimeDirectories('colors')
		  .filter(function(colorDir) colorDir)
		  .forEach(function(colorDir)
			io.readDirectory(colorDir)
			  .forEach(function(file) {
				if (/\.css$/.test(file.leafName.toLowerCase()) && !file.isDirectory()) {
					files.push(file);
				}
			}));
		return files;
	}
	function getURIFromName(aName){
		var ret = null;
		io.getRuntimeDirectories('colors').some(function(file){
			file.append(aName + '.css');
			if (file.exists()){
				ret = ios.newFileURI(file);
				return true;
			}
		});
		return ret;
	}
	function getURIFromCSS(aString) ios.newURI('data:text/css,' + aString, null, null);
	function getStylesheetList(){
		var list = [];
		var stylesheets = getAllStyleSheets(window.content);
		stylesheets.forEach(function(style){
			var media = style.media.mediaText.toLowerCase();
			if (media && media.indexOf('screen') == -1 && media.indexOf('all') == -1) return;
			if (style.title) list.push([style.title, style.disabled === true ? false : true]);
		});
		return list;
	}
	var manager = {
		load: function(css){
			if (!css) return false;
			var uri = null;
			if (typeof css == 'string'){
				uri = getURIFromName(css);
			} else if (css instanceof Components.interfaces.nsIURI){
				uri = css;
			}
			if (!uri) return false;
			if (sss.sheetRegistered(uri, sss.USER_SHEET))
				sss.unregisterSheet(uri, sss.USER_SHEET);
			sss.loadAndRegisterSheet(uri, sss.USER_SHEET);
			if (options.verbose > 8)
				log('Resisted colorschema '+css);
			return true;
		},
		unload: function(css){
			if (!css) return false;
			var uri = null;
			if (typeof css == 'string'){
				uri = getURIFromName(css);
			} else if (css instanceof Components.interfaces.nsIURI){
				uri = css;
			}
			if (!uri) return false;
			if (sss.sheetRegistered(uri, sss.USER_SHEET))
				sss.unregisterSheet(uri, sss.USER_SHEET);
			if (options.verbose > 8)
				log('Unresisted colorschema '+css);
			return true;
		},
		list: function(isAltanative){
			var str = [];
			if (isAltanative){
				str.push('<span class="hl-Title">Alternative StyleSheet List</span>');
				getStylesheetList().forEach(function(elm, i){
					var buf = ' ' + (i+1) + ' ';
					if (elm[1]){
						buf += '<span style="color:blue">*</span>';
					} else {
						buf += ' ';
					}
					str.push(buf + ' ' + elm[0]);
				});;
				if (str.length == 1) str = ['Alternative StyleSheet is none.'];
			} else {
				str.push('<span class="hl-Title">User StyleSheet List</span>');
				var files = getCSSFiles().map(function(file) file.leafName.replace(/\.css$/i, ''));
				files.forEach(function(file, i){
					var buf = ' ' + (i+1) + ' ';
					if (sss.sheetRegistered(getURIFromName(file), sss.USER_SHEET)){
						buf += '<span style="color:blue">*</span>';
					} else {
						buf += ' ';
					}
					str.push(buf +' ' + file);
				});
			}
			echo(str.join('\n'), true);
		},
		get highlightList(){
			return CSSData;
		}
	};
	commands.addUserCommand(['altcolo[rschema]'], 'set alternativeStyleSheet',
		function(arg){
			if (!arg){
				manager.list(true);
				return;
			} else if (getStylesheetList().some(function(elm) elm[0] == arg)){
				stylesheetSwitchAll(window.content, arg);
				setStyleDisabled(false);
			}
		}, {
			completer: function(aFilter){
				var styles = getStylesheetList().map(function(elm)
					[elm[0], elm[1] ? '* ' : '  ' + 'alternative style']);
				if (!aFilter) return [0, styles];
				var candidates = styles.filter(function(elm) elm[0].indexOf(aFilter) == 0);
				return [0, candidates];
			}
		}
	);
	commands.addUserCommand(['colo[rschema]'], 'set user stylesheet',
		function(arg, special){
			if (!arg){
				manager.list(false);
				return;
			}
			if (special){
				manager.unload(arg) && echo('Unredisted '+arg);
			} else {
				manager.load(arg) && echo('Redisted '+arg);
			}
		}, {
			completer: function(filter, special){
				var list = getCSSFiles().map(function(file){
					var name = file.leafName.replace(/\.css$/i, '');
					return [name, sss.sheetRegistered(getURIFromName(name), sss.USER_SHEET) ? '*' : ''];
				});
				if (!filter) return [0, list];
				var candidates = [];
				list.forEach(function(item){
					if (item[0].toLowerCase().indexOf(filter) == 0){
						candidates.push(item);
					}
				});
				return [0, candidates];
			},
			bang: true
		}
	);
	var CSSData = {};
	commands.addUserCommand(['hi[ghlight]'], 'temporary style changer',
		function(args){
			if (args.length == 0){
				var str = ['show highlight list'];
				for (let name in CSSData){
					str.push('<span class="hl-Title">' + name + '</span>');
					str.push(CSSData[name]);
				}
				echo(str.join('\n'), true);
			} else if (args.length == 1){
				var arg = args[0];
				if (arg == 'clear'){
					for (let name in CSSData){
						manager.unload(getURIFromCSS(CSSData[name]));
						delete CSSData[name];
					}
				} else if (arg in CSSData){
					echo('<span class="hl-Title">' + rel.args[0] + '</span>\n' + CSSData[rel.args[0]], true);
				}
			} else if (args.length > 1){
				var groupName = args.shift();
				if (groupName == 'clear'){
					args.forEach(function(name){
						if (name in CSSData){
							manager.unload(getURIFromCSS(CSSData[name]));
							delete CSSData[name];
						}
					});
				} else {
					if (groupName in CSSData) manager.unload(getURIFromCSS(CSSData[groupName]));
					CSSData[groupName] = args.join(' ');
					manager.load(getURIFromCSS(CSSData[groupName]));
				}
			}
		}, {
			completer: function(context, args){
				var list1 = [['clear', 'clear all or specified group']];
				var list2 = [];
				if (!args){
					for (let name in CSSData){
						list2.push([name, CSSData[name]]);
					}
					return [0, list1.concat(list2)];
				}
				if (args.length == 2 && args[0] == 'clear'){
					for (let name in CSSData){
						if (name.indexOf(args[1]) == 0) list2.push([name, CSSData[name]]);
					}
					return [6, list2];
				} else if (args.args.length == 1){
					for (let name in CSSData){
						if (name.indexOf(args[0]) == 0) list2.push([name, CSSData[name]]);
					}
					if ('clear'.indexOf(args[0]) == 0)
						return [0, list1.concat(list2)];
					else
						return [0, list2];
				}
			},
			argCount: '*'
		}
	);
	init();
	return manager;
})();

})();

// vim: sw=4 ts=4 sts=0 fdm=marker: