<commit_before>'use strict';
/* eslint-env node */
const { readFileSync } = require('fs');
const path = require('path');
const Rollup = require('broccoli-rollup');
const Funnel = require('broccoli-funnel');
const findLib = require('./find-lib');
const funnelLib = require('./funnel-lib');
const { VERSION } = require('./version');
const WriteFile = require('broccoli-file-creator');
const StringReplace = require('broccoli-string-replace');
const { RELEASE, DEBUG, toConst } = require('./features');
const GlimmerTemplatePrecompiler = require('./glimmer-template-compiler');
const VERSION_PLACEHOLDER = /VERSION_STRING_PLACEHOLDER/g;
const { stripIndent } = require('common-tags');
const toES5 = require('./to-es5');

module.exports.routerES = function _routerES() {
  return new Rollup(findLib('router_js', 'lib'), {
    rollup: {
      external: ['route-recognizer', 'rsvp'],
      entry: 'router.js',
      plugins: [{
        transform(code, id) {
          if (/[^t][^e][^r]\/router\.js$/.test(id)) {
            code += 'export { Transition } from \'./router/transition\';\n'
          } else if (/\/router\/handler-info\/[^\/]+\.js$/.test(id)) {
            code = code.replace(/\'router\//g, '\'../');
          }
          code = code.replace(/import\ Promise\ from \'rsvp\/promise\'/g, 'import { Promise } from \'rsvp\'')
          return {
            code: code,
            map: { mappings: '' }
          };
        }
      }],
      targets: [{
        dest: 'router.js',
        format: 'es'
      }]
    },
    annotation: 'router.js'
  });
}

module.exports.jquery = function _jquery() {
  return new Funnel(findLib('jquery'), {
    files: ['jquery.js'],
    destDir: 'jquery',
    annotation: 'jquery'
  });
}

module.exports.internalLoader = function _internalLoader() {
  return new Funnel('packages/loader/lib', {
    files: ['index.js'],
    getDestinationPath() {
      return 'loader.js';
    },
    annotation: 'internal loader'
  });
}

module.exports.qunit = function _qunit() {
  return new Funnel(findLib('qunitjs'), {
    files: ['qunit.js', 'qunit.css'],
    destDir: 'qunit',
    annotation: 'qunit'
  });
}

module.exports.emberGlimmerES = function _emberGlimmerES() {
  let pkg = new Funnel('packages/ember-glimmer/lib', {
    include: ['**/*.js', '**/*.hbs'],
    destDir: 'ember-glimmer'
  });

  return new GlimmerTemplatePrecompiler(pkg, {
    persist: true,
    glimmer: require('@glimmer/compiler'),
    annotation: 'ember-glimmer es'
  });
}

module.exports.handlebarsES = function _handlebars() {
  return new Rollup(findLib('handlebars', 'lib'), {
    rollup: {
      entry: 'handlebars/compiler/base.js',
      dest: 'handlebars.js',
      format: 'es',
      exports: 'named',
      plugins: [handlebarsFix()]
    },
    annotation: 'handlebars'
  })
}

function handlebarsFix() {
  var HANDLEBARS_PARSER = /\/parser.js$/;
  return {
    load: function(id) {
      if (HANDLEBARS_PARSER.test(id)) {
        var code = readFileSync(id, 'utf8');
        return {
          code: code
            .replace('exports.__esModule = true;', '')
            .replace('exports[\'default\'] = handlebars;', 'export default handlebars;'),

          map: { mappings: null }
        };
      }
    }
  }
}

module.exports.rsvpES = function _rsvpES() {
  let lib = path.resolve(path.dirname(require.resolve('rsvp')), '../lib');
  return new Rollup(lib, {
    rollup: {
      entry: 'rsvp.js',
      dest: 'rsvp.js',
      format: 'es',
      exports: 'named'
    },
    annotation: 'rsvp.js'
  });
}

module.exports.backburnerES = function _backburnerES() {
  return funnelLib('backburner.js', 'dist/es6', {
    files: ['backburner.js'],
    annotation: 'backburner es'
  });
}

module.exports.dagES = function _dagES() {
  return funnelLib('dag-map', {
    files: ['dag-map.js'],
    annotation: 'dag-map es'
  });
}

module.exports.routeRecognizerES = function _routeRecognizerES() {
  return funnelLib('route-recognizer', {
    files: ['route-recognizer.es.js'],
    getDestinationPath() {
      return 'route-recognizer.js'
    },
    annotation: 'route-recognizer es'
  });
}

module.exports.simpleHTMLTokenizerES = function _simpleHTMLTokenizerES() {
  return new Rollup(findLib('simple-html-tokenizer', 'dist/es6'), {
    rollup: {
      entry: 'index.js',
      dest: 'simple-html-tokenizer.js',
      format: 'es',
      exports: 'named'
    },
    annotation: 'simple-html-tokenizer es'
  })
}

module.exports.emberPkgES = function _emberPkgES(name, rollup, externs) {
  if (rollup) {
    return new Rollup(`packages/${name}/lib`, {
      rollup: {
        entry: 'index.js',
        dest: `${name}.js`,
        external: externs,
        format: 'es',
        exports: 'named'
      },
      annotation: `rollup ${name}`
    });
  }

  return new Funnel(`packages/${name}/lib`, {
    exclude: ['.gitkeep'],
    destDir: name,
    annotation: `${name} es`
  });
}

module.exports.glimmerPkgES = function _glimmerPkgES(name, externs = []) {
  return new Rollup(findLib(name, 'dist/modules'), {
    rollup: {
      entry: 'index.js',
      dest: `${name}.js`,
      external: externs,
      format: 'es',
      exports: 'named'
    },
    annotation: `${name} es`
  });
}

module.exports.emberTestsES = function _emberTestES(name) {
  return new Funnel(`packages/${name}/tests`, {
    exclude: ['.gitkeep'],
    destDir: `${name}/tests`,
    annotation: `${name} tests es`
  });
}

module.exports.nodeModuleUtils = function _nodeModuleUtils() {
  return new Funnel('packages/node-module/lib', {
    files: ['node-module.js']
  });
}

module.exports.emberVersionES = function _emberVersionES() {
  let content = 'export default ' + JSON.stringify(VERSION) + ';\n';
  return new WriteFile('ember/version.js', content, {
    annotation: 'ember/version'
  });
}

module.exports.emberLicense = function _emberLicense() {
  let license = new Funnel('generators', {
    files: ['license.js'],
    annotation: 'license'
  });

  return new StringReplace(license, {
    files: ['license.js'],
    patterns: [{
      match: VERSION_PLACEHOLDER,
      replacement: VERSION
    }],
    annotation: 'license'
  });
}

module.exports.emberFeaturesES = function _emberFeaturesES(production = false) {
  let FEATURES = production ? RELEASE : DEBUG;
  let content = stripIndent`
    import { ENV } from 'ember-environment';
    import { assign } from 'ember-utils';
    export const DEFAULT_FEATURES = ${JSON.stringify(FEATURES)};
    export const FEATURES = assign(DEFAULT_FEATURES, ENV.FEATURES);

    ${Object.keys(toConst(FEATURES)).map((FEATURE) => {
      return `export const ${FEATURE} = FEATURES["${FEATURE.replace(/_/g, '-').toLowerCase()}"];`
    }).join('\n')}
  `;

  return new WriteFile('ember/features.js', content, {
    annotation: `ember/features ${production ? 'production' : 'debug' }`
  });
}

module.exports.packageManagerJSONs = function _packageManagerJSONs() {
  var packageJsons = new Funnel('config/package_manager_files', {
    include: ['*.json'],
    destDir: '/',
    annotation: 'package.json'
  });

  packageJsons = new StringReplace(packageJsons, {
    patterns: [{
      match: VERSION_PLACEHOLDER,
      replacement: VERSION
    }],
    files: ['*.json']
  });
  packageJsons._annotation = 'package.json VERSION';
  return packageJsons;
}

module.exports.nodeTests = function _nodeTests() {
  return new Funnel('tests', {
    include: ['**/*/*.js']
  });
}

module.exports.rollupEmberMetal = function _rollupEmberMetal(tree, options) {
  options = Object.assign({ transformModules: false, annotation: 'ember metal' }, options);
  let emberMetalES5 = toES5(tree, options);
  return toES5(new Rollup(emberMetalES5, {
    rollup: {
      entry: `index.js`,
      dest: `ember-metal.js`,
      moduleId: 'ember-metal',
      external: [
        'node-module',
        'ember-babel',
        'ember-debug',
        'ember-environment',
        'ember-utils',
        '@glimmer/reference',
        'require',
        'backburner',
        'ember-console',
        'ember-env-flags',
        'ember/features'
      ],
      format: 'amd',
      exports: 'named'
    },
    annotation: `rollup ember-metal`
  }), { transformDefine: true });
}<commit_msg>added detection for backslash folder delimiter<commit_after>'use strict';
/* eslint-env node */
const { readFileSync } = require('fs');
const path = require('path');
const Rollup = require('broccoli-rollup');
const Funnel = require('broccoli-funnel');
const findLib = require('./find-lib');
const funnelLib = require('./funnel-lib');
const { VERSION } = require('./version');
const WriteFile = require('broccoli-file-creator');
const StringReplace = require('broccoli-string-replace');
const { RELEASE, DEBUG, toConst } = require('./features');
const GlimmerTemplatePrecompiler = require('./glimmer-template-compiler');
const VERSION_PLACEHOLDER = /VERSION_STRING_PLACEHOLDER/g;
const { stripIndent } = require('common-tags');
const toES5 = require('./to-es5');

module.exports.routerES = function _routerES() {
  return new Rollup(findLib('router_js', 'lib'), {
    rollup: {
      external: ['route-recognizer', 'rsvp'],
      entry: 'router.js',
      plugins: [{
        transform(code, id) {
          if (/[^t][^e][^r]\/router\.js$/.test(id)) {
            code += 'export { Transition } from \'./router/transition\';\n'
          } else if (/\/router\/handler-info\/[^\/]+\.js$/.test(id)) {
            code = code.replace(/\'router\//g, '\'../');
          }
          code = code.replace(/import\ Promise\ from \'rsvp\/promise\'/g, 'import { Promise } from \'rsvp\'')
          return {
            code: code,
            map: { mappings: '' }
          };
        }
      }],
      targets: [{
        dest: 'router.js',
        format: 'es'
      }]
    },
    annotation: 'router.js'
  });
}

module.exports.jquery = function _jquery() {
  return new Funnel(findLib('jquery'), {
    files: ['jquery.js'],
    destDir: 'jquery',
    annotation: 'jquery'
  });
}

module.exports.internalLoader = function _internalLoader() {
  return new Funnel('packages/loader/lib', {
    files: ['index.js'],
    getDestinationPath() {
      return 'loader.js';
    },
    annotation: 'internal loader'
  });
}

module.exports.qunit = function _qunit() {
  return new Funnel(findLib('qunitjs'), {
    files: ['qunit.js', 'qunit.css'],
    destDir: 'qunit',
    annotation: 'qunit'
  });
}

module.exports.emberGlimmerES = function _emberGlimmerES() {
  let pkg = new Funnel('packages/ember-glimmer/lib', {
    include: ['**/*.js', '**/*.hbs'],
    destDir: 'ember-glimmer'
  });

  return new GlimmerTemplatePrecompiler(pkg, {
    persist: true,
    glimmer: require('@glimmer/compiler'),
    annotation: 'ember-glimmer es'
  });
}

module.exports.handlebarsES = function _handlebars() {
  return new Rollup(findLib('handlebars', 'lib'), {
    rollup: {
      entry: 'handlebars/compiler/base.js',
      dest: 'handlebars.js',
      format: 'es',
      exports: 'named',
      plugins: [handlebarsFix()]
    },
    annotation: 'handlebars'
  })
}

function handlebarsFix() {
  var HANDLEBARS_PARSER = /[\/\\]parser.js$/;
  return {
    load: function(id) {
      if (HANDLEBARS_PARSER.test(id)) {
        var code = readFileSync(id, 'utf8');
        return {
          code: code
            .replace('exports.__esModule = true;', '')
            .replace('exports[\'default\'] = handlebars;', 'export default handlebars;'),

          map: { mappings: null }
        };
      }
    }
  }
}

module.exports.rsvpES = function _rsvpES() {
  let lib = path.resolve(path.dirname(require.resolve('rsvp')), '../lib');
  return new Rollup(lib, {
    rollup: {
      entry: 'rsvp.js',
      dest: 'rsvp.js',
      format: 'es',
      exports: 'named'
    },
    annotation: 'rsvp.js'
  });
}

module.exports.backburnerES = function _backburnerES() {
  return funnelLib('backburner.js', 'dist/es6', {
    files: ['backburner.js'],
    annotation: 'backburner es'
  });
}

module.exports.dagES = function _dagES() {
  return funnelLib('dag-map', {
    files: ['dag-map.js'],
    annotation: 'dag-map es'
  });
}

module.exports.routeRecognizerES = function _routeRecognizerES() {
  return funnelLib('route-recognizer', {
    files: ['route-recognizer.es.js'],
    getDestinationPath() {
      return 'route-recognizer.js'
    },
    annotation: 'route-recognizer es'
  });
}

module.exports.simpleHTMLTokenizerES = function _simpleHTMLTokenizerES() {
  return new Rollup(findLib('simple-html-tokenizer', 'dist/es6'), {
    rollup: {
      entry: 'index.js',
      dest: 'simple-html-tokenizer.js',
      format: 'es',
      exports: 'named'
    },
    annotation: 'simple-html-tokenizer es'
  })
}

module.exports.emberPkgES = function _emberPkgES(name, rollup, externs) {
  if (rollup) {
    return new Rollup(`packages/${name}/lib`, {
      rollup: {
        entry: 'index.js',
        dest: `${name}.js`,
        external: externs,
        format: 'es',
        exports: 'named'
      },
      annotation: `rollup ${name}`
    });
  }

  return new Funnel(`packages/${name}/lib`, {
    exclude: ['.gitkeep'],
    destDir: name,
    annotation: `${name} es`
  });
}

module.exports.glimmerPkgES = function _glimmerPkgES(name, externs = []) {
  return new Rollup(findLib(name, 'dist/modules'), {
    rollup: {
      entry: 'index.js',
      dest: `${name}.js`,
      external: externs,
      format: 'es',
      exports: 'named'
    },
    annotation: `${name} es`
  });
}

module.exports.emberTestsES = function _emberTestES(name) {
  return new Funnel(`packages/${name}/tests`, {
    exclude: ['.gitkeep'],
    destDir: `${name}/tests`,
    annotation: `${name} tests es`
  });
}

module.exports.nodeModuleUtils = function _nodeModuleUtils() {
  return new Funnel('packages/node-module/lib', {
    files: ['node-module.js']
  });
}

module.exports.emberVersionES = function _emberVersionES() {
  let content = 'export default ' + JSON.stringify(VERSION) + ';\n';
  return new WriteFile('ember/version.js', content, {
    annotation: 'ember/version'
  });
}

module.exports.emberLicense = function _emberLicense() {
  let license = new Funnel('generators', {
    files: ['license.js'],
    annotation: 'license'
  });

  return new StringReplace(license, {
    files: ['license.js'],
    patterns: [{
      match: VERSION_PLACEHOLDER,
      replacement: VERSION
    }],
    annotation: 'license'
  });
}

module.exports.emberFeaturesES = function _emberFeaturesES(production = false) {
  let FEATURES = production ? RELEASE : DEBUG;
  let content = stripIndent`
    import { ENV } from 'ember-environment';
    import { assign } from 'ember-utils';
    export const DEFAULT_FEATURES = ${JSON.stringify(FEATURES)};
    export const FEATURES = assign(DEFAULT_FEATURES, ENV.FEATURES);

    ${Object.keys(toConst(FEATURES)).map((FEATURE) => {
      return `export const ${FEATURE} = FEATURES["${FEATURE.replace(/_/g, '-').toLowerCase()}"];`
    }).join('\n')}
  `;

  return new WriteFile('ember/features.js', content, {
    annotation: `ember/features ${production ? 'production' : 'debug' }`
  });
}

module.exports.packageManagerJSONs = function _packageManagerJSONs() {
  var packageJsons = new Funnel('config/package_manager_files', {
    include: ['*.json'],
    destDir: '/',
    annotation: 'package.json'
  });

  packageJsons = new StringReplace(packageJsons, {
    patterns: [{
      match: VERSION_PLACEHOLDER,
      replacement: VERSION
    }],
    files: ['*.json']
  });
  packageJsons._annotation = 'package.json VERSION';
  return packageJsons;
}

module.exports.nodeTests = function _nodeTests() {
  return new Funnel('tests', {
    include: ['**/*/*.js']
  });
}

module.exports.rollupEmberMetal = function _rollupEmberMetal(tree, options) {
  options = Object.assign({ transformModules: false, annotation: 'ember metal' }, options);
  let emberMetalES5 = toES5(tree, options);
  return toES5(new Rollup(emberMetalES5, {
    rollup: {
      entry: `index.js`,
      dest: `ember-metal.js`,
      moduleId: 'ember-metal',
      external: [
        'node-module',
        'ember-babel',
        'ember-debug',
        'ember-environment',
        'ember-utils',
        '@glimmer/reference',
        'require',
        'backburner',
        'ember-console',
        'ember-env-flags',
        'ember/features'
      ],
      format: 'amd',
      exports: 'named'
    },
    annotation: `rollup ember-metal`
  }), { transformDefine: true });
}
<|endoftext|>


<commit_before>export default [
  {
    user: {
      firstName: 'John',
      lastName: 'Renner',
      dce: 'jmr2258',
    },
    officer: {
      title: 'President',
      email: 'president',
      primaryOfficer: true,
      userDce: 'jmr2258',
      startDate: new Date(2015, 7, 22),
    },
  },
  {
    user: {
      firstName: 'Brian',
      lastName: 'Besmanoff',
      dce: 'bmb6316',
    },
    officer: {
      title: 'Vice President',
      email: 'vp',
      primaryOfficer: true,
      userDce: 'bmb6316',
      startDate: new Date(2015, 7, 22),
    },
  },
  {
    user: {
      firstName: 'Ben',
      lastName: 'Kantor',
      dce: 'bdk3079',
    },
    officer: {
      title: 'Treasurer',
      email: 'treasurer',
      primaryOfficer: true,
      userDce: 'bdk3079',
      startDate: new Date(2015, 7, 22),
    },
  },
  {
    user: {
      firstName: 'Jesse',
      lastName: 'Jurman',
      dce: 'jrj2703',
    },
    officer: {
      title: 'Secretary',
      email: 'secretary',
      primaryOfficer: true,
      userDce: 'jrj2703',
      startDate: new Date(2015, 7, 22),
    },
  },
  {
    user: {
      firstName: 'Dominic',
      lastName: 'Cicilio',
      dce: 'dpc2061',
    },
    officer: {
      title: 'Public Relations Head',
      email: 'pr',
      primaryOfficer: false,
      userDce: 'dpc2061',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Public Relations',
      description: 'pr',
    },
  },
  {
    user: {
      firstName: 'Kristen',
      lastName: 'Mills',
      dce: 'knm5153',
    },
    officer: {
      title: 'Technology Head',
      email: 'technology',
      primaryOfficer: true,
      userDce: 'knm5153',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Technology',
      description: 'tech',
    },
  },
  {
    user: {
      firstName: 'John',
      lastName: 'Grischuk',
      dce: 'jdg6544',
    },
    officer: {
      title: 'Projects Head',
      email: 'projects',
      primaryOfficer: false,
      userDce: 'jdg6544',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Projects',
      description: 'projects',
    },
  },
  {
    user: {
      firstName: 'Matt',
      lastName: 'Mokary',
      dce: 'mxm6060',
    },
    officer: {
      title: 'Mentoring Head',
      email: 'mentoring',
      primaryOfficer: false,
      userDce: 'mxm6060',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Mentoring',
      description: 'mentoring',
    },
  },
  {
    user: {
      firstName: 'Colin',
      lastName: 'Fausnaught',
      dce: 'cjf1613',
    },
    officer: {
      title: 'Talks Head',
      email: 'talks',
      primaryOfficer: false,
      userDce: 'cjf1613',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Talks',
      description: 'talks',
    },
  },
  {
    user: {
      firstName: 'Justin',
      lastName: 'Peterson',
      dce: 'jmp3833',
    },
    officer: {
      title: 'Fundraising Head',
      email: 'fundraising',
      primaryOfficer: false,
      userDce: 'jmp3833',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Fundraising',
      description: 'fundraising',
    },
  },
  {
    user: {
      firstName: 'Matt',
      lastName: 'Smicinski',
      dce: 'mjs7769',
    },
    officer: {
      title: 'Lab Operations Head',
      email: 'labops',
      primaryOfficer: false,
      userDce: 'mjs7769',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Lab Operations',
      description: 'lab ops',
    },
  },
  {
    user: {
      firstName: 'Wade',
      lastName: 'Mauger',
      dce: 'wam9729',
    },
    officer: {
      title: 'Events Head',
      email: 'events',
      primaryOfficer: false,
      userDce: 'wam9729',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Events',
      description: 'events',
    },
  },
  {
    user: {
      firstName: 'Kayla',
      lastName: 'Nussbaum',
      dce: 'kxn3867',
    },
    officer: {
      title: 'Winterball Head',
      email: 'winterball',
      primaryOfficer: false,
      userDce: 'kxn3867',
      startDate: new Date(2015, 7, 22),
    },
    committee: {
      name: 'Winterball',
      description: 'winterball',
    },
  },

];
<commit_msg>updated them offers<commit_after>export default [
  {
    user: {
      firstName: 'Kayla',
      lastName: 'Davis',
      dce: 'kd9205',
    },
    officer: {
      title: 'President',
      email: 'president',
      primaryOfficer: true,
      userDce: 'kd9205',
      startDate: new Date(2016, 7, 22),
    },
  },
  {
    user: {
      firstName: 'Michael',
      lastName: 'Timbrook',
      dce: 'mpt2360',
    },
    officer: {
      title: 'Vice President',
      email: 'vp',
      primaryOfficer: true,
      userDce: 'mpt2360',
      startDate: new Date(2016, 7, 22),
    },
  },
  {
    user: {
      firstName: 'Carter',
      lastName: 'Buce',
      dce: 'cmb9400',
    },
    officer: {
      title: 'Treasurer',
      email: 'treasurer',
      primaryOfficer: true,
      userDce: 'cmb9400',
      startDate: new Date(2016, 7, 22),
    },
  },
  {
    user: {
      firstName: 'Marianna',
      lastName: 'Sternefeld',
      dce: 'mxs7353',
    },
    officer: {
      title: 'Secretary',
      email: 'secretary',
      primaryOfficer: true,
      userDce: 'mxs7353',
      startDate: new Date(2016, 7, 22),
    },
  },
  {
    user: {
      firstName: 'Christina',
      lastName: 'Howard',
      dce: 'chh2538',
    },
    officer: {
      title: 'Public Relations Head',
      email: 'pr',
      primaryOfficer: false,
      userDce: 'chh2538',
      startDate: new Date(2016, 7, 22),
    },
    committee: {
      name: 'Public Relations',
      description: 'pr',
    },
  },
  {
    user: {
      firstName: 'Dylan',
      lastName: 'Vuz',
      dce: 'dpv1592',
    },
    officer: {
      title: 'Technology Head',
      email: 'technology',
      primaryOfficer: true,
      userDce: 'dpv1592',
      startDate: new Date(2016, 7, 22),
    },
    committee: {
      name: 'Tech Committee',
      description: 'Best Committee',
    },
  },
  {
    user: {
      firstName: 'Robert',
      lastName: 'McLaughlin',
      dce: 'rem7127',
    },
    officer: {
      title: 'Projects Head',
      email: 'projects',
      primaryOfficer: false,
      userDce: 'rem7127',
      startDate: new Date(2016, 7, 22),
    },
    committee: {
      name: 'Projects',
      description: 'projects',
    },
  },
  {
    user: {
      firstName: 'John',
      lastName: 'Renner',
      dce: 'jmr2258',
    },
    officer: {
      title: 'Mentoring Head',
      email: 'mentoring',
      primaryOfficer: false,
      userDce: 'jmr2258',
      startDate: new Date(2016, 7, 22),
    },
    committee: {
      name: 'Mentoring',
      description: 'mentoring',
    },
  },
  {
    user: {
      firstName: 'Cameron',
      lastName: 'Braverman',
      dce: 'cjb9973',
    },
    officer: {
      title: 'Talks Head',
      email: 'talks',
      primaryOfficer: false,
      userDce: 'cjb9973',
      startDate: new Date(2016, 7, 22),
    },
    committee: {
      name: 'Talks',
      description: 'talks',
    },
  },
  {
    user: {
      firstName: 'Steven',
      lastName: 'Greenberg',
      dce: 'sjg8961',
    },
    officer: {
      title: 'Lab Operations Head',
      email: 'labops',
      primaryOfficer: false,
      userDce: 'sjg8961',
      startDate: new Date(2016, 7, 22),
    },
    committee: {
      name: 'Lab Operations',
      description: 'lab ops',
    },
  },
  {
    user: {
      firstName: 'Stephen',
      lastName: 'Cioffi',
      dce: 'scc3459',
    },
    officer: {
      title: 'Events Head',
      email: 'events',
      primaryOfficer: false,
      userDce: 'scc3459',
      startDate: new Date(2016, 7, 22),
    },
    committee: {
      name: 'Events',
      description: 'events',
    },
  },
];
<|endoftext|>


<commit_before>moduleAid.VERSION = '1.1.4';

this.CustomizableUI = null;

this.specialWidgets = ['separator', 'spring', 'spacer'];

this.trackSpecialWidgets = {
	onWidgetAdded: function(aId, aCurrentArea, aCurrentPosition) {
		if(aId.startsWith(objName+'-special-')) {
			var type = aId.split(objName+'-special-')[1];
			CustomizableUI.removeWidgetFromArea(aId);

			if(type != 'spring' || aCurrentArea != 'nav-bar') {
				CustomizableUI.addWidgetToArea(type, aCurrentArea, aCurrentPosition);
			}

			// Note: not setting WIDE_PANEL_CLASS to these widgets, in case they are inserted in the menu-panel,
			// so they can be more accuratelly placed.
		}
	}
};

this.trackStatusBar = function() {
	windowMediator.callOnAll(moveStatusBar, 'navigator:browser');
};

// move the status bar onto our container
this.moveStatusBar = function(aWindow) {
	if(aWindow.closed || aWindow.willClose) { return; }

	var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName]._statusBar.node;
	var sStack = aWindow.document.getElementById(objName+'-status-bar-stack');
	if(sBar.parentNode == sStack) { return; }

	if(!aWindow[objName]._statusBar) {
		aWindow[objName]._statusBar = {
			node: sBar,
			originalParent: sBar.parentNode
		};
	}

	setAttribute(sBar, 'removable', 'true');
	CustomizableUI.removeWidgetFromArea('status-bar');
	sStack.insertBefore(sBar, sStack.firstChild);
};

this.moveStatusBarBack = function(aWindow) {
	if(aWindow[objName]) {
		var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName]._statusBar.node;
		if(aWindow[objName]._statusBar.originalParent) {
			if(aWindow[objName]._statusBar.originalParent != sBar.parentNode) { aWindow[objName]._statusBar.originalParent.appendChild(sBar); }
		}
		else { aWindow.document.getElementById('addon-bar').appendChild(sBar); }
		setAttribute(sBar, 'removable', 'false');
	}
};

// see https://bugzilla.mozilla.org/show_bug.cgi?id=989338
this.preventLosingCustomizeData = function() {
	windowMediator.callOnAll(function(aWindow) {
		moveStatusBarBack(aWindow);
	}, 'navigator:browser');
	try { CustomizableUI.addWidgetToArea('status-bar', 'addon-bar'); } catch(ex) {}
};

moduleAid.LOADMODULE = function() {
	var scope = {};
	Cu.import("resource:///modules/CustomizableUI.jsm", scope);
	CustomizableUI = scope.CustomizableUI;

	// Make sure our special widgets aren't actually appended anywhere, they are just placeholders
	CustomizableUI.addListener(trackSpecialWidgets);

	for(var i=0; i<specialWidgets.length; i++) {
		CustomizableUI.removeWidgetFromArea(objName+'-special-'+specialWidgets[i]);
	}

	alwaysRunOnShutdown.push(preventLosingCustomizeData);

	overlayAid.overlayURI('chrome://'+objPathString+'/content/options.xul', 'optionsAustralis');
	overlayAid.overlayURI('chrome://browser/content/browser.xul', 'australisBar', null,
		function(aWindow) {
			moduleAid.load('compatibilityFix/sandboxFixes'); // We need our add-on bar registered for this

			prepareObject(window);

			moveStatusBar(aWindow);
			listenOnce(aWindow, 'unload', trackStatusBar);

			window[objName].moduleAid.load('australis', true);
		},
		function(aWindow) {
			moveStatusBarBack(aWindow);

			delete aWindow[objName]._statusBar;
			removeObject(aWindow);
		}
	);
};

moduleAid.UNLOADMODULE = function() {
	moduleAid.unload('compatibilityFix/sandboxFixes');

	overlayAid.removeOverlayURI('chrome://browser/content/browser.xul', 'australisBar');
	overlayAid.removeOverlayURI('chrome://'+objPathString+'/content/options.xul', 'optionsAustralis');

	preventLosingCustomizeData();

	CustomizableUI.removeListener(trackSpecialWidgets);
};
<commit_msg>better handling of status bar across multiple windows + little boo boo<commit_after>moduleAid.VERSION = '1.1.5';

this.CustomizableUI = null;

this.specialWidgets = ['separator', 'spring', 'spacer'];

this.trackSpecialWidgets = {
	onWidgetAdded: function(aId, aCurrentArea, aCurrentPosition) {
		if(aId.startsWith(objName+'-special-')) {
			var type = aId.split(objName+'-special-')[1];
			CustomizableUI.removeWidgetFromArea(aId);

			if(type != 'spring' || aCurrentArea != 'nav-bar') {
				CustomizableUI.addWidgetToArea(type, aCurrentArea, aCurrentPosition);
			}

			// Note: not setting WIDE_PANEL_CLASS to these widgets, in case they are inserted in the menu-panel,
			// so they can be more accuratelly placed.
		}
	}
};

// move the status bar onto our container
this.moveStatusBar = function(aWindow) {
	if(aWindow.closed || aWindow.willClose) { return; }

	var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName]._statusBar.node;
	var sStack = aWindow.document.getElementById(objName+'-status-bar-stack');
	if(sBar.parentNode == sStack) { return; }

	if(!aWindow[objName]._statusBar) {
		aWindow[objName]._statusBar = {
			node: sBar,
			originalParent: sBar.parentNode
		};
	}

	setAttribute(sBar, 'removable', 'true');
	if(CustomizableUI.getWidget('status-bar').areaType) {
		CustomizableUI.removeWidgetFromArea('status-bar');

		// because when we do the above command, the node is physically removed from all windows, we have to put it back
		windowMediator.callOnAll(function(aWindow) {
			if(!aWindow[objName]) { return; }
			moveStatusBarNode(aWindow);
		}, 'navigator:browser');
	} else {
		// this should never be triggered, but...
		moveStatusBarNode(aWindow);
	}
};

this.moveStatusBarNode = function(aWindow) {
	var sStack = aWindow.document.getElementById(objName+'-status-bar-stack');
	if(!aWindow[objName]._statusBar || aWindow[objName]._statusBar.node.parentNode == sStack) { return; }

	sStack.insertBefore(aWindow[objName]._statusBar.node, sStack.firstChild);
};

this.moveStatusBarBack = function(aWindow) {
	if(aWindow[objName]) {
		var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName]._statusBar.node;
		if(aWindow[objName]._statusBar.originalParent) {
			if(aWindow[objName]._statusBar.originalParent != sBar.parentNode) { aWindow[objName]._statusBar.originalParent.appendChild(sBar); }
		}
		else { aWindow.document.getElementById('addon-bar').appendChild(sBar); }
		setAttribute(sBar, 'removable', 'false');
	}
};

// see https://bugzilla.mozilla.org/show_bug.cgi?id=989338
this.preventLosingCustomizeData = function() {
	windowMediator.callOnAll(function(aWindow) {
		moveStatusBarBack(aWindow);
	}, 'navigator:browser');
	try { CustomizableUI.addWidgetToArea('status-bar', 'addon-bar'); } catch(ex) {}
};

moduleAid.LOADMODULE = function() {
	var scope = {};
	Cu.import("resource:///modules/CustomizableUI.jsm", scope);
	CustomizableUI = scope.CustomizableUI;

	// Make sure our special widgets aren't actually appended anywhere, they are just placeholders
	CustomizableUI.addListener(trackSpecialWidgets);

	for(var i=0; i<specialWidgets.length; i++) {
		CustomizableUI.removeWidgetFromArea(objName+'-special-'+specialWidgets[i]);
	}

	alwaysRunOnShutdown.push(preventLosingCustomizeData);

	overlayAid.overlayURI('chrome://'+objPathString+'/content/options.xul', 'optionsAustralis');
	overlayAid.overlayURI('chrome://browser/content/browser.xul', 'australisBar', null,
		function(aWindow) {
			moduleAid.load('compatibilityFix/sandboxFixes'); // We need our add-on bar registered for this
			prepareObject(aWindow);

			moveStatusBar(aWindow);
			window[objName].moduleAid.load('australis', true);
		},
		function(aWindow) {
			moveStatusBarBack(aWindow);

			delete aWindow[objName]._statusBar;
			removeObject(aWindow);
		}
	);
};

moduleAid.UNLOADMODULE = function() {
	moduleAid.unload('compatibilityFix/sandboxFixes');

	overlayAid.removeOverlayURI('chrome://browser/content/browser.xul', 'australisBar');
	overlayAid.removeOverlayURI('chrome://'+objPathString+'/content/options.xul', 'optionsAustralis');

	preventLosingCustomizeData();

	CustomizableUI.removeListener(trackSpecialWidgets);
};
<|endoftext|>


<commit_before>"use strict";

var reducible = require("./reducible")
var accumulate = require("./accumulate")

function normalize(source) {
  /**
  Takes potentially broken `source` collection and returns normalized,
  version of it. That suppress values after `source` is being ended, or
  errored.
  **/
  // If source is instance of reducible it's already normalized so there is
  // no need of normalizing it any more.
  if (source instanceof reducible.type) return source
  return reducible(function accumulateNormalized(next, initial) {
    accumulate(source, next, initial)
  })
}

module.exports = normalize
<commit_msg>Remove normalize from the core.<commit_after><|endoftext|>


<commit_before>const dayTemplate = (
  DateHelper,
  { domain, domainDynamicDimension, verticalOrientation },
) => {
  const ROWS_COUNT = 7;

  return {
    name: 'day',
    level: 30,
    rowsCount() {
      if (domain === 'week') {
        return 1;
      }
      return ROWS_COUNT;
    },
    columnsCount(d) {
      switch (domain) {
        case 'month':
          return Math.ceil(
            domainDynamicDimension && !verticalOrientation ?
              DateHelper.date(d).daysInMonth() / ROWS_COUNT :
              31 / ROWS_COUNT,
          );
        case 'year':
          return Math.ceil(
            domainDynamicDimension ?
              DateHelper.date(d).endOf('year').dayOfYear() / ROWS_COUNT :
              54,
          );
        case 'week':
        default:
          return ROWS_COUNT;
      }
    },
    mapping: (startDate, endDate, defaultValues) =>
      // eslint-disable-next-line implicit-arrow-linebreak
      DateHelper.intervals('day', startDate, DateHelper.date(endDate)).map(
        (d) => {
          const date = DateHelper.date(d);
          const endWeekNumber = DateHelper.date(d).endOf('year').week();
          let x = 0;

          switch (domain) {
            case 'month':
              x = DateHelper.getMonthWeekNumber(d) - 1;
              break;
            case 'year':
              if (endWeekNumber === 1 && date.week() === endWeekNumber) {
                x = DateHelper.date(d).subtract(1, 'week').week() + 1;
              }

              x = date.week() - 1;
              break;
            case 'week':
              x = date.weekday();
              break;
            default:
          }

          return {
            t: d,
            x,
            y: domain === 'week' ? 0 : date.weekday(),
            ...defaultValues,
          };
        },
      ),
    format: {
      date: 'dddd MMMM D, Y',
      legend: 'Do MMM',
      connector: 'on',
    },
    extractUnit(d) {
      return DateHelper.date(d).startOf('day').valueOf();
    },
  };
};

export default dayTemplate;
<commit_msg>Days subDomain max week columns may contains up to 6 weeks<commit_after>const dayTemplate = (
  DateHelper,
  { domain, domainDynamicDimension, verticalOrientation },
) => {
  const ROWS_COUNT = 7;

  return {
    name: 'day',
    level: 30,
    rowsCount() {
      if (domain === 'week') {
        return 1;
      }
      return ROWS_COUNT;
    },
    columnsCount(d) {
      switch (domain) {
        case 'month':
          return Math.ceil(
            domainDynamicDimension && !verticalOrientation ?
              DateHelper.date(d).daysInMonth() / ROWS_COUNT :
              6, // In rare case, when the first week contains less than 3 days
          );
        case 'year':
          return Math.ceil(
            domainDynamicDimension ?
              DateHelper.date(d).endOf('year').dayOfYear() / ROWS_COUNT :
              54,
          );
        case 'week':
        default:
          return ROWS_COUNT;
      }
    },
    mapping: (startDate, endDate, defaultValues) =>
      // eslint-disable-next-line implicit-arrow-linebreak
      DateHelper.intervals('day', startDate, DateHelper.date(endDate)).map(
        (d) => {
          const date = DateHelper.date(d);
          const endWeekNumber = DateHelper.date(d).endOf('year').week();
          let x = 0;

          switch (domain) {
            case 'month':
              x = DateHelper.getMonthWeekNumber(d) - 1;
              break;
            case 'year':
              if (endWeekNumber === 1 && date.week() === endWeekNumber) {
                x = DateHelper.date(d).subtract(1, 'week').week() + 1;
              }

              x = date.week() - 1;
              break;
            case 'week':
              x = date.weekday();
              break;
            default:
          }

          return {
            t: d,
            x,
            y: domain === 'week' ? 0 : date.weekday(),
            ...defaultValues,
          };
        },
      ),
    format: {
      date: 'dddd MMMM D, Y',
      legend: 'Do MMM',
      connector: 'on',
    },
    extractUnit(d) {
      return DateHelper.date(d).startOf('day').valueOf();
    },
  };
};

export default dayTemplate;
<|endoftext|>


<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

describe('Entity Extension', function() {
  var Y, EntityModel, entityModel, jujuConfig, models, utils;

  before(function(done) {
    Y = YUI(GlobalConfig).use([
      'juju-models',
      'juju-tests-utils'
    ], function(Y) {
      models = Y.namespace('juju.models');
      utils = Y.namespace('juju-tests.utils');
      done();
    });
  });

  beforeEach(function() {
    jujuConfig = window.juju_config;
    EntityModel = Y.Base.create(
      'entity-model', Y.Base, [models.EntityExtension], {});
    entityModel = new EntityModel();
    var attrs = {
      id: '~owner/foobar',
      storeId: 'cs:~owner/foobar-132',
      name: 'foo-bar',
      description: 'A test description.',
      downloads: '0',
      is_approved: false,
      revisions: [],
      url: 'http://example.com/'
    };
    entityModel.setAttrs(attrs);
  });

  afterEach(function() {
    entityModel.destroy();
    window.juju_config = jujuConfig;
  });

  it('parses owner from the ID', function() {
    assert.equal('owner', entityModel.ownerFromId(),
                 'owner was not extracted properly from the ID');
  });

  it('defaults to charmers when owner is not in ID', function() {
    entityModel.set('id', 'foobar');
    assert.equal('charmers', entityModel.ownerFromId(),
                 'default owner was not set to "charmers"');
  });

  it('converts a charm to an entity POJO', function() {
    var attrs = {
      entityType: 'charm',
      series: 'trusty',
      tags: ['database', 'application'],
    };
    var iconPath = 'v5/' + entityModel.get('id') + '/icon.svg';
    utils.getIconPath = sinon.stub().returns(iconPath);
    entityModel.setAttrs(attrs);
    var entity = entityModel.toEntity();
    var expected = {
      description: 'A test description.',
      displayName: 'foo bar',
      downloads: '0',
      id: '~owner/foobar',
      storeId: 'cs:~owner/foobar-132',
      name: 'foo-bar',
      owner: 'owner',
      promulgated: false,
      revisions: [],
      special: undefined,
      type: 'charm',
      url: 'http://example.com/',
      iconPath: iconPath,
      series: 'trusty',
      tags: ['database', 'application']
    };
    assert.deepEqual(expected, entity,
                     'charm POJO did not match expected object');
  });

  it('converts a bundle to an entity POJO', function() {
    entityModel.parseBundleServices = sinon.stub().returns([]);
    var attrs = {
      id: 'foobar',
      owner: 'foobar-charmers',
      entityType: 'bundle',
      applications: [],
      machineCount: 2,
      serviceCount: 3,
      unitCount: 5
    };
    entityModel.setAttrs(attrs);
    var entity = entityModel.toEntity();
    var expected = {
      description: 'A test description.',
      displayName: 'foo bar',
      downloads: '0',
      id: 'foobar',
      storeId: 'cs:~owner/foobar-132',
      machineCount: 2,
      name: 'foo-bar',
      owner: 'foobar-charmers',
      promulgated: false,
      revisions: [],
      special: undefined,
      type: 'bundle',
      url: 'http://example.com/',
      // no staticURL is defined on window.juju_config.staticURL so this
      // path should not include a staticURL prefix.
      iconPath: 'static/gui/build/app/assets/images/non-sprites/bundle.svg',
      serviceCount: 3,
      applications: [],
      unitCount: 5
    };
    assert.deepEqual(expected, entity,
                     'bundle POJO did not match expected object');
  });

  it('uses the staticURL for bundle asset if available', function() {
    window.juju_config = {
      staticURL: 'static'
    };
    entityModel.parseBundleServices = sinon.stub().returns([]);
    var attrs = {
      id: 'foobar',
      owner: 'foobar-charmers',
      entityType: 'bundle',
      services: [],
    };
    entityModel.setAttrs(attrs);
    var entity = entityModel.toEntity();
    assert.deepEqual(
      entity.iconPath,
       'static/static/gui/build/app/assets/images/non-sprites/bundle.svg');
  });
});
<commit_msg>Updated tests<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

describe('Entity Extension', function() {
  var Y, EntityModel, entityModel, jujuConfig, models, utils;

  before(function(done) {
    Y = YUI(GlobalConfig).use([
      'juju-models',
      'juju-tests-utils'
    ], function(Y) {
      models = Y.namespace('juju.models');
      utils = Y.namespace('juju-tests.utils');
      done();
    });
  });

  beforeEach(function() {
    jujuConfig = window.juju_config;
    EntityModel = Y.Base.create(
      'entity-model', Y.Base, [models.EntityExtension], {});
    entityModel = new EntityModel();
    var attrs = {
      id: '~owner/foobar',
      storeId: 'cs:~owner/foobar-132',
      name: 'foo-bar',
      description: 'A test description.',
      revision_id: 132,
      latest_revision: {
        id: 132,
        url: '/foobar-132',
        full_id: 'foobar-123'
      },
      downloads: '0',
      is_approved: false,
      revisions: [],
      url: 'http://example.com/'
    };
    entityModel.setAttrs(attrs);
  });

  afterEach(function() {
    entityModel.destroy();
    window.juju_config = jujuConfig;
  });

  it('parses owner from the ID', function() {
    assert.equal('owner', entityModel.ownerFromId(),
                 'owner was not extracted properly from the ID');
  });

  it('defaults to charmers when owner is not in ID', function() {
    entityModel.set('id', 'foobar');
    assert.equal('charmers', entityModel.ownerFromId(),
                 'default owner was not set to "charmers"');
  });

  it('converts a charm to an entity POJO', function() {
    var attrs = {
      entityType: 'charm',
      series: 'trusty',
      tags: ['database', 'application'],
    };
    var iconPath = 'v5/' + entityModel.get('id') + '/icon.svg';
    utils.getIconPath = sinon.stub().returns(iconPath);
    entityModel.setAttrs(attrs);
    var entity = entityModel.toEntity();
    var expected = {
      description: 'A test description.',
      displayName: 'foo bar',
      downloads: '0',
      id: '~owner/foobar',
      revision_id: 132,
      latest_revision: {
        id: 132,
        url: '/foobar-132',
        full_id: 'foobar-123'
      },
      storeId: 'cs:~owner/foobar-132',
      name: 'foo-bar',
      owner: 'owner',
      promulgated: false,
      revisions: [],
      special: undefined,
      type: 'charm',
      url: 'http://example.com/',
      iconPath: iconPath,
      series: 'trusty',
      tags: ['database', 'application']
    };

    assert.deepEqual(expected, entity,
                     'charm POJO did not match expected object');
  });

  it('converts a bundle to an entity POJO', function() {
    entityModel.parseBundleServices = sinon.stub().returns([]);
    var attrs = {
      id: 'foobar',
      owner: 'foobar-charmers',
      entityType: 'bundle',
      revision_id: '132',
      latest_revision: {
        id: 132,
        url: '/foobar-132',
        full_id: 'foobar-123'
      },
      applications: [],
      machineCount: 2,
      serviceCount: 3,
      unitCount: 5
    };
    entityModel.setAttrs(attrs);
    var entity = entityModel.toEntity();
    var expected = {
      description: 'A test description.',
      displayName: 'foo bar',
      downloads: '0',
      id: 'foobar',
      revision_id: '132',
      latest_revision: {
        id: 132,
        url: '/foobar-132',
        full_id: 'foobar-123'
      },
      storeId: 'cs:~owner/foobar-132',
      machineCount: 2,
      name: 'foo-bar',
      owner: 'foobar-charmers',
      promulgated: false,
      revisions: [],
      special: undefined,
      type: 'bundle',
      url: 'http://example.com/',
      // no staticURL is defined on window.juju_config.staticURL so this
      // path should not include a staticURL prefix.
      iconPath: 'static/gui/build/app/assets/images/non-sprites/bundle.svg',
      serviceCount: 3,
      applications: [],
      unitCount: 5
    };
    assert.deepEqual(expected, entity,
                     'bundle POJO did not match expected object');
  });

  it('uses the staticURL for bundle asset if available', function() {
    window.juju_config = {
      staticURL: 'static'
    };
    entityModel.parseBundleServices = sinon.stub().returns([]);
    var attrs = {
      id: 'foobar',
      owner: 'foobar-charmers',
      entityType: 'bundle',
      services: [],
    };
    entityModel.setAttrs(attrs);
    var entity = entityModel.toEntity();
    assert.deepEqual(
      entity.iconPath,
       'static/static/gui/build/app/assets/images/non-sprites/bundle.svg');
  });
});
<|endoftext|>


<commit_before>/**
 *
 * Base view for alert modals used throughout the application.
 * To initialize and show, render and call 'do_alert' with header and body parameters and options.
 *
 */

Atmo.Views.AlertModal = Backbone.View.extend({
    id: 'alert_modal',
    className: 'modal hide fade',
    template: _.template(Atmo.Templates.alert_modal),
    initialize: function() {

    },
    render: function() {
        this.$el.html(this.template());
		console.log(this.$el);
		console.log(this.template());
        return this;
    },
    do_alert: function(header, body, options) {

        /* Options:
			on_confirm: Function to execute if user confirms modal.
			on_cancel: If user cancels.
			ok_button: Alternate text for 'ok' button on modal.
		*/

        $('#alert_modal').modal({
            backdrop: true,
            keyboard: true
        });

        $('#alert_modal .modal-header h2').html(header);
        $('#alert_modal .modal-body p').html(body);

		// User clicks the 'x' button in the modal header
        $('#alert_modal .modal-header button').click(function() {
            $('#alert_modal').modal('hide');
        });

        $('#alert_modal').modal('show');

        $('#alert_modal .modal-footer a').unbind('click');

        var button_listener = function(callback) {
            return function(e) {
                e.preventDefault();
                $('#alert_modal').modal('hide');
                $('.modal-backdrop').remove();
                if (callback != undefined)
                    callback();
                $(window).unbind('keyup');
            }
        }

		// Allow user to hit enter to confirm
        $(window).on('keyup', function(e) {
            // Only confirm if user does not have cursor in a textarea
            if (e.keyCode == 13 && $('textarea:focus').length == 0) {
                $('#alert_modal .modal-footer a').eq(1).trigger('click');
            }
        });

        if (options != undefined && options.cancel_button != undefined)
            $('#alert_modal .modal-footer a').eq(0).html(options.cancel_button);
        else
            $('#alert_modal .modal-footer a').eq(0).html("Cancel");

        if (options != undefined && options.ok_button != undefined)
            $('#alert_modal .modal-footer a').eq(1).html(options.ok_button);
        else
            $('#alert_modal .modal-footer a').eq(1).html("Ok");

        $('#alert_modal .modal-footer a').show();
        $('#alert_modal .modal-footer a').eq(0).click(button_listener(options.on_cancel));
        $('#alert_modal .modal-footer a').eq(1).click(button_listener(options.on_confirm));
    }
});
<commit_msg>Removed from console logs from client<commit_after>/**
 *
 * Base view for alert modals used throughout the application.
 * To initialize and show, render and call 'do_alert' with header and body parameters and options.
 *
 */

Atmo.Views.AlertModal = Backbone.View.extend({
    id: 'alert_modal',
    className: 'modal hide fade',
    template: _.template(Atmo.Templates.alert_modal),
    initialize: function() {

    },
    render: function() {
        this.$el.html(this.template());
        return this;
    },
    do_alert: function(header, body, options) {

        /* Options:
			on_confirm: Function to execute if user confirms modal.
			on_cancel: If user cancels.
			ok_button: Alternate text for 'ok' button on modal.
		*/

        $('#alert_modal').modal({
            backdrop: true,
            keyboard: true
        });

        $('#alert_modal .modal-header h2').html(header);
        $('#alert_modal .modal-body p').html(body);

		// User clicks the 'x' button in the modal header
        $('#alert_modal .modal-header button').click(function() {
            $('#alert_modal').modal('hide');
        });

        $('#alert_modal').modal('show');

        $('#alert_modal .modal-footer a').unbind('click');

        var button_listener = function(callback) {
            return function(e) {
                e.preventDefault();
                $('#alert_modal').modal('hide');
                $('.modal-backdrop').remove();
                if (callback != undefined)
                    callback();
                $(window).unbind('keyup');
            }
        }

		// Allow user to hit enter to confirm
        $(window).on('keyup', function(e) {
            // Only confirm if user does not have cursor in a textarea
            if (e.keyCode == 13 && $('textarea:focus').length == 0) {
                $('#alert_modal .modal-footer a').eq(1).trigger('click');
            }
        });

        if (options != undefined && options.cancel_button != undefined)
            $('#alert_modal .modal-footer a').eq(0).html(options.cancel_button);
        else
            $('#alert_modal .modal-footer a').eq(0).html("Cancel");

        if (options != undefined && options.ok_button != undefined)
            $('#alert_modal .modal-footer a').eq(1).html(options.ok_button);
        else
            $('#alert_modal .modal-footer a').eq(1).html("Ok");

        $('#alert_modal .modal-footer a').show();
        $('#alert_modal .modal-footer a').eq(0).click(button_listener(options.on_cancel));
        $('#alert_modal .modal-footer a').eq(1).click(button_listener(options.on_confirm));
    }
});
<|endoftext|>


<commit_before>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function() {
  'use strict';

  window.OSjs = window.OSjs || {};

  var handler    = null;
  var loaded     = false;
  var inited     = false;
  var signingOut = false;

  /////////////////////////////////////////////////////////////////////////////
  // COMPABILITY
  /////////////////////////////////////////////////////////////////////////////

  // Make sure these namespaces exist
  (['API', 'GUI', 'Core', 'Dialogs', 'Helpers', 'Applications', 'Locales', 'VFS']).forEach(function(ns) {
    OSjs[ns] = OSjs[ns] || {};
  });

  // For browsers without "console" for some reason
  (function() {
    window.console    = window.console    || {};
    console.log       = console.log       || function() {};
    console.debug     = console.debug     || console.log;
    console.error     = console.error     || console.log;
    console.warn      = console.warn      || console.log;
    console.group     = console.group     || console.log;
    console.groupEnd  = console.groupEnd  || console.log;
  })();

  // Compability
  (function() {
    if ( window.HTMLCollection ) {
      window.HTMLCollection.prototype.forEach = Array.prototype.forEach;
    }
    if ( window.NodeList ) {
      window.NodeList.prototype.forEach = Array.prototype.forEach;
    }
    if ( window.FileList ) {
      window.FileList.prototype.forEach = Array.prototype.forEach;
    }

    (function () {
      function CustomEvent ( event, params ) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent( 'CustomEvent' );
        evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
        return evt;
      }

      CustomEvent.prototype = window.Event.prototype;
      window.CustomEvent = CustomEvent;

        /*
      if ( window.navigator.userAgent.match(/MSIE|Edge/) ) {
      }
      */
    })();
  })();

  /////////////////////////////////////////////////////////////////////////////
  // GLOBAL EVENTS
  /////////////////////////////////////////////////////////////////////////////

  var events = {
    body_contextmenu: function(ev) {
      ev.stopPropagation();
      if ( !OSjs.Utils.$isInput(ev) ) {
        ev.preventDefault();
        return false;
      }
      return true;
    },
    body_mousedown: function(ev) {
      ev.preventDefault();
      OSjs.API.blurMenu();
    },

    mousedown: function(ev) {
      var wm = OSjs.Core.getWindowManager();
      var win = wm ? wm.getCurrentWindow() : null;
      if ( win ) {
        win._blur();
      }
    },

    keydown: function(ev) {
      var wm  = OSjs.Core.getWindowManager();
      var win = wm ? wm.getCurrentWindow() : null;

      function checkPrevent() {
        var d = ev.srcElement || ev.target;
        var doPrevent = d.tagName === 'BODY' ? true : false;

        // We don't want backspace and tab triggering default browser events
        if ( (ev.keyCode === OSjs.Utils.Keys.BACKSPACE) && !OSjs.Utils.$isInput(ev) ) {
          doPrevent = true;
        } else if ( (ev.keyCode === OSjs.Utils.Keys.TAB) && OSjs.Utils.$isFormElement(ev) ) {
          doPrevent = true;
        }

        // Only prevent default event if current window is not set up to capture them by force
        if ( doPrevent && (!win || !win._properties.key_capture) ) {
          return true;
        }

        return false;
      }

      if ( checkPrevent() ) {
        ev.preventDefault();
      }

      // WindowManager and Window must always recieve events
      if ( wm ) {
        if ( win ) {
          win._onKeyEvent(ev, 'keydown');
        }
        wm.onKeyDown(ev, win);
      }

      return true;
    },
    keypress: function(ev) {
      var wm = OSjs.Core.getWindowManager();
      if ( wm ) {
        var win = wm.getCurrentWindow();
        if ( win ) {
          return win._onKeyEvent(ev, 'keypress');
        }
      }
      return true;
    },
    keyup: function(ev) {
      var wm = OSjs.Core.getWindowManager();
      if ( wm ) {
        wm.onKeyUp(ev, wm.getCurrentWindow());

        var win = wm.getCurrentWindow();
        if ( win ) {
          return win._onKeyEvent(ev, 'keyup');
        }
      }
      return true;
    },

    beforeunload: function(ev) {
      if ( signingOut ) { return; }

      try {
        var config = OSjs.Core.getConfig();
        if ( config.ShowQuitWarning ) {
          return OSjs.API._('MSG_SESSION_WARNING');
        }
      } catch ( e ) {}
    },

    resize: (function() {
      var _timeout;

      function _resize(ev) {
        var wm = OSjs.Core.getWindowManager();
        if ( !wm ) { return; }
        wm.resize(ev, wm.getWindowSpace());
      }

      return function(ev) {
        if ( _timeout ) {
          clearTimeout(_timeout);
          _timeout = null;
        }

        var self = this;
        _timeout = setTimeout(function() {
          _resize.call(self, ev);
        }, 100);
      };
    })(),

    scroll: function(ev) {
      if ( ev.target === document || ev.target === document.body ) {
        ev.preventDefault();
        ev.stopPropagation();
        return false;
      }

      document.body.scrollTop = 0;
      document.body.scrollLeft = 0;
      return true;
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // INITIALIZERS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * When an error occurs
   */
  function onError(msg) {
    OSjs.API.error(OSjs.API._('ERR_CORE_INIT_FAILED'), OSjs.API._('ERR_CORE_INIT_FAILED_DESC'), msg, null, true);
  }

  /**
   * Initialized some layout stuff
   */
  function initLayout() {
    var config = OSjs.Core.getConfig();
    var append = config.VersionAppend;

    var ver = config.Version || 'unknown verion';
    var cop = 'Copyright © 2011-2014 ';
    var lnk = document.createElement('a');
    lnk.href = 'mailto:andersevenrud@gmail.com';
    lnk.appendChild(document.createTextNode('Anders Evenrud'));

    var el = document.createElement('div');
    el.id = 'DebugNotice';
    el.appendChild(document.createTextNode(OSjs.Utils.format('OS.js {0}', ver)));
    el.appendChild(document.createElement('br'));
    el.appendChild(document.createTextNode(cop));
    el.appendChild(lnk);
    if ( append ) {
      el.appendChild(document.createElement('br'));
      el.innerHTML += append;
    }

    document.getElementById('LoadingScreen').style.display = 'none';

    document.body.appendChild(el);
  }

  /**
   * Initializes handler
   */
  function initHandler(config, callback) {
    handler = new OSjs.Core.Handler();
    handler.init(function() {
      if ( inited ) {
        return;
      }
      inited = true;

      handler.boot(function(result, error) {
        if ( error ) {
          onError(error);
          return;
        }

        callback();
      });
    });
  }

  /**
   * Initializes events
   */
  function initEvents() {
    document.body.addEventListener('contextmenu', events.body_contextmenu, false);
    document.body.addEventListener('mousedown', events.body_mousedown, false);
    document.addEventListener('keydown', events.keydown, true);
    document.addEventListener('keypress', events.keypress, true);
    document.addEventListener('keyup', events.keyup, true);
    document.addEventListener('mousedown', events.mousedown, false);
    window.addEventListener('resize', events.resize, false);
    window.addEventListener('scroll', events.scroll, false);
    window.onbeforeunload = events.beforeunload;

    window.onerror = function(message, url, linenumber, column, exception) {
      if ( typeof exception === 'string' ) {
        exception = null;
      }
      console.warn('window::onerror()', arguments);
      OSjs.API.error(OSjs.API._('ERR_JAVASCRIPT_EXCEPTION'),
                    OSjs.API._('ERR_JAVACSRIPT_EXCEPTION_DESC'),
                    OSjs.API._('BUGREPORT_MSG'),
                    exception || {name: 'window::onerror()', fileName: url, lineNumber: linenumber+':'+column, message: message},
                    true );

      return false;
    };
  }

  /**
   * Preloads configured files
   */
  function initPreload(config, callback) {
    var preloads = config.Preloads;
    preloads.forEach(function(val, index) {
      val.src = OSjs.Utils.checkdir(val.src);
    });

    OSjs.Utils.preload(preloads, function(total, errors, failed) {
      if ( errors ) {
        console.warn('doInitialize()', errors, 'preloads failed to load:', failed);
      }

      setTimeout(function() {
        callback();
      }, 0);
    });
  }

  /**
   * Initalizes the VFS
   */
  function initVFS(config, callback) {
    if ( OSjs.VFS.registerMounts ) {
      OSjs.VFS.registerMounts();
    }
    callback();
  }

  /**
   * Initializes the Window Manager
   */
  function initWindowManager(config, callback) {
    if ( !config.WM || !config.WM.exec ) {
      onError(OSjs.API._('ERR_CORE_INIT_NO_WM'));
      return;
    }

    OSjs.API.launch(config.WM.exec, (config.WM.args || {}), function(app) {
      callback();
    }, function(error, name, args, exception) {
      onError(OSjs.API._('ERR_CORE_INIT_WM_FAILED_FMT', error), exception);
    });
  }

  /**
   * Initializes the Session
   */
  function initSession(config, callback) {
    OSjs.API.playSound('service-login');

    var wm = OSjs.Core.getWindowManager();

    function autostart() {
      var config = OSjs.Core.getConfig();
      var start;

      try {
        start = config.System.AutoStart;
      } catch ( e ) {
        console.warn('doAutostart() exception', e, e.stack);
      }

      console.info('doAutostart()', start);
      if ( start ) {
        OSjs.API.launchList(autostart);
      }
    }

    handler.loadSession(function() {
      setTimeout(function() {
        events.resize();
      }, 500);

      callback();

      wm.onSessionLoaded();

      autostart();
    });
  }

  /**
   * Wrapper for initializing OS.js
   */
  function init() {
    var config = OSjs.Core.getConfig();

    initLayout();

    initHandler(config, function() {
      OSjs.API.triggerHook('onInitialize');

      initPreload(config, function() {
        OSjs.API.triggerHook('onInited');

        initVFS(config, function() {
          initWindowManager(config, function() {
            OSjs.API.triggerHook('onWMInited');

            OSjs.Utils.$remove(document.getElementById('LoadingScreen'));

            initEvents();
            var wm = OSjs.Core.getWindowManager();
            wm._fullyLoaded = true;

            initSession(config, function() {
              OSjs.API.triggerHook('onSessionLoaded');
            });
          });
        });
      });
    });
  }

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Shuts down OS.js
   *
   * @api OSjs.API.shutdown()
   */
  OSjs.API.shutdown = function() {
    if ( !inited || !loaded ) {
      return;
    }

    signingOut = true;

    document.body.removeEventListener('contextmenu', events.body_contextmenu, false);
    document.body.removeEventListener('mousedown', events.body_mousedown, false);
    document.removeEventListener('keydown', events.keydown, true);
    document.removeEventListener('keypress', events.keypress, true);
    document.removeEventListener('keyup', events.keyup, true);
    document.removeEventListener('mousedown', events.mousedown, false);
    window.removeEventListener('resize', events.resize, false);
    window.removeEventListener('scroll', events.scroll, false);

    window.onerror = null;
    window.onbeforeunload = null;

    OSjs.API.blurMenu();
    OSjs.API.killAll();

    var ring = OSjs.API.getServiceNotificationIcon();
    if ( ring ) {
      ring.destroy();
    }

    var handler = OSjs.Core.getHandler();
    if ( handler ) {
      handler.destroy();
      handler = null;
    }

    console.warn('OS.js was shut down!');

    if ( window.require ) {
      try {
        var gui = require('nw.gui');
        var win = gui.Window.get();
        setTimeout(function() {
          win.close();
        }, 500);
      } catch ( e ) {}
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // FILLERS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Get default configured settings
   *
   * THIS IS JUST A PLACEHOLDER. 'settings.js' SHOULD HAVE THIS!
   *
   * @return  Object
   *
   * @api     OSjs.Core.getConfig()
   */
  OSjs.Core.getConfig = OSjs.Core.getConfig || function() {
    return {};
  };

  /**
   * Get default configured packages
   *
   * THIS IS JUST A PLACEHOLDER. 'packages.js' SHOULD HAVE THIS!
   *
   * @return  Object
   *
   * @api     OSjs.Core.getMetadata()
   */
  OSjs.Core.getMetadata = OSjs.Core.getMetadata || function() {
    return {};
  };

  /////////////////////////////////////////////////////////////////////////////
  // MAIN
  /////////////////////////////////////////////////////////////////////////////

  (function() {
    function onLoad() {
      if ( loaded ) {
        return;
      }
      loaded = true;
      init();
    }

    function onUnload() {
      OSjs.API.shutdown();
    }

    document.addEventListener('DOMContentLoaded', onLoad);
    document.addEventListener('load', onLoad);
    document.addEventListener('unload', onUnload);
  })();

})();
<commit_msg>GUI::Menu fix for IE (2)<commit_after>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function() {
  'use strict';

  window.OSjs = window.OSjs || {};

  var handler    = null;
  var loaded     = false;
  var inited     = false;
  var signingOut = false;

  /////////////////////////////////////////////////////////////////////////////
  // COMPABILITY
  /////////////////////////////////////////////////////////////////////////////

  // Make sure these namespaces exist
  (['API', 'GUI', 'Core', 'Dialogs', 'Helpers', 'Applications', 'Locales', 'VFS']).forEach(function(ns) {
    OSjs[ns] = OSjs[ns] || {};
  });

  // For browsers without "console" for some reason
  (function() {
    window.console    = window.console    || {};
    console.log       = console.log       || function() {};
    console.debug     = console.debug     || console.log;
    console.error     = console.error     || console.log;
    console.warn      = console.warn      || console.log;
    console.group     = console.group     || console.log;
    console.groupEnd  = console.groupEnd  || console.log;
  })();

  // Compability
  (function() {
    if ( window.HTMLCollection ) {
      window.HTMLCollection.prototype.forEach = Array.prototype.forEach;
    }
    if ( window.NodeList ) {
      window.NodeList.prototype.forEach = Array.prototype.forEach;
    }
    if ( window.FileList ) {
      window.FileList.prototype.forEach = Array.prototype.forEach;
    }

    (function () {
      function CustomEvent ( event, params ) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent( 'CustomEvent' );
        evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
        return evt;
      }

      if ( window.navigator.userAgent.match(/MSIE|Edge|Trident/) ) {
        CustomEvent.prototype = window.Event.prototype;
        window.CustomEvent = CustomEvent;
      }
    })();
  })();

  /////////////////////////////////////////////////////////////////////////////
  // GLOBAL EVENTS
  /////////////////////////////////////////////////////////////////////////////

  var events = {
    body_contextmenu: function(ev) {
      ev.stopPropagation();
      if ( !OSjs.Utils.$isInput(ev) ) {
        ev.preventDefault();
        return false;
      }
      return true;
    },
    body_mousedown: function(ev) {
      ev.preventDefault();
      OSjs.API.blurMenu();
    },

    mousedown: function(ev) {
      var wm = OSjs.Core.getWindowManager();
      var win = wm ? wm.getCurrentWindow() : null;
      if ( win ) {
        win._blur();
      }
    },

    keydown: function(ev) {
      var wm  = OSjs.Core.getWindowManager();
      var win = wm ? wm.getCurrentWindow() : null;

      function checkPrevent() {
        var d = ev.srcElement || ev.target;
        var doPrevent = d.tagName === 'BODY' ? true : false;

        // We don't want backspace and tab triggering default browser events
        if ( (ev.keyCode === OSjs.Utils.Keys.BACKSPACE) && !OSjs.Utils.$isInput(ev) ) {
          doPrevent = true;
        } else if ( (ev.keyCode === OSjs.Utils.Keys.TAB) && OSjs.Utils.$isFormElement(ev) ) {
          doPrevent = true;
        }

        // Only prevent default event if current window is not set up to capture them by force
        if ( doPrevent && (!win || !win._properties.key_capture) ) {
          return true;
        }

        return false;
      }

      if ( checkPrevent() ) {
        ev.preventDefault();
      }

      // WindowManager and Window must always recieve events
      if ( wm ) {
        if ( win ) {
          win._onKeyEvent(ev, 'keydown');
        }
        wm.onKeyDown(ev, win);
      }

      return true;
    },
    keypress: function(ev) {
      var wm = OSjs.Core.getWindowManager();
      if ( wm ) {
        var win = wm.getCurrentWindow();
        if ( win ) {
          return win._onKeyEvent(ev, 'keypress');
        }
      }
      return true;
    },
    keyup: function(ev) {
      var wm = OSjs.Core.getWindowManager();
      if ( wm ) {
        wm.onKeyUp(ev, wm.getCurrentWindow());

        var win = wm.getCurrentWindow();
        if ( win ) {
          return win._onKeyEvent(ev, 'keyup');
        }
      }
      return true;
    },

    beforeunload: function(ev) {
      if ( signingOut ) { return; }

      try {
        var config = OSjs.Core.getConfig();
        if ( config.ShowQuitWarning ) {
          return OSjs.API._('MSG_SESSION_WARNING');
        }
      } catch ( e ) {}
    },

    resize: (function() {
      var _timeout;

      function _resize(ev) {
        var wm = OSjs.Core.getWindowManager();
        if ( !wm ) { return; }
        wm.resize(ev, wm.getWindowSpace());
      }

      return function(ev) {
        if ( _timeout ) {
          clearTimeout(_timeout);
          _timeout = null;
        }

        var self = this;
        _timeout = setTimeout(function() {
          _resize.call(self, ev);
        }, 100);
      };
    })(),

    scroll: function(ev) {
      if ( ev.target === document || ev.target === document.body ) {
        ev.preventDefault();
        ev.stopPropagation();
        return false;
      }

      document.body.scrollTop = 0;
      document.body.scrollLeft = 0;
      return true;
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // INITIALIZERS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * When an error occurs
   */
  function onError(msg) {
    OSjs.API.error(OSjs.API._('ERR_CORE_INIT_FAILED'), OSjs.API._('ERR_CORE_INIT_FAILED_DESC'), msg, null, true);
  }

  /**
   * Initialized some layout stuff
   */
  function initLayout() {
    var config = OSjs.Core.getConfig();
    var append = config.VersionAppend;

    var ver = config.Version || 'unknown verion';
    var cop = 'Copyright © 2011-2014 ';
    var lnk = document.createElement('a');
    lnk.href = 'mailto:andersevenrud@gmail.com';
    lnk.appendChild(document.createTextNode('Anders Evenrud'));

    var el = document.createElement('div');
    el.id = 'DebugNotice';
    el.appendChild(document.createTextNode(OSjs.Utils.format('OS.js {0}', ver)));
    el.appendChild(document.createElement('br'));
    el.appendChild(document.createTextNode(cop));
    el.appendChild(lnk);
    if ( append ) {
      el.appendChild(document.createElement('br'));
      el.innerHTML += append;
    }

    document.getElementById('LoadingScreen').style.display = 'none';

    document.body.appendChild(el);
  }

  /**
   * Initializes handler
   */
  function initHandler(config, callback) {
    handler = new OSjs.Core.Handler();
    handler.init(function() {
      if ( inited ) {
        return;
      }
      inited = true;

      handler.boot(function(result, error) {
        if ( error ) {
          onError(error);
          return;
        }

        callback();
      });
    });
  }

  /**
   * Initializes events
   */
  function initEvents() {
    document.body.addEventListener('contextmenu', events.body_contextmenu, false);
    document.body.addEventListener('mousedown', events.body_mousedown, false);
    document.addEventListener('keydown', events.keydown, true);
    document.addEventListener('keypress', events.keypress, true);
    document.addEventListener('keyup', events.keyup, true);
    document.addEventListener('mousedown', events.mousedown, false);
    window.addEventListener('resize', events.resize, false);
    window.addEventListener('scroll', events.scroll, false);
    window.onbeforeunload = events.beforeunload;

    window.onerror = function(message, url, linenumber, column, exception) {
      if ( typeof exception === 'string' ) {
        exception = null;
      }
      console.warn('window::onerror()', arguments);
      OSjs.API.error(OSjs.API._('ERR_JAVASCRIPT_EXCEPTION'),
                    OSjs.API._('ERR_JAVACSRIPT_EXCEPTION_DESC'),
                    OSjs.API._('BUGREPORT_MSG'),
                    exception || {name: 'window::onerror()', fileName: url, lineNumber: linenumber+':'+column, message: message},
                    true );

      return false;
    };
  }

  /**
   * Preloads configured files
   */
  function initPreload(config, callback) {
    var preloads = config.Preloads;
    preloads.forEach(function(val, index) {
      val.src = OSjs.Utils.checkdir(val.src);
    });

    OSjs.Utils.preload(preloads, function(total, errors, failed) {
      if ( errors ) {
        console.warn('doInitialize()', errors, 'preloads failed to load:', failed);
      }

      setTimeout(function() {
        callback();
      }, 0);
    });
  }

  /**
   * Initalizes the VFS
   */
  function initVFS(config, callback) {
    if ( OSjs.VFS.registerMounts ) {
      OSjs.VFS.registerMounts();
    }
    callback();
  }

  /**
   * Initializes the Window Manager
   */
  function initWindowManager(config, callback) {
    if ( !config.WM || !config.WM.exec ) {
      onError(OSjs.API._('ERR_CORE_INIT_NO_WM'));
      return;
    }

    OSjs.API.launch(config.WM.exec, (config.WM.args || {}), function(app) {
      callback();
    }, function(error, name, args, exception) {
      onError(OSjs.API._('ERR_CORE_INIT_WM_FAILED_FMT', error), exception);
    });
  }

  /**
   * Initializes the Session
   */
  function initSession(config, callback) {
    OSjs.API.playSound('service-login');

    var wm = OSjs.Core.getWindowManager();

    function autostart() {
      var config = OSjs.Core.getConfig();
      var start;

      try {
        start = config.System.AutoStart;
      } catch ( e ) {
        console.warn('doAutostart() exception', e, e.stack);
      }

      console.info('doAutostart()', start);
      if ( start ) {
        OSjs.API.launchList(autostart);
      }
    }

    handler.loadSession(function() {
      setTimeout(function() {
        events.resize();
      }, 500);

      callback();

      wm.onSessionLoaded();

      autostart();
    });
  }

  /**
   * Wrapper for initializing OS.js
   */
  function init() {
    var config = OSjs.Core.getConfig();

    initLayout();

    initHandler(config, function() {
      OSjs.API.triggerHook('onInitialize');

      initPreload(config, function() {
        OSjs.API.triggerHook('onInited');

        initVFS(config, function() {
          initWindowManager(config, function() {
            OSjs.API.triggerHook('onWMInited');

            OSjs.Utils.$remove(document.getElementById('LoadingScreen'));

            initEvents();
            var wm = OSjs.Core.getWindowManager();
            wm._fullyLoaded = true;

            initSession(config, function() {
              OSjs.API.triggerHook('onSessionLoaded');
            });
          });
        });
      });
    });
  }

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Shuts down OS.js
   *
   * @api OSjs.API.shutdown()
   */
  OSjs.API.shutdown = function() {
    if ( !inited || !loaded ) {
      return;
    }

    signingOut = true;

    document.body.removeEventListener('contextmenu', events.body_contextmenu, false);
    document.body.removeEventListener('mousedown', events.body_mousedown, false);
    document.removeEventListener('keydown', events.keydown, true);
    document.removeEventListener('keypress', events.keypress, true);
    document.removeEventListener('keyup', events.keyup, true);
    document.removeEventListener('mousedown', events.mousedown, false);
    window.removeEventListener('resize', events.resize, false);
    window.removeEventListener('scroll', events.scroll, false);

    window.onerror = null;
    window.onbeforeunload = null;

    OSjs.API.blurMenu();
    OSjs.API.killAll();

    var ring = OSjs.API.getServiceNotificationIcon();
    if ( ring ) {
      ring.destroy();
    }

    var handler = OSjs.Core.getHandler();
    if ( handler ) {
      handler.destroy();
      handler = null;
    }

    console.warn('OS.js was shut down!');

    if ( window.require ) {
      try {
        var gui = require('nw.gui');
        var win = gui.Window.get();
        setTimeout(function() {
          win.close();
        }, 500);
      } catch ( e ) {}
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // FILLERS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Get default configured settings
   *
   * THIS IS JUST A PLACEHOLDER. 'settings.js' SHOULD HAVE THIS!
   *
   * @return  Object
   *
   * @api     OSjs.Core.getConfig()
   */
  OSjs.Core.getConfig = OSjs.Core.getConfig || function() {
    return {};
  };

  /**
   * Get default configured packages
   *
   * THIS IS JUST A PLACEHOLDER. 'packages.js' SHOULD HAVE THIS!
   *
   * @return  Object
   *
   * @api     OSjs.Core.getMetadata()
   */
  OSjs.Core.getMetadata = OSjs.Core.getMetadata || function() {
    return {};
  };

  /////////////////////////////////////////////////////////////////////////////
  // MAIN
  /////////////////////////////////////////////////////////////////////////////

  (function() {
    function onLoad() {
      if ( loaded ) {
        return;
      }
      loaded = true;
      init();
    }

    function onUnload() {
      OSjs.API.shutdown();
    }

    document.addEventListener('DOMContentLoaded', onLoad);
    document.addEventListener('load', onLoad);
    document.addEventListener('unload', onUnload);
  })();

})();
<|endoftext|>