glowingbear-mainbox/js/glowingbear.js

813 lines
32 KiB
JavaScript
Raw Normal View History

(function() {
'use strict';
var weechat = angular.module('weechat', ['ngRoute', 'localStorage', 'weechatModels', 'plugins', 'IrcUtils', 'ngSanitize', 'ngWebsockets', 'ngTouch'], ['$compileProvider', function($compileProvider) {
// hacky way to be able to find out if we're in debug mode
weechat.compileProvider = $compileProvider;
}]);
weechat.config(['$compileProvider', function ($compileProvider) {
2014-12-30 21:05:40 +01:00
// hack to determine whether we're executing the tests
if (typeof(it) === "undefined" && typeof(describe) === "undefined") {
$compileProvider.debugInfoEnabled(false);
}
}]);
2013-02-18 00:49:42 +01:00
2014-12-22 22:17:01 +01:00
weechat.controller('WeechatCtrl', ['$rootScope', '$scope', '$store', '$timeout', '$log', 'models', 'connection', 'notifications', 'utils', 'settings',
function ($rootScope, $scope, $store, $timeout, $log, models, connection, notifications, utils, settings) {
window.openBuffer = function(channel) {
$scope.openBuffer(channel);
$scope.$apply();
};
$scope.command = '';
$scope.themes = ['dark', 'light'];
2014-12-30 20:24:33 +01:00
settings.setDefaults({
'theme': 'dark',
'host': 'localhost',
'port': 9001,
'ssl': (window.location.protocol === "https:"),
'savepassword': false,
'autoconnect': false,
'nonicklist': utils.isMobileUi(),
'noembed': true,
2014-12-30 20:24:33 +01:00
'onlyUnread': false,
'hotlistsync': true,
'orderbyserver': true,
'useFavico': true,
'showtimestamp': true,
'showtimestampSeconds': false,
'fontsize': '14px',
'fontfamily': (utils.isMobileUi() ? 'sans-serif' : 'Inconsolata, Consolas, Monaco, Ubuntu Mono, monospace'),
'readlineBindings': false,
'enableJSEmoji': (utils.isMobileUi() ? false : true),
'enableMathjax': false,
2014-12-30 20:24:33 +01:00
});
2014-12-22 22:17:01 +01:00
$scope.settings = settings;
// From: http://stackoverflow.com/a/18539624 by StackOverflow user "plantian"
2013-12-17 21:30:22 +01:00
$rootScope.countWatchers = function () {
var q = [$rootScope], watchers = 0, scope;
while (q.length > 0) {
scope = q.pop();
if (scope.$$watchers) {
watchers += scope.$$watchers.length;
}
if (scope.$$childHead) {
q.push(scope.$$childHead);
}
if (scope.$$nextSibling) {
q.push(scope.$$nextSibling);
}
}
$log.debug(watchers);
};
2014-02-25 21:41:41 +01:00
$scope.isinstalled = (function() {
// Check for firefox & app installed
if (navigator.mozApps !== undefined) {
navigator.mozApps.getSelf().onsuccess = function _onAppReady(evt) {
var app = evt.target.result;
if (app) {
return true;
} else {
return false;
}
};
} else {
return false;
}
}());
2013-10-06 12:34:41 +02:00
// Detect page visibility attributes
(function() {
// Sadly, the page visibility API still has a lot of vendor prefixes
if (typeof document.hidden !== "undefined") { // Chrome >= 33, Firefox >= 18, Opera >= 12.10, Safari >= 7
$scope.documentHidden = "hidden";
$scope.documentVisibilityChange = "visibilitychange";
} else if (typeof document.webkitHidden !== "undefined") { // 13 <= Chrome < 33
$scope.documentHidden = "webkitHidden";
$scope.documentVisibilityChange = "webkitvisibilitychange";
} else if (typeof document.mozHidden !== "undefined") { // 10 <= Firefox < 18
$scope.documentHidden = "mozHidden";
$scope.documentVisibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") { // IE >= 10
$scope.documentHidden = "msHidden";
$scope.documentVisibilityChange = "msvisibilitychange";
}
})();
// Enable debug mode if "?debug=1" or "?debug=true" is set
(function() {
window.location.search.substring(1).split('&').forEach(function(f) {
var segs = f.split('=');
if (segs[0] === "debug" && ["true", "1"].indexOf(segs[1]) != -1) {
$rootScope.debugMode = true;
}
});
// If we haven't reloaded yet, do an angular reload with debug infos
// store whether this has happened yet in a GET parameter
if ($rootScope.debugMode && !weechat.compileProvider.debugInfoEnabled()) {
angular.reloadWithDebugInfo();
}
})();
$rootScope.isWindowFocused = function() {
if (typeof $scope.documentHidden === "undefined") {
// Page Visibility API not supported, assume yes
return true;
} else {
var isHidden = document[$scope.documentHidden];
return !isHidden;
}
};
if (typeof $scope.documentVisibilityChange !== "undefined") {
document.addEventListener($scope.documentVisibilityChange, function() {
if (!document[$scope.documentHidden]) {
// We just switched back to the glowing-bear window and unread messages may have
// accumulated in the active buffer while the window was in the background
var buffer = models.getActiveBuffer();
// This can also be triggered before connecting to the relay, check for null (not undefined!)
if (buffer !== null) {
buffer.unread = 0;
buffer.notification = 0;
// Trigger title and favico update
$rootScope.$emit('notificationChanged');
}
// the unread badge in the bufferlist doesn't update if we don't do this
$rootScope.$apply();
}
}, false);
}
$rootScope.$on('activeBufferChanged', function(event, unreadSum) {
var ab = models.getActiveBuffer();
2014-06-26 22:38:04 +02:00
// Discard surplus lines. This is done *before* lines are fetched because that saves us the effort of special handling for the
// case where a buffer is opened for the first time ;)
var minRetainUnread = ab.lines.length - unreadSum + 5; // do not discard unread lines and keep 5 additional lines for context
var surplusLines = ab.lines.length - (2 * $scope.lines_per_screen + 10); // retain up to 2*(screenful + 10) + 10 lines because magic numbers
var linesToRemove = Math.min(minRetainUnread, surplusLines);
if (linesToRemove > 0) {
ab.lines.splice(0, linesToRemove); // remove the lines from the buffer
ab.requestedLines -= linesToRemove; // to ensure that the correct amount of lines is fetched should more be requested
ab.lastSeen -= linesToRemove; // adjust readmarker
ab.allLinesFetched = false; // we just removed lines, so we don't have all of them. re-enable "fetch more lines"
}
2014-06-26 22:38:04 +02:00
$scope.bufferlines = ab.lines;
$scope.nicklist = ab.nicklist;
// Send a request for the nicklist if it hasn't been loaded yet
if (!ab.nicklistRequested()) {
connection.requestNicklist(ab.id, function() {
$scope.showNicklist = $scope.updateShowNicklist();
// Scroll after nicklist has been loaded, as it may break long lines
$rootScope.scrollWithBuffer(true);
});
} else {
// Check if we should show nicklist or not
$scope.showNicklist = $scope.updateShowNicklist();
}
2014-06-27 04:36:30 +02:00
if (ab.requestedLines < $scope.lines_per_screen) {
2014-02-10 20:32:00 +01:00
// buffer has not been loaded, but some lines may already be present if they arrived after we connected
// try to determine how many lines to fetch
var numLines = $scope.lines_per_screen + 10; // that's (a screenful plus 10 lines) plus 10 lines, just to be safe
if (unreadSum > numLines) {
// request up to 4*(screenful + 10 lines)
numLines = Math.min(4*numLines, unreadSum);
}
$scope.fetchMoreLines(numLines).then(
// Update initial scroll position
// Most relevant when first connecting to properly initalise
function() {
$timeout(function() {
2014-09-23 02:08:27 +02:00
var bl = document.getElementById("bufferlines");
var lastScrollHeight = bl.scrollHeight;
var scrollHeightObserver = function() {
if (bl) {
var newScrollHeight = bl.scrollHeight;
if (newScrollHeight !== lastScrollHeight) {
$rootScope.updateBufferBottom($rootScope.bufferBottom);
lastScrollHeight = newScrollHeight;
}
setTimeout(scrollHeightObserver, 500);
}
};
$rootScope.updateBufferBottom(true);
$rootScope.scrollWithBuffer(true);
bl.onscroll = _.debounce(function() {
$rootScope.updateBufferBottom();
}, 80);
setTimeout(scrollHeightObserver, 500);
});
}
);
}
2014-08-28 18:25:40 +02:00
notifications.updateTitle(ab);
setTimeout(function(){
$scope.notifications = notifications.unreadCount('notification');
$scope.unread = notifications.unreadCount('unread');
});
2014-09-23 02:08:27 +02:00
$timeout(function() {
$rootScope.scrollWithBuffer(true);
});
// Clear search term on buffer change
$scope.search = '';
2013-12-17 21:30:22 +01:00
2014-08-28 18:25:40 +02:00
if (!utils.isMobileUi()) {
// This needs to happen asynchronously to prevent the enter key handler
// of the input bar to be triggered on buffer switch via the search.
// Otherwise its current contents would be sent to the new buffer
setTimeout(function() {
document.getElementById('sendMessage').focus();
}, 0);
}
// Do this part last since it's not important for the UI
if (settings.hotlistsync && ab.fullName) {
connection.sendHotlistClear();
}
});
2014-02-18 19:13:23 +01:00
2014-08-28 18:25:40 +02:00
$rootScope.favico = new Favico({animation: 'none'});
$scope.notifications = notifications.unreadCount('notification');
$scope.unread = notifications.unreadCount('unread');
2014-02-18 19:13:23 +01:00
2013-10-15 15:21:13 +02:00
$rootScope.$on('notificationChanged', function() {
2014-08-28 18:25:40 +02:00
notifications.updateTitle();
$scope.notifications = notifications.unreadCount('notification');
$scope.unread = notifications.unreadCount('unread');
2014-12-22 22:17:01 +01:00
if (settings.useFavico && $rootScope.favico) {
2014-08-28 18:25:40 +02:00
notifications.updateFavico();
2013-10-15 15:21:13 +02:00
}
});
$rootScope.$on('relayDisconnect', function() {
// Reset title
$rootScope.pageTitle = '';
$rootScope.notificationStatus = '';
notifications.cancelAll();
models.reinitialize();
2014-03-05 14:20:48 +01:00
$rootScope.$emit('notificationChanged');
$scope.connectbutton = 'Connect';
$scope.connectbuttonicon = 'glyphicon-chevron-right';
});
$scope.connectbutton = 'Connect';
$scope.connectbuttonicon = 'glyphicon-chevron-right';
$scope.getBuffers = models.getBuffers.bind(models);
2014-02-25 21:42:59 +01:00
$scope.bufferlines = {};
$scope.nicklist = {};
2013-12-16 14:09:01 +01:00
$scope.activeBuffer = models.getActiveBuffer;
2013-10-08 15:55:07 +02:00
$rootScope.connected = false;
$rootScope.waseverconnected = false;
$rootScope.userdisconnect = false;
$rootScope.reconnecting = false;
2013-02-16 19:18:14 +01:00
2013-10-08 15:55:07 +02:00
$rootScope.models = models;
$rootScope.iterCandidate = null;
2014-12-22 22:17:01 +01:00
if (settings.savepassword) {
$scope.$watch('password', function() {
settings.password = $scope.password;
});
settings.addCallback('password', function(password) {
$scope.password = password;
});
$scope.password = settings.password;
} else {
settings.password = '';
}
// Check if user decides to save password, and copy it over
settings.addCallback('savepassword', function(newvalue) {
if (settings.savepassword) {
// Init value in settings module
settings.setDefaults({'password': $scope.password});
settings.password = $scope.password;
}
});
$rootScope.wasMobileUi = false;
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
$rootScope.wasMobileUi = true;
}
2014-12-22 22:17:01 +01:00
if (!settings.fontfamily) {
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
2014-12-22 22:17:01 +01:00
settings.fontfamily = 'sans-serif';
} else {
2014-12-22 22:17:01 +01:00
settings.fontfamily = "Inconsolata, Consolas, Monaco, Ubuntu Mono, monospace";
}
}
2014-07-08 10:51:17 +02:00
$scope.isSidebarVisible = function() {
return document.getElementById('content').getAttribute('sidebar-state') === 'visible';
2014-07-08 10:51:17 +02:00
};
$scope.showSidebar = function() {
document.getElementById('sidebar').setAttribute('data-state', 'visible');
document.getElementById('content').setAttribute('sidebar-state', 'visible');
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
// de-focus the input bar when opening the sidebar on mobile, so that the keyboard goes down
_.each(document.getElementsByTagName('textarea'), function(elem) {
2014-09-23 23:36:03 +02:00
$timeout(function(){elem.blur();});
});
}
2014-07-08 10:51:17 +02:00
};
$rootScope.hideSidebar = function() {
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
document.getElementById('sidebar').setAttribute('data-state', 'hidden');
document.getElementById('content').setAttribute('sidebar-state', 'hidden');
}
2014-07-08 10:51:17 +02:00
};
2014-12-22 22:17:01 +01:00
settings.addCallback('autoconnect', function(autoconnect) {
if (autoconnect && !$rootScope.connected && !$rootScope.sslError && !$rootScope.securityError && !$rootScope.errorMessage) {
$scope.connect();
}
});
2014-07-08 10:51:17 +02:00
// toggle sidebar (if on mobile)
$scope.toggleSidebar = function() {
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
2014-07-08 10:51:17 +02:00
if ($scope.isSidebarVisible()) {
$scope.hideSidebar();
} else {
$scope.showSidebar();
}
2014-02-23 15:17:59 +01:00
}
2014-02-19 16:15:23 +01:00
};
2014-02-24 11:28:43 +01:00
2014-07-08 10:51:17 +02:00
// Open and close panels while on mobile devices through swiping
2014-02-19 16:15:23 +01:00
$scope.openNick = function() {
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
2014-12-22 22:17:01 +01:00
if (settings.nonicklist) {
settings.nonicklist = false;
2014-02-24 11:28:43 +01:00
}
2014-02-19 16:15:23 +01:00
}
};
$scope.closeNick = function() {
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
2014-12-22 22:17:01 +01:00
if (!settings.nonicklist) {
settings.nonicklist = true;
2014-02-24 11:28:43 +01:00
}
2014-02-19 16:15:23 +01:00
}
};
// Watch model and update channel sorting when it changes
2014-12-22 22:17:01 +01:00
settings.addCallback('orderbyserver', function(orderbyserver) {
$rootScope.predicate = orderbyserver ? 'serverSortKey' : 'number';
});
2014-12-22 22:17:01 +01:00
settings.addCallback('useFavico', function(useFavico) {
// this check is necessary as this is called on page load, too
if (!$rootScope.connected) {
return;
}
2014-12-22 22:17:01 +01:00
if (useFavico) {
2014-08-28 18:25:40 +02:00
notifications.updateFavico();
} else {
2014-08-28 18:25:40 +02:00
$rootScope.favico.reset();
}
});
// To prevent unnecessary loading times for users who don't
// want MathJax, load it only if the setting is enabled.
// This also fires when the page is loaded if enabled.
settings.addCallback('enableMathjax', function(enabled) {
if (enabled && !$rootScope.mathjax_init) {
// Load MathJax only once
$rootScope.mathjax_init = true;
(function () {
var head = document.getElementsByTagName("head")[0], script;
script = document.createElement("script");
script.type = "text/x-mathjax-config";
script[(window.opera ? "innerHTML" : "text")] =
"MathJax.Hub.Config({\n" +
" tex2jax: { inlineMath: [['$$','$$'], ['\\\\(','\\\\)']], displayMath: [['\\\\[','\\\\]']] },\n" +
"});";
head.appendChild(script);
script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML";
head.appendChild(script);
})();
}
});
// Inject theme CSS
settings.addCallback('theme', function(theme) {
// Unload old theme
var oldThemeCSS = document.getElementById("themeCSS");
if (oldThemeCSS) {
oldThemeCSS.parentNode.removeChild(oldThemeCSS);
}
// Load new theme
(function() {
var elem = document.createElement("link");
elem.rel = "stylesheet";
elem.href = "css/themes/" + theme + ".css";
elem.media = "screen";
elem.id = "themeCSS";
document.getElementsByTagName("head")[0].appendChild(elem);
})();
});
// Update font family when changed
2014-12-22 22:17:01 +01:00
settings.addCallback('fontfamily', function(fontfamily) {
utils.changeClassStyle('favorite-font', 'fontFamily', fontfamily);
});
2014-07-07 16:09:25 +02:00
// Update font size when changed
2014-12-22 22:17:01 +01:00
settings.addCallback('fontsize', function(fontsize) {
utils.changeClassStyle('favorite-font', 'fontSize', fontsize);
});
2013-10-02 02:32:18 +02:00
$scope.setActiveBuffer = function(bufferId, key) {
// If we are on mobile we need to collapse the menu on sidebar clicks
// We use 968 px as the cutoff, which should match the value in glowingbear.css
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
2014-07-08 10:51:17 +02:00
$scope.hideSidebar();
}
// Clear the hotlist for this buffer, because presumable you have read
// the messages in this buffer before you switched to the new one
// this is only needed with new type of clearing since in the old
// way WeeChat itself takes care of that part
if (models.version[0] >= 1) {
connection.sendHotlistClear();
}
return models.setActiveBuffer(bufferId, key);
2013-07-30 15:22:37 +02:00
};
$scope.openBuffer = function(bufferName) {
var fullName = models.getActiveBuffer().fullName;
fullName = fullName.substring(0, fullName.lastIndexOf('.') + 1) + bufferName; // substitute the last part
if (!$scope.setActiveBuffer(fullName, 'fullName')) {
// WeeChat 0.4.0+ supports /join -noswitch
// As Glowing Bear requires 0.4.2+, we don't need to check the version
var command = 'join -noswitch';
// Check if it's a query and we need to use /query instead
if (['#', '&', '+', '!'].indexOf(bufferName.charAt(0)) < 0) { // these are the characters a channel name can start with (RFC 2813-2813)
command = 'query';
// WeeChat 1.2+ supports /query -noswitch. See also #577 (different context)
if ((models.version[0] == 1 && models.version[1] >= 2) || models.version[1] > 1) {
command += " -noswitch";
}
}
connection.sendMessage('/' + command + ' ' + bufferName);
}
2013-12-16 14:09:01 +01:00
};
2014-08-28 18:25:40 +02:00
//XXX this does not belong here (or does it?)
// Calculate number of lines to fetch
$scope.calculateNumLines = function() {
var bufferlineElements = document.querySelectorAll(".bufferline");
var lineHeight = 0, idx = 0;
while (lineHeight === 0 && idx < bufferlineElements.length) {
lineHeight = bufferlineElements[idx++].clientHeight;
}
var areaHeight = document.querySelector("#bufferlines").clientHeight;
// Fetch 10 lines more than theoretically needed so that scrolling up will correctly trigger the loading of more lines
// Also, some lines might be hidden, so it's probably better to have a bit of buffer there
var numLines = Math.ceil(areaHeight/lineHeight + 10);
2014-06-27 04:36:30 +02:00
$scope.lines_per_screen = numLines;
};
$scope.calculateNumLines();
2014-09-23 02:08:27 +02:00
// get animationframe method
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;
// Recalculate number of lines on resize
window.addEventListener("resize", _.debounce(function() {
// Recalculation fails when not connected
if ($rootScope.connected) {
// Show the sidebar if switching away from mobile view, hide it when switching to mobile
// Wrap in a condition so we save ourselves the $apply if nothing changes (50ms or more)
2014-08-28 18:25:40 +02:00
if ($scope.wasMobileUi && !utils.isMobileUi()) {
2014-07-08 10:51:17 +02:00
$scope.showSidebar();
}
2014-08-28 18:25:40 +02:00
$scope.wasMobileUi = utils.isMobileUi();
$scope.calculateNumLines();
// if we're scrolled to the bottom, scroll down to the same position after the resize
// most common use case: opening the keyboard on a mobile device
2014-09-23 02:08:27 +02:00
if ($rootScope.bufferBottom) {
var rescroll = function(){
$rootScope.updateBufferBottom(true);
};
$timeout(rescroll, 500);
window.requestAnimationFrame(rescroll);
}
}
}, 100));
2014-02-10 19:43:52 +01:00
$rootScope.loadingLines = false;
$scope.fetchMoreLines = function(numLines) {
if (!numLines) {
2014-06-27 04:36:30 +02:00
numLines = $scope.lines_per_screen;
}
return connection.fetchMoreLines(numLines);
2014-02-10 20:32:00 +01:00
};
2014-02-10 19:43:52 +01:00
2014-09-23 02:08:27 +02:00
$rootScope.updateBufferBottom = function(bottom) {
var eob = document.getElementById("end-of-buffer");
var bl = document.getElementById('bufferlines');
if (bottom) {
eob.scrollIntoView();
}
$rootScope.bufferBottom = eob.offsetTop <= bl.scrollTop + bl.clientHeight;
};
$rootScope.scrollWithBuffer = function(scrollToReadmarker, moreLines) {
2013-12-28 16:50:31 +01:00
// First, get scrolling status *before* modification
// This is required to determine where we were in the buffer pre-change
var bl = document.getElementById('bufferlines');
var sVal = bl.scrollHeight - bl.clientHeight;
var scroll = function() {
2013-12-09 11:10:11 +01:00
var sTop = bl.scrollTop;
2013-12-28 16:50:31 +01:00
// Determine if we want to scroll at all
2014-02-05 11:19:54 +01:00
// Give the check 3 pixels of slack so you don't have to hit
// the exact spot. This fixes a bug in some browsers
if (((scrollToReadmarker || moreLines) && sTop < sVal) || (Math.abs(sTop - sVal) < 3)) {
var readmarker = document.querySelector(".readmarker");
if (scrollToReadmarker && readmarker) {
2013-12-28 16:50:31 +01:00
// Switching channels, scroll to read marker
bl.scrollTop = readmarker.offsetTop - readmarker.parentElement.scrollHeight + readmarker.scrollHeight;
} else if (moreLines) {
// We fetched more lines but the read marker is still out of view
// Keep the scroll position constant
bl.scrollTop = bl.scrollHeight - bl.clientHeight - sVal;
2013-12-28 16:50:31 +01:00
} else {
// New message, scroll with buffer (i.e. to bottom)
2014-09-23 02:08:27 +02:00
var eob = document.getElementById("end-of-buffer");
eob.scrollIntoView();
}
2014-09-23 02:08:27 +02:00
$rootScope.updateBufferBottom();
2013-10-11 18:45:01 +02:00
}
2013-12-16 14:09:01 +01:00
};
// Here be scrolling dragons
$timeout(scroll);
2014-09-23 02:08:27 +02:00
window.requestAnimationFrame(scroll);
2013-12-16 14:09:01 +01:00
};
2013-10-07 16:58:41 +02:00
2013-02-16 19:18:14 +01:00
2013-02-18 00:49:42 +01:00
$scope.connect = function() {
2014-08-28 18:25:40 +02:00
notifications.requestNotificationPermission();
2014-04-22 19:03:12 +02:00
$rootScope.sslError = false;
2014-05-06 21:48:40 +02:00
$rootScope.securityError = false;
2014-04-22 19:03:12 +02:00
$rootScope.errorMessage = false;
2014-09-23 02:08:27 +02:00
$rootScope.bufferBottom = true;
$scope.connectbutton = 'Connecting';
$scope.connectbuttonicon = 'glyphicon-refresh glyphicon-spin';
2014-12-22 22:17:01 +01:00
connection.connect(settings.host, settings.port, $scope.password, settings.ssl);
2013-12-16 14:09:01 +01:00
};
2013-10-16 14:44:44 +02:00
$scope.disconnect = function() {
$scope.connectbutton = 'Connect';
$scope.connectbuttonicon = 'glyphicon-chevron-right';
2013-10-16 14:25:07 +02:00
connection.disconnect();
2013-12-16 14:09:01 +01:00
};
$scope.reconnect = function() {
var bufferId = models.getActiveBuffer().id;
connection.attemptReconnect(bufferId, 3000);
};
2014-08-28 18:25:40 +02:00
//XXX this is a bit out of place here, either move up to the rest of the firefox install code or remove
2013-10-21 15:51:05 +02:00
$scope.install = function() {
if (navigator.mozApps !== undefined) {
// Find absolute url with trailing '/' or '/index.html' removed
var base_url = location.protocol + '//' + location.host +
location.pathname.replace(/\/(index\.html)?$/, '');
var request = navigator.mozApps.install(base_url + '/manifest.webapp');
2013-10-21 15:51:05 +02:00
request.onsuccess = function () {
$scope.isinstalled = true;
// Save the App object that is returned
var appRecord = this.result;
// Start the app.
appRecord.launch();
alert('Installation successful!');
};
request.onerror = function () {
// Display the error information from the DOMError object
alert('Install failed, error: ' + this.error.name);
};
} else {
2013-10-21 15:51:05 +02:00
alert('Sorry. Only supported in Firefox v26+');
}
2013-12-16 14:09:01 +01:00
};
2013-10-21 15:51:05 +02:00
2014-07-06 16:05:48 +02:00
$scope.showModal = function(elementId) {
document.getElementById(elementId).setAttribute('data-state', 'visible');
};
$scope.closeModal = function($event) {
function closest(elem, selector) {
var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector;
while (elem) {
if (matchesSelector.call(elem, selector)) return elem;
else elem = elem.parentElement;
}
}
closest($event.target, '.gb-modal').setAttribute('data-state', 'hidden');
};
$scope.toggleAccordion = function(event) {
event.stopPropagation();
event.preventDefault();
var target = event.target.parentNode.parentNode.parentNode;
target.setAttribute('data-state', target.getAttribute('data-state') === 'active' ? 'collapsed' : 'active');
// Hide all other siblings
var siblings = target.parentNode.children;
for (var childId in siblings) {
var child = siblings[childId];
if (child.nodeType === 1 && child !== target) {
child.setAttribute('data-state', 'collapsed');
}
}
};
2013-10-06 12:34:41 +02:00
2014-08-28 18:25:40 +02:00
//XXX what do we do with this?
$scope.hasUnread = function(buffer) {
2013-12-17 21:30:22 +01:00
// if search is set, return every buffer
if ($scope.search && $scope.search !== "") {
2013-10-11 23:47:47 +02:00
return true;
}
2014-12-22 22:17:01 +01:00
if (settings.onlyUnread) {
// Always show current buffer in list
2014-02-08 14:20:33 +01:00
if (models.getActiveBuffer() === buffer) {
return true;
}
// Always show core buffer in the list (issue #438)
// Also show server buffers in hierarchical view
if (buffer.fullName === "core.weechat" || (settings.orderbyserver && buffer.type === 'server')) {
return true;
}
return (buffer.unread > 0 || buffer.notification > 0) && !buffer.hidden;
}
return !buffer.hidden;
};
2013-10-11 15:59:55 +02:00
// Watch model and update show setting when it changes
2014-12-22 22:17:01 +01:00
settings.addCallback('nonicklist', function() {
$scope.showNicklist = $scope.updateShowNicklist();
2014-09-23 02:08:27 +02:00
// restore bottom view
if ($rootScope.connected && $rootScope.bufferBottom) {
$timeout(function(){
$rootScope.updateBufferBottom(true);
}, 500);
}
});
$scope.showNicklist = false;
2013-12-17 21:30:22 +01:00
// Utility function that template can use to check if nicklist should
// be displayed for current buffer or not
// is called on buffer switch
$scope.updateShowNicklist = function() {
var ab = models.getActiveBuffer();
if (!ab) {
return false;
}
// Check if option no nicklist is set
2014-12-22 22:17:01 +01:00
if (settings.nonicklist) {
return false;
}
// Check if nicklist is empty
if (ab.isNicklistEmpty()) {
return false;
}
return true;
2013-12-16 14:09:01 +01:00
};
2014-08-28 18:25:40 +02:00
//XXX not sure whether this belongs here
2013-10-11 15:59:55 +02:00
$rootScope.switchToActivityBuffer = function() {
// Find next buffer with activity and switch to it
var sortedBuffers = _.sortBy($scope.getBuffers(), 'number');
var i, buffer;
2014-02-18 19:13:23 +01:00
// Try to find buffer with notification
for (i in sortedBuffers) {
buffer = sortedBuffers[i];
if (buffer.notification > 0) {
2013-10-11 15:59:55 +02:00
$scope.setActiveBuffer(buffer.id);
return; // return instead of break so that the second for loop isn't executed
}
}
2014-02-18 19:13:23 +01:00
// No notifications, find first buffer with unread lines instead
for (i in sortedBuffers) {
buffer = sortedBuffers[i];
2014-02-18 19:13:23 +01:00
if (buffer.unread > 0) {
2013-10-11 15:59:55 +02:00
$scope.setActiveBuffer(buffer.id);
return;
2013-10-11 15:59:55 +02:00
}
2013-10-11 22:43:01 +02:00
}
2013-12-16 14:09:01 +01:00
};
2014-02-28 00:31:32 +01:00
// Helper function since the keypress handler is in a different scope
$rootScope.toggleNicklist = function() {
2014-12-22 22:17:01 +01:00
settings.nonicklist = !settings.nonicklist;
2014-02-28 03:25:59 +01:00
};
2013-10-11 15:59:55 +02:00
$rootScope.switchToAdjacentBuffer = function(direction) {
// direction is +1 for next buffer, -1 for previous buffer
var sortedBuffers = _.sortBy($scope.getBuffers(), $rootScope.predicate);
var activeBuffer = models.getActiveBuffer();
var index = sortedBuffers.indexOf(activeBuffer);
if (index >= 0) {
var newBuffer = sortedBuffers[index + direction];
if (newBuffer) {
$scope.setActiveBuffer(newBuffer.id);
}
}
};
2013-10-17 13:13:01 +02:00
$scope.handleSearchBoxKey = function($event) {
// Support different browser quirks
var code = $event.keyCode ? $event.keyCode : $event.charCode;
// Handle escape
2014-02-08 14:20:33 +01:00
if (code === 27) {
$event.preventDefault();
$scope.search = '';
2013-10-17 13:13:01 +02:00
} // Handle enter
2014-02-08 14:20:33 +01:00
else if (code === 13) {
$event.preventDefault();
if ($scope.filteredBuffers.length > 0) {
$scope.setActiveBuffer($scope.filteredBuffers[0].id);
}
$scope.search = '';
2013-10-17 13:13:01 +02:00
}
2013-12-16 14:09:01 +01:00
};
2013-10-15 15:21:13 +02:00
// Prevent user from accidentally leaving the page
window.onbeforeunload = function(event) {
if ($scope.command !== null && $scope.command !== '') {
event.preventDefault();
// Chrome requires this
// Firefox does not show the site provides message
event.returnValue = "Any unsent input will be lost. Are you sure that you want to quit?";
} else {
if ($rootScope.connected) {
$scope.disconnect();
}
$scope.favico.reset();
}
};
$scope.init = function() {
if (window.location.hash) {
var rawStr = atob(window.location.hash.substring(1));
window.location.hash = "";
var spl = rawStr.split(":");
var host = spl[0];
var port = parseInt(spl[1]);
var password = spl[2];
var ssl = spl.length > 3;
notifications.requestNotificationPermission();
$rootScope.sslError = false;
$rootScope.securityError = false;
$rootScope.errorMessage = false;
$rootScope.bufferBottom = true;
$scope.connectbutton = 'Connecting';
$scope.connectbuttonicon = 'glyphicon-chevron-right';
connection.connect(host, port, password, ssl);
}
};
2014-08-28 18:25:40 +02:00
}]);
2013-10-27 20:49:51 +01:00
2013-12-17 21:30:22 +01:00
weechat.config(['$routeProvider',
2013-10-27 20:49:51 +01:00
function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'index.html',
controller: 'WeechatCtrl'
2013-10-27 20:49:51 +01:00
});
}
]);
})();