summaryrefslogtreecommitdiff
path: root/common/content/statusline.js
blob: 54943425f6a650e99a916fd708911faba1dc896c (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
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
// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2011 by Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
"use strict";

/** @scope modules */

var StatusLine = Module("statusline", {
    init: function init() {
        this._statusLine = document.getElementById("status-bar");
        this.statusBar = document.getElementById("addon-bar") || this._statusLine;
        this.statusBar.collapsed = true;
        this.baseGroup = this.statusBar == this._statusLine ? "StatusLine " : "";

        if (this.statusBar.localName == "toolbar") {
            styles.system.add("addon-bar", config.styleableChrome, <css><![CDATA[
                #status-bar { margin-top: 0 !important; }
                #addon-bar > statusbar { -moz-box-flex: 1 }
                #addon-bar > #addonbar-closebutton { visibility: collapse; }
                #addon-bar > xul|toolbarspring { visibility: collapse; }
            ]]></css>);

            util.overlayWindow(window, { append: <><statusbar id="status-bar" ordinal="0"/></> });

            highlight.loadCSS(util.compileMacro(<![CDATA[
                !AddonBar;#addon-bar  {
                    padding-left: 0 !important;
                    min-height: 18px !important;
                    -moz-appearance: none !important;
                    <padding>
                }
                !AddonButton;#addon-bar xul|toolbarbutton  {
                    -moz-appearance: none !important;
                    padding: 0 !important;
                    border-width: 0px !important;
                    min-width: 0 !important;
                    color: inherit !important;
                }
                AddonButton:not(:hover)  background: transparent !important;
            ]]>)({ padding: util.OS.isMacOSX ? "padding-right: 10px !important;" : "" }));

            if (document.getElementById("appmenu-button"))
                highlight.loadCSS(<![CDATA[
                    AppmenuButton       min-width: 0 !important; padding: 0 .5em !important;
                ]]>);
        }

        XML.ignoreWhitespace = true;
        let _commandline = "if (window.dactyl) return dactyl.modules.commandline";
        let prepend = <e4x xmlns={XUL} xmlns:dactyl={NS}>
            <button id="appmenu-button" label="" image="chrome://branding/content/icon16.png" highlight="AppmenuButton" />
            <toolbarbutton id="appmenu-toolbar-button" label="" image="chrome://branding/content/icon16.png" />
            <statusbar id="status-bar" highlight="StatusLine">
                <!-- insertbefore="dactyl.statusBefore;" insertafter="dactyl.statusAfter;" -->
                <hbox key="container" hidden="false" align="center"  flex="1">
                    <stack orient="horizontal"       align="stretch" flex="1" highlight="CmdLine StatusCmdLine" class="dactyl-container">
                        <hbox                                                 highlight="CmdLine StatusCmdLine" class="dactyl-container">
                            <label key="mode"          crop="end"                                               class="plain" collapsed="true"/>
                            <stack  id="dactyl-statusline-stack"     flex="1" highlight="CmdLine StatusCmdLine" class="dactyl-container">
                                <textbox key="url"     crop="end"    flex="1"                                   class="plain dactyl-status-field-url" readonly="true"/>
                                <textbox key="message" crop="end"    flex="1" highlight="Normal StatusNormal"   class="plain"                         readonly="true"/>
                            </stack>
                        </hbox>
                    </stack>
                    <label class="plain" key="inputbuffer"    flex="0"/>
                    <label class="plain" key="progress"       flex="0"/>
                    <label class="plain" key="tabcount"       flex="0"/>
                    <label class="plain" key="bufferposition" flex="0"/>
                    <label class="plain" key="zoomlevel"      flex="0"/>
                </hbox>
                <!-- just hide them since other elements expect them -->
                <statusbarpanel id="statusbar-display"       hidden="true"/>
                <statusbarpanel id="statusbar-progresspanel" hidden="true"/>
            </statusbar>
        </e4x>;

        for each (let attr in prepend..@key)
            attr.parent().@id = "dactyl-statusline-field-" + attr;

        util.overlayWindow(window, {
            objects: this.widgets = { get status() this.container },
            prepend: prepend.elements()
        });

        try {
            this.security = content.document.dactylSecurity || "insecure";
        }
        catch (e) {}
    },

    get visible() !this.statusBar.collapsed && !this.statusBar.hidden,

    signals: {
        "browser.locationChange": function (webProgress, request, uri) {
            let win = webProgress.DOMWindow;
            this.status = buffer.uri;
            this.progress = uri && win && win.dactylProgress || "";

            // if this is not delayed we get the position of the old buffer
            this.timeout(function () {
                this.updateBufferPosition();
                this.updateZoomLevel();
            }, 500);
        },
        "browser.overLink": function (link) {
            switch (options["showstatuslinks"]) {
            case "status":
                this.status = link ? _("status.link", link) : buffer.uri;
                break;
            case "command":
                if (link)
                    dactyl.echo(_("status.link", link), commandline.FORCE_SINGLELINE);
                else
                    commandline.clear();
                break;
            }
        },
        "browser.progressChange": function onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) {
            if (webProgress && webProgress.DOMWindow)
                webProgress.DOMWindow.dactylProgress = curTotalProgress / maxTotalProgress;
            this.progress = curTotalProgress / maxTotalProgress;
        },
        "browser.securityChange": function onSecurityChange(webProgress, request, state) {

            if (state & Ci.nsIWebProgressListener.STATE_IS_BROKEN)
                this.security = "broken";
            else if (state & Ci.nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL)
                this.security = "extended";
            else if (state & Ci.nsIWebProgressListener.STATE_SECURE_HIGH)
                this.security = "secure";
            else // if (state & Ci.nsIWebProgressListener.STATE_IS_INSECURE)
                this.security = "insecure";

            if (webProgress && webProgress.DOMWindow)
                webProgress.DOMWindow.document.dactylSecurity = this.security;
        },
        "browser.stateChange": function onStateChange(webProgress, request, flags, status) {
            if (flags & Ci.nsIWebProgressListener.STATE_START)
                this.progress = 0;
            if (flags & Ci.nsIWebProgressListener.STATE_STOP) {
                this.progress = "";
                this.status = buffer.uri;
            }
        },
        "browser.statusChange": function onStatusChange(webProgress, request, status, message) {
            this.status = message || buffer.uri;
        },
    },

    /**
     * Update the status bar to indicate how secure the website is:
     * extended - Secure connection with Extended Validation(EV) certificate.
     * secure -   Secure connection with valid certificate.
     * broken -   Secure connection with invalid certificate, or
     *            mixed content.
     * insecure - Insecure connection.
     *
     * @param {'extended'|'secure'|'broken'|'insecure'} type
     */
    set security(type) {
        this._security = type;
        const highlightGroup = {
            extended: "StatusLineExtended",
            secure:   "StatusLineSecure",
            broken:   "StatusLineBroken",
            insecure: "StatusLineNormal"
        };

        highlight.highlightNode(this.statusBar, this.baseGroup + highlightGroup[type]);
    },
    get security() this._security,

    // update all fields of the statusline
    update: function update() {
        this.status = buffer.uri;
        this.inputBuffer = "";
        this.progress = "";
        this.updateTabCount();
        this.updateBufferPosition();
        this.updateZoomLevel();
    },

    // ripped from Firefox; modified
    unsafeURI: util.regexp(String.replace(<![CDATA[
            [
                \s
                // Invisible characters (bug 452979)
                U001C U001D U001E U001F // file/group/record/unit separator
                U00AD // Soft hyphen
                UFEFF // BOM
                U2060 // Word joiner
                U2062 U2063  // Invisible times/separator
                U200B UFFFC // Zero-width space/no-break space

                // Bidi formatting characters. (RFC 3987 sections 3.2 and 4.1 paragraph 6)
                U200E U200F U202A U202B U202C U202D U202E
            ]
        ]]>, /U/g, "\\u"),
        "gx"),
    losslessDecodeURI: function losslessDecodeURI(url) {
        return url.split("%25").map(function (url) {
                // Non-UTF-8 compliant URLs cause "malformed URI sequence" errors.
                try {
                    return decodeURI(url).replace(this.unsafeURI, encodeURIComponent);
                }
                catch (e) {
                    return url;
                }
            }, this).join("%25");
    },

    /**
     * Update the URL displayed in the status line. Also displays status
     * icons, [+-♥], when there are next and previous pages in the
     * current tab's history, and when the current URL is bookmarked,
     * respectively.
     *
     * @param {string} url The URL to display.
     */
    get status() this._uri,
    set status(uri) {
        let modified = "";
        let url = uri;
        if (isinstance(uri, Ci.nsIURI)) {
            // when session information is available, add [+] when we can go
            // backwards, [-] when we can go forwards
            if (uri.equals(buffer.uri) && window.getWebNavigation) {
                let sh = window.getWebNavigation().sessionHistory;
                if (sh && sh.index > 0)
                    modified += "+";
                if (sh && sh.index < sh.count - 1)
                    modified += "-";
            }

            if (modules.bookmarkcache) {
                if (bookmarkcache.isBookmarked(uri))
                    modified += UTF8("❤");
            }

            if (modules.quickmarks)
                modified += quickmarks.find(uri.spec.replace(/#.*/, "")).join("");

            url = this.losslessDecodeURI(uri.spec);
        }

        if (url == "about:blank") {
            if (!buffer.title)
                url = "[No Name]";
        }
        else {
            url = url.replace(RegExp("^dactyl://help/(\\S+)#(.*)"), function (m, n1, n2) n1 + " " + decodeURIComponent(n2) + " [Help]")
                     .replace(RegExp("^dactyl://help/(\\S+)"), "$1 [Help]");
        }

        if (modified)
            url += " [" + modified + "]";

        this.widgets.url.value = url;
        this._status = uri;

    },

    updateStatus: function updateStatus() { this.status = buffer.uri; },

    updateUrl: deprecated("statusline.status", function updateUrl(url) { this.status = url || buffer.uri }),

    /**
     * Set the contents of the status line's input buffer to the given
     * string. Used primarily when a key press requires further input
     * before being processed, including mapping counts and arguments,
     * along with multi-key mappings.
     *
     * @param {string} buffer
     * @optional
     */
    get inputBuffer() this.widgets.inputbuffer.value,
    set inputBuffer(val) this.widgets.inputbuffer.value = val == null ? "" : val,
    updateInputBuffer: deprecated("statusline.inputBuffer", function updateInputBuffer(val) { this.inputBuffer = val; }),

    /**
     * Update the page load progress bar.
     *
     * @param {string|number} progress The current progress, as follows:
     *    A string          - Displayed literally.
     *    A ratio 0 < n < 1 - Displayed as a progress bar.
     *    A number n <= 0   - Displayed as a "Loading" message.
     *    Any other number  - The progress is cleared.
     */
    progress: Modes.boundProperty({
        get: function progress() this._progress,
        set: function  progress(progress) {
            this._progress = progress || "";

            if (typeof progress == "string")
                this.widgets.progress.value = this._progress;
            else if (typeof progress == "number") {
                let progressStr = "";
                if (this._progress <= 0)
                    progressStr = "[ Loading...         ]";
                else if (this._progress < 1) {
                    let progress = Math.round(this._progress * 20);
                    progressStr = "["
                        + "===================>                    "
                            .substr(20 - progress, 20)
                        + "]";
                }
                this.widgets.progress.value = progressStr;
            }
        }
    }),
    updateProgress: deprecated("statusline.progress", function updateProgress(progress) {
        this.progress = progress;
    }),

    /**
     * Display the correct tabcount (e.g., [1/5]) on the status bar.
     *
     * @param {boolean} delayed When true, update count after a brief timeout.
     *     Useful in the many cases when an event that triggers an update is
     *     broadcast before the tab state is fully updated.
     * @optional
     */
    updateTabCount: function updateTabCount(delayed) {
        if (dactyl.has("tabs")) {
            if (delayed) {
                this.timeout(function () this.updateTabCount(false), 0);
                return;
            }

            this.widgets.tabcount.value = "[" + (tabs.index(null, true) + 1) + "/" + tabs.visibleTabs.length + "]";
        }
    },

    /**
     * Display the main content's vertical scroll position in the status
     * bar.
     *
     * @param {number} percent The position, as a percentage.
     * @optional
     */
    updateBufferPosition: function updateBufferPosition(percent) {
        if (percent == null) {
            let win = document.commandDispatcher.focusedWindow;
            if (!win)
                return;
            win.scrollY; // intentional - see Kris
            percent = win.scrollY    == 0 ?  0 : // This prevents a forced rendering
                      win.scrollMaxY == 0 ? -1 : win.scrollY / win.scrollMaxY;
        }

        percent = Math.round(percent * 100);

        if (percent < 0)
            var position = "All";
        else if (percent == 0)
            position = "Top";
        else if (percent >= 100)
            position = "Bot";
        else if (percent < 10)
            position = " " + percent + "%";
        else
            position = percent + "%";

        this.widgets.bufferposition.value = position;
    },

    /**
     * Display the main content's zoom level.
     *
     * @param {number} percent The zoom level, as a percentage. @optional
     * @param {boolean} full True if full zoom is in operation. @optional
     */
    updateZoomLevel: function updateZoomLevel(percent, full) {
        if (arguments.length == 0)
            [percent, full] = [buffer.zoomLevel, buffer.fullZoom];

        if (percent == 100)
            this.widgets.zoomlevel.value = "";
        else {
            percent = ("  " + Math.round(percent)).substr(-3);
            if (full)
                this.widgets.zoomlevel.value = " [" + percent + "%]";
            else
                this.widgets.zoomlevel.value = " (" + percent + "%)";
        }
    }
});

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