home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World 2005 December
/
PCWorld_2005-12_cd.bin
/
komunikace
/
netscape
/
nsb-install-8-0.exe
/
chrome
/
browser.jar
/
content
/
browser
/
spui.js
< prev
next >
Wrap
Text File
|
2005-09-26
|
41KB
|
1,182 lines
var spui = {
SPUI_DEBUG : false, // Set this to false to disable debug output
SPUI_NS : "http://home.netscape.com/NC-spui#",
SPUI_PREF_BRANCH : "spui.",
RES_URL : null,
RES_TYPE : null,
RES_LABEL : null,
RES_SRC : null,
RES_FRAMESTYLE : null,
RES_PREVIEWIMAGE : null,
RES_OVERFLOWURL : null,
RDFService : null,
RDFDataSource : null,
RDFLoadObserver : null,
RemoteRDFLoadObserver : null,
SPUI_CUSTOM_FEED_PREF_NAME : "spui.newsticker.",
SPUI_CUSTOM_REF_PREF_NAME : "",
SPUI_BROWSER_VERSION : "8.0.4",
SPUI_BROWSER_LOCALE : "",
SPUI_BROWSER_THEME : "",
k_idleTimer : 2000,
GLOBALS : new Object(), // global things that can be referenced by all SPUI's
Init : function() {
if (gPrefService.getPrefType("spui.debug")) {
this.SPUI_DEBUG = gPrefService.getBoolPref("spui.debug");
}
this.debug("Init()");
this.SPUI_BROWSER_THEME = gPrefService.getCharPref("general.skins.selectedSkin");
this.SPUI_BROWSER_LOCALE = gPrefService.getCharPref("general.useragent.locale");
if (!this.RDFService) {
this.RDFService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
.getService(Components.interfaces.nsIRDFService);
this.RES_URL = this.RDFService.GetResource(this.SPUI_NS+'url');
this.RES_TYPE = this.RDFService.GetResource(this.SPUI_NS+'type');
this.RES_LABEL = this.RDFService.GetResource(this.SPUI_NS+'label');
this.RES_TOOLGROUP = this.RDFService.GetResource(this.SPUI_NS+'toolgroup');
this.RES_SRC = this.RDFService.GetResource(this.SPUI_NS+'src');
this.RES_FRAMESTYLE = this.RDFService.GetResource(this.SPUI_NS+'framestyle');
this.RES_PREVIEWIMAGE = this.RDFService.GetResource(this.SPUI_NS+'previewimage');
this.RES_OVERFLOWURL = this.RDFService.GetResource(this.SPUI_NS+'overflowurl');
this.RDFDataSource = null;
}
if (!this.RDFLoadObserver) {
this.debug("Instantiating observer");
this.RDFLoadObserver = {
onBeginLoad : function(sink){},
onInterrupt : function(sink){},
onResume : function(sink){},
onError : function(sink,status,msg){},
onEndLoad : function(sink) {
RDFService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
.getService(Components.interfaces.nsIRDFService);
this.debug("onEndLoad()");
sink.removeXMLSinkObserver(this);
sink.QueryInterface(Components.interfaces.nsIRDFDataSource);
this.debug('Loaded datasource: '+sink.URI);
resources = sink.GetAllResources();
while (resources.hasMoreElements()) {
res = resources.getNext();
res.QueryInterface(Components.interfaces.nsIRDFResource);
this.parent.HandleResource(sink, res);
// RDFService.UnregisterResource(res);
}
// RDFService.UnregisterDataSource(sink);
// JMC: Just slap ordinals on the spui children to set their toolbar order
var toolbar = document.getElementById('navigator-toolbox').firstChild;
while (toolbar && (toolbar.localName == 'toolbar' || toolbar.localName == 'multibartray')) {
if (toolbar.localName == 'multibar')
{
toolbar = toolbar.firstChild;
} else if (toolbar.localName == 'multibartray' && (!toolbar.nextSibling)) {
toolbar.reorderItems();
toolbar = toolbar.parentNode.nextSibling;
} else {
toolbar.reorderItems();
toolbar = toolbar.nextSibling;
}
}
// Now update from the server
this.parent.RefreshRemoteComponents();
},
debug : function(msg) {
this.parent.debug('RDFLoadObserver: '+msg);
}
};
this.RDFLoadObserver.parent = this;
}
if (!this.RemoteRDFLoadObserver) {
this.debug("Instantiating other observer");
this.RemoteRDFLoadObserver = {
bNewComponents : false,
newList : null,
onBeginLoad : function(sink){},
onInterrupt : function(sink){},
onResume : function(sink){},
onError : function(sink,status,msg){},
onEndLoad : function(sink) {
RDFService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
.getService(Components.interfaces.nsIRDFService);
this.debug("onEndLoad()");
sink.removeXMLSinkObserver(this);
sink.QueryInterface(Components.interfaces.nsIRDFDataSource);
this.debug('Loaded datasource: '+sink.URI);
resources = sink.GetAllResources();
this.bNewComponents = false;
this.newList = new Array();
while (resources.hasMoreElements()) {
res = resources.getNext();
res.QueryInterface(Components.interfaces.nsIRDFResource);
this.CheckResource(sink, res);
// RDFService.UnregisterResource(res);
}
// If it's flagged, we'll save it locally
//if (this.bNewComponents) {
var fileURI = this.parent.GetLocalSupportedFile();
sink.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
sink.FlushTo(fileURI.spec);
if (this.bNewComponents) {
this.sendNotify();
}
// Pop notify
//}
// RDFService.UnregisterDataSource(sink);
},
debug : function(msg) {
this.parent.debug('RemoteRDFLoadObserver: '+msg);
},
sendNotify : function() {
// var showNotification = gPref.getBoolPref("spui.showNotifications");
var showNotification = true;
if (showNotification) {
/*
var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService);
var bundle = sbs.createBundle("chrome://mozapps/locale/update/update.properties");
var alertTitle = bundle.GetStringFromName("updatesAvailableTitle");
var alertText = bundle.GetStringFromName("updatesAvailableText");
*/
// JMC - Make a string bundle for this, too
var alertText = "";
var lineDivider = "|";
for (var i = 0; i < this.newList.length; i++) {
alertText += this.newList[i] + lineDivider;
}
var alerts = Components.classes["@mozilla.org/alerts-service;1"]
.getService(Components.interfaces.nsIAlertsService);
alerts.showAlertNotification("chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png",
"New Personal Buttons Available",
alertText, true, "", this);
}
},
QueryInterface: function(aIID)
{
if (!aIID.equals(Components.interfaces.nsIObserver) &&
!aIID.equals(Components.interfaces.nsIAlertListener) &&
!aIID.equals(Components.interfaces.nsISupports) &&
!aIID.equals(Components.interfaces.nsIRDFXMLSinkObserver))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
},
onAlertClickCallback : function (aAlertCookie)
{
BrowserCustomizeToolbar();
},
onAlertFinished : function (aAlertCookie) {
},
/*
If this component doesn't exist in the palette, it's a new one
*/
CheckResource : function(sink, res) {
if (!(sink.hasArcOut(res, this.parent.RES_URL) &&
sink.hasArcOut(res, this.parent.RES_TYPE) &&
sink.hasArcOut(res, this.parent.RES_LABEL)
)) {
return;
}
type = sink.GetTarget(res, this.parent.RES_TYPE, true);
type.QueryInterface(Components.interfaces.nsIRDFLiteral);
if (type.Value != 'toolbarframe') {
return;
}
var toolbox = document.getElementById('navigator-toolbox');
var palette = toolbox.palette;
var paletteButton = palette.firstChild;
while (paletteButton) {
if (paletteButton.id == res.Value) {
return;
}
paletteButton = paletteButton.nextSibling;
}
this.bNewComponents = true;
var label = sink.GetTarget(res, this.parent.RES_LABEL, true);
label.QueryInterface(Components.interfaces.nsIRDFLiteral);
this.newList.push(label.Value);
this.parent.HandleResource(sink, res);
}
};
this.RemoteRDFLoadObserver.parent = this;
}
},
GetLocalSupportedFile : function() {
var profileDir = Components.classes["@mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("ProfD", Components.interfaces.nsIFile);
profileDir.append("supported-spui-components.rdf");
var ios = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var fileURI = ios.newFileURI(profileDir);
return fileURI;
},
RefreshRemoteComponents : function() {
this.debug("RefreshRemoteComponents()");
// var user_guid = gPrefService.getCharPref("browser.info.guid");
// var partnerId;
// try {
// partnerId = gPrefService.getCharPref("browser.partnerId");
//} catch (ex) {
// partnerId = 'chapera';
// }
var SPUI_LOCAL_RDF_URL = gPrefService.getCharPref("spui.supportedURL");
//+ "?guid=" + user_guid + "&partnerId=" + partnerId;
try {
this.RDFDataSource = this.RDFService.GetDataSource(SPUI_LOCAL_RDF_URL);
this.RDFDataSource.QueryInterface(Components.interfaces.nsIRDFXMLSink);
this.RDFDataSource.addXMLSinkObserver(this.RemoteRDFLoadObserver);
} catch (ex) { }
this.debug("Finished RefreshRemoteComponents()");
},
PersistPref: function (newSpuiIds) {
var branch = gPrefService.getBranch("spui.");
var prefs = branch.getChildList("", {});
for(var i = 0; i < prefs.length; i++) {
var tokens = prefs[i].split(".");
if(tokens.length > 0 && !isNaN(tokens[0])) {
var oldId = tokens[0];
if(!(oldId in newSpuiIds)) {
branch.deleteBranch("" + prefs[i] + ".");
dump("deleting .. " + prefs[i]);
}
}
}
},
/**
* Grabs a local RDF file describing what SPUI components are
* currently available, and sets listener on the loading of that
* file.
**/
RefreshComponentList : function() {
this.debug("RefreshComponentList()");
this.Init();
// Load the local supported file, build the toolbar and palette
// Then load the remote file
// For each component in the remote file,
// If it doesn't exist in the palette,
// Then add it to the array of new ones,
// and set the flag to notify and copy.
// When done, check flag.
// If true, copy the remote rdf file into the local file.
// And call notification service
// get profile directory
var fileURI = this.GetLocalSupportedFile();
// this.debug("Gonna go get local file called : " + fileURI.spec + "\n");
try {
// Start loading RDF file of supported components
// this.RDFDataSource = this.RDFService.GetDataSource(SPUI_LOCAL_RDF_URL);
this.RDFDataSource = this.RDFService.GetDataSource(fileURI.spec);
// Register a listener to pick things up when the file is done
// loading. (Control will go to the onEndLoad function...)
this.RDFDataSource.QueryInterface(Components.interfaces.nsIRDFXMLSink);
this.RDFDataSource.addXMLSinkObserver(this.RDFLoadObserver);
} catch (ex) { this.RefreshRemoteComponents(); }
// For now, tell the RDF Service NOT to cache our datasource,
// because we don't know how to handle that properly yet.
// this.RDFService.UnregisterDataSource(this.RDFDataSource);
this.debug("Finished RefreshComponentList()");
},
/**
* Called after browser customize finishes, to re-establish SPUI links
* with all the active items.
**/
RedrawComponents : function() {
var newSpuiIds = new Object();
this.debug("Redrawing Components after browser customize...\n" );
var toolbox = document.getElementById('navigator-toolbox');
var toolbar = toolbox.firstChild;
while (toolbar) {
// this.debug(' Redrawing toolbar: '+toolbar.id+', currentSet: ' +toolbar.currentSetAtLoadTime);
var spuiButton = toolbar.firstChild;
while (spuiButton) {
// this.debug(' SpuiButton is '+spuiButton.id + '\n');
var tokens = spuiButton.id.split('|');
if(tokens.length > 0 && !isNaN(tokens[tokens.length-1])) {
newSpuiIds[tokens[tokens.length-1]] = "new";
}
var iframe = document.getElementById(spuiButton.id+'-iframe');
if (iframe) {
setTimeout("establishRemoteSPUILink('"+spuiButton.id+"');",500);
}
spuiButton = spuiButton.nextSibling;
}
if (toolbar.localName == 'multibar')
{
toolbar = toolbar.firstChild;
} else if (toolbar.localName == 'multibartray' && (!toolbar.nextSibling)) {
toolbar = toolbar.parentNode.nextSibling;
} else {
toolbar = toolbar.nextSibling;
}
}
this.PersistPref(newSpuiIds);
},
/**
* Parse the description for a particular resource
**/
HandleResource : function(datasource, res) {
// this.debug('Found resource: '+res.Value);
// This is basically just debug output
var labels = datasource.ArcLabelsOut(res);
while (labels.hasMoreElements()) {
var label = labels.getNext();
if (label instanceof Components.interfaces.nsIRDFResource) {
var dbg = '* '+label.Value;
var target = datasource.GetTarget(res, label, true);
if (target instanceof Components.interfaces.nsIRDFResource) {
dbg += ' => '+target.Value;
} else if (target instanceof Components.interfaces.nsIRDFLiteral) {
dbg += ' => '+target.Value;
} else {
try {
dbg += ' => '+target.Value;
} catch (ex) { }
}
// this.debug(dbg);
}
}
// See if this resource specifies an actual SPUI component
if (datasource.hasArcOut(res, this.RES_URL) &&
datasource.hasArcOut(res, this.RES_TYPE) &&
datasource.hasArcOut(res, this.RES_LABEL))
{
// this.debug('^** this is a SPUI component! **^');
this.HandleComponent(datasource, res);
}
},
/**
* Handle SPUI component loading
**/
HandleComponent : function(datasource, res) {
// this.debug('HandleComponent('+res.Value+')');
type = datasource.GetTarget(res, this.RES_TYPE, true);
type.QueryInterface(Components.interfaces.nsIRDFLiteral);
if (type.Value == 'toolbarframe') {
this.HandleToolbaritem(datasource, res);
} else {
this.debug('*** WARNING: component type not handled: '+type.Value);
}
},
ConstructComponent : function(datasource, res, newid) {
// Construct the new XUL component
// this.debug('ConstructComponent('+res.Value+')');
try {
var newItem = document.createElement('toolbaritem');
newItem.setAttribute('id', newid);
var label = datasource.GetTarget(res, this.RES_LABEL, true);
label.QueryInterface(Components.interfaces.nsIRDFLiteral);
// JMC added to support multiple customize panels
var toolgroup = datasource.GetTarget(res, this.RES_TOOLGROUP, true);
toolgroup.QueryInterface(Components.interfaces.nsIRDFLiteral);
newItem.setAttribute('label', label.Value);
newItem.setAttribute('title', label.Value);
newItem.setAttribute('class', 'spui-toolbaritem');
newItem.setAttribute('toolgroup', toolgroup.Value);
if (datasource.hasArcOut(res,this.RES_OVERFLOWURL)) {
var ovfURL = datasource.GetTarget(res, this.RES_OVERFLOWURL, true);
ovfURL.QueryInterface(Components.interfaces.nsIRDFLiteral);
newItem.setAttribute('overflowcommand','loadURIWithOpenPref("'+ovfURL.Value+'","browser.tabs.personaltoolbarbutton.open",null,null);');
}
// JMC - should read this from the rdf
var vbox = document.createElement('vbox');
var iframe = document.createElement('iframe');
var src = datasource.GetTarget(res, this.RES_SRC, true);
src.QueryInterface(Components.interfaces.nsIRDFLiteral);
iframe.setAttribute('id', newid+'-iframe');
iframe.setAttribute('name', newid+'-iframe');
iframe.setAttribute('type','content');
iframe.setAttribute('src', src.Value);
iframe.setAttribute('flex', '1');
iframe.setAttribute('allowtransparency',true);
iframe.setAttribute('scrolling','no');
iframe.setAttribute('isActive', 'true');
var framestyle = datasource.GetTarget(res, this.RES_FRAMESTYLE, true);
var iframestyle = "visibility: hidden;";
if (framestyle) {
framestyle.QueryInterface(Components.interfaces.nsIRDFLiteral);
iframestyle += framestyle.Value;
}
iframe.setAttribute('style', iframestyle);
newItem.setAttribute('allowDuplicate', true);
// JMC - Can be duplicate? Get property from RDF, push into button
vbox.appendChild(iframe);
vbox.setAttribute('class', 'spui-content');
var previewSrc = datasource.GetTarget(res, this.RES_PREVIEWIMAGE, true);
previewSrc.QueryInterface(Components.interfaces.nsIRDFLiteral);
previewImage = document.createElement('image');
previewImage.setAttribute('src', previewSrc.Value);
var spacer = document.createElement('spacer');
previewBox = document.createElement('toolbarbutton');
previewBox.appendChild(previewImage);
previewBox.setAttribute('class', 'spui-preview');
previewBox.setAttribute('mousethrough', 'never');
previewBox.setAttribute('label', label.Value);
var draggableBox = document.createElement('toolbarbutton');
draggableBox.setAttribute('class', 'spui-draggable');
draggableBox.setAttribute('mousethrough', 'never');
draggableBox.setAttribute('label', label.Value);
if (framestyle) {
previewBox.setAttribute('style', framestyle.Value);
draggableBox.setAttribute('style', framestyle.Value);
}
var stack = document.createElement('stack');
stack.appendChild(vbox);
stack.appendChild(previewBox);
stack.appendChild(draggableBox);
newItem.appendChild(stack);
iframe.setAttribute('onload', "establishRemoteSPUILink('"+newid+"');"); // JMC: Is this right?
return newItem;
} catch (ex) {
this.debug('WARNING: could not create component!');
return;
}
},
/**
* Handle toolbar item components
**/
HandleToolbaritem : function(datasource, res) {
// this.debug('HandleToobaritem('+res.Value+')');
var newSpuiIds = new Object();
// See if this component is supposed to go in a toolbar
// or just into the tool palette
var toolbox = document.getElementById('navigator-toolbox');
var toolbar = toolbox.firstChild;
var placed = true; // Force to create first component
while (toolbar) {
if (toolbar.currentSetAtLoadTime) {
// this.debug(' looking at toolbar: '+toolbar.id+', currentSet: '+toolbar.currentSetAtLoadTime);
var currentSet = toolbar.currentSetAtLoadTime.split(',');
for (var i = 0; i < currentSet.length; i++) {
placed = false;
// this.debug(' '+currentSet[i]);
// JMC - Peel the unique ID off the toolbar currentSet
// And match against the base id
// Save the suffix
var suffix;
var baseId;
if (currentSet[i].indexOf("|") > -1) // This has a unique id
{
suffix = currentSet[i].substring(currentSet[i].indexOf("|") + 1,currentSet[i].length);
baseId = currentSet[i].substring(0, currentSet[i].indexOf("|"));
newSpuiIds[suffix] = "new";
} else {
baseId = currentSet[i];
}
if (baseId == res.Value) {
// Found it!
var newid = res.Value;
// JMC - Update the ids with the suffix
if (suffix) {
newid = res.Value + "|" + suffix;
}
var newItem = this.ConstructComponent(datasource, res, newid);
placed = this.placeItemRelative(newItem, toolbar, currentSet, i, 10);
if (!placed) {
// That didn't work, so just tack it on the end
toolbar.appendChild(newItem);
this.debug(' placed at end of toolbar!');
placed = true;
}
setTimeout("establishRemoteSPUILink('"+newItem.id+"');",500);
// JMC: removed to support dups -- break;
}
}
}
if (toolbar.localName == 'multibar')
{
toolbar = toolbar.firstChild;
} else if (toolbar.localName == 'multibartray' && (!toolbar.nextSibling)) {
toolbar = toolbar.parentNode.nextSibling;
} else {
toolbar = toolbar.nextSibling;
}
}
// Regardless of whether this component got placed on a toolbar, we still
// need to put it in the tool palette as well, because that represents the
// set of all available toolbar items.
// this.debug(' No appropriate toolbar, so putting it on the palette.');
var palette = toolbox.palette;
var newItem = this.ConstructComponent(datasource, res, res.Value);
palette.appendChild(newItem);
this.PersistPref(newSpuiIds);
},
placeItemRelative : function(newItem, toolbar, currentSet, index) {
var bestBefore;
var beforeMe;
if (index == currentSet.length - 1) {
toolbar.appendChild(newItem);
return;
}
if (currentSet[index+1] &&
(currentSet[index+1] == 'spring') ||
(currentSet[index+1] == 'spacer') ||
(currentSet[index+1] == 'separator'))
{
// How many to be before?
var i;
var itemCount = 0;
for (i = currentSet.length; i > index; --i)
{
if (currentSet[index+1] == currentSet[i])
itemCount++;
}
// Get the nth instance of this item,
// and insert before it
var instanceCount = 0;
var child = toolbar.lastChild;
while (child)
{
if (currentSet[index+1] == child.id.substring(0,child.id.indexOf("|")))
{
this.debug("placement: found a matching " + currentSet[index+1]);
instanceCount++;
if (instanceCount == itemCount) {
beforeMe = child;
break;
}
}
child = child.previousSibling;
}
} else {
for (var j=currentSet.length; j > index; --j)
{
var toolbarChild = document.getElementById(currentSet[j]);
if (!toolbarChild) continue;
beforeMe = toolbarChild;
}
}
toolbar.insertBefore(newItem, beforeMe);
return true;
},
/*
placeItemRelative2 : function(newItem, toolbar, currentSet, index, maxIterations) {
// Look for toolbar buttons that are progressively further away in
// the currentSet
// JMC - Special case, index = 0
if (index == 0) {
var nextItem = toolbar.firstChild;
if (nextItem) {
toolbar.insertBefore(newItem, nextItem);
} else {
toolbar.appendChild(newItem);
}
return true;
}
var j = 1;
var placed = false;
if (!maxIterations) maxIterations = 10;
while (!placed && (j < maxIterations)) {
// First try placing it AFTER the previous item
var nextItem;
if (index >= j) {
// this doesnt work for spacers and other anonymous elements
var prevItem = document.getElementById(currentSet[index-j]);
if (!prevItem)
{
// Count the number of these special elements which occur in the toolbarset
// BEFORE this point, and then get the xth of them
var specialCountLimit = 0;
for (var i=0; i < index; i++) {
if (currentSet[i] == currentSet[index-j])
specialCountLimit++;
}
var paletteItem = toolbar.firstChild;
var specialCount =0;
while (paletteItem) {
var paletteId = paletteItem.id;
var stringLen = currentSet[index-j].length;
var aId = currentSet[index-j];
if (paletteId.substring(0,stringLen) == aId) {
specialCount++;
if (specialCount >= specialCountLimit) {
prevItem = paletteItem;
break;
}
}
paletteItem = paletteItem.nextSibling;
}
}
if (prevItem) {
nextItem = prevItem.nextSibling;
if (prevItem.nextSibling) {
toolbar.insertBefore(newItem, prevItem.nextSibling);
this.debug(' placed after '+currentSet[index-j]+'!');
placed = true;
} else {
toolbar.appendChild(newItem);
placed = true;
}
}
}
if (!placed && (index < currentSet.length-j)) {
// That didn't work, so try placing it BEFORE the next item
nextItem = document.getElementById(currentSet[index+1]);
if (!nextItem)
{
// Count the number of these special elements which occur in the toolbarset
// BEFORE this point, and then get the xth of them
var specialCountLimit = 0;
for (var i=index; i > 0; i--) {
if (currentSet[i] == currentSet[index+1])
specialCountLimit++;
}
var paletteItem = toolbar.lastChild;
var specialCount =0;
while (paletteItem) {
var paletteId = paletteItem.id;
var stringLen = currentSet[index+1].length;
var aId = currentSet[index+1];
if (paletteId.substring(0,stringLen) == aId) {
specialCount++;
if (specialCount >= specialCountLimit) {
nextItem = paletteItem;
break;
}
}
paletteItem = paletteItem.previousSibling;
}
}
if (nextItem) {
toolbar.insertBefore(newItem, nextItem);
this.debug(' placed before '+currentSet[index+1]+'!');
placed = true;
}
}
j++;
}
return placed;
},
*/
/**
* Print out debug text
**/
logger : null,
debug : function(msg) {
// To disabled debug output, set SPUI_DEBUG to "false"
// at the top of this file
if (gPrefService.getPrefType("spui.debug") && gPrefService.getBoolPref("spui.debug")) {
if (!this.logger) {
this.logger = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
}
dump('SPUI: '+msg+'\n');
this.logger.logStringMessage("SPUI: " + msg.replace(/\n/g, " -- "));
}
},
/*
*/
addLivemark : function(baseURL, feedURL, title ) {
// JMC: Which toolbar to add to?
var toolbar = document.getElementById('PersonalToolbar');
var newButton = toolbar.insertItem('spui:newsticker', null, null, null);
var componentId = newButton.id.substring(newButton.id.indexOf("|") + 1, newButton.id.length);
// JMC: ugly, should be wrapped up somewhere else
gPrefService.setCharPref('spui.' + componentId + '.newsticker.feed', 'custom');
gPrefService.setCharPref('spui.' + componentId + '.newsticker.customfeed', feedURL);
gPrefService.setCharPref('spui.' + componentId + '.newsticker.customref', baseURL);
this.debug("live bookmark id " + componentId);
this.RedrawComponents();
}
};
/**
* TODO: this should actually be a listener on the iframe contentDocument, instead
* of polling.
**/
function establishRemoteSPUILink(componentId, accumulator) {
if (!accumulator) accumulator = 0;
// spui.debug('establishRemoteSPUILink('+componentId+','+accumulator+')');
if (accumulator >= 30000) return; // timeout after 30 secs
var iframe = document.getElementById(componentId+'-iframe');
var wait = 0;
do { // Check for starting conditions
if (!iframe) {
spui.debug('WARNING: component does not have iframe: '+componentId);
wait = 2500;
break;
}
var contentDoc = iframe.contentDocument;
if (!contentDoc) {
spui.debug('WARNING: component does not have contentDocument: '+componentId);
wait = 500;
break;
}
var docURL = contentDoc.location;
if (!docURL) {
spui.debug('WARNING: component does not have contentDocument.location: '
+componentId);
wait = 500;
break;
}
else if (docURL == 'about:blank') {
spui.debug('WARNING: component URL is [about:blank]: '+componentId);
wait = 500;
break;
}
else if(String(contentDoc.documentElement).indexOf("XULElement") < 0) {
spui.debug('WARNING: ' + contentDoc.URL + ' is not xul - '+contentDoc.documentElement);
wait = 500;
break;
}
} while (false);
if (wait) {
accumulator += wait;
setTimeout("establishRemoteSPUILink('"+componentId+"',"
+accumulator+");",wait); // Try again later
return;
}
var iframestyle = String(iframe.getAttribute('style'));
var indhi = iframestyle.indexOf("hidden;");
if(indhi >= 0) {
iframe.setAttribute('style', iframestyle.substring(0,indhi) + "visible;" +iframestyle.substring(indhi + "hidden;".length));
}
if (!('spui' in contentDoc))
{
// Here is where we make some special browser functions available to the
// remote document
contentDoc.spui = new Object();
// JMC: Pass the id in to the component here
contentDoc.spui.componentId = componentId.substring(componentId.indexOf("|")+1,componentId.length);
// JMC: Save pointer to iframe parent, for resizing, etc
contentDoc.spui.iframe = iframe;
// JMC: Todo - Push modification time of local supported.rdf into variable for tool tip
// loadURI(uri) - loads URI in the main content window
contentDoc.spui.loadURI = function(uri) {
if (gPrefService.getCharPref("browser.tabs.personaltoolbarbutton.open") == 'overwrite') {
loadURI(uri);
} else {
this.loadURIInTab(uri);
}
};
// loadURIInTab(uri) - loads URI in a new tab
contentDoc.spui.loadURIInTab = function(uri) {
var theTab = gBrowser.addTabAt(uri);
if (!gPrefService.getBoolPref("browser.tabs.loadInBackground"))
gBrowser.selectedTab = theTab;
};
// JMC - Support for favicon locating for newsticker icons, etc
contentDoc.spui.getFaviconURI = function(fullurl) {
var ios = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var aURI = ios.newURI(fullurl, null, null);
return gBrowser.buildFavIconString(aURI);
};
// debug(text) - debug output
contentDoc.spui.debug = function(text) {
spui.debug(componentId+': '+text.replace(/\n/, " -- "));
};
contentDoc.spui.trackData = function(commandObject) {
perfmon.trackData(commandObject);
};
contentDoc.spui.resizeComponent = function(newWidth) {
contentDoc.spui.iframe.setAttribute('style', 'width: ' + newWidth);
// JMC: Change size of preview and draggable as well
var parentComponent = document.getElementById(contentDoc.spui.iframe.id.substring(0,contentDoc.spui.iframe.id.length - 7));
var parentStack = parentComponent.firstChild;
for (var i =0; i < parentStack.childNodes.length; i++) {
var thisChild = parentStack.childNodes[i];
if (thisChild.localName == "toolbarbutton") { // Preview and Draggable Boxes
thisChild.setAttribute('style', 'width: ' + newWidth);
}
}
contentDoc.spui.iframe.setAttribute('style', 'width: ' + newWidth);
reshuffleToolbars(true);
};
// allow getting of preferences that start with "spui."
contentDoc.spui.getPref = function(prefName) {
//contentDoc.spui.debug("getPref called with: " + prefName);
var prefService = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
var thesePrefs = prefService.getBranch("spui.");
var prefType = thesePrefs.getPrefType(prefName);
var userPrefValue = "";
switch (prefType) {
case thesePrefs.PREF_STRING:
userPrefValue = thesePrefs.getCharPref(prefName);
break;
case thesePrefs.PREF_INT:
userPrefValue = thesePrefs.getIntPref(prefName);
break;
case thesePrefs.PREF_BOOL:
userPrefValue = thesePrefs.getBoolPref(prefName);
break;
}
return userPrefValue;
};
// Wrapper for getting localized prefs (per button by componentId)
contentDoc.spui.getLocalPref = function (prefName) {
var userPrefValue = contentDoc.spui.getPref(contentDoc.spui.componentId + "." + prefName);
if (!userPrefValue) {
userPrefValue = contentDoc.spui.getPref(prefName);
}
return userPrefValue;
};
// Wrapper for setting localized prefs (per button by componentId)
contentDoc.spui.setLocalPref = function (prefName, prefValue, prefType) {
return contentDoc.spui.setPref(contentDoc.spui.componentId + "." + prefName, prefValue, prefType);
};
contentDoc.spui.clearLocalPref = function (prefName) {
var branch = "spui." + contentDoc.spui.componentId + "."
if(prefName && prefName.length > 0) {
branch += prefName + ".";
}
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var thesePrefs = prefService.getBranch(branch);
thesePrefs.deleteBranch("");
};
// allow setting of preferences that start with "spui."
contentDoc.spui.setPref = function(prefName, prefValue, prefType) {
//contentDoc.spui.debug("setPref called with: " + prefName +", " + prefValue);
var prefService = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
var thesePrefs = prefService.getBranch("spui.");
switch (prefType) {
case "STRING":
thesePrefs.setCharPref(prefName, prefValue);
break;
case "INT":
thesePrefs.setIntPref(prefName, prefValue);
break;
case "BOOL":
thesePrefs.setBoolPref(prefName, prefValue);
break;
}
};
contentDoc.spui.setHomePage = function(aUrl, bAppend) {
var prefService = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
if (bAppend) {
var homePage = prefService.getComplexValue("browser.startup.homepage", Components.interfaces.nsIPrefLocalizedString).data;
if(homePage) {
newHomePage = homePage + "|" + aUrl;
} else {
newHomePage = aUrl;
}
prefService.setCharPref("browser.startup.homepage", newHomePage);
} else {
prefService.setCharPref("browser.startup.homepage", aUrl);
}
};
contentDoc.spui.getHomePage = function() {
var prefService = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
return prefService.getComplexValue("browser.startup.homepage", Components.interfaces.nsIPrefLocalizedString).data;
};
// loadRDF(rdf, observer) - returns a datasource
contentDoc.spui.loadRDF = function(rdf, observer) {
var RDFService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
.getService(Components.interfaces.nsIRDFService);
var ds = RDFService.GetDataSource(rdf);
ds.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
ds.QueryInterface(Components.interfaces.nsIRDFXMLSink);
ds.addXMLSinkObserver(observer);
return ds;
};
contentDoc.spui.httpRequest = null;
contentDoc.spui.lastRequestURL = null;
contentDoc.spui.idleTimerId=null;
/* contentDoc.spui.requestServerData
* Makes an XMLHttp Request to the server for data.
*/
contentDoc.spui.requestServerData = function(requestURL, callbackFunc) {
// JMC: Finding memleak
/*
if (contentDoc.spui.httpRequest){
spui.debug("contentDoc.spui.httpRequest = null");
contentDoc.spui.httpRequest = null;
}
contentDoc.spui.httpRequest = new XMLHttpRequest();
contentDoc.spui.httpRequest.onload = callbackFunc;
*/
contentDoc.spui.debug("contentDoc.spui.requestServerData : requestURL = " + requestURL + "\n");
var requestAnswered;
if(!contentDoc.spui.getPref("isIdleAble") || !contentDoc.spui.lastRequestURL || iframe.contentWindow.screenX > 0 - 5000 && iframe.contentWindow.screenY > 0 - 2000 && iframe.getAttribute('isActive') == 'true') {
var httpRequest = new XMLHttpRequest();
httpRequest.onload = callbackFunc;
//Make the connection and send our data
try {
// contentDoc.spui.httpRequest.open("GET", requestURL, true, null, null);
// contentDoc.spui.httpRequest.send('');
contentDoc.spui.lastRequestURL = requestURL;
httpRequest.open("GET", requestURL, true, null, null);
httpRequest.send('');
contentDoc.spui.debug("query done\n");
requestAnswered = true;
}
catch (e){
dump('An error has occured calling the external site: '+e);
requestAnswered = false;
httpRequest=null; // Clean up the httpRequest
}
}
else {
contentDoc.spui.debug(" isActive=" + iframe.getAttribute('isActive') + " screenY=" + iframe.contentWindow.screenY + " screenX=" + iframe.contentWindow.screenX + "\n");
requestAnswered = false;
}
contentDoc.spui.debug("contentDoc.spui.requestServerData : requestAnswered = " + requestAnswered + "\n");
// Check to see if the contentDoc.spui.idleTimerId is aready set,
// if it is, clear it for the restart.
if(!requestAnswered) {
contentDoc.spui.debug("Idle Request");
if(contentDoc.spui.idleTimerId){
contentDoc.spui.debug("Clearing contentDoc.spui.idleTimerId");
clearTimeout(contentDoc.spui.idleTimerId);
contentDoc.spui.idleTimerId=null;
}
// try to get data from server in every 5 seconds if the previous request was not completed
contentDoc.spui.idleTimerId = setTimeout(function() { contentDoc.spui.requestServerData(requestURL, callbackFunc); }, spui.k_idleTimer);
contentDoc.spui.debug("contentDoc.spui.idleTimerId = setTimeout\n");
}
return true;
};
contentDoc.spui.phpRequestExecute = contentDoc.spui.requestServerData;
contentDoc.spui.getBrowserVersion = function () {
return spui.SPUI_BROWSER_VERSION;
};
contentDoc.spui.getBrowserTheme = function () {
return spui.SPUI_BROWSER_THEME;
};
contentDoc.spui.getBrowserLocale = function () {
return spui.SPUI_BROWSER_LOCALE;
};
// wrapper for window.openDialog
contentDoc.spui.openDialog = function(contentURL, opener, title, width, height) {
var SPUI_DIALOG = "chrome://browser/content/spuiDialog.xul";
contentDoc.spui.debug('openDialog('+SPUI_DIALOG+': '+contentURL+');');
var args = new Object();
args.contentURL = contentURL;
args.opener = opener;
if (!title) title = 'SPUI Dialog';
args.title = title;
if (!width) width = 300;
if (width < 100) width = 200;
if (width > 500) width = 500;
if (!height) height = 300;
if (height < 100) height = 200;
if (height > 500) height = 500;
var dialog = window.openDialog(SPUI_DIALOG, 'spuiDialog',
'chrome,modal=yes,resizable=no,centerscreen,'
+'width='+width+',height='+height+','
+'toolbars=no,menus=no',
args);
};
contentDoc.spui.openSidebar = function(SideBarName) {
RevealPanel(SideBarName);
};
// refreshDatasource(containerId, dsName) - refreshes a remote RDF datasource
contentDoc.spui.refreshDataSource = function(containerId, dsName, callbackFunc) {
contentDoc.spui.debug('refreshDataSource('+containerId+', '+dsName+')');
var container = contentDoc.getElementById(containerId);
if (!container) {
contentDoc.spui.debug(' container element not found: '+containerId);
return;
}
// We don't refresh when the menupopup is open, since this can cause crashes
else if (container.localName == 'menupopup' &&
('open' in container) && container.open) {
contentDoc.spui.debug(' Skipped refresh since menupopup open.');
return;
}
// Do not refresh if tray is not shown
else if(container.localName == 'vbox' && contentDoc.spui.iframe.getAttribute('isActive') != 'true') {
contentDoc.spui.debug(containerId + ' is not active ');
return;
}
else if(iframe.contentWindow.screenX < 0 - 5000 || iframe.contentWindow.screenY < 0 - 2000) {
contentDoc.spui.debug(' browser is off screen ' + " screenY " + iframe.contentWindow.screenY + " screenX " + iframe.contentWindow.screenX + "\n");
return;
}
// Get datasources
else if (!container.database) {
contentDoc.spui.debug(' container element "'+containerId+'" has no database');
return;
}
var sources = container.database.GetDataSources();
var count = 0;
while (sources.hasMoreElements()) {
// TODO: check the dsName and only refresh the appropriate ds
var ds = sources.getNext();
ds.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
ds.Refresh(false);
ds.QueryInterface(Components.interfaces.nsIRDFXMLSink);
if (('loadObserver' in container) && (container.loadObserver)) {
ds.removeXMLSinkObserver(container.loadObserver);
container.loadObserver = 0;
}
container.loadObserver = {
onBeginLoad : function(sink){},
onInterrupt : function(sink){},
onResume : function(sink){},
onError : function(sink,status,msg){},
onEndLoad : function(sink) {
// this.debug('refresh observer onEndLoad()!');
// rebuild() will crash browser if menupopup is open!!!
if ((container.localName == 'menupopup') && container.open) return;
// this.debug(' rebuilding '+container.localName+'...');
try {
this.container.builder.rebuild();
} catch (ex) {
this.debug(' exeption: '+ex);
// No point in continuing to observe the datasource if there
// is no builder. (This probably means the remote XUL document
// has been reloaded.)
this.ds.removeXMLSinkObserver(this);
}
if (callbackFunc && callbackFunc in this.iframeWindow) {
this.iframeWindow[callbackFunc]();
this.debug ( "Making the callback to " + callbackFunc);
}
},
debug : function(msg) {
this.parent.debug('loadObserver: '+msg);
}
};
container.loadObserver.parent = contentDoc.spui;
container.loadObserver.iframeWindow = iframe.contentWindow;
container.loadObserver.container = container;
container.loadObserver.ds = ds;
ds.addXMLSinkObserver(container.loadObserver);
count++;
}
// contentDoc.spui.debug(' Initiated asynchronous refresh for '+count+' datasource(s)');
};
contentDoc.spui.getGlobal = function (name) {
return spui.GLOBALS[name];
};
contentDoc.spui.setGlobal = function (name, obj) {
spui.GLOBALS[name] = obj;
};
// spui.debug('Established link with SPUI component: '+componentId);
}
if ('spuiInit' in iframe.contentWindow) {
spui.debug("calling spuiInit() " + componentId);
iframe.contentWindow.spuiInit();
/*
if ('initBackground' in iframe.contentWindow) {
iframe.contentWindow.initBackground(iframe.boxObject.x, 0);
}
*/
reshuffleToolbars(true);
} else { // Check back for init after javascript loads in
wait = 1000;
accumulator += wait;
setTimeout("establishRemoteSPUILink('"+componentId+"'," +accumulator+");",wait); // Try again later
}
}