TagSpaces is an offline, open source, document manager with tagging support
jshinting
uggrockd5c896a24308
diff --git a/data/js/core.api.js b/data/js/core.api.jsindex 3445afa84..26abf9306 100644--- a/data/js/core.api.js+++ b/data/js/core.api.js@@ -1,678 +1,622 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that+/* 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. *//*global isNode, isWin, isFirefox, Mousetrap, gui */define(function(require, exports, module) {-"use strict";-- console.log("Loading core.api.js ...");-- var tsSettings = require("tssetting");- var tsIOApi = require("tsioapi");+ 'use strict';+ console.log('Loading core.api.js ...');+ var tsSettings = require('tssetting');+ var tsIOApi = require('tsioapi');// var tsIOApiDropbox = require("tsioapidropbox");- var tsPersManager = require("tspersmanager");- var tsTagUtils = require("tstagutils");- var tsFileOpener = require("tsfileopener");- var tsTagsUI = require("tstagsui");- var tsDirectoriesUI = require("tsdirectoriesui");- var tsCoreUI = require("tscoreui");- var tsSearch = require("tssearch");-- var currentPath;- var currentLocationObject;- var currentPerspectiveID;-- // Current selected files- var selectedFiles = [];-- // Current directory list of files- var fileList = [];-- // List of the sub directories of the current directory- var subDirsList = [];-- // Last clicked button for removing a tag- var selectedTag = "";-- var selectedTagData = "";-- var startTime;-- var subfoldersDirBrowser;-- var directoryBrowser;-- function initApp() {- console.log("Init application");-- tsSettings.loadSettingsLocalStorage();-- checkLocalStorageEnabled();-- // In firefox, by empty local storage trying to load the settings from mozilla preferences- if(tsSettings.Settings === undefined && isFirefox) {- window.setTimeout(tsIOApi.loadSettings, 1000); // executes initUI and updateSettingMozillaPreferences by success- console.log("Loading setting with from mozilla pref execured with delay...");- }-- // If still nothing found, loading the default setting from the application's javascript- // This is usually the case by a new installation- if(tsSettings.Settings === undefined) {- tsSettings.Settings = tsSettings.DefaultSettings;- }-- tsSettings.upgradeSettings();-- // Init UI components- tsCoreUI.initUI();- tsTagsUI.initUI();- tsTagsUI.generateTagGroups();- tsDirectoriesUI.initUI();- tsDirectoriesUI.initLocations();- tsFileOpener.initUI();- tsPersManager.initPerspectives();-- hideLoadingAnimation();-- $(document).ready(function() {- initLayout();- var language = tsSettings.getInterfaceLangauge(); // "de-DE"- var langURLParam = getParameterByName("locale");- if(langURLParam.length > 1) {- language = langURLParam;- }- switchInterfaceLanguage(language);- initKeyBindings();-- tsIOApi.checkAccessFileURLAllowed();-- // Show welcome dialog of first start- if(tsSettings.isFirstRun()) {- tsCoreUI.showWelcomeDialog();- }-- // Show welcome dialog by no locations- if(tsSettings.Settings.tagspacesList.length < 1 ) {- $( "#createNewLocation" ).tooltip( "show" );- $( "#locationName" ).prop('disabled', true);- $( "#selectLocation" ).prop('disabled', true);- tsCoreUI.showWelcomeDialog();- }-- if(isNode || isChrome) {- // Handle command line argument in node-webkit- tsIOApi.handleStartParameters();-- // Handle minimizing to the tray in node-webkit- //tsIOApi.handleTray();- }-- console.log("Docoument ready finished. Layout initialized");-- //$( "#loading" ).hide(); moved to perspective manager- checkForNewVersion();- });+ var tsPersManager = require('tspersmanager');+ var tsTagUtils = require('tstagutils');+ var tsFileOpener = require('tsfileopener');+ var tsTagsUI = require('tstagsui');+ var tsDirectoriesUI = require('tsdirectoriesui');+ var tsCoreUI = require('tscoreui');+ var tsSearch = require('tssearch');+ var currentPath;+ var currentLocationObject;+ var currentPerspectiveID;+ // Current selected files+ var selectedFiles = [];+ // Current directory list of files+ var fileList = [];+ // List of the sub directories of the current directory+ var subDirsList = [];+ // Last clicked button for removing a tag+ var selectedTag = '';+ var selectedTagData = '';+ var startTime;+ var subfoldersDirBrowser;+ var directoryBrowser;++ function initApp() {+ console.log('Init application');+ tsSettings.loadSettingsLocalStorage();+ checkLocalStorageEnabled();+ // In firefox, by empty local storage trying to load the settings from mozilla preferences+ if (tsSettings.Settings === undefined && isFirefox) {+ window.setTimeout(tsIOApi.loadSettings, 1000);+ // executes initUI and updateSettingMozillaPreferences by success+ console.log('Loading setting with from mozilla pref execured with delay...');}-- function switchIOAPI(type) {- if(type=="dropbox") {- tsIOApiDropbox.init();- exports.IO = tsIOApiDropbox;- } else {- exports.IO = tsIOApi;- }+ // If still nothing found, loading the default setting from the application's javascript+ // This is usually the case by a new installation+ if (tsSettings.Settings === undefined) {+ tsSettings.Settings = tsSettings.DefaultSettings;}-- function switchInterfaceLanguage(language) {- $.i18n.init({- ns: { namespaces: ['ns.common','ns.dialogs','ns.perspectiveList']},- lng: language,- debug: true,- fallbackLng: "en_US"- }, function() {- $('[data-i18n]').i18n();- if(isNode) {- tsIOApi.initMainMenu();- }- });+ tsSettings.upgradeSettings();+ // Init UI components+ tsCoreUI.initUI();+ tsTagsUI.initUI();+ tsTagsUI.generateTagGroups();+ tsDirectoriesUI.initUI();+ tsDirectoriesUI.initLocations();+ tsFileOpener.initUI();+ tsPersManager.initPerspectives();+ hideLoadingAnimation();+ $(document).ready(function() {+ initLayout();+ var language = tsSettings.getInterfaceLangauge();+ // "de-DE"+ var langURLParam = getParameterByName('locale');+ if (langURLParam.length > 1) {+ language = langURLParam;+ }+ switchInterfaceLanguage(language);+ initKeyBindings();+ tsIOApi.checkAccessFileURLAllowed();+ // Show welcome dialog of first start+ if (tsSettings.isFirstRun()) {+ tsCoreUI.showWelcomeDialog();+ }+ // Show welcome dialog by no locations+ if (tsSettings.Settings.tagspacesList.length < 1) {+ $('#createNewLocation').tooltip('show');+ $('#locationName').prop('disabled', true);+ $('#selectLocation').prop('disabled', true);+ tsCoreUI.showWelcomeDialog();+ }+ if (isNode || isChrome) {+ // Handle command line argument in node-webkit+ tsIOApi.handleStartParameters(); // Handle minimizing to the tray in node-webkit+ //tsIOApi.handleTray();+ }+ console.log('Docoument ready finished. Layout initialized');+ //$( "#loading" ).hide(); moved to perspective manager+ checkForNewVersion();+ });+ }++ function switchIOAPI(type) {+ if (type == 'dropbox') {+ tsIOApiDropbox.init();+ exports.IO = tsIOApiDropbox;+ } else {+ exports.IO = tsIOApi;}-- function initKeyBindings() {- if(isNode) {- var win = gui.Window.get();- Mousetrap.bind(tsSettings.getOpenDevToolsScreenKeyBinding(), function() {- win.showDevTools();- });- Mousetrap.bind(tsSettings.getReloadApplicationKeyBinding(), function() {- win.reloadIgnoringCache();- });- Mousetrap.bind(tsSettings.getToggleFullScreenKeyBinding(), function() {- win.toggleFullscreen();- });- }-- Mousetrap.bind(tsSettings.getShowTagLibraryKeyBinding(), function() {- tsCoreUI.showTagsPanel();- });-- Mousetrap.bind(tsSettings.getShowFolderNavigatorBinding(), function() {- tsCoreUI.showLocationsPanel();- });-- Mousetrap.bind(tsSettings.getAddRemoveTagsKeyBinding(), function() {- tsTagsUI.showAddTagsDialog();- });-- // TODO add swipeleft for closing left panel- /* $(".col1").hammer().on("swipeleft", function(event) {+ }++ function switchInterfaceLanguage(language) {+ $.i18n.init({+ ns: {+ namespaces: [+ 'ns.common',+ 'ns.dialogs',+ 'ns.perspectiveList'+ ]+ },+ lng: language,+ debug: true,+ fallbackLng: 'en_US'+ }, function() {+ $('[data-i18n]').i18n();+ if (isNode) {+ tsIOApi.initMainMenu();+ }+ });+ }++ function initKeyBindings() {+ if (isNode) {+ var win = gui.Window.get();+ Mousetrap.bind(tsSettings.getOpenDevToolsScreenKeyBinding(), function() {+ win.showDevTools();+ });+ Mousetrap.bind(tsSettings.getReloadApplicationKeyBinding(), function() {+ win.reloadIgnoringCache();+ });+ Mousetrap.bind(tsSettings.getToggleFullScreenKeyBinding(), function() {+ win.toggleFullscreen();+ });+ }+ Mousetrap.bind(tsSettings.getShowTagLibraryKeyBinding(), function() {+ tsCoreUI.showTagsPanel();+ });+ Mousetrap.bind(tsSettings.getShowFolderNavigatorBinding(), function() {+ tsCoreUI.showLocationsPanel();+ });+ Mousetrap.bind(tsSettings.getAddRemoveTagsKeyBinding(), function() {+ tsTagsUI.showAddTagsDialog();+ }); // TODO add swipeleft for closing left panel+ /* $(".col1").hammer().on("swipeleft", function(event) {console.log("swipeleft");toggleLeftPanel();}) */- }-- function checkForNewVersion() {- if(tsSettings.getCheckForUpdates()) {- tsIOApi.checkNewVersion();- }- }+ }- function checkLocalStorageEnabled() {- var val = 'tagspaces';- try {- localStorage.setItem(val, val);- localStorage.removeItem(val);- } catch(e) {- tsCoreUI.showAlertDialog($.i18n.t("ns.dialogs:enableLocalStorageAlert"),"Error");- }+ function checkForNewVersion() {+ if (tsSettings.getCheckForUpdates()) {+ tsIOApi.checkNewVersion();}-- function getParameterByName(name) {- name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");- var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),- results = regex.exec(location.search);- return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));+ }++ function checkLocalStorageEnabled() {+ var val = 'tagspaces';+ try {+ localStorage.setItem(val, val);+ localStorage.removeItem(val);+ } catch (e) {+ tsCoreUI.showAlertDialog($.i18n.t('ns.dialogs:enableLocalStorageAlert'), 'Error');}-- function updateNewVersionData(data) {- console.log("Version Information: "+data);- var versioningData = JSON.parse(data);-- // Analysing Version Information- var availableBuild = parseInt(versioningData['appBuild']);- var verA = versioningData['appVersion'].split(".");- if(verA[1].length == 1) {- verA[1] = "0"+verA[1];- }- var availableVersion = parseFloat(verA[0]+"."+verA[1]);-- var currentBuild = parseInt(tsSettings.DefaultSettings["appBuild"]);- var verC = tsSettings.DefaultSettings["appVersion"].split(".");- if(verC[1].length == 1) {- verC[1] = "0"+verC[1];- }- var currentVersion = parseFloat(verC[0]+"."+verC[1]);-- /* Testing the new version notifications+ }++ function getParameterByName(name) {+ name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');+ var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),+ results = regex.exec(location.search);+ return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));+ }++ function updateNewVersionData(data) {+ console.log('Version Information: ' + data);+ var versioningData = JSON.parse(data);+ // Analysing Version Information+ var availableBuild = parseInt(versioningData.appBuild);+ var verA = versioningData.appVersion.split('.');+ if (verA[1].length == 1) {+ verA[1] = '0' + verA[1];+ }+ var availableVersion = parseFloat(verA[0] + '.' + verA[1]);+ var currentBuild = parseInt(tsSettings.DefaultSettings.appBuild);+ var verC = tsSettings.DefaultSettings.appVersion.split('.');+ if (verC[1].length == 1) {+ verC[1] = '0' + verC[1];+ }+ var currentVersion = parseFloat(verC[0] + '.' + verC[1]);+ /* Testing the new version notificationsavailableVersion = 2;currentVersion = 1;availableBuild = 2;currentBuild = 1; */-- if(availableVersion > currentVersion || ((availableVersion == currentVersion) && (availableBuild > currentBuild))) {- $("#newVersionAvailable").css("display","block");- $("#whatsNewModal iframe").attr("src","http://tagspaces.org/whatsnew/");- $('#whatsNewModal').on('show.bs.modal', function (e) {- $("#whatsNewModal iframe").attr("src","http://tagspaces.org/whatsnew/");- })- }+ if (availableVersion > currentVersion || availableVersion == currentVersion && availableBuild > currentBuild) {+ $('#newVersionAvailable').css('display', 'block');+ $('#whatsNewModal iframe').attr('src', 'http://tagspaces.org/whatsnew/');+ $('#whatsNewModal').on('show.bs.modal', function(e) {+ $('#whatsNewModal iframe').attr('src', 'http://tagspaces.org/whatsnew/');+ });}-- function updateLogger() {- console.log("Updating logger...");+ }++ function updateLogger() {+ console.log('Updating logger...');+ }++ function showLoadingAnimation() {+ $('#loadingAnimation').css('visibility', 'visible');+ }++ function hideLoadingAnimation() {+ $('#loadingAnimation').css('visibility', 'hidden');+ }++ function removeFileModel(model, filePath) {+ console.log('Removing file from model');+ for (var i = 0; i < model.length; i++) {+ if (model[i][exports.fileListFILEPATH] === filePath) {+ model.splice(i, 1);+ }}-- function showLoadingAnimation() {- $("#loadingAnimation").css('visibility', "visible");+ }++ function updateFileModel(model, oldPath, newPath) {+ console.log('Removing file from model');+ var title = tsTagUtils.extractTitle(newPath),+ fileExt = tsTagUtils.extractFileExtension(newPath),+ fileTags = tsTagUtils.extractTags(newPath);+ for (var i = 0; i < model.length; i++) {+ if (model[i][exports.fileListFILEPATH] == oldPath) {+ model[i][exports.fileListFILEPATH] = newPath;+ model[i][exports.fileListTITLE] = title;+ model[i][exports.fileListTAGS] = fileTags;+ model[i][exports.fileListFILEEXT] = fileExt; // TODO complete the list+ //model[i][exports.fileListFILELMDT] = newPath;+ //model[i][exports.fileListFILENAME] = newPath;+ //model[i][exports.fileListFILESIZE] = newPath;+ }}-- function hideLoadingAnimation() {- $("#loadingAnimation").css('visibility', "hidden");+ }++ function exportFileListCSV(fileList) {+ var csv = '';+ var headers = [];+ var rows = [];+ var numberOfTagColumns = 40;+ // max. estimated to 40 ca. 5 symbols per tag _[er], max. path length 25x chars+ headers.push('path');+ headers.push('title');+ headers.push('size');+ for (var i = 0; i < numberOfTagColumns; i++) {+ headers.push('tag' + i);}-- function removeFileModel(model, filePath) {- console.log("Removing file from model");- for(var i = 0; i < model.length; i++) {- if(model[i][exports.fileListFILEPATH] === filePath) {- model.splice( i, 1 );- }+ csv += headers.join(',') + '\n';+ for (var i = 0; i < fileList.length; i++) {+ var row = fileList[i][exports.fileListFILEPATH] + ',' + fileList[i][exports.fileListTITLE] + ',' + fileList[i][exports.fileListFILESIZE] + ',' + fileList[i][exports.fileListTAGS];+ rows.push(row);+ }+ csv += rows.join('\n');+ return csv;+ }++ function exportFileListArray(fileList) {+ var rows = [];+ for (var i = 0; i < fileList.length; i++) {+ var row = [];+ row.path = fileList[i][exports.fileListFILEPATH];+ row.title = fileList[i][exports.fileListTITLE];+ row.size = fileList[i][exports.fileListFILESIZE];+ var tags = fileList[i][exports.fileListTAGS];+ for (var j = 0; j < tags.length; j++) {+ row['tag' + j] = tags[j];}- }-- function updateFileModel(model, oldPath, newPath) {- console.log("Removing file from model");- var title = tsTagUtils.extractTitle(newPath),- fileExt = tsTagUtils.extractFileExtension(newPath),- fileTags = tsTagUtils.extractTags(newPath);-- for(var i = 0; i < model.length; i++) {- if(model[i][exports.fileListFILEPATH] == oldPath) {- model[i][exports.fileListFILEPATH] = newPath;- model[i][exports.fileListTITLE] = title;- model[i][exports.fileListTAGS] = fileTags;- model[i][exports.fileListFILEEXT] = fileExt;- // TODO complete the list- //model[i][exports.fileListFILELMDT] = newPath;- //model[i][exports.fileListFILENAME] = newPath;- //model[i][exports.fileListFILESIZE] = newPath;- }+ rows.push(row);+ }+ return rows;+ }+ // UI and Layout functionalities+ // Layout vars+ var layoutContainer;+ var col1Layout;+ var col2Layout;+ var isFullWidth = false;+ var shouldOpenCol1 = true;+ var shouldOpenCol3 = false;+ var col1DefaultWidth = 250;+ // End Layout Vars+ function reLayout() {+ //console.log("Window w: "+window.innerWidth+" h: "+window.innerHeight+" orient: "+window.orientation+" dpi: "+window.devicePixelRatio);+ var fullWidth = window.innerWidth;+ var halfWidth = Math.round(window.innerWidth / 2);+ var isPortret = fullWidth < window.innerHeight;+ var oneColumn = fullWidth < 660;+ var twoColumn = fullWidth >= 660 && fullWidth < 1024;+ //$(".col3").css("left","auto");+ layoutContainer.options.east.spacing_open = 1;+ // $("#toggleFullWidthButton").hide();+ if (isFullWidth) {+ oneColumn = true; // $("#toggleFullWidthButton").show();+ }+ if (oneColumn) {+ $('#closeLeftPanel').show();+ layoutContainer.options.east.spacing_open = 0;+ if (shouldOpenCol3) {+ layoutContainer.close('west');+ // workarround+ shouldOpenCol1 = false;+ //Closing col1+ layoutContainer.sizePane('east', fullWidth); // make col3 100%+ //$(".col3").css("left","0"); // workarround for removing 1px balkan on the left+ //east__spacing_open: 1+ } else {+ if (!layoutContainer.state.west.isClosed) {+ if (isPortret) {+ // by opened col1 panel make it 75%+ layoutContainer.sizePane('west', Math.round(3 * (window.innerWidth / 4)));+ } else {+ layoutContainer.sizePane('west', col1DefaultWidth);+ }}- }-- function exportFileListCSV(fileList) {- var csv = '';- var headers = [];- var rows = [];- var numberOfTagColumns = 40; // max. estimated to 40 ca. 5 symbols per tag _[er], max. path length 25x chars-- headers.push("path");- headers.push("title");- headers.push("size");- for(var i = 0; i < numberOfTagColumns; i++) {- headers.push("tag"+i);+ }+ if (!isFullWidth) {+ $('#toggleFullWidthButton').hide();+ }+ } else if (twoColumn) {+ //$("#closeLeftPanel").show();+ if (isPortret) {+ if (shouldOpenCol3) {+ layoutContainer.close('west');+ // workarround+ shouldOpenCol1 = false;+ //Closing col1+ layoutContainer.sizePane('east', fullWidth); // make col3 100%+ } else {+ // by opened col1 panel make it 250+ if (!layoutContainer.state.west.isClosed) {+ layoutContainer.sizePane('west', col1DefaultWidth);+ }}- csv += headers.join(',') + "\n";-- for(var i = 0; i < fileList.length; i++) {- var row = fileList[i][exports.fileListFILEPATH]+","+fileList[i][exports.fileListTITLE]+","+fileList[i][exports.fileListFILESIZE]+","+fileList[i][exports.fileListTAGS];- rows.push(row);+ } else {+ if (shouldOpenCol3) {+ shouldOpenCol1 = false;+ //Closing col1+ layoutContainer.sizePane('east', halfWidth); // make col3 100%+ } else {+ // by opened col1 panel make it 250+ if (!layoutContainer.state.west.isClosed) {+ layoutContainer.sizePane('west', col1DefaultWidth);+ }}-- csv += rows.join("\n");- return csv;- }-- function exportFileListArray(fileList) {- var rows = [];- for(var i = 0; i < fileList.length; i++) {- var row = [];- row["path"] = fileList[i][exports.fileListFILEPATH];- row["title"] = fileList[i][exports.fileListTITLE];- row["size"] = fileList[i][exports.fileListFILESIZE];-- var tags = fileList[i][exports.fileListTAGS];- for(var j = 0; j < tags.length; j++) {- row["tag"+(j)] = tags[j];- }- rows.push(row);+ }+ } else {+ // Regular case+ $('#closeLeftPanel').hide();+ if (isPortret) {+ if (shouldOpenCol3) {+ layoutContainer.close('west');+ // workarround+ shouldOpenCol1 = false;+ //Closing col1+ layoutContainer.sizePane('east', fullWidth); // make col3 100%+ } else {+ // by opened col1 panel make it 50%+ if (!layoutContainer.state.west.isClosed) {+ layoutContainer.sizePane('west', col1DefaultWidth);+ }}- return rows;- }-- // UI and Layout functionalities-- // Layout vars- var layoutContainer;- var col1Layout;- var col2Layout;-- var isFullWidth = false;- var shouldOpenCol1 = true;- var shouldOpenCol3 = false;- var col1DefaultWidth = 250;-- // End Layout Vars-- function reLayout() {- //console.log("Window w: "+window.innerWidth+" h: "+window.innerHeight+" orient: "+window.orientation+" dpi: "+window.devicePixelRatio);- var fullWidth = window.innerWidth;- var halfWidth = Math.round(window.innerWidth/2);- var isPortret = fullWidth < window.innerHeight;- var oneColumn = fullWidth < 660;- var twoColumn = (fullWidth >= 660 && fullWidth < 1024);- //$(".col3").css("left","auto");- layoutContainer.options.east.spacing_open = 1;-// $("#toggleFullWidthButton").hide();-- if(isFullWidth) {- oneColumn = true;-// $("#toggleFullWidthButton").show();+ } else {+ $('#toggleFullWidthButton').show();+ if (isFullWidth) {+ // TODO hide tags+ $('#viewerContainer').css('top', '38px');+ layoutContainer.close('west');+ // workarround+ shouldOpenCol1 = false;+ layoutContainer.sizePane('east', fullWidth);+ } else {+ $('#viewerContainer').css('top', '81px');+ layoutContainer.sizePane('west', col1DefaultWidth);+ layoutContainer.sizePane('east', halfWidth);}-- if(oneColumn) {- $("#closeLeftPanel").show();- layoutContainer.options.east.spacing_open = 0;- if(shouldOpenCol3) {- layoutContainer.close("west"); // workarround- shouldOpenCol1 = false; //Closing col1- layoutContainer.sizePane("east", fullWidth); // make col3 100%- //$(".col3").css("left","0"); // workarround for removing 1px balkan on the left- //east__spacing_open: 1- } else {- if(!layoutContainer.state.west.isClosed) {- if(isPortret) {- // by opened col1 panel make it 75%- layoutContainer.sizePane("west", Math.round(3*(window.innerWidth/4)));- } else {- layoutContainer.sizePane("west", col1DefaultWidth);- }- }- }- if(!isFullWidth) {- $("#toggleFullWidthButton").hide();- }- } else if(twoColumn) {- //$("#closeLeftPanel").show();- if(isPortret) {- if(shouldOpenCol3) {- layoutContainer.close("west"); // workarround- shouldOpenCol1 = false; //Closing col1- layoutContainer.sizePane("east", fullWidth); // make col3 100%- } else {- // by opened col1 panel make it 250- if(!layoutContainer.state.west.isClosed) {- layoutContainer.sizePane("west", col1DefaultWidth);- }- }- } else {- if(shouldOpenCol3) {- shouldOpenCol1 = false; //Closing col1- layoutContainer.sizePane("east", halfWidth); // make col3 100%- } else {- // by opened col1 panel make it 250- if(!layoutContainer.state.west.isClosed) {- layoutContainer.sizePane("west", col1DefaultWidth);- }- }- }- } else { // Regular case- $("#closeLeftPanel").hide();- if(isPortret) {- if(shouldOpenCol3) {- layoutContainer.close("west"); // workarround- shouldOpenCol1 = false; //Closing col1- layoutContainer.sizePane("east", fullWidth); // make col3 100%- } else {- // by opened col1 panel make it 50%- if(!layoutContainer.state.west.isClosed) {- layoutContainer.sizePane("west", col1DefaultWidth);- }- }- } else {- $("#toggleFullWidthButton").show();- if(isFullWidth) {- // TODO hide tags- $("#viewerContainer").css("top","38px");- layoutContainer.close("west"); // workarround- shouldOpenCol1 = false;- layoutContainer.sizePane("east", fullWidth);- } else {- $("#viewerContainer").css("top","81px");- layoutContainer.sizePane("west", col1DefaultWidth);- layoutContainer.sizePane("east", halfWidth);- }- }- }-- // Handle opening col1- shouldOpenCol1?layoutContainer.open("west"):layoutContainer.close("west");-- // Handle opening col3- shouldOpenCol3?layoutContainer.open("east"):layoutContainer.close("east");- }-- function openFileViewer() {- tsCoreUI.hideAllDropDownMenus();- shouldOpenCol3 = true;- reLayout();+ }}-- function closeFileViewer() {- shouldOpenCol3 = false;- isFullWidth = false;- reLayout();- }-- function toggleFullWidth() {- isFullWidth = !isFullWidth;- reLayout();+ // Handle opening col1+ shouldOpenCol1 ? layoutContainer.open('west') : layoutContainer.close('west');+ // Handle opening col3+ shouldOpenCol3 ? layoutContainer.open('east') : layoutContainer.close('east');+ }++ function openFileViewer() {+ tsCoreUI.hideAllDropDownMenus();+ shouldOpenCol3 = true;+ reLayout();+ }++ function closeFileViewer() {+ shouldOpenCol3 = false;+ isFullWidth = false;+ reLayout();+ }++ function toggleFullWidth() {+ isFullWidth = !isFullWidth;+ reLayout();+ }++ function toggleLeftPanel() {+ layoutContainer.toggle('west');+ shouldOpenCol1 = !shouldOpenCol1;+ }++ function openLeftPanel() {+ if (layoutContainer !== undefined) {+ layoutContainer.open('west');+ shouldOpenCol1 = true;}-- function toggleLeftPanel() {- layoutContainer.toggle("west");- shouldOpenCol1 = !shouldOpenCol1;- }-- function openLeftPanel() {- if(layoutContainer !== undefined) {- layoutContainer.open("west");- shouldOpenCol1 = true;+ }++ function reloadUI() {+ location.reload();+ }+ window.addEventListener('orientationchange', reLayout);+ $(window).on('resize', reLayout);++ function initLayout() {+ console.log('Initializing Layout...');+ layoutContainer = $('body').layout({+ panes: {+ // defaults for all panes in layout+ tips: {+ noRoomToOpen: '' // blank = no message}- }-- function reloadUI() {- location.reload();- }-- window.addEventListener("orientationchange", reLayout);-- $( window ).on('resize', reLayout);-- function initLayout (){- console.log("Initializing Layout...");-- layoutContainer = $('body').layout({- panes: { // defaults for all panes in layout- tips: {- noRoomToOpen: "" // blank = no message- }- },- name: 'outerLayout', // for debugging & auto-adding buttons (see below)- //fxName: "slide", // none, slide- //fxSpeed: "normal",- autoResize: true, // try to maintain pane-percentages- autoReopen: true, // auto-open panes that were previously auto-closed due to 'no room'- minSize: 0,- autoBindCustomButtons: true,- west__paneSelector: '.col1',- center__paneSelector: '.col2',- east__paneSelector: '.col3',- east__resizable: false,- west__size: col1DefaultWidth,- west__minWidth: col1DefaultWidth,- east__size: 0.5,- west__resizable: false,- west__spacing_open: 1,- east__spacing_open: 1,- center_minWidth: 0,- center_minHeight: 200,- spacing_closed: 0,- noRoomToOpenAction: "hide", // 'close' or 'hide' when no room to open a pane at minSize- // west__showOverflowOnHover: true,- // center__showOverflowOnHover: true,- // east__showOverflowOnHover: true,- enableCursorHotkey: false- // showErrorMessages: false,- });-- // Initially close the right panel- layoutContainer.close("east");-- col1Layout = layoutContainer.panes.west.layout({- name: 'col1Layout', // for debugging & auto-adding buttons (see below)- // north__paneSelector: '.row1',- center__paneSelector: '.row2',- south__paneSelector: '.row3',- // north__size: row1Height, // percentage size expresses as a string- south__size: 50,- north__spacing_open: 0,- south__spacing_open: 0,- autoResize: false, // try to maintain pane-percentages- closable: false,- //fxName: "slide", // none, slide- //fxSpeed: "slow", // normal, fast- togglerLength_open: 0, // hide toggler-buttons- spacing_closed: 0, // hide resizer/slider bar when closed- // autoReopen: true, // auto-open panes that were previously auto-closed due to 'no room'- autoBindCustomButtons: true,- minSize: 0,- center__minHeight: 25,- // north__showOverflowOnHover: true,- // center__showOverflowOnHover:true,- // south__showOverflowOnHover: true,- enableCursorHotkey: false- // showErrorMessages: false- });-- col2Layout = layoutContainer.panes.center.layout({- name: 'col2Layout', // for debugging & auto-adding buttons (see below)- // north__paneSelector: '.row1',- center__paneSelector: '.row2',- south__paneSelector: '.row3',- // north__size: row1Height, // percentage size expresses as a string- south__size: 45,- north__spacing_open: 0,- south__spacing_open: 0,- autoResize: true, // try to maintain pane-percentages- closable: false,- togglerLength_open: 0, // hide toggler-buttons- spacing_closed: 0, // hide resizer/slider bar when closed- autoReopen: true, // auto-open panes that were previously auto-closed due to 'no room'- autoBindCustomButtons: true,- minSize: 0,- center__minHeight: 25,- north__showOverflowOnHover: true,- // center__showOverflowOnHover:true,- // south__showOverflowOnHover: true,- enableCursorHotkey: false- // showErrorMessages: false- });-- /*- var col3Layout = layoutContainer.panes.east.layout({- name: 'col2Layout' // for debugging & auto-adding buttons (see below)- // , north__paneSelector: '.row1'- , center__paneSelector: '.row2'- , south__paneSelector: '.row3'- // , north__size: row1Height // percentage size expresses as a string- , south__size: row3Height- , north__spacing_open: 0- , south__spacing_open: 0- , autoResize: true // try to maintain pane-percentages- , closable: false- , togglerLength_open: 0 // hide toggler-buttons- , spacing_closed: 0 // hide resizer/slider bar when closed- , autoReopen: true // auto-open panes that were previously auto-closed due to 'no room'- , autoBindCustomButtons: true- , minSize: 25- , center__minHeight: 25- , north__showOverflowOnHover: true- // , center__showOverflowOnHover: true- // , south__showOverflowOnHover: true- , enableCursorHotkey: false- }); */-- reLayout();- }--- // Proxying applications parts- exports.Config = tsSettings;- exports.IO = tsIOApi;- exports.UI = tsCoreUI;- exports.PerspectiveManager = tsPersManager;- exports.TagUtils = tsTagUtils;- exports.FileOpener = tsFileOpener;- exports.Search = tsSearch;-- // Public API definition- exports.dirSeparator = (isWin && !isWeb)?"\\":"/";- exports.locationDesktop;- exports.initApp = initApp;- exports.reLayout = reLayout;- exports.updateLogger = updateLogger;- exports.showLoadingAnimation = showLoadingAnimation;- exports.hideLoadingAnimation = hideLoadingAnimation;-// exports.fileExists = fileExists;- exports.reloadUI = reloadUI;- exports.openFileViewer = openFileViewer;- exports.closeFileViewer = closeFileViewer;- exports.toggleLeftPanel = toggleLeftPanel;- exports.openLeftPanel = openLeftPanel;- exports.toggleFullWidth = toggleFullWidth;- exports.updateNewVersionData = updateNewVersionData;- exports.exportFileListCSV = exportFileListCSV;- exports.exportFileListArray = exportFileListArray;- exports.removeFileModel = removeFileModel;- exports.updateFileModel = updateFileModel;- exports.switchInterfaceLanguage = switchInterfaceLanguage;- exports.getParameterByName = getParameterByName;-- // Proxying functions from tsCoreUI- // TODO use TSCORE.UI instead- exports.clearSearchFilter = tsCoreUI.clearSearchFilter;- exports.openLinkExternally = tsCoreUI.openLinkExternally;- exports.enableTopToolbar = tsCoreUI.enableTopToolbar;- exports.disableTopToolbar = tsCoreUI.disableTopToolbar;- exports.showAlertDialog = tsCoreUI.showAlertDialog;- exports.showConfirmDialog = tsCoreUI.showConfirmDialog;- exports.showTagEditDialog = tsCoreUI.showTagEditDialog;- exports.hideAllDropDownMenus = tsCoreUI.hideAllDropDownMenus;- exports.showFileCreateDialog = tsCoreUI.showFileCreateDialog;- exports.showFileRenameDialog = tsCoreUI.showFileRenameDialog;- exports.showFileDeleteDialog = tsCoreUI.showFileDeleteDialog;- exports.showLocationsPanel = tsCoreUI.showLocationsPanel;- exports.showTagsPanel = tsCoreUI.showTagsPanel;- exports.showContextMenu = tsCoreUI.showContextMenu;- exports.showDirectoryBrowserDialog = tsCoreUI.showDirectoryBrowserDialog;- exports.createHTMLFile = tsCoreUI.createHTMLFile;- exports.createMDFile = tsCoreUI.createMDFile;- exports.createTXTFile = tsCoreUI.createTXTFile;- exports.showSearchArea = tsCoreUI.showSearchArea;-- // Proxying functions from tsTagsUI- exports.generateTagButtons = tsTagsUI.generateTagButtons;- exports.generateTagStyle = tsTagsUI.generateTagStyle;- exports.openTagMenu = tsTagsUI.openTagMenu;- exports.showWaitingDialog = tsCoreUI.showWaitingDialog;- exports.hideWaitingDialog = tsCoreUI.hideWaitingDialog;- exports.showMoveCopyFilesDialog = tsCoreUI.showMoveCopyFilesDialog;- exports.showAddTagsDialog = tsTagsUI.showAddTagsDialog;- exports.showTagEditInTreeDialog = tsTagsUI.showTagEditInTreeDialog;- exports.showDialogTagCreate = tsTagsUI.showDialogTagCreate;- exports.showDialogEditTagGroup = tsTagsUI.showDialogEditTagGroup;- exports.showDialogTagGroupCreate = tsTagsUI.showDialogTagGroupCreate;- exports.calculatedTags = tsTagsUI.calculatedTags;- exports.locationTags = tsTagsUI.locationTags;- exports.generateTagGroups = tsTagsUI.generateTagGroups;-- // Proxying functions from directoriesUI- exports.openLocation = tsDirectoriesUI.openLocation;- exports.updateSubDirs = tsDirectoriesUI.updateSubDirs;- exports.initLocations = tsDirectoriesUI.initLocations;- exports.showCreateDirectoryDialog = tsDirectoriesUI.showCreateDirectoryDialog;- exports.closeCurrentLocation = tsDirectoriesUI.closeCurrentLocation;- exports.navigateToDirectory = tsDirectoriesUI.navigateToDirectory;-- // Public variables definition- exports.currentPath = currentPath;- exports.currentLocationObject = currentLocationObject;- exports.currentPerspectiveID = currentPerspectiveID;- exports.selectedFiles = selectedFiles;- exports.fileList = fileList;- exports.subDirsList = subDirsList;- exports.selectedTag = selectedTag;- exports.selectedTagData = selectedTagData;- exports.startTime = startTime;- exports.subfoldersDirBrowser = subfoldersDirBrowser;- exports.directoryBrowser = directoryBrowser;-- exports.fileListFILEEXT = 0;- exports.fileListTITLE = 1;- exports.fileListTAGS = 2;- exports.fileListFILESIZE = 3;- exports.fileListFILELMDT = 4;- exports.fileListFILEPATH = 5;- exports.fileListFILENAME = 6;--});\ No newline at end of file+ },+ name: 'outerLayout',+ // for debugging & auto-adding buttons (see below)+ //fxName: "slide", // none, slide+ //fxSpeed: "normal",+ autoResize: true,+ // try to maintain pane-percentages+ autoReopen: true,+ // auto-open panes that were previously auto-closed due to 'no room'+ minSize: 0,+ autoBindCustomButtons: true,+ west__paneSelector: '.col1',+ center__paneSelector: '.col2',+ east__paneSelector: '.col3',+ east__resizable: false,+ west__size: col1DefaultWidth,+ west__minWidth: col1DefaultWidth,+ east__size: 0.5,+ west__resizable: false,+ west__spacing_open: 1,+ east__spacing_open: 1,+ center_minWidth: 0,+ center_minHeight: 200,+ spacing_closed: 0,+ noRoomToOpenAction: 'hide',+ // 'close' or 'hide' when no room to open a pane at minSize+ // west__showOverflowOnHover: true,+ // center__showOverflowOnHover: true,+ // east__showOverflowOnHover: true,+ enableCursorHotkey: false // showErrorMessages: false,+ });+ // Initially close the right panel+ layoutContainer.close('east');+ col1Layout = layoutContainer.panes.west.layout({+ name: 'col1Layout',+ // for debugging & auto-adding buttons (see below)+ // north__paneSelector: '.row1',+ center__paneSelector: '.row2',+ south__paneSelector: '.row3',+ // north__size: row1Height, // percentage size expresses as a string+ south__size: 50,+ north__spacing_open: 0,+ south__spacing_open: 0,+ autoResize: false,+ // try to maintain pane-percentages+ closable: false,+ //fxName: "slide", // none, slide+ //fxSpeed: "slow", // normal, fast+ togglerLength_open: 0,+ // hide toggler-buttons+ spacing_closed: 0,+ // hide resizer/slider bar when closed+ // autoReopen: true, // auto-open panes that were previously auto-closed due to 'no room'+ autoBindCustomButtons: true,+ minSize: 0,+ center__minHeight: 25,+ // north__showOverflowOnHover: true,+ // center__showOverflowOnHover:true,+ // south__showOverflowOnHover: true,+ enableCursorHotkey: false // showErrorMessages: false+ });+ col2Layout = layoutContainer.panes.center.layout({+ name: 'col2Layout',+ // for debugging & auto-adding buttons (see below)+ // north__paneSelector: '.row1',+ center__paneSelector: '.row2',+ south__paneSelector: '.row3',+ // north__size: row1Height, // percentage size expresses as a string+ south__size: 45,+ north__spacing_open: 0,+ south__spacing_open: 0,+ autoResize: true,+ // try to maintain pane-percentages+ closable: false,+ togglerLength_open: 0,+ // hide toggler-buttons+ spacing_closed: 0,+ // hide resizer/slider bar when closed+ autoReopen: true,+ // auto-open panes that were previously auto-closed due to 'no room'+ autoBindCustomButtons: true,+ minSize: 0,+ center__minHeight: 25,+ north__showOverflowOnHover: true,+ // center__showOverflowOnHover:true,+ // south__showOverflowOnHover: true,+ enableCursorHotkey: false // showErrorMessages: false+ });++ reLayout();+ }++ // Proxying applications parts+ exports.Config = tsSettings;+ exports.IO = tsIOApi;+ exports.UI = tsCoreUI;+ exports.PerspectiveManager = tsPersManager;+ exports.TagUtils = tsTagUtils;+ exports.FileOpener = tsFileOpener;+ exports.Search = tsSearch;++ // Public API definition+ exports.dirSeparator = isWin && !isWeb ? '\\' : '/';+ exports.locationDesktop;+ exports.initApp = initApp;+ exports.reLayout = reLayout;+ exports.updateLogger = updateLogger;+ exports.showLoadingAnimation = showLoadingAnimation;+ exports.hideLoadingAnimation = hideLoadingAnimation;+ exports.reloadUI = reloadUI;+ exports.openFileViewer = openFileViewer;+ exports.closeFileViewer = closeFileViewer;+ exports.toggleLeftPanel = toggleLeftPanel;+ exports.openLeftPanel = openLeftPanel;+ exports.toggleFullWidth = toggleFullWidth;+ exports.updateNewVersionData = updateNewVersionData;+ exports.exportFileListCSV = exportFileListCSV;+ exports.exportFileListArray = exportFileListArray;+ exports.removeFileModel = removeFileModel;+ exports.updateFileModel = updateFileModel;+ exports.switchInterfaceLanguage = switchInterfaceLanguage;+ exports.getParameterByName = getParameterByName;++ // Proxying functions from tsCoreUI+ // TODO use TSCORE.UI instead+ exports.clearSearchFilter = tsCoreUI.clearSearchFilter;+ exports.openLinkExternally = tsCoreUI.openLinkExternally;+ exports.enableTopToolbar = tsCoreUI.enableTopToolbar;+ exports.disableTopToolbar = tsCoreUI.disableTopToolbar;+ exports.showAlertDialog = tsCoreUI.showAlertDialog;+ exports.showConfirmDialog = tsCoreUI.showConfirmDialog;+ exports.showTagEditDialog = tsCoreUI.showTagEditDialog;+ exports.hideAllDropDownMenus = tsCoreUI.hideAllDropDownMenus;+ exports.showFileCreateDialog = tsCoreUI.showFileCreateDialog;+ exports.showFileRenameDialog = tsCoreUI.showFileRenameDialog;+ exports.showFileDeleteDialog = tsCoreUI.showFileDeleteDialog;+ exports.showLocationsPanel = tsCoreUI.showLocationsPanel;+ exports.showTagsPanel = tsCoreUI.showTagsPanel;+ exports.showContextMenu = tsCoreUI.showContextMenu;+ exports.showDirectoryBrowserDialog = tsCoreUI.showDirectoryBrowserDialog;+ exports.createHTMLFile = tsCoreUI.createHTMLFile;+ exports.createMDFile = tsCoreUI.createMDFile;+ exports.createTXTFile = tsCoreUI.createTXTFile;+ exports.showSearchArea = tsCoreUI.showSearchArea;++ // Proxying functions from tsTagsUI+ exports.generateTagButtons = tsTagsUI.generateTagButtons;+ exports.generateTagStyle = tsTagsUI.generateTagStyle;+ exports.openTagMenu = tsTagsUI.openTagMenu;+ exports.showWaitingDialog = tsCoreUI.showWaitingDialog;+ exports.hideWaitingDialog = tsCoreUI.hideWaitingDialog;+ exports.showMoveCopyFilesDialog = tsCoreUI.showMoveCopyFilesDialog;+ exports.showAddTagsDialog = tsTagsUI.showAddTagsDialog;+ exports.showTagEditInTreeDialog = tsTagsUI.showTagEditInTreeDialog;+ exports.showDialogTagCreate = tsTagsUI.showDialogTagCreate;+ exports.showDialogEditTagGroup = tsTagsUI.showDialogEditTagGroup;+ exports.showDialogTagGroupCreate = tsTagsUI.showDialogTagGroupCreate;+ exports.calculatedTags = tsTagsUI.calculatedTags;+ exports.locationTags = tsTagsUI.locationTags;+ exports.generateTagGroups = tsTagsUI.generateTagGroups;++ // Proxying functions from directoriesUI+ exports.openLocation = tsDirectoriesUI.openLocation;+ exports.updateSubDirs = tsDirectoriesUI.updateSubDirs;+ exports.initLocations = tsDirectoriesUI.initLocations;+ exports.showCreateDirectoryDialog = tsDirectoriesUI.showCreateDirectoryDialog;+ exports.closeCurrentLocation = tsDirectoriesUI.closeCurrentLocation;+ exports.navigateToDirectory = tsDirectoriesUI.navigateToDirectory;++ // Public variables definition+ exports.currentPath = currentPath;+ exports.currentLocationObject = currentLocationObject;+ exports.currentPerspectiveID = currentPerspectiveID;+ exports.selectedFiles = selectedFiles;+ exports.fileList = fileList;+ exports.subDirsList = subDirsList;+ exports.selectedTag = selectedTag;+ exports.selectedTagData = selectedTagData;+ exports.startTime = startTime;+ exports.subfoldersDirBrowser = subfoldersDirBrowser;+ exports.directoryBrowser = directoryBrowser;+ exports.fileListFILEEXT = 0;+ exports.fileListTITLE = 1;+ exports.fileListTAGS = 2;+ exports.fileListFILESIZE = 3;+ exports.fileListFILELMDT = 4;+ exports.fileListFILEPATH = 5;+ exports.fileListFILENAME = 6;++});diff --git a/data/js/core.ui.js b/data/js/core.ui.jsindex 75e705e68..8193f318d 100644--- a/data/js/core.ui.js+++ b/data/js/core.ui.js@@ -1,924 +1,778 @@-/* 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, Handlebars, isNode, isFirefox */-define(function(require, exports, module) {-"use strict";-- console.log("Loading core.ui.js ...");-- var TSCORE = require("tscore");-- var fileContent;- var fileType;-- var showWaitingDialog = function(message, title) {- if (!title) { title = $.i18n.t("ns.dialogs:titleWaiting"); }- if (!message) { message = 'No Message to Display.'; }-- var waitingModal = $('#waitingDialog');- waitingModal.find('#waitingHeader').text(title);- waitingModal.find('#waitingMessage').text(message);-- waitingModal.modal({backdrop: 'static',show: true});- };-- var hideWaitingDialog = function(message, title) {- $('#waitingDialog').modal('hide');- };-- var showAlertDialog = function(message, title) {- if (!title) { title = $.i18n.t("ns.dialogs:titleAlert"); }- if (!message) { message = 'No Message to Display.'; }-- var alertModal = $('#alertDialog');- alertModal.find('h4').text(title);- alertModal.find('.modal-body').empty();- alertModal.find('.modal-body').text(message);- alertModal.find('#okButton')- .off('click')- .click(function() {- alertModal.modal('hide');- }- );-- // Focusing the ok button by default- alertModal.off('shown.bs.modal');- alertModal.on('shown.bs.modal', function () {- alertModal.find('#okButton').focus();- });-- alertModal.modal({backdrop: 'static',show: true});- };-- var showConfirmDialog = function(title, message, okCallback, cancelCallback, confirmShowNextTime) {- if (!title) { title = $.i18n.t("ns.dialogs:titleConfirm"); }- if (!message) { message = 'No Message to Display.'; }-- var confirmModal = $('#confirmDialog');-- if(confirmShowNextTime) {- confirmModal.find('#showThisDialogAgain').prop('checked', true);- } else {- confirmModal.find('#showThisDialogAgainContainer').hide();- }-- confirmModal.find('h4').text(title);- confirmModal.find('#dialogContent').text(message);- confirmModal.find('#confirmButton')- .off('click')- .click(function() {- okCallback(confirmModal.find('#showThisDialogAgain').prop('checked'));- confirmModal.modal('hide');- }- );-- // Focusing the confirm button by default- confirmModal.off('shown.bs.modal');- confirmModal.on('shown.bs.modal', function () {- confirmModal.find('#confirmButton').focus();- });-- confirmModal.find('#cancelButton')- .off('click')- .click(function() {- if(cancelCallback != undefined) {- cancelCallback();- }- confirmModal.modal('hide');- }- );-- confirmModal.modal({backdrop: 'static',show: true});- };--- var showFileCreateDialog = function() {- fileContent = TSCORE.Config.getNewTextFileContent(); // Default new file in text file- fileType = "txt";-- $('#newFileNameTags').select2('data', null);- $("#newFileNameTags").select2({- multiple: true,- tags: TSCORE.Config.getAllTags(),- tokenSeparators: [",", " "],- minimumInputLength: 2,- selectOnBlur: true- });-- $("#newFileName").val("");- $("#tagWithCurrentDate").prop('checked', false);-- $( '#txtFileTypeButton' ).button('toggle');-- $("#formFileCreate").validator();- $("#formFileCreate").submit(function (e) { e.preventDefault(); });- $('#formFileCreate').on('invalid.bs.validator', function() {- $( "#fileCreateConfirmButton").prop( "disabled", true );- });- $('#formFileCreate').on('valid.bs.validator', function() {- $( "#fileCreateConfirmButton").prop( "disabled", false );- });-- $('#dialogFileCreate').on('shown.bs.modal', function () {- $('#newFileName').select2().focus();- });-- $( '#dialogFileCreate' ).modal({backdrop: 'static',show: true});- };-- var showFileRenameDialog = function(filePath) {- $( "#renamedFileName" ).attr("filepath",filePath);- $( "#renamedFileName" ).val(TSCORE.TagUtils.extractFileName(filePath));-- $("#formFileRename").validator();- $("#formFileRename").submit(function (e) { e.preventDefault(); });- $('#formFileRename').on('invalid.bs.validator', function() {- $( "#renameFileButton").prop( "disabled", true );- });- $('#formFileRename').on('valid.bs.validator', function() {- $( "#renameFileButton").prop( "disabled", false );- });-- $('#dialogFileRename').on('shown.bs.modal', function () {- $('#renamedFileName').focus();- });-- $( '#dialogFileRename' ).modal({backdrop: 'static',show: true});- };-- var showFileDeleteDialog = function(filePath) {- console.log("Deleting file...");- TSCORE.showConfirmDialog(- $.i18n.t("ns.dialogs:fileDeleteTitleConfirm"),- $.i18n.t("ns.dialogs:fileDeleteContentConfirm", {filePath: filePath}),- function() {- TSCORE.IO.deleteElement(filePath);- }- );- };-- var showTagEditDialog = function() {- $( "#newTagName" ).val(TSCORE.selectedTag);-- $("#formEditTag").validator();- $("#formEditTag").submit(function (e) { e.preventDefault(); });- $('#formEditTag').on('invalid.bs.validator', function() {- $( "#editTagButton").prop( "disabled", true );- });- $('#formEditTag').on('valid.bs.validator', function() {- $( "#editTagButton").prop( "disabled", false );- });-- $('#dialogEditTag').on('shown.bs.modal', function () {- $('#newTagName').focus();- });-- $( '#dialogEditTag' ).modal({backdrop: 'static',show: true});- };-- var showDirectoryBrowserDialog = function(path) {- require([- "text!templates/DirectoryBrowserDialog.html",- "tsdirectorybrowser"- ], function(uiTPL, controller) {- TSCORE.directoryBrowser = controller;- if($("#directoryBrowserDialog").length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $('body').append(uiTemplate());- TSCORE.directoryBrowser.initUI();- }- $("#directoryBrowserDialog").i18n();- TSCORE.IO.listSubDirectories(path);- });- };-- var showOptionsDialog = function() {- require([- "text!templates/OptionsDialog.html",- "tsoptions"- ], function(uiTPL, controller) {- if($("#dialogOptions").length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $('body').append(uiTemplate());- controller.initUI();- }- $("#dialogOptions").i18n();- controller.reInitUI();- });- };-- var showWelcomeDialog = function() {- require([- "text!templates/WelcomeDialog.html"- ], function(uiTPL) {- if($("#dialogWelcome").length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $('body').append(uiTemplate());- $('#welcomeCarosel').carousel();- }- $("#dialogWelcome").i18n();- $("#dialogWelcome").modal({backdrop: 'static',show: true});- });- };-- var showMoveCopyFilesDialog = function() {- require([- "text!templates/MoveCopyFilesDialog.html"- ], function(uiTPL) {- if($("#dialogMoveCopyFiles").length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $('body').append(uiTemplate());-- $( "#moveFilesButton" ).click(function(e) {- e.preventDefault();- TSCORE.showWaitingDialog("Files are being renaming");- var newFilePath;- for (var i = 0; i < TSCORE.selectedFiles.length; i++) {- newFilePath = $("#moveCopyDirectoryPath").val()+TSCORE.dirSeparator+TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[i]);- TSCORE.IO.renameFile(TSCORE.selectedFiles[i],newFilePath);- }- });-- $( "#copyFilesButton" ).click(function(e) {- e.preventDefault();- TSCORE.showWaitingDialog("Files are being copied");- var newFilePath;- for (var i = 0; i < TSCORE.selectedFiles.length; i++) {- newFilePath = $("#moveCopyDirectoryPath").val()+TSCORE.dirSeparator+TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[i]);- TSCORE.IO.copyFile(TSCORE.selectedFiles[i],newFilePath);- }- });-- $( "#selectDirectoryMoveCopyDialog" ).click(function(e) {- e.preventDefault();- TSCORE.IO.selectDirectory();- });- }- $("#moveCopyDirectoryPath").val(TSCORE.currentPath);-- $("#moveCopyFileList").children().remove();-- for (var i = 0; i < TSCORE.selectedFiles.length; i++) {- $("#moveCopyFileList").append($("<p>", {- text: TSCORE.selectedFiles[i]- }));- }-- $("#dialogMoveCopyFiles").i18n();-- $("#dialogMoveCopyFiles").draggable({- handle: ".modal-header"- });-- $("#dialogMoveCopyFiles").modal({backdrop: 'static',show: true});--- console.log("Selected files: "+TSCORE.selectedFiles);- });- };-- var showAboutDialog = function() {- $("#dialogAboutTS").modal({backdrop: 'static',show: true});- };-- var initUI = function() {- $("#appVersion").text(TSCORE.Config.DefaultSettings["appVersion"]+"."+TSCORE.Config.DefaultSettings["appBuild"]);- $("#appVersion").attr("title","BuildID: "+TSCORE.Config.DefaultSettings["appVersion"]+"."+TSCORE.Config.DefaultSettings["appBuild"]+"."+TSCORE.Config.DefaultSettings["appBuildID"]);-- // prevent default behavior from changing page on dropped file- $(document).on("drop dragend dragenter dragleave dragover", function(event) { // dragstart drag- event.preventDefault();- });-- // Managing droping of files in the perspectives- if(isNode) {- $("#viewContainers").on("dragenter", function(event) {- event.preventDefault();- $("#viewContainers").attr("style","border:2px dashed #098ddf");- });-- $("#viewContainers").on("dragleave", function(event) {- event.preventDefault();- $("#viewContainers").attr("style","border:0px");- });-- $("#viewContainers").on("drop", function(event) {- //event.preventDefault();- if(event.originalEvent.dataTransfer !== undefined) {- var files = event.originalEvent.dataTransfer.files;- TSCORE.IO.focusWindow();- $("#viewContainers").attr("style","border:0px");- TSCORE.PerspectiveManager.clearSelectedFiles();-- var filePath;- if(files !== undefined && files.length > 0) {- for (var i = 0; i < files.length; i++) {- filePath = files[i].path;- if(filePath.length > 1) {- //console.log("Selecting files: "+JSON.stringify(files[i]));- TSCORE.selectedFiles.push(filePath);- //{"webkitRelativePath":"","path\":"/home/na/Desktop/Kola2","lastModifiedDate":"2014-07-11T16:40:52.000Z","name":"Kola2","type":"","size":4096}- }- }- }- if(TSCORE.selectedFiles.length > 0) {- showMoveCopyFilesDialog();- }- }- });- }-- platformTuning();-- var addFileInputName = undefined;- $("#addFileInput").on("change", function(selection) {- //console.log("Selected File: "+$("#addFileInput").val());- var file = selection.currentTarget.files[0];- //console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0]));- addFileInputName = decodeURIComponent(file.name);- var reader = new FileReader();- reader.onload = onFileReadComplete;- reader.readAsArrayBuffer(file);- });-- function onFileReadComplete(event) {- console.log("Content on file read complete: "+JSON.stringify(event));- TSCORE.IO.saveBinaryFile(TSCORE.currentPath+TSCORE.dirSeparator+addFileInputName, event.currentTarget.result);- addFileInputName = undefined;- }-- $( "#toggleLeftPanel" ).click(function() {- TSCORE.toggleLeftPanel();- });-- $( "#closeLeftPanel" ).click(function() {- TSCORE.toggleLeftPanel();- });-- $( "#txtFileTypeButton" ).click(function(e) {- // Fixes reloading of the application by click- e.preventDefault();-- fileContent = TSCORE.Config.getNewTextFileContent();- fileType = "txt";-- });-- $( "#htmlFileTypeButton" ).click(function(e) {- // Fixes reloading of the application by click- e.preventDefault();-- fileContent = TSCORE.Config.getNewHTMLFileContent();- fileType = "html";- });-- $( "#mdFileTypeButton" ).click(function(e) {- // Fixes reloading of the application by click- e.preventDefault();-- fileContent = TSCORE.Config.getNewMDFileContent();- fileType = "md";- });--- $( '#fileCreateConfirmButton' ).click(function() {- var fileTags = "";- var rawTags = $( "#newFileNameTags" ).val().split(",");-- rawTags.forEach(function (value, index) {- if(index == 0) {- fileTags = value;- } else {- fileTags = fileTags + TSCORE.Config.getTagDelimiter() + value;- }- });-- if($("#tagWithCurrentDate").prop("checked")) {- if(fileTags.length < 1) {- fileTags = TSCORE.TagUtils.formatDateTime4Tag(new Date());- } else {- fileTags = fileTags + TSCORE.Config.getTagDelimiter() + TSCORE.TagUtils.formatDateTime4Tag(new Date());- }- }-- if(fileTags.length > 0) {- fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer;- }-- var filePath = TSCORE.currentPath+TSCORE.dirSeparator+$( "#newFileName" ).val()+fileTags+"."+fileType;-- TSCORE.IO.saveTextFile(filePath,fileContent);-- });-- $( '#renameFileButton' ).click(function() {- var initialFilePath = $( "#renamedFileName" ).attr("filepath");- var containingDir = TSCORE.TagUtils.extractContainingDirectoryPath(initialFilePath);- TSCORE.IO.renameFile(- initialFilePath,- containingDir+TSCORE.dirSeparator+$( "#renamedFileName" ).val()- );- });-- // Edit Tag Dialog-- $( "#plainTagTypeButton" ).click(function(e) {- // Fixes reloading of the application by click- e.preventDefault();-- TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("");- });-- $( "#dateTagTypeButton" ).click(function(e) {- // Fixes reloading of the application by click- e.preventDefault();-- TSCORE.selectedTag, $( "#newTagName" ).datepicker({- showWeek: true,- firstDay: 1,- dateFormat: "yymmdd"- });- });-- $( "#currencyTagTypeButton" ).click(function(e) {- // Fixes reloading of the application by click- e.preventDefault();-- TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("XEUR");- });-- $( "#editTagButton" ).click(function() {- TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, $( "#newTagName" ).val());- });-- // End Edit Tag Dialog-- $( "#startNewInstanceBack" ).click(function() {- if(!isCordova) {- window.open(window.location.href,'_blank');- }- });-- $( "#aboutDialogBack" ).click(function() {- $("#aboutIframe").attr("src","about.html");- });-- // Open About Dialog- $( "#openAboutBox" ).click(function() {- $('#dialogAbout').modal({backdrop: 'static',show: true});- });-- // Open Options Dialog- $( "#openOptions" ).click(function() {- showOptionsDialog();- });-- // File Menu- $( "#fileMenuAddTag" ).click( function() {- TSCORE.showAddTagsDialog();- });-- $( "#fileMenuOpenFile" ).click( function() {- TSCORE.FileOpener.openFile(TSCORE.selectedFiles[0]);- });-- $( "#fileMenuOpenNatively" )- .click( function() {- TSCORE.IO.openFile(TSCORE.selectedFiles[0]);- });-- $( "#fileMenuSendTo" )- .click( function() {- TSCORE.IO.sendFile(TSCORE.selectedFiles[0]);- });-- $( "#fileMenuOpenDirectory" ).click( function() {- TSCORE.IO.openDirectory(TSCORE.currentPath);- });-- $( "#fileMenuRenameFile" ).click( function() {- TSCORE.showFileRenameDialog(TSCORE.selectedFiles[0]);- });-- $( "#fileMenuMoveCopyFile" ).click( function() {- TSCORE.showMoveCopyFilesDialog();- });-- $( "#fileMenuDeleteFile" ).click( function() {- TSCORE.showFileDeleteDialog(TSCORE.selectedFiles[0]);- });-- $( "#fileOpenProperties" ).click( function() {- //TSCORE.showFilePropertiesDialog(TSCORE.selectedFiles[0]);- });- // End File Menu-- $('#showLocations').click(function() {- showLocationsPanel();- console.log("Show Directories");- });-- $('#showTagGroups').click(function() {- showTagsPanel();- console.log("Show Tags");- });-- $('#contactUs').click(function () {- showContactUsPanel();- console.log("Show Contact Us");- });-- // Hide the tagGroupsContent or locationContent by default- $('#locationContent').hide(); // #tagGroupsContent- $('#contactUsContent').hide();-- // Search UI-- $("#searchToolbar").on("click","#closeSearchOptionButton",function() {- $("#searchBox").popover("hide");- });-- $("#searchToolbar").on("click","#includeSubfoldersOption",function() {- var searchQuery = $("#searchBox").val();- if(searchQuery.indexOf("?")===0) {- $("#includeSubfoldersOption i").removeClass("fa-toggle-on").addClass("fa-toggle-off");- $("#searchBox").val(searchQuery.substring(1,searchQuery.length));- } else {- $("#includeSubfoldersOption i").removeClass("fa-toggle-off").addClass("fa-toggle-on");- $("#searchBox").val("?"+searchQuery);- }- });-- $('#searchBox').on('show.bs.popover', function() {- var searchQuery = $("#searchBox").val();- if(searchQuery.indexOf("?")===0) {- $("#includeSubfoldersOption i").removeClass("fa-toggle-off").addClass("fa-toggle-on");- } else {- $("#includeSubfoldersOption i").removeClass("fa-toggle-on").addClass("fa-toggle-off");- }- });-- $('#searchBox').on('shown.bs.popover', function() {- $(".popover").i18n();- });-- $("#searchBox")- .prop('disabled', true)- /*.focus(function() {- $("#searchOptions").show();- })*/- .popover({- html: true,- placement: 'bottom',- trigger: 'focus',- content: $("#searchOptions").html()- })- .keyup(function(e) {- // On enter fire the search- if (e.keyCode === 13) {- $( "#clearFilterButton").addClass("filterOn");- TSCORE.PerspectiveManager.redrawCurrentPerspective();- $("#searchOptions").hide();- $("#searchButton").focus();- } else if (e.keyCode == 27) {- cancelSearch();- } else {- TSCORE.Search.nextQuery = this.value;- }- if (this.value.length === 0) {- TSCORE.Search.nextQuery = this.value;- $( "#clearFilterButton").removeClass("filterOn");- TSCORE.PerspectiveManager.redrawCurrentPerspective();- }- })- .blur(function() {- if (this.value.length === 0) {- $( "#clearFilterButton").removeClass("filterOn");- TSCORE.PerspectiveManager.redrawCurrentPerspective();- }- });-- $("#showSearchButton").on("click", function() {- TSCORE.showSearchArea();- $("#searchBox").focus();- });-- $("#searchButton")- .prop('disabled', true)- .click(function(evt) {- evt.preventDefault();- $( "#clearFilterButton").addClass("filterOn");- $("#searchOptions").hide();- TSCORE.PerspectiveManager.redrawCurrentPerspective();- $("#searchBox").popover("hide");- });-- $("#clearFilterButton")- .prop('disabled', true)- .click(function(e) {- e.preventDefault();- cancelSearch();- });-- // Search UI END-- $('#perspectiveSwitcherButton').prop('disabled', true);-- var $contactUsContent = $("#contactUsContent");-- $contactUsContent.on('click',"#openHints", function () {- showWelcomeDialog();- });-- $contactUsContent.on('click',"#openUservoice", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#openGooglePlay", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#openWhatsnew", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#openGitHubIssues", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#helpUsTranslate", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#openTwitter", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#openTwitter2", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#openGooglePlus", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#openFacebook", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $contactUsContent.on('click',"#openSupportUs", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- $("#newVersionMenu").on('click',".whatsNewLink", function (e) {- e.preventDefault();- openLinkExternally($(this).attr("href"));- });-- // Hide drop downs by click and drag- $(document).click(function () {- TSCORE.hideAllDropDownMenus();- });- };-- function cancelSearch() {- clearSearchFilter();- $("#searchBox").popover("hide");- $("#searchToolbar").hide();- $("#showSearchButton").show();- // Restoring initial dir listing without subdirectories- TSCORE.IO.listDirectory(TSCORE.currentPath);- }-- function showSearchArea() {- $("#searchToolbar").show(); //.addClass('animated bounceIn');- $("#showSearchButton").hide();- }-- // Handle external links- function openLinkExternally(url) {- if(isNode) {- gui.Shell.openExternal(url);- } else {- // _system is needed for cordova- window.open(url,"_system");- }- }-- function clearSearchFilter() {- $("#searchOptions").hide();- $("#searchBox").val("");- $("#clearFilterButton").removeClass("filterOn");- TSCORE.Search.nextQuery = "";- }-- function disableTopToolbar() {- $("#perspectiveSwitcherButton")- .prop('disabled', true);-- $("#searchBox")- .prop('disabled', true);-- $("#searchButton")- .prop('disabled', true);-- $("#clearFilterButton")- .prop('disabled', true);- }-- function enableTopToolbar() {- $("#perspectiveSwitcherButton")- .prop('disabled', false);-- $("#searchBox")- .prop('disabled', false);-- $("#searchButton")- .prop('disabled', false);-- $("#clearFilterButton")- .prop('disabled', false);- }-- function platformTuning() {- if(isCordova) {- $("#directoryMenuOpenDirectory").parent().hide();- $("#fileMenuOpenDirectory").parent().hide();- $("#fullscreenFile").parent().hide();- $("#openDirectory").parent().hide();- $("#downloadFile").parent().hide();- $("#openFileInNewWindow").hide();- $("#openGooglePlay").hide();- $(".cancelButton").hide();- } else if(isChrome) {- $("#directoryMenuOpenDirectory").parent().hide();- $("#fileMenuOpenDirectory").parent().hide();- $("#fileMenuOpenNatively").parent().hide();- $("#openDirectory").parent().hide();- $("#openNatively").hide();- } else if(isWeb) {- $("#directoryMenuOpenDirectory").parent().hide();- $("#fileMenuOpenDirectory").parent().hide();- $("#fileMenuOpenNatively").parent().hide();- $("#openDirectory").parent().hide();- $("#openNatively").hide();- } else if(isFirefox) {- $("#openNatively").hide();- $("#fileMenuOpenNatively").parent().hide();- } else if(isNode) {- $("#fullscreenFile").hide();- $("#openFileInNewWindow").hide();-- // handling window maximization- var nwwin = gui.Window.get();- nwwin.on('maximize', function() {- TSCORE.Config.setIsWindowMaximized(true);- TSCORE.Config.saveSettings();- });- nwwin.on('unmaximize', function() {- TSCORE.Config.setIsWindowMaximized(false);- TSCORE.Config.saveSettings();- });-- // Disabling automatic maximazation of the main window- //if(TSCORE.Config.getIsWindowMaximized()){- // nwwin.maximize();- //}- }-- // Disable send to feature on all platforms except android cordova- if(!isCordova) {- $("#sendFile").hide();- $("#fileMenuSendTo").hide();- }- if(isOSX) {- $("body").addClass("osx");- }- }-- var showContextMenu = function(menuId, sourceObject) {- var leftPos = sourceObject.offset().left;- var topPos = sourceObject.offset().top+sourceObject.height()+5;- if (sourceObject.offset().top+sourceObject.height()+$(menuId).height() > window.innerHeight) {- topPos = window.innerHeight-$(menuId).height();- leftPos = sourceObject.offset().left+15;- }-- if (sourceObject.offset().left+sourceObject.width()+$(menuId).width() > window.innerWidth) {- leftPos = window.innerWidth-$(menuId).width();- }-- $(menuId).css({- display: "block",- left: leftPos,- top: topPos- });- };-- var hideAllDropDownMenus = function() {- $('#tagGroupMenu').hide();- $('#tagTreeMenu').hide();- $('#directoryMenu').hide();- $('#tagMenu').hide();- $('#fileMenu').hide();- $(".dirAltNavMenu").hide();- };-- var showLocationsPanel = function() {- TSCORE.openLeftPanel();- $('#contactUsContent').hide();- $('#tagGroupsContent').hide();- $('#locationContent').show();- $('#showTagGroups').removeClass("active");- $('#contactUs').removeClass("active");- $('#showLocations').addClass("active");- };-- var showTagsPanel = function() {- TSCORE.openLeftPanel();- $('#contactUsContent').hide();- $('#locationContent').hide();- $('#tagGroupsContent').show();- $('#showLocations').removeClass("active");- $('#contactUs').removeClass("active");- $('#showTagGroups').addClass("active");- };-- var showContactUsPanel = function() {- TSCORE.openLeftPanel();- $('#locationContent').hide();- $('#tagGroupsContent').hide();- $('#contactUsContent').show();- $('#showLocations').removeClass("active");- $('#showTagGroups').removeClass("active");- $('#contactUs').addClass("active");- };-- var createHTMLFile = function() {- var filePath = TSCORE.currentPath+- TSCORE.dirSeparator+- TSCORE.TagUtils.beginTagContainer+- TSCORE.TagUtils.formatDateTime4Tag(new Date(), true)+- TSCORE.TagUtils.endTagContainer+".html";- TSCORE.IO.saveTextFile(filePath,TSCORE.Config.getNewHTMLFileContent());- };-- var createMDFile = function() {- var filePath = TSCORE.currentPath+- TSCORE.dirSeparator+- TSCORE.TagUtils.beginTagContainer+- TSCORE.TagUtils.formatDateTime4Tag(new Date(), true)+- TSCORE.TagUtils.endTagContainer+".md";- TSCORE.IO.saveTextFile(filePath,TSCORE.Config.getNewMDFileContent());- };-- var createTXTFile = function() {- var filePath = TSCORE.currentPath+- TSCORE.dirSeparator+- TSCORE.TagUtils.beginTagContainer+- TSCORE.TagUtils.formatDateTime4Tag(new Date(), true)+- TSCORE.TagUtils.endTagContainer+".txt";- TSCORE.IO.saveTextFile(filePath,TSCORE.Config.getNewTextFileContent());- };--- // Public API definition- exports.showContextMenu = showContextMenu;- exports.initUI = initUI;- exports.clearSearchFilter = clearSearchFilter;- exports.openLinkExternally = openLinkExternally;- exports.enableTopToolbar = enableTopToolbar;- exports.disableTopToolbar = disableTopToolbar;- exports.hideWaitingDialog = hideWaitingDialog;- exports.showWaitingDialog = showWaitingDialog;- exports.showAlertDialog = showAlertDialog;- exports.showConfirmDialog = showConfirmDialog;- exports.showFileRenameDialog = showFileRenameDialog;- exports.showFileCreateDialog = showFileCreateDialog;- exports.showFileDeleteDialog = showFileDeleteDialog;- exports.showWelcomeDialog = showWelcomeDialog;- exports.showTagEditDialog = showTagEditDialog;- exports.showOptionsDialog = showOptionsDialog;- exports.showAboutDialog = showAboutDialog;- exports.showLocationsPanel = showLocationsPanel;- exports.showTagsPanel = showTagsPanel;- exports.showDirectoryBrowserDialog = showDirectoryBrowserDialog;- exports.showMoveCopyFilesDialog = showMoveCopyFilesDialog;- exports.hideAllDropDownMenus = hideAllDropDownMenus;- exports.createHTMLFile = createHTMLFile;- exports.createMDFile = createMDFile;- exports.createTXTFile = createTXTFile;- exports.showSearchArea = showSearchArea;--});\ No newline at end of file+/* 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. */+/* global define, Handlebars, isNode, isFirefox */+define(function(require, exports, module) {+ 'use strict';+ console.log('Loading core.ui.js ...');+ var TSCORE = require('tscore');+ var fileContent;+ var fileType;+ var showWaitingDialog = function(message, title) {+ if (!title) {+ title = $.i18n.t('ns.dialogs:titleWaiting');+ }+ if (!message) {+ message = 'No Message to Display.';+ }+ var waitingModal = $('#waitingDialog');+ waitingModal.find('#waitingHeader').text(title);+ waitingModal.find('#waitingMessage').text(message);+ waitingModal.modal({+ backdrop: 'static',+ show: true+ });+ };+ var hideWaitingDialog = function(message, title) {+ $('#waitingDialog').modal('hide');+ };+ var showAlertDialog = function(message, title) {+ if (!title) {+ title = $.i18n.t('ns.dialogs:titleAlert');+ }+ if (!message) {+ message = 'No Message to Display.';+ }+ var alertModal = $('#alertDialog');+ alertModal.find('h4').text(title);+ alertModal.find('.modal-body').empty();+ alertModal.find('.modal-body').text(message);+ alertModal.find('#okButton').off('click').click(function() {+ alertModal.modal('hide');+ });+ // Focusing the ok button by default+ alertModal.off('shown.bs.modal');+ alertModal.on('shown.bs.modal', function() {+ alertModal.find('#okButton').focus();+ });+ alertModal.modal({+ backdrop: 'static',+ show: true+ });+ };+ var showConfirmDialog = function(title, message, okCallback, cancelCallback, confirmShowNextTime) {+ if (!title) {+ title = $.i18n.t('ns.dialogs:titleConfirm');+ }+ if (!message) {+ message = 'No Message to Display.';+ }+ var confirmModal = $('#confirmDialog');+ if (confirmShowNextTime) {+ confirmModal.find('#showThisDialogAgain').prop('checked', true);+ } else {+ confirmModal.find('#showThisDialogAgainContainer').hide();+ }+ confirmModal.find('h4').text(title);+ confirmModal.find('#dialogContent').text(message);+ confirmModal.find('#confirmButton').off('click').click(function() {+ okCallback(confirmModal.find('#showThisDialogAgain').prop('checked'));+ confirmModal.modal('hide');+ });+ // Focusing the confirm button by default+ confirmModal.off('shown.bs.modal');+ confirmModal.on('shown.bs.modal', function() {+ confirmModal.find('#confirmButton').focus();+ });+ confirmModal.find('#cancelButton').off('click').click(function() {+ if (cancelCallback !== undefined) {+ cancelCallback();+ }+ confirmModal.modal('hide');+ });+ confirmModal.modal({+ backdrop: 'static',+ show: true+ });+ };+ var showFileCreateDialog = function() {+ fileContent = TSCORE.Config.getNewTextFileContent();+ // Default new file in text file+ fileType = 'txt';+ $('#newFileNameTags').select2('data', null);+ $('#newFileNameTags').select2({+ multiple: true,+ tags: TSCORE.Config.getAllTags(),+ tokenSeparators: [+ ',',+ ' '+ ],+ minimumInputLength: 2,+ selectOnBlur: true+ });+ $('#newFileName').val('');+ $('#tagWithCurrentDate').prop('checked', false);+ $('#txtFileTypeButton').button('toggle');+ $('#formFileCreate').validator();+ $('#formFileCreate').submit(function(e) {+ e.preventDefault();+ });+ $('#formFileCreate').on('invalid.bs.validator', function() {+ $('#fileCreateConfirmButton').prop('disabled', true);+ });+ $('#formFileCreate').on('valid.bs.validator', function() {+ $('#fileCreateConfirmButton').prop('disabled', false);+ });+ $('#dialogFileCreate').on('shown.bs.modal', function() {+ $('#newFileName').select2().focus();+ });+ $('#dialogFileCreate').modal({+ backdrop: 'static',+ show: true+ });+ };+ var showFileRenameDialog = function(filePath) {+ $('#renamedFileName').attr('filepath', filePath);+ $('#renamedFileName').val(TSCORE.TagUtils.extractFileName(filePath));+ $('#formFileRename').validator();+ $('#formFileRename').submit(function(e) {+ e.preventDefault();+ });+ $('#formFileRename').on('invalid.bs.validator', function() {+ $('#renameFileButton').prop('disabled', true);+ });+ $('#formFileRename').on('valid.bs.validator', function() {+ $('#renameFileButton').prop('disabled', false);+ });+ $('#dialogFileRename').on('shown.bs.modal', function() {+ $('#renamedFileName').focus();+ });+ $('#dialogFileRename').modal({+ backdrop: 'static',+ show: true+ });+ };+ var showFileDeleteDialog = function(filePath) {+ console.log('Deleting file...');+ TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:fileDeleteTitleConfirm'), $.i18n.t('ns.dialogs:fileDeleteContentConfirm', {+ filePath: filePath+ }), function() {+ TSCORE.IO.deleteElement(filePath);+ });+ };+ var showTagEditDialog = function() {+ $('#newTagName').val(TSCORE.selectedTag);+ $('#formEditTag').validator();+ $('#formEditTag').submit(function(e) {+ e.preventDefault();+ });+ $('#formEditTag').on('invalid.bs.validator', function() {+ $('#editTagButton').prop('disabled', true);+ });+ $('#formEditTag').on('valid.bs.validator', function() {+ $('#editTagButton').prop('disabled', false);+ });+ $('#dialogEditTag').on('shown.bs.modal', function() {+ $('#newTagName').focus();+ });+ $('#dialogEditTag').modal({+ backdrop: 'static',+ show: true+ });+ };+ var showDirectoryBrowserDialog = function(path) {+ require([+ 'text!templates/DirectoryBrowserDialog.html',+ 'tsdirectorybrowser'+ ], function(uiTPL, controller) {+ TSCORE.directoryBrowser = controller;+ if ($('#directoryBrowserDialog').length < 1) {+ var uiTemplate = Handlebars.compile(uiTPL);+ $('body').append(uiTemplate());+ TSCORE.directoryBrowser.initUI();+ }+ $('#directoryBrowserDialog').i18n();+ TSCORE.IO.listSubDirectories(path);+ });+ };+ var showOptionsDialog = function() {+ require([+ 'text!templates/OptionsDialog.html',+ 'tsoptions'+ ], function(uiTPL, controller) {+ if ($('#dialogOptions').length < 1) {+ var uiTemplate = Handlebars.compile(uiTPL);+ $('body').append(uiTemplate());+ controller.initUI();+ }+ $('#dialogOptions').i18n();+ controller.reInitUI();+ });+ };+ var showWelcomeDialog = function() {+ require(['text!templates/WelcomeDialog.html'], function(uiTPL) {+ if ($('#dialogWelcome').length < 1) {+ var uiTemplate = Handlebars.compile(uiTPL);+ $('body').append(uiTemplate());+ $('#welcomeCarosel').carousel();+ }+ $('#dialogWelcome').i18n();+ $('#dialogWelcome').modal({+ backdrop: 'static',+ show: true+ });+ });+ };+ var showMoveCopyFilesDialog = function() {+ require(['text!templates/MoveCopyFilesDialog.html'], function(uiTPL) {+ if ($('#dialogMoveCopyFiles').length < 1) {+ var uiTemplate = Handlebars.compile(uiTPL);+ $('body').append(uiTemplate());+ $('#moveFilesButton').click(function(e) {+ e.preventDefault();+ TSCORE.showWaitingDialog('Files are being renaming');+ var newFilePath;+ for (var i = 0; i < TSCORE.selectedFiles.length; i++) {+ newFilePath = $('#moveCopyDirectoryPath').val() + TSCORE.dirSeparator + TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[i]);+ TSCORE.IO.renameFile(TSCORE.selectedFiles[i], newFilePath);+ }+ });+ $('#copyFilesButton').click(function(e) {+ e.preventDefault();+ TSCORE.showWaitingDialog('Files are being copied');+ var newFilePath;+ for (var i = 0; i < TSCORE.selectedFiles.length; i++) {+ newFilePath = $('#moveCopyDirectoryPath').val() + TSCORE.dirSeparator + TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[i]);+ TSCORE.IO.copyFile(TSCORE.selectedFiles[i], newFilePath);+ }+ });+ $('#selectDirectoryMoveCopyDialog').click(function(e) {+ e.preventDefault();+ TSCORE.IO.selectDirectory();+ });+ }+ $('#moveCopyDirectoryPath').val(TSCORE.currentPath);+ $('#moveCopyFileList').children().remove();+ for (var i = 0; i < TSCORE.selectedFiles.length; i++) {+ $('#moveCopyFileList').append($('<p>', {+ text: TSCORE.selectedFiles[i]+ }));+ }+ $('#dialogMoveCopyFiles').i18n();+ $('#dialogMoveCopyFiles').draggable({+ handle: '.modal-header'+ });+ $('#dialogMoveCopyFiles').modal({+ backdrop: 'static',+ show: true+ });+ console.log('Selected files: ' + TSCORE.selectedFiles);+ });+ };+ var showAboutDialog = function() {+ $('#dialogAboutTS').modal({+ backdrop: 'static',+ show: true+ });+ };+ var initUI = function() {+ $('#appVersion').text(TSCORE.Config.DefaultSettings.appVersion + '.' + TSCORE.Config.DefaultSettings.appBuild);+ $('#appVersion').attr('title', 'BuildID: ' + TSCORE.Config.DefaultSettings.appVersion + '.' + TSCORE.Config.DefaultSettings.appBuild + '.' + TSCORE.Config.DefaultSettings.appBuildID);+ // prevent default behavior from changing page on dropped file+ $(document).on('drop dragend dragenter dragleave dragover', function(event) {+ // dragstart drag+ event.preventDefault();+ });+ // Managing droping of files in the perspectives+ if (isNode) {+ $('#viewContainers').on('dragenter', function(event) {+ event.preventDefault();+ $('#viewContainers').attr('style', 'border:2px dashed #098ddf');+ });+ $('#viewContainers').on('dragleave', function(event) {+ event.preventDefault();+ $('#viewContainers').attr('style', 'border:0px');+ });+ $('#viewContainers').on('drop', function(event) {+ //event.preventDefault();+ if (event.originalEvent.dataTransfer !== undefined) {+ var files = event.originalEvent.dataTransfer.files;+ TSCORE.IO.focusWindow();+ $('#viewContainers').attr('style', 'border:0px');+ TSCORE.PerspectiveManager.clearSelectedFiles();+ var filePath;+ if (files !== undefined && files.length > 0) {+ for (var i = 0; i < files.length; i++) {+ filePath = files[i].path;+ if (filePath.length > 1) {+ //console.log("Selecting files: "+JSON.stringify(files[i]));+ TSCORE.selectedFiles.push(filePath); //{"webkitRelativePath":"","path\":"/home/na/Desktop/Kola2","lastModifiedDate":"2014-07-11T16:40:52.000Z","name":"Kola2","type":"","size":4096}+ }+ }+ }+ if (TSCORE.selectedFiles.length > 0) {+ showMoveCopyFilesDialog();+ }+ }+ });+ }+ platformTuning();+ var addFileInputName;+ $('#addFileInput').on('change', function(selection) {+ //console.log("Selected File: "+$("#addFileInput").val());+ var file = selection.currentTarget.files[0];+ //console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0]));+ addFileInputName = decodeURIComponent(file.name);+ var reader = new FileReader();+ reader.onload = onFileReadComplete;+ reader.readAsArrayBuffer(file);+ });++ function onFileReadComplete(event) {+ console.log('Content on file read complete: ' + JSON.stringify(event));+ TSCORE.IO.saveBinaryFile(TSCORE.currentPath + TSCORE.dirSeparator + addFileInputName, event.currentTarget.result);+ addFileInputName = undefined;+ }+ $('#toggleLeftPanel').click(function() {+ TSCORE.toggleLeftPanel();+ });+ $('#closeLeftPanel').click(function() {+ TSCORE.toggleLeftPanel();+ });+ $('#txtFileTypeButton').click(function(e) {+ // Fixes reloading of the application by click+ e.preventDefault();+ fileContent = TSCORE.Config.getNewTextFileContent();+ fileType = 'txt';+ });+ $('#htmlFileTypeButton').click(function(e) {+ // Fixes reloading of the application by click+ e.preventDefault();+ fileContent = TSCORE.Config.getNewHTMLFileContent();+ fileType = 'html';+ });+ $('#mdFileTypeButton').click(function(e) {+ // Fixes reloading of the application by click+ e.preventDefault();+ fileContent = TSCORE.Config.getNewMDFileContent();+ fileType = 'md';+ });+ $('#fileCreateConfirmButton').click(function() {+ var fileTags = '';+ var rawTags = $('#newFileNameTags').val().split(',');+ rawTags.forEach(function(value, index) {+ if (index === 0) {+ fileTags = value;+ } else {+ fileTags = fileTags + TSCORE.Config.getTagDelimiter() + value;+ }+ });+ if ($('#tagWithCurrentDate').prop('checked')) {+ if (fileTags.length < 1) {+ fileTags = TSCORE.TagUtils.formatDateTime4Tag(new Date());+ } else {+ fileTags = fileTags + TSCORE.Config.getTagDelimiter() + TSCORE.TagUtils.formatDateTime4Tag(new Date());+ }+ }+ if (fileTags.length > 0) {+ fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer;+ }+ var filePath = TSCORE.currentPath + TSCORE.dirSeparator + $('#newFileName').val() + fileTags + '.' + fileType;+ TSCORE.IO.saveTextFile(filePath, fileContent);+ });+ $('#renameFileButton').click(function() {+ var initialFilePath = $('#renamedFileName').attr('filepath');+ var containingDir = TSCORE.TagUtils.extractContainingDirectoryPath(initialFilePath);+ TSCORE.IO.renameFile(initialFilePath, containingDir + TSCORE.dirSeparator + $('#renamedFileName').val());+ });+ // Edit Tag Dialog+ $('#plainTagTypeButton').click(function(e) {+ // Fixes reloading of the application by click+ e.preventDefault();+ TSCORE.selectedTag, $('#newTagName').datepicker('destroy').val('');+ });+ $('#dateTagTypeButton').click(function(e) {+ // Fixes reloading of the application by click+ e.preventDefault();+ TSCORE.selectedTag, $('#newTagName').datepicker({+ showWeek: true,+ firstDay: 1,+ dateFormat: 'yymmdd'+ });+ });+ $('#currencyTagTypeButton').click(function(e) {+ // Fixes reloading of the application by click+ e.preventDefault();+ TSCORE.selectedTag, $('#newTagName').datepicker('destroy').val('XEUR');+ });+ $('#editTagButton').click(function() {+ TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, $('#newTagName').val());+ });+ // End Edit Tag Dialog+ $('#startNewInstanceBack').click(function() {+ if (!isCordova) {+ window.open(window.location.href, '_blank');+ }+ });+ $('#aboutDialogBack').click(function() {+ $('#aboutIframe').attr('src', 'about.html');+ });+ // Open About Dialog+ $('#openAboutBox').click(function() {+ $('#dialogAbout').modal({+ backdrop: 'static',+ show: true+ });+ });+ // Open Options Dialog+ $('#openOptions').click(function() {+ showOptionsDialog();+ });+ // File Menu+ $('#fileMenuAddTag').click(function() {+ TSCORE.showAddTagsDialog();+ });+ $('#fileMenuOpenFile').click(function() {+ TSCORE.FileOpener.openFile(TSCORE.selectedFiles[0]);+ });+ $('#fileMenuOpenNatively').click(function() {+ TSCORE.IO.openFile(TSCORE.selectedFiles[0]);+ });+ $('#fileMenuSendTo').click(function() {+ TSCORE.IO.sendFile(TSCORE.selectedFiles[0]);+ });+ $('#fileMenuOpenDirectory').click(function() {+ TSCORE.IO.openDirectory(TSCORE.currentPath);+ });+ $('#fileMenuRenameFile').click(function() {+ TSCORE.showFileRenameDialog(TSCORE.selectedFiles[0]);+ });+ $('#fileMenuMoveCopyFile').click(function() {+ TSCORE.showMoveCopyFilesDialog();+ });+ $('#fileMenuDeleteFile').click(function() {+ TSCORE.showFileDeleteDialog(TSCORE.selectedFiles[0]);+ });+ $('#fileOpenProperties').click(function() {});+ // End File Menu+ $('#showLocations').click(function() {+ showLocationsPanel();+ console.log('Show Directories');+ });+ $('#showTagGroups').click(function() {+ showTagsPanel();+ console.log('Show Tags');+ });+ $('#contactUs').click(function() {+ showContactUsPanel();+ console.log('Show Contact Us');+ });+ // Hide the tagGroupsContent or locationContent by default+ $('#locationContent').hide();+ // #tagGroupsContent+ $('#contactUsContent').hide();+ // Search UI+ $('#searchToolbar').on('click', '#closeSearchOptionButton', function() {+ $('#searchBox').popover('hide');+ });+ $('#searchToolbar').on('click', '#includeSubfoldersOption', function() {+ var searchQuery = $('#searchBox').val();+ if (searchQuery.indexOf('?') === 0) {+ $('#includeSubfoldersOption i').removeClass('fa-toggle-on').addClass('fa-toggle-off');+ $('#searchBox').val(searchQuery.substring(1, searchQuery.length));+ } else {+ $('#includeSubfoldersOption i').removeClass('fa-toggle-off').addClass('fa-toggle-on');+ $('#searchBox').val('?' + searchQuery);+ }+ });+ $('#searchBox').on('show.bs.popover', function() {+ var searchQuery = $('#searchBox').val();+ if (searchQuery.indexOf('?') === 0) {+ $('#includeSubfoldersOption i').removeClass('fa-toggle-off').addClass('fa-toggle-on');+ } else {+ $('#includeSubfoldersOption i').removeClass('fa-toggle-on').addClass('fa-toggle-off');+ }+ });+ $('#searchBox').on('shown.bs.popover', function() {+ $('.popover').i18n();+ });+ $('#searchBox').prop('disabled', true)+ /*.focus(function() {+ $("#searchOptions").show();+ })*/+ .popover({+ html: true,+ placement: 'bottom',+ trigger: 'focus',+ content: $('#searchOptions').html()+ }).keyup(function(e) {+ // On enter fire the search+ if (e.keyCode === 13) {+ $('#clearFilterButton').addClass('filterOn');+ TSCORE.PerspectiveManager.redrawCurrentPerspective();+ $('#searchOptions').hide();+ $('#searchButton').focus();+ } else if (e.keyCode == 27) {+ cancelSearch();+ } else {+ TSCORE.Search.nextQuery = this.value;+ }+ if (this.value.length === 0) {+ TSCORE.Search.nextQuery = this.value;+ $('#clearFilterButton').removeClass('filterOn');+ TSCORE.PerspectiveManager.redrawCurrentPerspective();+ }+ }).blur(function() {+ if (this.value.length === 0) {+ $('#clearFilterButton').removeClass('filterOn');+ TSCORE.PerspectiveManager.redrawCurrentPerspective();+ }+ });+ $('#showSearchButton').on('click', function() {+ TSCORE.showSearchArea();+ $('#searchBox').focus();+ });+ $('#searchButton').prop('disabled', true).click(function(evt) {+ evt.preventDefault();+ $('#clearFilterButton').addClass('filterOn');+ $('#searchOptions').hide();+ TSCORE.PerspectiveManager.redrawCurrentPerspective();+ $('#searchBox').popover('hide');+ });+ $('#clearFilterButton').prop('disabled', true).click(function(e) {+ e.preventDefault();+ cancelSearch();+ });+ // Search UI END+ $('#perspectiveSwitcherButton').prop('disabled', true);+ var $contactUsContent = $('#contactUsContent');+ $contactUsContent.on('click', '#openHints', function() {+ showWelcomeDialog();+ });+ $contactUsContent.on('click', '#openUservoice', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#openGooglePlay', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#openWhatsnew', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#openGitHubIssues', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#helpUsTranslate', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#openTwitter', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#openTwitter2', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#openGooglePlus', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#openFacebook', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $contactUsContent.on('click', '#openSupportUs', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ $('#newVersionMenu').on('click', '.whatsNewLink', function(e) {+ e.preventDefault();+ openLinkExternally($(this).attr('href'));+ });+ // Hide drop downs by click and drag+ $(document).click(function() {+ TSCORE.hideAllDropDownMenus();+ });+ };++ function cancelSearch() {+ clearSearchFilter();+ $('#searchBox').popover('hide');+ $('#searchToolbar').hide();+ $('#showSearchButton').show();+ // Restoring initial dir listing without subdirectories+ TSCORE.IO.listDirectory(TSCORE.currentPath);+ }++ function showSearchArea() {+ $('#searchToolbar').show();+ //.addClass('animated bounceIn');+ $('#showSearchButton').hide();+ }+ // Handle external links+ function openLinkExternally(url) {+ if (isNode) {+ gui.Shell.openExternal(url);+ } else {+ // _system is needed for cordova+ window.open(url, '_system');+ }+ }++ function clearSearchFilter() {+ $('#searchOptions').hide();+ $('#searchBox').val('');+ $('#clearFilterButton').removeClass('filterOn');+ TSCORE.Search.nextQuery = '';+ }++ function disableTopToolbar() {+ $('#perspectiveSwitcherButton').prop('disabled', true);+ $('#searchBox').prop('disabled', true);+ $('#searchButton').prop('disabled', true);+ $('#clearFilterButton').prop('disabled', true);+ }++ function enableTopToolbar() {+ $('#perspectiveSwitcherButton').prop('disabled', false);+ $('#searchBox').prop('disabled', false);+ $('#searchButton').prop('disabled', false);+ $('#clearFilterButton').prop('disabled', false);+ }++ function platformTuning() {+ if (isCordova) {+ $('#directoryMenuOpenDirectory').parent().hide();+ $('#fileMenuOpenDirectory').parent().hide();+ $('#fullscreenFile').parent().hide();+ $('#openDirectory').parent().hide();+ $('#downloadFile').parent().hide();+ $('#openFileInNewWindow').hide();+ $('#openGooglePlay').hide();+ $('.cancelButton').hide();+ } else if (isChrome) {+ $('#directoryMenuOpenDirectory').parent().hide();+ $('#fileMenuOpenDirectory').parent().hide();+ $('#fileMenuOpenNatively').parent().hide();+ $('#openDirectory').parent().hide();+ $('#openNatively').hide();+ } else if (isWeb) {+ $('#directoryMenuOpenDirectory').parent().hide();+ $('#fileMenuOpenDirectory').parent().hide();+ $('#fileMenuOpenNatively').parent().hide();+ $('#openDirectory').parent().hide();+ $('#openNatively').hide();+ } else if (isFirefox) {+ $('#openNatively').hide();+ $('#fileMenuOpenNatively').parent().hide();+ } else if (isNode) {+ $('#fullscreenFile').hide();+ $('#openFileInNewWindow').hide();+ // handling window maximization+ var nwwin = gui.Window.get();+ nwwin.on('maximize', function() {+ TSCORE.Config.setIsWindowMaximized(true);+ TSCORE.Config.saveSettings();+ });+ nwwin.on('unmaximize', function() {+ TSCORE.Config.setIsWindowMaximized(false);+ TSCORE.Config.saveSettings();+ }); // Disabling automatic maximazation of the main window+ //if(TSCORE.Config.getIsWindowMaximized()){+ // nwwin.maximize();+ //}+ }+ // Disable send to feature on all platforms except android cordova+ if (!isCordova) {+ $('#sendFile').hide();+ $('#fileMenuSendTo').hide();+ }+ if (isOSX) {+ $('body').addClass('osx');+ }+ }+ var showContextMenu = function(menuId, sourceObject) {+ var leftPos = sourceObject.offset().left;+ var topPos = sourceObject.offset().top + sourceObject.height() + 5;+ if (sourceObject.offset().top + sourceObject.height() + $(menuId).height() > window.innerHeight) {+ topPos = window.innerHeight - $(menuId).height();+ leftPos = sourceObject.offset().left + 15;+ }+ if (sourceObject.offset().left + sourceObject.width() + $(menuId).width() > window.innerWidth) {+ leftPos = window.innerWidth - $(menuId).width();+ }+ $(menuId).css({+ display: 'block',+ left: leftPos,+ top: topPos+ });+ };+ var hideAllDropDownMenus = function() {+ $('#tagGroupMenu').hide();+ $('#tagTreeMenu').hide();+ $('#directoryMenu').hide();+ $('#tagMenu').hide();+ $('#fileMenu').hide();+ $('.dirAltNavMenu').hide();+ };+ var showLocationsPanel = function() {+ TSCORE.openLeftPanel();+ $('#contactUsContent').hide();+ $('#tagGroupsContent').hide();+ $('#locationContent').show();+ $('#showTagGroups').removeClass('active');+ $('#contactUs').removeClass('active');+ $('#showLocations').addClass('active');+ };+ var showTagsPanel = function() {+ TSCORE.openLeftPanel();+ $('#contactUsContent').hide();+ $('#locationContent').hide();+ $('#tagGroupsContent').show();+ $('#showLocations').removeClass('active');+ $('#contactUs').removeClass('active');+ $('#showTagGroups').addClass('active');+ };+ var showContactUsPanel = function() {+ TSCORE.openLeftPanel();+ $('#locationContent').hide();+ $('#tagGroupsContent').hide();+ $('#contactUsContent').show();+ $('#showLocations').removeClass('active');+ $('#showTagGroups').removeClass('active');+ $('#contactUs').addClass('active');+ };+ var createHTMLFile = function() {+ var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.html';+ TSCORE.IO.saveTextFile(filePath, TSCORE.Config.getNewHTMLFileContent());+ };+ var createMDFile = function() {+ var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.md';+ TSCORE.IO.saveTextFile(filePath, TSCORE.Config.getNewMDFileContent());+ };+ var createTXTFile = function() {+ var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.txt';+ TSCORE.IO.saveTextFile(filePath, TSCORE.Config.getNewTextFileContent());+ };+ // Public API definition+ exports.showContextMenu = showContextMenu;+ exports.initUI = initUI;+ exports.clearSearchFilter = clearSearchFilter;+ exports.openLinkExternally = openLinkExternally;+ exports.enableTopToolbar = enableTopToolbar;+ exports.disableTopToolbar = disableTopToolbar;+ exports.hideWaitingDialog = hideWaitingDialog;+ exports.showWaitingDialog = showWaitingDialog;+ exports.showAlertDialog = showAlertDialog;+ exports.showConfirmDialog = showConfirmDialog;+ exports.showFileRenameDialog = showFileRenameDialog;+ exports.showFileCreateDialog = showFileCreateDialog;+ exports.showFileDeleteDialog = showFileDeleteDialog;+ exports.showWelcomeDialog = showWelcomeDialog;+ exports.showTagEditDialog = showTagEditDialog;+ exports.showOptionsDialog = showOptionsDialog;+ exports.showAboutDialog = showAboutDialog;+ exports.showLocationsPanel = showLocationsPanel;+ exports.showTagsPanel = showTagsPanel;+ exports.showDirectoryBrowserDialog = showDirectoryBrowserDialog;+ exports.showMoveCopyFilesDialog = showMoveCopyFilesDialog;+ exports.hideAllDropDownMenus = hideAllDropDownMenus;+ exports.createHTMLFile = createHTMLFile;+ exports.createMDFile = createMDFile;+ exports.createTXTFile = createTXTFile;+ exports.showSearchArea = showSearchArea;+});diff --git a/data/js/directories.ui.js b/data/js/directories.ui.jsindex e201308bb..84d5fbd96 100644--- a/data/js/directories.ui.js+++ b/data/js/directories.ui.js@@ -1,745 +1,651 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that+/* 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. *//* global define, Handlebars, isCordova */-define(function(require, exports, module) {-"use strict";-- console.log("Loading directories.ui.js ...");-- var TSCORE = require("tscore");-- var directoryHistory = [];-- var dir4ContextMenu = null;-- var tsMetadataFolder = ".ts";- var tsMetadataFile = "tsm.json";-- var alternativeDirectoryNavigatorTmpl = Handlebars.compile(-// '<i class="fa fa-home"></i> ' +- '{{#each dirHistory}}'+- '<div class="btn-group dropup">'+- '<button class="btn btn-link dropdown-toggle" data-menu="{{@index}}">'+- '{{name}} <i class="fa fa-caret-right"></i> ' +- '</button>'+- '<div class="dropdown clearfix dirAltNavMenu" id="dirMenu{{@index}}">'+- '<ul style="overflow-y: auto; max-height: 430px; width: 250px; padding: 5px; display: block;" role="menu" class="dropdown-menu">'+- '<li class="dropdown-header"><button type="button" class="close">×</button>{{../actionsForDirectory}} "{{name}}"</li>'+- '<li><a class="btn btn-link pull-left reloadCurrentDirectory" data-path="{{path}}"><i class="fa fa-refresh fa-fw"></i> {{../reloadCurrentDirectory}}</a></li>'+- '<li class="notreadonly"><a class="btn btn-link pull-left createSubdirectory" data-path="{{path}}"><i class="fa fa-folder-o fa-fw"></i> {{../createSubdirectory}}</a></li>'+- '<li class="notreadonly"><a class="btn btn-link pull-left renameDirectory" data-path="{{path}}"><i class="fa fa-paragraph fa-fw"></i> {{../renameDirectory}}</a></li>'+- '<li class="divider" style="width: 100%"></li>'+- '<li class="dropdown-header">{{../subfodersOfDirectory}} "{{name}}"</li>'+- '{{#if children}}'+- '{{#each children}}'+- '<button class="btn dirButton" data-path="{{path}}" title="{{path}}" style="margin: 1px;">'+- '<i class="fa fa-folder-o"></i> {{name}}</button>'+- '{{/each}}'+- '{{else}}'+- '<div>{{../../noSubfoldersFound}}</div>'+- '{{/if}}'+- '</ul>'+- '</div>'+- '</div>'+- '{{/each}}'- );-- var mainDirectoryNavigatorTmpl = Handlebars.compile(- '<div>{{#each dirHistory}}'+- '<div class="accordion-group disableTextSelection" style="width: 99%; border: 0px #aaa solid;">'+- '<div class="accordion-heading btn-group" key="{{path}}" style="width:100%; margin: 0; ">'+- '<button class="btn btn-link btn-lg directoryIcon" data-toggle="collapse" data-target="#dirButtons{{@index}}" key="{{path}}" title="{{../toggleDirectory}}">'+- '<i class="fa fa-folder fa-fw"></i>'+- '</button>'+- '<button class="btn btn-link directoryTitle ui-droppable" key="{{path}}" title="{{path}}">{{name}}</button>'+- '<button class="btn btn-link btn-lg directoryActions" key="{{path}}" title="{{../directoryOperations}}">'+- '<b class="fa fa-ellipsis-v"></b>'+- '</button>'+- '</div>'+- '<div class="accordion-body collapse in" id="dirButtons{{@index}}">'+- '<div class="accordion-inner" id="dirButtonsContent{{@index}}" style="padding: 4px;">'+- '{{#if children}}'+- '<div>{{#each children}}'+- '<button class="btn btn-sm dirButton ui-droppable" key="{{path}}" title="{{path}}" style="margin: 1px;">'+- '<i class="fa fa-folder-o"></i> {{name}}</button>'+- '{{/each}}</div>'+- '{{else}}'+- '<div>{{../../noSubfoldersFound}}</div>'+- '{{/if}}'+- '</div>'+- '</div>'+- '</div>'+- '{{/each}}</div>'- );-- var locationChooserTmpl = Handlebars.compile(- '<li class="dropdown-header" data-i18n="ns.common:yourLocations">{{yourLocations}} '+- '<button type="button" class="close">×</button>'+- '</li>'+- '<li class="divider" ></li>'+- '{{#each locations}}'+- '<li style="line-height: 45px">'+- '<button title="{{path}}" path="{{path}}" name="{{name}}" style="width: 180px; text-align: left; border: 0;" class="btn btn-default">'+- '<i class="fa fa-bookmark"></i> {{name}}' +- '</button>'+- '<button type="button" data-i18n="[title]ns.common:editLocation" title="{{editLocationTitle}}" location="{{name}}" path="{{path}}" class="btn btn-link pull-right" style="margin-right: 5px; margin-top: 5px">'+- '<i class="fa fa-pencil fa-lg"></i>'+- '</button>'+- '</li>'+- '{{/each}}'- );-- function openLocation(path) {- console.log("Opening location in : "+path);-- if(TSCORE.Config.getLoadLocationMeta()) {- loadFolderMetaData(path);- }-- TSCORE.currentLocationObject = TSCORE.Config.getLocation(path);- if(TSCORE.currentLocationObject != undefined) {- document.title = TSCORE.currentLocationObject.name + " | " + TSCORE.Config.DefaultSettings.appName;-- $( "#locationName" ).text(TSCORE.currentLocationObject.name).attr("title",path);-- // Handle open default perspective for a location- var defaultPerspective = TSCORE.currentLocationObject.perspective;- TSCORE.PerspectiveManager.changePerspective(defaultPerspective);-- // Saving the last opened location path in the settings- TSCORE.Config.setLastOpenedLocation(path);- TSCORE.Config.saveSettings();- }-- // Clear search query- TSCORE.clearSearchFilter();-- // Clears the directory history- directoryHistory = [];- navigateToDirectory(path);-- TSCORE.showLocationsPanel();+ 'use strict';+ console.log('Loading directories.ui.js ...');+ var TSCORE = require('tscore');+ var directoryHistory = [];+ var dir4ContextMenu = null;+ var tsMetadataFolder = '.ts';+ var tsMetadataFile = 'tsm.json';+ var alternativeDirectoryNavigatorTmpl = Handlebars.compile(+ '{{#each dirHistory}}' ++ '<div class="btn-group dropup">' ++ '<button class="btn btn-link dropdown-toggle" data-menu="{{@index}}">' ++ '{{name}} <i class="fa fa-caret-right"></i> ' ++ '</button>' ++ '<div class="dropdown clearfix dirAltNavMenu" id="dirMenu{{@index}}">' ++ '<ul style="overflow-y: auto; max-height: 430px; width: 250px; padding: 5px; display: block;" role="menu" class="dropdown-menu">' ++ '<li class="dropdown-header"><button type="button" class="close">×</button>{{../actionsForDirectory}} "{{name}}"</li>' ++ '<li><a class="btn btn-link pull-left reloadCurrentDirectory" data-path="{{path}}"><i class="fa fa-refresh fa-fw"></i> {{../reloadCurrentDirectory}}</a></li>' ++ '<li class="notreadonly"><a class="btn btn-link pull-left createSubdirectory" data-path="{{path}}"><i class="fa fa-folder-o fa-fw"></i> {{../createSubdirectory}}</a></li>' ++ '<li class="notreadonly"><a class="btn btn-link pull-left renameDirectory" data-path="{{path}}"><i class="fa fa-paragraph fa-fw"></i> {{../renameDirectory}}</a></li>' ++ '<li class="divider" style="width: 100%"></li>' ++ '<li class="dropdown-header">{{../subfodersOfDirectory}} "{{name}}"</li>' ++ '{{#if children}}' ++ '{{#each children}}' ++ '<button class="btn dirButton" data-path="{{path}}" title="{{path}}" style="margin: 1px;">' ++ '<i class="fa fa-folder-o"></i> {{name}}</button>' ++ '{{/each}}' ++ '{{else}}' ++ '<div>{{../../noSubfoldersFound}}</div>' ++ '{{/if}}' ++ '</ul>' ++ '</div>' ++ '</div>' ++ '{{/each}}'+ );+ var mainDirectoryNavigatorTmpl = Handlebars.compile(+ '<div>{{#each dirHistory}}' ++ '<div class="accordion-group disableTextSelection" style="width: 99%; border: 0px #aaa solid;">' ++ '<div class="accordion-heading btn-group" key="{{path}}" style="width:100%; margin: 0; ">' ++ '<button class="btn btn-link btn-lg directoryIcon" data-toggle="collapse" data-target="#dirButtons{{@index}}" key="{{path}}" title="{{../toggleDirectory}}">' ++ '<i class="fa fa-folder fa-fw"></i>' ++ '</button>' ++ '<button class="btn btn-link directoryTitle ui-droppable" key="{{path}}" title="{{path}}">{{name}}</button>' ++ '<button class="btn btn-link btn-lg directoryActions" key="{{path}}" title="{{../directoryOperations}}">' ++ '<b class="fa fa-ellipsis-v"></b>' ++ '</button>' ++ '</div>' ++ '<div class="accordion-body collapse in" id="dirButtons{{@index}}">' ++ '<div class="accordion-inner" id="dirButtonsContent{{@index}}" style="padding: 4px;">' ++ '{{#if children}}' ++ '<div>{{#each children}}' ++ '<button class="btn btn-sm dirButton ui-droppable" key="{{path}}" title="{{path}}" style="margin: 1px;">' ++ '<i class="fa fa-folder-o"></i> {{name}}</button>' ++ '{{/each}}</div>' ++ '{{else}}' ++ '<div>{{../../noSubfoldersFound}}</div>' ++ '{{/if}}' ++ '</div>' ++ '</div>' ++ '</div>' ++ '{{/each}}</div>'+ );+ var locationChooserTmpl = Handlebars.compile(+ '<li class="dropdown-header" data-i18n="ns.common:yourLocations">{{yourLocations}} ' ++ '<button type="button" class="close">×</button>' ++ '</li>' ++ '<li class="divider" ></li>' ++ '{{#each locations}}' ++ '<li style="line-height: 45px">' ++ '<button title="{{path}}" path="{{path}}" name="{{name}}" style="width: 180px; text-align: left; border: 0;" class="btn btn-default">' ++ '<i class="fa fa-bookmark"></i> {{name}}' ++ '</button>' ++ '<button type="button" data-i18n="[title]ns.common:editLocation" title="{{editLocationTitle}}" location="{{name}}" path="{{path}}" class="btn btn-link pull-right" style="margin-right: 5px; margin-top: 5px">' ++ '<i class="fa fa-pencil fa-lg"></i>' ++ '</button>' ++ '</li>' ++ '{{/each}}'+ );++ function openLocation(path) {+ console.log('Opening location in : ' + path);+ if (TSCORE.Config.getLoadLocationMeta()) {+ loadFolderMetaData(path);}-- function loadFolderMetaData(path) {- var metadataPath;- if(isWeb) {- metadataPath = path+TSCORE.dirSeparator+tsMetadataFolder+TSCORE.dirSeparator+tsMetadataFile;- } else {- metadataPath = "file://"+path+TSCORE.dirSeparator+tsMetadataFolder+TSCORE.dirSeparator+tsMetadataFile;+ TSCORE.currentLocationObject = TSCORE.Config.getLocation(path);+ if (TSCORE.currentLocationObject !== undefined) {+ document.title = TSCORE.currentLocationObject.name + ' | ' + TSCORE.Config.DefaultSettings.appName;+ $('#locationName').text(TSCORE.currentLocationObject.name).attr('title', path);+ // Handle open default perspective for a location+ var defaultPerspective = TSCORE.currentLocationObject.perspective;+ TSCORE.PerspectiveManager.changePerspective(defaultPerspective);+ // Saving the last opened location path in the settings+ TSCORE.Config.setLastOpenedLocation(path);+ TSCORE.Config.saveSettings();+ }+ // Clear search query+ TSCORE.clearSearchFilter();+ // Clears the directory history+ directoryHistory = [];+ navigateToDirectory(path);+ TSCORE.showLocationsPanel();+ }++ function loadFolderMetaData(path) {+ var metadataPath;+ if (isWeb) {+ metadataPath = path + TSCORE.dirSeparator + tsMetadataFolder + TSCORE.dirSeparator + tsMetadataFile;+ } else {+ metadataPath = 'file://' + path + TSCORE.dirSeparator + tsMetadataFolder + TSCORE.dirSeparator + tsMetadataFile;+ }+ $.get(metadataPath, function(data) {+ if (data.length > 1) {+ var metadata = JSON.parse(data);+ console.log('Location Metadata: ' + JSON.stringify(metadata));+ if (metadata.tagGroups.length > 0) {+ TSCORE.locationTags = metadata.tagGroups;+ TSCORE.generateTagGroups();+ }}-- $.get( metadataPath, function( data ) {- if (data.length > 1) {- var metadata = JSON.parse(data);- console.log("Location Metadata: " + JSON.stringify(metadata));- if (metadata.tagGroups.length > 0) {- TSCORE.locationTags = metadata.tagGroups;- TSCORE.generateTagGroups();- }- }- });+ });}-// Updates the directory subtree- function updateSubDirs(dirList) {- //console.log("Updating subdirs(TSCORE)..."+JSON.stringify(dirList));-- var hasSubFolders = false;-- for(var i=0; i < directoryHistory.length; i++) {- if(directoryHistory[i].path === TSCORE.currentPath) {- directoryHistory[i].children = [];- for(var j=0; j < dirList.length; j++) {- if(!dirList[j].isFile) {- if (TSCORE.Config.getShowUnixHiddenEntries() || (!TSCORE.Config.getShowUnixHiddenEntries() && (dirList[j].name.indexOf(".") !== 0))) {- directoryHistory[i].children.push(dirList[j]);- hasSubFolders = true;- }- }- }- // Sort the dirList alphabetically- directoryHistory[i].children.sort(function(a,b) { return a.name.localeCompare(b.name); });+ function updateSubDirs(dirList) {+ //console.log("Updating subdirs(TSCORE)..."+JSON.stringify(dirList));+ var hasSubFolders = false;+ for (var i = 0; i < directoryHistory.length; i++) {+ if (directoryHistory[i].path === TSCORE.currentPath) {+ directoryHistory[i].children = [];+ for (var j = 0; j < dirList.length; j++) {+ if (!dirList[j].isFile) {+ if (TSCORE.Config.getShowUnixHiddenEntries() || !TSCORE.Config.getShowUnixHiddenEntries() && dirList[j].name.indexOf('.') !== 0) {+ directoryHistory[i].children.push(dirList[j]);+ hasSubFolders = true;}+ }}-- generateDirPath();- generateAlternativeDirPath();- handleDirCollapsion();- }-- function generateAlternativeDirPath() {- console.log("Generating Alternative Directory Path...");- var $alternativeNavigator = $("#alternativeNavigator");-- $alternativeNavigator.children().remove();- $alternativeNavigator.html(alternativeDirectoryNavigatorTmpl({- "dirHistory":directoryHistory,- "actionsForDirectory":$.i18n.t("ns.common:actionsForDirectory2"),- "subfodersOfDirectory":$.i18n.t("ns.common:subfodersOfDirectory2"),- "noSubfoldersFound":$.i18n.t("ns.common:noSubfoldersFound"),- "reloadCurrentDirectory":$.i18n.t("ns.common:reloadCurrentDirectory"),- "createSubdirectory":$.i18n.t("ns.common:createSubdirectory"),- "renameDirectory":$.i18n.t("ns.common:renameDirectory")- }));-- $alternativeNavigator.find(".reloadCurrentDirectory").each(function() {- $(this).on("click", function () {- navigateToDirectory($(this).attr("data-path"))- })- });-- $alternativeNavigator.find(".createSubdirectory").each(function() {- $(this).on("click", function () {- showCreateDirectoryDialog($(this).attr("data-path"))- })- });-- $alternativeNavigator.find(".renameDirectory").each(function() {- $(this).on("click", function () {- showRenameDirectoryDialog($(this).attr("data-path"))- })- });-- $alternativeNavigator.find(".dropdown-toggle").each(function() {- $(this).on("contextmenu click", function () {- TSCORE.hideAllDropDownMenus();- showDropUp("#dirMenu"+$(this).attr("data-menu"), $(this));- return false;- })- });-- $alternativeNavigator.find(".close").each(function() {- $(this).click(function() {- TSCORE.hideAllDropDownMenus();- })- });-- $alternativeNavigator.find(".dirButton").each(function() {- $(this).click(function () {- navigateToDirectory($(this).attr("data-path"));- })- });- }-- var showDropUp = function(menuId, sourceObject) {- var $menu = $(menuId);- var leftPos = 0;- var topPos = -$menu.height();-- if (sourceObject.offset().left+300 > window.innerWidth) {- leftPos = -200+sourceObject.width();- }- //console.log(leftPos+" "+sourceObject.offset().left+" "+$menu.width()+" "+window.innerWidth);-- $menu.css({- display: "block",- left: leftPos+"px",- top: topPos- });- };-- function generateDirPath() {- console.log("Generating Directory Path...");- var $locationContent = $("#locationContent");- $locationContent.children().remove();-- $locationContent.html(mainDirectoryNavigatorTmpl({- "dirHistory":directoryHistory,- "noSubfoldersFound":$.i18n.t("ns.common:noSubfoldersFound"),- "toggleDirectory":$.i18n.t("ns.common:toggleDirectory"),- "directoryOperations":$.i18n.t("ns.common:directoryOperations")- }));-- $locationContent.find(".directoryTitle").each(function() {- $(this)- .click(function () {- navigateToDirectory($(this).attr("key"));- })- .droppable({- greedy: "true",- accept: '.fileTitleButton,.fileTile',- hoverClass: "dropOnFolder",- drop: function( event, ui ) {- ui.draggable.detach();- var filePath = ui.draggable.attr("filepath");- var fileName = TSCORE.TagUtils.extractFileName(filePath);- var targetDir = $(this).attr("key");- console.log("Moving file: "+filePath+" to "+targetDir);- TSCORE.IO.renameFile(filePath, targetDir+TSCORE.dirSeparator+fileName);- $(ui.helper).remove();- }- })- });-- $locationContent.find(".dirButton").each(function() {- $(this)- .click(function () {- navigateToDirectory($(this).attr("key"));- })- .droppable({- greedy: "true",- accept: ".fileTitleButton,.fileTile",- hoverClass: "dropOnFolder",- drop: function( event, ui ) {- ui.draggable.detach();- // Fixing issue with dropping on stacked/overlapped directories- if( $(this).parent().parent().parent().hasClass("in") ) {- var filePath = ui.draggable.attr("filepath");- var fileName = TSCORE.TagUtils.extractFileName(filePath);- var targetDir = $(this).attr("key");- console.log("Moving file: "+filePath+" to "+targetDir);- TSCORE.IO.renameFile(filePath, targetDir+TSCORE.dirSeparator+fileName);- $(ui.helper).remove();- }- }- })+ // Sort the dirList alphabetically+ directoryHistory[i].children.sort(function(a, b) {+ return a.name.localeCompare(b.name);});+ }}-- function handleDirCollapsion() {- $("#locationContent").find(".accordion-heading").each(function() {- var key = $(this).attr("key");- console.log("Entered Header for: "+key);- if(getDirectoryCollapsed(key)) {- $(this).find("i").removeClass("fa-folder-open");- $(this).find("i").addClass("fa-folder");- $(this).next().removeClass("in");- $(this).next().addClass("out");- } else {- $(this).find("i").removeClass("fa-folder");- $(this).find("i").addClass("fa-folder-open");- $(this).next().removeClass("out");- $(this).next().addClass("in");- }- });+ generateDirPath();+ generateAlternativeDirPath();+ handleDirCollapsion();+ }++ function generateAlternativeDirPath() {+ console.log('Generating Alternative Directory Path...');+ var $alternativeNavigator = $('#alternativeNavigator');+ $alternativeNavigator.children().remove();+ $alternativeNavigator.html(alternativeDirectoryNavigatorTmpl({+ 'dirHistory': directoryHistory,+ 'actionsForDirectory': $.i18n.t('ns.common:actionsForDirectory2'),+ 'subfodersOfDirectory': $.i18n.t('ns.common:subfodersOfDirectory2'),+ 'noSubfoldersFound': $.i18n.t('ns.common:noSubfoldersFound'),+ 'reloadCurrentDirectory': $.i18n.t('ns.common:reloadCurrentDirectory'),+ 'createSubdirectory': $.i18n.t('ns.common:createSubdirectory'),+ 'renameDirectory': $.i18n.t('ns.common:renameDirectory')+ }));+ $alternativeNavigator.find('.reloadCurrentDirectory').each(function() {+ $(this).on('click', function() {+ navigateToDirectory($(this).attr('data-path'));+ });+ });+ $alternativeNavigator.find('.createSubdirectory').each(function() {+ $(this).on('click', function() {+ showCreateDirectoryDialog($(this).attr('data-path'));+ });+ });+ $alternativeNavigator.find('.renameDirectory').each(function() {+ $(this).on('click', function() {+ showRenameDirectoryDialog($(this).attr('data-path'));+ });+ });+ $alternativeNavigator.find('.dropdown-toggle').each(function() {+ $(this).on('contextmenu click', function() {+ TSCORE.hideAllDropDownMenus();+ showDropUp('#dirMenu' + $(this).attr('data-menu'), $(this));+ return false;+ });+ });+ $alternativeNavigator.find('.close').each(function() {+ $(this).click(function() {+ TSCORE.hideAllDropDownMenus();+ });+ });+ $alternativeNavigator.find('.dirButton').each(function() {+ $(this).click(function() {+ navigateToDirectory($(this).attr('data-path'));+ });+ });+ }+ var showDropUp = function(menuId, sourceObject) {+ var $menu = $(menuId);+ var leftPos = 0;+ var topPos = -$menu.height();+ if (sourceObject.offset().left + 300 > window.innerWidth) {+ leftPos = -200 + sourceObject.width();}-- function getDirectoryCollapsed(directoryPath) {- for(var i=0; i < directoryHistory.length; i++) {- if(directoryHistory[i].path === directoryPath) {- return directoryHistory[i].collapsed;- }+ //console.log(leftPos+" "+sourceObject.offset().left+" "+$menu.width()+" "+window.innerWidth);+ $menu.css({+ display: 'block',+ left: leftPos + 'px',+ top: topPos+ });+ };++ function generateDirPath() {+ console.log('Generating Directory Path...');+ var $locationContent = $('#locationContent');+ $locationContent.children().remove();+ $locationContent.html(mainDirectoryNavigatorTmpl({+ 'dirHistory': directoryHistory,+ 'noSubfoldersFound': $.i18n.t('ns.common:noSubfoldersFound'),+ 'toggleDirectory': $.i18n.t('ns.common:toggleDirectory'),+ 'directoryOperations': $.i18n.t('ns.common:directoryOperations')+ }));+ $locationContent.find('.directoryTitle').each(function() {+ $(this).click(function() {+ navigateToDirectory($(this).attr('key'));+ }).droppable({+ greedy: 'true',+ accept: '.fileTitleButton,.fileTile',+ hoverClass: 'dropOnFolder',+ drop: function(event, ui) {+ ui.draggable.detach();+ var filePath = ui.draggable.attr('filepath');+ var fileName = TSCORE.TagUtils.extractFileName(filePath);+ var targetDir = $(this).attr('key');+ console.log('Moving file: ' + filePath + ' to ' + targetDir);+ TSCORE.IO.renameFile(filePath, targetDir + TSCORE.dirSeparator + fileName);+ $(ui.helper).remove();}- }-- function setDirectoryCollapse(directoryPath, collapsed) {- for(var i=0; i < directoryHistory.length; i++) {- if(directoryHistory[i].path === directoryPath) {- directoryHistory[i].collapsed = collapsed;- }+ });+ });+ $locationContent.find('.dirButton').each(function() {+ $(this).click(function() {+ navigateToDirectory($(this).attr('key'));+ }).droppable({+ greedy: 'true',+ accept: '.fileTitleButton,.fileTile',+ hoverClass: 'dropOnFolder',+ drop: function(event, ui) {+ ui.draggable.detach();+ // Fixing issue with dropping on stacked/overlapped directories+ if ($(this).parent().parent().parent().hasClass('in')) {+ var filePath = ui.draggable.attr('filepath');+ var fileName = TSCORE.TagUtils.extractFileName(filePath);+ var targetDir = $(this).attr('key');+ console.log('Moving file: ' + filePath + ' to ' + targetDir);+ TSCORE.IO.renameFile(filePath, targetDir + TSCORE.dirSeparator + fileName);+ $(ui.helper).remove();+ }}+ });+ });+ }++ function handleDirCollapsion() {+ $('#locationContent').find('.accordion-heading').each(function() {+ var key = $(this).attr('key');+ console.log('Entered Header for: ' + key);+ if (getDirectoryCollapsed(key)) {+ $(this).find('i').removeClass('fa-folder-open');+ $(this).find('i').addClass('fa-folder');+ $(this).next().removeClass('in');+ $(this).next().addClass('out');+ } else {+ $(this).find('i').removeClass('fa-folder');+ $(this).find('i').addClass('fa-folder-open');+ $(this).next().removeClass('out');+ $(this).next().addClass('in');+ }+ });+ }++ function getDirectoryCollapsed(directoryPath) {+ for (var i = 0; i < directoryHistory.length; i++) {+ if (directoryHistory[i].path === directoryPath) {+ return directoryHistory[i].collapsed;+ }}-- function navigateToDirectory(directoryPath) {- console.log("Navigating to directory: "+directoryPath);-- // Clearing search results on directory change- TSCORE.clearSearchFilter();-- // Cleaning the directory path from \\ \ and /- if( (directoryPath.lastIndexOf('/')+1 === directoryPath.length) || (directoryPath.lastIndexOf('\\')+1 === directoryPath.length)) {- directoryPath = directoryPath.substring(0,directoryPath.length-1);- }- if( (directoryPath.lastIndexOf('\\\\')+1 === directoryPath.length)) {- directoryPath = directoryPath.substring(0,directoryPath.length-2);- }-- var directoryFoundOn = -1;- for(var i=0; i < directoryHistory.length; i++) {- if(directoryHistory[i].path === directoryPath) {- directoryHistory[i].collapsed = false;- directoryFoundOn = i;- } else {- directoryHistory[i].collapsed = true;- }- }-- // Removes the history only if it is a completely new path- if(directoryFoundOn >= 0) {- var diff1 = directoryHistory.length - (directoryFoundOn+1);- if(diff1 > 0) {- directoryHistory.splice(directoryFoundOn+1, diff1);- }- }-- // If directory path not in history then add it to the history- if(directoryFoundOn < 0) {- // var parentLocation = directoryPath.substring(0, directoryPath.lastIndexOf(TSCORE.dirSeparator));- var parentLocation = TSCORE.TagUtils.extractParentDirectoryPath(directoryPath);- var parentFound = -1;- for(var j=0; j < directoryHistory.length; j++) {- if(directoryHistory[j].path === parentLocation) {- parentFound = j;- }- }- if(parentFound >= 0) {- var diff2 = directoryHistory.length - (parentFound+1);- if(diff2 > 0) {- directoryHistory.splice(parentFound+1, diff2);- }- }-- var locationTitle = directoryPath.substring(directoryPath.lastIndexOf(TSCORE.dirSeparator)+1,directoryPath.length);- directoryHistory.push({- "name": locationTitle,- "path": directoryPath,- "collapsed": false- });- }- console.log("Dir History: "+JSON.stringify(directoryHistory));- TSCORE.currentPath = directoryPath;- TSCORE.IO.listDirectory(directoryPath);- }-- function initUI() {- // Context Menus-- $("body").on("contextmenu click", ".directoryActions", function () {- TSCORE.hideAllDropDownMenus();- dir4ContextMenu = $(this).attr("key");- TSCORE.showContextMenu("#directoryMenu", $(this));- return false;- });-- // Context menu for the tags in the file table and the file viewer- $( "#directoryMenuReloadDirectory" ).click( function() {- navigateToDirectory(dir4ContextMenu);- });-- $( "#directoryMenuCreateDirectory" ).click( function() {- showCreateDirectoryDialog(dir4ContextMenu);- });-- $( "#directoryMenuRenameDirectory" ).click( function() {- showRenameDirectoryDialog(dir4ContextMenu);- });-- $( "#directoryMenuDeleteDirectory" ).click( function() {- TSCORE.showConfirmDialog(- $.i18n.t("ns.dialogs:deleteDirectoryTitleConfirm"),- $.i18n.t("ns.dialogs:deleteDirectoryContentConfirm", { dirPath: dir4ContextMenu }),- function() {- TSCORE.IO.deleteDirectory(dir4ContextMenu);- }- );- });-- $( "#directoryMenuOpenDirectory" ).click( function() {- TSCORE.IO.openDirectory(dir4ContextMenu);- });+ }- $( "#createNewLocation" ).click(function() {- showLocationCreateDialog();- });+ function setDirectoryCollapse(directoryPath, collapsed) {+ for (var i = 0; i < directoryHistory.length; i++) {+ if (directoryHistory[i].path === directoryPath) {+ directoryHistory[i].collapsed = collapsed;+ }}-- function createLocation() {- var locationPath = $("#folderLocation").val();- TSCORE.Config.createLocation(- $("#connectionName").val(),- locationPath,- $("#locationPerspective").val()- );-- // Enable the UI behavior by not empty location list- $( "#createNewLocation" ).attr("title",$.i18n.t("ns.common:connectNewLocationTooltip")).tooltip( "destroy" );- $( "#locationName" ).prop('disabled', false);- $( "#selectLocation" ).prop('disabled', false);-- initLocations();- openLocation(locationPath);+ }++ function navigateToDirectory(directoryPath) {+ console.log('Navigating to directory: ' + directoryPath);+ // Clearing search results on directory change+ TSCORE.clearSearchFilter();+ // Cleaning the directory path from \\ \ and /+ if (directoryPath.lastIndexOf('/') + 1 === directoryPath.length || directoryPath.lastIndexOf('\\') + 1 === directoryPath.length) {+ directoryPath = directoryPath.substring(0, directoryPath.length - 1);}-- function editLocation() {- var $connectionName2 = $("#connectionName2");- var $folderLocation2 = $("#folderLocation2");- TSCORE.Config.editLocation(- $connectionName2.attr("oldName"),- $connectionName2.val(),- $folderLocation2.val(),- $("#locationPerspective2").val()- );- initLocations();- openLocation($folderLocation2.val());+ if (directoryPath.lastIndexOf('\\\\') + 1 === directoryPath.length) {+ directoryPath = directoryPath.substring(0, directoryPath.length - 2);}-- function selectLocalDirectory() {- TSCORE.IO.selectDirectory();- //TSCORE.showDirectoryBrowserDialog("/media");+ var directoryFoundOn = -1;+ for (var i = 0; i < directoryHistory.length; i++) {+ if (directoryHistory[i].path === directoryPath) {+ directoryHistory[i].collapsed = false;+ directoryFoundOn = i;+ } else {+ directoryHistory[i].collapsed = true;+ }}-- function showLocationEditDialog(name,path) {- require([- "text!templates/LocationEditDialog.html"- ], function(uiTPL) {- var $dialogLocationEdit = $("#dialogLocationEdit");-- // Check if dialog already created- if($dialogLocationEdit.length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $("body").append(uiTemplate());-- if(isWeb) {- $("#selectLocalDirectory2").attr("style","visibility: hidden");- } else {- $("#selectLocalDirectory2").on("click",function(e) {- e.preventDefault();- selectLocalDirectory();- });- }-- $( "#saveLocationButton" ).on("click", function() {- editLocation();- });-- $( "#deleteLocationButton" ).on("click", function() {- showDeleteFolderConnectionDialog();- });- }-- var $connectionName2 = $("#connectionName2");- var $folderLocation2 = $("#folderLocation2");- var $locationPerspective2 = $("#locationPerspective2");-- var selectedPerspectiveId = TSCORE.Config.getLocation(path).perspective;- $locationPerspective2.children().remove();- TSCORE.Config.getActivatedPerspectiveExtensions().forEach( function(value) {- if (selectedPerspectiveId === value.id) {- $locationPerspective2.append($("<option>").attr("selected","selected").text(value.id).val(value.id));- } else {- $locationPerspective2.append($("<option>").text(value.id).val(value.id));- }- }- );-- $connectionName2.val(name);- $connectionName2.attr("oldName",name);- $folderLocation2.val(path);- $("#dialogLocationEdit").i18n();- if(isCordova) {- $("#folderLocation2").attr("placeholder","e.g.: DCIM/Camera");- } else if(isWeb) {- $("#folderLocation2").attr("placeholder","e.g.: /owncloud/remote.php/webdav/");- }-- $("#formLocationEdit").validator();- $("#formLocationEdit").submit(function (e) { e.preventDefault(); });- $('#formLocationEdit').on('invalid.bs.validator', function() {- $( "#saveLocationButton").prop( "disabled", true );- });- $('#formLocationEdit').on('valid.bs.validator', function() {- $( "#saveLocationButton").prop( "disabled", false );- });-- $('#dialogLocationEdit').on('shown.bs.modal', function () {- $('#folderLocation2').focus();- });-- $("#dialogLocationEdit").modal({backdrop: 'static',show: true});- });- }-- function showLocationCreateDialog() {- require([- "text!templates/LocationCreateDialog.html"- ], function(uiTPL) {- var $dialogCreateFolderConnection = $("#dialogCreateFolderConnection");-- // Check if dialog already created- if($dialogCreateFolderConnection.length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $("body").append(uiTemplate());-- if(isWeb) {- $("#selectLocalDirectory").attr("style","visibility: hidden");- } else {- $("#selectLocalDirectory").on("click",function(e) {- e.preventDefault();- selectLocalDirectory();- });- }-- TSCORE.Config.getActivatedPerspectiveExtensions().forEach( function(value) {- $("#locationPerspective").append($("<option>").text(value.id).val(value.id));- });-- $( "#createFolderConnectionButton" ).on("click", function() {- createLocation();- });-- }- $("#connectionName").val("");- $("#folderLocation").val("");- $("#dialogCreateFolderConnection").i18n();- if(isCordova) {- $("#folderLocation").attr("placeholder","e.g.: DCIM/Camera");- } else if(isWeb) {- $("#folderLocation").attr("placeholder","e.g.: /owncloud/remote.php/webdav/");- }-- $("#formLocationCreate").validator();- $("#formLocationCreate").submit(function (e) { e.preventDefault(); });- $('#formLocationCreate').on('invalid.bs.validator', function() {- $( "#createFolderConnectionButton").prop( "disabled", true );- });- $('#formLocationCreate').on('valid.bs.validator', function() {- $( "#createFolderConnectionButton").prop( "disabled", false );- });-- $('#dialogCreateFolderConnection').on('shown.bs.modal', function () {- $('#folderLocation').focus();- });-- $("#dialogCreateFolderConnection").modal({backdrop: 'static',show: true});- });- }-- function showCreateDirectoryDialog(dirPath) {- require([- "text!templates/DirectoryCreateDialog.html"- ], function(uiTPL) {- if($("#dialogDirectoryCreate").length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $('body').append(uiTemplate());-- $( "#createNewDirectoryButton" ).on("click", function() {- // TODO validate folder name- TSCORE.IO.createDirectory($( "#createNewDirectoryButton" ).attr("path")+TSCORE.dirSeparator+$( "#newDirectoryName" ).val());- });- }- $( "#createNewDirectoryButton" ).attr("path", dirPath);- $("#newDirectoryName").val("");- $('#dialogDirectoryCreate').i18n();-- $("#formDirectoryCreate").validator();- $("#formDirectoryCreate").submit(function (e) { e.preventDefault(); });- $('#formDirectoryCreate').on('invalid.bs.validator', function() {- $( "#createNewDirectoryButton").prop( "disabled", true );- });- $('#formDirectoryCreate').on('valid.bs.validator', function() {- $( "#createNewDirectoryButton").prop( "disabled", false );- });-- $('#dialogDirectoryCreate').on('shown.bs.modal', function () {- $('#newDirectoryName').focus();- });-- $('#dialogDirectoryCreate').modal({backdrop: 'static',show: true});- });+ // Removes the history only if it is a completely new path+ if (directoryFoundOn >= 0) {+ var diff1 = directoryHistory.length - (directoryFoundOn + 1);+ if (diff1 > 0) {+ directoryHistory.splice(directoryFoundOn + 1, diff1);+ }}-- function showRenameDirectoryDialog(dirPath) {- require([- "text!templates/DirectoryRenameDialog.html"- ], function(uiTPL) {- if($("#dialogDirectoryRename").length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $('body').append(uiTemplate());-- $( "#renameDirectoryButton" ).on("click", function() {- TSCORE.IO.renameDirectory($( "#renameDirectoryButton" ).attr("path"), $( "#directoryNewName" ).val());- });- }-- $("#formDirectoryRename").validator();- $("#formDirectoryRename").submit(function (e) { e.preventDefault(); });- $('#formDirectoryRename').on('invalid.bs.validator', function() {- $( "#renameDirectoryButton").prop( "disabled", true );- });- $('#formDirectoryRename').on('valid.bs.validator', function() {- $( "#renameDirectoryButton").prop( "disabled", false );- });-- $( "#renameDirectoryButton" ).attr("path", dirPath);- var dirName = TSCORE.TagUtils.extractDirectoryName(dirPath);- $("#directoryNewName").val(dirName);- $('#dialogDirectoryRename').i18n();-- $('#dialogDirectoryRename').on('shown.bs.modal', function () {- $('#directoryNewName').focus();- });-- $('#dialogDirectoryRename').modal({backdrop: 'static',show: true});- });+ // If directory path not in history then add it to the history+ if (directoryFoundOn < 0) {+ // var parentLocation = directoryPath.substring(0, directoryPath.lastIndexOf(TSCORE.dirSeparator));+ var parentLocation = TSCORE.TagUtils.extractParentDirectoryPath(directoryPath);+ var parentFound = -1;+ for (var j = 0; j < directoryHistory.length; j++) {+ if (directoryHistory[j].path === parentLocation) {+ parentFound = j;+ }+ }+ if (parentFound >= 0) {+ var diff2 = directoryHistory.length - (parentFound + 1);+ if (diff2 > 0) {+ directoryHistory.splice(parentFound + 1, diff2);+ }+ }+ var locationTitle = directoryPath.substring(directoryPath.lastIndexOf(TSCORE.dirSeparator) + 1, directoryPath.length);+ directoryHistory.push({+ 'name': locationTitle,+ 'path': directoryPath,+ 'collapsed': false+ });}-- function deleteLocation(name) {- console.log("Deleting folder connection..");- TSCORE.Config.deleteLocation(name);-- initLocations();-- //Opens the first location in the settings after deleting a location- if(TSCORE.Config.Settings.tagspacesList.length > 0) {- openLocation(TSCORE.Config.Settings.tagspacesList[0].path);+ console.log('Dir History: ' + JSON.stringify(directoryHistory));+ TSCORE.currentPath = directoryPath;+ TSCORE.IO.listDirectory(directoryPath);+ }++ function initUI() {+ // Context Menus+ $('body').on('contextmenu click', '.directoryActions', function() {+ TSCORE.hideAllDropDownMenus();+ dir4ContextMenu = $(this).attr('key');+ TSCORE.showContextMenu('#directoryMenu', $(this));+ return false;+ });+ // Context menu for the tags in the file table and the file viewer+ $('#directoryMenuReloadDirectory').click(function() {+ navigateToDirectory(dir4ContextMenu);+ });+ $('#directoryMenuCreateDirectory').click(function() {+ showCreateDirectoryDialog(dir4ContextMenu);+ });+ $('#directoryMenuRenameDirectory').click(function() {+ showRenameDirectoryDialog(dir4ContextMenu);+ });+ $('#directoryMenuDeleteDirectory').click(function() {+ TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:deleteDirectoryTitleConfirm'), $.i18n.t('ns.dialogs:deleteDirectoryContentConfirm', {+ dirPath: dir4ContextMenu+ }), function() {+ TSCORE.IO.deleteDirectory(dir4ContextMenu);+ });+ });+ $('#directoryMenuOpenDirectory').click(function() {+ TSCORE.IO.openDirectory(dir4ContextMenu);+ });+ $('#createNewLocation').click(function() {+ showLocationCreateDialog();+ });+ }++ function createLocation() {+ var locationPath = $('#folderLocation').val();+ TSCORE.Config.createLocation($('#connectionName').val(), locationPath, $('#locationPerspective').val());+ // Enable the UI behavior by not empty location list+ $('#createNewLocation').attr('title', $.i18n.t('ns.common:connectNewLocationTooltip')).tooltip('destroy');+ $('#locationName').prop('disabled', false);+ $('#selectLocation').prop('disabled', false);+ initLocations();+ openLocation(locationPath);+ }++ function editLocation() {+ var $connectionName2 = $('#connectionName2');+ var $folderLocation2 = $('#folderLocation2');+ TSCORE.Config.editLocation($connectionName2.attr('oldName'), $connectionName2.val(), $folderLocation2.val(), $('#locationPerspective2').val());+ initLocations();+ openLocation($folderLocation2.val());+ }++ function selectLocalDirectory() {+ TSCORE.IO.selectDirectory(); //TSCORE.showDirectoryBrowserDialog("/media");+ }++ function showLocationEditDialog(name, path) {+ require(['text!templates/LocationEditDialog.html'], function(uiTPL) {+ var $dialogLocationEdit = $('#dialogLocationEdit');+ // Check if dialog already created+ if ($dialogLocationEdit.length < 1) {+ var uiTemplate = Handlebars.compile(uiTPL);+ $('body').append(uiTemplate());+ if (isWeb) {+ $('#selectLocalDirectory2').attr('style', 'visibility: hidden');} else {- closeCurrentLocation();+ $('#selectLocalDirectory2').on('click', function(e) {+ e.preventDefault();+ selectLocalDirectory();+ });}- }-- function closeCurrentLocation() {- console.log("Closing location..");- $("#locationName").text($.i18n.t("ns.common:chooseLocation")).attr("title","");- $("#locationContent").children().remove();-- // Clear the footer- $("#statusBar").children().remove();- $("#alternativeNavigator").children().remove();--- TSCORE.disableTopToolbar();- TSCORE.PerspectiveManager.hideAllPerspectives();- }-- function showDeleteFolderConnectionDialog() {- TSCORE.showConfirmDialog(- $.i18n.t("ns.dialogs:deleteLocationTitleAlert"),- $.i18n.t("ns.dialogs:deleteLocationContentAlert", { locationName: $("#connectionName2").attr("oldName") }),- function() {- deleteLocation($("#connectionName2").attr("oldName"));- $("#dialogLocationEdit").modal('hide');- }- );- }-- function initLocations() {- console.log("Creating location menu...");-- var $locationsList = $( "#locationsList" );- $locationsList.children().remove();-- $locationsList.html(locationChooserTmpl({- "locations":TSCORE.Config.Settings.tagspacesList,- "yourLocations":$.i18n.t("ns.common:yourLocations"),- "editLocationTitle":$.i18n.t("ns.common:editLocation")- }));-- $locationsList.find(".btn-default").each(function() {- $(this).on("click", function () {- openLocation($(this).attr( "path" ));- })+ $('#saveLocationButton').on('click', function() {+ editLocation();});-- $locationsList.find(".btn-link").each(function() {- $(this).on("click", function () {- console.log("Edit location clicked");- showLocationEditDialog($(this).attr("location"),$(this).attr("path"));- return false;- })+ $('#deleteLocationButton').on('click', function() {+ showDeleteFolderConnectionDialog();});-+ }+ var $connectionName2 = $('#connectionName2');+ var $folderLocation2 = $('#folderLocation2');+ var $locationPerspective2 = $('#locationPerspective2');+ var selectedPerspectiveId = TSCORE.Config.getLocation(path).perspective;+ $locationPerspective2.children().remove();+ TSCORE.Config.getActivatedPerspectiveExtensions().forEach(function(value) {+ if (selectedPerspectiveId === value.id) {+ $locationPerspective2.append($('<option>').attr('selected', 'selected').text(value.id).val(value.id));+ } else {+ $locationPerspective2.append($('<option>').text(value.id).val(value.id));+ }+ });+ $connectionName2.val(name);+ $connectionName2.attr('oldName', name);+ $folderLocation2.val(path);+ $('#dialogLocationEdit').i18n();+ if (isCordova) {+ $('#folderLocation2').attr('placeholder', 'e.g.: DCIM/Camera');+ } else if (isWeb) {+ $('#folderLocation2').attr('placeholder', 'e.g.: /owncloud/remote.php/webdav/');+ }+ $('#formLocationEdit').validator();+ $('#formLocationEdit').submit(function(e) {+ e.preventDefault();+ });+ $('#formLocationEdit').on('invalid.bs.validator', function() {+ $('#saveLocationButton').prop('disabled', true);+ });+ $('#formLocationEdit').on('valid.bs.validator', function() {+ $('#saveLocationButton').prop('disabled', false);+ });+ $('#dialogLocationEdit').on('shown.bs.modal', function() {+ $('#folderLocation2').focus();+ });+ $('#dialogLocationEdit').modal({+ backdrop: 'static',+ show: true+ });+ });+ }++ function showLocationCreateDialog() {+ require(['text!templates/LocationCreateDialog.html'], function(uiTPL) {+ var $dialogCreateFolderConnection = $('#dialogCreateFolderConnection');+ // Check if dialog already created+ if ($dialogCreateFolderConnection.length < 1) {+ var uiTemplate = Handlebars.compile(uiTPL);+ $('body').append(uiTemplate());+ if (isWeb) {+ $('#selectLocalDirectory').attr('style', 'visibility: hidden');+ } else {+ $('#selectLocalDirectory').on('click', function(e) {+ e.preventDefault();+ selectLocalDirectory();+ });+ }+ TSCORE.Config.getActivatedPerspectiveExtensions().forEach(function(value) {+ $('#locationPerspective').append($('<option>').text(value.id).val(value.id));+ });+ $('#createFolderConnectionButton').on('click', function() {+ createLocation();+ });+ }+ $('#connectionName').val('');+ $('#folderLocation').val('');+ $('#dialogCreateFolderConnection').i18n();+ if (isCordova) {+ $('#folderLocation').attr('placeholder', 'e.g.: DCIM/Camera');+ } else if (isWeb) {+ $('#folderLocation').attr('placeholder', 'e.g.: /owncloud/remote.php/webdav/');+ }+ $('#formLocationCreate').validator();+ $('#formLocationCreate').submit(function(e) {+ e.preventDefault();+ });+ $('#formLocationCreate').on('invalid.bs.validator', function() {+ $('#createFolderConnectionButton').prop('disabled', true);+ });+ $('#formLocationCreate').on('valid.bs.validator', function() {+ $('#createFolderConnectionButton').prop('disabled', false);+ });+ $('#dialogCreateFolderConnection').on('shown.bs.modal', function() {+ $('#folderLocation').focus();+ });+ $('#dialogCreateFolderConnection').modal({+ backdrop: 'static',+ show: true+ });+ });+ }++ function showCreateDirectoryDialog(dirPath) {+ require(['text!templates/DirectoryCreateDialog.html'], function(uiTPL) {+ if ($('#dialogDirectoryCreate').length < 1) {+ var uiTemplate = Handlebars.compile(uiTPL);+ $('body').append(uiTemplate());+ $('#createNewDirectoryButton').on('click', function() {+ // TODO validate folder name+ TSCORE.IO.createDirectory($('#createNewDirectoryButton').attr('path') + TSCORE.dirSeparator + $('#newDirectoryName').val());+ });+ }+ $('#createNewDirectoryButton').attr('path', dirPath);+ $('#newDirectoryName').val('');+ $('#dialogDirectoryCreate').i18n();+ $('#formDirectoryCreate').validator();+ $('#formDirectoryCreate').submit(function(e) {+ e.preventDefault();+ });+ $('#formDirectoryCreate').on('invalid.bs.validator', function() {+ $('#createNewDirectoryButton').prop('disabled', true);+ });+ $('#formDirectoryCreate').on('valid.bs.validator', function() {+ $('#createNewDirectoryButton').prop('disabled', false);+ });+ $('#dialogDirectoryCreate').on('shown.bs.modal', function() {+ $('#newDirectoryName').focus();+ });+ $('#dialogDirectoryCreate').modal({+ backdrop: 'static',+ show: true+ });+ });+ }++ function showRenameDirectoryDialog(dirPath) {+ require(['text!templates/DirectoryRenameDialog.html'], function(uiTPL) {+ if ($('#dialogDirectoryRename').length < 1) {+ var uiTemplate = Handlebars.compile(uiTPL);+ $('body').append(uiTemplate());+ $('#renameDirectoryButton').on('click', function() {+ TSCORE.IO.renameDirectory($('#renameDirectoryButton').attr('path'), $('#directoryNewName').val());+ });+ }+ $('#formDirectoryRename').validator();+ $('#formDirectoryRename').submit(function(e) {+ e.preventDefault();+ });+ $('#formDirectoryRename').on('invalid.bs.validator', function() {+ $('#renameDirectoryButton').prop('disabled', true);+ });+ $('#formDirectoryRename').on('valid.bs.validator', function() {+ $('#renameDirectoryButton').prop('disabled', false);+ });+ $('#renameDirectoryButton').attr('path', dirPath);+ var dirName = TSCORE.TagUtils.extractDirectoryName(dirPath);+ $('#directoryNewName').val(dirName);+ $('#dialogDirectoryRename').i18n();+ $('#dialogDirectoryRename').on('shown.bs.modal', function() {+ $('#directoryNewName').focus();+ });+ $('#dialogDirectoryRename').modal({+ backdrop: 'static',+ show: true+ });+ });+ }++ function deleteLocation(name) {+ console.log('Deleting folder connection..');+ TSCORE.Config.deleteLocation(name);+ initLocations();+ //Opens the first location in the settings after deleting a location+ if (TSCORE.Config.Settings.tagspacesList.length > 0) {+ openLocation(TSCORE.Config.Settings.tagspacesList[0].path);+ } else {+ closeCurrentLocation();}-- // Public API definition- exports.openLocation = openLocation;- exports.closeCurrentLocation = closeCurrentLocation;- exports.updateSubDirs = updateSubDirs;- exports.initUI = initUI;- exports.initLocations = initLocations;- exports.showCreateDirectoryDialog = showCreateDirectoryDialog;- exports.navigateToDirectory = navigateToDirectory;+ }++ function closeCurrentLocation() {+ console.log('Closing location..');+ $('#locationName').text($.i18n.t('ns.common:chooseLocation')).attr('title', '');+ $('#locationContent').children().remove();+ // Clear the footer+ $('#statusBar').children().remove();+ $('#alternativeNavigator').children().remove();+ TSCORE.disableTopToolbar();+ TSCORE.PerspectiveManager.hideAllPerspectives();+ }++ function showDeleteFolderConnectionDialog() {+ TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:deleteLocationTitleAlert'), $.i18n.t('ns.dialogs:deleteLocationContentAlert', {+ locationName: $('#connectionName2').attr('oldName')+ }), function() {+ deleteLocation($('#connectionName2').attr('oldName'));+ $('#dialogLocationEdit').modal('hide');+ });+ }++ function initLocations() {+ console.log('Creating location menu...');+ var $locationsList = $('#locationsList');+ $locationsList.children().remove();+ $locationsList.html(locationChooserTmpl({+ 'locations': TSCORE.Config.Settings.tagspacesList,+ 'yourLocations': $.i18n.t('ns.common:yourLocations'),+ 'editLocationTitle': $.i18n.t('ns.common:editLocation')+ }));+ $locationsList.find('.btn-default').each(function() {+ $(this).on('click', function() {+ openLocation($(this).attr('path'));+ });+ });+ $locationsList.find('.btn-link').each(function() {+ $(this).on('click', function() {+ console.log('Edit location clicked');+ showLocationEditDialog($(this).attr('location'), $(this).attr('path'));+ return false;+ });+ });+ }+ // Public API definition+ exports.openLocation = openLocation;+ exports.closeCurrentLocation = closeCurrentLocation;+ exports.updateSubDirs = updateSubDirs;+ exports.initUI = initUI;+ exports.initLocations = initLocations;+ exports.showCreateDirectoryDialog = showCreateDirectoryDialog;+ exports.navigateToDirectory = navigateToDirectory;});diff --git a/data/js/directorybrowser.js b/data/js/directorybrowser.jsindex 81694c647..66660eb45 100644--- a/data/js/directorybrowser.js+++ b/data/js/directorybrowser.js@@ -1,69 +1,59 @@-/* 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. */-define(function(require, exports, module) {-"use strict";-- console.log("Loading directorybrowser.js ...");-- var TSCORE = require("tscore");- var TSPOSTIO = require("tspostioapi");-- function initUI() {- $( "#gotoParentDirButton" ).click(function() {- var parent = TSCORE.TagUtils.extractParentDirectoryPath($("#directoryPath").val());- TSCORE.IO.listSubDirectories(parent);- });-- if(isWin) {- $( "#driveSelectorForm" ).show();- var driveSelector = $('#driveSelector');- driveSelector.change(function() {- $('#subdirectoriesArea').empty();- $('#directoryPath').val(driveSelector.val());- TSCORE.IO.listSubDirectories(driveSelector.val());- });- }-- $( "#selectDirectoryButton" ).click(function() {- TSPOSTIO.selectDirectory($("#directoryPath").val());- $('#driveSelector').prop('selectedIndex',0);- });- }-- function reInitUI(dirPath) {- $('#directoryPath').val(dirPath);--- var subfolders = $('#subdirectoriesArea').empty();- if(TSCORE.subfoldersDirBrowser === undefined || TSCORE.subfoldersDirBrowser.length <= 0) {- subfolders.append("<div class='alert alert-warning'>No subfolders found</div>");- } else {- for(var j=0; j < TSCORE.subfoldersDirBrowser.length; j++) {- if (TSCORE.Config.getShowUnixHiddenEntries() ||- (!TSCORE.Config.getShowUnixHiddenEntries() && (TSCORE.subfoldersDirBrowser[j].name.indexOf(".") !== 0))- ) {- subfolders.append($("<button>", {- "class": "btn btn-sm dirButton",- "path": TSCORE.subfoldersDirBrowser[j].path,- "title": TSCORE.subfoldersDirBrowser[j].path,- "style": "margin: 1px;",- "text": " "+TSCORE.subfoldersDirBrowser[j].name- })- .prepend("<i class='fa fa-folder-o'></i>")- .click( function() {- TSCORE.IO.listSubDirectories($(this).attr("path"));- })- );- }- }- }-- $('#directoryBrowserDialog').modal({backdrop: 'static',show: true});- }-- // Public Methods- exports.initUI = initUI;- exports.reInitUI = reInitUI;--});\ No newline at end of file+/* 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. */+define(function(require, exports, module) {+ 'use strict';+ console.log('Loading directorybrowser.js ...');+ var TSCORE = require('tscore');+ var TSPOSTIO = require('tspostioapi');++ function initUI() {+ $('#gotoParentDirButton').click(function() {+ var parent = TSCORE.TagUtils.extractParentDirectoryPath($('#directoryPath').val());+ TSCORE.IO.listSubDirectories(parent);+ });+ if (isWin) {+ $('#driveSelectorForm').show();+ var driveSelector = $('#driveSelector');+ driveSelector.change(function() {+ $('#subdirectoriesArea').empty();+ $('#directoryPath').val(driveSelector.val());+ TSCORE.IO.listSubDirectories(driveSelector.val());+ });+ }+ $('#selectDirectoryButton').click(function() {+ TSPOSTIO.selectDirectory($('#directoryPath').val());+ $('#driveSelector').prop('selectedIndex', 0);+ });+ }++ function reInitUI(dirPath) {+ $('#directoryPath').val(dirPath);+ var subfolders = $('#subdirectoriesArea').empty();+ if (TSCORE.subfoldersDirBrowser === undefined || TSCORE.subfoldersDirBrowser.length <= 0) {+ subfolders.append('<div class=\'alert alert-warning\'>No subfolders found</div>');+ } else {+ for (var j = 0; j < TSCORE.subfoldersDirBrowser.length; j++) {+ if (TSCORE.Config.getShowUnixHiddenEntries() || !TSCORE.Config.getShowUnixHiddenEntries() && TSCORE.subfoldersDirBrowser[j].name.indexOf('.') !== 0) {+ subfolders.append($('<button>', {+ 'class': 'btn btn-sm dirButton',+ 'path': TSCORE.subfoldersDirBrowser[j].path,+ 'title': TSCORE.subfoldersDirBrowser[j].path,+ 'style': 'margin: 1px;',+ 'text': ' ' + TSCORE.subfoldersDirBrowser[j].name+ }).prepend('<i class=\'fa fa-folder-o\'></i>').click(function() {+ TSCORE.IO.listSubDirectories($(this).attr('path'));+ })); // jshint ignore:line+ }+ }+ }+ $('#directoryBrowserDialog').modal({+ backdrop: 'static',+ show: true+ });+ }++ // Public Methods+ exports.initUI = initUI;+ exports.reInitUI = reInitUI;+});diff --git a/data/js/fileopener.js b/data/js/fileopener.jsindex b288488bd..55111dafa 100644--- a/data/js/fileopener.js+++ b/data/js/fileopener.js@@ -1,4 +1,4 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.+/* 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. *//* undef: true, unused: false */@@ -217,7 +217,7 @@ define(function(require, exports, module) {var editorExt = TSCORE.Config.getFileTypeEditor(fileExt);console.log('File Viewer: ' + viewerExt + ' File Editor: ' + editorExt);// Handling the edit button depending on existense of an editor- if (editorExt == false || editorExt == 'false' || editorExt === '') {+ if (editorExt === false || editorExt === 'false' || editorExt === '') {$('#editDocument').hide();} else {$('#editDocument').show();@@ -452,11 +452,11 @@ define(function(require, exports, module) {console.log('Tag suggestion clicked: ' + tagName);TSCORE.TagUtils.writeTagsToFile(filePath, [tagName]);return false;- }))));+ })))); // jshint ignore:line}}}-+// TODO Make file properties dialog accessible from corefunction showFilePropertiesDialog() {require(['text!templates/FilePropertiesDialog.html'], function(uiTPL) {@@ -478,7 +478,7 @@ define(function(require, exports, module) {});});}-+// Public API definitionexports.initUI = initUI;exports.openFile = openFile;@@ -492,4 +492,4 @@ define(function(require, exports, module) {exports.getOpenedFilePath = getOpenedFilePath;exports.updateEditorContent = updateEditorContent;exports.setFileProperties = setFileProperties;-});\ No newline at end of file+});diff --git a/data/js/options.ui.js b/data/js/options.ui.jsindex 1b0498a5f..07e16db5e 100644--- a/data/js/options.ui.js+++ b/data/js/options.ui.js@@ -1,241 +1,195 @@-/* 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, Mousetrap, Handlebars */- define(function(require, exports, module) {-"use strict";-- console.log("Loading options.ui.js ...");-- var TSCORE = require("tscore");-- require(['libs/filesaver.js/FileSaver.js'], function() {});-- function generateSelectOptions(parent, data, selectedId) {- parent.empty();- parent.append($("<option>").text("").val("false"));- data.forEach( function(value) {- if (selectedId === value) {- parent.append($("<option>").attr("selected","selected").text(value).val(value));- } else {- parent.append($("<option>").text(value).val(value));- }- });- }-- function addPerspective(parent, perspectiveId) {- var perspectiveControl = $("<div class='form-inline'>")- .append($("<div class='input-group' style='width: 90%'>")- .append($("<select class='form-control' style='width: 70%'></select>"))- .append($("<button class='btn btn-default' style='width: 40px' data-i18n='[title]ns.dialogs:removePerspectiveTooltip'><i class='fa fa-times'></button>")- .click(function() {- $(this).parent().parent().remove();- })- )- )- .i18n();-- generateSelectOptions(perspectiveControl.find("select"), TSCORE.Config.getPerspectiveExtensions(), perspectiveId);- parent.append(perspectiveControl);- }-- function addFileType(parent, fileext, viewerId, editorId) {- var fileTypeControl = $("<div class='form-inline'>")- .append($("<div class='input-group' >")- .append($("<input style='width: 80px' type='text' class='form-control' data-i18n='[placeholder]ns.dialogs:fileExtensionPlaceholder'>").val(fileext))- .append($("<select class='ftviewer form-control' style='width: 170px'></select>"))- .append($("<select class='fteditor form-control' style='width: 170px'></select>"))- .append($("<button style='width: 40px' class='btn btn-default' data-i18n='[title]ns.dialogs:removeFileTypeTooltip'><i class='fa fa-times'></button>")- .click(function() {- $(this).parent().parent().remove();- })- )- )- .i18n();- generateSelectOptions(fileTypeControl.find(".ftviewer"), TSCORE.Config.getViewerExtensions(), viewerId);- generateSelectOptions(fileTypeControl.find(".fteditor"), TSCORE.Config.getEditorExtensions(), editorId);- parent.append(fileTypeControl);- }-- function initUI() {- $('#addFileTypeButton').click(function(e) {- // Fixes reloading of the application by click- e.preventDefault();-- addFileType($('#fileTypesList'), "", "", "");- });-- $('#addPerspectiveButton').click(function(e) {- // Fixes reloading of the application by click- e.preventDefault();-- addPerspective($('#perspectiveList'), "");- });-- $('#saveSettingsCloseButton').click(function() {- updateSettings();- $('#dialogOptions').modal("hide");- //TSCORE.reloadUI();- });-- $( "#defaultSettingsButton" ).click(function() {- TSCORE.showConfirmDialog(- $.i18n.t("ns.dialogs:restoreDefaulSettingTitleConfirm"),- $.i18n.t("ns.dialogs:restoreDefaulSettingMessageConfirm"),- function() {- TSCORE.Config.loadDefaultSettings();- }- );- });-- $("#keyBindingInstructions").toggle();- $("#keyBindingInstructionsToggle").on("click", function(){- $("#keyBindingInstructions").toggle();- return false;- })-- if(isCordova) {- $( "#exportTagGroupsButton").hide();- }-- $( "#exportTagGroupsButton" ).click(function() {- var jsonFormat = '{ "appName": "'+TSCORE.Config.DefaultSettings['appName']+- '", "appVersion": "'+TSCORE.Config.DefaultSettings['appVersion']+- '", "appBuild": "'+TSCORE.Config.DefaultSettings['appBuild']+- '", "settingsVersion": '+TSCORE.Config.DefaultSettings['settingsVersion']+- ', "tagGroups": '- var blob = new Blob([jsonFormat+JSON.stringify(TSCORE.Config.getAllTagGroupData())+"}"], {type: "application/json"});- saveAs(blob, "tsm["+TSCORE.TagUtils.formatDateTime4Tag(new Date(),true)+"].json");- console.log("Group Data Saved...");- });- }-- function reInitUI() {- $("#extensionsPathInput").val(TSCORE.Config.getExtensionPath());- $("#showHiddenFilesCheckbox").attr("checked",TSCORE.Config.getShowUnixHiddenEntries());- $("#showMainMenuCheckbox").attr("checked",TSCORE.Config.getShowMainMenu());- $("#checkforUpdatesCheckbox").attr("checked",TSCORE.Config.getCheckForUpdates());- $("#calculateTagsCheckbox").attr("checked",TSCORE.Config.getCalculateTags());- $("#loadLocationMetaData").attr("checked",TSCORE.Config.getLoadLocationMeta());- $("#tagsDelimiterInput").val(TSCORE.Config.getTagDelimiter());- $("#prefixTagContainerInput").val(TSCORE.Config.getPrefixTagContainer());-- $("#nextDocumentKeyBinding").val(TSCORE.Config.getNextDocumentKeyBinding());- $("#prevDocumentKeyBinding").val(TSCORE.Config.getPrevDocumentKeyBinding());- $("#closeDocumentKeyBinding").val(TSCORE.Config.getCloseViewerKeyBinding());- $("#addRemoveTagsKeyBinding").val(TSCORE.Config.getAddRemoveTagsKeyBinding());- $("#editDocumentKeyBinding").val(TSCORE.Config.getEditDocumentKeyBinding());- $("#reloadDocumentKeyBinding").val(TSCORE.Config.getReloadDocumentKeyBinding());- $("#saveDocumentKeyBinding").val(TSCORE.Config.getSaveDocumentKeyBinding());- $("#documentPropertiesKeyBinding").val(TSCORE.Config.getPropertiesDocumentKeyBinding());-- $('#perspectiveList').empty();- TSCORE.Config.getPerspectives().forEach(function (value) {- addPerspective($('#perspectiveList'), value.id);- });-- var $languagesDropdown = $("#languagesList");- $languagesDropdown.empty();- TSCORE.Config.getSupportedLanguages().forEach( function(value) {- if (TSCORE.Config.getInterfaceLangauge() === value.iso) {- $languagesDropdown.append($("<option>").attr("selected","selected").text(value.title).val(value.iso));- } else {- $languagesDropdown.append($("<option>").text(value.title).val(value.iso));- }- });-- $('#fileTypesList')- .empty()- .append($("<div class='input-group' >")- .append($("<span style='width: 80px; border: 0' class='form-control' data-i18n='ns.dialogs:fileExtension'></span>"))- .append($("<span style=' border: 0; width: 170px' class='ftviewer form-control' data-i18n='ns.dialogs:fileViewer'></span>"))- .append($("<span style=' border: 0; width: 170px' class='fteditor form-control' data-i18n='ns.dialogs:fileEditor'></span>"))- ).i18n();-- TSCORE.Config.getSupportedFileTypes().sort(function(a, b){- if (a.type > b.type) {- return 1;- }- if (a.type < b.type) {- return -1;- }- return 0;- }).forEach(function (value) {- addFileType($('#fileTypesList'), value.type, value.viewer, value.editor);- });-- $('#dialogOptions a:first').tab('show');- $('#dialogOptions').modal({backdrop: 'static',show: true});- }-- function parseKeyBinding(keybinding) {- keybinding = keybinding.trim();- if(keybinding.indexOf(",") >= 0) {- keybinding = keybinding.split(",");- }- return keybinding;- }-- function updateSettings() {- TSCORE.Config.setExtensionPath($("#extensionsPathInput").val());- TSCORE.Config.setShowUnixHiddenEntries($('#showHiddenFilesCheckbox').is(":checked"));- TSCORE.Config.setShowMainMenu($('#showMainMenuCheckbox').is(":checked"));- TSCORE.Config.setCheckForUpdates($('#checkforUpdatesCheckbox').is(":checked"));- TSCORE.Config.setCalculateTags($('#calculateTagsCheckbox').is(":checked"));- TSCORE.Config.setTagDelimiter($("#tagsDelimiterInput").val());- TSCORE.Config.setPrefixTagContainer($("#prefixTagContainerInput").val());- TSCORE.Config.setLoadLocationMeta($("#loadLocationMetaData").is(":checked"));-- TSCORE.Config.setNextDocumentKeyBinding(parseKeyBinding($("#nextDocumentKeyBinding").val()));- TSCORE.Config.setPrevDocumentKeyBinding(parseKeyBinding($("#prevDocumentKeyBinding").val()));- TSCORE.Config.setCloseViewerKeyBinding(parseKeyBinding($("#closeDocumentKeyBinding").val()));- TSCORE.Config.setAddRemoveTagsKeyBinding(parseKeyBinding($("#addRemoveTagsKeyBinding").val()));- TSCORE.Config.setEditDocumentKeyBinding(parseKeyBinding($("#editDocumentKeyBinding").val()));- TSCORE.Config.setReloadDocumentKeyBinding(parseKeyBinding($("#reloadDocumentKeyBinding").val()));- TSCORE.Config.setSaveDocumentKeyBinding(parseKeyBinding($("#saveDocumentKeyBinding").val()));- TSCORE.Config.setPropertiesDocumentKeyBinding(parseKeyBinding($("#documentPropertiesKeyBinding").val()));-- var interfaceLang = $("#languagesList").val();- TSCORE.Config.setInterfaceLangauge(interfaceLang);- TSCORE.switchInterfaceLanguage(interfaceLang);-- TSCORE.Config.setPerspectives(collectPerspectivesData());- TSCORE.Config.setSupportedFileTypes(collectSupportedFileTypesData());-- TSCORE.Config.saveSettings();- }-- function collectPerspectivesData() {- var data = [];- $('#perspectiveList').children().each( function(index, element) {- if($(element).find("select").val() != "false") {- data.push({- "id":$(element).find("select").val()- });- }- }- );- return data;- }-- function collectSupportedFileTypesData() {- var data = [];- $('#fileTypesList').children().each( function(index, element) {- // Skiping the first line with the descriptions- if(index > 0) {- data.push({- "type": $(element).find("input").val(),- "viewer": $(element).find(".ftviewer").val(),- "editor": $(element).find(".fteditor").val()- });- }- }- );- return data;- }-- // Public Methods- exports.initUI = initUI;- exports.reInitUI = reInitUI;--});\ No newline at end of file+/* 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. */+/* global define, Mousetrap, Handlebars */+define(function(require, exports, module) {+ 'use strict';+ console.log('Loading options.ui.js ...');+ var TSCORE = require('tscore');+ require(['libs/filesaver.js/FileSaver.js'], function() {});++ function generateSelectOptions(parent, data, selectedId) {+ parent.empty();+ parent.append($('<option>').text('').val('false'));+ data.forEach(function(value) {+ if (selectedId === value) {+ parent.append($('<option>').attr('selected', 'selected').text(value).val(value));+ } else {+ parent.append($('<option>').text(value).val(value));+ }+ });+ }++ function addPerspective(parent, perspectiveId) {+ var perspectiveControl = $('<div class=\'form-inline\'>').append($('<div class=\'input-group\' style=\'width: 90%\'>').append($('<select class=\'form-control\' style=\'width: 70%\'></select>')).append($('<button class=\'btn btn-default\' style=\'width: 40px\' data-i18n=\'[title]ns.dialogs:removePerspectiveTooltip\'><i class=\'fa fa-times\'></button>').click(function() {+ $(this).parent().parent().remove();+ }))).i18n();+ generateSelectOptions(perspectiveControl.find('select'), TSCORE.Config.getPerspectiveExtensions(), perspectiveId);+ parent.append(perspectiveControl);+ }++ function addFileType(parent, fileext, viewerId, editorId) {+ var fileTypeControl = $('<div class=\'form-inline\'>').append($('<div class=\'input-group\' >').append($('<input style=\'width: 80px\' type=\'text\' class=\'form-control\' data-i18n=\'[placeholder]ns.dialogs:fileExtensionPlaceholder\'>').val(fileext)).append($('<select class=\'ftviewer form-control\' style=\'width: 170px\'></select>')).append($('<select class=\'fteditor form-control\' style=\'width: 170px\'></select>')).append($('<button style=\'width: 40px\' class=\'btn btn-default\' data-i18n=\'[title]ns.dialogs:removeFileTypeTooltip\'><i class=\'fa fa-times\'></button>').click(function() {+ $(this).parent().parent().remove();+ }))).i18n();+ generateSelectOptions(fileTypeControl.find('.ftviewer'), TSCORE.Config.getViewerExtensions(), viewerId);+ generateSelectOptions(fileTypeControl.find('.fteditor'), TSCORE.Config.getEditorExtensions(), editorId);+ parent.append(fileTypeControl);+ }++ function initUI() {+ $('#addFileTypeButton').click(function(e) {+ // Fixes reloading of the application by click+ e.preventDefault();+ addFileType($('#fileTypesList'), '', '', '');+ });+ $('#addPerspectiveButton').click(function(e) {+ // Fixes reloading of the application by click+ e.preventDefault();+ addPerspective($('#perspectiveList'), '');+ });+ $('#saveSettingsCloseButton').click(function() {+ updateSettings();+ $('#dialogOptions').modal('hide'); //TSCORE.reloadUI();+ });+ $('#defaultSettingsButton').click(function() {+ TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:restoreDefaulSettingTitleConfirm'), $.i18n.t('ns.dialogs:restoreDefaulSettingMessageConfirm'), function() {+ TSCORE.Config.loadDefaultSettings();+ });+ });+ $('#keyBindingInstructions').toggle();+ $('#keyBindingInstructionsToggle').on('click', function() {+ $('#keyBindingInstructions').toggle();+ return false;+ });+ if (isCordova) {+ $('#exportTagGroupsButton').hide();+ }+ $('#exportTagGroupsButton').click(function() {+ var jsonFormat = '{ "appName": "' + TSCORE.Config.DefaultSettings.appName ++ '", "appVersion": "' + TSCORE.Config.DefaultSettings.appVersion ++ '", "appBuild": "' + TSCORE.Config.DefaultSettings.appBuild ++ '", "settingsVersion": ' + TSCORE.Config.DefaultSettings.settingsVersion ++ ', "tagGroups": ';+ var blob = new Blob([jsonFormat + JSON.stringify(TSCORE.Config.getAllTagGroupData()) + '}'], {+ type: 'application/json'+ });+ saveAs(blob, 'tsm[' + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + '].json');+ console.log('Group Data Saved...');+ });+ }++ function reInitUI() {+ $('#extensionsPathInput').val(TSCORE.Config.getExtensionPath());+ $('#showHiddenFilesCheckbox').attr('checked', TSCORE.Config.getShowUnixHiddenEntries());+ $('#showMainMenuCheckbox').attr('checked', TSCORE.Config.getShowMainMenu());+ $('#checkforUpdatesCheckbox').attr('checked', TSCORE.Config.getCheckForUpdates());+ $('#calculateTagsCheckbox').attr('checked', TSCORE.Config.getCalculateTags());+ $('#loadLocationMetaData').attr('checked', TSCORE.Config.getLoadLocationMeta());+ $('#tagsDelimiterInput').val(TSCORE.Config.getTagDelimiter());+ $('#prefixTagContainerInput').val(TSCORE.Config.getPrefixTagContainer());+ $('#nextDocumentKeyBinding').val(TSCORE.Config.getNextDocumentKeyBinding());+ $('#prevDocumentKeyBinding').val(TSCORE.Config.getPrevDocumentKeyBinding());+ $('#closeDocumentKeyBinding').val(TSCORE.Config.getCloseViewerKeyBinding());+ $('#addRemoveTagsKeyBinding').val(TSCORE.Config.getAddRemoveTagsKeyBinding());+ $('#editDocumentKeyBinding').val(TSCORE.Config.getEditDocumentKeyBinding());+ $('#reloadDocumentKeyBinding').val(TSCORE.Config.getReloadDocumentKeyBinding());+ $('#saveDocumentKeyBinding').val(TSCORE.Config.getSaveDocumentKeyBinding());+ $('#documentPropertiesKeyBinding').val(TSCORE.Config.getPropertiesDocumentKeyBinding());+ $('#perspectiveList').empty();+ TSCORE.Config.getPerspectives().forEach(function(value) {+ addPerspective($('#perspectiveList'), value.id);+ });+ var $languagesDropdown = $('#languagesList');+ $languagesDropdown.empty();+ TSCORE.Config.getSupportedLanguages().forEach(function(value) {+ if (TSCORE.Config.getInterfaceLangauge() === value.iso) {+ $languagesDropdown.append($('<option>').attr('selected', 'selected').text(value.title).val(value.iso));+ } else {+ $languagesDropdown.append($('<option>').text(value.title).val(value.iso));+ }+ });+ $('#fileTypesList').empty().append($('<div class=\'input-group\' >').append($('<span style=\'width: 80px; border: 0\' class=\'form-control\' data-i18n=\'ns.dialogs:fileExtension\'></span>')).append($('<span style=\' border: 0; width: 170px\' class=\'ftviewer form-control\' data-i18n=\'ns.dialogs:fileViewer\'></span>')).append($('<span style=\' border: 0; width: 170px\' class=\'fteditor form-control\' data-i18n=\'ns.dialogs:fileEditor\'></span>'))).i18n();+ TSCORE.Config.getSupportedFileTypes().sort(function(a, b) {+ if (a.type > b.type) {+ return 1;+ }+ if (a.type < b.type) {+ return -1;+ }+ return 0;+ }).forEach(function(value) {+ addFileType($('#fileTypesList'), value.type, value.viewer, value.editor);+ });+ $('#dialogOptions a:first').tab('show');+ $('#dialogOptions').modal({+ backdrop: 'static',+ show: true+ });+ }++ function parseKeyBinding(keybinding) {+ keybinding = keybinding.trim();+ if (keybinding.indexOf(',') >= 0) {+ keybinding = keybinding.split(',');+ }+ return keybinding;+ }++ function updateSettings() {+ TSCORE.Config.setExtensionPath($('#extensionsPathInput').val());+ TSCORE.Config.setShowUnixHiddenEntries($('#showHiddenFilesCheckbox').is(':checked'));+ TSCORE.Config.setShowMainMenu($('#showMainMenuCheckbox').is(':checked'));+ TSCORE.Config.setCheckForUpdates($('#checkforUpdatesCheckbox').is(':checked'));+ TSCORE.Config.setCalculateTags($('#calculateTagsCheckbox').is(':checked'));+ TSCORE.Config.setTagDelimiter($('#tagsDelimiterInput').val());+ TSCORE.Config.setPrefixTagContainer($('#prefixTagContainerInput').val());+ TSCORE.Config.setLoadLocationMeta($('#loadLocationMetaData').is(':checked'));+ TSCORE.Config.setNextDocumentKeyBinding(parseKeyBinding($('#nextDocumentKeyBinding').val()));+ TSCORE.Config.setPrevDocumentKeyBinding(parseKeyBinding($('#prevDocumentKeyBinding').val()));+ TSCORE.Config.setCloseViewerKeyBinding(parseKeyBinding($('#closeDocumentKeyBinding').val()));+ TSCORE.Config.setAddRemoveTagsKeyBinding(parseKeyBinding($('#addRemoveTagsKeyBinding').val()));+ TSCORE.Config.setEditDocumentKeyBinding(parseKeyBinding($('#editDocumentKeyBinding').val()));+ TSCORE.Config.setReloadDocumentKeyBinding(parseKeyBinding($('#reloadDocumentKeyBinding').val()));+ TSCORE.Config.setSaveDocumentKeyBinding(parseKeyBinding($('#saveDocumentKeyBinding').val()));+ TSCORE.Config.setPropertiesDocumentKeyBinding(parseKeyBinding($('#documentPropertiesKeyBinding').val()));++ var interfaceLang = $('#languagesList').val();+ TSCORE.Config.setInterfaceLangauge(interfaceLang);+ TSCORE.switchInterfaceLanguage(interfaceLang);+ TSCORE.Config.setPerspectives(collectPerspectivesData());+ TSCORE.Config.setSupportedFileTypes(collectSupportedFileTypesData());+ TSCORE.Config.saveSettings();+ }++ function collectPerspectivesData() {+ var data = [];+ $('#perspectiveList').children().each(function(index, element) {+ if ($(element).find('select').val() != 'false') {+ data.push({+ 'id': $(element).find('select').val()+ });+ }+ });+ return data;+ }++ function collectSupportedFileTypesData() {+ var data = [];+ $('#fileTypesList').children().each(function(index, element) {+ // Skiping the first line with the descriptions+ if (index > 0) {+ data.push({+ 'type': $(element).find('input').val(),+ 'viewer': $(element).find('.ftviewer').val(),+ 'editor': $(element).find('.fteditor').val()+ });+ }+ });+ return data;+ }++ // Public Methods+ exports.initUI = initUI;+ exports.reInitUI = reInitUI;+});diff --git a/data/js/perspective.manager.js b/data/js/perspective.manager.jsindex 4f1df92f3..56306e4aa 100644--- a/data/js/perspective.manager.js+++ b/data/js/perspective.manager.js@@ -1,329 +1,285 @@-/* 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. */-define(function(require, exports, module) {-"use strict";--console.log("Loading perspective.manager.js ...");--var perspectives;--var TSCORE = require("tscore");--var initPerspectives = function () {-- perspectives = [];-- $("#viewSwitcher").empty();- $("#viewToolbars").empty();- $("#viewContainers").empty();- $("#viewFooters").empty();-- initWelcomeScreen();-- var extensions = TSCORE.Config.getPerspectives();- for (var i=0; i < extensions.length; i++) {-- // TODO Some libraries such as ace editor are not working using paths like this "file:///C:/blabal/extension.js"- var extPath = TSCORE.Config.getExtensionPath()+"/"+extensions[i].id+"/extension.js";-- require([extPath], function(perspective) {- perspectives.push(perspective);- try {- // Creating perspective's toolbar- $("#viewToolbars").append($("<div>", {- id: perspective.ID+"Toolbar",- class: "btn-toolbar"- }).hide());-- // Creating perspective's container- $("#viewContainers").append($("<div>", {- id: perspective.ID+"Container",- style: "width: 100%; height: 100%"- }).hide());-- // Creating perspective's footer- $("#viewFooters").append($("<div>", {- id: perspective.ID+"Footer"- }).hide());- perspective.init();- } catch(e) {- console.log("Error while executing 'init' on "+perspectives[i].ID+" - "+e);- } finally {- if( perspectives.length === extensions.length) {- initPerspectiveSwitcher();-- // Opening last saved location by the start of the application (not in firefox)- var lastLocation = TSCORE.Config.getLastOpenedLocation();- if(lastLocation !== undefined && lastLocation.length > 1 && !isFirefox) {- TSCORE.openLocation(lastLocation);- TSCORE.IO.checkAccessFileURLAllowed();- }-- $( "#loading" ).hide();- }- }- });- }-};--var initWelcomeScreen = function() {- /* require([- "text!templates/WelcomeScreen.html",- ], function(uiTPL) {- // Check if dialog already created- if($("#dialogLocationEdit").length < 1) {- var uiTemplate = Handlebars.compile( uiTPL );- $("#viewContainers").append(uiTemplate());- }- }); */- $("#viewContainers").append('<div id="welcomeScreen"></div>');-};--var initPerspectiveSwitcher = function() {- var extensions = TSCORE.Config.getPerspectives();- var $viewSwitcher = $("#viewSwitcher");- $viewSwitcher.empty();- $viewSwitcher.append($('<li>', {- class: "dropdown-header",- text: $.i18n.t("ns.common:perspectiveSwitch")- })- .append('<button type="button" class="close">×</button>')- );- $viewSwitcher.append("<li class='divider'></li>");- for (var i=0; i < extensions.length; i++) {- var curPers;- // Finding the right perspective- perspectives.forEach(function(value) {- if(value.ID === extensions[i].id) {- curPers = value;- }- });-- $viewSwitcher.append($("<li>", {})- .append($("<a>", {- "viewid": curPers.ID,- "title": curPers.ID,- "id": curPers.ID+"Button",- "text": curPers.Title- })- .prepend($("<i>", {- "class": curPers.Icon+" fa-lg",- "style": "margin-right: 15px"- }))));-- // Adding event listener & icon to the radio button- $( "#"+curPers.ID+"Button" ).click(function() {- changePerspective($(this).attr("viewid"));- });- }-};--var redrawCurrentPerspective = function () {- for (var i=0; i < perspectives.length; i++) {- if(perspectives[i].ID === TSCORE.currentPerspectiveID) {- try {- perspectives[i].load();- break;- } catch(e) {- console.error("Error while executing 'redrawCurrentPerspective' on "+perspectives[i].ID+" "+e);- }- }- }-};--var removeFileUI = function (filePath) {- console.log("Removing file from perspectives");- for (var i=0; i < perspectives.length; i++) {- try {- perspectives[i].removeFileUI(filePath);- } catch(e) {- console.error("Error while executing 'removeFileUI' on "+perspectives[i].ID+" "+e);- }- }-};--var updateFileUI = function (oldFilePath,newFilePath) {- console.log("Updating file in perspectives");- for (var i=0; i < perspectives.length; i++) {- try {- perspectives[i].updateFileUI(oldFilePath, newFilePath);- } catch(e) {- console.error("Error while executing 'updateFileUI' on "+perspectives[i].ID+" "+e);- }- }-};--var getNextFile = function (filePath) {- for (var i=0; i < perspectives.length; i++) {- if(perspectives[i].ID === TSCORE.currentPerspectiveID) {- try {- return perspectives[i].getNextFile(filePath);- } catch(e) {- console.error("Error while executing 'getNextFile' on "+perspectives[i].ID+" "+e);- }- }- }-};--var getPrevFile = function (filePath) {- for (var i=0; i < perspectives.length; i++) {- if(perspectives[i].ID === TSCORE.currentPerspectiveID) {- try {- return perspectives[i].getPrevFile(filePath);- } catch(e) {- console.error("Error while executing 'getPrevFile' on "+perspectives[i].ID+" "+e);- }- }- }-};--var updateTreeData = function (treeData) {- for (var i=0; i < perspectives.length; i++) {- try {- perspectives[i].updateTreeData(treeData);- } catch(e) {- console.error("Error while executing 'updateTreeData' on "+perspectives[i].ID+" "+e);- }- }-};--var updateFileBrowserData = function(dirList) {- console.log("Updating the file browser data...");-- TSCORE.fileList = [];- var tags,- ext,- title,- fileSize,- fileLMDT,- path,- filename,- entry;-- for (var i=0; i < dirList.length; i++) {- // Considering Unix HiddenEntries (. in the beginning of the filename)- if (TSCORE.Config.getShowUnixHiddenEntries() ||- (!TSCORE.Config.getShowUnixHiddenEntries() && (dirList[i].path.indexOf(TSCORE.dirSeparator+".") < 0))) {- filename = dirList[i].name.replace(/(<([^>]+)>)/ig,""); // sanitizing filename- path = dirList[i].path.replace(/(<([^>]+)>)/ig,""); // sanitizing filepath- title = TSCORE.TagUtils.extractTitle(path);-- if (dirList[i].isFile){- ext = TSCORE.TagUtils.extractFileExtension(path);- tags = TSCORE.TagUtils.extractTags(path);- fileSize = dirList[i].size;- fileLMDT = dirList[i].lmdt;-- if(fileSize == undefined) { fileSize = "" };- if(fileLMDT == undefined) { fileLMDT = "" };- entry = [ext,title,tags,fileSize,fileLMDT,path,filename];- TSCORE.fileList.push(entry);- } else {- entry = [path,filename];- TSCORE.subDirsList.push(entry);- }- }- }- changePerspective(TSCORE.currentPerspectiveID);-};--var refreshFileListContainer = function() {- // TODO consider search view- TSCORE.IO.listDirectory(TSCORE.currentPath);-};--var hideAllPerspectives = function() {- $( "#welcomeScreen" ).hide();- for (var i=0; i < perspectives.length; i++) {- $( "#"+perspectives[i].ID+"Container" ).hide();- $( "#"+perspectives[i].ID+"Toolbar" ).hide();- $( "#"+perspectives[i].ID+"Footer" ).hide();- }-};--var changePerspective = function (viewType) {- console.log("Change to "+viewType+" perspective.");- TSCORE.showLoadingAnimation();-- // Loading first perspective by default- if(viewType == undefined) {- TSCORE.currentPerspectiveID = perspectives[0].ID;- } else {- //Setting the current view- TSCORE.currentPerspectiveID = viewType;- }-- if(TSCORE.currentPerspectiveID == undefined) {- TSCORE.showAlertDialog("No Perspectives found","");- return false;- }-- hideAllPerspectives();-- for (var i=0; i < perspectives.length; i++) {- if(perspectives[i].ID === viewType) {- var $currentPerspectitveIcon = $('#currentPerspectitveIcon'),- $currentPerspectitveName = $('#currentPerspectitveName');-- $currentPerspectitveIcon.removeClass();- $currentPerspectitveIcon.addClass(perspectives[i].Icon);- $currentPerspectitveIcon.addClass("fa-lg");- $currentPerspectitveName.text(" "+perspectives[i].Title);- $currentPerspectitveName.attr("title",perspectives[i].ID);-- perspectives[i].load();-- $( "#"+perspectives[i].ID+"Container" ).show();- $( "#"+perspectives[i].ID+"Toolbar" ).show();- $( "#"+perspectives[i].ID+"Footer" ).show();- }- }-- // Clear the list with the selected files- clearSelectedFiles();-- // Enabled the main toolbar e.g. search functionality- TSCORE.enableTopToolbar();-- TSCORE.hideLoadingAnimation();-};--var clearSelectedFiles = function () {- // Clear selected files- TSCORE.selectedFiles = [];- for (var i=0; i < perspectives.length; i++) {- try {- perspectives[i].clearSelectedFiles();- } catch(e) {- console.error("Error while executing 'clearSelectedFiles' on "+perspectives[i].ID+" - "+e);- }- }-};--/*var generateDesktop = function () {- for (var i=0; i < perspectives.length; i++) {- try {- perspectives[i].generateDesktop();- } catch(e) {- console.error("Error while executing 'generateDesktop' on "+perspectives[i].ID+" - "+e);- }- }-};*/---exports.initPerspectives = initPerspectives;-exports.hideAllPerspectives = hideAllPerspectives;-exports.redrawCurrentPerspective = redrawCurrentPerspective;-exports.getNextFile = getNextFile;-exports.getPrevFile = getPrevFile;-exports.updateTreeData = updateTreeData;-exports.updateFileBrowserData = updateFileBrowserData;-exports.refreshFileListContainer = refreshFileListContainer;-exports.clearSelectedFiles = clearSelectedFiles;-exports.removeFileUI = removeFileUI;-exports.updateFileUI = updateFileUI;-exports.changePerspective = changePerspective;-//exports.generateDesktop = generateDesktop;--});\ No newline at end of file+/* 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. */+define(function(require, exports, module) {+ 'use strict';+ console.log('Loading perspective.manager.js ...');+ var perspectives;+ var TSCORE = require('tscore');+ var initPerspectives = function() {+ perspectives = [];+ $('#viewSwitcher').empty();+ $('#viewToolbars').empty();+ $('#viewContainers').empty();+ $('#viewFooters').empty();+ initWelcomeScreen();+ var extensions = TSCORE.Config.getPerspectives();+ for (var i = 0; i < extensions.length; i++) {+ // TODO Some libraries such as ace editor are not working using paths like this "file:///C:/blabal/extension.js"+ var extPath = TSCORE.Config.getExtensionPath() + '/' + extensions[i].id + '/extension.js';+ require([extPath], function(perspective) {+ perspectives.push(perspective);+ try {+ // Creating perspective's toolbar+ $('#viewToolbars').append($('<div>', {+ id: perspective.ID + 'Toolbar',+ class: 'btn-toolbar'+ }).hide());+ // Creating perspective's container+ $('#viewContainers').append($('<div>', {+ id: perspective.ID + 'Container',+ style: 'width: 100%; height: 100%'+ }).hide());+ // Creating perspective's footer+ $('#viewFooters').append($('<div>', {+ id: perspective.ID + 'Footer'+ }).hide());+ perspective.init();+ } catch (e) {+ console.log('Error while executing \'init\' on ' + perspectives[i].ID + ' - ' + e);+ } finally {+ if (perspectives.length === extensions.length) {+ initPerspectiveSwitcher();+ // Opening last saved location by the start of the application (not in firefox)+ var lastLocation = TSCORE.Config.getLastOpenedLocation();+ if (lastLocation !== undefined && lastLocation.length > 1 && !isFirefox) {+ TSCORE.openLocation(lastLocation);+ TSCORE.IO.checkAccessFileURLAllowed();+ }+ $('#loading').hide();+ }+ }+ }); // jshint ignore:line+ }+ };+ var initWelcomeScreen = function() {+ /* require([+ "text!templates/WelcomeScreen.html",+ ], function(uiTPL) {+ // Check if dialog already created+ if($("#dialogLocationEdit").length < 1) {+ var uiTemplate = Handlebars.compile( uiTPL );+ $("#viewContainers").append(uiTemplate());+ }+ }); */+ $('#viewContainers').append('<div id="welcomeScreen"></div>');+ };+ var initPerspectiveSwitcher = function() {+ var extensions = TSCORE.Config.getPerspectives();+ var $viewSwitcher = $('#viewSwitcher');+ $viewSwitcher.empty();+ $viewSwitcher.append($('<li>', {+ class: 'dropdown-header',+ text: $.i18n.t('ns.common:perspectiveSwitch')+ }).append('<button type="button" class="close">\xD7</button>'));+ $viewSwitcher.append('<li class=\'divider\'></li>');+ for (var i = 0; i < extensions.length; i++) {+ var curPers;+ // Finding the right perspective+ perspectives.forEach(function(value) {+ if (value.ID === extensions[i].id) {+ curPers = value;+ }+ }); // jshint ignore:line+ $viewSwitcher.append($('<li>', {}).append($('<a>', {+ 'viewid': curPers.ID,+ 'title': curPers.ID,+ 'id': curPers.ID + 'Button',+ 'text': curPers.Title+ }).prepend($('<i>', {+ 'class': curPers.Icon + ' fa-lg',+ 'style': 'margin-right: 15px'+ }))));+ // Adding event listener & icon to the radio button+ $('#' + curPers.ID + 'Button').click(function() {+ changePerspective($(this).attr('viewid'));+ }); // jshint ignore:line+ }+ };+ var redrawCurrentPerspective = function() {+ for (var i = 0; i < perspectives.length; i++) {+ if (perspectives[i].ID === TSCORE.currentPerspectiveID) {+ try {+ perspectives[i].load();+ break;+ } catch (e) {+ console.error('Error while executing \'redrawCurrentPerspective\' on ' + perspectives[i].ID + ' ' + e);+ }+ }+ }+ };+ var removeFileUI = function(filePath) {+ console.log('Removing file from perspectives');+ for (var i = 0; i < perspectives.length; i++) {+ try {+ perspectives[i].removeFileUI(filePath);+ } catch (e) {+ console.error('Error while executing \'removeFileUI\' on ' + perspectives[i].ID + ' ' + e);+ }+ }+ };+ var updateFileUI = function(oldFilePath, newFilePath) {+ console.log('Updating file in perspectives');+ for (var i = 0; i < perspectives.length; i++) {+ try {+ perspectives[i].updateFileUI(oldFilePath, newFilePath);+ } catch (e) {+ console.error('Error while executing \'updateFileUI\' on ' + perspectives[i].ID + ' ' + e);+ }+ }+ };+ var getNextFile = function(filePath) {+ for (var i = 0; i < perspectives.length; i++) {+ if (perspectives[i].ID === TSCORE.currentPerspectiveID) {+ try {+ return perspectives[i].getNextFile(filePath);+ } catch (e) {+ console.error('Error while executing \'getNextFile\' on ' + perspectives[i].ID + ' ' + e);+ }+ }+ }+ };+ var getPrevFile = function(filePath) {+ for (var i = 0; i < perspectives.length; i++) {+ if (perspectives[i].ID === TSCORE.currentPerspectiveID) {+ try {+ return perspectives[i].getPrevFile(filePath);+ } catch (e) {+ console.error('Error while executing \'getPrevFile\' on ' + perspectives[i].ID + ' ' + e);+ }+ }+ }+ };+ var updateTreeData = function(treeData) {+ for (var i = 0; i < perspectives.length; i++) {+ try {+ perspectives[i].updateTreeData(treeData);+ } catch (e) {+ console.error('Error while executing \'updateTreeData\' on ' + perspectives[i].ID + ' ' + e);+ }+ }+ };+ var updateFileBrowserData = function(dirList) {+ console.log('Updating the file browser data...');+ TSCORE.fileList = [];+ var tags, ext, title, fileSize, fileLMDT, path, filename, entry;+ for (var i = 0; i < dirList.length; i++) {+ // Considering Unix HiddenEntries (. in the beginning of the filename)+ if (TSCORE.Config.getShowUnixHiddenEntries() || !TSCORE.Config.getShowUnixHiddenEntries() && dirList[i].path.indexOf(TSCORE.dirSeparator + '.') < 0) {+ filename = dirList[i].name.replace(/(<([^>]+)>)/gi, ''); // sanitizing filename+ path = dirList[i].path.replace(/(<([^>]+)>)/gi, ''); // sanitizing filepath+ title = TSCORE.TagUtils.extractTitle(path);++ if (dirList[i].isFile) {+ ext = TSCORE.TagUtils.extractFileExtension(path);+ tags = TSCORE.TagUtils.extractTags(path);+ fileSize = dirList[i].size;+ fileLMDT = dirList[i].lmdt;+ if (fileSize === undefined) {+ fileSize = '';+ }+ if (fileLMDT === undefined) {+ fileLMDT = '';+ }+ entry = [+ ext,+ title,+ tags,+ fileSize,+ fileLMDT,+ path,+ filename+ ];+ TSCORE.fileList.push(entry);+ } else {+ entry = [+ path,+ filename+ ];+ TSCORE.subDirsList.push(entry);+ }+ }+ }+ changePerspective(TSCORE.currentPerspectiveID);+ };+ var refreshFileListContainer = function() {+ // TODO consider search view+ TSCORE.IO.listDirectory(TSCORE.currentPath);+ };+ var hideAllPerspectives = function() {+ $('#welcomeScreen').hide();+ for (var i = 0; i < perspectives.length; i++) {+ $('#' + perspectives[i].ID + 'Container').hide();+ $('#' + perspectives[i].ID + 'Toolbar').hide();+ $('#' + perspectives[i].ID + 'Footer').hide();+ }+ };+ var changePerspective = function(viewType) {+ console.log('Change to ' + viewType + ' perspective.');+ TSCORE.showLoadingAnimation();+ // Loading first perspective by default+ if (viewType === undefined) {+ TSCORE.currentPerspectiveID = perspectives[0].ID;+ } else {+ //Setting the current view+ TSCORE.currentPerspectiveID = viewType;+ }+ if (TSCORE.currentPerspectiveID === undefined) {+ TSCORE.showAlertDialog('No Perspectives found', '');+ return false;+ }+ hideAllPerspectives();+ for (var i = 0; i < perspectives.length; i++) {+ if (perspectives[i].ID === viewType) {+ var $currentPerspectitveIcon = $('#currentPerspectitveIcon'),+ $currentPerspectitveName = $('#currentPerspectitveName');+ $currentPerspectitveIcon.removeClass();+ $currentPerspectitveIcon.addClass(perspectives[i].Icon);+ $currentPerspectitveIcon.addClass('fa-lg');+ $currentPerspectitveName.text(' ' + perspectives[i].Title);+ $currentPerspectitveName.attr('title', perspectives[i].ID);+ perspectives[i].load();+ $('#' + perspectives[i].ID + 'Container').show();+ $('#' + perspectives[i].ID + 'Toolbar').show();+ $('#' + perspectives[i].ID + 'Footer').show();+ }+ }+ // Clear the list with the selected files+ clearSelectedFiles();+ // Enabled the main toolbar e.g. search functionality+ TSCORE.enableTopToolbar();+ TSCORE.hideLoadingAnimation();+ };+ var clearSelectedFiles = function() {+ // Clear selected files+ TSCORE.selectedFiles = [];+ for (var i = 0; i < perspectives.length; i++) {+ try {+ perspectives[i].clearSelectedFiles();+ } catch (e) {+ console.error('Error while executing \'clearSelectedFiles\' on ' + perspectives[i].ID + ' - ' + e);+ }+ }+ };+ /*var generateDesktop = function () {+ for (var i=0; i < perspectives.length; i++) {+ try {+ perspectives[i].generateDesktop();+ } catch(e) {+ console.error("Error while executing 'generateDesktop' on "+perspectives[i].ID+" - "+e);+ }+ }+};*/+ exports.initPerspectives = initPerspectives;+ exports.hideAllPerspectives = hideAllPerspectives;+ exports.redrawCurrentPerspective = redrawCurrentPerspective;+ exports.getNextFile = getNextFile;+ exports.getPrevFile = getPrevFile;+ exports.updateTreeData = updateTreeData;+ exports.updateFileBrowserData = updateFileBrowserData;+ exports.refreshFileListContainer = refreshFileListContainer;+ exports.clearSelectedFiles = clearSelectedFiles;+ exports.removeFileUI = removeFileUI;+ exports.updateFileUI = updateFileUI;+ exports.changePerspective = changePerspective; //exports.generateDesktop = generateDesktop;+});diff --git a/data/js/postioapi.js b/data/js/postioapi.jsindex b482fc23c..1fd3d8c12 100644--- a/data/js/postioapi.js+++ b/data/js/postioapi.js@@ -1,167 +1,157 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that+/* 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. */define(function(require, exports, module) {-"use strict";-- // Activating browser specific exports modul- console.log("Loading postioapi.js ...");-- var TSCORE = require("tscore");-- exports.createDirectoryIndex = function(directoryIndex) {- console.log("Directory index created");- TSCORE.PerspectiveManager.updateFileBrowserData(directoryIndex);- TSCORE.hideWaitingDialog();- };-- exports.createDirectoryTree = function(directoyTree) {- TSCORE.PerspectiveManager.updateTreeData(directoyTree);- TSCORE.hideWaitingDialog();- };-- exports.createDirectory = function(dirPath) {- TSCORE.navigateToDirectory(dirPath);- TSCORE.hideWaitingDialog();- };-- exports.copyFile = function(sourceFilePath, targetFilePath) {- var targetDirectory = TSCORE.TagUtils.extractContainingDirectoryPath(targetFilePath);- if(targetDirectory === TSCORE.currentPath) {- TSCORE.navigateToDirectory(TSCORE.currentPath);- TSCORE.PerspectiveManager.clearSelectedFiles();- }- TSCORE.hideWaitingDialog();- };-- exports.renameFile = function(oldFilePath, newFilePath) {- var lastOpenedFile = TSCORE.FileOpener.getOpenedFilePath();- if(lastOpenedFile != undefined) {- console.log("Last opened Filename: "+lastOpenedFile);- // TODO handle case in which a file opened for editing and a tag has been added / file renamed- if(TSCORE.FileOpener.isFileOpened() && (oldFilePath == lastOpenedFile) ) {- TSCORE.FileOpener.openFile(newFilePath);- }- }-- var oldFileContainingPath = TSCORE.TagUtils.extractContainingDirectoryPath(oldFilePath),- newFileConaintingPath = TSCORE.TagUtils.extractContainingDirectoryPath(newFilePath);- if(oldFileContainingPath !== newFileConaintingPath) {- // File was moved- // TODO consider case - file was moved in subdir shown in the recursive search results- //TSCORE.removeFileModel(TSCORE.fileList, oldFilePath);- //TSCORE.PerspectiveManager.removeFileUI(oldFilePath);- TSCORE.navigateToDirectory(TSCORE.currentPath);- } else {- // File was renamed- TSCORE.updateFileModel(TSCORE.fileList, oldFilePath, newFilePath);- TSCORE.PerspectiveManager.updateFileUI(oldFilePath, newFilePath);- }- TSCORE.hideWaitingDialog();- //TSCORE.PerspectiveManager.clearSelectedFiles();- };-- exports.renameDirectory = function(dirOldPath, dirNewPath) {- TSCORE.navigateToDirectory(dirNewPath);- TSCORE.hideLoadingAnimation();- };-- exports.loadTextFile = function(content) {- TSCORE.FileOpener.updateEditorContent(content);- TSCORE.hideLoadingAnimation();- };-- exports.saveBinaryFile = function(filePath) {- TSCORE.PerspectiveManager.refreshFileListContainer();- };-- exports.saveTextFile = function(filePath, isNewFile) {- TSCORE.PerspectiveManager.refreshFileListContainer();-- if(isNewFile) {- // If file is new open it in edit mode- TSCORE.FileOpener.openFile(filePath, true);- }- TSCORE.FileOpener.setFileChanged(false);- };-- exports.listDirectory = function(anotatedDirList) {- TSCORE.PerspectiveManager.updateFileBrowserData(anotatedDirList);- TSCORE.updateSubDirs(anotatedDirList);- };-- exports.listSubDirectories = function(dirList, dirPath) {- console.log("Listing Subdirs: "+JSON.stringify(dirList));- TSCORE.subfoldersDirBrowser = dirList;- if(TSCORE.directoryBrowser !== undefined) {- TSCORE.directoryBrowser.reInitUI(dirPath);- }- };-- exports.errorOpeningPath = function(dirPath) {- // Normalazing the paths- var dir1 = TSCORE.TagUtils.cleanTrailingDirSeparator(TSCORE.currentLocationObject.path);- var dir2 = TSCORE.TagUtils.cleanTrailingDirSeparator(dirPath);- // Close the current location if the its path could not be opened- if(dir1 === dir2) {- TSCORE.showAlertDialog($.i18n.t("ns.dialogs:errorOpeningLocationAlert"));- TSCORE.closeCurrentLocation();- } else {- TSCORE.showAlertDialog($.i18n.t("ns.dialogs:errorOpeningPathAlert"));- }- };-- exports.deleteElement = function(filePath) {- TSCORE.removeFileModel(TSCORE.fileList, filePath);- TSCORE.PerspectiveManager.removeFileUI(filePath);- if(filePath === TSCORE.FileOpener.getOpenedFilePath()) {- TSCORE.FileOpener.closeFile(true);- }- TSCORE.hideLoadingAnimation();- };-- exports.deleteDirectory = function(dirPath) {- TSCORE.navigateToDirectory(TSCORE.TagUtils.extractParentDirectoryPath(dirPath));- TSCORE.hideLoadingAnimation();- };-- exports.deleteDirectoryFailed = function(dirPath) {- console.log("Deleting of '"+dirPath+"' failed");- TSCORE.showAlertDialog($.i18n.t("ns.dialogs:errorDeletingDirectoryAlert"));- TSCORE.hideLoadingAnimation();- };-- exports.checkNewVersion = function(data) {- TSCORE.updateNewVersionData(data);- };-- exports.selectDirectory = function(dirPath) {- // TODO make the use of this function more general- if(!TSCORE.TagUtils.stringEndsWith(dirPath, TSCORE.dirSeparator)) {- dirPath = dirPath + TSCORE.dirSeparator;- }- var dirName = TSCORE.TagUtils.extractContainingDirectoryName(dirPath);- $("#connectionName").val(dirName);- $("#folderLocation").val(dirPath);- $("#folderLocation2").val(dirPath);- $("#moveCopyDirectoryPath").val(dirPath);- };-- exports.openDirectory = function(dirPath) {-- };-- exports.selectFile = function() {- console.log("File selected: "+$(this).val());- };-- exports.openExtensionsDirectory = function() {-- };-- exports.getFileProperties = function(fileProperties) {- console.log("File properties: "+JSON.stringify(fileProperties));- TSCORE.FileOpener.setFileProperties(fileProperties);- };--});\ No newline at end of file+ 'use strict';++ // Activating browser specific exports modul+ console.log('Loading postioapi.js ...');+ var TSCORE = require('tscore');+ exports.createDirectoryIndex = function(directoryIndex) {+ console.log('Directory index created');+ TSCORE.PerspectiveManager.updateFileBrowserData(directoryIndex);+ TSCORE.hideWaitingDialog();+ };++ exports.createDirectoryTree = function(directoyTree) {+ TSCORE.PerspectiveManager.updateTreeData(directoyTree);+ TSCORE.hideWaitingDialog();+ };++ exports.createDirectory = function(dirPath) {+ TSCORE.navigateToDirectory(dirPath);+ TSCORE.hideWaitingDialog();+ };++ exports.copyFile = function(sourceFilePath, targetFilePath) {+ var targetDirectory = TSCORE.TagUtils.extractContainingDirectoryPath(targetFilePath);+ if (targetDirectory === TSCORE.currentPath) {+ TSCORE.navigateToDirectory(TSCORE.currentPath);+ TSCORE.PerspectiveManager.clearSelectedFiles();+ }+ TSCORE.hideWaitingDialog();+ };++ exports.renameFile = function(oldFilePath, newFilePath) {+ var lastOpenedFile = TSCORE.FileOpener.getOpenedFilePath();+ if (lastOpenedFile !== undefined) {+ console.log('Last opened Filename: ' + lastOpenedFile);+ // TODO handle case in which a file opened for editing and a tag has been added / file renamed+ if (TSCORE.FileOpener.isFileOpened() && oldFilePath == lastOpenedFile) {+ TSCORE.FileOpener.openFile(newFilePath);+ }+ }+ var oldFileContainingPath = TSCORE.TagUtils.extractContainingDirectoryPath(oldFilePath),+ newFileConaintingPath = TSCORE.TagUtils.extractContainingDirectoryPath(newFilePath);+ if (oldFileContainingPath !== newFileConaintingPath) {+ // File was moved+ // TODO consider case - file was moved in subdir shown in the recursive search results+ //TSCORE.removeFileModel(TSCORE.fileList, oldFilePath);+ //TSCORE.PerspectiveManager.removeFileUI(oldFilePath);+ TSCORE.navigateToDirectory(TSCORE.currentPath);+ } else {+ // File was renamed+ TSCORE.updateFileModel(TSCORE.fileList, oldFilePath, newFilePath);+ TSCORE.PerspectiveManager.updateFileUI(oldFilePath, newFilePath);+ }+ TSCORE.hideWaitingDialog(); //TSCORE.PerspectiveManager.clearSelectedFiles();+ };++ exports.renameDirectory = function(dirOldPath, dirNewPath) {+ TSCORE.navigateToDirectory(dirNewPath);+ TSCORE.hideLoadingAnimation();+ };++ exports.loadTextFile = function(content) {+ TSCORE.FileOpener.updateEditorContent(content);+ TSCORE.hideLoadingAnimation();+ };++ exports.saveBinaryFile = function(filePath) {+ TSCORE.PerspectiveManager.refreshFileListContainer();+ };++ exports.saveTextFile = function(filePath, isNewFile) {+ TSCORE.PerspectiveManager.refreshFileListContainer();+ if (isNewFile) {+ // If file is new open it in edit mode+ TSCORE.FileOpener.openFile(filePath, true);+ }+ TSCORE.FileOpener.setFileChanged(false);+ };++ exports.listDirectory = function(anotatedDirList) {+ TSCORE.PerspectiveManager.updateFileBrowserData(anotatedDirList);+ TSCORE.updateSubDirs(anotatedDirList);+ };++ exports.listSubDirectories = function(dirList, dirPath) {+ console.log('Listing Subdirs: ' + JSON.stringify(dirList));+ TSCORE.subfoldersDirBrowser = dirList;+ if (TSCORE.directoryBrowser !== undefined) {+ TSCORE.directoryBrowser.reInitUI(dirPath);+ }+ };++ exports.errorOpeningPath = function(dirPath) {+ // Normalazing the paths+ var dir1 = TSCORE.TagUtils.cleanTrailingDirSeparator(TSCORE.currentLocationObject.path);+ var dir2 = TSCORE.TagUtils.cleanTrailingDirSeparator(dirPath);+ // Close the current location if the its path could not be opened+ if (dir1 === dir2) {+ TSCORE.showAlertDialog($.i18n.t('ns.dialogs:errorOpeningLocationAlert'));+ TSCORE.closeCurrentLocation();+ } else {+ TSCORE.showAlertDialog($.i18n.t('ns.dialogs:errorOpeningPathAlert'));+ }+ };++ exports.deleteElement = function(filePath) {+ TSCORE.removeFileModel(TSCORE.fileList, filePath);+ TSCORE.PerspectiveManager.removeFileUI(filePath);+ if (filePath === TSCORE.FileOpener.getOpenedFilePath()) {+ TSCORE.FileOpener.closeFile(true);+ }+ TSCORE.hideLoadingAnimation();+ };++ exports.deleteDirectory = function(dirPath) {+ TSCORE.navigateToDirectory(TSCORE.TagUtils.extractParentDirectoryPath(dirPath));+ TSCORE.hideLoadingAnimation();+ };++ exports.deleteDirectoryFailed = function(dirPath) {+ console.log('Deleting of \'' + dirPath + '\' failed');+ TSCORE.showAlertDialog($.i18n.t('ns.dialogs:errorDeletingDirectoryAlert'));+ TSCORE.hideLoadingAnimation();+ };++ exports.checkNewVersion = function(data) {+ TSCORE.updateNewVersionData(data);+ };++ exports.selectDirectory = function(dirPath) {+ // TODO make the use of this function more general+ if (!TSCORE.TagUtils.stringEndsWith(dirPath, TSCORE.dirSeparator)) {+ dirPath = dirPath + TSCORE.dirSeparator;+ }+ var dirName = TSCORE.TagUtils.extractContainingDirectoryName(dirPath);+ $('#connectionName').val(dirName);+ $('#folderLocation').val(dirPath);+ $('#folderLocation2').val(dirPath);+ $('#moveCopyDirectoryPath').val(dirPath);+ };++ exports.openDirectory = function(dirPath) {};++ exports.selectFile = function() {+ console.log('File selected: ' + $(this).val());+ };++ exports.openExtensionsDirectory = function() {};++ exports.getFileProperties = function(fileProperties) {+ console.log('File properties: ' + JSON.stringify(fileProperties));+ TSCORE.FileOpener.setFileProperties(fileProperties);+ };+});diff --git a/data/js/search.js b/data/js/search.jsindex aae492a89..c2c5fa63f 100644--- a/data/js/search.js+++ b/data/js/search.js@@ -1,159 +1,152 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that+/* 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. */define(function(require, exports, module) {-"use strict";-- console.log("Loading search.js ...");-- var TSCORE = require("tscore");- var currentQuery = "";- var nextQuery = "";-- var search4Tag = function(tagQuery) {- TSCORE.Search.nextQuery = "+"+tagQuery;- $("#searchBox").val("+"+tagQuery);- TSCORE.PerspectiveManager.redrawCurrentPerspective();- TSCORE.showSearchArea();- };-- var search4String = function(query) {- TSCORE.Search.nextQuery = "+"+query;- $("#searchBox").val("+"+query);- TSCORE.PerspectiveManager.redrawCurrentPerspective();- TSCORE.showSearchArea();- };-- var calculateTags = function(data) {- console.log("Calculating tags from search results");- var allTags = [];-- data.forEach(function(fileEntry) {- fileEntry[TSCORE.fileListTAGS].forEach(function(tag) {- allTags.push(tag.toLowerCase());- });- });-- var countData = _.countBy(allTags, function(obj){- return obj;- });-- TSCORE.calculatedTags.length = 0;- _.each(countData, function(count, tag) {- TSCORE.calculatedTags.push({- "title": tag,- "type" : "plain",- "count": count- });- });-- TSCORE.generateTagGroups();- };-- var searchData = function(data, query) {- query = query.toLowerCase().replace(/^\s+|\s+$/g, "");-- if(query.indexOf("?") === 0) {- TSCORE.Search.nextQuery = query.substring(1,query.length);- TSCORE.IO.createDirectoryIndex(TSCORE.currentPath);+ 'use strict';+ console.log('Loading search.js ...');+ var TSCORE = require('tscore');+ var currentQuery = '';+ var nextQuery = '';++ var search4Tag = function(tagQuery) {+ TSCORE.Search.nextQuery = '+' + tagQuery;+ $('#searchBox').val('+' + tagQuery);+ TSCORE.PerspectiveManager.redrawCurrentPerspective();+ TSCORE.showSearchArea();+ };++ var search4String = function(query) {+ TSCORE.Search.nextQuery = '+' + query;+ $('#searchBox').val('+' + query);+ TSCORE.PerspectiveManager.redrawCurrentPerspective();+ TSCORE.showSearchArea();+ };++ var calculateTags = function(data) {+ console.log('Calculating tags from search results');+ var allTags = [];+ data.forEach(function(fileEntry) {+ fileEntry[TSCORE.fileListTAGS].forEach(function(tag) {+ allTags.push(tag.toLowerCase());+ });+ });+ var countData = _.countBy(allTags, function(obj) {+ return obj;+ });+ TSCORE.calculatedTags.length = 0;+ _.each(countData, function(count, tag) {+ TSCORE.calculatedTags.push({+ 'title': tag,+ 'type': 'plain',+ 'count': count+ });+ });+ TSCORE.generateTagGroups();+ };++ var searchData = function(data, query) {+ query = query.toLowerCase().replace(/^\s+|\s+$/g, '');+ if (query.indexOf('?') === 0) {+ TSCORE.Search.nextQuery = query.substring(1, query.length);+ TSCORE.IO.createDirectoryIndex(TSCORE.currentPath);+ return false;+ }+ // By empty filter just return the data+ if (query.length > 0) {+ var queryTerms = query.split(' ');+ // Analysing filter+ var includedTerms = [];+ var excludedTerms = [];+ var includedTags = [];+ var excludedTags = [];+ queryTerms.forEach(function(value) {+ if (value.length > 1) {+ if (value.indexOf('!') === 0) {+ excludedTerms.push([+ value.substring(1, value.length),+ false+ ]);+ } else if (value.indexOf('+') === 0) {+ includedTags.push([+ value.substring(1, value.length),+ true+ ]);+ } else if (value.indexOf('-') === 0) {+ excludedTags.push([+ value.substring(1, value.length),+ true+ ]);+ } else {+ includedTerms.push([+ value,+ false+ ]);+ }+ }+ });+ data = _.filter(data, function(value) {+ // Searching in the whole filename+ var parentDir = TSCORE.TagUtils.extractParentDirectoryPath(value[TSCORE.fileListFILEPATH].toLowerCase());+ var searchIn = value[TSCORE.fileListFILENAME].toLowerCase();+ var tags = value[TSCORE.fileListTAGS];+ var result = true;+ if (tags.length < 1 && includedTags.length > 0) {+ return false;+ }+ for (var i = 0; i < includedTerms.length; i++) {+ if ((parentDir + searchIn).indexOf(includedTerms[i][0]) >= 0) {+ includedTerms[i][1] = true;+ } else {+ return false;+ }+ }+ for (var i = 0; i < excludedTerms.length; i++) {+ if (searchIn.indexOf(excludedTerms[i][0]) < 0) {+ excludedTerms[i][1] = true;+ } else {return false;+ }+ }+ for (var i = 0; i < includedTags.length; i++) {+ includedTags[i][1] = false;+ for (var j = 0; j < tags.length; j++) {+ if (tags[j].toLowerCase() == includedTags[i][0]) {+ includedTags[i][1] = true;+ }+ }+ }+ for (var i = 0; i < includedTags.length; i++) {+ result = result & includedTags[i][1];}-- // By empty filter just return the data- if(query.length > 0) {-- var queryTerms = query.split(" ");-- // Analysing filter- var includedTerms = [];- var excludedTerms = [];- var includedTags = [];- var excludedTags = [];-- queryTerms.forEach(function (value) {- if(value.length > 1) {- if(value.indexOf("!") == 0) {- excludedTerms.push([value.substring(1,value.length),false]);- } else if(value.indexOf("+") == 0) {- includedTags.push([value.substring(1,value.length),true]);- } else if(value.indexOf("-") == 0) {- excludedTags.push([value.substring(1,value.length),true]);- } else {- includedTerms.push([value,false]);- }- }- });-- data = _.filter(data, function(value) {- // Searching in the whole filename- var parentDir = TSCORE.TagUtils.extractParentDirectoryPath(value[TSCORE.fileListFILEPATH].toLowerCase());- var searchIn = value[TSCORE.fileListFILENAME].toLowerCase();- var tags = value[TSCORE.fileListTAGS];- var result = true;- if(tags.length < 1 && includedTags.length > 0) {- return false;- }- for (var i=0; i < includedTerms.length; i++) {- if((parentDir+searchIn).indexOf(includedTerms[i][0]) >= 0) {- includedTerms[i][1] = true;- } else {- return false;- }- }- for (var i=0; i < excludedTerms.length; i++) {- if(searchIn.indexOf(excludedTerms[i][0]) < 0) {- excludedTerms[i][1] = true;- } else {- return false;- }- }-- for (var i=0; i < includedTags.length; i++) {- includedTags[i][1] = false;- for (var j=0; j < tags.length; j++) {- if(tags[j].toLowerCase() == includedTags[i][0]) {- includedTags[i][1] = true;- }- }- }- for (var i=0; i < includedTags.length; i++) {- result = result & includedTags[i][1];- }-- for (var i=0; i < excludedTags.length; i++) {- excludedTags[i][1] = true;- for (var j=0; j < tags.length; j++) {- if(tags[j].toLowerCase() == excludedTags[i][0]) {- excludedTags[i][1] = false;- }- }- }- for (var i=0; i < excludedTags.length; i++) {- result = result & excludedTags[i][1];- }-- return result;- });-- currentQuery = nextQuery;+ for (var i = 0; i < excludedTags.length; i++) {+ excludedTags[i][1] = true;+ for (var j = 0; j < tags.length; j++) {+ if (tags[j].toLowerCase() == excludedTags[i][0]) {+ excludedTags[i][1] = false;+ }+ }}-- if(TSCORE.Config.getCalculateTags()) {- // Find all tags in the current search results- exports.calculateTags(data);+ for (var i = 0; i < excludedTags.length; i++) {+ result = result & excludedTags[i][1];}-- return data;- };-- // Public variables definition- exports.currentQuery = currentQuery;- exports.nextQuery = nextQuery;-- // Public API definition- exports.searchData = searchData;- exports.searchForTag = search4Tag;- exports.searchForString = search4String;- exports.calculateTags = calculateTags;--});\ No newline at end of file+ return result;+ });+ currentQuery = nextQuery;+ }+ if (TSCORE.Config.getCalculateTags()) {+ // Find all tags in the current search results+ exports.calculateTags(data);+ }+ return data;+ };++ // Public variables definition+ exports.currentQuery = currentQuery;+ exports.nextQuery = nextQuery;++ // Public API definition+ exports.searchData = searchData;+ exports.searchForTag = search4Tag;+ exports.searchForString = search4String;+ exports.calculateTags = calculateTags;+});diff --git a/data/js/settings.api.js b/data/js/settings.api.jsindex 1202cbf16..7cb12ed0f 100644--- a/data/js/settings.api.js+++ b/data/js/settings.api.js@@ -1,1085 +1,984 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.- * Use of this source code is governed by a AGPL3 license that+/* 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. *//* global define, isFirefox */-- define(function(require, exports, module) {-"use strict";-- console.log("Loading settings.api.js..");-- var TSCORE = require("tscore");-- exports.DefaultSettings = require("tssettingsdefault").defaultSettings;-- exports.Settings = undefined;-- var tagTemplate = {- "title" : undefined,- "type" : "plain"- /* ,- "pattern":"yyyymmddhhmmss-yyyymmddhhmmss",- "example":"20120114123456-20120823231235",- "regex":"",- "maxlength":17,- "chainedTags":[- "isbn","autor"- ],- "url": "http://example.com",- "action":"showDatePicker",- "prefixes":[- "EUR", "USD", "BGN"- ]- */- };-- var locationTemplate = {- "name": undefined,- "path": undefined,- "perspective": undefined- };-- var tagGroupTemplate = {- "title": undefined,- "key": undefined,- "expanded": true,- "children": []- };-- var firstRun = false;-- var upgradeSettings = function() {- var oldBuildNumber = parseInt(exports.Settings.appBuildID);- // For compartibility reasons- if(exports.Settings.appBuildID === undefined) {- oldBuildNumber = parseInt(exports.Settings.appBuild);- exports.Settings.appBuildID = exports.DefaultSettings.appBuildID;- saveSettings();- }- var newBuildNumber = parseInt(exports.DefaultSettings.appBuildID);- // Workarround for settings update, please comment for production- //oldBuildNumber = 1;- //newBuildNumber = 2;- if(oldBuildNumber < newBuildNumber) {- console.log("Upgrading settings");- exports.Settings.appVersion = exports.DefaultSettings.appVersion;- exports.Settings.appBuild = exports.DefaultSettings.appBuild;- exports.Settings.appBuildID = exports.DefaultSettings.appBuildID;- getPerspectiveExtensions();- getExtensionPath();- getShowUnixHiddenEntries();- getCheckForUpdates();-- if(oldBuildNumber <= 1700) {- setPrefixTagContainer("");- setTagDelimiter(" ");- setCalculateTags(false);- }-- if(oldBuildNumber <= 201403070000) {- addFileType({ "type": "odt", "viewer": "editorODF", "editor": "false" });- addFileType({ "type": "ods", "viewer": "editorODF", "editor": "false" });- addFileType({ "type": "odp", "viewer": "editorODF", "editor": "false" });- addFileType({ "type": "odg", "viewer": "editorODF", "editor": "false" });- }-- if(oldBuildNumber <= 201405120000) {- addTagGroup(- {- "title": "Ratings", "key": "REV", "expanded": true, "children": [- {- "type": "plain",- "title": "1star",- "color": "#FFCC24",- "textcolor": "#ffffff",- "keyBinding": "t 1"- },- {- "type": "plain",- "title": "2star",- "color": "#FFCC24",- "textcolor": "#ffffff",- "keyBinding": "t 2"- },- {- "type": "plain",- "title": "3star",- "color": "#FFCC24",- "textcolor": "#ffffff",- "keyBinding": "t 3"- },- {- "type": "plain",- "title": "4star",- "color": "#FFCC24",- "textcolor": "#ffffff",- "keyBinding": "t 4"- },- {- "type": "plain",- "title": "5star",- "color": "#FFCC24",- "textcolor": "#ffffff",- "keyBinding": "t 5"- }- ]- }- );- }-- if(oldBuildNumber <= 201407251310) {- addFileType({ "type": "json", "viewer": "editorJSON", "editor": "editorJSON" });- //addToSettingsArray(exports.Settings.ootbViewers,"editorJSON");- //addToSettingsArray(exports.Settings.ootbEditors,"editorJSON");- }-- if(oldBuildNumber <= 201410020000) {- updateFileType({ "type": "json", "viewer": "editorJSON", "editor": "editorJSON" });- updateFileType({ "type": "html", "viewer": "viewerHTML", "editor": "editorHTML" });- updateFileType({ "type": "htm", "viewer": "viewerHTML", "editor": "editorHTML" });- }-- if(oldBuildNumber <= 201411230000) {- //addToSettingsArray(exports.Settings.ootbViewers,"viewerMHTML");- updateFileType({ "type": "mhtml", "viewer": "viewerMHTML", "editor": "false" });- updateFileType({ "type": "mht", "viewer": "viewerMHTML", "editor": "false" });- }-- saveSettings();- }-- };-- //////////////////// Settings upgrade methods ///////////////////-- var addTagGroup = function(newTagGroup) {- var tagGroupExist = false;- exports.Settings.tagGroups.forEach(function (value) {- if(value.key === newTagGroup.key) {- tagGroupExist = true;- }- });- if(!tagGroupExist) {- exports.Settings.tagGroups.push(newTagGroup);- }- };-- var addFileType = function(newFileType) {- var fileTypeExist = false;- exports.Settings.supportedFileTypes.forEach(function (value) {- if(value.type === newFileType.type) {- fileTypeExist = true;- }- });- if(!fileTypeExist) {- exports.Settings.supportedFileTypes.push(newFileType);- }- };-- var updateFileType = function(newFileType) {- exports.Settings.supportedFileTypes.forEach(function (value) {- if(value.type === newFileType.type) {- value.viewer = newFileType.viewer;- value.editor = newFileType.editor;- }- });- };-- var addToSettingsArray = function(arrayLocation, value) {- if(arrayLocation instanceof Array) {- if($.inArray(value, arrayLocation) < 0) {- arrayLocation.push(value);- }- }- };-- var removeFromSettingsArray = function(arrayLocation, value) {- if(arrayLocation instanceof Array) {- arrayLocation.splice( $.inArray(value, arrayLocation), 1 );- }- };-- var removeFromSettingsArrayById = function(arrayLocation, id) {- if(arrayLocation instanceof Array) {- arrayLocation.forEach(function (value, index) {- if(value.id === id) {- arrayLocation.splice( index, 1 );- }- });- }- };-- //////////////////// getter and setter methods ///////////////////-- var getPerspectiveExtensions = function() {- return exports.DefaultSettings.ootbPerspectives;- };-- var getActivatedPerspectiveExtensions = function() {- if(exports.Settings.perspectives === undefined) {- exports.Settings.perspectives = exports.DefaultSettings.perspectives;- }- return exports.Settings.perspectives;- };-- var getViewerExtensions = function() {- return exports.DefaultSettings.ootbViewers;- };-- var getEditorExtensions = function() {- return exports.DefaultSettings.ootbEditors;- };-- var getPerspectives = function() {- if(exports.Settings.perspectives === undefined) {- exports.Settings.perspectives = exports.DefaultSettings.perspectives;- }- return exports.Settings.perspectives;- };-- var setPerspectives = function(value) {- exports.Settings.perspectives = value;- };-- var getExtensionPath = function() {- if(exports.Settings.extensionsPath === undefined) {- exports.Settings.extensionsPath = exports.DefaultSettings.extensionsPath;- }- return exports.Settings.extensionsPath;- };-- var setExtensionPath = function(value) {- exports.Settings.extensionsPath = value;- };-- var isFirstRun = function() {- if(exports.Settings.firstRun === undefined) {- exports.Settings.firstRun = false;- }- if(exports.Settings.firstRun){- exports.Settings.firstRun = false;- saveSettings();- return true;+define(function(require, exports, module) {+ 'use strict';+ console.log('Loading settings.api.js..');+ var TSCORE = require('tscore');+ exports.DefaultSettings = require('tssettingsdefault').defaultSettings;+ exports.Settings = undefined;+ var tagTemplate = {+ 'title': undefined,+ 'type': 'plain'+ /* ,+ "pattern":"yyyymmddhhmmss-yyyymmddhhmmss",+ "example":"20120114123456-20120823231235",+ "regex":"",+ "maxlength":17,+ "chainedTags":[+ "isbn","autor"+ ],+ "url": "http://example.com",+ "action":"showDatePicker",+ "prefixes":[+ "EUR", "USD", "BGN"+ ]+ */+ };+ var locationTemplate = {+ 'name': undefined,+ 'path': undefined,+ 'perspective': undefined+ };+ var tagGroupTemplate = {+ 'title': undefined,+ 'key': undefined,+ 'expanded': true,+ 'children': []+ };+ var firstRun = false;+ var upgradeSettings = function() {+ var oldBuildNumber = parseInt(exports.Settings.appBuildID);+ // For compartibility reasons+ if (exports.Settings.appBuildID === undefined) {+ oldBuildNumber = parseInt(exports.Settings.appBuild);+ exports.Settings.appBuildID = exports.DefaultSettings.appBuildID;+ saveSettings();+ }+ var newBuildNumber = parseInt(exports.DefaultSettings.appBuildID);+ // Workarround for settings update, please comment for production+ //oldBuildNumber = 1;+ //newBuildNumber = 2;+ if (oldBuildNumber < newBuildNumber) {+ console.log('Upgrading settings');+ exports.Settings.appVersion = exports.DefaultSettings.appVersion;+ exports.Settings.appBuild = exports.DefaultSettings.appBuild;+ exports.Settings.appBuildID = exports.DefaultSettings.appBuildID;+ getPerspectiveExtensions();+ getExtensionPath();+ getShowUnixHiddenEntries();+ getCheckForUpdates();+ if (oldBuildNumber <= 1700) {+ setPrefixTagContainer('');+ setTagDelimiter(' ');+ setCalculateTags(false);+ }+ if (oldBuildNumber <= 201403070000) {+ addFileType({+ 'type': 'odt',+ 'viewer': 'editorODF',+ 'editor': 'false'+ });+ addFileType({+ 'type': 'ods',+ 'viewer': 'editorODF',+ 'editor': 'false'+ });+ addFileType({+ 'type': 'odp',+ 'viewer': 'editorODF',+ 'editor': 'false'+ });+ addFileType({+ 'type': 'odg',+ 'viewer': 'editorODF',+ 'editor': 'false'+ });+ }+ if (oldBuildNumber <= 201405120000) {+ addTagGroup({+ 'title': 'Ratings',+ 'key': 'REV',+ 'expanded': true,+ 'children': [{+ 'type': 'plain',+ 'title': '1star',+ 'color': '#FFCC24',+ 'textcolor': '#ffffff',+ 'keyBinding': 't 1'+ }, {+ 'type': 'plain',+ 'title': '2star',+ 'color': '#FFCC24',+ 'textcolor': '#ffffff',+ 'keyBinding': 't 2'+ }, {+ 'type': 'plain',+ 'title': '3star',+ 'color': '#FFCC24',+ 'textcolor': '#ffffff',+ 'keyBinding': 't 3'+ }, {+ 'type': 'plain',+ 'title': '4star',+ 'color': '#FFCC24',+ 'textcolor': '#ffffff',+ 'keyBinding': 't 4'+ }, {+ 'type': 'plain',+ 'title': '5star',+ 'color': '#FFCC24',+ 'textcolor': '#ffffff',+ 'keyBinding': 't 5'+ }]+ });+ }+ if (oldBuildNumber <= 201407251310) {+ addFileType({+ 'type': 'json',+ 'viewer': 'editorJSON',+ 'editor': 'editorJSON'+ }); //addToSettingsArray(exports.Settings.ootbViewers,"editorJSON");+ //addToSettingsArray(exports.Settings.ootbEditors,"editorJSON");+ }+ if (oldBuildNumber <= 201410020000) {+ updateFileType({+ 'type': 'json',+ 'viewer': 'editorJSON',+ 'editor': 'editorJSON'+ });+ updateFileType({+ 'type': 'html',+ 'viewer': 'viewerHTML',+ 'editor': 'editorHTML'+ });+ updateFileType({+ 'type': 'htm',+ 'viewer': 'viewerHTML',+ 'editor': 'editorHTML'+ });+ }+ if (oldBuildNumber <= 201411230000) {+ //addToSettingsArray(exports.Settings.ootbViewers,"viewerMHTML");+ updateFileType({+ 'type': 'mhtml',+ 'viewer': 'viewerMHTML',+ 'editor': 'false'+ });+ updateFileType({+ 'type': 'mht',+ 'viewer': 'viewerMHTML',+ 'editor': 'false'+ });+ }+ saveSettings();+ }+ };+ //////////////////// Settings upgrade methods ///////////////////+ var addTagGroup = function(newTagGroup) {+ var tagGroupExist = false;+ exports.Settings.tagGroups.forEach(function(value) {+ if (value.key === newTagGroup.key) {+ tagGroupExist = true;+ }+ });+ if (!tagGroupExist) {+ exports.Settings.tagGroups.push(newTagGroup);+ }+ };+ var addFileType = function(newFileType) {+ var fileTypeExist = false;+ exports.Settings.supportedFileTypes.forEach(function(value) {+ if (value.type === newFileType.type) {+ fileTypeExist = true;+ }+ });+ if (!fileTypeExist) {+ exports.Settings.supportedFileTypes.push(newFileType);+ }+ };+ var updateFileType = function(newFileType) {+ exports.Settings.supportedFileTypes.forEach(function(value) {+ if (value.type === newFileType.type) {+ value.viewer = newFileType.viewer;+ value.editor = newFileType.editor;+ }+ });+ };+ var addToSettingsArray = function(arrayLocation, value) {+ if (arrayLocation instanceof Array) {+ if ($.inArray(value, arrayLocation) < 0) {+ arrayLocation.push(value);+ }+ }+ };+ var removeFromSettingsArray = function(arrayLocation, value) {+ if (arrayLocation instanceof Array) {+ arrayLocation.splice($.inArray(value, arrayLocation), 1);+ }+ };+ var removeFromSettingsArrayById = function(arrayLocation, id) {+ if (arrayLocation instanceof Array) {+ arrayLocation.forEach(function(value, index) {+ if (value.id === id) {+ arrayLocation.splice(index, 1);+ }+ });+ }+ };+ //////////////////// getter and setter methods ///////////////////+ var getPerspectiveExtensions = function() {+ return exports.DefaultSettings.ootbPerspectives;+ };+ var getActivatedPerspectiveExtensions = function() {+ if (exports.Settings.perspectives === undefined) {+ exports.Settings.perspectives = exports.DefaultSettings.perspectives;+ }+ return exports.Settings.perspectives;+ };+ var getViewerExtensions = function() {+ return exports.DefaultSettings.ootbViewers;+ };+ var getEditorExtensions = function() {+ return exports.DefaultSettings.ootbEditors;+ };+ var getPerspectives = function() {+ if (exports.Settings.perspectives === undefined) {+ exports.Settings.perspectives = exports.DefaultSettings.perspectives;+ }+ return exports.Settings.perspectives;+ };+ var setPerspectives = function(value) {+ exports.Settings.perspectives = value;+ };+ var getExtensionPath = function() {+ if (exports.Settings.extensionsPath === undefined) {+ exports.Settings.extensionsPath = exports.DefaultSettings.extensionsPath;+ }+ return exports.Settings.extensionsPath;+ };+ var setExtensionPath = function(value) {+ exports.Settings.extensionsPath = value;+ };+ var isFirstRun = function() {+ if (exports.Settings.firstRun === undefined) {+ exports.Settings.firstRun = false;+ }+ if (exports.Settings.firstRun) {+ exports.Settings.firstRun = false;+ saveSettings();+ return true;+ } else {+ return false;+ }+ };+ var getIsWindowMaximized = function() {+ if (exports.Settings.isWindowMaximized === undefined) {+ exports.Settings.isWindowMaximized = exports.DefaultSettings.isWindowMaximized;+ }+ return exports.Settings.isWindowMaximized;+ };+ var setIsWindowMaximized = function(value) {+ exports.Settings.isWindowMaximized = value;+ };+ var getLastOpenedLocation = function() {+ if (exports.Settings.lastOpenedLocation === undefined) {+ exports.Settings.lastOpenedLocation = exports.DefaultSettings.lastOpenedLocation;+ }+ return exports.Settings.lastOpenedLocation;+ };+ var setLastOpenedLocation = function(value) {+ exports.Settings.lastOpenedLocation = value;+ };+ var getSupportedLanguages = function() {+ return exports.DefaultSettings.supportedLanguages;+ };+ var getCloseViewerKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.closeViewer === undefined) {+ exports.Settings.keyBindings.closeViewer = exports.DefaultSettings.keyBindings.closeViewer;+ saveSettings();+ }+ return exports.Settings.keyBindings.closeViewer;+ };+ var setCloseViewerKeyBinding = function(value) {+ exports.Settings.keyBindings.closeViewer = value;+ };+ var getEditDocumentKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.editDocument === undefined) {+ exports.Settings.keyBindings.editDocument = exports.DefaultSettings.keyBindings.editDocument;+ saveSettings();+ }+ return exports.Settings.keyBindings.editDocument;+ };+ var setEditDocumentKeyBinding = function(value) {+ exports.Settings.keyBindings.editDocument = value;+ };+ var getSaveDocumentKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.saveDocument === undefined) {+ exports.Settings.keyBindings.saveDocument = exports.DefaultSettings.keyBindings.saveDocument;+ saveSettings();+ }+ return exports.Settings.keyBindings.saveDocument;+ };+ var setSaveDocumentKeyBinding = function(value) {+ exports.Settings.keyBindings.saveDocument = value;+ };+ var getReloadApplicationKeyBinding = function() {+ //if (exports.Settings.keyBindings === undefined) {+ // exports.Settings.keyBindings = exports.DefaultSettings.keyBindings;+ // saveSettings();+ //}+ //if (exports.Settings.keyBindings.reloadApplication === undefined) {+ // exports.Settings.keyBindings.reloadApplication = exports.DefaultSettings.keyBindings.reloadApplication;+ // saveSettings();+ //}+ return exports.DefaultSettings.keyBindings.reloadApplication;+ };+ var setReloadApplicationKeyBinding = function(value) {+ consolo.log('Not supported command'); //exports.Settings.keyBindings.reloadApplication = value;+ };+ var getToggleFullScreenKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.toggleFullScreen === undefined) {+ exports.Settings.keyBindings.toggleFullScreen = exports.DefaultSettings.keyBindings.toggleFullScreen;+ saveSettings();+ }+ return exports.Settings.keyBindings.toggleFullScreen;+ };+ var setToggleFullScreenKeyBinding = function(value) {+ exports.Settings.keyBindings.toggleFullScreen = value;+ };+ var getAddRemoveTagsKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.addRemoveTags === undefined) {+ exports.Settings.keyBindings.addRemoveTags = exports.DefaultSettings.keyBindings.addRemoveTags;+ saveSettings();+ }+ return exports.Settings.keyBindings.addRemoveTags;+ };+ var setAddRemoveTagsKeyBinding = function(value) {+ exports.Settings.keyBindings.addRemoveTags = value;+ };+ var getReloadDocumentKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.reloadDocument === undefined) {+ exports.Settings.keyBindings.reloadDocument = exports.DefaultSettings.keyBindings.reloadDocument;+ saveSettings();+ }+ return exports.Settings.keyBindings.reloadDocument;+ };+ var setReloadDocumentKeyBinding = function(value) {+ exports.Settings.keyBindings.reloadDocument = value;+ };+ var getDeleteDocumentKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.deleteDocument === undefined) {+ exports.Settings.keyBindings.deleteDocument = exports.DefaultSettings.keyBindings.deleteDocument;+ saveSettings();+ }+ return exports.Settings.keyBindings.deleteDocument;+ };+ var setDeleteDocumentKeyBinding = function(value) {+ exports.Settings.keyBindings.deleteDocument = value;+ };+ var getPropertiesDocumentKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.propertiesDocument === undefined) {+ exports.Settings.keyBindings.propertiesDocument = exports.DefaultSettings.keyBindings.propertiesDocument;+ saveSettings();+ }+ return exports.Settings.keyBindings.propertiesDocument;+ };+ var setPropertiesDocumentKeyBinding = function(value) {+ exports.Settings.keyBindings.propertiesDocument = value;+ };+ var getNextDocumentKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.nextDocument === undefined) {+ exports.Settings.keyBindings.nextDocument = exports.DefaultSettings.keyBindings.nextDocument;+ saveSettings();+ }+ return exports.Settings.keyBindings.nextDocument;+ };+ var setNextDocumentKeyBinding = function(value) {+ exports.Settings.keyBindings.nextDocument = value;+ };+ var getPrevDocumentKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.prevDocument === undefined) {+ exports.Settings.keyBindings.prevDocument = exports.DefaultSettings.keyBindings.prevDocument;+ saveSettings();+ }+ return exports.Settings.keyBindings.prevDocument;+ };+ var setShowTagLibraryKeyBinding = function(value) {+ exports.Settings.keyBindings.showTagLibrary = value;+ };+ var getShowTagLibraryKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.showTagLibrary === undefined) {+ exports.Settings.keyBindings.showTagLibrary = exports.DefaultSettings.keyBindings.showTagLibrary;+ saveSettings();+ }+ return exports.Settings.keyBindings.showTagLibrary;+ };+ var setShowFolderNavigatorKeyBinding = function(value) {+ exports.Settings.keyBindings.showFolderNavigator = value;+ };+ var getShowFolderNavigatorBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.showFolderNavigator === undefined) {+ exports.Settings.keyBindings.showFolderNavigator = exports.DefaultSettings.keyBindings.showFolderNavigator;+ saveSettings();+ }+ return exports.Settings.keyBindings.showFolderNavigator;+ };+ var setPrevDocumentKeyBinding = function(value) {+ exports.Settings.keyBindings.prevDocument = value;+ };+ var getOpenDevToolsScreenKeyBinding = function() {+ updateKeyBindingsSetting();+ if (exports.Settings.keyBindings.openDevTools === undefined) {+ exports.Settings.keyBindings.openDevTools = exports.DefaultSettings.keyBindings.openDevTools;+ saveSettings();+ }+ return exports.Settings.keyBindings.openDevTools;+ };+ var setOpenDevToolsScreenKeyBinding = function(value) {+ exports.Settings.keyBindings.openDevTools = value;+ };+ var getInterfaceLangauge = function() {+ if (exports.Settings.interfaceLanguage === undefined) {+ exports.Settings.interfaceLanguage = exports.DefaultSettings.interfaceLanguage;+ saveSettings();+ }+ return exports.Settings.interfaceLanguage;+ };+ var setInterfaceLangauge = function(value) {+ exports.Settings.interfaceLanguage = value;+ };+ var getShowWarningRecursiveScan = function() {+ if (exports.Settings.showWarningRecursiveScan === undefined) {+ exports.Settings.showWarningRecursiveScan = exports.DefaultSettings.showWarningRecursiveScan;+ saveSettings();+ }+ return exports.Settings.showWarningRecursiveScan;+ };+ var setShowWarningRecursiveScan = function(value) {+ exports.Settings.showWarningRecursiveScan = value;+ saveSettings();+ };+ var getShowMainMenu = function() {+ if (exports.Settings.showMainMenu === undefined) {+ exports.Settings.showMainMenu = exports.DefaultSettings.showMainMenu;+ }+ return exports.Settings.showMainMenu;+ };+ var setShowMainMenu = function(value) {+ exports.Settings.showMainMenu = value;+ };+ var getWebDavPath = function() {+ if (exports.Settings.webDavPath === undefined) {+ exports.Settings.webDavPath = exports.DefaultSettings.webDavPath;+ }+ return exports.Settings.webDavPath;+ };+ var setWebDavPath = function(value) {+ exports.Settings.webDavPath = value;+ };+ var getShowUnixHiddenEntries = function() {+ if (exports.Settings.showUnixHiddenEntries === undefined) {+ exports.Settings.showUnixHiddenEntries = exports.DefaultSettings.showUnixHiddenEntries;+ }+ return exports.Settings.showUnixHiddenEntries;+ };+ var setShowUnixHiddenEntries = function(value) {+ exports.Settings.showUnixHiddenEntries = value;+ };+ var getCheckForUpdates = function() {+ if (exports.Settings.checkForUpdates === undefined) {+ exports.Settings.checkForUpdates = exports.DefaultSettings.checkForUpdates;+ }+ return exports.Settings.checkForUpdates;+ };+ var setCheckForUpdates = function(value) {+ exports.Settings.checkForUpdates = value;+ };+ var getPrefixTagContainer = function() {+ if (exports.Settings.prefixTagContainer === undefined) {+ exports.Settings.prefixTagContainer = exports.DefaultSettings.prefixTagContainer;+ }+ return exports.Settings.prefixTagContainer;+ };+ var setPrefixTagContainer = function(value) {+ exports.Settings.prefixTagContainer = value;+ };+ var getTagDelimiter = function() {+ if (exports.Settings.tagDelimiter === undefined) {+ exports.Settings.tagDelimiter = exports.DefaultSettings.tagDelimiter;+ }+ return exports.Settings.tagDelimiter;+ };+ var setTagDelimiter = function(value) {+ exports.Settings.tagDelimiter = value;+ };+ var getCalculateTags = function() {+ if (exports.Settings.calculateTags === undefined) {+ exports.Settings.calculateTags = exports.DefaultSettings.calculateTags;+ }+ return exports.Settings.calculateTags;+ };+ var setCalculateTags = function(value) {+ exports.Settings.calculateTags = value;+ };+ var getLoadLocationMeta = function() {+ if (exports.Settings.loadLocationMeta === undefined) {+ exports.Settings.loadLocationMeta = exports.DefaultSettings.loadLocationMeta;+ }+ return exports.Settings.loadLocationMeta;+ };+ var setLoadLocationMeta = function(value) {+ exports.Settings.loadLocationMeta = value;+ };+ var getSupportedFileTypes = function() {+ if (exports.Settings.supportedFileTypes === undefined) {+ exports.Settings.supportedFileTypes = exports.DefaultSettings.supportedFileTypes;+ }+ return exports.Settings.supportedFileTypes;+ };+ var setSupportedFileTypes = function(value) {+ exports.Settings.supportedFileTypes = value;+ };+ var getNewTextFileContent = function() {+ return exports.DefaultSettings.newTextFileContent;+ };+ var getNewHTMLFileContent = function() {+ return exports.DefaultSettings.newHTMLFileContent;+ };+ var getNewMDFileContent = function() {+ return exports.DefaultSettings.newMDFileContent;+ };+ //////////////////// API methods ///////////////////+ var getFileTypeEditor = function(fileTypeExt) {+ for (var i = 0; i < exports.Settings.supportedFileTypes.length; i++) {+ if (exports.Settings.supportedFileTypes[i].type === fileTypeExt) {+ return exports.Settings.supportedFileTypes[i].editor;+ }+ }+ return false;+ };+ var getFileTypeViewer = function(fileTypeExt) {+ for (var i = 0; i < exports.Settings.supportedFileTypes.length; i++) {+ if (exports.Settings.supportedFileTypes[i].type === fileTypeExt) {+ return exports.Settings.supportedFileTypes[i].viewer;+ }+ }+ return false;+ };+ // Returns the tag information from the setting for a given tag+ var findTag = function(tagName) {+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ for (var j = 0; j < exports.Settings.tagGroups[i].children.length; j++) {+ // console.log("Current tagname "+exports.Settings.tagGroups[i].children[j].title);+ if (exports.Settings.tagGroups[i].children[j].title === tagName) {+ return exports.Settings.tagGroups[i].children[j];+ }+ }+ }+ return false;+ };+ var getAllTags = function() {+ var allTags = [];+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ // console.log("Current taggroup "+exports.Settings.tagGroups[i].key);+ for (var j = 0; j < exports.Settings.tagGroups[i].children.length; j++) {+ // console.log("Current tagname "+exports.Settings.tagGroups[i].children[j].title);+ if (exports.Settings.tagGroups[i].children[j].type === 'plain') {+ allTags.push(exports.Settings.tagGroups[i].children[j].title);+ }+ }+ }+ return allTags;+ };+ var getTagData = function(tagTitle, tagGroupKey) {+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ if (exports.Settings.tagGroups[i].key === tagGroupKey) {+ for (var j = 0; j < exports.Settings.tagGroups[i].children.length; j++) {+ if (exports.Settings.tagGroups[i].children[j].title === tagTitle) {+ return exports.Settings.tagGroups[i].children[j];+ }+ }+ }+ }+ };+ var getTagGroupData = function(tagGroupKey) {+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ if (exports.Settings.tagGroups[i].key === tagGroupKey) {+ return exports.Settings.tagGroups[i];+ }+ }+ };+ var getAllTagGroupData = function() {+ if (exports.Settings.tagGroups.length > 0) {+ return exports.Settings.tagGroups;+ }+ };+ var deleteTagGroup = function(tagData) {+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ if (exports.Settings.tagGroups[i].key === tagData.key) {+ console.log('Deleting taggroup ' + exports.Settings.tagGroups[i].key);+ exports.Settings.tagGroups.splice(i, 1);+ break;+ }+ }+ saveSettings();+ };+ var editTag = function(tagData, newTagName, newColor, newTextColor, newKeyBinding) {+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ if (exports.Settings.tagGroups[i].key === tagData.parentKey) {+ for (var j = 0; j < exports.Settings.tagGroups[i].children.length; j++) {+ if (exports.Settings.tagGroups[i].children[j].title === tagData.title) {+ exports.Settings.tagGroups[i].children[j].title = newTagName;+ exports.Settings.tagGroups[i].children[j].color = newColor;+ exports.Settings.tagGroups[i].children[j].textcolor = newTextColor;+ exports.Settings.tagGroups[i].children[j].keyBinding = newKeyBinding;+ break;+ }+ }+ }+ }+ saveSettings();+ };+ var deleteTag = function(tagData) {+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ if (exports.Settings.tagGroups[i].key === tagData.parentKey) {+ for (var j = 0; j < exports.Settings.tagGroups[i].children.length; j++) {+ if (exports.Settings.tagGroups[i].children[j].title === tagData.title) {+ exports.Settings.tagGroups[i].children.splice(j, 1);+ break;+ }+ }+ }+ }+ exports.saveSettings();+ };+ var moveTag = function(tagData, targetTagGroupKey) {+ var targetTagGroupData = getTagGroupData(targetTagGroupKey);+ if (createTag(targetTagGroupData, tagData.title, tagData.color, tagData.textcolor)) {+ deleteTag(tagData);+ saveSettings();+ }+ };+ var createTag = function(tagData, newTagName, newTagColor, newTagTextColor) {+ exports.Settings.tagGroups.forEach(function(value) {+ if (value.key === tagData.key) {+ //console.log("Creating tag: "+newTagName+" with parent: "+tagData.key);+ var tagExistsInGroup = false;+ value.children.forEach(function(child) {+ if (child.title === newTagName) {+ tagExistsInGroup = true;+ }+ });+ // Create tag if it is not existing in the current group+ // And is at least 2 characters long+ if (!tagExistsInGroup && newTagName.length >= 2) {+ var newTagModel = JSON.parse(JSON.stringify(tagTemplate));+ newTagModel.title = newTagName;+ newTagModel.color = newTagColor;+ newTagModel.textcolor = newTagTextColor;+ value.children.push(newTagModel);} else {- return false;- }- };-- var getIsWindowMaximized = function() {- if(exports.Settings.isWindowMaximized === undefined) {- exports.Settings.isWindowMaximized = exports.DefaultSettings.isWindowMaximized;- }- return exports.Settings.isWindowMaximized;- };-- var setIsWindowMaximized = function(value) {- exports.Settings.isWindowMaximized = value;- };-- var getLastOpenedLocation = function() {- if(exports.Settings.lastOpenedLocation === undefined) {- exports.Settings.lastOpenedLocation = exports.DefaultSettings.lastOpenedLocation;- }- return exports.Settings.lastOpenedLocation;- };-- var setLastOpenedLocation = function(value) {- exports.Settings.lastOpenedLocation = value;- };-- var getSupportedLanguages = function () {- return exports.DefaultSettings.supportedLanguages;- };-- var getCloseViewerKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.closeViewer === undefined) {- exports.Settings.keyBindings.closeViewer = exports.DefaultSettings.keyBindings.closeViewer;- saveSettings();- }- return exports.Settings.keyBindings.closeViewer;- };-- var setCloseViewerKeyBinding = function (value) {- exports.Settings.keyBindings.closeViewer = value;- };-- var getEditDocumentKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.editDocument === undefined) {- exports.Settings.keyBindings.editDocument = exports.DefaultSettings.keyBindings.editDocument;- saveSettings();- }- return exports.Settings.keyBindings.editDocument;- };-- var setEditDocumentKeyBinding = function (value) {- exports.Settings.keyBindings.editDocument = value;- };-- var getSaveDocumentKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.saveDocument === undefined) {- exports.Settings.keyBindings.saveDocument = exports.DefaultSettings.keyBindings.saveDocument;- saveSettings();- }- return exports.Settings.keyBindings.saveDocument;- };-- var setSaveDocumentKeyBinding = function (value) {- exports.Settings.keyBindings.saveDocument = value;- };-- var getReloadApplicationKeyBinding = function () {- //if (exports.Settings.keyBindings === undefined) {- // exports.Settings.keyBindings = exports.DefaultSettings.keyBindings;- // saveSettings();- //}- //if (exports.Settings.keyBindings.reloadApplication === undefined) {- // exports.Settings.keyBindings.reloadApplication = exports.DefaultSettings.keyBindings.reloadApplication;- // saveSettings();- //}- return exports.DefaultSettings.keyBindings.reloadApplication;- };-- var setReloadApplicationKeyBinding = function (value) {- consolo.log("Not supported command");- //exports.Settings.keyBindings.reloadApplication = value;- };-- var getToggleFullScreenKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.toggleFullScreen === undefined) {- exports.Settings.keyBindings.toggleFullScreen = exports.DefaultSettings.keyBindings.toggleFullScreen;- saveSettings();- }- return exports.Settings.keyBindings.toggleFullScreen;- };-- var setToggleFullScreenKeyBinding = function (value) {- exports.Settings.keyBindings.toggleFullScreen = value;- };-- var getAddRemoveTagsKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.addRemoveTags === undefined) {- exports.Settings.keyBindings.addRemoveTags = exports.DefaultSettings.keyBindings.addRemoveTags;- saveSettings();- }- return exports.Settings.keyBindings.addRemoveTags;- };-- var setAddRemoveTagsKeyBinding = function (value) {- exports.Settings.keyBindings.addRemoveTags = value;- };-- var getReloadDocumentKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.reloadDocument === undefined) {- exports.Settings.keyBindings.reloadDocument = exports.DefaultSettings.keyBindings.reloadDocument;- saveSettings();- }- return exports.Settings.keyBindings.reloadDocument;- };-- var setReloadDocumentKeyBinding = function (value) {- exports.Settings.keyBindings.reloadDocument = value;- };-- var getDeleteDocumentKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.deleteDocument === undefined) {- exports.Settings.keyBindings.deleteDocument = exports.DefaultSettings.keyBindings.deleteDocument;- saveSettings();- }- return exports.Settings.keyBindings.deleteDocument;- };-- var setDeleteDocumentKeyBinding = function (value) {- exports.Settings.keyBindings.deleteDocument = value;- };-- var getPropertiesDocumentKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.propertiesDocument === undefined) {- exports.Settings.keyBindings.propertiesDocument = exports.DefaultSettings.keyBindings.propertiesDocument;- saveSettings();- }- return exports.Settings.keyBindings.propertiesDocument;- };-- var setPropertiesDocumentKeyBinding = function (value) {- exports.Settings.keyBindings.propertiesDocument = value;- };-- var getNextDocumentKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.nextDocument === undefined) {- exports.Settings.keyBindings.nextDocument = exports.DefaultSettings.keyBindings.nextDocument;- saveSettings();- }- return exports.Settings.keyBindings.nextDocument;- };-- var setNextDocumentKeyBinding = function (value) {- exports.Settings.keyBindings.nextDocument = value;- };-- var getPrevDocumentKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.prevDocument === undefined) {- exports.Settings.keyBindings.prevDocument = exports.DefaultSettings.keyBindings.prevDocument;- saveSettings();- }- return exports.Settings.keyBindings.prevDocument;- };-- var setShowTagLibraryKeyBinding = function (value) {- exports.Settings.keyBindings.showTagLibrary = value;- };-- var getShowTagLibraryKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.showTagLibrary === undefined) {- exports.Settings.keyBindings.showTagLibrary = exports.DefaultSettings.keyBindings.showTagLibrary;- saveSettings();- }- return exports.Settings.keyBindings.showTagLibrary;- };-- var setShowFolderNavigatorKeyBinding = function (value) {- exports.Settings.keyBindings.showFolderNavigator = value;- };-- var getShowFolderNavigatorBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.showFolderNavigator === undefined) {- exports.Settings.keyBindings.showFolderNavigator = exports.DefaultSettings.keyBindings.showFolderNavigator;- saveSettings();- }- return exports.Settings.keyBindings.showFolderNavigator;- };-- var setPrevDocumentKeyBinding = function (value) {- exports.Settings.keyBindings.prevDocument = value;- };-- var getOpenDevToolsScreenKeyBinding = function () {- updateKeyBindingsSetting();- if (exports.Settings.keyBindings.openDevTools === undefined) {- exports.Settings.keyBindings.openDevTools = exports.DefaultSettings.keyBindings.openDevTools;- saveSettings();- }- return exports.Settings.keyBindings.openDevTools;- };-- var setOpenDevToolsScreenKeyBinding = function (value) {- exports.Settings.keyBindings.openDevTools = value;- };-- var getInterfaceLangauge = function () {- if (exports.Settings.interfaceLanguage === undefined) {- exports.Settings.interfaceLanguage = exports.DefaultSettings.interfaceLanguage;- saveSettings();- }- return exports.Settings.interfaceLanguage;- };-- var setInterfaceLangauge = function (value) {- exports.Settings.interfaceLanguage = value;- };-- var getShowWarningRecursiveScan = function () {- if (exports.Settings.showWarningRecursiveScan === undefined) {- exports.Settings.showWarningRecursiveScan = exports.DefaultSettings.showWarningRecursiveScan;- saveSettings();- }- return exports.Settings.showWarningRecursiveScan;- };-- var setShowWarningRecursiveScan = function (value) {- exports.Settings.showWarningRecursiveScan = value;- saveSettings();- };-- var getShowMainMenu = function() {- if(exports.Settings.showMainMenu === undefined) {- exports.Settings.showMainMenu = exports.DefaultSettings.showMainMenu;- }- return exports.Settings.showMainMenu;- };-- var setShowMainMenu = function(value) {- exports.Settings.showMainMenu = value;- };-- var getWebDavPath = function() {- if(exports.Settings.webDavPath === undefined) {- exports.Settings.webDavPath = exports.DefaultSettings.webDavPath;- }- return exports.Settings.webDavPath;- };-- var setWebDavPath = function(value) {- exports.Settings.webDavPath = value;- };-- var getShowUnixHiddenEntries = function() {- if(exports.Settings.showUnixHiddenEntries === undefined) {- exports.Settings.showUnixHiddenEntries = exports.DefaultSettings.showUnixHiddenEntries;- }- return exports.Settings.showUnixHiddenEntries;- };-- var setShowUnixHiddenEntries = function(value) {- exports.Settings.showUnixHiddenEntries = value;- };-- var getCheckForUpdates = function() {- if(exports.Settings.checkForUpdates === undefined) {- exports.Settings.checkForUpdates = exports.DefaultSettings.checkForUpdates;- }- return exports.Settings.checkForUpdates;- };-- var setCheckForUpdates = function(value) {- exports.Settings.checkForUpdates = value;- };-- var getPrefixTagContainer = function() {- if(exports.Settings.prefixTagContainer === undefined) {- exports.Settings.prefixTagContainer = exports.DefaultSettings.prefixTagContainer;- }- return exports.Settings.prefixTagContainer;- };-- var setPrefixTagContainer = function(value) {- exports.Settings.prefixTagContainer = value;- };-- var getTagDelimiter = function() {- if(exports.Settings.tagDelimiter === undefined) {- exports.Settings.tagDelimiter = exports.DefaultSettings.tagDelimiter;- }- return exports.Settings.tagDelimiter;- };-- var setTagDelimiter = function(value) {- exports.Settings.tagDelimiter = value;- };-- var getCalculateTags = function() {- if(exports.Settings.calculateTags === undefined) {- exports.Settings.calculateTags = exports.DefaultSettings.calculateTags;- }- return exports.Settings.calculateTags;- };-- var setCalculateTags = function(value) {- exports.Settings.calculateTags = value;- };-- var getLoadLocationMeta = function() {- if(exports.Settings.loadLocationMeta === undefined) {- exports.Settings.loadLocationMeta = exports.DefaultSettings.loadLocationMeta;- }- return exports.Settings.loadLocationMeta;- };-- var setLoadLocationMeta = function(value) {- exports.Settings.loadLocationMeta = value;- };-- var getSupportedFileTypes = function() {- if(exports.Settings.supportedFileTypes === undefined) {- exports.Settings.supportedFileTypes = exports.DefaultSettings.supportedFileTypes;- }- return exports.Settings.supportedFileTypes;- };-- var setSupportedFileTypes = function(value) {- exports.Settings.supportedFileTypes = value;- };-- var getNewTextFileContent = function() {- return exports.DefaultSettings.newTextFileContent;- };-- var getNewHTMLFileContent = function() {- return exports.DefaultSettings.newHTMLFileContent;- };-- var getNewMDFileContent = function() {- return exports.DefaultSettings.newMDFileContent;- };-- //////////////////// API methods ///////////////////-- var getFileTypeEditor = function(fileTypeExt) {- for(var i=0; i < exports.Settings.supportedFileTypes.length; i++) {- if(exports.Settings.supportedFileTypes[i].type === fileTypeExt) {- return exports.Settings.supportedFileTypes[i].editor;- }- }- return false;- };-- var getFileTypeViewer = function(fileTypeExt) {- for(var i=0; i < exports.Settings.supportedFileTypes.length; i++) {- if(exports.Settings.supportedFileTypes[i].type === fileTypeExt) {- return exports.Settings.supportedFileTypes[i].viewer;- }- }- return false;- };-- // Returns the tag information from the setting for a given tag- var findTag = function(tagName) {- for(var i=0; i < exports.Settings.tagGroups.length; i++) {-// if(exports.Settings.tagGroups[i].key == tagGroupKey) {- for(var j=0; j < exports.Settings.tagGroups[i].children.length; j++) {- // console.log("Current tagname "+exports.Settings.tagGroups[i].children[j].title);- if(exports.Settings.tagGroups[i].children[j].title === tagName) {- return exports.Settings.tagGroups[i].children[j];- }- }-// }- }- return false;- };-- var getAllTags = function() {- var allTags = [];- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- // console.log("Current taggroup "+exports.Settings.tagGroups[i].key);- for(var j=0; j < exports.Settings.tagGroups[i].children.length; j++) {- // console.log("Current tagname "+exports.Settings.tagGroups[i].children[j].title);- if(exports.Settings.tagGroups[i].children[j].type === "plain") {- allTags.push(exports.Settings.tagGroups[i].children[j].title);- }- }- }- return allTags;- };-- var getTagData = function(tagTitle, tagGroupKey) {- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- if(exports.Settings.tagGroups[i].key === tagGroupKey) {- for(var j=0; j < exports.Settings.tagGroups[i].children.length; j++) {- if(exports.Settings.tagGroups[i].children[j].title === tagTitle) {- return exports.Settings.tagGroups[i].children[j];- }- }- }- }- };-- var getTagGroupData = function(tagGroupKey) {- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- if(exports.Settings.tagGroups[i].key === tagGroupKey) {- return exports.Settings.tagGroups[i];- }- }- };-- var getAllTagGroupData = function() {- if(exports.Settings.tagGroups.length > 0) {- return exports.Settings.tagGroups;- }- };-- var deleteTagGroup = function(tagData) {- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- if(exports.Settings.tagGroups[i].key === tagData.key) {- console.log("Deleting taggroup "+exports.Settings.tagGroups[i].key);- exports.Settings.tagGroups.splice(i, 1);- break;- }- }- saveSettings();- };-- var editTag = function(tagData, newTagName, newColor, newTextColor, newKeyBinding) {- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- if(exports.Settings.tagGroups[i].key === tagData.parentKey) {- for(var j=0; j < exports.Settings.tagGroups[i].children.length; j++) {- if(exports.Settings.tagGroups[i].children[j].title === tagData.title) {- exports.Settings.tagGroups[i].children[j].title = newTagName;- exports.Settings.tagGroups[i].children[j].color = newColor;- exports.Settings.tagGroups[i].children[j].textcolor = newTextColor;- exports.Settings.tagGroups[i].children[j].keyBinding = newKeyBinding;- break;- }- }- }- }- saveSettings();- };-- var deleteTag = function(tagData) {- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- if(exports.Settings.tagGroups[i].key === tagData.parentKey) {- for(var j=0; j < exports.Settings.tagGroups[i].children.length; j++) {- if(exports.Settings.tagGroups[i].children[j].title === tagData.title) {- exports.Settings.tagGroups[i].children.splice(j, 1);- break;- }- }- }- }- exports.saveSettings();- };-- var moveTag = function(tagData, targetTagGroupKey) {- var targetTagGroupData = getTagGroupData(targetTagGroupKey);- if(createTag(targetTagGroupData, tagData.title, tagData.color, tagData.textcolor)) {- deleteTag(tagData);- saveSettings();- }- };-- var createTag = function(tagData, newTagName, newTagColor, newTagTextColor) {- exports.Settings.tagGroups.forEach(function (value) {- if(value.key === tagData.key) {- //console.log("Creating tag: "+newTagName+" with parent: "+tagData.key);- var tagExistsInGroup = false;- value.children.forEach(function (child) {- if(child.title === newTagName) {- tagExistsInGroup = true;- }- });- // Create tag if it is not existing in the current group- // And is at least 2 characters long- if(!tagExistsInGroup && (newTagName.length >= 2)) {- var newTagModel = JSON.parse( JSON.stringify(tagTemplate) );- newTagModel.title = newTagName;- newTagModel.color = newTagColor;- newTagModel.textcolor = newTagTextColor;- value.children.push(newTagModel);- } else {- console.log("Tag with the same name already exist in this group or tag length >= 2");- }- }- });- saveSettings();- return true;- };-- var editTagGroup = function(tagData, tagGroupName) {- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- if(exports.Settings.tagGroups[i].key === tagData.key) {- exports.Settings.tagGroups[i].title = tagGroupName;- break;- }- }- saveSettings();- };-- var duplicateTagGroup = function(tagData, tagGroupName, tagGroupKey) {- var newTagGroupModel;- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- if(exports.Settings.tagGroups[i].key === tagData.key) {- newTagGroupModel = JSON.parse( JSON.stringify(exports.Settings.tagGroups[i]));- break;- }- }- newTagGroupModel.title = tagGroupName;- newTagGroupModel.key = tagGroupKey;- console.log("Creating taggroup: "+JSON.stringify(newTagGroupModel)+" with key: "+tagGroupKey);- exports.Settings.tagGroups.push(newTagGroupModel);- saveSettings();- };-- var sortTagGroup = function(tagData) {- for(var i=0; i < exports.Settings.tagGroups.length; i++) {- if(exports.Settings.tagGroups[i].key === tagData.key) {- exports.Settings.tagGroups[i].children.sort(function(a,b) { return a.title.localeCompare(b.title); });- break;- }- }- saveSettings();- };-- var createTagGroup = function(tagData, tagGroupName) {- var newTagGroupModel = JSON.parse( JSON.stringify( tagGroupTemplate ) );- newTagGroupModel.title = tagGroupName;- //newTagGroupModel.children = [];- newTagGroupModel.key = ""+getRandomInt(10000,99999);- console.log("Creating taggroup: "+JSON.stringify(newTagGroupModel)+" with key: "+newTagGroupModel.key);- exports.Settings.tagGroups.push(newTagGroupModel);- saveSettings();- };-- var moveTagGroup = function(tagData, direction) {- var targetPosition;- var currentPosition;- exports.Settings.tagGroups.forEach(function (value, index) {- if(value.key === tagData.key) {- currentPosition = index;- }+ console.log('Tag with the same name already exist in this group or tag length >= 2');+ }+ }+ });+ saveSettings();+ return true;+ };+ var editTagGroup = function(tagData, tagGroupName) {+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ if (exports.Settings.tagGroups[i].key === tagData.key) {+ exports.Settings.tagGroups[i].title = tagGroupName;+ break;+ }+ }+ saveSettings();+ };+ var duplicateTagGroup = function(tagData, tagGroupName, tagGroupKey) {+ var newTagGroupModel;+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ if (exports.Settings.tagGroups[i].key === tagData.key) {+ newTagGroupModel = JSON.parse(JSON.stringify(exports.Settings.tagGroups[i]));+ break;+ }+ }+ newTagGroupModel.title = tagGroupName;+ newTagGroupModel.key = tagGroupKey;+ console.log('Creating taggroup: ' + JSON.stringify(newTagGroupModel) + ' with key: ' + tagGroupKey);+ exports.Settings.tagGroups.push(newTagGroupModel);+ saveSettings();+ };+ var sortTagGroup = function(tagData) {+ for (var i = 0; i < exports.Settings.tagGroups.length; i++) {+ if (exports.Settings.tagGroups[i].key === tagData.key) {+ exports.Settings.tagGroups[i].children.sort(function(a, b) {+ return a.title.localeCompare(b.title);});-- if (direction === "up") { targetPosition = currentPosition -1; }- if (direction === "down") { targetPosition = currentPosition +1; }-- // Check if target position is within the taggroups array range- if (targetPosition < 0 || targetPosition >= exports.Settings.tagGroups.length || targetPosition === currentPosition) {- return false;- }-- var tmpTagGroup = exports.Settings.tagGroups[currentPosition];- exports.Settings.tagGroups[currentPosition] = exports.Settings.tagGroups[targetPosition];- exports.Settings.tagGroups[targetPosition] = tmpTagGroup;- saveSettings();- };-- var createLocation = function(name, location, perspectiveId) {- var newLocationModel = JSON.parse( JSON.stringify(locationTemplate));- name = name.replace("\\", "\\\\");- name = name.replace("\\\\\\", "\\\\");- name = name.replace("\\\\\\\\", "\\\\");- newLocationModel.name = name;- newLocationModel.path = location;- newLocationModel.perspective = perspectiveId;- var createLoc = true;- exports.Settings.tagspacesList.forEach(function (value) {- if(value.path === newLocationModel.path) {- TSCORE.showAlertDialog(- $.i18n.t("ns.dialogs:selectedPathExistContentAlert"),- $.i18n.t("ns.dialogs:selectedPathExistTitleAlert")- );- createLoc = false;- }- if(value.name === newLocationModel.name) {- TSCORE.showAlertDialog(- $.i18n.t("ns.dialogs:selectedLocationNameExistContentAlert"),- $.i18n.t("ns.dialogs:selectedLocationNameExistTitleAlert")- );- createLoc = false;- }- });- if(createLoc) {- exports.Settings.tagspacesList.push(newLocationModel);- saveSettings();- }- };-- var editLocation = function(oldName, newName, newLocation, perspectiveId) {-// name = name.replace("\\", "\\\\");-// name = name.replace("\\\\\\", "\\\\");-// name = name.replace("\\\\\\\\", "\\\\");- console.log("Old Name: "+oldName+" New Name: "+newName+" New Loc: "+newLocation);- var editLoc = true;- exports.Settings.tagspacesList.forEach(function (value) {- /* if(value.path == newLocation) {+ break;+ }+ }+ saveSettings();+ };+ var createTagGroup = function(tagData, tagGroupName) {+ var newTagGroupModel = JSON.parse(JSON.stringify(tagGroupTemplate));+ newTagGroupModel.title = tagGroupName;+ //newTagGroupModel.children = [];+ newTagGroupModel.key = '' + getRandomInt(10000, 99999);+ console.log('Creating taggroup: ' + JSON.stringify(newTagGroupModel) + ' with key: ' + newTagGroupModel.key);+ exports.Settings.tagGroups.push(newTagGroupModel);+ saveSettings();+ };+ var moveTagGroup = function(tagData, direction) {+ var targetPosition;+ var currentPosition;+ exports.Settings.tagGroups.forEach(function(value, index) {+ if (value.key === tagData.key) {+ currentPosition = index;+ }+ });+ if (direction === 'up') {+ targetPosition = currentPosition - 1;+ }+ if (direction === 'down') {+ targetPosition = currentPosition + 1;+ }+ // Check if target position is within the taggroups array range+ if (targetPosition < 0 || targetPosition >= exports.Settings.tagGroups.length || targetPosition === currentPosition) {+ return false;+ }+ var tmpTagGroup = exports.Settings.tagGroups[currentPosition];+ exports.Settings.tagGroups[currentPosition] = exports.Settings.tagGroups[targetPosition];+ exports.Settings.tagGroups[targetPosition] = tmpTagGroup;+ saveSettings();+ };+ var createLocation = function(name, location, perspectiveId) {+ var newLocationModel = JSON.parse(JSON.stringify(locationTemplate));+ name = name.replace('\\', '\\\\');+ name = name.replace('\\\\\\', '\\\\');+ name = name.replace('\\\\\\\\', '\\\\');+ newLocationModel.name = name;+ newLocationModel.path = location;+ newLocationModel.perspective = perspectiveId;+ var createLoc = true;+ exports.Settings.tagspacesList.forEach(function(value) {+ if (value.path === newLocationModel.path) {+ TSCORE.showAlertDialog($.i18n.t('ns.dialogs:selectedPathExistContentAlert'), $.i18n.t('ns.dialogs:selectedPathExistTitleAlert'));+ createLoc = false;+ }+ if (value.name === newLocationModel.name) {+ TSCORE.showAlertDialog($.i18n.t('ns.dialogs:selectedLocationNameExistContentAlert'), $.i18n.t('ns.dialogs:selectedLocationNameExistTitleAlert'));+ createLoc = false;+ }+ });+ if (createLoc) {+ exports.Settings.tagspacesList.push(newLocationModel);+ saveSettings();+ }+ };+ var editLocation = function(oldName, newName, newLocation, perspectiveId) {+ // name = name.replace("\\", "\\\\");+ // name = name.replace("\\\\\\", "\\\\");+ // name = name.replace("\\\\\\\\", "\\\\");+ console.log('Old Name: ' + oldName + ' New Name: ' + newName + ' New Loc: ' + newLocation);+ var editLoc = true;+ exports.Settings.tagspacesList.forEach(function(value) {+ /* if(value.path == newLocation) {TSCORE.showAlertDialog("Selected path is already used by a location!","Duplicated Location Path");editLocation = false;} */- if(value.name === newName && value.name !== oldName) {- TSCORE.showAlertDialog(- $.i18n.t("ns.dialogs:selectedLocationNameExistContentAlert"),- $.i18n.t("ns.dialogs:selectedLocationNameExistTitleAlert")- );- editLoc = false;- }- });- if(editLoc) {- exports.Settings.tagspacesList.forEach(function (value) {- if(value.name === oldName) {- value.name = newName;- value.path = newLocation;- value.perspective = perspectiveId;- }- });- saveSettings();- }- };-- var getLocation = function(path) {- var location;- exports.Settings.tagspacesList.forEach(function (value) {- if(value.path === path) {- location = value;- }- });- return location;- };-- var deleteLocation = function(name) {- for(var i=0; i < exports.Settings.tagspacesList.length; i++) {- console.log("Traversing connections "+exports.Settings.tagspacesList[i].name+" searching for "+name);- if(exports.Settings.tagspacesList[i].name === name) {- console.log("Deleting connections "+exports.Settings.tagspacesList[i].name);- exports.Settings.tagspacesList.splice(i, 1);- break;- }- }- saveSettings();- };-- var updateSettingMozillaPreferences = function(settings) {- var tmpSettings = JSON.parse(settings);- if(tmpSettings !== null) {- exports.Settings = tmpSettings;- console.log("Settings loaded from firefox preferences: "+tmpSettings);- } else {- exports.Settings = exports.DefaultSettings;- console.log('Default settings loaded(Firefox)!');- }- saveSettings();- };-- var loadDefaultSettings = function() {- exports.Settings = exports.DefaultSettings;- saveSettings();- TSCORE.reloadUI();- console.log("Default settings loaded.");- };-- var loadSettingsLocalStorage = function() {- try {- var tmpSettings = JSON.parse(localStorage.getItem('tagSpacesSettings'));- //console.log("Settings: "+JSON.stringify(tmpSettings));- if(tmpSettings !== null) {- exports.Settings = tmpSettings;- } else {- // If no settings found in the local storage,- // the application runs for the first time.- firstRun = true;- }- console.log("Loaded settings from local storage: "+JSON.stringify(exports.Settings));- } catch(ex) {- console.log("Loading settings from local storage failed due exception: "+ex);- }- };-- // Save setting- var saveSettings = function() {- // TODO Make a file based json backup-- // Making a backup of the last settings- localStorage.setItem('tagSpacesSettingsBackup1', localStorage.getItem('tagSpacesSettings'));-- // Storing setting in the local storage of mozilla and chorme- localStorage.setItem('tagSpacesSettings', JSON.stringify(exports.Settings));-- // Storing settings in firefox native preferences- if(isFirefox || isChrome) {- TSCORE.IO.saveSettings(JSON.stringify(exports.Settings));- }-- console.log('Tagspace Settings Saved!');- };-- var getRandomInt = function(min, max) {- return Math.floor(Math.random() * (max - min + 1)) + min;- };-- function updateKeyBindingsSetting() {- if (exports.Settings.keyBindings === undefined) {- exports.Settings.keyBindings = exports.DefaultSettings.keyBindings;- saveSettings();- }+ if (value.name === newName && value.name !== oldName) {+ TSCORE.showAlertDialog($.i18n.t('ns.dialogs:selectedLocationNameExistContentAlert'), $.i18n.t('ns.dialogs:selectedLocationNameExistTitleAlert'));+ editLoc = false;+ }+ });+ if (editLoc) {+ exports.Settings.tagspacesList.forEach(function(value) {+ if (value.name === oldName) {+ value.name = newName;+ value.path = newLocation;+ value.perspective = perspectiveId;+ }+ });+ saveSettings();}-- // Public API definition- exports.upgradeSettings = upgradeSettings;- exports.getPerspectives = getPerspectives;- exports.setPerspectives = setPerspectives;- exports.isFirstRun = isFirstRun;- exports.getExtensionPath = getExtensionPath;- exports.setExtensionPath = setExtensionPath;- exports.getShowUnixHiddenEntries = getShowUnixHiddenEntries;- exports.setShowUnixHiddenEntries = setShowUnixHiddenEntries;- exports.getCheckForUpdates = getCheckForUpdates;- exports.setCheckForUpdates = setCheckForUpdates;- exports.getSupportedFileTypes = getSupportedFileTypes;- exports.setSupportedFileTypes = setSupportedFileTypes;- exports.setPrefixTagContainer = setPrefixTagContainer;- exports.getPrefixTagContainer = getPrefixTagContainer;- exports.getTagDelimiter = getTagDelimiter;- exports.setTagDelimiter = setTagDelimiter;- exports.getShowMainMenu = getShowMainMenu;- exports.setShowMainMenu = setShowMainMenu;- exports.getWebDavPath = getWebDavPath;- exports.setWebDavPath = setWebDavPath;- exports.getCalculateTags = getCalculateTags;- exports.setCalculateTags = setCalculateTags;- exports.getLoadLocationMeta = getLoadLocationMeta;- exports.setLoadLocationMeta = setLoadLocationMeta;- exports.getIsWindowMaximized = getIsWindowMaximized;- exports.setIsWindowMaximized = setIsWindowMaximized;- exports.getLastOpenedLocation = getLastOpenedLocation;- exports.setLastOpenedLocation = setLastOpenedLocation;- exports.getShowWarningRecursiveScan = getShowWarningRecursiveScan;- exports.setShowWarningRecursiveScan = setShowWarningRecursiveScan;- exports.getSupportedLanguages = getSupportedLanguages;- exports.getInterfaceLangauge = getInterfaceLangauge;- exports.setInterfaceLangauge = setInterfaceLangauge;- exports.getCloseViewerKeyBinding = getCloseViewerKeyBinding;- exports.setCloseViewerKeyBinding = setCloseViewerKeyBinding;- exports.getAddRemoveTagsKeyBinding = getAddRemoveTagsKeyBinding;- exports.setAddRemoveTagsKeyBinding = setAddRemoveTagsKeyBinding;- exports.getEditDocumentKeyBinding = getEditDocumentKeyBinding;- exports.setEditDocumentKeyBinding = setEditDocumentKeyBinding;- exports.getOpenDevToolsScreenKeyBinding = getOpenDevToolsScreenKeyBinding;- exports.setOpenDevToolsScreenKeyBinding = setOpenDevToolsScreenKeyBinding;- exports.getToggleFullScreenKeyBinding = getToggleFullScreenKeyBinding;- exports.setToggleFullScreenKeyBinding = setToggleFullScreenKeyBinding;- exports.getReloadApplicationKeyBinding = getReloadApplicationKeyBinding;- exports.setReloadApplicationKeyBinding = setReloadApplicationKeyBinding;- exports.getSaveDocumentKeyBinding = getSaveDocumentKeyBinding;- exports.setSaveDocumentKeyBinding = setSaveDocumentKeyBinding;- exports.getReloadDocumentKeyBinding = getReloadDocumentKeyBinding;- exports.setReloadDocumentKeyBinding = setReloadDocumentKeyBinding;- exports.getDeleteDocumentKeyBinding = getDeleteDocumentKeyBinding;- exports.setDeleteDocumentKeyBinding = setDeleteDocumentKeyBinding;- exports.getPropertiesDocumentKeyBinding = getPropertiesDocumentKeyBinding;- exports.setPropertiesDocumentKeyBinding = setPropertiesDocumentKeyBinding;- exports.getNextDocumentKeyBinding = getNextDocumentKeyBinding;- exports.setNextDocumentKeyBinding = setNextDocumentKeyBinding;- exports.getPrevDocumentKeyBinding = getPrevDocumentKeyBinding;- exports.setPrevDocumentKeyBinding = setPrevDocumentKeyBinding;- exports.setShowTagLibraryKeyBinding = setShowTagLibraryKeyBinding;- exports.getShowTagLibraryKeyBinding = getShowTagLibraryKeyBinding;- exports.setShowFolderNavigatorKeyBinding = setShowFolderNavigatorKeyBinding;- exports.getShowFolderNavigatorBinding = getShowFolderNavigatorBinding;--- exports.getPerspectiveExtensions = getPerspectiveExtensions;- exports.getActivatedPerspectiveExtensions = getActivatedPerspectiveExtensions;- exports.getViewerExtensions = getViewerExtensions;- exports.getEditorExtensions = getEditorExtensions;-- exports.getNewTextFileContent = getNewTextFileContent;- exports.getNewHTMLFileContent = getNewHTMLFileContent;- exports.getNewMDFileContent = getNewMDFileContent;- exports.getFileTypeEditor = getFileTypeEditor;- exports.getFileTypeViewer = getFileTypeViewer;- exports.getAllTags = getAllTags;-- exports.getTagData = getTagData;- exports.getTagGroupData = getTagGroupData;- exports.getAllTagGroupData = getAllTagGroupData;-- exports.deleteTag = deleteTag;- exports.deleteTagGroup = deleteTagGroup;- exports.editTag = editTag;- exports.createTag = createTag;- exports.findTag = findTag;- exports.moveTag = moveTag;- exports.editTagGroup = editTagGroup;- exports.sortTagGroup = sortTagGroup;- exports.moveTagGroup = moveTagGroup;- exports.createTagGroup = createTagGroup;- exports.duplicateTagGroup = duplicateTagGroup;- exports.createLocation = createLocation;- exports.editLocation = editLocation;- exports.deleteLocation = deleteLocation;- exports.getLocation = getLocation;- exports.updateSettingMozillaPreferences = updateSettingMozillaPreferences;- exports.loadSettingsLocalStorage = loadSettingsLocalStorage;- exports.loadDefaultSettings = loadDefaultSettings;- exports.saveSettings = saveSettings;--});\ No newline at end of file+ };+ var getLocation = function(path) {+ var location;+ exports.Settings.tagspacesList.forEach(function(value) {+ if (value.path === path) {+ location = value;+ }+ });+ return location;+ };+ var deleteLocation = function(name) {+ for (var i = 0; i < exports.Settings.tagspacesList.length; i++) {+ console.log('Traversing connections ' + exports.Settings.tagspacesList[i].name + ' searching for ' + name);+ if (exports.Settings.tagspacesList[i].name === name) {+ console.log('Deleting connections ' + exports.Settings.tagspacesList[i].name);+ exports.Settings.tagspacesList.splice(i, 1);+ break;+ }+ }+ saveSettings();+ };+ var updateSettingMozillaPreferences = function(settings) {+ var tmpSettings = JSON.parse(settings);+ if (tmpSettings !== null) {+ exports.Settings = tmpSettings;+ console.log('Settings loaded from firefox preferences: ' + tmpSettings);+ } else {+ exports.Settings = exports.DefaultSettings;+ console.log('Default settings loaded(Firefox)!');+ }+ saveSettings();+ };+ var loadDefaultSettings = function() {+ exports.Settings = exports.DefaultSettings;+ saveSettings();+ TSCORE.reloadUI();+ console.log('Default settings loaded.');+ };+ var loadSettingsLocalStorage = function() {+ try {+ var tmpSettings = JSON.parse(localStorage.getItem('tagSpacesSettings'));+ //console.log("Settings: "+JSON.stringify(tmpSettings));+ if (tmpSettings !== null) {+ exports.Settings = tmpSettings;+ } else {+ // If no settings found in the local storage,+ // the application runs for the first time.+ firstRun = true;+ }+ console.log('Loaded settings from local storage: ' + JSON.stringify(exports.Settings));+ } catch (ex) {+ console.log('Loading settings from local storage failed due exception: ' + ex);+ }+ };+ // Save setting+ var saveSettings = function() {+ // TODO Make a file based json backup+ // Making a backup of the last settings+ localStorage.setItem('tagSpacesSettingsBackup1', localStorage.getItem('tagSpacesSettings'));+ // Storing setting in the local storage of mozilla and chorme+ localStorage.setItem('tagSpacesSettings', JSON.stringify(exports.Settings));+ // Storing settings in firefox native preferences+ if (isFirefox || isChrome) {+ TSCORE.IO.saveSettings(JSON.stringify(exports.Settings));+ }+ console.log('Tagspace Settings Saved!');+ };+ var getRandomInt = function(min, max) {+ return Math.floor(Math.random() * (max - min + 1)) + min;+ };++ function updateKeyBindingsSetting() {+ if (exports.Settings.keyBindings === undefined) {+ exports.Settings.keyBindings = exports.DefaultSettings.keyBindings;+ saveSettings();+ }+ }++ // Public API definition+ exports.upgradeSettings = upgradeSettings;+ exports.getPerspectives = getPerspectives;+ exports.setPerspectives = setPerspectives;+ exports.isFirstRun = isFirstRun;+ exports.getExtensionPath = getExtensionPath;+ exports.setExtensionPath = setExtensionPath;+ exports.getShowUnixHiddenEntries = getShowUnixHiddenEntries;+ exports.setShowUnixHiddenEntries = setShowUnixHiddenEntries;+ exports.getCheckForUpdates = getCheckForUpdates;+ exports.setCheckForUpdates = setCheckForUpdates;+ exports.getSupportedFileTypes = getSupportedFileTypes;+ exports.setSupportedFileTypes = setSupportedFileTypes;+ exports.setPrefixTagContainer = setPrefixTagContainer;+ exports.getPrefixTagContainer = getPrefixTagContainer;+ exports.getTagDelimiter = getTagDelimiter;+ exports.setTagDelimiter = setTagDelimiter;+ exports.getShowMainMenu = getShowMainMenu;+ exports.setShowMainMenu = setShowMainMenu;+ exports.getWebDavPath = getWebDavPath;+ exports.setWebDavPath = setWebDavPath;+ exports.getCalculateTags = getCalculateTags;+ exports.setCalculateTags = setCalculateTags;+ exports.getLoadLocationMeta = getLoadLocationMeta;+ exports.setLoadLocationMeta = setLoadLocationMeta;+ exports.getIsWindowMaximized = getIsWindowMaximized;+ exports.setIsWindowMaximized = setIsWindowMaximized;+ exports.getLastOpenedLocation = getLastOpenedLocation;+ exports.setLastOpenedLocation = setLastOpenedLocation;+ exports.getShowWarningRecursiveScan = getShowWarningRecursiveScan;+ exports.setShowWarningRecursiveScan = setShowWarningRecursiveScan;+ exports.getSupportedLanguages = getSupportedLanguages;+ exports.getInterfaceLangauge = getInterfaceLangauge;+ exports.setInterfaceLangauge = setInterfaceLangauge;+ exports.getCloseViewerKeyBinding = getCloseViewerKeyBinding;+ exports.setCloseViewerKeyBinding = setCloseViewerKeyBinding;+ exports.getAddRemoveTagsKeyBinding = getAddRemoveTagsKeyBinding;+ exports.setAddRemoveTagsKeyBinding = setAddRemoveTagsKeyBinding;+ exports.getEditDocumentKeyBinding = getEditDocumentKeyBinding;+ exports.setEditDocumentKeyBinding = setEditDocumentKeyBinding;+ exports.getOpenDevToolsScreenKeyBinding = getOpenDevToolsScreenKeyBinding;+ exports.setOpenDevToolsScreenKeyBinding = setOpenDevToolsScreenKeyBinding;+ exports.getToggleFullScreenKeyBinding = getToggleFullScreenKeyBinding;+ exports.setToggleFullScreenKeyBinding = setToggleFullScreenKeyBinding;+ exports.getReloadApplicationKeyBinding = getReloadApplicationKeyBinding;+ exports.setReloadApplicationKeyBinding = setReloadApplicationKeyBinding;+ exports.getSaveDocumentKeyBinding = getSaveDocumentKeyBinding;+ exports.setSaveDocumentKeyBinding = setSaveDocumentKeyBinding;+ exports.getReloadDocumentKeyBinding = getReloadDocumentKeyBinding;+ exports.setReloadDocumentKeyBinding = setReloadDocumentKeyBinding;+ exports.getDeleteDocumentKeyBinding = getDeleteDocumentKeyBinding;+ exports.setDeleteDocumentKeyBinding = setDeleteDocumentKeyBinding;+ exports.getPropertiesDocumentKeyBinding = getPropertiesDocumentKeyBinding;+ exports.setPropertiesDocumentKeyBinding = setPropertiesDocumentKeyBinding;+ exports.getNextDocumentKeyBinding = getNextDocumentKeyBinding;+ exports.setNextDocumentKeyBinding = setNextDocumentKeyBinding;+ exports.getPrevDocumentKeyBinding = getPrevDocumentKeyBinding;+ exports.setPrevDocumentKeyBinding = setPrevDocumentKeyBinding;+ exports.setShowTagLibraryKeyBinding = setShowTagLibraryKeyBinding;+ exports.getShowTagLibraryKeyBinding = getShowTagLibraryKeyBinding;+ exports.setShowFolderNavigatorKeyBinding = setShowFolderNavigatorKeyBinding;+ exports.getShowFolderNavigatorBinding = getShowFolderNavigatorBinding;++ exports.getPerspectiveExtensions = getPerspectiveExtensions;+ exports.getActivatedPerspectiveExtensions = getActivatedPerspectiveExtensions;+ exports.getViewerExtensions = getViewerExtensions;+ exports.getEditorExtensions = getEditorExtensions;++ exports.getNewTextFileContent = getNewTextFileContent;+ exports.getNewHTMLFileContent = getNewHTMLFileContent;+ exports.getNewMDFileContent = getNewMDFileContent;+ exports.getFileTypeEditor = getFileTypeEditor;+ exports.getFileTypeViewer = getFileTypeViewer;+ exports.getAllTags = getAllTags;++ exports.getTagData = getTagData;+ exports.getTagGroupData = getTagGroupData;+ exports.getAllTagGroupData = getAllTagGroupData;++ exports.deleteTag = deleteTag;+ exports.deleteTagGroup = deleteTagGroup;+ exports.editTag = editTag;+ exports.createTag = createTag;+ exports.findTag = findTag;+ exports.moveTag = moveTag;+ exports.editTagGroup = editTagGroup;+ exports.sortTagGroup = sortTagGroup;+ exports.moveTagGroup = moveTagGroup;+ exports.createTagGroup = createTagGroup;+ exports.duplicateTagGroup = duplicateTagGroup;+ exports.createLocation = createLocation;+ exports.editLocation = editLocation;+ exports.deleteLocation = deleteLocation;+ exports.getLocation = getLocation;+ exports.updateSettingMozillaPreferences = updateSettingMozillaPreferences;+ exports.loadSettingsLocalStorage = loadSettingsLocalStorage;+ exports.loadDefaultSettings = loadDefaultSettings;+ exports.saveSettings = saveSettings;+});diff --git a/data/js/settings.default.js b/data/js/settings.default.jsindex 81182c4ac..2c8baba39 100644--- a/data/js/settings.default.js+++ b/data/js/settings.default.js@@ -1,4 +1,4 @@-/* Copyright (c) 2012-2014 The TagSpaces Authors. All rights reserved.+/* 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. */define(function (require, exports, module) {diff --git a/data/js/tags.ui.js b/data/js/tags.ui.jsindex 3aabab800..3fa4d405e 100644--- a/data/js/tags.ui.js+++ b/data/js/tags.ui.js@@ -1,590 +1,523 @@-/* 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, Handlebars */-- define(function(require, exports, module) {-"use strict";-- console.log("Loading tags.ui.js...");-- var locationTagGroupKey = "LTG",- calculatedTagGroupKey = "CTG";-- var TSCORE = require("tscore");-- var tagGroupsTmpl = Handlebars.compile(- '{{#each tagGroups}}'+- '<div class="accordion-group disableTextSelection tagGroupContainer">'+- '<div class="accordion-heading btn-group ui-droppable tagGroupContainerHeading" key="{{key}}">'+- '<button class="btn btn-link btn-lg tagGroupIcon" data-toggle="collapse" data-target="#tagButtons{{@index}}" data-i18n="[title]ns.common:toggleTagGroup" title="{{../toggleTagGroup}}">'+- '<i class="fa fa-tags fa-fw"></i>'+- '</button>'+- '<button class="btn btn-link tagGroupTitle" key="{{key}}">{{title}}</button>'+- '<button class="btn btn-link btn-lg tagGroupActions" key="{{key}}" data-i18n="[title]ns.common:tagGroupOperations" title="{{../tagGroupOperations}}">'+- '<b class="fa fa-ellipsis-v"></b>'+- '</button>'+- '</div>'+- '<div class="accordion-body collapse in" id="tagButtons{{@index}}">'+- '<div class="accordion-inner" id="tagButtonsContent{{@index}}" style="padding: 2px;">'+- '<div>'+- '{{#each children}}'+- '<a class="btn btn-sm tagButton" tag="{{title}}" parentkey="{{../key}}" style="{{style}}" title="{{titleUI}}" >' +- '<span class="{{icon}}" /> '+- '{{title}}'+- '{{#if count}} [{{count}}]{{/if}}'+- ' <span class="caret"></span>'+- '</a>'+- '{{/each}}'+- '</div>'+- '</div>'+- '</div>'+- '</div>'+- '{{/each}}'- );-- function initUI() {-- $( "#extMenuAddTagAsFilter" ).click( function() {- // TODO search for extension- //TSCORE.Search.searchForString(TSCORE.selectedTag);- });-- // Context menu for the tags in the file table and the file viewer- $( "#tagMenuAddTagAsFilter" ).click( function() {- TSCORE.Search.searchForTag(TSCORE.selectedTag);- });-- $( "#tagMenuEditTag" ).click( function() {- TSCORE.showTagEditDialog();- });-- $( "#tagMenuRemoveTag" ).click( function() {- TSCORE.TagUtils.removeTag(TSCORE.selectedFiles[0],TSCORE.selectedTag);- });-- $( "#tagMenuMoveTagFirst" ).click( function() {- TSCORE.TagUtils.moveTagLocation(TSCORE.selectedFiles[0],TSCORE.selectedTag, "first");- });-- $( "#tagMenuMoveTagRight" ).click( function() {- TSCORE.TagUtils.moveTagLocation(TSCORE.selectedFiles[0],TSCORE.selectedTag, "next");- });-- $( "#tagMenuMoveTagLeft" ).click( function() {- TSCORE.TagUtils.moveTagLocation(TSCORE.selectedFiles[0],TSCORE.selectedTag, "prev");- });-- // Context menu for the tags in the tag tree- $( "#tagTreeMenuAddTagToFile" ).click( function() {- TSCORE.TagUtils.addTag(TSCORE.selectedFiles, [TSCORE.selectedTag]);- });-- $( "#tagTreeMenuAddTagAsFilter" ).click( function() {- TSCORE.Search.searchForTag(TSCORE.selectedTag);- });-- $( "#tagTreeMenuEditTag" ).click( function() {- TSCORE.showTagEditInTreeDialog();- });-- $( "#tagTreeMenuDeleteTag" ).click( function() {- TSCORE.showConfirmDialog(- "Delete Tag",- "Do you want to delete this tag from the taggroup?",- function() {- TSCORE.Config.deleteTag(TSCORE.selectedTagData);- generateTagGroups();- }- );- });-- // Context menu for the tags groups- $( "#tagGroupMenuCreateNewTag" ).click( function() {- TSCORE.showDialogTagCreate();- });-- $( "#tagGroupMenuCreateTagGroup" ).click( function() {- TSCORE.showDialogTagGroupCreate();- });-- $( "#tagGroupSort" ).click( function() {- TSCORE.Config.sortTagGroup(TSCORE.selectedTagData);- generateTagGroups();- });-- $( "#tagGroupMenuMoveUp" ).click( function() {- TSCORE.Config.moveTagGroup(TSCORE.selectedTagData, "up");- generateTagGroups();- });-- $( "#tagGroupMenuMoveDown" ).click( function() {- TSCORE.Config.moveTagGroup(TSCORE.selectedTagData, "down");- generateTagGroups();- });-- $( "#tagGroupMenuEdit" ).click( function() {- TSCORE.showDialogEditTagGroup();- });-- $( "#tagGroupMenuDelete" ).click( function() {- TSCORE.showConfirmDialog(- $.i18n.t("ns.dialogs:deleteTagGroupTitleConfirm"),- $.i18n.t("ns.dialogs:deleteTagGroupContentConfirm", {tagGroup: TSCORE.selectedTagData.title}),- function() {- TSCORE.Config.deleteTagGroup(TSCORE.selectedTagData);- generateTagGroups();- }- );- });-- // Dialogs- $( "#editTagInTreeButton" ).click( function() {- TSCORE.Config.editTag(- TSCORE.selectedTagData,- $( "#tagInTreeName" ).val(),- $( "#tagColor" ).val(),- $( "#tagTextColor" ).val(),- $( "#tagInTreeKeyBinding" ).val()- );- generateTagGroups();- TSCORE.PerspectiveManager.refreshFileListContainer();- });-- $( "#cleanTagsButton" ).click( function() {- TSCORE.showConfirmDialog(- $.i18n.t("ns.dialogs:cleanFilesTitleConfirm"),- $.i18n.t("ns.dialogs:cleanFilesContentConfirm"),- function() {- TSCORE.TagUtils.cleanFilesFromTags(TSCORE.selectedFiles);- }- );- });-- $( "#addTagsButton" ).click( function() {- var tags = $("#tags").val().split(",");- TSCORE.TagUtils.addTag(TSCORE.selectedFiles, tags);- });-- $( "#removeTagsButton" ).click( function() {- var tags = $("#tags").val().split(",");- TSCORE.TagUtils.removeTags(TSCORE.selectedFiles, tags);- });-- $( "#createTagButton" ).click( function() {- var tags = $( "#newTagTitle" ).val().split(",");- tags.forEach(function (value) {- TSCORE.Config.createTag(TSCORE.selectedTagData, value );- });- generateTagGroups();- });-- $( "#createTagGroupButton" ).click( function() {- TSCORE.Config.createTagGroup(TSCORE.selectedTagData, $( "#newTagGroupName" ).val() );- generateTagGroups();- });-- $( "#editTagGroupButton" ).click( function() {- TSCORE.Config.editTagGroup(TSCORE.selectedTagData, $( "#tagGroupName" ).val() );- generateTagGroups();- });- }-- function generateTagGroups() {- console.log("Generating TagGroups...");- var $tagGroupsContent = $("#tagGroupsContent");- $tagGroupsContent.children().remove();- $tagGroupsContent.addClass("accordion");-- // Show TagGroup create button if no taggroup exist- if(TSCORE.Config.Settings.tagGroups.length < 1) {- $tagGroupsContent.append($("<button>", {- "class": "btn",- "text": $.i18n.t("ns.common:createTagGroup"),- "data-i18n": "ns.common:createTagGroup"- })- .click( function() {- TSCORE.showDialogTagGroupCreate();- })- );- return true; // quit the taggroup generation- }-- var tagGroups = TSCORE.Config.Settings.tagGroups;- var tag;-- // Cleaning Special TagGroups- for(var k=0; k < tagGroups.length; k++) {- if(tagGroups[k].key.indexOf(locationTagGroupKey) === 0 || tagGroups[k].key === calculatedTagGroupKey) {- console.log("Deleting:"+tagGroups[k].key+" "+k);- tagGroups.splice(k, 1);- k--;- }- }-- // Adding tags to the calculated tag group- if(TSCORE.Config.getCalculateTags() && TSCORE.calculatedTags !== null) {- tagGroups.push({- "title": $.i18n.t("ns.common:tagsFromCurrentFolder"),- "key": calculatedTagGroupKey,- "expanded": true,- "children": TSCORE.calculatedTags- });- }-- // Adding tag groups from the current location- if(TSCORE.Config.getLoadLocationMeta() && TSCORE.locationTags !== null) {- TSCORE.locationTags.forEach(function(data) {- tagGroups.push({- "title": data.title+" (imported)",- "key": locationTagGroupKey+TSCORE.TagUtils.formatDateTime4Tag(new Date(),true, true),- "expanded": true,- "children": data.children- });- });-- }-- // ehnances the taggroups with addition styling information- for(var i=0; i < tagGroups.length; i++) {- for(var j=0; j < tagGroups[i].children.length; j++) {- tag = tagGroups[i].children[j];-- if(tag.description !== undefined) {- tag.titleUI = tag.description;- } else {- tag.titleUI = tag.title;- }-- tag.icon = "";- if(tag.type === "smart"){- tag.icon = "fa fa-flask";- }-- // Add keybinding to tags- if(tag.keyBinding !== undefined && tag.keyBinding.length > 0) {- tag.icon = "fa fa-keyboard-o";- tag.titleUI = tag.titleUI + " [" +tag.keyBinding+ "]";- Mousetrap.unbind(tag.keyBinding);- Mousetrap.bind(- tag.keyBinding,- (function(innerTag) {- return function( e ) {- TSCORE.TagUtils.addTag(TSCORE.selectedFiles, [innerTag]);- };- })(tag.title)- );- }- tag.style = generateTagStyle(tag);- }- }-- $tagGroupsContent.html(tagGroupsTmpl({- "tagGroups": tagGroups,- "toggleTagGroup": $.i18n.t("ns.common:toggleTagGroup"),- "tagGroupOperations": $.i18n.t("ns.common:tagGroupOperations")- }));-- $tagGroupsContent.find(".tagButton").each(function() {- $(this).draggable({- "appendTo": "body",- "helper": "clone",- "revert": 'invalid',- "start": function() {- console.log("Start dragging..........");- TSCORE.selectedTagData = TSCORE.Config.getTagData($(this).attr("tag"), $(this).attr("parentKey"));- TSCORE.selectedTag = generateTagValue(TSCORE.selectedTagData);- TSCORE.selectedTagData.parentKey = $(this).attr("parentKey");- }- }).on("dblclick", function() {- TSCORE.hideAllDropDownMenus();- TSCORE.selectedTagData = TSCORE.Config.getTagData($(this).attr("tag"), $(this).attr("parentKey"));- TSCORE.selectedTag = generateTagValue(TSCORE.selectedTagData);- TSCORE.TagUtils.addTag(TSCORE.selectedFiles, [TSCORE.selectedTag]);- })- });-- $tagGroupsContent.find(".tagGroupTitle").each(function() {- $(this)- .droppable({- accept: '.tagButton',- hoverClass: "dirButtonActive",- drop: function( event, ui ) {- //ui.draggable.detach();- var tagGroupData = TSCORE.Config.getTagData(ui.draggable.attr("tag"), ui.draggable.attr("parentKey"));- tagGroupData.parentKey = ui.draggable.attr("parentKey");- var targetTagGroupKey = $(this).attr("key");- console.log("Moving tag: "+tagGroupData.title+" to "+targetTagGroupKey);- TSCORE.Config.moveTag(tagGroupData, targetTagGroupKey);- generateTagGroups();- $(ui.helper).remove();- }- })- });-- $tagGroupsContent.on("contextmenu click", ".tagGroupActions", function () {- TSCORE.hideAllDropDownMenus();- TSCORE.selectedTag = $(this).attr("tag");- TSCORE.selectedTagData = TSCORE.Config.getTagGroupData($(this).attr("key"));- TSCORE.selectedTagData.parentKey = undefined;- TSCORE.showContextMenu("#tagGroupMenu", $(this));- return false;- });-- $tagGroupsContent.on("contextmenu click", ".tagButton", function () {- TSCORE.hideAllDropDownMenus();- TSCORE.selectedTagData = TSCORE.Config.getTagData($(this).attr("tag"), $(this).attr("parentKey"));- TSCORE.selectedTag = generateTagValue(TSCORE.selectedTagData);- TSCORE.selectedTagData.parentKey = $(this).attr("parentKey");- TSCORE.showContextMenu("#tagTreeMenu", $(this));- return false;- });- }-- function generateTagValue(tagData) {- var tagValue = tagData.title;- var d;- if (tagData.type === "smart") {- switch (tagData.functionality){- case "here": {- /* window.onload = function() {- if (navigator.geolocation) {- navigator.geolocation.getCurrentPosition(function(position) {- var lat = position.coords.latitude;- var lng = position.coords.longitude;- alert("Current position: " + lat + " " + lng);- }, function(error) {- alert('Error occurred. Error code: ' + error.code);- },{timeout:50000});- }else{- alert('no geolocation support');- }- };*/- break;- }- case "today": {- tagValue = TSCORE.TagUtils.formatDateTime4Tag(new Date(), false);- break;- }- case "tomorrow": {- d = new Date();- d.setDate(d.getDate() + 1);- tagValue = TSCORE.TagUtils.formatDateTime4Tag(d, false);- break;- }- case "yesterday": {- d = new Date();- d.setDate(d.getDate() - 1);- tagValue = TSCORE.TagUtils.formatDateTime4Tag(d, false);- break;- }- case "currentMonth": {- var cMonth = ""+((new Date()).getMonth()+1);- if(cMonth.length === 1) {- cMonth = "0"+cMonth;- }- tagValue = ""+(new Date()).getFullYear()+cMonth;- break;- }- case "currentYear": {- tagValue = ""+(new Date()).getFullYear();- break;- }- case "now": {- tagValue = TSCORE.TagUtils.formatDateTime4Tag(new Date(), true);- break;- }- default : {- break;- }- }- }- return tagValue;- }-- function openTagMenu(tagButton, tag, filePath) {- TSCORE.selectedFiles.push(filePath);- TSCORE.selectedTag = tag;- }-- var tagButtonTmpl = Handlebars.compile('{{#each tags}} <button class="btn btn-sm tagButton" tag="{{tag}}" ' +- 'filepath="{{filepath}}" style="{{style}}">{{tag}} <span class="caret"></span></button>{{/each}}');-- // Helper function generating tag buttons- function generateTagButtons(commaSeparatedTags, filePath) {- //console.log("Creating tags...");- var tagString = ""+commaSeparatedTags;-- var context = { tags : [] };-- if(tagString.length > 0) {- var tags = tagString.split(",");- for (var i=0; i < tags.length; i++) {- context.tags.push({- filepath: filePath,- tag: tags[i],- style: generateTagStyle(TSCORE.Config.findTag(tags[i]))- });- }- }-- return tagButtonTmpl(context);- }-- // Get the color for a tag- function generateTagStyle(tagObject) {- var tagStyle = "";- if(tagObject.color !== undefined) {- var textColor = tagObject.textcolor;- if(textColor === undefined) {- textColor = "white";- }- tagStyle = "color: "+textColor+" !important; background-color: "+tagObject.color+" !important;";- }- return tagStyle;- }-- function showDialogTagCreate() {- $( "#newTagTitle" ).val("");-- $("#formAddTags").validator();- $("#formAddTags").submit(function (e) { e.preventDefault(); });- $('#formAddTags').on('invalid.bs.validator', function() {- $( "#createTagButton").prop( "disabled", true );- });- $('#formAddTags').on('valid.bs.validator', function() {- $( "#createTagButton").prop( "disabled", false );- });-- $('#dialogTagCreate').on('shown.bs.modal', function () {- $('#newTagTitle').focus();- });- $('#dialogTagCreate').modal({backdrop: 'static',show: true});- }-- function showDialogEditTagGroup() {- $( "#tagGroupName" ).val(TSCORE.selectedTagData.title);-- $("#formTagGroupEdit").validator();- $("#formTagGroupEdit").submit(function (e) { e.preventDefault(); });- $('#formTagGroupEdit').on('invalid.bs.validator', function() {- $( "#editTagGroupButton").prop( "disabled", true );- });- $('#formTagGroupEdit').on('valid.bs.validator', function() {- $( "#editTagGroupButton").prop( "disabled", false );- });-- $('#dialogEditTagGroup').on('shown.bs.modal', function () {- $('#tagGroupName').focus();- });-- $( '#dialogEditTagGroup' ).modal({backdrop: 'static',show: true});- }-- function showDialogTagGroupCreate() {- $( "#newTagGroupName" ).val("");-- $("#formTagGroupCreate").validator();- $("#formTagGroupCreate").submit(function (e) { e.preventDefault(); });- $('#formTagGroupCreate').on('invalid.bs.validator', function() {- $( "#createTagGroupButton").prop( "disabled", true );- });- $('#formTagGroupCreate').on('valid.bs.validator', function() {- $( "#createTagGroupButton").prop( "disabled", false );- });-- $('#dialogTagGroupCreate').on('shown.bs.modal', function () {- $('#newTagGroupName').focus();- });-- $( '#dialogTagGroupCreate' ).modal({backdrop: 'static',show: true});- }-- function showTagEditInTreeDialog() {- $( "#tagInTreeName" ).val(TSCORE.selectedTagData.title);-- $( "#tagInTreeKeyBinding" ).val(TSCORE.selectedTagData.keyBinding);-- var $tagColorChooser = $( "#tagColorChooser" );- var $tagColor = $('#tagColor');- $tagColorChooser.simplecolorpicker({picker: false});- $tagColorChooser.on("change", function() {- $tagColor.val($tagColorChooser.val());- });- if(TSCORE.selectedTagData.color === undefined- || TSCORE.selectedTagData.color.length < 1) {- $tagColor.val('#008000');- } else {- $tagColor.val(TSCORE.selectedTagData.color);- }-- var $tagTextColorChooser = $( "#tagTextColorChooser" );- var $tagTextColor = $('#tagTextColor');- $tagTextColorChooser.simplecolorpicker({picker: false});- $tagTextColorChooser.on("change", function() {- $tagTextColor.val($tagTextColorChooser.val());- });- if(TSCORE.selectedTagData.textcolor === undefined- || TSCORE.selectedTagData.textcolor.length < 1) {- $tagTextColor.val('#ffffff');- } else {- $tagTextColor.val(TSCORE.selectedTagData.textcolor);- }-- $("#formEditInTreeTag").validator();- $('#formEditInTreeTag').on('invalid.bs.validator', function() {- $( "#editTagInTreeButton").prop( "disabled", true );- });- $('#formEditInTreeTag').on('valid.bs.validator', function() {- $( "#editTagInTreeButton").prop( "disabled", false );- });-- $('#dialogEditInTreeTag').on('shown.bs.modal', function () {- $('#tagInTreeName').focus();- });-- $( '#dialogEditInTreeTag' ).modal({backdrop: 'static',show: true});- }-- function showAddTagsDialog() {- console.log("Adding tags...");- //function split( val ) {- // return val.split( /,\s*/ );- //}- //function extractLast( term ) {- // return split( term ).pop();- //}*/-- $('#tags').select2('data', null);- $("#tags").select2({- multiple: true,- tags: TSCORE.Config.getAllTags(),- tokenSeparators: [","," "],- minimumInputLength: 2,- selectOnBlur: true- });-- $('#dialogAddTags').on('shown.bs.modal', function () {- $('.select2-input').focus();- });-- $( '#dialogAddTags' ).modal({backdrop: 'static',show: true});- }-- // Public Vars- exports.calculatedTags = [];- exports.locationTags = [];-- // Public API definition- exports.initUI = initUI;- exports.generateTagGroups = generateTagGroups;- exports.openTagMenu = openTagMenu;- exports.generateTagStyle = generateTagStyle;- exports.generateTagButtons = generateTagButtons;- exports.showAddTagsDialog = showAddTagsDialog;- exports.showTagEditInTreeDialog = showTagEditInTreeDialog;- exports.showDialogTagCreate = showDialogTagCreate;- exports.showDialogEditTagGroup = showDialogEditTagGroup;- exports.showDialogTagGroupCreate = showDialogTagGroupCreate;--});+/* 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. */+/* global define, Handlebars */+define(function(require, exports, module) {+ 'use strict';+ console.log('Loading tags.ui.js...');+ var locationTagGroupKey = 'LTG',+ calculatedTagGroupKey = 'CTG';+ var TSCORE = require('tscore');+ var tagGroupsTmpl = Handlebars.compile(+ '{{#each tagGroups}}' ++ '<div class="accordion-group disableTextSelection tagGroupContainer">' ++ '<div class="accordion-heading btn-group ui-droppable tagGroupContainerHeading" key="{{key}}">' ++ '<button class="btn btn-link btn-lg tagGroupIcon" data-toggle="collapse" data-target="#tagButtons{{@index}}" data-i18n="[title]ns.common:toggleTagGroup" title="{{../toggleTagGroup}}">' ++ '<i class="fa fa-tags fa-fw"></i>' ++ '</button>' ++ '<button class="btn btn-link tagGroupTitle" key="{{key}}">{{title}}</button>' ++ '<button class="btn btn-link btn-lg tagGroupActions" key="{{key}}" data-i18n="[title]ns.common:tagGroupOperations" title="{{../tagGroupOperations}}">' ++ '<b class="fa fa-ellipsis-v"></b>' ++ '</button>' ++ '</div>' ++ '<div class="accordion-body collapse in" id="tagButtons{{@index}}">' ++ '<div class="accordion-inner" id="tagButtonsContent{{@index}}" style="padding: 2px;">' ++ '<div>' ++ '{{#each children}}' ++ '<a class="btn btn-sm tagButton" tag="{{title}}" parentkey="{{../key}}" style="{{style}}" title="{{titleUI}}" >' ++ '<span class="{{icon}}" /> ' ++ '{{title}}' ++ '{{#if count}} [{{count}}]{{/if}}' ++ ' <span class="caret"></span>' ++ '</a>' ++ '{{/each}}' ++ '</div>' ++ '</div>' ++ '</div>' ++ '</div>' ++ '{{/each}}'+ );++ function initUI() {+ $('#extMenuAddTagAsFilter').click(function() {});+ // Context menu for the tags in the file table and the file viewer+ $('#tagMenuAddTagAsFilter').click(function() {+ TSCORE.Search.searchForTag(TSCORE.selectedTag);+ });+ $('#tagMenuEditTag').click(function() {+ TSCORE.showTagEditDialog();+ });+ $('#tagMenuRemoveTag').click(function() {+ TSCORE.TagUtils.removeTag(TSCORE.selectedFiles[0], TSCORE.selectedTag);+ });+ $('#tagMenuMoveTagFirst').click(function() {+ TSCORE.TagUtils.moveTagLocation(TSCORE.selectedFiles[0], TSCORE.selectedTag, 'first');+ });+ $('#tagMenuMoveTagRight').click(function() {+ TSCORE.TagUtils.moveTagLocation(TSCORE.selectedFiles[0], TSCORE.selectedTag, 'next');+ });+ $('#tagMenuMoveTagLeft').click(function() {+ TSCORE.TagUtils.moveTagLocation(TSCORE.selectedFiles[0], TSCORE.selectedTag, 'prev');+ });+ // Context menu for the tags in the tag tree+ $('#tagTreeMenuAddTagToFile').click(function() {+ TSCORE.TagUtils.addTag(TSCORE.selectedFiles, [TSCORE.selectedTag]);+ });+ $('#tagTreeMenuAddTagAsFilter').click(function() {+ TSCORE.Search.searchForTag(TSCORE.selectedTag);+ });+ $('#tagTreeMenuEditTag').click(function() {+ TSCORE.showTagEditInTreeDialog();+ });+ $('#tagTreeMenuDeleteTag').click(function() {+ TSCORE.showConfirmDialog('Delete Tag', 'Do you want to delete this tag from the taggroup?', function() {+ TSCORE.Config.deleteTag(TSCORE.selectedTagData);+ generateTagGroups();+ });+ });+ // Context menu for the tags groups+ $('#tagGroupMenuCreateNewTag').click(function() {+ TSCORE.showDialogTagCreate();+ });+ $('#tagGroupMenuCreateTagGroup').click(function() {+ TSCORE.showDialogTagGroupCreate();+ });+ $('#tagGroupSort').click(function() {+ TSCORE.Config.sortTagGroup(TSCORE.selectedTagData);+ generateTagGroups();+ });+ $('#tagGroupMenuMoveUp').click(function() {+ TSCORE.Config.moveTagGroup(TSCORE.selectedTagData, 'up');+ generateTagGroups();+ });+ $('#tagGroupMenuMoveDown').click(function() {+ TSCORE.Config.moveTagGroup(TSCORE.selectedTagData, 'down');+ generateTagGroups();+ });+ $('#tagGroupMenuEdit').click(function() {+ TSCORE.showDialogEditTagGroup();+ });+ $('#tagGroupMenuDelete').click(function() {+ TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:deleteTagGroupTitleConfirm'), $.i18n.t('ns.dialogs:deleteTagGroupContentConfirm', {+ tagGroup: TSCORE.selectedTagData.title+ }), function() {+ TSCORE.Config.deleteTagGroup(TSCORE.selectedTagData);+ generateTagGroups();+ });+ });+ // Dialogs+ $('#editTagInTreeButton').click(function() {+ TSCORE.Config.editTag(TSCORE.selectedTagData, $('#tagInTreeName').val(), $('#tagColor').val(), $('#tagTextColor').val(), $('#tagInTreeKeyBinding').val());+ generateTagGroups();+ TSCORE.PerspectiveManager.refreshFileListContainer();+ });+ $('#cleanTagsButton').click(function() {+ TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:cleanFilesTitleConfirm'), $.i18n.t('ns.dialogs:cleanFilesContentConfirm'), function() {+ TSCORE.TagUtils.cleanFilesFromTags(TSCORE.selectedFiles);+ });+ });+ $('#addTagsButton').click(function() {+ var tags = $('#tags').val().split(',');+ TSCORE.TagUtils.addTag(TSCORE.selectedFiles, tags);+ });+ $('#removeTagsButton').click(function() {+ var tags = $('#tags').val().split(',');+ TSCORE.TagUtils.removeTags(TSCORE.selectedFiles, tags);+ });+ $('#createTagButton').click(function() {+ var tags = $('#newTagTitle').val().split(',');+ tags.forEach(function(value) {+ TSCORE.Config.createTag(TSCORE.selectedTagData, value);+ });+ generateTagGroups();+ });+ $('#createTagGroupButton').click(function() {+ TSCORE.Config.createTagGroup(TSCORE.selectedTagData, $('#newTagGroupName').val());+ generateTagGroups();+ });+ $('#editTagGroupButton').click(function() {+ TSCORE.Config.editTagGroup(TSCORE.selectedTagData, $('#tagGroupName').val());+ generateTagGroups();+ });+ }++ function generateTagGroups() {+ console.log('Generating TagGroups...');+ var $tagGroupsContent = $('#tagGroupsContent');+ $tagGroupsContent.children().remove();+ $tagGroupsContent.addClass('accordion');+ // Show TagGroup create button if no taggroup exist+ if (TSCORE.Config.Settings.tagGroups.length < 1) {+ $tagGroupsContent.append($('<button>', {+ 'class': 'btn',+ 'text': $.i18n.t('ns.common:createTagGroup'),+ 'data-i18n': 'ns.common:createTagGroup'+ }).click(function() {+ TSCORE.showDialogTagGroupCreate();+ }));+ return true; // quit the taggroup generation+ }+ var tagGroups = TSCORE.Config.Settings.tagGroups;+ var tag;+ // Cleaning Special TagGroups+ for (var k = 0; k < tagGroups.length; k++) {+ if (tagGroups[k].key.indexOf(locationTagGroupKey) === 0 || tagGroups[k].key === calculatedTagGroupKey) {+ console.log('Deleting:' + tagGroups[k].key + ' ' + k);+ tagGroups.splice(k, 1);+ k--;+ }+ }+ // Adding tags to the calculated tag group+ if (TSCORE.Config.getCalculateTags() && TSCORE.calculatedTags !== null) {+ tagGroups.push({+ 'title': $.i18n.t('ns.common:tagsFromCurrentFolder'),+ 'key': calculatedTagGroupKey,+ 'expanded': true,+ 'children': TSCORE.calculatedTags+ });+ }+ // Adding tag groups from the current location+ if (TSCORE.Config.getLoadLocationMeta() && TSCORE.locationTags !== null) {+ TSCORE.locationTags.forEach(function(data) {+ tagGroups.push({+ 'title': data.title + ' (imported)',+ 'key': locationTagGroupKey + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true, true),+ 'expanded': true,+ 'children': data.children+ });+ });+ }+ // ehnances the taggroups with addition styling information+ for (var i = 0; i < tagGroups.length; i++) {+ for (var j = 0; j < tagGroups[i].children.length; j++) {+ tag = tagGroups[i].children[j];+ if (tag.description !== undefined) {+ tag.titleUI = tag.description;+ } else {+ tag.titleUI = tag.title;+ }+ tag.icon = '';+ if (tag.type === 'smart') {+ tag.icon = 'fa fa-flask';+ }+ // Add keybinding to tags+ if (tag.keyBinding !== undefined && tag.keyBinding.length > 0) {+ tag.icon = 'fa fa-keyboard-o';+ tag.titleUI = tag.titleUI + ' [' + tag.keyBinding + ']';+ Mousetrap.unbind(tag.keyBinding);+ Mousetrap.bind(tag.keyBinding, function(innerTag) {+ return function(e) {+ TSCORE.TagUtils.addTag(TSCORE.selectedFiles, [innerTag]);+ };+ }(tag.title)); // jshint ignore:line+ }+ tag.style = generateTagStyle(tag);+ }+ }+ $tagGroupsContent.html(tagGroupsTmpl({+ 'tagGroups': tagGroups,+ 'toggleTagGroup': $.i18n.t('ns.common:toggleTagGroup'),+ 'tagGroupOperations': $.i18n.t('ns.common:tagGroupOperations')+ }));+ $tagGroupsContent.find('.tagButton').each(function() {+ $(this).draggable({+ 'appendTo': 'body',+ 'helper': 'clone',+ 'revert': 'invalid',+ 'start': function() {+ console.log('Start dragging..........');+ TSCORE.selectedTagData = TSCORE.Config.getTagData($(this).attr('tag'), $(this).attr('parentKey'));+ TSCORE.selectedTag = generateTagValue(TSCORE.selectedTagData);+ TSCORE.selectedTagData.parentKey = $(this).attr('parentKey');+ }+ }).on('dblclick', function() {+ TSCORE.hideAllDropDownMenus();+ TSCORE.selectedTagData = TSCORE.Config.getTagData($(this).attr('tag'), $(this).attr('parentKey'));+ TSCORE.selectedTag = generateTagValue(TSCORE.selectedTagData);+ TSCORE.TagUtils.addTag(TSCORE.selectedFiles, [TSCORE.selectedTag]);+ });+ });+ $tagGroupsContent.find('.tagGroupTitle').each(function() {+ $(this).droppable({+ accept: '.tagButton',+ hoverClass: 'dirButtonActive',+ drop: function(event, ui) {+ //ui.draggable.detach();+ var tagGroupData = TSCORE.Config.getTagData(ui.draggable.attr('tag'), ui.draggable.attr('parentKey'));+ tagGroupData.parentKey = ui.draggable.attr('parentKey');+ var targetTagGroupKey = $(this).attr('key');+ console.log('Moving tag: ' + tagGroupData.title + ' to ' + targetTagGroupKey);+ TSCORE.Config.moveTag(tagGroupData, targetTagGroupKey);+ generateTagGroups();+ $(ui.helper).remove();+ }+ });+ });+ $tagGroupsContent.on('contextmenu click', '.tagGroupActions', function() {+ TSCORE.hideAllDropDownMenus();+ TSCORE.selectedTag = $(this).attr('tag');+ TSCORE.selectedTagData = TSCORE.Config.getTagGroupData($(this).attr('key'));+ TSCORE.selectedTagData.parentKey = undefined;+ TSCORE.showContextMenu('#tagGroupMenu', $(this));+ return false;+ });+ $tagGroupsContent.on('contextmenu click', '.tagButton', function() {+ TSCORE.hideAllDropDownMenus();+ TSCORE.selectedTagData = TSCORE.Config.getTagData($(this).attr('tag'), $(this).attr('parentKey'));+ TSCORE.selectedTag = generateTagValue(TSCORE.selectedTagData);+ TSCORE.selectedTagData.parentKey = $(this).attr('parentKey');+ TSCORE.showContextMenu('#tagTreeMenu', $(this));+ return false;+ });+ }++ function generateTagValue(tagData) {+ var tagValue = tagData.title;+ var d;+ if (tagData.type === 'smart') {+ switch (tagData.functionality) {+ case 'here': {+ /* window.onload = function() {+ if (navigator.geolocation) {+ navigator.geolocation.getCurrentPosition(function(position) {+ var lat = position.coords.latitude;+ var lng = position.coords.longitude;+ alert("Current position: " + lat + " " + lng);+ }, function(error) {+ alert('Error occurred. Error code: ' + error.code);+ },{timeout:50000});+ }else{+ alert('no geolocation support');+ }+ };*/+ break;+ }+ case 'today': {+ tagValue = TSCORE.TagUtils.formatDateTime4Tag(new Date(), false);+ break;+ }+ case 'tomorrow': {+ d = new Date();+ d.setDate(d.getDate() + 1);+ tagValue = TSCORE.TagUtils.formatDateTime4Tag(d, false);+ break;+ }+ case 'yesterday': {+ d = new Date();+ d.setDate(d.getDate() - 1);+ tagValue = TSCORE.TagUtils.formatDateTime4Tag(d, false);+ break;+ }+ case 'currentMonth': {+ var cMonth = '' + (new Date().getMonth() + 1);+ if (cMonth.length === 1) {+ cMonth = '0' + cMonth;+ }+ tagValue = '' + new Date().getFullYear() + cMonth;+ break;+ }+ case 'currentYear': {+ tagValue = '' + new Date().getFullYear();+ break;+ }+ case 'now': {+ tagValue = TSCORE.TagUtils.formatDateTime4Tag(new Date(), true);+ break;+ }+ default: {+ break;+ }+ }+ }+ return tagValue;+ }++ function openTagMenu(tagButton, tag, filePath) {+ TSCORE.selectedFiles.push(filePath);+ TSCORE.selectedTag = tag;+ }+ var tagButtonTmpl = Handlebars.compile('{{#each tags}} <button class="btn btn-sm tagButton" tag="{{tag}}" ' + 'filepath="{{filepath}}" style="{{style}}">{{tag}} <span class="caret"></span></button>{{/each}}');+ // Helper function generating tag buttons+ function generateTagButtons(commaSeparatedTags, filePath) {+ //console.log("Creating tags...");+ var tagString = '' + commaSeparatedTags;+ var context = {+ tags: []+ };+ if (tagString.length > 0) {+ var tags = tagString.split(',');+ for (var i = 0; i < tags.length; i++) {+ context.tags.push({+ filepath: filePath,+ tag: tags[i],+ style: generateTagStyle(TSCORE.Config.findTag(tags[i]))+ });+ }+ }+ return tagButtonTmpl(context);+ }+ // Get the color for a tag+ function generateTagStyle(tagObject) {+ var tagStyle = '';+ if (tagObject.color !== undefined) {+ var textColor = tagObject.textcolor;+ if (textColor === undefined) {+ textColor = 'white';+ }+ tagStyle = 'color: ' + textColor + ' !important; background-color: ' + tagObject.color + ' !important;';+ }+ return tagStyle;+ }++ function showDialogTagCreate() {+ $('#newTagTitle').val('');+ $('#formAddTags').validator();+ $('#formAddTags').submit(function(e) {+ e.preventDefault();+ });+ $('#formAddTags').on('invalid.bs.validator', function() {+ $('#createTagButton').prop('disabled', true);+ });+ $('#formAddTags').on('valid.bs.validator', function() {+ $('#createTagButton').prop('disabled', false);+ });+ $('#dialogTagCreate').on('shown.bs.modal', function() {+ $('#newTagTitle').focus();+ });+ $('#dialogTagCreate').modal({+ backdrop: 'static',+ show: true+ });+ }++ function showDialogEditTagGroup() {+ $('#tagGroupName').val(TSCORE.selectedTagData.title);+ $('#formTagGroupEdit').validator();+ $('#formTagGroupEdit').submit(function(e) {+ e.preventDefault();+ });+ $('#formTagGroupEdit').on('invalid.bs.validator', function() {+ $('#editTagGroupButton').prop('disabled', true);+ });+ $('#formTagGroupEdit').on('valid.bs.validator', function() {+ $('#editTagGroupButton').prop('disabled', false);+ });+ $('#dialogEditTagGroup').on('shown.bs.modal', function() {+ $('#tagGroupName').focus();+ });+ $('#dialogEditTagGroup').modal({+ backdrop: 'static',+ show: true+ });+ }++ function showDialogTagGroupCreate() {+ $('#newTagGroupName').val('');+ $('#formTagGroupCreate').validator();+ $('#formTagGroupCreate').submit(function(e) {+ e.preventDefault();+ });+ $('#formTagGroupCreate').on('invalid.bs.validator', function() {+ $('#createTagGroupButton').prop('disabled', true);+ });+ $('#formTagGroupCreate').on('valid.bs.validator', function() {+ $('#createTagGroupButton').prop('disabled', false);+ });+ $('#dialogTagGroupCreate').on('shown.bs.modal', function() {+ $('#newTagGroupName').focus();+ });+ $('#dialogTagGroupCreate').modal({+ backdrop: 'static',+ show: true+ });+ }++ function showTagEditInTreeDialog() {+ $('#tagInTreeName').val(TSCORE.selectedTagData.title);+ $('#tagInTreeKeyBinding').val(TSCORE.selectedTagData.keyBinding);+ var $tagColorChooser = $('#tagColorChooser');+ var $tagColor = $('#tagColor');+ $tagColorChooser.simplecolorpicker({+ picker: false+ });+ $tagColorChooser.on('change', function() {+ $tagColor.val($tagColorChooser.val());+ });+ if (TSCORE.selectedTagData.color === undefined || TSCORE.selectedTagData.color.length < 1) {+ $tagColor.val('#008000');+ } else {+ $tagColor.val(TSCORE.selectedTagData.color);+ }+ var $tagTextColorChooser = $('#tagTextColorChooser');+ var $tagTextColor = $('#tagTextColor');+ $tagTextColorChooser.simplecolorpicker({+ picker: false+ });+ $tagTextColorChooser.on('change', function() {+ $tagTextColor.val($tagTextColorChooser.val());+ });+ if (TSCORE.selectedTagData.textcolor === undefined || TSCORE.selectedTagData.textcolor.length < 1) {+ $tagTextColor.val('#ffffff');+ } else {+ $tagTextColor.val(TSCORE.selectedTagData.textcolor);+ }+ $('#formEditInTreeTag').validator();+ $('#formEditInTreeTag').on('invalid.bs.validator', function() {+ $('#editTagInTreeButton').prop('disabled', true);+ });+ $('#formEditInTreeTag').on('valid.bs.validator', function() {+ $('#editTagInTreeButton').prop('disabled', false);+ });+ $('#dialogEditInTreeTag').on('shown.bs.modal', function() {+ $('#tagInTreeName').focus();+ });+ $('#dialogEditInTreeTag').modal({+ backdrop: 'static',+ show: true+ });+ }++ function showAddTagsDialog() {+ console.log('Adding tags...');+ //function split( val ) {+ // return val.split( /,\s*/ );+ //}+ //function extractLast( term ) {+ // return split( term ).pop();+ //}*/+ $('#tags').select2('data', null);+ $('#tags').select2({+ multiple: true,+ tags: TSCORE.Config.getAllTags(),+ tokenSeparators: [+ ',',+ ' '+ ],+ minimumInputLength: 2,+ selectOnBlur: true+ });+ $('#dialogAddTags').on('shown.bs.modal', function() {+ $('.select2-input').focus();+ });+ $('#dialogAddTags').modal({+ backdrop: 'static',+ show: true+ });+ }++ // Public Vars+ exports.calculatedTags = [];+ exports.locationTags = [];++ // Public API definition+ exports.initUI = initUI;+ exports.generateTagGroups = generateTagGroups;+ exports.openTagMenu = openTagMenu;+ exports.generateTagStyle = generateTagStyle;+ exports.generateTagButtons = generateTagButtons;+ exports.showAddTagsDialog = showAddTagsDialog;+ exports.showTagEditInTreeDialog = showTagEditInTreeDialog;+ exports.showDialogTagCreate = showDialogTagCreate;+ exports.showDialogEditTagGroup = showDialogEditTagGroup;+ exports.showDialogTagGroupCreate = showDialogTagGroupCreate;+});diff --git a/data/js/tagutils.js b/data/js/tagutils.jsindex a7db0e6e5..c674aaa9c 100644--- a/data/js/tagutils.js+++ b/data/js/tagutils.js@@ -1,516 +1,505 @@-/* 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 tagutils.js ...");-- var TSCORE = require("tscore");-- var BEGIN_TAG_CONTAINER = "[";- var END_TAG_CONTAINER = "]";-- function extractFileName(filePath) {- return filePath.substring(filePath.lastIndexOf(TSCORE.dirSeparator) + 1, filePath.length);- }-- function cleanTrailingDirSeparator(dirPath) {- if(dirPath !== undefined) {- if(dirPath.lastIndexOf("\\") === dirPath.length-1) {- return dirPath.substring(0, dirPath.length-1)- } else if(dirPath.lastIndexOf("/") === dirPath.length-1) {- return dirPath.substring(0,dirPath.length-1)- } else {- return dirPath;- }- } else {- console.error("Directory Path "+dirPath+" undefined");- }- }-- function extractFileNameWithoutExt(filePath) {- var fileName = extractFileName(filePath);- var indexOfDot = fileName.lastIndexOf(".");- var lastIndexBeginTagContainer = fileName.lastIndexOf(BEGIN_TAG_CONTAINER);- var lastIndexEndTagContainer = fileName.lastIndexOf(END_TAG_CONTAINER);-- if(lastIndexBeginTagContainer === 0 && lastIndexEndTagContainer+1 === fileName.length ) { // case: "[tag1 tag.2]"- return "";- } else if(indexOfDot > 0 ) { // case: regular- return fileName.substring(0, indexOfDot);- } else if(indexOfDot === 0) { // case ".txt"- return "";- } else {- return fileName;- }- }-- function stringEndsWith(str, suffix) {- return str.indexOf(suffix, str.length - suffix.length) !== -1;- }-- function extractContainingDirectoryPath(filePath) {- return filePath.substring(0, filePath.lastIndexOf(TSCORE.dirSeparator));- }-- function extractParentDirectoryPath(dirPath) {- if(stringEndsWith(dirPath, TSCORE.dirSeparator)) {- dirPath = dirPath.substring(0, dirPath.lastIndexOf(TSCORE.dirSeparator));- }- return dirPath.substring(0, dirPath.lastIndexOf(TSCORE.dirSeparator));- }-- function extractDirectoryName(dirPath) {- if(stringEndsWith(dirPath, TSCORE.dirSeparator)) {- dirPath = dirPath.substring(0, dirPath.lastIndexOf(TSCORE.dirSeparator));- }- return dirPath.substring(dirPath.lastIndexOf(TSCORE.dirSeparator)+1,dirPath.length);- }-- function extractContainingDirectoryName(filePath) {- var tmpStr = filePath.substring(0, filePath.lastIndexOf(TSCORE.dirSeparator));- return tmpStr.substring(tmpStr.lastIndexOf(TSCORE.dirSeparator)+1,tmpStr.length);- }-- function extractFileExtension(filePath) {- var lastindexDirSeparator = filePath.lastIndexOf(TSCORE.dirSeparator);- var lastIndexEndTagContainer = filePath.lastIndexOf(END_TAG_CONTAINER);- var lastindexDot = filePath.lastIndexOf(".");- if (lastindexDot < 0) {- return "";- } else if (lastindexDot < lastindexDirSeparator) { // case: "../remote.php/webdav/somefilename"- return "";- } else if (lastindexDot < lastIndexEndTagContainer) { // case: "[20120125 89.4kg 19.5% 60.5% 39.8% 2.6kg]"- return "";- } else {- return filePath.substring(lastindexDot + 1, filePath.length).toLowerCase().trim();- }- }-- function extractTitle(filePath) {- console.log("Extracting title from: "+filePath);- var fileName = extractFileNameWithoutExt(filePath);- var beginTagContainer = fileName.indexOf(BEGIN_TAG_CONTAINER);- var endTagContainer = fileName.lastIndexOf(END_TAG_CONTAINER);-- /* cases like "", "t", "["- if( fileName.length <= 1) {- // cases like "asd ] asd ["- else if (beginTagContainer > endTagContainer) {- // case: [ not found in the filename- else if ( beginTagContainer < 0 )- else if ( endTagContainer < 0 ) */-- if( (beginTagContainer >= 0 ) && (beginTagContainer < endTagContainer) ){- if(beginTagContainer === 0 && endTagContainer === fileName.trim().length) { // case: "[tag1, tag2]"- return "";- } else if (endTagContainer === fileName.trim().length) { // case: "asd[tag1, tag2]"- return fileName.slice(0,beginTagContainer);- } else { // case: "title1 [tag1 tag2] title2"- return fileName.slice(0,beginTagContainer)+fileName.slice(endTagContainer+1,fileName.length);- }- } else {- return fileName;- }- }-- function formatFileSize(sizeInBytes, siSystem) {- var threshold = siSystem ? 1000 : 1024;- if(sizeInBytes < threshold) { return sizeInBytes + ' B'; }- var units = siSystem ? ['kB','MB','GB','TB','PB','EB'] : ['KiB','MiB','GiB','TiB','PiB','EiB'];- var cUnit = -1;- do {- sizeInBytes /= threshold;- ++cUnit;- }- while(sizeInBytes >= threshold);- return sizeInBytes.toFixed(1)+' '+units[cUnit];- }-- function formatDateTime(date, includeTime) {- if ((date === undefined) || (date === "")) { return ""; }- var d = new Date(date);- var cDate = d.getDate();- cDate = cDate + "";- if (cDate.length === 1) { cDate = "0" + cDate; }- var cMonth = d.getMonth(); cMonth++;- cMonth = cMonth + "";- if (cMonth.length === 1) { cMonth = "0" + cMonth; }- var cYear = d.getFullYear();- var cHour = d.getHours();- cHour = cHour + "";- if (cHour.length === 1) { cHour = "0" + cHour; }- var cMinute = d.getMinutes();- cMinute = cMinute + "";- if (cMinute.length === 1) { cMinute = "0" + cMinute; }- var cSecond = d.getSeconds();- cSecond = cSecond + "";- if (cSecond.length === 1) { cSecond = "0" + cSecond; }- var time = "";- if (includeTime) {- time = " - "+cHour+":"+cMinute+":"+cSecond;- }- return cYear+"."+cMonth+"."+cDate+time;- }-- function formatDateTime4Tag(date, includeTime, includeMS) {- if ((date === undefined) || (date === "")) { return ""; }- var d = new Date(date);- var cDate = d.getDate();- cDate = cDate + "";- if (cDate.length === 1) { cDate = "0" + cDate; }- var cMonth = d.getMonth(); cMonth++;- cMonth = cMonth + "";- if (cMonth.length === 1) { cMonth = "0" + cMonth; }- var cYear = d.getFullYear();- var cHour = d.getHours();- cHour = cHour + "";- if (cHour.length === 1) { cHour = "0" + cHour; }- var cMinute = d.getMinutes();- cMinute = cMinute + "";- if (cMinute.length === 1) { cMinute = "0" + cMinute; }- var cSecond = d.getSeconds();- cSecond = cSecond + "";- if (cSecond.length === 1) { cSecond = "0" + cSecond; }- var time = "";- if (includeTime) {- time = "-"+cHour+""+cMinute+""+cSecond;- }- var milliseconds = "";- if (includeMS) {- milliseconds = "-"+d.getMilliseconds();- }- return cYear+""+cMonth+""+cDate+time+milliseconds;- }-- function convertStringToDate(dateString) {- if ((dateString === undefined) || (dateString === "")) { return false; }- if (dateString.length === 8) {- return new Date(dateString.substring(0,4)+"-"+dateString.substring(4,6)+"-"+dateString.substring(6,8));- } else {- return false;- }- }-- function extractTags(filePath) {- console.log("Extracting tags from: "+filePath);-- var fileName = extractFileName(filePath); // WithoutExt-- var tags = [];- var beginTagContainer = fileName.indexOf(BEGIN_TAG_CONTAINER);- var endTagContainer = fileName.indexOf(END_TAG_CONTAINER);- if( ( beginTagContainer < 0 ) || ( endTagContainer < 0 ) || ( beginTagContainer >= endTagContainer ) ) {- console.log("Filename does not contains tags. Aborting extraction.");- return tags;- }- var cleanedTags = [];-- var tagContainer = fileName.slice(beginTagContainer+1,endTagContainer).trim();- tags = tagContainer.split(TSCORE.Config.getTagDelimiter());-- for (var i=0; i < tags.length; i++) {- // Min tag length set to 1 character- if(tags[i].trim().length > 0) {- cleanedTags.push(tags[i]);- }- }-- console.log("Extracting finished ");- return cleanedTags;- }-- function suggestTags(filePath) {- console.log("Suggesting tags for: "+filePath);-- var fileName = extractFileName(filePath);-- var tags;- var tagContainer;- var beginTagContainer = fileName.indexOf(BEGIN_TAG_CONTAINER);- if(beginTagContainer < 0) {- tagContainer = fileName.slice(0,fileName.lastIndexOf(".")).trim();- } else {- tagContainer = fileName.slice(0,beginTagContainer).trim();- }-- // Splitting filename with space, comma, plus, underscore and score delimiters- tags = tagContainer.split(/[\s,.+_-]+/);-- var cleanedTags = [];-- // Extracting tags from the name of the containing directory- var tagsFromDirName = extractContainingDirectoryName(filePath).trim().split(/[\s,+_-]+/);-- for (var i=0; i < tagsFromDirName.length; i++) {- if(tagsFromDirName[i].trim().length > 1) {- cleanedTags.push(tagsFromDirName[i]);- }- }-- // Cleaning the tags from filename- for (var j=0; j < tags.length; j++) {- if(tags[j].trim().length > 1) {- cleanedTags.push(tags[j]);- }- }- return cleanedTags;- }-- // Internal- function generateFileName(fileName, tags) {- var tagsString = "";- // Creating the string will all the tags by more that 0 tags- if(tags.length > 0){- tagsString = BEGIN_TAG_CONTAINER;- for (var i=0; i < tags.length; i++) {- tagsString += tags[i]+TSCORE.Config.getTagDelimiter();- }- tagsString = tagsString.trim();- tagsString += END_TAG_CONTAINER;- }- console.log("The tags string: "+tagsString);-- var fileExt = extractFileExtension(fileName);- console.log("Filename: "+fileName+" file extenstion: "+fileExt);-- // Assembling the new filename with the tags- var newFileName = "";- var beginTagContainer = fileName.indexOf(BEGIN_TAG_CONTAINER);- var endTagContainer = fileName.indexOf(END_TAG_CONTAINER);- var lastDotPosition = fileName.lastIndexOf(".");-- if( ( beginTagContainer < 0 ) || ( endTagContainer < 0 ) || ( beginTagContainer >= endTagContainer ) ) {- // Filename does not contains tags.- if(lastDotPosition < 0) {- // File does not have an extension- newFileName = fileName +tagsString;- } else {- // File has an extension- newFileName = fileName.substring(0,lastDotPosition)+TSCORE.Config.getPrefixTagContainer()+tagsString+"."+fileExt;- }- } else {- // File does not have an extension- newFileName = fileName.substring(0,beginTagContainer)+tagsString+fileName.substring(endTagContainer+1,fileName.length);- }- if(newFileName.length < 1) {- throw "Generated filename is invalid";- }- return newFileName;- }-- function writeTagsToFile(filePath, tags) {- console.log("Add the tags to: "+filePath);-- var fileName = extractFileName(filePath);-- var containingDirectoryPath = extractContainingDirectoryPath(filePath);-- var extractedTags = extractTags(filePath);-- for (var i=0; i < tags.length; i++) {- // check if tag is already in the tag array- if(extractedTags.indexOf(tags[i].trim()) < 0) {- // Adding the new tag- extractedTags.push(tags[i].trim());- }- }-- var newFileName = generateFileName(fileName, extractedTags);-- TSCORE.IO.renameFile(filePath, containingDirectoryPath+TSCORE.dirSeparator+newFileName);- }-- function removeTagsFromFile(filePath, tags) {- console.log("Remove the tags from: "+filePath);-- var fileName = extractFileName(filePath);-- var containingDirectoryPath = extractContainingDirectoryPath(filePath);-- var extractedTags = extractTags(filePath);-- for (var i=0; i < tags.length; i++) {- // check if tag is already in the tag array- var tagLoc = extractedTags.indexOf(tags[i].trim());- if(tagLoc >= 0) {- // Remove the new tag- extractedTags.splice(tagLoc,1);- }- }-- var newFileName = generateFileName(fileName, extractedTags);-- TSCORE.IO.renameFile(filePath, containingDirectoryPath+TSCORE.dirSeparator+newFileName);- }-- function cleanFileFromTags(filePath) {- console.log("Cleaning file from tags: " + filePath);- var fileTitle = extractTitle(filePath);- var fileExt = extractFileExtension(filePath);- var containingDirectoryPath = extractContainingDirectoryPath(filePath);- if(fileExt.length > 0) {- fileExt = "."+fileExt;- }- TSCORE.IO.renameFile(filePath, containingDirectoryPath+TSCORE.dirSeparator+fileTitle+fileExt);- }-- function cleanFilesFromTags(filePathArray) {- console.log("Cleaning file from tags");- for (var i=0; i < filePathArray.length; i++) {- cleanFileFromTags(filePathArray[i]);- }- }-- function addTag(filePathArray, tagArray) {- console.log("Adding tags to files");- for (var i=0; i < filePathArray.length; i++) {- writeTagsToFile(filePathArray[i], tagArray);- }- }-- function removeTags(filePathArray, tagArray) {- console.log("Remove tags from files");- for (var i=0; i < filePathArray.length; i++) {- removeTagsFromFile(filePathArray[i], tagArray);- }- }-- // Moves the location of tag in the file name- // possible directions should be next, prev, last, first- function moveTagLocation(filePath, tagName, direction) {- console.log("Moves the location of tag in the file name: "+filePath);-- var fileName = extractFileName(filePath);-- var containingDirectoryPath = extractContainingDirectoryPath(filePath);-- var extractedTags = extractTags(filePath);-- var tmpTag;-- for (var i=0; i < extractedTags.length; i++) {- // check if tag is already in the tag array- if(extractedTags[i] === tagName) {- if((direction === "prev") && (i > 0)) {- tmpTag = extractedTags[i-1];- extractedTags[i-1] = extractedTags[i];- extractedTags[i] = tmpTag;- break;- } else if ((direction === "next") && i < (extractedTags.length-1) ){- tmpTag = extractedTags[i];- extractedTags[i] = extractedTags[i+1];- extractedTags[i+1] = tmpTag;- break;- } else if ((direction === "first") && i > 0 ){- tmpTag = extractedTags[i];- extractedTags[i] = extractedTags[0];- extractedTags[0] = tmpTag;- break;- }- }- }-- var newFileName = generateFileName(fileName, extractedTags);-- TSCORE.IO.renameFile(filePath, containingDirectoryPath+TSCORE.dirSeparator+newFileName);-- }-- // Replaces a tag with a new one- function renameTag(filePath, oldTag, newTag) {- console.log("Rename tag for file: "+filePath);-- var fileName = extractFileName(filePath);-- var containingDirectoryPath = extractContainingDirectoryPath(filePath);-- var extractedTags = extractTags(filePath);-- for (var i=0; i < extractedTags.length; i++) {- // check if tag is already in the tag array- if(extractedTags[i] === oldTag) {- extractedTags[i] = newTag.trim();- }- }-- var newFileName = generateFileName(fileName, extractedTags);-- TSCORE.IO.renameFile(filePath, containingDirectoryPath+TSCORE.dirSeparator+newFileName);-- }-- function changeTitle(filePath, newTitle) {- console.log("Changing title for file: "+filePath);-- var containingDirectoryPath = extractContainingDirectoryPath(filePath);-- var extractedTags = extractTags(filePath);-- var fileExt = extractFileExtension(filePath);- if(fileExt.length > 0) {- fileExt = "."+fileExt;- }-- // TODO generalize generateFileName to support fileTitle & fileExtension- var newFileName = generateFileName(newTitle, extractedTags);-- TSCORE.IO.renameFile(filePath, containingDirectoryPath+TSCORE.dirSeparator+newFileName+fileExt);-- return true;- }-- // Removing a tag from a filename- function removeTag(filePath, tagName) {- console.log("Removing tag: "+tagName+" from "+filePath);-- var fileName = extractFileName(filePath);-- var containingDirectoryPath = extractContainingDirectoryPath(filePath);-- var tags = extractTags(filePath);-- var newTags = [];- for (var i=0; i < tags.length; i++) {- if(tags[i] !== tagName) {- newTags.push(tags[i]);- }- }-- var newFileName = generateFileName(fileName, newTags);-- TSCORE.IO.renameFile(filePath, containingDirectoryPath+TSCORE.dirSeparator+newFileName);- }-- // Public API definition- exports.beginTagContainer = BEGIN_TAG_CONTAINER;- exports.endTagContainer = END_TAG_CONTAINER;-- exports.extractFileName = extractFileName;- exports.extractFileNameWithoutExt = extractFileNameWithoutExt;- exports.extractContainingDirectoryPath = extractContainingDirectoryPath;- exports.extractContainingDirectoryName = extractContainingDirectoryName;- exports.extractDirectoryName = extractDirectoryName;- exports.extractParentDirectoryPath = extractParentDirectoryPath;- exports.extractFileExtension = extractFileExtension;- exports.extractTitle = extractTitle;- exports.formatFileSize = formatFileSize;- exports.formatDateTime = formatDateTime;- exports.formatDateTime4Tag = formatDateTime4Tag;- exports.convertStringToDate = convertStringToDate;- exports.extractTags = extractTags;- exports.suggestTags = suggestTags;- exports.writeTagsToFile = writeTagsToFile;- exports.moveTagLocation = moveTagLocation;- exports.renameTag = renameTag;- exports.removeTag = removeTag;- exports.removeTags = removeTags;- exports.addTag = addTag;- exports.cleanFilesFromTags = cleanFilesFromTags;- exports.cleanTrailingDirSeparator = cleanTrailingDirSeparator;- exports.changeTitle = changeTitle;- exports.stringEndsWith = stringEndsWith;--});\ No newline at end of file+/* 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. */+/* global define */+define(function(require, exports, module) {+ 'use strict';+ console.log('Loading tagutils.js ...');+ var TSCORE = require('tscore');+ var BEGIN_TAG_CONTAINER = '[';+ var END_TAG_CONTAINER = ']';++ function extractFileName(filePath) {+ return filePath.substring(filePath.lastIndexOf(TSCORE.dirSeparator) + 1, filePath.length);+ }++ function cleanTrailingDirSeparator(dirPath) {+ if (dirPath !== undefined) {+ if (dirPath.lastIndexOf('\\') === dirPath.length - 1) {+ return dirPath.substring(0, dirPath.length - 1);+ } else if (dirPath.lastIndexOf('/') === dirPath.length - 1) {+ return dirPath.substring(0, dirPath.length - 1);+ } else {+ return dirPath;+ }+ } else {+ console.error('Directory Path ' + dirPath + ' undefined');+ }+ }++ function extractFileNameWithoutExt(filePath) {+ var fileName = extractFileName(filePath);+ var indexOfDot = fileName.lastIndexOf('.');+ var lastIndexBeginTagContainer = fileName.lastIndexOf(BEGIN_TAG_CONTAINER);+ var lastIndexEndTagContainer = fileName.lastIndexOf(END_TAG_CONTAINER);+ if (lastIndexBeginTagContainer === 0 && lastIndexEndTagContainer + 1 === fileName.length) {+ // case: "[tag1 tag.2]"+ return '';+ } else if (indexOfDot > 0) {+ // case: regular+ return fileName.substring(0, indexOfDot);+ } else if (indexOfDot === 0) {+ // case ".txt"+ return '';+ } else {+ return fileName;+ }+ }++ function stringEndsWith(str, suffix) {+ return str.indexOf(suffix, str.length - suffix.length) !== -1;+ }++ function extractContainingDirectoryPath(filePath) {+ return filePath.substring(0, filePath.lastIndexOf(TSCORE.dirSeparator));+ }++ function extractParentDirectoryPath(dirPath) {+ if (stringEndsWith(dirPath, TSCORE.dirSeparator)) {+ dirPath = dirPath.substring(0, dirPath.lastIndexOf(TSCORE.dirSeparator));+ }+ return dirPath.substring(0, dirPath.lastIndexOf(TSCORE.dirSeparator));+ }++ function extractDirectoryName(dirPath) {+ if (stringEndsWith(dirPath, TSCORE.dirSeparator)) {+ dirPath = dirPath.substring(0, dirPath.lastIndexOf(TSCORE.dirSeparator));+ }+ return dirPath.substring(dirPath.lastIndexOf(TSCORE.dirSeparator) + 1, dirPath.length);+ }++ function extractContainingDirectoryName(filePath) {+ var tmpStr = filePath.substring(0, filePath.lastIndexOf(TSCORE.dirSeparator));+ return tmpStr.substring(tmpStr.lastIndexOf(TSCORE.dirSeparator) + 1, tmpStr.length);+ }++ function extractFileExtension(filePath) {+ var lastindexDirSeparator = filePath.lastIndexOf(TSCORE.dirSeparator);+ var lastIndexEndTagContainer = filePath.lastIndexOf(END_TAG_CONTAINER);+ var lastindexDot = filePath.lastIndexOf('.');+ if (lastindexDot < 0) {+ return '';+ } else if (lastindexDot < lastindexDirSeparator) {+ // case: "../remote.php/webdav/somefilename"+ return '';+ } else if (lastindexDot < lastIndexEndTagContainer) {+ // case: "[20120125 89.4kg 19.5% 60.5% 39.8% 2.6kg]"+ return '';+ } else {+ return filePath.substring(lastindexDot + 1, filePath.length).toLowerCase().trim();+ }+ }++ function extractTitle(filePath) {+ console.log('Extracting title from: ' + filePath);+ var fileName = extractFileNameWithoutExt(filePath);+ var beginTagContainer = fileName.indexOf(BEGIN_TAG_CONTAINER);+ var endTagContainer = fileName.lastIndexOf(END_TAG_CONTAINER);+ /* cases like "", "t", "["+ if( fileName.length <= 1) {+ // cases like "asd ] asd ["+ else if (beginTagContainer > endTagContainer) {+ // case: [ not found in the filename+ else if ( beginTagContainer < 0 )+ else if ( endTagContainer < 0 ) */+ if (beginTagContainer >= 0 && beginTagContainer < endTagContainer) {+ if (beginTagContainer === 0 && endTagContainer === fileName.trim().length) {+ // case: "[tag1, tag2]"+ return '';+ } else if (endTagContainer === fileName.trim().length) {+ // case: "asd[tag1, tag2]"+ return fileName.slice(0, beginTagContainer);+ } else {+ // case: "title1 [tag1 tag2] title2"+ return fileName.slice(0, beginTagContainer) + fileName.slice(endTagContainer + 1, fileName.length);+ }+ } else {+ return fileName;+ }+ }++ function formatFileSize(sizeInBytes, siSystem) {+ var threshold = siSystem ? 1000 : 1024;+ if (sizeInBytes < threshold) {+ return sizeInBytes + ' B';+ }+ var units = siSystem ? [+ 'kB',+ 'MB',+ 'GB',+ 'TB',+ 'PB',+ 'EB'+ ] : [+ 'KiB',+ 'MiB',+ 'GiB',+ 'TiB',+ 'PiB',+ 'EiB'+ ];+ var cUnit = -1;+ do {+ sizeInBytes /= threshold;+ ++cUnit;+ } while (sizeInBytes >= threshold);+ return sizeInBytes.toFixed(1) + ' ' + units[cUnit];+ }++ function formatDateTime(date, includeTime) {+ if (date === undefined || date === '') {+ return '';+ }+ var d = new Date(date);+ var cDate = d.getDate();+ cDate = cDate + '';+ if (cDate.length === 1) {+ cDate = '0' + cDate;+ }+ var cMonth = d.getMonth();+ cMonth++;+ cMonth = cMonth + '';+ if (cMonth.length === 1) {+ cMonth = '0' + cMonth;+ }+ var cYear = d.getFullYear();+ var cHour = d.getHours();+ cHour = cHour + '';+ if (cHour.length === 1) {+ cHour = '0' + cHour;+ }+ var cMinute = d.getMinutes();+ cMinute = cMinute + '';+ if (cMinute.length === 1) {+ cMinute = '0' + cMinute;+ }+ var cSecond = d.getSeconds();+ cSecond = cSecond + '';+ if (cSecond.length === 1) {+ cSecond = '0' + cSecond;+ }+ var time = '';+ if (includeTime) {+ time = ' - ' + cHour + ':' + cMinute + ':' + cSecond;+ }+ return cYear + '.' + cMonth + '.' + cDate + time;+ }++ function formatDateTime4Tag(date, includeTime, includeMS) {+ if (date === undefined || date === '') {+ return '';+ }+ var d = new Date(date);+ var cDate = d.getDate();+ cDate = cDate + '';+ if (cDate.length === 1) {+ cDate = '0' + cDate;+ }+ var cMonth = d.getMonth();+ cMonth++;+ cMonth = cMonth + '';+ if (cMonth.length === 1) {+ cMonth = '0' + cMonth;+ }+ var cYear = d.getFullYear();+ var cHour = d.getHours();+ cHour = cHour + '';+ if (cHour.length === 1) {+ cHour = '0' + cHour;+ }+ var cMinute = d.getMinutes();+ cMinute = cMinute + '';+ if (cMinute.length === 1) {+ cMinute = '0' + cMinute;+ }+ var cSecond = d.getSeconds();+ cSecond = cSecond + '';+ if (cSecond.length === 1) {+ cSecond = '0' + cSecond;+ }+ var time = '';+ if (includeTime) {+ time = '-' + cHour + '' + cMinute + '' + cSecond;+ }+ var milliseconds = '';+ if (includeMS) {+ milliseconds = '-' + d.getMilliseconds();+ }+ return cYear + '' + cMonth + '' + cDate + time + milliseconds;+ }++ function convertStringToDate(dateString) {+ if (dateString === undefined || dateString === '') {+ return false;+ }+ if (dateString.length === 8) {+ return new Date(dateString.substring(0, 4) + '-' + dateString.substring(4, 6) + '-' + dateString.substring(6, 8));+ } else {+ return false;+ }+ }++ function extractTags(filePath) {+ console.log('Extracting tags from: ' + filePath);+ var fileName = extractFileName(filePath);+ // WithoutExt+ var tags = [];+ var beginTagContainer = fileName.indexOf(BEGIN_TAG_CONTAINER);+ var endTagContainer = fileName.indexOf(END_TAG_CONTAINER);+ if (beginTagContainer < 0 || endTagContainer < 0 || beginTagContainer >= endTagContainer) {+ console.log('Filename does not contains tags. Aborting extraction.');+ return tags;+ }+ var cleanedTags = [];+ var tagContainer = fileName.slice(beginTagContainer + 1, endTagContainer).trim();+ tags = tagContainer.split(TSCORE.Config.getTagDelimiter());+ for (var i = 0; i < tags.length; i++) {+ // Min tag length set to 1 character+ if (tags[i].trim().length > 0) {+ cleanedTags.push(tags[i]);+ }+ }+ console.log('Extracting finished ');+ return cleanedTags;+ }++ function suggestTags(filePath) {+ console.log('Suggesting tags for: ' + filePath);+ var fileName = extractFileName(filePath);+ var tags;+ var tagContainer;+ var beginTagContainer = fileName.indexOf(BEGIN_TAG_CONTAINER);+ if (beginTagContainer < 0) {+ tagContainer = fileName.slice(0, fileName.lastIndexOf('.')).trim();+ } else {+ tagContainer = fileName.slice(0, beginTagContainer).trim();+ }+ // Splitting filename with space, comma, plus, underscore and score delimiters+ tags = tagContainer.split(/[\s,.+_-]+/);+ var cleanedTags = [];+ // Extracting tags from the name of the containing directory+ var tagsFromDirName = extractContainingDirectoryName(filePath).trim().split(/[\s,+_-]+/);+ for (var i = 0; i < tagsFromDirName.length; i++) {+ if (tagsFromDirName[i].trim().length > 1) {+ cleanedTags.push(tagsFromDirName[i]);+ }+ }+ // Cleaning the tags from filename+ for (var j = 0; j < tags.length; j++) {+ if (tags[j].trim().length > 1) {+ cleanedTags.push(tags[j]);+ }+ }+ return cleanedTags;+ }++ // Internal+ function generateFileName(fileName, tags) {+ var tagsString = '';+ // Creating the string will all the tags by more that 0 tags+ if (tags.length > 0) {+ tagsString = BEGIN_TAG_CONTAINER;+ for (var i = 0; i < tags.length; i++) {+ tagsString += tags[i] + TSCORE.Config.getTagDelimiter();+ }+ tagsString = tagsString.trim();+ tagsString += END_TAG_CONTAINER;+ }+ console.log('The tags string: ' + tagsString);+ var fileExt = extractFileExtension(fileName);+ console.log('Filename: ' + fileName + ' file extenstion: ' + fileExt);+ // Assembling the new filename with the tags+ var newFileName = '';+ var beginTagContainer = fileName.indexOf(BEGIN_TAG_CONTAINER);+ var endTagContainer = fileName.indexOf(END_TAG_CONTAINER);+ var lastDotPosition = fileName.lastIndexOf('.');+ if (beginTagContainer < 0 || endTagContainer < 0 || beginTagContainer >= endTagContainer) {+ // Filename does not contains tags.+ if (lastDotPosition < 0) {+ // File does not have an extension+ newFileName = fileName + tagsString;+ } else {+ // File has an extension+ newFileName = fileName.substring(0, lastDotPosition) + TSCORE.Config.getPrefixTagContainer() + tagsString + '.' + fileExt;+ }+ } else {+ // File does not have an extension+ newFileName = fileName.substring(0, beginTagContainer) + tagsString + fileName.substring(endTagContainer + 1, fileName.length);+ }+ if (newFileName.length < 1) {+ throw 'Generated filename is invalid';+ }+ return newFileName;+ }++ function writeTagsToFile(filePath, tags) {+ console.log('Add the tags to: ' + filePath);+ var fileName = extractFileName(filePath);+ var containingDirectoryPath = extractContainingDirectoryPath(filePath);+ var extractedTags = extractTags(filePath);+ for (var i = 0; i < tags.length; i++) {+ // check if tag is already in the tag array+ if (extractedTags.indexOf(tags[i].trim()) < 0) {+ // Adding the new tag+ extractedTags.push(tags[i].trim());+ }+ }+ var newFileName = generateFileName(fileName, extractedTags);+ TSCORE.IO.renameFile(filePath, containingDirectoryPath + TSCORE.dirSeparator + newFileName);+ }++ function removeTagsFromFile(filePath, tags) {+ console.log('Remove the tags from: ' + filePath);+ var fileName = extractFileName(filePath);+ var containingDirectoryPath = extractContainingDirectoryPath(filePath);+ var extractedTags = extractTags(filePath);+ for (var i = 0; i < tags.length; i++) {+ // check if tag is already in the tag array+ var tagLoc = extractedTags.indexOf(tags[i].trim());+ if (tagLoc >= 0) {+ // Remove the new tag+ extractedTags.splice(tagLoc, 1);+ }+ }+ var newFileName = generateFileName(fileName, extractedTags);+ TSCORE.IO.renameFile(filePath, containingDirectoryPath + TSCORE.dirSeparator + newFileName);+ }++ function cleanFileFromTags(filePath) {+ console.log('Cleaning file from tags: ' + filePath);+ var fileTitle = extractTitle(filePath);+ var fileExt = extractFileExtension(filePath);+ var containingDirectoryPath = extractContainingDirectoryPath(filePath);+ if (fileExt.length > 0) {+ fileExt = '.' + fileExt;+ }+ TSCORE.IO.renameFile(filePath, containingDirectoryPath + TSCORE.dirSeparator + fileTitle + fileExt);+ }++ function cleanFilesFromTags(filePathArray) {+ console.log('Cleaning file from tags');+ for (var i = 0; i < filePathArray.length; i++) {+ cleanFileFromTags(filePathArray[i]);+ }+ }++ function addTag(filePathArray, tagArray) {+ console.log('Adding tags to files');+ for (var i = 0; i < filePathArray.length; i++) {+ writeTagsToFile(filePathArray[i], tagArray);+ }+ }++ function removeTags(filePathArray, tagArray) {+ console.log('Remove tags from files');+ for (var i = 0; i < filePathArray.length; i++) {+ removeTagsFromFile(filePathArray[i], tagArray);+ }+ }+ // Moves the location of tag in the file name+ // possible directions should be next, prev, last, first+ function moveTagLocation(filePath, tagName, direction) {+ console.log('Moves the location of tag in the file name: ' + filePath);+ var fileName = extractFileName(filePath);+ var containingDirectoryPath = extractContainingDirectoryPath(filePath);+ var extractedTags = extractTags(filePath);+ var tmpTag;+ for (var i = 0; i < extractedTags.length; i++) {+ // check if tag is already in the tag array+ if (extractedTags[i] === tagName) {+ if (direction === 'prev' && i > 0) {+ tmpTag = extractedTags[i - 1];+ extractedTags[i - 1] = extractedTags[i];+ extractedTags[i] = tmpTag;+ break;+ } else if (direction === 'next' && i < extractedTags.length - 1) {+ tmpTag = extractedTags[i];+ extractedTags[i] = extractedTags[i + 1];+ extractedTags[i + 1] = tmpTag;+ break;+ } else if (direction === 'first' && i > 0) {+ tmpTag = extractedTags[i];+ extractedTags[i] = extractedTags[0];+ extractedTags[0] = tmpTag;+ break;+ }+ }+ }+ var newFileName = generateFileName(fileName, extractedTags);+ TSCORE.IO.renameFile(filePath, containingDirectoryPath + TSCORE.dirSeparator + newFileName);+ }++ // Replaces a tag with a new one+ function renameTag(filePath, oldTag, newTag) {+ console.log('Rename tag for file: ' + filePath);+ var fileName = extractFileName(filePath);+ var containingDirectoryPath = extractContainingDirectoryPath(filePath);+ var extractedTags = extractTags(filePath);+ for (var i = 0; i < extractedTags.length; i++) {+ // check if tag is already in the tag array+ if (extractedTags[i] === oldTag) {+ extractedTags[i] = newTag.trim();+ }+ }+ var newFileName = generateFileName(fileName, extractedTags);+ TSCORE.IO.renameFile(filePath, containingDirectoryPath + TSCORE.dirSeparator + newFileName);+ }++ function changeTitle(filePath, newTitle) {+ console.log('Changing title for file: ' + filePath);+ var containingDirectoryPath = extractContainingDirectoryPath(filePath);+ var extractedTags = extractTags(filePath);+ var fileExt = extractFileExtension(filePath);+ if (fileExt.length > 0) {+ fileExt = '.' + fileExt;+ }+ // TODO generalize generateFileName to support fileTitle & fileExtension+ var newFileName = generateFileName(newTitle, extractedTags);+ TSCORE.IO.renameFile(filePath, containingDirectoryPath + TSCORE.dirSeparator + newFileName + fileExt);+ return true;+ }++ // Removing a tag from a filename+ function removeTag(filePath, tagName) {+ console.log('Removing tag: ' + tagName + ' from ' + filePath);+ var fileName = extractFileName(filePath);+ var containingDirectoryPath = extractContainingDirectoryPath(filePath);+ var tags = extractTags(filePath);+ var newTags = [];+ for (var i = 0; i < tags.length; i++) {+ if (tags[i] !== tagName) {+ newTags.push(tags[i]);+ }+ }+ var newFileName = generateFileName(fileName, newTags);+ TSCORE.IO.renameFile(filePath, containingDirectoryPath + TSCORE.dirSeparator + newFileName);+ }++ // Public API definition+ exports.beginTagContainer = BEGIN_TAG_CONTAINER;+ exports.endTagContainer = END_TAG_CONTAINER;+ exports.extractFileName = extractFileName;+ exports.extractFileNameWithoutExt = extractFileNameWithoutExt;+ exports.extractContainingDirectoryPath = extractContainingDirectoryPath;+ exports.extractContainingDirectoryName = extractContainingDirectoryName;+ exports.extractDirectoryName = extractDirectoryName;+ exports.extractParentDirectoryPath = extractParentDirectoryPath;+ exports.extractFileExtension = extractFileExtension;+ exports.extractTitle = extractTitle;+ exports.formatFileSize = formatFileSize;+ exports.formatDateTime = formatDateTime;+ exports.formatDateTime4Tag = formatDateTime4Tag;+ exports.convertStringToDate = convertStringToDate;+ exports.extractTags = extractTags;+ exports.suggestTags = suggestTags;+ exports.writeTagsToFile = writeTagsToFile;+ exports.moveTagLocation = moveTagLocation;+ exports.renameTag = renameTag;+ exports.removeTag = removeTag;+ exports.removeTags = removeTags;+ exports.addTag = addTag;+ exports.cleanFilesFromTags = cleanFilesFromTags;+ exports.cleanTrailingDirSeparator = cleanTrailingDirSeparator;+ exports.changeTitle = changeTitle;+ exports.stringEndsWith = stringEndsWith;+});