<commit_before>/* 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');
  var tsExtManager = require('tsextmanager');
  var saveAs = require('libs/filesaver.js/FileSaver.min.js');

  function generateSelectOptions(parent, data, selectedId, helpI18NString) {
    parent.empty();
    if (!helpI18NString) {
      helpI18NString = "";
    }
    parent.append($('<option>').text('').attr("data-i18n", helpI18NString).val('false'));
    data.forEach(function(extension) {
      if (selectedId === extension.id) {
        parent.append($('<option>').attr('selected', 'selected').text(extension.name).val(extension.id));
      } else {
        parent.append($('<option>').text(extension.name).val(extension.id));
      }
    });
  }

  function addPerspective(parent, perspectiveId) {
    var perspectiveControl = $('
').append($('
').append($('<select class="form-control flexMaxWidth"></select>')).append($('<button class="btn btn-link" style="width: 40px" data-i18n="[title]ns.dialogs:removePerspectiveTooltip"></button>').click(function() {
      var row4Remove = $(this).parent().parent();
      TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:titleConfirm'), "Do you really want to remove this perspective?", function() {
        row4Remove.remove();
      });
    })));
    generateSelectOptions(perspectiveControl.find('select'), TSCORE.Config.getPerspectiveExtensions(), perspectiveId, "ns.dialogs:choosePerspective");
    perspectiveControl.i18n();
    parent.append(perspectiveControl);
  }

  function addFileType(parent, fileext, viewerId, editorId) {
    var fileTypeControl = $('
').append($('
').append($('<input style="width: 80px" type="text" class="form-control" data-i18n="[placeholder]ns.dialogs:fileExtensionPlaceholder">').val(fileext)).append($('<select class="ftviewer form-control flexMaxWidth"></select>')).append($('<select class="fteditor form-control flexMaxWidth"></select>')).append($('<button style="width: 30px" class="btn btn-link" data-i18n="[title]ns.dialogs:removeFileTypeTooltip"></button>').click(function() {
      var row4Remove = $(this).parent().parent();
      TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:titleConfirm'), "Do you really want to remove this file type?", function() {
        row4Remove.remove();
      });
    })));

    generateSelectOptions(fileTypeControl.find('.ftviewer'), TSCORE.Config.getViewerExtensions(), viewerId, "ns.dialogs:chooseFileViewer");
    generateSelectOptions(fileTypeControl.find('.fteditor'), TSCORE.Config.getEditorExtensions(), editorId, "ns.dialogs:chooseFileEditor");

    fileTypeControl.i18n();
    parent.prepend(fileTypeControl);
  }

  function enableMetaData() {
    if (!TSCORE.PRO) {
      return;
    }
    var isMetaEnabled = $('#enableMetaData').is(':checked');
    if (!isMetaEnabled) {
      $('#writeMetaToSidecarFile').attr('checked', false);
      $('#useOCR').attr('checked', false);
      $('#useTextExtraction').attr('checked', false);
      $('#useGenerateThumbnails').attr('checked', false);
      //TSCORE.Config.setWriteMetaToSidecarFile(false);
    }
    $('#writeMetaToSidecarFile').attr('disabled', !isMetaEnabled);
    $('#useOCR').attr('disabled', !isMetaEnabled);
    $('#useTextExtraction').attr('disabled', !isMetaEnabled);
    $('#useGenerateThumbnails').attr('disabled', !isMetaEnabled);
  }

  function initUI() {
    var defaultTagColor = TSCORE.Config.getDefaultTagColor();
    var defaultTagTextColor = TSCORE.Config.getDefaultTagTextColor();

    var $tagsBackgroundColorChooser = $('#tagsBackgroundColorChooser');
    var $tagsBackgroundColor = $('#tagsBackgroundColor');
    var $tagForegroundColor = $('#tagsForegroundColor');
    $tagsBackgroundColorChooser.simplecolorpicker({
      picker: false
    });
    $tagsBackgroundColorChooser.on('change', function() {
      $tagsBackgroundColor.val($tagsBackgroundColorChooser.val());
    });
    $tagsBackgroundColor.val(defaultTagColor);

    var $tagForegroundColorChooser = $('#tagForegroundColorChooser');
    $tagForegroundColorChooser.simplecolorpicker({
      picker: false
    });
    $tagForegroundColorChooser.on('change', function() {
      $tagForegroundColor.val($tagForegroundColorChooser.val());
    });
    $tagForegroundColor.val(defaultTagTextColor);

    $('#addFileTypeButton').click(function(e) {
      // Fixes reloading of the application by click
      e.preventDefault();
      addFileType($('#fileTypesList'), '', '', '');
      //$('#fileTypesList').parent().animate({ scrollTop: ($('#fileTypesList').height()) }, 'slow');
    });
    $('#addPerspectiveButton').click(function(e) {
      // Fixes reloading of the application by click
      e.preventDefault();
      addPerspective($('#perspectiveList'), '');
    });
    $('#saveSettingsButton').click(function() {
      updateSettings();
      $('#dialogOptions').modal('hide');
    });
    $('#saveSettingsRestartButton').click(function() {
      updateSettings();
      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 (!isElectron) {
      $('#watchCurrentDirectoryControls').hide();
    }
    if (isCordova) {
      $('#trashCanArea').hide();
      $('#exportTagGroupsButton').hide();
      $('#showMainMenuCheckbox').parent().hide();
    }

    $('#exportTagGroupsButton').on('click', exportTagGroups);

    $('#enableMetaData').change(function() {
      enableMetaData();
    });
  }

  function exportTagGroups() {
    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'
    });
    var dateTimeTag = TSCORE.TagUtils.formatDateTime4Tag(new Date(), true);
    saveAs(blob, 'tsm[' + dateTimeTag + '].json');
    console.log('TagGroup Data Exported...');
  }

  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());
    $('#useSearchInSubfolders').attr('checked', TSCORE.Config.getUseSearchInSubfolders());
    $('#maxSearchResultCount').val(TSCORE.Config.getMaxSearchResultCount());
    $('#watchCurrentDirectory').attr('checked', TSCORE.Config.getWatchCurrentDirectory());
    $('#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());
    $('#renamingFileKeyBinding').val(TSCORE.Config.getRenamingFileKeyBinding());
    $('#selectAllKeyBinding').val(TSCORE.Config.getSelectAllKeyBinding());
    $('#showSearchKeyBinding').val(TSCORE.Config.getSearchKeyBinding());
    $('#perspectiveList').empty();
    $('#writeMetaToSidecarFile').attr('checked', TSCORE.Config.getWriteMetaToSidecarFile());
    $('#useDefaultLocationCheckbox').attr('checked', TSCORE.Config.getUseDefaultLocation());
    $('#coloredFileExtensionsEnabledCheckbox').attr('checked', TSCORE.Config.getColoredFileExtensionsEnabled());
    $('#showTagAreaOnStartupCheckbox').attr('checked', TSCORE.Config.getShowTagAreaOnStartup());
    if (TSCORE.PRO) {
      $('#enableMetaData').attr('checked', TSCORE.Config.getEnableMetaData());
      $('#useTrashCan').attr('checked', TSCORE.Config.getUseTrashCan());
      $('#useOCR').attr('checked', TSCORE.Config.getUseOCR());
      $('#useTextExtraction').attr('checked', TSCORE.Config.getUseTextExtraction());
      $('#useGenerateThumbnails').attr('checked', TSCORE.Config.getUseGenerateThumbnails());
      $('#defaultThumbnailSize').val(TSCORE.Config.getDefaultThumbnailSize());
      $('#defaultThumbnailFormat').val(TSCORE.Config.getDefaultThumbnailFormat());
      enableMetaData();
    }

    var $languagesDropdown = $('#languagesList');
    $languagesDropdown.empty();
    TSCORE.Config.getSupportedLanguages().forEach(function(value) {
      if (TSCORE.Config.getInterfaceLanguage() === value.iso) {
        $languagesDropdown.append($('<option>').attr('selected', 'selected').text(value.title).val(value.iso));
      } else {
        $languagesDropdown.append($('<option>').text(value.title).val(value.iso));
      }
    });

    var $thumbnailsizeDropdown = $('#defaultThumbnailSize');
    $thumbnailsizeDropdown.empty();
    TSCORE.Config.getAvailableThumbnailSizes().forEach(function(value) {
      if (TSCORE.Config.getDefaultThumbnailSize() === value) {
        $thumbnailsizeDropdown.append($('<option>').attr('selected', 'selected').text(value + "px").val(value));
      } else {
        $thumbnailsizeDropdown.append($('<option>').text(value + "px").val(value));
      }
    });

    var $thumbnailformatDropdown = $('#defaultThumbnailFormat');
    $thumbnailformatDropdown.empty();
    TSCORE.Config.getAvailableThumbnailFormat().forEach(function(value) {
      if (TSCORE.Config.getDefaultThumbnailFormat() === value) {
        $thumbnailformatDropdown.append($('<option>').attr('selected', 'selected').text(value).val(value));
      } else {
        $thumbnailformatDropdown.append($('<option>').text(value).val(value));
      }
    });

    $('#fileTypesList').empty();

    TSCORE.Config.getActivatedPerspectives().forEach(function(value) {
      addPerspective($('#perspectiveList'), value.id);
    });

    TSCORE.Config.getSupportedFileTypes().sort(stringSorting).forEach(function(value) {
      addFileType($('#fileTypesList'), value.type, value.viewer, value.editor);
    });

    $('#dialogOptions a:first').tab('show');
    $('#dialogOptions').modal({
      backdrop: 'static',
      show: true
    });
  }

  function stringSorting(a, b) {
    if (a.type > b.type) {
      return -1;
    }
    if (a.type = 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.setUseSearchInSubfolders($('#useSearchInSubfolders').is(':checked'));
    TSCORE.Config.setMaxSearchResultCount($('#maxSearchResultCount').val());
    TSCORE.Config.setWatchCurrentDirectory($('#watchCurrentDirectory').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()));
    TSCORE.Config.setSearchKeyBinding(parseKeyBinding($('#showSearchKeyBinding').val()));
    TSCORE.Config.setSelectAllKeyBinding(parseKeyBinding($('#selectAllKeyBinding').val()));
    TSCORE.Config.setRenamingFileKeyBinding(parseKeyBinding($('#renamingFileKeyBinding').val()));
    TSCORE.Config.setDefaultTagColor($('#tagsBackgroundColor').val());
    TSCORE.Config.setDefaultTagTextColor($('#tagsForegroundColor').val());
    if (TSCORE.PRO) {
      //var thumbnailSize = $('#defaultThumbnailSize').val();
      TSCORE.Config.setEnableMetaData($('#enableMetaData').is(':checked'));
      TSCORE.Config.setUseTrashCan($('#useTrashCan').is(':checked'));
      TSCORE.Config.setUseOCR($('#useOCR').is(':checked'));
      TSCORE.Config.setUseTextExtraction($('#useTextExtraction').is(':checked'));
      TSCORE.Config.setUseGenerateThumbnails($('#useGenerateThumbnails').is(':checked'));
      TSCORE.Config.setDefaultThumbnailSize($('#defaultThumbnailSize').val());
      TSCORE.Config.setDefaultThumbnailFormat($('#defaultThumbnailFormat').val());
    }
    var interfaceLang = $('#languagesList').val();
    TSCORE.Config.setInterfaceLanguage($('#languagesList').val());
    TSCORE.switchInterfaceLanguage(interfaceLang);
    TSCORE.Config.setActivatedPerspectives(collectPerspectivesData());
    TSCORE.Config.setSupportedFileTypes(collectSupportedFileTypesData());
    TSCORE.Config.setWriteMetaToSidecarFile($('#writeMetaToSidecarFile').is(':checked'));
    TSCORE.Config.setUseDefaultLocation($('#useDefaultLocationCheckbox').is(':checked'));
    TSCORE.Config.setColoredFileExtensionsEnabled($('#coloredFileExtensionsEnabledCheckbox').is(':checked'));
    TSCORE.Config.setShowTagAreaOnStartup($('#showTagAreaOnStartupCheckbox').is(':checked'));
    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) {
      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;
});
<commit_msg>restoring old code<commit_after>/* 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');
  var tsExtManager = require('tsextmanager');
  var saveAs = require('libs/filesaver.js/FileSaver.min.js');

  function generateSelectOptions(parent, data, selectedId, helpI18NString) {
    parent.empty();
    if (!helpI18NString) {
      helpI18NString = "";
    }
    parent.append($('<option>').text('').attr("data-i18n", helpI18NString).val('false'));
    data.forEach(function(extension) {
      if (selectedId === extension.id) {
        parent.append($('<option>').attr('selected', 'selected').text(extension.name).val(extension.id));
      } else {
        parent.append($('<option>').text(extension.name).val(extension.id));
      }
    });
  }

  function addPerspective(parent, perspectiveId) {
    var perspectiveControl = $('
').append($('
').append($('<select class="form-control flexMaxWidth"></select>')).append($('<button class="btn btn-link" style="width: 40px" data-i18n="[title]ns.dialogs:removePerspectiveTooltip"></button>').click(function() {
      var row4Remove = $(this).parent().parent();
      TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:titleConfirm'), "Do you really want to remove this perspective?", function() {
        row4Remove.remove();
      });
    })));
    generateSelectOptions(perspectiveControl.find('select'), TSCORE.Config.getPerspectiveExtensions(), perspectiveId, "ns.dialogs:choosePerspective");
    perspectiveControl.i18n();
    parent.append(perspectiveControl);
  }

  function addFileType(parent, fileext, viewerId, editorId) {
    var fileTypeControl = $('
').append($('
').append($('<input style="width: 80px" type="text" class="form-control" data-i18n="[placeholder]ns.dialogs:fileExtensionPlaceholder">').val(fileext)).append($('<select class="ftviewer form-control flexMaxWidth"></select>')).append($('<select class="fteditor form-control flexMaxWidth"></select>')).append($('<button style="width: 30px" class="btn btn-link" data-i18n="[title]ns.dialogs:removeFileTypeTooltip"></button>').click(function() {
      var row4Remove = $(this).parent().parent();
      TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:titleConfirm'), "Do you really want to remove this file type?", function() {
        row4Remove.remove();
      });
    })));

    generateSelectOptions(fileTypeControl.find('.ftviewer'), TSCORE.Config.getViewerExtensions(), viewerId, "ns.dialogs:chooseFileViewer");
    generateSelectOptions(fileTypeControl.find('.fteditor'), TSCORE.Config.getEditorExtensions(), editorId, "ns.dialogs:chooseFileEditor");

    fileTypeControl.i18n();
    parent.prepend(fileTypeControl);
  }

  function enableMetaData() {
    if (!TSCORE.PRO) {
      return;
    }
    var isMetaEnabled = $('#enableMetaData').is(':checked');
    if (!isMetaEnabled) {
      $('#writeMetaToSidecarFile').attr('checked', false);
      $('#useOCR').attr('checked', false);
      $('#useTextExtraction').attr('checked', false);
      $('#useGenerateThumbnails').attr('checked', false);
      //TSCORE.Config.setWriteMetaToSidecarFile(false);
    }
    $('#writeMetaToSidecarFile').attr('disabled', !isMetaEnabled);
    $('#useOCR').attr('disabled', !isMetaEnabled);
    $('#useTextExtraction').attr('disabled', !isMetaEnabled);
    $('#useGenerateThumbnails').attr('disabled', !isMetaEnabled);
  }

  function initUI() {
    var defaultTagColor = TSCORE.Config.getDefaultTagColor();
    var defaultTagTextColor = TSCORE.Config.getDefaultTagTextColor();

    var $tagsBackgroundColorChooser = $('#tagsBackgroundColorChooser');
    var $tagsBackgroundColor = $('#tagsBackgroundColor');
    var $tagForegroundColor = $('#tagsForegroundColor');
    $tagsBackgroundColorChooser.simplecolorpicker({
      picker: false
    });
    $tagsBackgroundColorChooser.on('change', function() {
      $tagsBackgroundColor.val($tagsBackgroundColorChooser.val());
    });
    $tagsBackgroundColor.val(defaultTagColor);

    var $tagForegroundColorChooser = $('#tagForegroundColorChooser');
    $tagForegroundColorChooser.simplecolorpicker({
      picker: false
    });
    $tagForegroundColorChooser.on('change', function() {
      $tagForegroundColor.val($tagForegroundColorChooser.val());
    });
    $tagForegroundColor.val(defaultTagTextColor);

    $('#addFileTypeButton').click(function(e) {
      // Fixes reloading of the application by click
      e.preventDefault();
      addFileType($('#fileTypesList'), '', '', '');
      //$('#fileTypesList').parent().animate({ scrollTop: ($('#fileTypesList').height()) }, 'slow');
    });
    $('#addPerspectiveButton').click(function(e) {
      // Fixes reloading of the application by click
      e.preventDefault();
      addPerspective($('#perspectiveList'), '');
    });
    $('#saveSettingsButton').click(function() {
      updateSettings();
      $('#dialogOptions').modal('hide');
    });
    $('#saveSettingsRestartButton').click(function() {
      updateSettings();
      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 (!isElectron) {
      $('#watchCurrentDirectoryControls').hide();
    }
    if (isCordova) {
      $('#trashCanArea').hide();
      $('#exportTagGroupsButton').hide();
      $('#showMainMenuCheckbox').parent().hide();
    }

    $('#exportTagGroupsButton').on('click', exportTagGroups);

    $('#enableMetaData').change(function() {
      enableMetaData();
    });
  }

  function exportTagGroups() {
    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'
    });
    var dateTimeTag = TSCORE.TagUtils.formatDateTime4Tag(new Date(), true);
    saveAs(blob, 'tsm[' + dateTimeTag + '].json');
    console.log('TagGroup Data Exported...');
  }

  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());
    $('#useSearchInSubfolders').attr('checked', TSCORE.Config.getUseSearchInSubfolders());
    $('#maxSearchResultCount').val(TSCORE.Config.getMaxSearchResultCount());
    $('#watchCurrentDirectory').attr('checked', TSCORE.Config.getWatchCurrentDirectory());
    $('#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());
    $('#renamingFileKeyBinding').val(TSCORE.Config.getRenamingFileKeyBinding());
    $('#selectAllKeyBinding').val(TSCORE.Config.getSelectAllKeyBinding());
    $('#showSearchKeyBinding').val(TSCORE.Config.getSearchKeyBinding());
    $('#perspectiveList').empty();
    $('#writeMetaToSidecarFile').attr('checked', TSCORE.Config.getWriteMetaToSidecarFile());
    $('#useDefaultLocationCheckbox').attr('checked', TSCORE.Config.getUseDefaultLocation());
    $('#coloredFileExtensionsEnabledCheckbox').attr('checked', TSCORE.Config.getColoredFileExtensionsEnabled());
    $('#showTagAreaOnStartupCheckbox').attr('checked', TSCORE.Config.getShowTagAreaOnStartup());
    if (TSCORE.PRO) {
      $('#enableMetaData').attr('checked', TSCORE.Config.getEnableMetaData());
      $('#useTrashCan').attr('checked', TSCORE.Config.getUseTrashCan());
      $('#useOCR').attr('checked', TSCORE.Config.getUseOCR());
      $('#useTextExtraction').attr('checked', TSCORE.Config.getUseTextExtraction());
      $('#useGenerateThumbnails').attr('checked', TSCORE.Config.getUseGenerateThumbnails());
      $('#defaultThumbnailSize').val(TSCORE.Config.getDefaultThumbnailSize());
      $('#defaultThumbnailFormat').val(TSCORE.Config.getDefaultThumbnailFormat());
      enableMetaData();
    }

    var $languagesDropdown = $('#languagesList');
    $languagesDropdown.empty();
    TSCORE.Config.getSupportedLanguages().forEach(function(value) {
      if (TSCORE.Config.getInterfaceLanguage() === value.iso) {
        $languagesDropdown.append($('<option>').attr('selected', 'selected').text(value.title).val(value.iso));
      } else {
        $languagesDropdown.append($('<option>').text(value.title).val(value.iso));
      }
    });

    var $thumbnailsizeDropdown = $('#defaultThumbnailSize');
    $thumbnailsizeDropdown.empty();
    TSCORE.Config.getAvailableThumbnailSizes().forEach(function(value) {
      if (TSCORE.Config.getDefaultThumbnailSize() === value) {
        $thumbnailsizeDropdown.append($('<option>').attr('selected', 'selected').text(value + "px").val(value));
      } else {
        $thumbnailsizeDropdown.append($('<option>').text(value + "px").val(value));
      }
    });

    var $thumbnailformatDropdown = $('#defaultThumbnailFormat');
    $thumbnailformatDropdown.empty();
    TSCORE.Config.getAvailableThumbnailFormat().forEach(function(value) {
      if (TSCORE.Config.getDefaultThumbnailFormat() === value) {
        $thumbnailformatDropdown.append($('<option>').attr('selected', 'selected').text(value).val(value));
      } else {
        $thumbnailformatDropdown.append($('<option>').text(value).val(value));
      }
    });

    $('#fileTypesList').empty();

    TSCORE.Config.getActivatedPerspectives().forEach(function(value) {
      addPerspective($('#perspectiveList'), value.id);
    });

    TSCORE.Config.getSupportedFileTypes().sort(stringSorting).forEach(function(value) {
      addFileType($('#fileTypesList'), value.type, value.viewer, value.editor);
    });

    $('#dialogOptions a:first').tab('show');
    $('#dialogOptions').modal({
      backdrop: 'static',
      show: true
    });
  }

  function stringSorting(a, b) {
    if (a.type > b.type) {
      return -1;
    }
    if (a.type = 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.setUseSearchInSubfolders($('#useSearchInSubfolders').is(':checked'));
    TSCORE.Config.setMaxSearchResultCount($('#maxSearchResultCount').val());
    TSCORE.Config.setWatchCurrentDirectory($('#watchCurrentDirectory').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()));
    TSCORE.Config.setSearchKeyBinding(parseKeyBinding($('#showSearchKeyBinding').val()));
    TSCORE.Config.setSelectAllKeyBinding(parseKeyBinding($('#selectAllKeyBinding').val()));
    TSCORE.Config.setRenamingFileKeyBinding(parseKeyBinding($('#renamingFileKeyBinding').val()));
    TSCORE.Config.setDefaultTagColor($('#tagsBackgroundColor').val());
    TSCORE.Config.setDefaultTagTextColor($('#tagsForegroundColor').val());
    if (TSCORE.PRO) {
      //var thumbnailSize = $('#defaultThumbnailSize').val();
      TSCORE.Config.setEnableMetaData($('#enableMetaData').is(':checked'));
      TSCORE.Config.setUseTrashCan($('#useTrashCan').is(':checked'));
      TSCORE.Config.setUseOCR($('#useOCR').is(':checked'));
      TSCORE.Config.setUseTextExtraction($('#useTextExtraction').is(':checked'));
      TSCORE.Config.setUseGenerateThumbnails($('#useGenerateThumbnails').is(':checked'));
      TSCORE.Config.setDefaultThumbnailSize($('#defaultThumbnailSize').val());
      TSCORE.Config.setDefaultThumbnailFormat($('#defaultThumbnailFormat').val());
    }
    var interfaceLang = $('#languagesList').val();
    TSCORE.Config.setInterfaceLanguage(interfaceLang);
    TSCORE.switchInterfaceLanguage(interfaceLang);
    TSCORE.Config.setActivatedPerspectives(collectPerspectivesData());
    TSCORE.Config.setSupportedFileTypes(collectSupportedFileTypesData());
    TSCORE.Config.setWriteMetaToSidecarFile($('#writeMetaToSidecarFile').is(':checked'));
    TSCORE.Config.setUseDefaultLocation($('#useDefaultLocationCheckbox').is(':checked'));
    TSCORE.Config.setColoredFileExtensionsEnabled($('#coloredFileExtensionsEnabledCheckbox').is(':checked'));
    TSCORE.Config.setShowTagAreaOnStartup($('#showTagAreaOnStartupCheckbox').is(':checked'));
    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) {
      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;
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014, D.C.S. LLC. All Rights Reserved. Licensed Software.
 * @private
 */

var log = require('loglevel');
var respoke = require('./respoke');

/**
 * Class for managing the remote media stream.
 * @class respoke.RemoteMedia
 * @constructor
 * @augments respoke.EventEmitter
 * @param {object} params
 * @param {string} params.instanceId - client id
 * @param {object} params.callSettings
 * @param {HTMLVideoElement} params.videoRemoteElement - Pass in an optional html video element to have remote video attached to it.
 * @returns {respoke.RemoteMedia}
 */
module.exports = function (params) {
    "use strict";
    params = params || {};
    /**
     * @memberof! respoke.RemoteMedia
     * @name instanceId
     * @private
     * @type {string}
     */
    var instanceId = params.instanceId;
    var that = respoke.EventEmitter(params);
    delete that.instanceId;
    /**
     * @memberof! respoke.RemoteMedia
     * @name className
     * @type {string}
     */
    that.className = 'respoke.RemoteMedia';
    /**
     * @memberof! respoke.RemoteMedia
     * @name id
     * @type {string}
     */
    that.id = respoke.makeGUID();

    /**
     * @memberof! respoke.RemoteMedia
     * @name client
     * @private
     * @type {respoke.getClient}
     */
    var client = respoke.getClient(instanceId);
    /**
     * @memberof! respoke.RemoteMedia
     * @name element
     * @type {Video}
     */
    that.element = params.videoRemoteElement;
    /**
     * @memberof! respoke.RemoteMedia
     * @name sdpHasAudio
     * @private
     * @type {boolean}
     */
    var sdpHasAudio = false;
    /**
     * @memberof! respoke.RemoteMedia
     * @name sdpHasVideo
     * @private
     * @type {boolean}
     */
    var sdpHasVideo = false;
    /**
     * @memberof! respoke.RemoteMedia
     * @name sdpHasDataChannel
     * @private
     * @type {boolean}
     */
    var sdpHasDataChannel = false;
    /**
     * @memberof! respoke.RemoteMedia
     * @name videoIsMuted
     * @private
     * @type {boolean}
     */
    var videoIsMuted = false;
    /**
     * @memberof! respoke.RemoteMedia
     * @name audioIsMuted
     * @private
     * @type {boolean}
     */
    var audioIsMuted = false;
    /**
     * A timer to make sure we only fire {respoke.RemoteMedia#requesting-media} if the browser doesn't
     * automatically grant permission on behalf of the user. Timer is canceled in onReceiveUserMedia.
     * @memberof! respoke.RemoteMedia
     * @name allowTimer
     * @private
     * @type {number}
     */
    var allowTimer = 0;
    /**
     * @memberof! respoke.RemoteMedia
     * @name callSettings
     * @private
     * @type {object}
     */
    var callSettings = params.callSettings || callSettings || {};
    callSettings.constraints = params.constraints || callSettings.constraints;
    /**
     * @memberof! respoke.RemoteMedia
     * @name mediaOptions
     * @private
     * @type {object}
     */
    var mediaOptions = {
        optional: [
            { DtlsSrtpKeyAgreement: true },
            { RtpDataChannels: false }
        ]
    };
    /**
     * @memberof! respoke.RemoteMedia
     * @name pc
     * @private
     * @type {respoke.PeerConnection}
     */
    var pc = params.pc;
    delete that.pc;
    /**
     * The remote `MediaStream`.
     * @memberof! respoke.RemoteMedia
     * @name stream
     * @type {RTCMediaStream}
     */
    that.stream = null;

    /**
     * Mute remote video stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.muteVideo
     * @fires respoke.RemoteMedia#mute
     */
    that.muteVideo = function () {
        if (videoIsMuted) {
            return;
        }
        that.stream.getVideoTracks().forEach(function eachTrack(track) {
            track.enabled = false;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'video',
            muted: true
        });
        videoIsMuted = true;
    };

    /**
     * Unmute remote video stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.unmuteVideo
     * @fires respoke.RemoteMedia#mute
     */
    that.unmuteVideo = function () {
        if (!videoIsMuted) {
            return;
        }
        that.stream.getVideoTracks().forEach(function eachTrack(track) {
            track.enabled = true;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'video',
            muted: false
        });
        videoIsMuted = false;
    };

    /**
     * Mute remote audio stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.muteAudio
     * @fires respoke.RemoteMedia#mute
     */
    that.muteAudio = function () {
        if (audioIsMuted) {
            return;
        }
        that.stream.getAudioTracks().forEach(function eachTrack(track) {
            track.enabled = false;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'audio',
            muted: true
        });
        audioIsMuted = true;
    };

    /**
     * Unmute remote audio stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.unmuteAudio
     * @fires respoke.RemoteMedia#mute
     */
    that.unmuteAudio = function () {
        if (!audioIsMuted) {
            return;
        }
        that.stream.getAudioTracks().forEach(function eachTrack(track) {
            track.enabled = true;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'audio',
            muted: false
        });
        audioIsMuted = false;
    };

    /**
     * Indicate whether we are receiving video.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.hasVideo
     * @return {boolean}
     */
    that.hasVideo = function () {
        if (that.stream) {
            return (that.stream.getVideoTracks().length > 0);
        }
        return sdpHasVideo;
    };

    /**
     * Indicate whether we are receiving audio.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.hasAudio
     * @return {boolean}
     */
    that.hasAudio = function () {
        if (that.stream) {
            return (that.stream.getAudioTracks().length > 0);
        }
        return sdpHasAudio;
    };

    /**
     * Indicate whether we have media yet.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.hasMedia
     * @return {boolean}
     */
    that.hasMedia = function () {
        return !!that.stream;
    };

    /**
     * Save and parse the SDP
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.setSDP
     * @param {RTCSessionDescription} oSession
     * @private
     */
    that.setSDP = function (oSession) {
        sdpHasVideo = respoke.sdpHasVideo(oSession.sdp);
        sdpHasAudio = respoke.sdpHasAudio(oSession.sdp);
        sdpHasDataChannel = respoke.sdpHasDataChannel(oSession.sdp);
    };

    /**
     * Parse the constraints
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.setConstraints
     * @param {MediaConstraints} constraints
     * @private
     */
    that.setConstraints = function (constraints) {
        that.constraints = constraints;
        sdpHasVideo = respoke.constraintsHasVideo(constraints);
        sdpHasAudio = respoke.constraintsHasAudio(constraints);
    };

    /**
     * Save the media stream
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.setStream
     * @param {MediaStream} str
     * @private
     */
    that.setStream = function (str) {
        if (str) {
            that.stream = str;
            that.element = that.element || document.createElement('video');
            attachMediaStream(that.element, that.stream);
            that.element.autoplay = true;
            setTimeout(that.element.play.bind(that.element));
        }
    };

    /**
     * Stop the stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.stop
     * @fires respoke.RemoteMedia#stop
     */
    that.stop = function () {
        if (!that.stream) {
            return;
        }

        that.stream.numPc -= 1;
        if (that.stream.numPc === 0) {
            that.stream.stop();
            delete respoke.streams[that.constraints];
        }
        that.stream = null;
        /**
         * @event respoke.RemoteMedia#stop
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         */
        that.fire('stop');
    };

    /**
     * Mute local video stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.muteVideo
     * @fires respoke.RemoteMedia#mute
     */
    that.muteVideo = function () {
        if (videoIsMuted) {
            return;
        }
        that.stream.getVideoTracks().forEach(function eachTrack(track) {
            track.enabled = false;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'video',
            muted: true
        });
        videoIsMuted = true;
    };

    /**
     * Unmute local video stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.unmuteVideo
     * @fires respoke.RemoteMedia#mute
     */
    that.unmuteVideo = function () {
        if (!videoIsMuted) {
            return;
        }
        that.stream.getVideoTracks().forEach(function eachTrack(track) {
            track.enabled = true;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'video',
            muted: false
        });
        videoIsMuted = false;
    };

    /**
     * Mute local audio stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.muteAudio
     * @fires respoke.RemoteMedia#mute
     */
    that.muteAudio = function () {
        if (audioIsMuted) {
            return;
        }
        that.stream.getAudioTracks().forEach(function eachTrack(track) {
            track.enabled = false;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'audio',
            muted: true
        });
        audioIsMuted = true;
    };

    /**
     * Unmute local audio stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.unmuteAudio
     * @fires respoke.RemoteMedia#mute
     */
    that.unmuteAudio = function () {
        if (!audioIsMuted) {
            return;
        }
        that.stream.getAudioTracks().forEach(function eachTrack(track) {
            track.enabled = true;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'audio',
            muted: false
        });
        audioIsMuted = false;
    };

    return that;
}; // End respoke.RemoteMedia
<commit_msg>exposing getTracks on remote video<commit_after>/**
 * Copyright (c) 2014, D.C.S. LLC. All Rights Reserved. Licensed Software.
 * @private
 */

var log = require('loglevel');
var respoke = require('./respoke');

/**
 * Class for managing the remote media stream.
 * @class respoke.RemoteMedia
 * @constructor
 * @augments respoke.EventEmitter
 * @param {object} params
 * @param {string} params.instanceId - client id
 * @param {object} params.callSettings
 * @param {HTMLVideoElement} params.videoRemoteElement - Pass in an optional html video element to have remote video attached to it.
 * @returns {respoke.RemoteMedia}
 */
module.exports = function (params) {
    "use strict";
    params = params || {};
    /**
     * @memberof! respoke.RemoteMedia
     * @name instanceId
     * @private
     * @type {string}
     */
    var instanceId = params.instanceId;
    var that = respoke.EventEmitter(params);
    delete that.instanceId;
    /**
     * @memberof! respoke.RemoteMedia
     * @name className
     * @type {string}
     */
    that.className = 'respoke.RemoteMedia';
    /**
     * @memberof! respoke.RemoteMedia
     * @name id
     * @type {string}
     */
    that.id = respoke.makeGUID();

    /**
     * @memberof! respoke.RemoteMedia
     * @name client
     * @private
     * @type {respoke.getClient}
     */
    var client = respoke.getClient(instanceId);
    /**
     * @memberof! respoke.RemoteMedia
     * @name element
     * @type {Video}
     */
    that.element = params.videoRemoteElement;
    /**
     * @memberof! respoke.RemoteMedia
     * @name sdpHasAudio
     * @private
     * @type {boolean}
     */
    var sdpHasAudio = false;
    /**
     * @memberof! respoke.RemoteMedia
     * @name sdpHasVideo
     * @private
     * @type {boolean}
     */
    var sdpHasVideo = false;
    /**
     * @memberof! respoke.RemoteMedia
     * @name sdpHasDataChannel
     * @private
     * @type {boolean}
     */
    var sdpHasDataChannel = false;
    /**
     * @memberof! respoke.RemoteMedia
     * @name videoIsMuted
     * @private
     * @type {boolean}
     */
    var videoIsMuted = false;
    /**
     * @memberof! respoke.RemoteMedia
     * @name audioIsMuted
     * @private
     * @type {boolean}
     */
    var audioIsMuted = false;
    /**
     * A timer to make sure we only fire {respoke.RemoteMedia#requesting-media} if the browser doesn't
     * automatically grant permission on behalf of the user. Timer is canceled in onReceiveUserMedia.
     * @memberof! respoke.RemoteMedia
     * @name allowTimer
     * @private
     * @type {number}
     */
    var allowTimer = 0;
    /**
     * @memberof! respoke.RemoteMedia
     * @name callSettings
     * @private
     * @type {object}
     */
    var callSettings = params.callSettings || callSettings || {};
    callSettings.constraints = params.constraints || callSettings.constraints;
    /**
     * @memberof! respoke.RemoteMedia
     * @name mediaOptions
     * @private
     * @type {object}
     */
    var mediaOptions = {
        optional: [
            { DtlsSrtpKeyAgreement: true },
            { RtpDataChannels: false }
        ]
    };
    /**
     * @memberof! respoke.RemoteMedia
     * @name pc
     * @private
     * @type {respoke.PeerConnection}
     */
    var pc = params.pc;
    delete that.pc;
    /**
     * The remote `MediaStream`.
     * @memberof! respoke.RemoteMedia
     * @name stream
     * @type {RTCMediaStream}
     */
    that.stream = null;

    /**
     * Mute remote video stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.muteVideo
     * @fires respoke.RemoteMedia#mute
     */
    that.muteVideo = function () {
        if (videoIsMuted) {
            return;
        }
        that.stream.getVideoTracks().forEach(function eachTrack(track) {
            track.enabled = false;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'video',
            muted: true
        });
        videoIsMuted = true;
    };

    /**
     * Unmute remote video stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.unmuteVideo
     * @fires respoke.RemoteMedia#mute
     */
    that.unmuteVideo = function () {
        if (!videoIsMuted) {
            return;
        }
        that.stream.getVideoTracks().forEach(function eachTrack(track) {
            track.enabled = true;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'video',
            muted: false
        });
        videoIsMuted = false;
    };

    /**
     * Mute remote audio stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.muteAudio
     * @fires respoke.RemoteMedia#mute
     */
    that.muteAudio = function () {
        if (audioIsMuted) {
            return;
        }
        that.stream.getAudioTracks().forEach(function eachTrack(track) {
            track.enabled = false;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'audio',
            muted: true
        });
        audioIsMuted = true;
    };

    /**
     * Unmute remote audio stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.unmuteAudio
     * @fires respoke.RemoteMedia#mute
     */
    that.unmuteAudio = function () {
        if (!audioIsMuted) {
            return;
        }
        that.stream.getAudioTracks().forEach(function eachTrack(track) {
            track.enabled = true;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'audio',
            muted: false
        });
        audioIsMuted = false;
    };

    /**
     * Indicate whether we are receiving video.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.hasVideo
     * @return {boolean}
     */
    that.hasVideo = function () {
        if (that.stream) {
            return (that.stream.getVideoTracks().length > 0);
        }
        return sdpHasVideo;
    };

    /**
     * Indicate whether we are receiving audio.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.hasAudio
     * @return {boolean}
     */
    that.hasAudio = function () {
        if (that.stream) {
            return (that.stream.getAudioTracks().length > 0);
        }
        return sdpHasAudio;
    };

    /**
     * Indicate whether we have media yet.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.hasMedia
     * @return {boolean}
     */
    that.hasMedia = function () {
        return !!that.stream;
    };

    /**
     * Save and parse the SDP
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.setSDP
     * @param {RTCSessionDescription} oSession
     * @private
     */
    that.setSDP = function (oSession) {
        sdpHasVideo = respoke.sdpHasVideo(oSession.sdp);
        sdpHasAudio = respoke.sdpHasAudio(oSession.sdp);
        sdpHasDataChannel = respoke.sdpHasDataChannel(oSession.sdp);
    };

    /**
     * Parse the constraints
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.setConstraints
     * @param {MediaConstraints} constraints
     * @private
     */
    that.setConstraints = function (constraints) {
        that.constraints = constraints;
        sdpHasVideo = respoke.constraintsHasVideo(constraints);
        sdpHasAudio = respoke.constraintsHasAudio(constraints);
    };

    /**
     * Save the media stream
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.setStream
     * @param {MediaStream} str
     * @private
     */
    that.setStream = function (str) {
        if (str) {
            that.stream = str;
            /**
             * Expose getAudioTracks.
             */
            that.getAudioTracks = that.stream.getAudioTracks.bind(that.stream);
            /**
             * Expose getVideoTracks.
             */
            that.getVideoTracks = that.stream.getVideoTracks.bind(that.stream);
            that.element = that.element || document.createElement('video');
            attachMediaStream(that.element, that.stream);
            that.element.autoplay = true;
            setTimeout(that.element.play.bind(that.element));
        }
    };

    /**
     * Stop the stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.stop
     * @fires respoke.RemoteMedia#stop
     */
    that.stop = function () {
        if (!that.stream) {
            return;
        }

        that.stream.numPc -= 1;
        if (that.stream.numPc === 0) {
            that.stream.stop();
            delete respoke.streams[that.constraints];
        }
        that.stream = null;
        /**
         * @event respoke.RemoteMedia#stop
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         */
        that.fire('stop');
    };

    /**
     * Mute local video stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.muteVideo
     * @fires respoke.RemoteMedia#mute
     */
    that.muteVideo = function () {
        if (videoIsMuted) {
            return;
        }
        that.stream.getVideoTracks().forEach(function eachTrack(track) {
            track.enabled = false;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'video',
            muted: true
        });
        videoIsMuted = true;
    };

    /**
     * Unmute local video stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.unmuteVideo
     * @fires respoke.RemoteMedia#mute
     */
    that.unmuteVideo = function () {
        if (!videoIsMuted) {
            return;
        }
        that.stream.getVideoTracks().forEach(function eachTrack(track) {
            track.enabled = true;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'video',
            muted: false
        });
        videoIsMuted = false;
    };

    /**
     * Mute local audio stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.muteAudio
     * @fires respoke.RemoteMedia#mute
     */
    that.muteAudio = function () {
        if (audioIsMuted) {
            return;
        }
        that.stream.getAudioTracks().forEach(function eachTrack(track) {
            track.enabled = false;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'audio',
            muted: true
        });
        audioIsMuted = true;
    };

    /**
     * Unmute local audio stream.
     * @memberof! respoke.RemoteMedia
     * @method respoke.RemoteMedia.unmuteAudio
     * @fires respoke.RemoteMedia#mute
     */
    that.unmuteAudio = function () {
        if (!audioIsMuted) {
            return;
        }
        that.stream.getAudioTracks().forEach(function eachTrack(track) {
            track.enabled = true;
        });
        /**
         * @event respoke.RemoteMedia#mute
         * @property {string} name - the event name.
         * @property {respoke.RemoteMedia} target
         * @property {string} type - Either "audio" or "video" to specify the type of stream whose muted state
         * has been changed.
         * @property {boolean} muted - Whether the stream is now muted. Will be set to false if mute was turned off.
         */
        that.fire('mute', {
            type: 'audio',
            muted: false
        });
        audioIsMuted = false;
    };

    return that;
}; // End respoke.RemoteMedia
<|endoftext|>


<commit_before>/**
 *
 * This is the base constructor for Simple HTML based multiples.
 *
 * @param userConfig The chart's configuration.
 *
 * @returns {Multiples}
 *
 * @memberof dex/charts/multiples
 *
 */
var Multiples = function (userConfig) {
  var chart;
  var cells;
  var baseInstance;

  var defaults = {
    "parent": "#MultiplesParent",
    "id": "MultiplesId",
    "class": "MultiplesClass",
    "resizable": true,
    "width": "100%",
    "height": "100%",
    "model": {options: {}, attributes: {}},
    "refreshType": "update",
    "cell.height": 300,
    "cell.width": 400,
    "limit": 100
  };

  chart = new dex.component(userConfig, defaults);

  //dex.console.log("CHART", chart);

  baseInstance = chart.config.model.chartConstructor(chart.config.model.attributes || {});

  // Good for debugging
  //chart.subscribe(chart, "attr", function (evt) {
  //  dex.console.log("Setting: '" + evt.attr + "'='" + evt.value + "'");
  //});

  chart.getGuiDefinition = function getGuiDefinition(config) {
    var defaults = {
      "type": "group",
      "name": "Multiples Configuration",
      "contents": [
        {
          "type": "group",
          "name": "Dimensions",
          "contents": [
            {
              "name": "Cell Height",
              "description": "Cell Height",
              "type": "int",
              "minValue": 50,
              "maxValue": 1600,
              "step": 10,
              "initialValue": 300,
              "target": "cell.height"
            },
            {
              "name": "Cell Width",
              "description": "Cell Width",
              "type": "int",
              "minValue": 50,
              "maxValue": 2000,
              "step": 10,
              "initialValue": 400,
              "target": "cell.width"
            }
          ]
        }
      ]
    };

    var guiDef = dex.config.expandAndOverlay(config, defaults);
    guiDef = dex.config.gui.sync(chart, guiDef);

    var biGuiDef = baseInstance.getGuiDefinition();
    // Redefine default gui configuration to be a child of Multiples
    // with the base path of: target='model.attributes.${original_path}'
    // This causes the engine to keep state for a multiples base-chart
    // encapsulated within itself.  IE: No eventing models necessary to
    // communicate basic changes.
    //
    //  We do this by visiting every object withini the gui-def of the
    // name 'target'.  We rename the object key to have the given
    // prefixed target.
    //
    // Basically stitches the basechart gui-config into the Multiples
    // component and simplifies the interface.
    dex.object.visit(biGuiDef, function (obj) {
      //dex.console.log("BI-GUI-DEF Visiting: ", name + "=" + obj);
      if (obj["target"] !== undefined) {
        obj["target"] = "model.attributes." + obj["target"];
        //dex.console.log("Renaming: '" + obj["target"] +
        //  "' to 'model.attributes." + obj["target"] + "'");
      }
    });

    guiDef.contents.push(biGuiDef);
    //dex.console.log("GUI-DEF:", biGuiDef);
    return guiDef;
  };

  chart.render = function render() {
    var config = chart.config;
    var csv = config.csv;
    var $parent = $(config.parent);

    // If we have previous cells, delete them and start with a new array of cells.
    if (cells !== undefined) {
      dex.console.log("-- REMOVING " + cells.length + " CELLS");
      // Unregisters any window resize handlers.
      cells.forEach(function (cell, i) {
        //dex.console.log("-- REMOVING CELL[" + i + "]=", cell);
        cell.deleteChart();
      });
    }

    cells = [];

    //dex.console.log("dex.charts.multiples.SimpleMultiples.baseInstance=", baseInstance,
    //  "CHART=", chart);

    // Remove the children of the chart's parent.
    $parent.empty();

    var frames = csv.getFramesByIndex(0);
    if (frames.frameIndices.length > config.limit) {
      $parent.append("
Limit of " + config.limit + " multiples imposed.  Attempted to chart " +
        frames.frameIndices.length + " multiples.
");
      return chart;
    }
    //dex.console.stacktrace();
    //dex.console.log("SIMPLE-MULTIPLES-FRAMES", frames);

    var $container = $parent.append("

")
      .addClass("dex-multiples")
      .attr("width", config.width)
      .attr("height", config.height);

    frames.frames.forEach(function (frame, i) {
      var cellId = config.id + "_cell_" + i;
      var $cell = $("

")
        .addClass("dex-multiples-cell")
        .attr("id", cellId);

      var title = frames.frameIndices[i];
      var $title = $("

")
        .addClass("dex-multiples-cell-title")
        .text(title)
        .css("width", config.cell.width);
      $cell.append($title);

      var $cellContents = $("

")
        .addClass("dex-multiples-cell-contents")
        .css("width", config.cell.width)
        .css("height", config.cell.height);

      $cell.append($cellContents);

      $container.append($cell);

      var cellConfig = {
        "parent": "#" + cellId + " .dex-multiples-cell-contents",
        "csv": frame
      };

      var cellChart = chart.config.model.chartConstructor(
        dex.config.expandAndOverlay(cellConfig, chart.config.model.attributes || {}));

      cellChart.render();
      cells.push(cellChart);
    });

    return chart;
  };

  chart.update = function () {
    return chart.render();
  };

  $(document).ready(function () {
    //var config = chart.config;
  });

  return chart;
};

module.exports = Multiples;<commit_msg>Total revamp<commit_after>/**
 *
 * This is the base constructor for Simple HTML based multiples.
 *
 * @param userConfig The chart's configuration.
 *
 * @returns {Multiples}
 *
 * @memberof dex/charts/multiples
 *
 */
var Multiples = function (userConfig) {
    var chart;
    var cells;
    var baseInstance;

    var defaults = {
      "parent": "#MultiplesParent",
      "id": "MultiplesId",
      "class": "MultiplesClass",
      "resizable": true,
      "width": "100%",
      "height": "100%",
      "model": {options: {}, attributes: {}},
      "refreshType": "update",
      "cell.height": 300,
      "cell.width": 400,
      "limit": 500,
      "groupBy": ""
    };

    chart = new dex.component(userConfig, defaults);

    //dex.console.log("CHART", chart);

    baseInstance = chart.config.model.chartConstructor(chart.config.model.attributes || {});

    // Good for debugging
    //chart.subscribe(chart, "attr", function (evt) {
    //  dex.console.log("Setting: '" + evt.attr + "'='" + evt.value + "'");
    //});

    chart.getGuiDefinition = function getGuiDefinition(config) {
      var defaults = {
        "type": "group",
        "name": "Multiples Configuration",
        "contents": [
          {
            "type": "group",
            "name": "Cell Dimensions",
            "contents": [
              {
                "name": "Cell Height",
                "description": "Cell Height",
                "type": "int",
                "minValue": 50,
                "maxValue": 1600,
                "step": 10,
                "initialValue": 300,
                "target": "cell.height"
              },
              {
                "name": "Cell Width",
                "description": "Cell Width",
                "type": "int",
                "minValue": 50,
                "maxValue": 2000,
                "step": 10,
                "initialValue": 400,
                "target": "cell.width"
              }
            ]
          },
          {
            "name": "Group By",
            "description": "Pick the columns on which to categorize or group the multiples by.",
            "type": "multiple-choice",
            "choices": chart.config.csv.header,
            "initialValue": chart.config.csv.header[0],
            "target": "groupBy"
          }
        ]
      };

      var guiDef = dex.config.expandAndOverlay(config, defaults);
      guiDef = dex.config.gui.sync(chart, guiDef);

      var biGuiDef = baseInstance.getGuiDefinition();
      // Redefine default gui configuration to be a child of Multiples
      // with the base path of: target='model.attributes.${original_path}'
      // This causes the engine to keep state for a multiples base-chart
      // encapsulated within itself.  IE: No eventing models necessary to
      // communicate basic changes.
      //
      //  We do this by visiting every object withini the gui-def of the
      // name 'target'.  We rename the object key to have the given
      // prefixed target.
      //
      // Basically stitches the basechart gui-config into the Multiples
      // component and simplifies the interface.
      dex.object.visit(biGuiDef, function (obj) {
        //dex.console.log("BI-GUI-DEF Visiting: ", name + "=" + obj);
        if (obj !== undefined && obj !== null && obj["target"] !== undefined
          && obj["target"] !== null) {
          obj["target"] = "model.attributes." + obj["target"];
          //dex.console.log("Renaming: '" + obj["target"] +
          //  "' to 'model.attributes." + obj["target"] + "'");
        }
      });

      guiDef.contents.push(biGuiDef);
      //dex.console.log("GUI-DEF:", biGuiDef);
      return guiDef;
    };

    chart.render = function render() {
      var config = chart.config;
      var csv = config.csv;
      var $parent = $(config.parent);

      // If we have previous cells, delete them and start with a new array of cells.
      if (cells !== undefined) {
        dex.console.log("-- REMOVING " + cells.length + " CELLS");
        // Unregisters any window resize handlers.
        cells.forEach(function (cell, i) {
          //dex.console.log("-- REMOVING CELL[" + i + "]=", cell);
          cell.deleteChart();
        });
      }

      cells = [];

      //dex.console.log("dex.charts.multiples.SimpleMultiples.baseInstance=", baseInstance,
      //  "CHART=", chart);

      // Remove the children of the chart's parent.
      $parent.empty();

      //dex.console.log("GROUPING-BY: ", config.groupBy);
      var frames;

      if (config.groupBy !== undefined && config.groupBy.length > 0) {
        //dex.console.log("GROUP-BY", config.groupBy);
        //var columnNames = config.groupBy.split(",");
        frames = csv.getFramesByColumns(config.groupBy);
      }
      else {
        frames = csv.getFramesByIndex(0);
      }

      if (frames.frameIndices.length > config.limit) {
        $parent.append("
Limit of " + config.limit + " multiples imposed.  Attempted to chart " +
          frames.frameIndices.length + " multiples.
");
        return chart;
      }
      //dex.console.stacktrace();
      //dex.console.log("SIMPLE-MULTIPLES-FRAMES", frames);

      var $container = $parent.append("

")
        .addClass("dex-multiples")
        .attr("width", config.width)
        .attr("height", config.height);

      frames.frames.forEach(function (frame, i) {
        var cellId = config.id + "_cell_" + i;
        var $cell = $("

")
          .addClass("dex-multiples-cell")
          .attr("id", cellId);

        var title = frames.frameIndices[i];
        var $title = $("

")
          .addClass("dex-multiples-cell-title")
          .text(title)
          .css("width", config.cell.width);
        $cell.append($title);

        var $cellContents = $("

")
          .addClass("dex-multiples-cell-contents")
          .css("width", config.cell.width)
          .css("height", config.cell.height);

        $cell.append($cellContents);

        $container.append($cell);

        var cellConfig = {
          "parent": "#" + cellId + " .dex-multiples-cell-contents",
          "csv": frame
        };

        var cellChart = chart.config.model.chartConstructor(
          dex.config.expandAndOverlay(cellConfig, chart.config.model.attributes || {}));

        cellChart.render();
        cells.push(cellChart);
      });

      return chart;
    };

    chart.update = function () {
      return chart.render();
    };

    $(document).ready(function () {
      //var config = chart.config;
    });

    return chart;
  }
;

module.exports = Multiples;<|endoftext|>


<commit_before>"use strict";

angular.module("hikeio").
	factory("selection", ["$window", function($window) {

		var SelectionService = function() {
		};

		SelectionService.prototype.clear = function(query) {
			if ($window.getSelection) {
				if ($window.getSelection().empty) {
					$window.getSelection().empty();
				} else if ($window.getSelection().removeAllRanges) {
					$window.getSelection().removeAllRanges();
				}
			} else if ($window.document.selection) {
				$window.document.selection.empty();
			}
		};

		return new SelectionService();
	}]);
<commit_msg>Blur active element, otherwise in IE it looks like the contenteditable still has focus, even though input doesn't work.<commit_after>"use strict";

angular.module("hikeio").
	factory("selection", ["$window", function($window) {

		var SelectionService = function() {
		};

		SelectionService.prototype.clear = function(query) {
			if ($window.getSelection) {
				if ($window.getSelection().empty) {
					$window.getSelection().empty();
				} else if ($window.getSelection().removeAllRanges) {
					$window.getSelection().removeAllRanges();
				}
			} else if ($window.document.selection) {
				$window.document.selection.empty();
			}
			$window.document.activeElement.blur();
		};

		return new SelectionService();
	}]);
<|endoftext|>


<commit_before>
module.exports = {
  bsClass:
    'Base CSS class and prefix for the component. Generally one should only ' +
    'change `bsClass` to provide new, non-Bootstrap, CSS styles for a ' +
    'component.',
  bsStyle: 'Component visual or contextual style variants.',
  bsSize: 'Component size variations.',
  componentClass: 'You can use a custom element type for this component.',

  eventKey:
    'A unique identifier for the Component, the `eventKey` makes it distinguishable from others in a set. ' +
    'Similar to React\'s `key` prop, in that it only needs to be ' +
    'unique amoungst the Components siblings, not globally. '
};
<commit_msg>fix lint<commit_after>
module.exports = {
  bsClass:
    'Base CSS class and prefix for the component. Generally one should only ' +
    'change `bsClass` to provide new, non-Bootstrap, CSS styles for a ' +
    'component.',
  bsStyle: 'Component visual or contextual style variants.',
  bsSize: 'Component size variations.',
  componentClass: 'You can use a custom element type for this component.',

  eventKey:
    'A unique identifier for the Component, the `eventKey` makes it distinguishable from others in a set. ' +
    'Similar to React\'s `key` prop, in that it only needs to be ' +
    'unique amoungst the Components siblings, not globally. ',
};
<|endoftext|>


<commit_before>var settings = Ti.App.Properties.getObject('app-survey-settings');
var distanceData = module.exports =  {
    'METRIC': [
        {
            id: 0,
            icon: '/images/icons/material/plastic.png',
            valueLabel: '0 - 10',
            captionLabel: 'Meter',
            type: 'large'
        },
        {
            id: 1,
            icon: '/images/icons/material/foam.png',
            valueLabel: '10 - 50',
            captionLabel: 'Meter',
        type: 'large'
        },
        {
            id: 2,
            icon: '/images/icons/material/glass.png',
            valueLabel: '50 - 100',
            captionLabel: 'Meter',
        type: 'large'
        },
        {
            id: 3,
            icon: '/images/icons/material/metal.png',
            valueLabel: '100+',
            captionLabel: 'Meter',
        type: 'large'
        }
    ],
    'IMPERIAL': [
        {
            id: 0,
            icon: '/images/icons/material/plastic.png',
            valueLabel: '0 - 11',
            captionLabel: 'Yards',
            type: 'large'
        },
        {
            id: 1,
            icon: '/images/icons/material/foam.png',
            valueLabel: '11 - 55',
            captionLabel: 'Yards',
        type: 'large'
        },
        {
            id: 2,
            icon: '/images/icons/material/glass.png',
            valueLabel: '55 - 110',
            captionLabel: 'Yards',
        type: 'large'
        },
        {
            id: 3,
            icon: '/images/icons/material/metal.png',
            valueLabel: '110+',
            captionLabel: 'Yards',
        type: 'large'
        }
    ],
};

<commit_msg>minor fix in distance<commit_after>var settings = Ti.App.Properties.getObject('app-survey-settings');
var distanceData = module.exports =  {
    'METRIC': [
        {
            id: 0,
            icon: '/images/icons/material/plastic.png',
            valueLabel: '0 - 10',
            captionLabel: 'Meter',
            type: 'large'
        },
        {
            id: 1,
            icon: '/images/icons/material/foam.png',
            valueLabel: '10 - 50',
            captionLabel: 'Meter',
            type: 'large'
        },
        {
            id: 2,
            icon: '/images/icons/material/glass.png',
            valueLabel: '50 - 100',
            captionLabel: 'Meter',
            type: 'large'
        },
        {
            id: 3,
            icon: '/images/icons/material/metal.png',
            valueLabel: '100+',
            captionLabel: 'Meter',
            type: 'large'
        }
    ],
    'IMPERIAL': [
        {
            id: 0,
            icon: '/images/icons/material/plastic.png',
            valueLabel: '0 - 11',
            captionLabel: 'Yards',
            type: 'large'
        },
        {
            id: 1,
            icon: '/images/icons/material/foam.png',
            valueLabel: '11 - 55',
            captionLabel: 'Yards',
            type: 'large'
        },
        {
            id: 2,
            icon: '/images/icons/material/glass.png',
            valueLabel: '55 - 110',
            captionLabel: 'Yards',
            type: 'large'
        },
        {
            id: 3,
            icon: '/images/icons/material/metal.png',
            valueLabel: '110+',
            captionLabel: 'Yards',
            type: 'large'
        }
    ],
};

<|endoftext|>


<commit_before>/*
 * C S O U N D
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 */

// Setup a single global AudioContext object
var CSOUND_AUDIO_CONTEXT = CSOUND_AUDIO_CONTEXT ||
  (function() {

    try {
      var AudioContext = window.AudioContext || window.webkitAudioContext;
      return new AudioContext();
    }
    catch(error) {

      console.log('Web Audio API is not supported in this browser');
    }
    return null;
  }());

// Global singleton variables
var AudioWorkletGlobalScope = AudioWorkletGlobalScope || {};
var CSOUND;

class CsoundNodeFactory {

  // Utility function to load a script and set callback
  static loadScript(src, callback) {
    var script = document.createElement('script');
    script.src = src;
    script.onload = callback;
    document.head.appendChild(script);
  }

  static importScripts(script_base='./') {
    return new Promise((resolve) => {
      CsoundNodeFactory.loadScript(script_base + 'libcsound.js', () => {
        AudioWorkletGlobalScope.WAM = {}
        let WAM = AudioWorkletGlobalScope.WAM;

        WAM["ENVIRONMENT"] = "WEB";
        WAM["print"] = (t) => console.log(t);
        WAM["printErr"] = (t) => console.log(t);
        WAM["locateFile"] = (f) => script_base + f;

        AudioWorkletGlobalScope.libcsound(WAM).then(() => {

          // Cache cwrap functions into CSOUND global object
          CSOUND = {
            new: WAM.cwrap('CsoundObj_new', ['number'], null),
            compileCSD: WAM.cwrap('CsoundObj_compileCSD', ['number'], ['number', 'string']),
            evaluateCode: WAM.cwrap('CsoundObj_evaluateCode', ['number'], ['number', 'string']),
            readScore: WAM.cwrap('CsoundObj_readScore', ['number'], ['number', 'string']),
            reset: WAM.cwrap('CsoundObj_reset', null, ['number']),
            getOutputBuffer: WAM.cwrap('CsoundObj_getOutputBuffer', ['number'], ['number']),
            getInputBuffer: WAM.cwrap('CsoundObj_getInputBuffer', ['number'], ['number']),
            getControlChannel: WAM.cwrap('CsoundObj_getControlChannel', ['number'], ['number', 'string']),
            setControlChannel: WAM.cwrap('CsoundObj_setControlChannel', null, ['number', 'string', 'number']),
            setStringChannel: WAM.cwrap('CsoundObj_setStringChannel', null, ['number', 'string', 'string']),
            getKsmps: WAM.cwrap('CsoundObj_getKsmps', ['number'], ['number']),
            performKsmps: WAM.cwrap('CsoundObj_performKsmps', ['number'], ['number']),
            render: WAM.cwrap('CsoundObj_render', null, ['number']),
            getInputChannelCount: WAM.cwrap('CsoundObj_getInputChannelCount', ['number'], ['number']),
            getOutputChannelCount: WAM.cwrap('CsoundObj_getOutputChannelCount', ['number'], ['number']),
            getTableLength: WAM.cwrap('CsoundObj_getTableLength', ['number'], ['number', 'number']),
            getTable: WAM.cwrap('CsoundObj_getTable', ['number'], ['number', 'number']),
            getZerodBFS: WAM.cwrap('CsoundObj_getZerodBFS', ['number'], ['number']),
            setMidiCallbacks: WAM.cwrap('CsoundObj_setMidiCallbacks', null, ['number']),
            pushMidiMessage: WAM.cwrap('CsoundObj_pushMidiMessage', null, ['number', 'number', 'number', 'number']),
            setOutputChannelCallback: WAM.cwrap('CsoundObj_setOutputChannelCallback', null, ['number', 'number']),
            compileOrc: WAM.cwrap('CsoundObj_compileOrc', 'number', ['number', 'string']),
            setOption: WAM.cwrap('CsoundObj_setOption', null, ['number', 'string']),
            prepareRT: WAM.cwrap('CsoundObj_prepareRT', null, ['number']),
            getScoreTime: WAM.cwrap('CsoundObj_getScoreTime', null, ['number']),
            setTable: WAM.cwrap('CsoundObj_setTable', null, ['number', 'number', 'number', 'number']),
            openAudioOut: WAM.cwrap('CsoundObj_openAudioOut', null, ['number']),
            closeAudioOut: WAM.cwrap('CsoundObj_closeAudioOut', null, ['number']),
            play: WAM.cwrap('CsoundObj_play', null, ['number']),
            pause: WAM.cwrap('CsoundObj_pause', null, ['number']),
            destroy: WAM.cwrap('CsoundObj_destroy', null, ['number'])
          }

          resolve();
        })
      })
    });
  }

  static createNode(inputChannelCount=1, outputChannelCount=2) {
    var spn = CSOUND_AUDIO_CONTEXT.createScriptProcessor(0, inputChannelCount, outputChannelCount);
    //bufferSize = audioProcessNode.bufferSize;
    // console.error("bufferSize = " + bufferSize);
    spn.inputCount = inputChannelCount;
    spn.outputCount = outputChannelCount;

    let cs = CSOUND.new();
    CSOUND.setMidiCallbacks(cs);
    CSOUND.setOption(cs, "-odac");
    CSOUND.setOption(cs, "-+rtaudio=null");

    let CsoundMixin = {
      csound: cs,
      compiled: false,
      msgCallback: (t) => console.log(t),
      csoundRunning: false,
      csoundOutputBuffer: null,
      csoundInputBuffer: null,
      zerodBFS: 1.0,
      offset: 32,
      ksmps: 32,
      running: false,
      started: false,
      cnt: 0,
      res: 0,

      writeToFS(filePath, blobData) {
        let FS = WAM["FS"];
        let stream = FS.open(filePath, 'w+');
        let buf = new Uint8Array(blobData)
        FS.write(stream, buf, 0, buf.length, 0);
        FS.close(stream);
      },

      compileCSD(filePath) {
        CSOUND.prepareRT(this.csound);
        CSOUND.compileCSD(this.csound, filePath);
        this.compiled = true;
      },

      compileOrc(orcString) {
        CSOUND.prepareRT(this.csound);
        CSOUND.compileOrc(this.csound, orcString);
        this.compiled = true;
      },

      setOption(option) {
        CSOUND.setOption(this.csound, option);
      },

      render(filePath) {
        CSOUND.compileCSD(this.csound, filePath);
        CSOUND.render(this.csound);
        this.compiled = false;
      },

      evaluateCode(codeString) {
        CSOUND.evaluateCode(this.csound, codeString);
      },

      readScore(scoreString) {
        CSOUND.readScore(this.csound, scoreString);
      },

      setControlChannel(channelName, value) {
        CSOUND.setControlChannel(this.csound, channelName, value);
      },

      setStringChannel(channelName, value) {
        CSOUND.setStringChannel(this.csound, channelName, value);
      },

      start() {
        if(this.started == false) {
          let ksmps = CSOUND.getKsmps(this.csound);
          this.ksmps = ksmps;
          this.cnt = ksmps;

          //hardcode for now, but has to match Node's input/output settings
          this.nchnls = 2;
          this.nchnls_i = 1;

          CSOUND.prepareRT(this.csound);
          CSOUND.play(this.csound);

          let outputPointer = CSOUND.getOutputBuffer(this.csound);
          this.csoundOutputBuffer = new Float32Array(WAM.HEAP8.buffer, outputPointer, ksmps * outputChannelCount);
          let inputPointer = CSOUND.getInputBuffer(this.csound);
          this.csoundInputBuffer = new Float32Array(WAM.HEAP8.buffer, inputPointer, ksmps * inputChannelCount);
          this.zerodBFS = CSOUND.getZerodBFS(this.csound);
          this.started = true;
        }
        this.running = true;

      },

      reset() {
        CSOUND.reset(this.csound);
        this.compiled = false;
      },

      destroy() {
        CSOUND.destroy(this.csound);
      },

      play() {
        CSOUND.play(this.csound);
      },

      setMessageCallback(msgCallback) {
        this.msgCallBack = msgCallback;
      },

      pushMidiMessage(byte1, byte2, byte3) {
        CSOUNDpushMidiMessage(this.csound, byte1, byte2, byte3);
      },

      onaudioprocess(e) {
        if (this.csoundOutputBuffer == null ||
          this.running == false) {
          return;
        }

        let input = e.inputBuffer;
        let output = e.outputBuffer;

        let bufferLen = output.getChannelData(0).length;

        let csOut = this.csoundOutputBuffer;
        let csIn = this.csoundInputBuffer;
        let ksmps = this.ksmps;
        let zerodBFS = this.zerodBFS;

        let cnt = this.cnt;
        let nchnls = this.nchnls;
        let res = this.res;

        for (let i = 0; i < bufferLen; i++, cnt++) {
          if(cnt >= ksmps && res == 0) {
            // if we need more samples from Csound
            res = CSOUND.performKsmps(this.csound);
            cnt = 0;
          }

          for (let channel = 0; channel < input.numberOfChannels; channel++) {
            let inputChannel = input.getChannelData(channel);
            csIn[cnt*nchnls + channel] = inputChannel[i] * zerodBFS;
          }
          for (let channel = 0; channel < output.numberOfChannels; channel++) {
            let outputChannel = output.getChannelData(channel);
            if(res == 0)
              outputChannel[i] = csOut[cnt*nchnls + channel] / zerodBFS;
            else
              outputChannel[i] = 0;
          }
        }

        this.cnt = cnt;
        this.res = res;
      }
    }

    let WAM = AudioWorkletGlobalScope.WAM;
    WAM["print"] = (t) => spn.msgCallback(t);
    WAM["printErr"] = (t) => spn.msgCallback(t);

    return Object.assign(spn,CsoundMixin);
  }
}
<commit_msg>fixed typo<commit_after>/*
 * C S O U N D
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 */

// Setup a single global AudioContext object
var CSOUND_AUDIO_CONTEXT = CSOUND_AUDIO_CONTEXT ||
  (function() {

    try {
      var AudioContext = window.AudioContext || window.webkitAudioContext;
      return new AudioContext();
    }
    catch(error) {

      console.log('Web Audio API is not supported in this browser');
    }
    return null;
  }());

// Global singleton variables
var AudioWorkletGlobalScope = AudioWorkletGlobalScope || {};
var CSOUND;

class CsoundNodeFactory {

  // Utility function to load a script and set callback
  static loadScript(src, callback) {
    var script = document.createElement('script');
    script.src = src;
    script.onload = callback;
    document.head.appendChild(script);
  }

  static importScripts(script_base='./') {
    return new Promise((resolve) => {
      CsoundNodeFactory.loadScript(script_base + 'libcsound.js', () => {
        AudioWorkletGlobalScope.WAM = {}
        let WAM = AudioWorkletGlobalScope.WAM;

        WAM["ENVIRONMENT"] = "WEB";
        WAM["print"] = (t) => console.log(t);
        WAM["printErr"] = (t) => console.log(t);
        WAM["locateFile"] = (f) => script_base + f;

        AudioWorkletGlobalScope.libcsound(WAM).then(() => {

          // Cache cwrap functions into CSOUND global object
          CSOUND = {
            new: WAM.cwrap('CsoundObj_new', ['number'], null),
            compileCSD: WAM.cwrap('CsoundObj_compileCSD', ['number'], ['number', 'string']),
            evaluateCode: WAM.cwrap('CsoundObj_evaluateCode', ['number'], ['number', 'string']),
            readScore: WAM.cwrap('CsoundObj_readScore', ['number'], ['number', 'string']),
            reset: WAM.cwrap('CsoundObj_reset', null, ['number']),
            getOutputBuffer: WAM.cwrap('CsoundObj_getOutputBuffer', ['number'], ['number']),
            getInputBuffer: WAM.cwrap('CsoundObj_getInputBuffer', ['number'], ['number']),
            getControlChannel: WAM.cwrap('CsoundObj_getControlChannel', ['number'], ['number', 'string']),
            setControlChannel: WAM.cwrap('CsoundObj_setControlChannel', null, ['number', 'string', 'number']),
            setStringChannel: WAM.cwrap('CsoundObj_setStringChannel', null, ['number', 'string', 'string']),
            getKsmps: WAM.cwrap('CsoundObj_getKsmps', ['number'], ['number']),
            performKsmps: WAM.cwrap('CsoundObj_performKsmps', ['number'], ['number']),
            render: WAM.cwrap('CsoundObj_render', null, ['number']),
            getInputChannelCount: WAM.cwrap('CsoundObj_getInputChannelCount', ['number'], ['number']),
            getOutputChannelCount: WAM.cwrap('CsoundObj_getOutputChannelCount', ['number'], ['number']),
            getTableLength: WAM.cwrap('CsoundObj_getTableLength', ['number'], ['number', 'number']),
            getTable: WAM.cwrap('CsoundObj_getTable', ['number'], ['number', 'number']),
            getZerodBFS: WAM.cwrap('CsoundObj_getZerodBFS', ['number'], ['number']),
            setMidiCallbacks: WAM.cwrap('CsoundObj_setMidiCallbacks', null, ['number']),
            pushMidiMessage: WAM.cwrap('CsoundObj_pushMidiMessage', null, ['number', 'number', 'number', 'number']),
            setOutputChannelCallback: WAM.cwrap('CsoundObj_setOutputChannelCallback', null, ['number', 'number']),
            compileOrc: WAM.cwrap('CsoundObj_compileOrc', 'number', ['number', 'string']),
            setOption: WAM.cwrap('CsoundObj_setOption', null, ['number', 'string']),
            prepareRT: WAM.cwrap('CsoundObj_prepareRT', null, ['number']),
            getScoreTime: WAM.cwrap('CsoundObj_getScoreTime', null, ['number']),
            setTable: WAM.cwrap('CsoundObj_setTable', null, ['number', 'number', 'number', 'number']),
            openAudioOut: WAM.cwrap('CsoundObj_openAudioOut', null, ['number']),
            closeAudioOut: WAM.cwrap('CsoundObj_closeAudioOut', null, ['number']),
            play: WAM.cwrap('CsoundObj_play', null, ['number']),
            pause: WAM.cwrap('CsoundObj_pause', null, ['number']),
            destroy: WAM.cwrap('CsoundObj_destroy', null, ['number'])
          }

          resolve();
        })
      })
    });
  }

  static createNode(inputChannelCount=1, outputChannelCount=2) {
    var spn = CSOUND_AUDIO_CONTEXT.createScriptProcessor(0, inputChannelCount, outputChannelCount);
    //bufferSize = audioProcessNode.bufferSize;
    // console.error("bufferSize = " + bufferSize);
    spn.inputCount = inputChannelCount;
    spn.outputCount = outputChannelCount;

    let cs = CSOUND.new();
    CSOUND.setMidiCallbacks(cs);
    CSOUND.setOption(cs, "-odac");
    CSOUND.setOption(cs, "-+rtaudio=null");

    let CsoundMixin = {
      csound: cs,
      compiled: false,
      msgCallback: (t) => console.log(t),
      csoundRunning: false,
      csoundOutputBuffer: null,
      csoundInputBuffer: null,
      zerodBFS: 1.0,
      offset: 32,
      ksmps: 32,
      running: false,
      started: false,
      cnt: 0,
      res: 0,

      writeToFS(filePath, blobData) {
        let FS = WAM["FS"];
        let stream = FS.open(filePath, 'w+');
        let buf = new Uint8Array(blobData)
        FS.write(stream, buf, 0, buf.length, 0);
        FS.close(stream);
      },

      compileCSD(filePath) {
        CSOUND.prepareRT(this.csound);
        CSOUND.compileCSD(this.csound, filePath);
        this.compiled = true;
      },

      compileOrc(orcString) {
        CSOUND.prepareRT(this.csound);
        CSOUND.compileOrc(this.csound, orcString);
        this.compiled = true;
      },

      setOption(option) {
        CSOUND.setOption(this.csound, option);
      },

      render(filePath) {
        CSOUND.compileCSD(this.csound, filePath);
        CSOUND.render(this.csound);
        this.compiled = false;
      },

      evaluateCode(codeString) {
        CSOUND.evaluateCode(this.csound, codeString);
      },

      readScore(scoreString) {
        CSOUND.readScore(this.csound, scoreString);
      },

      setControlChannel(channelName, value) {
        CSOUND.setControlChannel(this.csound, channelName, value);
      },

      setStringChannel(channelName, value) {
        CSOUND.setStringChannel(this.csound, channelName, value);
      },

      start() {
        if(this.started == false) {
          let ksmps = CSOUND.getKsmps(this.csound);
          this.ksmps = ksmps;
          this.cnt = ksmps;

          //hardcode for now, but has to match Node's input/output settings
          this.nchnls = 2;
          this.nchnls_i = 1;

          CSOUND.prepareRT(this.csound);
          CSOUND.play(this.csound);

          let outputPointer = CSOUND.getOutputBuffer(this.csound);
          this.csoundOutputBuffer = new Float32Array(WAM.HEAP8.buffer, outputPointer, ksmps * outputChannelCount);
          let inputPointer = CSOUND.getInputBuffer(this.csound);
          this.csoundInputBuffer = new Float32Array(WAM.HEAP8.buffer, inputPointer, ksmps * inputChannelCount);
          this.zerodBFS = CSOUND.getZerodBFS(this.csound);
          this.started = true;
        }
        this.running = true;

      },

      reset() {
        CSOUND.reset(this.csound);
        this.compiled = false;
      },

      destroy() {
        CSOUND.destroy(this.csound);
      },

      play() {
        CSOUND.play(this.csound);
      },

      setMessageCallback(msgCallback) {
        this.msgCallBack = msgCallback;
      },

      midiMessage(byte1, byte2, byte3) {
        CSOUND.pushMidiMessage(this.csound, byte1, byte2, byte3);
      },

      onaudioprocess(e) {
        if (this.csoundOutputBuffer == null ||
          this.running == false) {
          return;
        }

        let input = e.inputBuffer;
        let output = e.outputBuffer;

        let bufferLen = output.getChannelData(0).length;

        let csOut = this.csoundOutputBuffer;
        let csIn = this.csoundInputBuffer;
        let ksmps = this.ksmps;
        let zerodBFS = this.zerodBFS;

        let cnt = this.cnt;
        let nchnls = this.nchnls;
        let res = this.res;

        for (let i = 0; i < bufferLen; i++, cnt++) {
          if(cnt >= ksmps && res == 0) {
            // if we need more samples from Csound
            res = CSOUND.performKsmps(this.csound);
            cnt = 0;
          }

          for (let channel = 0; channel < input.numberOfChannels; channel++) {
            let inputChannel = input.getChannelData(channel);
            csIn[cnt*nchnls + channel] = inputChannel[i] * zerodBFS;
          }
          for (let channel = 0; channel < output.numberOfChannels; channel++) {
            let outputChannel = output.getChannelData(channel);
            if(res == 0)
              outputChannel[i] = csOut[cnt*nchnls + channel] / zerodBFS;
            else
              outputChannel[i] = 0;
          }
        }

        this.cnt = cnt;
        this.res = res;
      }
    }

    let WAM = AudioWorkletGlobalScope.WAM;
    WAM["print"] = (t) => spn.msgCallback(t);
    WAM["printErr"] = (t) => spn.msgCallback(t);

    return Object.assign(spn,CsoundMixin);
  }
}
<|endoftext|>