Skip to content

Instantly share code, notes, and snippets.

@systemfreund
Last active December 27, 2015 14:39
Show Gist options
  • Save systemfreund/7341820 to your computer and use it in GitHub Desktop.
Save systemfreund/7341820 to your computer and use it in GitHub Desktop.
Use this in a .slate.js configuration to cycle through a list of applications.
// Usage:
//
// slate.bind("1:cmd;alt", Cycler(["Safari", "Google Chrome", "Firefox"]));
//
var Cycler = (function() {
function Cycler(appNames, cycleWindows) {
this.appNames = appNames;
this.cycleWindows = cycleWindows;
this.lastIndex = -1;
var that = this;
this.callback = function(win) {
var apps = getApps(that.appNames);
if (apps.length === 0) { return; }
if (anyHasFocus(apps)) {
that.lastIndex = cycle(that.lastIndex, apps);
} else {
if (that.lastIndex === -1) { that.lastIndex = 0; }
var toFocus = apps[that.lastIndex];
if (toFocus !== undefined) {
focusApp(toFocus);
}
}
};
}
function getApps(names) {
var apps = [];
slate.eachApp(function(app) {
if (_.contains(names, app.name())) {
apps.push(app);
}
});
return _.sortBy(apps, function(app) { return app.pid(); });
}
function anyHasFocus(apps) {
var focusedApp = slate.app();
return _.some(apps, function(app) {
return focusedApp.pid() === app.pid();
});
}
function cycle(lastIndex, apps) {
var newIndex = (lastIndex + 1) % apps.length;
var appToFocus = apps[newIndex];
slate.log("appToFocus: " + appToFocus.name());
// cycle again if the current app in focus is already the app which was going to be focused
if (slate.app().pid() === appToFocus.pid() && apps.length > 1) {
slate.log("cycle again");
return cycle(newIndex, apps);
}
focusApp(appToFocus);
return newIndex;
}
function focusApp(app) {
var main = app.mainWindow();
if (main !== null) {
main.focus();
}
}
return function(appNames, cycleWindows) {
return new Cycler(appNames, cycleWindows).callback;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment