<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

Components.utils.import("chrome://htitle/content/HTitleTools.jsm");

var HTitle = {
    ENABLED: true,

    windowControlsObservers: [],

    window: null,

    currentMode: "auto",
    previousState: 0,
    previousChangeTime: 0,

    init: function() {
        HTitleTools.prefs.addObserver("", HTitle, false);

        if (HTitleTools.prefs.getBoolPref("check_gnome_shell") && HTitleTools.checkPresenceGnomeShell() != 0) {
            // Nothing doing if WM is not GNOME Shell.
            HTitle.ENABLED = false;
            return;
        }

        HTitle.window = document.getElementById(HTitleTools.isThunderbird() ? "messengerWindow" : "main-window");

        HTitle.start();

        /* Upgrade from previous (< 2.5) versions */
        if (HTitleTools.prefs.getPrefType("show_close_button") && HTitleTools.prefs.getBoolPref("show_close_button")) {
            HTitleTools.prefs.setBoolPref("show_close_button", false);
            HTitleTools.prefs.setBoolPref("show_window_controls", true);
        }

        if (HTitleTools.prefs.getBoolPref("window_controls.get_layout_by_gsettings"))
            HTitle.setWindowControlsLayoutAttribute();

        if (HTitleTools.prefs.getBoolPref("show_window_controls"))
            HTitle.showWindowControls();
    },

    setWindowControlsLayoutAttribute: function() {
        var windowctls = document.getElementById("window-controls");
        if (windowctls) {
            windowctls.setAttribute("htitle-button-layout", HTitleTools.windowControlsLayout);
        }
    },

    showWindowControls: function() {
        var windowctls = document.getElementById("window-controls");
        windowctls.setAttribute("htitle", "true");

        // Appling CSS
        if (HTitle.currentMode == "always")
            HTitleTools.loadStyle("windowControlsAlways");
        else
            HTitleTools.loadStyle("windowControlsAuto");

        if (HTitleTools.isFirefox()) {
            window.addEventListener("sizemodechange", HTitle.updateWindowControlsPosition);

            var targets_map = [
                    ["TabsToolbar", "tabsontop"],
                    ["toolbar-menubar", "autohide"]
                ];
            if (HTitleTools.isAustralisUI()) {
                targets_map.push(["nav-bar", "default-tabs-position"]);
            }
            else {
                targets_map.push(["nav-bar", "collapsed"]);
            }
        }
        else {
            var targets_map = [
                    ["mail-toolbar-menubar2", "autohide"]
                ];
        }

        for (var i = 0; i < targets_map.length; i++) {
            var tempObserver = new MutationObserver(function(mutations) {
                mutations.forEach(HTitle.updateWindowControlsPosition);
            });
            tempObserver.observe(document.getElementById(targets_map[i][0]), { attributes: true, attributeFilter: [targets_map[i][1]] });
            HTitle.windowControlsObservers.push(tempObserver);
        }
        HTitleTools.log("HTitle.windowControlsObservers = " + HTitle.windowControlsObservers.length, "DEBUG");

        HTitle.updateWindowControlsPosition();
    },

    hideWindowControls: function() {
        if (HTitle.currentMode == "always")
            HTitleTools.unloadStyle("windowControlsAlways");
        else
            HTitleTools.unloadStyle("windowControlsAuto");

        var spring = document.getElementById("htitle-menubar-spring");
        if (spring)
            spring.remove();

        var windowctls = document.getElementById("window-controls");
        windowctls.removeAttribute("htitle");
        //windowctls.setAttribute("flex", "1");

        if (HTitleTools.isFirefox()) {
            window.removeEventListener("sizemodechange", HTitle.updateWindowControlsPosition);

            var navbar = document.getElementById("nav-bar");
            HTitleTools.moveWindowControlsTo(windowctls, navbar);
        }

        for (var i = 0; i < HTitle.windowControlsObservers.length; i++) {
            HTitle.windowControlsObservers[i].disconnect();
        }
        HTitle.windowControlsObservers = [];
    },

    updateWindowControlsPosition: function() {
        var windowctls = document.getElementById("window-controls");

        if (HTitleTools.isFirefox()) {
            var menubar = document.getElementById("toolbar-menubar");
            var navbar = document.getElementById("nav-bar");
            var tabsbar = document.getElementById("TabsToolbar");

            if (!windowctls || !menubar || !navbar || !tabsbar) {
                return;
            }

            if (tabsbar.getAttribute("tabsontop") === "") {
                var tabsontop = navbar.getAttribute("default-tabs-position") != "bottom";
            }
            else {
                var tabsontop = tabsbar.getAttribute("tabsontop") != "false";
            }
        }
        else {
            var menubar = document.getElementById("mail-toolbar-menubar2");
            var tabsbar = document.getElementById("tabs-toolbar");

            if (!windowctls || !menubar || !tabsbar) {
                return;
            }

            var tabsontop = true;
        }

        if (menubar.getAttribute("autohide") != "true" && window.windowState != window.STATE_FULLSCREEN) {
            // Moving to the Menu bar
            if (menubar == windowctls.parentNode)
                return;

            var need_spring = true;
            var nodes = menubar.childNodes;
            for (var i = 0; i < nodes.length; i++) {
                if (parseInt(nodes[i].getAttribute("flex"), 10) >= 1) {
                    need_spring = false;
                    break;
                }
            }

            if (need_spring) {
                var spring = document.createElement("toolbarspring");
                spring.setAttribute("id", "htitle-menubar-spring");
                spring.setAttribute("removable", HTitleTools.isAustralisUI() ? "false" : "true");
                spring.setAttribute("flex", "1");
                HTitleTools.addToCurrentset(menubar, "htitle-menubar-spring");
                menubar.appendChild(spring);
            }

            HTitleTools.moveWindowControlsTo(windowctls, menubar);
        }
        else if (tabsontop || navbar.collapsed || HTitleTools.isThunderbird()) {
            // Moving to the Tabs toolbar
            if (tabsbar == windowctls.parentNode)
                return;
            HTitleTools.moveWindowControlsTo(windowctls, tabsbar);
        }
        else {
            // Moving to the Navigation toolbar
            if (navbar == windowctls.parentNode)
                return;
            HTitleTools.moveWindowControlsTo(windowctls, navbar);
        }

        windowctls.removeAttribute("flex");
    },

    start: function() {
        var result = -2;

        if (!HTitleTools.prefs.getBoolPref("legacy_mode.enable")) {
            HTitleTools.log("Start in normal mode", "DEBUG");

            var utils = HTitleTools.checkUtilsAvailable(["bash", "xwininfo", "xprop"]);
            if (utils) {
                var wm_class = HTitleTools.getWMClass().replace(/\"/g, '\\$&');

                if (HTitleTools.prefs.getIntPref("hide_mode") == 2) {
                    var str = 'WINDOWS=""; i="0"; while [ "$WINDOWS" == "" ] && [ $i -lt 1200 ]; do sleep 0.05; WINDOWS=$(xwininfo -tree -root | grep "(' + wm_class + ')" | sed "s/[ ]*//" | grep -o "0x[0-9a-f]*"); i=$[$i+1]; done; for ID in $WINDOWS; do xprop -id $ID -f _MOTIF_WM_HINTS 32c -set _MOTIF_WM_HINTS "0x2, 0x0, 0x2, 0x0, 0x0"; done';
                }
                else {
                    var str = 'WINDOWS=""; i="0"; while [ "$WINDOWS" == "" ] && [ $i -lt 1200 ]; do sleep 0.05; WINDOWS=$(xwininfo -tree -root | grep "(' + wm_class + ')" | sed "s/[ ]*//" | grep -o "0x[0-9a-f]*"); i=$[$i+1]; done; for ID in $WINDOWS; do xprop -id $ID -f _GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED 32c -set _GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED 1; done';
                }

                var args = ["-c", str];
                result = HTitleTools.run(utils.bash, args, false);
            }
            else {
                result = -1;
            }
        }

        if (result == 0) {
            HTitle.window.setAttribute("hidechrome", false);
            if (HTitleTools.prefs.getIntPref("hide_mode") == 2)
                HTitle.currentMode = "always";
            else {
                HTitle.currentMode = "auto";
                HTitle.window.setAttribute("hidetitlebarwhenmaximized", true);
            }
        }
        else {
            if (result == -1 && !HTitleTools.defaultModeFailed) {
                HTitleTools.defaultModeFailed = true;
                HTitleTools.prefs.setBoolPref("legacy_mode.enable", true);
            }
            HTitleTools.log("Start in legacy mode", "DEBUG");
            HTitleTools.log("TIMEOUT_CHECK = " + HTitleTools.timeoutCheck + "; TIMEOUT_BETWEEN_CHANGES = " + HTitleTools.timeoutBetweenChanges, "DEBUG");
            window.addEventListener("sizemodechange", HTitle.onWindowStateChange);
            HTitle.currentMode = "legacy";

            setTimeout(function(){HTitle.checkWindowState();}, HTitleTools.timeoutCheck);
        }
        HTitle.window.setAttribute("htitlemode", HTitle.currentMode);
    },

    stop: function() {
        if (HTitle.currentMode != "legacy") {
            var utils = HTitleTools.checkUtilsAvailable(["bash"]);
            if (utils) {
                var wm_class = HTitleTools.getWMClass().replace(/\"/g, '\\$&');
                var str = 'WINDOWS=$(xwininfo -tree -root | grep "(' + wm_class + ')" | sed "s/[ ]*//" | grep -o "0x[0-9a-f]*"); for ID in $WINDOWS; do xprop -id $ID -f _MOTIF_WM_HINTS 32c -set _MOTIF_WM_HINTS "0x2, 0x0, 0x1, 0x0, 0x0"; xprop -id $ID -remove _GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED; done';
                var args = ["-c", str]
                result = HTitleTools.run(utils.bash, args, false);
            }
            HTitle.window.removeAttribute("hidetitlebarwhenmaximized");
        }
        else if (HTitle.currentMode == "legacy") {
            window.removeEventListener("sizemodechange", HTitle.onWindowStateChange);
            HTitle.window.setAttribute("hidechrome", false);
        }
        HTitle.currentMode = "stopped";
        HTitle.previousState = 0;
        HTitle.previousChangeTime = 0;
        HTitle.window.setAttribute("htitlemode", HTitle.currentMode);
    },

    observe: function(subject, topic, data) {
        if (topic != "nsPref:changed")
            return;

        switch(data) {
            case "show_window_controls":
                if (HTitleTools.prefs.getBoolPref("show_window_controls")) {
                    HTitleTools.log("Enable show close button", "DEBUG");
                    HTitle.updateWindowControlsPosition(null);
                    HTitle.showWindowControls();
                }
                else {
                    HTitleTools.log("Disable show close button", "DEBUG");
                    HTitle.hideWindowControls();
                }
                break;
            case "legacy_mode.enable":
                if (HTitle.ENABLED && !HTitleTools.defaultModeFailed && HTitle.currentMode != "stopped") {
                    if (HTitleTools.prefs.getBoolPref("show_window_controls"))
                        HTitle.hideWindowControls();

                    HTitle.stop();
                    HTitleTools.prefs.setIntPref("hide_mode", 1);
                    HTitle.start();

                    if (HTitleTools.prefs.getBoolPref("show_window_controls"))
                        HTitle.showWindowControls();
                }
                break;
            case "hide_mode":
                if (HTitle.ENABLED && HTitle.currentMode != "stopped") {
                    if (HTitleTools.prefs.getBoolPref("show_window_controls"))
                        HTitle.hideWindowControls();

                    HTitle.stop();
                    if (HTitleTools.prefs.getIntPref("hide_mode") != 1)
                        HTitleTools.prefs.setBoolPref("legacy_mode.enable", false);
                    HTitle.start();

                    if (HTitleTools.prefs.getBoolPref("show_window_controls"))
                        HTitle.showWindowControls();
                }
                break;
            case "check_gnome_shell":
                if (!HTitle.ENABLED && !HTitleTools.prefs.getBoolPref("check_gnome_shell")) {
                    HTitle.ENABLED = true;
                    HTitle.start();
                }
                else if (HTitle.ENABLED && !HTitleTools.prefs.getBoolPref("check_gnome_shell")) {
                    return;
                }
                else if (HTitleTools.prefs.getBoolPref("check_gnome_shell") && HTitleTools.checkPresenceGnomeShell() != 0 && HTitle.ENABLED) {
                    HTitle.ENABLED = false;
                    HTitle.stop();
                }
                break;
            case "debug":
                HTitleTool.DEBUG = HTitleTools.prefs.getBoolPref("debug");
                break;
            case "legacy_mode.timeout_check":
                HTitleTools.timeoutCheck = HTitleTools.prefs.getIntPref("legacy_mode.timeout_check");
                break;
            case "legacy_mode.timeout_between_changes":
                HTitleTools.timeoutBetweenChanges = HTitleTools.prefs.getIntPref("legacy_mode.timeout_between_changes");
                break;
        }
    },

    onWindowStateChange: function(e) {
        if (HTitle.previousState == window.windowState || window.windowState == window.STATE_FULLSCREEN || window.windowState == window.STATE_MINIMIZED) {
            return;
        }

        if ((Date.now() - HTitle.previousChangeTime) < HTitleTools.timeoutBetweenChanges) {
            if (window.windowState == window.STATE_NORMAL && HTitle.window.getAttribute("hidechrome"))
                 window.maximize();
            return;
        }

        HTitle.logWindowState("onWindowStateChange");

        HTitle.window.setAttribute("hidechrome", (window.windowState == window.STATE_MAXIMIZED));

        HTitle.previousState = window.windowState;
        HTitle.previousChangeTime = Date.now();
    },

    checkWindowState: function() {
        if (window.windowState == window.STATE_NORMAL) {
            HTitle.logWindowState("checkWindowState");
            HTitle.window.setAttribute("hidechrome", false);
            HTitle.previousState = window.STATE_NORMAL;
            HTitle.previousChangeTime = Date.now();
        }
        else if (window.windowState == window.STATE_MAXIMIZED) {
            HTitle.logWindowState("checkWindowState");
            HTitle.window.setAttribute("hidechrome", true);
            HTitle.previousState = window.STATE_MAXIMIZED;
            HTitle.previousChangeTime = Date.now();
        }
    },

    logWindowState: function(from) {
        if (HTitle.DEBUG == false)
            return

        switch (window.windowState) {
            case window.STATE_MAXIMIZED:   var windowState = "maximized"; break;
            case window.STATE_NORMAL:      var windowState = "normal"; break;
            case window.STATE_FULLSCREEN:  var windowState = "fullscreen"; break;
            default: var windowState = window.windowState.toString();
        }

        HTitleTools.log("Action = " + from + "; windowState = " + windowState + ";  hidechrome = " + HTitle.window.getAttribute("hidechrome"), "DEBUG");
    },

    shutdown: function() {
        HTitleTools.prefs.removeObserver("", HTitle);
        //if (HTitleTools.prefs.getBoolPref("show_window_controls"))
        //    HTitle.hideWindowControls();
    },
}

window.addEventListener("load",   HTitle.init);
window.addEventListener("unload", HTitle.shutdown);
<commit_msg>Remove show_close_button key check<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

Components.utils.import("chrome://htitle/content/HTitleTools.jsm");

var HTitle = {
    ENABLED: true,

    windowControlsObservers: [],

    window: null,

    currentMode: "auto",
    previousState: 0,
    previousChangeTime: 0,

    init: function() {
        HTitleTools.prefs.addObserver("", HTitle, false);

        if (HTitleTools.prefs.getBoolPref("check_gnome_shell") && HTitleTools.checkPresenceGnomeShell() != 0) {
            // Nothing doing if WM is not GNOME Shell.
            HTitle.ENABLED = false;
            return;
        }

        HTitle.window = document.getElementById(HTitleTools.isThunderbird() ? "messengerWindow" : "main-window");

        HTitle.start();

        if (HTitleTools.prefs.getBoolPref("window_controls.get_layout_by_gsettings"))
            HTitle.setWindowControlsLayoutAttribute();

        if (HTitleTools.prefs.getBoolPref("show_window_controls"))
            HTitle.showWindowControls();
    },

    setWindowControlsLayoutAttribute: function() {
        var windowctls = document.getElementById("window-controls");
        if (windowctls) {
            windowctls.setAttribute("htitle-button-layout", HTitleTools.windowControlsLayout);
        }
    },

    showWindowControls: function() {
        var windowctls = document.getElementById("window-controls");
        windowctls.setAttribute("htitle", "true");

        // Appling CSS
        if (HTitle.currentMode == "always")
            HTitleTools.loadStyle("windowControlsAlways");
        else
            HTitleTools.loadStyle("windowControlsAuto");

        if (HTitleTools.isFirefox()) {
            window.addEventListener("sizemodechange", HTitle.updateWindowControlsPosition);

            var targets_map = [
                    ["TabsToolbar", "tabsontop"],
                    ["toolbar-menubar", "autohide"]
                ];
            if (HTitleTools.isAustralisUI()) {
                targets_map.push(["nav-bar", "default-tabs-position"]);
            }
            else {
                targets_map.push(["nav-bar", "collapsed"]);
            }
        }
        else {
            var targets_map = [
                    ["mail-toolbar-menubar2", "autohide"]
                ];
        }

        for (var i = 0; i < targets_map.length; i++) {
            var tempObserver = new MutationObserver(function(mutations) {
                mutations.forEach(HTitle.updateWindowControlsPosition);
            });
            tempObserver.observe(document.getElementById(targets_map[i][0]), { attributes: true, attributeFilter: [targets_map[i][1]] });
            HTitle.windowControlsObservers.push(tempObserver);
        }
        HTitleTools.log("HTitle.windowControlsObservers = " + HTitle.windowControlsObservers.length, "DEBUG");

        HTitle.updateWindowControlsPosition();
    },

    hideWindowControls: function() {
        if (HTitle.currentMode == "always")
            HTitleTools.unloadStyle("windowControlsAlways");
        else
            HTitleTools.unloadStyle("windowControlsAuto");

        var spring = document.getElementById("htitle-menubar-spring");
        if (spring)
            spring.remove();

        var windowctls = document.getElementById("window-controls");
        windowctls.removeAttribute("htitle");
        //windowctls.setAttribute("flex", "1");

        if (HTitleTools.isFirefox()) {
            window.removeEventListener("sizemodechange", HTitle.updateWindowControlsPosition);

            var navbar = document.getElementById("nav-bar");
            HTitleTools.moveWindowControlsTo(windowctls, navbar);
        }

        for (var i = 0; i < HTitle.windowControlsObservers.length; i++) {
            HTitle.windowControlsObservers[i].disconnect();
        }
        HTitle.windowControlsObservers = [];
    },

    updateWindowControlsPosition: function() {
        var windowctls = document.getElementById("window-controls");

        if (HTitleTools.isFirefox()) {
            var menubar = document.getElementById("toolbar-menubar");
            var navbar = document.getElementById("nav-bar");
            var tabsbar = document.getElementById("TabsToolbar");

            if (!windowctls || !menubar || !navbar || !tabsbar) {
                return;
            }

            if (tabsbar.getAttribute("tabsontop") === "") {
                var tabsontop = navbar.getAttribute("default-tabs-position") != "bottom";
            }
            else {
                var tabsontop = tabsbar.getAttribute("tabsontop") != "false";
            }
        }
        else {
            var menubar = document.getElementById("mail-toolbar-menubar2");
            var tabsbar = document.getElementById("tabs-toolbar");

            if (!windowctls || !menubar || !tabsbar) {
                return;
            }

            var tabsontop = true;
        }

        if (menubar.getAttribute("autohide") != "true" && window.windowState != window.STATE_FULLSCREEN) {
            // Moving to the Menu bar
            if (menubar == windowctls.parentNode)
                return;

            var need_spring = true;
            var nodes = menubar.childNodes;
            for (var i = 0; i < nodes.length; i++) {
                if (parseInt(nodes[i].getAttribute("flex"), 10) >= 1) {
                    need_spring = false;
                    break;
                }
            }

            if (need_spring) {
                var spring = document.createElement("toolbarspring");
                spring.setAttribute("id", "htitle-menubar-spring");
                spring.setAttribute("removable", HTitleTools.isAustralisUI() ? "false" : "true");
                spring.setAttribute("flex", "1");
                HTitleTools.addToCurrentset(menubar, "htitle-menubar-spring");
                menubar.appendChild(spring);
            }

            HTitleTools.moveWindowControlsTo(windowctls, menubar);
        }
        else if (tabsontop || navbar.collapsed || HTitleTools.isThunderbird()) {
            // Moving to the Tabs toolbar
            if (tabsbar == windowctls.parentNode)
                return;
            HTitleTools.moveWindowControlsTo(windowctls, tabsbar);
        }
        else {
            // Moving to the Navigation toolbar
            if (navbar == windowctls.parentNode)
                return;
            HTitleTools.moveWindowControlsTo(windowctls, navbar);
        }

        windowctls.removeAttribute("flex");
    },

    start: function() {
        var result = -2;

        if (!HTitleTools.prefs.getBoolPref("legacy_mode.enable")) {
            HTitleTools.log("Start in normal mode", "DEBUG");

            var utils = HTitleTools.checkUtilsAvailable(["bash", "xwininfo", "xprop"]);
            if (utils) {
                var wm_class = HTitleTools.getWMClass().replace(/\"/g, '\\$&');

                if (HTitleTools.prefs.getIntPref("hide_mode") == 2) {
                    var str = 'WINDOWS=""; i="0"; while [ "$WINDOWS" == "" ] && [ $i -lt 1200 ]; do sleep 0.05; WINDOWS=$(xwininfo -tree -root | grep "(' + wm_class + ')" | sed "s/[ ]*//" | grep -o "0x[0-9a-f]*"); i=$[$i+1]; done; for ID in $WINDOWS; do xprop -id $ID -f _MOTIF_WM_HINTS 32c -set _MOTIF_WM_HINTS "0x2, 0x0, 0x2, 0x0, 0x0"; done';
                }
                else {
                    var str = 'WINDOWS=""; i="0"; while [ "$WINDOWS" == "" ] && [ $i -lt 1200 ]; do sleep 0.05; WINDOWS=$(xwininfo -tree -root | grep "(' + wm_class + ')" | sed "s/[ ]*//" | grep -o "0x[0-9a-f]*"); i=$[$i+1]; done; for ID in $WINDOWS; do xprop -id $ID -f _GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED 32c -set _GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED 1; done';
                }

                var args = ["-c", str];
                result = HTitleTools.run(utils.bash, args, false);
            }
            else {
                result = -1;
            }
        }

        if (result == 0) {
            HTitle.window.setAttribute("hidechrome", false);
            if (HTitleTools.prefs.getIntPref("hide_mode") == 2)
                HTitle.currentMode = "always";
            else {
                HTitle.currentMode = "auto";
                HTitle.window.setAttribute("hidetitlebarwhenmaximized", true);
            }
        }
        else {
            if (result == -1 && !HTitleTools.defaultModeFailed) {
                HTitleTools.defaultModeFailed = true;
                HTitleTools.prefs.setBoolPref("legacy_mode.enable", true);
            }
            HTitleTools.log("Start in legacy mode", "DEBUG");
            HTitleTools.log("TIMEOUT_CHECK = " + HTitleTools.timeoutCheck + "; TIMEOUT_BETWEEN_CHANGES = " + HTitleTools.timeoutBetweenChanges, "DEBUG");
            window.addEventListener("sizemodechange", HTitle.onWindowStateChange);
            HTitle.currentMode = "legacy";

            setTimeout(function(){HTitle.checkWindowState();}, HTitleTools.timeoutCheck);
        }
        HTitle.window.setAttribute("htitlemode", HTitle.currentMode);
    },

    stop: function() {
        if (HTitle.currentMode != "legacy") {
            var utils = HTitleTools.checkUtilsAvailable(["bash"]);
            if (utils) {
                var wm_class = HTitleTools.getWMClass().replace(/\"/g, '\\$&');
                var str = 'WINDOWS=$(xwininfo -tree -root | grep "(' + wm_class + ')" | sed "s/[ ]*//" | grep -o "0x[0-9a-f]*"); for ID in $WINDOWS; do xprop -id $ID -f _MOTIF_WM_HINTS 32c -set _MOTIF_WM_HINTS "0x2, 0x0, 0x1, 0x0, 0x0"; xprop -id $ID -remove _GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED; done';
                var args = ["-c", str]
                result = HTitleTools.run(utils.bash, args, false);
            }
            HTitle.window.removeAttribute("hidetitlebarwhenmaximized");
        }
        else if (HTitle.currentMode == "legacy") {
            window.removeEventListener("sizemodechange", HTitle.onWindowStateChange);
            HTitle.window.setAttribute("hidechrome", false);
        }
        HTitle.currentMode = "stopped";
        HTitle.previousState = 0;
        HTitle.previousChangeTime = 0;
        HTitle.window.setAttribute("htitlemode", HTitle.currentMode);
    },

    observe: function(subject, topic, data) {
        if (topic != "nsPref:changed")
            return;

        switch(data) {
            case "show_window_controls":
                if (HTitleTools.prefs.getBoolPref("show_window_controls")) {
                    HTitleTools.log("Enable show close button", "DEBUG");
                    HTitle.updateWindowControlsPosition(null);
                    HTitle.showWindowControls();
                }
                else {
                    HTitleTools.log("Disable show close button", "DEBUG");
                    HTitle.hideWindowControls();
                }
                break;
            case "legacy_mode.enable":
                if (HTitle.ENABLED && !HTitleTools.defaultModeFailed && HTitle.currentMode != "stopped") {
                    if (HTitleTools.prefs.getBoolPref("show_window_controls"))
                        HTitle.hideWindowControls();

                    HTitle.stop();
                    HTitleTools.prefs.setIntPref("hide_mode", 1);
                    HTitle.start();

                    if (HTitleTools.prefs.getBoolPref("show_window_controls"))
                        HTitle.showWindowControls();
                }
                break;
            case "hide_mode":
                if (HTitle.ENABLED && HTitle.currentMode != "stopped") {
                    if (HTitleTools.prefs.getBoolPref("show_window_controls"))
                        HTitle.hideWindowControls();

                    HTitle.stop();
                    if (HTitleTools.prefs.getIntPref("hide_mode") != 1)
                        HTitleTools.prefs.setBoolPref("legacy_mode.enable", false);
                    HTitle.start();

                    if (HTitleTools.prefs.getBoolPref("show_window_controls"))
                        HTitle.showWindowControls();
                }
                break;
            case "check_gnome_shell":
                if (!HTitle.ENABLED && !HTitleTools.prefs.getBoolPref("check_gnome_shell")) {
                    HTitle.ENABLED = true;
                    HTitle.start();
                }
                else if (HTitle.ENABLED && !HTitleTools.prefs.getBoolPref("check_gnome_shell")) {
                    return;
                }
                else if (HTitleTools.prefs.getBoolPref("check_gnome_shell") && HTitleTools.checkPresenceGnomeShell() != 0 && HTitle.ENABLED) {
                    HTitle.ENABLED = false;
                    HTitle.stop();
                }
                break;
            case "debug":
                HTitleTool.DEBUG = HTitleTools.prefs.getBoolPref("debug");
                break;
            case "legacy_mode.timeout_check":
                HTitleTools.timeoutCheck = HTitleTools.prefs.getIntPref("legacy_mode.timeout_check");
                break;
            case "legacy_mode.timeout_between_changes":
                HTitleTools.timeoutBetweenChanges = HTitleTools.prefs.getIntPref("legacy_mode.timeout_between_changes");
                break;
        }
    },

    onWindowStateChange: function(e) {
        if (HTitle.previousState == window.windowState || window.windowState == window.STATE_FULLSCREEN || window.windowState == window.STATE_MINIMIZED) {
            return;
        }

        if ((Date.now() - HTitle.previousChangeTime) < HTitleTools.timeoutBetweenChanges) {
            if (window.windowState == window.STATE_NORMAL && HTitle.window.getAttribute("hidechrome"))
                 window.maximize();
            return;
        }

        HTitle.logWindowState("onWindowStateChange");

        HTitle.window.setAttribute("hidechrome", (window.windowState == window.STATE_MAXIMIZED));

        HTitle.previousState = window.windowState;
        HTitle.previousChangeTime = Date.now();
    },

    checkWindowState: function() {
        if (window.windowState == window.STATE_NORMAL) {
            HTitle.logWindowState("checkWindowState");
            HTitle.window.setAttribute("hidechrome", false);
            HTitle.previousState = window.STATE_NORMAL;
            HTitle.previousChangeTime = Date.now();
        }
        else if (window.windowState == window.STATE_MAXIMIZED) {
            HTitle.logWindowState("checkWindowState");
            HTitle.window.setAttribute("hidechrome", true);
            HTitle.previousState = window.STATE_MAXIMIZED;
            HTitle.previousChangeTime = Date.now();
        }
    },

    logWindowState: function(from) {
        if (HTitle.DEBUG == false)
            return

        switch (window.windowState) {
            case window.STATE_MAXIMIZED:   var windowState = "maximized"; break;
            case window.STATE_NORMAL:      var windowState = "normal"; break;
            case window.STATE_FULLSCREEN:  var windowState = "fullscreen"; break;
            default: var windowState = window.windowState.toString();
        }

        HTitleTools.log("Action = " + from + "; windowState = " + windowState + ";  hidechrome = " + HTitle.window.getAttribute("hidechrome"), "DEBUG");
    },

    shutdown: function() {
        HTitleTools.prefs.removeObserver("", HTitle);
        //if (HTitleTools.prefs.getBoolPref("show_window_controls"))
        //    HTitle.hideWindowControls();
    },
}

window.addEventListener("load",   HTitle.init);
window.addEventListener("unload", HTitle.shutdown);
<|endoftext|>


<commit_before>import { EventEmitter } from 'events';
const Twitter = require('twitter');

export default class TwitterClient {
  constructor({ accessToken, accessTokenSecret, consumerKey, consumerSecret }) {
    this.accessToken = accessToken;
    this.accessTokenSecret = accessTokenSecret;
    this.consumerKey = consumerKey;
    this.consumerSecret = consumerSecret;
  }

  _underlying() {
    if (!this.underlying) {
      this.underlying = new Twitter({
        access_token_key: this.accessToken,
        access_token_secret: this.accessTokenSecret,
        consumer_key: this.consumerKey,
        consumer_secret: this.consumerSecret
      });
    }
    return this.underlying;
  }

  _requestWith(method) {
    return new Promise((resolve, reject) => {
      method((errors, entities) => {
          if (errors !== null) {
            const error = errors[0];
            reject(error);
          } else {
            resolve(entities);
          }
        }
      );
    });
  }

  _get(path, params = {}) {
    return this._requestWith((callback) => this._underlying().get(path, params, callback));
  }

  _post(path, params) {
    return this._requestWith((callback) => this._underlying().post(path, params, callback));
  }

  favoritesCreate({ tweetId }) {
    return this._post(
      'favorites/create',
      { id: tweetId }
    );
  }

  favoritesDestroy({ tweetId }) {
    return this._post(
      'favorites/destroy',
      { id: tweetId }
    );
  }

  favoriteList({ userId, screenName, count, sinceTweetId, maxTweetId, includeEntities }) {
    return this._get(
      'favorites/list',
      {
        user_id: userId,
        screen_name: screenName,
        count: count,
        since_id: sinceTweetId,
        max_id: maxTweetId,
        include_entities: includeEntities
      });
  }

  fetchUser() {
    return this._get(
      'account/verify_credentials'
    );
  }

  /**
   * https://dev.twitter.com/rest/reference/get/friends/list
   *
   * @param {string} userId
   * @param {string|undefined} screenName
   * @param {string|undefined} cursor
   * @param {number|undefined} count
   * @param {boolean|undefined} skipStatus
   * @param {boolean|undefined} includeEntities
   * @returns {Promise<Object>} following
   */
  friendsList({ userId, screenName, cursor, count, skipStatus, includeEntities }) {
    return this._get(
      'friends/list',
      {
        user_id: userId,
        screen_name: screenName,
        cursor: cursor,
        count: count,
        skipStatus: skipStatus,
        include_entities: includeEntities
      });
  }

  /**
   * https://dev.twitter.com/rest/reference/get/followers/list
   *
   * @param {string} userId
   * @param {string|undefined} screenName
   * @param {string|undefined} cursor
   * @param {number|undefined} count
   * @param {boolean|undefined} skipStatus
   * @param {boolean|undefined} includeEntities
   * @returns {Promise<Object>} following
   */
  followersList({ userId, screenName, cursor, count, skipStatus, includeEntities }) {
    return this._get(
      'followers/list',
      {
        user_id: userId,
        screen_name: screenName,
        cursor: cursor,
        count: count,
        skipStatus: skipStatus,
        include_entities: includeEntities
      });
  }

  /**
   * https://dev.twitter.com/rest/reference/get/lists/ownerships
   *
   * @param userId
   * @param screenName
   * @param count
   * @param cursor
   * @return {Promise<Object>}
   */
  listsOwnership({ userId, screenName, count, cursor }) {
    return this._get(
      'lists/ownerships',
      {
        user_id: userId,
        screen_name: screenName,
        count: count,
        cursor: cursor
      });
  }

  /**
   * https://dev.twitter.com/rest/reference/get/lists/statuses
   *
   * @param {string} listId
   * @param {string} [slug] - You can identify a list by its slug instead of its numerical id
   * @param {string} [ownerScreenName]
   * @param {string} [ownerId]
   * @param {string} [sinceId]
   * @param {number} [maxId]
   * @param {number} [count]
   * @param {boolean} [includeEntities]
   * @param {boolean} [includeRts]
   * @return {Promise<Object>}
   */
  listsStatuses({ listId, slug, ownerScreenName, ownerId, sinceId, maxId, count, includeEntities, includeRts }) {
    return this._get(
      'lists/statuses',
      {
        list_id: listId,
        slug: slug,
        owner_screen_name: ownerScreenName,
        owner_id: ownerId,
        since_id: sinceId,
        max_id: maxId,
        count: count,
        include_entities: includeEntities,
        include_rts: includeRts,
      });
  }

  statusesHomeTimeline({ count, sinceId, maxId, trimUser, excludeReplies, contributorDetails, includeEntities }) {
    return this._get(
      'statuses/home_timeline',
      {
        count: count,
        since_id: sinceId,
        max_id: maxId,
        trim_user: trimUser,
        exclude_replies: excludeReplies,
        contributor_details: contributorDetails,
        include_entities: includeEntities
      });
  }

  statusesUserTimeline({ userId, screenName, sinceId, count, maxId, trimUser, excludeReplies, contributorDetails, includeRts }) {
    return this._get(
      'statuses/user_timeline',
      {
        user_id: userId,
        screen_name: screenName,
        since_id: sinceId,
        count: count,
        max_id: maxId,
        trim_user: trimUser,
        exclude_replies: excludeReplies,
        contributor_details: contributorDetails,
        include_rts: includeRts
      });
  }

  statusesUpdate({ text }) {
    return this._post(
      'statuses/update',
      {
        status: text
      }
    );
  }

  /**
   * @param userId {string}
   * @returns {EventEmitter}
   */
  subscribeUserStream(userId) {
    const eventEmitter = new EventEmitter();
    this._underlying().stream(
      'user',
      (stream) => {
        stream.on('follow', (data) => {
          eventEmitter.emit('follow', data);
        });
        stream.on('block', (data) => {
          eventEmitter.emit('block', data);
        });
        stream.on('favorite', (data) => {
          if (data.source.id_str !== userId) {
            eventEmitter.emit('favorite', data);
          }
        });
        stream.on('list_created', (data) => {
          eventEmitter.emit('list_created', data);
        });
        stream.on('list_destroyed', (data) => {
          eventEmitter.emit('list_destroyed', data);
        });
        stream.on('list_member_added', (data) => {
          eventEmitter.emit('list_member_added', data);
        });
        stream.on('list_member_removed', (data) => {
          eventEmitter.emit('list_member_removed', data);
        });
        stream.on('list_updated', (data) => {
          eventEmitter.emit('list_updated', data);
        });
        stream.on('list_user_subscribed', (data) => {
          eventEmitter.emit('list_user_subscribed', data);
        });
        stream.on('list_user_unsubscribed', (data) => {
          eventEmitter.emit('list_user_unsubscribed', data);
        });
        stream.on('unblock', (data) => {
          eventEmitter.emit('unblock', data);
        });
        stream.on('unfavorite', (data) => {
          eventEmitter.emit('unfavorite', data);
        });
        stream.on('user_update', (data) => {
          eventEmitter.emit('user_update', data);
        });
        stream.on('data', (data) => {
          if (data.friends) {
            eventEmitter.emit('friends', data);
          } else if (data.event) {
          } else if (data.delete) {
            eventEmitter.emit('delete', data);
          } else if (data.created_at) {
            if (data.retweeted_status && data.retweeted_status.user.id_str === userId) {
              eventEmitter.emit('retweet', data);
            }
            eventEmitter.emit('tweet', data);
          }
        });
      }
    );
    return eventEmitter;
  }

}
<commit_msg>Implement users/show api to TwitterClient<commit_after>import { EventEmitter } from 'events';
const Twitter = require('twitter');

export default class TwitterClient {
  constructor({ accessToken, accessTokenSecret, consumerKey, consumerSecret }) {
    this.accessToken = accessToken;
    this.accessTokenSecret = accessTokenSecret;
    this.consumerKey = consumerKey;
    this.consumerSecret = consumerSecret;
  }

  _underlying() {
    if (!this.underlying) {
      this.underlying = new Twitter({
        access_token_key: this.accessToken,
        access_token_secret: this.accessTokenSecret,
        consumer_key: this.consumerKey,
        consumer_secret: this.consumerSecret
      });
    }
    return this.underlying;
  }

  _requestWith(method) {
    return new Promise((resolve, reject) => {
      method((errors, entities) => {
          if (errors !== null) {
            const error = errors[0];
            reject(error);
          } else {
            resolve(entities);
          }
        }
      );
    });
  }

  _get(path, params = {}) {
    return this._requestWith((callback) => this._underlying().get(path, params, callback));
  }

  _post(path, params) {
    return this._requestWith((callback) => this._underlying().post(path, params, callback));
  }

  favoritesCreate({ tweetId }) {
    return this._post(
      'favorites/create',
      { id: tweetId }
    );
  }

  favoritesDestroy({ tweetId }) {
    return this._post(
      'favorites/destroy',
      { id: tweetId }
    );
  }

  favoriteList({ userId, screenName, count, sinceTweetId, maxTweetId, includeEntities }) {
    return this._get(
      'favorites/list',
      {
        user_id: userId,
        screen_name: screenName,
        count: count,
        since_id: sinceTweetId,
        max_id: maxTweetId,
        include_entities: includeEntities
      });
  }

  fetchUser() {
    return this._get(
      'account/verify_credentials'
    );
  }

  /**
   * https://dev.twitter.com/rest/reference/get/friends/list
   *
   * @param {string} userId
   * @param {string|undefined} screenName
   * @param {string|undefined} cursor
   * @param {number|undefined} count
   * @param {boolean|undefined} skipStatus
   * @param {boolean|undefined} includeEntities
   * @returns {Promise<Object>} following
   */
  friendsList({ userId, screenName, cursor, count, skipStatus, includeEntities }) {
    return this._get(
      'friends/list',
      {
        user_id: userId,
        screen_name: screenName,
        cursor: cursor,
        count: count,
        skipStatus: skipStatus,
        include_entities: includeEntities
      });
  }

  /**
   * https://dev.twitter.com/rest/reference/get/followers/list
   *
   * @param {string} userId
   * @param {string|undefined} screenName
   * @param {string|undefined} cursor
   * @param {number|undefined} count
   * @param {boolean|undefined} skipStatus
   * @param {boolean|undefined} includeEntities
   * @returns {Promise<Object>} following
   */
  followersList({ userId, screenName, cursor, count, skipStatus, includeEntities }) {
    return this._get(
      'followers/list',
      {
        user_id: userId,
        screen_name: screenName,
        cursor: cursor,
        count: count,
        skipStatus: skipStatus,
        include_entities: includeEntities
      });
  }

  /**
   * https://dev.twitter.com/rest/reference/get/lists/ownerships
   *
   * @param userId
   * @param screenName
   * @param count
   * @param cursor
   * @return {Promise<Object>}
   */
  listsOwnership({ userId, screenName, count, cursor }) {
    return this._get(
      'lists/ownerships',
      {
        user_id: userId,
        screen_name: screenName,
        count: count,
        cursor: cursor
      });
  }

  /**
   * https://dev.twitter.com/rest/reference/get/lists/statuses
   *
   * @param {string} listId
   * @param {string} [slug] - You can identify a list by its slug instead of its numerical id
   * @param {string} [ownerScreenName]
   * @param {string} [ownerId]
   * @param {string} [sinceId]
   * @param {number} [maxId]
   * @param {number} [count]
   * @param {boolean} [includeEntities]
   * @param {boolean} [includeRts]
   * @return {Promise<Object>}
   */
  listsStatuses({ listId, slug, ownerScreenName, ownerId, sinceId, maxId, count, includeEntities, includeRts }) {
    return this._get(
      'lists/statuses',
      {
        list_id: listId,
        slug: slug,
        owner_screen_name: ownerScreenName,
        owner_id: ownerId,
        since_id: sinceId,
        max_id: maxId,
        count: count,
        include_entities: includeEntities,
        include_rts: includeRts,
      });
  }

  statusesHomeTimeline({ count, sinceId, maxId, trimUser, excludeReplies, contributorDetails, includeEntities }) {
    return this._get(
      'statuses/home_timeline',
      {
        count: count,
        since_id: sinceId,
        max_id: maxId,
        trim_user: trimUser,
        exclude_replies: excludeReplies,
        contributor_details: contributorDetails,
        include_entities: includeEntities
      });
  }

  statusesUserTimeline({ userId, screenName, sinceId, count, maxId, trimUser, excludeReplies, contributorDetails, includeRts }) {
    return this._get(
      'statuses/user_timeline',
      {
        user_id: userId,
        screen_name: screenName,
        since_id: sinceId,
        count: count,
        max_id: maxId,
        trim_user: trimUser,
        exclude_replies: excludeReplies,
        contributor_details: contributorDetails,
        include_rts: includeRts
      });
  }

  statusesUpdate({ text }) {
    return this._post(
      'statuses/update',
      {
        status: text
      }
    );
  }

  /**
   * https://dev.twitter.com/rest/reference/get/users/show
   *
   * @param {string} userId
   * @param {string} [screenName]
   * @param {boolean} [includeEntities]
   * @return {*}
   */
  usersShow({ userId, screenName, includeEntities }) {
    return this._get(
      'users/show',
      {
        user_id: userId,
        screen_name: screenName,
        include_entities: includeEntities
      });
  }

  /**
   * @param userId {string}
   * @returns {EventEmitter}
   */
  subscribeUserStream(userId) {
    const eventEmitter = new EventEmitter();
    this._underlying().stream(
      'user',
      (stream) => {
        stream.on('follow', (data) => {
          eventEmitter.emit('follow', data);
        });
        stream.on('block', (data) => {
          eventEmitter.emit('block', data);
        });
        stream.on('favorite', (data) => {
          if (data.source.id_str !== userId) {
            eventEmitter.emit('favorite', data);
          }
        });
        stream.on('list_created', (data) => {
          eventEmitter.emit('list_created', data);
        });
        stream.on('list_destroyed', (data) => {
          eventEmitter.emit('list_destroyed', data);
        });
        stream.on('list_member_added', (data) => {
          eventEmitter.emit('list_member_added', data);
        });
        stream.on('list_member_removed', (data) => {
          eventEmitter.emit('list_member_removed', data);
        });
        stream.on('list_updated', (data) => {
          eventEmitter.emit('list_updated', data);
        });
        stream.on('list_user_subscribed', (data) => {
          eventEmitter.emit('list_user_subscribed', data);
        });
        stream.on('list_user_unsubscribed', (data) => {
          eventEmitter.emit('list_user_unsubscribed', data);
        });
        stream.on('unblock', (data) => {
          eventEmitter.emit('unblock', data);
        });
        stream.on('unfavorite', (data) => {
          eventEmitter.emit('unfavorite', data);
        });
        stream.on('user_update', (data) => {
          eventEmitter.emit('user_update', data);
        });
        stream.on('data', (data) => {
          if (data.friends) {
            eventEmitter.emit('friends', data);
          } else if (data.event) {
          } else if (data.delete) {
            eventEmitter.emit('delete', data);
          } else if (data.created_at) {
            if (data.retweeted_status && data.retweeted_status.user.id_str === userId) {
              eventEmitter.emit('retweet', data);
            }
            eventEmitter.emit('tweet', data);
          }
        });
      }
    );
    return eventEmitter;
  }

}
<|endoftext|>


<commit_before>var _curry3 = require('./internal/_curry3');
var map = require('./map');
var sequence = require('./sequence');

/**
 * Maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning
 * function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable),
 * then uses [`sequence`](#sequence) to transform the resulting Traversable of Applicative
 * into an Applicative of Traversable.
 *
 * Dispatches to the `sequence` method of the third argument, if present.
 *
 * @func
 * @memberOf R
 * @since v0.19.0
 * @category List
 * @sig (Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b)
 * @param {Function} of
 * @param {Function} f
 * @param {*} traversable
 * @return {*}
 * @see R.sequence
 * @example
 *
 *      // Returns `Nothing` if the given divisor is `0`
 *      safeDiv = n => d => d === 0 ? Nothing() : Just(n / d)
 *
 *      R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Just([5, 2.5, 2])
 *      R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Nothing
 */
module.exports = _curry3(function traverse(of, f, traversable) {
  return typeof traversable['fantasy-land/traverse'] === 'function' ?
    traversable['fantasy-land/traverse'](f, of) :
    sequence(of, map(f, traversable));
});
<commit_msg>Fix traverse doc (#2236)<commit_after>var _curry3 = require('./internal/_curry3');
var map = require('./map');
var sequence = require('./sequence');

/**
 * Maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning
 * function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable),
 * then uses [`sequence`](#sequence) to transform the resulting Traversable of Applicative
 * into an Applicative of Traversable.
 *
 * Dispatches to the `traverse` method of the third argument, if present.
 *
 * @func
 * @memberOf R
 * @since v0.19.0
 * @category List
 * @sig (Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b)
 * @param {Function} of
 * @param {Function} f
 * @param {*} traversable
 * @return {*}
 * @see R.sequence
 * @example
 *
 *      // Returns `Nothing` if the given divisor is `0`
 *      safeDiv = n => d => d === 0 ? Nothing() : Just(n / d)
 *
 *      R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Just([5, 2.5, 2])
 *      R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Nothing
 */
module.exports = _curry3(function traverse(of, f, traversable) {
  return typeof traversable['fantasy-land/traverse'] === 'function' ?
    traversable['fantasy-land/traverse'](f, of) :
    sequence(of, map(f, traversable));
});
<|endoftext|>


<commit_before>QUnit.module("Loader Factory", {
    before: function() {
        console.log("Kickoff: " + Math.random());
    },
    beforeEach: function() {
        console.log("Creating new test object");
        this.image_loader = new ImageLoader_0_5_x();
    }
});

QUnit.test("Confirm version number has been updated.", function(assert) {
    var target_version = "0.5.0";
    assert.equal(target_version, this.image_loader.version_number());
});

/************************************************************\
 * Integration Tests
\************************************************************/

QUnit.test("Integration Test 1: Base functionality using the minimum setup and call", function(assert) {
    // TODO:
    // - Add environmental overrides so it doesn't matter what browser is being tested.
    // - Add something like `imageLoader.load_environment()` to Given for the standard setup

    // Given
    this.image_loader._url_template = '//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]';

    // When
    var target_string = '';

    var result_string = this.image_loader.image_string_from_params( {
        filename: "horses.jpg",
        alt_text: "Photo of Horses",
        source_file_width: 1600,
        source_file_height: 1067
    });

    // Then
    assert.equal(result_string, target_string);
});

/************************************************************\
 * Unit Tests
\************************************************************/

QUnit.test("Default Settings Test: Ensure default max width is set.", function(assert) {
    var target_default_max_percentage_width_of_window = 94;
    var result = this.image_loader._max_width_of_window_percentage;
    assert.equal(result, target_default_max_percentage_width_of_window)
});

QUnit.test("Unit Test: assembled_url()", function(assert) {
    // Preflight
    var target = '//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]';

    // Given
    this.image_loader._url_template = '//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]';

    // When
    var result = this.image_loader.assembled_url();

    // Then
    assert.equal(target, result);
});

QUnit.test("Unit Test: calculate_logical_width(params)", function(assert) {

    // Given
    var target = 640;

    // When
    var result = this.image_loader.calculate_logical_width({
        max_physical_width: 640,
        percent_of_viewport_width: 94,
        viewport_width: 1028
    });

    // Then
    assert.equal(result, target);

});

QUnit.test("Unit Test: calculate_logical_height(params)", function(assert) {
    // Preflight
    var target = 436;

    // Given
    this.image_loader._source_file_width = 436;

    // When
    var result = this.image_loader.calculate_logical_height();

    // Then
    assert.equal(result, target);
});

/******************************************************\
 * DEPRECATED TESTS
 *
 * The tests below are for the prior versoin. They
 * are being kept temporarirly to make sure new
 * versions testing the same things are completed
 * before they are removed.
 *
/******************************************************/

// QUnit.test("Integration Test: Verify environmental parameters load", function(assert) {
//
//     // It's a little weird to tests these params, but I
//     // want to make sure they work for integration purposes.
//
//     // Given
//     var target_dpr = window.devicePixelRatio ? window.devicePixelRatio : 1;
//
//     // When
//     var imageLoader = new ImageLoader_0_5_x();
//     imageLoader.load_environmental_params();
//
//     // Then
//     assert.equal(imageLoader._dpr, target_dpr);
//
// });
//
//
// QUnit.test("2x DPR Basic call stright to load_params", function(assert) {
//
//   // Given
// 	var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//     	image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then - Verify instance variables.
//   assert.equal(imageLoader._dpr, 2, "Device pixel resolution");
//   assert.equal(imageLoader._image_name, "horses.jpg", "Image name");
//   assert.equal(imageLoader._raw_height, 1067, "Raw image height");
//   assert.equal(imageLoader._raw_width, 1600, "Raw image width");
//   assert.equal(imageLoader._percent_of_viewport_width, 50, "Percent of viewport width");
//   assert.equal(imageLoader._quality, 80, "Quality level");
//   assert.equal(imageLoader._viewport_height, 680, "Viewport height");
//   assert.equal(imageLoader._viewport_width, 1024, "Viewport width");
//   assert.equal(imageLoader._url_template, "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]", "URL Template");
//
//   // And - Verify functions
//   assert.equal(imageLoader.url_to_call(), "http://res.cloudinary.com/demo/image/upload/w_1024,h_682,q_80/horses.jpg", "Final URL");
//   assert.equal(imageLoader.render_height(), 341, "Render height");
//   assert.equal(imageLoader.render_width(), 512, "Render width");
//   assert.equal(imageLoader.url_request_height(), 682, "Request height");
//   assert.equal(imageLoader.url_request_width(), 1024, "Request width");
//   assert.equal(imageLoader.img_tag(), '', "Image tag");
//
// });
//
// QUnit.test("2x DPR stright to load_params with max width enforced", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       max_render_width: 200,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 200, "Max render width");
//   assert.equal(imageLoader.render_width(), 200, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.render_height(), 133, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.url_request_width(), 400, "Request width");
//   assert.equal(imageLoader.url_request_height(), 266, "Request height");
//
// });
//
//
// QUnit.test("Verify defaults", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       image_name: "horses.jpg",
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 1600, "Default Max Render Width == Raw Width");
//   assert.equal(imageLoader._dpr, 1, "Device pixel ratio default");
//   assert.equal(imageLoader._percent_of_viewport_width, 100, "Percent of viewport width default");
//   assert.equal(imageLoader._quality, 80, "Quality default");
//
// });
//
//
//
// QUnit.test("Ensure values are integers", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 25,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1021,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader.render_height(), 170, "Render height");
//   assert.equal(imageLoader.render_width(), 255, "Render width is 255 and not 255.25");
//   assert.equal(imageLoader.url_request_height(), 340, "Request height");
//   assert.equal(imageLoader.url_request_width(), 510, "Request width is 510 and not 510.5");
//
// });
//
//
// QUnit.test("Restrict height", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 1,
//       image_name: "horses.jpg",
//       percent_of_viewport_height: 90,
//       raw_height: 2000,
//       raw_width: 2200,
//       viewport_height: 1000,
//       viewport_width: 1800,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   assert.equal(imageLoader.render_height(), 900, "Render height");
//
//
// });
//
//
<commit_msg>Starting to rework the main integration test to remove passing params<commit_after>QUnit.module("Loader Factory", {
    before: function() {
        console.log("Kickoff: " + Math.random());
    },
    beforeEach: function() {
        console.log("Creating new test object");
        this.image_loader = new ImageLoader_0_5_x();
    }
});

QUnit.test("Confirm version number has been updated.", function(assert) {
    var target_version = "0.5.0";
    assert.equal(target_version, this.image_loader.version_number());
});

/************************************************************\
 * Integration Tests
\************************************************************/

QUnit.test("Integration Test 1: Base functionality using the minimum setup and call", function(assert) {

    // Preflight
    var target = '';

    // Given
    this.image_loader._url_template = '//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]';

    // When
    var result =  '';

//      var result_string = this.image_loader.image_string_from_params( {
//          filename: "horses.jpg",
//          alt_text: "Photo of Horses",
//          source_file_width: 1600,
//          source_file_height: 1067
//      });

    // Then
    assert.equal(target, result);
});

/************************************************************\
 * Unit Tests
\************************************************************/

QUnit.test("Default Settings Test: Ensure default max width is set.", function(assert) {
    var target_default_max_percentage_width_of_window = 94;
    var result = this.image_loader._max_width_of_window_percentage;
    assert.equal(result, target_default_max_percentage_width_of_window)
});

QUnit.test("Unit Test: assembled_url()", function(assert) {
    // Preflight
    var target = '//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]';

    // Given
    this.image_loader._url_template = '//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]';

    // When
    var result = this.image_loader.assembled_url();

    // Then
    assert.equal(target, result);
});

QUnit.test("Unit Test: calculate_logical_width(params)", function(assert) {

    // Given
    var target = 640;

    // When
    var result = this.image_loader.calculate_logical_width({
        max_physical_width: 640,
        percent_of_viewport_width: 94,
        viewport_width: 1028
    });

    // Then
    assert.equal(result, target);

});

QUnit.test("Unit Test: calculate_logical_height(params)", function(assert) {
    // Preflight
    var target = 436;

    // Given
    this.image_loader._source_file_width = 436;

    // When
    var result = this.image_loader.calculate_logical_height();

    // Then
    assert.equal(result, target);
});

/******************************************************\
 * DEPRECATED TESTS
 *
 * The tests below are for the prior versoin. They
 * are being kept temporarirly to make sure new
 * versions testing the same things are completed
 * before they are removed.
 *
/******************************************************/

// QUnit.test("Integration Test: Verify environmental parameters load", function(assert) {
//
//     // It's a little weird to tests these params, but I
//     // want to make sure they work for integration purposes.
//
//     // Given
//     var target_dpr = window.devicePixelRatio ? window.devicePixelRatio : 1;
//
//     // When
//     var imageLoader = new ImageLoader_0_5_x();
//     imageLoader.load_environmental_params();
//
//     // Then
//     assert.equal(imageLoader._dpr, target_dpr);
//
// });
//
//
// QUnit.test("2x DPR Basic call stright to load_params", function(assert) {
//
//   // Given
// 	var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//     	image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then - Verify instance variables.
//   assert.equal(imageLoader._dpr, 2, "Device pixel resolution");
//   assert.equal(imageLoader._image_name, "horses.jpg", "Image name");
//   assert.equal(imageLoader._raw_height, 1067, "Raw image height");
//   assert.equal(imageLoader._raw_width, 1600, "Raw image width");
//   assert.equal(imageLoader._percent_of_viewport_width, 50, "Percent of viewport width");
//   assert.equal(imageLoader._quality, 80, "Quality level");
//   assert.equal(imageLoader._viewport_height, 680, "Viewport height");
//   assert.equal(imageLoader._viewport_width, 1024, "Viewport width");
//   assert.equal(imageLoader._url_template, "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]", "URL Template");
//
//   // And - Verify functions
//   assert.equal(imageLoader.url_to_call(), "http://res.cloudinary.com/demo/image/upload/w_1024,h_682,q_80/horses.jpg", "Final URL");
//   assert.equal(imageLoader.render_height(), 341, "Render height");
//   assert.equal(imageLoader.render_width(), 512, "Render width");
//   assert.equal(imageLoader.url_request_height(), 682, "Request height");
//   assert.equal(imageLoader.url_request_width(), 1024, "Request width");
//   assert.equal(imageLoader.img_tag(), '', "Image tag");
//
// });
//
// QUnit.test("2x DPR stright to load_params with max width enforced", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       max_render_width: 200,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 200, "Max render width");
//   assert.equal(imageLoader.render_width(), 200, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.render_height(), 133, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.url_request_width(), 400, "Request width");
//   assert.equal(imageLoader.url_request_height(), 266, "Request height");
//
// });
//
//
// QUnit.test("Verify defaults", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       image_name: "horses.jpg",
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 1600, "Default Max Render Width == Raw Width");
//   assert.equal(imageLoader._dpr, 1, "Device pixel ratio default");
//   assert.equal(imageLoader._percent_of_viewport_width, 100, "Percent of viewport width default");
//   assert.equal(imageLoader._quality, 80, "Quality default");
//
// });
//
//
//
// QUnit.test("Ensure values are integers", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 25,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1021,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader.render_height(), 170, "Render height");
//   assert.equal(imageLoader.render_width(), 255, "Render width is 255 and not 255.25");
//   assert.equal(imageLoader.url_request_height(), 340, "Request height");
//   assert.equal(imageLoader.url_request_width(), 510, "Request width is 510 and not 510.5");
//
// });
//
//
// QUnit.test("Restrict height", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 1,
//       image_name: "horses.jpg",
//       percent_of_viewport_height: 90,
//       raw_height: 2000,
//       raw_width: 2200,
//       viewport_height: 1000,
//       viewport_width: 1800,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   assert.equal(imageLoader.render_height(), 900, "Render height");
//
//
// });
//
//
<|endoftext|>


<commit_before>const helper = require('../../tools/selenium-helper.js');
const expect = require('chai').expect;
const {Key, By} = require('selenium-webdriver');

describe('dash-tabs', function() {
  beforeEach(function() {
    return this.driver.get(`${this.address}/dash-tabs_demo.html`)
      .then(_ => helper.waitForElement(this.driver, 'dash-tabs'));
  });

  it('should focus the next tab on [arrow right]',
    async function() {
      const found =
        await helper.pressKeyUntil(
          this.driver,
          Key.TAB,
          `return document.activeElement.getAttribute('role') === 'tab';`
        );
      expect(found).to.equal(true);

      await this.driver
        .executeScript(`window.firstTab = document.activeElement;`);
      await this.driver.actions().sendKeys(Key.ARROW_RIGHT).perform();
      const focusedSomeTab = await this.driver.executeScript(`
        return window.firstTab !== document.activeElement &&
          !!document.activeElement.getAttribute('role')
      `);
      expect(focusedSomeTab).to.equal(true);
    }
  );

  it('should focus the prev tab on [arrow left]',
    async function() {
      const found =
        await helper.pressKeyUntil(
          this.driver,
          Key.TAB,
          `return document.activeElement.getAttribute('role') === 'tab';`
        );
      expect(found).to.equal(true);

      await this.driver
        .executeScript(`window.firstTab = document.activeElement;`);
      await this.driver.actions().sendKeys(Key.ARROW_LEFT).perform();
      const focusedAnotherTab = await this.driver.executeScript(`
        return window.firstTab !== document.activeElement &&
          document.activeElement.getAttribute('role') === 'tab';
      `);
      expect(focusedAnotherTab).to.equal(true);
    }
  );

  it('should focus the last tab on [end]',
    async function() {
      const found =
        await helper.pressKeyUntil(
          this.driver,
          Key.TAB,
          `return document.activeElement.getAttribute('role') === 'tab';`
        );
      expect(found).to.equal(true);
      await this.driver
        .executeScript(`window.firstTab = document.activeElement;`);

      await this.driver.actions().sendKeys(Key.END).perform();
      const focusedSomeTab = await this.driver.executeScript(`
        return window.firstTab !== document.activeElement &&
          document.activeElement.getAttribute('role') === 'tab';
      `);
      expect(focusedSomeTab).to.equal(true);

      await this.driver.actions().sendKeys(Key.ARROW_RIGHT).perform();
      const nextTabWasFirstTab = await this.driver.executeScript(`
        return window.firstTab === document.activeElement;
      `);
      expect(nextTabWasFirstTab).to.equal(true);
    }
  );

  it('should focus the first tab on [home]',
    async function() {
      const found =
        await helper.pressKeyUntil(
          this.driver,
          Key.TAB,
          `return document.activeElement.getAttribute('role') === 'tab';`
        );
      expect(found).to.equal(true);
      await this.driver
        .executeScript(`window.firstTab = document.activeElement;`);

      await this.driver.actions().sendKeys(Key.ARROW_LEFT).perform();
      await this.driver.actions().sendKeys(Key.HOME).perform();
      const focusedSomeTab = await this.driver.executeScript(`
        return window.firstTab === document.activeElement;
      `);
      expect(focusedSomeTab).to.equal(true);
    }
  );

 it('should focus a tab on click',
    async function() {
      const lastTab =
        await this.driver.findElement(By.css('[role=tab]:last-of-type'));
      expect(lastTab.getAttribute('aria-selected')).to.not.equal('true');
      await lastTab.click();
      expect(await lastTab.getAttribute('aria-selected')).to.equal('true');
    }
  );
});
<commit_msg>Add missing `await` to e2e test<commit_after>const helper = require('../../tools/selenium-helper.js');
const expect = require('chai').expect;
const {Key, By} = require('selenium-webdriver');

describe('dash-tabs', function() {
  beforeEach(function() {
    return this.driver.get(`${this.address}/dash-tabs_demo.html`)
      .then(_ => helper.waitForElement(this.driver, 'dash-tabs'));
  });

  it('should focus the next tab on [arrow right]',
    async function() {
      const found =
        await helper.pressKeyUntil(
          this.driver,
          Key.TAB,
          `return document.activeElement.getAttribute('role') === 'tab';`
        );
      expect(found).to.equal(true);

      await this.driver
        .executeScript(`window.firstTab = document.activeElement;`);
      await this.driver.actions().sendKeys(Key.ARROW_RIGHT).perform();
      const focusedSomeTab = await this.driver.executeScript(`
        return window.firstTab !== document.activeElement &&
          !!document.activeElement.getAttribute('role')
      `);
      expect(focusedSomeTab).to.equal(true);
    }
  );

  it('should focus the prev tab on [arrow left]',
    async function() {
      const found =
        await helper.pressKeyUntil(
          this.driver,
          Key.TAB,
          `return document.activeElement.getAttribute('role') === 'tab';`
        );
      expect(found).to.equal(true);

      await this.driver
        .executeScript(`window.firstTab = document.activeElement;`);
      await this.driver.actions().sendKeys(Key.ARROW_LEFT).perform();
      const focusedAnotherTab = await this.driver.executeScript(`
        return window.firstTab !== document.activeElement &&
          document.activeElement.getAttribute('role') === 'tab';
      `);
      expect(focusedAnotherTab).to.equal(true);
    }
  );

  it('should focus the last tab on [end]',
    async function() {
      const found =
        await helper.pressKeyUntil(
          this.driver,
          Key.TAB,
          `return document.activeElement.getAttribute('role') === 'tab';`
        );
      expect(found).to.equal(true);
      await this.driver
        .executeScript(`window.firstTab = document.activeElement;`);

      await this.driver.actions().sendKeys(Key.END).perform();
      const focusedSomeTab = await this.driver.executeScript(`
        return window.firstTab !== document.activeElement &&
          document.activeElement.getAttribute('role') === 'tab';
      `);
      expect(focusedSomeTab).to.equal(true);

      await this.driver.actions().sendKeys(Key.ARROW_RIGHT).perform();
      const nextTabWasFirstTab = await this.driver.executeScript(`
        return window.firstTab === document.activeElement;
      `);
      expect(nextTabWasFirstTab).to.equal(true);
    }
  );

  it('should focus the first tab on [home]',
    async function() {
      const found =
        await helper.pressKeyUntil(
          this.driver,
          Key.TAB,
          `return document.activeElement.getAttribute('role') === 'tab';`
        );
      expect(found).to.equal(true);
      await this.driver
        .executeScript(`window.firstTab = document.activeElement;`);

      await this.driver.actions().sendKeys(Key.ARROW_LEFT).perform();
      await this.driver.actions().sendKeys(Key.HOME).perform();
      const focusedSomeTab = await this.driver.executeScript(`
        return window.firstTab === document.activeElement;
      `);
      expect(focusedSomeTab).to.equal(true);
    }
  );

 it('should focus a tab on click',
    async function() {
      const lastTab =
        await this.driver.findElement(By.css('[role=tab]:last-of-type'));
      expect(await lastTab.getAttribute('aria-selected')).to.not.equal('true');
      await lastTab.click();
      expect(await lastTab.getAttribute('aria-selected')).to.equal('true');
    }
  );
});
<|endoftext|>


<commit_before>var version = "1.0.1";
var loadTime = 500;
var swalTimeout = 1000;
var previousVolume = 0; // Used for remembering the last volume value when muted
var volume = 0;

var url;
var rpcUrl;
var roomData;
var devices = [];
var displayInputs = {}; // map of each displayOutput to their current displayInput
var audioInputs = {}; // map of each audioOutput to their current audioInput
var blanks = {}; // map of each displayOutput to true/false

function init() {
	displayVersion();
}

function getRoom() {
	var hostname = document.getElementById('hostname').innerHTML;
	hostname = hostname.replace(/\s+/g, ''); // remove white space
	console.log("hostname =", hostname);
	var split = hostname.split('-');

	url = "http://" + hostname +":8000/buildings/" + split[0] + "/rooms/" + split[1];
	rpcUrl = "http://" + hostname + ":8100/buildings/" + split[0] + "/rooms/" + split[1];
	console.log("url for this room: ", url);

	console.log("here");
	getAllData();

	// get devices, put them into an array
	for (i in roomData.devices) {
		devices.push(roomData.devices[i]);
	}
}

function getAllData() {
	// get the all room information
	$.ajax({
		type: "GET",
		url: url,
		async: false,
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		success: function(data) {
			console.log("returning room data: ", data);
			roomData = data;
		},
		complete: function() {
			swal.close();
		},
		contentType: "application/json; charset=utf-8"
	});
}

function setup() {
	console.log("setup()");
	var numOfDisplayIns = 0;
	var numOfDisplayOuts = 0;
	var numOfAudioIns = 0;
	var numOfAudioOuts = 0;

	// if there are no devices
	if (devices.length == 0) {
		console.log("no devices found");
		$("#vol-slider").hide();
		$("#blank").hide();
		document.getElementById("volume-level").innerHTML = ":(";

		swal({
			title: "no devices found",
			text: "please contact a CSR for help",
			showConfirmButton: false,
			type: "warning",
		});
	}

	for (var i in devices) {
		for (var j in devices[i].roles) {
			if (devices[i].roles[j] == "VideoOut") {
				numOfDisplayOuts++;
				// add the item into displayOutputs
				displayInputs[devices[i].name] = "";
				blanks[devices[i].name] = false;

				console.log("devices[" + i + "](" + devices[i].name + ") is a display *output* device, building a button for it!");

				// create a button for each output display
				var button = document.createElement("button");

				button.type = "button";
				button.className = "display-output-button";
				var name = devices[i].name;
				button.onclick = (function(name) {
					return function() {
						setDisplayOutput(name, this);
					}
				})(name);
				button.innerHTML = name;
				document.getElementById("displays").appendChild(button);
				// set default, turn on first device
				if (numOfDisplayOuts == 1) {
					setDisplayOutput(name, button);
					powerOnRoom(); // this is not async. if it takes a long time to boot up, this is why.
					// can set async to true to solve this issue.
				}
			} else if (devices[i].roles[j] == "VideoIn") {
				numOfDisplayIns++;
				console.log("devices[" + i + "](" + devices[i].name + ") is an display *input* device, building a button for it!");

				//create a button for each input
				var button = document.createElement("button");
				button.type = "button";
				button.className = "display-input-button";
				var name = devices[i].name;
				button.onclick = (function(name) {
					return function() {
						switchDisplayInput(name, this);
					}
				})(name);
				button.innerHTML = name;
				document.getElementById("display-inputs").appendChild(button);
			} else if (devices[i].roles[j] == "AudioOut") {
				numOfAudioOuts++;

				// add the item into displayOutputs
				audioInputs[devices[i].name] = "";

				console.log("devices[" + i + "](" + devices[i].name + ") is a audio *output* device, building a button for it!");

				//create a button for each input
				var button = document.createElement("button");
				button.type = "button";
				button.className = "audio-output-button";
				var name = devices[i].name;
				// need to create a switchAudioOutput function?
				button.onclick = (function(name) {
					return function() {
						setAudioOutput(name, this);
					}
				})(name);
				button.innerHTML = name;
				document.getElementById("audio-outs").appendChild(button);

				setAudioOutput(name, button);

				// set default (initial) volume (only for first audio device)
				if (numOfAudioOuts == 1 && canGetVolume) {
					volume = devices[i].volume;
					volume = 0; // temporary, need a way to get the volume

					// hack to get the current volume
					$.ajax({
						type: "GET",
						url: "http://" + hostname + ":8004/" + devices[i].address + "/volume/get",
						async: false,
						headers: {
							'Access-Control-Allow-Origin': '*'
						},
						success: function(data) {
							console.log("setting volume to", data);
							volume = data;
							slider.setAttribute("value", volume);
						},
						contentType: "application/json; charset=utf-8"
					});
				}
			} else if (devices[i].roles[j] == "AudioIn") {
				numOfAudioIns++;
				console.log("devices[" + i + "](" + devices[i].name + ") is a audio *input* device, building a button for it!");
				// if it is an output, create a button on the displays page for it
				var button = document.createElement("button");

				//create a button for each input
				button.type = "button";
				button.className = "audio-input-button";
				var name = devices[i].name;
				button.onclick = (function(name) {
					return function() {
						switchAudioInput(name, this);
					}
				})(name);
				button.innerHTML = name;
				document.getElementById("audio-ins").appendChild(button);
			} else {
				// console.log("my role is " + devices[i].roles[j] + ". I don't get a button :( my name is: " + devices[i].name);
			}
		}
	}

	// update width of display buttons
	var newMargin = 5 / numOfDisplayOuts;
	var displayOutputButtons = document.querySelectorAll(".display-output-button");
	for (var i = 0; i < displayOutputButtons.length; i++) {
		displayOutputButtons[i].style.marginLeft = newMargin + "%";
		displayOutputButtons[i].style.marginRight = newMargin + "%";
	}

	// update width of display-input buttons
	newMargin = 5 / numOfDisplayIns;
	var displayInputButtons = document.querySelectorAll(".display-input-button");
	for (var i = 0; i < displayInputButtons.length; i++) {
		displayInputButtons[i].style.marginLeft = newMargin + "%";
		displayInputButtons[i].style.marginRight = newMargin + "%";
		if (displayInputButtons[i].scrollWidth > displayInputButtons.innerWidth) {
			console.log("overflow");
		}
	}

	// update width of audio-output buttons
	newMargin = 5 / numOfAudioOuts;
	var audioOutputButtons = document.querySelectorAll(".audio-output-button");
	for (var i = 0; i < audioOutputButtons.length; i++) {
		audioOutputButtons[i].style.marginLeft = newMargin + "%";
		audioOutputButtons[i].style.marginRight = newMargin + "%";
	}

	// update width of audio-input buttons
	newMargin = 5 / numOfDisplayIns;
	var audioInputButtons = document.querySelectorAll(".audio-input-button");
	for (var i = 0; i < audioInputButtons.length; i++) {
		audioInputButtons[i].style.marginLeft = newMargin + "%";
		audioInputButtons[i].style.marginRight = newMargin + "%";
	}
}

function pleaseWait() {
	swal({
		title: "Please Wait",
		text: "Command sent successfully.",
		timer: swalTimeout,
		showConfirmButton: false
	});
}

function wakeSystem() {
	swal({
		title: "Please Wait",
		text: "\"It's not my fault\" - Lando Calrissian",
		imageUrl: "https://upload.wikimedia.org/wikipedia/en/c/cb/Lando6-2.jpg",
		showConfirmButton: false
	});

	$("#idle-splash").hide();
	$("#loading-splash").show();

	setTimeout(function() {
		$("#loading-splash").fadeOut();
		getRoom();
		setup();

		bootpage.show("displays-page", updateActiveTab);
	}, loadTime);
}

function displayVersion() {
	$(".version-number").text("version " + version);
}

function confirmPowerOff() {
	swal({
		title: "Turn system off?",
		text: "I'll miss you!",
		type: "warning",
		showCancelButton: true,
		confirmButtonColor: "#DD6B55",
		confirmButtonText: "Yes",
		cancelButtonText: "No",
		closeOnConfirm: false,
		closeOnCancel: false
	}, function(isConfirm) {
		if (isConfirm) {
			swal({
				title: "Powering off!",
				text: "The system will now shut down.",
				type: "success",
				timer: swalTimeout,
				showConfirmButton: false
			}, function() {
				powerOffRoom();
			});

			setTimeout(function() {
				window.location = "/"; // Reload the page without hashes
			}, swalTimeout);
		} else {
			swal.close();
		}
	});
}

function updateActiveTab() {
	$("#displays-tab").removeClass("active")
	$("#audio-control-tab").removeClass("active");

	var currentTab = bootpage.currentPage.substring(0, bootpage.currentPage.length - 5);

	$("#" + currentTab + "-tab").addClass("active");
}
<commit_msg>finished<commit_after>var version = "1.0.1";
var loadTime = 500;
var swalTimeout = 1000;
var previousVolume = 0; // Used for remembering the last volume value when muted
var volume = 0;

var url;
var rpcUrl;
var roomData;
var devices = [];
var displayInputs = {}; // map of each displayOutput to their current displayInput
var audioInputs = {}; // map of each audioOutput to their current audioInput
var blanks = {}; // map of each displayOutput to true/false

function init() {
	displayVersion();
}

function getRoom() {
	var hostname = document.getElementById('hostname').innerHTML;
	hostname = hostname.replace(/\s+/g, ''); // remove white space
	console.log("hostname =", hostname);
	var split = hostname.split('-');

	var urlHost = document.location.host;
	urlHost = /.+?(?=:)/.exec(urlHost) // remove port info
	console.log("urlHost =", urlHost);
	url = "http://" + urlHost  + ":8000/buildings/" + split[0] + "/rooms/" + split[1];
	rpcUrl = "http://" + urlHost + ":8100/buildings/" + split[0] + "/rooms/" + split[1];
	console.log("url for this room: ", url);

	getAllData();

	// get devices, put them into an array
	for (i in roomData.devices) {
		devices.push(roomData.devices[i]);
	}
}

function getAllData() {
	// get the all room information
	$.ajax({
		type: "GET",
		url: url,
		async: false,
		headers: {
			'Access-Control-Allow-Origin': '*'
		},
		success: function(data) {
			console.log("returning room data: ", data);
			roomData = data;
		},
		complete: function() {
			swal.close();
		},
		contentType: "application/json; charset=utf-8"
	});
}

function setup() {
	console.log("setup()");
	var numOfDisplayIns = 0;
	var numOfDisplayOuts = 0;
	var numOfAudioIns = 0;
	var numOfAudioOuts = 0;

	// if there are no devices
	if (devices.length == 0) {
		console.log("no devices found");
		$("#vol-slider").hide();
		$("#blank").hide();
		document.getElementById("volume-level").innerHTML = ":(";

		swal({
			title: "no devices found",
			text: "please contact a CSR for help",
			showConfirmButton: false,
			type: "warning",
		});
	}

	for (var i in devices) {
		for (var j in devices[i].roles) {
			if (devices[i].roles[j] == "VideoOut") {
				numOfDisplayOuts++;
				// add the item into displayOutputs
				displayInputs[devices[i].name] = "";
				blanks[devices[i].name] = false;

				console.log("devices[" + i + "](" + devices[i].name + ") is a display *output* device, building a button for it!");

				// create a button for each output display
				var button = document.createElement("button");

				button.type = "button";
				button.className = "display-output-button";
				var name = devices[i].name;
				button.onclick = (function(name) {
					return function() {
						setDisplayOutput(name, this);
					}
				})(name);
				button.innerHTML = name;
				document.getElementById("displays").appendChild(button);
				// set default, turn on first device
				if (numOfDisplayOuts == 1) {
					setDisplayOutput(name, button);
					powerOnRoom(); // this is not async. if it takes a long time to boot up, this is why.
					// can set async to true to solve this issue.
				}
			} else if (devices[i].roles[j] == "VideoIn") {
				numOfDisplayIns++;
				console.log("devices[" + i + "](" + devices[i].name + ") is an display *input* device, building a button for it!");

				//create a button for each input
				var button = document.createElement("button");
				button.type = "button";
				button.className = "display-input-button";
				var name = devices[i].name;
				button.onclick = (function(name) {
					return function() {
						switchDisplayInput(name, this);
					}
				})(name);
				button.innerHTML = name;
				document.getElementById("display-inputs").appendChild(button);
			} else if (devices[i].roles[j] == "AudioOut") {
				numOfAudioOuts++;

				// add the item into displayOutputs
				audioInputs[devices[i].name] = "";

				console.log("devices[" + i + "](" + devices[i].name + ") is a audio *output* device, building a button for it!");

				//create a button for each input
				var button = document.createElement("button");
				button.type = "button";
				button.className = "audio-output-button";
				var name = devices[i].name;
				// need to create a switchAudioOutput function?
				button.onclick = (function(name) {
					return function() {
						setAudioOutput(name, this);
					}
				})(name);
				button.innerHTML = name;
				document.getElementById("audio-outs").appendChild(button);

				setAudioOutput(name, button);

				// set default (initial) volume (only for first audio device)
				if (numOfAudioOuts == 1 && canGetVolume) {
					volume = devices[i].volume;
					volume = 0; // temporary, need a way to get the volume

					// hack to get the current volume
					$.ajax({
						type: "GET",
						url: "http://" + hostname + ":8004/" + devices[i].address + "/volume/get",
						async: false,
						headers: {
							'Access-Control-Allow-Origin': '*'
						},
						success: function(data) {
							console.log("setting volume to", data);
							volume = data;
							slider.setAttribute("value", volume);
						},
						contentType: "application/json; charset=utf-8"
					});
				}
			} else if (devices[i].roles[j] == "AudioIn") {
				numOfAudioIns++;
				console.log("devices[" + i + "](" + devices[i].name + ") is a audio *input* device, building a button for it!");
				// if it is an output, create a button on the displays page for it
				var button = document.createElement("button");

				//create a button for each input
				button.type = "button";
				button.className = "audio-input-button";
				var name = devices[i].name;
				button.onclick = (function(name) {
					return function() {
						switchAudioInput(name, this);
					}
				})(name);
				button.innerHTML = name;
				document.getElementById("audio-ins").appendChild(button);
			} else {
				// console.log("my role is " + devices[i].roles[j] + ". I don't get a button :( my name is: " + devices[i].name);
			}
		}
	}

	// update width of display buttons
	var newMargin = 5 / numOfDisplayOuts;
	var displayOutputButtons = document.querySelectorAll(".display-output-button");
	for (var i = 0; i < displayOutputButtons.length; i++) {
		displayOutputButtons[i].style.marginLeft = newMargin + "%";
		displayOutputButtons[i].style.marginRight = newMargin + "%";
	}

	// update width of display-input buttons
	newMargin = 5 / numOfDisplayIns;
	var displayInputButtons = document.querySelectorAll(".display-input-button");
	for (var i = 0; i < displayInputButtons.length; i++) {
		displayInputButtons[i].style.marginLeft = newMargin + "%";
		displayInputButtons[i].style.marginRight = newMargin + "%";
		if (displayInputButtons[i].scrollWidth > displayInputButtons.innerWidth) {
			console.log("overflow");
		}
	}

	// update width of audio-output buttons
	newMargin = 5 / numOfAudioOuts;
	var audioOutputButtons = document.querySelectorAll(".audio-output-button");
	for (var i = 0; i < audioOutputButtons.length; i++) {
		audioOutputButtons[i].style.marginLeft = newMargin + "%";
		audioOutputButtons[i].style.marginRight = newMargin + "%";
	}

	// update width of audio-input buttons
	newMargin = 5 / numOfDisplayIns;
	var audioInputButtons = document.querySelectorAll(".audio-input-button");
	for (var i = 0; i < audioInputButtons.length; i++) {
		audioInputButtons[i].style.marginLeft = newMargin + "%";
		audioInputButtons[i].style.marginRight = newMargin + "%";
	}
}

function pleaseWait() {
	swal({
		title: "Please Wait",
		text: "Command sent successfully.",
		timer: swalTimeout,
		showConfirmButton: false
	});
}

function wakeSystem() {
	swal({
		title: "Please Wait",
		text: "\"It's not my fault\" - Lando Calrissian",
		imageUrl: "https://upload.wikimedia.org/wikipedia/en/c/cb/Lando6-2.jpg",
		showConfirmButton: false
	});

	$("#idle-splash").hide();
	$("#loading-splash").show();

	setTimeout(function() {
		$("#loading-splash").fadeOut();
		getRoom();
		setup();

		bootpage.show("displays-page", updateActiveTab);
	}, loadTime);
}

function displayVersion() {
	$(".version-number").text("version " + version);
}

function confirmPowerOff() {
	swal({
		title: "Turn system off?",
		text: "I'll miss you!",
		type: "warning",
		showCancelButton: true,
		confirmButtonColor: "#DD6B55",
		confirmButtonText: "Yes",
		cancelButtonText: "No",
		closeOnConfirm: false,
		closeOnCancel: false
	}, function(isConfirm) {
		if (isConfirm) {
			swal({
				title: "Powering off!",
				text: "The system will now shut down.",
				type: "success",
				timer: swalTimeout,
				showConfirmButton: false
			}, function() {
				powerOffRoom();
			});

			setTimeout(function() {
				window.location = "/"; // Reload the page without hashes
			}, swalTimeout);
		} else {
			swal.close();
		}
	});
}

function updateActiveTab() {
	$("#displays-tab").removeClass("active")
	$("#audio-control-tab").removeClass("active");

	var currentTab = bootpage.currentPage.substring(0, bootpage.currentPage.length - 5);

	$("#" + currentTab + "-tab").addClass("active");
}
<|endoftext|>