New eventMgr

This commit is contained in:
benweet 2013-07-30 09:46:36 +01:00
parent 42b2002826
commit d9e47ff539
31 changed files with 428 additions and 409 deletions

View File

@ -2,10 +2,10 @@ define([
"underscore", "underscore",
"core", "core",
"utils", "utils",
"extensionMgr", "eventMgr",
"config", "config",
"libs/stacktrace", "libs/stacktrace",
], function(_, core, utils, extensionMgr) { ], function(_, core, utils, eventMgr) {
var taskQueue = []; var taskQueue = [];
@ -85,7 +85,7 @@ define([
} }
error = error || new Error("Unknown error"); error = error || new Error("Unknown error");
if(error.message) { if(error.message) {
extensionMgr.onError(error); eventMgr.onError(error);
} }
runSafe(this, this.errorCallbacks, error); runSafe(this, this.errorCallbacks, error);
// Exit the current call stack // Exit the current call stack
@ -156,7 +156,7 @@ define([
currentTaskStartTime = utils.currentTime; currentTaskStartTime = utils.currentTime;
if(asyncRunning === false) { if(asyncRunning === false) {
asyncRunning = true; asyncRunning = true;
extensionMgr.onAsyncRunning(true); eventMgr.onAsyncRunning(true);
} }
} }
@ -185,7 +185,7 @@ define([
} }
if(taskQueue.length === 0) { if(taskQueue.length === 0) {
asyncRunning = false; asyncRunning = false;
extensionMgr.onAsyncRunning(false); eventMgr.onAsyncRunning(false);
} }
else { else {
runTask(); runTask();

View File

@ -3,7 +3,7 @@ define([
"underscore", "underscore",
"utils", "utils",
"settings", "settings",
"extensionMgr", "eventMgr",
"mousetrap", "mousetrap",
"text!html/settingsTemplateTooltip.html", "text!html/settingsTemplateTooltip.html",
"text!html/settingsUserCustomExtensionTooltip.html", "text!html/settingsUserCustomExtensionTooltip.html",
@ -12,14 +12,14 @@ define([
"libs/bootstrap", "libs/bootstrap",
"libs/layout", "libs/layout",
"libs/Markdown.Editor" "libs/Markdown.Editor"
], function($, _, utils, settings, extensionMgr, mousetrap, settingsTemplateTooltipHTML, settingsUserCustomExtensionTooltipHTML) { ], function($, _, utils, settings, eventMgr, mousetrap, settingsTemplateTooltipHTML, settingsUserCustomExtensionTooltipHTML) {
var core = {}; var core = {};
// Used for periodic tasks // Used for periodic tasks
var intervalId = undefined; var intervalId = undefined;
var periodicCallbacks = [ var periodicCallbacks = [
extensionMgr.onPeriodicRun eventMgr.onPeriodicRun
]; ];
core.runPeriodically = function(callback) { core.runPeriodically = function(callback) {
periodicCallbacks.push(callback); periodicCallbacks.push(callback);
@ -74,13 +74,13 @@ define([
offlineTime = utils.currentTime; offlineTime = utils.currentTime;
if(core.isOffline === false) { if(core.isOffline === false) {
core.isOffline = true; core.isOffline = true;
extensionMgr.onOfflineChanged(true); eventMgr.onOfflineChanged(true);
} }
}; };
function setOnline() { function setOnline() {
if(core.isOffline === true) { if(core.isOffline === true) {
core.isOffline = false; core.isOffline = false;
extensionMgr.onOfflineChanged(false); eventMgr.onOfflineChanged(false);
} }
} }
function checkOnline() { function checkOnline() {
@ -121,7 +121,7 @@ define([
utils.setInputValue("#input-settings-ssh-proxy", settings.sshProxy); utils.setInputValue("#input-settings-ssh-proxy", settings.sshProxy);
// Load extension settings // Load extension settings
extensionMgr.onLoadSettings(); eventMgr.onLoadSettings();
} }
// Save settings from settings dialog // Save settings from settings dialog
@ -149,7 +149,7 @@ define([
// Save extension settings // Save extension settings
newSettings.extensionSettings = {}; newSettings.extensionSettings = {};
extensionMgr.onSaveSettings(newSettings.extensionSettings, event); eventMgr.onSaveSettings(newSettings.extensionSettings, event);
if(!event.isPropagationStopped()) { if(!event.isPropagationStopped()) {
$.extend(settings, newSettings); $.extend(settings, newSettings);
@ -178,7 +178,7 @@ define([
center__minWidth: 200, center__minWidth: 200,
center__minHeight: 200 center__minHeight: 200
}; };
extensionMgr.onLayoutConfigure(layoutGlobalConfig); eventMgr.onLayoutConfigure(layoutGlobalConfig);
if(settings.layoutOrientation == "horizontal") { if(settings.layoutOrientation == "horizontal") {
$(".ui-layout-south").remove(); $(".ui-layout-south").remove();
$(".preview-container").html('<div id="extension-preview-buttons"></div><div id="preview-contents"><div id="wmd-preview" class="preview-content"></div></div>'); $(".preview-container").html('<div id="extension-preview-buttons"></div><div id="preview-contents"><div id="wmd-preview" class="preview-content"></div></div>');
@ -204,7 +204,7 @@ define([
$(".ui-layout-toggler-south").addClass("btn").append($("<b>").addClass("caret")); $(".ui-layout-toggler-south").addClass("btn").append($("<b>").addClass("caret"));
$(".ui-layout-toggler-east").addClass("btn").append($("<b>").addClass("caret")); $(".ui-layout-toggler-east").addClass("btn").append($("<b>").addClass("caret"));
extensionMgr.onLayoutCreated(layout); eventMgr.onLayoutCreated(layout);
} }
; ;
@ -214,7 +214,7 @@ define([
var documentContent = undefined; var documentContent = undefined;
core.initEditor = function(fileDescParam) { core.initEditor = function(fileDescParam) {
if(fileDesc !== undefined) { if(fileDesc !== undefined) {
extensionMgr.onFileClosed(fileDesc); eventMgr.onFileClosed(fileDesc);
} }
fileDesc = fileDescParam; fileDesc = fileDescParam;
documentContent = undefined; documentContent = undefined;
@ -224,7 +224,7 @@ define([
if(editor !== undefined) { if(editor !== undefined) {
// If the editor is already created // If the editor is already created
editor.undoManager.reinit(initDocumentContent, fileDesc.editorStart, fileDesc.editorEnd, fileDesc.editorScrollTop); editor.undoManager.reinit(initDocumentContent, fileDesc.editorStart, fileDesc.editorEnd, fileDesc.editorScrollTop);
extensionMgr.onFileOpen(fileDesc); eventMgr.onFileOpen(fileDesc);
editor.refreshPreview(); editor.refreshPreview();
return; return;
} }
@ -268,7 +268,7 @@ define([
}); });
// Last section // Last section
sectionList.push(tmpText.substring(offset, text.length)); sectionList.push(tmpText.substring(offset, text.length));
extensionMgr.onSectionsCreated(sectionList); eventMgr.onSectionsCreated(sectionList);
return text; return text;
}); });
editor = new Markdown.Editor(converter); editor = new Markdown.Editor(converter);
@ -294,7 +294,7 @@ define([
var newDocumentContent = editorElt.val(); var newDocumentContent = editorElt.val();
if(documentContent !== undefined && documentContent != newDocumentContent) { if(documentContent !== undefined && documentContent != newDocumentContent) {
fileDesc.content = newDocumentContent; fileDesc.content = newDocumentContent;
extensionMgr.onContentChanged(fileDesc); eventMgr.onContentChanged(fileDesc);
} }
documentContent = newDocumentContent; documentContent = newDocumentContent;
} }
@ -318,7 +318,7 @@ define([
else { else {
previewWrapper = function(makePreview) { previewWrapper = function(makePreview) {
return function() { return function() {
extensionMgr.previewStartTime = new Date(); eventMgr.previewStartTime = new Date();
makePreview(); makePreview();
if(documentContent === undefined) { if(documentContent === undefined) {
previewContainerElt.scrollTop(fileDesc.previewScrollTop); previewContainerElt.scrollTop(fileDesc.previewScrollTop);
@ -327,8 +327,8 @@ define([
}; };
}; };
} }
extensionMgr.onEditorConfigure(editor); eventMgr.onEditorConfigure(editor);
editor.hooks.chain("onPreviewRefresh", extensionMgr.onAsyncPreview); editor.hooks.chain("onPreviewRefresh", eventMgr.onAsyncPreview);
editor.run(previewWrapper); editor.run(previewWrapper);
editor.undoManager.reinit(initDocumentContent, fileDesc.editorStart, fileDesc.editorEnd, fileDesc.editorScrollTop); editor.undoManager.reinit(initDocumentContent, fileDesc.editorStart, fileDesc.editorEnd, fileDesc.editorScrollTop);
@ -349,7 +349,7 @@ define([
$("#wmd-undo-button").append($('<i class="icon-undo">')); $("#wmd-undo-button").append($('<i class="icon-undo">'));
$("#wmd-redo-button").append($('<i class="icon-share-alt">')); $("#wmd-redo-button").append($('<i class="icon-share-alt">'));
extensionMgr.onFileOpen(fileDesc); eventMgr.onFileOpen(fileDesc);
}; };
// Used to lock the editor from the user interaction during asynchronous tasks // Used to lock the editor from the user interaction during asynchronous tasks
@ -489,7 +489,7 @@ define([
JSON.parse(content); JSON.parse(content);
} }
catch(e) { catch(e) {
extensionMgr.onError(importedFile.name + " is not a valid JSON file."); eventMgr.onError(importedFile.name + " is not a valid JSON file.");
return; return;
} }
localStorage.settings = content; localStorage.settings = content;
@ -561,7 +561,7 @@ define([
} }
}, 1000); }, 1000);
}); });
core.onReady(extensionMgr.onReady); core.onReady(eventMgr.onReady);
// After extensions onReady callbacks // After extensions onReady callbacks
core.onReady(function() { core.onReady(function() {

251
js/eventMgr.js Normal file
View File

@ -0,0 +1,251 @@
define([
"jquery",
"underscore",
"crel",
"utils",
"classes/Extension",
"settings",
"text!html/settingsExtensionsAccordion.html",
"extensions/partialRendering",
"extensions/userCustom",
"extensions/googleAnalytics",
"extensions/dialogAbout",
"extensions/dialogManagePublication",
"extensions/dialogManageSynchronization",
"extensions/dialogOpenHarddrive",
"extensions/documentSelector",
"extensions/documentTitle",
"extensions/workingIndicator",
"extensions/notifications",
"extensions/markdownExtra",
"extensions/toc",
"extensions/mathJax",
"extensions/emailConverter",
"extensions/scrollLink",
"extensions/buttonSync",
"extensions/buttonPublish",
"extensions/buttonShare",
"extensions/buttonStat",
"extensions/buttonHtmlCode",
"extensions/buttonMarkdownSyntax",
"extensions/buttonViewer",
"libs/bootstrap",
"libs/jquery.waitforimages"
], function($, _, crel, utils, Extension, settings, settingsExtensionsAccordionHTML) {
var eventMgr = {};
// Create a list of extensions from module arguments
var extensionList = _.chain(arguments).map(function(argument) {
return argument instanceof Extension && argument;
}).compact().value();
// Configure extensions
extensionSettings = settings.extensionSettings || {};
_.each(extensionList, function(extension) {
// Set the extension.config attribute from settings or default configuration
extension.config = _.extend({}, extension.defaultConfig, extensionSettings[extension.extensionId]);
// Skip enabling the extension if we are in the viewer and extension doesn't support it
if(viewerMode === true && extension.disableInViewer) {
return;
}
// Enable the extension if it's not optional or it has not been disabled by the user
extension.config.enabled = !extension.isOptional || extension.config.enabled === undefined || extension.config.enabled === true;
});
// Returns all listeners with the specified name that are implemented in the enabled extensions
function getExtensionListenerList(eventName) {
return _.chain(extensionList).map(function(extension) {
return extension.config.enabled && extension[eventName];
}).compact().value();
}
// Returns a function that calls every listeners with the specified name from all enabled extensions
var eventListenerListMap = {};
function createEventHook(eventName) {
eventListenerListMap[eventName] = getExtensionListenerList(eventName);
return function() {
logger.log(eventName, arguments);
var eventArguments = arguments;
_.each(eventListenerListMap[eventName], function(listener) {
// Use try/catch in case userCustom listener contains error
try {
listener.apply(null, eventArguments);
}
catch(e) {
console.error(e);
}
});
};
}
// Add a Hook to the eventMgr that we can fire using eventMgr.eventName()
function addEventHook(eventName) {
eventMgr[eventName] = createEventHook(eventName);
}
// Used by external modules (not extensions) to listen to events
eventMgr.addListener = function(eventName, listener) {
try {
eventListenerListMap[eventName].push(listener);
} catch(e) {
console.error('No event listener called ' + eventName);
}
};
// Call every onInit listeners (extensions only)
createEventHook("onInit")();
// Load/Save extension config from/to settings
eventMgr["onLoadSettings"] = function() {
logger.log("onLoadSettings");
_.each(extensionList, function(extension) {
utils.setInputChecked("#input-enable-extension-" + extension.extensionId, extension.config.enabled);
var onLoadSettingsListener = extension.onLoadSettings;
onLoadSettingsListener && onLoadSettingsListener();
});
};
eventMgr["onSaveSettings"] = function(newExtensionSettings, event) {
logger.log("onSaveSettings");
_.each(extensionList, function(extension) {
var newExtensionConfig = _.extend({}, extension.defaultConfig);
newExtensionConfig.enabled = utils.getInputChecked("#input-enable-extension-" + extension.extensionId);
var onSaveSettingsListener = extension.onSaveSettings;
onSaveSettingsListener && onSaveSettingsListener(newExtensionConfig, event);
newExtensionSettings[extension.extensionId] = newExtensionConfig;
});
};
addEventHook("onMessage");
addEventHook("onError");
addEventHook("onOfflineChanged");
addEventHook("onAsyncRunning", true);
addEventHook("onPeriodicRun", true);
// To access modules that are loaded after extensions
addEventHook("onFileMgrCreated");
addEventHook("onSynchronizerCreated");
addEventHook("onPublisherCreated");
addEventHook("onEventMgrCreated");
// Operations on files
addEventHook("onFileCreated");
addEventHook("onFileDeleted");
addEventHook("onFileSelected");
addEventHook("onFileOpen");
addEventHook("onFileClosed");
addEventHook("onContentChanged");
addEventHook("onTitleChanged");
// Sync events
addEventHook("onSyncRunning");
addEventHook("onSyncSuccess");
addEventHook("onSyncImportSuccess");
addEventHook("onSyncExportSuccess");
addEventHook("onSyncRemoved");
// Publish events
addEventHook("onPublishRunning");
addEventHook("onPublishSuccess");
addEventHook("onNewPublishSuccess");
addEventHook("onPublishRemoved");
// Operations on Layout
addEventHook("onLayoutConfigure");
addEventHook("onLayoutCreated");
// Operations on PageDown
addEventHook("onEditorConfigure");
addEventHook("onSectionsCreated");
var onPreviewFinished = createEventHook("onPreviewFinished");
var onAsyncPreviewListenerList = getExtensionListenerList("onAsyncPreview");
// The number of times we expect tryFinished to be called
var nbAsyncPreviewListener = onAsyncPreviewListenerList.length + 1;
var previewContentsElt = undefined;
var previewContentsJQElt = undefined;
eventMgr["onAsyncPreview"] = function() {
logger.log("onAsyncPreview");
logger.log("Conversion time: " + (new Date() - eventMgr.previewStartTime));
// Call onPreviewFinished listeners when all async preview are finished
var counter = 0;
function tryFinished() {
if(++counter === nbAsyncPreviewListener) {
logger.log("Preview time: " + (new Date() - eventMgr.previewStartTime));
_.defer(function() {
var html = "";
_.each(previewContentsElt.children, function(elt) {
html += elt.innerHTML;
});
onPreviewFinished(utils.trim(html));
});
}
}
// We assume images are loading in the preview
previewContentsJQElt.waitForImages(tryFinished);
_.each(onAsyncPreviewListenerList, function(asyncPreviewListener) {
asyncPreviewListener(tryFinished);
});
};
var onReady = createEventHook("onReady");
eventMgr["onReady"] = function() {
previewContentsElt = document.getElementById('preview-contents');
previewContentsJQElt = $(previewContentsElt);
if(viewerMode === false) {
// Create accordion in settings dialog
var accordionHtml = _.chain(extensionList).sortBy(function(extension) {
return extension.extensionName.toLowerCase();
}).reduce(function(html, extension) {
return html + _.template(settingsExtensionsAccordionHTML, {
extensionId: extension.extensionId,
extensionName: extension.extensionName,
isOptional: extension.isOptional,
settingsBlock: extension.settingsBlock
});
}, "").value();
document.getElementById('accordion-extensions').innerHTML = accordionHtml;
// Create a button from an extension listener
function createBtn(listener) {
var buttonGrpElt = crel('div', {
class: 'btn-group'
});
var btnElt = listener();
if(_.isString(btnElt)) {
buttonGrpElt.innerHTML = btnElt;
}
else if(_.isElement(btnElt)) {
buttonGrpElt.appendChild(btnElt);
}
return buttonGrpElt;
}
// Create extension buttons
logger.log("onCreateButton");
var onCreateButtonListenerList = getExtensionListenerList("onCreateButton");
var extensionButtonsFragment = document.createDocumentFragment();
_.each(onCreateButtonListenerList, function(listener) {
extensionButtonsFragment.appendChild(createBtn(listener));
});
document.getElementById('extension-buttons').appendChild(extensionButtonsFragment);
// Create extension preview buttons
logger.log("onCreatePreviewButton");
var onCreatePreviewButtonListenerList = getExtensionListenerList("onCreatePreviewButton");
var extensionPreviewButtonsFragment = document.createDocumentFragment();
_.each(onCreatePreviewButtonListenerList, function(listener) {
extensionPreviewButtonsFragment.appendChild(createBtn(listener));
});
document.getElementById('extension-preview-buttons').appendChild(extensionPreviewButtonsFragment);
}
// Call onReady listeners
onReady();
};
// For extensions that need to call other extensions
eventMgr.onEventMgrCreated(eventMgr);
return eventMgr;
});

View File

@ -1,225 +0,0 @@
define([
"jquery",
"underscore",
"utils",
"classes/Extension",
"settings",
"text!html/settingsExtensionsAccordion.html",
"extensions/partialRendering",
"extensions/userCustom",
"extensions/googleAnalytics",
"extensions/dialogAbout",
"extensions/dialogManagePublication",
"extensions/dialogManageSynchronization",
"extensions/dialogOpenHarddrive",
"extensions/documentSelector",
"extensions/documentTitle",
"extensions/workingIndicator",
"extensions/notifications",
"extensions/markdownExtra",
"extensions/toc",
"extensions/mathJax",
"extensions/emailConverter",
"extensions/scrollLink",
"extensions/buttonSync",
"extensions/buttonPublish",
"extensions/buttonShare",
"extensions/buttonStat",
"extensions/buttonHtmlCode",
"extensions/buttonMarkdownSyntax",
"extensions/buttonViewer",
"libs/bootstrap",
"libs/jquery.waitforimages"
], function($, _, utils, Extension, settings, settingsExtensionsAccordionHTML) {
var extensionMgr = {};
// Create a list of extensions
var extensionList = _.chain(arguments).map(function(argument) {
return argument instanceof Extension && argument;
}).compact().value();
// Returns all callbacks with the specified name that are implemented in extensions
function getExtensionCallbackList(hookName) {
return _.chain(extensionList).map(function(extension) {
return extension.config.enabled && extension[hookName];
}).compact().value();
}
// Return a function that calls every callbacks with the specified name from all extensions
var hookCallbackList = {};
function createHook(hookName, noLog) {
hookCallbackList[hookName] = getExtensionCallbackList(hookName);
return function() {
if(!noLog) {
logger.log(hookName, arguments);
}
var callbackArguments = arguments;
_.each(hookCallbackList[hookName], function(callback) {
// In case user custom callback contains error
try {
callback.apply(null, callbackArguments);
}
catch(e) {
console.error(e);
}
});
};
}
// Add a Hook to the extensionMgr
function addHook(hookName, noLog) {
extensionMgr[hookName] = createHook(hookName, noLog);
}
// Used by external modules to listen to extension events
extensionMgr.addHookCallback = function(hookName, callback) {
hookCallbackList[hookName].push(callback);
};
// Set extension config
extensionSettings = settings.extensionSettings || {};
_.each(extensionList, function(extension) {
extension.config = _.extend({}, extension.defaultConfig, extensionSettings[extension.extensionId]);
extension.config.enabled = !extension.isOptional || extension.config.enabled === undefined || extension.config.enabled === true;
if(viewerMode === true && extension.disableInViewer) {
extension.config.enabled = false;
}
});
// Call every onInit callbacks
createHook("onInit")();
// Load/Save extension config from/to settings
extensionMgr["onLoadSettings"] = function() {
logger.log("onLoadSettings");
_.each(extensionList, function(extension) {
utils.setInputChecked("#input-enable-extension-" + extension.extensionId, extension.config.enabled);
var onLoadSettingsCallback = extension.onLoadSettings;
onLoadSettingsCallback && onLoadSettingsCallback();
});
};
extensionMgr["onSaveSettings"] = function(newExtensionSettings, event) {
logger.log("onSaveSettings");
_.each(extensionList, function(extension) {
var newExtensionConfig = _.extend({}, extension.defaultConfig);
newExtensionConfig.enabled = utils.getInputChecked("#input-enable-extension-" + extension.extensionId);
var onSaveSettingsCallback = extension.onSaveSettings;
onSaveSettingsCallback && onSaveSettingsCallback(newExtensionConfig, event);
newExtensionSettings[extension.extensionId] = newExtensionConfig;
});
};
addHook("onMessage");
addHook("onError");
addHook("onOfflineChanged");
addHook("onAsyncRunning", true);
addHook("onPeriodicRun", true);
// To access modules that are loaded after extensions
addHook("onFileMgrCreated");
addHook("onSynchronizerCreated");
addHook("onPublisherCreated");
addHook("onExtensionMgrCreated");
// Operations on files
addHook("onFileCreated");
addHook("onFileDeleted");
addHook("onFileSelected");
addHook("onFileOpen");
addHook("onFileClosed");
addHook("onContentChanged");
addHook("onTitleChanged");
// Sync events
addHook("onSyncRunning");
addHook("onSyncSuccess");
addHook("onSyncImportSuccess");
addHook("onSyncExportSuccess");
addHook("onSyncRemoved");
// Publish events
addHook("onPublishRunning");
addHook("onPublishSuccess");
addHook("onNewPublishSuccess");
addHook("onPublishRemoved");
// Operations on Layout
addHook("onLayoutConfigure");
addHook("onLayoutCreated");
// Operations on PageDown
addHook("onEditorConfigure");
addHook("onSectionsCreated");
var onPreviewFinished = createHook("onPreviewFinished");
var onAsyncPreviewCallbackList = getExtensionCallbackList("onAsyncPreview");
// The number of times we expect tryFinished to be called
var nbAsyncPreviewCallback = onAsyncPreviewCallbackList.length + 1;
var previewContentsElt = undefined;
var previewContentsJQElt = undefined;
extensionMgr["onAsyncPreview"] = function() {
logger.log("onAsyncPreview");
logger.log("Conversion time: " + (new Date() - extensionMgr.previewStartTime));
// Call onPreviewFinished callbacks when all async preview are finished
var counter = 0;
function tryFinished() {
if(++counter === nbAsyncPreviewCallback) {
logger.log("Preview time: " + (new Date() - extensionMgr.previewStartTime));
_.defer(function() {
var html = "";
_.each(previewContentsElt.children, function(elt) {
html += elt.innerHTML;
});
onPreviewFinished(utils.trim(html));
});
}
}
// We assume images are loading in the preview
previewContentsJQElt.waitForImages(tryFinished);
_.each(onAsyncPreviewCallbackList, function(asyncPreviewCallback) {
asyncPreviewCallback(tryFinished);
});
};
function createSettings(extension) {
$("#accordion-extensions").append($(_.template(settingsExtensionsAccordionHTML, {
extensionId: extension.extensionId,
extensionName: extension.extensionName,
isOptional: extension.isOptional,
settingsBlock: extension.settingsBlock
})));
}
extensionMgr["onReady"] = function() {
previewContentsElt = document.getElementById('preview-contents');
previewContentsJQElt = $(previewContentsElt);
// Create accordion in settings dialog
_.chain(extensionList).sortBy(function(extension) {
return extension.extensionName.toLowerCase();
}).each(createSettings);
// Create extension buttons
logger.log("onCreateButton");
var onCreateButtonCallbackList = getExtensionCallbackList("onCreateButton");
_.each(onCreateButtonCallbackList, function(callback) {
$("#extension-buttons").append($('<div class="btn-group">').append(callback()));
});
// Create extension preview buttons
logger.log("onCreatePreviewButton");
var onCreatePreviewButtonCallbackList = getExtensionCallbackList("onCreatePreviewButton");
_.each(onCreatePreviewButtonCallbackList, function(callback) {
$("#extension-preview-buttons").append($('<div class="btn-group">').append(callback()));
});
// Call extensions onReady callbacks
var onReady = createHook("onReady");
onReady();
};
// For extensions that need to call other extensions
extensionMgr.onExtensionMgrCreated(extensionMgr);
return extensionMgr;
});

View File

@ -21,13 +21,13 @@ define([
newConfig.template = utils.getInputValue("#textarea-html-code-template"); newConfig.template = utils.getInputValue("#textarea-html-code-template");
}; };
var extensionMgr = undefined; var eventMgr = undefined;
buttonHtmlCode.onExtensionMgrCreated = function(extensionMgrParameter) { buttonHtmlCode.onEventMgrCreated = function(eventMgrParameter) {
extensionMgr = extensionMgrParameter; eventMgr = eventMgrParameter;
}; };
buttonHtmlCode.onCreatePreviewButton = function() { buttonHtmlCode.onCreatePreviewButton = function() {
return $(buttonHtmlCodeHTML); return buttonHtmlCodeHTML;
}; };
var selectedFileDesc = undefined; var selectedFileDesc = undefined;
@ -46,7 +46,7 @@ define([
textareaElt.value = htmlCode; textareaElt.value = htmlCode;
} }
catch(e) { catch(e) {
extensionMgr.onError(e); eventMgr.onError(e);
return e.message; return e.message;
} }
}; };

View File

@ -8,7 +8,7 @@ define([
buttonMarkdownSyntax.settingsBlock = '<p>Adds a "Markdown syntax" button over the preview.</p>'; buttonMarkdownSyntax.settingsBlock = '<p>Adds a "Markdown syntax" button over the preview.</p>';
buttonMarkdownSyntax.onCreatePreviewButton = function() { buttonMarkdownSyntax.onCreatePreviewButton = function() {
return $(buttonMarkdownSyntaxHTML); return buttonMarkdownSyntaxHTML;
}; };
return buttonMarkdownSyntax; return buttonMarkdownSyntax;

View File

@ -38,7 +38,7 @@ define([
publisher.publish(); publisher.publish();
} }
}); });
return button; return button[0];
}; };
buttonPublish.onPublishRunning = function(isRunning) { buttonPublish.onPublishRunning = function(isRunning) {

View File

@ -10,7 +10,7 @@ define([
buttonShare.settingsBlock = '<p>Adds a "Share document" button in the navigation bar.</p>'; buttonShare.settingsBlock = '<p>Adds a "Share document" button in the navigation bar.</p>';
buttonShare.onCreateButton = function() { buttonShare.onCreateButton = function() {
return $(buttonShareHTML); return buttonShareHTML;
}; };
var fileDesc = undefined; var fileDesc = undefined;

View File

@ -41,7 +41,7 @@ define([
}; };
buttonStat.onCreatePreviewButton = function() { buttonStat.onCreatePreviewButton = function() {
return $(_.template(buttonStatHTML, buttonStat.config)); return _.template(buttonStatHTML, buttonStat.config);
}; };
var previewContentsElt = undefined; var previewContentsElt = undefined;

View File

@ -59,7 +59,7 @@ define([
synchronizer.sync(); synchronizer.sync();
} }
}); });
return button; return button[0];
}; };
buttonSync.onReady = updateButtonState; buttonSync.onReady = updateButtonState;

View File

@ -8,7 +8,7 @@ define([
buttonViewer.settingsBlock = '<p>Adds a "Viewer" button over the preview.</p>'; buttonViewer.settingsBlock = '<p>Adds a "Viewer" button over the preview.</p>';
buttonViewer.onCreatePreviewButton = function() { buttonViewer.onCreatePreviewButton = function() {
return $(buttonViewerHTML); return buttonViewerHTML;
}; };
return buttonViewer; return buttonViewer;

View File

@ -8,9 +8,9 @@ define([
var dialogManagePublication = new Extension("dialogManagePublication", 'Dialog "Manage publication"'); var dialogManagePublication = new Extension("dialogManagePublication", 'Dialog "Manage publication"');
dialogManagePublication.settingsBlock = '<p>Populates the "Manage publication" dialog box.</p>'; dialogManagePublication.settingsBlock = '<p>Populates the "Manage publication" dialog box.</p>';
var extensionMgr = undefined; var eventMgr = undefined;
dialogManagePublication.onExtensionMgrCreated = function(extensionMgrParameter) { dialogManagePublication.onEventMgrCreated = function(eventMgrParameter) {
extensionMgr = extensionMgrParameter; eventMgr = eventMgrParameter;
}; };
var fileDesc = undefined; var fileDesc = undefined;
@ -41,7 +41,7 @@ define([
})); }));
lineElement.append($(removeButtonTemplate).click(function() { lineElement.append($(removeButtonTemplate).click(function() {
fileDesc.removePublishLocation(publishAttributes); fileDesc.removePublishLocation(publishAttributes);
extensionMgr.onPublishRemoved(fileDesc, publishAttributes); eventMgr.onPublishRemoved(fileDesc, publishAttributes);
})); }));
publishList.append(lineElement); publishList.append(lineElement);
}); });

View File

@ -8,9 +8,9 @@ define([
var dialogManageSynchronization = new Extension("dialogManageSynchronization", 'Dialog "Manage synchronization"'); var dialogManageSynchronization = new Extension("dialogManageSynchronization", 'Dialog "Manage synchronization"');
dialogManageSynchronization.settingsBlock = '<p>Populates the "Manage synchronization" dialog box.</p>'; dialogManageSynchronization.settingsBlock = '<p>Populates the "Manage synchronization" dialog box.</p>';
var extensionMgr = undefined; var eventMgr = undefined;
dialogManageSynchronization.onExtensionMgrCreated = function(extensionMgrParameter) { dialogManageSynchronization.onEventMgrCreated = function(eventMgrParameter) {
extensionMgr = extensionMgrParameter; eventMgr = eventMgrParameter;
}; };
var synchronizer = undefined; var synchronizer = undefined;
@ -44,7 +44,7 @@ define([
lineElement.append($(removeButtonTemplate).click(function() { lineElement.append($(removeButtonTemplate).click(function() {
synchronizer.tryStopRealtimeSync(); synchronizer.tryStopRealtimeSync();
fileDesc.removeSyncLocation(syncAttributes); fileDesc.removeSyncLocation(syncAttributes);
extensionMgr.onSyncRemoved(fileDesc, syncAttributes); eventMgr.onSyncRemoved(fileDesc, syncAttributes);
})); }));
syncList.append(lineElement); syncList.append(lineElement);
}); });

View File

@ -15,9 +15,9 @@ define([
fileMgr = fileMgrParameter; fileMgr = fileMgrParameter;
}; };
var extensionMgr = undefined; var eventMgr = undefined;
dialogOpenHarddrive.onExtensionMgrCreated = function(extensionMgrParameter) { dialogOpenHarddrive.onEventMgrCreated = function(eventMgrParameter) {
extensionMgr = extensionMgrParameter; eventMgr = eventMgrParameter;
}; };
var contentWrapper = undefined; var contentWrapper = undefined;
@ -39,12 +39,12 @@ define([
return function(e) { return function(e) {
var content = e.target.result; var content = e.target.result;
if(content.match(/\uFFFD/)) { if(content.match(/\uFFFD/)) {
extensionMgr.onError(importedFile.name + " is a binary file."); eventMgr.onError(importedFile.name + " is a binary file.");
return; return;
} }
content = contentWrapper ? contentWrapper(content) : content; content = contentWrapper ? contentWrapper(content) : content;
if(content === undefined) { if(content === undefined) {
extensionMgr.onError(importedFile.name + " is not a valid HTML file."); eventMgr.onError(importedFile.name + " is not a valid HTML file.");
return; return;
} }
var title = importedFile.name; var title = importedFile.name;
@ -96,7 +96,7 @@ define([
} }
content = converter.makeMd(content); content = converter.makeMd(content);
if(content === undefined) { if(content === undefined) {
extensionMgr.onError("Invalid HTML code."); eventMgr.onError("Invalid HTML code.");
return; return;
} }
var fileDesc = fileMgr.createFile(undefined, content); var fileDesc = fileMgr.createFile(undefined, content);

View File

@ -26,7 +26,7 @@ define([
toc.onCreatePreviewButton = function() { toc.onCreatePreviewButton = function() {
if(toc.config.button) { if(toc.config.button) {
return $(buttonTocHTML); return buttonTocHTML;
} }
}; };

View File

@ -29,9 +29,9 @@ define([
publisher = publisherParameter; publisher = publisherParameter;
}; };
var extensionMgr = undefined; var eventMgr = undefined;
userCustom.onExtensionMgrCreated = function(extensionMgrParameter) { userCustom.onEventMgrCreated = function(eventMgrParameter) {
extensionMgr = extensionMgrParameter; eventMgr = eventMgrParameter;
}; };
userCustom.onLoadSettings = function() { userCustom.onLoadSettings = function() {
@ -44,7 +44,7 @@ define([
eval(newConfig.code); eval(newConfig.code);
} }
catch(e) { catch(e) {
extensionMgr.onError(e); eventMgr.onError(e);
// Mark the textarea as error // Mark the textarea as error
utils.getInputTextValue("#textarea-usercustom-code", event, /^$/); utils.getInputTextValue("#textarea-usercustom-code", event, /^$/);
} }

View File

@ -4,11 +4,11 @@ define([
"core", "core",
"utils", "utils",
"settings", "settings",
"extensionMgr", "eventMgr",
"fileSystem", "fileSystem",
"classes/FileDescriptor", "classes/FileDescriptor",
"text!../WELCOME.md" "text!../WELCOME.md"
], function($, _, core, utils, settings, extensionMgr, fileSystem, FileDescriptor, welcomeContent) { ], function($, _, core, utils, settings, eventMgr, fileSystem, FileDescriptor, welcomeContent) {
var fileMgr = {}; var fileMgr = {};
@ -38,7 +38,7 @@ define([
fileDesc.selectTime = new Date().getTime(); fileDesc.selectTime = new Date().getTime();
// Notify extensions // Notify extensions
extensionMgr.onFileSelected(fileDesc); eventMgr.onFileSelected(fileDesc);
// Hide the viewer pencil button // Hide the viewer pencil button
if(fileDesc.fileIndex == TEMPORARY_FILE_INDEX) { if(fileDesc.fileIndex == TEMPORARY_FILE_INDEX) {
@ -93,7 +93,7 @@ define([
if(!isTemporary) { if(!isTemporary) {
utils.appendIndexToArray("file.list", fileIndex); utils.appendIndexToArray("file.list", fileIndex);
fileSystem[fileIndex] = fileDesc; fileSystem[fileIndex] = fileDesc;
extensionMgr.onFileCreated(fileDesc); eventMgr.onFileCreated(fileDesc);
} }
return fileDesc; return fileDesc;
}; };
@ -127,7 +127,7 @@ define([
localStorage.removeItem(fileDesc.fileIndex + ".sync"); localStorage.removeItem(fileDesc.fileIndex + ".sync");
localStorage.removeItem(fileDesc.fileIndex + ".publish"); localStorage.removeItem(fileDesc.fileIndex + ".publish");
extensionMgr.onFileDeleted(fileDesc); eventMgr.onFileDeleted(fileDesc);
}; };
// Get the file descriptor associated to a syncIndex // Get the file descriptor associated to a syncIndex
@ -143,15 +143,6 @@ define([
return fileDesc && fileDesc.syncLocations[syncIndex]; return fileDesc && fileDesc.syncLocations[syncIndex];
}; };
// Returns true if provider has locations to synchronize
fileMgr.hasSync = function(provider) {
return _.some(fileSystem, function(fileDesc) {
return _.some(fileDesc.syncLocations, function(syncAttributes) {
return syncAttributes.provider === provider;
});
});
};
// Get the file descriptor associated to a publishIndex // Get the file descriptor associated to a publishIndex
fileMgr.getFileFromPublishIndex = function(publishIndex) { fileMgr.getFileFromPublishIndex = function(publishIndex) {
return _.find(fileSystem, function(fileDesc) { return _.find(fileSystem, function(fileDesc) {
@ -192,7 +183,7 @@ define([
var fileDesc = fileMgr.currentFile; var fileDesc = fileMgr.currentFile;
if(title && title != fileDesc.title) { if(title && title != fileDesc.title) {
fileDesc.title = title; fileDesc.title = title;
extensionMgr.onTitleChanged(fileDesc); eventMgr.onTitleChanged(fileDesc);
} }
input.val(fileDesc.title); input.val(fileDesc.title);
$("#wmd-input").focus(); $("#wmd-input").focus();
@ -224,6 +215,6 @@ define([
}); });
}); });
extensionMgr.onFileMgrCreated(fileMgr); eventMgr.onFileMgrCreated(fileMgr);
return fileMgr; return fileMgr;
}); });

View File

@ -2,9 +2,9 @@ define([
"jquery", "jquery",
"underscore", "underscore",
"core", "core",
"extensionMgr", "eventMgr",
"classes/AsyncTask" "classes/AsyncTask"
], function($, _, core, extensionMgr, AsyncTask) { ], function($, _, core, eventMgr, AsyncTask) {
var client = undefined; var client = undefined;
var authenticated = false; var authenticated = false;
@ -57,7 +57,7 @@ define([
var immediate = true; var immediate = true;
function localAuthenticate() { function localAuthenticate() {
if(immediate === false) { if(immediate === false) {
extensionMgr.onMessage("Please make sure the Dropbox authorization popup is not blocked by your browser."); eventMgr.onMessage("Please make sure the Dropbox authorization popup is not blocked by your browser.");
// If not immediate we add time for user to enter his // If not immediate we add time for user to enter his
// credentials // credentials
task.timeout = ASYNC_TASK_LONG_TIMEOUT; task.timeout = ASYNC_TASK_LONG_TIMEOUT;
@ -320,7 +320,7 @@ define([
task.chain(); task.chain();
}; };
Dropbox.choose(options); Dropbox.choose(options);
extensionMgr.onMessage("Please make sure the Dropbox chooser popup is not blocked by your browser."); eventMgr.onMessage("Please make sure the Dropbox chooser popup is not blocked by your browser.");
}); });
task.onSuccess(function() { task.onSuccess(function() {
callback(undefined, paths); callback(undefined, paths);

View File

@ -2,9 +2,9 @@ define([
"jquery", "jquery",
"core", "core",
"utils", "utils",
"extensionMgr", "eventMgr",
"classes/AsyncTask" "classes/AsyncTask"
], function($, core, utils, extensionMgr, AsyncTask) { ], function($, core, utils, eventMgr, AsyncTask) {
var connected = undefined; var connected = undefined;
var github = undefined; var github = undefined;
@ -58,7 +58,7 @@ define([
task.chain(); task.chain();
return; return;
} }
extensionMgr.onMessage("Please make sure the Github authorization popup is not blocked by your browser."); eventMgr.onMessage("Please make sure the Github authorization popup is not blocked by your browser.");
var errorMsg = "Failed to retrieve a token from GitHub."; var errorMsg = "Failed to retrieve a token from GitHub.";
// We add time for user to enter his credentials // We add time for user to enter his credentials
task.timeout = ASYNC_TASK_LONG_TIMEOUT; task.timeout = ASYNC_TASK_LONG_TIMEOUT;

View File

@ -2,9 +2,9 @@ define([
"jquery", "jquery",
"core", "core",
"utils", "utils",
"extensionMgr", "eventMgr",
"classes/AsyncTask" "classes/AsyncTask"
], function($, core, utils, extensionMgr, AsyncTask) { ], function($, core, utils, eventMgr, AsyncTask) {
var connected = false; var connected = false;
var authenticated = false; var authenticated = false;
@ -53,7 +53,7 @@ define([
var immediate = true; var immediate = true;
function localAuthenticate() { function localAuthenticate() {
if(immediate === false) { if(immediate === false) {
extensionMgr.onMessage("Please make sure the Google authorization popup is not blocked by your browser."); eventMgr.onMessage("Please make sure the Google authorization popup is not blocked by your browser.");
// If not immediate we add time for user to enter his // If not immediate we add time for user to enter his
// credentials // credentials
task.timeout = ASYNC_TASK_LONG_TIMEOUT; task.timeout = ASYNC_TASK_LONG_TIMEOUT;

View File

@ -2,9 +2,9 @@ define([
"jquery", "jquery",
"core", "core",
"utils", "utils",
"extensionMgr", "eventMgr",
"classes/AsyncTask" "classes/AsyncTask"
], function($, core, utils, extensionMgr, AsyncTask) { ], function($, core, utils, eventMgr, AsyncTask) {
var oauthParams = undefined; var oauthParams = undefined;
@ -36,7 +36,7 @@ define([
task.chain(); task.chain();
return; return;
} }
extensionMgr.onMessage("Please make sure the Tumblr authorization popup is not blocked by your browser."); eventMgr.onMessage("Please make sure the Tumblr authorization popup is not blocked by your browser.");
var errorMsg = "Failed to retrieve a token from Tumblr."; var errorMsg = "Failed to retrieve a token from Tumblr.";
// We add time for user to enter his credentials // We add time for user to enter his credentials
task.timeout = ASYNC_TASK_LONG_TIMEOUT; task.timeout = ASYNC_TASK_LONG_TIMEOUT;

View File

@ -2,9 +2,9 @@ define([
"jquery", "jquery",
"core", "core",
"utils", "utils",
"extensionMgr", "eventMgr",
"classes/AsyncTask" "classes/AsyncTask"
], function($, core, utils, extensionMgr, AsyncTask) { ], function($, core, utils, eventMgr, AsyncTask) {
var token = undefined; var token = undefined;
@ -31,7 +31,7 @@ define([
task.chain(); task.chain();
return; return;
} }
extensionMgr.onMessage("Please make sure the Wordpress authorization popup is not blocked by your browser."); eventMgr.onMessage("Please make sure the Wordpress authorization popup is not blocked by your browser.");
var errorMsg = "Failed to retrieve a token from Wordpress."; var errorMsg = "Failed to retrieve a token from Wordpress.";
// We add time for user to enter his credentials // We add time for user to enter his credentials
task.timeout = ASYNC_TASK_LONG_TIMEOUT; task.timeout = ASYNC_TASK_LONG_TIMEOUT;

View File

@ -6,7 +6,7 @@ Extension variable name:
<br /> <br />
userCustom.onPreviewFinished = function() { userCustom.onPreviewFinished = function() {
<br /> <br />
&nbsp;&nbsp;extensionMgr.onMessage(&quot;Finished!&quot;); &nbsp;&nbsp;eventMgr.onMessage(&quot;Finished!&quot;);
<br /> <br />
}; };
<br /> <br />

54
js/main-min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -3,9 +3,9 @@ define([
"underscore", "underscore",
"classes/Provider", "classes/Provider",
"core", "core",
"extensionMgr", "eventMgr",
"providers/gplusProvider" "providers/gplusProvider"
], function($, _, Provider, core, extensionMgr) { ], function($, _, Provider, core, eventMgr) {
var mediaImporter = {}; var mediaImporter = {};

View File

@ -2,10 +2,10 @@ define([
"underscore", "underscore",
"utils", "utils",
"classes/Provider", "classes/Provider",
"extensionMgr", "eventMgr",
"fileMgr", "fileMgr",
"helpers/dropboxHelper" "helpers/dropboxHelper"
], function(_, utils, Provider, extensionMgr, fileMgr, dropboxHelper) { ], function(_, utils, Provider, eventMgr, fileMgr, dropboxHelper) {
var PROVIDER_DROPBOX = "dropbox"; var PROVIDER_DROPBOX = "dropbox";
@ -17,7 +17,7 @@ define([
return undefined; return undefined;
} }
if(!path.match(/^[^\\<>:"\|?\*]+$/)) { if(!path.match(/^[^\\<>:"\|?\*]+$/)) {
extensionMgr.onError('"' + path + '" contains invalid characters.'); eventMgr.onError('"' + path + '" contains invalid characters.');
return undefined; return undefined;
} }
if(path.indexOf("/") !== 0) { if(path.indexOf("/") !== 0) {
@ -59,7 +59,7 @@ define([
fileDescList.push(fileDesc); fileDescList.push(fileDesc);
}); });
if(fileDescList.length !== 0) { if(fileDescList.length !== 0) {
extensionMgr.onSyncImportSuccess(fileDescList, dropboxProvider); eventMgr.onSyncImportSuccess(fileDescList, dropboxProvider);
} }
}); });
}); });
@ -75,7 +75,7 @@ define([
var syncIndex = createSyncIndex(path); var syncIndex = createSyncIndex(path);
var fileDesc = fileMgr.getFileFromSyncIndex(syncIndex); var fileDesc = fileMgr.getFileFromSyncIndex(syncIndex);
if(fileDesc !== undefined) { if(fileDesc !== undefined) {
extensionMgr.onError('"' + fileDesc.title + '" was already imported.'); eventMgr.onError('"' + fileDesc.title + '" was already imported.');
return; return;
} }
importPaths.push(path); importPaths.push(path);
@ -95,7 +95,7 @@ define([
var fileDesc = fileMgr.getFileFromSyncIndex(syncIndex); var fileDesc = fileMgr.getFileFromSyncIndex(syncIndex);
if(fileDesc !== undefined) { if(fileDesc !== undefined) {
var existingTitle = fileDesc.title; var existingTitle = fileDesc.title;
extensionMgr.onError('File path is already synchronized with "' + existingTitle + '".'); eventMgr.onError('File path is already synchronized with "' + existingTitle + '".');
callback(true); callback(true);
return; return;
} }
@ -180,9 +180,9 @@ define([
var localTitle = fileDesc.title; var localTitle = fileDesc.title;
// File deleted // File deleted
if(change.wasRemoved === true) { if(change.wasRemoved === true) {
extensionMgr.onError('"' + localTitle + '" has been removed from Dropbox.'); eventMgr.onError('"' + localTitle + '" has been removed from Dropbox.');
fileDesc.removeSyncLocation(syncAttributes); fileDesc.removeSyncLocation(syncAttributes);
extensionMgr.onSyncRemoved(fileDesc, syncAttributes); eventMgr.onSyncRemoved(fileDesc, syncAttributes);
return; return;
} }
var localContent = fileDesc.content; var localContent = fileDesc.content;
@ -194,13 +194,13 @@ define([
// Conflict detection // Conflict detection
if(fileContentChanged === true && localContentChanged === true && remoteContentChanged === true) { if(fileContentChanged === true && localContentChanged === true && remoteContentChanged === true) {
fileMgr.createFile(localTitle + " (backup)", localContent); fileMgr.createFile(localTitle + " (backup)", localContent);
extensionMgr.onMessage('Conflict detected on "' + localTitle + '". A backup has been created locally.'); eventMgr.onMessage('Conflict detected on "' + localTitle + '". A backup has been created locally.');
} }
// If file content changed // If file content changed
if(fileContentChanged && remoteContentChanged === true) { if(fileContentChanged && remoteContentChanged === true) {
fileDesc.content = file.content; fileDesc.content = file.content;
extensionMgr.onContentChanged(fileDesc); eventMgr.onContentChanged(fileDesc);
extensionMgr.onMessage('"' + localTitle + '" has been updated from Dropbox.'); eventMgr.onMessage('"' + localTitle + '" has been updated from Dropbox.');
if(fileMgr.currentFile === fileDesc) { if(fileMgr.currentFile === fileDesc) {
fileMgr.selectFile(); // Refresh editor fileMgr.selectFile(); // Refresh editor
} }

View File

@ -4,10 +4,10 @@ define([
"utils", "utils",
"classes/Provider", "classes/Provider",
"settings", "settings",
"extensionMgr", "eventMgr",
"fileMgr", "fileMgr",
"helpers/googleHelper" "helpers/googleHelper"
], function(_, core, utils, Provider, settings, extensionMgr, fileMgr, googleHelper) { ], function(_, core, utils, Provider, settings, eventMgr, fileMgr, googleHelper) {
var PROVIDER_GDRIVE = "gdrive"; var PROVIDER_GDRIVE = "gdrive";
@ -52,7 +52,7 @@ define([
fileDescList.push(fileDesc); fileDescList.push(fileDesc);
}); });
if(fileDesc !== undefined) { if(fileDesc !== undefined) {
extensionMgr.onSyncImportSuccess(fileDescList, gdriveProvider); eventMgr.onSyncImportSuccess(fileDescList, gdriveProvider);
fileMgr.selectFile(fileDesc); fileMgr.selectFile(fileDesc);
} }
}); });
@ -69,7 +69,7 @@ define([
var syncIndex = createSyncIndex(doc.id); var syncIndex = createSyncIndex(doc.id);
var fileDesc = fileMgr.getFileFromSyncIndex(syncIndex); var fileDesc = fileMgr.getFileFromSyncIndex(syncIndex);
if(fileDesc !== undefined) { if(fileDesc !== undefined) {
extensionMgr.onError('"' + fileDesc.title + '" was already imported.'); eventMgr.onError('"' + fileDesc.title + '" was already imported.');
return; return;
} }
importIds.push(doc.id); importIds.push(doc.id);
@ -111,7 +111,7 @@ define([
var syncIndex = createSyncIndex(id); var syncIndex = createSyncIndex(id);
var fileDesc = fileMgr.getFileFromSyncIndex(syncIndex); var fileDesc = fileMgr.getFileFromSyncIndex(syncIndex);
if(fileDesc !== undefined) { if(fileDesc !== undefined) {
extensionMgr.onError('File ID is already synchronized with "' + fileDesc.title + '".'); eventMgr.onError('File ID is already synchronized with "' + fileDesc.title + '".');
callback(true); callback(true);
return; return;
} }
@ -188,9 +188,9 @@ define([
var localTitle = fileDesc.title; var localTitle = fileDesc.title;
// File deleted // File deleted
if(change.deleted === true) { if(change.deleted === true) {
extensionMgr.onError('"' + localTitle + '" has been removed from Google Drive.'); eventMgr.onError('"' + localTitle + '" has been removed from Google Drive.');
fileDesc.removeSyncLocation(syncAttributes); fileDesc.removeSyncLocation(syncAttributes);
extensionMgr.onSyncRemoved(fileDesc, syncAttributes); eventMgr.onSyncRemoved(fileDesc, syncAttributes);
if(syncAttributes.isRealtime === true && fileMgr.currentFile === fileDesc) { if(syncAttributes.isRealtime === true && fileMgr.currentFile === fileDesc) {
gdriveProvider.stopRealtimeSync(); gdriveProvider.stopRealtimeSync();
} }
@ -209,19 +209,19 @@ define([
// Conflict detection // Conflict detection
if((fileTitleChanged === true && localTitleChanged === true && remoteTitleChanged === true) || (!syncAttributes.isRealtime && fileContentChanged === true && localContentChanged === true && remoteContentChanged === true)) { if((fileTitleChanged === true && localTitleChanged === true && remoteTitleChanged === true) || (!syncAttributes.isRealtime && fileContentChanged === true && localContentChanged === true && remoteContentChanged === true)) {
fileMgr.createFile(localTitle + " (backup)", localContent); fileMgr.createFile(localTitle + " (backup)", localContent);
extensionMgr.onMessage('Conflict detected on "' + localTitle + '". A backup has been created locally.'); eventMgr.onMessage('Conflict detected on "' + localTitle + '". A backup has been created locally.');
} }
// If file title changed // If file title changed
if(fileTitleChanged && remoteTitleChanged === true) { if(fileTitleChanged && remoteTitleChanged === true) {
fileDesc.title = file.title; fileDesc.title = file.title;
extensionMgr.onTitleChanged(fileDesc); eventMgr.onTitleChanged(fileDesc);
extensionMgr.onMessage('"' + localTitle + '" has been renamed to "' + file.title + '" on Google Drive.'); eventMgr.onMessage('"' + localTitle + '" has been renamed to "' + file.title + '" on Google Drive.');
} }
// If file content changed // If file content changed
if(!syncAttributes.isRealtime && fileContentChanged && remoteContentChanged === true) { if(!syncAttributes.isRealtime && fileContentChanged && remoteContentChanged === true) {
fileDesc.content = file.content; fileDesc.content = file.content;
extensionMgr.onContentChanged(fileDesc); eventMgr.onContentChanged(fileDesc);
extensionMgr.onMessage('"' + file.title + '" has been updated from Google Drive.'); eventMgr.onMessage('"' + file.title + '" has been updated from Google Drive.');
if(fileMgr.currentFile === fileDesc) { if(fileMgr.currentFile === fileDesc) {
fileMgr.selectFile(); // Refresh editor fileMgr.selectFile(); // Refresh editor
} }
@ -263,7 +263,7 @@ define([
// Keep a link to the pagedown editor // Keep a link to the pagedown editor
var editor = undefined; var editor = undefined;
extensionMgr.addHookCallback("onEditorConfigure", function(editorParam) { eventMgr.addListener("onEditorConfigure", function(editorParam) {
editor = editorParam; editor = editorParam;
}); });
@ -327,7 +327,7 @@ define([
if(remoteContentChanged === true) { if(remoteContentChanged === true) {
// Conflict detected // Conflict detected
fileMgr.createFile(fileDesc.title + " (backup)", localContent); fileMgr.createFile(fileDesc.title + " (backup)", localContent);
extensionMgr.onMessage('Conflict detected on "' + fileDesc.title + '". A backup has been created locally.'); eventMgr.onMessage('Conflict detected on "' + fileDesc.title + '". A backup has been created locally.');
} }
else { else {
// Add local modifications if no collaborators change // Add local modifications if no collaborators change
@ -371,13 +371,13 @@ define([
googleHelper.forceAuthenticate(); googleHelper.forceAuthenticate();
} }
else if(err.type == "not_found") { else if(err.type == "not_found") {
extensionMgr.onError('"' + fileDesc.title + '" has been removed from Google Drive.'); eventMgr.onError('"' + fileDesc.title + '" has been removed from Google Drive.');
fileDesc.removeSyncLocation(syncAttributes); fileDesc.removeSyncLocation(syncAttributes);
extensionMgr.onSyncRemoved(fileDesc, syncAttributes); eventMgr.onSyncRemoved(fileDesc, syncAttributes);
gdriveProvider.stopRealtimeSync(); gdriveProvider.stopRealtimeSync();
} }
else if(err.isFatal) { else if(err.isFatal) {
extensionMgr.onError('An error has forced real time synchronization to stop.'); eventMgr.onError('An error has forced real time synchronization to stop.');
gdriveProvider.stopRealtimeSync(); gdriveProvider.stopRealtimeSync();
} }
}); });
@ -417,7 +417,7 @@ define([
syncLocations[syncAttributes.syncIndex] = syncAttributes; syncLocations[syncAttributes.syncIndex] = syncAttributes;
var fileDesc = fileMgr.createFile(file.title, file.content, syncLocations); var fileDesc = fileMgr.createFile(file.title, file.content, syncLocations);
fileMgr.selectFile(fileDesc); fileMgr.selectFile(fileDesc);
extensionMgr.onMessage('"' + file.title + '" created successfully on Google Drive.'); eventMgr.onMessage('"' + file.title + '" created successfully on Google Drive.');
}); });
} }
else if(state.action == "open") { else if(state.action == "open") {

View File

@ -3,9 +3,9 @@ define([
"core", "core",
"utils", "utils",
"classes/Provider", "classes/Provider",
"extensionMgr", "eventMgr",
"helpers/googleHelper" "helpers/googleHelper"
], function(_, core, utils, Provider, extensionMgr, googleHelper) { ], function(_, core, utils, Provider, eventMgr, googleHelper) {
var PROVIDER_GPLUS = "gplus"; var PROVIDER_GPLUS = "gplus";
@ -28,7 +28,7 @@ define([
var importImagePreferences = utils.retrieveIgnoreError(PROVIDER_GPLUS + ".importImagePreferences"); var importImagePreferences = utils.retrieveIgnoreError(PROVIDER_GPLUS + ".importImagePreferences");
function showImportImgDialog() { function showImportImgDialog() {
if(!imageDoc.thumbnails) { if(!imageDoc.thumbnails) {
extensionMgr.onError("Image " + imageDoc.name + " is not accessible."); eventMgr.onError("Image " + imageDoc.name + " is not accessible.");
callback(true); callback(true);
return; return;
} }

View File

@ -4,7 +4,7 @@ define([
"core", "core",
"utils", "utils",
"settings", "settings",
"extensionMgr", "eventMgr",
"fileSystem", "fileSystem",
"fileMgr", "fileMgr",
"sharing", "sharing",
@ -17,7 +17,7 @@ define([
"providers/sshProvider", "providers/sshProvider",
"providers/tumblrProvider", "providers/tumblrProvider",
"providers/wordpressProvider" "providers/wordpressProvider"
], function($, _, core, utils, settings, extensionMgr, fileSystem, fileMgr, sharing, Provider) { ], function($, _, core, utils, settings, eventMgr, fileSystem, fileMgr, sharing, Provider) {
var publisher = {}; var publisher = {};
@ -46,7 +46,7 @@ define([
} }
catch(e) { catch(e) {
// localStorage can be corrupted // localStorage can be corrupted
extensionMgr.onError(e); eventMgr.onError(e);
// Remove publish location // Remove publish location
utils.removeIndexFromArray(fileDesc.fileIndex + ".publish", publishIndex); utils.removeIndexFromArray(fileDesc.fileIndex + ".publish", publishIndex);
localStorage.removeItem(publishIndex); localStorage.removeItem(publishIndex);
@ -65,7 +65,7 @@ define([
}); });
} }
catch(e) { catch(e) {
extensionMgr.onError(e); eventMgr.onError(e);
return e.message; return e.message;
} }
}; };
@ -110,7 +110,7 @@ define([
var errorMsg = error.toString(); var errorMsg = error.toString();
if(errorMsg.indexOf("|removePublish") !== -1) { if(errorMsg.indexOf("|removePublish") !== -1) {
publishFileDesc.removePublishLocation(publishAttributes); publishFileDesc.removePublishLocation(publishAttributes);
extensionMgr.onPublishRemoved(publishFileDesc, publishAttributes); eventMgr.onPublishRemoved(publishFileDesc, publishAttributes);
} }
if(errorMsg.indexOf("|stopPublish") !== -1) { if(errorMsg.indexOf("|stopPublish") !== -1) {
callback(error); callback(error);
@ -123,7 +123,7 @@ define([
// Get the html from the onPreviewFinished callback // Get the html from the onPreviewFinished callback
var previewHtml = undefined; var previewHtml = undefined;
extensionMgr.addHookCallback("onPreviewFinished", function(html) { eventMgr.addListener("onPreviewFinished", function(html) {
previewHtml = html; previewHtml = html;
}); });
@ -136,15 +136,15 @@ define([
} }
publishRunning = true; publishRunning = true;
extensionMgr.onPublishRunning(true); eventMgr.onPublishRunning(true);
publishFileDesc = fileMgr.currentFile; publishFileDesc = fileMgr.currentFile;
publishHTML = previewHtml; publishHTML = previewHtml;
publishAttributesList = _.values(publishFileDesc.publishLocations); publishAttributesList = _.values(publishFileDesc.publishLocations);
publishLocation(function(errorFlag) { publishLocation(function(errorFlag) {
publishRunning = false; publishRunning = false;
extensionMgr.onPublishRunning(false); eventMgr.onPublishRunning(false);
if(errorFlag === undefined) { if(errorFlag === undefined) {
extensionMgr.onPublishSuccess(publishFileDesc); eventMgr.onPublishSuccess(publishFileDesc);
} }
}); });
}; };
@ -157,7 +157,7 @@ define([
} while (_.has(localStorage, publishIndex)); } while (_.has(localStorage, publishIndex));
publishAttributes.publishIndex = publishIndex; publishAttributes.publishIndex = publishIndex;
fileDesc.addPublishLocation(publishAttributes); fileDesc.addPublishLocation(publishAttributes);
extensionMgr.onNewPublishSuccess(fileDesc, publishAttributes); eventMgr.onNewPublishSuccess(fileDesc, publishAttributes);
} }
// Initialize the "New publication" dialog // Initialize the "New publication" dialog
@ -251,6 +251,6 @@ define([
}); });
}); });
extensionMgr.onPublisherCreated(publisher); eventMgr.onPublisherCreated(publisher);
return publisher; return publisher;
}); });

View File

@ -3,13 +3,13 @@ define([
"underscore", "underscore",
"core", "core",
"utils", "utils",
"extensionMgr", "eventMgr",
"fileMgr", "fileMgr",
"classes/AsyncTask", "classes/AsyncTask",
"classes/Provider", "classes/Provider",
"providers/downloadProvider", "providers/downloadProvider",
"providers/gistProvider" "providers/gistProvider"
], function($, _, core, utils, extensionMgr, fileMgr, AsyncTask, Provider) { ], function($, _, core, utils, eventMgr, fileMgr, AsyncTask, Provider) {
var sharing = {}; var sharing = {};
@ -59,7 +59,7 @@ define([
attributes.sharingLink = shortUrl; attributes.sharingLink = shortUrl;
} }
else { else {
extensionMgr.onError("An error occured while creating sharing link."); eventMgr.onError("An error occured while creating sharing link.");
attributes.sharingLink = url; attributes.sharingLink = url;
} }
task.chain(); task.chain();

View File

@ -3,13 +3,13 @@ define([
"underscore", "underscore",
"core", "core",
"utils", "utils",
"extensionMgr", "eventMgr",
"fileSystem", "fileSystem",
"fileMgr", "fileMgr",
"classes/Provider", "classes/Provider",
"providers/dropboxProvider", "providers/dropboxProvider",
"providers/gdriveProvider" "providers/gdriveProvider"
], function($, _, core, utils, extensionMgr, fileSystem, fileMgr, Provider) { ], function($, _, core, utils, eventMgr, fileSystem, fileMgr, Provider) {
var synchronizer = {}; var synchronizer = {};
@ -38,7 +38,7 @@ define([
} }
catch(e) { catch(e) {
// localStorage can be corrupted // localStorage can be corrupted
extensionMgr.onError(e); eventMgr.onError(e);
// Remove sync location // Remove sync location
utils.removeIndexFromArray(fileDesc.fileIndex + ".sync", syncIndex); utils.removeIndexFromArray(fileDesc.fileIndex + ".sync", syncIndex);
localStorage.removeItem(syncIndex); localStorage.removeItem(syncIndex);
@ -47,9 +47,11 @@ define([
}); });
// Returns true if at least one file has synchronized location // Returns true if at least one file has synchronized location
synchronizer.hasSync = function() { synchronizer.hasSync = function(provider) {
return _.some(providerMap, function(provider) { return _.some(fileSystem, function(fileDesc) {
return fileMgr.hasSync(provider); return _.some(fileDesc.syncLocations, function(syncAttributes) {
return provider === undefined || syncAttributes.provider === provider;
});
}); });
}; };
@ -148,7 +150,7 @@ define([
var provider = providerList.pop(); var provider = providerList.pop();
// Check that provider has files to sync // Check that provider has files to sync
if(!fileMgr.hasSync(provider)) { if(!synchronizer.hasSync(provider)) {
providerDown(callback); providerDown(callback);
return; return;
} }
@ -177,13 +179,13 @@ define([
return false; return false;
} }
syncRunning = true; syncRunning = true;
extensionMgr.onSyncRunning(true); eventMgr.onSyncRunning(true);
uploadCycle = true; uploadCycle = true;
function isError(error) { function isError(error) {
if(error !== undefined) { if(error !== undefined) {
syncRunning = false; syncRunning = false;
extensionMgr.onSyncRunning(false); eventMgr.onSyncRunning(false);
return true; return true;
} }
return false; return false;
@ -198,8 +200,8 @@ define([
return; return;
} }
syncRunning = false; syncRunning = false;
extensionMgr.onSyncRunning(false); eventMgr.onSyncRunning(false);
extensionMgr.onSyncSuccess(); eventMgr.onSyncSuccess();
}); });
}); });
return true; return true;
@ -251,11 +253,11 @@ define([
} }
}; };
// Triggers realtime synchronization from extensionMgr events // Triggers realtime synchronization from eventMgr events
if(viewerMode === false) { if(viewerMode === false) {
extensionMgr.addHookCallback("onFileOpen", onFileOpen); eventMgr.addListener("onFileOpen", onFileOpen);
extensionMgr.addHookCallback("onFileClosed", synchronizer.tryStopRealtimeSync); eventMgr.addListener("onFileClosed", synchronizer.tryStopRealtimeSync);
extensionMgr.addHookCallback("onOfflineChanged", onOfflineChanged); eventMgr.addListener("onOfflineChanged", onOfflineChanged);
} }
/*************************************************************************** /***************************************************************************
@ -297,7 +299,7 @@ define([
if(isRealtime) { if(isRealtime) {
if(_.size(fileDesc.syncLocations) > 0) { if(_.size(fileDesc.syncLocations) > 0) {
extensionMgr.onError("Real time collaborative document can't be synchronized with multiple locations"); eventMgr.onError("Real time collaborative document can't be synchronized with multiple locations");
return; return;
} }
// Perform the provider's real time export // Perform the provider's real time export
@ -307,7 +309,7 @@ define([
} }
syncAttributes.isRealtime = true; syncAttributes.isRealtime = true;
fileDesc.addSyncLocation(syncAttributes); fileDesc.addSyncLocation(syncAttributes);
extensionMgr.onSyncExportSuccess(fileDesc, syncAttributes); eventMgr.onSyncExportSuccess(fileDesc, syncAttributes);
// Start the real time sync // Start the real time sync
realtimeFileDesc = fileDesc; realtimeFileDesc = fileDesc;
@ -317,7 +319,7 @@ define([
} }
else { else {
if(_.size(fileDesc.syncLocations) > 0 && _.first(_.values(fileDesc.syncLocations)).isRealtime) { if(_.size(fileDesc.syncLocations) > 0 && _.first(_.values(fileDesc.syncLocations)).isRealtime) {
extensionMgr.onError("Real time collaborative document can't be synchronized with multiple locations"); eventMgr.onError("Real time collaborative document can't be synchronized with multiple locations");
return; return;
} }
// Perform the provider's standard export // Perform the provider's standard export
@ -326,7 +328,7 @@ define([
return; return;
} }
fileDesc.addSyncLocation(syncAttributes); fileDesc.addSyncLocation(syncAttributes);
extensionMgr.onSyncExportSuccess(fileDesc, syncAttributes); eventMgr.onSyncExportSuccess(fileDesc, syncAttributes);
}); });
} }
@ -342,7 +344,7 @@ define([
$(".action-sync-manual-" + provider.providerId).click(function(event) { $(".action-sync-manual-" + provider.providerId).click(function(event) {
var fileDesc = fileMgr.currentFile; var fileDesc = fileMgr.currentFile;
if(_.size(fileDesc.syncLocations) > 0 && _.first(_.values(fileDesc.syncLocations)).isRealtime) { if(_.size(fileDesc.syncLocations) > 0 && _.first(_.values(fileDesc.syncLocations)).isRealtime) {
extensionMgr.onError("Real time collaborative document can't be synchronized with multiple locations"); eventMgr.onError("Real time collaborative document can't be synchronized with multiple locations");
return; return;
} }
provider.exportManual(event, fileDesc.title, fileDesc.content, function(error, syncAttributes) { provider.exportManual(event, fileDesc.title, fileDesc.content, function(error, syncAttributes) {
@ -350,12 +352,12 @@ define([
return; return;
} }
fileDesc.addSyncLocation(syncAttributes); fileDesc.addSyncLocation(syncAttributes);
extensionMgr.onSyncExportSuccess(fileDesc, syncAttributes); eventMgr.onSyncExportSuccess(fileDesc, syncAttributes);
}); });
}); });
}); });
}); });
extensionMgr.onSynchronizerCreated(synchronizer); eventMgr.onSynchronizerCreated(synchronizer);
return synchronizer; return synchronizer;
}); });