<commit_before>var UploadManager = {
  upload: function(file) {
    this.running = true;
    this.finishedResponse = null;
    this.lastProgress = null;
    var imageService = ImageService.getService(OptionsBackend.get('image_upload_service'));
    var _this = this;
    imageService.upload(file, function(success, urlOrError) {
      _this.running = false;
      if(!_this.onFinish || !_this.onFinish(success, urlOrError)) {
        _this.finishedResponse = {
          success: success,
          urlOrError: urlOrError
        };
        _this.onFinish = null;
      }
    },
    function(loaded, total) {
      if(!_this.onProgress || !_this.onProgress(loaded, total)) {
        _this.lastProgress = {
          loaded: loaded,
          total: total
        };
        _this.onProgress = null;
      }
    });
  },

  registerCallbacks: function(onFinish, onProgress) {
    this.onFinish = onFinish;
    this.onProgress = onProgress;

    if(this.finishedResponse) {
      onFinish(this.finishedResponse.success, this.finishedResponse.urlOrError);
      this.finishedResponse = null;
      return false;
    }
    if(this.running) {
      if(this.lastProgress) {
        this.onProgress(this.lastProgress.loaded, this.lastProgress.total);
      }
      return true;
    }
    return false;
  }
};

function ImageService(domain, options) {
  this.domain = domain;
  if(typeof options.thumb == 'function') {
    this.thumbFunc = options.thumb;
  } else {
    this.thumbUrl = options.thumb;
  }

  if(options.upload) {
    this.uploadOptions = $.extend(true, {}, ImageService.defaultUploadOptions, options.upload);
  }

  this.getThumb = function(url) {
    var urlMatch = url.match(/(https?:\/\/|www\.)(.*?)\/(.*)$/i);
    var domain = urlMatch[2];
    var path = urlMatch[3];
    if(this.domain == domain) {
      if(this.thumbFunc) {
        return this.thumbFunc(path, url);
      }
      return this.thumbUrl.replace('$1', path).replace('$2', url);
    }
    return null;
  };

  this.hasUpload = function() {
    return !!this.uploadOptions;
  };

  this.upload = function(file, onFinish, onProgress) {
    var xhr = new XMLHttpRequest();
    xhr.open('post', this.uploadOptions.url, true);

    var _this = this;
    xhr.onreadystatechange = function() {
      if (this.readyState != 4) {
        return;
      }
      if(xhr.status == 200 && xhr.responseText) {
        var parsedResponse = null;
        if(_this.uploadOptions.dataType == 'json') {
          try {
            parsedResponse = JSON.parse(xhr.responseText);
          } catch(e) {}
        } else if(_this.uploadOptions.dataType == 'xml') {
          try {
            parsedResponse = $(xhr.responseText);
          } catch(e) {}
        }
        if(parsedResponse) {
          onFinish(true, _this.uploadOptions.parseSuccess(parsedResponse, xhr));
          return;
        }
      }
      onFinish(false, _this.uploadOptions.parseError(xhr));
    };

    TweetManager.instance.twitterBackend.signOauthEcho(xhr, this.uploadOptions.signingUrl);

    var formData = new FormData();
    for(var param in this.uploadOptions.params) {
      var paramValue = this.uploadOptions.params[param];
      if(paramValue == '$file') {
        paramValue = file;
      }
      formData.append(param, paramValue);
    }

    if(onProgress) {
      xhr.upload.addEventListener("progress", function(e) {
        onProgress(e.loaded, e.total);
      }, false);
    }

    xhr.send(formData);
  };
}

$.extend(ImageService, {
  addService: function(domain, options) {
    this.services = this.services || [];
    this.servicesMap = this.servicesMap || {};
    var service = new ImageService(domain, options);
    this.services.push(service);
    this.servicesMap[domain] = service;
  },

  getThumb: function(url) {
    for(var i = 0, len = this.services.length; i < len; ++i) {
      var service = this.services[i];
      var thumbUrl = service.getThumb(url);
      if(thumbUrl) {
        return thumbUrl;
      }
    }
    return null;
  },

  getService: function(serviceName) {
    return this.servicesMap[serviceName];
  },

  defaultUploadOptions: {
    url: '', // Mandatory
    signingUrl: 'https://api.twitter.com/1/account/verify_credentials.json',
    params: {
      media: '$file'
    },
    dataType: 'json',
    parseError: null, // Mandatory
    parseSuccess: null // Mandatory
  }
});

// $1 is the remaining url after the server and domain name, $2 is the full original url
ImageService.addService('twitpic.com', {
  thumb: 'http://twitpic.com/show/thumb/$1',
  upload: {
    url: 'http://api.twitpic.com/2/upload.json',
    params: {
      key: SecretKeys.twitpic.key
    },
    parseError: function(xhr) {
      var formattedErr;
      if(xhr.responseText) {
        formattedErr = '';
        var errorObj = JSON.parse(xhr.responseText);
        for(var i = 0, len = errorObj.errors.length; i < len; ++i) {
          var error = errorObj.errors[i];
          formattedErr += error.code + ': ' + error.message;
          if(i > 0) {
            formattedErr += '
';
          }
        }
      } else {
        formattedErr = 'Error code: ' + xhr.status;
      }
      return formattedErr;
    },
    parseSuccess: function(obj, xhr) {
      return obj.url;
    }
  }
});

ImageService.addService('yfrog.com', {
 thumb: 'http://yfrog.com/$1.th.jpg',
 upload: {
   url: 'https://yfrog.com/api/xauth_upload',
   params: {
     key: SecretKeys.yfrog.key
   },
   parseError: function(xhr) {
     var errXml = $('err', xhr.responseText);
     var errorStr = 'Error ' + errXml.attr('code') + ': ' + errXml.attr('msg');
     return errorStr;
   },
   parseSuccess: function(obj, xhr) {
     return obj.rsp.mediaurl;
   }
 }
});

ImageService.addService('pict.mobi', {
  thumb: 'http://pict.mobi/show/thumb/$1',
  upload: {
    url: 'http://pict.mobi/upload/',
    dataType: 'xml',
    parseError: function(xhr) {
      return 'Undefined error while uploading.';
    },
    parseSuccess: function(obj, xhr) {
      return obj.text();
    }
  }
});

ImageService.addService('twitshoot.com', {
  thumb: 'http://twitshoot.com/show/thumb/$1',
  upload: {
    url: 'http://twitshoot.com/api/upload.json',
    parseError: function(xhr) {
      return "The upload has failed.";
    },
    parseSuccess: function(obj, xhr) {
		  return obj.image.mediaurl;
    }
  }
});

ImageService.addService('i.imgur.com', {
  thumb: 'http://i.imgur.com/$1'
});

ImageService.addService('movapic.com', {
  thumb: function(path) { return 'http://image.movapic.com/pic/t_' + path.split('/')[1] + '.jpeg'; }
});
ImageService.addService('tweetphoto.com', {
  thumb: 'http://TweetPhotoAPI.com/api/TPAPI.svc/imagefromurl?url=$2'
});<commit_msg>Show thumbnail on imgur images.<commit_after>var UploadManager = {
  upload: function(file) {
    this.running = true;
    this.finishedResponse = null;
    this.lastProgress = null;
    var imageService = ImageService.getService(OptionsBackend.get('image_upload_service'));
    var _this = this;
    imageService.upload(file, function(success, urlOrError) {
      _this.running = false;
      if(!_this.onFinish || !_this.onFinish(success, urlOrError)) {
        _this.finishedResponse = {
          success: success,
          urlOrError: urlOrError
        };
        _this.onFinish = null;
      }
    },
    function(loaded, total) {
      if(!_this.onProgress || !_this.onProgress(loaded, total)) {
        _this.lastProgress = {
          loaded: loaded,
          total: total
        };
        _this.onProgress = null;
      }
    });
  },

  registerCallbacks: function(onFinish, onProgress) {
    this.onFinish = onFinish;
    this.onProgress = onProgress;

    if(this.finishedResponse) {
      onFinish(this.finishedResponse.success, this.finishedResponse.urlOrError);
      this.finishedResponse = null;
      return false;
    }
    if(this.running) {
      if(this.lastProgress) {
        this.onProgress(this.lastProgress.loaded, this.lastProgress.total);
      }
      return true;
    }
    return false;
  }
};

function ImageService(domain, options) {
  this.domain = domain;
  if(typeof options.thumb == 'function') {
    this.thumbFunc = options.thumb;
  } else {
    this.thumbUrl = options.thumb;
  }

  if(options.upload) {
    this.uploadOptions = $.extend(true, {}, ImageService.defaultUploadOptions, options.upload);
  }

  this.getThumb = function(url) {
    var urlMatch = url.match(/(https?:\/\/|www\.)(.*?)\/(.*)$/i);
    var domain = urlMatch[2];
    var path = urlMatch[3];
    if(this.domain == domain) {
      if(this.thumbFunc) {
        return this.thumbFunc(path, url);
      }
      return this.thumbUrl.replace('$1', path).replace('$2', url);
    }
    return null;
  };

  this.hasUpload = function() {
    return !!this.uploadOptions;
  };

  this.upload = function(file, onFinish, onProgress) {
    var xhr = new XMLHttpRequest();
    xhr.open('post', this.uploadOptions.url, true);

    var _this = this;
    xhr.onreadystatechange = function() {
      if (this.readyState != 4) {
        return;
      }
      if(xhr.status == 200 && xhr.responseText) {
        var parsedResponse = null;
        if(_this.uploadOptions.dataType == 'json') {
          try {
            parsedResponse = JSON.parse(xhr.responseText);
          } catch(e) {}
        } else if(_this.uploadOptions.dataType == 'xml') {
          try {
            parsedResponse = $(xhr.responseText);
          } catch(e) {}
        }
        if(parsedResponse) {
          onFinish(true, _this.uploadOptions.parseSuccess(parsedResponse, xhr));
          return;
        }
      }
      onFinish(false, _this.uploadOptions.parseError(xhr));
    };

    TweetManager.instance.twitterBackend.signOauthEcho(xhr, this.uploadOptions.signingUrl);

    var formData = new FormData();
    for(var param in this.uploadOptions.params) {
      var paramValue = this.uploadOptions.params[param];
      if(paramValue == '$file') {
        paramValue = file;
      }
      formData.append(param, paramValue);
    }

    if(onProgress) {
      xhr.upload.addEventListener("progress", function(e) {
        onProgress(e.loaded, e.total);
      }, false);
    }

    xhr.send(formData);
  };
}

$.extend(ImageService, {
  addService: function(domain, options) {
    this.services = this.services || [];
    this.servicesMap = this.servicesMap || {};
    var service = new ImageService(domain, options);
    this.services.push(service);
    this.servicesMap[domain] = service;
  },

  getThumb: function(url) {
    for(var i = 0, len = this.services.length; i < len; ++i) {
      var service = this.services[i];
      var thumbUrl = service.getThumb(url);
      if(thumbUrl) {
        return thumbUrl;
      }
    }
    return null;
  },

  getService: function(serviceName) {
    return this.servicesMap[serviceName];
  },

  defaultUploadOptions: {
    url: '', // Mandatory
    signingUrl: 'https://api.twitter.com/1/account/verify_credentials.json',
    params: {
      media: '$file'
    },
    dataType: 'json',
    parseError: null, // Mandatory
    parseSuccess: null // Mandatory
  }
});

// $1 is the remaining url after the server and domain name, $2 is the full original url
ImageService.addService('twitpic.com', {
  thumb: 'http://twitpic.com/show/thumb/$1',
  upload: {
    url: 'http://api.twitpic.com/2/upload.json',
    params: {
      key: SecretKeys.twitpic.key
    },
    parseError: function(xhr) {
      var formattedErr;
      if(xhr.responseText) {
        formattedErr = '';
        var errorObj = JSON.parse(xhr.responseText);
        for(var i = 0, len = errorObj.errors.length; i < len; ++i) {
          var error = errorObj.errors[i];
          formattedErr += error.code + ': ' + error.message;
          if(i > 0) {
            formattedErr += '
';
          }
        }
      } else {
        formattedErr = 'Error code: ' + xhr.status;
      }
      return formattedErr;
    },
    parseSuccess: function(obj, xhr) {
      return obj.url;
    }
  }
});

ImageService.addService('yfrog.com', {
 thumb: 'http://yfrog.com/$1.th.jpg',
 upload: {
   url: 'https://yfrog.com/api/xauth_upload',
   params: {
     key: SecretKeys.yfrog.key
   },
   parseError: function(xhr) {
     var errXml = $('err', xhr.responseText);
     var errorStr = 'Error ' + errXml.attr('code') + ': ' + errXml.attr('msg');
     return errorStr;
   },
   parseSuccess: function(obj, xhr) {
     return obj.rsp.mediaurl;
   }
 }
});

ImageService.addService('pict.mobi', {
  thumb: 'http://pict.mobi/show/thumb/$1',
  upload: {
    url: 'http://pict.mobi/upload/',
    dataType: 'xml',
    parseError: function(xhr) {
      return 'Undefined error while uploading.';
    },
    parseSuccess: function(obj, xhr) {
      return obj.text();
    }
  }
});

ImageService.addService('twitshoot.com', {
  thumb: 'http://twitshoot.com/show/thumb/$1',
  upload: {
    url: 'http://twitshoot.com/api/upload.json',
    parseError: function(xhr) {
      return "The upload has failed.";
    },
    parseSuccess: function(obj, xhr) {
		  return obj.image.mediaurl;
    }
  }
});

ImageService.addService('i.imgur.com', {
  thumb: function(path) { return 'http://i.imgur.com/' + path.split('.')[0] + 's.' + path.split('.')[1]; }
});

ImageService.addService('movapic.com', {
  thumb: function(path) { return 'http://image.movapic.com/pic/t_' + path.split('/')[1] + '.jpeg'; }
});
ImageService.addService('tweetphoto.com', {
  thumb: 'http://TweetPhotoAPI.com/api/TPAPI.svc/imagefromurl?url=$2'
});
<|endoftext|>


<commit_before>// Copyright 2014 The Closure Library Authors. 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 test file for testing goog.module.
 */

goog.module('goog.test_module');
goog.setTestOnly('goog.test_module');
goog.module.declareLegacyNamespace();

/** @suppress {extraRequire} */
goog.require('goog.test_module_dep');

/** @constructor */
exports = function() {};
<commit_msg>Add var for extraRequire <commit_after>// Copyright 2014 The Closure Library Authors. 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 test file for testing goog.module.
 */

goog.module('goog.test_module');
goog.setTestOnly('goog.test_module');
goog.module.declareLegacyNamespace();

/** @suppress {extraRequire} */
var testModuleDep = goog.require('goog.test_module_dep');

/** @constructor */
exports = function() {};
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Reset All button.  This version is drawn in code using shapes, gradients,
 * and such, and does not use any image files.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // Includes
  var Circle = require( 'SCENERY/nodes/Circle' );
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Matrix3 = require( 'DOT/Matrix3' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var PushButton = require( 'SUN/PushButton' );
  var RadialGradient = require( 'SCENERY/util/RadialGradient' );
  var Shape = require( 'KITE/Shape' );
  var Vector2 = require( 'DOT/Vector2' );
  var RoundShinyButton = require( 'SCENERY_PHET/RoundShinyButton' );

  // Constants
  var DEFAULT_RADIUS = 32; // Derived from images initially used for reset button.

  /**
   * @param {function} callback
   * @param {Object} options
   * @constructor
   */
  function ResetAllButton( callback, options ) {
    options = _.extend( {
      radius: DEFAULT_RADIUS,

      // Default orange color scheme, standard for PhET reset buttons
//      upFill: new Color( 247, 151, 34 ),
//      overFill: new Color( 251, 171, 39 ),
//      disabledFill: new Color( 180, 180, 180 ),
//      downFill: new Color( 235, 141, 24 ),

      // The arrow shape is not perfectly centered, account for that here, and see docs in RoundShinyButton
      iconOffsetX: 1,
      iconOffsetY: 0
    }, options );
    options.listener = callback;

    // Create the curved arrow shape, starting at the inside of the non-
    // pointed end.  The parameters immediately below can be adjusted in order
    // to tweak the appearance of the arrow.
    var innerRadius = options.radius * 0.4;
    var outerRadius = options.radius * 0.625;
    var headWidth = 2.25 * ( outerRadius - innerRadius );
    var startAngle = -Math.PI * 0.35;
    var endToNeckAngularSpan = -2 * Math.PI * 0.85;
    var arrowHeadAngularSpan = -Math.PI * 0.18;
    //---- End of tweak params ----
    var curvedArrowShape = new Shape();
    curvedArrowShape.moveTo( innerRadius * Math.cos( startAngle ), innerRadius * Math.sin( startAngle ) ); // Inner edge of end.
    curvedArrowShape.lineTo( outerRadius * Math.cos( startAngle ), outerRadius * Math.sin( startAngle ) );
    var neckAngle = startAngle + endToNeckAngularSpan;
    curvedArrowShape.arc( 0, 0, outerRadius, startAngle, neckAngle, true ); // Outer curve.
    var headWidthExtrusion = ( headWidth - ( outerRadius - innerRadius ) ) / 2;
    curvedArrowShape.lineTo(
      ( outerRadius + headWidthExtrusion ) * Math.cos( neckAngle ),
      ( outerRadius + headWidthExtrusion ) * Math.sin( neckAngle ) );
    var pointRadius = ( outerRadius + innerRadius ) * 0.55; // Tweaked a little from center for better look.
    curvedArrowShape.lineTo( // Tip of arrowhead.
      pointRadius * Math.cos( neckAngle + arrowHeadAngularSpan ),
      pointRadius * Math.sin( neckAngle + arrowHeadAngularSpan ) );
    curvedArrowShape.lineTo( ( innerRadius - headWidthExtrusion ) * Math.cos( neckAngle ), ( innerRadius - headWidthExtrusion ) * Math.sin( neckAngle ) );
    curvedArrowShape.lineTo( innerRadius * Math.cos( neckAngle ), innerRadius * Math.sin( neckAngle ) );
    curvedArrowShape.arc( 0, 0, innerRadius, neckAngle, startAngle ); // Inner curve.
    curvedArrowShape.close();

    var icon = new Path( curvedArrowShape, { fill: 'white' } );

    RoundShinyButton.call( this, callback, icon, options );
  }

  return inherit( RoundShinyButton, ResetAllButton );
} );<commit_msg>Put the color back to orange.<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Reset All button.  This version is drawn in code using shapes, gradients,
 * and such, and does not use any image files.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // Includes
  var Circle = require( 'SCENERY/nodes/Circle' );
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Matrix3 = require( 'DOT/Matrix3' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var PushButton = require( 'SUN/PushButton' );
  var RadialGradient = require( 'SCENERY/util/RadialGradient' );
  var Shape = require( 'KITE/Shape' );
  var Vector2 = require( 'DOT/Vector2' );
  var RoundShinyButton = require( 'SCENERY_PHET/RoundShinyButton' );

  // Constants
  var DEFAULT_RADIUS = 32; // Derived from images initially used for reset button.

  /**
   * @param {function} callback
   * @param {Object} options
   * @constructor
   */
  function ResetAllButton( callback, options ) {
    options = _.extend( {
      radius: DEFAULT_RADIUS,

      // Default orange color scheme, standard for PhET reset buttons
      upFill: new Color( 247, 151, 34 ),
      overFill: new Color( 251, 171, 39 ),
      disabledFill: new Color( 180, 180, 180 ),
      downFill: new Color( 235, 141, 24 ),

      // The arrow shape is not perfectly centered, account for that here, and see docs in RoundShinyButton
      iconOffsetX: 1,
      iconOffsetY: 0
    }, options );
    options.listener = callback;

    // Create the curved arrow shape, starting at the inside of the non-
    // pointed end.  The parameters immediately below can be adjusted in order
    // to tweak the appearance of the arrow.
    var innerRadius = options.radius * 0.4;
    var outerRadius = options.radius * 0.625;
    var headWidth = 2.25 * ( outerRadius - innerRadius );
    var startAngle = -Math.PI * 0.35;
    var endToNeckAngularSpan = -2 * Math.PI * 0.85;
    var arrowHeadAngularSpan = -Math.PI * 0.18;
    //---- End of tweak params ----
    var curvedArrowShape = new Shape();
    curvedArrowShape.moveTo( innerRadius * Math.cos( startAngle ), innerRadius * Math.sin( startAngle ) ); // Inner edge of end.
    curvedArrowShape.lineTo( outerRadius * Math.cos( startAngle ), outerRadius * Math.sin( startAngle ) );
    var neckAngle = startAngle + endToNeckAngularSpan;
    curvedArrowShape.arc( 0, 0, outerRadius, startAngle, neckAngle, true ); // Outer curve.
    var headWidthExtrusion = ( headWidth - ( outerRadius - innerRadius ) ) / 2;
    curvedArrowShape.lineTo(
      ( outerRadius + headWidthExtrusion ) * Math.cos( neckAngle ),
      ( outerRadius + headWidthExtrusion ) * Math.sin( neckAngle ) );
    var pointRadius = ( outerRadius + innerRadius ) * 0.55; // Tweaked a little from center for better look.
    curvedArrowShape.lineTo( // Tip of arrowhead.
      pointRadius * Math.cos( neckAngle + arrowHeadAngularSpan ),
      pointRadius * Math.sin( neckAngle + arrowHeadAngularSpan ) );
    curvedArrowShape.lineTo( ( innerRadius - headWidthExtrusion ) * Math.cos( neckAngle ), ( innerRadius - headWidthExtrusion ) * Math.sin( neckAngle ) );
    curvedArrowShape.lineTo( innerRadius * Math.cos( neckAngle ), innerRadius * Math.sin( neckAngle ) );
    curvedArrowShape.arc( 0, 0, innerRadius, neckAngle, startAngle ); // Inner curve.
    curvedArrowShape.close();

    var icon = new Path( curvedArrowShape, { fill: 'white' } );

    RoundShinyButton.call( this, callback, icon, options );
  }

  return inherit( RoundShinyButton, ResetAllButton );
} );<|endoftext|>


<commit_before>// Copyright 2009 The Closure Library Authors. 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 facilities for creating and querying tweaks.
 * @see http://go/jstweaks
 *
 * @author agrieve@google.com (Andrew Grieve)
 */

goog.provide('goog.tweak');
goog.provide('goog.tweak.ConfigParams');

goog.require('goog.asserts');
goog.require('goog.tweak.BooleanGroup');
goog.require('goog.tweak.BooleanInGroupSetting');
goog.require('goog.tweak.BooleanSetting');
goog.require('goog.tweak.ButtonAction');
goog.require('goog.tweak.NumericSetting');
goog.require('goog.tweak.Registry');
goog.require('goog.tweak.StringSetting');

/**
 * Calls to this function are overridden by the compiler by the processTweaks
 * pass. It returns the overrides to default values for tweaks set by compiler
 * options.
 * @return {!Object.<number|string|boolean>} A map of tweakId -> defaultValue.
 * @private
 */
goog.tweak.getCompilerOverrides_ = function() {
  return {};
};

/**
 * The global reference to the registry, if it exists.
 * @type {goog.tweak.Registry}
 * @private
 */
goog.tweak.registry_ = null;

/**
 * The boolean group set by beginBooleanGroup and cleared by endBooleanGroup.
 * @type {goog.tweak.BooleanGroup}
 * @private
 */
goog.tweak.activeBooleanGroup_ = null;

/**
 * Returns/creates the registry singleton.
 * @return {!goog.tweak.Registry} The tweak registry.
 */
goog.tweak.getRegistry = function() {
  if (!goog.tweak.registry_) {
    var queryString = window.location.search;
    var overrides = goog.tweak.getCompilerOverrides_();
    goog.tweak.registry_ = new goog.tweak.Registry(queryString, overrides);
  }
  return goog.tweak.registry_;
};

/**
 * Type for configParams.
 * TODO(agrieve): Remove |Object when optional fields in struct types are
 *     implemented.
 * @typedef {{
 *     label:(string|undefined),
 *     validValues:(!Array.<string>|!Array.<number>|undefined),
 *     paramName:(string|undefined),
 *     restartRequired:(boolean|undefined),
 *     callback:(Function|undefined),
 *     token:(string|undefined)
 *     }|!Object}
 */
goog.tweak.ConfigParams;

/**
 * Silences warning about properties on ConfigParams never being set when
 * running JsLibTest.
 * @return {goog.tweak.ConfigParams} Dummy return.
 * @private
 */
goog.tweak.configParamsNeverCompilerWarningWorkAround_ = function() {
  return {
    label: '',
    validValues: [],
    paramName: '',
    restartRequired: true,
    callback: goog.nullFunction,
    token: ''
  };
};

/**
 * Applies all extra configuration parameters in configParams.
 * @param {!goog.tweak.BaseEntry} entry The entry to apply them to.
 * @param {!goog.tweak.ConfigParams} configParams Extra configuration
 *     parameters.
 * @private
 */
goog.tweak.applyConfigParams_ = function(entry, configParams) {
  if (configParams.label) {
    entry.label = configParams.label;
    delete configParams.label;
  }
  if (configParams.validValues) {
    goog.asserts.assert(entry instanceof goog.tweak.StringSetting ||
        entry instanceof goog.tweak.NumericSetting,
        'Cannot set validValues on tweak: %s', entry.getId());
    entry.setValidValues(configParams.validValues);
    delete configParams.validValues;
  }
  if (goog.isDef(configParams.paramName)) {
    goog.asserts.assertInstanceof(entry, goog.tweak.BaseSetting,
        'Cannot set paramName on tweak: %s', entry.getId());
    entry.setParamName(configParams.paramName);
    delete configParams.paramName;
  }
  if (goog.isDef(configParams.restartRequired)) {
    entry.setRestartRequired(configParams.restartRequired);
    delete configParams.restartRequired;
  }
  if (configParams.callback) {
    entry.addCallback(configParams.callback);
    delete configParams.callback;
    goog.asserts.assert(
        !entry.isRestartRequired() || (configParams.restartRequired == false),
        'Tweak %s should set restartRequired: false, when adding a callback.',
        entry.getId());
  }
  if (configParams.token) {
    goog.asserts.assertInstanceof(entry, goog.tweak.BooleanInGroupSetting,
        'Cannot set token on tweak: %s', entry.getId());
    entry.setToken(configParams.token);
    delete configParams.token;
  }
  for (var key in configParams) {
    goog.asserts.fail('Unknown config options (' + key + '=' +
        configParams[key] + ') for tweak ' + entry.getId());
  }
};

/**
 * Registers a tweak using the given factoryFunc.
 * @param {!goog.tweak.BaseEntry} entry The entry to register.
 * @param {boolean|string|number=} opt_defaultValue Default value.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra
 *     configuration parameters.
 * @private
 */
goog.tweak.doRegister_ = function(entry, opt_defaultValue, opt_configParams) {
  if (opt_configParams) {
    goog.tweak.applyConfigParams_(entry, opt_configParams);
  }
  if (opt_defaultValue != undefined) {
    entry.setDefaultValue(opt_defaultValue);
  }
  if (goog.tweak.activeBooleanGroup_) {
    goog.asserts.assertInstanceof(entry, goog.tweak.BooleanInGroupSetting,
        'Forgot to end Boolean Group: %s',
        goog.tweak.activeBooleanGroup_.getId());
    goog.tweak.activeBooleanGroup_.addChild(
        /** @type {!goog.tweak.BooleanInGroupSetting} */ (entry));
  }
  goog.tweak.getRegistry().register(entry);
};

/**
 * Creates and registers a group of BooleanSettings that are all set by a
 * single query parameter. A call to goog.tweak.endBooleanGroup() must be used
 * to close this group. Only goog.tweak.registerBoolean() calls are allowed with
 * the beginBooleanGroup()/endBooleanGroup().
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the setting does.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
 *     parameters.
 */
goog.tweak.beginBooleanGroup = function(id, description, opt_configParams) {
  var entry = new goog.tweak.BooleanGroup(id, description);
  goog.tweak.doRegister_(entry, undefined, opt_configParams);
  goog.tweak.activeBooleanGroup_ = entry;
};

/**
 * Stops adding boolean entries to the active boolean group.
 */
goog.tweak.endBooleanGroup = function() {
  goog.tweak.activeBooleanGroup_ = null;
};

/**
 * Creates and registers a BooleanSetting.
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the setting does.
 * @param {boolean=} opt_defaultValue The default value for the setting.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
 *     parameters.
 */
goog.tweak.registerBoolean =
    function(id, description, opt_defaultValue, opt_configParams) {
  // TODO(agrieve): There is a bug in the compiler that causes these calls not
  //     to be stripped without this outer if. Might be Issue #90.
  if (goog.tweak.activeBooleanGroup_) {
    var entry = new goog.tweak.BooleanInGroupSetting(id, description,
        goog.tweak.activeBooleanGroup_);
  } else {
    entry = new goog.tweak.BooleanSetting(id, description);
  }
  goog.tweak.doRegister_(entry, opt_defaultValue, opt_configParams);
};

/**
 * Creates and registers a StringSetting.
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the setting does.
 * @param {string=} opt_defaultValue The default value for the setting.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
 *     parameters.
 */
goog.tweak.registerString =
    function(id, description, opt_defaultValue, opt_configParams) {
  goog.tweak.doRegister_(new goog.tweak.StringSetting(id, description),
                         opt_defaultValue, opt_configParams);
};

/**
 * Creates and registers a NumericSetting.
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the setting does.
 * @param {number=} opt_defaultValue The default value for the setting.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
 *     parameters.
 */
goog.tweak.registerNumber =
    function(id, description, opt_defaultValue, opt_configParams) {
  goog.tweak.doRegister_(new goog.tweak.NumericSetting(id, description),
                         opt_defaultValue, opt_configParams);
};

/**
 * Creates and registers a ButtonAction.
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the action does.
 * @param {!Function} callback Function to call when the button is clicked.
 * @param {string=} opt_label The button text (instead of the ID).
 */
goog.tweak.registerButton = function(id, description, callback, opt_label) {
  var tweak = new goog.tweak.ButtonAction(id, description, callback);
  tweak.label = opt_label || tweak.label;
  goog.tweak.doRegister_(tweak);
};

/**
 * Sets a default value to use for the given tweak instead of the one passed
 * to the register* function. This function must be called before the tweak is
 * registered.
 * @param {string} id The unique string that identifies the entry.
 * @param {string|number|boolean} value The new default value for the tweak.
 */
goog.tweak.overrideDefaultValue = function(id, value) {
  goog.tweak.getRegistry().overrideDefaultValue(id, value);
};

/**
 * Returns the value of the boolean setting with the given ID.
 * @param {string} id The unique string that identifies this entry.
 * @return {boolean} The value of the tweak.
 */
goog.tweak.getBoolean = function(id) {
  return goog.tweak.getRegistry().getBooleanSetting(id).getValue();
};

/**
 * Returns the value of the string setting with the given ID,
 * @param {string} id The unique string that identifies this entry.
 * @return {string} The value of the tweak.
 */
goog.tweak.getString = function(id) {
  return goog.tweak.getRegistry().getStringSetting(id).getValue();
};

/**
 * Returns the value of the numeric setting with the given ID.
 * @param {string} id The unique string that identifies this entry.
 * @return {number} The value of the tweak.
 */
goog.tweak.getNumber = function(id) {
  return goog.tweak.getRegistry().getNumericSetting(id).getValue();
};

<commit_msg><commit_after>// Copyright 2009 The Closure Library Authors. 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 facilities for creating and querying tweaks.
 * @see http://code.google.com/p/closure-library/wiki/UsingTweaks
 *
 * @author agrieve@google.com (Andrew Grieve)
 */

goog.provide('goog.tweak');
goog.provide('goog.tweak.ConfigParams');

goog.require('goog.asserts');
goog.require('goog.tweak.BooleanGroup');
goog.require('goog.tweak.BooleanInGroupSetting');
goog.require('goog.tweak.BooleanSetting');
goog.require('goog.tweak.ButtonAction');
goog.require('goog.tweak.NumericSetting');
goog.require('goog.tweak.Registry');
goog.require('goog.tweak.StringSetting');

/**
 * Calls to this function are overridden by the compiler by the processTweaks
 * pass. It returns the overrides to default values for tweaks set by compiler
 * options.
 * @return {!Object.<number|string|boolean>} A map of tweakId -> defaultValue.
 * @private
 */
goog.tweak.getCompilerOverrides_ = function() {
  return {};
};

/**
 * The global reference to the registry, if it exists.
 * @type {goog.tweak.Registry}
 * @private
 */
goog.tweak.registry_ = null;

/**
 * The boolean group set by beginBooleanGroup and cleared by endBooleanGroup.
 * @type {goog.tweak.BooleanGroup}
 * @private
 */
goog.tweak.activeBooleanGroup_ = null;

/**
 * Returns/creates the registry singleton.
 * @return {!goog.tweak.Registry} The tweak registry.
 */
goog.tweak.getRegistry = function() {
  if (!goog.tweak.registry_) {
    var queryString = window.location.search;
    var overrides = goog.tweak.getCompilerOverrides_();
    goog.tweak.registry_ = new goog.tweak.Registry(queryString, overrides);
  }
  return goog.tweak.registry_;
};

/**
 * Type for configParams.
 * TODO(agrieve): Remove |Object when optional fields in struct types are
 *     implemented.
 * @typedef {{
 *     label:(string|undefined),
 *     validValues:(!Array.<string>|!Array.<number>|undefined),
 *     paramName:(string|undefined),
 *     restartRequired:(boolean|undefined),
 *     callback:(Function|undefined),
 *     token:(string|undefined)
 *     }|!Object}
 */
goog.tweak.ConfigParams;

/**
 * Silences warning about properties on ConfigParams never being set when
 * running JsLibTest.
 * @return {goog.tweak.ConfigParams} Dummy return.
 * @private
 */
goog.tweak.configParamsNeverCompilerWarningWorkAround_ = function() {
  return {
    label: '',
    validValues: [],
    paramName: '',
    restartRequired: true,
    callback: goog.nullFunction,
    token: ''
  };
};

/**
 * Applies all extra configuration parameters in configParams.
 * @param {!goog.tweak.BaseEntry} entry The entry to apply them to.
 * @param {!goog.tweak.ConfigParams} configParams Extra configuration
 *     parameters.
 * @private
 */
goog.tweak.applyConfigParams_ = function(entry, configParams) {
  if (configParams.label) {
    entry.label = configParams.label;
    delete configParams.label;
  }
  if (configParams.validValues) {
    goog.asserts.assert(entry instanceof goog.tweak.StringSetting ||
        entry instanceof goog.tweak.NumericSetting,
        'Cannot set validValues on tweak: %s', entry.getId());
    entry.setValidValues(configParams.validValues);
    delete configParams.validValues;
  }
  if (goog.isDef(configParams.paramName)) {
    goog.asserts.assertInstanceof(entry, goog.tweak.BaseSetting,
        'Cannot set paramName on tweak: %s', entry.getId());
    entry.setParamName(configParams.paramName);
    delete configParams.paramName;
  }
  if (goog.isDef(configParams.restartRequired)) {
    entry.setRestartRequired(configParams.restartRequired);
    delete configParams.restartRequired;
  }
  if (configParams.callback) {
    entry.addCallback(configParams.callback);
    delete configParams.callback;
    goog.asserts.assert(
        !entry.isRestartRequired() || (configParams.restartRequired == false),
        'Tweak %s should set restartRequired: false, when adding a callback.',
        entry.getId());
  }
  if (configParams.token) {
    goog.asserts.assertInstanceof(entry, goog.tweak.BooleanInGroupSetting,
        'Cannot set token on tweak: %s', entry.getId());
    entry.setToken(configParams.token);
    delete configParams.token;
  }
  for (var key in configParams) {
    goog.asserts.fail('Unknown config options (' + key + '=' +
        configParams[key] + ') for tweak ' + entry.getId());
  }
};

/**
 * Registers a tweak using the given factoryFunc.
 * @param {!goog.tweak.BaseEntry} entry The entry to register.
 * @param {boolean|string|number=} opt_defaultValue Default value.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra
 *     configuration parameters.
 * @private
 */
goog.tweak.doRegister_ = function(entry, opt_defaultValue, opt_configParams) {
  if (opt_configParams) {
    goog.tweak.applyConfigParams_(entry, opt_configParams);
  }
  if (opt_defaultValue != undefined) {
    entry.setDefaultValue(opt_defaultValue);
  }
  if (goog.tweak.activeBooleanGroup_) {
    goog.asserts.assertInstanceof(entry, goog.tweak.BooleanInGroupSetting,
        'Forgot to end Boolean Group: %s',
        goog.tweak.activeBooleanGroup_.getId());
    goog.tweak.activeBooleanGroup_.addChild(
        /** @type {!goog.tweak.BooleanInGroupSetting} */ (entry));
  }
  goog.tweak.getRegistry().register(entry);
};

/**
 * Creates and registers a group of BooleanSettings that are all set by a
 * single query parameter. A call to goog.tweak.endBooleanGroup() must be used
 * to close this group. Only goog.tweak.registerBoolean() calls are allowed with
 * the beginBooleanGroup()/endBooleanGroup().
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the setting does.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
 *     parameters.
 */
goog.tweak.beginBooleanGroup = function(id, description, opt_configParams) {
  var entry = new goog.tweak.BooleanGroup(id, description);
  goog.tweak.doRegister_(entry, undefined, opt_configParams);
  goog.tweak.activeBooleanGroup_ = entry;
};

/**
 * Stops adding boolean entries to the active boolean group.
 */
goog.tweak.endBooleanGroup = function() {
  goog.tweak.activeBooleanGroup_ = null;
};

/**
 * Creates and registers a BooleanSetting.
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the setting does.
 * @param {boolean=} opt_defaultValue The default value for the setting.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
 *     parameters.
 */
goog.tweak.registerBoolean =
    function(id, description, opt_defaultValue, opt_configParams) {
  // TODO(agrieve): There is a bug in the compiler that causes these calls not
  //     to be stripped without this outer if. Might be Issue #90.
  if (goog.tweak.activeBooleanGroup_) {
    var entry = new goog.tweak.BooleanInGroupSetting(id, description,
        goog.tweak.activeBooleanGroup_);
  } else {
    entry = new goog.tweak.BooleanSetting(id, description);
  }
  goog.tweak.doRegister_(entry, opt_defaultValue, opt_configParams);
};

/**
 * Creates and registers a StringSetting.
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the setting does.
 * @param {string=} opt_defaultValue The default value for the setting.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
 *     parameters.
 */
goog.tweak.registerString =
    function(id, description, opt_defaultValue, opt_configParams) {
  goog.tweak.doRegister_(new goog.tweak.StringSetting(id, description),
                         opt_defaultValue, opt_configParams);
};

/**
 * Creates and registers a NumericSetting.
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the setting does.
 * @param {number=} opt_defaultValue The default value for the setting.
 * @param {goog.tweak.ConfigParams=} opt_configParams Extra configuration
 *     parameters.
 */
goog.tweak.registerNumber =
    function(id, description, opt_defaultValue, opt_configParams) {
  goog.tweak.doRegister_(new goog.tweak.NumericSetting(id, description),
                         opt_defaultValue, opt_configParams);
};

/**
 * Creates and registers a ButtonAction.
 * @param {string} id The unique ID for the setting.
 * @param {string} description A description of what the action does.
 * @param {!Function} callback Function to call when the button is clicked.
 * @param {string=} opt_label The button text (instead of the ID).
 */
goog.tweak.registerButton = function(id, description, callback, opt_label) {
  var tweak = new goog.tweak.ButtonAction(id, description, callback);
  tweak.label = opt_label || tweak.label;
  goog.tweak.doRegister_(tweak);
};

/**
 * Sets a default value to use for the given tweak instead of the one passed
 * to the register* function. This function must be called before the tweak is
 * registered.
 * @param {string} id The unique string that identifies the entry.
 * @param {string|number|boolean} value The new default value for the tweak.
 */
goog.tweak.overrideDefaultValue = function(id, value) {
  goog.tweak.getRegistry().overrideDefaultValue(id, value);
};

/**
 * Returns the value of the boolean setting with the given ID.
 * @param {string} id The unique string that identifies this entry.
 * @return {boolean} The value of the tweak.
 */
goog.tweak.getBoolean = function(id) {
  return goog.tweak.getRegistry().getBooleanSetting(id).getValue();
};

/**
 * Returns the value of the string setting with the given ID,
 * @param {string} id The unique string that identifies this entry.
 * @return {string} The value of the tweak.
 */
goog.tweak.getString = function(id) {
  return goog.tweak.getRegistry().getStringSetting(id).getValue();
};

/**
 * Returns the value of the numeric setting with the given ID.
 * @param {string} id The unique string that identifies this entry.
 * @return {number} The value of the tweak.
 */
goog.tweak.getNumber = function(id) {
  return goog.tweak.getRegistry().getNumericSetting(id).getValue();
};

<|endoftext|>


<commit_before>console.time(PKG.name);

angular
  .module(PKG.name, [

    angular.module(PKG.name+'.features', [
      PKG.name+'.feature.home',
      PKG.name+'.feature.overview',
      PKG.name+'.feature.login',
      PKG.name+'.feature.dashboard',
      PKG.name+'.feature.apps',
      PKG.name+'.feature.data',
      PKG.name+'.feature.admin',
      PKG.name+'.feature.userprofile',
      PKG.name+'.feature.foo',
      PKG.name+'.feature.etlapps',
      PKG.name+'.feature.explore'
    ]).name,

    angular.module(PKG.name+'.commons', [

      angular.module(PKG.name+'.services', [
        PKG.name+'.config',
        'ngAnimate',
        'ngSanitize',
        // 'ngResource',
        'ngStorage',
        'ui.router',
        'cask-angular-window-manager',
        'cask-angular-theme',
        'cask-angular-focus'
      ]).name,

      angular.module(PKG.name+'.filters', [
        PKG.name+'.services',
        'cask-angular-capitalize'
      ]).name,

      'cask-angular-sortable',
      'cask-angular-confirmable',
      'cask-angular-promptable',
      'cask-angular-json-edit',

      'mgcrea.ngStrap.datepicker',
      'mgcrea.ngStrap.timepicker',

      'mgcrea.ngStrap.alert',
      'mgcrea.ngStrap.tooltip',
      'mgcrea.ngStrap.popover',
      'mgcrea.ngStrap.dropdown',
      'mgcrea.ngStrap.typeahead',
      'mgcrea.ngStrap.select',
      'mgcrea.ngStrap.collapse',
      'mgcrea.ngStrap.button',
      'mgcrea.ngStrap.tab',

      // 'mgcrea.ngStrap.modal',
      'ui.bootstrap.modal',
      'ui.bootstrap',

      'mgcrea.ngStrap.modal',

      'ncy-angular-breadcrumb',
      'angularMoment'

    ]).name,

    'angular-loading-bar'
  ])

  .run(function ($rootScope, $state, $stateParams) {
    // It's very handy to add references to $state and $stateParams to the $rootScope
    // so that you can access them from any scope within your applications.For example,
    //
 will set the

    // to active whenever 'contacts.list' or one of its decendents is active.
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    // for debugging... or to trigger easter eggs?
    window.$go = $state.go;
  })

  .config(function ($locationProvider) {
    $locationProvider.html5Mode(true);
  })

  .config(function ($alertProvider) {
    angular.extend($alertProvider.defaults, {
      animation: 'am-fade-and-scale',
      container: '#alerts > .container',
      duration: 3
    });
  })

  .config(function ($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(
      /^\s*(https?|ftp|mailto|tel|file|blob):/
    );
  })

  .config(function (cfpLoadingBarProvider) {
    cfpLoadingBarProvider.includeSpinner = false;
  })

  .config(function (caskThemeProvider) {
    caskThemeProvider.setThemes([
      'cdap',   // customized theme
      'default' // bootstrap default theme
    ]);
  })

  .run(function ($rootScope, MYSOCKET_EVENT, myAlert) {
    $rootScope.$on(MYSOCKET_EVENT.closed, function (angEvent, data) {
      myAlert({
        title: 'Error',
        content: data.reason || 'could not connect to the server',
        type: 'danger'
      });
    });

    $rootScope.$on(MYSOCKET_EVENT.message, function (angEvent, data) {
      if(data.statusCode>399) {
        myAlert({
          title: data.statusCode.toString(),
          content: data.response || 'Something went terribly wrong',
          type: 'danger'
        });
      }

      // The user doesn't need to know that the backend node
      // is unable to connect to CDAP. Error messages add no
      // more value than the pop showing that the FE is waiting
      // for system to come back up. Most of the issues are with
      // connect, other that connect pass everything else to user.
      if(data.warning && data.error.syscall !== 'connect') {
        myAlert({
          content: data.warning,
          type: 'warning'
        });
      }
    });
  })

  .run(function(MyDataSource, EventPipe, MY_CONFIG, $rootScope) {
    // verify backend server is running
    var dataSrc = new MyDataSource($rootScope.$new());
    function pingBackend() {
      dataSrc.poll({
        url: ['http://',
              MY_CONFIG.cdap.routerServerUrl,
              ':',
              MY_CONFIG.cdap.routerServerPort,
              '/status'].join(''),
        interval: 2000
      }, function(res) {
        EventPipe.emit('backendUp');
      }, function(res) {
        if (res.error.code === 'ECONNREFUSED') {
          EventPipe.emit('backendDown');
        }
      });
    }

    pingBackend(); // execute immediately when initially opening a page

  })

  /**
   * BodyCtrl
   * attached to the  tag, mostly responsible for
   *  setting the className based events from $state and caskTheme
   */
  .controller('BodyCtrl', function ($scope, caskTheme, CASK_THEME_EVENT, MyDataSource, EventPipe, MY_CONFIG) {

    var activeThemeClass = caskTheme.getClassName();

    $scope.$on(CASK_THEME_EVENT.changed, function (event, newClassName) {
      if(!event.defaultPrevented) {
        $scope.bodyClass = $scope.bodyClass.replace(activeThemeClass, newClassName);
        activeThemeClass = newClassName;
      }
    });

    $scope.$on('$stateChangeSuccess', function (event, state) {
      var classes = [];
      if(state.data && state.data.bodyClass) {
        classes = [state.data.bodyClass];
      }
      else {
        var parts = state.name.split('.'),
            count = parts.length + 1;
        while (1<count--) {
          classes.push('state-' + parts.slice(0,count).join('-'));
        }
      }

      classes.push(activeThemeClass);

      $scope.bodyClass = classes.join(' ');
    });

    console.timeEnd(PKG.name);
  });
<commit_msg>Modified the error messages to reflect the correct state of the backend to the user and propose right actions<commit_after>console.time(PKG.name);

angular
  .module(PKG.name, [

    angular.module(PKG.name+'.features', [
      PKG.name+'.feature.home',
      PKG.name+'.feature.overview',
      PKG.name+'.feature.login',
      PKG.name+'.feature.dashboard',
      PKG.name+'.feature.apps',
      PKG.name+'.feature.data',
      PKG.name+'.feature.admin',
      PKG.name+'.feature.userprofile',
      PKG.name+'.feature.foo',
      PKG.name+'.feature.etlapps',
      PKG.name+'.feature.explore'
    ]).name,

    angular.module(PKG.name+'.commons', [

      angular.module(PKG.name+'.services', [
        PKG.name+'.config',
        'ngAnimate',
        'ngSanitize',
        // 'ngResource',
        'ngStorage',
        'ui.router',
        'cask-angular-window-manager',
        'cask-angular-theme',
        'cask-angular-focus'
      ]).name,

      angular.module(PKG.name+'.filters', [
        PKG.name+'.services',
        'cask-angular-capitalize'
      ]).name,

      'cask-angular-sortable',
      'cask-angular-confirmable',
      'cask-angular-promptable',
      'cask-angular-json-edit',

      'mgcrea.ngStrap.datepicker',
      'mgcrea.ngStrap.timepicker',

      'mgcrea.ngStrap.alert',
      'mgcrea.ngStrap.tooltip',
      'mgcrea.ngStrap.popover',
      'mgcrea.ngStrap.dropdown',
      'mgcrea.ngStrap.typeahead',
      'mgcrea.ngStrap.select',
      'mgcrea.ngStrap.collapse',
      'mgcrea.ngStrap.button',
      'mgcrea.ngStrap.tab',

      // 'mgcrea.ngStrap.modal',
      'ui.bootstrap.modal',
      'ui.bootstrap',

      'mgcrea.ngStrap.modal',

      'ncy-angular-breadcrumb',
      'angularMoment'

    ]).name,

    'angular-loading-bar'
  ])

  .run(function ($rootScope, $state, $stateParams) {
    // It's very handy to add references to $state and $stateParams to the $rootScope
    // so that you can access them from any scope within your applications.For example,
    //
 will set the

    // to active whenever 'contacts.list' or one of its decendents is active.
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    // for debugging... or to trigger easter eggs?
    window.$go = $state.go;
  })

  .config(function ($locationProvider) {
    $locationProvider.html5Mode(true);
  })

  .config(function ($alertProvider) {
    angular.extend($alertProvider.defaults, {
      animation: 'am-fade-and-scale',
      container: '#alerts > .container',
      duration: 3
    });
  })

  .config(function ($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(
      /^\s*(https?|ftp|mailto|tel|file|blob):/
    );
  })

  .config(function (cfpLoadingBarProvider) {
    cfpLoadingBarProvider.includeSpinner = false;
  })

  .config(function (caskThemeProvider) {
    caskThemeProvider.setThemes([
      'cdap',   // customized theme
      'default' // bootstrap default theme
    ]);
  })

  .run(function ($rootScope, MYSOCKET_EVENT, myAlert) {
    $rootScope.$on(MYSOCKET_EVENT.closed, function (angEvent, data) {
      myAlert({
        title: 'Error',
        content: data.reason || 'Unable to connect to CDAP',
        type: 'danger'
      });
    });

    $rootScope.$on(MYSOCKET_EVENT.message, function (angEvent, data) {
      if(data.statusCode > 399) {
        myAlert({
          title: data.statusCode.toString(),
          content: data.response || 'Server had an issue, please try refreshing the page',
          type: 'danger'
        });
      }

      // The user doesn't need to know that the backend node
      // is unable to connect to CDAP. Error messages add no
      // more value than the pop showing that the FE is waiting
      // for system to come back up. Most of the issues are with
      // connect, other than that pass everything else to user.
      if(data.warning && data.error.syscall !== 'connect') {
        myAlert({
          content: data.warning,
          type: 'warning'
        });
      }
    });
  })

  .run(function(MyDataSource, EventPipe, MY_CONFIG, $rootScope) {
    // verify backend server is running
    var dataSrc = new MyDataSource($rootScope.$new());
    function pingBackend() {
      dataSrc.poll({
        url: ['http://',
              MY_CONFIG.cdap.routerServerUrl,
              ':',
              MY_CONFIG.cdap.routerServerPort,
              '/status'].join(''),
        interval: 2000
      }, function(res) {
        EventPipe.emit('backendUp');
      }, function(res) {
        if (res.error.code === 'ECONNREFUSED') {
          EventPipe.emit('backendDown');
        }
      });
    }

    pingBackend(); // execute immediately when initially opening a page

  })

  /**
   * BodyCtrl
   * attached to the  tag, mostly responsible for
   *  setting the className based events from $state and caskTheme
   */
  .controller('BodyCtrl', function ($scope, caskTheme, CASK_THEME_EVENT, MyDataSource, EventPipe, MY_CONFIG) {

    var activeThemeClass = caskTheme.getClassName();

    $scope.$on(CASK_THEME_EVENT.changed, function (event, newClassName) {
      if(!event.defaultPrevented) {
        $scope.bodyClass = $scope.bodyClass.replace(activeThemeClass, newClassName);
        activeThemeClass = newClassName;
      }
    });

    $scope.$on('$stateChangeSuccess', function (event, state) {
      var classes = [];
      if(state.data && state.data.bodyClass) {
        classes = [state.data.bodyClass];
      }
      else {
        var parts = state.name.split('.'),
            count = parts.length + 1;
        while (1<count--) {
          classes.push('state-' + parts.slice(0,count).join('-'));
        }
      }

      classes.push(activeThemeClass);

      $scope.bodyClass = classes.join(' ');
    });

    console.timeEnd(PKG.name);
  });
<|endoftext|>


<commit_before>'use babel';

import IntelliHelponView from './intelli-helpon-view';
import { CompositeDisposable } from 'atom';

export default {

  intelliHelponView: null,
  modalPanel: null,
  subscriptions: null,
  wordCount : 0,
  activate(state) {
    this.intelliHelponView = new IntelliHelponView(state.intelliHelponViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.intelliHelponView.getElement(),
      visible: false
    });

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'intelli-helpon:toggle': () => this.toggle()
    }));
  },

  deactivate() {
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.intelliHelponView.destroy();
  },

  serialize() {
    return {
      intelliHelponViewState: this.intelliHelponView.serialize()
    };
  },

  toggle() {
    if(this.modalPanel.isVisible())
      this.modalPanel.hide();
    else{
      editor = atom.workspace.getActiveTextEditor();
      filenameArr = editor.getFileName().split(".");
      fileType = filenameArr[filenameArr.length-1];
      alert('You want to find about '+ fileType);//js, md, json, less, java, cpp, h, c
      selection = editor.getSelectedText();
      filetypeMap = {'js':'JavaScript', 'c':'C', 'cpp':'CPP', 'java':'Java'};
      typeMark = "UnSpecific";
      if (fileType in filetypeMap){
          typeMark = filetypeMap[fileType];
      }
      this.intelliHelponView.loadData(selection, typeMark);
      this.intelliHelponView.setHeader(selection);
      this.modalPanel.show();
    }
  }
};
<commit_msg>update<commit_after>'use babel';

import IntelliHelponView from './intelli-helpon-view';
import { CompositeDisposable } from 'atom';

export default {

  intelliHelponView: null,
  modalPanel: null,
  subscriptions: null,
  wordCount : 0,
  activate(state) {
    this.intelliHelponView = new IntelliHelponView(state.intelliHelponViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.intelliHelponView.getElement(),
      visible: false
    });

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'intelli-helpon:toggle': () => this.toggle()
    }));
  },

  deactivate() {
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.intelliHelponView.destroy();
  },

  serialize() {
    return {
      intelliHelponViewState: this.intelliHelponView.serialize()
    };
  },

  toggle() {
    if(this.modalPanel.isVisible())
      this.modalPanel.hide();
    else{
      editor = atom.workspace.getActiveTextEditor();
      filenameArr = editor.getFileName().split(".");
      fileType = filenameArr[filenameArr.length-1];
      //alert('You want to find about '+ fileType);//js, md, json, less, java, cpp, h, c
      selection = editor.getSelectedText();
      filetypeMap = {'js':'JavaScript', 'c':'C', 'cpp':'CPP', 'java':'Java'};
      typeMark = "UnSpecific";
      if (fileType in filetypeMap){
          typeMark = filetypeMap[fileType];
      }
      this.intelliHelponView.loadData(selection, typeMark);
      this.intelliHelponView.setHeader(selection);
      this.modalPanel.show();
    }
  }
};
<|endoftext|>


<commit_before>/**
 * @author: Jeff Thompson
 * See COPYING for copyright and distribution information.
 * Implement getAsync and putAsync used by NDN using nsISocketTransportService.
 * This is used inside Firefox XPCOM modules.
 */

// Assume already imported the following:
// Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
// Components.utils.import("resource://gre/modules/NetUtil.jsm");

var XpcomTransport = function XpcomTransport() {
    this.ndn = null;
    this.socket = null; // nsISocketTransport
    this.outStream = null;
    this.connectedHost = null;
    this.connectedPort = null;

    this.defaultGetHostAndPort = NDN.makeShuffledGetHostAndPort
        (["A.hub.ndn.ucla.edu", "B.hub.ndn.ucla.edu", "C.hub.ndn.ucla.edu", "D.hub.ndn.ucla.edu",
          "E.hub.ndn.ucla.edu", "F.hub.ndn.ucla.edu", "G.hub.ndn.ucla.edu", "H.hub.ndn.ucla.edu"],
         9695);
};

/*
 * Connect to the host and port in ndn.  This replaces a previous connection.
 * Listen on the port to read an entire binary XML encoded element and call
 *    listener.onReceivedElement(data) where data is Uint8Array.
 */
XpcomTransport.prototype.connect = function(ndn, listener) {
    if (this.socket != null) {
        try {
            this.socket.close(0);
        } catch (ex) {
			console.log("XpcomTransport socket.close exception: " + ex);
		}
        this.socket = null;
    }
    this.ndn = ndn;

	var transportService = Components.classes["@mozilla.org/network/socket-transport-service;1"].getService
        (Components.interfaces.nsISocketTransportService);
	var pump = Components.classes["@mozilla.org/network/input-stream-pump;1"].createInstance
        (Components.interfaces.nsIInputStreamPump);
	this.socket = transportService.createTransport(null, 0, ndn.host, ndn.port, null);
    this.connectedHost = ndn.host;
    this.connectedPort = ndn.port;
    this.outStream = this.socket.openOutputStream(1, 0, 0);

    var inStream = this.socket.openInputStream(0, 0, 0);
	var dataListener = {
		dataParts: [],
        structureDecoder: new BinaryXMLStructureDecoder(),

		onStartRequest: function (request, context) {
		},
		onStopRequest: function (request, context, status) {
		},
		onDataAvailable: function (request, context, _inputStream, offset, count) {
			try {
				// Use readInputStreamToString to handle binary data.
                // TODO: Can we go directly from the stream to Uint8Array?
				var rawData = DataUtils.toNumbersFromString
                    (NetUtil.readInputStreamToString(inStream, count));

                // Process multiple objects in this packet.
                while(true) {
                    // Scan the input to check if a whole ccnb object has been read.
                    this.structureDecoder.seek(0);
                    if (this.structureDecoder.findElementEnd(rawData)) {
                        // Got the remainder of an object.  Report to the caller.
                        this.dataParts.push(rawData.subarray(0, this.structureDecoder.offset));
                        listener.onReceivedElement(DataUtils.concatArrays(this.dataParts));

                        // Need to read a new object.
                        rawData = rawData.subarray(this.structureDecoder.offset, rawData.length);
                        this.dataParts = [];
                        this.structureDecoder = new BinaryXMLStructureDecoder();
                        if (rawData.length == 0)
                            // No more data in the packet.
                            return;

                        // else loop back to decode.
                    }
                    else {
                        // Save for a later call to concatArrays so that we only copy data once.
                        this.dataParts.push(rawData);
                        return;
                    }
                }
			} catch (ex) {
				console.log("XpcomTransport.onDataAvailable exception: " + ex);
			}
		}
    };

	pump.init(inStream, -1, -1, 0, 0, true);
    pump.asyncRead(dataListener, null);
};

/*
 * Send the data over the connection created by connect.
 */
XpcomTransport.prototype.send = function(/* Uint8Array */ data) {
    if (this.socket == null) {
        console.log("XpcomTransport connection is not established.");
        return;
    }

    var rawDataString = DataUtils.toString(data);
	this.outStream.write(rawDataString, rawDataString.length);
	this.outStream.flush();
};

XpcomTransport.prototype.expressInterest = function(ndn, interest, closure) {
    var thisXpcomTransport = this;

    if (this.socket == null || this.connectedHost != ndn.host || this.connectedPort != ndn.port) {
      var dataListener = {
		onReceivedElement : function(data) {
			if (data == null || data == undefined || data.length == 0)
				console.log("XpcomTransport: received empty data from socket.");
			else {
                var decoder = new BinaryXMLDecoder(data);
                if (decoder.peekStartElement(CCNProtocolDTags.Interest)) {
                    // TODO: handle interest properly.  For now, assume the only use in getting
                    //   an interest is knowing that the host is alive from NDN.ccndIdFetcher.
					var pitEntry = NDN.getEntryForExpressedInterest(NDN.ccndIdFetcher);
					if (pitEntry != null) {
						// Remove PIT entry from NDN.PITTable.
						var index = NDN.PITTable.indexOf(pitEntry);
						if (index >= 0)
							NDN.PITTable.splice(index, 1);

                        pitEntry.closure.upcall(Closure.UPCALL_INTEREST, null);
                    }
                }
                else if (decoder.peekStartElement(CCNProtocolDTags.ContentObject)) {
                    var co = new ContentObject();
                    co.from_ccnb(decoder);

					var pitEntry = NDN.getEntryForExpressedInterest(co.name);
					if (pitEntry != null) {
						// Remove PIT entry from NDN.PITTable.
                        // TODO: This needs to be a single thread-safe transaction.
						var index = NDN.PITTable.indexOf(pitEntry);
						if (index >= 0)
							NDN.PITTable.splice(index, 1);
                    }
   					if (pitEntry != null) {
						var currentClosure = pitEntry.closure;

                        // TODO: verify the content object and set kind to UPCALL_CONTENT.
                        var result = currentClosure.upcall(Closure.UPCALL_CONTENT_UNVERIFIED,
                                    new UpcallInfo(thisXpcomTransport.ndn, null, 0, co));
                        if (result == Closure.RESULT_OK) {
                            // success
                        }
                        else if (result == Closure.RESULT_ERR)
                            console.log("XpcomTransport: upcall returned RESULT_ERR.");
                        else if (result == Closure.RESULT_REEXPRESS) {
                            // TODO: Handl re-express interest.
                        }
                        else if (result == Closure.RESULT_VERIFY) {
                            // TODO: force verification of content.
                        }
                        else if (result == Closure.RESULT_FETCHKEY) {
                            // TODO: get the key in the key locator and re-call the interest
                            //   with the key available in the local storage.
                        }
                    }
                }
                else
                    console.log('Incoming packet is not Interest or ContentObject. Discard now.');
			}
		}
	  }

      this.connect(ndn, dataListener);
    }

    var binaryInterest = encodeToBinaryInterest(interest);

                        // TODO: This needs to be a single thread-safe transaction.
	var pitEntry = new PITEntry(interest, closure);
	NDN.PITTable.push(pitEntry);

    this.send(binaryInterest);
};
<commit_msg>In onReceivedElement, renamed arg data to element.<commit_after>/**
 * @author: Jeff Thompson
 * See COPYING for copyright and distribution information.
 * Implement getAsync and putAsync used by NDN using nsISocketTransportService.
 * This is used inside Firefox XPCOM modules.
 */

// Assume already imported the following:
// Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
// Components.utils.import("resource://gre/modules/NetUtil.jsm");

var XpcomTransport = function XpcomTransport() {
    this.ndn = null;
    this.socket = null; // nsISocketTransport
    this.outStream = null;
    this.connectedHost = null;
    this.connectedPort = null;

    this.defaultGetHostAndPort = NDN.makeShuffledGetHostAndPort
        (["A.hub.ndn.ucla.edu", "B.hub.ndn.ucla.edu", "C.hub.ndn.ucla.edu", "D.hub.ndn.ucla.edu",
          "E.hub.ndn.ucla.edu", "F.hub.ndn.ucla.edu", "G.hub.ndn.ucla.edu", "H.hub.ndn.ucla.edu"],
         9695);
};

/*
 * Connect to the host and port in ndn.  This replaces a previous connection.
 * Listen on the port to read an entire binary XML encoded element and call
 *    listener.onReceivedElement(element) where element is Uint8Array.
 */
XpcomTransport.prototype.connect = function(ndn, listener) {
    if (this.socket != null) {
        try {
            this.socket.close(0);
        } catch (ex) {
			console.log("XpcomTransport socket.close exception: " + ex);
		}
        this.socket = null;
    }
    this.ndn = ndn;

	var transportService = Components.classes["@mozilla.org/network/socket-transport-service;1"].getService
        (Components.interfaces.nsISocketTransportService);
	var pump = Components.classes["@mozilla.org/network/input-stream-pump;1"].createInstance
        (Components.interfaces.nsIInputStreamPump);
	this.socket = transportService.createTransport(null, 0, ndn.host, ndn.port, null);
    this.connectedHost = ndn.host;
    this.connectedPort = ndn.port;
    this.outStream = this.socket.openOutputStream(1, 0, 0);

    var inStream = this.socket.openInputStream(0, 0, 0);
	var dataListener = {
		dataParts: [],
        structureDecoder: new BinaryXMLStructureDecoder(),

		onStartRequest: function (request, context) {
		},
		onStopRequest: function (request, context, status) {
		},
		onDataAvailable: function (request, context, _inputStream, offset, count) {
			try {
				// Use readInputStreamToString to handle binary data.
                // TODO: Can we go directly from the stream to Uint8Array?
				var rawData = DataUtils.toNumbersFromString
                    (NetUtil.readInputStreamToString(inStream, count));

                // Process multiple objects in this packet.
                while(true) {
                    // Scan the input to check if a whole ccnb object has been read.
                    this.structureDecoder.seek(0);
                    if (this.structureDecoder.findElementEnd(rawData)) {
                        // Got the remainder of an object.  Report to the caller.
                        this.dataParts.push(rawData.subarray(0, this.structureDecoder.offset));
                        listener.onReceivedElement(DataUtils.concatArrays(this.dataParts));

                        // Need to read a new object.
                        rawData = rawData.subarray(this.structureDecoder.offset, rawData.length);
                        this.dataParts = [];
                        this.structureDecoder = new BinaryXMLStructureDecoder();
                        if (rawData.length == 0)
                            // No more data in the packet.
                            return;

                        // else loop back to decode.
                    }
                    else {
                        // Save for a later call to concatArrays so that we only copy data once.
                        this.dataParts.push(rawData);
                        return;
                    }
                }
			} catch (ex) {
				console.log("XpcomTransport.onDataAvailable exception: " + ex);
			}
		}
    };

	pump.init(inStream, -1, -1, 0, 0, true);
    pump.asyncRead(dataListener, null);
};

/*
 * Send the data over the connection created by connect.
 */
XpcomTransport.prototype.send = function(/* Uint8Array */ data) {
    if (this.socket == null) {
        console.log("XpcomTransport connection is not established.");
        return;
    }

    var rawDataString = DataUtils.toString(data);
	this.outStream.write(rawDataString, rawDataString.length);
	this.outStream.flush();
};

XpcomTransport.prototype.expressInterest = function(ndn, interest, closure) {
    var thisXpcomTransport = this;

    if (this.socket == null || this.connectedHost != ndn.host || this.connectedPort != ndn.port) {
      var dataListener = {
		onReceivedElement : function(element) {
            var decoder = new BinaryXMLDecoder(element);
            if (decoder.peekStartElement(CCNProtocolDTags.Interest)) {
                // TODO: handle interest properly.  For now, assume the only use in getting
                //   an interest is knowing that the host is alive from NDN.ccndIdFetcher.
                var pitEntry = NDN.getEntryForExpressedInterest(NDN.ccndIdFetcher);
				if (pitEntry != null) {
					// Remove PIT entry from NDN.PITTable.
					var index = NDN.PITTable.indexOf(pitEntry);
					if (index >= 0)
						NDN.PITTable.splice(index, 1);

                    pitEntry.closure.upcall(Closure.UPCALL_INTEREST, null);
                }
            }
            else if (decoder.peekStartElement(CCNProtocolDTags.ContentObject)) {
                var co = new ContentObject();
                co.from_ccnb(decoder);

				var pitEntry = NDN.getEntryForExpressedInterest(co.name);
				if (pitEntry != null) {
					// Remove PIT entry from NDN.PITTable.
                    // TODO: This needs to be a single thread-safe transaction.
					var index = NDN.PITTable.indexOf(pitEntry);
					if (index >= 0)
						NDN.PITTable.splice(index, 1);
                }
   				if (pitEntry != null) {
					var currentClosure = pitEntry.closure;

                    // TODO: verify the content object and set kind to UPCALL_CONTENT.
                    var result = currentClosure.upcall(Closure.UPCALL_CONTENT_UNVERIFIED,
                                new UpcallInfo(thisXpcomTransport.ndn, null, 0, co));
                    if (result == Closure.RESULT_OK) {
                        // success
                    }
                    else if (result == Closure.RESULT_ERR)
                        console.log("XpcomTransport: upcall returned RESULT_ERR.");
                    else if (result == Closure.RESULT_REEXPRESS) {
                        // TODO: Handl re-express interest.
                    }
                    else if (result == Closure.RESULT_VERIFY) {
                        // TODO: force verification of content.
                    }
                    else if (result == Closure.RESULT_FETCHKEY) {
                        // TODO: get the key in the key locator and re-call the interest
                        //   with the key available in the local storage.
                    }
                }
            }
            else
                console.log('Incoming packet is not Interest or ContentObject. Discard now.');
		}
	  }

      this.connect(ndn, dataListener);
    }

    var binaryInterest = encodeToBinaryInterest(interest);

                        // TODO: This needs to be a single thread-safe transaction.
	var pitEntry = new PITEntry(interest, closure);
	NDN.PITTable.push(pitEntry);

    this.send(binaryInterest);
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule react-native-implementation
 * @noflow - get/set properties not yet supported by flow. also `...require(x)` is broken #6560135
 */
'use strict';

const warning = require('fbjs/lib/warning');

if (__DEV__) {
  var warningDedupe = {};
  var addonWarn = function(prevName, newPackageName) {
    warning(
      warningDedupe[prevName],
      'React.addons.' + prevName + ' is deprecated. Please import the "' +
      newPackageName + '" package instead.'
    );
    warningDedupe[prevName] = true;
  };
}

// Export React, plus some native additions.
const ReactNative = {
  // Components
  get AccessibilityInfo() { return require('AccessibilityInfo'); },
  get ActivityIndicator() { return require('ActivityIndicator'); },
  get ART() { return require('ReactNativeART'); },
  get Button() { return require('Button'); },
  get DatePickerIOS() { return require('DatePickerIOS'); },
  get DrawerLayoutAndroid() { return require('DrawerLayoutAndroid'); },
  get FlatList() { return require('FlatList'); },
  get Image() { return require('Image'); },
  get ImageEditor() { return require('ImageEditor'); },
  get ImageStore() { return require('ImageStore'); },
  get KeyboardAvoidingView() { return require('KeyboardAvoidingView'); },
  get ListView() { return require('ListView'); },
  get Modal() { return require('Modal'); },
  get Navigator() { return require('Navigator'); },
  get NavigatorIOS() { return require('NavigatorIOS'); },
  get Picker() { return require('Picker'); },
  get PickerIOS() { return require('PickerIOS'); },
  get ProgressBarAndroid() { return require('ProgressBarAndroid'); },
  get ProgressViewIOS() { return require('ProgressViewIOS'); },
  get ScrollView() { return require('ScrollView'); },
  get SectionList() { return require('SectionList'); },
  get SegmentedControlIOS() { return require('SegmentedControlIOS'); },
  get Slider() { return require('Slider'); },
  get SnapshotViewIOS() { return require('SnapshotViewIOS'); },
  get Switch() { return require('Switch'); },
  get RefreshControl() { return require('RefreshControl'); },
  get StatusBar() { return require('StatusBar'); },
  get SwipeableListView() { return require('SwipeableListView'); },
  get TabBarIOS() { return require('TabBarIOS'); },
  get Text() { return require('Text'); },
  get TextInput() { return require('TextInput'); },
  get ToastAndroid() { return require('ToastAndroid'); },
  get ToolbarAndroid() { return require('ToolbarAndroid'); },
  get Touchable() { return require('Touchable'); },
  get TouchableHighlight() { return require('TouchableHighlight'); },
  get TouchableNativeFeedback() { return require('TouchableNativeFeedback'); },
  get TouchableOpacity() { return require('TouchableOpacity'); },
  get TouchableWithoutFeedback() { return require('TouchableWithoutFeedback'); },
  get View() { return require('View'); },
  get ViewPagerAndroid() { return require('ViewPagerAndroid'); },
  get VirtualizedList() { return require('VirtualizedList'); },
  get WebView() { return require('WebView'); },

  // APIs
  get ActionSheetIOS() { return require('ActionSheetIOS'); },
  get AdSupportIOS() { return require('AdSupportIOS'); },
  get Alert() { return require('Alert'); },
  get AlertIOS() { return require('AlertIOS'); },
  get Animated() { return require('Animated'); },
  get AppRegistry() { return require('AppRegistry'); },
  get AppState() { return require('AppState'); },
  get AsyncStorage() { return require('AsyncStorage'); },
  get BackAndroid() { return require('BackAndroid'); }, // deprecated: use BackHandler instead
  get BackHandler() { return require('BackHandler'); },
  get CameraRoll() { return require('CameraRoll'); },
  get Clipboard() { return require('Clipboard'); },
  get DatePickerAndroid() { return require('DatePickerAndroid'); },
  get DeviceInfo() { return require('DeviceInfo'); },
  get Dimensions() { return require('Dimensions'); },
  get Easing() { return require('Easing'); },
  get I18nManager() { return require('I18nManager'); },
  get ImagePickerIOS() { return require('ImagePickerIOS'); },
  get InteractionManager() { return require('InteractionManager'); },
  get Keyboard() { return require('Keyboard'); },
  get LayoutAnimation() { return require('LayoutAnimation'); },
  get Linking() { return require('Linking'); },
  get NativeEventEmitter() { return require('NativeEventEmitter'); },
  get NetInfo() { return require('NetInfo'); },
  get PanResponder() { return require('PanResponder'); },
  get PermissionsAndroid() { return require('PermissionsAndroid'); },
  get PixelRatio() { return require('PixelRatio'); },
  get PushNotificationIOS() { return require('PushNotificationIOS'); },
  get Settings() { return require('Settings'); },
  get Share() { return require('Share'); },
  get StatusBarIOS() { return require('StatusBarIOS'); },
  get StyleSheet() { return require('StyleSheet'); },
  get Systrace() { return require('Systrace'); },
  get TimePickerAndroid() { return require('TimePickerAndroid'); },
  get TVEventHandler() { return require('TVEventHandler'); },
  get UIManager() { return require('UIManager'); },
  get Vibration() { return require('Vibration'); },
  get VibrationIOS() { return require('VibrationIOS'); },

  // Plugins
  get DeviceEventEmitter() { return require('RCTDeviceEventEmitter'); },
  get NativeAppEventEmitter() { return require('RCTNativeAppEventEmitter'); },
  get NativeModules() { return require('NativeModules'); },
  get Platform() { return require('Platform'); },
  get processColor() { return require('processColor'); },
  get requireNativeComponent() { return require('requireNativeComponent'); },

  // Prop Types
  get ColorPropType() { return require('ColorPropType'); },
  get EdgeInsetsPropType() { return require('EdgeInsetsPropType'); },
  get PointPropType() { return require('PointPropType'); },
};

// Better error messages when accessing React APIs on ReactNative
if (__DEV__) {
  const throwOnWrongReactAPI = require('throwOnWrongReactAPI');
  const reactAPIs = [ 'createClass', 'Component' ];

  for (const key of reactAPIs) {
    Object.defineProperty(ReactNative, key, {
      get() { throwOnWrongReactAPI(key); },
      enumerable: false,
      configurable: false,
    });
  }
}

// Preserve getters with warnings on the internal ReactNative copy without
// invoking them.
const ReactNativeInternal = require('ReactNative');
function applyForwarding(key) {
  if (__DEV__) {
    Object.defineProperty(
      ReactNative,
      key,
      Object.getOwnPropertyDescriptor(ReactNativeInternal, key)
    );
    return;
  }
  ReactNative[key] = ReactNativeInternal[key];
}
for (const key in ReactNativeInternal) {
  applyForwarding(key);
}
module.exports = ReactNative;
<commit_msg>Exposed new ViewPropTypes object on ReactNative renderer (stack and fiber)<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule react-native-implementation
 * @noflow - get/set properties not yet supported by flow. also `...require(x)` is broken #6560135
 */
'use strict';

const warning = require('fbjs/lib/warning');

if (__DEV__) {
  var warningDedupe = {};
  var addonWarn = function(prevName, newPackageName) {
    warning(
      warningDedupe[prevName],
      'React.addons.' + prevName + ' is deprecated. Please import the "' +
      newPackageName + '" package instead.'
    );
    warningDedupe[prevName] = true;
  };
}

// Export React, plus some native additions.
const ReactNative = {
  // Components
  get AccessibilityInfo() { return require('AccessibilityInfo'); },
  get ActivityIndicator() { return require('ActivityIndicator'); },
  get ART() { return require('ReactNativeART'); },
  get Button() { return require('Button'); },
  get DatePickerIOS() { return require('DatePickerIOS'); },
  get DrawerLayoutAndroid() { return require('DrawerLayoutAndroid'); },
  get FlatList() { return require('FlatList'); },
  get Image() { return require('Image'); },
  get ImageEditor() { return require('ImageEditor'); },
  get ImageStore() { return require('ImageStore'); },
  get KeyboardAvoidingView() { return require('KeyboardAvoidingView'); },
  get ListView() { return require('ListView'); },
  get Modal() { return require('Modal'); },
  get Navigator() { return require('Navigator'); },
  get NavigatorIOS() { return require('NavigatorIOS'); },
  get Picker() { return require('Picker'); },
  get PickerIOS() { return require('PickerIOS'); },
  get ProgressBarAndroid() { return require('ProgressBarAndroid'); },
  get ProgressViewIOS() { return require('ProgressViewIOS'); },
  get ScrollView() { return require('ScrollView'); },
  get SectionList() { return require('SectionList'); },
  get SegmentedControlIOS() { return require('SegmentedControlIOS'); },
  get Slider() { return require('Slider'); },
  get SnapshotViewIOS() { return require('SnapshotViewIOS'); },
  get Switch() { return require('Switch'); },
  get RefreshControl() { return require('RefreshControl'); },
  get StatusBar() { return require('StatusBar'); },
  get SwipeableListView() { return require('SwipeableListView'); },
  get TabBarIOS() { return require('TabBarIOS'); },
  get Text() { return require('Text'); },
  get TextInput() { return require('TextInput'); },
  get ToastAndroid() { return require('ToastAndroid'); },
  get ToolbarAndroid() { return require('ToolbarAndroid'); },
  get Touchable() { return require('Touchable'); },
  get TouchableHighlight() { return require('TouchableHighlight'); },
  get TouchableNativeFeedback() { return require('TouchableNativeFeedback'); },
  get TouchableOpacity() { return require('TouchableOpacity'); },
  get TouchableWithoutFeedback() { return require('TouchableWithoutFeedback'); },
  get View() { return require('View'); },
  get ViewPagerAndroid() { return require('ViewPagerAndroid'); },
  get VirtualizedList() { return require('VirtualizedList'); },
  get WebView() { return require('WebView'); },

  // APIs
  get ActionSheetIOS() { return require('ActionSheetIOS'); },
  get AdSupportIOS() { return require('AdSupportIOS'); },
  get Alert() { return require('Alert'); },
  get AlertIOS() { return require('AlertIOS'); },
  get Animated() { return require('Animated'); },
  get AppRegistry() { return require('AppRegistry'); },
  get AppState() { return require('AppState'); },
  get AsyncStorage() { return require('AsyncStorage'); },
  get BackAndroid() { return require('BackAndroid'); }, // deprecated: use BackHandler instead
  get BackHandler() { return require('BackHandler'); },
  get CameraRoll() { return require('CameraRoll'); },
  get Clipboard() { return require('Clipboard'); },
  get DatePickerAndroid() { return require('DatePickerAndroid'); },
  get DeviceInfo() { return require('DeviceInfo'); },
  get Dimensions() { return require('Dimensions'); },
  get Easing() { return require('Easing'); },
  get I18nManager() { return require('I18nManager'); },
  get ImagePickerIOS() { return require('ImagePickerIOS'); },
  get InteractionManager() { return require('InteractionManager'); },
  get Keyboard() { return require('Keyboard'); },
  get LayoutAnimation() { return require('LayoutAnimation'); },
  get Linking() { return require('Linking'); },
  get NativeEventEmitter() { return require('NativeEventEmitter'); },
  get NetInfo() { return require('NetInfo'); },
  get PanResponder() { return require('PanResponder'); },
  get PermissionsAndroid() { return require('PermissionsAndroid'); },
  get PixelRatio() { return require('PixelRatio'); },
  get PushNotificationIOS() { return require('PushNotificationIOS'); },
  get Settings() { return require('Settings'); },
  get Share() { return require('Share'); },
  get StatusBarIOS() { return require('StatusBarIOS'); },
  get StyleSheet() { return require('StyleSheet'); },
  get Systrace() { return require('Systrace'); },
  get TimePickerAndroid() { return require('TimePickerAndroid'); },
  get TVEventHandler() { return require('TVEventHandler'); },
  get UIManager() { return require('UIManager'); },
  get Vibration() { return require('Vibration'); },
  get VibrationIOS() { return require('VibrationIOS'); },

  // Plugins
  get DeviceEventEmitter() { return require('RCTDeviceEventEmitter'); },
  get NativeAppEventEmitter() { return require('RCTNativeAppEventEmitter'); },
  get NativeModules() { return require('NativeModules'); },
  get Platform() { return require('Platform'); },
  get processColor() { return require('processColor'); },
  get requireNativeComponent() { return require('requireNativeComponent'); },

  // Prop Types
  get ColorPropType() { return require('ColorPropType'); },
  get EdgeInsetsPropType() { return require('EdgeInsetsPropType'); },
  get PointPropType() { return require('PointPropType'); },
  get ViewPropTypes() { return require('ViewPropTypes'); },
};

// Better error messages when accessing React APIs on ReactNative
if (__DEV__) {
  const throwOnWrongReactAPI = require('throwOnWrongReactAPI');
  const reactAPIs = [ 'createClass', 'Component' ];

  for (const key of reactAPIs) {
    Object.defineProperty(ReactNative, key, {
      get() { throwOnWrongReactAPI(key); },
      enumerable: false,
      configurable: false,
    });
  }
}

// Preserve getters with warnings on the internal ReactNative copy without
// invoking them.
const ReactNativeInternal = require('ReactNative');
function applyForwarding(key) {
  if (__DEV__) {
    Object.defineProperty(
      ReactNative,
      key,
      Object.getOwnPropertyDescriptor(ReactNativeInternal, key)
    );
    return;
  }
  ReactNative[key] = ReactNativeInternal[key];
}
for (const key in ReactNativeInternal) {
  applyForwarding(key);
}
module.exports = ReactNative;
<|endoftext|>