home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 2011 November
/
CHIP_2011_11.iso
/
Programy
/
Narzedzia
/
AIMP2
/
aimp_2.61.583.exe
/
$TEMP
/
YandexPackSetup.msi
/
fil1B932810AB57451412FF973063D263CA
< prev
next >
Wrap
Text File
|
2010-07-12
|
34KB
|
870 lines
function BarApplication(core) {
this._barCore = core;
this._logger = this._barCore.Log4Moz.repository.getLogger(core.appName + ".App");
this._dirs._barApp = this;
this._controllerName = this.name + "OverlayController";
this._updater = new this._barCore.Lib.Update(this);
this._init();
try {
this._cleanupPreferences();
}
catch (e) {
this._logger.error("Failed cleaning preferences. " + this._barCore.Lib.misc.formatError(e));
}
}
BarApplication.prototype = {
get defaultWidgetsInfo() {
return this._presetWidgetsInfo;
},
get name() {
return this._barCore.appName;
},
getNewControllerID: function barApp_getNewControllerID() {
return this._newCID++;
},
getNewWidgetInstanceID: function barApp_getNewWidgetInstanceID() {
return "" + Date.now() + this._newWID++;
},
get localeString() {
if (!this._localeString) {
try {
let localeFromPref = this.core.Preferences.get("general.useragent.locale", "");
if (localeFromPref && /^([a-z]{2})(\-|$)/.test(localeFromPref)) {
this._localeString = localeFromPref;
} else {
let xulChromeReg = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry);
this._localeString = xulChromeReg.getSelectedLocale("global");
}
} catch(e) {
return "ru";
}
}
return this._localeString || "ru";
},
get core() {
return this._barCore;
},
get directories() {
return this._dirs;
},
get packageManager() {
return this._pacMan;
},
get widgetLibrary() {
return this._widgetLib;
},
get overlayProvider() {
return this._overlayProvider;
},
restartWidgets: function barApp_restartWidgets(packageID) {
this.switchWidgets(packageID, false);
this.packageManager.reloadPackage(packageID);
this.switchWidgets(packageID, true);
},
switchWidgets: function barApp_switchWidgets(packageID, on) {
this.forEachWindow(
function(controller) {
controller.switchWidgets(packageID, on);
});
},
forEachWindow: function barApp_forEachWindow(func, contextObj) {
if (typeof func !== "function")
throw new this._barCore.Lib.CustomErrors.EArgType("func", "Function", typeof func);
var windows = this.core.Lib.misc.getNavigatorWindows();
for each (let window in windows) {
let controller = window[this._controllerName];
if (controller)
func.call(contextObj, controller);
}
},
installPreset: function barApp_installPreset(url) {
this._barCore.Lib.misc.openWindow({
url: "chrome://" + this.name + "/content/custombar/dialogs/package-management/install/install.xul",
features: "__popup__",
name: "package-management-install",
mode: "install",
preset: url,
application: this
});
},
navigate: function barApp_navigate(srcWnd, unsafeURL, target, wndWidth, wndHeight, yandexAction, callerProto) {
const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
let uri = ioService.newURI(unsafeURL, null, null);
if (!(uri && /^(http|ftp)s?$/.test(uri.scheme)))
throw new this._barCore.Lib.CustomErrors.ESecurityViolation("application.navigate", "URL=" + unsafeURL);
let url = uri.spec;
if (!target)
target = "current tab";
switch (target) {
case "current tab":
target = "tab";
break;
case "new tab":
target = "new-tab";
break;
case "new window":
target = "window";
break;
}
if (yandexAction) {
let packageURI = ioService.newURI(this.packageManager.getPackageInfo(callerProto.unit.unitPackage.id).uri, null, null);
if (!this.isTrustedPackageURI(packageURI))
yandexAction = undefined;
}
if (target != "new popup") {
var statData = undefined;
if (yandexAction)
statData = {action: yandexAction};
srcWnd.Ya.loadURI(url, target, statData);
}
switch (target) {
case "new popup": {
let sizeFeatures = (wndWidth && wndHeight) ? ",width=" + wndWidth + ",height=" + wndHeight : "";
srcWnd.openDialog("chrome://" + this.name + "/content/custombar/dialogs/popup_browser/popup_browser.xul", "_blank",
"chrome,all,dialog=no,resizable" + sizeFeatures, url, wndWidth, wndHeight);
break;
}
}
},
selectBestPackage: function BarApp_selectBestPackage(manifest /* XB.PackageManifest */) {
if (!(manifest instanceof this._barCore.Lib.XB.PackageManifest))
throw new this._barCore.Lib.CustomErrors.EArgType("manifest", "PackageManifest",
manifest ? manifest.constructor.name : typeof manifest);
var coreVersion = parseInt(this.core.version, 10),
bestPackageInfo = null,
bestVersion = "0",
bestPackageInfo2 = null,
bestVersion2 = "0";
var comparator = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
.getService(Components.interfaces.nsIVersionComparator);
for each(let packageInfo in manifest.packagesInfo) {
if (packageInfo.platformMin <= coreVersion) {
let newerPackage = (comparator.compare(packageInfo.version, bestVersion) > 0),
newerPlatform = bestPackageInfo && (packageInfo.platformMin > bestPackageInfo.platformMin);
if (newerPackage || newerPlatform) {
bestPackageInfo = packageInfo;
bestVersion = packageInfo.version;
}
}
else {
if (comparator.compare(packageInfo.version, bestVersion2) > 0) {
bestPackageInfo2 = packageInfo;
bestVersion2 = packageInfo.version;
}
}
}
return [bestPackageInfo, bestPackageInfo2];
},
isYandexHost: function barApp_isYandexHost(hostName) {
return this._yandexHostsPattern.test(hostName);
},
isTrustedPresetUri: function barApp_isTrustedPresetUri(uri /*nsIURI*/) {
if (!(uri instanceof Ci.nsIURI))
throw new this._barApp.core.Lib.CustomErrors.EArgType("uri", "nsIURI", typeof uri);
if ((uri.scheme != "http") && (uri.scheme != "https"))
return false;
return (uri.host == this._downloadHost) ||
((this._approvedCompsHosts.indexOf(uri.host) >= 0) && uri.path.indexOf("/components/approved") == 0);
}, // boolean
isTrustedPackageURI: function BarApp_isTrustedPackageURI(uri /*nsIURI*/) {
if (!(uri instanceof Ci.nsIURI))
throw new this._barApp.core.Lib.CustomErrors.EArgType("uri", "nsIURI", typeof uri);
if ((uri.scheme != "http") && (uri.scheme != "https")) {
return false;
}
return (uri.host == this._downloadHost) || ((uri.host == this._barHost) && (uri.path.indexOf("/packages") == 0));
},
isPreinstalledPackage: function BarApp_isPreinstalledPackage(packageID) {
return (packageID == "http://bar.yandex.ru/packages/yandexbar" ||
packageID == "http://bar.yandex.ru/packages/samples");
}, // boolean
isPreinstalledWidget: function barApp_isPreinstalledWidget(protoID) {
return (this._preinstalledWidgetsIDs.indexOf(protoID) >= 0);
},
finalize: function barApp_finalize() {
this._widgetLib.finalize();
this._pacMan.finalize();
this._widgetLib = null;
this._pacMan = null;
this._overlayProvider.clear();
this._overlayProvider = null;
this._barCore.Lib.XB.finalize();
this._presetWidgetsInfo = null;
this._logger = null;
this._barCore = null;
},
onNewNavigatorReady: function barApp_onNewNavigatorReady(controller) {
try {
var autoPresetURL = this._autoPresetURL;
if (autoPresetURL && (this._newCID == 1)) {
let cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);
cookieManager.remove("." + this._autoPresetCookieDomain, this._autoPresetCookieName, "/", false);
this.installPreset(autoPresetURL);
}
}
catch (e) {
this._logger.error("Could not check autoinstalled preset. " + this._barCore.Lib.misc.formatError(e));
}
},
_barCore: null,
_logger: null,
_presetWidgetsInfo: null,
_overlayProvider: null,
_newCID: 0,
_newWID: 0,
_localeString: null,
_controllerName: null,
_yandexHostsPattern: /(^|\.)yandex\.(ru|ua|by|kz|net|com)$/i,
_downloadHost: "download.yandex.ru",
_barHost: "bar.yandex.ru",
_approvedCompsHosts: ["toolbar.yandex.ru", "bar.yandex.ru"],
_autoPresetCookieDomain: "bar.yandex.ru",
_autoPresetCookieName: "bar-install-preset",
_dirs: {
get XBRoot() {
var dirFile = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
dirFile.append(this.XBDirName);
this._forceDir(dirFile);
return dirFile;
},
get XBPackages() {
let packagesDir = this.XBRoot;
packagesDir.append("packages");
this._forceDir(packagesDir);
return packagesDir;
},
get XBPresets() {
let presetsDir = this.XBRoot;
presetsDir.append("presets");
this._forceDir(presetsDir);
return presetsDir;
},
get XBTemp() {
var dirFile = this.XBRoot;
dirFile.append("temp");
this._forceDir(dirFile);
return dirFile;
},
get content() {
var contentDirFile = this._barApp.core.extensionPathFile;
contentDirFile.append("chrome");
contentDirFile.append("content");
contentDirFile.append("custombar");
return contentDirFile;
},
get XBDirName() {
return this._xbDirName || (this._xbDirName = this._barApp.name + "-xb");
},
_barApp: null,
_forceDir: function baxbd_forceDir(dirFile, perm) {
perm = perm || 0755;
if (!(dirFile.exists() && dirFile.isDirectory()))
dirFile.create(Ci.nsIFile.DIRECTORY_TYPE, perm);
}
},
_pacMan: null,
_widgetLib: null,
_preinstalledWidgetsIDs: null,
_updater: null,
get _autoPresetURL() {
var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
var autoPresetCookieURI = ioService.newURI("http://" + this._autoPresetCookieDomain + "/", null, null);
var cookieService = Cc["@mozilla.org/cookieService;1"].getService().QueryInterface(Ci.nsICookieService);
var cookieString = cookieService.getCookieString(autoPresetCookieURI, null);
var presetURL;
if (cookieString) {
var cookies = cookieString.split(";");
for each (let cookie in cookies) {
let separatorPos = cookie.indexOf("=");
if (separatorPos == -1)
continue;
let cookieName = this._barCore.Lib.sysutils.trimAllSpaces( cookie.substring(0, separatorPos) );
if (cookieName == this._autoPresetCookieName)
presetURL = unescape( cookie.substring(separatorPos + 1) );
}
}
this.__defineGetter__("_autoPresetURL", function() presetURL);
return this._autoPresetURL;
},
_init: function barApp_init() {
this._logger.config("Initializing...");
this._barCore.Lib.XB.init(this);
this._initPackageSystem();
this._initWidgetLibrary();
this._loadDefaultpreset();
this._setOverlayProvider();
this._logger.config("Init done");
},
_initPackageSystem: function barApp__initPackageSystem() {
this._logger.config("Scanning installed packages");
var packagesDir = this._dirs.content;
packagesDir.append("packages");
var packagesCommonDir = packagesDir.clone();
packagesCommonDir.append("common");
this._pacMan = new this._PacMan(this, [packagesCommonDir]);
},
_initWidgetLibrary: function barApp__initWidgetLibrary() {
this._widgetLib = new this._WidgetLibrary(this);
try {
var preinstIDsFile = this.directories.content;
preinstIDsFile.append("preinstalled_widgets.json");
this._preinstalledWidgetsIDs = this.core.JSON.parse(this.core.Lib.sysutils.readTextFile(preinstIDsFile));
this._widgetLib.acquaintWithWidgets(this._preinstalledWidgetsIDs);
}
catch (e) {
this._logger.error("Could not load preinstalled widgets list. " + this.core.Lib.misc.formatError(e));
}
},
_loadDefaultpreset: function barApp__loadDefaultpreset() {
this._logger.config("Loading application default preset");
try {
var presetChromeURL = "chrome://" + this.name + "/locale/base_preset.xml";
var presetRequest = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
presetRequest.open("GET", presetChromeURL, false);
presetRequest.send(null);
var presetDoc = presetRequest.responseXML;
var widgetPreset = new this._barCore.Lib.XB.Preset(presetDoc, "");
this._presetWidgetsInfo = widgetPreset.widgetsInfo;
}
catch (e) {
this._logger.error("Failed loading default preset.\n" + this._barCore.Lib.misc.formatError(e));
this._logger.debug("Stack trace:\n" + e.stack);
}
},
_setOverlayProvider: function barApp__setOverlayProvider() {
this._logger.config("Adding XUL overlay provider");
this._overlayProvider = new this._barCore.Lib.OverlayProvider(this);
var appProtocol = Cc["@mozilla.org/network/protocol;1?name=" + this.name]
.getService(Ci.nsIProtocolHandler).wrappedJSObject;
appProtocol.addDataProvider(this._overlayProvider);
},
_cleanupPreferences: function barApp__clearPreferences() {
let prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);
let xbWidgetsPrefBranch = prefService.getBranch(this.name + ".xbwidgets.");
let branchKeys = xbWidgetsPrefBranch.getChildList("", {});
let widgetSettingKeyPattern = /^(.+#.+)\.(\d+)\..+$/;
let currentSetData = this._overlayProvider.currentSetIds;
for each (let key in branchKeys) {
let keyMatch = key.match(widgetSettingKeyPattern);
if (!keyMatch)
continue;
let prefProtoID = keyMatch[1];
let prefInstID = keyMatch[2];
let instArray = currentSetData[prefProtoID];
if (!instArray) {
xbWidgetsPrefBranch.deleteBranch(prefProtoID);
}
else {
if (instArray.indexOf(prefInstID) < 0) {
let settingKey = prefProtoID + "." + prefInstID;
xbWidgetsPrefBranch.deleteBranch(settingKey);
}
}
}
}
};
BarApplication.prototype._PacMan = function PacMan_constructor(barApp, extraPackagesDirs) {
this._logger = barApp.core.Log4Moz.repository.getLogger(barApp.name + ".pacman");
this._barApp = barApp;
this._packagesInfo = {};
this._cachedPackages = {};
if (extraPackagesDirs && !(extraPackagesDirs instanceof Array))
throw new this._barApp.core.Lib.CustomErrors.EArgType("extraPackagesDirs", "Array", typeof extraPackagesDirs);
this._extraPackagesDirs = extraPackagesDirs;
this.rescanPackages();
};
BarApplication.prototype._PacMan.prototype = {
constructor: BarApplication._PacMan,
get packagesIDs() {
var IDs = [];
for (let id in this._packagesInfo) {
IDs.push(id);
}
return IDs;
},
rescanPackages: function barPacMan_rescanPackages() {
this._logger.debug("Looking for packages...");
this._unloadPackages();
this._packagesInfo = {};
var packagesDir = this._barApp.directories.XBPackages;
var entries = packagesDir.directoryEntries;
while (entries.hasMoreElements()) {
let packageDir = entries.getNext().QueryInterface(Ci.nsIFile);
if (packageDir.isDirectory()) {
let packageInfo = this._checkPackageDir(packageDir);
if (!packageInfo)
continue;
let properDirName = this._makePkgDirName(packageInfo.id);
if (properDirName !== packageDir.leafName)
packageDir.moveTo(null, properDirName);
this._logger.debug(this._consts.STR_FOUND_PACKAGE + packageDir.leafName);
this._packagesInfo[packageInfo.id] = packageInfo;
}
}
if (this._extraPackagesDirs) {
for each (let packageDir in this._extraPackagesDirs) {
let packageInfo = this._checkPackageDir(packageDir);
if (packageInfo) {
this._logger.debug(this._consts.STR_FOUND_PACKAGE + packageDir.leafName);
this._packagesInfo[packageInfo.id] = packageInfo;
}
}
}
},
installPackage: function barPacMan_installPackage(srcFile, packageInfo) {
if (!(srcFile instanceof Ci.nsILocalFile))
throw new this._barApp.core.Lib.CustomErrors.EArgType("srcFile", "nsILocalFile", typeof srcFile);
this._validatePackageInfo(packageInfo);
var packageDir;
if (srcFile.isDirectory()) {
packageDir = srcFile.clone();
}
else {
packageDir = srcFile.clone();
packageDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0755);
this._barApp.core.Lib.sysutils.extractZipArchive(srcFile, packageDir);
srcFile.remove();
}
if (this.isPackageInstalled(packageInfo.id))
this.unloadPackage(packageInfo.id);
var packagesDirectory = this._barApp.directories.XBPackages;
var destDirName = this._makePkgDirName(packageInfo.id);
/** NOTE!:
* For some reason FF 3.5 does not mutate nsIFile after calling its' moveTo method (at least on Linux).
* So we have to make another nsIFile pointing to the final package destination.
*/
var destPackageDir = packagesDirectory.clone();
destPackageDir.append(destDirName);
var destDir = packagesDirectory.clone();
destDir.append(destDirName);
this._barApp.core.Lib.misc.removeFileSafe(destDir);
try {
packageDir.moveTo(packagesDirectory, destDirName);
}
catch (e) {
this._barApp.core.Lib.misc.removeFileSafe(destDir);
this._barApp.core.Lib.misc.removeFileSafe(srcFile);
throw e;
}
let metaInfoFile = destPackageDir.clone();
metaInfoFile.append(this._consts.STR_PKGINFO_FILE_NAME);
this._barApp.core.Lib.sysutils.writeTextFile(metaInfoFile, this._barApp.core.JSON.stringify(packageInfo), 0644);
packageInfo.installDir = destPackageDir;
this._packagesInfo[packageInfo.id] = packageInfo;
},
uninstallPackage: function barPacMan_uninstallPackage(packageID) {
this.unloadPackage(packageID);
var dir = this._getPackageInstallInfo(packageID).installDir;
try {
dir.remove(true);
}
finally {
delete this._packagesInfo[packageID];
}
},
isPackageInstalled: function barPacMan_isPackageInstalled(packageID) {
return !!this._packagesInfo[packageID];
},
getPackage: function barPacMan_getPackage(packageID) {
let pkg = this._cachedPackages[packageID];
if (pkg)
return pkg;
let packageInfo = this.getPackageInfo(packageID);
let package_ = new this._barApp.core.Lib.XB.WidgetPackage(packageInfo.installDir, packageID);
this._cachedPackages[packageID] = package_;
return package_;
},
unloadPackage: function barPacMan_unloadPackage(packageID) {
if (!this._packagesInfo[packageID])
throw new Error(this._consts.ERR_NO_SUCH_PACKAGE + " " + packageID);
this._barApp.widgetLibrary.flushPackageProtos(packageID);
var pkg = this._cachedPackages[packageID];
if (!pkg) return;
pkg.finalize();
delete this._cachedPackages[packageID];
},
reloadPackage: function barPacMan_reloadPackage(packageID) {
this.unloadPackage(packageID);
this.getPackage(packageID);
},
finalize: function barPacMan_finalize() {
this._unloadPackages();
this._cachedPackages = null;
this._packagesInfo = null;
},
getPackageInfo: function barpacMan_getPackageInfo(packageID) {
var packageInfo = this._getPackageInstallInfo(packageID);
packageInfo = this._barApp.core.Lib.sysutils.copyObj(packageInfo, false);
packageInfo.installDir = packageInfo.installDir.clone();
return packageInfo;
},
_unloadPackages: function barPacMan__unloadPackages() {
for (let packageID in this._cachedPackages) {
try {
this.unloadPackage(packageID);
}
catch (e) {
this._logger.error("Error finalizing package " + packageID + ". " +
this._barApp.core.Lib.misc.formatError(e));
}
}
},
_getPackageInstallInfo: function barPacMan__getPackageInstallInfo(packageID) {
var packageInfo = this._packagesInfo[packageID];
if (!packageInfo) {
this._logger.warn("barPacMan_getPackageInstallInfo: " +
this._consts.ERR_NO_SUCH_PACKAGE + " " + packageID);
throw new Error(this._consts.ERR_NO_SUCH_PACKAGE + " " + packageID);
}
return packageInfo;
},
_checkPackageDir: function barPacMan__checkPackageDir(packageDir) {
var dirName = "";
try {
dirName = packageDir.leafName;
this._logger.trace("Checking directory " + dirName);
let pkgInfoFile = packageDir.clone();
pkgInfoFile.append(this._consts.STR_PKGINFO_FILE_NAME);
if ( !(pkgInfoFile.exists() && pkgInfoFile.isReadable()) ) {
this._logger.warn("Directory '" + dirName + "' does not contain a valid package");
return null;
}
var packageInfo = this._barApp.core.JSON.parse( this._barApp.core.Lib.sysutils.readTextFile(pkgInfoFile) );
if ((typeof packageInfo == 'object') && !(packageInfo instanceof Object))
packageInfo.__proto__ = Object.prototype;
this._validatePackageInfo(packageInfo);
packageInfo.installDir = packageDir;
return packageInfo;
}
catch (e) {
this._logger.warn("An error occured while checking package directory " + dirName + ". " +
this._barApp.core.Lib.misc.formatError(e));
return null;
}
},
_validatePackageInfo: function BarPacMan_validatePackageInfo(packageInfo) {
if (!(packageInfo instanceof Object))
throw this._barApp.core.Lib.CustomErrors.EArgType("packageInfo", "Object", packageInfo);
for (let propName in this._metainfoPropNames)
if (!(propName in packageInfo))
throw new SyntaxError(this._consts.ERR_CORRUPT_PKGINFOFILE + " (" + propName + ")");
for (let propName in packageInfo)
if (!(propName in this._metainfoPropNames))
delete packageInfo[propName];
},
_makePkgDirName: function barPacMan__makePkgDirName(packageID) {
return this._barApp.core.Lib.misc.stringMD5(packageID);
},
_backgroundDownload: function barPacMan__backgroundDownload(pkgManURL, context) {
let progressWatcher = context.progressWatcher;
if (progressWatcher) {
if ((typeof progressWatcher.onProgress != "function") ||
(typeof progressWatcher.shouldCancel != "function") ||
(typeof progressWatcher.beforeFilesReplaced != "function"))
throw new TypeError(this._consts.ERR_PROGRESS_WATCHER_INTF);
}
let destPkgFile = this._barApp.directories.XBTemp;
destPkgFile.append("tmp-" + encodeURIComponent(pkgManURL));
this._barApp._logger.debug("Starting BG download " + pkgManURL);
let downloadTask = new this._DownloadTask(this, this._barApp, pkgManURL, destPkgFile, context);
let bgThread = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager).newThread(0);
bgThread.dispatch(downloadTask, bgThread.DISPATCH_NORMAL);
var currentThread = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager).currentThread;
while (!downloadTask.finished) {
if (progressWatcher) {
progressWatcher.onProgress(downloadTask.progress);
if (progressWatcher.shouldCancel())
downloadTask.cancel();
}
currentThread.processNextEvent(true);
}
if (downloadTask.error)
throw downloadTask.error;
if (progressWatcher)
progressWatcher.onProgress(downloadTask.progress);
},
_consts: {
STR_PKGINFO_FILE_NAME: ".package.json",
STR_ARRAY_EXPECTED: "Array expected",
STR_FOUND_PACKAGE: "Found a package in directory ",
ERR_NO_SUCH_PACKAGE: "No such package",
ERR_PKGINFO_REQUIRED: "Package inforamtion required",
ERR_CORRUPT_PKGINFOFILE: "Package information file is corrupt",
ERR_WRONG_MANIFEST_SYNTAX: "Wrong manifest syntax",
ERR_WRONG_PKGID: "Manifest declares wrong package ID",
ERR_PROGRESS_WATCHER_INTF: "Progress watcher object does not support proper interface"
},
_metainfoPropNames: {id: 0, uri: 0, version: 0, platformMin: 0, __proto__: null},
_barApp: null,
_logger: null,
_packagesInfo: null,
_cachedPackages: null,
_extraPackagesDirs: undefined
};
BarApplication.prototype._WidgetLibrary = function BarWidgetLib(application) {
this._barApp = application;
this._logger = application.core.Log4Moz.repository.getLogger(application.name + ".WLib");
this._knownWidgets = {};
this._packages = {};
try {
this._loadKnownWidgets();
}
catch (e) {
this._logger.error("An error occured while loading known widgets. " +
this._barApp.core.Lib.misc.formatError(e));
}
};
BarApplication.prototype._WidgetLibrary.prototype = {
constructor: BarApplication.prototype._WidgetLibrary,
clear: function WidgetLibrary_clear() {
this._packages = {};
this._knownWidgets = {};
},
finalize: function WidgetLibrary_finalize() {
this._saveKnownWidgetsData();
this.clear();
this._logger = null;
},
acquaintWithWidgets: function WidgetLibrary_acquaintWithWidgets(protoIDsArray) {
for each (let protoID in protoIDsArray) {
if (!this._knownWidgets[protoID])
this._knownWidgets[protoID] = this._loadWidgetProto(protoID);
}
this._saveKnownWidgetsData();
},
forgetWidgets: function WidgetLibrary_forgetWidget(protoIDsArray) {
for each (let protoID in protoIDsArray) {
if (protoID in this._knownWidgets) {
delete this._knownWidgets[protoID];
}
}
this._saveKnownWidgetsData();
},
getWidgetProto: function WidgetLibrary_getWidgetProto(protoID) {
if (!this._barApp.core.Lib.sysutils.isString(protoID))
throw new this._barApp.core.Lib.CustomErrors.EArgType("protoID", "String", typeof protoID);
return this._knownWidgets[protoID] || this._loadWidgetProto(protoID);
},
getWidgetProtos: function WidgetLibrary_getWidgetProtos(fromPackageID) {
var result = [];
for (let protoID in this._knownWidgets) {
if (fromPackageID) {
let [packageID, ] = this.parseWidgetProtoID(protoID);
if (packageID !== fromPackageID)
continue;
}
result.push(this.getWidgetProto(protoID));
}
return result;
},
getWidgetProtoIDs: function WidgetLibrary_getWidgetProtoIDs(fromPackageID) {
var result = [];
for (let protoID in this._knownWidgets) {
if (fromPackageID) {
let [packageID, ] = this.parseWidgetProtoID(protoID);
if (packageID !== fromPackageID)
continue;
}
result.push(protoID);
}
return result;
},
isKnownWidget: function WidgetLibrary_isKnownWidget(prototypeId) {
return prototypeId in this._knownWidgets;
},
persist: function WidgetLibrary_persist() {
this._saveKnownWidgetsData();
},
flushPackageProtos: function WidgetLibrary_flushPackageProtos(packageID) {
for (let protoID in this._knownWidgets) {
let widgetProto = this._knownWidgets[protoID];
if (widgetProto)
if ( !packageID || (widgetProto.unit.unitPackage.id == packageID) )
this._knownWidgets[protoID] = undefined;
}
},
parseWidgetProtoID: function WidgetLibrary_parseWidgetProtoID(protoID) {
var separatorPos = protoID.indexOf("#");
var packageID = protoID.substring(0, separatorPos);
var widgetName = protoID.substring(separatorPos + 1);
return [packageID, widgetName];
},
_consts: {
STR_KNOWN_WIDGETS_FILE_NAME: "known_widgets.json",
ERR_UNIT_HAS_NO_WIDGET: "Unit does not define a widget"
},
_barApp: null,
_logger: null,
_packages: null,
_knownWidgets: null,
_loadKnownWidgets: function WidgetLibrary__loadKnownWidgets() {
let dataFile = this._barApp.directories.XBRoot;
dataFile.append(this._consts.STR_KNOWN_WIDGETS_FILE_NAME);
if (dataFile.exists() && dataFile.isFile() && dataFile.isReadable()) {
let protoIDsArray = this._barApp.core.JSON.parse( this._barApp.core.Lib.sysutils.readTextFile(dataFile) );
let knownWidgetsListChanged = false;
for each (let protoID in protoIDsArray) {
try {
this._knownWidgets[protoID] = this._loadWidgetProto(protoID);
}
catch (e) {
this._logger.warn("Previously known widget \"" + protoID +
"\" could not be loaded. Will forget it. Error: " +
this._barApp.core.Lib.misc.formatError(e));
}
}
if (knownWidgetsListChanged)
this._saveKnownWidgetsData();
}
},
_saveKnownWidgetsData: function WidgetLibrary__saveKnownWidgetsData() {
let dataFile = this._barApp.directories.XBRoot;
dataFile.append(this._consts.STR_KNOWN_WIDGETS_FILE_NAME);
this._barApp.core.Lib.sysutils.writeTextFile(dataFile,
this._barApp.core.JSON.stringify(this.getWidgetProtoIDs()), 0644);
},
_loadWidgetProto: function WidgetLibrary__loadWidgetProto(protoID) {
var [packageID, widgetName] = this.parseWidgetProtoID(protoID);
var package_ = this._barApp.packageManager.getPackage(packageID);
var proto = package_.getUnit(widgetName).widgetProto;
if (!proto)
throw new Error(this._consts.ERR_UNIT_HAS_NO_WIDGET);
return proto;
}
};