<commit_before>// InstrumentClone.js
//
// Copyright 2018 High Fidelity, Inc.
// Created by Robin Wilson 7/5/2018
// Expands on guitarMexico.js created by Rebecca Stankus 01/31/18
//
// Entity script that plays the sound while holding the entity.
// Chooses the sound bite randomly from a list passed in.
// Takes two parameters :
//     musicURLs - list of relative music urls
//     audioVolumeLevel - sets the magnitude of the sounds defaults to 0.3
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html

/* global module */

var NO_HANDS = 0;
var ONE_HAND = 1;
var BOTH_HANDS = 2;
var LIFETIME_ON_PICKUP = 18;
var LIFETIME_ON_RELEASE = 8;

var SECS_TO_MS = 1000;
var UPDATE_POSITION_MS = 50;
var FIRST_LOAD_TIMEOUT = 50;
var DEFAULT_VOLUME_LEVEL = 0.1;
var DEBUG = false;

var InstrumentClone = function (musicURLs, audioVolumeLevel) {
    this.musicURLs = musicURLs;
    this.audioVolumeLevel = audioVolumeLevel || DEFAULT_VOLUME_LEVEL;
    this.injector = null;
    this.playing = false;
    this.sounds = [];
    this.firstLoad = true;
    this.handNum = 0;
    this.updatePositionInterval = null;
    this.currentPosition;
};

InstrumentClone.prototype = {

    // ENTITY METHODS
    preload: function (entityID) {
        this.entityID = entityID;

        var entityProperties = Entities.getEntityProperties(this.entityID, ["position", "name", "age"]);
        this.currentPosition = entityProperties.position;
        this.handNum = 0;

        Script.setTimeout(function(){
            if(entityProperties.name && entityProperties.name.indexOf("clone") !== -1){
                if (DEBUG) {
                    print("Instrument clone: preload edit lifetime ", entityProperties.name);
                }
                Entities.editEntity(this.entityID, { lifetime: entityProperties.age + LIFETIME_ON_PICKUP });
            }
        }, FIRST_LOAD_TIMEOUT);

        this.loadSounds();
    },

    startNearGrab: function (thisEntity, otherEntity, collision) {

        if (DEBUG) {
            print("Instrument clone: Start near grab");
        }

        if (this.handNum === NO_HANDS) {
            this.handNum = ONE_HAND;
        } else {
            this.handNum = BOTH_HANDS;
        }

        var age = Entities.getEntityProperties(this.entityID, "age").age;
        Entities.editEntity(this.entityID, { lifetime: age + LIFETIME_ON_PICKUP });
        this.startSound();
    },

    releaseGrab: function () {
        if (DEBUG) {
            print("Instrument clone: release grab");
        }

        if (this.handNum === BOTH_HANDS) {
            this.handNum = ONE_HAND;
        } else {
            this.stopSound();

            var age = Entities.getEntityProperties(this.entityID, "age").age;
            Entities.editEntity(this.entityID, { lifetime: age + LIFETIME_ON_RELEASE });
            this.handNum = NO_HANDS;
        }
    },

    clickReleaseOnEntity: function (entityID, mouseEvent) {

        if (mouseEvent.isLeftButton) {
            if (!this.playing) {
                this.startSound();
            } else {
                this.stopSound();
            }
        }
    },

    unload: function () {
        this.stopSound();
        this.handNum = NO_HANDS;
    },
    // END ENTITY METHODS

    // SOUND UTILITIES
    loadSounds: function () {

        if (DEBUG) {
            print("Instrument clone: load sounds ", JSON.stringify(this.musicURLs));
        }

        var _this = this;

        this.musicURLs.forEach(function (soundURL, idx) {
            _this.sounds[idx] = SoundCache.getSound(Script.resolvePath(soundURL));
        });

        this.firstLoad = true;

        if (DEBUG) {
            print("Instrument clone: Sounds are:", JSON.stringify(this.sounds));
        }
    },

    startSound: function () {
        var _this = this;

        if (DEBUG) {
            print("Instrument clone: Start sound, first load is ", this.firstLoad);
        }

        if (this.firstLoad) {
            // Give time to ensure random sound is downloaded on first pickup
            Script.setTimeout(function () {
                _this.playSound();
            }, FIRST_LOAD_TIMEOUT);

            this.firstLoad = false;
        } else {
            this.playSound();
        }
    },

    getRandomSound: function () {
        var randSound = this.sounds[Math.floor(Math.random() * this.sounds.length)];
        return randSound;
    },

    playSound: function () {

        var _this = this;
        var sound = this.getRandomSound();

        if (DEBUG) {
            print("Instrument clone: isPlaying ", !this.playing, " soundDownloaded", sound.downloaded);
            print("Instrument clone: Random soung ", JSON.stringify(sound));
        }

        if (!this.playing && sound.downloaded) {

            var position = Entities.getEntityProperties(this.entityID, 'position').position;

            // Play sound
            this.injector = Audio.playSound(sound, {
                position: position,
                volume: _this.audioVolumeLevel
            });

            this.playing = true;

            var injector = this.injector;
            var entityID = this.entityID;

            // Update sound position using interval
            this.updatePositionInterval = Script.setInterval(function () {
                var position = Entities.getEntityProperties(entityID, 'position').position;
                injector.options = { position: position };
            }, UPDATE_POSITION_MS);

            // length of sound timeout
            var soundLength = sound.duration * SECS_TO_MS;

            Script.setTimeout(function () {
                if (_this.playing) {
                    _this.stopSound();
                }
            }, soundLength);
        }
    },

    stopSound: function () {

        if (DEBUG) {
            print("Instrument clone: stop sound");
        }

        this.playing = false;

        if (this.injector) {
            this.injector.stop();
            this.injector = null;
        }
        if (this.updatePositionInterval) {
            Script.clearInterval(this.updatePositionInterval);
            this.updatePositionInterval = null;
        }
    }
    // END SOUND UTILITIES
};

module.exports = {
    instrumentClone: InstrumentClone
};
<commit_msg>commented click on entity<commit_after>// InstrumentClone.js
//
// Copyright 2018 High Fidelity, Inc.
// Created by Robin Wilson 7/5/2018
// Expands on guitarMexico.js created by Rebecca Stankus 01/31/18
//
// Entity script that plays the sound while holding the entity.
// Chooses the sound bite randomly from a list passed in.
// Takes two parameters :
//     musicURLs - list of relative music urls
//     audioVolumeLevel - sets the magnitude of the sounds defaults to 0.3
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html

/* global module */

var NO_HANDS = 0;
var ONE_HAND = 1;
var BOTH_HANDS = 2;
var LIFETIME_ON_PICKUP = 18;
var LIFETIME_ON_RELEASE = 8;

var SECS_TO_MS = 1000;
var UPDATE_POSITION_MS = 50;
var FIRST_LOAD_TIMEOUT = 50;
var DEFAULT_VOLUME_LEVEL = 0.1;
var DEBUG = false;

var InstrumentClone = function (musicURLs, audioVolumeLevel) {
    this.musicURLs = musicURLs;
    this.audioVolumeLevel = audioVolumeLevel || DEFAULT_VOLUME_LEVEL;
    this.injector = null;
    this.playing = false;
    this.sounds = [];
    this.firstLoad = true;
    this.handNum = 0;
    this.updatePositionInterval = null;
    this.currentPosition;
};

InstrumentClone.prototype = {

    // ENTITY METHODS
    preload: function (entityID) {
        this.entityID = entityID;

        var entityProperties = Entities.getEntityProperties(this.entityID, ["position", "name", "age"]);
        this.currentPosition = entityProperties.position;
        this.handNum = 0;

        Script.setTimeout(function(){
            if(entityProperties.name && entityProperties.name.indexOf("clone") !== -1){
                if (DEBUG) {
                    print("Instrument clone: preload edit lifetime ", entityProperties.name);
                }
                Entities.editEntity(this.entityID, { lifetime: entityProperties.age + LIFETIME_ON_PICKUP });
            }
        }, FIRST_LOAD_TIMEOUT);

        this.loadSounds();
    },

    startNearGrab: function (thisEntity, otherEntity, collision) {

        if (DEBUG) {
            print("Instrument clone: Start near grab");
        }

        if (this.handNum === NO_HANDS) {
            this.handNum = ONE_HAND;
        } else {
            this.handNum = BOTH_HANDS;
        }

        var age = Entities.getEntityProperties(this.entityID, "age").age;
        Entities.editEntity(this.entityID, { lifetime: age + LIFETIME_ON_PICKUP });
        this.startSound();
    },

    releaseGrab: function () {
        if (DEBUG) {
            print("Instrument clone: release grab");
        }

        if (this.handNum === BOTH_HANDS) {
            this.handNum = ONE_HAND;
        } else {
            this.stopSound();

            var age = Entities.getEntityProperties(this.entityID, "age").age;
            Entities.editEntity(this.entityID, { lifetime: age + LIFETIME_ON_RELEASE });
            this.handNum = NO_HANDS;
        }
    },

    // clickReleaseOnEntity: function (entityID, mouseEvent) {

    //     if (mouseEvent.isLeftButton) {
    //         if (!this.playing) {
    //             this.startSound();
    //         } else {
    //             this.stopSound();
    //         }
    //     }
    // },

    unload: function () {
        this.stopSound();
        this.handNum = NO_HANDS;
    },
    // END ENTITY METHODS

    // SOUND UTILITIES
    loadSounds: function () {

        if (DEBUG) {
            print("Instrument clone: load sounds ", JSON.stringify(this.musicURLs));
        }

        var _this = this;

        this.musicURLs.forEach(function (soundURL, idx) {
            _this.sounds[idx] = SoundCache.getSound(Script.resolvePath(soundURL));
        });

        this.firstLoad = true;

        if (DEBUG) {
            print("Instrument clone: Sounds are:", JSON.stringify(this.sounds));
        }
    },

    startSound: function () {
        var _this = this;

        if (DEBUG) {
            print("Instrument clone: Start sound, first load is ", this.firstLoad);
        }

        if (this.firstLoad) {
            // Give time to ensure random sound is downloaded on first pickup
            Script.setTimeout(function () {
                _this.playSound();
            }, FIRST_LOAD_TIMEOUT);

            this.firstLoad = false;
        } else {
            this.playSound();
        }
    },

    getRandomSound: function () {
        var randSound = this.sounds[Math.floor(Math.random() * this.sounds.length)];
        return randSound;
    },

    playSound: function () {

        var _this = this;
        var sound = this.getRandomSound();

        if (DEBUG) {
            print("Instrument clone: isPlaying ", !this.playing, " soundDownloaded", sound.downloaded);
            print("Instrument clone: Random soung ", JSON.stringify(sound));
        }

        if (!this.playing && sound.downloaded) {

            var position = Entities.getEntityProperties(this.entityID, 'position').position;

            // Play sound
            this.injector = Audio.playSound(sound, {
                position: position,
                volume: _this.audioVolumeLevel
            });

            this.playing = true;

            var injector = this.injector;
            var entityID = this.entityID;

            // Update sound position using interval
            this.updatePositionInterval = Script.setInterval(function () {
                var position = Entities.getEntityProperties(entityID, 'position').position;
                injector.options = { position: position };
            }, UPDATE_POSITION_MS);

            // length of sound timeout
            var soundLength = sound.duration * SECS_TO_MS;

            Script.setTimeout(function () {
                if (_this.playing) {
                    _this.stopSound();
                }
            }, soundLength);
        }
    },

    stopSound: function () {

        if (DEBUG) {
            print("Instrument clone: stop sound");
        }

        this.playing = false;

        if (this.injector) {
            this.injector.stop();
            this.injector = null;
        }
        if (this.updatePositionInterval) {
            Script.clearInterval(this.updatePositionInterval);
            this.updatePositionInterval = null;
        }
    }
    // END SOUND UTILITIES
};

module.exports = {
    instrumentClone: InstrumentClone
};
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {

var OptionsPage = options.OptionsPage;

  //
  // AdvancedOptions class
  // Encapsulated handling of advanced options page.
  //
  function AdvancedOptions() {
    OptionsPage.call(this, 'advanced', templateData.advancedPage,
                     'advancedPage');
  }

  cr.addSingletonGetter(AdvancedOptions);

  AdvancedOptions.prototype = {
    // Inherit AdvancedOptions from OptionsPage.
    __proto__: options.OptionsPage.prototype,

    /**
     * Initializes the page.
     */
    initializePage: function() {
      // Call base class implementation to starts preference initialization.
      OptionsPage.prototype.initializePage.call(this);

      // Set up click handlers for buttons.
      $('privacyContentSettingsButton').onclick = function(event) {
        OptionsPage.showPageByName('content');
        OptionsPage.showTab($('cookies-nav-tab'));
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ContentSettings']);
      };
      $('privacyClearDataButton').onclick = function(event) {
        OptionsPage.showOverlay('clearBrowserDataOverlay');
        chrome.send('coreOptionsUserMetricsAction', ['Options_ClearData']);
      };

      // 'metricsReportingEnabled' element is only present on Chrome branded
      // builds.
      if ($('metricsReportingEnabled')) {
        $('metricsReportingEnabled').onclick = function(event) {
          chrome.send('metricsReportingCheckboxAction',
              [String(event.target.checked)]);
        };
      }

      $('autoOpenFileTypesResetToDefault').onclick = function(event) {
        chrome.send('autoOpenFileTypesAction');
      };
      $('fontSettingsCustomizeFontsButton').onclick = function(event) {
        OptionsPage.showPageByName('fontSettings');
        chrome.send('coreOptionsUserMetricsAction', ['Options_FontSettings']);
      };
      $('defaultFontSize').onchange = function(event) {
        chrome.send('defaultFontSizeAction',
            [String(event.target.options[event.target.selectedIndex].value)]);
      };
      $('language-button').onclick = function(event) {
        OptionsPage.showPageByName('language');
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_LanuageAndSpellCheckSettings']);
      };

      if (cr.isWindows || cr.isMac) {
        $('certificatesManageButton').onclick = function(event) {
          chrome.send('showManageSSLCertificates');
        };
      } else {
        $('certificatesManageButton').onclick = function(event) {
          OptionsPage.showPageByName('certificateManager');
          OptionsPage.showTab($('personal-certs-nav-tab'));
          chrome.send('coreOptionsUserMetricsAction',
                      ['Options_ManageSSLCertificates']);
        };
      }

      if (!cr.isChromeOS) {
        $('proxiesConfigureButton').onclick = function(event) {
          chrome.send('showNetworkProxySettings');
        };
        $('downloadLocationChangeButton').onclick = function(event) {
          chrome.send('selectDownloadLocation');
        };

        // Remove Windows-style accelerators from the Browse button label.
        // TODO(csilv): Remove this after the accelerator has been removed from
        // the localized strings file, pending removal of old options window.
        $('downloadLocationChangeButton').textContent =
            localStrings.getStringWithoutAccelerator(
                'downloadLocationChangeButton');
      } else {
        $('proxiesConfigureButton').onclick = function(event) {
          OptionsPage.showPageByName('proxy');
          chrome.send('coreOptionsUserMetricsAction',
              ['Options_ShowProxySettings']);
        };
      }

      if (cr.isWindows) {
        $('sslCheckRevocation').onclick = function(event) {
          chrome.send('checkRevocationCheckboxAction',
              [String($('sslCheckRevocation').checked)]);
        };
        $('sslUseSSL3').onclick = function(event) {
          chrome.send('useSSL3CheckboxAction',
              [String($('sslUseSSL3').checked)]);
        };
        $('sslUseTLS1').onclick = function(event) {
          chrome.send('useTLS1CheckboxAction',
              [String($('sslUseTLS1').checked)]);
        };
        $('gearSettingsConfigureGearsButton').onclick = function(event) {
          chrome.send('showGearsSettings');
        };
      }

      // 'cloudPrintProxyEnabled' is true for Chrome branded builds on
      // certain platforms, or could be enabled by a lab.
      if (!cr.isChromeOS &&
          localStrings.getString('enable-cloud-print-proxy') == 'true') {
        $('cloudPrintProxySetupButton').onclick = function(event) {
          if ($('cloudPrintProxyManageButton').style.display == 'none') {
            // Disable the button, set it's text to the intermediate state.
            $('cloudPrintProxySetupButton').textContent =
              localStrings.getString('cloudPrintProxyEnablingButton');
            $('cloudPrintProxySetupButton').disabled = true;
            chrome.send('showCloudPrintSetupDialog');
          } else {
            chrome.send('disableCloudPrintProxy');
          }
        };
        $('cloudPrintProxyManageButton').onclick = function(event) {
          chrome.send('showCloudPrintManagePage');
        };
      }

      if ($('remotingSetupButton')) {
        $('remotingSetupButton').onclick = function(event) {
          chrome.send('showRemotingSetupDialog');
        }
      }
    }
  };

  //
  // Chrome callbacks
  //

  // Set the checked state of the metrics reporting checkbox.
  AdvancedOptions.SetMetricsReportingCheckboxState = function(
      checked, disabled) {
    $('metricsReportingEnabled').checked = checked;
    $('metricsReportingEnabled').disabled = disabled;
    if (disabled)
      $('metricsReportingEnabledText').className = 'disable-services-span';
  }

  AdvancedOptions.SetMetricsReportingSettingVisibility = function(visible) {
    if (visible) {
      $('metricsReportingSetting').style.display = 'block';
    } else {
      $('metricsReportingSetting').style.display = 'none';
    }
  }

  // Set the font size selected item.
  AdvancedOptions.SetFontSize = function(fixed_font_size_value,
      font_size_value) {
    var selectCtl = $('defaultFontSize');
    if (fixed_font_size_value == font_size_value) {
      for (var i = 0; i < selectCtl.options.length; i++) {
        if (selectCtl.options[i].value == font_size_value) {
          selectCtl.selectedIndex = i;
          if ($('Custom'))
            selectCtl.remove($('Custom').index);
          return;
        }
      }
    }

    // Add/Select Custom Option in the font size label list.
    if (!$('Custom')) {
      var option = new Option(localStrings.getString('fontSizeLabelCustom'),
                              -1, false, true);
      option.setAttribute("id", "Custom");
      selectCtl.add(option);
    }
    $('Custom').selected = true;
  };

  // Set the download path.
  AdvancedOptions.SetDownloadLocationPath = function(path) {
    if (!cr.isChromeOS)
      $('downloadLocationPath').value = path;
  };

  // Set the enabled state for the autoOpenFileTypesResetToDefault button.
  AdvancedOptions.SetAutoOpenFileTypesDisabledAttribute = function(disabled) {
    $('autoOpenFileTypesResetToDefault').disabled = disabled;
  };

  // Set the enabled state for the proxy settings button.
  AdvancedOptions.SetupProxySettingsSection = function(disabled, label) {
    $('proxiesConfigureButton').disabled = disabled;
    $('proxiesLabel').textContent = label;
  };

  // Set the checked state for the sslCheckRevocation checkbox.
  AdvancedOptions.SetCheckRevocationCheckboxState = function(
      checked, disabled) {
    $('sslCheckRevocation').checked = checked;
    $('sslCheckRevocation').disabled = disabled;
  };

  // Set the checked state for the sslUseSSL3 checkbox.
  AdvancedOptions.SetUseSSL3CheckboxState = function(checked, disabled) {
    $('sslUseSSL3').checked = checked;
    $('sslUseSSL3').disabled = disabled;
  };

  // Set the checked state for the sslUseTLS1 checkbox.
  AdvancedOptions.SetUseTLS1CheckboxState = function(checked, disabled) {
    $('sslUseTLS1').checked = checked;
    $('sslUseTLS1').disabled = disabled;
  };

  // Set the Cloud Print proxy UI to enabled, disabled, or processing.
  AdvancedOptions.SetupCloudPrintProxySection = function(disabled, label) {
    if (!cr.isChromeOS) {
      $('cloudPrintProxyLabel').textContent = label;
      if (disabled) {
        $('cloudPrintProxySetupButton').textContent =
          localStrings.getString('cloudPrintProxyDisabledButton');
        $('cloudPrintProxyManageButton').style.display = 'none';
      } else {
        $('cloudPrintProxySetupButton').textContent =
          localStrings.getString('cloudPrintProxyEnabledButton');
        $('cloudPrintProxyManageButton').style.display = 'inline';
      }
      $('cloudPrintProxySetupButton').disabled = false;
    }
  };

  AdvancedOptions.RemoveCloudPrintProxySection = function() {
    if (!cr.isChromeOS) {
      var proxySectionElm = $('cloud-print-proxy-section');
      proxySectionElm.parentNode.removeChild(proxySectionElm);
    }
  };

  AdvancedOptions.SetRemotingStatus = function(enabled, status) {
    if (enabled) {
      $('remotingSetupButton').style.display = 'none';
      $('remotingStopButton').style.display = 'inline';
    } else {
      $('remotingSetupButton').style.display = 'inline';
      $('remotingStopButton').style.display = 'none';
    }
    $('remotingStatus').textContent = status;
  };

  AdvancedOptions.RemoveRemotingSection = function() {
    var proxySectionElm = $('remoting-section');
    if (proxySectionElm)
      proxySectionElm.parentNode.removeChild(proxySectionElm);
  };

  // Export
  return {
    AdvancedOptions: AdvancedOptions
  };

});
<commit_msg>Fix the regression caused by r72061. The CL ifdef'ed out for some parts of HTML, but it did not touch the corresponding JS code that modifies the part.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {

var OptionsPage = options.OptionsPage;

  //
  // AdvancedOptions class
  // Encapsulated handling of advanced options page.
  //
  function AdvancedOptions() {
    OptionsPage.call(this, 'advanced', templateData.advancedPage,
                     'advancedPage');
  }

  cr.addSingletonGetter(AdvancedOptions);

  AdvancedOptions.prototype = {
    // Inherit AdvancedOptions from OptionsPage.
    __proto__: options.OptionsPage.prototype,

    /**
     * Initializes the page.
     */
    initializePage: function() {
      // Call base class implementation to starts preference initialization.
      OptionsPage.prototype.initializePage.call(this);

      // Set up click handlers for buttons.
      $('privacyContentSettingsButton').onclick = function(event) {
        OptionsPage.showPageByName('content');
        OptionsPage.showTab($('cookies-nav-tab'));
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ContentSettings']);
      };
      $('privacyClearDataButton').onclick = function(event) {
        OptionsPage.showOverlay('clearBrowserDataOverlay');
        chrome.send('coreOptionsUserMetricsAction', ['Options_ClearData']);
      };

      // 'metricsReportingEnabled' element is only present on Chrome branded
      // builds.
      if ($('metricsReportingEnabled')) {
        $('metricsReportingEnabled').onclick = function(event) {
          chrome.send('metricsReportingCheckboxAction',
              [String(event.target.checked)]);
        };
      }

      if (!cr.isChromeOS) {
        $('autoOpenFileTypesResetToDefault').onclick = function(event) {
          chrome.send('autoOpenFileTypesAction');
        };
      }

      $('fontSettingsCustomizeFontsButton').onclick = function(event) {
        OptionsPage.showPageByName('fontSettings');
        chrome.send('coreOptionsUserMetricsAction', ['Options_FontSettings']);
      };
      $('defaultFontSize').onchange = function(event) {
        chrome.send('defaultFontSizeAction',
            [String(event.target.options[event.target.selectedIndex].value)]);
      };
      $('language-button').onclick = function(event) {
        OptionsPage.showPageByName('language');
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_LanuageAndSpellCheckSettings']);
      };

      if (cr.isWindows || cr.isMac) {
        $('certificatesManageButton').onclick = function(event) {
          chrome.send('showManageSSLCertificates');
        };
      } else {
        $('certificatesManageButton').onclick = function(event) {
          OptionsPage.showPageByName('certificateManager');
          OptionsPage.showTab($('personal-certs-nav-tab'));
          chrome.send('coreOptionsUserMetricsAction',
                      ['Options_ManageSSLCertificates']);
        };
      }

      if (!cr.isChromeOS) {
        $('proxiesConfigureButton').onclick = function(event) {
          chrome.send('showNetworkProxySettings');
        };
        $('downloadLocationChangeButton').onclick = function(event) {
          chrome.send('selectDownloadLocation');
        };

        // Remove Windows-style accelerators from the Browse button label.
        // TODO(csilv): Remove this after the accelerator has been removed from
        // the localized strings file, pending removal of old options window.
        $('downloadLocationChangeButton').textContent =
            localStrings.getStringWithoutAccelerator(
                'downloadLocationChangeButton');
      } else {
        $('proxiesConfigureButton').onclick = function(event) {
          OptionsPage.showPageByName('proxy');
          chrome.send('coreOptionsUserMetricsAction',
              ['Options_ShowProxySettings']);
        };
      }

      if (cr.isWindows) {
        $('sslCheckRevocation').onclick = function(event) {
          chrome.send('checkRevocationCheckboxAction',
              [String($('sslCheckRevocation').checked)]);
        };
        $('sslUseSSL3').onclick = function(event) {
          chrome.send('useSSL3CheckboxAction',
              [String($('sslUseSSL3').checked)]);
        };
        $('sslUseTLS1').onclick = function(event) {
          chrome.send('useTLS1CheckboxAction',
              [String($('sslUseTLS1').checked)]);
        };
        $('gearSettingsConfigureGearsButton').onclick = function(event) {
          chrome.send('showGearsSettings');
        };
      }

      // 'cloudPrintProxyEnabled' is true for Chrome branded builds on
      // certain platforms, or could be enabled by a lab.
      if (!cr.isChromeOS &&
          localStrings.getString('enable-cloud-print-proxy') == 'true') {
        $('cloudPrintProxySetupButton').onclick = function(event) {
          if ($('cloudPrintProxyManageButton').style.display == 'none') {
            // Disable the button, set it's text to the intermediate state.
            $('cloudPrintProxySetupButton').textContent =
              localStrings.getString('cloudPrintProxyEnablingButton');
            $('cloudPrintProxySetupButton').disabled = true;
            chrome.send('showCloudPrintSetupDialog');
          } else {
            chrome.send('disableCloudPrintProxy');
          }
        };
        $('cloudPrintProxyManageButton').onclick = function(event) {
          chrome.send('showCloudPrintManagePage');
        };
      }

      if ($('remotingSetupButton')) {
        $('remotingSetupButton').onclick = function(event) {
          chrome.send('showRemotingSetupDialog');
        }
      }
    }
  };

  //
  // Chrome callbacks
  //

  // Set the checked state of the metrics reporting checkbox.
  AdvancedOptions.SetMetricsReportingCheckboxState = function(
      checked, disabled) {
    $('metricsReportingEnabled').checked = checked;
    $('metricsReportingEnabled').disabled = disabled;
    if (disabled)
      $('metricsReportingEnabledText').className = 'disable-services-span';
  }

  AdvancedOptions.SetMetricsReportingSettingVisibility = function(visible) {
    if (visible) {
      $('metricsReportingSetting').style.display = 'block';
    } else {
      $('metricsReportingSetting').style.display = 'none';
    }
  }

  // Set the font size selected item.
  AdvancedOptions.SetFontSize = function(fixed_font_size_value,
      font_size_value) {
    var selectCtl = $('defaultFontSize');
    if (fixed_font_size_value == font_size_value) {
      for (var i = 0; i < selectCtl.options.length; i++) {
        if (selectCtl.options[i].value == font_size_value) {
          selectCtl.selectedIndex = i;
          if ($('Custom'))
            selectCtl.remove($('Custom').index);
          return;
        }
      }
    }

    // Add/Select Custom Option in the font size label list.
    if (!$('Custom')) {
      var option = new Option(localStrings.getString('fontSizeLabelCustom'),
                              -1, false, true);
      option.setAttribute("id", "Custom");
      selectCtl.add(option);
    }
    $('Custom').selected = true;
  };

  // Set the download path.
  AdvancedOptions.SetDownloadLocationPath = function(path) {
    if (!cr.isChromeOS)
      $('downloadLocationPath').value = path;
  };

  // Set the enabled state for the autoOpenFileTypesResetToDefault button.
  AdvancedOptions.SetAutoOpenFileTypesDisabledAttribute = function(disabled) {
    if (!cr.isChromeOS)
      $('autoOpenFileTypesResetToDefault').disabled = disabled;
  };

  // Set the enabled state for the proxy settings button.
  AdvancedOptions.SetupProxySettingsSection = function(disabled, label) {
    $('proxiesConfigureButton').disabled = disabled;
    $('proxiesLabel').textContent = label;
  };

  // Set the checked state for the sslCheckRevocation checkbox.
  AdvancedOptions.SetCheckRevocationCheckboxState = function(
      checked, disabled) {
    $('sslCheckRevocation').checked = checked;
    $('sslCheckRevocation').disabled = disabled;
  };

  // Set the checked state for the sslUseSSL3 checkbox.
  AdvancedOptions.SetUseSSL3CheckboxState = function(checked, disabled) {
    $('sslUseSSL3').checked = checked;
    $('sslUseSSL3').disabled = disabled;
  };

  // Set the checked state for the sslUseTLS1 checkbox.
  AdvancedOptions.SetUseTLS1CheckboxState = function(checked, disabled) {
    $('sslUseTLS1').checked = checked;
    $('sslUseTLS1').disabled = disabled;
  };

  // Set the Cloud Print proxy UI to enabled, disabled, or processing.
  AdvancedOptions.SetupCloudPrintProxySection = function(disabled, label) {
    if (!cr.isChromeOS) {
      $('cloudPrintProxyLabel').textContent = label;
      if (disabled) {
        $('cloudPrintProxySetupButton').textContent =
          localStrings.getString('cloudPrintProxyDisabledButton');
        $('cloudPrintProxyManageButton').style.display = 'none';
      } else {
        $('cloudPrintProxySetupButton').textContent =
          localStrings.getString('cloudPrintProxyEnabledButton');
        $('cloudPrintProxyManageButton').style.display = 'inline';
      }
      $('cloudPrintProxySetupButton').disabled = false;
    }
  };

  AdvancedOptions.RemoveCloudPrintProxySection = function() {
    if (!cr.isChromeOS) {
      var proxySectionElm = $('cloud-print-proxy-section');
      proxySectionElm.parentNode.removeChild(proxySectionElm);
    }
  };

  AdvancedOptions.SetRemotingStatus = function(enabled, status) {
    if (enabled) {
      $('remotingSetupButton').style.display = 'none';
      $('remotingStopButton').style.display = 'inline';
    } else {
      $('remotingSetupButton').style.display = 'inline';
      $('remotingStopButton').style.display = 'none';
    }
    $('remotingStatus').textContent = status;
  };

  AdvancedOptions.RemoveRemotingSection = function() {
    var proxySectionElm = $('remoting-section');
    if (proxySectionElm)
      proxySectionElm.parentNode.removeChild(proxySectionElm);
  };

  // Export
  return {
    AdvancedOptions: AdvancedOptions
  };

});
<|endoftext|>


<commit_before>"use strict";
const puppeteer = require("puppeteer");
const express = require("express");
const proxy = require("express-http-proxy");
const { createReadStream } = require("fs");

const app = express();
app.get("/smoke", (_req, res) => {
  res.type("html");
  res.end('<!DOCTYPE html><script src="/smoke/web.js"></script>');
});
app.get("/smoke/web.js", (_req, res) => {
  res.type("js");
  createReadStream("build/web.js").pipe(res);
});
app.get("/smoke/web.js.map", (_req, res) => {
  res.type("js");
  createReadStream("build/web.js.map").pipe(res);
});
app.use("/", proxy("arangodb:8529"));

app.listen(8529, () => {
  (async () => {
    const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
    const page = await browser.newPage();
    await page.goto("http://localhost:8529/smoke", {
      waitUntil: "networkidle2",
    });
    const server = await page.evaluate(`async function () {
      var Database = arangojs.Database;
      var db = new Database();
      var el = document.getElementById("version");
      const info = await db.version();
      return info.server;
    }`);
    await browser.close();
    if (server !== "arango") {
      console.error("Unexpected version response:", server);
      process.exit(1);
    }
  })();
});
<commit_msg>Better error handling<commit_after>"use strict";
const puppeteer = require("puppeteer");
const express = require("express");
const proxy = require("express-http-proxy");
const { createReadStream } = require("fs");

const app = express();
app.get("/smoke", (_req, res) => {
  res.type("html");
  res.end('<!DOCTYPE html><script src="/smoke/web.js"></script>');
});
app.get("/smoke/web.js", (_req, res) => {
  res.type("js");
  createReadStream("build/web.js").pipe(res);
});
app.get("/smoke/web.js.map", (_req, res) => {
  res.type("js");
  createReadStream("build/web.js.map").pipe(res);
});
app.use("/", proxy("arangodb:8529"));

app.listen(8529, () => {
  (async () => {
    let server;
    try {
      const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
      const page = await browser.newPage();
      await page.goto("http://localhost:8529/smoke", {
        waitUntil: "networkidle2",
      });
      server = await page.evaluate(`async function () {
      var Database = arangojs.Database;
      var db = new Database();
      var el = document.getElementById("version");
      const info = await db.version();
      return info.server;
    }`);
      await browser.close();
    } catch (e) {
      console.error(e);
    }
    if (server !== "arango") {
      console.error("Unexpected version response:", server);
      process.exit(1);
    } else {
      process.exit(0);
    }
  })();
});
<|endoftext|>


<commit_before>module.exports = {
  title: 'Node-minify',
  description: 'Full documentation of node-minify',
  head: [
    ['link', { rel: 'manifest', href: '/manifest.json' }],
    ['meta', { name: 'theme-color', content: '#3eaf7c' }]
  ],
  serviceWorker: true,
  evergreen: true,
  ga: 'UA-65399-7',
  themeConfig: {
    serviceWorker: {
      updatePopup: true
    },
    nav: [
      {
        text: 'Releases',
        link: 'https://github.com/srod/node-minify/releases'
      },
      {
        text: 'GitHub',
        link: 'https://github.com/srod/node-minify'
      },
      {
        text: 'NPM',
        link: 'https://www.npmjs.com/package/node-minify'
      }
    ],
    sidebar: [
      {
        title: '',
        collapsable: false,
        children: [['', 'Introduction'], 'getting-started', 'options', 'cli']
      },
      {
        title: 'Compressors',
        collapsable: false,
        children: [
          'compressors/babel-minify',
          'compressors/clean-css',
          'compressors/crass',
          'compressors/cssnano',
          'compressors/csso',
          'compressors/gcc',
          'compressors/html-minifier',
          'compressors/jsonminify',
          'compressors/sqwish',
          'compressors/terser',
          'compressors/uglify-es',
          'compressors/uglify-js',
          'compressors/yui'
        ]
      }
    ]
  }
};
<commit_msg>docs(npm): update npm url<commit_after>module.exports = {
  title: 'Node-minify',
  description: 'Full documentation of node-minify',
  head: [
    ['link', { rel: 'manifest', href: '/manifest.json' }],
    ['meta', { name: 'theme-color', content: '#3eaf7c' }]
  ],
  serviceWorker: true,
  evergreen: true,
  ga: 'UA-65399-7',
  themeConfig: {
    serviceWorker: {
      updatePopup: true
    },
    nav: [
      {
        text: 'Releases',
        link: 'https://github.com/srod/node-minify/releases'
      },
      {
        text: 'GitHub',
        link: 'https://github.com/srod/node-minify'
      },
      {
        text: 'NPM',
        link: 'https://www.npmjs.com/package/@node-minify/core'
      }
    ],
    sidebar: [
      {
        title: '',
        collapsable: false,
        children: [['', 'Introduction'], 'getting-started', 'options', 'cli']
      },
      {
        title: 'Compressors',
        collapsable: false,
        children: [
          'compressors/babel-minify',
          'compressors/clean-css',
          'compressors/crass',
          'compressors/cssnano',
          'compressors/csso',
          'compressors/gcc',
          'compressors/html-minifier',
          'compressors/jsonminify',
          'compressors/sqwish',
          'compressors/terser',
          'compressors/uglify-es',
          'compressors/uglify-js',
          'compressors/yui'
        ]
      }
    ]
  }
};
<|endoftext|>


<commit_before>// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

const path = require('path');
const rulesDirPlugin = require('eslint-plugin-rulesdir');
rulesDirPlugin.RULES_DIR = path.join(__dirname, '..', 'scripts', 'eslint_rules', 'lib');

module.exports = {
  'overrides': [{
    'files': ['*.ts'],
    'rules': {
      '@typescript-eslint/explicit-function-return-type': 2,

      'rulesdir/kebab_case_events': 2,
      'rulesdir/set_data_type_reference': 2,
      'rulesdir/lit_html_data_as_type': 2,
      'rulesdir/lit_no_style_interpolation': 2,
    }
  }]
};
<commit_msg>Enforce camelCase for private and protected class members<commit_after>// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

const path = require('path');
const rulesDirPlugin = require('eslint-plugin-rulesdir');
rulesDirPlugin.RULES_DIR = path.join(__dirname, '..', 'scripts', 'eslint_rules', 'lib');

module.exports = {
  'overrides': [{
    'files': ['*.ts'],
    'rules': {
      '@typescript-eslint/explicit-function-return-type': 2,

      'rulesdir/kebab_case_events': 2,
      'rulesdir/set_data_type_reference': 2,
      'rulesdir/lit_html_data_as_type': 2,
      'rulesdir/lit_no_style_interpolation': 2,
      '@typescript-eslint/naming-convention': [
        'error', {
          'selector': 'property',
          'modifiers': ['private', 'protected'],
          'format': ['camelCase'],
        },
        {
          'selector': 'method',
          'modifiers': ['private', 'protected'],
          'format': ['camelCase'],
        }
      ]
    }
  }]
};
<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(){

var HTMLElementElement = function(inElement) {
  inElement.register = HTMLElementElement.prototype.register;
  parseElementElement(inElement);
  return inElement;
};

HTMLElementElement.prototype = {
  register: function(inMore) {
    if (inMore) {
      this.options.lifecycle = inMore.lifecycle;
      if (inMore.prototype) {
        mixin(this.options.prototype, inMore.prototype);
      }
    }
  }
};

function parseElementElement(inElement) {
  // options to glean from inElement attributes
  var options = {
    name: '',
    extends: null
  };
  // glean them
  takeAttributes(inElement, options);
  // default base
  var base = HTMLElement.prototype;
  // optional specified base
  if (options.extends) {
    // build an instance of options.extends
    var archetype = document.createElement(options.extends);
    // acquire the prototype
    // TODO(sjmiles): __proto__ may be hinted by the custom element
    // system on platforms that don't support native __proto__
    // on those platforms the API is mixed into archetype and the
    // effective base is not archetype's real prototype
    base = archetype.__proto__ || Object.getPrototypeOf(archetype);
  }
  // extend base
  options.prototype = Object.create(base);
  // install options
  inElement.options = options;
  // locate user script
  var script = inElement.querySelector('script,scripts');
  if (script) {
    // execute user script in 'inElement' context
    executeComponentScript(script.textContent, inElement, options.name);
  };
  // register our new element
  document.register(options.name, options);
}

// each property in inDictionary takes a value
// from the matching attribute in inElement, if any
function takeAttributes(inElement, inDictionary) {
  for (var n in inDictionary) {
    var a = inElement.attributes[n];
    if (a) {
      inDictionary[n] = a.value;
    }
  }
}

// invoke inScript in inContext scope
function executeComponentScript(inScript, inContext, inName) {
  // set (highlander) context
  context = inContext;
  // source location
  var owner = context.ownerDocument;
  // compose script
  var code = "__componentScript('"
    + inName
    + "', function(){"
    + inScript
    + "});"
    + "\n//@ sourceURL=" + (owner._URL || owner.URL) + "\n"
  ;
  // inject script
  eval(code);
}

var context;

// global necessary for script injection
window.__componentScript = function(inName, inFunc) {
  inFunc.call(context);
};

// utility

// copy all properties from inProps (et al) to inObj
function mixin(inObj/*, inProps, inMoreProps, ...*/) {
  var obj = inObj || {};
  for (var i = 1; i < arguments.length; i++) {
    var p = arguments[i];
    try {
      for (var n in p) {
        copyProperty(n, p, obj);
      }
    } catch(x) {
    }
  }
  return obj;
}

// copy property inName from inSource object to inTarget object
function copyProperty(inName, inSource, inTarget) {
  var pd = getPropertyDescriptor(inSource, inName);
  Object.defineProperty(inTarget, inName, pd);
}

// get property descriptor for inName on inObject, even if
// inName exists on some link in inObject's prototype chain
function getPropertyDescriptor(inObject, inName) {
  if (inObject) {
    var pd = Object.getOwnPropertyDescriptor(inObject, inName);
    return pd || getPropertyDescriptor(Object.getPrototypeOf(inObject), inName);
  }
}

// exports

window.HTMLElementElement = HTMLElementElement;
// TODO(sjmiles): completely ad-hoc, used by toolkit.register
window.mixin = mixin;

})();<commit_msg>Correct source map used to run custom element scripts to work properly when more than one element is defined in a document.<commit_after>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(){

var HTMLElementElement = function(inElement) {
  inElement.register = HTMLElementElement.prototype.register;
  parseElementElement(inElement);
  return inElement;
};

HTMLElementElement.prototype = {
  register: function(inMore) {
    if (inMore) {
      this.options.lifecycle = inMore.lifecycle;
      if (inMore.prototype) {
        mixin(this.options.prototype, inMore.prototype);
      }
    }
  }
};

function parseElementElement(inElement) {
  // options to glean from inElement attributes
  var options = {
    name: '',
    extends: null
  };
  // glean them
  takeAttributes(inElement, options);
  // default base
  var base = HTMLElement.prototype;
  // optional specified base
  if (options.extends) {
    // build an instance of options.extends
    var archetype = document.createElement(options.extends);
    // acquire the prototype
    // TODO(sjmiles): __proto__ may be hinted by the custom element
    // system on platforms that don't support native __proto__
    // on those platforms the API is mixed into archetype and the
    // effective base is not archetype's real prototype
    base = archetype.__proto__ || Object.getPrototypeOf(archetype);
  }
  // extend base
  options.prototype = Object.create(base);
  // install options
  inElement.options = options;
  // locate user script
  var script = inElement.querySelector('script,scripts');
  if (script) {
    // execute user script in 'inElement' context
    executeComponentScript(script.textContent, inElement, options.name);
  };
  // register our new element
  document.register(options.name, options);
}

// each property in inDictionary takes a value
// from the matching attribute in inElement, if any
function takeAttributes(inElement, inDictionary) {
  for (var n in inDictionary) {
    var a = inElement.attributes[n];
    if (a) {
      inDictionary[n] = a.value;
    }
  }
}

// invoke inScript in inContext scope
function executeComponentScript(inScript, inContext, inName) {
  // set (highlander) context
  context = inContext;
  // source location
  var owner = context.ownerDocument;
  var url = (owner._URL || owner.URL);
  var match = url.match(/.*\/([^.]*)[.]?.*$/);
  if (match) {
    var name = match[1];
    url += name != inName ? ':' + inName : '';
  }
  // compose script
  var code = "__componentScript('"
    + inName
    + "', function(){"
    + inScript
    + "});"
    + "\n//@ sourceURL=" + url + "\n"
  ;
  // inject script
  eval(code);
}

var context;

// global necessary for script injection
window.__componentScript = function(inName, inFunc) {
  inFunc.call(context);
};

// utility

// copy all properties from inProps (et al) to inObj
function mixin(inObj/*, inProps, inMoreProps, ...*/) {
  var obj = inObj || {};
  for (var i = 1; i < arguments.length; i++) {
    var p = arguments[i];
    try {
      for (var n in p) {
        copyProperty(n, p, obj);
      }
    } catch(x) {
    }
  }
  return obj;
}

// copy property inName from inSource object to inTarget object
function copyProperty(inName, inSource, inTarget) {
  var pd = getPropertyDescriptor(inSource, inName);
  Object.defineProperty(inTarget, inName, pd);
}

// get property descriptor for inName on inObject, even if
// inName exists on some link in inObject's prototype chain
function getPropertyDescriptor(inObject, inName) {
  if (inObject) {
    var pd = Object.getOwnPropertyDescriptor(inObject, inName);
    return pd || getPropertyDescriptor(Object.getPrototypeOf(inObject), inName);
  }
}

// exports

window.HTMLElementElement = HTMLElementElement;
// TODO(sjmiles): completely ad-hoc, used by toolkit.register
window.mixin = mixin;

})();<|endoftext|>


<commit_before>//= require jquery.treetable
//= require browse_everything/behavior

// Show the files in the queue
Blacklight.onLoad( function() {
  // We need to check this because https://github.com/samvera/browse-everything/issues/169
  if ($('#browse-btn').length > 0) {
    $('#browse-btn').browseEverything()
    .done(function(data) {
      var evt = { isDefaultPrevented: function() { return false; } };
      var files = $.map(data, function(d) { return { name: d.file_name, size: d.file_size, id: d.url } });
      $.blueimp.fileupload.prototype.options.done.call($('#fileupload').fileupload(), evt, { result: { files: files }});
    })
  }
});
<commit_msg>Fix loading of browse-everything done event<commit_after>//= require jquery.treetable
//= require browse_everything/behavior

// Show the files in the queue
function showBrowseEverythingFiles() {
  // We need to check this because https://github.com/samvera/browse-everything/issues/169
  if ($('#browse-btn').length > 0) {
    $('#browse-btn').browseEverything()
    .done(function(data) {
      var evt = { isDefaultPrevented: function() { return false; } };
      var files = $.map(data, function(d) { return { name: d.file_name, size: d.file_size, id: d.url } });
      $.blueimp.fileupload.prototype.options.done.call($('#fileupload').fileupload(), evt, { result: { files: files }});
    })
  }
}
$(document).on('click', '#browse-btn', showBrowseEverythingFiles);

<|endoftext|>


<commit_before>/*global describe: false,
         beforeEach: false,
         it: false */
/*jshint node: true */
"use strict";

var BPMux = require('..').BPMux,
    chai = require('chai'),
    expect = chai.expect,
    stream = require('stream'),
    util = require('util'),
    Duplex = stream.Duplex,
    PassThrough = stream.PassThrough;

function RightDuplex(left)
{
    Duplex.call(this);
    this.left = left;
    this.on('finish', function ()
    {
        left.push(null);
    });
}

util.inherits(RightDuplex, Duplex);

RightDuplex.prototype._read = function ()
{
    if (this._cb)
    {
        var cb = this._cb;
        this._cb = null;
        cb();
    }
};

RightDuplex.prototype._write = function (chunk, encoding, cb)
{
    if (this.left.push(chunk, encoding))
    {
        cb();
    }
    else
    {
        this.left._cb = cb;
    }
};

function LeftDuplex()
{
    Duplex.call(this);
    this.right = new RightDuplex(this);
    this.on('finish', function ()
    {
        this.right.push(null);
    }.bind(this));
}

util.inherits(LeftDuplex, Duplex);

LeftDuplex.prototype._read = function ()
{
    if (this._cb)
    {
        var cb = this._cb;
        this._cb = null;
        cb();
    }
};

LeftDuplex.prototype._write = function (chunk, encoding, cb)
{
    if (this.right.push(chunk, encoding))
    {
        cb();
    }
    else
    {
        this.right._cb = cb;
    }
};

describe('inline stream', function ()
{
    var left, right, lmux, rmux;

    beforeEach(function ()
    {
        left = new LeftDuplex();
        right = left.right;
        lmux = new BPMux(left);
        rmux = new BPMux(right);
    });

    it('should multiplex over inline stream', function (cb)
    {
        rmux.once('handshake', function (duplex, hsdata)
        {
            expect(hsdata.toString()).to.equal('left hs');

            var bufs = [];

            duplex.on('end', function ()
            {
                var buf = Buffer.concat(bufs);
                expect(buf.toString()).to.equal('left data');

                rmux.multiplex(
                {
                    handshake_data: new Buffer('right hs')
                }).end('right data');
            });

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null)
                    {
                        break;
                    }
                    bufs.push(data);
                }
            });
        });

        lmux.multiplex(
        {
            handshake_data: new Buffer('left hs')
        }).end('left data');

        lmux.on('handshake', function (duplex, hsdata, delay)
        {
            if (!delay)
            {
                return expect(hsdata.length).to.equal(0);
            }

            expect(hsdata.toString()).to.equal('right hs');

            var bufs = [];

            duplex.on('end', function ()
            {
                var buf = Buffer.concat(bufs);
                expect(buf.toString()).to.equal('right data');
                cb();
            });

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null)
                    {
                        break;
                    }
                    bufs.push(data);
                }
            });
        });
    });

    it('should ping-pong', function (cb)
    {
        var duplex = rmux.multiplex();

        duplex.once('readable', function ()
        {
            expect(this.read()[0]).to.equal(1);

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null) { break; }
                    expect(data[0]).to.equal(3);
                }
            });

            this.end(new Buffer([2]));
        });

        duplex.on('end', cb);

        lmux.on('handshake', function (duplex)
        {
            duplex.write(new Buffer([1]));

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null) { break; }
                    expect(data[0]).to.equal(2);
                    this.end(new Buffer([3]));
                }
            });
        });
    });

    it('should emit handshake on multiplexed duplex', function (cb)
    {
        // right mux is intially in sync mode so need to send some data
        var control = lmux.multiplex();

        lmux.on('handshake', function (duplex, hdata, delay)
        {
            if (duplex !== control)
            {
                return;
            }

            // give right mux chance to exit sync mode so it will
            // emit readable and send handshake straight away
            process.nextTick(function ()
            {
                lmux.multiplex().on('handshake', function ()
                {
                    cb();
                });
            });
        });
    });

    it('should pass delay to one side when both sides multiplex a duplex with the same channel number', function (cb)
    {
        var rdelay = null, lduplex, rduplex;

        lduplex = lmux.multiplex();
        expect(lduplex.get_channel()).to.equal(0);
        lduplex.on('handshake', function (hdata, delay)
        {
            // handshake sent so delay will be null
            expect(delay).to.equal(null);
            expect(rdelay).not.to.equal(null); // see below
            cb();
        });

        rduplex = rmux.multiplex();
        expect(rduplex.get_channel()).to.equal(0);
        rduplex.on('handshake', function (hdata, delay)
        {
            // handshake not sent yet so delay won't be null
            rdelay = delay;
        });

        // when rmux comes to send its original handshake (from the
        // multiplex call), it won't be sent because we already sent
        // one in response to the one from lmux (we didn't delay it)
    });

    it('should support giving a different channel range to each side', function (cb)
    {
        left = new LeftDuplex();
        right = left.right;
        lmux = new BPMux(left);
        rmux = new BPMux(right, { high_channels: true });

        var ldelay, lduplex, rduplex;

        lduplex = lmux.multiplex();
        expect(lduplex.get_channel()).to.equal(0);
        lduplex.on('handshake', function (hdata, delay)
        {
            ldelay = delay;
            // right handshake won't be received yet as different channel
        });

        rduplex = rmux.multiplex();
        expect(rduplex.get_channel()).to.equal(Math.pow(2, 31));
        rduplex.on('handshake', function (hdata, delay)
        {
            expect(delay).to.equal(null);
            expect(ldelay).to.equal(null);
            cb();
        });
    });

    it('should support ending stream before sending delayed handshake',
    function (cb)
    {
        rmux.on('handshake', function (duplex, hsdata, delay)
        {
            expect(hsdata.length).to.equal(0);

            duplex.end();

            var handshake = delay(),
                bufs = [];

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (!data) { return; }
                    bufs.push(data);
                }
            });

            duplex.on('end', function ()
            {
                expect(bufs.length).to.equal(0);
                handshake();
            });
        });

        lmux.on('handshake', function (duplex, hsdata, delay)
        {
            expect(delay).to.equal(null);
            cb();
        });

        lmux.multiplex().end();
    });

    it('should support ending stream (with data) before sending delayed handshake',
    function (cb)
    {
        rmux.on('handshake', function (duplex, hsdata, delay)
        {
            expect(hsdata.length).to.equal(0);

            duplex.end();

            var handshake = delay(),
                bufs = [];

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (!data) { return; }
                    bufs.push(data);
                }
            });

            duplex.on('end', function ()
            {
                expect(Buffer.concat(bufs).toString()).to.equal('foo');
                handshake();
            });
        });

        lmux.on('handshake', function (duplex, hsdata, delay)
        {
            expect(delay).to.equal(null);
            cb();
        });

        lmux.multiplex().end('foo');
    });

    it('should emit handshake_sent event', function (cb)
    {
        var lcomplete, lcomplete2, rcomplete, rcomplete2;

        function check()
        {
            if (lcomplete && lcomplete2 && rcomplete && rcomplete2)
            {
                cb();
            }
        }

        rmux.on('handshake', function (duplex)
        {
            duplex.on('handshake_sent', function (complete)
            {
                rcomplete = complete;
                check();
            });
        });

        rmux.on('handshake_sent', function (duplex, complete)
        {
            rcomplete2 = complete;
            check();
        });

        lmux.on('handshake_sent', function (duplex, complete)
        {
            lcomplete2 = complete;
            check();
        });

        lmux.multiplex().on('handshake_sent', function (complete)
        {
            lcomplete = complete;
            check();
        });
    });

    it('should support backpressure on handshakes', function (cb)
    {
        this.timeout(2 * 60 * 1000);

        left._write = function ()
        {
        };

        var count_complete = 0,
            count_incomplete = 0;

        function sent(complete)
        {
            if (complete)
            {
                count_complete += 1;
            }
            else
            {
                count_incomplete += 1;
            }
            if ((count_complete + count_incomplete) === 4343)
            {
                expect(count_complete).to.equal(4342);
                expect(count_incomplete).to.equal(1);
                cb();
            }
        }

        // number will change if change handshake buffer size
        for (var i = 0; i < 4343; i += 1)
        {
            lmux.multiplex().on('handshake_sent', sent);
        }
    });

    it('should support sending large buffers', function (cb)
    {
        var buf = new Buffer(32 * 1024);
        buf.fill('a');

        rmux.once('handshake', function (duplex)
        {
            var bufs = [];

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null)
                    {
                        break;
                    }
                    bufs.push(data);
                }
            });

            duplex.on('end', function ()
            {
                expect(Buffer.concat(bufs).toString()).to.equal(buf.toString());
                cb();
            });
        });

        lmux.multiplex().end(buf);
    });

    it('should support sending large buffers with delayed handshake',
    function (cb)
    {
        var buf = new Buffer(100 * 1024);
        buf.fill('a');

        rmux.on('handshake', function (duplex, hsdata, delay)
        {
            delay();

            var bufs = [];

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null)
                    {
                        break;
                    }
                    bufs.push(data);
                }
            });

            duplex.on('end', function ()
            {
                expect(Buffer.concat(bufs).toString()).to.equal(buf.toString());                cb();
            });
        });

        lmux.multiplex().end(buf);
    });
});

<commit_msg>Don't do large buffer + delayed hs test on 0.12<commit_after>/*global describe: false,
         beforeEach: false,
         it: false */
/*jshint node: true */
"use strict";

var BPMux = require('..').BPMux,
    chai = require('chai'),
    expect = chai.expect,
    stream = require('stream'),
    util = require('util'),
    Duplex = stream.Duplex,
    PassThrough = stream.PassThrough;

function RightDuplex(left)
{
    Duplex.call(this);
    this.left = left;
    this.on('finish', function ()
    {
        left.push(null);
    });
}

util.inherits(RightDuplex, Duplex);

RightDuplex.prototype._read = function ()
{
    if (this._cb)
    {
        var cb = this._cb;
        this._cb = null;
        cb();
    }
};

RightDuplex.prototype._write = function (chunk, encoding, cb)
{
    if (this.left.push(chunk, encoding))
    {
        cb();
    }
    else
    {
        this.left._cb = cb;
    }
};

function LeftDuplex()
{
    Duplex.call(this);
    this.right = new RightDuplex(this);
    this.on('finish', function ()
    {
        this.right.push(null);
    }.bind(this));
}

util.inherits(LeftDuplex, Duplex);

LeftDuplex.prototype._read = function ()
{
    if (this._cb)
    {
        var cb = this._cb;
        this._cb = null;
        cb();
    }
};

LeftDuplex.prototype._write = function (chunk, encoding, cb)
{
    if (this.right.push(chunk, encoding))
    {
        cb();
    }
    else
    {
        this.right._cb = cb;
    }
};

describe('inline stream', function ()
{
    var left, right, lmux, rmux;

    beforeEach(function ()
    {
        left = new LeftDuplex();
        right = left.right;
        lmux = new BPMux(left);
        rmux = new BPMux(right);
    });

    it('should multiplex over inline stream', function (cb)
    {
        rmux.once('handshake', function (duplex, hsdata)
        {
            expect(hsdata.toString()).to.equal('left hs');

            var bufs = [];

            duplex.on('end', function ()
            {
                var buf = Buffer.concat(bufs);
                expect(buf.toString()).to.equal('left data');

                rmux.multiplex(
                {
                    handshake_data: new Buffer('right hs')
                }).end('right data');
            });

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null)
                    {
                        break;
                    }
                    bufs.push(data);
                }
            });
        });

        lmux.multiplex(
        {
            handshake_data: new Buffer('left hs')
        }).end('left data');

        lmux.on('handshake', function (duplex, hsdata, delay)
        {
            if (!delay)
            {
                return expect(hsdata.length).to.equal(0);
            }

            expect(hsdata.toString()).to.equal('right hs');

            var bufs = [];

            duplex.on('end', function ()
            {
                var buf = Buffer.concat(bufs);
                expect(buf.toString()).to.equal('right data');
                cb();
            });

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null)
                    {
                        break;
                    }
                    bufs.push(data);
                }
            });
        });
    });

    it('should ping-pong', function (cb)
    {
        var duplex = rmux.multiplex();

        duplex.once('readable', function ()
        {
            expect(this.read()[0]).to.equal(1);

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null) { break; }
                    expect(data[0]).to.equal(3);
                }
            });

            this.end(new Buffer([2]));
        });

        duplex.on('end', cb);

        lmux.on('handshake', function (duplex)
        {
            duplex.write(new Buffer([1]));

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null) { break; }
                    expect(data[0]).to.equal(2);
                    this.end(new Buffer([3]));
                }
            });
        });
    });

    it('should emit handshake on multiplexed duplex', function (cb)
    {
        // right mux is intially in sync mode so need to send some data
        var control = lmux.multiplex();

        lmux.on('handshake', function (duplex, hdata, delay)
        {
            if (duplex !== control)
            {
                return;
            }

            // give right mux chance to exit sync mode so it will
            // emit readable and send handshake straight away
            process.nextTick(function ()
            {
                lmux.multiplex().on('handshake', function ()
                {
                    cb();
                });
            });
        });
    });

    it('should pass delay to one side when both sides multiplex a duplex with the same channel number', function (cb)
    {
        var rdelay = null, lduplex, rduplex;

        lduplex = lmux.multiplex();
        expect(lduplex.get_channel()).to.equal(0);
        lduplex.on('handshake', function (hdata, delay)
        {
            // handshake sent so delay will be null
            expect(delay).to.equal(null);
            expect(rdelay).not.to.equal(null); // see below
            cb();
        });

        rduplex = rmux.multiplex();
        expect(rduplex.get_channel()).to.equal(0);
        rduplex.on('handshake', function (hdata, delay)
        {
            // handshake not sent yet so delay won't be null
            rdelay = delay;
        });

        // when rmux comes to send its original handshake (from the
        // multiplex call), it won't be sent because we already sent
        // one in response to the one from lmux (we didn't delay it)
    });

    it('should support giving a different channel range to each side', function (cb)
    {
        left = new LeftDuplex();
        right = left.right;
        lmux = new BPMux(left);
        rmux = new BPMux(right, { high_channels: true });

        var ldelay, lduplex, rduplex;

        lduplex = lmux.multiplex();
        expect(lduplex.get_channel()).to.equal(0);
        lduplex.on('handshake', function (hdata, delay)
        {
            ldelay = delay;
            // right handshake won't be received yet as different channel
        });

        rduplex = rmux.multiplex();
        expect(rduplex.get_channel()).to.equal(Math.pow(2, 31));
        rduplex.on('handshake', function (hdata, delay)
        {
            expect(delay).to.equal(null);
            expect(ldelay).to.equal(null);
            cb();
        });
    });

    it('should support ending stream before sending delayed handshake',
    function (cb)
    {
        rmux.on('handshake', function (duplex, hsdata, delay)
        {
            expect(hsdata.length).to.equal(0);

            duplex.end();

            var handshake = delay(),
                bufs = [];

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (!data) { return; }
                    bufs.push(data);
                }
            });

            duplex.on('end', function ()
            {
                expect(bufs.length).to.equal(0);
                handshake();
            });
        });

        lmux.on('handshake', function (duplex, hsdata, delay)
        {
            expect(delay).to.equal(null);
            cb();
        });

        lmux.multiplex().end();
    });

    it('should support ending stream (with data) before sending delayed handshake',
    function (cb)
    {
        rmux.on('handshake', function (duplex, hsdata, delay)
        {
            expect(hsdata.length).to.equal(0);

            duplex.end();

            var handshake = delay(),
                bufs = [];

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (!data) { return; }
                    bufs.push(data);
                }
            });

            duplex.on('end', function ()
            {
                expect(Buffer.concat(bufs).toString()).to.equal('foo');
                handshake();
            });
        });

        lmux.on('handshake', function (duplex, hsdata, delay)
        {
            expect(delay).to.equal(null);
            cb();
        });

        lmux.multiplex().end('foo');
    });

    it('should emit handshake_sent event', function (cb)
    {
        var lcomplete, lcomplete2, rcomplete, rcomplete2;

        function check()
        {
            if (lcomplete && lcomplete2 && rcomplete && rcomplete2)
            {
                cb();
            }
        }

        rmux.on('handshake', function (duplex)
        {
            duplex.on('handshake_sent', function (complete)
            {
                rcomplete = complete;
                check();
            });
        });

        rmux.on('handshake_sent', function (duplex, complete)
        {
            rcomplete2 = complete;
            check();
        });

        lmux.on('handshake_sent', function (duplex, complete)
        {
            lcomplete2 = complete;
            check();
        });

        lmux.multiplex().on('handshake_sent', function (complete)
        {
            lcomplete = complete;
            check();
        });
    });

    it('should support backpressure on handshakes', function (cb)
    {
        this.timeout(2 * 60 * 1000);

        left._write = function ()
        {
        };

        var count_complete = 0,
            count_incomplete = 0;

        function sent(complete)
        {
            if (complete)
            {
                count_complete += 1;
            }
            else
            {
                count_incomplete += 1;
            }
            if ((count_complete + count_incomplete) === 4343)
            {
                expect(count_complete).to.equal(4342);
                expect(count_incomplete).to.equal(1);
                cb();
            }
        }

        // number will change if change handshake buffer size
        for (var i = 0; i < 4343; i += 1)
        {
            lmux.multiplex().on('handshake_sent', sent);
        }
    });

    it('should support sending large buffers', function (cb)
    {
        var buf = new Buffer(32 * 1024);
        buf.fill('a');

        rmux.once('handshake', function (duplex)
        {
            var bufs = [];

            duplex.on('readable', function ()
            {
                while (true)
                {
                    var data = this.read();
                    if (data === null)
                    {
                        break;
                    }
                    bufs.push(data);
                }
            });

            duplex.on('end', function ()
            {
                expect(Buffer.concat(bufs).toString()).to.equal(buf.toString());
                cb();
            });
        });

        lmux.multiplex().end(buf);
    });

    // https://github.com/nodejs/node/pull/7292 isn't on 0.12
    if (parseFloat(process.versions.node) > 0.12)
    {
        it('should support sending large buffers with delayed handshake',
        function (cb)
        {
            var buf = new Buffer(100 * 1024);
            buf.fill('a');

            rmux.on('handshake', function (duplex, hsdata, delay)
            {
                delay();

                var bufs = [];

                duplex.on('readable', function ()
                {
                    while (true)
                    {
                        var data = this.read();
                        if (data === null)
                        {
                            break;
                        }
                        bufs.push(data);
                    }
                });

                duplex.on('end', function ()
                {
                    expect(Buffer.concat(bufs).toString()).to.equal(buf.toString());                cb();
                });
            });

            lmux.multiplex().end(buf);
        });
    }
});

<|endoftext|>


<commit_before>import React from "react";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { Panel } from "react-bootstrap";

import { getSoftwareUpdates } from "../../updates/actions";
import { Icon } from "../../base";

class Welcome extends React.Component {

    componentDidMount () {
        this.props.onGet();
    }

    render () {
        let version;

        if (this.props.version) {
            version = (

                    {this.props.version}

            );
        }
        return (

                <Panel>
                    <Panel.Body>

Virtool {version}

Viral infection diagnostics using next-generation sequencing

                            <Icon name="globe" /> Website

                    </Panel.Body>
                </Panel>

        );
    }
}

const mapStateToProps = (state) => ({
    version: get(state.updates.software, "version")
});

const mapDispatchToProps = (dispatch) => ({

    onGet: () => {
        dispatch(getSoftwareUpdates());
    }

});

export default connect(mapStateToProps, mapDispatchToProps)(Welcome);
<commit_msg>Fix home virtool version display<commit_after>import React from "react";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { Panel } from "react-bootstrap";

import { getSoftwareUpdates } from "../../updates/actions";
import { Icon } from "../../base";

class Welcome extends React.Component {

    componentDidMount () {
        this.props.onGet();
    }

    render () {
        let version;

        if (this.props.version) {
            version = (

                    {this.props.version}

            );
        }
        return (

                <Panel>
                    <Panel.Body>

Virtool {version}

Viral infection diagnostics using next-generation sequencing

                            <Icon name="globe" /> Website

                    </Panel.Body>
                </Panel>

        );
    }
}

const mapStateToProps = (state) => ({
    version: get(state.updates, "version")
});

const mapDispatchToProps = (dispatch) => ({

    onGet: () => {
        dispatch(getSoftwareUpdates());
    }

});

export default connect(mapStateToProps, mapDispatchToProps)(Welcome);
<|endoftext|>


<commit_before>export { ConstantWhenPassThrough };

import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import { Base } from "./Depthwise_Base.js";

/**
 * Depthwise convolution whose output will be constant value (no matter what input) when pass-through.
 *
 * It has the following properties:
 *   - ( nPassThroughStyleId == ValueDesc.PassThroughStyle.Singleton.Ids.PASS_THROUGH_STYLE_FILTER_0_BIAS_1 ) (1).
 *
 * Usually, this is used for squeeze-and-excitaion depthwise.
 *
 */
class ConstantWhenPassThrough extends Base {

  /**
   */
  constructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, nActivationId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf ) {

    super(
      inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, nActivationId,
      ValueDesc.PassThroughStyle.Singleton.Ids.PASS_THROUGH_STYLE_FILTER_0_BIAS_1,
      nHigherHalfDifferent, inputChannelCount_lowerHalf );

  }

}
<commit_msg>Update Depthwise_ConstantWhenPassThrough.js<commit_after>export { ConstantWhenPassThrough };

import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import { Base } from "./Depthwise_Base.js";

/**
 * Depthwise convolution whose output will be constant value (no matter what input) when pass-through.
 *
 * It has the following properties:
 *   - ( nPassThroughStyleId == ValueDesc.PassThroughStyle.Singleton.Ids.PASS_THROUGH_STYLE_FILTER_0_BIAS_1 ) (1).
 *
 * Usually, this is used for squeeze-and-excitaion depthwise.
 *
 */
class ConstantWhenPassThrough extends Base {

  /**
   */
  constructor(
    inputTensorPlaceholder0,
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, nActivationId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf ) {

    super(
      inputTensorPlaceholder0,
      inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, nActivationId,
      ValueDesc.PassThroughStyle.Singleton.Ids.PASS_THROUGH_STYLE_FILTER_0_BIAS_1,
      nHigherHalfDifferent, inputChannelCount_lowerHalf );

  }

}
<|endoftext|>


<commit_before>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var ground = require('./ground');
var xhr = require('./xhr');
var invertKey = chessground.util.invertKey;
var key2pos = chessground.util.key2pos;

var promoting = null;
var prePromotionRole = null;

function start(ctrl, orig, dest, isPremove) {
  var d = ctrl.data, cg = ctrl.chessground;
  var piece = cg.data.pieces[dest];
  var premovePiece = cg.data.pieces[orig];
  if (((piece && piece.role === 'pawn') || (premovePiece && premovePiece.role === 'pawn')) && (
    (dest[1] == 8 && d.player.color === 'white') ||
    (dest[1] == 1 && d.player.color === 'black'))) {
    if (prePromotionRole && isPremove) {
      ground.promote(cg, dest, prePromotionRole);
      ctrl.sendMove(orig, dest, prePromotionRole);
      cancelPrePromotion(ctrl);
      return true;
    }
    if (d.pref.autoQueen === 3 || d.pref.autoQueen === 2) {
      if (premovePiece) setPrePromotion(ctrl, dest, 'queen');
      else {
        ground.promote(cg, dest, 'queen');
        ctrl.sendMove(orig, dest, 'queen');
        cancelPrePromotion(ctrl);
      }
      return true;
    }
    m.startComputation();
    cancelPrePromotion(ctrl);
    promoting = {
      move: [orig, dest],
      pre: !!premovePiece
    };
    m.endComputation();
    return true;
  }
  return false;
}

function setPrePromotion(ctrl, dest, role) {
  prePromotionRole = role;
  ctrl.chessground.setAutoShapes([{
    orig: dest,
    piece: {
      color: ctrl.data.player.color,
      role: role,
      opacity: 0.8
    }
  }]);
}

function cancelPrePromotion(ctrl) {
  if (prePromotionRole) ctrl.chessground.setAutoShapes([]);
  prePromotionRole = null;
}

function finish(ctrl, role) {
  if (promoting) {
    if (promoting.pre) setPrePromotion(ctrl, promoting.move[1], role);
    else {
      ground.promote(ctrl.chessground, promoting.move[1], role);
      ctrl.sendMove(promoting.move[0], promoting.move[1], role);
    }
  }
  promoting = null;
}

function cancel(ctrl) {
  cancelPrePromotion(ctrl);
  if (promoting) xhr.reload(ctrl).then(ctrl.reload);
  promoting = null;
}

function renderPromotion(ctrl, dest, pieces, color, orientation) {
  var left =  (key2pos(orientation === 'white' ? dest : invertKey(dest))[0] -1) * 12.5;
  var vertical = color === orientation ? 'top' : 'bottom';

  return m('div#promotion_choice.' + vertical, {
    onclick: partial(cancel, ctrl)
  }, pieces.map(function(serverRole, i) {
    var top = (color === orientation ? i : 7 - i) * 12.5;
    return m('square', {
      style: 'top: ' + top + '%;left: ' + left + '%',
      onclick: function(e) {
        e.stopPropagation();
        finish(ctrl, serverRole);
      }
    }, m('piece.' + serverRole + '.' + color));
  }));
}

module.exports = {

  start: start,
  cancel: cancel,

  view: function(ctrl) {
    if (!promoting) return;
    var pieces = ['queen', 'knight', 'rook', 'bishop'];
    if (ctrl.data.game.variant.key === "antichess") pieces.push('king');

    return renderPromotion(ctrl, promoting.move[1], pieces,
        ctrl.data.player.color,
        ctrl.chessground.data.orientation);
  }
};
<commit_msg>pref.premove = 2, don't autopromote without a premove<commit_after>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var ground = require('./ground');
var xhr = require('./xhr');
var invertKey = chessground.util.invertKey;
var key2pos = chessground.util.key2pos;

var promoting = null;
var prePromotionRole = null;

function start(ctrl, orig, dest, isPremove) {
  var d = ctrl.data, cg = ctrl.chessground;
  var piece = cg.data.pieces[dest];
  var premovePiece = cg.data.pieces[orig];
  if (((piece && piece.role === 'pawn') || (premovePiece && premovePiece.role === 'pawn')) && (
    (dest[1] == 8 && d.player.color === 'white') ||
    (dest[1] == 1 && d.player.color === 'black'))) {
    if (prePromotionRole && isPremove) {
      ground.promote(cg, dest, prePromotionRole);
      ctrl.sendMove(orig, dest, prePromotionRole);
      cancelPrePromotion(ctrl);
      return true;
    }
    if (d.pref.autoQueen === 3 || (d.pref.autoQueen === 2 && premovePiece)) {
      if (premovePiece) setPrePromotion(ctrl, dest, 'queen');
      else {
        ground.promote(cg, dest, 'queen');
        ctrl.sendMove(orig, dest, 'queen');
        cancelPrePromotion(ctrl);
      }
      return true;
    }
    m.startComputation();
    cancelPrePromotion(ctrl);
    promoting = {
      move: [orig, dest],
      pre: !!premovePiece
    };
    m.endComputation();
    return true;
  }
  return false;
}

function setPrePromotion(ctrl, dest, role) {
  prePromotionRole = role;
  ctrl.chessground.setAutoShapes([{
    orig: dest,
    piece: {
      color: ctrl.data.player.color,
      role: role,
      opacity: 0.8
    }
  }]);
}

function cancelPrePromotion(ctrl) {
  if (prePromotionRole) ctrl.chessground.setAutoShapes([]);
  prePromotionRole = null;
}

function finish(ctrl, role) {
  if (promoting) {
    if (promoting.pre) setPrePromotion(ctrl, promoting.move[1], role);
    else {
      ground.promote(ctrl.chessground, promoting.move[1], role);
      ctrl.sendMove(promoting.move[0], promoting.move[1], role);
    }
  }
  promoting = null;
}

function cancel(ctrl) {
  cancelPrePromotion(ctrl);
  if (promoting) xhr.reload(ctrl).then(ctrl.reload);
  promoting = null;
}

function renderPromotion(ctrl, dest, pieces, color, orientation) {
  var left =  (key2pos(orientation === 'white' ? dest : invertKey(dest))[0] -1) * 12.5;
  var vertical = color === orientation ? 'top' : 'bottom';

  return m('div#promotion_choice.' + vertical, {
    onclick: partial(cancel, ctrl)
  }, pieces.map(function(serverRole, i) {
    var top = (color === orientation ? i : 7 - i) * 12.5;
    return m('square', {
      style: 'top: ' + top + '%;left: ' + left + '%',
      onclick: function(e) {
        e.stopPropagation();
        finish(ctrl, serverRole);
      }
    }, m('piece.' + serverRole + '.' + color));
  }));
}

module.exports = {

  start: start,
  cancel: cancel,

  view: function(ctrl) {
    if (!promoting) return;
    var pieces = ['queen', 'knight', 'rook', 'bishop'];
    if (ctrl.data.game.variant.key === "antichess") pieces.push('king');

    return renderPromotion(ctrl, promoting.move[1], pieces,
        ctrl.data.player.color,
        ctrl.chessground.data.orientation);
  }
};
<|endoftext|>