PK
5 content/scrapbook/PK
5/f f content/scrapbook/about.js
const kVERSION = "1.2.0.8";
const kBUILD_TEXT = " (Build ID 20061215)";
const kUPDATE_URL = "http://amb.vis.ne.jp/mozilla/scrapbook/update.rdf";
var gAboutString;
var gUpdateImage;
var gUpdateLabel;
function SB_initAbout()
{
gAboutString = document.getElementById("sbAboutString");
gUpdateImage = document.getElementById("sbUpdateImage");
gUpdateLabel = document.getElementById("sbUpdateLabel");
document.getElementById("sbAboutVersion").value = "Version " + kVERSION + kBUILD_TEXT;
gUpdateImage.src = "chrome://scrapbook/skin/status_busy.gif";
try {
gUpdateLabel.value = gAboutString.getFormattedString("updatingMessage", ["ScrapBook"]);
} catch(ex) {
gUpdateLabel.value = gAboutString.getString("updatingMsg");
}
setTimeout(SB_setUpdateInfo, 500);
}
function SB_visit(aElem)
{
var href = aElem.getAttribute("href");
if ( href.indexOf("@") > 0 )
sbCommonUtils.loadURL("mailto:" + href, false);
else
sbCommonUtils.loadURL(href, true);
window.close();
}
function SB_secret()
{
window.opener.top.document.getElementById("sidebar-box").width = window.opener.top.outerWidth < 800 ? 190 : 200;
setTimeout(function() { window.opener.top.document.getElementById("statusbar-display").label = "Transferring data from www.mozilla.org..."; }, 0);
}
function SB_setUpdateInfo()
{
var req = new XMLHttpRequest();
req.open("GET", kUPDATE_URL + "?ver=" + kVERSION);
req.onload = function(aEvent)
{
try {
var latestVer = req.responseXML.getElementsByTagNameNS("http://www.mozilla.org/2004/em-rdf#", "version")[0].textContent;
const VER_COMP = Components.classes['@mozilla.org/xpcom/version-comparator;1'].getService(Components.interfaces.nsIVersionComparator);
if ( VER_COMP.compare(latestVer, kVERSION) > 0 ) {
try {
gUpdateLabel.value = gAboutString.getFormattedString("updateAvailableMessage", [latestVer, kVERSION]);
} catch(ex) {
gUpdateLabel.value = gAboutString.getFormattedString("updateAvailableMsg", [latestVer]);
}
gUpdateLabel.className = "link";
gUpdateLabel.style.fontWeight = "bold";
gUpdateLabel.onclick = function(){ sbCommonUtils.loadURL("http://amb.vis.ne.jp/mozilla/scrapbook/"); window.close(); };
} else {
try {
gUpdateLabel.setAttribute("value", gAboutString.getFormattedString("updateNoUpdateMessage", ["ScrapBook"]));
} catch(ex) {
gUpdateLabel.setAttribute("value", gAboutString.getString("updateNoUpdateMsg"));
}
}
} catch(ex) {
SB_onUpdateError();
}
gUpdateImage.src = "";
};
try {
req.setRequestHeader("User-Agent", "ScrapBook/" + kVERSION);
req.overrideMimeType("application/xml");
req.send(null);
} catch(ex) {
req.abort();
SB_onUpdateError();
}
}
function SB_onUpdateError()
{
gUpdateLabel.value = gAboutString.getString("updateErrorMessage");
gUpdateImage.src = "";
}
PK
{5] ] content/scrapbook/about.xul
%mainDTD;
%aboutDTD;
%mozaboutDTD;
]>
PK
2!56 content/scrapbook/cache.xul
PK
5*vs s content/scrapbook/calculate.js
var sbCalcService = {
get TREE() { return document.getElementById("sbTree"); },
get STRING() { return document.getElementById("sbPropString"); },
get STATUS() { return document.getElementById("sbCalcMessage"); },
get PROGRESS() { return document.getElementById("sbCalcProgress"); },
dirEnum : null,
treeItems : [],
count : 0,
total : 0,
grandSum : 0,
invalidCount : 0,
exec : function()
{
sbDataSource.init();
var resEnum = sbDataSource.data.GetAllResources();
while ( resEnum.hasMoreElements() )
{
var res = resEnum.getNext();
if ( !sbDataSource.isContainer(res) ) this.total++;
}
var dataDir = sbCommonUtils.getScrapBookDir().clone();
dataDir.append("data");
this.dirEnum = dataDir.directoryEntries;
this.processAsync();
},
processAsync : function()
{
if ( !this.dirEnum.hasMoreElements() )
{
this.finish();
return;
}
this.count++;
var dir = this.dirEnum.getNext().QueryInterface(Components.interfaces.nsIFile);
if ( dir.isDirectory() )
{
var id = dir.leafName;
var bytes = sbPropService.getTotalFileSize(id)[0];
this.grandSum += bytes;
var res = sbCommonUtils.RDF.GetResource("urn:scrapbook:item" + id);
var valid = sbDataSource.exists(res);
var icon = sbDataSource.getProperty(res, "icon");
if ( !icon ) icon = sbCommonUtils.getDefaultIcon(sbDataSource.getProperty(res, "type"));
this.treeItems.push([
id,
sbDataSource.getProperty(res, "type"),
sbDataSource.getProperty(res, "title"),
icon,
bytes,
sbPropService.formatFileSize(bytes),
valid,
]);
if ( !valid ) this.invalidCount++;
this.STATUS.label = this.STRING.getString("CALCULATING") + "... (" + this.count + "/" + this.total + ")";
this.PROGRESS.value = Math.round(this.count / this.total * 100);
}
setTimeout(function() { sbCalcService.processAsync(); }, 0);
},
finish : function()
{
sbCustomTreeUtil.heapSort(this.treeItems, 4);
this.treeItems.reverse();
this.initTree();
this.STATUS.label = "";
this.PROGRESS.hidden = true;
var msg = sbPropService.formatFileSize(this.grandSum);
msg += " " + this.STRING.getFormattedString("ITEMS_COUNT", [this.count]);
document.getElementById("sbCalcTotalSize").value = msg;
msg = ( this.invalidCount == 0 ) ? this.STRING.getString("DIAGNOSIS_OK") : this.STRING.getFormattedString("DIAGNOSIS_NG", [this.invalidCount]);
document.getElementById("sbCalcDiagnosis").value = msg;
this.checkDoubleEntries();
},
initTree : function()
{
var colIDs = [
"sbTreeColTitle",
"sbTreeColSize",
"sbTreeColState",
];
var treeView = new sbCustomTreeView(colIDs, this.treeItems);
treeView.getCellText = function(row, col)
{
switch ( col.index )
{
case 0 : return this._items[row][2]; break;
case 1 : return this._items[row][5]; break;
case 2 : return this._items[row][6] ? "" : sbCalcService.STRING.getString("INVALID"); break;
}
};
treeView.getImageSrc = function(row, col)
{
if ( col.index == 0 ) return this._items[row][3];
};
treeView.getCellProperties = function(row, col, properties)
{
if ( this._items[row][6] && col.index != 0 ) return;
properties.AppendElement(ATOM_SERVICE.getAtom(!this._items[row][6] ? "invalid" : this._items[row][1]));
};
treeView.cycleHeader = function(col)
{
sbCustomTreeUtil.sortItems(sbCalcService, col.element);
};
this.TREE.view = treeView;
},
checkDoubleEntries : function()
{
var hashTable = {};
var resList = sbDataSource.flattenResources(sbCommonUtils.RDF.GetResource("urn:scrapbook:root"), 0, true);
for ( var i = 0; i < resList.length; i++ )
{
if ( resList[i].Value in hashTable )
{
alert("ScrapBook WARNING: Found double entries.\n" + sbDataSource.getProperty(resList[i], "title"));
var parRes = sbDataSource.findParentResource(resList[i]);
if ( parRes ) sbDataSource.removeFromContainer(parRes.Value, resList[i]);
}
hashTable[resList[i].Value] = true;
}
},
};
var sbCalcController = {
get CURRENT_TREEITEM()
{
return sbCalcService.treeItems[sbCalcService.TREE.currentIndex];
},
createPopupMenu : function(aEvent)
{
var valid = this.CURRENT_TREEITEM[6];
document.getElementById("sbPopupRemove").setAttribute("disabled", valid);
document.getElementById("sbPopupProperty").setAttribute("disabled", !valid);
},
onDblClick : function(aEvent)
{
if ( aEvent.button == 0 && aEvent.originalTarget.localName == "treechildren" ) this.open(false);
},
open : function(tabbed)
{
var res = sbCommonUtils.RDF.GetResource("urn:scrapbook:item" + this.CURRENT_TREEITEM[0]);
sbCommonUtils.loadURL(sbDataSource.getURL(res), tabbed);
},
remove : function()
{
if ( this.CURRENT_TREEITEM[6] ) return;
var id = this.CURRENT_TREEITEM[0];
if ( id.length != 14 ) return;
if ( sbCommonUtils.removeDirSafety(sbCommonUtils.getContentDir(id), true) )
{
sbCalcService.treeItems.splice(sbCalcService.TREE.currentIndex, 1);
sbCalcService.initTree();
}
},
forward : function(aCommand)
{
var id = this.CURRENT_TREEITEM[0];
switch ( aCommand )
{
case "P" : window.openDialog("chrome://scrapbook/content/property.xul", "", "modal,centerscreen,chrome" ,id); break;
case "L" : sbController.launch(sbCommonUtils.getContentDir(id));
default : break;
}
},
};
PK
*4CB content/scrapbook/calculate.xul
%mainDTD;
%treeDTD;
%propDTD;
%calcDTD;
]>
PK
5?] ] content/scrapbook/capture.js
var gURLs = [];
var gDepths = [];
var gRefURL = "";
var gShowDetail = false;
var gResName = "";
var gResIdx = 0;
var gReferItem = null;
var gOption = {};
var gFile2URL = {};
var gURL2Name = {};
var gPreset = [];
var gContext = "";
function SB_trace(aMessage)
{
document.getElementById("sbCaptureTextbox").value = aMessage;
}
function SB_initCapture()
{
var myURLs = window.arguments[0];
gRefURL = window.arguments[1];
gShowDetail = window.arguments[2];
gResName = window.arguments[3];
gResIdx = window.arguments[4];
gReferItem = window.arguments[5];
gOption = window.arguments[6];
gFile2URL = window.arguments[7];
gPreset = window.arguments[8];
if ( gReferItem )
{
gContext = "indepth";
gURL2Name[unescape(gReferItem.source)] = "index";
}
else if ( gPreset )
{
gContext = gPreset[1] == "index" ? "renew" : "renew-deep";
if ( gContext == "renew-deep" )
{
var contDir = sbCommonUtils.getContentDir(gPreset[0]);
var file = contDir.clone();
file.append("sb-file2url.txt");
if ( !file.exists() ) { alert("ScrapBook ERROR: Could not find 'sb-file2url.txt'."); window.close(); }
var lines = sbCommonUtils.readFile(file).split("\n");
for ( var i = 0; i < lines.length; i++ )
{
var arr = lines[i].split("\t");
if ( arr.length == 2 ) gFile2URL[arr[0]] = arr[1];
}
file = sbCommonUtils.getContentDir(gPreset[0]).clone();
file.append("sb-url2name.txt");
if ( !file.exists() ) { alert("ScrapBook ERROR: Could not find 'sb-url2name.txt'."); window.close(); }
lines = sbCommonUtils.readFile(file).split("\n");
for ( i = 0; i < lines.length; i++ )
{
var arr = lines[i].split("\t");
if ( arr.length == 2 )
{
gURL2Name[arr[0]] = arr[1];
if ( arr[1] == gPreset[1] ) myURLs = [arr[0]];
}
}
gPreset[3] = gFile2URL;
if ( !myURLs[0] ) { alert("ScrapBook ERROR: Could not find the source URL for " + gPreset[1] + ".html."); window.close(); }
}
}
else gContext = "link";
if ( !gOption ) gOption = {};
if ( !("script" in gOption ) ) gOption["script"] = false;
if ( !("images" in gOption ) ) gOption["images"] = true;
sbInvisibleBrowser.init();
sbCaptureTask.init(myURLs);
gURLs.length == 1 ? sbCaptureTask.start() : sbCaptureTask.countDown();
}
function SB_splitByAnchor(aURL)
{
var pos = 0;
return ( (pos = aURL.indexOf("#")) < 0 ) ? [aURL, ""] : [aURL.substring(0, pos), aURL.substring(pos, aURL.length)];
}
function SB_suggestName(aURL)
{
var baseName = sbCommonUtils.validateFileName(sbCommonUtils.splitFileName(sbCommonUtils.getFileName(aURL))[0]);
baseName = baseName.toLowerCase();
if ( baseName == "index" ) baseName = "default";
if ( !baseName ) baseName = "default";
var name = baseName + ".html";
var seq = 0;
while ( gFile2URL[name] ) name = baseName + "_" + sbContentSaver.leftZeroPad3(++seq) + ".html";
name = sbCommonUtils.splitFileName(name)[0];
gFile2URL[name + ".html"] = aURL;
gFile2URL[name + ".css"] = true;
return name;
}
function SB_fireNotification(aItem)
{
var win = sbCommonUtils.WINDOW.getMostRecentWindow("navigator:browser");
win.sbCaptureObserverCallback.onCaptureComplete(aItem);
}
var sbCaptureTask = {
get INTERVAL() { return 3; },
get LISTBOX() { return document.getElementById("sbCaptureListbox"); },
get STRING() { return document.getElementById("sbCaptureString"); },
get URL() { return gURLs[this.index]; },
index : 0,
contentType : "",
isDocument : false,
canRefresh : true,
sniffer : null,
seconds : 3,
timerID : 0,
forceExit : 0,
init : function(myURLs)
{
if ( gContext != "indepth" && myURLs.length == 1 )
{
this.LISTBOX.collapsed = true;
this.LISTBOX.setAttribute("class", "plain");
document.getElementById("sbCaptureSkipButton").hidden = true;
}
else
{
this.LISTBOX.setAttribute("rows", 10);
}
if ( gContext == "indepth" )
{
var button = document.getElementById("sbCaptureFilterButton");
button.hidden = false;
button.nextSibling.hidden = false;
button.firstChild.firstChild.label += " (" + sbCommonUtils.getRootHref(gReferItem.source) + ")" ;
button.firstChild.firstChild.nextSibling.label += " (" + sbCommonUtils.getBaseHref(gReferItem.source) + ")";
}
for ( var i = 0; i < myURLs.length; i++ ) this.add(myURLs[i], 1);
},
add : function(aURL, aDepth)
{
if ( gURLs.length > 10000 ) return;
if ( !aURL.match(/^(http|https|ftp|file):\/\//i) ) return;
if ( gContext == "indepth" )
{
if ( aDepth > gOption["inDepth"] ) {
return;
}
aURL = SB_splitByAnchor(aURL)[0];
if ( !gOption["isPartial"] && aURL == gReferItem.source ) return;
if ( gURLs.indexOf(aURL) != -1 ) return;
}
gURLs.push(aURL);
gDepths.push(aDepth);
var listitem = document.createElement("listitem");
listitem.setAttribute("label", aDepth + " [" + (gURLs.length - 1) + "] " + aURL);
listitem.setAttribute("type", "checkbox");
listitem.setAttribute("checked", this.filter(gURLs.length - 1));
this.LISTBOX.appendChild(listitem);
},
start : function(aOverriddenURL)
{
this.seconds = -1;
this.toggleStartPause(true);
this.toggleSkipButton(true);
this.LISTBOX.getItemAtIndex(this.index).setAttribute("indicated", true);
if ( this.index > 0 ) this.LISTBOX.getItemAtIndex(this.index - 1).removeAttribute("indicated");
this.LISTBOX.ensureIndexIsVisible(this.index);
var listitem = this.LISTBOX.getItemAtIndex(this.index);
listitem.setAttribute("disabled", true);
if ( !listitem.checked )
{
this.next(true);
return;
}
this.contentType = "";
this.isDocument = true;
this.canRefresh = true;
var url = aOverriddenURL || gURLs[this.index];
SB_trace(this.STRING.getString("CONNECT") + "... " + url);
if ( url.indexOf("file://") == 0 ) {
sbInvisibleBrowser.load(url);
} else {
this.sniffer = new sbHeaderSniffer(url, gRefURL);
this.sniffer.httpHead();
}
},
succeed : function()
{
this.LISTBOX.getItemAtIndex(this.index).setAttribute("status", "succeed");
this.next(false);
},
fail : function(aErrorMsg)
{
if ( aErrorMsg ) SB_trace(aErrorMsg);
var listitem = this.LISTBOX.getItemAtIndex(this.index);
listitem.setAttribute("label", gDepths[this.index] + " [" + this.index + "] " + aErrorMsg);
listitem.setAttribute("status", "failure");
if ( gURLs.length > 1 ) {
this.next(true);
} else {
this.toggleStartPause(false);
}
},
next : function(quickly)
{
this.toggleStartPause(true);
this.toggleSkipButton(false);
this.LISTBOX.getItemAtIndex(this.index).setAttribute("disabled", true);
this.LISTBOX.getItemAtIndex(this.index).removeAttribute("indicated");
if ( this.sniffer ) this.sniffer.onHttpSuccess = function(){};
sbInvisibleBrowser.ELEMENT.stop();
if ( ++this.index >= gURLs.length ) {
this.finalize();
} else {
if ( quickly || gURLs[this.index].indexOf("file://") == 0 ) {
window.setTimeout(function(){ sbCaptureTask.start(); }, 0);
} else {
this.seconds = this.INTERVAL;
sbCaptureTask.countDown();
}
}
},
countDown : function()
{
SB_trace(this.STRING.getFormattedString("WAITING", [sbCaptureTask.seconds]) + "...");
if ( --this.seconds > 0 )
this.timerID = window.setTimeout(function(){ sbCaptureTask.countDown(); }, 1000);
else
this.timerID = window.setTimeout(function(){ sbCaptureTask.start(); }, 1000);
},
finalize : function()
{
if ( gContext == "indepth" )
{
sbCrossLinker.invoke();
}
else
{
if ( gURLs.length > 1 ) SB_fireNotification(null);
window.setTimeout(function(){ window.close(); }, 1000);
}
},
activate : function()
{
this.toggleStartPause(true);
if ( this.seconds < 0 )
sbCaptureTask.start();
else
this.countDown();
},
pause : function()
{
this.toggleStartPause(false);
if ( this.seconds < 0 ) {
sbInvisibleBrowser.ELEMENT.stop();
} else {
this.seconds++;
window.clearTimeout(this.timerID);
}
},
abort : function()
{
if ( gContext != "indepth" ) window.close();
if ( ++this.forceExit > 2 ) window.close();
if ( this.index < gURLs.length - 1 ) { this.index = gURLs.length - 1; this.next(); }
},
toggleStartPause : function(allowPause)
{
document.getElementById("sbCapturePauseButton").disabled = false;
document.getElementById("sbCapturePauseButton").hidden = !allowPause;
document.getElementById("sbCaptureStartButton").hidden = allowPause;
document.getElementById("sbCaptureTextbox").disabled = !allowPause;
},
toggleSkipButton : function(willEnable)
{
document.getElementById("sbCaptureSkipButton").disabled = !willEnable;
},
filter : function(i)
{
return true;
},
applyFilter : function(type)
{
switch ( type )
{
case "D" : var ref = sbCommonUtils.getRootHref(gReferItem.source).toLowerCase(); this.filter = function(i){ return gURLs[i].toLowerCase().indexOf(ref) == 0; }; break;
case "L" : var ref = sbCommonUtils.getBaseHref(gReferItem.source).toLowerCase(); this.filter = function(i){ return gURLs[i].toLowerCase().indexOf(ref) == 0; }; break;
case "S" :
var ret = { value : "" };
if ( !sbCommonUtils.PROMPT.prompt(window, "ScrapBook", this.STRING.getString("FILTER_BY_STRING"), ret, null, {}) ) return;
if ( ret.value ) this.filter = function(i){ return gURLs[i].toLowerCase().indexOf(ret.value.toLowerCase()) != -1; };
break;
case "N" : this.filter = function(i){ return true; }; break;
case "F" : this.filter = function(i){ return false; }; break;
case "I" : this.filter = function(i){ return !sbCaptureTask.LISTBOX.getItemAtIndex(i).checked; }; break;
default : return;
}
for ( var i = this.index; i < gURLs.length; i++ )
{
this.LISTBOX.getItemAtIndex(i).checked = this.filter(i);
}
},
};
var sbInvisibleBrowser = {
get ELEMENT() { return document.getElementById("sbCaptureBrowser"); },
fileCount : 0,
onload : null,
init : function()
{
this.ELEMENT.webProgress.addProgressListener(this, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
this.onload = function(){ sbInvisibleBrowser.execCapture(); };
this.ELEMENT.addEventListener("load", sbInvisibleBrowser.onload, true);
},
refreshEvent : function(aEvent)
{
this.ELEMENT.removeEventListener("load", this.onload, true);
this.onload = aEvent;
this.ELEMENT.addEventListener("load", this.onload, true);
},
load : function(aURL)
{
this.fileCount = 0;
this.ELEMENT.docShell.allowJavascript = gOption["script"];
this.ELEMENT.docShell.allowImages = gOption["images"];
this.ELEMENT.docShell.allowMetaRedirects = false;
this.ELEMENT.docShell.QueryInterface(Components.interfaces.nsIDocShellHistory).useGlobalHistory = false;
this.ELEMENT.loadURI(aURL, null, null);
},
execCapture : function()
{
SB_trace(sbCaptureTask.STRING.getString("CAPTURE_START"));
document.getElementById("sbCapturePauseButton").disabled = true;
sbCaptureTask.toggleSkipButton(false);
var ret = null;
var preset = gReferItem ? [gReferItem.id, SB_suggestName(sbCaptureTask.URL), gOption, gFile2URL, gDepths[sbCaptureTask.index]] : null;
if ( gPreset ) preset = gPreset;
if ( this.ELEMENT.contentDocument.body && sbCaptureTask.isDocument )
{
var metaElems = this.ELEMENT.contentDocument.getElementsByTagName("meta");
for ( var i = 0; i < metaElems.length; i++ )
{
if ( metaElems[i].hasAttribute("http-equiv") && metaElems[i].hasAttribute("content") &&
metaElems[i].getAttribute("http-equiv").toLowerCase() == "refresh" &&
metaElems[i].getAttribute("content").match(/URL\=(.*)$/i) )
{
var newURL = sbCommonUtils.resolveURL(sbCaptureTask.URL, RegExp.$1);
if ( newURL != sbCaptureTask.URL && sbCaptureTask.canRefresh )
{
gURLs[sbCaptureTask.index] = newURL;
sbCaptureTask.canRefresh = false;
this.ELEMENT.loadURI(newURL, null, null);
return;
}
}
}
ret = sbContentSaver.captureWindow(this.ELEMENT.contentWindow, false, gShowDetail, gResName, gResIdx, preset, gContext);
}
else
{
var type = sbCaptureTask.contentType.match(/image/i) ? "image" : "file";
ret = sbContentSaver.captureFile(sbCaptureTask.URL, gRefURL ? gRefURL : sbCaptureTask.URL, type, gShowDetail, gResName, gResIdx, preset, gContext);
}
if ( ret )
{
if ( gContext == "indepth" )
{
gURL2Name[unescape(sbCaptureTask.URL)] = ret[0];
gFile2URL = ret[1];
}
else if ( gContext == "renew-deep" )
{
gFile2URL = ret[1];
var contDir = sbCommonUtils.getContentDir(gPreset[0]);
var txtFile = contDir.clone();
txtFile.append("sb-file2url.txt");
var txt = "";
for ( var f in gFile2URL ) txt += f + "\t" + gFile2URL[f] + "\n";
sbCommonUtils.writeFile(txtFile, txt, "UTF-8");
}
}
else
{
if ( gShowDetail ) window.close();
SB_trace(sbCaptureTask.STRING.getString("CAPTURE_ABORT"));
sbCaptureTask.fail("");
}
},
QueryInterface : function(aIID)
{
if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsIXULBrowserWindow) ||
aIID.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus)
{
if ( aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_START )
{
SB_trace(sbCaptureTask.STRING.getString("LOADING") + "... " + (++this.fileCount) + " " + (sbCaptureTask.URL ? sbCaptureTask.URL : this.ELEMENT.contentDocument.title));
}
},
onProgressChange : function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress)
{
if ( aCurTotalProgress != aMaxTotalProgress )
{
SB_trace(sbCaptureObserverCallback.getString("TRANSFER_DATA") + "... (" + aCurTotalProgress + " Bytes)");
}
},
onStatusChange : function() {},
onLocationChange : function() {},
onSecurityChange : function() {},
};
var sbCrossLinker = {
get ELEMENT(){ return document.getElementById("sbCaptureBrowser"); },
index : -1,
baseURL : "",
nameList : [],
XML : null,
rootNode : null,
nodeHash : {},
invoke : function()
{
if ( !sbDataSource.data ) sbDataSource.init();
sbDataSource.setProperty(sbCommonUtils.RDF.GetResource("urn:scrapbook:item" + gReferItem.id), "type", "site");
sbDataSource.flush();
sbInvisibleBrowser.refreshEvent(function(){ sbCrossLinker.exec(); });
this.ELEMENT.docShell.allowImages = false;
sbInvisibleBrowser.onStateChange = function(aWebProgress, aRequest, aStateFlags, aStatus)
{
if ( aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_START )
{
SB_trace(sbCaptureTask.STRING.getFormattedString("REBUILD_LINKS", [sbCrossLinker.index + 1, sbCrossLinker.nameList.length]) + "... "
+ ++sbInvisibleBrowser.fileCount + " : " + sbCrossLinker.nameList[sbCrossLinker.index] + ".html");
}
};
this.baseURL = sbCommonUtils.IO.newFileURI(sbCommonUtils.getContentDir(gReferItem.id)).spec;
this.nameList.push("index");
for ( var url in gURL2Name )
{
this.nameList.push(gURL2Name[url]);
}
this.XML = document.implementation.createDocument("", "", null);
this.rootNode = this.XML.createElement("site");
this.start();
},
start : function()
{
if ( ++this.index < this.nameList.length )
{
dump("sbCrossLinker::start [" + this.index + "] " + this.nameList[this.index] + "\n");
sbInvisibleBrowser.fileCount = 0;
this.ELEMENT.loadURI(this.baseURL + this.nameList[this.index] + ".html", null, null);
}
else
{
SB_trace(sbCaptureTask.STRING.getString("REBUILD_LINKS_COMPLETE"));
this.flushXML();
SB_fireNotification(gReferItem);
window.setTimeout(function(){ window.close(); }, 1000);
}
},
exec : function()
{
if ( this.ELEMENT.currentURI.scheme != "file" )
{
return;
}
sbContentSaver.frameList = sbContentSaver.flattenFrames(this.ELEMENT.contentWindow);
if ( !this.nodeHash[this.nameList[this.index]] )
{
this.nodeHash[this.nameList[this.index]] = this.createNode(this.nameList[this.index], gReferItem.title);
this.nodeHash[this.nameList[this.index]].setAttribute("title", sbDataSource.sanitize(this.ELEMENT.contentTitle));
}
else
{
this.nodeHash[this.nameList[this.index]].setAttribute("title", sbDataSource.sanitize(this.ELEMENT.contentTitle));
}
for ( var f = 0; f < sbContentSaver.frameList.length; f++ )
{
var doc = sbContentSaver.frameList[f].document;
if ( !doc.links ) continue;
var shouldSave = false;
var linkList = doc.links;
for ( var i = 0; i < linkList.length; i++ )
{
var urlLR = SB_splitByAnchor(unescape(linkList[i].href));
if ( gURL2Name[urlLR[0]] )
{
var name = gURL2Name[urlLR[0]];
linkList[i].href = name + ".html" + urlLR[1];
linkList[i].setAttribute("indepth", "true");
if ( !this.nodeHash[name] )
{
var text = linkList[i].text ? linkList[i].text.replace(/\r|\n|\t/g, " ") : "";
if ( text.replace(/\s/g, "") == "" ) text = "";
this.nodeHash[name] = this.createNode(name, text);
if ( !this.nodeHash[name] ) this.nodeHash[name] = name;
this.nodeHash[this.nameList[this.index]].appendChild(this.nodeHash[name]);
}
shouldSave = true;
}
}
if ( shouldSave )
{
var rootNode = doc.getElementsByTagName("html")[0];
var src = "";
src = sbContentSaver.surroundByTags(rootNode, rootNode.innerHTML);
src = sbContentSaver.doctypeToString(doc.doctype) + src;
var file = sbCommonUtils.getContentDir(gReferItem.id);
file.append(sbCommonUtils.getFileName(doc.location.href));
sbCommonUtils.writeFile(file, src, doc.characterSet);
}
}
this.forceReloading(gReferItem.id, this.nameList[this.index]);
this.start();
},
createNode : function(aName, aText)
{
aText = sbCommonUtils.crop(aText, 100);
var node = this.XML.createElement("page");
node.setAttribute("file", aName + ".html");
node.setAttribute("text", sbDataSource.sanitize(aText));
return node;
},
flushXML : function()
{
this.rootNode.appendChild(this.nodeHash["index"]);
this.XML.appendChild(this.rootNode);
var src = "";
src += '\n';
src += '\n';
src += (new XMLSerializer()).serializeToString(this.XML).replace(/>\n<");
src += '\n';
var xslFile = sbCommonUtils.getScrapBookDir().clone();
xslFile.append("sitemap.xsl");
if ( !xslFile.exists() ) sbCommonUtils.saveTemplateFile("chrome://scrapbook/skin/sitemap.xsl", xslFile);
var contDir = sbCommonUtils.getContentDir(gReferItem.id);
var xmlFile = contDir.clone();
xmlFile.append("sitemap.xml");
sbCommonUtils.writeFile(xmlFile, src, "UTF-8");
var txt = "";
var txtFile1 = contDir.clone();
txtFile1.append("sb-file2url.txt");
for ( var f in gFile2URL ) txt += f + "\t" + gFile2URL[f] + "\n";
sbCommonUtils.writeFile(txtFile1, txt, "UTF-8");
txt = "";
var txtFile2 = contDir.clone();
txtFile2.append("sb-url2name.txt");
for ( var u in gURL2Name ) txt += u + "\t" + gURL2Name[u] + "\n";
sbCommonUtils.writeFile(txtFile2, txt, "UTF-8");
},
forceReloading : function(aID, aName)
{
try {
var win = sbCommonUtils.WINDOW.getMostRecentWindow("navigator:browser");
var nodes = win.gBrowser.mTabContainer.childNodes;
for ( var i = 0; i < nodes.length; i++ )
{
var uri = win.gBrowser.getBrowserForTab(nodes[i]).currentURI.spec;
if ( uri.indexOf("/data/" + aID + "/" + aName + ".html") > 0 )
{
win.gBrowser.getBrowserForTab(nodes[i]).reload();
}
}
} catch(ex) {
}
},
};
function sbHeaderSniffer(aURLSpec, aRefURLSpec)
{
this.URLSpec = aURLSpec;
this.refURLSpec = aRefURLSpec;
}
sbHeaderSniffer.prototype = {
_URL : Components.classes['@mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURL),
_channel : null,
_headers : null,
httpHead : function()
{
this._channel = null;
this._headers = {};
try {
this._URL.spec = this.URLSpec;
this._channel = sbCommonUtils.IO.newChannelFromURI(this._URL).QueryInterface(Components.interfaces.nsIHttpChannel);
this._channel.loadFlags = this._channel.LOAD_BYPASS_CACHE;
this._channel.setRequestHeader("User-Agent", navigator.userAgent, false);
if ( this.refURLSpec ) this._channel.setRequestHeader("Referer", this.refURLSpec, false);
} catch(ex) {
this.onHttpError("Invalid URL");
}
try {
this._channel.requestMethod = "HEAD";
this._channel.asyncOpen(this, this);
} catch(ex) {
this.onHttpError(ex);
}
},
getHeader : function(aHeader)
{
try { return this._channel.getResponseHeader(aHeader); } catch(ex) { return ""; }
},
getStatus : function()
{
try { return this._channel.responseStatus; } catch(ex) { return ""; }
},
visitHeader : function(aHeader, aValue)
{
this._headers[aHeader] = aValue;
},
onDataAvailable : function(aRequest, aContext, aInputStream, aOffset, aCount) {},
onStartRequest : function(aRequest, aContext) {},
onStopRequest : function(aRequest, aContext, aStatus) { this.onHttpSuccess(); },
onHttpSuccess : function()
{
sbCaptureTask.contentType = this.getHeader("Content-Type");
var httpStatus = this.getStatus();
SB_trace(sbCaptureTask.STRING.getString("CONNECT_SUCCESS") + " (Content-Type: " + sbCaptureTask.contentType + ")");
switch ( httpStatus )
{
case 404 : sbCaptureTask.fail(sbCaptureTask.STRING.getString("HTTP_STATUS_404") + " (404 Not Found)"); return;
case 403 : sbCaptureTask.fail(sbCaptureTask.STRING.getString("HTTP_STATUS_403") + " (403 Forbidden)"); return;
case 500 : sbCaptureTask.fail("500 Internal Server Error"); return;
}
var redirectURL = this.getHeader("Location");
if ( redirectURL )
{
if ( redirectURL.indexOf("http") != 0 ) redirectURL = this._URL.resolve(redirectURL);
sbCaptureTask.start(redirectURL);
return;
}
if ( !sbCaptureTask.contentType )
{
sbCaptureTask.contentType = "text/html";
}
if ( sbCaptureTask.contentType.match(/(text|html|xml)/i) )
{
sbCaptureTask.isDocument = true;
sbInvisibleBrowser.load(this.URLSpec);
}
else
{
sbCaptureTask.isDocument = false;
if ( gContext == "indepth" ) {
sbCaptureTask.next(true);
} else {
sbInvisibleBrowser.execCapture();
}
}
},
onHttpError : function(aErrorMsg)
{
sbCaptureTask.fail(sbCaptureTask.STRING.getString("CONNECT_FAILURE") + " (" + aErrorMsg + ")");
},
};
sbCaptureObserverCallback.getString = function(aBundleName)
{
return document.getElementById("sbOverlayString").getString(aBundleName);
},
sbCaptureObserverCallback.trace = function(aText)
{
SB_trace(aText);
};
sbCaptureObserverCallback.onCaptureComplete = function(aItem)
{
if ( gContext != "indepth" && gURLs.length == 1 ) SB_fireNotification(aItem);
if ( gContext == "renew" || gContext == "renew-deep" )
{
sbCrossLinker.forceReloading(gPreset[0], gPreset[1]);
sbDataSource.init();
var res = sbCommonUtils.RDF.GetResource("urn:scrapbook:item" + gPreset[0]);
sbDataSource.setProperty(res, "chars", aItem.chars);
if ( gPreset[5] ) sbDataSource.setProperty(res, "type", "");
}
sbCaptureTask.succeed();
};
PK
8!5~
content/scrapbook/capture.xul
PK
5Ds: s: content/scrapbook/combine.js
var sbCommonUtils;
var sbDataSource;
var sbCombineService = {
get WIZARD() { return document.getElementById("sbCombineWizard"); },
get STRING() { return document.getElementById("sbCombineString"); },
get LISTBOX() { return document.getElementById("sbCombineListbox"); },
get curID() { return this.idList[this.index]; },
get curRes() { return this.resList[this.index]; },
index : 0,
idList : [],
resList : [],
parList : [],
option : {},
prefix : "",
postfix : "",
dropObserver :
{
getSupportedFlavours : function()
{
var flavours = new FlavourSet();
flavours.appendFlavour("moz/rdfitem");
return flavours;
},
onDragOver : function(event, flavour, session) {},
onDragExit : function(event, session) {},
onDrop : function(event, transferData, session)
{
var idxList = window.top.sbTreeHandler.getSelection(false, 2);
idxList.forEach(function(aIdx)
{
var res = window.top.sbTreeHandler.TREE.builderView.getResourceAtIndex(aIdx);
var parRes = window.top.sbTreeHandler.getParentResource(aIdx);
sbCombineService.add(res, parRes);
});
},
},
init : function()
{
gOption = { "script" : true, "images" : true };
if ( window.top.location.href != "chrome://scrapbook/content/manage.xul" )
{
document.documentElement.collapsed = true;
return;
}
window.top.document.getElementById("mbToolbarButton").disabled = true;
sbCommonUtils = window.top.sbCommonUtils;
sbDataSource = window.top.sbDataSource;
this.index = 0;
sbFolderSelector2.init();
this.WIZARD.getButton("back").onclick = function(){ sbCombineService.undo(); };
this.WIZARD.getButton("cancel").hidden = true;
this.updateButtons();
},
done : function()
{
window.top.document.getElementById("mbToolbarButton").disabled = false;
},
add : function(aRes, aParRes)
{
if ( this.resList.indexOf(aRes) != -1 ) return;
var type = sbDataSource.getProperty(aRes, "type");
if ( type == "folder" ) return;
if ( type == "site" ) alert(this.STRING.getString("WARN_ABOUT_INDEPTH"));
var icon = sbDataSource.getProperty(aRes, "icon");
if ( !icon ) icon = sbCommonUtils.getDefaultIcon(type);
var listItem = this.LISTBOX.appendItem(sbDataSource.getProperty(aRes, "title"));
listItem.setAttribute("class", "listitem-iconic");
listItem.setAttribute("image", icon);
this.idList.push(sbDataSource.getProperty(aRes, "id"));
this.resList.push(aRes);
this.parList.push(aParRes);
this.updateButtons();
},
undo : function()
{
if ( this.idList.length == 0 ) return;
this.LISTBOX.removeItemAt(this.idList.length - 1);
this.idList.pop();
this.resList.pop();
this.parList.pop();
this.updateButtons();
},
updateButtons : function()
{
this.WIZARD.canRewind = this.idList.length > 0;
this.WIZARD.canAdvance = this.idList.length > 1;
},
initPreview : function()
{
this.WIZARD.canRewind = false;
this.WIZARD.canAdvance = false;
this.WIZARD.getButton("back").onclick = null;
this.WIZARD.getButton("finish").label = this.STRING.getString("FINISH_BUTTON_LABEL");
this.WIZARD.getButton("finish").disabled = true;
this.option["R"] = document.getElementById("sbCombineOptionRemove").checked;
sbInvisibleBrowser.init();
sbInvisibleBrowser.ELEMENT.removeEventListener("load", sbInvisibleBrowser.onload, true);
sbInvisibleBrowser.onload = function(){ sbPageCombiner.exec(); };
sbInvisibleBrowser.ELEMENT.addEventListener("load", sbInvisibleBrowser.onload, true);
this.next();
},
next : function()
{
if ( this.index < this.idList.length )
{
this.prefix = "(" + (this.index + 1) + "/" + this.idList.length + ") ";
this.postfix = sbDataSource.getProperty(this.resList[this.index], "title");
var type = sbDataSource.getProperty(this.resList[this.index], "type");
if ( type == "file" || type == "bookmark" )
sbPageCombiner.exec(type);
else
sbInvisibleBrowser.load(sbCommonUtils.getBaseHref(sbDataSource.data.URI) + "data/" + this.curID + "/index.html");
}
else
{
this.prefix = "";
this.postfix = "combine.html";
this.donePreview();
}
},
donePreview : function()
{
var htmlFile = sbCommonUtils.getScrapBookDir();
htmlFile.append("combine.html");
sbCommonUtils.writeFile(htmlFile, sbPageCombiner.htmlSrc, "UTF-8");
var cssFile = sbCommonUtils.getScrapBookDir();
cssFile.append("combine.css");
sbCommonUtils.writeFile(cssFile, sbPageCombiner.cssText, "UTF-8");
sbInvisibleBrowser.refreshEvent(function(){ sbCombineService.showBrowser(); });
sbInvisibleBrowser.load(sbCommonUtils.convertFilePathToURL(htmlFile.path));
},
showBrowser : function()
{
this.toggleElements(false);
sbInvisibleBrowser.ELEMENT.onclick = function(aEvent){ aEvent.preventDefault(); };
this.WIZARD.getButton("finish").disabled = false;
this.WIZARD.getButton("finish").onclick = function(){ sbCombineService.finish(); };
},
finish : function()
{
this.WIZARD.getButton("finish").disabled = true;
this.toggleElements(true);
SB_trace(sbCaptureTask.STRING.getString("CAPTURE_START"));
setTimeout(function(){ sbContentSaver.captureWindow(sbInvisibleBrowser.ELEMENT.contentWindow, false, false, sbFolderSelector2.selection, 0, null); }, 0);
},
toggleElements : function(isProgressMode)
{
sbInvisibleBrowser.ELEMENT.collapsed = isProgressMode;
document.getElementById("sbCaptureTextbox").collapsed = !isProgressMode;
},
onCombineComplete : function(aItem)
{
var newRes = sbCommonUtils.RDF.GetResource("urn:scrapbook:item" + aItem.id);
sbDataSource.setProperty(newRes, "type", "combine");
sbDataSource.setProperty(newRes, "source", sbDataSource.getProperty(this.resList[0], "source"));
var newIcon = sbDataSource.getProperty(this.resList[0], "icon");
if ( newIcon.match(/\d{14}/) ) newIcon = "resource://scrapbook/data/" + aItem.id + "/" + sbCommonUtils.getFileName(newIcon);
sbDataSource.setProperty(newRes, "icon", newIcon);
var newComment = "";
for ( var i = 0; i < this.resList.length; i++ )
{
var comment = sbDataSource.getProperty(this.resList[i], "comment");
if ( comment ) newComment += comment + " __BR__ ";
}
if ( newComment ) sbDataSource.setProperty(newRes, "comment", newComment);
return newRes;
},
};
var sbPageCombiner = {
get BROWSER(){ return document.getElementById("sbCaptureBrowser"); },
get BODY() { return this.BROWSER.contentDocument.body; },
htmlSrc : "",
cssText : "",
offsetTop : 0,
isTargetCombined : false,
exec : function(aType)
{
this.isTargetCombined = false;
if ( sbCombineService.index == 0 )
{
this.htmlSrc += '';
this.htmlSrc += '
';
this.htmlSrc += '';
this.htmlSrc += '';
this.htmlSrc += '' + sbDataSource.getProperty(sbCombineService.curRes, "title") + '';
this.htmlSrc += '';
this.htmlSrc += '';
this.htmlSrc += '';
this.htmlSrc += '\n';
}
if ( aType == "file" || aType == "bookmark" )
{
this.htmlSrc += this.getCiteHTML(aType);
}
else
{
this.processDOMRecursively(this.BROWSER.contentDocument.body);
if ( !this.isTargetCombined ) this.htmlSrc += this.getCiteHTML(aType);
this.htmlSrc += this.surroundDOM();
this.cssText += this.surroundCSS();
this.offsetTop += this.BROWSER.contentDocument.body.offsetHeight;
}
if ( sbCombineService.index == sbCombineService.idList.length - 1 )
{
this.htmlSrc += '\n\n\n';
}
sbCombineService.index++;
sbCombineService.next();
},
getCiteHTML : function(aType)
{
var src = '\n\n';
var title = sbCommonUtils.crop(sbDataSource.getProperty(sbCombineService.curRes, "title") , 100);
var linkURL = "";
switch ( aType )
{
case "file" :
var htmlFile = sbCommonUtils.getContentDir(sbCombineService.curID);
htmlFile.append("index.html");
var isMatch = sbCommonUtils.readFile(htmlFile).match(/URL=\.\/([^\"]+)\"/);
if ( isMatch ) linkURL = "./data/" + sbCombineService.curID + "/" + RegExp.$1;
break;
case "note" :
linkURL = ""; break;
default :
linkURL = sbDataSource.getProperty(sbCombineService.curRes, "source"); break;
}
var icon = sbDataSource.getProperty(sbCombineService.curRes, "icon");
if ( !icon ) icon = sbCommonUtils.getDefaultIcon(aType);
if ( icon.indexOf("resource://") == 0 && icon.indexOf(sbCombineService.curID) > 0 )
{
icon = "./data/" + sbCombineService.curID + "/" + sbCommonUtils.getFileName(icon);
}
src += '\n';
return src;
},
surroundDOM : function()
{
if ( this.BODY.localName.toUpperCase() != "BODY" )
{
alert(sbCombineService.STRING.getString("CANNOT_COMBINE_FRAMES") + "\n" + sbDataSource.getProperty(sbCombineService.curRes, "title"));
this.BROWSER.stop();
window.location.reload();
}
var divElem = this.BROWSER.contentDocument.createElement("DIV");
var bodyStyle = "";
if ( this.BODY.hasAttribute("class") ) divElem.setAttribute("class", this.BODY.getAttribute("class"));
if ( this.BODY.hasAttribute("bgcolor") ) bodyStyle += "background-color: " + this.BODY.getAttribute("bgcolor") + ";";
if ( this.BODY.background ) bodyStyle += "background-image: url('" + this.BODY.background + "');";
if ( bodyStyle ) divElem.setAttribute("style", bodyStyle);
this.BROWSER.contentDocument.body.appendChild(divElem);
var childNodes = this.BODY.childNodes;
for ( var i = childNodes.length - 2; i >= 0; i-- )
{
var nodeName = childNodes[i].nodeName.toUpperCase();
if ( nodeName == "DIV" && childNodes[i].hasAttribute("class") && childNodes[i].getAttribute("class") == "scrapbook-sticky" )
childNodes[i].style.top = (parseInt(childNodes[i].style.top) + this.offsetTop) + "px";
else if ( nodeName == "CITE" && childNodes[i].hasAttribute("class") && childNodes[i].getAttribute("class") == "scrapbook-header" ) continue;
else if ( nodeName == "DIV" && childNodes[i].id.match(/^item\d{14}$/) ) continue;
divElem.insertBefore(childNodes[i], divElem.firstChild);
}
divElem.id = "item" + sbCombineService.curID;
divElem.appendChild(this.BROWSER.contentDocument.createTextNode("\n"));
return this.BODY.innerHTML;
},
surroundCSS : function()
{
var ret = "";
for ( var i = 0; i < this.BROWSER.contentDocument.styleSheets.length; i++ )
{
if ( this.BROWSER.contentDocument.styleSheets[i].href.indexOf("chrome") == 0 ) continue;
var cssRules = this.BROWSER.contentDocument.styleSheets[i].cssRules;
for ( var j = 0; j < cssRules.length; j++ )
{
var cssText = cssRules[j].cssText;
if ( !this.isTargetCombined )
{
cssText = cssText.replace(/^html /, "");
cssText = cssText.replace(/^body /, "");
cssText = cssText.replace(/^body, /, ", ");
cssText = cssText.replace(/position: absolute; /, "position: relative; ");
cssText = "div#item" + sbCombineService.curID + " " + cssText;
}
var blanketLR = cssText.split("{");
if ( blanketLR[0].indexOf(",") > 0 )
{
blanketLR[0] = blanketLR[0].replace(/,/g, ", div#item" + sbCombineService.curID);
cssText = blanketLR.join("{");
}
ret += this.inspectCSSText(cssText) + "\n";
}
}
return ret + "\n\n";
},
inspectCSSText : function(aCSSText)
{
var i = 0;
var RE = new RegExp(/ url\(([^\'\)]+)\)/);
while ( aCSSText.match(RE) && ++i < 10 )
{
aCSSText = aCSSText.replace(RE, " url('./data/" + sbCombineService.curID + "/" + RegExp.$1 + "')");
}
return aCSSText;
},
processDOMRecursively : function(rootNode)
{
for ( var curNode = rootNode.firstChild; curNode != null; curNode = curNode.nextSibling )
{
if ( curNode.nodeName == "#text" || curNode.nodeName == "#comment" ) continue;
curNode = this.inspectNode(curNode);
this.processDOMRecursively(curNode);
}
},
inspectNode : function(aNode)
{
switch ( aNode.nodeName.toUpperCase() )
{
case "IMG" : case "EMBED" : case "IFRAME" :
if ( aNode.src ) aNode.setAttribute("src", aNode.src);
break;
case "OBJECT" :
if ( aNode.data ) aNode.setAttribute("data", aNode.data);
break;
case "BODY" : case "TABLE" : case "TD" :
aNode = this.setAbsoluteURL(aNode, "background");
break;
case "INPUT" :
if ( aNode.type.toLowerCase() == "image" ) aNode = this.setAbsoluteURL(aNode, "src");
break;
case "A" :
case "AREA" :
if ( aNode.href.indexOf("file://") == 0 ) aNode.setAttribute("href", aNode.href);
break;
case "CITE" :
if ( aNode.hasAttribute("class") && aNode.getAttribute("class") == "scrapbook-header" ) this.isTargetCombined = true;
break;
}
if ( aNode.style && aNode.style.cssText )
{
var newCSStext = this.inspectCSSText(aNode.style.cssText);
if ( newCSStext ) aNode.setAttribute("style", newCSStext);
}
return aNode;
},
setAbsoluteURL : function(aNode, aAttr)
{
if ( aNode.getAttribute(aAttr) )
{
aNode.setAttribute(aAttr, sbCommonUtils.resolveURL(this.BROWSER.currentURI.spec, aNode.getAttribute(aAttr)));
}
return aNode;
},
};
sbCaptureObserverCallback.onCaptureComplete = function(aItem)
{
var newRes = sbCombineService.onCombineComplete(aItem);
if ( sbCombineService.option["R"] )
{
if ( sbCombineService.resList.length != sbCombineService.parList.length ) return;
var rmIDs = window.top.sbController.removeInternal(sbCombineService.resList, sbCombineService.parList);
if ( rmIDs ) SB_trace(window.top.sbMainService.STRING.getFormattedString("ITEMS_REMOVED", [rmIDs.length]));
}
SB_fireNotification(aItem);
setTimeout(function()
{
window.top.sbManageService.toggleRightPane("sbToolbarCombine");
window.top.sbMainService.locate(newRes);
}, 500);
}
sbInvisibleBrowser.onStateChange = function(aWebProgress, aRequest, aStateFlags, aStatus)
{
if ( aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_START )
{
SB_trace(sbCaptureTask.STRING.getString("LOADING") + "... " + sbCombineService.prefix + (++this.fileCount) + " " + sbCombineService.postfix);
}
};
PK
5I
content/scrapbook/combine.xul
%mainDTD;
%propDTD;
%detailDTD;
%combineDTD;
]>
&sb.combine.dragdrop;
PK
5=A. . content/scrapbook/common.js
const NS_SCRAPBOOK = "http://amb.vis.ne.jp/mozilla/scrapbook-rdf#";
function ScrapBookItem(aID)
{
this.id = aID;
this.type = "";
this.title = "";
this.chars = "";
this.icon = "";
this.source = "";
this.comment = "";
}
var sbCommonUtils = {
get RDF() { return Components.classes['@mozilla.org/rdf/rdf-service;1'].getService(Components.interfaces.nsIRDFService); },
get RDFC() { return Components.classes['@mozilla.org/rdf/container;1'].getService(Components.interfaces.nsIRDFContainer); },
get RDFCU() { return Components.classes['@mozilla.org/rdf/container-utils;1'].getService(Components.interfaces.nsIRDFContainerUtils); },
get DIR() { return Components.classes['@mozilla.org/file/directory_service;1'].getService(Components.interfaces.nsIProperties); },
get IO() { return Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService); },
get UNICODE() { return Components.classes['@mozilla.org/intl/scriptableunicodeconverter'].getService(Components.interfaces.nsIScriptableUnicodeConverter); },
get WINDOW() { return Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator); },
get PROMPT() { return Components.classes['@mozilla.org/embedcomp/prompt-service;1'].getService(Components.interfaces.nsIPromptService); },
get PREF() { return Components.classes['@mozilla.org/preferences;1'].getService(Components.interfaces.nsIPrefBranch); },
newItem : function(aID)
{
return { id : aID || "", type : "", title : "", chars : "", icon : "", source : "", comment : "" };
},
getScrapBookDir : function()
{
var dir;
try {
var isDefault = this.PREF.getBoolPref("scrapbook.data.default");
dir = this.PREF.getComplexValue("scrapbook.data.path", Components.interfaces.nsIPrefLocalizedString).data;
dir = this.convertPathToFile(dir);
} catch(ex) {
isDefault = true;
}
if ( isDefault )
{
dir = this.DIR.get("ProfD", Components.interfaces.nsIFile);
dir.append("ScrapBook");
}
if ( !dir.exists() )
{
dir.create(dir.DIRECTORY_TYPE, 0700);
}
return dir;
},
getContentDir : function(aID, aSuppressCreate)
{
if ( !aID || aID.length != 14 )
{
alert("ScrapBook FATAL ERROR: Failed to get directory '" + aID + "'.");
return null;
}
var dir = this.getScrapBookDir().clone();
dir.append("data");
if ( !dir.exists() ) dir.create(dir.DIRECTORY_TYPE, 0700);
dir.append(aID);
if ( !dir.exists() )
{
if ( aSuppressCreate )
{
return null;
}
dir.create(dir.DIRECTORY_TYPE, 0700);
}
return dir;
},
removeDirSafety : function(aDir, check)
{
var file;
try {
if ( check && !aDir.leafName.match(/^\d{14}$/) ) return;
var fileEnum = aDir.directoryEntries;
while ( fileEnum.hasMoreElements() )
{
file = fileEnum.getNext().QueryInterface(Components.interfaces.nsIFile);
if ( file.isFile() ) file.remove(false);
}
file = aDir;
if ( aDir.isDirectory() ) aDir.remove(false);
return true;
} catch(ex) {
alert("ScrapBook ERROR: Failed to remove file '" + file.leafName + "'.\n" + ex);
return false;
}
},
loadURL : function(aURL, tabbed)
{
var win = this.WINDOW.getMostRecentWindow("navigator:browser");
var browser = win.document.getElementById("content");
if ( tabbed ) {
browser.selectedTab = browser.addTab(aURL);
} else {
browser.loadURI(aURL);
}
},
rebuildGlobal : function()
{
var winEnum = this.WINDOW.getEnumerator("navigator:browser");
while ( winEnum.hasMoreElements() )
{
var win = winEnum.getNext().QueryInterface(Components.interfaces.nsIDOMWindow);
try {
win.sbMenuHandler.shouldRebuild = true;
win.document.getElementById("sidebar").contentWindow.sbTreeHandler.TREE.builder.rebuild();
win.document.getElementById("sidebar").contentWindow.sbListHandler.LIST.builder.rebuild();
} catch(ex) {
}
}
},
getTimeStamp : function(advance)
{
var dd = new Date;
if ( advance ) dd.setTime(dd.getTime() + 1000 * advance);
var y = dd.getFullYear();
var m = dd.getMonth() + 1; if ( m < 10 ) m = "0" + m;
var d = dd.getDate(); if ( d < 10 ) d = "0" + d;
var h = dd.getHours(); if ( h < 10 ) h = "0" + h;
var i = dd.getMinutes(); if ( i < 10 ) i = "0" + i;
var s = dd.getSeconds(); if ( s < 10 ) s = "0" + s;
return y.toString() + m.toString() + d.toString() + h.toString() + i.toString() + s.toString();
},
getRootHref : function(aURLSpec)
{
var url = Components.classes['@mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURL);
url.spec = aURLSpec;
return url.scheme + "://" + url.host + "/";
},
getBaseHref : function(sURI)
{
var pos, base;
base = ( (pos = sURI.indexOf("?")) != -1 ) ? sURI.substring(0, pos) : sURI;
base = ( (pos = base.indexOf("#")) != -1 ) ? base.substring(0, pos) : base;
base = ( (pos = base.lastIndexOf("/")) != -1 ) ? base.substring(0, ++pos) : base;
return base;
},
getFileName : function(aURI)
{
var pos, name;
name = ( (pos = aURI.indexOf("?")) != -1 ) ? aURI.substring(0, pos) : aURI;
name = ( (pos = name.indexOf("#")) != -1 ) ? name.substring(0, pos) : name;
name = ( (pos = name.lastIndexOf("/")) != -1 ) ? name.substring(++pos) : name;
return name;
},
splitFileName : function(aFileName)
{
var pos = aFileName.lastIndexOf(".");
var ret = [];
if ( pos != -1 ) {
ret[0] = aFileName.substring(0, pos);
ret[1] = aFileName.substring(pos + 1, aFileName.length);
} else {
ret[0] = aFileName;
ret[1] = "";
}
return ret;
},
validateFileName : function(aFileName)
{
aFileName = aFileName.replace(/[\"\?!~`]+/g, "");
aFileName = aFileName.replace(/[\*\&]+/g, "+");
aFileName = aFileName.replace(/[\\\/\|\:;]+/g, "-");
aFileName = aFileName.replace(/[\<]+/g, "(");
aFileName = aFileName.replace(/[\>]+/g, ")");
aFileName = aFileName.replace(/[\s]+/g, "_");
aFileName = aFileName.replace(/[%]+/g, "@");
return aFileName;
},
resolveURL : function(aBaseURL, aRelURL)
{
try {
var baseURLObj = this.convertURLToObject(aBaseURL);
return baseURLObj.resolve(aRelURL);
} catch(ex) {
alert("ScrapBook ERROR: Failed to resolve URL.\n" + aBaseURL + "\n" + aRelURL);
}
},
crop : function(aString, aMaxLength)
{
return aString.length > aMaxLength ? aString.substring(0, aMaxLength) + "..." : aString;
},
readFile : function(aFile)
{
try {
var istream = Components.classes['@mozilla.org/network/file-input-stream;1'].createInstance(Components.interfaces.nsIFileInputStream);
istream.init(aFile, 1, 0, false);
var sstream = Components.classes['@mozilla.org/scriptableinputstream;1'].createInstance(Components.interfaces.nsIScriptableInputStream);
sstream.init(istream);
var content = sstream.read(sstream.available());
sstream.close();
istream.close();
return content;
}
catch(ex)
{
return false;
}
},
writeFile : function(aFile, aContent, aChars)
{
if ( aFile.exists() ) aFile.remove(false);
try {
aFile.create(aFile.NORMAL_FILE_TYPE, 0666);
this.UNICODE.charset = aChars;
aContent = this.UNICODE.ConvertFromUnicode(aContent);
var ostream = Components.classes['@mozilla.org/network/file-output-stream;1'].createInstance(Components.interfaces.nsIFileOutputStream);
ostream.init(aFile, 2, 0x200, false);
ostream.write(aContent, aContent.length);
ostream.close();
}
catch(ex)
{
alert("ScrapBook ERROR: Failed to write file: " + aFile.leafName);
}
},
writeIndexDat : function(aItem, aFile)
{
if ( !aFile )
{
aFile = this.getContentDir(aItem.id).clone();
aFile.append("index.dat");
}
var content = "";
for ( var prop in aItem )
{
content += prop + "\t" + aItem[prop] + "\n";
}
this.writeFile(aFile, content, "UTF-8");
},
saveTemplateFile : function(aURISpec, aFile)
{
if ( aFile.exists() ) return;
var uri = Components.classes['@mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURL);
uri.spec = aURISpec;
var WBP = Components.classes['@mozilla.org/embedding/browser/nsWebBrowserPersist;1'].createInstance(Components.interfaces.nsIWebBrowserPersist);
WBP.saveURI(uri, null, null, null, null, aFile);
},
convertToUnicode : function(aString, aCharset)
{
if ( !aString ) return "";
try {
this.UNICODE.charset = aCharset;
aString = this.UNICODE.ConvertToUnicode(aString);
} catch(ex) {
}
return aString;
},
convertPathToFile : function(aPath)
{
var aFile = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
aFile.initWithPath(aPath);
return aFile;
},
convertFilePathToURL : function(aFilePath)
{
var tmpFile = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
tmpFile.initWithPath(aFilePath);
return this.IO.newFileURI(tmpFile).spec;
},
convertURLToObject : function(aURLString)
{
var aURL = Components.classes['@mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURI);
aURL.spec = aURLString;
return aURL;
},
convertURLToFile : function(aURLString)
{
var aURL = this.convertURLToObject(aURLString);
if ( !aURL.schemeIs("file") ) return;
try {
var fileHandler = this.IO.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
return fileHandler.getFileFromURLSpec(aURLString);
} catch(ex) {
}
},
execProgram : function(aExecFilePath, args)
{
var execfile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
try {
execfile.initWithPath(aExecFilePath);
if ( !execfile.exists() ) {
alert("ScrapBook ERROR: File does not exist.\n" + aExecFilePath);
return;
}
process.init(execfile);
process.run(false, args, args.length);
} catch (ex) {
alert("ScrapBook ERROR: File is not executable.\n" + aExecFilePath);
}
},
getFocusedWindow : function()
{
var win = document.commandDispatcher.focusedWindow;
if ( !win || win == window || win instanceof Components.interfaces.nsIDOMChromeWindow ) win = window._content;
return win;
},
getDefaultIcon : function(type)
{
switch ( type )
{
case "folder" : return "chrome://scrapbook/skin/treefolder.png"; break;
case "note" : return "chrome://scrapbook/skin/treenote.png"; break;
default : return "chrome://scrapbook/skin/treeitem.png"; break;
}
},
getBoolPref : function(aName, aDefVal)
{
try {
return this.PREF.getBoolPref(aName);
} catch(ex) {
return aDefVal;
}
},
escapeComment : function(aStr)
{
if ( aStr.length > 10000 ) alert("NOTICE: Too long comment makes ScrapBook slow.");
return aStr.replace(/\r|\n|\t/g, " __BR__ ");
},
openManageWindow : function(aRes, aModEltID)
{
window.openDialog("chrome://scrapbook/content/manage.xul", "ScrapBook:Manage", "chrome,centerscreen,all,resizable,dialog=no", aRes, aModEltID);
},
log : function(aMsg, aOpen)
{
const CONSOLE = Components.classes['@mozilla.org/consoleservice;1'].getService(Components.interfaces.nsIConsoleService);
CONSOLE.logStringMessage(aMsg);
},
};
function dumpObj(aObj, aLimit)
{
dump("\n\n----------------[DUMP_OBJECT]----------------\n\n");
for ( var i in aObj )
{
try {
dump(i + (aLimit ? "" : " -> " + aObj[i]) + "\n");
} catch(ex) {
dump("XXXXXXXXXX ERROR XXXXXXXXXX\n" + ex + "\n");
}
}
dump("\n\n");
}
PK
5ƥ content/scrapbook/customTree.js
const ATOM_SERVICE = Components.classes['@mozilla.org/atom-service;1'].getService(Components.interfaces.nsIAtomService);
function sbCustomTreeView(aColIDs, aItems)
{
this._items = aItems;
this._rowCount = aItems.length;
this.colIDs = aColIDs;
}
sbCustomTreeView.prototype =
{
get rowCount()
{
return this._rowCount;
},
getCellText: function(row, col)
{
return this._items[row][col.index];
},
setCellText: function(row, col, val)
{
this._items[row][col.index] = val;
},
setTree: function(tree)
{
this._treeBox = tree;
},
cycleHeader : function(colID, elem){},
getRowProperties : function(index, properties){},
getCellProperties : function(row, colID, properties){},
getColumnProperties : function(colID, colElem, properties){},
isContainer : function(row){},
isContainerOpen : function(row){},
isContainerEmpty : function(row){},
isSeparator : function(row){},
isSorted : function(row){},
canDrop : function(index, orient){},
canDropOn : function(index){},
canDropBeforeAfter : function(index, before){},
drop : function(index, orient){},
getParentIndex : function getParentIndex(index){ return -1; },
hasNextSibling : function(index, afterIndex){},
getLevel : function(index){},
getImageSrc : function(row, col){},
getProgressMode : function(row, colID){},
getCellValue : function(row, colID){},
selectionChanged : function(){},
cycleCell : function(row, colID){},
isEditable : function(row, colID){},
toggleOpenState : function(index){},
performAction : function(action){},
performActionOnRow : function(action, row){},
performActionOnCell : function(action, row, colID){},
};
var sbCustomTreeUtil = {
sortItems : function(aService, aColElem)
{
var asc = aColElem.getAttribute("sortDirection") == "descending";
var elems = aService.TREE.firstChild.childNodes;
for ( var i = 0; i < elems.length; i++ )
{
elems[i].removeAttribute("sortDirection");
}
if ( !asc ) {
aService.treeItems.reverse();
} else {
this.heapSort(aService.treeItems, aColElem.getAttribute("sortIndex"));
}
aColElem.setAttribute("sortDirection", asc ? "ascending" : "descending");
aService.initTree();
},
heapSort : function(array, k)
{
var h, i, j, n;
array[array.length] = array[0];
var N = array.length - 1;
for( h=N; h>0; h-- ) {
i = h;
n = array[i];
while( (j=i*2) <= N ) {
if( (j= array[j][k] ) break;
array[i] = array[j];
i = j;
}
array[i] = n;
}
while( N>1 ) {
n = array[N];
array[N] = array[1];
N--;
i = 1;
while( (j=i*2)<=N ) {
if( (j= array[j][k] ) break;
array[i] = array[j];
i = j;
}
array[i] = n;
}
for( i=0; i