Caret/background.js
Thomas Wilburn 2c34939a43 Open a new window if a command is received while inactive.
Commands will be buffered and passed in to be fired on initialization.
To suppress app launch, add the quiet flag to your command when firing
the message from an extension.
Fixes #122
2014-01-10 22:15:35 -08:00

71 lines
No EOL
1.9 KiB
JavaScript

var mainWindow = null;
var pending = null;
var upgrading = false;
var files = [];
var commands = [];
var openWindow = function() {
//if window exists, re-use it
if (mainWindow) {
mainWindow.contentWindow.launchData = files;
mainWindow.contentWindow.require(["command"], function(c) {
c.fire("session:open-launch");
});
mainWindow.focus();
mainWindow.drawAttention();
files = [];
pending = null;
return;
}
//otherwise, open a new window
var defaults = {
width: 800,
height: 600,
left: 50,
top: 50
};
chrome.app.window.create("main.html", {
bounds: defaults,
id: "caret:main"
}, function(win) {
mainWindow = win;
win.contentWindow.launchData = files;
win.contentWindow.launchCommands = commands;
mainWindow.onClosed.addListener(function() {
mainWindow = null;
});
files = [];
commands = [];
pending = null;
});
}
var launch = function(launchData) {
if (launchData && launchData.items) files.push.apply(files, launchData.items);
//we delay opening the actual window to give multiple file events time to fire
if (pending !== null) return;
if (upgrading) return;
pending = setTimeout(openWindow, 250);
};
var onMessage = function(message, sender, sendResponse) {
//main window will pick up the message, if it's open
//we also allow extensions to suppress launch behavior for spurious messages
if (mainWindow || message.quiet) return;
commands.push({
message: message,
sender: sender,
sendResponse: sendResponse
});
if (pending !== null) return;
if (upgrading) return;
pending = setTimeout(openWindow, 250);
};
chrome.app.runtime.onLaunched.addListener(launch);
chrome.app.runtime.onRestarted.addListener(launch);
chrome.runtime.onMessageExternal.addListener(onMessage);