code
stringlengths 1
2.08M
| language
stringclasses 1
value |
|---|---|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Moog-like low pass audio filter.
*/
goog.provide('doodle.moog.LowPassFilter');
goog.require('doodle.moog.CompoundAudioNode');
/**
* A dynamic low pass filter emulator.
* @param {!AudioContext} audioContext Audio context to which this oscillator
* will be bound.
* @param {number} cutoffFrequency The cutoff frequency above which the
* frequencies are attenuated.
* @param {number} contour Amount of contour to apply to the filter envelope.
* @param {number} attackTime Initial attack time in seconds.
* @param {number} decayTime Initial decay time in seconds.
* @param {number} sustainLevel Initial sustain level [0..1].
* @constructor
* @implements {doodle.moog.CompoundAudioNode}
*/
doodle.moog.LowPassFilter = function(
audioContext, cutoffFrequency, contour, attackTime, decayTime,
sustainLevel) {
/**
* Audio context in which this filter operates.
* @type {!AudioContext}
* @private
*/
this.audioContext_ = audioContext;
/**
* The low pass filter Web Audio node.
* @type {!BiquadFilterNode}
* @private
*/
this.lowPassFilterNode_ = audioContext.createBiquadFilter();
this.lowPassFilterNode_.type =
doodle.moog.LowPassFilter.LOW_PASS_FILTER_TYPE_ID_;
/**
* Frequency above which sound should be progressively attenuated.
* @type {number}
* @private
*/
this.cutoffFrequency_ = cutoffFrequency;
/**
* The amount of 'contour' to add to the low pass filter ADS (attack, decay,
* sustain) envelope. Contour is essentially a variable cutoff frequency
* coefficient. See doodle.moog.EnvelopeGenerator for an explanation of how
* ADS envelopes work.
* @type {number}
* @private
*/
this.contour_ = contour;
/**
* The duration of the attack phase in seconds.
* @type {number}
* @private
*/
this.attackTime_ = attackTime;
/**
* The duration of the decay phase in seconds.
* @type {number}
* @private
*/
this.decayTime_ = decayTime;
/**
* The sustain frequency coefficient.
* @type {number}
* @private
*/
this.sustainLevel_ = sustainLevel;
this.resetContourEnvelope_();
};
/**
* Biquad Filter type ID for a low pass filter (from the Web Audio spec).
* @type {number}
* @const
* @private
*/
doodle.moog.LowPassFilter.LOW_PASS_FILTER_TYPE_ID_ = 0;
/**
* Initiates the attack phase of the contour envelope (e.g., when a key is
* pressed).
*/
doodle.moog.LowPassFilter.prototype.startAttack = function() {
var now = this.audioContext_.currentTime;
this.lowPassFilterNode_.frequency.cancelScheduledValues(now);
this.lowPassFilterNode_.frequency.value = this.cutoffFrequency_;
this.lowPassFilterNode_.frequency.setValueAtTime(this.cutoffFrequency_, now);
var contourFrequency = this.contour_ * this.cutoffFrequency_;
this.lowPassFilterNode_.frequency.exponentialRampToValueAtTime(
contourFrequency, now + this.attackTime_);
this.lowPassFilterNode_.frequency.exponentialRampToValueAtTime(
this.cutoffFrequency_ +
this.sustainLevel_ * (contourFrequency - this.cutoffFrequency_),
now + this.attackTime_ + this.decayTime_);
};
/**
* Sets the filter cutoff frequency.
* @param {number} cutoffFrequency The cutoff frequency above which the
* frequencies are attenuated.
*/
doodle.moog.LowPassFilter.prototype.setCutoffFrequency = function(
cutoffFrequency) {
this.cutoffFrequency_ = cutoffFrequency;
this.resetContourEnvelope_();
};
/**
* Sets the filter envelope contour.
* @param {number} contour Amount of contour to apply to the filter envelope.
*/
doodle.moog.LowPassFilter.prototype.setContour = function(contour) {
this.contour_ = contour;
this.resetContourEnvelope_();
};
/**
* Sets attack phase duration.
* @param {number} time Duration of the attack phase in seconds.
*/
doodle.moog.LowPassFilter.prototype.setContourAttackTime = function(time) {
this.attackTime_ = time;
this.resetContourEnvelope_();
};
/**
* Sets decay phase duration.
* @param {number} time Duration of the decay phase in seconds.
*/
doodle.moog.LowPassFilter.prototype.setContourDecayTime = function(time) {
this.decayTime_ = time;
this.resetContourEnvelope_();
};
/**
* Sets the sustain level.
* @param {number} level The sustain level, a number in the range [0, 1].
*/
doodle.moog.LowPassFilter.prototype.setContourSustainLevel = function(level) {
this.sustainLevel_ = level;
this.resetContourEnvelope_();
};
/**
* Resets the contour envelope AudioParam using current LowPassFilter state.
* @private
*/
doodle.moog.LowPassFilter.prototype.resetContourEnvelope_ = function() {
this.lowPassFilterNode_.frequency.cancelScheduledValues(0);
this.lowPassFilterNode_.frequency.value = this.cutoffFrequency_;
};
/** @inheritDoc */
doodle.moog.LowPassFilter.prototype.getSourceNode = function() {
return this.lowPassFilterNode_;
};
/** @inheritDoc */
doodle.moog.LowPassFilter.prototype.connect = function(destination) {
this.lowPassFilterNode_.connect(destination);
};
/** @inheritDoc */
doodle.moog.LowPassFilter.prototype.disconnect = function() {
this.lowPassFilterNode_.disconnect();
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.addDependency('../../../compound_audio_node.js', ['doodle.moog.CompoundAudioNode'], []);
goog.addDependency('../../../envelope_generator.js', ['doodle.moog.EnvelopeGenerator'], []);
goog.addDependency('../../../low_pass_filter.js', ['doodle.moog.LowPassFilter'], ['doodle.moog.CompoundAudioNode']);
goog.addDependency('../../../master_mixer.js', ['doodle.moog.MasterMixer'], ['doodle.moog.MasterMixerInterface']);
goog.addDependency('../../../master_mixer_interface.js', ['doodle.moog.MasterMixerInterface'], []);
goog.addDependency('../../../moog.js', ['doodle.moog.Moog'], ['doodle.moog.LowPassFilter', 'doodle.moog.MasterMixer', 'doodle.moog.Oscillator', 'doodle.moog.OscillatorInterface', 'doodle.moog.Synthesizer', 'doodle.moog.WideBandPassFilter', 'goog.Disposable']);
goog.addDependency('../../../oscillator.js', ['doodle.moog.Oscillator'], ['doodle.moog.EnvelopeGenerator', 'doodle.moog.OscillatorInterface']);
goog.addDependency('../../../oscillator_interface.js', ['doodle.moog.OscillatorInterface', 'doodle.moog.OscillatorInterface.FillMode', 'doodle.moog.OscillatorInterface.Range', 'doodle.moog.OscillatorInterface.WaveForm'], []);
goog.addDependency('../../../synthesizer.js', ['doodle.moog.Synthesizer'], ['doodle.moog.CompoundAudioNode', 'doodle.moog.OscillatorInterface', 'doodle.moog.SynthesizerInterface', 'goog.array', 'goog.userAgent']);
goog.addDependency('../../../synthesizer_interface.js', ['doodle.moog.SynthesizerInterface'], []);
goog.addDependency('../../../wide_band_pass_filter.js', ['doodle.moog.WideBandPassFilter'], ['doodle.moog.CompoundAudioNode']);
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Voltage controlled oscillator emulators.
*/
goog.provide('doodle.moog.OscillatorInterface');
goog.provide('doodle.moog.OscillatorInterface.FillMode');
goog.provide('doodle.moog.OscillatorInterface.Range');
goog.provide('doodle.moog.OscillatorInterface.WaveForm');
/**
* Oscillator interface to be implemented in WebAudio and FlashAudio.
* @interface
*/
doodle.moog.OscillatorInterface = function() {};
/**
* Different methods in which an oscillator can fill an audio buffer.
* @enum {number}
*/
doodle.moog.OscillatorInterface.FillMode = {
// Clobber any pre-existing data in the buffer.
CLOBBER: 0,
// Add signal to the buffer.
ADD: 1,
// Add signal to the buffer and then do an even mix down.
MIX: 2
};
/**
* Different 'ranges' (i.e., octaves in synth lingo) in which an oscillator can
* generate a tone. 'LO' is a special Moog-ism that generates sub-audio clicks
* and pops.
* @enum {number}
*/
doodle.moog.OscillatorInterface.Range = {
LO: 0.0625,
R32: 2,
R16: 4,
R8: 8,
R4: 16,
R2: 32
};
/**
* Different wave forms that can be generated by an oscillator, each of which
* has a different overtone spectrum leading to a different base timbre.
* @enum {number}
*/
doodle.moog.OscillatorInterface.WaveForm = {
TRIANGLE: 0,
SAWANGLE: 1,
RAMP: 2,
REVERSE_RAMP: 3,
SQUARE: 4,
FAT_PULSE: 5,
PULSE: 6
};
/**
* Sets the volume on this oscillator.
* @param {number} volume Volume in the range of [0, 1].
*/
doodle.moog.OscillatorInterface.prototype.setVolume = function(volume) {};
/**
* Sets the wave form generated by this oscillator.
* @param {!doodle.moog.OscillatorInterface.WaveForm} waveForm The wave form to
* use.
*/
doodle.moog.OscillatorInterface.prototype.setWaveForm = function(waveForm) {};
/**
* Sets the pitch bend on this oscillator.
* @param {number} pitchBend Pitch bend amount in the range of [-1, 1].
*/
doodle.moog.OscillatorInterface.prototype.setPitchBend = function(pitchBend) {};
/**
* Sets the octave/range of this oscillator.
* @param {!doodle.moog.OscillatorInterface.Range} range The range of this
* oscillator.
*/
doodle.moog.OscillatorInterface.prototype.setRange = function(range) {};
/**
* Turns on keyboard pitch control.
*/
doodle.moog.OscillatorInterface.prototype.turnOnKeyboardPitchControl =
function() {};
/**
* Turns off keyboard pitch control.
*/
doodle.moog.OscillatorInterface.prototype.turnOffKeyboardPitchControl =
function() {};
/**
* Turns on frequency modulation.
*/
doodle.moog.OscillatorInterface.prototype.turnOnFrequencyModulation =
function() {};
/**
* Turns off frequency modulation.
*/
doodle.moog.OscillatorInterface.prototype.turnOffFrequencyModulation =
function() {};
/**
* Sets the modulation signal level.
* @param {number} modulatorLevel If a modulator, how strong the modulator
* control signal should be [0..1].
*/
doodle.moog.OscillatorInterface.prototype.setModulatorLevel =
function(modulatorLevel) {};
/**
* Turns on glide.
*/
doodle.moog.OscillatorInterface.prototype.turnOnGlide = function() {};
/**
* Turns off glide.
*/
doodle.moog.OscillatorInterface.prototype.turnOffGlide = function() {};
/**
* Sets the duration of gliding.
* @param {number} time The time to glide between notes in seconds.
*/
doodle.moog.OscillatorInterface.prototype.setGlideDuration = function(time) {};
/**
* Sets the note this oscillator should generate.
* @param {number} note Chromatic index of the note to be played relative to the
* beginning of the keyboard.
*/
doodle.moog.OscillatorInterface.prototype.setActiveNote = function(note) {};
/**
* Sets the attack time for this oscillator's envelope generator.
* @param {number} attackTime The new attack time.
*/
doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorAttackTime =
function(attackTime) {};
/**
* Sets the decay time for this oscillator's envelope generator.
* @param {number} decayTime The new decay time.
*/
doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorDecayTime =
function(decayTime) {};
/**
* Sets the sustain level for this oscillator's envelope generator.
* @param {number} sustainLevel The new sustain level.
*/
doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorSustainLevel =
function(sustainLevel) {};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A moog-like audio synthesizer built on top of the HTML5 Web
* Audio API.
*/
goog.provide('doodle.moog.Synthesizer');
goog.require('doodle.moog.CompoundAudioNode');
goog.require('doodle.moog.OscillatorInterface');
goog.require('doodle.moog.SynthesizerInterface');
goog.require('goog.array');
goog.require('goog.userAgent');
/**
* A Moog-like synthesizer built on top of the HTML5 Web Audio API.
* @param {!AudioContext} audioContext Audio context in which this synthesizer
* will operate.
* @param {!Array.<!doodle.moog.Oscillator>} oscillators The oscillators used
* within this synthesizer.
* @param {!doodle.moog.LowPassFilter} lowPassFilter The low pass filter used
* within this synthesizer.
* @param {number} volume How much the gain should be adjusted.
* @implements {doodle.moog.CompoundAudioNode}
* @implements {doodle.moog.SynthesizerInterface}
* @constructor
*/
doodle.moog.Synthesizer = function(
audioContext, oscillators, lowPassFilter, volume) {
/**
* The audio context in which this synthesizer operates.
* @type {!AudioContext}
* @private
*/
this.audioContext_ = audioContext;
/**
* Oscillators used to generate synthesizer sounds.
* @type {!Array.<!doodle.moog.Oscillator>}
*/
this.oscillators = oscillators;
/**
* Filter used to cut off high frequencies.
* @type {!doodle.moog.LowPassFilter}
*/
this.lowPassFilter = lowPassFilter;
/**
* The volume Web Audio node.
* @type {!AudioGainNode}
* @private
*/
this.volumeNode_ = audioContext.createGainNode();
/**
* Frequency analyser node.
* @type {!RealtimeAnalyserNode}
*/
this.analyserNode = audioContext.createAnalyser();
this.analyserNode.smoothingTimeConstant = 0.5;
/**
* Volume/gain adjustment to apply to the output signal.
* @type {number}
* @private
*/
this.volume_;
this.setVolume(volume);
/**
* Web Audio JavaScript node used by oscillators to generate sound.
* Chrome 20+ won't connect a js node with no inputs for some reason.
* @type {!JavaScriptAudioNode}
* @private
*/
this.jsAudioNode_ = goog.userAgent.isVersion('20.0') ?
audioContext.createJavaScriptNode(
doodle.moog.Synthesizer.BUFFER_SIZE_, 1, 1) :
audioContext.createJavaScriptNode(
doodle.moog.Synthesizer.BUFFER_SIZE_, 0, 1);
this.jsAudioNode_.onaudioprocess = goog.bind(this.fillAudioBuffer_, this);
this.jsAudioNode_.connect(this.lowPassFilter.getSourceNode());
this.lowPassFilter.connect(this.volumeNode_);
this.volumeNode_.connect(this.analyserNode);
};
/**
* How many samples to fill at a time in a JavaScript audio node callback. A
* larger number here will decrease the chance of jitters/gaps at the expense of
* control latency.
* @type {number}
* @const
* @private
*/
doodle.moog.Synthesizer.BUFFER_SIZE_ = 1024;
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setKeyDown = function(note) {
goog.array.forEach(this.oscillators, function(oscillator) {
oscillator.setActiveNote(note);
oscillator.envelopeGenerator.startAttack();
});
this.lowPassFilter.startAttack();
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setKeyDownCallback = function(callback) {
// No-op, since this is only required on non-WebAudio browsers.
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setKeyUp = function() {
goog.array.forEach(this.oscillators, function(oscillator) {
oscillator.envelopeGenerator.startRelease();
});
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpCutoffFrequency =
function(cutoffFrequency) {
this.lowPassFilter.setCutoffFrequency(cutoffFrequency);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpContour = function(contour) {
this.lowPassFilter.setContour(contour);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpContourAttackTime = function(time) {
this.lowPassFilter.setContourAttackTime(time);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpContourDecayTime = function(time) {
this.lowPassFilter.setContourDecayTime(time);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setLpContourSustainLevel = function(level) {
this.lowPassFilter.setContourSustainLevel(level);
};
/**
* Fills the passed audio buffer with tones generated by oscillators.
* @param {!AudioProcessingEvent} e The audio process event object.
* @private
*/
doodle.moog.Synthesizer.prototype.fillAudioBuffer_ = function(e) {
// NOTE: We fill oscillator 2 first since it generates a modulation control
// signal on which oscillators 0 and 1 depend.
this.oscillators[2].fillAudioBuffer(
e, null, doodle.moog.OscillatorInterface.FillMode.CLOBBER);
this.oscillators[0].fillAudioBuffer(
e, this.oscillators[2].modulatorSignal,
doodle.moog.OscillatorInterface.FillMode.ADD);
this.oscillators[1].fillAudioBuffer(
e, this.oscillators[2].modulatorSignal,
doodle.moog.OscillatorInterface.FillMode.MIX, this.oscillators.length);
};
/** @inheritDoc */
doodle.moog.Synthesizer.prototype.setVolume = function(volume) {
this.volume_ = volume;
this.volumeNode_.gain.value = volume;
};
/** @override */
doodle.moog.Synthesizer.prototype.getSourceNode = function() {
return this.jsAudioNode_;
};
/** @override */
doodle.moog.Synthesizer.prototype.connect = function(destination) {
this.analyserNode.connect(destination);
};
/** @override */
doodle.moog.Synthesizer.prototype.disconnect = function() {
this.analyserNode.disconnect();
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Attack, Decay, Sustain, Decay (ADSD) envelope generator.
*/
goog.provide('doodle.moog.EnvelopeGenerator');
/**
* An ADSD envelope generator, used to control volume of a single synth note.
*
* See the Phase_ enum below for a description of how ADSD envelopes work.
*
* @param {number} sampleInterval How many seconds pass with each sample.
* @param {number} attackTime Initial attack time in seconds.
* @param {number} decayTime Initial decay time in seconds.
* @param {number} sustainLevel Initial sustain level [0..1].
* @constructor
*/
doodle.moog.EnvelopeGenerator = function(
sampleInterval, attackTime, decayTime, sustainLevel) {
/**
* How many seconds pass with each sample.
* @type {number}
* @private
* @const
*/
this.SAMPLE_INTERVAL_ = sampleInterval;
/**
* The amount by which the tone associated with this envelope should be
* scaled. A number in the range [0, 1].
* @type {number}
* @private
*/
this.amplitudeCoefficient_ = 0;
/**
* The current phase of the envelope.
* @type {!doodle.moog.EnvelopeGenerator.Phase_}
* @private
*/
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.INACTIVE;
/**
* The duration of the attack phase in seconds.
* @type {number}
* @private
*/
this.attackTime_ = attackTime;
/**
* How much the amplitude should be increased for each sample in the attack
* phase.
*
* NOTE: This variable and other 'step' variables can be computed from other
* EnvelopeGenerator state. We explicitly store these values though since
* they are precisely the data needed in getNextAmplitudeCoefficient which is
* typically executed in a sound buffer filling loop and therefore performance
* critical.
* @type {number}
* @private
*/
this.attackStep_;
/**
* The duration of the decay phase in seconds.
* @type {number}
* @private
*/
this.decayTime_ = decayTime;
/**
* How much the amplitude should be decreased for each sample in the decay
* phase.
* @type {number}
* @private
*/
this.decayStep_;
/**
* The sustain amplitude coefficient.
* @type {number}
* @private
*/
this.sustainLevel_ = sustainLevel;
/**
* How much the amplitude should be decreased for each sample in the release
* phase.
* @type {number}
* @private
*/
this.releaseStep_;
this.recomputePhaseSteps_();
};
/**
* The different phases of an ADSD envelope. When playing a key on a synth,
* these phases are always executed in the order they're defined in this enum.
*
* @enum {number}
* @private
*/
doodle.moog.EnvelopeGenerator.Phase_ = {
// A linear ramp up from no volume (just before a key is struck) to maximum
// volume.
ATTACK: 0,
// A linear ramp down from maximum volume to the sustain volume level.
DECAY: 1,
// Once the attack and decay phases have completed, the volume at which the
// note is held until the key is released.
SUSTAIN: 2,
// A linear ramp down from the sustain volume to no volume after a key is
// released. Moog instruments uniquely reuse the decay time parameter for the
// release time (hence the "ADSD" acronym instead of "ADSR").
RELEASE: 3,
// Meta state indicating that the envelope is not currently active.
INACTIVE: 4
};
/**
* Initiates the attack phase of the envelope (e.g., when a key is pressed).
*/
doodle.moog.EnvelopeGenerator.prototype.startAttack = function() {
this.recomputePhaseSteps_();
this.amplitudeCoefficient_ = 0;
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.ATTACK;
};
/**
* Initiates the release phase of the envelope (e.g., when a key is lifted).
*/
doodle.moog.EnvelopeGenerator.prototype.startRelease = function() {
if (this.phase_ == doodle.moog.EnvelopeGenerator.Phase_.RELEASE) {
return;
} else {
// Compute release step based on the current amplitudeCoefficient_.
if (this.decayTime_ <= 0) {
this.releaseStep_ = 1;
} else {
this.releaseStep_ =
this.amplitudeCoefficient_ * this.SAMPLE_INTERVAL_ / this.decayTime_;
}
}
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.RELEASE;
};
/**
* Gets the next amplitude coefficient that should be applied to the currently
* playing note. This method must be called (and applied, natch) for each
* sample filled for the duration of a note.
*
* @return {number} An amplitude coefficient in the range [0, 1] that should be
* applied to the current sample.
*/
doodle.moog.EnvelopeGenerator.prototype.getNextAmplitudeCoefficient =
function() {
switch (this.phase_) {
case doodle.moog.EnvelopeGenerator.Phase_.ATTACK:
this.amplitudeCoefficient_ += this.attackStep_;
if (this.amplitudeCoefficient_ >= 1) {
this.amplitudeCoefficient_ = 1;
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.DECAY;
}
break;
case doodle.moog.EnvelopeGenerator.Phase_.DECAY:
this.amplitudeCoefficient_ -= this.decayStep_;
if (this.amplitudeCoefficient_ <= this.sustainLevel_) {
this.amplitudeCoefficient_ = this.sustainLevel_;
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.SUSTAIN;
}
break;
case doodle.moog.EnvelopeGenerator.Phase_.SUSTAIN:
// Just stay at the sustain level until a release is signaled.
break;
case doodle.moog.EnvelopeGenerator.Phase_.RELEASE:
this.amplitudeCoefficient_ -= this.releaseStep_;
if (this.amplitudeCoefficient_ <= 0) {
this.amplitudeCoefficient_ = 0;
this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.INACTIVE;
}
break;
case doodle.moog.EnvelopeGenerator.Phase_.INACTIVE:
// Stay at 0, as set in the release transition (muted).
break;
}
return this.amplitudeCoefficient_;
};
/**
* Sets attack phase duration.
* @param {number} time Duration of the attack phase in seconds.
*/
doodle.moog.EnvelopeGenerator.prototype.setAttackTime = function(time) {
this.attackTime_ = time;
this.recomputePhaseSteps_();
};
/**
* Sets decay phase duration.
* @param {number} time Duration of the decay phase in seconds.
*/
doodle.moog.EnvelopeGenerator.prototype.setDecayTime = function(time) {
this.decayTime_ = time;
this.recomputePhaseSteps_();
};
/**
* Sets the sustain level.
* @param {number} level The sustain level, a number in the range [0, 1].
*/
doodle.moog.EnvelopeGenerator.prototype.setSustainLevel = function(level) {
this.sustainLevel_ = level;
this.recomputePhaseSteps_();
};
/**
* Updates phase step variables to reflect current EnvelopeGenerator state.
* @private
*/
doodle.moog.EnvelopeGenerator.prototype.recomputePhaseSteps_ = function() {
if (this.attackTime_ <= 0) {
this.attackStep_ = 1;
} else {
this.attackStep_ = this.SAMPLE_INTERVAL_ / this.attackTime_;
}
if (this.decayTime_ <= 0) {
this.decayStep_ = 1;
this.releaseStep_ = 1;
} else {
this.decayStep_ =
(1 - this.sustainLevel_) * this.SAMPLE_INTERVAL_ / this.decayTime_;
this.releaseStep_ =
this.sustainLevel_ * this.SAMPLE_INTERVAL_ / this.decayTime_;
}
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Interface for compound Web Audio audio nodes.
*/
goog.provide('doodle.moog.CompoundAudioNode');
/**
* Connection interface for compound Web Audio nodes.
* @interface
*/
doodle.moog.CompoundAudioNode = function() {};
/**
* Gets the source node for this compound node.
* @return {!AudioNode} The input/source node for this compound node.
*/
doodle.moog.CompoundAudioNode.prototype.getSourceNode = function() {};
/**
* Connects this compound node to a destination audio node.
* @param {!AudioNode} destination The destination to connect this node to.
*/
doodle.moog.CompoundAudioNode.prototype.connect = function(destination) {};
/**
* Disconnects this compound node from any destination audio node.
*/
doodle.moog.CompoundAudioNode.prototype.disconnect = function() {
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A moog-like audio synthesizer built on top of the HTML5 Web
* Audio API.
*/
goog.provide('doodle.moog.SynthesizerInterface');
/**
* A Moog-like synthesizer built on top of the HTML5 Web Audio API.
* @interface
*/
doodle.moog.SynthesizerInterface = function() {};
/**
* Signals that a key on the synthesizer has been pressed.
* @param {number} note Chromatic index of the note to be played relative to
* the beginning of the keyboard.
*/
doodle.moog.SynthesizerInterface.prototype.setKeyDown = function(note) {};
/**
* Binds a callback to a key down event.
* @param {function(number)} callback The function called when a key is pressed.
*/
doodle.moog.SynthesizerInterface.prototype.setKeyDownCallback =
function(callback) {};
/**
* Signals that a key on the synthesizer has been released. Since the
* synthesizer is monophonic, no note parameter is necessary.
*/
doodle.moog.SynthesizerInterface.prototype.setKeyUp = function() {};
/**
* Increases/decreases the output gain.
* @param {number} volume The output volume level. A number in the range
* [0..1].
*/
doodle.moog.SynthesizerInterface.prototype.setVolume = function(volume) {};
/**
* Proxy to the synthesizer's low-pass filter setCutoffFrequency.
* @param {number} cutoffFrequency The cutoff frequency above which the
* frequencies are attenuated.
*/
doodle.moog.SynthesizerInterface.prototype.setLpCutoffFrequency =
function(cutoffFrequency) {};
/**
* Proxy to the synthesizer's low-pass filter setContour.
* @param {number} contour Amount of contour to apply to the filter envelope.
*/
doodle.moog.SynthesizerInterface.prototype.setLpContour =
function(contour) {};
/**
* Proxy to the synthesizer's low-pass filter setContourAttackTime.
* @param {number} time Duration of the attack phase in seconds.
*/
doodle.moog.SynthesizerInterface.prototype.setLpContourAttackTime =
function(time) {};
/**
* Proxy to the synthesizer's low-pass filter setContourDecayTime.
* @param {number} time Duration of the decay phase in seconds.
*/
doodle.moog.SynthesizerInterface.prototype.setLpContourDecayTime =
function(time) {};
/**
* Proxy to the synthesizer's low-pass filter setContourSustainLevel.
* @param {number} level The sustain level, a number in the range [0, 1].
*/
doodle.moog.SynthesizerInterface.prototype.setLpContourSustainLevel =
function(level) {};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Voltage controlled oscillator emulators.
*/
goog.provide('doodle.moog.Oscillator');
goog.require('doodle.moog.EnvelopeGenerator');
goog.require('doodle.moog.OscillatorInterface');
/**
* A voltage controlled oscillator emulator built on the HTML5 Audio API. This
* is the root source of all sound in the Moog doodle.
*
* @param {!AudioContext} audioContext Audio context to which this oscillator
* will be bound.
* @param {number} volume Initial volume level [0..1].
* @param {!doodle.moog.OscillatorInterface.WaveForm} waveForm Initial wave
* form.
* @param {!doodle.moog.OscillatorInterface.Range} range Initial pitch range.
* @param {number} pitchBend Initial pitch bend [-1..1].
* @param {boolean} isAcceptingKeyboardPitch Whether keyboard control is on.
* @param {boolean} isFrequencyModulationOn Whether this oscillator should
* modulate its frequency using the modulator control signal.
* @param {boolean} isModulator Whether this modulator should act as a modulator
* control signal in addition to an audio signal.
* @param {number} modulatorLevel If a modulator, how strong the modulator
* control signal should be [0..1].
* @param {boolean} isGlideOn Whether glide is on.
* @param {number} glideTime Glide time in seconds.
* @param {number} attackTime Initial attack time in seconds.
* @param {number} decayTime Initial decay time in seconds.
* @param {number} sustainLevel Initial sustain level [0..1].
* @constructor
* @implements {doodle.moog.OscillatorInterface}
*/
doodle.moog.Oscillator = function(
audioContext, volume, waveForm, range, pitchBend, isAcceptingKeyboardPitch,
isFrequencyModulationOn, isModulator, modulatorLevel, isGlideOn, glideTime,
attackTime, decayTime, sustainLevel) {
/**
* How many seconds pass with each sample.
* @type {number}
* @private
* @const
*/
this.SAMPLE_INTERVAL_ = 1 / audioContext.sampleRate;
/**
* How many seconds we have advanced in the current cycle.
* @type {number}
* @private
*/
this.phase_ = 0.0;
/**
* The amount of oscillator signal which is fed into the mixer. Mapped onto
* the range [0.0, 1.0] where 0 means muted and 1.0 means full loudness.
* @type {number}
* @private
*/
this.volume_ = volume;
/**
* Shape of the wave this oscillator generates.
* @type {!doodle.moog.OscillatorInterface.WaveForm}
* @private
*/
this.waveForm_ = waveForm;
/**
* Octave/range in which the oscillator functions.
* @type {!doodle.moog.OscillatorInterface.Range}
* @private
*/
this.range_ = range;
/**
* Pitch bend to apply on top of the base frequency on the range [-1.0, 1.0].
* If isAcceptingKeyboardPitch_ is true, -1/1 are a major 6th down/up; 0 is no
* pitch bend. If isAcceptingKeyboardPitch_ is false, -1/1 are 3 octaves
* down/up; 0 is still no pitch bend.
* @type {number}
* @private
*/
this.pitchBend_ = pitchBend;
/**
* Whether the oscillator pitch is controlled by keyboard signals. If true,
* the pitch follows the keyboard as one would expect on a piano-like
* instrument. If false, pressing any key on the keyboard will result in the
* same pitch (as set by range_ and pitchBend_).
* @type {boolean}
* @private
*/
this.isAcceptingKeyboardPitch_ = isAcceptingKeyboardPitch;
/**
* Whether this oscillator should modulate its frequency using the modulator
* control signal.
* @type {boolean}
* @private
*/
this.isFrequencyModulationOn_ = isFrequencyModulationOn;
/**
* Whether this modulator should act as a modulator control signal in addition
* to an audio signal.
* @type {boolean}
* @const
* @private
*/
this.IS_MODULATOR_ = isModulator;
/**
* If this oscillator is also a modulator, how strong the modulator control
* signal should be [0..1]. 0 fully attenuates the control signal; 1 fully
* applies it.
* @type {number}
* @private
*/
this.modulatorLevel_ = modulatorLevel;
/**
* If this oscillator is also a modulator, a buffer for storing modulator
* control signal samples. Null iff this oscillator does not act as a
* modulator.
* @type {Float32Array}
*/
this.modulatorSignal = null;
/**
* Whether glide (portamento sliding between notes) is enabled.
* @type {boolean}
* @private
*/
this.isGlideOn_ = isGlideOn;
/**
* Glide duration in seconds.
* @type {number}
* @private
*/
this.glideDuration_ = glideTime;
/**
* How much to advanced the frequency per sample while gliding. Null until
* the first tone is played.
* @type {?number}
* @private
*/
this.glideDelta_ = null;
/**
* Current glide pitch. Null until the first tone is played.
* @type {?number}
* @private
*/
this.currentGlidePitch_ = null;
/**
* Target glide pitch. Null until the first tone is played.
* @type {?number}
* @private
*/
this.targetGlidePitch_ = null;
/**
* Chromatic index of the note to be played relative to the beginning of the
* keyboard.
* @type {number}
* @private
*/
this.activeNote_ = 0;
/**
* Envelope generator that will shape the dynamics of this oscillator.
* @type {!doodle.moog.EnvelopeGenerator}
*/
this.envelopeGenerator =
new doodle.moog.EnvelopeGenerator(
this.SAMPLE_INTERVAL_, attackTime, decayTime, sustainLevel);
};
/**
* The base frequency (in hertz) from which other notes' frequencies are
* calculated. A low 'A'.
* @type {number}
* @const
* @private
*/
doodle.moog.Oscillator.BASE_FREQUENCY_ = 55;
/**
* Frequency ratio of major sixth musical interval.
* @type {number}
* @const
* @private
*/
doodle.moog.Oscillator.MAJOR_SIXTH_FREQUENCY_RATIO_ = 5 / 3;
/**
* Frequency ratio of a three octave musical interval.
* @type {number}
* @const
* @private
*/
doodle.moog.Oscillator.THREE_OCTAVE_FREQUENCY_RATIO_ = 8;
/**
* The chromatic distance between keyboard notes (as passed to
* getInstantaneousFrequency_) and low A.
* @type {number}
* @const
* @private
*/
doodle.moog.Oscillator.NOTE_OFFSET_ = -4;
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setVolume = function(volume) {
this.volume_ = volume;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setWaveForm = function(waveForm) {
this.waveForm_ = waveForm;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setPitchBend = function(pitchBend) {
this.pitchBend_ = pitchBend;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setRange = function(range) {
this.range_ = range;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOnKeyboardPitchControl = function() {
this.isAcceptingKeyboardPitch_ = true;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOffKeyboardPitchControl = function() {
this.isAcceptingKeyboardPitch_ = false;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOnFrequencyModulation = function() {
this.isFrequencyModulationOn_ = true;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOffFrequencyModulation = function() {
this.isFrequencyModulationOn_ = false;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setModulatorLevel = function(modulatorLevel) {
this.modulatorLevel_ = modulatorLevel;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOnGlide = function() {
this.isGlideOn_ = true;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.turnOffGlide = function() {
this.isGlideOn_ = false;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setGlideDuration = function(time) {
this.glideDuration_ = time;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setActiveNote = function(note) {
this.activeNote_ = note;
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setEnvelopeGeneratorAttackTime =
function(attackTime) {
this.envelopeGenerator.setAttackTime(attackTime);
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setEnvelopeGeneratorDecayTime =
function(decayTime) {
this.envelopeGenerator.setDecayTime(decayTime);
};
/** @inheritDoc */
doodle.moog.Oscillator.prototype.setEnvelopeGeneratorSustainLevel =
function(sustainLevel) {
this.envelopeGenerator.setSustainLevel(sustainLevel);
};
/**
* Gets the instantaneous frequency that this oscillator ought to be generating.
* @param {number} note Chromatic index of the note to be played relative to
* the beginning of the keyboard.
* @return {number} The instantaneous frequency.
* @private
*/
doodle.moog.Oscillator.prototype.getInstantaneousFrequency_ = function(note) {
if (!this.isAcceptingKeyboardPitch_) {
note = 0;
}
return doodle.moog.Oscillator.BASE_FREQUENCY_ *
this.range_ *
Math.pow(2, (note + doodle.moog.Oscillator.NOTE_OFFSET_) / 12);
};
/**
* Gets the pitch bend that should be applied to this oscillator.
* @return {number} The frequency ratio that should be applied to the base
* pitch.
* @private
*/
doodle.moog.Oscillator.prototype.getPitchBend_ = function() {
var pitchBendScale = doodle.moog.Oscillator.MAJOR_SIXTH_FREQUENCY_RATIO_;
if (!this.isAcceptingKeyboardPitch_) {
pitchBendScale = doodle.moog.Oscillator.THREE_OCTAVE_FREQUENCY_RATIO_;
}
var normalizedPitchBend =
Math.abs(this.pitchBend_ * (pitchBendScale - 1)) + 1;
return this.pitchBend_ >= 0 ? normalizedPitchBend : 1 / normalizedPitchBend;
};
/**
* Gets the frequency this oscillator ought to generate after undergoing
* optional glide.
* @param {number} target The target frequency to move towards.
* @return {number} The frequency this oscillator should generate with glide.
* @private
*/
doodle.moog.Oscillator.prototype.getGlideFrequency_ = function(target) {
if (!this.isGlideOn_ ||
this.currentGlidePitch_ === null ||
this.glideDuration_ <= 0 ||
Math.abs(this.currentGlidePitch_ - target) <=
Math.abs(this.glideDelta_)) {
this.currentGlidePitch_ = this.targetGlidePitch_ = target;
return target;
}
if (this.targetGlidePitch_ != target) {
var glideDurationInSamples = this.glideDuration_ / this.SAMPLE_INTERVAL_;
this.glideDelta_ =
(target - this.currentGlidePitch_) / glideDurationInSamples;
this.targetGlidePitch_ = target;
}
this.currentGlidePitch_ += this.glideDelta_;
return this.currentGlidePitch_;
};
/**
* Gets the frequency this oscillator ought to generate after undergoing
* optional frequency modulation.
* @param {number} baseFrequency The base frequency to modulate.
* @param {Float32Array} modulatorSignal Modulator signal buffer to apply to
* this oscillator. If null, no modulation should be applied.
* @param {number} index Sample index of the modulation signal to apply.
* @return {number} The frequency this oscillator should generate with
* modulation.
* @private
*/
doodle.moog.Oscillator.prototype.getModulationFrequency_ = function(
baseFrequency, modulatorSignal, index) {
if (!modulatorSignal || !this.isFrequencyModulationOn_) {
return baseFrequency;
}
// Linearly project modulation level [0..1] onto [0.5..2] (down/up an octave).
// TODO: Re-evaluate this maximum frequency modulation range based on real
// Moog behavior.
return (modulatorSignal[index] * 0.75 + 1.25) * baseFrequency;
};
/**
* Advances the oscillator's phase of play. This helper function must be called
* exactly once per sample.
* @param {number} frequency The frequency being played.
* @return {number} Progress made in the current cycle, projected on the range
* [0, 1].
* @private
*/
doodle.moog.Oscillator.prototype.advancedPhase_ = function(frequency) {
var cycleLengthInSeconds = 2 / frequency;
if (this.phase_ > cycleLengthInSeconds) {
this.phase_ -= cycleLengthInSeconds;
}
var progressInCycle = this.phase_ * frequency / 2;
this.phase_ += this.SAMPLE_INTERVAL_;
return progressInCycle;
};
/**
* Fills the passed audio buffer with the tone represented by this oscillator.
* @param {!AudioProcessingEvent} e The audio process event object.
* @param {Float32Array} modulatorSignal Modulator signal buffer to apply to
* this oscillator. If null, no modulation will be applied.
* @param {!doodle.moog.OscillatorInterface.FillMode} fillMode How the
* oscillator should fill the passed audio buffer.
* @param {number=} opt_mixDivisor Iff using FillMode.MIX, how much to mix down
* the buffer. This should usually be the number of oscillators that have
* added data to the buffer.
*/
doodle.moog.Oscillator.prototype.fillAudioBuffer = function(
e, modulatorSignal, fillMode, opt_mixDivisor) {
var buffer = e.outputBuffer;
var left = buffer.getChannelData(1);
var right = buffer.getChannelData(0);
if (this.IS_MODULATOR_ && !this.modulatorSignal) {
this.modulatorSignal = new Float32Array(buffer.length);
}
var targetFrequency = this.getInstantaneousFrequency_(this.activeNote_);
var pitchBend = this.getPitchBend_();
var frequency = targetFrequency * pitchBend;
var audioLevel, envelopeCoefficient, level, on, progressInCycle, ramp;
for (var i = 0; i < buffer.length; ++i) {
envelopeCoefficient =
this.envelopeGenerator.getNextAmplitudeCoefficient();
progressInCycle = this.advancedPhase_(
pitchBend *
this.getModulationFrequency_(
this.getGlideFrequency_(targetFrequency), modulatorSignal, i));
switch (this.waveForm_) {
case doodle.moog.OscillatorInterface.WaveForm.TRIANGLE:
level = 4 * ((progressInCycle > 0.5 ?
1 - progressInCycle : progressInCycle) - .25);
break;
case doodle.moog.OscillatorInterface.WaveForm.SAWANGLE:
ramp = progressInCycle < 0.5;
level = ramp ? (4 * progressInCycle - 1) : (-2 * progressInCycle + 1);
break;
case doodle.moog.OscillatorInterface.WaveForm.RAMP:
level = 2 * (progressInCycle - 0.5);
break;
case doodle.moog.OscillatorInterface.WaveForm.REVERSE_RAMP:
level = -2 * (progressInCycle - 0.5);
break;
case doodle.moog.OscillatorInterface.WaveForm.SQUARE:
level = progressInCycle < 0.5 ? 1 : -1;
break;
case doodle.moog.OscillatorInterface.WaveForm.FAT_PULSE:
level = progressInCycle < 1 / 3 ? 1 : -1;
break;
case doodle.moog.OscillatorInterface.WaveForm.PULSE:
level = progressInCycle < 0.25 ? 1 : -1;
break;
}
if (this.IS_MODULATOR_) {
this.modulatorSignal[i] = level * this.modulatorLevel_;
}
audioLevel = level * this.volume_ * envelopeCoefficient;
if (fillMode == doodle.moog.OscillatorInterface.FillMode.CLOBBER) {
right[i] = audioLevel;
} else if (fillMode == doodle.moog.OscillatorInterface.FillMode.ADD) {
right[i] = right[i] + audioLevel;
} else { // Otherwise FillMode.MIX.
right[i] = (right[i] + audioLevel) / opt_mixDivisor;
// In older versions of Chrome, Web Audio API always created two
// channels even if you have requested monaural sound. However, this
// is not the case in the newer (dev/canary) versions. This should
// cover both.
if (left) {
left[i] = right[i];
}
}
}
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a wide band pass filter to protect headphones and
* speakers from really low and high frequencies.
*/
goog.provide('doodle.moog.WideBandPassFilter');
goog.require('doodle.moog.CompoundAudioNode');
/**
* A wide band pass filter designed to filter out low and high frequencies that
* might damage poorly made speakers connected to poorly made sound cards.
* @param {!AudioContext} audioContext Audio context to which this oscillator
* will be bound.
* @param {number} lowCutoffFrequency The cutoff frequency below which sound is
* attenuated.
* @param {number} highCutoffFrequency The cutoff frequency above which sound is
* attenuated.
* @constructor
* @implements {doodle.moog.CompoundAudioNode}
*/
doodle.moog.WideBandPassFilter = function(
audioContext, lowCutoffFrequency, highCutoffFrequency) {
/**
* The low pass filter Web Audio node.
* @type {!BiquadFilterNode}
* @private
*/
this.lowPassFilterNode_ = audioContext.createBiquadFilter();
this.lowPassFilterNode_.type =
doodle.moog.WideBandPassFilter.LOW_PASS_FILTER_TYPE_ID_;
this.lowPassFilterNode_.frequency.value = highCutoffFrequency;
/**
* The high pass filter Web Audio node.
* @type {!BiquadFilterNode}
* @private
*/
this.highPassFilterNode_ = audioContext.createBiquadFilter();
this.highPassFilterNode_.type =
doodle.moog.WideBandPassFilter.HIGH_PASS_FILTER_TYPE_ID_;
this.highPassFilterNode_.frequency.value = lowCutoffFrequency;
this.lowPassFilterNode_.connect(this.highPassFilterNode_);
};
/**
* Biquad Filter type ID for a low pass filter (from the Web Audio spec).
* @type {number}
* @const
* @private
*/
doodle.moog.WideBandPassFilter.LOW_PASS_FILTER_TYPE_ID_ = 0;
/**
* Biquad Filter type ID for a low pass filter (from the Web Audio spec).
* @type {number}
* @const
* @private
*/
doodle.moog.WideBandPassFilter.HIGH_PASS_FILTER_TYPE_ID_ = 1;
/** @inheritDoc */
doodle.moog.WideBandPassFilter.prototype.getSourceNode = function() {
return this.lowPassFilterNode_;
};
/** @inheritDoc */
doodle.moog.WideBandPassFilter.prototype.connect = function(destination) {
this.highPassFilterNode_.connect(destination);
};
/** @inheritDoc */
doodle.moog.WideBandPassFilter.prototype.disconnect = function() {
this.highPassFilterNode_.disconnect();
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Master mixer interface for all doodle Web Audio sources.
*/
goog.provide('doodle.moog.MasterMixerInterface');
/**
* Master mixer for the multiple virtual synthesizers that may play back
* simultaneously via the Sequencer.
* @interface
*/
doodle.moog.MasterMixerInterface = function() {};
/**
* Turns on the mixer.
*/
doodle.moog.MasterMixerInterface.prototype.turnOn = function() {};
/**
* Turns off the mixer.
*/
doodle.moog.MasterMixerInterface.prototype.turnOff = function() {};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Main module for the Dr. Robert Moog Synthesizer doodle.
*/
goog.provide('doodle.moog.Moog');
goog.require('doodle.moog.LowPassFilter');
goog.require('doodle.moog.MasterMixer');
goog.require('doodle.moog.Oscillator');
goog.require('doodle.moog.OscillatorInterface');
goog.require('doodle.moog.Synthesizer');
goog.require('doodle.moog.WideBandPassFilter');
goog.require('goog.Disposable');
/**
* The Moog doodle manager.
* @constructor
* @extends {goog.Disposable}
*/
doodle.moog.Moog = function() {
goog.base(this);
/**
* The set of available synthesizers.
* @type {!Array.<!doodle.moog.SynthesizerInterface>}
* @private
*/
this.synthesizers_ = [];
/**
* A reference to a master mixer instance.
* @type {!doodle.moog.MasterMixerInterface}
* @private
*/
this.masterMixer_;
/**
* @private
*/
this.isWebAudioEnabled_ = typeof webkitAudioContext === 'function';
if (this.isWebAudioEnabled_) {
this.initializeWebAudio_();
}
};
goog.inherits(doodle.moog.Moog, goog.Disposable);
/** @inheritDoc */
doodle.moog.Moog.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.turnOffAudio();
};
/**
* Initializes the Moog doodle on WebAudio-compatible browsers.
* @private
*/
doodle.moog.Moog.prototype.initializeWebAudio_ = function() {
try {
// Audio context creation can throw an error if the user is missing sound
// drivers, etc.
var audioContext = new webkitAudioContext();
} catch(e7) {
// Abort the initialization sequence like we do with flash.
return;
}
var oscillators = [
new doodle.moog.Oscillator(
audioContext, 0.46, doodle.moog.OscillatorInterface.WaveForm.SQUARE,
doodle.moog.OscillatorInterface.Range.R16, 0, true, false, false, 0,
true, 0.05, 0, 0.4, 1),
new doodle.moog.Oscillator(
audioContext, 0.82, doodle.moog.OscillatorInterface.WaveForm.SQUARE,
doodle.moog.OscillatorInterface.Range.R4, 0, true, false, false, 0,
true, 0.05, 0, 0.4, 1),
new doodle.moog.Oscillator(
audioContext, 0.46, doodle.moog.OscillatorInterface.WaveForm.SQUARE,
doodle.moog.OscillatorInterface.Range.R32, 0, true, false, true, 0.6,
true, 0.05, 0, 0.4, 1)
];
var lowPassFilter = new doodle.moog.LowPassFilter(
audioContext, 2100, 7, 0, .8, 0);
this.synthesizers_.push(new doodle.moog.Synthesizer(
audioContext, oscillators, lowPassFilter, 0.82));
var wideBandPassFilter = new doodle.moog.WideBandPassFilter(
audioContext, 20, 20000);
this.masterMixer_ = new doodle.moog.MasterMixer(
audioContext, this.synthesizers_, wideBandPassFilter);
};
/**
* Turns on the audio pipeline.
*/
doodle.moog.Moog.prototype.turnOnAudio = function() {
if (this.masterMixer_) {
this.masterMixer_.turnOn();
}
};
/**
* Turns off the audio pipeline.
*/
doodle.moog.Moog.prototype.turnOffAudio = function() {
if (this.masterMixer_) {
this.masterMixer_.turnOff();
}
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Master mixer for all doodle Web Audio sources.
*/
goog.provide('doodle.moog.MasterMixer');
goog.require('doodle.moog.MasterMixerInterface');
/**
* Master mixer for the multiple virtual synthesizers that may play back
* simultaneously via the Sequencer.
* @param {!AudioContext} audioContext Audio context in which this mixer will
* operate.
* @param {!Array.<!doodle.moog.SynthesizerInterface>} synthesizers The
* synthesizers that feed into this mixer.
* @param {!doodle.moog.WideBandPassFilter} wideBandPassFilter The wide band
* pass filter used within this mixer.
* @constructor
* @implements {doodle.moog.MasterMixerInterface}
*/
doodle.moog.MasterMixer = function(
audioContext, synthesizers, wideBandPassFilter) {
/**
* The audio context in which this mixer operates.
* @type {!AudioContext}
* @private
*/
this.audioContext_ = audioContext;
/**
* The synthesizers this mixer mixes.
* @type {!Array.<!doodle.moog.Synthesizer>}
* @private
*/
this.synthesizers_ = synthesizers;
/**
* Filter used to cut out really low/high frequencies.
* @type {!doodle.moog.WideBandPassFilter}
* @private
*/
this.wideBandPassFilter_ = wideBandPassFilter;
for (var i = 0; i < synthesizers.length; i++) {
synthesizers[i].connect(wideBandPassFilter.getSourceNode());
}
};
/** @inheritDoc */
doodle.moog.MasterMixer.prototype.turnOn = function() {
window.setTimeout(goog.bind(function() {
// NOTE: The audio pipeline is connected in a setTimeout to avoid a Chrome
// bug in which the audio will occasionally fail to initialize/play.
this.wideBandPassFilter_.connect(this.audioContext_.destination);
}, this), 0);
};
/** @inheritDoc */
doodle.moog.MasterMixer.prototype.turnOff = function() {
this.wideBandPassFilter_.disconnect();
};
|
JavaScript
|
$(document).ready(function() {
$('#home-slide').cycle('fade');
});
|
JavaScript
|
/*******
*** Anchor Slider by Cedric Dugas ***
*** Http://www.position-absolute.com ***
Never have an anchor jumping your content, slide it.
Don't forget to put an id to your anchor !
You can use and modify this script for any project you want, but please leave this comment as credit.
*****/
$(document).ready(function() {
$("a.anchorLink").anchorAnimate()
});
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 1100
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = $(caller).attr("href")
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}
|
JavaScript
|
$(document).ready(function() {
$('#home-slide').cycle('fade');
});
|
JavaScript
|
/*******
*** Anchor Slider by Cedric Dugas ***
*** Http://www.position-absolute.com ***
Never have an anchor jumping your content, slide it.
Don't forget to put an id to your anchor !
You can use and modify this script for any project you want, but please leave this comment as credit.
*****/
$(document).ready(function() {
$("a.anchorLink").anchorAnimate()
});
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 1100
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = $(caller).attr("href")
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}
|
JavaScript
|
$(document).ready(function() {
$('#home-slide').cycle('fade');
});
|
JavaScript
|
/*******
*** Anchor Slider by Cedric Dugas ***
*** Http://www.position-absolute.com ***
Never have an anchor jumping your content, slide it.
Don't forget to put an id to your anchor !
You can use and modify this script for any project you want, but please leave this comment as credit.
*****/
$(document).ready(function() {
$("a.anchorLink").anchorAnimate()
});
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 1100
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = $(caller).attr("href")
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}
|
JavaScript
|
function getVal(id) {
return $("#" + id).val();
}
function getAttr(id, attr) {
return $("#" + id).attr(attr)
}
/**//************************************************************************
| 函数名称: setCookie |
| 函数功能: 设置cookie函数 |
| 入口参数: name:cookie名称;value:cookie值 |
| 维护记录: Spark(创建) |
*************************************************************************/
function setCookie(name, value) {
var argv = setCookie.arguments;
var argc = setCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
if (expires != null) {
var LargeExpDate = new Date();
LargeExpDate.setTime(LargeExpDate.getTime()
+ (expires * 1000 * 3600 * 24));
}
document.cookie = name
+ "="
+ escape(value)
+ ((expires == null) ? "" : ("; expires=" + LargeExpDate
.toGMTString()));
}
/**//************************************************************************
| 函数名称: getCookie |
| 函数功能: 读取cookie函数 |
| 入口参数: Name:cookie名称 |
| 维护记录: Spark(创建) |
*************************************************************************/
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset)
if (end == -1)
end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
} else
return ""
}
}
/**//************************************************************************
| 函数名称: deleteCookie |
| 函数功能: 删除cookie函数 |
| 入口参数: Name:cookie名称 |
| 维护记录: Spark(创建) |
*************************************************************************/
function deleteCookie(name) {
var expdate = new Date();
expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
setCookie(name, "", expdate);
}
|
JavaScript
|
/**
*
*/
|
JavaScript
|
/**
*
*/
colors = Array("#ffb","#fbf","#bff","#6ff","#ff6","#f6f","#6ff");
color = 0;
$(document).ready(function() {
$(".component").hover(function() {
$("#"+$(this).children(".position").text()).addClass("myhover");
//$("#"+$(this).attr("value")).css("color","#fff");
},function() {
$("#"+$(this).children(".position").text()).removeClass("myhover");
});
$(".component").click(function() {
if($(this).hasClass("mystayhover")) {
$(this).removeClass("mystayhover");
text = $(this).children(".position").text();
rem = true;
$(".mystayhover").each(function() {
if($(this).children(".position").text() == text) rem = false;
});
if(rem) $("#"+$(this).children(".position").text()).removeClass("mystayhover");
}else {
$(this).addClass("mystayhover");
$("#"+$(this).children(".position").text()).addClass("mystayhover");
}
});
$(".box").hover(function() {
id = $(this).attr("id");
$(".position").each(function() {
if($(this).text() == id) {
$(this).parent().addClass("myhover");
}
});
},function() {
$(".position").each(function() {
if($(this).text() == id) {
$(this).parent().removeClass("myhover");
}
});
});
$(".box").click(function() {
if($(this).hasClass("mystayhover")) {
$(this).removeClass("mystayhover");
id = $(this).attr("id");
$(".position").each(function() {
if($(this).text() == id) {
$(this).parent().removeClass("mystayhover");
}
});
}else {
$(this).addClass("mystayhover");
id = $(this).attr("id");
$(".position").each(function() {
if($(this).text() == id) {
$(this).parent().addClass("mystayhover");
}
});
}
});
registNumOpera();
$(".box").dblclick(function() {
self.location = "./addcomp.php?position=" + $(this).text();
});
});
function registNumOpera() {
// TODO 添加数量增减支持
$(".comPlus").click(function() {
self = $(this);
$.post("function.php",{
id:$(this).parent().parent().attr("value"),
func:"addNum"
},function(data) {
self.parent().html(data + "<input type=\"button\" class=\"comPlus yage_button\" value=\"+\" /><input type=\"button\" class=\"yage_button comMinus\" value=\"-\" />");
registNumOpera();
});
});
$(".comMinus").click(function() {
self = $(this);
$.post("function.php",{
id:$(this).parent().parent().attr("value"),
func:"minNum"
},function(data) {
if(data == 0) {
self.parent().parent().remove();
}
else {
self.parent().html(data + "<input type=\"button\" class=\"comPlus yage_button\" value=\"+\" /><input type=\"button\" class=\"yage_button comMinus\" value=\"-\" />");
registNumOpera();
}
});
});
}
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
prop = {
header, // String
property, // String
events, //
type, // checkbox, select, input.type, button
extra // depend on type
}
*/
function List(config) {
this.config = config;
this.props = config.props;
this.main = config.main;
this.selectedLine = -2;
this.lines = [];
if (!config.getItems) {
config.getItems = function() {
return config.items;
}
}
if (!config.getItemProp) {
config.getItemProp = function(id, prop) {
return config.getItem(id)[prop];
}
}
if (!config.setItemProp) {
config.setItemProp = function(id, prop, value) {
config.getItem(id)[prop] = value;
}
}
if (!config.getItem) {
config.getItem = function(id) {
return config.getItems()[id];
}
}
if (!config.move) {
config.move = function(a, b) {
if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) {
var list = config.getItems();
var tmp = list[a];
// remove a
list.splice(a, 1);
// insert b
list.splice(b, 0, tmp);
}
}
};
if (!config.insert) {
config.insert = function(id, newItem) {
config.getItems().splice(id, 0, newItem);
}
}
if (!config.remove) {
config.remove = function(a) {
config.move(a, config.count() - 1);
config.getItems().pop();
}
}
if (!config.validate) {
config.validate = function() {return true;};
}
if (!config.count) {
config.count = function() {
return config.getItems().length;
}
}
if (!config.patch) {
config.patch = function(id, newVal) {
for (var name in newVal) {
config.setItemProp(id, name, newVal[name]);
}
}
}
if (!config.defaultValue) {
config.defaultValue = {};
}
config.main.addClass('list');
}
List.ids = {
noline: -1,
};
List.types = {};
List.prototype = {
init: function() {
with (this) {
if (this.inited) {
return;
}
this.inited = true;
this.headergroup = $('<div class="headers"></div>');
for (var i = 0; i < props.length; ++i) {
var header = $('<div class="header"></div>').
attr('property', props[i].property).html(props[i].header);
headergroup.append(header);
}
this.scrolls = $('<div>').addClass('listscroll');
this.contents = $('<div class="listitems"></div>').appendTo(scrolls);
scrolls.scroll(function() {
headergroup.css('left', -(scrolls.scrollLeft()) + 'px');
});
contents.click(function(e) {
if (e.target == contents[0]) {
selectLine(List.ids.noline);
}
});
$(main).append(headergroup).append(scrolls);
var height = this.main.height() - this.headergroup.outerHeight();
this.scrolls.height(height);
load();
selectLine(List.ids.noline);
}
},
editNewLine: function() {
this.startEdit(this.lines[this.lines.length - 1]);
},
updatePropDisplay : function(line, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var id = Number(line.attr('row'));
if (id == this.config.count()) {
var value = this.config.defaultValue[name];
if (value) {
ctrl.value = value;
}
obj.trigger('createNew');
} else {
ctrl.value = this.config.getItemProp(id, name);
obj.trigger('update');
}
},
updateLine: function(line) {
for (var i = 0; i < this.props.length; ++i) {
this.updatePropDisplay(line, this.props[i]);
}
if (Number(line.attr('row')) < this.config.count()) {
line.trigger('update');
} else {
line.addClass('newline');
}
},
createLine: function() {
with (this) {
var line = $('<div></div>').addClass('itemline');
var inner = $('<div>');
line.append(inner);
// create input boxes
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
var ctrl = $('<div></div>').attr('property', prop.property)
.addClass('listvalue').attr('tabindex', -1);
var valueobj = new List.types[prop.type](ctrl, prop);
var data = {list: this, line: line, prop: prop};
for (var e in prop.events) {
ctrl.bind(e, data, prop.events[e]);
}
ctrl.bind('change', function(e) {
validate(line);
return true;
});
ctrl.bind('keyup', function(e) {
if (e.keyCode == 27) {
cancelEdit(line);
}
});
ctrl.trigger('create');
inner.append(ctrl);
}
// Event listeners
line.click(function(e) {
startEdit(line);
});
line.focusin(function(e) {
startEdit(line);
});
line.focusout(function(e) {
finishEdit(line);
});
for (var e in this.config.lineEvents) {
line.bind(e, {list: this, line: line}, this.config.lineEvents[e]);
}
var list = this;
line.bind('updating', function() {
$(list).trigger('updating');
});
line.bind('updated', function() {
$(list).trigger('updated');
});
this.bindId(line, this.lines.length);
this.lines.push(line);
line.appendTo(this.contents);
return line;
}
},
refresh: function(lines) {
var all = false;
if (lines === undefined) {
all = true;
lines = [];
}
for (var i = this.lines.length; i <= this.config.count(); ++i) {
var line = this.createLine();
lines.push(i);
}
while (this.lines.length > this.config.count() + 1) {
this.lines.pop().remove();
}
$('.newline', this.contents).removeClass('newline');
this.lines[this.lines.length - 1].addClass('newline');
if (all) {
for (var i = 0; i < this.lines.length; ++i) {
this.updateLine(this.lines[i]);
}
} else {
for (var i = 0; i < lines.length; ++i) {
this.updateLine(this.lines[lines[i]]);
}
}
},
load: function() {
this.contents.empty();
this.lines = [];
this.refresh();
},
bindId: function(line, id) {
line.attr('row', id);
},
getLineNewValue: function(line) {
var ret = {};
for (var i = 0; i < this.props.length; ++i) {
this.getPropValue(line, ret, this.props[i]);
}
return ret;
},
getPropValue: function(line, item, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var value = ctrl.value;
if (value !== undefined) {
item[name] = value;
}
return value;
},
startEdit: function(line) {
if (line.hasClass('editing')) {
return;
}
line.addClass('editing');
this.showLine(line);
this.selectLine(line);
var list = this;
setTimeout(function() {
if (!line[0].contains(document.activeElement)) {
$('.valinput', line).first().focus();
}
list.validate(line);
}, 50);
},
finishEdit: function(line) {
var list = this;
function doFinishEdit() {
with(list) {
if (line[0].contains(document.activeElement)) {
return;
}
var valid = isValid(line);
if (valid) {
var id = Number(line.attr('row'));
var newval = getLineNewValue(line);
if (line.hasClass('newline')) {
$(list).trigger('updating');
if(!config.insert(id, newval)) {
line.removeClass('newline');
list.selectLine(line);
$(list).trigger('add', id);
addNewLine();
}
} else {
line.trigger('updating');
config.patch(id, newval);
}
line.trigger('updated');
}
cancelEdit(line);
}
};
setTimeout(doFinishEdit, 50);
},
cancelEdit: function(line) {
line.removeClass('editing');
line.removeClass('error');
var id = Number(line.attr('row'));
if (id == this.config.count() && this.selectedLine == id) {
this.selectedLine = List.ids.noline;
}
this.updateLine(line);
},
addNewLine: function() {
with(this) {
var line = $('.newline', contents);
if (!line.length) {
line = createLine().addClass('newline');
}
return line;
}
},
isValid: function(line) {
var id = Number(line.attr('row'));
var obj = this.getLineNewValue(line);
return valid = this.config.validate(id, obj);
},
validate: function(line) {
if (this.isValid(line)) {
line.removeClass('error');
} else {
line.addClass('error');
}
},
move: function(a, b, keepSelect) {
var len = this.config.count();
if (a == b || a < 0 || b < 0 || a >= len || b >= len) {
return;
}
this.config.move(a, b);
for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) {
this.updateLine(this.getLine(i));
}
if (keepSelect) {
if (this.selectedLine == a) {
this.selectLine(b);
} else if (this.selectedLine == b) {
this.selectLine(a);
}
}
},
getLine: function(id) {
if (id < 0 || id >= this.lines.length) {
return null;
}
return this.lines[id];
},
remove: function(id) {
id = Number(id);
if (id < 0 || id >= this.config.count()) {
return;
}
$(this).trigger('updating');
var len = this.lines.length;
this.getLine(id).trigger('removing');
if (this.config.remove(id)) {
return;
}
this.getLine(len - 1).remove();
this.lines.pop();
for (var i = id; i < len - 1; ++i) {
this.updateLine(this.getLine(i));
}
if (id >= len - 2) {
this.selectLine(id);
} else {
this.selectLine(List.ids.noline);
}
$(this).trigger('updated');
},
selectLine: function(id) {
var line = id;
if (typeof id == "number") {
line = this.getLine(id);
} else {
id = Number(line.attr('row'));
}
// Can't select the new line.
if (line && line.hasClass('newline')) {
line = null;
id = List.ids.noline;
}
if (this.selectedLine == id) {
return;
}
var oldline = this.getLine(this.selectedLine);
if (oldline) {
this.cancelEdit(oldline);
oldline.removeClass('selected');
oldline.trigger('deselect');
this.selectedLine = List.ids.noline;
}
this.selectedLine = id;
if (line != null) {
line.addClass('selected');
line.trigger('select');
this.showLine(line);
}
$(this).trigger('select');
},
showLine: function(line) {
var showtop = this.scrolls.scrollTop();
var showbottom = showtop + this.scrolls.height();
var top = line.offset().top - this.contents.offset().top;
// Include the scroll bar
var bottom = top + line.height() + 20;
if (top < showtop) {
// show at top
this.scrolls.scrollTop(top);
} else if (bottom > showbottom) {
// show at bottom
this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height()));
}
}
};
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var baseDir = '/setting/';
var rules = [];
var scripts = [];
var issues = [];
var dirty = false;
function stringHash(str) {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
ch = str.charCodeAt(i);
hash = ((hash << 5) - hash) + ch;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
function setScriptAutoComplete(e) {
var last = /[^\s]*$/;
var obj = $('input', e.target);
$(obj).bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
scriptItems, last.exec(request.term)[0]));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
this.value = this.value.replace(last, ui.item.value);
return false;
}
});
}
var ruleProps = [ {
header: "Identifier",
property: "identifier",
type: "input"
}, {
header: "Name",
property: "title",
type: "input"
}, {
header: "Mode",
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: "WildChar"},
{value: "regex", text: "RegEx"},
{value: "clsid", text: "CLSID"}
]
}, {
header: "Pattern",
property: "value",
type: "input"
}, {
header: "Keyword",
property: "keyword",
type: "input"
}, {
header: "testURL",
property: "testUrl",
type: "input"
}, {
header: "UserAgent",
property: "userAgent",
type: "select",
option: "static",
options: [
{value: "", text: "Chrome"},
{value: "ie9", text: "MSIE9"},
{value: "ie8", text: "MSIE8"},
{value: "ie7", text: "MSIE7"},
{value: "ff7win", text: "Firefox 7 Windows"},
{value: "ff7mac", text: "Firefox 7 Mac"},
{value: "ip5", text: "iPhone"},
{value: "ipad5", text: "iPad"}
]
}, {
header: "Helper Script",
property: "script",
type: "input",
events: {
create: setScriptAutoComplete
}
}];
var currentScript = -1;
function showScript(id) {
var url = baseDir + scripts[id].url;
currentScript = id;
$(scriptEditor).val('');
$.ajax(url, {
success: function(value) {
origScript = value;
$(scriptEditor).val(value);
}
});
$('#scriptDialog').dialog('open');
}
function saveToFile(file, value) {
$.ajax(baseDir + 'upload.php', {
type: "POST",
data: {
file: file,
data: value
}
});
}
var checksumComputing = 0;
function computeScriptChecksum(id) {
scripts[id].checksum = "computing";
++checksumComputing;
scriptList.updateLine(scriptList.lines[id]);
$.ajax(baseDir + scripts[id].url, {
complete: function() {
--checksumComputing;
},
dataType: "text",
success: function(value, status, xhr) {
scripts[id].checksum = stringHash(value);
scriptList.updateLine(scriptList.lines[id]);
}
});
}
var origScript;
function saveScript(id) {
var value = $('#scriptEditor').val();
if (value == origScript) {
return;
}
var file = scripts[id].url;
++scripts[id].version;
scriptList.updateLine(scriptList.getLine(id));
saveToFile(file, value);
dirty = true;
}
var scriptProps = [{
property: "identifier",
header: "Identifier",
type: "input"
}, {
property: "url",
header: "URL",
type: "input"
}, {
property: "version",
header: "Version",
type: "input"
}, {
property: "context",
header: "Context",
type: "select",
option: "static",
options: [
{value: "page", text: "Page"},
{value: "extension", text: "Extension"}
]
}, {
property: "show",
header: "Show",
type: "button",
events: {
create: function(e) {
$('button', this).text('Show');
},
command: function(e) {
showScript(Number(e.data.line.attr('row')), true);
}
}
}, {
property: "checksum",
header: "checksum",
type: "input",
events: {
"create": function(e) {
$(this).addClass('readonly');
}
}
}, {
property: "compute",
header: "Checksum",
type: "button",
events: {
create: function(e) {
$('button', this).text('Recompute');
},
command: function(e) {
computeScriptChecksum(Number(e.data.line.attr('row')));
}
}
}];
var issueProps = [{
header: "Identifier",
property: "identifier",
type: "input"
}, {
header: "Mode",
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: "WildChar"},
{value: "regex", text: "RegEx"},
{value: "clsid", text: "CLSID"}
]
}, {
header: "Pattern",
property: "value",
type: "input"
}, {
header: "Description",
property: "description",
type: "input"
}, {
header: "IssueId",
property: "issueId",
type: "input"
}, {
header: "url",
property: "url",
type: "input"
}];
// The JSON formatter is from http://joncom.be/code/javascript-json-formatter/
function FormatJSON(oData, sIndent) {
function RealTypeOf(v) {
if (typeof(v) == "object") {
if (v === null) return "null";
if (v.constructor == Array) return "array";
if (v.constructor == Date) return "date";
if (v.constructor == RegExp) return "regex";
return "object";
}
return typeof(v);
}
if (arguments.length < 2) {
var sIndent = "";
}
var sIndentStyle = " ";
var sDataType = RealTypeOf(oData);
// open object
if (sDataType == "array") {
if (oData.length == 0) {
return "[]";
}
var sHTML = "[";
} else {
var iCount = 0;
$.each(oData, function() {
iCount++;
return;
});
if (iCount == 0) { // object is empty
return "{}";
}
var sHTML = "{";
}
// loop through items
var iCount = 0;
$.each(oData, function(sKey, vValue) {
if (iCount > 0) {
sHTML += ",";
}
if (sDataType == "array") {
sHTML += ("\n" + sIndent + sIndentStyle);
} else {
sHTML += ("\n" + sIndent + sIndentStyle + "\"" + sKey + "\"" + ": ");
}
// display relevant data type
switch (RealTypeOf(vValue)) {
case "array":
case "object":
sHTML += FormatJSON(vValue, (sIndent + sIndentStyle));
break;
case "boolean":
case "number":
sHTML += vValue.toString();
break;
case "null":
sHTML += "null";
break;
case "string":
sHTML += ("\"" + vValue + "\"");
break;
default:
sHTML += JSON.stringify(vValue);
}
// loop
iCount++;
});
// close object
if (sDataType == "array") {
sHTML += ("\n" + sIndent + "]");
} else {
sHTML += ("\n" + sIndent + "}");
}
// return
return sHTML;
}
function loadRules(value) {
rules = [];
for (var i in value) {
rules.push(value[i]);
}
ruleList.refresh();
freezeIdentifier(ruleList);
}
function loadIssues(value) {
issues = [];
for (var i in value) {
issues.push(value[i]);
}
issueList.refresh();
freezeIdentifier(issueList);
}
function loadScripts(value) {
scripts = [];
for (var i in value) {
scripts.push(value[i]);
}
scriptList.refresh();
freezeIdentifier(scriptList);
updateScriptItems();
}
function serialize(list) {
var obj = {};
for (var i = 0; i < list.length; ++i) {
obj[list[i].identifier] = list[i];
}
return FormatJSON(obj);
}
function save() {
saveToFile('setting.json', serialize(rules));
saveToFile('scripts.json', serialize(scripts));
saveToFile('issues.json', serialize(issues));
dirty= false;
freezeIdentifier(ruleList);
freezeIdentifier(scriptList);
}
function reload() {
$.ajax(baseDir + 'setting.json', {
success: loadRules
});
$.ajax(baseDir + 'scripts.json', {
success: loadScripts
});
$.ajax(baseDir + 'issues.json', {
success: loadIssues
});
dirty = false;
}
function freezeIdentifier(list) {
$('.itemline:not(.newline) div[property=identifier]', list.contents)
.addClass('readonly');
}
var scriptList, ruleList, issueList;
var scriptItems = [];
function updateScriptItems() {
scriptItems = [];
for (var i = 0; i < scripts.length; ++i) {
scriptItems.push(scripts[i].identifier);
}
}
$(document).ready(function() {
window.onbeforeunload=function() {
if (dirty) {
return 'Page not saved. Continue?';
}
}
$('#addRule').click(function() {
ruleList.editNewLine();
}).button();
$('#deleteRule').click(function() {
ruleList.remove(ruleList.selectedLine);
}).button();
$('#addScript').click(function() {
scriptList.editNewLine();
}).button();
$('#deleteScript').click(function() {
scriptList.remove(scriptList.selectedLine);
}).button();
$('#compute_checkSum').click(function() {
for (var i = 0; i < scripts.length; ++i) {
computeScriptChecksum(i);
}
}).button();
$('#addIssue').click(function() {
issueList.editNewLine();
}).button();
$('#deleteIssue').click(function() {
issueList.remove(issueList.selectedLine);
}).button();
$('.doSave').each(function() {
$(this).click(save).button();
});
$('#tabs').tabs();
$('#scriptDialog').dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
"Save": function() {
saveScript(currentScript);
$(this).dialog('close');
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
$.ajaxSetup({
cache: false
});
scriptList = new List({
props: scriptProps,
main: $('#scriptTable'),
getItems: function() {return scripts;}
});
$(scriptList).bind('updated', function() {
dirty = true;
updateScriptItems();
});
scriptList.init();
ruleList = new List({
props: ruleProps,
main: $('#ruleTable'),
getItems: function() {return rules;}
});
ruleList.init();
$(ruleList).bind('updated', function() {
dirty = true;
});
issueList = new List({
props: issueProps,
main: $('#issueTable'),
getItems: function() {return issues;}
});
issueList.init();
$(issueList).bind('updated', function() {
dirty = true;
});
reload();
});
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
List.types.input = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input></input>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
this.input.focus(function(e) {
input.select();
});
this.input.keypress(function(e) {
p.trigger('change');
});
this.input.keyup(function(e) {
p.trigger('change');
});
this.input.change(function(e) {
p.trigger('change');
});
p.append(this.input).append(this.label);
};
List.types.input.prototype.__defineSetter__('value', function(val) {
this.input.val(val);
this.label.text(val);
});
List.types.input.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<select></select>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
if (prop.option == 'static') {
this.loadOptions(prop.options);
}
var select = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
select.value = select.lastval;
} else {
p.trigger('change');
}
});
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
p.append(this.input).append(this.label);
};
List.types.select.prototype.loadOptions = function(options) {
this.options = options;
this.mapping = {};
this.input.html("");
for (var i = 0; i < options.length; ++i) {
this.mapping[options[i].value] = options[i].text;
var o = $('<option></option>').val(options[i].value).text(options[i].text)
this.input.append(o);
}
}
List.types.select.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input.val(val);
this.label.text(this.mapping[val]);
});
List.types.checkbox = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input type="checkbox">').addClass('valcheck');
var box = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
box.value = box.lastval;
} else {
p.trigger('change');
}
});
p.append(this.input);
};
List.types.checkbox.prototype.__defineGetter__('value', function() {
return this.input[0].checked;
});
List.types.checkbox.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input[0].checked = val;
});
List.types.button = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<button>');
if (prop.caption) {
input.text(prop.caption);
}
input.click(function(e) {
p.trigger('command');
return false;
});
p.append(this.input);
};
List.types.button.prototype.__defineGetter__('value', function() {
return undefined;
});
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabStatus = {};
var version;
var default_id = "lgllffgicojgllpmdbemgglaponefajn";
var debug = chrome.i18n.getMessage("@@extension_id") != default_id;
var firstRun = false;
var firstUpgrade = false;
var blackList = [
/^https?:\/\/[^\/]*\.taobao\.com\/.*/i,
/^https?:\/\/[^\/]*\.alipay\.com\/.*/i
];
var MAX_LOG = 400;
(function getVersion() {
$.ajax('manifest.json', {
success: function (v){
v = JSON.parse(v);
version = v.version;
trackVersion(version);
}
});
})();
function startListener() {
chrome.extension.onConnect.addListener(function(port) {
if (!port.sender.tab) {
console.error('Not connect from tab');
return;
}
initPort(port);
});
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (!sender.tab) {
console.error('Request from non-tab');
} else if (request.command == 'Configuration') {
var config = setting.getPageConfig(request.href);
sendResponse(config);
if (request.top) {
resetTabStatus(sender.tab.id);
var dummy = {href: request.href, clsid: 'NULL'};
if (!config.pageRule &&
setting.getFirstMatchedRule(
dummy, setting.defaultRules)) {
detectControl(dummy, sender.tab.id, 0);
}
}
//notifyUser(request, sender, config);
} else {
sendResponse({});
}
}
);
}
var greenIcon = chrome.extension.getURL('icon16.png');
var grayIcon = chrome.extension.getURL('icon16-gray.png');
var errorIcon = chrome.extension.getURL('icon16-error.png');
var responseCommands = {};
function resetTabStatus(tabId) {
tabStatus[tabId] = {
count: 0,
actived: 0,
error: 0,
issueId: null,
logs: {"0":[]},
objs: {"0":[]},
frames: 1,
tracking: false
};
}
function initPort(port) {
var tabId = port.sender.tab.id;
if (!(tabId in tabStatus)) {
resetTabStatus(tabId);
}
var status = tabStatus[tabId];
var frameId = tabStatus[tabId].frames++;
status.logs[frameId] = [];
status.objs[frameId] = [];
port.onMessage.addListener(function(request) {
var resp = responseCommands[request.command];
if (resp) {
delete request.command;
resp(request, tabId, frameId);
} else {
console.error("Unknown command " + request.command);
}
});
port.onDisconnect.addListener(function() {
for (var i = 0; i < status.objs[frameId].length; ++i) {
countTabObject(status, status.objs[frameId][i], -1);
}
showTabStatus(tabId);
if (status.tracking) {
if (status.count == 0) {
// Open the log page.
window.open('log.html?tabid=' + tabId);
status.tracking = false;
}
} else {
// Clean up.
status.logs[frameId] = [];
status.objs[frameId] = [];
}
});
}
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
if (tabStatus[tabId]) {
tabStatus[tabId].removed = true;
var TIMEOUT = 1000 * 60 * 5;
// clean up after 5 mins.
window.setTimeout(function() {
delete tabStatus[tabId];
}, TIMEOUT);
}
});
function countTabObject(status, info, delta) {
for (var i = 0; i < blackList.length; ++i) {
if (info.href.match(blackList[i])) {
return;
}
}
if (info.actived) {
status.actived += delta;
if (delta > 0) {
trackUse(info.rule);
}
} else if (delta > 0) {
trackNotUse(info.href);
}
status.count += delta;
var issue = setting.getMatchedIssue(info);
if (issue) {
status.error += delta;
status.issueId = issue.identifier;
if (delta > 0) {
trackIssue(issue);
}
}
}
function showTabStatus(tabId) {
if (tabStatus[tabId].removed) {
return;
}
var status = tabStatus[tabId];
var title = "";
if (status.count == 0) {
chrome.pageAction.hide(tabId);
return;
} else {
chrome.pageAction.show(tabId);
}
chrome.pageAction.setPopup({
tabId: tabId,
popup: 'popup.html?tabid=' + tabId
});
if (status.count == 0) {
// Do nothing..
} else if (status.error != 0) {
chrome.pageAction.setIcon({
tabId: tabId,
path: errorIcon
});
title = $$('status_error');
} else if (status.count != status.actived) {
// Disabled..
chrome.pageAction.setIcon({
tabId: tabId,
path: grayIcon
});
title = $$('status_disabled');
} else {
// OK
chrome.pageAction.setIcon({
tabId: tabId,
path: greenIcon
});
title = $$('status_ok');
}
chrome.pageAction.setTitle({
tabId: tabId,
title: title
});
}
function detectControl(request, tabId, frameId) {
var status = tabStatus[tabId];
if (frameId != 0 && status.objs[0].length) {
// Remove the item to identify the page.
countTabObject(status, status.objs[0][0], -1);
status.objs[0] = [];
}
status.objs[frameId].push(request);
countTabObject(status, request, 1);
showTabStatus(tabId);
}
responseCommands.DetectControl = detectControl;
responseCommands.Log = function(request, tabId, frameId) {
var logs = tabStatus[tabId].logs[frameId];
if (logs.length < MAX_LOG) {
logs.push(request.message);
} else if (logs.length == MAX_LOG) {
logs.push('More logs clipped');
}
}
function generateLogFile(tabId) {
var status = tabStatus[tabId];
if (!status) {
return '';
}
var ret = '';
ret += 'UserAgent: ' + navigator.userAgent + '\n';
ret += 'Extension version: ' + version + '\n';
ret += '\n';
for (var i = 0; i < status.frames; ++i) {
if (i) {
ret += '\n\n';
}
ret += '------------ Frame ' + (i + 1) + ' ------------------\n';
ret += 'Objects:\n';
for (var j = 0; j < status.objs[i].length; ++j) {
ret += JSON.stringify(status.objs[i][j]) + '\n';
}
ret += '\n';
ret += 'Log:\n';
for (var j = 0; j < status.logs[i].length; ++j) {
ret += status.logs[i][j] + '\n';
}
}
return ret;
}
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
// Permission for experimental not given.
var handler = chrome.webRequest;
function onBeforeSendHeaders(details) {
var rule = setting.getFirstMatchedRule(
{href: details.url}, setting.cache.userAgent);
if (!rule || !(rule.userAgent in agents)) {
return {};
}
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (details.requestHeaders[i].name == 'User-Agent') {
details.requestHeaders[i].value = agents[rule.userAgent];
break;
}
}
return {requestHeaders: details.requestHeaders};
}
function registerRequestListener() {
if (!handler) {
return;
}
var filters = {
urls: ["<all_urls>"],
types: ["main_frame", "sub_frame", "xmlhttprequest"]
};
try{
handler.onBeforeSendHeaders.addListener(
onBeforeSendHeaders, filters, ["requestHeaders", "blocking"]);
} catch (e) {
console.log('Your browser doesn\'t support webRequest');
}
}
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
Rule: {
identifier: an unique identifier
title: description
type: Can be "wild", "regex", "clsid"
value: pattern, correspond to type
userAgent: the useragent value. See var "agents" for options.
script: script to inject. Separated by spaces
}
Order: {
status: enabled / disabled / custom
position: default / custom
identifier: identifier of rule
}
Issue: {
type: Can be "wild", "regex", "clsid"
value: pattern, correspond to type
description: The description of this issue
issueId: Issue ID on issue tracking page
url: optional, support page for issue tracking.
Use code.google.com if omitted.
}
ServerSide:
ActiveXConfig: {
version: version
rules: object of user-defined rules, propertied by identifiers
defaultRules: ojbect of default rules
scripts: mapping of workaround scripts, by identifiers. metadatas
localScripts: metadatas of local scripts.
order: the order of rules
cache: to accerlerate processing
issues: The bugs/unsuppoted sites that we have accepted.
misc:{
lastUpdate: last timestamp of updating
logEnabled: log
tracking: Allow GaS tracking.
verbose: verbose level of logging
}
}
PageSide:
ActiveXConfig: {
pageSide: Flag of pageside.
pageScript: Helper script to execute on context of page
extScript: Helper script to execute on context of extension
pageRule: If page is matched.
clsidRules: If page is not matched or disabled. valid CLSID rules
logEnabled: log
verbose: verbose level of logging
}
*/
// Update per 5 hours.
var DEFAULT_INTERVAL = 1000 * 3600 * 5;
function ActiveXConfig(input)
{
var settings;
if (input === undefined) {
var defaultSetting = {
version: 3,
rules: {},
defaultRules: {},
scripts: {},
localScripts: {},
order: [],
notify: [],
issues: [],
misc: {
lastUpdate: 0,
logEnabled: false,
tracking: true,
verbose: 3
}
};
input = defaultSetting;
}
if (input.version == '3') {
settings = input;
settings.__proto__ = ActiveXConfig.prototype;
} else {
settings = ActiveXConfig.convertVersion(input);
}
settings.updateCache();
return settings;
}
var settingKey = 'setting';
var scriptPrefix = 'script_';
clsidPattern = /[^0-9A-F][0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}[^0-9A-F]/;
var agents = {
ie9: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)",
ie8: "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0)",
ie7: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64;)",
ff7win: "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1",
ip5: "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3",
ipad5: "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3"
};
function stringHash(str) {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
ch = str.charCodeAt(i);
hash = ((hash << 5) - hash) + ch;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
function getUserAgent(key) {
// This script is always run under sandbox, so useragent should be always
// correct.
if (key == '' || !(key in agents)) {
return "";
}
var current = navigator.userAgent;
var wow64 = current.indexOf('WOW64') >= 0;
var value = agents[key];
if (!wow64) {
value = value.replace(' WOW64;', '');
}
return value;
}
ActiveXConfig.convertVersion = function(setting) {
if (setting.version == 3) {
return setting;
} else if (setting.version == 2) {
function parsePattern(pattern) {
pattern = pattern.trim();
var title = pattern.match(/###(.*)/);
if (title != null) {
return {
pattern: pattern.match(/(.*)###/)[1].trim(),
title: title[1].trim()
}
} else {
return {
pattern: pattern,
title: "Rule"
}
}
}
var ret = new ActiveXConfig();
if (setting.logEnabled) {
ret.misc.logEnabled = true;
}
var urls = setting.url_plain.split('\n');
for (var i = 0; i < urls.length; ++i) {
var rule = ret.createRule();
var pattern = parsePattern(urls[i]);
rule.title = pattern.title;
var url = pattern.pattern;
if (url.substr(0, 2) == 'r/') {
rule.type = 'regex';
rule.value = url.substr(2);
} else {
rule.type == 'wild';
rule.value = url;
}
ret.addCustomRule(rule, 'convert');
}
var clsids = setting.trust_clsids.split('\n');
for (var i = 0; i < clsids.length; ++i) {
var rule = ret.createRule();
rule.type = 'clsid';
var pattern = parsePattern(clsids[i]);
rule.title = pattern.title;
rule.value = pattern.pattern;
ret.addCustomRule(rule, 'convert');
}
firstUpgrade = true;
return ret;
}
}
ActiveXConfig.prototype = {
// Only used for user-scripts
shouldEnable: function(object) {
if (this.pageRule) {
return this.pageRule;
}
var clsidRule = this.getFirstMatchedRule(object, this.clsidRules);
if (clsidRule) {
return clsidRule;
} else {
return null;
}
},
createRule: function() {
return {
title: "Rule",
type: "wild",
value: "",
userAgent: "",
scriptItems: "",
};
},
addCustomRule: function(newItem, auto) {
if (!this.validateRule(newItem)) {
return;
}
var identifier = this.createIdentifier();
newItem.identifier = identifier;
this.rules[identifier] = newItem;
this.order.push({
status: 'custom',
position: 'custom',
identifier: identifier
});
this.update()
trackAddCustomRule(newItem, auto);
},
updateDefaultRules: function(newRules) {
var deleteAll = false, ruleToDelete = {};
if (typeof this.defaultRules != 'object') {
// There might be some errors!
// Clear all defaultRules
console.log('Corrupted default rules, reload all');
deleteAll = true;
this.defaultRules = {};
} else {
for (var i in this.defaultRules) {
if (!(i in newRules)) {
console.log('Remove rule ' + i);
ruleToDelete[i] = true;
delete this.defaultRules[i];
}
}
}
var newOrder = [];
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].position == 'custom' ||
(!deleteAll && !ruleToDelete[this.order[i].identifier])) {
newOrder.push(this.order[i]);
}
}
this.order = newOrder;
var position = 0;
for (var i in newRules) {
if (!(i in this.defaultRules)) {
this.addDefaultRule(newRules[i], position++);
}
this.defaultRules[i] = newRules[i];
}
},
updateConfig: function(session) {
session.startUpdate();
console.log('Start updating');
var updated = {
issues: false,
setting: false,
scripts: false
};
var setting = this;
session.updateFile({
url: 'setting.json',
dataType: "json",
success: function(nv, status, xhr) {
console.log('Update default rules');
updated.setting = true;
setting.updateDefaultRules(nv);
if (updated.setting && updated.scripts) {
setting.updateAllScripts(session);
}
setting.update();
}
});
session.updateFile({
url: 'scripts.json',
dataType: "json",
success: function(nv, status, xhr) {
updated.scripts = true;
console.log('Update scripts');
setting.scripts = nv;
if (updated.setting && updated.scripts) {
setting.updateAllScripts(session);
}
setting.update();
}
});
session.updateFile({
url: 'issues.json',
dataType: "json",
success: function(nv, status, xhr) {
console.log('Update issues');
setting.issues = nv;
setting.update();
}
});
},
getPageConfig: function(href) {
var ret = {};
ret.pageSide = true;
ret.version = this.version;
ret.verbose = this.misc.verbose;
ret.logEnabled = this.misc.logEnabled;
ret.pageRule = this.getFirstMatchedRule({href:href});
if (!ret.pageRule) {
ret.clsidRules = this.cache.clsidRules;
} else {
var script = this.getScripts(ret.pageRule.script);
ret.pageScript = script.page;
ret.extScript = script.extension;
}
return ret;
},
getFirstMatchedRule: function(object, rules) {
var useCache = false;
if (!rules) {
rules = this.cache.validRules;
useCache = true;
}
if (Array.isArray(rules)) {
for (var i = 0; i < rules.length; ++i) {
if (this.isRuleMatched(rules[i], object, useCache ? i : -1)) {
return rules[i];
}
}
} else {
for (var i in rules) {
if (this.isRuleMatched(rules[i], object)) {
return rules[i];
}
}
}
return null;
},
getMatchedIssue: function(filter) {
return this.getFirstMatchedRule(filter, this.issues);
},
activeRule: function(rule) {
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].identifier == rule.identifier) {
if (this.order[i].status == 'disabled') {
this.order[i].status = 'enabled';
trackAutoEnable(rule.identifier);
}
break;
}
}
this.update();
},
validateRule: function(rule) {
var ret = true;
try {
if (rule.type == 'wild') {
ret &= this.convertUrlWildCharToRegex(rule.value) != null;
} else if (rule.type == 'regex') {
ret &= rule.value != '';
var r = new RegExp(rule.value, 'i');
} else if (rule.type == 'clsid') {
var v = rule.value.toUpperCase();
if (!clsidPattern.test(v) || v.length > 55)
ret = false;
}
} catch (e) {
ret = false;
}
return ret;
},
isRuleMatched: function(rule, object, id) {
if (rule.type == "wild" || rule.type == "regex" ) {
var regex;
if (id >= 0) {
regex = this.cache.regex[id];
} else if (rule.type == 'wild') {
regex = this.convertUrlWildCharToRegex(rule.value);
} else if (rule.type == 'regex') {
regex = new RegExp('^' + rule.value + '$', 'i');
}
if (object.href && regex.test(object.href)) {
return true;
}
} else if (rule.type == "clsid") {
if (object.clsid) {
var v1 = clsidPattern.exec(rule.value.toUpperCase());
var v2 = clsidPattern.exec(object.clsid.toUpperCase());
if (v1 && v2 && v1[0] == v2[0]) {
return true;
}
}
}
return false;
},
getScripts: function(script) {
var ret = {
page: "",
extension: ""
};
if (!script) {
return ret;
}
var items = script.split(' ');
for (var i = 0; i < items.length; ++i) {
if (items[i] == '' || !this.scripts[items[i]]) {
continue;
}
var name = items[i];
var val = '// ';
val += items[i] + '\n';
val += this.getScriptContent(name);
val += '\n\n';
ret[this.scripts[name].context] += val;
}
return ret;
},
getScriptContent: function(scriptid) {
this.updateScript(scriptid, false);
var local = this.localScripts[scriptid];
if (!local) {
// The script not found.
return "";
}
var id = scriptPrefix + scriptid;
return localStorage[id];
},
updateAllScripts: function(session) {
console.log('updateAllScripts');
var scripts = {};
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].status == 'disabled') {
continue;
}
var rule = this.getItem(this.order[i]);
var script = rule.script;
if (!script) {
continue;
}
var items = script.split(' ');
for (var j = 0; j < items.length; ++j) {
scripts[items[j]] = true;
}
}
for (var i in scripts) {
this.updateScript(i, true, session);
}
},
updateScript: function(id, async, session) {
var remote = this.scripts[id];
var local = this.localScripts[id];
if (!remote || remote.updating) {
return;
}
if (local && local.checksum == remote.checksum) {
return;
}
remote.updating = true;
var setting = this;
var config = {
url: remote.url + "?hash=" + remote.checksum,
async: async,
complete: function() {
delete remote.updating;
},
error: function() {
console.log('Update script ' + remote.identifier + ' failed');
},
context: this,
success: function(nv, status, xhr) {
delete remote.updating;
var hash = stringHash(nv);
if (hash == remote.checksum) {
localStorage[scriptPrefix + id] = nv;
setting.localScripts[id] = remote;
setting.save();
console.log('script updated ', id);
} else {
var message = 'Hashcode mismatch!!';
message += ' script: ' + remote.identifier;
messsge += ' actual: ' + hash;
message += ' expected: ' + remote.checksum;
console.log(message);
}
},
// Don't evaluate this.
dataType: "text"
};
if (!UpdateSession && !session) {
// Should run update from background
throw "Not valid session";
}
if (session) {
session.updateFile(config);
} else {
UpdateSession.updateFile(config);
}
},
convertUrlWildCharToRegex: function(wild) {
try {
function escapeRegex(str, star) {
if (!star) star = '*';
var escapeChars = /([\.\\\/\?\{\}\+\[\]])/g;
return str.replace(escapeChars, "\\$1").replace('*', star);
}
wild = wild.toLowerCase();
if (wild == "<all_urls>") {
wild = "*://*/*";
}
var pattern = /^(.*?):\/\/(\*?[^\/\*]*)\/(.*)$/i;
// pattern: [all, scheme, host, page]
var parts = pattern.exec(wild);
if (parts == null) {
return null;
}
var scheme = parts[1];
var host = parts[2];
var page = parts[3];
var regex = '^' + escapeRegex(scheme, '[^:]*') + ':\\/\\/';
regex += escapeRegex(host, '[^\\/]*') + '/';
regex += escapeRegex(page, '.*');
return new RegExp(regex, 'i');
} catch (e) {
return null;
}
},
update: function() {
if (this.pageSide) {
return;
}
this.updateCache();
if (this.cache.listener) {
this.cache.listener.trigger('update');
}
this.save();
},
// Please remember to call update() after all works are done.
addDefaultRule: function(rule, position) {
console.log("Add new default rule: ", rule);
var custom = null;
if (rule.type == 'clsid') {
for (var i in this.rules) {
var info = {href: "not-a-URL-/", clsid: rule.value};
if (this.isRuleMatched(this.rules[i], info, -1)) {
custom = this.rules[i];
break;
}
}
} else if (rule.keyword && rule.testUrl) {
// Try to find matching custom rule
for (var i in this.rules) {
if (this.isRuleMatched(this.rules[i], {href: rule.testUrl}, -1)) {
if (this.rules[i].value.toLowerCase().indexOf(rule.keyword) != -1) {
custom = this.rules[i];
break;
}
}
}
}
var newStatus = 'disabled';
if (custom) {
console.log('Convert custom rule', custom, ' to default', rule);
// Found a custom rule which is similiar to this default rule.
newStatus = 'enabled';
// Remove old one
delete this.rules[custom.identifier];
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].identifier == custom.identifier) {
this.order.splice(i, 1);
break;
}
}
}
this.order.splice(position, 0, {
position: 'default',
status: newStatus,
identifier: rule.identifier
});
this.defaultRules[rule.identifier] = rule;
},
updateCache: function() {
if (this.pageSide) {
return;
}
this.cache = {
validRules: [],
regex: [],
clsidRules: [],
userAgentRules: [],
listener: (this.cache || {}).listener
}
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].status == 'custom' || this.order[i].status == 'enabled') {
var rule = this.getItem(this.order[i]);
var cacheId = this.cache.validRules.push(rule) - 1;
if (rule.type == 'clsid') {
this.cache.clsidRules.push(rule);
} else if (rule.type == 'wild') {
this.cache.regex[cacheId] =
this.convertUrlWildCharToRegex(rule.value);
} else if (rule.type == 'regex') {
this.cache.regex[cacheId] = new RegExp('^' + rule.value + '$', 'i');
}
if (rule.userAgent != '') {
this.cache.userAgentRules.push(rule);
}
}
}
},
save: function() {
if (location.protocol == "chrome-extension:") {
// Don't include cache in localStorage.
var cache = this.cache;
delete this.cache;
localStorage[settingKey] = JSON.stringify(this);
this.cache = cache;
}
},
createIdentifier: function() {
var base = 'custom_' + Date.now() + "_" + this.order.length + "_";
var ret;
do {
ret = base + Math.round(Math.random() * 65536);
} while (this.getItem(ret));
return ret;
},
getItem: function(item) {
var identifier = item;
if (typeof identifier != 'string') {
identifier = item.identifier;
}
if (identifier in this.rules) {
return this.rules[identifier];
} else {
return this.defaultRules[identifier];
}
}
};
function loadLocalSetting() {
var setting = undefined;
if (localStorage[settingKey]) {
try{
setting = JSON.parse(localStorage[settingKey]);
} catch (e){
setting = undefined;
}
}
if (!setting) {
firstRun = true;
}
return new ActiveXConfig(setting);
}
function clearSetting() {
localStorage.removeItem(settingKey);
setting = loadLocalSetting();
}
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
// Updater events:
// error
// updating
// complete
// success
// itemupdated
// progress
// properties:
// status
// lastUpdate
// Can be used for debugging.
var defaultServer = "http://settings.np-activex.googlecode.com/hg/";
var server=localStorage.updateServer || defaultServer;
function ObjectWithEvent() {
this._events = {};
};
ObjectWithEvent.prototype = {
bind: function(name, func) {
if (!Array.isArray(this._events[name])) {
this._events[name] = [];
}
this._events[name].push(func);
},
unbind: function(name, func) {
if (!Array.isArray(this._events[name])) {
return;
}
for (var i = 0; i < this._events[name].length; ++i) {
if (this._events[name][i] == func) {
this._events[name].splice(i, 1);
break;
}
}
},
trigger: function(name, argument) {
if (this._events[name]) {
var handlers = this._events[name];
for (var i = 0; i < handlers.length; ++i) {
handlers[i].apply(this, argument);
}
}
}
};
function UpdateSession() {
ObjectWithEvent.call(this);
this.jqXHRs = [];
this.reset();
}
UpdateSession.prototype = {
__proto__: ObjectWithEvent.prototype,
updateProgress: function() {
with(this) {
if (finished == total) {
if (error == 0) {
this.trigger('success');
}
this.trigger('complete');
} else {
this.trigger('progress');
}
}
},
updateFile: function(request) {
++this.total;
var session = this;
var jqXHR = UpdateSession.updateFile(request)
.fail(function(xhr, msg, thrown) {
++session.error;
session.trigger('error', [xhr, msg, thrown]);
session.updateProgress();
}).always(function() {
++session.finished;
session.updateProgress();
});
this.jqXHRs.push(jqXHR);
},
reset: function() {
this.finished = this.total = this.error = 0;
if (this.updateToken) {
clearTimeout(this.updateToken);
this.updateToken = undefined;
}
for (var i = 0; i < this.jqXHRs.length; ++i) {
//this.jqXHRs[i].abort();
}
this.jqXHRs = [];
},
startUpdate: function() {
this.reset();
this.trigger('updating');
}
};
UpdateSession.prototype.__defineGetter__('status', function() {
if (this.finished == this.total) {
return "stop";
} else {
return "updating";
}
});
UpdateSession.setUpdateInterval= function(callback, session, interval) {
session.bind('complete', function() {
session.updateToken = setTimeout(callback, interval);
});
callback();
};
UpdateSession.updateFile = function(request) {
if (request.url.match(/^.*:\/\//) == null) {
request.url = server + request.url;
}
trackUpdateFile(request.url);
return $.ajax(request);
};
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var FLASH_CLSID = '{d27cdb6e-ae6d-11cf-96b8-444553540000}';
var typeId = "application/x-itst-activex";
function executeScript(script) {
var scriptobj = document.createElement("script");
scriptobj.innerHTML = script;
var element = document.head || document.body ||
document.documentElement || document;
element.insertBefore(scriptobj, element.firstChild);
element.removeChild(scriptobj);
}
function checkParents(obj) {
var parent = obj;
var level = 0;
while (parent && parent.nodeType == 1) {
if (getComputedStyle(parent).display == 'none') {
var desp = obj.id + ' at level ' + level;
if (scriptConfig.none2block) {
parent.style.display = 'block';
parent.style.height = '0px';
parent.style.width = '0px';
log('Remove display:none for ' + desp);
} else {
log('Warning: Detected display:none for ' + desp);
}
}
parent = parent.parentNode;
++level;
}
}
function getLinkDest(url) {
if (typeof url != 'string') {
return url;
}
url = url.trim();
if (/^https?:\/\/.*/.exec(url)) {
return url;
}
if (url[0] == '/') {
if (url[1] == '/') {
return location.protocol + url;
} else {
return location.origin + url;
}
}
return location.href.replace(/\/[^\/]*$/, '/' + url);
}
var hostElement = null;
function enableobj(obj) {
// We can't use classid directly because it confuses the browser.
obj.setAttribute("clsid", getClsid(obj));
obj.removeAttribute("classid");
checkParents(obj);
var newObj = obj.cloneNode(true);
newObj.type = typeId;
// Remove all script nodes. They're executed.
var scripts = newObj.getElementsByTagName('script');
for (var i = 0; i < scripts.length; ++i) {
scripts[i].parentNode.removeChild(scripts[i]);
}
// Set codebase to full path.
var codebase = newObj.getAttribute('codebase');
if (codebase && codebase != '') {
newObj.setAttribute('codebase', getLinkDest(codebase));
}
newObj.activex_process = true;
obj.parentNode.insertBefore(newObj, obj);
obj.parentNode.removeChild(obj);
obj = newObj;
if (obj.id) {
var command = '';
if (obj.form && scriptConfig.formid) {
var form = obj.form.name;
command += "document.all." + form + "." + obj.id;
command + " = document.all." + obj.id + ';\n';
log('Set form[obj.id]: form: ' + form + ', object: ' + obj.id)
}
// Allow access by document.obj.id
if (obj.id && scriptConfig.documentid) {
command += "delete document." + obj.id + ";\n";
command += "document." + obj.id + '=' + obj.id + ';\n';
}
if (command) {
executeScript(command);
}
}
log("Enabled object, id: " + obj.id + " clsid: " + getClsid(obj));
return obj;
}
function getClsid(obj) {
if (obj.hasAttribute("clsid"))
return obj.getAttribute("clsid");
var clsid = obj.getAttribute("classid");
var compos = clsid.indexOf(":");
if (clsid.substring(0, compos).toLowerCase() != "clsid")
return;
clsid = clsid.substring(compos + 1);
return "{" + clsid + "}";
}
function notify(data) {
connect();
data.command = 'DetectControl';
port.postMessage(data);
}
function process(obj) {
if (obj.activex_process)
return;
if (onBeforeLoading.caller == enableobj ||
onBeforeLoading.caller == process ||
onBeforeLoading.caller == checkParents) {
log("Nested onBeforeLoading " + obj.id);
return;
}
if (obj.type == typeId) {
if (!config || !config.pageRule) {
// hack??? Deactive this object.
log("Deactive unexpected object " + obj.outerHTML);
return true;
}
log("Found objects created by client scripts");
notify({
href: location.href,
clsid: clsid,
actived: true,
rule: config.pageRule.identifier
});
obj.activex_process = true;
return;
}
if (obj.type != "" || !obj.hasAttribute("classid"))
return;
if (getClsid(obj).toLowerCase() == FLASH_CLSID) {
return;
}
if (config == null) {
// Delay the process of this object.
// Hope config will be load soon.
log('Pending object ', obj.id);
pendingObjects.push(obj);
return;
}
obj.activex_process = true;
connect();
var clsid = getClsid(obj);
var rule = config.shouldEnable({href: location.href, clsid:clsid});
if (rule) {
obj = enableobj(obj);
notify({
href: location.href,
clsid: clsid,
actived: true,
rule: rule.identifier
});
} else {
notify({href: location.href, clsid: clsid, actived: false});
}
}
function replaceDocument() {
var s = document.querySelectorAll('object[classid]');
log("found " + s.length + " object(s) on page");
for (var i = 0; i < s.length; ++i) {
process(s[i]);
}
};
function onBeforeLoading(event) {
var obj = event.target;
if (obj.nodeName == "OBJECT") {
log("BeforeLoading " + obj.id);
if (process(obj)) {
event.preventDefault();
}
}
}
function onError(event) {
var message = 'Error: ';
message += event.message;
message += ' at ';
message += event.filename;
message += ':';
message += event.lineno;
log(message);
}
function setUserAgent() {
if (!config.pageRule) {
return;
}
var agent = getUserAgent(config.pageRule.userAgent);
if (agent && agent != '') {
log("Set userAgent: " + config.pageRule.userAgent);
var js = "(function(agent) {";
js += "delete navigator.userAgent;";
js += "navigator.userAgent = agent;";
js += "delete navigator.appVersion;";
js += "navigator.appVersion = agent.substr(agent.indexOf('/') + 1);";
js += "if (agent.indexOf('MSIE') >= 0) {";
js += "delete navigator.appName;";
js += 'navigator.appName = "Microsoft Internet Explorer";}})("';
js += agent;
js += '")';
executeScript(js);
}
}
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var controlLogFName="__npactivex_log";
var controlLogEvent="__npactivex_log_event__";
var config = null;
var port = null;
var logs = [];
var scriptConfig = {
none2block: false,
formid: false,
documentid: false
};
function onControlLog(event) {
var message = event.data;
log(message);
}
window.addEventListener(controlLogEvent, onControlLog, false);
function connect() {
if (port) {
return;
}
port = chrome.extension.connect();
for (var i = 0; i < logs.length; ++i) {
port.postMessage({command: 'Log', message: logs[i]});
}
if (port && config) {
logs = undefined;
}
}
function log(message) {
var time = (new Date()).toLocaleTimeString();
message = time + ' ' + message;
if (config && config.logEnabled) {
console.log(message);
}
if (port) {
port.postMessage({command: 'Log', message: message});
}
if (!config || !port) {
logs.push(message);
}
}
log('PageURL: ' + location.href);
var pendingObjects = [];
function init(response) {
config = new ActiveXConfig(response);
if (config.logEnabled) {
for (var i = 0; i < logs.length; ++i) {
console.log(logs[i]);
}
}
eval(config.extScript);
executeScript(config.pageScript);
setUserAgent();
log('Page rule:' + JSON.stringify(config.pageRule));
for (var i = 0; i < pendingObjects.length; ++i) {
pendingObjects[i].activex_process = false;
process(pendingObjects[i]);
cacheConfig();
}
delete pendingObjects;
}
function cacheConfig() {
sessionStorage.activex_config_cache = JSON.stringify(config);
}
function loadConfig(response) {
if (config) {
config = new ActiveXConfig(response);
var cache = sessionStorage.activex_config_cache;
if (cache) {
cacheConfig();
}
} else {
init(response);
}
if (config.pageRule) {
cacheConfig();
}
}
function loadSessionConfig() {
var cache = sessionStorage.activex_config_cache;
if (cache) {
log('Loading config from session cache');
init(JSON.parse(cache));
}
}
loadSessionConfig();
chrome.extension.sendRequest(
{command:"Configuration", href:location.href, top: self == top}, loadConfig);
window.addEventListener("beforeload", onBeforeLoading, true);
window.addEventListener('error', onError, true);
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
prop = {
header, // String
property, // String
events, //
type, // checkbox, select, input.type, button
extra // depend on type
}
*/
function List(config) {
this.config = config;
this.props = config.props;
this.main = config.main;
this.selectedLine = -2;
this.lines = [];
if (!config.getItems) {
config.getItems = function() {
return config.items;
}
}
if (!config.getItemProp) {
config.getItemProp = function(id, prop) {
return config.getItem(id)[prop];
}
}
if (!config.setItemProp) {
config.setItemProp = function(id, prop, value) {
config.getItem(id)[prop] = value;
}
}
if (!config.getItem) {
config.getItem = function(id) {
return config.getItems()[id];
}
}
if (!config.move) {
config.move = function(a, b) {
if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) {
var list = config.getItems();
var tmp = list[a];
// remove a
list.splice(a, 1);
// insert b
list.splice(b, 0, tmp);
}
}
};
if (!config.insert) {
config.insert = function(id, newItem) {
config.getItems().splice(id, 0, newItem);
}
}
if (!config.remove) {
config.remove = function(a) {
config.move(a, config.count() - 1);
config.getItems().pop();
}
}
if (!config.validate) {
config.validate = function() {return true;};
}
if (!config.count) {
config.count = function() {
return config.getItems().length;
}
}
if (!config.patch) {
config.patch = function(id, newVal) {
for (var name in newVal) {
config.setItemProp(id, name, newVal[name]);
}
}
}
if (!config.defaultValue) {
config.defaultValue = {};
}
config.main.addClass('list');
}
List.ids = {
noline: -1,
};
List.types = {};
List.prototype = {
init: function() {
with (this) {
if (this.inited) {
return;
}
this.inited = true;
this.headergroup = $('<div class="headers"></div>');
for (var i = 0; i < props.length; ++i) {
var header = $('<div class="header"></div>').
attr('property', props[i].property).html(props[i].header);
headergroup.append(header);
}
this.scrolls = $('<div>').addClass('listscroll');
this.contents = $('<div class="listitems"></div>').appendTo(scrolls);
scrolls.scroll(function() {
headergroup.css('left', -(scrolls.scrollLeft()) + 'px');
});
contents.click(function(e) {
if (e.target == contents[0]) {
selectLine(List.ids.noline);
}
});
$(main).append(headergroup).append(scrolls);
var height = this.main.height() - this.headergroup.outerHeight();
this.scrolls.height(height);
load();
selectLine(List.ids.noline);
}
},
editNewLine: function() {
this.startEdit(this.lines[this.lines.length - 1]);
},
updatePropDisplay : function(line, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var id = Number(line.attr('row'));
if (id == this.config.count()) {
var value = this.config.defaultValue[name];
if (value) {
ctrl.value = value;
}
obj.trigger('createNew');
} else {
ctrl.value = this.config.getItemProp(id, name);
obj.trigger('update');
}
},
updateLine: function(line) {
for (var i = 0; i < this.props.length; ++i) {
this.updatePropDisplay(line, this.props[i]);
}
if (Number(line.attr('row')) < this.config.count()) {
line.trigger('update');
} else {
line.addClass('newline');
}
},
createLine: function() {
with (this) {
var line = $('<div></div>').addClass('itemline');
var inner = $('<div>');
line.append(inner);
// create input boxes
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
var ctrl = $('<div></div>').attr('property', prop.property)
.addClass('listvalue').attr('tabindex', -1);
var valueobj = new List.types[prop.type](ctrl, prop);
var data = {list: this, line: line, prop: prop};
for (var e in prop.events) {
ctrl.bind(e, data, prop.events[e]);
}
ctrl.bind('change', function(e) {
validate(line);
return true;
});
ctrl.bind('keyup', function(e) {
if (e.keyCode == 27) {
cancelEdit(line);
}
});
ctrl.trigger('create');
inner.append(ctrl);
}
// Event listeners
line.click(function(e) {
startEdit(line);
});
line.focusin(function(e) {
startEdit(line);
});
line.focusout(function(e) {
finishEdit(line);
});
for (var e in this.config.lineEvents) {
line.bind(e, {list: this, line: line}, this.config.lineEvents[e]);
}
var list = this;
line.bind('updating', function() {
$(list).trigger('updating');
});
line.bind('updated', function() {
$(list).trigger('updated');
});
this.bindId(line, this.lines.length);
this.lines.push(line);
line.appendTo(this.contents);
return line;
}
},
refresh: function(lines) {
var all = false;
if (lines === undefined) {
all = true;
lines = [];
}
for (var i = this.lines.length; i <= this.config.count(); ++i) {
var line = this.createLine();
lines.push(i);
}
while (this.lines.length > this.config.count() + 1) {
this.lines.pop().remove();
}
$('.newline', this.contents).removeClass('newline');
this.lines[this.lines.length - 1].addClass('newline');
if (all) {
for (var i = 0; i < this.lines.length; ++i) {
this.updateLine(this.lines[i]);
}
} else {
for (var i = 0; i < lines.length; ++i) {
this.updateLine(this.lines[lines[i]]);
}
}
},
load: function() {
this.contents.empty();
this.lines = [];
this.refresh();
},
bindId: function(line, id) {
line.attr('row', id);
},
getLineNewValue: function(line) {
var ret = {};
for (var i = 0; i < this.props.length; ++i) {
this.getPropValue(line, ret, this.props[i]);
}
return ret;
},
getPropValue: function(line, item, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var value = ctrl.value;
if (value !== undefined) {
item[name] = value;
}
return value;
},
startEdit: function(line) {
if (line.hasClass('editing')) {
return;
}
line.addClass('editing');
this.showLine(line);
this.selectLine(line);
var list = this;
setTimeout(function() {
if (!line[0].contains(document.activeElement)) {
$('.valinput', line).first().focus();
}
list.validate(line);
}, 50);
},
finishEdit: function(line) {
var list = this;
function doFinishEdit() {
with(list) {
if (line[0].contains(document.activeElement)) {
return;
}
var valid = isValid(line);
if (valid) {
var id = Number(line.attr('row'));
var newval = getLineNewValue(line);
if (line.hasClass('newline')) {
$(list).trigger('updating');
if(!config.insert(id, newval)) {
line.removeClass('newline');
list.selectLine(line);
$(list).trigger('add', id);
addNewLine();
}
} else {
line.trigger('updating');
config.patch(id, newval);
}
line.trigger('updated');
}
cancelEdit(line);
}
};
setTimeout(doFinishEdit, 50);
},
cancelEdit: function(line) {
line.removeClass('editing');
line.removeClass('error');
var id = Number(line.attr('row'));
if (id == this.config.count() && this.selectedLine == id) {
this.selectedLine = List.ids.noline;
}
this.updateLine(line);
},
addNewLine: function() {
with(this) {
var line = $('.newline', contents);
if (!line.length) {
line = createLine().addClass('newline');
}
return line;
}
},
isValid: function(line) {
var id = Number(line.attr('row'));
var obj = this.getLineNewValue(line);
return valid = this.config.validate(id, obj);
},
validate: function(line) {
if (this.isValid(line)) {
line.removeClass('error');
} else {
line.addClass('error');
}
},
move: function(a, b, keepSelect) {
var len = this.config.count();
if (a == b || a < 0 || b < 0 || a >= len || b >= len) {
return;
}
this.config.move(a, b);
for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) {
this.updateLine(this.getLine(i));
}
if (keepSelect) {
if (this.selectedLine == a) {
this.selectLine(b);
} else if (this.selectedLine == b) {
this.selectLine(a);
}
}
},
getLine: function(id) {
if (id < 0 || id >= this.lines.length) {
return null;
}
return this.lines[id];
},
remove: function(id) {
id = Number(id);
if (id < 0 || id >= this.config.count()) {
return;
}
$(this).trigger('updating');
var len = this.lines.length;
this.getLine(id).trigger('removing');
if (this.config.remove(id)) {
return;
}
this.getLine(len - 1).remove();
this.lines.pop();
for (var i = id; i < len - 1; ++i) {
this.updateLine(this.getLine(i));
}
if (id >= len - 2) {
this.selectLine(id);
} else {
this.selectLine(List.ids.noline);
}
$(this).trigger('updated');
},
selectLine: function(id) {
var line = id;
if (typeof id == "number") {
line = this.getLine(id);
} else {
id = Number(line.attr('row'));
}
// Can't select the new line.
if (line && line.hasClass('newline')) {
line = null;
id = List.ids.noline;
}
if (this.selectedLine == id) {
return;
}
var oldline = this.getLine(this.selectedLine);
if (oldline) {
this.cancelEdit(oldline);
oldline.removeClass('selected');
oldline.trigger('deselect');
this.selectedLine = List.ids.noline;
}
this.selectedLine = id;
if (line != null) {
line.addClass('selected');
line.trigger('select');
this.showLine(line);
}
$(this).trigger('select');
},
showLine: function(line) {
var showtop = this.scrolls.scrollTop();
var showbottom = showtop + this.scrolls.height();
var top = line.offset().top - this.contents.offset().top;
// Include the scroll bar
var bottom = top + line.height() + 20;
if (top < showtop) {
// show at top
this.scrolls.scrollTop(top);
} else if (bottom > showbottom) {
// show at bottom
this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height()));
}
}
};
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
replaceDocument();
window.addEventListener('load', replaceDocument, false);
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var USE_RECORD_GAP = 3 * 60 * 1000; // 3 minutes
var background = chrome.extension.getBackgroundPage();
var _gaq = background._gaq || _gaq || [];
if (window == background) {
_gaq.push(['_setAccount', 'UA-28870762-4']);
}
_gaq.push(['_trackPageview', location.href]);
function initGAS() {
var setting = setting || background.setting || {};
if (!debug && setting.misc.tracking) {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
} else if (!debug) {
// dummy it. Non-debug && non-track
_gaq.push = function() {};
}
}
var useHistory = {};
var issueHistory = {};
function trackCheckSpan(history, item) {
var last = history[item];
if (last && Date.now() - last < USE_RECORD_GAP) {
return false;
}
history[item] = Date.now();
return true;
}
function trackIssue(issue) {
if (!trackCheckSpan(issueHistory, issue.identifier)) {
return;
}
_gaq.push(['_trackEvent', 'usage', 'error', '' + issue.identifier]);
}
function trackVersion(version) {
_gaq.push(['_trackEvent', 'option', 'version', version]);
}
function serializeRule(rule) {
return rule.type[0] + ' ' + rule.value;
}
function trackUse(identifier) {
if (!trackCheckSpan(useHistory, identifier)) {
return;
}
if (identifier.substr(0, 7) == 'custom_') {
var setting = setting || background.setting || {};
var rule = setting.getItem(identifier);
_gaq.push(['_trackEvent', 'usage', 'use-custom', serializeRule(rule)]);
} else {
_gaq.push(['_trackEvent', 'usage', 'use', identifier]);
}
}
var urlHistory = {}
function trackNotUse(url) {
if (!trackCheckSpan(urlHistory, url)) {
return;
}
_gaq.push(['_trackEvent', 'usage', 'notuse', url]);
}
function trackDisable(identifier) {
_gaq.push(['_trackEvent', 'option', 'disable', identifier]);
}
function trackAutoEnable(identifier) {
_gaq.push(['_trackEvent', 'option', 'autoenable', identifier]);
}
function trackEnable(identifier) {
_gaq.push(['_trackEvent', 'option', 'enable', identifier]);
}
function trackAddCustomRule(rule, auto) {
var cmd = 'add';
if (auto) {
cmd = 'add-' + auto;
}
_gaq.push(['_trackEvent', 'option', cmd, serializeRule(rule)]);
}
function trackManualUpdate() {
_gaq.push(['_trackEvent', 'update', 'manual']);
}
function trackUpdateFile(url) {
_gaq.push(['_trackEvent', 'update', 'file', url]);
}
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1'));
if (isNaN(tabId)) {
alert('Invalid tab id');
}
var backgroundPage = chrome.extension.getBackgroundPage();
var tabInfo = backgroundPage.tabStatus[tabId];
var setting = backgroundPage.setting;
if (!tabInfo) {
alert('Cannot get tab tabInfo');
}
$(document).ready(function() {
$('.status').hide();
$('#submitissue').hide();
if (tabInfo.count == 0) {
// Shouldn't have this popup
} else if (tabInfo.error != 0) {
$('#status_error').show();
} else if (tabInfo.count != tabInfo.actived) {
$('#status_disabled').show();
} else {
$('#status_ok').show();
$('#submitissue').show();
}
});
$(document).ready(function() {
$('#issue_view').hide();
if (tabInfo.error != 0) {
var errorid = tabInfo.issueId;
var issue = setting.issues[errorid];
$('#issue_content').text(issue.description);
var url = issue.url;
if (!url) {
var issueUrl = "http://code.google.com/p/np-activex/issues/detail?id=";
url = issueUrl + issue.issueId;
}
$('#issue_track').click(function() {
chrome.tabs.create({url:url});
window.close();
});
$('#issue_view').show();
}
});
function refresh() {
alert($$('refresh_needed'));
window.close();
}
function showEnableBtns() {
var list = $('#enable_btns');
list.hide();
if (tabInfo.count > tabInfo.actived) {
list.show();
var info = {actived: true};
for (var i = 0; i < tabInfo.frames && info.actived; ++i) {
for (var j = 0; j < tabInfo.objs[i].length && info.actived; ++j) {
info = tabInfo.objs[i][j];
}
}
if (info.actived) {
return;
}
var rule = setting.getFirstMatchedRule(info, setting.defaultRules);
if (rule) {
var button = $('<button>').addClass('defaultRule');
button.text($$('enable_default_rule', rule.title));
button.click(function() {
setting.activeRule(rule);
refresh();
});
list.append(button);
} else {
var site = info.href.replace(/[^:]*:\/\/([^\/]*).*/, '$1');
var sitepattern = info.href.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*');
var btn1 = $('<button>').addClass('customRule').
text($$('add_rule_site', site)).click(function() {
var rule = setting.createRule();
rule.type = 'wild';
rule.value = sitepattern;
setting.addCustomRule(rule, 'popup');
refresh();
});
var clsid = info.clsid;
var btn2 = $('<button>').addClass('customRule').
text($$('add_rule_clsid')).click(function() {
var rule = setting.createRule();
rule.type = 'clsid';
rule.value = clsid;
setting.addCustomRule(rule, 'popup');
refresh();
});
list.append(btn1).append(btn2);
}
}
}
$(document).ready(function() {
$('#submitissue').click(function() {
tabInfo.tracking = true;
alert($$('issue_submitting_desp'));
window.close();
});
});
$(document).ready(showEnableBtns);
$(window).load(function() {
$('#share').load('share.html');
});
|
JavaScript
|
// Copyright (c) 2010 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var $$ = chrome.i18n.getMessage;
function loadI18n() {
document.title = chrome.i18n.getMessage("option_title")
var spans = document.querySelectorAll('[i18n]');
for (var i = 0; i < spans.length; ++i) {
var obj = spans[i];
v = $$(obj.getAttribute("i18n"));
if (v == "")
v = obj.getAttribute('i18n');
if (obj.tagName == 'INPUT') {
obj.value = v;
} else {
obj.innerText = v;
}
}
}
window.addEventListener("load", loadI18n, false);
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var background = chrome.extension.getBackgroundPage();
var setting = background.setting;
var updateSession = background.updateSession;
function toggleRule(e) {
var line = e.data.line;
var index = line.attr('row');
var item = setting.order[index];
if (item.position == 'default') {
if (item.status == 'enabled') {
item.status = 'disabled';
trackDisable(item.identifier);
} else if (item.status == 'disabled') {
item.status = 'enabled';
trackEnable(item.identifier);
}
}
line.blur();
e.data.list.finishEdit(line);
e.data.list.updateLine(line);
save();
}
var settingProps = [ {
header: "",
property: "status",
type: 'button',
caption: "",
events: {
command: toggleRule,
update: setStatus,
createNew: setStatusNew
}
}, {
header: $$("title"),
property: "title",
type: "input"
}, {
header: $$("mode"),
property: "type",
type: "select",
option: "static",
options: [
{value: "wild", text: $$("WildChar")},
{value: "regex", text: $$("RegEx")},
{value: "clsid", text: $$("CLSID")}
]
}, {
header: $$("pattern"),
property: "value",
type: "input"
}, {
header: $$("user_agent"),
property: "userAgent",
type: "select",
option: "static",
options: [
{value: "", text: "Chrome"},
{value: "ie9", text: "MSIE9"},
{value: "ie8", text: "MSIE8"},
{value: "ie7", text: "MSIE7"},
{value: "ff7win", text: "Firefox 7"},
{value: "ip5", text: "iPhone"},
{value: "ipad5", text: "iPad"}
]
}, {
header: $$("helper_script"),
property: "script",
type: "input"
}
];
var table;
var dirty = false;
function save() {
dirty = true;
}
function doSave() {
if (dirty) {
dirty = false;
setting.update();
}
}
function setReadonly(e) {
var line = e.data.line;
var id = line.attr('row');
if (id < 0) {
return;
}
var order = setting.order[id];
var divs = $('.listvalue', line);
if (order.position != 'custom') {
divs.addClass('readonly');
} else {
divs.removeClass('readonly');
}
}
$(window).blur(doSave);
function refresh() {
table.refresh();
}
// Main setting
$(document).ready(function() {
table = new List({
props: settingProps,
main: $('#tbSetting'),
lineEvents: {
update: setReadonly
},
getItems: function() {
return setting.order;
},
getItemProp: function(i, prop) {
if (prop in setting.order[i]) {
return setting.order[i][prop];
}
return setting.getItem(setting.order[i])[prop];
},
setItemProp: function(i, prop, value) {
if (prop in setting.order[i]) {
setting.order[i][prop] = value;
} else {
setting.getItem(setting.order[i])[prop] = value;
}
},
defaultValue: setting.createRule(),
count: function() {
return setting.order.length;
},
insert: function(id, newItem) {
setting.addCustomRule(newItem);
this.move(setting.order.length - 1, id);
},
remove: function(id) {
if (setting.order[id].position != 'custom') {
return true;
}
var identifier = setting.order[id].identifier;
delete setting.rules[identifier];
setting.order.splice(id, 1);
},
validate: function(id, rule) {
return setting.validateRule(rule);
}
});
$(table).bind('updated', save);
$('#addRule').bind('click', function() {
table.editNewLine();
});
$(table).bind('select', function() {
var line = table.selectedLine;
if (line < 0) {
$('#moveUp').attr('disabled', 'disabled');
$('#moveDown').attr('disabled', 'disabled');
$('#deleteRule').attr('disabled', 'disabled');
} else {
if (line != 0) {
$('#moveUp').removeAttr('disabled');
} else {
$('#moveUp').attr('disabled', 'disabled');
}
if (line != setting.order.length - 1) {
$('#moveDown').removeAttr('disabled');
} else {
$('#moveDown').attr('disabled', 'disabled');
}
if (setting.order[line].position != 'custom') {
$('#deleteRule').attr('disabled', 'disabled');
} else {
$('#deleteRule').removeAttr('disabled');
}
}
});
$('#moveUp').click(function() {
var line = table.selectedLine;
table.move(line, line - 1, true);
});
$('#moveDown').click(function() {
var line = table.selectedLine;
table.move(line, line + 1, true);
});
$('#deleteRule').click(function() {
var line = table.selectedLine;
table.remove(line);
});
table.init();
updateSession.bind('update', refresh);
updateSession.bind('updating', showUpdatingState);
updateSession.bind('progress', showUpdatingState);
updateSession.bind('complete', showUpdatingState);
});
window.onbeforeunload = function() {
updateSession.unbind('update', refresh);
updateSession.unbind('updating', showUpdatingState);
updateSession.unbind('progress', showUpdatingState);
updateSession.unbind('complete', showUpdatingState);
}
function setStatusNew(e) {
with (e.data) {
s = 'Custom';
color = '#33f';
$('button', line).text(s).css('background-color', color);
}
}
function setStatus(e) {
with (e.data) {
var id = line.attr('row');
var order = setting.order[id];
var rule = setting.getItem(order);
var s, color;
if (order.status == 'enabled') {
s = $$('Enabled');
color = '#0A0';
} else if (order.status == 'disabled') {
s = $$('Disabled');
color = 'indianred';
} else {
s = $$('Custom');
color = '#33f';
}
$('button', line).text(s).css('background-color', color);
}
}
function showTime(time) {
var never = 'Never'
if (time == 0) {
return never;
}
var delta = Date.now() - time;
if (delta < 0) {
return never;
}
function getDelta(delta) {
var sec = delta / 1000;
if (sec < 60) {
return [sec, 'second'];
}
var minute = sec / 60;
if (minute < 60) {
return [minute, 'minute'];
}
var hour = minute / 60;
if (hour < 60) {
return [hour, 'hour'];
}
var day = hour / 24;
return [day, 'day'];
}
var disp = getDelta(delta);
var v1 = Math.floor(disp[0]);
return v1 + ' ' + disp[1] + (v1 != 1 ? 's' : '') + " ago";
}
function showUpdatingState(e) {
if (updateSession.status == 'stop') {
$('#lastUpdate').text(showTime(setting.misc.lastUpdate));
} else {
$('#lastUpdate').text($$("update_progress") + updateSession.finish + '/' + updateSession.total);
}
}
$(document).ready(function() {
showUpdatingState({});
$('#doUpdate').click(function() {
setting.updateConfig(updateSession);
trackManualUpdate();
});
$('#log_enable').change(function(e) {
setting.misc.logEnabled = e.target.checked;
save();
})[0].checked = setting.misc.logEnabled;
$('#tracking').change(function(e) {
setting.misc.tracking = e.target.checked;
save();
})[0].checked = setting.misc.tracking;
});
$(document).ready(function() {
var help = 'http://code.google.com/p/np-activex/wiki/ExtensionHelp?wl=';
help = help + $$('wikicode');
$('.help').each(function() {
this.href = help;
});
});
$(window).load(function() {
$('#share').load('share.html');
if (background.firstUpgrade) {
background.firstUpgrade = false;
alert($$("upgrade_show"));
}
$('#follow').html('<iframe width="136" height="24" frameborder="0" allowtransparency="true" marginwidth="0" marginheight="0" scrolling="no" border="0" src="http://widget.weibo.com/relationship/followbutton.php?language=zh_cn&width=136&height=24&uid=2356524070&style=2&btn=red&dpc=1"></iframe>');
});
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
List.types.input = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input></input>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
this.input.focus(function(e) {
input.select();
});
this.input.keypress(function(e) {
p.trigger('change');
});
this.input.keyup(function(e) {
p.trigger('change');
});
this.input.change(function(e) {
p.trigger('change');
});
p.append(this.input).append(this.label);
};
List.types.input.prototype.__defineSetter__('value', function(val) {
this.input.val(val);
this.label.text(val);
});
List.types.input.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<select></select>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
if (prop.option == 'static') {
this.loadOptions(prop.options);
}
var select = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
select.value = select.lastval;
} else {
p.trigger('change');
}
});
this.label.click(function(e) {
setTimeout(function(){
input.focus();
}, 10);
});
p.append(this.input).append(this.label);
};
List.types.select.prototype.loadOptions = function(options) {
this.options = options;
this.mapping = {};
this.input.html("");
for (var i = 0; i < options.length; ++i) {
this.mapping[options[i].value] = options[i].text;
var o = $('<option></option>').val(options[i].value).text(options[i].text)
this.input.append(o);
}
}
List.types.select.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input.val(val);
this.label.text(this.mapping[val]);
});
List.types.checkbox = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input type="checkbox">').addClass('valcheck');
var box = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
box.value = box.lastval;
} else {
p.trigger('change');
}
});
p.append(this.input);
};
List.types.checkbox.prototype.__defineGetter__('value', function() {
return this.input[0].checked;
});
List.types.checkbox.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input[0].checked = val;
});
List.types.button = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<button>');
if (prop.caption) {
input.text(prop.caption);
}
input.click(function(e) {
p.trigger('command');
return false;
});
p.append(this.input);
};
List.types.button.prototype.__defineGetter__('value', function() {
return undefined;
});
|
JavaScript
|
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1'));
if (isNaN(tabId)) {
alert('Invalid tab id');
}
var backgroundPage = chrome.extension.getBackgroundPage();
$(document).ready(function() {
var s = backgroundPage.generateLogFile(tabId);
$("#text").val(s);
});
|
JavaScript
|
$(document).ready(function() {
$('#userRole').datagrid({
data :null
});
$('#reloadList').linkbutton('disable');
$("#targetUser").combobox({
onSelect : function(record) {
loadGridData(record.id);
$('#reloadList').linkbutton('enable');
}
});
});
function loadGridData(username) {
if (username == undefined)
return;
// $.getJSON('listRole.htm?userId=' + username, function(resData) {
// $('#userRole').datagrid({
// data : resData
// });
// });
$.getJSON('listRole.htm?userId=' + username, function(resData) {
$('#userRole').datagrid({
data : resData
});
})
.done(function(data){
var rows = $('#userRole').datagrid('getRows');
for (var i = 0; i < rows.length; ++i) {
if (rows[i]['permitted'] == true)
$('#userRole').datagrid('checkRow', i);
}
});
}
function reloadList(){
loadGridData($("#targetUser").combobox('getValue'));
}
function saveList(){
var roles = [];
var rows = $('#userRole').datagrid('getSelections');
for(var i=0;i<rows.length;i++){
roles.push(rows[i].name);
}
var data = {};
data["roles"]=roles.join(':');
data["targetUser"]=$("#targetUser").combobox('getValue');
$.postJSON("UpdateRole.htm", data, function(result) {
if (result.success) {
showMessager("Info", result.message);
loadGridData('Pending');
} else {
showMessager("Exception", result.message);
}
}, function(xhr, ajaxOptions, thrownError) {
showMessager("Exception", thrownError);
});
}
|
JavaScript
|
var inData;
$(document).ready(
function() {
toggleNotebooks();
var prjObjId = $("#prjObjId").val();
var oppId=$("#opportunityId").val();
$.getJSON('getCompleteOpportunity.htm?prjObjId=' + prjObjId + "&oppId=" + oppId,
function(data) {
inData = $.extend({}, data.opportunity, data.review);
createOppStatusTable(data.oppStatus);
$("#projectName").text(inData.title);
$("#oppCurrentStatus").text("Current State : - " +data.oppCurrentStatus);
// inData = data;
loadDetails();
});
});
function showPanel(opt) {
$("#reviewAccordion").accordion('select', opt-1);
$("#reviewAccordion").accordion('getSelected', true);
}
function createOppStatusTable(statusData) {
var htmlTbl = "<table class='blueTable'>";
htmlTbl += '<tr><td>Assign Date</td><td>Role</td><td>User</td><td>Status</td><td>End Date</td><td>Outcome</td></tr>';
var colNames = [ "startDate", "role","userId", "status","endDate",
"outcome" ];
$.each(statusData, function(ind, obj) {
htmlTbl += "<tr>";
$.each(colNames, function(i, col) {
if (obj.hasOwnProperty(col))
htmlTbl += "<td>" + obj[col] + "</td>";
else
htmlTbl += "<td> </td>";
});
htmlTbl += "</tr>";
});
htmlTbl += "</table>";
$("#oppStatus").html(htmlTbl);
}
function loadDetails() {
$.each(inData, function(key, value) {
try {
if (jQuery.type(inData[key]) === "object") {
$("#" + key).html(inData[key].value);
} else {
$("#" + key).html(inData[key]);
}
} catch (e) {
}
});
showPanel(1);
}
function toggleNotebooks() {
$(".notebook span:first-child").each(function(ind, obj) {
$(obj).addClass("collapse");
$(obj).parent().parent().find("div").addClass("collapseNotebook");
});
$(".notebook span:first-child").click(
function(obj) {
if ($(obj.target).hasClass('expand')) {
$(obj.target).removeClass('expand');
$(obj.target).addClass('collapse');
$(obj.target).parent().parent().find("div").eq(0)
.removeClass("expandNotebook");
$(obj.target).parent().parent().find("div").eq(0).addClass(
"collapseNotebook");
} else {
$(obj.target).removeClass('collapse');
$(obj.target).addClass('expand');
$(obj.target).parent().parent().find("div").eq(0)
.removeClass("collapseNotebook");
$(obj.target).parent().parent().find("div").eq(0).addClass(
"expandNotebook");
}
});
}
function createNotebookRow(title, id) {
var content = "";
if (inData.hasOwnProperty(id))
content = inData[id];
var row = "<tr><td class='notebook' colspan='2'><b><span> </span><span>"
+ title + "</span></b>" + createDiv(id, content) + "</td></tr>";
return row;
}
function createTextRow(title, id) {
var content = "";
if (inData.hasOwnProperty(id))
content = inData[id];
var row = "<tr><td><b>" + title + "</b></td><td>" + createSpan(id, content)
+ "</td></tr>";
return row;
}
function createObjectRow(title, id) {
var content = "";
if (inData.hasOwnProperty(id))
content = inData[id];
var row = "<tr><td><b>" + title + "</b></td><td>"
+ createSpan(id, content.value) + "</td></tr>";
return row;
}
function createDiv(divId, content) {
content = (content === undefined ? "" : content);
return "<div id='" + divId + "' >" + content + "</div>";
}
function createSpan(spanId, spanData) {
content = (content === undefined ? "" : content);
return "<Span id='" + spanId + "' style='width: 400px; height: 20px'>"
+ spanData + "</Span>";
}
|
JavaScript
|
$(document).ready(function() {
loadGridData("");
$('#dg').datagrid({
toolbar : toolbar,
rownumbers : true,
singleSelect : true
});
});
function loadGridData(filter) {
var userId = $("#userId").val();
if (userId == undefined)
return;
$.getJSON('listActionItems.htm?userId=' + userId + '&filter=' + filter,
function(resData) {
$('#dg').datagrid({
data : resData
});
});
}
var toolbar = [ {
id : 'btnClaim',
text : 'Claim',
iconCls : 'icon-add',
handler : claimOpportunity
}, {
id : 'btnApprove',
text : 'Approve',
iconCls : 'icon-ok',
handler : approveOpportunity
}, {
id : 'btnReject',
text : 'Reject',
iconCls : 'icon-cancel',
handler : rejectOpportunity
}, '-', {
id : 'btnMyClaims',
text : 'My Claims',
iconCls : 'icon-inbox-plus',
handler : getClaimedByMe
}, {
id : 'btnAllOpportunity',
text : 'All Opportunity',
iconCls : 'icon-archives',
handler : getAllOpportunity
}, '-', {
id : 'btnViewDetails',
text : 'View Details',
iconCls : 'icon-search',
handler : viewOpportunityDetails
}
];
function viewOpportunityDetails() {
var row = $('#dg').datagrid('getSelected');
if (row == null) {
showMessager("Info", "Please select an opportunity to view details");
return;
}
if(row.stepId == "6" || row.stepId == 6){
var win = window.open("ResourceDetails.htm?assId=" + row.id
+ "&opportunityId=" + row.opportunityId + "&prjObjId="
+ row.prjObjId,
"width=880,height=750,scrollbars=yes,location=no,menubar=no");
win.focus();
}else if(row.stepId == "5" || row.stepId == 5){
}
else{
var win = window.open("ViewOpportunity.htm?assId=" + row.id
+ "&opportunityId=" + row.opportunityId + "&prjObjId="
+ row.prjObjId,
"width=880,height=750,scrollbars=yes,location=no,menubar=no");
win.focus();
}
}
function getOpportunityDetails() {
var row = $('#dg').datagrid('getSelected');
if (row == null) {
showMessager("Info", "Please select an opportunity to view details");
return;
}
var url = "getDetail.htm?opportunityId=" + row.opportunityId;
$.ajax({
url : url
});
}
function gridReset() {
loadGridData('Pending');
}
function getClaimedByMe() {
loadGridData('Claimed');
}
function getAllOpportunity() {
loadGridData('Pending');
}
function claimOpportunity() {
var row = $('#dg').datagrid('getSelected');
if (row == null) {
showMessager("Error", "Please select an Opportunity to claim!");
return false;
}
if ((row.stepId == "2" || row.stepId == "3" || row.stepId == "4" || row.stepId == "5" || row.stepId == "6") && row.status == "Pending") {
} else {
showMessager("Error", "Only pending opportunity can be claimed!");
return false;
}
var data = {
"opportunityId" : row.opportunityId,
"id" : row.id,
"userId" : $("#userId").val(),
"action" : "claim",
"pmuser" : "None"
};
$.postJSON("OpportunityAction.htm", data, function(result) {
if (result.success) {
showMessager("Info", result.message);
loadGridData('Pending');
} else {
showMessager("Exception", result.message);
}
}, function(xhr, ajaxOptions, thrownError) {
showMessager("Exception", thrownError);
});
}
function approveOpportunity() {
var row = $('#dg').datagrid('getSelected');
if (row == null) {
showMessager("Error", "Please select an Opportunity to approve!");
return false;
}
if (row.status != "Claimed") {
showMessager("Error", "Only claimed opportunity can be approved!");
return false;
}
if (row.userId != $("#userId").val()) {
showMessager("Error",
"You can not approve any opportunity claimed by others !!!");
return false;
}
if (row.stepId == "4" || row.stepId == 4 ) {
$('#prcApprovalWindow').dialog('open');
return false;
}
if (row.stepId == "2") {
openApprovalWindow();
return false;
}
var data = {
"opportunityId" : row.opportunityId,
"id" : row.id,
"userId" : $("#userId").val(),
"action" : "approve",
"pmuser" : "None"
};
$.postJSON("OpportunityAction.htm", data, function(result) {
if (result.success) {
showMessager("Info", result.message);
loadGridData('Pending');
} else {
showMessager("Exception", result.message);
}
}, function(xhr, ajaxOptions, thrownError) {
showMessager("Exception", thrownError);
});
}
function approvePRCOpportunity() {
if (!$("#approvalForm").form('validate')) {
showMessager("Alert", 'Required fields can not be left blank.');
return false;
}
var row = $('#dg').datagrid('getSelected');
var pmuser=$("#showPM").combobox('getValue');
if (row == null) {
showMessager("Error", "Please select an Opportunity to approve!");
return false;
}
if (row.status != "Claimed") {
showMessager("Error", "Only claimed opportunity can be approved!");
return false;
}
if (row.userId != $("#userId").val()) {
showMessager("Error",
"You can not approve any opportunity claimed by others !!!");
return false;
}
var data = {
"opportunityId" : row.opportunityId,
"id" : row.id,
"userId" : $("#userId").val(),
"action" : "approve",
"pmuser" : pmuser
};
$.postJSON("OpportunityAction.htm", data, function(result) {
if (result.success) {
showMessager("Info", result.message);
loadGridData('Pending');
$('#prcApprovalWindow').dialog('close');
} else {
showMessager("Exception", result.message);
}
}, function(xhr, ajaxOptions, thrownError) {
showMessager("Exception", thrownError);
});
}
function rejectOpportunity() {
var row = $('#dg').datagrid('getSelected');
if (row == null) {
showMessager("Error", "Please select an Opportunity to reject!");
return false;
}
var data = {
"opportunityId" : row.opportunityId,
"id" : row.id,
"userId" : $("#userId").val(),
"action" : "reject",
"pmuser" : "None"
};
$.postJSON("OpportunityAction.htm", data, function(result) {
if (result.success) {
showMessager("Info", result.message);
loadGridData('Pending');
} else {
showMessager("Exception", result.message);
}
}, function(xhr, ajaxOptions, thrownError) {
showMessager("Exception", thrownError);
});
}
//function rejectOpportunity() {
// var row = $('#dg').datagrid('getSelected');
// if (row == null) {
// showMessager("Error", "Please select an Opportunity to reject!");
// return false;
// }
// if ((row.stepId == "3" || row.stepId == "4" || row.stepId == "6") && row.status == "Claimed") {
//
// } else if (row.stepId == "2" && row.status == "Claimed") {
// showMessager("Error", "You cannot reject the Opportunity!");
// return false;
// } else {
// showMessager("Error", "Only claimed opportunity can be rejected!");
// return false;
// }
//
//
// var data = {
// "opportunityId" : row.opportunityId,
// "id" : row.id,
// "userId" : $("#userId").val(),
// "action" : "reject",
// "pmuser" : "None"
// };
//
// $.postJSON("OpportunityAction.htm", data, function(result) {
// if (result.success) {
// showMessager("Info", result.message);
// loadGridData('Pending');
// } else {
// showMessager("Exception", result.message);
// }
// }, function(xhr, ajaxOptions, thrownError) {
// showMessager("Exception", thrownError);
// });
//}
function openApprovalWindow() {
var row = $('#dg').datagrid('getSelected');
if (row == null) {
showMessager("Error", "Please select an Opportunity to approve!");
return false;
}
if (row.status != "Claimed") {
showMessager("Error", "Only Claimed opportunity can be approved!");
return false;
}
if (row.userId != $("#userId").val()) {
showMessager("Error",
"You can not approve any opportunity claimed by others!");
return false;
}
var type = "";
if (row.role == "FC")
type = "financial";
else if (row.role == "CA")
type = "legal";
else if (row.role == "PMO")
type = "strategic";
else if (row.role == "PMORM")
type = "capability";
else if (row.role == "BD")
type = "BD";
var url = "OppReview.htm?type=" + type + "&userId=" + $("#userId").val()
+ "&opportunityId=" + row.opportunityId + "&prjObjId="
+ row.prjObjId + "&assignmentId=" + row.id;
window.open(url, "popupWindow",
"width=880,height=750,scrollbars=yes,location=no,menubar=no");
return false;
}
|
JavaScript
|
$(document).ready(function() {
loadGridData("");
$('#resourceGrid').datagrid({
rownumbers : true,
singleSelect : true
});
});
function loadGridData(filter) {
var prjObjId = $("#prjObjId").val();
if (prjObjId == undefined)
return;
$.getJSON('getResourceDetails.htm?prjObjId=' + prjObjId,
function(resData) {
$('#resourceGrid').datagrid({
data : resData
});
});
}
|
JavaScript
|
$(document).ready(function() {
$("#contractValSel").click(addCost);
$("#contractValClear").click(clearCost);
var prjObjId = $("#prjObjId").val();
$.getJSON('getOpportunityViewData.htm?prjObjId=' + prjObjId, function(data) {
setFormData("ff", data);
//alert($("#hiddenAddNotes").val());
});
});
function clearCost() {
$('#contractVal').validatebox('enableValidation');
var opt = document.getElementById('contractValBreakup');
opt.options.length = 0;
}
function addCost() {
var conVal = $("#contractVal").val();
var cur = $("#contractValCur").combobox('getValue');
if (conVal == "") {
showMessager('Invalid input', 'Please input currency value!');
return false;
} else if (cur == "") {
showMessager('Invalid input', 'Please select currency!');
return false;
}
var curOpt = conVal + " " + cur;
var opt = document.getElementById('contractValBreakup');
opt.options[opt.options.length] = new Option(curOpt, curOpt);
$("#contractVal").val("");
$('#contractVal').numberbox('setValue', '');
$('#contractVal').validatebox('disableValidation');
}
function getFieldObject(id, value) {
return {
"id" : id,
"value" : value
};
}
function saveOpportunity() {
if (!$("#ff").form('validate')) {
$.messager.show({
title : 'Alert',
msg : 'Required fields can not be left blank.',
showType : 'show'
});
return false;
}
var data = getFormData("ff");
var costList = document.getElementById('contractValBreakup');
var costAry = new Array();
for ( var i = 0; i < costList.options.length; i++) {
var d = costList.options[i].value;
var dAry = d.split(" ");
costAry.push({
"value" : dAry[0],
"currency" : dAry[1]
});
}
if (costAry.length > 0)
data["contractVal"] = costAry;
data["userId"] = $("#userId").val();
data["projectType"] = {
"id" : $("#projectType").val(),
"value" : $("#projectType").val()
};
data["market"] = {
"id" : $("#market").val(),
"value" : $("#market").val()
};
data["portfolio"] = {
"id" : $("#portfolio").val(),
"value" : $("#portfolio").val()
};
data["portfolioName"] = {
"id" : $("#portfolioName").val(),
"value" : $("#portfolioName").val()
};
$.postJSON("saveOpportunity.htm", data, function(result) {
if (result.success) {
showMessager("Info", "Opportunity Saved");
window.close();
} else {
showMessager("Exception", result.message);
}
}, function(xhr, ajaxOptions, thrownError) {
showMessager("Exception", thrownError);
});
}
function resetForm() {
$("#ff").reset();
}
|
JavaScript
|
function saveReviewData() {
if (!$("#ff").form('validate')) {
showMessager("Alert", 'Required fields can not be left blank.');
return false;
}
var data = getFormData("ff");
data["userId"] = $("#userId").val();
data["opportunityId"] = $("#opportunityId").val();
data["prjObjId"] = $("#prjObjId").val();
data["assignmentId"] = $("#assignmentId").val();
$.postJSON("saveReviewData.htm?type=financial", data, function(result) {
if (result.success) {
showMessager("Info", result.message);
} else {
showMessager("Exception", result.message);
}
}, function(xhr, ajaxOptions, thrownError) {
showMessager("Exception", thrownError);
});
}
function approveReview() {
if (!$("#ff").form('validate')) {
$.messager.show({
title : 'Alert',
msg : 'Required fields can not be left blank.',
showType : 'show'
});
return false;
}
approveReviewOpportunity($("#opportunityId").val(), $("#assignmentId")
.val(), $("#userId").val(), true);
}
function showAddComments() {
$("#addNotesContent").html($("#hiddenAddNotes").val());
$('#winAddNotes').window('open');
return false;
}
$(document).ready(function() {
var prjObjId = $("#prjObjId").val();
$.getJSON('getViewData.htm?prjObjId=' + prjObjId, function(data) {
if (data.hasOwnProperty("addNotes")) {
$("#hiddenAddNotes").val(data.addNotes);
data["addNotes"] = "";
}
setFormData("ff", data);
if ($("#hiddenAddNotes").val() == ""){
$("#btnShowAddComments").hide();
}
//alert($("#hiddenAddNotes").val());
});
});
|
JavaScript
|
JavaScript-Code-Large
JavaScript-Code-Large is a large-scale corpus of JavaScript source code comprising around 5 million JavaScript files. The dataset is designed to support research in large language model (LLM) pretraining, code intelligence, software engineering automation, and program analysis for the JavaScript ecosystem.
By providing a high-volume, language-specific corpus, JavaScript-Code-Large enables systematic experimentation in JavaScript-focused model training, domain adaptation, and downstream code understanding tasks.
JavaScript-Code-Large addresses the need for a dedicated JavaScript-only dataset at substantial scale, enabling focused research across frontend, backend, and full-stack JavaScript environments. .
1. Dataset Composition
Programming Language: JavaScript
File Count: 5M+ JavaScript files
File Format: .jsonl
Content Types
The dataset includes a wide variety of JavaScript constructs and paradigms, such as:
Functions (declarations, expressions, arrow functions)
Classes and prototypes
Modules (CommonJS and ES Modules)
Asynchronous patterns (async/await, Promises, callbacks)
Event-driven code
Closures and higher-order functions
Functional programming constructs
DOM manipulation code
Node.js backend logic
Frontend framework components
JSDoc comments
Error handling patterns
Modern ES6+ features
2. Intended Research Applications
2.1 Pretraining
Training JavaScript code foundation models from scratch
Continued pretraining of existing LLMs
JavaScript-specialized language modeling
Tokenizer training for JS ecosystems
2.2 Fine-Tuning and Adaptation
Code completion systems
Intelligent IDE assistants
Automated refactoring tools
Conversational programming agents
JavaScript-specific copilots
2.3 Code Intelligence Tasks
Code summarization
Code-to-text generation
Documentation generation
Bug detection
Vulnerability detection
Clone detection
Code similarity modeling
Minified-to-readable code transformation
Static and structural analysis
2.4 Software Engineering Research
Empirical studies of JavaScript coding patterns
Analysis of async and event-driven architectures
Framework usage studies
Dependency modeling
AST-based experiments
Cross-version JavaScript evolution analysis
3. Relationship to Java-Code-Large
JavaScript-Code-Large complements Java-Code-Large, enabling comparative research between:
Statically typed vs dynamically typed languages
Class-based vs prototype-based paradigms
Backend vs frontend dominant ecosystems
JVM vs Node.js environments
Together, these datasets support cross-language transfer learning and controlled specialization studies.
Thanks to open source community for all the guidance & support!!
- Downloads last month
- 51