<commit_before>/*
 * This file is part of WebCL – Web Computing Language.
 *
 * This Source Code Form is subject to the terms of the
 * Mozilla Public License, v. 2.0. If a copy of the MPL
 * was not distributed with this file, You can obtain
 * one at http://mozilla.org/MPL/2.0/.
 *
 * The Original Contributor of this Source Code Form is
 * Nokia Research Tampere (http://webcl.nokiaresearch.com).
 *
 * Author: Tomi Aarnio, 2014
 */

//////////////////////////////////////////////////////////////////////////////
//
// Properties -> Signature
//
describe("Signature", function() {

  it("must have the singleton 'webcl' object", function() {
    expect(webcl).toBeDefined();
  });

  it("must have all the expected classes", function() {
    for (var className in expectedClasses) {
      expect(window).toHaveFunction(className);
    }
  });

  it("must have all the expected member functions", function() {
    checkSignature('webcl', true);
    for (var className in expectedClasses) {
      checkSignature(className, true);
    }
  });

  it("must have error code enums ranging from 0 to -64", function() {
    for (var enumName in errorEnums) {
      var actualValue = WebCL[enumName];
      var expectedValue = errorEnums[enumName];
      expect(actualValue).toBeDefined();
      expect(actualValue).toEqual(expectedValue);
    }
  });

  it("must have device info enums ranging from 0x1000 to 0x103D", function() {
    for (var enumName in deviceInfoEnums) {
      var actualValue = WebCL[enumName];
      var expectedValue = deviceInfoEnums[enumName];
      expect(actualValue).toBeDefined();
      expect(actualValue).toEqual(expectedValue);
    }
  });

  it("must not have any disallowed member functions", function() {
    checkSignature('webcl', false);
    for (var className in expectedClasses) {
      checkSignature(className, false);
    }
  });

  it("must not have any disallowed device info enums", function() {
    for (var enumName in removedDeviceInfoEnums) {
      expect('webcl').not.toHaveProperty(enumName);
    }
  });

  it("must not have error code enums that have been removed", function() {
    for (var enumName in removedErrorEnums) {
      expect(WebCL[enumName]).not.toBeDefined();
    }
  });

  //////////////////////////////////////////////////////////////

  var customMatchers = {
    toHaveProperty: function(util, customEqualityTesters) {
      return {
        compare: function(actual, expected) {
          var obj = typeof(actual) === "string" ? window[actual] : actual;
          return { pass: (obj[name] !== undefined) };
        }
      };
    },
    toHaveFunction: function(util, customEqualityTesters) {
      return {
        compare: function(actual, expected) {
          var obj = typeof(actual) === "string" ? window[actual] : actual;
          var exists = obj && (typeof(obj[expected]) === 'function');
          exists = exists || (obj && obj.prototype && typeof(obj.prototype[expected]) === 'function');
          return { pass: exists };
        }
      };
    },
  };

  beforeEach(function() {
    jasmine.addMatchers(customMatchers);
  });

  afterEach(function() {
    //console.log("afterEach jasmine.Suite(): ", jasmine);
    //testSuiteTrace(this);
  });

  function checkSignature(className, checkExisting) {
    for (var funcName in expectedFunctions[className]) {
      if (checkExisting && expectedFunctions[className][funcName] === true) {
        expect(className).toHaveFunction(funcName);
      }
      if (!checkExisting && expectedFunctions[className][funcName] === false) {
        expect(className).not.toHaveFunction(funcName);
      }
    }
  };

  //////////////////////////////////////////////////////////////

  var expectedClasses = {
    WebCL : true,
    WebCLPlatform : true,
    WebCLDevice : true,
    WebCLContext : true,
    WebCLCommandQueue : true,
    WebCLMemoryObject : true,
    WebCLSampler : true,
    WebCLProgram : true,
    WebCLKernel : true,
    WebCLEvent : true,
    WebCLBuffer : true,
    WebCLImage : true,
    WebCLUserEvent : true,
  };

  var expectedFunctions = {

    WebCL : {
      getPlatforms : true,
      createContext : true,
      getSupportedExtensions : true,
      enableExtension : true,
      waitForEvents : true,
      releaseAll : true,
      getPlatformIDs : false,         // renamed to getPlatforms
      createContextFromType : false,  // merged into createContext
    },

    WebCLPlatform : {
      getInfo : true,
      getDevices : true,
      getSupportedExtensions : true,
      enableExtension : true,
      getDeviceIDs : false,           // renamed to getDevices
      getPlatformInfo : false,        // renamed to getInfo
    },

    WebCLDevice : {
      getInfo : true,
      getSupportedExtensions : true,
      enableExtension : true,
      getDeviceInfo : false,          // renamed to getInfo
    },

    WebCLContext : {
      createBuffer : true,
      createCommandQueue : true,
      createImage : true,
      createProgram : true,
      createSampler : true,
      createUserEvent : true,
      getInfo : true,
      getSupportedImageFormats : true,
      release : true,
      releaseAll : true,
      createImage2D : false,            // renamed to createImage
      createImage3D : false,            // disallowed by WebCL
      createProgramWithSource : false,  // renamed to createProgram
      createProgramWithBinary : false,  // disallowed by WebCL
      getContextInfo : false,           // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLCommandQueue : {
      enqueueCopyBuffer : true,
      enqueueCopyBufferRect : true,
      enqueueCopyImage : true,
      enqueueCopyImageToBuffer : true,
      enqueueCopyBufferToImage : true,
      enqueueReadBuffer : true,
      enqueueReadBufferRect : true,
      enqueueReadImage : true,
      enqueueWriteBuffer : true,
      enqueueWriteBufferRect : true,
      enqueueWriteImage : true,
      enqueueNDRangeKernel : true,
      enqueueMarker : true,
      enqueueBarrier : true,
      enqueueWaitForEvents : true,
      finish : true,
      flush : true,
      getInfo : true,
      release : true,
      enqueueTask : false,              // disallowed by WebCL
      enqueueMapBuffer : false,         // disallowed by WebCL
      enqueueMapImage : false,          // disallowed by WebCL
      enqueueUnmapMemObject : false,    // disallowed by WebCL
      getCommandQueueInfo : false,      // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLMemoryObject : {
      getInfo : true,
      release : true,
      createSubBuffer : false,
      getImageInfo: false,              // moved to WebCLImage
      getMemObjectInfo : false,         // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLBuffer : {
      createSubBuffer : true,
      releaseCLResources : false,       // renamed to release
    },

    WebCLImage : {
      getInfo : true,
      getImageInfo: false,              // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLSampler : {
      getInfo : true,
      release : true,
      getSamplerInfo: false,            // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLProgram : {
      getInfo : true,
      getBuildInfo : true,
      build : true,
      createKernel : true,
      createKernelsInProgram : true,
      release : true,
      buildProgram : false,             // renamed to build
      getProgramInfo : false,           // renamed to getInfo
      getProgramBuildInfo : false,      // renamed to getBuildInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLKernel : {
      getInfo : true,
      getWorkGroupInfo : true,
      setArg : true,
      release : true,
      setKernelArg : false,             // renamed to setArg
      setKernelArgLocal : false,        // renamed to setArg
      getKernelInfo: false,             // renamed to getInfo
      getKernelWorkGroupInfo : false,   // renamed to getWorkGroupInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLEvent : {
      getInfo : true,
      getProfilingInfo : true,
      setCallback : true,
      release : true,
      setUserEventStatus : false,       // moved to WebCLUserEvent
      getEventInfo : false,             // renamed to getInfo
      getEventProfilingInfo : false,    // renamed to getProfilingInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLUserEvent : {
      setStatus : true,
      setUserEventStatus : false,       // renamed to setStatus
      releaseCLResources : false,       // renamed to release
    },
  };

});
<commit_msg>All tests now fail if WebCL is not present<commit_after>/*
 * This file is part of WebCL – Web Computing Language.
 *
 * This Source Code Form is subject to the terms of the
 * Mozilla Public License, v. 2.0. If a copy of the MPL
 * was not distributed with this file, You can obtain
 * one at http://mozilla.org/MPL/2.0/.
 *
 * The Original Contributor of this Source Code Form is
 * Nokia Research Tampere (http://webcl.nokiaresearch.com).
 *
 * Author: Tomi Aarnio, 2014
 */

//////////////////////////////////////////////////////////////////////////////
//
// Properties -> Signature
//
describe("Signature", function() {

  beforeEach(function() {
    expect(webcl).toBeDefined();
  });

  it("must have the singleton 'webcl' object", function() {
  });

  it("must have all the expected classes", function() {
    for (var className in expectedClasses) {
      expect(window).toHaveFunction(className);
    }
  });

  it("must have all the expected member functions", function() {
    checkSignature('webcl', true);
    for (var className in expectedClasses) {
      checkSignature(className, true);
    }
  });

  it("must have error code enums ranging from 0 to -64", function() {
    for (var enumName in errorEnums) {
      var actualValue = WebCL[enumName];
      var expectedValue = errorEnums[enumName];
      expect(actualValue).toBeDefined();
      expect(actualValue).toEqual(expectedValue);
    }
  });

  it("must have device info enums ranging from 0x1000 to 0x103D", function() {
    for (var enumName in deviceInfoEnums) {
      var actualValue = WebCL[enumName];
      var expectedValue = deviceInfoEnums[enumName];
      expect(actualValue).toBeDefined();
      expect(actualValue).toEqual(expectedValue);
    }
  });

  it("must not have any disallowed member functions", function() {
    checkSignature('webcl', false);
    for (var className in expectedClasses) {
      checkSignature(className, false);
    }
  });

  it("must not have any disallowed device info enums", function() {
    for (var enumName in removedDeviceInfoEnums) {
      expect('webcl').not.toHaveProperty(enumName);
    }
  });

  it("must not have error code enums that have been removed", function() {
    for (var enumName in removedErrorEnums) {
      expect(WebCL[enumName]).not.toBeDefined();
    }
  });

  //////////////////////////////////////////////////////////////

  var customMatchers = {
    toHaveProperty: function(util, customEqualityTesters) {
      return {
        compare: function(actual, expected) {
          var obj = typeof(actual) === "string" ? window[actual] : actual;
          return { pass: (obj[name] !== undefined) };
        }
      };
    },
    toHaveFunction: function(util, customEqualityTesters) {
      return {
        compare: function(actual, expected) {
          var obj = typeof(actual) === "string" ? window[actual] : actual;
          var exists = obj && (typeof(obj[expected]) === 'function');
          exists = exists || (obj && obj.prototype && typeof(obj.prototype[expected]) === 'function');
          return { pass: exists };
        }
      };
    },
  };

  beforeEach(function() {
    jasmine.addMatchers(customMatchers);
  });

  afterEach(function() {
    //console.log("afterEach jasmine.Suite(): ", jasmine);
    //testSuiteTrace(this);
  });

  function checkSignature(className, checkExisting) {
    for (var funcName in expectedFunctions[className]) {
      if (checkExisting && expectedFunctions[className][funcName] === true) {
        expect(className).toHaveFunction(funcName);
      }
      if (!checkExisting && expectedFunctions[className][funcName] === false) {
        expect(className).not.toHaveFunction(funcName);
      }
    }
  };

  //////////////////////////////////////////////////////////////

  var expectedClasses = {
    WebCL : true,
    WebCLPlatform : true,
    WebCLDevice : true,
    WebCLContext : true,
    WebCLCommandQueue : true,
    WebCLMemoryObject : true,
    WebCLSampler : true,
    WebCLProgram : true,
    WebCLKernel : true,
    WebCLEvent : true,
    WebCLBuffer : true,
    WebCLImage : true,
    WebCLUserEvent : true,
  };

  var expectedFunctions = {

    WebCL : {
      getPlatforms : true,
      createContext : true,
      getSupportedExtensions : true,
      enableExtension : true,
      waitForEvents : true,
      releaseAll : true,
      getPlatformIDs : false,         // renamed to getPlatforms
      createContextFromType : false,  // merged into createContext
    },

    WebCLPlatform : {
      getInfo : true,
      getDevices : true,
      getSupportedExtensions : true,
      enableExtension : true,
      getDeviceIDs : false,           // renamed to getDevices
      getPlatformInfo : false,        // renamed to getInfo
    },

    WebCLDevice : {
      getInfo : true,
      getSupportedExtensions : true,
      enableExtension : true,
      getDeviceInfo : false,          // renamed to getInfo
    },

    WebCLContext : {
      createBuffer : true,
      createCommandQueue : true,
      createImage : true,
      createProgram : true,
      createSampler : true,
      createUserEvent : true,
      getInfo : true,
      getSupportedImageFormats : true,
      release : true,
      releaseAll : true,
      createImage2D : false,            // renamed to createImage
      createImage3D : false,            // disallowed by WebCL
      createProgramWithSource : false,  // renamed to createProgram
      createProgramWithBinary : false,  // disallowed by WebCL
      getContextInfo : false,           // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLCommandQueue : {
      enqueueCopyBuffer : true,
      enqueueCopyBufferRect : true,
      enqueueCopyImage : true,
      enqueueCopyImageToBuffer : true,
      enqueueCopyBufferToImage : true,
      enqueueReadBuffer : true,
      enqueueReadBufferRect : true,
      enqueueReadImage : true,
      enqueueWriteBuffer : true,
      enqueueWriteBufferRect : true,
      enqueueWriteImage : true,
      enqueueNDRangeKernel : true,
      enqueueMarker : true,
      enqueueBarrier : true,
      enqueueWaitForEvents : true,
      finish : true,
      flush : true,
      getInfo : true,
      release : true,
      enqueueTask : false,              // disallowed by WebCL
      enqueueMapBuffer : false,         // disallowed by WebCL
      enqueueMapImage : false,          // disallowed by WebCL
      enqueueUnmapMemObject : false,    // disallowed by WebCL
      getCommandQueueInfo : false,      // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLMemoryObject : {
      getInfo : true,
      release : true,
      createSubBuffer : false,
      getImageInfo: false,              // moved to WebCLImage
      getMemObjectInfo : false,         // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLBuffer : {
      createSubBuffer : true,
      releaseCLResources : false,       // renamed to release
    },

    WebCLImage : {
      getInfo : true,
      getImageInfo: false,              // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLSampler : {
      getInfo : true,
      release : true,
      getSamplerInfo: false,            // renamed to getInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLProgram : {
      getInfo : true,
      getBuildInfo : true,
      build : true,
      createKernel : true,
      createKernelsInProgram : true,
      release : true,
      buildProgram : false,             // renamed to build
      getProgramInfo : false,           // renamed to getInfo
      getProgramBuildInfo : false,      // renamed to getBuildInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLKernel : {
      getInfo : true,
      getWorkGroupInfo : true,
      setArg : true,
      release : true,
      setKernelArg : false,             // renamed to setArg
      setKernelArgLocal : false,        // renamed to setArg
      getKernelInfo: false,             // renamed to getInfo
      getKernelWorkGroupInfo : false,   // renamed to getWorkGroupInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLEvent : {
      getInfo : true,
      getProfilingInfo : true,
      setCallback : true,
      release : true,
      setUserEventStatus : false,       // moved to WebCLUserEvent
      getEventInfo : false,             // renamed to getInfo
      getEventProfilingInfo : false,    // renamed to getProfilingInfo
      releaseCLResources : false,       // renamed to release
    },

    WebCLUserEvent : {
      setStatus : true,
      setUserEventStatus : false,       // renamed to setStatus
      releaseCLResources : false,       // renamed to release
    },
  };

});
<|endoftext|>


<commit_before>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= packagejs.name %> <%= packagejs.version %>
'use strict';

var gulp = require('gulp'),<% if(useSass) { %>
    expect = require('gulp-expect-file'),
    sass = require('gulp-sass'),<% } %>
    rev = require('gulp-rev'),
    templateCache = require('gulp-angular-templatecache'),
    htmlmin = require('gulp-htmlmin'),
    imagemin = require('gulp-imagemin'),
    ngConstant = require('gulp-ng-constant'),
    rename = require('gulp-rename'),
    eslint = require('gulp-eslint'),<% if (testFrameworks.indexOf('protractor') > -1) { %>
    argv = require('yargs').argv,
    gutil = require('gulp-util'),
    protractor = require('gulp-protractor').protractor,<% } %>
    es = require('event-stream'),
    flatten = require('gulp-flatten'),
    del = require('del'),
    runSequence = require('run-sequence'),
    browserSync = require('browser-sync'),
    KarmaServer = require('karma').Server,
    plumber = require('gulp-plumber'),
    changed = require('gulp-changed'),
    gulpIf = require('gulp-if'),
    inject = require('gulp-inject'),
    angularFilesort = require('gulp-angular-filesort'),
    naturalSort = require('gulp-natural-sort'),
    bowerFiles = require('main-bower-files'),
    typescript = require('gulp-typescript'),
    sourcemaps = require('gulp-sourcemaps'),
    tslint = require('gulp-tslint');

var handleErrors = require('./gulp/handleErrors'),
    serve = require('./gulp/serve'),
    util = require('./gulp/utils'),
    build = require('./gulp/build'),
    tscConfig = require('./tsconfig.json');

<%_ if(enableTranslation) { _%>
var yorc = require('./.yo-rc.json')['generator-jhipster'];
<%_ } _%>

var config = require('./gulp/config');

gulp.task('clean', function () {
    return del([config.dist], { dot: true });
});

gulp.task('copy', [<% if(enableTranslation) { %>'copy:i18n', <% } %>'copy:fonts', 'copy:common', 'copy:deps']);
<% if(enableTranslation) { /* copy i18n folders only if translation is enabled */ %>
gulp.task('copy:i18n', function () {
    return gulp.src(config.app + 'i18n/**')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'i18n/'))
        .pipe(gulp.dest(config.dist + 'i18n/'));
});
<% } %>
gulp.task('copy:fonts', function () {
    return es.merge(<% if(!useSass) { %>gulp.src(config.bower + 'bootstrap/fonts/*.*')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/fonts/'))
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/fonts/'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist)),<% } %>
        gulp.src(config.app + 'content/**/*.{woff,woff2,svg,ttf,eot,otf}')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/fonts/'))
        .pipe(flatten())
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/fonts/'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist))
    );
});

gulp.task('copy:common', function () {
    return gulp.src([config.app + 'robots.txt', config.app + 'favicon.ico', config.app + '.htaccess'], { dot: true })
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist))
        .pipe(gulp.dest(config.dist));
});

//copy npm dependencies to vendor folder
//TODO optimize to copy only required minified files
gulp.task('copy:deps', function(){
    return gulp.src([
        'node_modules/core-js/client/shim.min.js',
        'node_modules/zone.js/dist/zone.js',
        'node_modules/reflect-metadata/Reflect.js',
        'node_modules/systemjs/dist/system.src.js',
        'node_modules/@angular/**/*.js',
        'node_modules/rxjs/**/*.js'
    ], { base: 'node_modules' })
    .pipe(gulp.dest(config.app + 'vendor'));
});

gulp.task('images', function () {
    return gulp.src(config.app + 'content/images/**')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/images'))
        .pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true}))
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/images'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist))
        .pipe(browserSync.reload({stream: true}));
});

<%_ if(useSass) { _%>
gulp.task('sass', function () {
    return es.merge(
        gulp.src(config.sassSrc)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(expect(config.sassSrc))
        .pipe(changed(config.cssDir, {extension: '.css'}))
        .pipe(sass({includePaths:config.bower}).on('error', sass.logError))
        .pipe(gulp.dest(config.cssDir)),
        gulp.src(config.bower + '**/fonts/**/*.{woff,woff2,svg,ttf,eot,otf}')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.app + 'content/fonts'))
        .pipe(flatten())
        .pipe(gulp.dest(config.app + 'content/fonts'))
    );
});
<%_ } _%>

<%_ if(enableTranslation) { _%>
gulp.task('languages', function () {
    var locales = yorc.languages.map(function (locale) {
        return config.bower + 'angular-i18n/angular-locale_' + locale + '.js';
    });
    return gulp.src(locales)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.app + 'i18n/'))
        .pipe(gulp.dest(config.app + 'i18n/'));
});
<%_ } _%>

gulp.task('styles', [<% if(useSass) { %>'sass'<% } %>], function () {
    return gulp.src(config.app + 'content/css')
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('inject', ['tscompile','inject:dep', 'inject:app']);
gulp.task('inject:dep', ['inject:test', 'inject:vendor']);

gulp.task('tscompile', ['clean'], function(cb){
     return gulp
    .src(config.app+'app/**/*.ts').pipe(sourcemaps.init())
    .pipe(typescript(tscConfig.compilerOptions))
    .pipe(sourcemaps.write('.'));
});

gulp.task('inject:app', function () {
    return gulp.src(config.app + 'index.html')
        .pipe(inject(gulp.src(config.app + 'app/**/*.js')
            .pipe(naturalSort())
            .pipe(angularFilesort()), {relative: true}))
        .pipe(gulp.dest(config.app));
});

gulp.task('inject:vendor', function () {
    var stream = gulp.src(config.app + 'index.html')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(inject(gulp.src(bowerFiles(), {read: false}), {
            name: 'bower',
            relative: true
        }))
        .pipe(gulp.dest(config.app));

    return <% if (useSass) { %>es.merge(stream, gulp.src(config.sassVendor)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(inject(gulp.src(bowerFiles({filter:['**/*.{scss,sass}']}), {read: false}), {
            name: 'bower',
            relative: true
        }))
        .pipe(gulp.dest(config.scss)));<% } else { %>stream;<% } %>
});

gulp.task('inject:test', function () {
    return gulp.src(config.test + 'karma.conf.js')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(inject(gulp.src(bowerFiles({includeDev: true, filter: ['**/*.js']}), {read: false}), {
            starttag: '// bower:js',
            endtag: '// endbower',
            transform: function (filepath) {
                return '\'' + filepath.substring(1, filepath.length) + '\',';
            }
        }))
        .pipe(gulp.dest(config.test));
});

gulp.task('inject:troubleshoot', function () {
    /* this task removes the troubleshooting content from index.html*/
    return gulp.src(config.app + 'index.html')
        .pipe(plumber({errorHandler: handleErrors}))
        /* having empty src as we dont have to read any files*/
        .pipe(inject(gulp.src('', {read: false}), {
            starttag: '<!-- inject:troubleshoot -->',
            removeTags: true,
            transform: function () {
                return '<!-- Angular views -->';
            }
        }))
        .pipe(gulp.dest(config.app));
});

gulp.task('assets:prod', ['images', 'styles', 'html'], build);

gulp.task('html', function () {
    return gulp.src(config.app + 'app/**/*.html')
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(templateCache({
            module: '<%= angularAppName %>',
            root: 'app/',
            moduleSystem: 'IIFE'
        }))
        .pipe(gulp.dest(config.tmp));
});

gulp.task('ngconstant:dev', function () {
    return ngConstant({
        name: '<%= angularAppName %>',
        constants: {
            VERSION: util.parseVersion(),
            DEBUG_INFO_ENABLED: true
        },
        template: config.constantTemplate,
        stream: true
    })
    .pipe(rename('app.constants.ts'))
    .pipe(gulp.dest(config.app + 'app/'));
});

gulp.task('ngconstant:prod', function () {
    return ngConstant({
        name: '<%= angularAppName %>',
        constants: {
            VERSION: util.parseVersion(),
            DEBUG_INFO_ENABLED: false
        },
        template: config.constantTemplate,
        stream: true
    })
    .pipe(rename('app.constants.ts'))
    .pipe(gulp.dest(config.app + 'app/'));
});

// check app for eslint errors
gulp.task('eslint', function () {
    return gulp.src(['gulpfile.js', config.app + 'app/**/*.js'])
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failOnError());
});

// check app for eslint errors anf fix some of them
gulp.task('eslint:fix', function () {
    return gulp.src(config.app + 'app/**/*.js')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(eslint({
            fix: true
        }))
        .pipe(eslint.format())
        .pipe(gulpIf(util.isLintFixed, gulp.dest(config.app + 'app')));
});

// check app for any tslint errors
gulp.task('tslint', function() {
  return gulp.src('app/**/*.ts')
    .pipe(tslint())
    .pipe(tslint.report('verbose'));
});

gulp.task('test', ['inject:test', 'ngconstant:dev'], function (done) {
    new KarmaServer({
        configFile: __dirname + '/' + config.test + 'karma.conf.js',
        singleRun: true
    }, done).start();
});

<%_ if (testFrameworks.indexOf('protractor') > -1) { _%>
/* to run individual suites pass `gulp itest --suite suiteName` */
gulp.task('protractor', function () {
    var configObj = {
        configFile: config.test + 'protractor.conf.js'
    };
    if (argv.suite) {
        configObj['args'] = ['--suite', argv.suite];
    }
    return gulp.src([])
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(protractor(configObj))
        .on('error', function () {
            gutil.log('E2E Tests failed');
            process.exit(1);
        });
});

gulp.task('itest', ['protractor']);
<%_ } _%>

gulp.task('watch', function () {
    gulp.watch('bower.json', ['install']);
    gulp.watch(['gulpfile.js', <% if(buildTool == 'maven') { %>'pom.xml'<% } else { %>'build.gradle'<% } %>], ['ngconstant:dev']);
    gulp.watch(<% if(useSass) { %>config.sassSrc<% } else { %>config.app + 'content/css/**/*.css'<% } %>, ['styles']);
    gulp.watch(config.app + 'content/images/**', ['images']);
    gulp.watch(config.app + 'app/**/*.js', ['inject:app']);
    gulp.watch([config.app + '*.html', config.app + 'app/**', config.app + 'i18n/**']).on('change', browserSync.reload);
});

gulp.task('install', function () {
    runSequence(['inject:dep', 'ngconstant:dev']<% if(useSass) { %>, 'sass'<% } %><% if(enableTranslation) { %>, 'languages'<% } %>, 'inject:app', 'inject:troubleshoot');
});

gulp.task('serve', function () {
    runSequence('install', serve);
});

gulp.task('build', ['clean'], function (cb) {
    runSequence(['copy', 'inject:vendor', 'ngconstant:prod'<% if(enableTranslation) { %>, 'languages'<% } %>], 'inject:app', 'inject:troubleshoot', 'assets:prod', cb);
});

gulp.task('default', ['serve']);
<commit_msg>fix tasks in gulpfile<commit_after>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= packagejs.name %> <%= packagejs.version %>
'use strict';

var gulp = require('gulp'),<% if(useSass) { %>
    expect = require('gulp-expect-file'),
    sass = require('gulp-sass'),<% } %>
    rev = require('gulp-rev'),
    templateCache = require('gulp-angular-templatecache'),
    htmlmin = require('gulp-htmlmin'),
    imagemin = require('gulp-imagemin'),
    ngConstant = require('gulp-ng-constant'),
    rename = require('gulp-rename'),
    eslint = require('gulp-eslint'),<% if (testFrameworks.indexOf('protractor') > -1) { %>
    argv = require('yargs').argv,
    gutil = require('gulp-util'),
    protractor = require('gulp-protractor').protractor,<% } %>
    es = require('event-stream'),
    flatten = require('gulp-flatten'),
    del = require('del'),
    runSequence = require('run-sequence'),
    browserSync = require('browser-sync'),
    KarmaServer = require('karma').Server,
    plumber = require('gulp-plumber'),
    changed = require('gulp-changed'),
    gulpIf = require('gulp-if'),
    inject = require('gulp-inject'),
    angularFilesort = require('gulp-angular-filesort'),
    naturalSort = require('gulp-natural-sort'),
    bowerFiles = require('main-bower-files'),
    typescript = require('gulp-typescript'),
    sourcemaps = require('gulp-sourcemaps'),
    tslint = require('gulp-tslint');

var handleErrors = require('./gulp/handleErrors'),
    serve = require('./gulp/serve'),
    util = require('./gulp/utils'),
    build = require('./gulp/build'),
    tscConfig = require('./tsconfig.json');

<%_ if(enableTranslation) { _%>
var yorc = require('./.yo-rc.json')['generator-jhipster'];
<%_ } _%>

var config = require('./gulp/config');

gulp.task('clean', function () {
    return del([config.dist], { dot: true });
});

gulp.task('copy', [<% if(enableTranslation) { %>'copy:i18n', <% } %>'copy:fonts', 'copy:common', 'copy:deps']);
<% if(enableTranslation) { /* copy i18n folders only if translation is enabled */ %>
gulp.task('copy:i18n', function () {
    return gulp.src(config.app + 'i18n/**')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'i18n/'))
        .pipe(gulp.dest(config.dist + 'i18n/'));
});
<% } %>
gulp.task('copy:fonts', function () {
    return es.merge(<% if(!useSass) { %>gulp.src(config.bower + 'bootstrap/fonts/*.*')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/fonts/'))
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/fonts/'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist)),<% } %>
        gulp.src(config.app + 'content/**/*.{woff,woff2,svg,ttf,eot,otf}')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/fonts/'))
        .pipe(flatten())
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/fonts/'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist))
    );
});

gulp.task('copy:common', function () {
    return gulp.src([config.app + 'robots.txt', config.app + 'favicon.ico', config.app + '.htaccess'], { dot: true })
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist))
        .pipe(gulp.dest(config.dist));
});

//copy npm dependencies to vendor folder
//TODO optimize to copy only required minified files
gulp.task('copy:deps', function(){
    return gulp.src([
        'node_modules/core-js/client/shim.min.js',
        'node_modules/zone.js/dist/zone.js',
        'node_modules/reflect-metadata/Reflect.js',
        'node_modules/systemjs/dist/system.src.js',
        'node_modules/@angular/**/*.js',
        'node_modules/rxjs/**/*.js'
    ], { base: 'node_modules' })
    .pipe(gulp.dest(config.app + 'vendor'));
});

gulp.task('images', function () {
    return gulp.src(config.app + 'content/images/**')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/images'))
        .pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true}))
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/images'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist))
        .pipe(browserSync.reload({stream: true}));
});

<%_ if(useSass) { _%>
gulp.task('sass', function () {
    return es.merge(
        gulp.src(config.sassSrc)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(expect(config.sassSrc))
        .pipe(changed(config.cssDir, {extension: '.css'}))
        .pipe(sass({includePaths:config.bower}).on('error', sass.logError))
        .pipe(gulp.dest(config.cssDir)),
        gulp.src(config.bower + '**/fonts/**/*.{woff,woff2,svg,ttf,eot,otf}')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.app + 'content/fonts'))
        .pipe(flatten())
        .pipe(gulp.dest(config.app + 'content/fonts'))
    );
});
<%_ } _%>

<%_ if(enableTranslation) { _%>
gulp.task('languages', function () {
    var locales = yorc.languages.map(function (locale) {
        return config.bower + 'angular-i18n/angular-locale_' + locale + '.js';
    });
    return gulp.src(locales)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.app + 'i18n/'))
        .pipe(gulp.dest(config.app + 'i18n/'));
});
<%_ } _%>

gulp.task('styles', [<% if(useSass) { %>'sass'<% } %>], function () {
    return gulp.src(config.app + 'content/css')
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('inject', ['tscompile','inject:dep', 'inject:app']);
gulp.task('inject:dep', ['inject:test', 'inject:vendor']);

gulp.task('tscompile', ['clean'], function(cb){
     return gulp
    .src(config.app+'app/**/*.ts').pipe(sourcemaps.init())
    .pipe(typescript(tscConfig.compilerOptions))
    .pipe(sourcemaps.write('.'));
});

gulp.task('inject:app', function () {
    return gulp.src(config.app + 'index.html')
        .pipe(inject(gulp.src(config.app + 'app/**/*.js')
            .pipe(naturalSort())
            .pipe(angularFilesort()), {relative: true}))
        .pipe(gulp.dest(config.app));
});

gulp.task('inject:vendor', function () {
    var stream = gulp.src(config.app + 'index.html')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(inject(gulp.src(bowerFiles(), {read: false}), {
            name: 'bower',
            relative: true
        }))
        .pipe(gulp.dest(config.app));

    return <% if (useSass) { %>es.merge(stream, gulp.src(config.sassVendor)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(inject(gulp.src(bowerFiles({filter:['**/*.{scss,sass}']}), {read: false}), {
            name: 'bower',
            relative: true
        }))
        .pipe(gulp.dest(config.scss)));<% } else { %>stream;<% } %>
});

gulp.task('inject:test', function () {
    return gulp.src(config.test + 'karma.conf.js')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(inject(gulp.src(bowerFiles({includeDev: true, filter: ['**/*.js']}), {read: false}), {
            starttag: '// bower:js',
            endtag: '// endbower',
            transform: function (filepath) {
                return '\'' + filepath.substring(1, filepath.length) + '\',';
            }
        }))
        .pipe(gulp.dest(config.test));
});

gulp.task('inject:troubleshoot', function () {
    /* this task removes the troubleshooting content from index.html*/
    return gulp.src(config.app + 'index.html')
        .pipe(plumber({errorHandler: handleErrors}))
        /* having empty src as we dont have to read any files*/
        .pipe(inject(gulp.src('', {read: false}), {
            starttag: '<!-- inject:troubleshoot -->',
            removeTags: true,
            transform: function () {
                return '<!-- Angular views -->';
            }
        }))
        .pipe(gulp.dest(config.app));
});

gulp.task('assets:prod', ['images', 'styles', 'html'], build);

gulp.task('html', function () {
    return gulp.src(config.app + 'app/**/*.html')
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(templateCache({
            module: '<%= angularAppName %>',
            root: 'app/',
            moduleSystem: 'IIFE'
        }))
        .pipe(gulp.dest(config.tmp));
});

gulp.task('ngconstant:dev', function () {
    return ngConstant({
        name: '<%= angularAppName %>',
        constants: {
            VERSION: util.parseVersion(),
            DEBUG_INFO_ENABLED: true
        },
        template: config.constantTemplate,
        stream: true
    })
    .pipe(rename('app.constants.ts'))
    .pipe(gulp.dest(config.app + 'app/'));
});

gulp.task('ngconstant:prod', function () {
    return ngConstant({
        name: '<%= angularAppName %>',
        constants: {
            VERSION: util.parseVersion(),
            DEBUG_INFO_ENABLED: false
        },
        template: config.constantTemplate,
        stream: true
    })
    .pipe(rename('app.constants.ts'))
    .pipe(gulp.dest(config.app + 'app/'));
});

// check app for eslint errors
gulp.task('eslint', function () {
    return gulp.src(['gulpfile.js', config.app + 'app/**/*.js'])
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failOnError());
});

// check app for eslint errors anf fix some of them
gulp.task('eslint:fix', function () {
    return gulp.src(config.app + 'app/**/*.js')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(eslint({
            fix: true
        }))
        .pipe(eslint.format())
        .pipe(gulpIf(util.isLintFixed, gulp.dest(config.app + 'app')));
});

// check app for any tslint errors
gulp.task('tslint', function() {
  return gulp.src('app/**/*.ts')
    .pipe(tslint())
    .pipe(tslint.report('verbose'));
});

gulp.task('test', ['inject:test', 'ngconstant:dev'], function (done) {
    new KarmaServer({
        configFile: __dirname + '/' + config.test + 'karma.conf.js',
        singleRun: true
    }, done).start();
});

<%_ if (testFrameworks.indexOf('protractor') > -1) { _%>
/* to run individual suites pass `gulp itest --suite suiteName` */
gulp.task('protractor', function () {
    var configObj = {
        configFile: config.test + 'protractor.conf.js'
    };
    if (argv.suite) {
        configObj['args'] = ['--suite', argv.suite];
    }
    return gulp.src([])
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(protractor(configObj))
        .on('error', function () {
            gutil.log('E2E Tests failed');
            process.exit(1);
        });
});

gulp.task('itest', ['protractor']);
<%_ } _%>

gulp.task('watch', function () {
    gulp.watch('bower.json', ['install']);
    gulp.watch(['gulpfile.js', <% if(buildTool == 'maven') { %>'pom.xml'<% } else { %>'build.gradle'<% } %>], ['ngconstant:dev']);
    gulp.watch(<% if(useSass) { %>config.sassSrc<% } else { %>config.app + 'content/css/**/*.css'<% } %>, ['styles']);
    gulp.watch(config.app + 'content/images/**', ['images']);
    gulp.watch(config.app + 'app/**/*.js', ['inject:app']);
    gulp.watch([config.app + '*.html', config.app + 'app/**', config.app + 'i18n/**']).on('change', browserSync.reload);
});

gulp.task('install', function () {
    runSequence(['inject:dep', 'ngconstant:dev', 'tscompile', 'copy:deps']<% if(useSass) { %>, 'sass'<% } %><% if(enableTranslation) { %>, 'languages'<% } %>, 'inject:app', 'inject:troubleshoot');
});

gulp.task('serve', function () {
    runSequence('install', serve);
});

gulp.task('build', ['clean'], function (cb) {
    runSequence(['copy', 'inject:vendor', 'tscompile', 'ngconstant:prod'<% if(enableTranslation) { %>, 'languages'<% } %>], 'inject:app', 'inject:troubleshoot', 'assets:prod', cb);
});

gulp.task('default', ['serve']);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { ChannelItem } from './channel-item';

export class GroupItem extends Component {
  render() {
    const { props } = this;
    const association = props.association ? props.association : {};

    let title = association['app-path'] ? association['app-path'] : 'Direct Messages';
    if (association.metadata && association.metadata.title) {
      title = association.metadata.title !== ''
        ? association.metadata.title
        : title;
    }

    const channels = props.channels ? props.channels : [];
    const first = (props.index === 0) ? 'mt1 ' : 'mt6 ';

    const channelItems = channels.sort((a, b) => {
      if (props.index === 'dm') {
        const aPreview = props.messagePreviews[a];
        const bPreview = props.messagePreviews[b];
        const aWhen = aPreview ? aPreview.when : 0;
        const bWhen = bPreview ? bPreview.when : 0;

        return bWhen - aWhen;
      } else {
      const aAssociation = a in props.chatMetadata ? props.chatMetadata[a] : {};
      const bAssociation = b in props.chatMetadata ? props.chatMetadata[b] : {};
      let aTitle = a;
      let bTitle = b;
      if (aAssociation.metadata && aAssociation.metadata.title) {
        aTitle = (aAssociation.metadata.title !== '')
          ? aAssociation.metadata.title : a;
        }
      if (bAssociation.metadata && bAssociation.metadata.title) {
        bTitle =
          bAssociation.metadata.title !== '' ? bAssociation.metadata.title : b;
        }
      return aTitle.toLowerCase().localeCompare(bTitle.toLowerCase());
      }
    }).map((each, i) => {
      const unread = props.unreads[each];
      let title = each.substr(1);
      if (
        each in props.chatMetadata &&
        props.chatMetadata[each].metadata
      ) {
        title = props.chatMetadata[each].metadata.title
          ? props.chatMetadata[each].metadata.title
          : each.substr(1);
      }
      const selected = props.station === each;

      return (
        <ChannelItem
          key={i}
          unread={unread}
          title={title}
          selected={selected}
          box={each}
          {...props}
        />
      );
    });

    if (channelItems.length === 0) {
      channelItems.push(
No direct messages
);
    }

    let dmLink =
;

    if (props.index === 'dm') {
      dmLink = <Link
                className="absolute right-0 f9 top-0 mr4 green2 bg-gray5 bg-gray1-d b--transparent br1"
                to="/~chat/new/dm"
                style={{ padding: '0rem 0.2rem' }}
               >
               + DM
               </Link>;
    }
    return (

{title}

        {dmLink}
        {channelItems}

    );
  }
}

export default GroupItem;
<commit_msg>chat: only show other participant in dms<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { ChannelItem } from './channel-item';
import { deSig } from "~/logic/lib/util";

export class GroupItem extends Component {
  render() {
    const { props } = this;
    const association = props.association ? props.association : {};
    const DEFAULT_TITLE_REGEX = new RegExp(`(( <-> )?~${deSig(window.ship)}( <-> )?)`);

    let title = association['app-path'] ? association['app-path'] : 'Direct Messages';
    if (association.metadata && association.metadata.title) {
      title = association.metadata.title !== ''
        ? association.metadata.title
        : title;
    }

    const channels = props.channels ? props.channels : [];
    const first = (props.index === 0) ? 'mt1 ' : 'mt6 ';

    const channelItems = channels.sort((a, b) => {
      if (props.index === 'dm') {
        const aPreview = props.messagePreviews[a];
        const bPreview = props.messagePreviews[b];
        const aWhen = aPreview ? aPreview.when : 0;
        const bWhen = bPreview ? bPreview.when : 0;

        return bWhen - aWhen;
      } else {
      const aAssociation = a in props.chatMetadata ? props.chatMetadata[a] : {};
      const bAssociation = b in props.chatMetadata ? props.chatMetadata[b] : {};
      let aTitle = a;
      let bTitle = b;
      if (aAssociation.metadata && aAssociation.metadata.title) {
        aTitle = (aAssociation.metadata.title !== '')
          ? aAssociation.metadata.title : a;
        }
      if (bAssociation.metadata && bAssociation.metadata.title) {
        bTitle =
          bAssociation.metadata.title !== '' ? bAssociation.metadata.title : b;
        }
      return aTitle.toLowerCase().localeCompare(bTitle.toLowerCase());
      }
    }).map((each, i) => {
      const unread = props.unreads[each];
      let title = each.substr(1);
      if (
        each in props.chatMetadata &&
        props.chatMetadata[each].metadata
      ) {
        if (props.chatMetadata[each].metadata.title) {
          title = props.chatMetadata[each].metadata.title
        }
      }

      if (DEFAULT_TITLE_REGEX.test(title) && props.index === "dm") {
        title = title.replace(DEFAULT_TITLE_REGEX, '');
      }
      const selected = props.station === each;

      return (
        <ChannelItem
          key={i}
          unread={unread}
          title={title}
          selected={selected}
          box={each}
          {...props}
        />
      );
    });

    if (channelItems.length === 0) {
      channelItems.push(
No direct messages
);
    }

    let dmLink =
;

    if (props.index === 'dm') {
      dmLink = <Link
                className="absolute right-0 f9 top-0 mr4 green2 bg-gray5 bg-gray1-d b--transparent br1"
                to="/~chat/new/dm"
                style={{ padding: '0rem 0.2rem' }}
               >
               + DM
               </Link>;
    }
    return (

{title}

        {dmLink}
        {channelItems}

    );
  }
}

export default GroupItem;
<|endoftext|>


<commit_before>'use strict';

// Jessie =============================================================
/* Constructor/Prototype pattern */
function Jessie(hostname) {
    this.hostname = hostname;
    this.createDate = new Date();
    this._runLevel = 4;
}

Jessie.prototype = {
    version: 8.2,
    releaseDate: new Date(2015, 8, 5, 0, 0, 0, 0),
}

Object.defineProperty(Jessie.prototype, "constructor", {
    enumerable: false,
    value: Jessie
});

Object.defineProperty(Jessie.prototype, "OSName", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: "Debian/Jessie"
});

Object.defineProperty(Jessie.prototype, "runLevel", {
    configurable: false,
    get: function () {
        return this._runLevel;
    },
    set: function (newRunLevel) {
        if (newRunLevel < 0) {
            newRunLevel = 0;
        } else if (newRunLevel > 6) {
            newRunLevel = 6;
        }
        this._runLevel = newRunLevel;
    }
});
// End Jessie =========================================================

class DoublyLinkedList {
    constructor(name = (new Date()).toString()) {
        // this.name is read-only.
        Object.defineProperty(this, 'name', {
            value: name,
            enumerable: true,
        });

        this.writable = 'a';
        this._arr = [];
    }

    addLast(node) {
        this._arr.push(node);
    }
}

class StackLinkedList extends DoublyLinkedList {
}

function FuncConstructor(name) {
    this.name = name;
}

exports.Jessie = Jessie;
exports.DoublyLinkedList = DoublyLinkedList;
exports.StackLinkedList = StackLinkedList;
exports.FuncConstructor = FuncConstructor;
<commit_msg>Added dummy constructors<commit_after>'use strict';

// Jessie =============================================================
/* Constructor/Prototype pattern */
function Jessie(hostname) {
    this.hostname = hostname;
    this.createDate = new Date();
    this._runLevel = 4;
}

Jessie.prototype = {
    version: 8.2,
    releaseDate: new Date(2015, 8, 5, 0, 0, 0, 0),
}

Object.defineProperty(Jessie.prototype, "constructor", {
    enumerable: false,
    value: Jessie
});

Object.defineProperty(Jessie.prototype, "OSName", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: "Debian/Jessie"
});

Object.defineProperty(Jessie.prototype, "runLevel", {
    configurable: false,
    get: function () {
        return this._runLevel;
    },
    set: function (newRunLevel) {
        if (newRunLevel < 0) {
            newRunLevel = 0;
        } else if (newRunLevel > 6) {
            newRunLevel = 6;
        }
        this._runLevel = newRunLevel;
    }
});
// End Jessie =========================================================

class DoublyLinkedList {
    constructor(name = (new Date()).toString()) {
        // this.name is read-only.
        Object.defineProperty(this, 'name', {
            value: name,
            enumerable: true,
        });

        this.writable = 'a';
        this._arr = [];
    }

    addLast(node) {
        this._arr.push(node);
    }
}

class StackLinkedList extends DoublyLinkedList {
}

class Class00 {
    constructor(name = (new Date()).toString()) {
        this.name = name;
    }
}

function FunctionConstructorWithThis(name) {
    this.name = name;
}

function FunctionConstructorWithoutThis() {
}

exports.Jessie = Jessie;
exports.DoublyLinkedList = DoublyLinkedList;
exports.StackLinkedList = StackLinkedList;
exports.Class00 = Class00;
exports.FunctionConstructorWithThis = FunctionConstructorWithThis;
exports.FunctionConstructorWithoutThis = FunctionConstructorWithoutThis;
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const {classes: Cc, interfaces: Ci, utils: Cu} = Components;

Cu.import("resource://gre/modules/ctypes.jsm");

Cu.import("chrome://htitle/content/HTitleShare.jsm");
Cu.import("chrome://htitle/content/PrefPageObserver.jsm");
Cu.import("chrome://htitle/content/Libs.jsm");

var EXPORTED_SYMBOLS = ["HTitleUtils"];

var HTitlePrefObserver = {
    register: function() {
        HTitleUtils.prefs.addObserver("", this, false);
    },

    unregister: function() {
        HTitleUtils.prefs.removeObserver("", this);
    },

    observe: function(subject, topic, data) {
        if (topic != "nsPref:changed")
            return;

        switch(data) {
            case "debug":
                HTitleShare.debug = HTitleUtils.prefs.getBoolPref("debug");
                break;
            case "legacy_mode.timeout_check":
                HTitleUtils.timeoutCheck = HTitleUtils.prefs.getIntPref("legacy_mode.timeout_check");
                break;
            case "legacy_mode.timeout_between_changes":
                HTitleUtils.timeoutBetweenChanges = HTitleUtils.prefs.getIntPref("legacy_mode.timeout_between_changes");
                break;
        }
    }
}

var HTitleUtilsPrivate = {
    execute: function(path, args, needWait=true) {
        var file = Cc["@mozilla.org/file/local;1"]
                     .createInstance(Ci.nsIFile);
        file.initWithPath(path);

        var process = Cc["@mozilla.org/process/util;1"]
                        .createInstance(Ci.nsIProcess);
        try {
            process.init(file);
            process.run(needWait, args, args.length);
        }
        catch (error) {
            HTitleUtils.log(error.message, "ERROR");
            return -1;
        }

        if (needWait) {
            HTitleUtils.log("Exit value of " + path + " is \"" + process.exitValue + "\"", "DEBUG");
            return process.exitValue;
        }
        else
            return 0;
    }
}

var HTitleUtils = {
    appInfo: null,
    prefs: null,

    windowControlsLayout: null,
    titlebarActions: null,

    utils: {},

    timeoutCheck: 200, // ms
    timeoutBetweenChanges: 200, // ms

    init: function() {
        this.appInfo = Cc["@mozilla.org/xre/app-info;1"]
                         .getService(Ci.nsIXULAppInfo);

        this.prefs = Cc["@mozilla.org/preferences-service;1"]
                       .getService(Ci.nsIPrefService)
                       .getBranch("extensions.htitle.");
        HTitlePrefObserver.register();

        HTitleShare.debug = this.prefs.getBoolPref("debug");
        this.timeoutCheck = this.prefs.getIntPref("legacy_mode.timeout_check");
        this.timeoutBetweenChanges = this.prefs.getIntPref("legacy_mode.timeout_between_changes");

        HTitleShare.gtkVersion = this.getGtkVersion();
        this.windowControlsLayout = this.getWindowControlsLayout();
        this.titlebarActions = this.getTitlebarActions();
    },

    /* ::::: App info functions ::::: */

    isFirefox: function() {
        return (this.appInfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}");
    },

    isThunderbird: function() {
        return (this.appInfo.ID == "{3550f703-e582-4d05-9a08-453d09bdfdc6}");
    },

    isSeaMonkey: function() {
        return (this.appInfo.ID == "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}");
    },

    /* ::::: Change currentset attribute ::::: */

    addToCurrentset: function(node, id) {
        var currentset = node.getAttribute("currentset");
        if (!currentset)
            currentset = node.getAttribute("defaultset");
        currentset = currentset + (currentset == "" ? "" : ",") + id;
        node.setAttribute("currentset", currentset);
    },

    removeFromCurrentset: function(node, id) {
        var currentset = node.getAttribute("currentset");
        if (!currentset)
            currentset = node.getAttribute("defaultset");
        var re = new RegExp("(^|,)" + id + "($|,)");
        currentset = currentset.replace(re, "$2");
        node.setAttribute("currentset", currentset);
    },

    /* ::::: Toolkit version ::::: */

    getGtkVersion: function() {
        var widget_toolkit;
        if (this.prefs.getPrefType("widget_toolkit") == this.prefs.PREF_STRING) {
            widget_toolkit = this.prefs.getCharPref("widget_toolkit");
        }
        else {
            var xul_runtime = Cc["@mozilla.org/xre/app-info;1"]
                                .getService(Ci.nsIXULRuntime);
            widget_toolkit = xul_runtime.widgetToolkit;
        }
        return (widget_toolkit == "gtk3") ? 3 : 2;
    },

    /* ::::: Use external utilities ::::: */

    findPathToExec: function(name) {
        // Return full path or null. Works like "which $name"

        var file = Cc["@mozilla.org/file/local;1"]
                     .createInstance(Ci.nsIFile);

        var env = Cc["@mozilla.org/process/environment;1"]
                    .getService(Ci.nsIEnvironment);
        var path = env.get("PATH").split(":");

        for (var i = 0; i < path.length; i++) {
            var full_path_to_exec = path[i] + "/" + name;

            file.initWithPath(full_path_to_exec);
            if (file.exists() && file.isExecutable()) {
                this.log("Command \"" + name + "\" was found in \"" + path[i] + "\"", "DEBUG");
                return full_path_to_exec;
            }
        }

        this.log("$PATH = " + path, "DEBUG");
        this.log("Command \"" + name + "\" not found", "ERROR");

        return null;
    },

    checkUtilsAvailable: function(utils) {
        var paths = {};
        for (var i = 0; i < utils.length; i++) {
            var path;
            if (this.utils[utils[i]] === undefined) {
                path = this.findPathToExec(utils[i]);
                this.utils[utils[i]] = path;
            }
            else {
                path = this.utils[utils[i]];
            }
            if (path == null)
                return null;
            paths[utils[i]] = path;
        }
        return paths;
    },

    checkPresenceGnomeShell: function() {
        this.log("Start checking DE", "DEBUG");

        var path = this.checkUtilsAvailable(["pidof"]);

        if (path.pidof) {
            var exitValue = HTitleUtilsPrivate.execute(path.pidof, ["gnome-shell"]);
            return (exitValue == 1 ? 1 : 0);
        }
        else {
            this.log("pidof doesn't exist", "ERROR");
            return 2;
        }
    },

    /* ::::: Native window ::::: */

    changeWindowProperty: function(window, mode, action) {
        var X11 = Libs.open("X11");
        var Gdk = Libs.open("Gdk", HTitleShare.gtkVersion, X11);

        /* Get native window */
        var base_window = window.QueryInterface(Ci.nsIInterfaceRequestor)
                                .getInterface(Ci.nsIWebNavigation)
                                .QueryInterface(Ci.nsIDocShellTreeItem)
                                .treeOwner
                                .QueryInterface(Ci.nsIInterfaceRequestor)
                                .nsIBaseWindow;
        var native_handle = base_window.nativeHandle;

        var gdk_window = new Gdk.GdkWindow.ptr(ctypes.UInt64(native_handle));
        gdk_window = Gdk.Window.get_toplevel(gdk_window);

        var gdk_display = Gdk.Display.get_default();
        var x11_display = Gdk.X11Display.get_xdisplay(gdk_display);
        if (HTitleShare.gtkVersion == 3) {
            var x11_window = Gdk.X11Window.get_xid(gdk_window);
        }
        else {
            var x11_window = Gdk.X11Window.get_xid(ctypes.cast(gdk_window, Gdk.GdkDrawable.ptr));
        }

        //Gdk.Window.hide(gdk_window);
        if (mode == "always") {
            Gdk.Window.set_decorations(gdk_window, (action == "set") ? Gdk.GDK_DECOR_BORDER : Gdk.GDK_DECOR_ALL);
        }
        else {
            if (HTitleShare.gtkVersion == 3) {
                Gdk.X11Window.set_hide_titlebar_when_maximized(gdk_window, (action == "set"));
            }
            else {
                let x11_property = Gdk.x11_get_xatom_by_name_for_display(gdk_display, "_GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED");
                if (action == "set") {
                    // let t = new Uint8Array([1]);
                    // let x11_data = ctypes.uint8_t.ptr(t);
                    let t = new Uint32Array([1]);
                    let x11_data = ctypes.uint32_t.ptr(t);
                    X11.XChangeProperty(x11_display, x11_window, x11_property, X11.XA_CARDINAL, 32, X11.PropModeReplace, x11_data, 1);
                }
                else {
                    X11.XDeleteProperty(x11_display, x11_window, x11_property);
                }
            }
        }
        //Gdk.Window.show(gdk_window);

        Libs.close(Gdk);
        Libs.close(X11);
    },

    setWindowProperty: function(window, mode) {
        try {
            this.changeWindowProperty(window, mode, "set");
        } catch (e) {
            return -1;
        }
        return 0;
    },

    removeWindowProperty: function(window, mode) {
        try {
            this.changeWindowProperty(window, mode, "remove");
        } catch (e) {
            return -1;
        }
        return 0;
    },

    lowerWindow: function(window) {
        var Gdk = Libs.open("Gdk", HTitleShare.gtkVersion);
        var base_window = window.QueryInterface(Ci.nsIInterfaceRequestor)
                                .getInterface(Ci.nsIWebNavigation)
                                .QueryInterface(Ci.nsIDocShellTreeItem)
                                .treeOwner
                                .QueryInterface(Ci.nsIInterfaceRequestor)
                                .nsIBaseWindow;
        var native_handle = base_window.nativeHandle;
        var gdk_window = new Gdk.GdkWindow.ptr(ctypes.UInt64(native_handle));
        gdk_window = Gdk.Window.get_toplevel(gdk_window);
        Gdk.Window.lower(gdk_window);
        Libs.close(Gdk);
    },

    /* ::::: CSS stylesheets ::::: */

    loadStyle: function(name) {
        var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
                    .getService(Ci.nsIStyleSheetService);
        var io = Cc["@mozilla.org/network/io-service;1"]
                   .getService(Ci.nsIIOService);
        var uri = io.newURI("chrome://htitle/skin/" + name + ".css", null, null);
        if (!sss.sheetRegistered(uri, sss.USER_SHEET))
            sss.loadAndRegisterSheet(uri, sss.USER_SHEET);
    },

    unloadStyle: function(name) {
        var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
                    .getService(Ci.nsIStyleSheetService);
        var io = Cc["@mozilla.org/network/io-service;1"]
                   .getService(Ci.nsIIOService);
        var uri = io.newURI("chrome://htitle/skin/" + name + ".css", null, null);
        if (sss.sheetRegistered(uri, sss.USER_SHEET))
            sss.unregisterSheet(uri, sss.USER_SHEET);
    },

    /* ::::: Preferences ::::: */

    getWindowControlsLayout: function() {
        var layout = ":close"; // It's default for GNOME 3

        if (!this.prefs.getBoolPref("window_controls.get_layout_by_gsettings"))
            return layout;

        try {
            var gsettings = Cc["@mozilla.org/gsettings-service;1"]
                              .getService(Ci.nsIGSettingsService);
        } catch(e) {
            this.log("GSettings isn't available", "WARNING");
            return layout;
        }

        var button_layout;
        var keys = ["org.gnome.shell.overrides", "org.gnome.desktop.wm.preferences"];
        for (let i=0; i<keys.length; i++) {
            try {
                button_layout = gsettings.getCollectionForSchema(keys[i])
                                         .getString("button-layout");
                this.log(keys[i] + ".button-layout = '" + button_layout + "'", "DEBUG");
                break;
            } catch(e) {
                continue;
            }
        }

        if (!button_layout) {
            this.log("Cann't get value from GSettings", "WARNING");
            return layout;
        }
        else if (/^([a-zA-Z0-9:,]*)$/.test(button_layout)) {
            layout = button_layout;
        }
        return layout;
    },

    getTitlebarActions: function() {
        var actions = {double: "toggle-maximize",
                       middle: "lower",
                       right:  "menu"}; // It's default for GNOME 3

        if (!this.prefs.getBoolPref("titlebar.get_actions_by_gsettings"))
            return actions;

        try {
            let gsettings = Cc["@mozilla.org/gsettings-service;1"]
                              .getService(Ci.nsIGSettingsService)
                              .getCollectionForSchema("org.gnome.desktop.wm.preferences");

            actions.double = gsettings.getString("action-double-click-titlebar");
            actions.middle = gsettings.getString("action-middle-click-titlebar");
            actions.right = gsettings.getString("action-right-click-titlebar");

            this.log("org.gnome.desktop.wm.preferences.action-double-click-titlebar = '" + actions.double + "'", "DEBUG");
            this.log("org.gnome.desktop.wm.preferences.action-middle-click-titlebar = '" + actions.middle + "'", "DEBUG");
            this.log("org.gnome.desktop.wm.preferences.action-right-click-titlebar = '" + actions.right + "'", "DEBUG");
        } catch(e) {
            this.log("GSettings isn't available", "WARNING");
            return actions;
        }

        return actions;
    },

    /* ::::: Logging ::::: */

    log: function(message, level="ERROR") {
        if (HTitleShare.debug == false && level == "DEBUG")
            return;

        var console = Cc["@mozilla.org/consoleservice;1"]
                        .getService(Ci.nsIConsoleService);

        var flag;
        switch (level) {
            case "ERROR":
                flag = 0;
                break;
            case "WARNING":
                flag = 1;
                break;
            default:
                flag = 4;
        }

        if (flag == 4) {
            console.logStringMessage("HTitle DEBUG: " + message);
        }
        else {
            var console_message = Cc["@mozilla.org/scripterror;1"]
                                    .createInstance(Ci.nsIScriptError);
            console_message.init(message, "HTitle", null, null, null, flag, null);
            console.logMessage(console_message);
        }
    },
}

HTitleUtils.init();
<commit_msg>Fix creating data array for X11.XChangeProperty()<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const {classes: Cc, interfaces: Ci, utils: Cu} = Components;

Cu.import("resource://gre/modules/ctypes.jsm");

Cu.import("chrome://htitle/content/HTitleShare.jsm");
Cu.import("chrome://htitle/content/PrefPageObserver.jsm");
Cu.import("chrome://htitle/content/Libs.jsm");

var EXPORTED_SYMBOLS = ["HTitleUtils"];

var HTitlePrefObserver = {
    register: function() {
        HTitleUtils.prefs.addObserver("", this, false);
    },

    unregister: function() {
        HTitleUtils.prefs.removeObserver("", this);
    },

    observe: function(subject, topic, data) {
        if (topic != "nsPref:changed")
            return;

        switch(data) {
            case "debug":
                HTitleShare.debug = HTitleUtils.prefs.getBoolPref("debug");
                break;
            case "legacy_mode.timeout_check":
                HTitleUtils.timeoutCheck = HTitleUtils.prefs.getIntPref("legacy_mode.timeout_check");
                break;
            case "legacy_mode.timeout_between_changes":
                HTitleUtils.timeoutBetweenChanges = HTitleUtils.prefs.getIntPref("legacy_mode.timeout_between_changes");
                break;
        }
    }
}

var HTitleUtilsPrivate = {
    execute: function(path, args, needWait=true) {
        var file = Cc["@mozilla.org/file/local;1"]
                     .createInstance(Ci.nsIFile);
        file.initWithPath(path);

        var process = Cc["@mozilla.org/process/util;1"]
                        .createInstance(Ci.nsIProcess);
        try {
            process.init(file);
            process.run(needWait, args, args.length);
        }
        catch (error) {
            HTitleUtils.log(error.message, "ERROR");
            return -1;
        }

        if (needWait) {
            HTitleUtils.log("Exit value of " + path + " is \"" + process.exitValue + "\"", "DEBUG");
            return process.exitValue;
        }
        else
            return 0;
    }
}

var HTitleUtils = {
    appInfo: null,
    prefs: null,

    windowControlsLayout: null,
    titlebarActions: null,

    utils: {},

    timeoutCheck: 200, // ms
    timeoutBetweenChanges: 200, // ms

    init: function() {
        this.appInfo = Cc["@mozilla.org/xre/app-info;1"]
                         .getService(Ci.nsIXULAppInfo);

        this.prefs = Cc["@mozilla.org/preferences-service;1"]
                       .getService(Ci.nsIPrefService)
                       .getBranch("extensions.htitle.");
        HTitlePrefObserver.register();

        HTitleShare.debug = this.prefs.getBoolPref("debug");
        this.timeoutCheck = this.prefs.getIntPref("legacy_mode.timeout_check");
        this.timeoutBetweenChanges = this.prefs.getIntPref("legacy_mode.timeout_between_changes");

        HTitleShare.gtkVersion = this.getGtkVersion();
        this.windowControlsLayout = this.getWindowControlsLayout();
        this.titlebarActions = this.getTitlebarActions();
    },

    /* ::::: App info functions ::::: */

    isFirefox: function() {
        return (this.appInfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}");
    },

    isThunderbird: function() {
        return (this.appInfo.ID == "{3550f703-e582-4d05-9a08-453d09bdfdc6}");
    },

    isSeaMonkey: function() {
        return (this.appInfo.ID == "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}");
    },

    /* ::::: Change currentset attribute ::::: */

    addToCurrentset: function(node, id) {
        var currentset = node.getAttribute("currentset");
        if (!currentset)
            currentset = node.getAttribute("defaultset");
        currentset = currentset + (currentset == "" ? "" : ",") + id;
        node.setAttribute("currentset", currentset);
    },

    removeFromCurrentset: function(node, id) {
        var currentset = node.getAttribute("currentset");
        if (!currentset)
            currentset = node.getAttribute("defaultset");
        var re = new RegExp("(^|,)" + id + "($|,)");
        currentset = currentset.replace(re, "$2");
        node.setAttribute("currentset", currentset);
    },

    /* ::::: Toolkit version ::::: */

    getGtkVersion: function() {
        var widget_toolkit;
        if (this.prefs.getPrefType("widget_toolkit") == this.prefs.PREF_STRING) {
            widget_toolkit = this.prefs.getCharPref("widget_toolkit");
        }
        else {
            var xul_runtime = Cc["@mozilla.org/xre/app-info;1"]
                                .getService(Ci.nsIXULRuntime);
            widget_toolkit = xul_runtime.widgetToolkit;
        }
        return (widget_toolkit == "gtk3") ? 3 : 2;
    },

    /* ::::: Use external utilities ::::: */

    findPathToExec: function(name) {
        // Return full path or null. Works like "which $name"

        var file = Cc["@mozilla.org/file/local;1"]
                     .createInstance(Ci.nsIFile);

        var env = Cc["@mozilla.org/process/environment;1"]
                    .getService(Ci.nsIEnvironment);
        var path = env.get("PATH").split(":");

        for (var i = 0; i < path.length; i++) {
            var full_path_to_exec = path[i] + "/" + name;

            file.initWithPath(full_path_to_exec);
            if (file.exists() && file.isExecutable()) {
                this.log("Command \"" + name + "\" was found in \"" + path[i] + "\"", "DEBUG");
                return full_path_to_exec;
            }
        }

        this.log("$PATH = " + path, "DEBUG");
        this.log("Command \"" + name + "\" not found", "ERROR");

        return null;
    },

    checkUtilsAvailable: function(utils) {
        var paths = {};
        for (var i = 0; i < utils.length; i++) {
            var path;
            if (this.utils[utils[i]] === undefined) {
                path = this.findPathToExec(utils[i]);
                this.utils[utils[i]] = path;
            }
            else {
                path = this.utils[utils[i]];
            }
            if (path == null)
                return null;
            paths[utils[i]] = path;
        }
        return paths;
    },

    checkPresenceGnomeShell: function() {
        this.log("Start checking DE", "DEBUG");

        var path = this.checkUtilsAvailable(["pidof"]);

        if (path.pidof) {
            var exitValue = HTitleUtilsPrivate.execute(path.pidof, ["gnome-shell"]);
            return (exitValue == 1 ? 1 : 0);
        }
        else {
            this.log("pidof doesn't exist", "ERROR");
            return 2;
        }
    },

    /* ::::: Native window ::::: */

    changeWindowProperty: function(window, mode, action) {
        var X11 = Libs.open("X11");
        var Gdk = Libs.open("Gdk", HTitleShare.gtkVersion, X11);

        /* Get native window */
        var base_window = window.QueryInterface(Ci.nsIInterfaceRequestor)
                                .getInterface(Ci.nsIWebNavigation)
                                .QueryInterface(Ci.nsIDocShellTreeItem)
                                .treeOwner
                                .QueryInterface(Ci.nsIInterfaceRequestor)
                                .nsIBaseWindow;
        var native_handle = base_window.nativeHandle;

        var gdk_window = new Gdk.GdkWindow.ptr(ctypes.UInt64(native_handle));
        gdk_window = Gdk.Window.get_toplevel(gdk_window);

        var gdk_display = Gdk.Display.get_default();
        var x11_display = Gdk.X11Display.get_xdisplay(gdk_display);
        if (HTitleShare.gtkVersion == 3) {
            var x11_window = Gdk.X11Window.get_xid(gdk_window);
        }
        else {
            var x11_window = Gdk.X11Window.get_xid(ctypes.cast(gdk_window, Gdk.GdkDrawable.ptr));
        }

        //Gdk.Window.hide(gdk_window);
        if (mode == "always") {
            Gdk.Window.set_decorations(gdk_window, (action == "set") ? Gdk.GDK_DECOR_BORDER : Gdk.GDK_DECOR_ALL);
        }
        else {
            if (HTitleShare.gtkVersion == 3) {
                Gdk.X11Window.set_hide_titlebar_when_maximized(gdk_window, (action == "set"));
            }
            else {
                let x11_property = Gdk.x11_get_xatom_by_name_for_display(gdk_display, "_GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED");
                if (action == "set") {
                    let t = new ctypes.ArrayType(ctypes.uint32_t)(1);
                    t[0] = 1;
                    let x11_data = ctypes.uint32_t.ptr(t);
                    X11.XChangeProperty(x11_display, x11_window, x11_property, X11.XA_CARDINAL, 32, X11.PropModeReplace, x11_data, 1);
                }
                else {
                    X11.XDeleteProperty(x11_display, x11_window, x11_property);
                }
            }
        }
        //Gdk.Window.show(gdk_window);

        Libs.close(Gdk);
        Libs.close(X11);
    },

    setWindowProperty: function(window, mode) {
        try {
            this.changeWindowProperty(window, mode, "set");
        } catch (e) {
            return -1;
        }
        return 0;
    },

    removeWindowProperty: function(window, mode) {
        try {
            this.changeWindowProperty(window, mode, "remove");
        } catch (e) {
            return -1;
        }
        return 0;
    },

    lowerWindow: function(window) {
        var Gdk = Libs.open("Gdk", HTitleShare.gtkVersion);
        var base_window = window.QueryInterface(Ci.nsIInterfaceRequestor)
                                .getInterface(Ci.nsIWebNavigation)
                                .QueryInterface(Ci.nsIDocShellTreeItem)
                                .treeOwner
                                .QueryInterface(Ci.nsIInterfaceRequestor)
                                .nsIBaseWindow;
        var native_handle = base_window.nativeHandle;
        var gdk_window = new Gdk.GdkWindow.ptr(ctypes.UInt64(native_handle));
        gdk_window = Gdk.Window.get_toplevel(gdk_window);
        Gdk.Window.lower(gdk_window);
        Libs.close(Gdk);
    },

    /* ::::: CSS stylesheets ::::: */

    loadStyle: function(name) {
        var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
                    .getService(Ci.nsIStyleSheetService);
        var io = Cc["@mozilla.org/network/io-service;1"]
                   .getService(Ci.nsIIOService);
        var uri = io.newURI("chrome://htitle/skin/" + name + ".css", null, null);
        if (!sss.sheetRegistered(uri, sss.USER_SHEET))
            sss.loadAndRegisterSheet(uri, sss.USER_SHEET);
    },

    unloadStyle: function(name) {
        var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
                    .getService(Ci.nsIStyleSheetService);
        var io = Cc["@mozilla.org/network/io-service;1"]
                   .getService(Ci.nsIIOService);
        var uri = io.newURI("chrome://htitle/skin/" + name + ".css", null, null);
        if (sss.sheetRegistered(uri, sss.USER_SHEET))
            sss.unregisterSheet(uri, sss.USER_SHEET);
    },

    /* ::::: Preferences ::::: */

    getWindowControlsLayout: function() {
        var layout = ":close"; // It's default for GNOME 3

        if (!this.prefs.getBoolPref("window_controls.get_layout_by_gsettings"))
            return layout;

        try {
            var gsettings = Cc["@mozilla.org/gsettings-service;1"]
                              .getService(Ci.nsIGSettingsService);
        } catch(e) {
            this.log("GSettings isn't available", "WARNING");
            return layout;
        }

        var button_layout;
        var keys = ["org.gnome.shell.overrides", "org.gnome.desktop.wm.preferences"];
        for (let i=0; i<keys.length; i++) {
            try {
                button_layout = gsettings.getCollectionForSchema(keys[i])
                                         .getString("button-layout");
                this.log(keys[i] + ".button-layout = '" + button_layout + "'", "DEBUG");
                break;
            } catch(e) {
                continue;
            }
        }

        if (!button_layout) {
            this.log("Cann't get value from GSettings", "WARNING");
            return layout;
        }
        else if (/^([a-zA-Z0-9:,]*)$/.test(button_layout)) {
            layout = button_layout;
        }
        return layout;
    },

    getTitlebarActions: function() {
        var actions = {double: "toggle-maximize",
                       middle: "lower",
                       right:  "menu"}; // It's default for GNOME 3

        if (!this.prefs.getBoolPref("titlebar.get_actions_by_gsettings"))
            return actions;

        try {
            let gsettings = Cc["@mozilla.org/gsettings-service;1"]
                              .getService(Ci.nsIGSettingsService)
                              .getCollectionForSchema("org.gnome.desktop.wm.preferences");

            actions.double = gsettings.getString("action-double-click-titlebar");
            actions.middle = gsettings.getString("action-middle-click-titlebar");
            actions.right = gsettings.getString("action-right-click-titlebar");

            this.log("org.gnome.desktop.wm.preferences.action-double-click-titlebar = '" + actions.double + "'", "DEBUG");
            this.log("org.gnome.desktop.wm.preferences.action-middle-click-titlebar = '" + actions.middle + "'", "DEBUG");
            this.log("org.gnome.desktop.wm.preferences.action-right-click-titlebar = '" + actions.right + "'", "DEBUG");
        } catch(e) {
            this.log("GSettings isn't available", "WARNING");
            return actions;
        }

        return actions;
    },

    /* ::::: Logging ::::: */

    log: function(message, level="ERROR") {
        if (HTitleShare.debug == false && level == "DEBUG")
            return;

        var console = Cc["@mozilla.org/consoleservice;1"]
                        .getService(Ci.nsIConsoleService);

        var flag;
        switch (level) {
            case "ERROR":
                flag = 0;
                break;
            case "WARNING":
                flag = 1;
                break;
            default:
                flag = 4;
        }

        if (flag == 4) {
            console.logStringMessage("HTitle DEBUG: " + message);
        }
        else {
            var console_message = Cc["@mozilla.org/scripterror;1"]
                                    .createInstance(Ci.nsIScriptError);
            console_message.init(message, "HTitle", null, null, null, flag, null);
            console.logMessage(console_message);
        }
    },
}

HTitleUtils.init();
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/lib/trace",
    "firebug/lib/locale",
    "firebug/lib/options",
    "firebug/lib/css",
    "firebug/lib/deprecated"
],
function(FBTrace, Locale, Options, Css, Deprecated) {

// ********************************************************************************************* //
// Constants

var Menu = {};

// ********************************************************************************************* //

Menu.createMenu = function(popup, label)
{
    var menu = popup.ownerDocument.createElement("menu");
    menu.setAttribute("label", label);

    var menuPopup = popup.ownerDocument.createElement("menupopup");

    popup.appendChild(menu);
    menu.appendChild(menuPopup);

    return menuPopup;
};

Menu.createMenuItem = function(popup, item, before)
{
    if ((typeof(item) == "string" && item == "-") || item.label == "-")
        return Menu.createMenuSeparator(popup, before);

    var menuitem = popup.ownerDocument.createElement("menuitem");

    Menu.setItemIntoElement(menuitem, item);

    if (before)
        popup.insertBefore(menuitem, before);
    else
        popup.appendChild(menuitem);

    return menuitem;
};

Menu.setItemIntoElement = function(element, item)
{
    var label = item.nol10n ? item.label : Locale.$STR(item.label);

    element.setAttribute("label", label);

    if (item.id)
        element.setAttribute("id", item.id);

    if (item.type)
        element.setAttribute("type", item.type);

    // Avoid closing the popup menu if a preference has been changed.
    // This allows to quickly change more options.
    if (item.type == "checkbox" && !item.closemenu)
        element.setAttribute("closemenu", "none");

    if (item.checked)
        element.setAttribute("checked", "true");

    if (item.disabled)
        element.setAttribute("disabled", "true");

    if (item.image)
    {
        element.setAttribute("class", "menuitem-iconic");
        element.setAttribute("image", item.image);
    }

    if (item.command)
        element.addEventListener("command", item.command, false);

    if (item.commandID)
        element.setAttribute("command", item.commandID);

    if (item.option)
        element.setAttribute("option", item.option);

    if (item.tooltiptext)
    {
        var tooltiptext = item.nol10n ? item.tooltiptext : Locale.$STR(item.tooltiptext);
        element.setAttribute("tooltiptext", tooltiptext);
    }

    if (item.className)
        Css.setClass(element, item.className);

    if (item.acceltext)
        element.setAttribute("acceltext", item.acceltext);
    else if (item.key)
        element.setAttribute("key", item.key);

    if (item.name)
        element.setAttribute("name", item.name);

    return element;
}

Menu.createMenuHeader = function(popup, item)
{
    var header = popup.ownerDocument.createElement("label");
    header.setAttribute("class", "menuHeader");

    var label = item.nol10n ? item.label : Locale.$STR(item.label);

    header.setAttribute("value", label);

    popup.appendChild(header);
    return header;
};

Menu.createMenuSeparator = function(popup, item, before)
{
    if (item instanceof Node)
    {
        return Deprecated.deprecated("The function's header changed to "+
            "createMenuSeparator(popup, item, before)",
            Menu.createMenuSeparator, [popup, null, before])();
    }

    if (!popup.firstChild)
        return;

    if (FBTrace.DBG_MENU)
        FBTrace.sysout("createMenuSeparator", {popup: popup, item: item, before: before});

    var menuItem = popup.ownerDocument.createElement("menuseparator");
    if (item && item.id)
        menuItem.setAttribute("id", item.id);

    if (before)
        popup.insertBefore(menuItem, before);
    else
        popup.appendChild(menuItem);
    return menuItem;
};

/**
 * Create an option menu item definition. This method is usually used in methods like:
 * {@link Firebug.Panel.getOptionsMenuItems} or {@link Firebug.Panel.getContextMenuItems}.
 *
 * @param {String} label Name of the string from *.properties file.
 * @param {String} option Name of the associated option.
 * @param {String, Optional} tooltiptext Optional name of the string from *.properties file
 *      that should be used as a tooltip for the menu.
 */
Menu.optionMenu = function(label, option, tooltiptext)
{
    return {
        label: label,
        type: "checkbox",
        checked: Firebug[option],
        option: option,
        tooltiptext: tooltiptext,
        command: function() {
            return Options.togglePref(option);
        }
    };
};

// ********************************************************************************************* //
// Registration

return Menu;

// ********************************************************************************************* //
});
<commit_msg>Allow creating submenus via Menu.createMenu() and Menu.createMenuItem()<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/trace",
    "firebug/lib/locale",
    "firebug/lib/options",
    "firebug/lib/css",
    "firebug/lib/deprecated"
],
function(FBTrace, Locale, Options, Css, Deprecated) {

// ********************************************************************************************* //
// Constants

var Menu = {};

// ********************************************************************************************* //

Menu.createMenu = function(popup, item)
{
    if (typeof item == "string")
    {
        return Deprecated.deprecated("The function's header changed to "+
            "createMenu(popup, item)",
            Menu.createMenu, [popup, {label: item}])();
    }

    var menu = popup.ownerDocument.createElement("menu");

    Menu.setItemIntoElement(menu, item);

    var menuPopup = popup.ownerDocument.createElement("menupopup");

    popup.appendChild(menu);
    menu.appendChild(menuPopup);

    if (item.items)
    {
        for (var i = 0, len = item.items.length; i < len; ++i)
            Menu.createMenuItem(menuPopup, item.items[i]);
    }

    return menuPopup;
};

Menu.createMenuItem = function(popup, item, before)
{
    if ((typeof(item) == "string" && item == "-") || item.label == "-")
        return Menu.createMenuSeparator(popup, item, before);

    if (item.items)
        return Menu.createMenu(popup, item);

    var menuitem = popup.ownerDocument.createElement("menuitem");

    Menu.setItemIntoElement(menuitem, item);

    if (before)
        popup.insertBefore(menuitem, before);
    else
        popup.appendChild(menuitem);

    return menuitem;
};

Menu.setItemIntoElement = function(element, item)
{
    var label = item.nol10n ? item.label : Locale.$STR(item.label);

    element.setAttribute("label", label);

    if (item.id)
        element.setAttribute("id", item.id);

    if (item.type)
        element.setAttribute("type", item.type);

    // Avoid closing the popup menu if a preference has been changed.
    // This allows to quickly change more options.
    if (item.type == "checkbox" && !item.closemenu)
        element.setAttribute("closemenu", "none");

    if (item.checked)
        element.setAttribute("checked", "true");

    if (item.disabled)
        element.setAttribute("disabled", "true");

    if (item.image)
    {
        element.setAttribute("class", "menuitem-iconic");
        element.setAttribute("image", item.image);
    }

    if (item.command)
        element.addEventListener("command", item.command, false);

    if (item.commandID)
        element.setAttribute("command", item.commandID);

    if (item.option)
        element.setAttribute("option", item.option);

    if (item.tooltiptext)
    {
        var tooltiptext = item.nol10n ? item.tooltiptext : Locale.$STR(item.tooltiptext);
        element.setAttribute("tooltiptext", tooltiptext);
    }

    if (item.className)
        Css.setClass(element, item.className);

    if (item.acceltext)
        element.setAttribute("acceltext", item.acceltext);
    else if (item.key)
        element.setAttribute("key", item.key);

    if (item.name)
        element.setAttribute("name", item.name);

    if (item.items && (item.command || item.commandID))
        element.setAttribute("type", "splitmenu");

    return element;
}

Menu.createMenuHeader = function(popup, item)
{
    var header = popup.ownerDocument.createElement("label");
    header.setAttribute("class", "menuHeader");

    var label = item.nol10n ? item.label : Locale.$STR(item.label);

    header.setAttribute("value", label);

    popup.appendChild(header);
    return header;
};

Menu.createMenuSeparator = function(popup, item, before)
{
    if (item instanceof Node)
    {
        return Deprecated.deprecated("The function's header changed to "+
            "createMenuSeparator(popup, item, before)",
            Menu.createMenuSeparator, [popup, null, before])();
    }

    if (!popup.firstChild)
        return;

    if (FBTrace.DBG_MENU)
        FBTrace.sysout("createMenuSeparator", {popup: popup, item: item, before: before});

    var menuItem = popup.ownerDocument.createElement("menuseparator");
    if (typeof item == "object" && item.id)
        menuItem.setAttribute("id", item.id);

    if (before)
        popup.insertBefore(menuItem, before);
    else
        popup.appendChild(menuItem);
    return menuItem;
};

/**
 * Create an option menu item definition. This method is usually used in methods like:
 * {@link Firebug.Panel.getOptionsMenuItems} or {@link Firebug.Panel.getContextMenuItems}.
 *
 * @param {String} label Name of the string from *.properties file.
 * @param {String} option Name of the associated option.
 * @param {String, Optional} tooltiptext Optional name of the string from *.properties file
 *      that should be used as a tooltip for the menu.
 */
Menu.optionMenu = function(label, option, tooltiptext)
{
    return {
        label: label,
        type: "checkbox",
        checked: Firebug[option],
        option: option,
        tooltiptext: tooltiptext,
        command: function() {
            return Options.togglePref(option);
        }
    };
};

// ********************************************************************************************* //
// Registration

return Menu;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>// javascript functions

//globals
var sections;
var userPosition;
var map;

//init globals
function initPage(){
  sections = [
    document.getElementById("home_section"),
    document.getElementById("about_section"),
    document.getElementById("locations_section"),
    document.getElementById("media_section"),
    document.getElementById("contact_section"),
  ];

  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      setLocation, geoLoadFail, {timeout:10000});
  } else {
    geoLoadFail();
  }

  initMap();
}

function initMap(){
  var center = new google.maps.LatLng(38.898013, -77.036539);
  if(userPosition){
    center = userPosition;
  }

  console.log("Center position: " + center);

  var mapOptions = {
    center: center,
    zoom: 8 };
  map = new google.maps.Map(
    document.getElementById("locationMap"),
    mapOptions);

  addMarker(38.885492, -77.097200, "Arlington, VA");
  addMarker(38.916833, -77.226124, "McLean, VA");
  addMarker(38.998082, -76.910128, "Greenbelt, MD");
}

function addMarker(lat, lng, title) {
  var mark = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    title: title
  });
}

function showSection(name){
  sections.forEach(function (item, index, array) {
    item.style.display = "none";
    if(item.id.indexOf(name) == 0){
      item.style.display = "";
    }
  });
}

function setLocation(position) {
  console.log("Latitude: " + position.coords.latitude);
  console.log("Longitude: " + position.coords.longitude);
  userPosition = position;

}

function geoLoadFail() {
  console.log("Geolocation information not available or not authorized.");
  userPosition = null;
}
<commit_msg>Fix google map display<commit_after>// javascript functions

//globals
var sections;
var userPosition;
var map;
var mapLoaded = false;

function initMap(){
  var center = new google.maps.LatLng(38.898013, -77.036539);
  if(userPosition){
    center = userPosition;
  }

  console.log("Center position: " + center);

  var mapOptions = {
    center: center,
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(
      document.getElementById("locationMap"),
      mapOptions);

  addMarker(38.885492, -77.097200, "Arlington, VA");
  addMarker(38.916833, -77.226124, "McLean, VA");
  addMarker(38.998082, -76.910128, "Greenbelt, MD");
}

function addMarker(lat, lng, title) {
  var mark = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    title: title
  });
}

function showSection(name){
  sections.forEach(function (item, index, array) {
    item.style.display = "none";
    if(item.id.indexOf(name) == 0){
      item.style.display = "";
    }
  });

  if (name == "locations" && !mapLoaded){
    initMap();
    google.maps.event.trigger(map, "resize");
    mapLoaded = true;
  }
}

function setLocation(position) {
  console.log("Geolocation Latitude: " + position.coords.latitude);
  console.log("Geolocation Longitude: " + position.coords.longitude);
  userPosition = new google.maps.LatLng(position.coords.latitude,
      position.coords.longitude);

}

function geoLoadFail() {
  console.log("Geolocation information not available or not authorized.");
  userPosition = null;
}

//init globals
function initPage(){
  sections = [
    document.getElementById("home_section"),
    document.getElementById("about_section"),
    document.getElementById("locations_section"),
    document.getElementById("media_section"),
    document.getElementById("contact_section")
  ];

  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        setLocation, geoLoadFail, {timeout:10000});
  } else {
    geoLoadFail();
  }
}

<|endoftext|>