TagSpaces is an offline, open source, document manager with tagging support
js code beautifying
uggrock0af7f38da22d
diff --git a/data/mozilla/firefoxos.api.js b/data/mozilla/firefoxos.api.jsindex 2ec358719..7587df478 100644--- a/data/mozilla/firefoxos.api.js+++ b/data/mozilla/firefoxos.api.js@@ -1,235 +1,226 @@/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that+ * Use of this source code is governed by a AGPL3 license that* can be found in the LICENSE file. */define(function(require, exports, module) {-"use strict";-- // Activating browser specific exports modul- console.log("Loading firefoxos.js..");-- var TSCORE = require("tscore");- var TSPOSTIO = require("tspostioapi");---- /* var directoryExist = function(dirPath) {- console.log("Checks if a directory exist: "+dirPath);- //TSPOSTIO.- }; */-- var createDirectoryIndex = function(dirPath) {- console.log("Creating index for directory: "+dirPath);- TSCORE.showLoadingAnimation();-- var directoryIndex = [];- TSPOSTIO.createDirectoryIndex(directoryIndex);- };-- var createDirectoryTree = function(dirPath) {- console.log("Creating directory index for: "+dirPath);- TSCORE.showLoadingAnimation();-- var directoyTree = [];- //console.log(JSON.stringify(directoyTree));- TSPOSTIO.createDirectoryTree(directoyTree);- };-- var createDirectory = function(dirPath) {- console.log("Creating directory: "+dirPath);- TSCORE.showLoadingAnimation();-- TSPOSTIO.createDirectory(dirPath);+ "use strict";- };+ // Activating browser specific exports modul+ console.log("Loading firefoxos.js..");- var renameFile = function(filePath, newFilePath) {- console.log("Renaming file: "+filePath+" to "+newFilePath);- TSCORE.showLoadingAnimation();-- TSPOSTIO.renameFile(filePath, newFilePath);- };-- var loadTextFile = function(filePath) {- console.log("Loading file: "+filePath);- TSCORE.showLoadingAnimation();-- TSPOSTIO.loadTextFile(content);- };-- var saveTextFile = function(filePath,content,overWrite) {- console.log("Saving file: "+filePath);- TSCORE.showLoadingAnimation();--- // Handling the UTF8 support for text files- var UTF8_BOM = "\ufeff";-- if(content.indexOf(UTF8_BOM) == 0) {- // already has a UTF8 bom- } else {- content = UTF8_BOM+content;- }-- var isNewFile = !pathUtils.existsSync(filePath);-- TSPOSTIO.saveTextFile(filePath, isNewFile);- };-- /*- http://rominirani.com/2013/08/16/firefox-os-tutorial-episode-9-device-storage/- listContents('sdcard');- listContents('videos');- listContents('music');- listContents('pictures');-- */- function listContents(storagename) {- //Clear up the list first- var files = navigator.getDeviceStorage(storagename);- var cursor = files.enumerate();- console.log("Listing storage!");- cursor.onsuccess = function () {- console.log("Listing storage success!");- var file = this.result;- if (file != null) {- //var imageElement = $('<img height="100" width="75">');- //imageElement.attr('src', window.URL.createObjectURL(file));- //$("<p>" + file.name + "," + file.lastModifiedDate + "," + file.type + "," + file.size + "</p>").appendTo('#results');- //imageElement.appendTo("#results");- console.log("file: " + file.name + "," + file.lastModifiedDate + "," + file.type + "," + file.size);- this.done = false;- } else {- this.done = true;- }- if (!this.done) {- this.continue();- }- };- cursor.onerror = function (e) {- console.log("Listing storage failed! "+e);- };- }+ var TSCORE = require("tscore");+ var TSPOSTIO = require("tspostioapi");- listContents('sdcard');--- var listDirectory = function(dirPath) {- console.log("Listing directory: "+dirPath);- TSCORE.showLoadingAnimation();--- TSPOSTIO.errorOpeningPath();-- var anotatedDirList = [],- dirList = []; // remove- for (var i=0; i < dirList.length; i++) {- var path = dirPath+TSCORE.dirSeparator+dirList[i];- var stats = fs.statSync(path);- //console.log('stats: ' + JSON.stringify(stats));- anotatedDirList.push({- "name": dirList[i],- "isFile": !stats.isDirectory(),- "size": stats.size,- "lmdt": stats.mtime,- "path": path- });- }- TSPOSTIO.listDirectory(anotatedDirList);---- };-- var deleteElement = function(path) {- console.log("Deleting: "+path);- TSCORE.showLoadingAnimation();-- TSPOSTIO.deleteElement(path);+ /* var directoryExist = function(dirPath) {+ console.log("Checks if a directory exist: "+dirPath);+ //TSPOSTIO.+ }; */- };-- var checkAccessFileURLAllowed = function() {- console.log("checkAccessFileURLAllowed function not relevant for node..");- };-- var checkNewVersion = function() {- console.log("Checking for new version...");- var cVer = TSCORE.Config.DefaultSettings["appVersion"]+"."+TSCORE.Config.DefaultSettings["appBuild"];- $.ajax({- url: 'http://tagspaces.org/releases/version.json?nVer='+cVer,- type: 'GET',- })- .done(function(data) {- TSPOSTIO.checkNewVersion(data);- })- .fail(function(data) {- console.log("AJAX failed "+data);- })- ;- };-- var selectDirectory = function() {+ var createDirectoryIndex = function(dirPath) {+ console.log("Creating index for directory: " + dirPath);+ TSCORE.showLoadingAnimation();- };-- var openDirectory = function(dirPath) {+ var directoryIndex = [];+ TSPOSTIO.createDirectoryIndex(directoryIndex);+ };- };+ var createDirectoryTree = function(dirPath) {+ console.log("Creating directory index for: " + dirPath);+ TSCORE.showLoadingAnimation();- var openFile = function(filePath) {+ var directoyTree = [];+ //console.log(JSON.stringify(directoyTree));+ TSPOSTIO.createDirectoryTree(directoyTree);+ };- };+ var createDirectory = function(dirPath) {+ console.log("Creating directory: " + dirPath);+ TSCORE.showLoadingAnimation();- var selectFile = function() {- };-- var openExtensionsDirectory = function() {+ TSPOSTIO.createDirectory(dirPath);- };+ };-/* stats for file:- dev: 2114,- ino: 48064969,- mode: 33188,- nlink: 1,- uid: 85,- gid: 100,- rdev: 0,- size: 527,- blksize: 4096,- blocks: 8,- atime: Mon, 10 Oct 2011 23:24:11 GMT,- mtime: Mon, 10 Oct 2011 23:24:11 GMT,- ctime: Mon, 10 Oct 2011 23:24:11 GMT-*/- var getFileProperties = function(filePath) {- var fileProperties = {};-/* var stats = fs.statSync(filePath);- if (stats.isFile()) {- fileProperties.path = filePath;- fileProperties.size = stats.size;- fileProperties.lmdt = stats.mtime;- TSPOSTIO.getFileProperties(fileProperties);- } else {- console.warn("Error getting file properties. "+filePath+" is directory");- }*/- };-- exports.createDirectory = createDirectory;- exports.renameFile = renameFile;- exports.loadTextFile = loadTextFile;- exports.saveTextFile = saveTextFile;- exports.listDirectory = listDirectory;- exports.deleteElement = deleteElement;- exports.createDirectoryIndex = createDirectoryIndex;- exports.createDirectoryTree = createDirectoryTree;- exports.selectDirectory = selectDirectory;- exports.openDirectory = openDirectory;- exports.openFile = openFile;- exports.selectFile = selectFile;- exports.openExtensionsDirectory = openExtensionsDirectory;- exports.checkAccessFileURLAllowed = checkAccessFileURLAllowed;- exports.checkNewVersion = checkNewVersion;- exports.getFileProperties = getFileProperties;--});\ No newline at end of file+ var renameFile = function(filePath, newFilePath) {+ console.log("Renaming file: " + filePath + " to " + newFilePath);+ TSCORE.showLoadingAnimation();++ TSPOSTIO.renameFile(filePath, newFilePath);+ };++ var loadTextFile = function(filePath) {+ console.log("Loading file: " + filePath);+ TSCORE.showLoadingAnimation();++ TSPOSTIO.loadTextFile(content);+ };++ var saveTextFile = function(filePath, content, overWrite) {+ console.log("Saving file: " + filePath);+ TSCORE.showLoadingAnimation();++ // Handling the UTF8 support for text files+ var UTF8_BOM = "\ufeff";++ if (content.indexOf(UTF8_BOM) == 0) {+ // already has a UTF8 bom+ } else {+ content = UTF8_BOM + content;+ }++ var isNewFile = !pathUtils.existsSync(filePath);++ TSPOSTIO.saveTextFile(filePath, isNewFile);+ };++ /*+ http://rominirani.com/2013/08/16/firefox-os-tutorial-episode-9-device-storage/+ listContents('sdcard');+ listContents('videos');+ listContents('music');+ listContents('pictures');++ */+ function listContents(storagename) {+ //Clear up the list first+ var files = navigator.getDeviceStorage(storagename);+ var cursor = files.enumerate();+ console.log("Listing storage!");+ cursor.onsuccess = function() {+ console.log("Listing storage success!");+ var file = this.result;+ if (file != null) {+ //var imageElement = $('<img height="100" width="75">');+ //imageElement.attr('src', window.URL.createObjectURL(file));+ //$("<p>" + file.name + "," + file.lastModifiedDate + "," + file.type + "," + file.size + "</p>").appendTo('#results');+ //imageElement.appendTo("#results");+ console.log("file: " + file.name + "," + file.lastModifiedDate + "," + file.type + "," + file.size);+ this.done = false;+ } else {+ this.done = true;+ }+ if (!this.done) {+ this.continue();+ }+ };+ cursor.onerror = function(e) {+ console.log("Listing storage failed! " + e);+ };+ }++ listContents('sdcard');++ var listDirectory = function(dirPath) {+ console.log("Listing directory: " + dirPath);+ TSCORE.showLoadingAnimation();++ TSPOSTIO.errorOpeningPath();++ var anotatedDirList = [],+ dirList = []; // remove+ for (var i = 0; i < dirList.length; i++) {+ var path = dirPath + TSCORE.dirSeparator + dirList[i];+ var stats = fs.statSync(path);+ //console.log('stats: ' + JSON.stringify(stats));+ anotatedDirList.push({+ "name": dirList[i],+ "isFile": !stats.isDirectory(),+ "size": stats.size,+ "lmdt": stats.mtime,+ "path": path+ });+ }+ TSPOSTIO.listDirectory(anotatedDirList);++ };++ var deleteElement = function(path) {+ console.log("Deleting: " + path);+ TSCORE.showLoadingAnimation();++ TSPOSTIO.deleteElement(path);++ };++ var checkAccessFileURLAllowed = function() {+ console.log("checkAccessFileURLAllowed function not relevant for node..");+ };++ var checkNewVersion = function() {+ console.log("Checking for new version...");+ var cVer = TSCORE.Config.DefaultSettings["appVersion"] + "." + TSCORE.Config.DefaultSettings["appBuild"];+ $.ajax({+ url: 'http://tagspaces.org/releases/version.json?nVer=' + cVer,+ type: 'GET',+ })+ .done(function(data) {+ TSPOSTIO.checkNewVersion(data);+ })+ .fail(function(data) {+ console.log("AJAX failed " + data);+ });+ };++ var selectDirectory = function() {++ };++ var openDirectory = function(dirPath) {++ };++ var openFile = function(filePath) {++ };++ var selectFile = function() {};++ var openExtensionsDirectory = function() {++ };++ /* stats for file:+ dev: 2114,+ ino: 48064969,+ mode: 33188,+ nlink: 1,+ uid: 85,+ gid: 100,+ rdev: 0,+ size: 527,+ blksize: 4096,+ blocks: 8,+ atime: Mon, 10 Oct 2011 23:24:11 GMT,+ mtime: Mon, 10 Oct 2011 23:24:11 GMT,+ ctime: Mon, 10 Oct 2011 23:24:11 GMT+ */+ var getFileProperties = function(filePath) {+ var fileProperties = {};+ /* var stats = fs.statSync(filePath);+ if (stats.isFile()) {+ fileProperties.path = filePath;+ fileProperties.size = stats.size;+ fileProperties.lmdt = stats.mtime;+ TSPOSTIO.getFileProperties(fileProperties);+ } else {+ console.warn("Error getting file properties. "+filePath+" is directory");+ }*/+ };++ exports.createDirectory = createDirectory;+ exports.renameFile = renameFile;+ exports.loadTextFile = loadTextFile;+ exports.saveTextFile = saveTextFile;+ exports.listDirectory = listDirectory;+ exports.deleteElement = deleteElement;+ exports.createDirectoryIndex = createDirectoryIndex;+ exports.createDirectoryTree = createDirectoryTree;+ exports.selectDirectory = selectDirectory;+ exports.openDirectory = openDirectory;+ exports.openFile = openFile;+ exports.selectFile = selectFile;+ exports.openExtensionsDirectory = openExtensionsDirectory;+ exports.checkAccessFileURLAllowed = checkAccessFileURLAllowed;+ exports.checkNewVersion = checkNewVersion;+ exports.getFileProperties = getFileProperties;++});diff --git a/data/mozilla/ioutils.js b/data/mozilla/ioutils.jsindex fa67128e7..86f5de500 100644--- a/data/mozilla/ioutils.js+++ b/data/mozilla/ioutils.js@@ -1,573 +1,609 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that- * can be found in the LICENSE file. */-/* jshint moz: true, strict: false */-/* global exports */--// good source for xpcom api https://developer.mozilla.org/en-US/Add-ons/Code_snippets/File_I_O-const {components, Cc, Ci, Cr, Cu} = require("chrome");-var filesIO = require("sdk/io/file"); // file-var runtime = require("sdk/system/runtime"); // runtime-const { getTabs, getTabId, getOwnerWindow } = require("sdk/tabs/utils"); // tabs/utils--function getWindow(worker) {- let { tab } = worker;-- if (!tab) {- return null;- }-- let rawTabs = getTabs();-- for (let rawTab of rawTabs) {- if (getTabId(rawTab) === tab.id) {- return getOwnerWindow(rawTab);- }- }-- return null;-}--function searchDir(dirPath, index, keewords) {-// console.log("Indexing directory: "+dirPath);- var path = "";- var isFile = false;- try {- var dirList = filesIO.list(dirPath);-- for (var i=0; i < dirList.length; i++) {- path = filesIO.join(dirPath,dirList[i]);- isFile = filesIO.isFile(path);- if(dirList[i].indexOf(keewords)>= 0) {- index.push({- "name": dirList[i],- "type": isFile?"file":"directory",- "path": path- });- }- if(!isFile) {- searchDir(path, index, keewords);- }- }- return index;- } catch(ex) {- console.error("Searching dir: "+path+" failed "+ex);- }-}--exports.searchDirectory = function searchDirectory(dirPath, keewords, worker) {- console.log("Searching directory: "+dirPath+" for: "+keewords);- var resultIndex = [];- resultIndex = searchDir(dirPath, resultIndex, keewords);-// console.log("Index: "+JSON.stringify(resultIndex));- worker.postMessage({- "command": "indexDirectory",- "success": true,- "content": directoryIndex- });-};--exports.createDirectoryIndex = function createDirectoryIndex(dirPath, worker) {- console.log("Creating index for directory: "+dirPath);- var directoryIndex = [];- directoryIndex = scanDirectory(dirPath, directoryIndex);-// console.log("Index: "+JSON.stringify(directoryIndex));- worker.postMessage({- "command": "indexDirectory",- "success": true,- "content": directoryIndex- });-};--exports.createDirectoryTree = function createDirectoryTree(dirPath, worker) {- console.log("Creating directory tree: "+dirPath);- var dirTree = directoryTree(dirPath);-// console.log("Index: "+JSON.stringify(dirTree));- worker.postMessage({- "command": "createDirectoryTree",- "success": true,- "content": dirTree- });-};--function directoryTree(dirPath) {- try {- var tree = {};- var dirList = filesIO.list(dirPath);- var directory = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);- directory.initWithPath(dirPath);- tree["name"] = directory.leafName;- tree["isFile"] = false;- tree["lmdt"] = directory.lastModifiedTime;- tree["path"] = dirPath;- tree["children"] = [];-- for (var i=0; i < dirList.length; i++) {- try {- var path = filesIO.join(dirPath,dirList[i]);- var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);- file.initWithPath(path);- if (file.isFile()) {- tree["children"].push({- "name": file.leafName,- "isFile": true,- "size": file.fileSize,- "lmdt": file.lastModifiedTime,- "path": path- });- } else {- tree["children"].push( directoryTree(path) );- }- } catch(ex) {- console.error("Filepath has a invalid encoding "+ex);- }-- }- return tree;- } catch(ex) {- console.error("Creating directory index failed "+ex);- }-}--function scanDirectory(dirPath, index) {- try {- var dirList = filesIO.list(dirPath);- for (var i=0; i < dirList.length; i++) {- try {- var path = filesIO.join(dirPath,dirList[i]);- var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);- file.initWithPath(path);- index.push({- "name": file.leafName,- "isFile": file.isFile(),- "size": file.fileSize,- "lmdt": file.lastModifiedTime,- "path": path- });- if (!file.isFile()) {- scanDirectory(path, index);- }- } catch(ex) {- console.error("Filepath has a invalid encoding "+ex);- }- }- return index;- } catch(ex) {- console.error("Listing directory failed "+ex);- }-}--exports.listDirectory = function listDirectory(dirPath, worker) {- console.log("Listing directory: "+dirPath);- try {- var dirList = filesIO.list(dirPath);- var anotatedDirList = [];- for (var i=0; i < dirList.length; i++) {- try {- var path = filesIO.join(dirPath,dirList[i]);- var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);- file.initWithPath(filesIO.join(dirPath,dirList[i]));- anotatedDirList.push({- "name": file.leafName,- "isFile": file.isFile(),- "size": file.fileSize,- "lmdt": file.lastModifiedTime,- "path": path- });- } catch(ex) {- console.error("Filepath has a invalid encoding "+ex);- }- }- worker.postMessage({- "command": "listDirectory",- "success": true,- "content": anotatedDirList- });- console.log("Listing directory successful!");- } catch(ex) {- console.error("Listing directory failed "+ex);- worker.postMessage({- "command": "listDirectory",- "success": false- });- }-};--exports.createDirectory = function createDirectory(dirPath, worker) {- console.log("Creating directory: "+dirPath);- try {- filesIO.mkpath(dirPath);- worker.postMessage({- "command": "createDirectory",- "content": dirPath,- "success": true- });- console.log("Creating successful!");- } catch(ex) {- worker.postMessage({- "command": "createDirectory",- "success": false- });- console.error("Creating failed "+ex);- }-};--exports.loadTextFile = function loadTextFile(filePath, worker) {- console.log("Loading text file: "+filePath);- try {- var content = filesIO.read(filePath);- worker.postMessage({- "command": "loadTextFile",- "success": true,- "content": content- });- console.log("Loading file successful!");- } catch(ex) {- worker.postMessage({- "command": "loadTextFile",- "success": false- });- console.error("Loading file failed "+ex);- }-};--exports.deleteElement = function deleteElement(path, worker) {- console.log("Deleting: "+path);- try {- if(filesIO.isFile(path)) {- filesIO.remove(path);- worker.postMessage({- "command": "delete",- "success": true,- "content": path- });- console.log("Deleting file successful!");- } /* else {- filesIO.rmdir(path);- worker.postMessage({- "command": "delete",- "success": true- });- console.log("Deleting directory successful!");- } */- } catch(ex) {- worker.postMessage({- "command": "delete",- "success": false- });- console.error("Deleting file failed "+ex);- }-};--exports.rename = function rename(filePath, newFilePath, worker) {- console.log("Renaming file: "+filePath+" to "+newFilePath);-- // Checks if the file already exists.- if(!filesIO.exists(newFilePath)) {- try {- // TODO Remove the OSX custom code after https://bugzilla.mozilla.org/show_bug.cgi?id=913663 is fixed- if(runtime.OS.toLowerCase().indexOf("darwin")>=0) {- console.log("Renaming under macos ");-- var binaryFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- binaryFile.initWithPath( filePath );- console.log("Init File: "+filePath);-- var istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);- istream.init(binaryFile, -1, -1, false);- var bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);- bstream.setInputStream(istream);- var binaryStream = bstream.readBytes(bstream.available());-- var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- file.initWithPath(newFilePath);- console.log("InitFile: "+newFilePath);-- var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);- stream.init(file, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate- stream.write(binaryStream,binaryStream.length);- if (stream instanceof Ci.nsISafeOutputStream) {- stream.finish();- } else {- stream.close();- }-- filesIO.remove(filePath);- worker.postMessage({ "command": "rename", "success": true, "content": [filePath, newFilePath] });- } else {- var targetDir;- var targetFileName;- // Detecting WIN os- if(runtime.OS.toLowerCase().indexOf("win")!=-1) {- targetDir = newFilePath.substring(0,newFilePath.lastIndexOf("\\"));- targetFileName = newFilePath.substring(newFilePath.lastIndexOf("\\")+1,newFilePath.length);- } else {- targetDir = newFilePath.substring(0,newFilePath.lastIndexOf("/"));- targetFileName = newFilePath.substring(newFilePath.lastIndexOf("/")+1,newFilePath.length);- }- console.log("Target dir: "+targetDir+" filename: "+targetFileName);- var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- file.initWithPath(filePath);-- //let FileUtils = Cu.import('resource://gre/modules/FileUtils.jsm').FileUtils;- //var targetDirFile = new FileUtils.File(targetDir);-- var targetDirFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- targetDirFile.initWithPath(filesIO.join(targetDir,""));- //targetDirFile.initWithPath(targetDir);-- console.log("After init: "+file.path+" targetdir: "+targetDirFile.path+" targetfilename: "+targetFileName);- file.moveTo(targetDirFile,targetFileName);- var targetPath = filesIO.join(targetDir,targetFileName);- worker.postMessage({ "command": "rename", "success": true, "content": [filePath, targetPath] });- }- } catch(ex) {- worker.postMessage({ "command": "rename", "success": false });- console.error("Renaming failed "+ex);- }- } else {- worker.postMessage({ "command": "rename", "success": false });- console.error("Renaming failed. Target filepath already exists.");- }-};--exports.copy = function copy(filePath, newFilePath, worker) {- console.log("Copy file: "+filePath+" to "+newFilePath);-- // Checks if the target file already exists.- if(!filesIO.exists(newFilePath)) {- try {- var binaryFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- binaryFile.initWithPath( filePath );- console.log("Init File: "+filePath);-- var istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);- istream.init(binaryFile, -1, -1, false);- var bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);- bstream.setInputStream(istream);- var binaryStream = bstream.readBytes(bstream.available());-- var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- file.initWithPath(newFilePath);- console.log("InitFile: "+newFilePath);-- var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);- stream.init(file, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate- stream.write(binaryStream,binaryStream.length);- if (stream instanceof Ci.nsISafeOutputStream) {- stream.finish();- } else {- stream.close();- }-- worker.postMessage({ "command": "copy", "success": true, "content": [filePath, newFilePath] });- } catch(ex) {- worker.postMessage({ "command": "copy", "success": false });- console.error("Copy failed "+ex);- }- } else {- worker.postMessage({ "command": "copy", "success": false, "content": "TargetFileAlreadyExistsError" });- //console.error("Copy failed. Target filepath already exists.");- }-};--exports.saveTextFile = function saveTextFile(filePath, content, worker) {- console.log("Saving file: "+filePath);- try {- var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- file.initWithPath(filePath);- //if(!file.exists()) {- // file.create(0,0664);- //}--/* Cu.import("resource://gre/modules/NetUtil.jsm");- Cu.import("resource://gre/modules/FileUtils.jsm");- var ostream = FileUtils.openSafeFileOutputStream(file);- var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);- converter.charset = "UTF-8";- var istream = converter.convertToInputStream(content);- NetUtil.asyncCopy(istream, ostream, function(status) {- //if (!Components.isSuccessCode(status)) {- // handle error- // return- //}- });*/-- var foStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);- foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);- var converter = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);- converter.init(foStream, "UTF-8", 0, 0);- converter.writeString(content);- converter.close(); // this closes foStream-- worker.postMessage({ "command": "saveTextFile","content": filePath,"success": true });- console.log("Save successed!");- } catch(ex) {- worker.postMessage({- "command": "saveTextFile",- "content": filePath,- "success": false- });- console.error("Save failed "+ex);- }-};--exports.saveBinaryFile = function saveBinaryFile(filePath, content, worker) {- console.log("Saving binary file: "+filePath); //+" - "+content);- try {- var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- file.initWithPath(filePath);- if(!file.exists()) {- file.create(0,0664);- }- var out = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);- out.init(file,0x20|0x02,00004,null);- out.write(content,content.length);- out.flush();- out.close();- worker.postMessage({- "command": "saveTextFile", // TODO change saveBinarFile- "content": filePath,- "success": true- });- console.log("Save successed!");- } catch(ex) {- worker.postMessage({- "command": "saveTextFile",- "content": filePath,- "success": false- });- console.error("Save failed "+ex);- }-};--/**- * Returning a path to a file selected from the user- * documentation is https://developer.mozilla.org/en/NsIFilePicker- */-exports.promptFileOpenPicker = function promptFileOpenPicker(worker) {- console.log("Opening file selection dialog");- try {- var window = getWindow(worker);- var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);- fp.init(window, "PDF Open", Ci.nsIFilePicker.modeOpen);- fp.appendFilter("PDF files", "*.pdf");- fp.appendFilters(Ci.nsIFilePicker.filterAll);- fp.filterIndex = 0;- var result = fp.show();- if (result === Ci.nsIFilePicker.returnOK || result === Ci.nsIFilePicker.returnReplace) {- worker.postMessage({- "command": "selectFile",- "success": true,- "content": fp.file.path- });- }- } catch(ex) {- worker.postMessage({- "command": "selectFile",- "success": false- });- console.error("File selection failed "+ex);- }-};--/**- * Returning a path to a directory selected from the user- * documentation is https://developer.mozilla.org/en/NsIFilePicker- */-exports.promptDirectorySelector = function promptDirectorySelector(worker) {- console.log("Opening directory selection dialog...");- try {-// var window = require("window/utils").getMostRecentBrowserWindow();- var window = getWindow(worker);- var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);- fp.init(window, "Directory Selection", Ci.nsIFilePicker.modeGetFolder);- var result = fp.show();- if (result === Ci.nsIFilePicker.returnOK) {- worker.postMessage({- "command": "selectDirectory",- "success": true,- "content": fp.file.path- });- }- } catch(ex) {- worker.postMessage({- "command": "selectDirectory",- "success": false- });- console.error("Directory selection failed "+ex);- }-};--/**- * Open a directory in the default directory viewer (e.g. windows explorer)- * http://stackoverflow.com/questions/9453786- */-exports.openDirectory = function openDirectory(dirPath, worker) {- console.log("Opening directory: "+dirPath);- dirPath = "file://"+dirPath;- try {- var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);- var uri = ioService.newURI(dirPath, null, null);- if (uri instanceof Ci.nsIFileURL && uri.file.isDirectory()) {- uri.file.QueryInterface(Ci.nsILocalFile).launch();- }- } catch(ex) {- console.error("Opening directory failed "+ex);- }-};--/**- * Open the directory where the user can install tagspaces extensions- * This directory is located in the profile with which firefox is started- */-exports.openExtensionsDirectory = function openExtensionsDirectory(worker) {- console.log("Opening extensions directory (not implemented yet)");-/* try {- // Other nsIPropertues such as ProfD could be found on- // https://developer.mozilla.org/de/docs/Code_snippets/File_I_O- var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);- var profileDir = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- profileDir.initWithPath(file.path+"/extensions/jid1-FBaMKxTifTSahQ@jetpack/resources/tagspaces/data/ext");- if (profileDir.isDirectory()) {- profileDir.QueryInterface(Ci.nsILocalFile).launch();- }- } catch(ex) {- console.error("Opening extensions directory failed "+ex);- } */-};--/*- "leafName":"2013",- "permissions":438,- "permissionsOfLink":438,- "lastModifiedTime":1350309208000,- "lastModifiedTimeOfLink":1350309208000,- "fileSize":0,- "fileSizeOfLink":0,- "target":"Z:\\Chronique\\2013",- "path":"Z:\\Chronique\\2013",- "parent":{}-*/--exports.getFileProperties = function(filePath, worker) {- var fileProperties = {};- try {- var targetFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);- targetFile.initWithPath(filesIO.join(filePath,""));- if(targetFile.isFile()) {- fileProperties.path = filePath;- fileProperties.size = targetFile.fileSize;- fileProperties.lmdt = targetFile.lastModifiedTime;- worker.postMessage({- "command": "getFileProperties",- "success": true,- "content": fileProperties- });- } else {- console.warn("Error getting file properties. "+filePath+" is directory");- }- } catch(ex) {- console.error("Error getting properties for file "+filePath+" - "+ex);- }-};\ No newline at end of file+/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.+ * Use of this source code is governed by a AGPL3 license that+ * can be found in the LICENSE file. */+/* jshint moz: true, strict: false */+/* global exports */++// good source for xpcom api https://developer.mozilla.org/en-US/Add-ons/Code_snippets/File_I_O+const {+ components, Cc, Ci, Cr, Cu+} = require("chrome");+var filesIO = require("sdk/io/file"); // file+var runtime = require("sdk/system/runtime"); // runtime+const {+ getTabs, getTabId, getOwnerWindow+} = require("sdk/tabs/utils"); // tabs/utils++function getWindow(worker) {+ let {+ tab+ } = worker;++ if (!tab) {+ return null;+ }++ let rawTabs = getTabs();++ for (let rawTab of rawTabs) {+ if (getTabId(rawTab) === tab.id) {+ return getOwnerWindow(rawTab);+ }+ }++ return null;+}++function searchDir(dirPath, index, keewords) {+ // console.log("Indexing directory: "+dirPath);+ var path = "";+ var isFile = false;+ try {+ var dirList = filesIO.list(dirPath);++ for (var i = 0; i < dirList.length; i++) {+ path = filesIO.join(dirPath, dirList[i]);+ isFile = filesIO.isFile(path);+ if (dirList[i].indexOf(keewords) >= 0) {+ index.push({+ "name": dirList[i],+ "type": isFile ? "file" : "directory",+ "path": path+ });+ }+ if (!isFile) {+ searchDir(path, index, keewords);+ }+ }+ return index;+ } catch (ex) {+ console.error("Searching dir: " + path + " failed " + ex);+ }+}++exports.searchDirectory = function searchDirectory(dirPath, keewords, worker) {+ console.log("Searching directory: " + dirPath + " for: " + keewords);+ var resultIndex = [];+ resultIndex = searchDir(dirPath, resultIndex, keewords);+ // console.log("Index: "+JSON.stringify(resultIndex));+ worker.postMessage({+ "command": "indexDirectory",+ "success": true,+ "content": directoryIndex+ });+};++exports.createDirectoryIndex = function createDirectoryIndex(dirPath, worker) {+ console.log("Creating index for directory: " + dirPath);+ var directoryIndex = [];+ directoryIndex = scanDirectory(dirPath, directoryIndex);+ // console.log("Index: "+JSON.stringify(directoryIndex));+ worker.postMessage({+ "command": "indexDirectory",+ "success": true,+ "content": directoryIndex+ });+};++exports.createDirectoryTree = function createDirectoryTree(dirPath, worker) {+ console.log("Creating directory tree: " + dirPath);+ var dirTree = directoryTree(dirPath);+ // console.log("Index: "+JSON.stringify(dirTree));+ worker.postMessage({+ "command": "createDirectoryTree",+ "success": true,+ "content": dirTree+ });+};++function directoryTree(dirPath) {+ try {+ var tree = {};+ var dirList = filesIO.list(dirPath);+ var directory = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);+ directory.initWithPath(dirPath);+ tree["name"] = directory.leafName;+ tree["isFile"] = false;+ tree["lmdt"] = directory.lastModifiedTime;+ tree["path"] = dirPath;+ tree["children"] = [];++ for (var i = 0; i < dirList.length; i++) {+ try {+ var path = filesIO.join(dirPath, dirList[i]);+ var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);+ file.initWithPath(path);+ if (file.isFile()) {+ tree["children"].push({+ "name": file.leafName,+ "isFile": true,+ "size": file.fileSize,+ "lmdt": file.lastModifiedTime,+ "path": path+ });+ } else {+ tree["children"].push(directoryTree(path));+ }+ } catch (ex) {+ console.error("Filepath has a invalid encoding " + ex);+ }++ }+ return tree;+ } catch (ex) {+ console.error("Creating directory index failed " + ex);+ }+}++function scanDirectory(dirPath, index) {+ try {+ var dirList = filesIO.list(dirPath);+ for (var i = 0; i < dirList.length; i++) {+ try {+ var path = filesIO.join(dirPath, dirList[i]);+ var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);+ file.initWithPath(path);+ index.push({+ "name": file.leafName,+ "isFile": file.isFile(),+ "size": file.fileSize,+ "lmdt": file.lastModifiedTime,+ "path": path+ });+ if (!file.isFile()) {+ scanDirectory(path, index);+ }+ } catch (ex) {+ console.error("Filepath has a invalid encoding " + ex);+ }+ }+ return index;+ } catch (ex) {+ console.error("Listing directory failed " + ex);+ }+}++exports.listDirectory = function listDirectory(dirPath, worker) {+ console.log("Listing directory: " + dirPath);+ try {+ var dirList = filesIO.list(dirPath);+ var anotatedDirList = [];+ for (var i = 0; i < dirList.length; i++) {+ try {+ var path = filesIO.join(dirPath, dirList[i]);+ var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);+ file.initWithPath(filesIO.join(dirPath, dirList[i]));+ anotatedDirList.push({+ "name": file.leafName,+ "isFile": file.isFile(),+ "size": file.fileSize,+ "lmdt": file.lastModifiedTime,+ "path": path+ });+ } catch (ex) {+ console.error("Filepath has a invalid encoding " + ex);+ }+ }+ worker.postMessage({+ "command": "listDirectory",+ "success": true,+ "content": anotatedDirList+ });+ console.log("Listing directory successful!");+ } catch (ex) {+ console.error("Listing directory failed " + ex);+ worker.postMessage({+ "command": "listDirectory",+ "success": false+ });+ }+};++exports.createDirectory = function createDirectory(dirPath, worker) {+ console.log("Creating directory: " + dirPath);+ try {+ filesIO.mkpath(dirPath);+ worker.postMessage({+ "command": "createDirectory",+ "content": dirPath,+ "success": true+ });+ console.log("Creating successful!");+ } catch (ex) {+ worker.postMessage({+ "command": "createDirectory",+ "success": false+ });+ console.error("Creating failed " + ex);+ }+};++exports.loadTextFile = function loadTextFile(filePath, worker) {+ console.log("Loading text file: " + filePath);+ try {+ var content = filesIO.read(filePath);+ worker.postMessage({+ "command": "loadTextFile",+ "success": true,+ "content": content+ });+ console.log("Loading file successful!");+ } catch (ex) {+ worker.postMessage({+ "command": "loadTextFile",+ "success": false+ });+ console.error("Loading file failed " + ex);+ }+};++exports.deleteElement = function deleteElement(path, worker) {+ console.log("Deleting: " + path);+ try {+ if (filesIO.isFile(path)) {+ filesIO.remove(path);+ worker.postMessage({+ "command": "delete",+ "success": true,+ "content": path+ });+ console.log("Deleting file successful!");+ }+ /* else {+ filesIO.rmdir(path);+ worker.postMessage({+ "command": "delete",+ "success": true+ });+ console.log("Deleting directory successful!");+ } */+ } catch (ex) {+ worker.postMessage({+ "command": "delete",+ "success": false+ });+ console.error("Deleting file failed " + ex);+ }+};++exports.rename = function rename(filePath, newFilePath, worker) {+ console.log("Renaming file: " + filePath + " to " + newFilePath);++ // Checks if the file already exists.+ if (!filesIO.exists(newFilePath)) {+ try {+ // TODO Remove the OSX custom code after https://bugzilla.mozilla.org/show_bug.cgi?id=913663 is fixed+ if (runtime.OS.toLowerCase().indexOf("darwin") >= 0) {+ console.log("Renaming under macos ");++ var binaryFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ binaryFile.initWithPath(filePath);+ console.log("Init File: " + filePath);++ var istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);+ istream.init(binaryFile, -1, -1, false);+ var bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);+ bstream.setInputStream(istream);+ var binaryStream = bstream.readBytes(bstream.available());++ var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ file.initWithPath(newFilePath);+ console.log("InitFile: " + newFilePath);++ var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);+ stream.init(file, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate+ stream.write(binaryStream, binaryStream.length);+ if (stream instanceof Ci.nsISafeOutputStream) {+ stream.finish();+ } else {+ stream.close();+ }++ filesIO.remove(filePath);+ worker.postMessage({+ "command": "rename",+ "success": true,+ "content": [filePath, newFilePath]+ });+ } else {+ var targetDir;+ var targetFileName;+ // Detecting WIN os+ if (runtime.OS.toLowerCase().indexOf("win") != -1) {+ targetDir = newFilePath.substring(0, newFilePath.lastIndexOf("\\"));+ targetFileName = newFilePath.substring(newFilePath.lastIndexOf("\\") + 1, newFilePath.length);+ } else {+ targetDir = newFilePath.substring(0, newFilePath.lastIndexOf("/"));+ targetFileName = newFilePath.substring(newFilePath.lastIndexOf("/") + 1, newFilePath.length);+ }+ console.log("Target dir: " + targetDir + " filename: " + targetFileName);+ var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ file.initWithPath(filePath);++ //let FileUtils = Cu.import('resource://gre/modules/FileUtils.jsm').FileUtils;+ //var targetDirFile = new FileUtils.File(targetDir);++ var targetDirFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ targetDirFile.initWithPath(filesIO.join(targetDir, ""));+ //targetDirFile.initWithPath(targetDir);++ console.log("After init: " + file.path + " targetdir: " + targetDirFile.path + " targetfilename: " + targetFileName);+ file.moveTo(targetDirFile, targetFileName);+ var targetPath = filesIO.join(targetDir, targetFileName);+ worker.postMessage({+ "command": "rename",+ "success": true,+ "content": [filePath, targetPath]+ });+ }+ } catch (ex) {+ worker.postMessage({+ "command": "rename",+ "success": false+ });+ console.error("Renaming failed " + ex);+ }+ } else {+ worker.postMessage({+ "command": "rename",+ "success": false+ });+ console.error("Renaming failed. Target filepath already exists.");+ }+};++exports.copy = function copy(filePath, newFilePath, worker) {+ console.log("Copy file: " + filePath + " to " + newFilePath);++ // Checks if the target file already exists.+ if (!filesIO.exists(newFilePath)) {+ try {+ var binaryFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ binaryFile.initWithPath(filePath);+ console.log("Init File: " + filePath);++ var istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);+ istream.init(binaryFile, -1, -1, false);+ var bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);+ bstream.setInputStream(istream);+ var binaryStream = bstream.readBytes(bstream.available());++ var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ file.initWithPath(newFilePath);+ console.log("InitFile: " + newFilePath);++ var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);+ stream.init(file, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate+ stream.write(binaryStream, binaryStream.length);+ if (stream instanceof Ci.nsISafeOutputStream) {+ stream.finish();+ } else {+ stream.close();+ }++ worker.postMessage({+ "command": "copy",+ "success": true,+ "content": [filePath, newFilePath]+ });+ } catch (ex) {+ worker.postMessage({+ "command": "copy",+ "success": false+ });+ console.error("Copy failed " + ex);+ }+ } else {+ worker.postMessage({+ "command": "copy",+ "success": false,+ "content": "TargetFileAlreadyExistsError"+ });+ //console.error("Copy failed. Target filepath already exists.");+ }+};++exports.saveTextFile = function saveTextFile(filePath, content, worker) {+ console.log("Saving file: " + filePath);+ try {+ var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ file.initWithPath(filePath);+ //if(!file.exists()) {+ // file.create(0,0664);+ //}++ /* Cu.import("resource://gre/modules/NetUtil.jsm");+ Cu.import("resource://gre/modules/FileUtils.jsm");+ var ostream = FileUtils.openSafeFileOutputStream(file);+ var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);+ converter.charset = "UTF-8";+ var istream = converter.convertToInputStream(content);+ NetUtil.asyncCopy(istream, ostream, function(status) {+ //if (!Components.isSuccessCode(status)) {+ // handle error+ // return+ //}+ });*/++ var foStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);+ foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);+ var converter = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);+ converter.init(foStream, "UTF-8", 0, 0);+ converter.writeString(content);+ converter.close(); // this closes foStream++ worker.postMessage({+ "command": "saveTextFile",+ "content": filePath,+ "success": true+ });+ console.log("Save successed!");+ } catch (ex) {+ worker.postMessage({+ "command": "saveTextFile",+ "content": filePath,+ "success": false+ });+ console.error("Save failed " + ex);+ }+};++exports.saveBinaryFile = function saveBinaryFile(filePath, content, worker) {+ console.log("Saving binary file: " + filePath); //+" - "+content);+ try {+ var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ file.initWithPath(filePath);+ if (!file.exists()) {+ file.create(0, 0664);+ }+ var out = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);+ out.init(file, 0x20 | 0x02, 00004, null);+ out.write(content, content.length);+ out.flush();+ out.close();+ worker.postMessage({+ "command": "saveTextFile", // TODO change saveBinarFile+ "content": filePath,+ "success": true+ });+ console.log("Save successed!");+ } catch (ex) {+ worker.postMessage({+ "command": "saveTextFile",+ "content": filePath,+ "success": false+ });+ console.error("Save failed " + ex);+ }+};++/**+ * Returning a path to a file selected from the user+ * documentation is https://developer.mozilla.org/en/NsIFilePicker+ */+exports.promptFileOpenPicker = function promptFileOpenPicker(worker) {+ console.log("Opening file selection dialog");+ try {+ var window = getWindow(worker);+ var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);+ fp.init(window, "PDF Open", Ci.nsIFilePicker.modeOpen);+ fp.appendFilter("PDF files", "*.pdf");+ fp.appendFilters(Ci.nsIFilePicker.filterAll);+ fp.filterIndex = 0;+ var result = fp.show();+ if (result === Ci.nsIFilePicker.returnOK || result === Ci.nsIFilePicker.returnReplace) {+ worker.postMessage({+ "command": "selectFile",+ "success": true,+ "content": fp.file.path+ });+ }+ } catch (ex) {+ worker.postMessage({+ "command": "selectFile",+ "success": false+ });+ console.error("File selection failed " + ex);+ }+};++/**+ * Returning a path to a directory selected from the user+ * documentation is https://developer.mozilla.org/en/NsIFilePicker+ */+exports.promptDirectorySelector = function promptDirectorySelector(worker) {+ console.log("Opening directory selection dialog...");+ try {+ // var window = require("window/utils").getMostRecentBrowserWindow();+ var window = getWindow(worker);+ var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);+ fp.init(window, "Directory Selection", Ci.nsIFilePicker.modeGetFolder);+ var result = fp.show();+ if (result === Ci.nsIFilePicker.returnOK) {+ worker.postMessage({+ "command": "selectDirectory",+ "success": true,+ "content": fp.file.path+ });+ }+ } catch (ex) {+ worker.postMessage({+ "command": "selectDirectory",+ "success": false+ });+ console.error("Directory selection failed " + ex);+ }+};++/**+ * Open a directory in the default directory viewer (e.g. windows explorer)+ * http://stackoverflow.com/questions/9453786+ */+exports.openDirectory = function openDirectory(dirPath, worker) {+ console.log("Opening directory: " + dirPath);+ dirPath = "file://" + dirPath;+ try {+ var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);+ var uri = ioService.newURI(dirPath, null, null);+ if (uri instanceof Ci.nsIFileURL && uri.file.isDirectory()) {+ uri.file.QueryInterface(Ci.nsILocalFile).launch();+ }+ } catch (ex) {+ console.error("Opening directory failed " + ex);+ }+};++/**+ * Open the directory where the user can install tagspaces extensions+ * This directory is located in the profile with which firefox is started+ */+exports.openExtensionsDirectory = function openExtensionsDirectory(worker) {+ console.log("Opening extensions directory (not implemented yet)");+ /* try {+ // Other nsIPropertues such as ProfD could be found on+ // https://developer.mozilla.org/de/docs/Code_snippets/File_I_O+ var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);+ var profileDir = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ profileDir.initWithPath(file.path+"/extensions/jid1-FBaMKxTifTSahQ@jetpack/resources/tagspaces/data/ext");+ if (profileDir.isDirectory()) {+ profileDir.QueryInterface(Ci.nsILocalFile).launch();+ }+ } catch(ex) {+ console.error("Opening extensions directory failed "+ex);+ } */+};++/*+ "leafName":"2013",+ "permissions":438,+ "permissionsOfLink":438,+ "lastModifiedTime":1350309208000,+ "lastModifiedTimeOfLink":1350309208000,+ "fileSize":0,+ "fileSizeOfLink":0,+ "target":"Z:\\Chronique\\2013",+ "path":"Z:\\Chronique\\2013",+ "parent":{}+*/++exports.getFileProperties = function(filePath, worker) {+ var fileProperties = {};+ try {+ var targetFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);+ targetFile.initWithPath(filesIO.join(filePath, ""));+ if (targetFile.isFile()) {+ fileProperties.path = filePath;+ fileProperties.size = targetFile.fileSize;+ fileProperties.lmdt = targetFile.lastModifiedTime;+ worker.postMessage({+ "command": "getFileProperties",+ "success": true,+ "content": fileProperties+ });+ } else {+ console.warn("Error getting file properties. " + filePath + " is directory");+ }+ } catch (ex) {+ console.error("Error getting properties for file " + filePath + " - " + ex);+ }+};diff --git a/data/mozilla/main.js b/data/mozilla/main.jsindex 0baf34d2e..0797e10c0 100644--- a/data/mozilla/main.js+++ b/data/mozilla/main.js@@ -1,250 +1,250 @@-/* Copyright (c) 2012-2015 The Tagspaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that- * can be found in the LICENSE file. */-/* jshint moz: true, strict: false */-/* global exports */-// the value of this var is replaced to "true" by the build script-var PRODUCTION = "@@PRODUCTION";-var VERSION = "@@VERSION";-// Disabling all output to console in production mode-if (PRODUCTION == "true") {- console = console || {};- console.log = function() {};- console.error = function() {};-}-// Import the needed APIs-var data = require('sdk/self').data; // self-var ioutils = require("ioutils");-var settings = require("settings");-var request = require("sdk/request"); // request-var tabs = require("sdk/tabs");-var unload = require('sdk/system/unload');-var Panel = require('sdk/panel').Panel;-//var userstyles = require("userstyles");-var {- Cc, Ci, Cu-} = require('chrome');-var utils = require('sdk/window/utils');-//var os = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;-var workers = [];-var toolbarButton;-if (require("sdk/system").staticArgs.disableStrict) {- require("sdk/preferences/service").set("javascript.options.strict", false);-}-exports.main = function(options, callbacks) {- console.log("Load reason: " + options.loadReason);- var mainUIMod = require("sdk/page-mod"); // page-mod- mainUIMod.PageMod({- include: data.url("index.html"),- contentScript: '' +- 'self.on("message", function(message) {' +- // 'console.log("Message received in content script from addon: "+JSON.stringify(message));'+- 'var event = document.createEvent("CustomEvent");' +- 'var cloned = cloneInto(message, document.defaultView);' +- 'event.initCustomEvent("tsMessage", true, true, cloned);' +- 'document.documentElement.dispatchEvent(event);' +- '}); ' +- 'document.documentElement.addEventListener("addon-message", function(event) {' +- // 'console.log("Message received from page script in content script "+JSON.stringify(event.detail));'+- 'self.postMessage(event.detail);' +- '}, false);' +- '',- contentScriptWhen: 'end',- onAttach: function onAttach(worker) {- console.log("Attaching worker on tab with title: " + worker.tab.title);- workers.push(worker);- worker.on('message', function(data) {- handleMessage(data, this);- });- worker.on('detach', function() {- detachWorker(this);- });- }- });- // Adding menuitem to the tools menu- var menuitem = require("menuitems").Menuitem({- id: "TagSpacesMenuItem",- menuid: "menu_ToolsPopup",- label: "TagSpaces",- // image: data.url("assets/icon16.png"),- onCommand: openTagSpacesInNewTab,- insertbefore: "menu_pageInfo"- });- // Adding toolbar button- initToobarButton();- if (options.loadReason == "install" || options.loadReason == "enable") {- installToolbarButton();- }-};--function installToolbarButton() {- toolbarButton.moveTo({- toolbarID: "nav-bar",- insertbefore: "home-button",- forceMove: false- });-}--function openTagSpacesInNewTab() {- tabs.open({- url: data.url("index.html"),- //isPinned: true,- isPrivate: true- });-}--function initToobarButton() {- // Toolbar icon with badge- /*toolbarButton = require('toolbarbutton').ToolbarButton({- id: "tagspaces",- label: "TagSpaces",- tooltiptext: "TagSpaces",- onClick: openTagSpacesInNewTab- });- toolbarButton.badge = "1.8.6";-- // Loading style for the toolbar icon with badge- userstyles.load(data.url("mozilla/overlay.css"));- if (os == "Linux") {- userstyles.load(data.url("mozilla/overlay-linux.css"));- }- else if (os == "Darwin") {- userstyles.load(data.url("mozilla/overlay-darwin.css"));- }*/- var tagspacesPanel = new Panel({- width: 520,- height: 400,- contentURL: data.url('popup.html')- });- var buttons = require('sdk/ui/button/action');- toolbarButton = buttons.ActionButton({- id: "TSToolbarButton",- label: "TagSpaces",- icon: {- "32": data.url("assets/icon32.png"),- "64": data.url("assets/icon64.png")- },- onClick: openTagSpacesInNewTab- /*onClick: function() {- tagspacesPanel.show({- position: toolbarButton- });- }*/- });-}-unload.when(function(reason) {- // since FF24 reason is never 'uninstall' see https://bugzilla.mozilla.org/show_bug.cgi?id=571049- if (reason === 'uninstall' || reason === 'disable') {- // action by uninstall or disable- let prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);- if (prompts.confirm(utils.getMostRecentBrowserWindow(), "Fill the uninstall survey", "Please fill the uninstall survey and tell us why are you removing TagSpaces. Your feedback could be very valuable for us! Would you like to fill it out?")) {- tabs.open({- url: "http://www.tagspaces.com/uninstallsurvey"- });- }- }-});-exports.onUnload = function(reason) {- console.log(reason);-};--function detachWorker(worker) {- console.log("Detaching worker...");- var index = workers.indexOf(worker);- workers.splice(index, 1);-}-var checkForNewVersion = request.Request({- url: "http://tagspaces.org/releases/version.json?fVer=" + VERSION,- onComplete: function(response) {- // console.log("Result: " + response.text + " " + response.status);- return response.text;- }-});--function checkNewVersion(worker) {- try {- var content;- var versionReq = request.Request({- url: "http://tagspaces.org/releases/version.json?fVer=" + VERSION,- onComplete: function(response) {- console.log("Result: " + response.text + " " + response.status);- response.text;- worker.postMessage({- "command": "checkNewVersion",- "content": response.text,- "success": true- });- console.log("Loading settings successful!");- }- }).get();- } catch (ex) {- worker.postMessage({- "command": "checkNewVersion",- "success": false- });- console.error("Checking new version failed " + ex);- }-}--function handleMessage(msg, worker) {- //console.log("Message in main.js: " + JSON.stringify(msg) + " from tab " + worker.tab.title);- //console.log("Thumbnail: "+worker.tab.getThumbnail());- switch (msg.detail.command) {- case "loadSettings":- settings.loadSettings(worker);- break;- case "checkNewVersion":- checkNewVersion(worker);- break;- case "saveSettings":- settings.saveSettings(msg.detail.content, worker);- break;- case "rename":- ioutils.rename(msg.detail.path, msg.detail.newPath, worker);- break;- case "copy":- ioutils.copy(msg.detail.path, msg.detail.newPath, worker);- break;- case "saveTextFile":- ioutils.saveTextFile(msg.detail.path, msg.detail.content, worker);- break;- case "saveBinaryFile":- ioutils.saveBinaryFile(msg.detail.path, msg.detail.content, worker);- break;- case "createDirectory":- ioutils.createDirectory(msg.detail.path, worker);- break;- case "loadTextFile":- ioutils.loadTextFile(msg.detail.path, worker);- break;- case "listDirectory":- ioutils.listDirectory(msg.detail.path, worker);- break;- case "delete":- ioutils.deleteElement(msg.detail.path, worker);- break;- case "selectFile":- ioutils.promptFileOpenPicker(worker);- break;- case "selectDirectory":- ioutils.promptDirectorySelector(worker);- break;- case "openDirectory":- ioutils.openDirectory(msg.detail.path, worker);- break;- case "openExtensionsDirectory":- ioutils.openExtensionsDirectory(worker);- break;- case "createDirectoryIndex":- ioutils.createDirectoryIndex(msg.detail.path, worker);- break;- case "createDirectoryTree":- ioutils.createDirectoryTree(msg.detail.path, worker);- break;- case "getFileProperties":- ioutils.getFileProperties(msg.detail.path, worker);- break;- default:- break;- }-}+/* Copyright (c) 2012-2015 The Tagspaces Authors. All rights reserved.+ * Use of this source code is governed by a AGPL3 license that+ * can be found in the LICENSE file. */+/* jshint moz: true, strict: false */+/* global exports */+// the value of this var is replaced to "true" by the build script+var PRODUCTION = "@@PRODUCTION";+var VERSION = "@@VERSION";+// Disabling all output to console in production mode+if (PRODUCTION == "true") {+ console = console || {};+ console.log = function() {};+ console.error = function() {};+}+// Import the needed APIs+var data = require('sdk/self').data; // self+var ioutils = require("ioutils");+var settings = require("settings");+var request = require("sdk/request"); // request+var tabs = require("sdk/tabs");+var unload = require('sdk/system/unload');+var Panel = require('sdk/panel').Panel;+//var userstyles = require("userstyles");+var {+ Cc, Ci, Cu+} = require('chrome');+var utils = require('sdk/window/utils');+//var os = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;+var workers = [];+var toolbarButton;+if (require("sdk/system").staticArgs.disableStrict) {+ require("sdk/preferences/service").set("javascript.options.strict", false);+}+exports.main = function(options, callbacks) {+ console.log("Load reason: " + options.loadReason);+ var mainUIMod = require("sdk/page-mod"); // page-mod+ mainUIMod.PageMod({+ include: data.url("index.html"),+ contentScript: '' ++ 'self.on("message", function(message) {' ++ // 'console.log("Message received in content script from addon: "+JSON.stringify(message));'++ 'var event = document.createEvent("CustomEvent");' ++ 'var cloned = cloneInto(message, document.defaultView);' ++ 'event.initCustomEvent("tsMessage", true, true, cloned);' ++ 'document.documentElement.dispatchEvent(event);' ++ '}); ' ++ 'document.documentElement.addEventListener("addon-message", function(event) {' ++ // 'console.log("Message received from page script in content script "+JSON.stringify(event.detail));'++ 'self.postMessage(event.detail);' ++ '}, false);' ++ '',+ contentScriptWhen: 'end',+ onAttach: function onAttach(worker) {+ console.log("Attaching worker on tab with title: " + worker.tab.title);+ workers.push(worker);+ worker.on('message', function(data) {+ handleMessage(data, this);+ });+ worker.on('detach', function() {+ detachWorker(this);+ });+ }+ });+ // Adding menuitem to the tools menu+ var menuitem = require("menuitems").Menuitem({+ id: "TagSpacesMenuItem",+ menuid: "menu_ToolsPopup",+ label: "TagSpaces",+ // image: data.url("assets/icon16.png"),+ onCommand: openTagSpacesInNewTab,+ insertbefore: "menu_pageInfo"+ });+ // Adding toolbar button+ initToobarButton();+ if (options.loadReason == "install" || options.loadReason == "enable") {+ installToolbarButton();+ }+};++function installToolbarButton() {+ toolbarButton.moveTo({+ toolbarID: "nav-bar",+ insertbefore: "home-button",+ forceMove: false+ });+}++function openTagSpacesInNewTab() {+ tabs.open({+ url: data.url("index.html"),+ //isPinned: true,+ isPrivate: true+ });+}++function initToobarButton() {+ // Toolbar icon with badge+ /*toolbarButton = require('toolbarbutton').ToolbarButton({+ id: "tagspaces",+ label: "TagSpaces",+ tooltiptext: "TagSpaces",+ onClick: openTagSpacesInNewTab+ });+ toolbarButton.badge = "1.8.6";++ // Loading style for the toolbar icon with badge+ userstyles.load(data.url("mozilla/overlay.css"));+ if (os == "Linux") {+ userstyles.load(data.url("mozilla/overlay-linux.css"));+ }+ else if (os == "Darwin") {+ userstyles.load(data.url("mozilla/overlay-darwin.css"));+ }*/+ var tagspacesPanel = new Panel({+ width: 520,+ height: 400,+ contentURL: data.url('popup.html')+ });+ var buttons = require('sdk/ui/button/action');+ toolbarButton = buttons.ActionButton({+ id: "TSToolbarButton",+ label: "TagSpaces",+ icon: {+ "32": data.url("assets/icon32.png"),+ "64": data.url("assets/icon64.png")+ },+ onClick: openTagSpacesInNewTab+ /*onClick: function() {+ tagspacesPanel.show({+ position: toolbarButton+ });+ }*/+ });+}+unload.when(function(reason) {+ // since FF24 reason is never 'uninstall' see https://bugzilla.mozilla.org/show_bug.cgi?id=571049+ if (reason === 'uninstall' || reason === 'disable') {+ // action by uninstall or disable+ let prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);+ if (prompts.confirm(utils.getMostRecentBrowserWindow(), "Fill the uninstall survey", "Please fill the uninstall survey and tell us why are you removing TagSpaces. Your feedback could be very valuable for us! Would you like to fill it out?")) {+ tabs.open({+ url: "http://www.tagspaces.com/uninstallsurvey"+ });+ }+ }+});+exports.onUnload = function(reason) {+ console.log(reason);+};++function detachWorker(worker) {+ console.log("Detaching worker...");+ var index = workers.indexOf(worker);+ workers.splice(index, 1);+}+var checkForNewVersion = request.Request({+ url: "http://tagspaces.org/releases/version.json?fVer=" + VERSION,+ onComplete: function(response) {+ // console.log("Result: " + response.text + " " + response.status);+ return response.text;+ }+});++function checkNewVersion(worker) {+ try {+ var content;+ var versionReq = request.Request({+ url: "http://tagspaces.org/releases/version.json?fVer=" + VERSION,+ onComplete: function(response) {+ console.log("Result: " + response.text + " " + response.status);+ response.text;+ worker.postMessage({+ "command": "checkNewVersion",+ "content": response.text,+ "success": true+ });+ console.log("Loading settings successful!");+ }+ }).get();+ } catch (ex) {+ worker.postMessage({+ "command": "checkNewVersion",+ "success": false+ });+ console.error("Checking new version failed " + ex);+ }+}++function handleMessage(msg, worker) {+ //console.log("Message in main.js: " + JSON.stringify(msg) + " from tab " + worker.tab.title);+ //console.log("Thumbnail: "+worker.tab.getThumbnail());+ switch (msg.detail.command) {+ case "loadSettings":+ settings.loadSettings(worker);+ break;+ case "checkNewVersion":+ checkNewVersion(worker);+ break;+ case "saveSettings":+ settings.saveSettings(msg.detail.content, worker);+ break;+ case "rename":+ ioutils.rename(msg.detail.path, msg.detail.newPath, worker);+ break;+ case "copy":+ ioutils.copy(msg.detail.path, msg.detail.newPath, worker);+ break;+ case "saveTextFile":+ ioutils.saveTextFile(msg.detail.path, msg.detail.content, worker);+ break;+ case "saveBinaryFile":+ ioutils.saveBinaryFile(msg.detail.path, msg.detail.content, worker);+ break;+ case "createDirectory":+ ioutils.createDirectory(msg.detail.path, worker);+ break;+ case "loadTextFile":+ ioutils.loadTextFile(msg.detail.path, worker);+ break;+ case "listDirectory":+ ioutils.listDirectory(msg.detail.path, worker);+ break;+ case "delete":+ ioutils.deleteElement(msg.detail.path, worker);+ break;+ case "selectFile":+ ioutils.promptFileOpenPicker(worker);+ break;+ case "selectDirectory":+ ioutils.promptDirectorySelector(worker);+ break;+ case "openDirectory":+ ioutils.openDirectory(msg.detail.path, worker);+ break;+ case "openExtensionsDirectory":+ ioutils.openExtensionsDirectory(worker);+ break;+ case "createDirectoryIndex":+ ioutils.createDirectoryIndex(msg.detail.path, worker);+ break;+ case "createDirectoryTree":+ ioutils.createDirectoryTree(msg.detail.path, worker);+ break;+ case "getFileProperties":+ ioutils.getFileProperties(msg.detail.path, worker);+ break;+ default:+ break;+ }+}diff --git a/data/mozilla/mozilla.api.js b/data/mozilla/mozilla.api.jsindex c040e9a8b..6f9e1755a 100644--- a/data/mozilla/mozilla.api.js+++ b/data/mozilla/mozilla.api.js@@ -1,373 +1,409 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that- * can be found in the LICENSE file. */-/* global define */--define(function(require, exports, module) {-"use strict";-- console.log("Loading mozilla.api.js..");-- var TSCORE = require("tscore");-- var TSPOSTIO = require("tspostioapi");-- document.documentElement.addEventListener("tsMessage", function(event) {- console.log("Message received in page script from content script"); //+JSON.stringify(event.detail));- var message = event.detail;- switch (message.command) {- case "loadSettings":- if(message.success) {- try {- console.log("Loading settings...: "+JSON.stringify(message.content));- TSCORE.Config.updateSettingMozillaPreferences(message.content);-- TSCORE.initLocations();- TSCORE.generateTagGroups();-- } catch (ex) {- console.log("Exception while getting setting from firefox failed "+ex);- }- } else {- console.log("Getting setting from firefox failed");- }- break;- case "saveSettings":- if(message.success) {- console.log("Saving setting as native mozilla preference successfull!");- } else {- console.log("Saving setting as native mozilla preference failed!");- }- break;- case "rename":- if(message.success){- TSPOSTIO.renameFile(message.content[0],message.content[1]);- } else {- console.error("Rename failed");- }- break;- case "copy":- if(message.success){- TSPOSTIO.copyFile(message.content[0],message.content[1]);- } else {- TSCORE.hideWaitingDialog();- console.error("Rename failed "+message.content);- }- break;- case "saveTextFile":- if(message.success){- TSPOSTIO.saveTextFile(message.content);- } else {- console.error("Save failed");- }- break;- case "saveBinaryFile":- if(message.success){- TSPOSTIO.saveBinaryFile(message.content);- } else {- console.error("Save binary failed");- }- break;- case "createDirectory":- if(message.success){- TSPOSTIO.createDirectory(message.content);- } else {- console.error("Create dir failed");- }- break;- case "loadTextFile":- if(message.success){- TSPOSTIO.loadTextFile(message.content);- } else {- console.error("File loading failed");- }- break;- case "listDirectory":- if(message.success){- TSPOSTIO.listDirectory(message.content);- } else {- TSPOSTIO.errorOpeningPath();- }- break;- case "indexDirectory":- if(message.success){- TSPOSTIO.createDirectoryIndex(message.content);- } else {- console.error("Indexing directory failed");- }- break;- case "createDirectoryTree":- if(message.success){- console.log("Directory tree: "+JSON.stringify(message.content));- TSPOSTIO.createDirectoryTree(message.content);- } else {- console.error("Indexing directory failed");- }- break;- case "delete":- if(message.success){- TSPOSTIO.deleteElement(message.content);- } else {- console.error("Delete failed");- }- break;- case "selectDirectory":- if(message.success){- TSPOSTIO.selectDirectory(message.content);- } else {- console.error("Selecting directory failed.");- }- break;- case "checkNewVersion":- if(message.success){- TSPOSTIO.checkNewVersion(message.content);- } else {- console.error("Checking for new version failed.");- }- break;- case "getFileProperties":- if(message.success){- TSPOSTIO.getFileProperties(message.content);- } else {- console.error("Getting file properties failed.");- }- break;- default:- break;- }- }, false);-- var saveSettings = function(content) {- console.log("Saving setting...");- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "saveSettings",- "content": content- }});- document.documentElement.dispatchEvent(event);- };-- var loadSettings = function() {- console.log("Loading setting from firefox preferences...");- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "loadSettings"- }});- document.documentElement.dispatchEvent(event);- };-- var createDirectory = function(dirPath) {- console.log("Directory "+dirPath+" created.");- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "createDirectory",- "path": dirPath- }});- document.documentElement.dispatchEvent(event);- };-- var loadTextFile = function(filePath) {- console.log("Loading file: "+filePath);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "loadTextFile",- "path": filePath- }});- document.documentElement.dispatchEvent(event);- };-- var copyFile = function(filePath, newFilePath) {- console.log("Copy "+filePath+" to "+newFilePath);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "copy",- "path": filePath,- "newPath": newFilePath- }});- document.documentElement.dispatchEvent(event);- };-- var renameFile = function(filePath, newFilePath) {- console.log("Renaming "+filePath+" to "+newFilePath);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "rename",- "path": filePath,- "newPath": newFilePath- }});- document.documentElement.dispatchEvent(event);- };-- var renameDirectory = function(filePath, newFilePath) {- TSCORE.showAlertDialog("Rename directory functionality is not implemented in firefox yet.");- };-- var saveTextFile = function(filePath,content) {- console.log("Saving file: "+filePath);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "saveTextFile",- "path": filePath,- "content": content- }});- document.documentElement.dispatchEvent(event);- };-- function ab2str(buf) {- //TODO add support for larger files- // http://updates.html5rocks.com/2014/08/Easier-ArrayBuffer---String-conversion-with-the-Encoding-API- return String.fromCharCode.apply(null, new Uint8Array(buf));- }-- var saveBinaryFile = function(filePath,content) {- console.log("Saving binary file post: "+filePath); //+" - "+content);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "saveBinaryFile",- "path": filePath,- "content": ab2str(content)- }});- document.documentElement.dispatchEvent(event);- };-- var listDirectory = function(dirPath) {- console.log("Listing directory: "+dirPath);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "listDirectory",- "path": dirPath- }});- document.documentElement.dispatchEvent(event);- };-- var deleteElement = function(path) {- console.log("Deleting: "+path);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "delete",- "path": path- }});- document.documentElement.dispatchEvent(event);- };-- var deleteDirectory = function(dirPath) {- TSCORE.showAlertDialog("Delete directory functionality is not implemented in Firefox yet.");- };-- var checkAccessFileURLAllowed = function() {- console.log("checkAccessFileURLAllowed function not relevant for node..");- };-- var selectDirectory = function() {- console.log("Selecting directory...");- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "selectDirectory"- }});- document.documentElement.dispatchEvent(event);- };-- var selectFile = function() {- console.log("Selecting file...");- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "selectFile"- }});- document.documentElement.dispatchEvent(event);- };-- var openDirectory = function(dirPath) {- console.log("Opening directory: "+dirPath);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "openDirectory",- "path": dirPath- }});- document.documentElement.dispatchEvent(event);- };-- var openExtensionsDirectory = function() {- console.log("Opening extensions directory...");- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "openExtensionsDirectory"- }});- document.documentElement.dispatchEvent(event);- };-- var createDirectoryIndex = function(dirPath) {- console.log("Creating directory index for: "+dirPath);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "createDirectoryIndex",- "path": dirPath- }});- document.documentElement.dispatchEvent(event);- };-- var createDirectoryTree = function(dirPath) {- console.log("Creating directory tree for: "+dirPath);- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "createDirectoryTree",- "path": dirPath- }});- document.documentElement.dispatchEvent(event);- };-- var checkNewVersion = function() {- console.log("Checking for new version...");- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "checkNewVersion"- }});- document.documentElement.dispatchEvent(event);- };-- var getFileProperties = function(filePath) {- console.log("Getting file properties...");- var event = document.createEvent('CustomEvent');- event.initCustomEvent("addon-message", true, true, {"detail":{- "command": "getFileProperties",- "path": filePath- }});- document.documentElement.dispatchEvent(event);- };-- var openFile = function(filePath) {- // TODO implement openFile for firefox- console.log("Open file functionality not implemented in Firefox yet!");- TSCORE.showAlertDialog($.i18n.t("ns.dialogs:openFileNativelyAlert"));- };-- // Bring the TagSpaces window on top of the windows- var focusWindow = function() {- window.focus();- };-- exports.focusWindow = focusWindow;- exports.createDirectory = createDirectory;- exports.copyFile = copyFile;- exports.renameFile = renameFile;- exports.renameDirectory = renameDirectory;- exports.loadTextFile = loadTextFile;- exports.saveTextFile = saveTextFile;- exports.saveBinaryFile = saveBinaryFile;- exports.listDirectory = listDirectory;- exports.deleteElement = deleteElement;- exports.deleteDirectory = deleteDirectory;- exports.createDirectoryIndex = createDirectoryIndex;- exports.createDirectoryTree = createDirectoryTree;- exports.selectDirectory = selectDirectory;- exports.openDirectory = openDirectory;- exports.openFile = openFile;- exports.selectFile = selectFile;- exports.openExtensionsDirectory = openExtensionsDirectory;- exports.checkAccessFileURLAllowed = checkAccessFileURLAllowed;- exports.checkNewVersion = checkNewVersion;- exports.getFileProperties = getFileProperties;-- // mozilla specific- exports.saveSettings = saveSettings;- exports.loadSettings = loadSettings;-});+/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.+ * Use of this source code is governed by a AGPL3 license that+ * can be found in the LICENSE file. */+/* global define */++define(function(require, exports, module) {+ "use strict";++ console.log("Loading mozilla.api.js..");++ var TSCORE = require("tscore");++ var TSPOSTIO = require("tspostioapi");++ document.documentElement.addEventListener("tsMessage", function(event) {+ console.log("Message received in page script from content script"); //+JSON.stringify(event.detail));+ var message = event.detail;+ switch (message.command) {+ case "loadSettings":+ if (message.success) {+ try {+ console.log("Loading settings...: " + JSON.stringify(message.content));+ TSCORE.Config.updateSettingMozillaPreferences(message.content);++ TSCORE.initLocations();+ TSCORE.generateTagGroups();++ } catch (ex) {+ console.log("Exception while getting setting from firefox failed " + ex);+ }+ } else {+ console.log("Getting setting from firefox failed");+ }+ break;+ case "saveSettings":+ if (message.success) {+ console.log("Saving setting as native mozilla preference successfull!");+ } else {+ console.log("Saving setting as native mozilla preference failed!");+ }+ break;+ case "rename":+ if (message.success) {+ TSPOSTIO.renameFile(message.content[0], message.content[1]);+ } else {+ console.error("Rename failed");+ }+ break;+ case "copy":+ if (message.success) {+ TSPOSTIO.copyFile(message.content[0], message.content[1]);+ } else {+ TSCORE.hideWaitingDialog();+ console.error("Rename failed " + message.content);+ }+ break;+ case "saveTextFile":+ if (message.success) {+ TSPOSTIO.saveTextFile(message.content);+ } else {+ console.error("Save failed");+ }+ break;+ case "saveBinaryFile":+ if (message.success) {+ TSPOSTIO.saveBinaryFile(message.content);+ } else {+ console.error("Save binary failed");+ }+ break;+ case "createDirectory":+ if (message.success) {+ TSPOSTIO.createDirectory(message.content);+ } else {+ console.error("Create dir failed");+ }+ break;+ case "loadTextFile":+ if (message.success) {+ TSPOSTIO.loadTextFile(message.content);+ } else {+ console.error("File loading failed");+ }+ break;+ case "listDirectory":+ if (message.success) {+ TSPOSTIO.listDirectory(message.content);+ } else {+ TSPOSTIO.errorOpeningPath();+ }+ break;+ case "indexDirectory":+ if (message.success) {+ TSPOSTIO.createDirectoryIndex(message.content);+ } else {+ console.error("Indexing directory failed");+ }+ break;+ case "createDirectoryTree":+ if (message.success) {+ console.log("Directory tree: " + JSON.stringify(message.content));+ TSPOSTIO.createDirectoryTree(message.content);+ } else {+ console.error("Indexing directory failed");+ }+ break;+ case "delete":+ if (message.success) {+ TSPOSTIO.deleteElement(message.content);+ } else {+ console.error("Delete failed");+ }+ break;+ case "selectDirectory":+ if (message.success) {+ TSPOSTIO.selectDirectory(message.content);+ } else {+ console.error("Selecting directory failed.");+ }+ break;+ case "checkNewVersion":+ if (message.success) {+ TSPOSTIO.checkNewVersion(message.content);+ } else {+ console.error("Checking for new version failed.");+ }+ break;+ case "getFileProperties":+ if (message.success) {+ TSPOSTIO.getFileProperties(message.content);+ } else {+ console.error("Getting file properties failed.");+ }+ break;+ default:+ break;+ }+ }, false);++ var saveSettings = function(content) {+ console.log("Saving setting...");+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "saveSettings",+ "content": content+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var loadSettings = function() {+ console.log("Loading setting from firefox preferences...");+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "loadSettings"+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var createDirectory = function(dirPath) {+ console.log("Directory " + dirPath + " created.");+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "createDirectory",+ "path": dirPath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var loadTextFile = function(filePath) {+ console.log("Loading file: " + filePath);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "loadTextFile",+ "path": filePath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var copyFile = function(filePath, newFilePath) {+ console.log("Copy " + filePath + " to " + newFilePath);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "copy",+ "path": filePath,+ "newPath": newFilePath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var renameFile = function(filePath, newFilePath) {+ console.log("Renaming " + filePath + " to " + newFilePath);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "rename",+ "path": filePath,+ "newPath": newFilePath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var renameDirectory = function(filePath, newFilePath) {+ TSCORE.showAlertDialog("Rename directory functionality is not implemented in firefox yet.");+ };++ var saveTextFile = function(filePath, content) {+ console.log("Saving file: " + filePath);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "saveTextFile",+ "path": filePath,+ "content": content+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ function ab2str(buf) {+ //TODO add support for larger files+ // http://updates.html5rocks.com/2014/08/Easier-ArrayBuffer---String-conversion-with-the-Encoding-API+ return String.fromCharCode.apply(null, new Uint8Array(buf));+ }++ var saveBinaryFile = function(filePath, content) {+ console.log("Saving binary file post: " + filePath); //+" - "+content);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "saveBinaryFile",+ "path": filePath,+ "content": ab2str(content)+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var listDirectory = function(dirPath) {+ console.log("Listing directory: " + dirPath);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "listDirectory",+ "path": dirPath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var deleteElement = function(path) {+ console.log("Deleting: " + path);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "delete",+ "path": path+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var deleteDirectory = function(dirPath) {+ TSCORE.showAlertDialog("Delete directory functionality is not implemented in Firefox yet.");+ };++ var checkAccessFileURLAllowed = function() {+ console.log("checkAccessFileURLAllowed function not relevant for node..");+ };++ var selectDirectory = function() {+ console.log("Selecting directory...");+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "selectDirectory"+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var selectFile = function() {+ console.log("Selecting file...");+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "selectFile"+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var openDirectory = function(dirPath) {+ console.log("Opening directory: " + dirPath);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "openDirectory",+ "path": dirPath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var openExtensionsDirectory = function() {+ console.log("Opening extensions directory...");+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "openExtensionsDirectory"+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var createDirectoryIndex = function(dirPath) {+ console.log("Creating directory index for: " + dirPath);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "createDirectoryIndex",+ "path": dirPath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var createDirectoryTree = function(dirPath) {+ console.log("Creating directory tree for: " + dirPath);+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "createDirectoryTree",+ "path": dirPath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var checkNewVersion = function() {+ console.log("Checking for new version...");+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "checkNewVersion"+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var getFileProperties = function(filePath) {+ console.log("Getting file properties...");+ var event = document.createEvent('CustomEvent');+ event.initCustomEvent("addon-message", true, true, {+ "detail": {+ "command": "getFileProperties",+ "path": filePath+ }+ });+ document.documentElement.dispatchEvent(event);+ };++ var openFile = function(filePath) {+ // TODO implement openFile for firefox+ console.log("Open file functionality not implemented in Firefox yet!");+ TSCORE.showAlertDialog($.i18n.t("ns.dialogs:openFileNativelyAlert"));+ };++ // Bring the TagSpaces window on top of the windows+ var focusWindow = function() {+ window.focus();+ };++ exports.focusWindow = focusWindow;+ exports.createDirectory = createDirectory;+ exports.copyFile = copyFile;+ exports.renameFile = renameFile;+ exports.renameDirectory = renameDirectory;+ exports.loadTextFile = loadTextFile;+ exports.saveTextFile = saveTextFile;+ exports.saveBinaryFile = saveBinaryFile;+ exports.listDirectory = listDirectory;+ exports.deleteElement = deleteElement;+ exports.deleteDirectory = deleteDirectory;+ exports.createDirectoryIndex = createDirectoryIndex;+ exports.createDirectoryTree = createDirectoryTree;+ exports.selectDirectory = selectDirectory;+ exports.openDirectory = openDirectory;+ exports.openFile = openFile;+ exports.selectFile = selectFile;+ exports.openExtensionsDirectory = openExtensionsDirectory;+ exports.checkAccessFileURLAllowed = checkAccessFileURLAllowed;+ exports.checkNewVersion = checkNewVersion;+ exports.getFileProperties = getFileProperties;++ // mozilla specific+ exports.saveSettings = saveSettings;+ exports.loadSettings = loadSettings;+});diff --git a/data/mozilla/settings.js b/data/mozilla/settings.jsindex 1f28cbd3f..7897c27be 100644--- a/data/mozilla/settings.js+++ b/data/mozilla/settings.js@@ -1,58 +1,58 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that- * can be found in the LICENSE file. */-/* jshint moz: true, strict: false */-/* global exports */--const prefs = require('sdk/preferences/service'); // preferences-service--const PREF_PREFIX = 'extensions.tagspaces.';--function save(field, value) {- if (typeof value != 'undefined' && value != null) {- prefs.set(PREF_PREFIX + field, value);- }-}--function get(field) {- var value = prefs.get(PREF_PREFIX + field);- return value;-}--exports.loadSettings = function loadSettings(worker) {- console.log("Loading setting...");- try {- var content = get("settings");- console.log("Content: "+content);- worker.postMessage({- "command": "loadSettings",- "content": content,- "success": true- });- console.log("Loading settings successful!");- } catch(ex) {- worker.postMessage({- "command": "loadSettings",- "success": false- });- console.error("Loading settings failed "+ex);- }-};--exports.saveSettings = function saveSettings(content, worker) {- console.log("Saving setting...");- try {- save("settings", content);- worker.postMessage({- "command": "saveSettings",- "success": true- });- console.log("Saving settings successful!");- } catch(ex) {- worker.postMessage({- "command": "saveSettings",- "success": false- });- console.error("Saving settings failed "+ex);- }-};\ No newline at end of file+/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.+ * Use of this source code is governed by a AGPL3 license that+ * can be found in the LICENSE file. */+/* jshint moz: true, strict: false */+/* global exports */++const prefs = require('sdk/preferences/service'); // preferences-service++const PREF_PREFIX = 'extensions.tagspaces.';++function save(field, value) {+ if (typeof value != 'undefined' && value != null) {+ prefs.set(PREF_PREFIX + field, value);+ }+}++function get(field) {+ var value = prefs.get(PREF_PREFIX + field);+ return value;+}++exports.loadSettings = function loadSettings(worker) {+ console.log("Loading setting...");+ try {+ var content = get("settings");+ console.log("Content: " + content);+ worker.postMessage({+ "command": "loadSettings",+ "content": content,+ "success": true+ });+ console.log("Loading settings successful!");+ } catch (ex) {+ worker.postMessage({+ "command": "loadSettings",+ "success": false+ });+ console.error("Loading settings failed " + ex);+ }+};++exports.saveSettings = function saveSettings(content, worker) {+ console.log("Saving setting...");+ try {+ save("settings", content);+ worker.postMessage({+ "command": "saveSettings",+ "success": true+ });+ console.log("Saving settings successful!");+ } catch (ex) {+ worker.postMessage({+ "command": "saveSettings",+ "success": false+ });+ console.error("Saving settings failed " + ex);+ }+};