]> git.donarmstrong.com Git - dactyl.git/blob - common/content/statusline.js
4cf50c47813e4a8b119dcfa837eabe5cc4c82941
[dactyl.git] / common / content / statusline.js
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2012 Kris Maglione <maglione.k@gmail.com>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 "use strict";
8
9 /** @scope modules */
10
11 var StatusLine = Module("statusline", {
12     init: function init() {
13         this._statusLine = document.getElementById("status-bar");
14         this.statusBar = document.getElementById("addon-bar") || this._statusLine;
15         this.baseGroup = this.statusBar == this._statusLine ? "StatusLine " : "";
16
17         if (this.statusBar.localName == "toolbar") {
18             styles.system.add("addon-bar", config.styleableChrome, literal(/*
19                 #status-bar { margin-top: 0 !important; }
20                 #addon-bar > statusbar { -moz-box-flex: 1 }
21                 #addon-bar > #addonbar-closebutton { visibility: collapse; }
22                 #addon-bar > xul|toolbarspring { visibility: collapse; }
23             */));
24
25             overlay.overlayWindow(window, {
26                 append: [
27                     ["statusbar", { id: "status-bar", ordinal: "0" }]]
28             });
29
30             highlight.loadCSS(util.compileMacro(literal(/*
31                 !AddonBar;#addon-bar {
32                     padding-left: 0 !important;
33                     min-height: 18px !important;
34                     -moz-appearance: none !important;
35                     <padding>
36                 }
37                 !AddonButton;#addon-bar xul|toolbarbutton {
38                     -moz-appearance: none !important;
39                     padding: 0 !important;
40                     border-width: 0px !important;
41                     min-width: 0 !important;
42                     color: inherit !important;
43                 }
44                 AddonButton:not(:hover)  background: transparent;
45             */))({ padding: config.OS.isMacOSX ? "padding-right: 10px !important;" : "" }));
46
47             if (document.getElementById("appmenu-button"))
48                 highlight.loadCSS(literal(/*
49                     AppmenuButton       min-width: 0 !important; padding: 0 .5em !important;
50                 */));
51         }
52
53         let _commandline = "if (window.dactyl) return dactyl.modules.commandline";
54         let prepend = [
55             ["button", { id: "appmenu-button", label: "", image: "chrome://branding/content/icon16.png", highlight: "AppmenuButton", xmlns: "xul" }],
56             ["toolbarbutton", { id: "appmenu-toolbar-button", label: "", image: "chrome://branding/content/icon16.png" }],
57             ["statusbar", { id: "status-bar", highlight: "StatusLine", xmlns: "xul" },
58                 // <!-- insertbefore="dactyl.statusBefore;" insertafter="dactyl.statusAfter;" -->
59                 ["hbox", { key: "container", hidden: "false", align: "center",  flex: "1" },
60                     ["stack", { orient: "horizontal",       align: "stretch", flex: "1", highlight: "CmdLine StatusCmdLine", class: "dactyl-container" },
61                         ["hbox", {                                                       highlight: "CmdLine StatusCmdLine", class: "dactyl-container" },
62                             ["label", { key: "mode",          crop: "end",                                                   class: "plain", collapsed: "true" }],
63                             ["stack", {  id: "dactyl-statusline-stack",       flex: "1", highlight: "CmdLine StatusCmdLine", class: "dactyl-container" },
64                                 ["textbox", { key: "url",     crop: "end",    flex: "1", style: "background: transparent;",  class: "plain dactyl-status-field-url",
65                                               readonly: "true" }],
66                                 ["hbox", { key: "message-box" },
67                                     ["label", { key: "message-pre", highlight: "WarningMsg StatusWarningMsg", class: "plain", readonly: "true" }],
68                                     ["textbox", { key: "message", crop: "end",    flex: "1", highlight: "Normal StatusNormal",   class: "plain",
69                                                   readonly: "true" }]]]]],
70                     ["label", { class: "plain", key: "inputbuffer",    flex: "0" }],
71                     ["label", { class: "plain", key: "progress",       flex: "0" }],
72                     ["label", { class: "plain", key: "tabcount",       flex: "0" }],
73                     ["label", { class: "plain", key: "bufferposition", flex: "0" }],
74                     ["label", { class: "plain", key: "zoomlevel",      flex: "0" }]],
75                 // just hide them since other elements expect them
76                 ["statusbarpanel", { id: "statusbar-display",       hidden: "true" }],
77                 ["statusbarpanel", { id: "statusbar-progresspanel", hidden: "true" }]]];
78
79         (function rec(ary) {
80             ary.forEach(function (elem) {
81                 if ("key" in elem[1])
82                     elem[1].id = "dactyl-statusline-field-" + elem[1].key;
83                 if (elem.length > 2)
84                     rec(elem.slice(2));
85             });
86         })(prepend);
87
88         overlay.overlayWindow(window, {
89             objects: this.widgets = { get status() this.container },
90             prepend: prepend
91         });
92
93         try {
94             this.security = content.document.dactylSecurity || "insecure";
95         }
96         catch (e) {}
97     },
98
99     get visible() !this.statusBar.collapsed && !this.statusBar.hidden,
100
101     signals: {
102         "browser.locationChange": function (webProgress, request, uri) {
103             let win = webProgress.DOMWindow;
104             this.status = uri;
105             this.progress = uri && win && win.dactylProgress || "";
106
107             // if this is not delayed we get the position of the old buffer
108             this.timeout(function () {
109                 this.updateBufferPosition();
110                 this.updateZoomLevel();
111             }, 500);
112         },
113         "browser.overLink": function (link) {
114             switch (options["showstatuslinks"]) {
115             case "status":
116                 this.overLink = link ? _("status.link", link) : null;
117                 this.status = link ? _("status.link", link) : buffer.uri;
118                 break;
119             case "command":
120                 this.overLink = null;
121                 if (link)
122                     dactyl.echo(_("status.link", link), commandline.FORCE_SINGLELINE);
123                 else
124                     commandline.clear();
125                 break;
126             }
127         },
128         "browser.progressChange": function onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) {
129             if (webProgress && webProgress.DOMWindow)
130                 webProgress.DOMWindow.dactylProgress = curTotalProgress / maxTotalProgress;
131             this.progress = curTotalProgress / maxTotalProgress;
132         },
133         "browser.securityChange": function onSecurityChange(webProgress, request, state) {
134
135             if (state & Ci.nsIWebProgressListener.STATE_IS_BROKEN)
136                 this.security = "broken";
137             else if (state & Ci.nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL)
138                 this.security = "extended";
139             else if (state & Ci.nsIWebProgressListener.STATE_SECURE_HIGH)
140                 this.security = "secure";
141             else // if (state & Ci.nsIWebProgressListener.STATE_IS_INSECURE)
142                 this.security = "insecure";
143
144             if (webProgress && webProgress.DOMWindow)
145                 webProgress.DOMWindow.document.dactylSecurity = this.security;
146         },
147         "browser.stateChange": function onStateChange(webProgress, request, flags, status) {
148             const L = Ci.nsIWebProgressListener;
149
150             if (flags & (L.STATE_IS_DOCUMENT | L.STATE_IS_WINDOW))
151                 if (flags & L.STATE_START)
152                     this.progress = 0;
153                 else if (flags & L.STATE_STOP)
154                     this.progress = "";
155
156             if (flags & L.STATE_STOP)
157                 this.updateStatus();
158         },
159         "browser.statusChange": function onStatusChange(webProgress, request, status, message) {
160             this.timeout(function () {
161                 this.status = message || buffer.uri;
162             });
163         },
164         "fullscreen": function onFullscreen(fullscreen) {
165             let go = options.get("guioptions");
166             if (fullscreen) {
167                 this.wasVisible = go.has("s");
168                 go.op("-", "s");
169             }
170             else if (this.wasVisible) {
171                 go.op("+", "s");
172             }
173         }
174     },
175
176     /**
177      * Update the status bar to indicate how secure the website is:
178      * extended - Secure connection with Extended Validation(EV) certificate.
179      * secure -   Secure connection with valid certificate.
180      * broken -   Secure connection with invalid certificate, or
181      *            mixed content.
182      * insecure - Insecure connection.
183      *
184      * @param {'extended'|'secure'|'broken'|'insecure'} type
185      */
186     set security(type) {
187         this._security = type;
188         const highlightGroup = {
189             extended: "StatusLineExtended",
190             secure:   "StatusLineSecure",
191             broken:   "StatusLineBroken",
192             insecure: "StatusLineNormal"
193         };
194
195         highlight.highlightNode(this.statusBar, this.baseGroup + highlightGroup[type]);
196     },
197     get security() this._security,
198
199     // update all fields of the statusline
200     update: function update() {
201         this.updateStatus();
202         this.inputBuffer = "";
203         this.progress = "";
204         this.updateTabCount();
205         this.updateBufferPosition();
206         this.updateZoomLevel();
207     },
208
209     unsafeURI: deprecated("util.unsafeURI", { get: function unsafeURI() util.unsafeURI }),
210     losslessDecodeURI: deprecated("util.losslessDecodeURI", function losslessDecodeURI() util.losslessDecodeURI.apply(util, arguments)),
211
212     /**
213      * Update the URL displayed in the status line. Also displays status
214      * icons, [+-♥], when there are next and previous pages in the
215      * current tab's history, and when the current URL is bookmarked,
216      * respectively.
217      *
218      * @param {string} url The URL to display.
219      */
220     get status() this._uri,
221     set status(uri) {
222         let modified = "";
223         let url = uri;
224         if (isinstance(uri, Ci.nsIURI)) {
225             // when session information is available, add [+] when we can go
226             // backwards, [-] when we can go forwards
227             if (uri.equals(buffer.uri) && window.getWebNavigation) {
228                 let sh = window.getWebNavigation().sessionHistory;
229                 if (sh && sh.index > 0)
230                     modified += "-";
231                 if (sh && sh.index < sh.count - 1)
232                     modified += "+";
233                 if (this.bookmarked)
234                     modified += UTF8("❤");
235             }
236
237             if (modules.quickmarks)
238                 modified += quickmarks.find(uri.spec.replace(/#.*/, "")).join("");
239
240             url = util.losslessDecodeURI(uri.spec);
241         }
242
243         if (url == "about:blank") {
244             if (!buffer.title)
245                 url = _("buffer.noName");
246         }
247         else {
248             url = url.replace(RegExp("^dactyl://help/(\\S+)#(.*)"), function (m, n1, n2) n1 + " " + decodeURIComponent(n2) + " " + _("buffer.help"))
249                      .replace(RegExp("^dactyl://help/(\\S+)"), "$1 " + _("buffer.help"));
250         }
251
252         if (modified)
253             url += " [" + modified + "]";
254
255         this.widgets.url.value = url;
256         this._status = uri;
257     },
258
259     get bookmarked() this._bookmarked,
260     set bookmarked(val) {
261         this._bookmarked = val;
262         if (this.status)
263             this.status = this.status;
264     },
265
266     updateStatus: function updateStatus() {
267         this.timeout(function () {
268             this.status = this.overLink || buffer.uri;
269         });
270     },
271
272     updateUrl: deprecated("statusline.status", function updateUrl(url) { this.status = url || buffer.uri; }),
273
274     /**
275      * Set the contents of the status line's input buffer to the given
276      * string. Used primarily when a key press requires further input
277      * before being processed, including mapping counts and arguments,
278      * along with multi-key mappings.
279      *
280      * @param {string} buffer
281      * @optional
282      */
283     get inputBuffer() this.widgets.inputbuffer.value,
284     set inputBuffer(val) this.widgets.inputbuffer.value = val == null ? "" : val,
285     updateInputBuffer: deprecated("statusline.inputBuffer", function updateInputBuffer(val) { this.inputBuffer = val; }),
286
287     /**
288      * Update the page load progress bar.
289      *
290      * @param {string|number} progress The current progress, as follows:
291      *    A string          - Displayed literally.
292      *    A ratio 0 < n < 1 - Displayed as a progress bar.
293      *    A number n <= 0   - Displayed as a "Loading" message.
294      *    Any other number  - The progress is cleared.
295      */
296     progress: Modes.boundProperty({
297         get: function progress() this._progress,
298         set: function progress(progress) {
299             this._progress = progress || "";
300
301             if (isinstance(progress, ["String", _]))
302                 this.widgets.progress.value = this._progress;
303             else if (typeof progress == "number") {
304                 let progressStr = "";
305                 if (this._progress <= 0)
306                     progressStr = /*L*/"[ Loading...         ]";
307                 else if (this._progress < 1) {
308                     let progress = Math.round(this._progress * 20);
309                     progressStr = "["
310                         + "===================>                    "
311                             .substr(20 - progress, 20)
312                         + "]";
313                 }
314                 this.widgets.progress.value = progressStr;
315             }
316         }
317     }),
318     updateProgress: deprecated("statusline.progress", function updateProgress(progress) {
319         this.progress = progress;
320     }),
321
322     /**
323      * Display the correct tabcount (e.g., [1/5]) on the status bar.
324      *
325      * @param {boolean} delayed When true, update count after a brief timeout.
326      *     Useful in the many cases when an event that triggers an update is
327      *     broadcast before the tab state is fully updated.
328      * @optional
329      */
330     updateTabCount: function updateTabCount(delayed) {
331         if (dactyl.has("tabs")) {
332             if (delayed) {
333                 this.timeout(function () this.updateTabCount(false), 0);
334                 return;
335             }
336
337             this.widgets.tabcount.value = "[" + (tabs.index(null, true) + 1) + "/" + tabs.visibleTabs.length + "]";
338         }
339     },
340
341     /**
342      * Display the main content's vertical scroll position in the status
343      * bar.
344      *
345      * @param {number} percent The position, as a percentage.
346      * @optional
347      */
348     updateBufferPosition: function updateBufferPosition(percent) {
349         if (percent == null) {
350             let win = document.commandDispatcher.focusedWindow;
351             if (!win)
352                 return;
353             win.scrollY; // intentional - see Kris
354             percent = win.scrollY    == 0 ?  0 : // This prevents a forced rendering
355                       win.scrollMaxY == 0 ? -1 : win.scrollY / win.scrollMaxY;
356         }
357
358         percent = Math.round(percent * 100);
359
360         if (percent < 0)
361             var position = "All";
362         else if (percent == 0)
363             position = "Top";
364         else if (percent >= 100)
365             position = "Bot";
366         else if (percent < 10)
367             position = " " + percent + "%";
368         else
369             position = percent + "%";
370
371         this.widgets.bufferposition.value = position;
372     },
373
374     /**
375      * Display the main content's zoom level.
376      *
377      * @param {number} percent The zoom level, as a percentage. @optional
378      * @param {boolean} full True if full zoom is in operation. @optional
379      */
380     updateZoomLevel: function updateZoomLevel(percent, full) {
381         if (arguments.length == 0)
382             [percent, full] = [buffer.zoomLevel, buffer.fullZoom];
383
384         if (percent == 100)
385             this.widgets.zoomlevel.value = "";
386         else {
387             percent = ("  " + Math.round(percent)).substr(-3);
388             if (full)
389                 this.widgets.zoomlevel.value = " [" + percent + "%]";
390             else
391                 this.widgets.zoomlevel.value = " (" + percent + "%)";
392         }
393     }
394 });
395
396 // vim: set fdm=marker sw=4 sts=4 ts=8 et: