]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/template.jsm
8a398c2e148c1fab6e153a2a2eaf0320c316443b
[dactyl.git] / common / modules / template.jsm
1 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k at Gmail>
2 //
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
5 "use strict";
6
7 Components.utils.import("resource://dactyl/bootstrap.jsm");
8 defineModule("template", {
9     exports: ["Binding", "Template", "template"],
10     require: ["util"],
11     use: ["messages", "services"]
12 }, this);
13
14 default xml namespace = XHTML;
15
16 var Binding = Class("Binding", {
17     init: function (node, nodes) {
18         this.node = node;
19         this.nodes = nodes;
20         node.dactylBinding = this;
21
22         Object.defineProperties(node, this.constructor.properties);
23
24         for (let [event, handler] in values(this.constructor.events))
25             node.addEventListener(event, handler, false);
26     },
27
28     set collapsed(collapsed) {
29         if (collapsed)
30             this.setAttribute("collapsed", "true");
31         else
32             this.removeAttribute("collapsed");
33     },
34     get collapsed() !!this.getAttribute("collapsed"),
35
36     __noSuchMethod__: Class.Property({
37         configurable: true,
38         writeable: true,
39         value: function __noSuchMethod__(meth, args) {
40             return this.node[meth].apply(this.node, args);
41         }
42     })
43 }, {
44     get bindings() {
45         let bindingProto = Object.getPrototypeOf(Binding.prototype);
46         for (let obj = this.prototype; obj !== bindingProto; obj = Object.getPrototypeOf(obj))
47             yield obj;
48     },
49
50     bind: function bind(func) function bound() {
51         try {
52             return func.apply(this.dactylBinding, arguments);
53         }
54         catch (e) {
55             util.reportError(e);
56             throw e;
57         }
58     },
59
60     events: Class.memoize(function () {
61         let res = [];
62         for (let obj in this.bindings)
63             if (Object.getOwnPropertyDescriptor(obj, "events"))
64                 for (let [event, handler] in Iterator(obj.events))
65                     res.push([event, this.bind(handler)]);
66         return res;
67     }),
68
69     properties: Class.memoize(function () {
70         let res = {};
71         for (let obj in this.bindings)
72             for (let prop in properties(obj)) {
73                 let desc = Object.getOwnPropertyDescriptor(obj, prop);
74                 if (desc.enumerable) {
75                     for (let k in values(["get", "set", "value"]))
76                         if (typeof desc[k] === "function")
77                             desc[k] = this.bind(desc[k]);
78                     res[prop] = desc;
79                 }
80             }
81         return res;
82     })
83 });
84
85 var Template = Module("Template", {
86     add: function add(a, b) a + b,
87     join: function join(c) function (a, b) a + c + b,
88
89     map: function map(iter, func, sep, interruptable) {
90         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
91         if (iter.length) // FIXME: Kludge?
92             iter = array.iterValues(iter);
93         let res = <></>;
94         let n = 0;
95         for each (let i in Iterator(iter)) {
96             let val = func(i, n);
97             if (val == undefined)
98                 continue;
99             if (n++ && sep)
100                 res += sep;
101             if (interruptable && n % interruptable == 0)
102                 util.threadYield(true, true);
103             res += val;
104         }
105         return res;
106     },
107
108     bindings: {
109         Button: Class("Button", Binding, {
110             init: function init(node, params) {
111                 init.supercall(this, node);
112
113                 this.target = params.commandTarget;
114             },
115
116             get command() this.getAttribute("command") || this.getAttribute("key"),
117
118             events: {
119                 "click": function onClick(event) {
120                     event.preventDefault();
121                     if (this.commandAllowed) {
122                         if (set.has(this.target.commands || {}, this.command))
123                             this.target.commands[this.command].call(this.target);
124                         else
125                             this.target.command(this.command);
126                     }
127                 }
128             },
129
130             get commandAllowed() {
131                 if (set.has(this.target.allowedCommands || {}, this.command))
132                     return this.target.allowedCommands[this.command];
133                 if ("commandAllowed" in this.target)
134                     return this.target.commandAllowed(this.command);
135                 return true;
136             },
137
138             update: function update() {
139                 let collapsed = this.collapsed;
140                 this.collapsed = !this.commandAllowed;
141
142                 if (collapsed == this.commandAllowed) {
143                     let event = this.node.ownerDocument.createEvent("Events");
144                     event.initEvent("dactyl-commandupdate", true, false);
145                     this.node.ownerDocument.dispatchEvent(event);
146                 }
147             }
148         }),
149
150         Events: Class("Events", Binding, {
151             init: function init(node, params) {
152                 init.supercall(this, node);
153
154                 let obj = params.eventTarget;
155                 let events = obj[this.getAttribute("events") || "events"];
156
157                 for (let [event, handler] in Iterator(events))
158                     node.addEventListener(event, obj.closure(handler), false);
159             }
160         })
161     },
162
163     bookmarkDescription: function (item, text)
164     <>
165         {
166             !(item.extra && item.extra.length) ? "" :
167             <span highlight="URLExtra">
168                 ({
169                     template.map(item.extra, function (e)
170                     <>{e[0]}: <span highlight={e[2]}>{e[1]}</span></>,
171                     <>&#xa0;</>)
172                 })&#xa0;</span>
173         }
174         <a xmlns:dactyl={NS} identifier={item.id || ""} dactyl:command={item.command || ""}
175            href={item.item.url} highlight="URL">{text || ""}</a>
176     </>,
177
178     filter: function (str) <span highlight="Filter">{str}</span>,
179
180     completionRow: function completionRow(item, highlightGroup) {
181         if (typeof icon == "function")
182             icon = icon();
183
184         if (highlightGroup) {
185             var text = item[0] || "";
186             var desc = item[1] || "";
187         }
188         else {
189             var text = this.processor[0].call(this, item, item.result);
190             var desc = this.processor[1].call(this, item, item.description);
191         }
192
193         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
194         // <e4x>
195         return <div highlight={highlightGroup || "CompItem"} style="white-space: nowrap">
196                    <!-- The non-breaking spaces prevent empty elements
197                       - from pushing the baseline down and enlarging
198                       - the row.
199                       -->
200                    <li highlight="CompResult">{text}&#xa0;</li>
201                    <li highlight="CompDesc">{desc}&#xa0;</li>
202                </div>;
203         // </e4x>
204     },
205
206     helpLink: function (token, text, type) {
207         if (!services["dactyl:"].initialized)
208             util.dactyl.initHelp();
209
210         let topic = token; // FIXME: Evil duplication!
211         if (/^\[.*\]$/.test(topic))
212             topic = topic.slice(1, -1);
213         else if (/^n_/.test(topic))
214             topic = topic.slice(2);
215
216         if (services["dactyl:"].initialized && !set.has(services["dactyl:"].HELP_TAGS, topic))
217             return <span highlight={type || ""}>{text || token}</span>;
218
219         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
220         type = type || (/^'.*'$/.test(token)   ? "HelpOpt" :
221                         /^\[.*\]$|^E\d{3}$/.test(token) ? "HelpTopic" :
222                         /^:\w/.test(token)     ? "HelpEx"  : "HelpKey");
223
224         return <a highlight={"InlineHelpLink " + type} tag={topic} href={"dactyl://help-tag/" + topic} dactyl:command="dactyl.help" xmlns:dactyl={NS}>{text || topic}</a>;
225     },
226     HelpLink: function (token) {
227         if (!services["dactyl:"].initialized)
228             util.dactyl.initHelp();
229
230         let topic = token; // FIXME: Evil duplication!
231         if (/^\[.*\]$/.test(topic))
232             topic = topic.slice(1, -1);
233         else if (/^n_/.test(topic))
234             topic = topic.slice(2);
235
236         if (services["dactyl:"].initialized && !set.has(services["dactyl:"].HELP_TAGS, topic))
237             return <>{token}</>;
238
239         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
240         let tag = (/^'.*'$/.test(token)            ? "o" :
241                    /^\[.*\]$|^E\d{3}$/.test(token) ? "t" :
242                    /^:\w/.test(token)              ? "ex"  : "k");
243
244         topic = topic.replace(/^'(.*)'$/, "$1");
245         return <{tag} xmlns={NS}>{topic}</{tag}>;
246     },
247     linkifyHelp: function linkifyHelp(str, help) {
248         let re = util.regexp(<![CDATA[
249             (?P<pre> [/\s]|^)
250             (?P<tag> '[\w-]+' | :(?:[\w-]+!?|!) | (?:._)?<[\w-]+>\w* | [a-zA-Z]_\w+ | \[[\w-]+\] | E\d{3} )
251             (?=      [[\)!,:;./\s]|$)
252         ]]>, "gx");
253         return this.highlightSubstrings(str, (function () {
254             for (let res in re.iterate(str))
255                 yield [res.index + res.pre.length, res.tag.length];
256         })(), template[help ? "HelpLink" : "helpLink"]);
257     },
258
259     // if "processStrings" is true, any passed strings will be surrounded by " and
260     // any line breaks are displayed as \n
261     highlight: function highlight(arg, processStrings, clip) {
262         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
263         // some objects like window.JSON or getBrowsers()._browsers need the try/catch
264         try {
265             let str = clip ? util.clip(String(arg), clip) : String(arg);
266             switch (arg == null ? "undefined" : typeof arg) {
267             case "number":
268                 return <span highlight="Number">{str}</span>;
269             case "string":
270                 if (processStrings)
271                     str = str.quote();
272                 return <span highlight="String">{str}</span>;
273             case "boolean":
274                 return <span highlight="Boolean">{str}</span>;
275             case "function":
276                 // Vim generally doesn't like /foo*/, because */ looks like a comment terminator.
277                 // Using /foo*(:?)/ instead.
278                 if (processStrings)
279                     return <span highlight="Function">{str.replace(/\{(.|\n)*(?:)/g, "{ ... }")}</span>;
280                     <>}</>; /* Vim */
281                 return <>{arg}</>;
282             case "undefined":
283                 return <span highlight="Null">{arg}</span>;
284             case "object":
285                 if (arg instanceof Ci.nsIDOMElement)
286                     return util.objectToString(arg, false);
287                 // for java packages value.toString() would crash so badly
288                 // that we cannot even try/catch it
289                 if (/^\[JavaPackage.*\]$/.test(arg))
290                     return <>[JavaPackage]</>;
291                 if (processStrings && false)
292                     str = template.highlightFilter(str, "\n", function () <span highlight="NonText">^J</span>);
293                 return <span highlight="Object">{str}</span>;
294             case "xml":
295                 return arg;
296             default:
297                 return <![CDATA[<unknown type>]]>;
298             }
299         }
300         catch (e) {
301             return <![CDATA[<unknown>]]>;
302         }
303     },
304
305     highlightFilter: function highlightFilter(str, filter, highlight) {
306         return this.highlightSubstrings(str, (function () {
307             if (filter.length == 0)
308                 return;
309             let lcstr = String.toLowerCase(str);
310             let lcfilter = filter.toLowerCase();
311             let start = 0;
312             while ((start = lcstr.indexOf(lcfilter, start)) > -1) {
313                 yield [start, filter.length];
314                 start += filter.length;
315             }
316         })(), highlight || template.filter);
317     },
318
319     highlightRegexp: function highlightRegexp(str, re, highlight) {
320         return this.highlightSubstrings(str, (function () {
321             for (let res in util.regexp.iterate(re, str))
322                 yield [res.index, res[0].length, res.wholeMatch ? [res] : res];
323         })(), highlight || template.filter);
324     },
325
326     highlightSubstrings: function highlightSubstrings(str, iter, highlight) {
327         XML.ignoreWhitespace = XML.prettyPrinting = false;
328         if (typeof str == "xml")
329             return str;
330         if (str == "")
331             return <>{str}</>;
332
333         str = String(str).replace(" ", "\u00a0");
334         let s = <></>;
335         let start = 0;
336         let n = 0, _i;
337         for (let [i, length, args] in iter) {
338             if (i == _i || i < _i)
339                 break;
340             _i = i;
341
342             XML.ignoreWhitespace = false;
343             s += <>{str.substring(start, i)}</>;
344             s += highlight.apply(this, Array.concat(args || str.substr(i, length)));
345             start = i + length;
346         }
347         return s + <>{str.substr(start)}</>;
348     },
349
350     highlightURL: function highlightURL(str, force) {
351         if (force || /^[a-zA-Z]+:\/\//.test(str))
352             return <a highlight="URL" href={str}>{str}</a>;
353         else
354             return str;
355     },
356
357     icon: function (item, text) <>
358         <span highlight="CompIcon">{item.icon ? <img src={item.icon}/> : <></>}</span><span class="td-strut"/>{text}
359     </>,
360
361     jumps: function jumps(index, elems) {
362         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
363         // <e4x>
364         return <table>
365                 <tr style="text-align: left;" highlight="Title">
366                     <th colspan="2">jump</th><th>title</th><th>URI</th>
367                 </tr>
368                 {
369                     this.map(Iterator(elems), function ([idx, val])
370                     <tr>
371                         <td class="indicator">{idx == index ? ">" : ""}</td>
372                         <td>{Math.abs(idx - index)}</td>
373                         <td style="width: 250px; max-width: 500px; overflow: hidden;">{val.title}</td>
374                         <td><a href={val.URI.spec} highlight="URL jump-list">{val.URI.spec}</a></td>
375                     </tr>)
376                 }
377             </table>;
378         // </e4x>
379     },
380
381     options: function options(title, opts, verbose) {
382         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
383         // <e4x>
384         return <table>
385                 <tr highlight="Title" align="left">
386                     <th>--- {title} ---</th>
387                 </tr>
388                 {
389                     this.map(opts, function (opt)
390                     <tr>
391                         <td>
392                             <div highlight="Message"
393                             ><span style={opt.isDefault ? "" : "font-weight: bold"}>{opt.pre}{opt.name}</span><span>{opt.value}</span>{
394                                 opt.isDefault || opt.default == null ? "" : <span class="extra-info"> (default: {opt.default})</span>
395                             }</div>{
396                                 verbose && opt.setFrom ? <div highlight="Message">       Last set from {template.sourceLink(opt.setFrom)}</div> : <></>
397                             }
398                         </td>
399                     </tr>)
400                 }
401             </table>;
402         // </e4x>
403     },
404
405     sourceLink: function (frame) {
406         let url = util.fixURI(frame.filename || "unknown");
407         let path = util.urlPath(url);
408
409         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
410         return <a xmlns:dactyl={NS} dactyl:command="buffer.viewSource"
411             href={url} path={path} line={frame.lineNumber}
412             highlight="URL">{
413             path + ":" + frame.lineNumber
414         }</a>;
415     },
416
417     table: function table(title, data, indent) {
418         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
419         let table = // <e4x>
420             <table>
421                 <tr highlight="Title" align="left">
422                     <th colspan="2">{title}</th>
423                 </tr>
424                 {
425                     this.map(data, function (datum)
426                     <tr>
427                        <td style={"font-weight: bold; min-width: 150px; padding-left: " + (indent || "2ex")}>{datum[0]}</td>
428                        <td>{datum[1]}</td>
429                     </tr>)
430                 }
431             </table>;
432         // </e4x>
433         if (table.tr.length() > 1)
434             return table;
435     },
436
437     tabular: function tabular(headings, style, iter) {
438         // TODO: This might be mind-bogglingly slow. We'll see.
439         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
440         // <e4x>
441         return <table>
442                 <tr highlight="Title" align="left">
443                 {
444                     this.map(headings, function (h)
445                     <th>{h}</th>)
446                 }
447                 </tr>
448                 {
449                     this.map(iter, function (row)
450                     <tr>
451                     {
452                         template.map(Iterator(row), function ([i, d])
453                         <td style={style[i] || ""}>{d}</td>)
454                     }
455                     </tr>)
456                 }
457             </table>;
458         // </e4x>
459     },
460
461     usage: function usage(iter, format) {
462         XML.ignoreWhitespace = false; XML.prettyPrinting = false;
463         format = format || {};
464         let desc = format.description || function (item) template.linkifyHelp(item.description);
465         let help = format.help || function (item) item.name;
466         function sourceLink(frame) {
467             let source = template.sourceLink(frame);
468             source.@NS::hint = source.text();
469             return source;
470         }
471         // <e4x>
472         return <table>
473             { format.headings ?
474                 <thead highlight="UsageHead">
475                     <tr highlight="Title" align="left">
476                     {
477                         this.map(format.headings, function (h) <th>{h}</th>)
478                     }
479                     </tr>
480                 </thead> : ""
481             }
482             { format.columns ?
483                 <colgroup>
484                 {
485                     this.map(format.columns, function (c) <col style={c}/>)
486                 }
487                 </colgroup> : ""
488             }
489             <tbody highlight="UsageBody">{
490                 this.map(iter, function (item)
491                 <tr highlight="UsageItem">
492                     <td style="padding-right: 2em;">
493                         <span highlight="Usage Link">{
494                             let (name = item.name || item.names[0], frame = item.definedAt)
495                                 !frame ? name :
496                                     template.helpLink(help(item), name, "Title") +
497                                     <span highlight="LinkInfo" xmlns:dactyl={NS}>Defined at {sourceLink(frame)}</span>
498                         }</span>
499                     </td>
500                     { item.columns ? template.map(item.columns, function (c) <td>{c}</td>) : "" }
501                     <td>{desc(item)}</td>
502                 </tr>)
503             }</tbody>
504         </table>;
505         // </e4x>
506     }
507 });
508
509 endModule();
510
511 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: