<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS_ERROR_HANDLING_HPP__
#define __STAN__PROB__DISTRIBUTIONS_ERROR_HANDLING_HPP__

#include <boost/math/policies/policy.hpp>

#include "stan/agrad/agrad.hpp"

namespace stan {
  namespace prob {
    // reimplementing a lot from: #include <boost/math/distributions/detail/common_error_handling.hpp>
    template <typename T>
    inline double convert (const T& x) {
      return x;
    }
    template <>
    inline double convert (const stan::agrad::var& x) {
      return x.val();
    }

    template <typename T_x, typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const T_x& x,
			T_result* result,
			const Policy& pol) {
      if (!(boost::math::isfinite)(convert(x))) {
	*result = boost::math::policies::raise_domain_error<double>(function,
								 "Random variate x is %1%, but must be finite!",
								 convert(x), pol);
	return false;
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    }

    /*template <typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const stan::agrad::var& x,
			T_result* result,
			const Policy& pol) {
      if(!(boost::math::isfinite)(x.val())) {
	*result = boost::math::policies::raise_domain_error<double>(function,
								    "Random variate x is %1%, but must be finite!", x.val(), pol);
	return false;
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    } // bool check_x
    */

    template <typename T_x, typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const std::vector<T_x>& x,
			T_result* result,
			const Policy& pol) {
      for (int i = 0; i < x.size(); i++) {
	if (!(boost::math::isfinite)(convert(x[i]))) {
	  *result = boost::math::policies::raise_domain_error<double>(function,
								   "Random variate x is %1%, but must be finite!",
								   convert(x[i]), pol);
	  return false;
	}
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    }

  /*template <typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const std::vector<stan::agrad::var>& x,
			T_result* result,
			const Policy& pol) {
      for (int i = 0; i < x.size(); i++) {
	if (!(boost::math::isfinite)(x[i].val())) {
	  *result = boost::math::policies::raise_domain_error<double>(function,
								      "Random variate x is %1%, but must be finite!",
								      x[i].val(), pol);
	  return false;
	}
	return true;
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    } // bool check_x
  */

    template <typename T_x, typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const Eigen::Matrix<T_x,Eigen::Dynamic,1>& x,
			T_result* result,
			const Policy& pol) {
      for (int i = 0; i < x.rows(); i++) {
	if (!(boost::math::isfinite)(convert(x[i]))) {
	  *result = boost::math::policies::raise_domain_error<double>(function,
								   "Random variate x is %1%, but must be finite!",
								   convert(x[i]), pol);
	  return false;
	}
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    }

/*
    template <typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const Eigen::Matrix<stan::agrad::var,Eigen::Dynamic,1>& x,
			T_result* result,
			const Policy& pol) {
      for (int i = 0; i < x.rows(); i++) {
	if (!(boost::math::isfinite)(x[i].val())) {
	  *result = boost::math::policies::raise_domain_error<double>(function,
								      "Random variate x is %1%, but must be finite!",
								      x[i].val(), pol);
	  return false;
	}
	return true;
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    } // bool check_x
*/

    template <typename T_scale, typename T_result, class Policy>
    inline bool check_scale(
			    const char* function,
			    const T_scale& scale,
			    T_result* result,
			    const Policy& pol) {
      if((scale <= 0) || !(boost::math::isfinite)(convert(scale))) { // Assume scale == 0 is NOT valid for any distribution.
	*result = boost::math::policies::raise_domain_error<double>(
								     function,
								     "Scale parameter is %1%, but must be > 0 !", convert(scale), pol);
	return false;
      }
      return true;
    }

/*
    template <typename T_result, class Policy>
    inline bool check_scale(
			    const char* function,
			    const stan::agrad::var& scale,
			    T_result* result,
			    const Policy& pol)
    {
      if((scale <= 0) || !(boost::math::isfinite)(scale.val())) { // Assume scale == 0 is NOT valid for any distribution.
	*result = boost::math::policies::raise_domain_error<double>(
								    function,
								    "Scale parameter is %1%, but must be > 0 !", scale.val(), pol);
	return false;
      }
      return true;
    }
*/

    template <typename T_x, typename T_result, class Policy>
    inline bool check_nonnegative(
				  const char* function,
				  const T_x& x,
				  const char* name,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(convert(x)) || !(x >= 0)) {
	std::ostringstream stream;
	stream << name << " is %1%, but must be finite and >= 0!";
	*result = boost::math::policies::raise_domain_error<double>(
								 function,
								 stream.str().c_str(), convert(x), pol);
	return false;
      }
      return true;
    }

/*
template <typename T_result, class Policy>
    inline bool check_nonnegative(
				  const char* function,
				  const stan::agrad::var& x,
				  const char* name,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(x.val()) || !(x >= 0)) {
	std::ostringstream stream;
	stream << name << " is %1%, but must be finite and >= 0!";
	*result = boost::math::policies::raise_domain_error<double>(
								    function,
								    stream.str().c_str(), x.val(), pol);
	return false;
      }
      return true;
    }
*/

    template <typename T_x, typename T_result, class Policy>
    inline bool check_positive(
				  const char* function,
				  const T_x& x,
				  const char* name,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(convert(x)) || !(x > 0)) {
	std::ostringstream stream;
	stream << name << " is %1%, but must be finite and > 0!";
	*result = boost::math::policies::raise_domain_error<double>(
								 function,
								 stream.str().c_str(), convert(x), pol);
	return false;
      }
      return true;
    }
/*
    template <typename T_result, class Policy>
    inline bool check_positive(
				  const char* function,
				  const stan::agrad::var& x,
				  const char* name,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(x.val()) || !(x > 0)) {
	std::ostringstream stream;
	stream << name << " is %1%, but must be finite and > 0!";
	*result = boost::math::policies::raise_domain_error<double>(
								    function,
								    stream.str().c_str(), x.val(), pol);
	return false;
      }
      return true;
    }
*/

    template <typename T_location, typename T_result, class Policy>
    inline bool check_location(
			       const char* function,
			       const T_location& location,
			       T_result* result,
			       const Policy& pol) {
      if(!(boost::math::isfinite)(convert(location))) {
	*result = boost::math::policies::raise_domain_error<double>(
									function,
									"Location parameter is %1%, but must be finite!", convert(location), pol);
	return false;
      }
      return true;
    }

/*
    template <typename T_result, class Policy>
    inline bool check_location(
			       const char* function,
			       const stan::agrad::var& location,
			       T_result* result,
			       const Policy& pol) {
      if(!(boost::math::isfinite)(location.val()))
	{
	  *result = boost::math::policies::raise_domain_error<double>(
								      function,
								      "Location parameter is %1%, but must be finite!", location.val(), pol);
	  return false;
	}
      return true;
    }
*/

    template <typename T_bound, typename T_result, class Policy>
    inline bool check_lower_bound(
				  const char* function,
				  const T_bound& lb,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(convert(lb))) {
	*result = boost::math::policies::raise_domain_error<double>(
								     function,
								     "Lower bound is %1%, but must be finite!", convert(lb), pol);
	return false;
      }
      return true;
    }

/*
    template <typename T_result, class Policy>
    inline bool check_lower_bound(
				  const char* function,
				  const stan::agrad::var& lb,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(lb.val()))
	{
	  *result = boost::math::policies::raise_domain_error<double>(
								      function,
								      "Lower bound is %1%, but must be finite!", lb.val(), pol);
	  return false;
	}
      return true;
    }
*/
    template <typename T_bound, typename T_result, class Policy>
    inline bool check_upper_bound(
				  const char* function,
				  const T_bound& ub,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(convert(ub))) {
	*result = boost::math::policies::raise_domain_error<double>(
								     function,
								     "Upper bound is %1%, but must be finite!", convert(ub), pol);
	return false;
      }
      return true;
    }

    /*
    template <typename T_result, class Policy>
    inline bool check_upper_bound(
				  const char* function,
				  const stan::agrad::var& ub,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(ub.val()))
	{
	  *result = boost::math::policies::raise_domain_error<double>(
								      function,
								      "Upper bound is %1%, but must be finite!", ub.val(), pol);
	  return false;
	}
      return true;
    }
    */

    template <typename T_lb, typename T_ub, typename T_result, class Policy>
    inline bool check_bounds(
			     const char* function,
			     const T_lb& lower,
			     const T_ub& upper,
			     T_result* result,
			     const Policy& pol) {
      if (false == check_lower_bound(function, lower, result, pol))
	return false;
      if (false == check_upper_bound(function, upper, result, pol))
	return false;
      if (lower >= upper) {
	*result = boost::math::policies::raise_domain_error<double>(function,
								  "lower parameter is %1%, but must be less than upper!", convert(lower), pol);
	return false;
      }
      return true;
    }

    /*
    template <typename T_ub, typename T_result, class Policy>
    inline bool check_bounds(
			     const char* function,
			     const stan::agrad::var& lower,
			     const T_ub& upper,
			     T_result* result,
			     const Policy& pol) {
      if (false == check_lower_bound(function, lower, result, pol))
	return false;
      if (false == check_upper_bound(function, upper, result, pol))
	return false;
      if (lower >= upper) {
	*result = boost::math::policies::raise_domain_error<double>(function,
								    "lower parameter is %1%, but must be less than upper!", lower.val(), pol);
	return false;
      }
      return true;
    }
    */

    template <typename T_covar, typename T_result, class Policy>
    inline bool check_cov_matrix(
				 const char* function,
				 const Matrix<T_covar,Dynamic,Dynamic>& Sigma,
				 T_result* result,
				 const Policy& pol) {
      if (!stan::prob::cov_matrix_validate(Sigma)) {
	std::ostringstream stream;
	stream << "Sigma is not a valid covariance matrix. Sigma must be symmetric and positive semi-definite. Sigma: \n"<< Sigma << "\nSigma(0,0): %1%";
	*result = boost::math::policies::raise_domain_error<double>(function,
								     stream.str().c_str(),
								     convert(Sigma(0,0)),
								     pol);
	return false;
      }
      return true;
    }

    /*
    template <typename T_result, class Policy>
    inline bool check_cov_matrix(
				 const char* function,
				 const Matrix<stan::agrad::var,Dynamic,Dynamic>& Sigma,
				 T_result* result,
				 const Policy& pol) {
      if (!stan::prob::cov_matrix_validate(Sigma)) {
	std::ostringstream stream;
	stream << "Sigma is not a valid covariance matrix. Sigma must be symmetric and positive semi-definite. Sigma: \n"<< Sigma << "\nSigma(0,0): %1%";
	*result = boost::math::policies::raise_domain_error<double>(function,
								    stream.str().c_str(),
								    Sigma(0,0),
								    pol);
	return false;
      }
      return true;
    }
    */

  }
}
#endif
<commit_msg>distributions: removed unused code<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS_ERROR_HANDLING_HPP__
#define __STAN__PROB__DISTRIBUTIONS_ERROR_HANDLING_HPP__

#include <boost/math/policies/policy.hpp>

#include "stan/agrad/agrad.hpp"

namespace stan {
  namespace prob {
    // reimplementing a lot from: #include <boost/math/distributions/detail/common_error_handling.hpp>
    template <typename T>
    inline double convert (const T& x) {
      return x;
    }
    template <>
    inline double convert (const stan::agrad::var& x) {
      return x.val();
    }

    template <typename T_x, typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const T_x& x,
			T_result* result,
			const Policy& pol) {
      if (!(boost::math::isfinite)(convert(x))) {
	*result = boost::math::policies::raise_domain_error<double>(function,
								 "Random variate x is %1%, but must be finite!",
								 convert(x), pol);
	return false;
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    }

    template <typename T_x, typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const std::vector<T_x>& x,
			T_result* result,
			const Policy& pol) {
      for (int i = 0; i < x.size(); i++) {
	if (!(boost::math::isfinite)(convert(x[i]))) {
	  *result = boost::math::policies::raise_domain_error<double>(function,
								   "Random variate x is %1%, but must be finite!",
								   convert(x[i]), pol);
	  return false;
	}
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    }

    template <typename T_x, typename T_result, class Policy>
    inline bool check_x(
			const char* function,
			const Eigen::Matrix<T_x,Eigen::Dynamic,1>& x,
			T_result* result,
			const Policy& pol) {
      for (int i = 0; i < x.rows(); i++) {
	if (!(boost::math::isfinite)(convert(x[i]))) {
	  *result = boost::math::policies::raise_domain_error<double>(function,
								   "Random variate x is %1%, but must be finite!",
								   convert(x[i]), pol);
	  return false;
	}
      }
      return true;
      // Note that this test catches both infinity and NaN.
      // Some special cases permit x to be infinite, so these must be tested 1st,
      // leaving this test to catch any NaNs.  see Normal and cauchy for example.
    }

    template <typename T_scale, typename T_result, class Policy>
    inline bool check_scale(
			    const char* function,
			    const T_scale& scale,
			    T_result* result,
			    const Policy& pol) {
      if((scale <= 0) || !(boost::math::isfinite)(convert(scale))) { // Assume scale == 0 is NOT valid for any distribution.
	*result = boost::math::policies::raise_domain_error<double>(
								     function,
								     "Scale parameter is %1%, but must be > 0 !", convert(scale), pol);
	return false;
      }
      return true;
    }

    template <typename T_x, typename T_result, class Policy>
    inline bool check_nonnegative(
				  const char* function,
				  const T_x& x,
				  const char* name,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(convert(x)) || !(x >= 0)) {
	std::ostringstream stream;
	stream << name << " is %1%, but must be finite and >= 0!";
	*result = boost::math::policies::raise_domain_error<double>(
								 function,
								 stream.str().c_str(), convert(x), pol);
	return false;
      }
      return true;
    }

    template <typename T_x, typename T_result, class Policy>
    inline bool check_positive(
				  const char* function,
				  const T_x& x,
				  const char* name,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(convert(x)) || !(x > 0)) {
	std::ostringstream stream;
	stream << name << " is %1%, but must be finite and > 0!";
	*result = boost::math::policies::raise_domain_error<double>(
								 function,
								 stream.str().c_str(), convert(x), pol);
	return false;
      }
      return true;
    }

    template <typename T_location, typename T_result, class Policy>
    inline bool check_location(
			       const char* function,
			       const T_location& location,
			       T_result* result,
			       const Policy& pol) {
      if(!(boost::math::isfinite)(convert(location))) {
	*result = boost::math::policies::raise_domain_error<double>(
									function,
									"Location parameter is %1%, but must be finite!", convert(location), pol);
	return false;
      }
      return true;
    }

    template <typename T_bound, typename T_result, class Policy>
    inline bool check_lower_bound(
				  const char* function,
				  const T_bound& lb,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(convert(lb))) {
	*result = boost::math::policies::raise_domain_error<double>(
								     function,
								     "Lower bound is %1%, but must be finite!", convert(lb), pol);
	return false;
      }
      return true;
    }

    template <typename T_bound, typename T_result, class Policy>
    inline bool check_upper_bound(
				  const char* function,
				  const T_bound& ub,
				  T_result* result,
				  const Policy& pol) {
      if(!(boost::math::isfinite)(convert(ub))) {
	*result = boost::math::policies::raise_domain_error<double>(
								     function,
								     "Upper bound is %1%, but must be finite!", convert(ub), pol);
	return false;
      }
      return true;
    }

    template <typename T_lb, typename T_ub, typename T_result, class Policy>
    inline bool check_bounds(
			     const char* function,
			     const T_lb& lower,
			     const T_ub& upper,
			     T_result* result,
			     const Policy& pol) {
      if (false == check_lower_bound(function, lower, result, pol))
	return false;
      if (false == check_upper_bound(function, upper, result, pol))
	return false;
      if (lower >= upper) {
	*result = boost::math::policies::raise_domain_error<double>(function,
								  "lower parameter is %1%, but must be less than upper!", convert(lower), pol);
	return false;
      }
      return true;
    }

    template <typename T_covar, typename T_result, class Policy>
    inline bool check_cov_matrix(
				 const char* function,
				 const Matrix<T_covar,Dynamic,Dynamic>& Sigma,
				 T_result* result,
				 const Policy& pol) {
      if (!stan::prob::cov_matrix_validate(Sigma)) {
	std::ostringstream stream;
	stream << "Sigma is not a valid covariance matrix. Sigma must be symmetric and positive semi-definite. Sigma: \n"<< Sigma << "\nSigma(0,0): %1%";
	*result = boost::math::policies::raise_domain_error<double>(function,
								     stream.str().c_str(),
								     convert(Sigma(0,0)),
								     pol);
	return false;
      }
      return true;
    }

  }
}
#endif
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
#define ll long long
using namespace std;

void give_score(int score) {
  cerr << "score: " << score << "\n";
  exit(0);
}
ll get_hash(string A, ll M, ll B) {
  ll val = 0;
  ll bpower = 1;

  reverse(A.begin(), A.end());
  for (size_t i = 0; i < A.size(); ++i) {
    val = val + ((A[i] - '0') + 1) * bpower;
    val %= M;

    bpower = bpower * B;
    bpower %= M;
  }
  return val;
}
int main() {
#ifndef ONLINE_JUDGE
  ifstream prb_in("coliziune.in");
  ifstream prb_out("coliziune.out");
#endif

  ll M, B;
  assert(prb_in >> M >> B);
  assert(2 <= B && B <= M - 2);
  assert(4 <= M && M <= 1e14);

  prb_in.close();

  string X, Y;
  if (!(prb_out >> X >> Y)) {
    give_score(0);
  }
  string Z; prb_out >> Z;
  if (Z != "") {
    give_score(0);
  }
  if (X.size() > 1e6 || Y.size() > 1e6) {
    give_score(0);
  }
  if (get_hash(X, M, B) == get_hash(Y, M, B)) {
    give_score(10);
  } else {
    give_score(0);
  }
  return 0;
}
<commit_msg>added cool verifier<commit_after>#include <bits/stdc++.h>
#define ll long long
using namespace std;

void printResult(int score, string message, int exit_status = 0) {
  cout << score << " " << message;
  exit(exit_status);
}
ll get_hash(string A, ll M, ll B) {
  ll val = 0;
  ll bpower = 1;

  reverse(A.begin(), A.end());
  for (size_t i = 0; i < A.size(); ++i) {
    val = val + ((A[i] - '0') + 1) * bpower;
    val %= M;

    bpower = bpower * B;
    bpower %= M;
  }
  return val;
}
int main() {
  ifstream prb_in("coliziune.in");

  if (!prb_in.is_open()) {
    printResult(0, "Fisier de intrare lipsa", -1);
  }

  ll M, B;
  if (!(prb_in >> M >> B)) {
    printResult(0, "Fisier de intrare incomplet", -1);
  }
  assert(2 <= B && B <= M - 2);
  assert(4 <= M && M <= 1e14);

  prb_in.close();

  string X, Y;

  ifstream prb_out("coliziune.out");
  if (!prb_out.is_open()) {
    printResult(0, "Fisier de iesire incomplet", -1);
  }
  if (!(prb_out >> X >> Y)) {
    printResult(0, "Fisier de iesire incomplet");
  }
  string Z; prb_out >> Z;
  if (Z != "") {
    printResult(0, "Prea multe siruri in fisierul de iesire");
  }
  if (X.size() > 1e6 || Y.size() > 1e6) {
    printResult(0, "Sirurile depasesc lungimea maxima admisa");
  }
  if (get_hash(X, M, B) == get_hash(Y, M, B)) {
    printResult(10, "Ai nimerit!");
  } else {
    printResult(0, "Functia H are valori diferite");
  }
  return 0;
}
<|endoftext|>


<commit_before>// Copyright 2006-2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "v8.h"

#include "token.h"
#include "scanner.h"
#include "parser.h"
#include "utils.h"
#include "execution.h"
#include "scanner.h"
#include "preparser.h"
#include "cctest.h"

namespace i = ::v8::internal;

TEST(KeywordMatcher) {
  struct KeywordToken {
    const char* keyword;
    i::Token::Value token;
  };

  static const KeywordToken keywords[] = {
#define KEYWORD(t, s, d) { s, i::Token::t },
#define IGNORE(t, s, d)  /* */
      TOKEN_LIST(IGNORE, KEYWORD, IGNORE)
#undef KEYWORD
      { NULL, i::Token::IDENTIFIER }
  };

  static const char* future_keywords[] = {
#define FUTURE(t, s, d) s,
      TOKEN_LIST(IGNORE, IGNORE, FUTURE)
#undef FUTURE
#undef IGNORE
      NULL
  };

  KeywordToken key_token;
  for (int i = 0; (key_token = keywords[i]).keyword != NULL; i++) {
    i::KeywordMatcher matcher;
    const char* keyword = key_token.keyword;
    int length = i::StrLength(keyword);
    for (int j = 0; j < length; j++) {
      if (key_token.token == i::Token::INSTANCEOF && j == 2) {
        // "in" is a prefix of "instanceof". It's the only keyword
        // that is a prefix of another.
        CHECK_EQ(i::Token::IN, matcher.token());
      } else {
        CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
      }
      matcher.AddChar(keyword[j]);
    }
    CHECK_EQ(key_token.token, matcher.token());
    // Adding more characters will make keyword matching fail.
    matcher.AddChar('z');
    CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
    // Adding a keyword later will not make it match again.
    matcher.AddChar('i');
    matcher.AddChar('f');
    CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
  }

  // Future keywords are not recognized.
  const char* future_keyword;
  for (int i = 0; (future_keyword = future_keywords[i]) != NULL; i++) {
    i::KeywordMatcher matcher;
    int length = i::StrLength(future_keyword);
    for (int j = 0; j < length; j++) {
      matcher.AddChar(future_keyword[j]);
    }
    CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
  }

  // Zero isn't ignored at first.
  i::KeywordMatcher bad_start;
  bad_start.AddChar(0);
  CHECK_EQ(i::Token::IDENTIFIER, bad_start.token());
  bad_start.AddChar('i');
  bad_start.AddChar('f');
  CHECK_EQ(i::Token::IDENTIFIER, bad_start.token());

  // Zero isn't ignored at end.
  i::KeywordMatcher bad_end;
  bad_end.AddChar('i');
  bad_end.AddChar('f');
  CHECK_EQ(i::Token::IF, bad_end.token());
  bad_end.AddChar(0);
  CHECK_EQ(i::Token::IDENTIFIER, bad_end.token());

  // Case isn't ignored.
  i::KeywordMatcher bad_case;
  bad_case.AddChar('i');
  bad_case.AddChar('F');
  CHECK_EQ(i::Token::IDENTIFIER, bad_case.token());

  // If we mark it as failure, continuing won't help.
  i::KeywordMatcher full_stop;
  full_stop.AddChar('i');
  CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
  full_stop.Fail();
  CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
  full_stop.AddChar('f');
  CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
}

TEST(ScanHTMLEndComments) {
  // Regression test. See:
  //    http://code.google.com/p/chromium/issues/detail?id=53548
  // Tests that --> is correctly interpreted as comment-to-end-of-line if there
  // is only whitespace before it on the line, even after a multiline-comment
  // comment. This was not the case if it occurred before the first real token
  // in the input.
  const char* tests[] = {
      // Before first real token.
      "--> is eol-comment\nvar y = 37;\n",
      "\n --> is eol-comment\nvar y = 37;\n",
      "/* precomment */ --> is eol-comment\nvar y = 37;\n",
      "\n/* precomment */ --> is eol-comment\nvar y = 37;\n",
      // After first real token.
      "var x = 42;\n--> is eol-comment\nvar y = 37;\n",
      "var x = 42;\n/* precomment */ --> is eol-comment\nvar y = 37;\n",
      NULL
  };

  // Parser/Scanner needs a stack limit.
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  for (int i = 0; tests[i]; i++) {
    v8::ScriptData* data =
        v8::ScriptData::PreCompile(tests[i], i::StrLength(tests[i]));
    CHECK(data != NULL && !data->HasError());
    delete data;
  }
}

class ScriptResource : public v8::String::ExternalAsciiStringResource {
 public:
  ScriptResource(const char* data, size_t length)
      : data_(data), length_(length) { }

  const char* data() const { return data_; }
  size_t length() const { return length_; }

 private:
  const char* data_;
  size_t length_;
};

TEST(Preparsing) {
  v8::HandleScope handles;
  v8::Persistent<v8::Context> context = v8::Context::New();
  v8::Context::Scope context_scope(context);
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  // Source containing functions that might be lazily compiled  and all types
  // of symbols (string, propertyName, regexp).
  const char* source =
      "var x = 42;"
      "function foo(a) { return function nolazy(b) { return a + b; } }"
      "function bar(a) { if (a) return function lazy(b) { return b; } }"
      "var z = {'string': 'string literal', bareword: 'propertyName', "
      "         42: 'number literal', for: 'keyword as propertyName', "
      "         f\\u006fr: 'keyword propertyname with escape'};"
      "var v = /RegExp Literal/;"
      "var w = /RegExp Literal\\u0020With Escape/gin;"
      "var y = { get getter() { return 42; }, "
      "          set setter(v) { this.value = v; }};";
  int source_length = i::StrLength(source);
  const char* error_source = "var x = y z;";
  int error_source_length = i::StrLength(error_source);

  v8::ScriptData* preparse =
      v8::ScriptData::PreCompile(source, source_length);
  CHECK(!preparse->HasError());
  bool lazy_flag = i::FLAG_lazy;
  {
    i::FLAG_lazy = true;
    ScriptResource* resource = new ScriptResource(source, source_length);
    v8::Local<v8::String> script_source = v8::String::NewExternal(resource);
    v8::Script::Compile(script_source, NULL, preparse);
  }

  {
    i::FLAG_lazy = false;

    ScriptResource* resource = new ScriptResource(source, source_length);
    v8::Local<v8::String> script_source = v8::String::NewExternal(resource);
    v8::Script::New(script_source, NULL, preparse, v8::Local<v8::String>());
  }
  delete preparse;
  i::FLAG_lazy = lazy_flag;

  // Syntax error.
  v8::ScriptData* error_preparse =
      v8::ScriptData::PreCompile(error_source, error_source_length);
  CHECK(error_preparse->HasError());
  i::ScriptDataImpl *pre_impl =
      reinterpret_cast<i::ScriptDataImpl*>(error_preparse);
  i::Scanner::Location error_location =
      pre_impl->MessageLocation();
  // Error is at "z" in source, location 10..11.
  CHECK_EQ(10, error_location.beg_pos);
  CHECK_EQ(11, error_location.end_pos);
  // Should not crash.
  const char* message = pre_impl->BuildMessage();
  i::Vector<const char*> args = pre_impl->BuildArgs();
  CHECK_GT(strlen(message), 0);
}

TEST(StandAlonePreParser) {
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  const char* programs[] = {
      "{label: 42}",
      "var x = 42;",
      "function foo(x, y) { return x + y; }",
      "native function foo(); return %ArgleBargle(glop);",
      "var x = new new Function('this.x = 42');",
      NULL
  };

  for (int i = 0; programs[i]; i++) {
    const char* program = programs[i];
    unibrow::Utf8InputBuffer<256> stream(program, strlen(program));
    i::CompleteParserRecorder log;
    i::Scanner scanner;
    scanner.Initialize(i::Handle<i::String>::null(), &stream, i::JAVASCRIPT);
    v8::preparser::PreParser<i::Scanner, i::CompleteParserRecorder> preparser;
    bool result = preparser.PreParseProgram(&scanner, &log, true);
    CHECK(result);
    i::ScriptDataImpl data(log.ExtractData());
    CHECK(!data.has_error());
  }
}

TEST(RegressChromium62639) {
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  char buffer[4096];
  const char* program_template = "var x = '%01024d';  // filler\n"
                                 "escape: function() {}";
  // Fails parsing expecting an identifier after "function".
  // Before fix, didn't check *ok after Expect(Token::Identifier, ok),
  // and then used the invalid currently scanned literal. This always
  // failed in debug mode, and sometimes crashed in release mode.

  snprintf(buffer, sizeof(buffer), program_template, 0);
  unibrow::Utf8InputBuffer<256> stream(buffer, strlen(buffer));
  i::ScriptDataImpl* data =
      i::ParserApi::PreParse(i::Handle<i::String>::null(), &stream, NULL);
  CHECK(data->HasError());
  delete data;
}

TEST(Regress928) {
  // Preparsing didn't consider the catch clause of a try statement
  // as with-content, which made it assume that a function inside
  // the block could be lazily compiled, and an extra, unexpected,
  // entry was added to the data.
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  const char* program =
      "try { } catch (e) { var foo = function () { /* first */ } }"
      "var bar = function () { /* second */ }";

  unibrow::Utf8InputBuffer<256> stream(program, strlen(program));
  i::ScriptDataImpl* data =
      i::ParserApi::PartialPreParse(i::Handle<i::String>::null(),
                                    &stream, NULL);
  CHECK(!data->HasError());

  data->Initialize();

  int first_function = strstr(program, "function") - program;
  int first_lbrace = first_function + strlen("function () ");
  CHECK_EQ('{', program[first_lbrace]);
  i::FunctionEntry entry1 = data->GetFunctionEntry(first_lbrace);
  CHECK(!entry1.is_valid());

  int second_function = strstr(program + first_lbrace, "function") - program;
  int second_lbrace = second_function + strlen("function () ");
  CHECK_EQ('{', program[second_lbrace]);
  i::FunctionEntry entry2 = data->GetFunctionEntry(second_lbrace);
  CHECK(entry2.is_valid());
  CHECK_EQ('}', program[entry2.end_pos() - 1]);
  delete data;
}
<commit_msg>Fix compile error on Windows (no snprintf support). Luckily the snprintf wasn't really needed.<commit_after>// Copyright 2006-2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "v8.h"

#include "token.h"
#include "scanner.h"
#include "parser.h"
#include "utils.h"
#include "execution.h"
#include "scanner.h"
#include "preparser.h"
#include "cctest.h"

namespace i = ::v8::internal;

TEST(KeywordMatcher) {
  struct KeywordToken {
    const char* keyword;
    i::Token::Value token;
  };

  static const KeywordToken keywords[] = {
#define KEYWORD(t, s, d) { s, i::Token::t },
#define IGNORE(t, s, d)  /* */
      TOKEN_LIST(IGNORE, KEYWORD, IGNORE)
#undef KEYWORD
      { NULL, i::Token::IDENTIFIER }
  };

  static const char* future_keywords[] = {
#define FUTURE(t, s, d) s,
      TOKEN_LIST(IGNORE, IGNORE, FUTURE)
#undef FUTURE
#undef IGNORE
      NULL
  };

  KeywordToken key_token;
  for (int i = 0; (key_token = keywords[i]).keyword != NULL; i++) {
    i::KeywordMatcher matcher;
    const char* keyword = key_token.keyword;
    int length = i::StrLength(keyword);
    for (int j = 0; j < length; j++) {
      if (key_token.token == i::Token::INSTANCEOF && j == 2) {
        // "in" is a prefix of "instanceof". It's the only keyword
        // that is a prefix of another.
        CHECK_EQ(i::Token::IN, matcher.token());
      } else {
        CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
      }
      matcher.AddChar(keyword[j]);
    }
    CHECK_EQ(key_token.token, matcher.token());
    // Adding more characters will make keyword matching fail.
    matcher.AddChar('z');
    CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
    // Adding a keyword later will not make it match again.
    matcher.AddChar('i');
    matcher.AddChar('f');
    CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
  }

  // Future keywords are not recognized.
  const char* future_keyword;
  for (int i = 0; (future_keyword = future_keywords[i]) != NULL; i++) {
    i::KeywordMatcher matcher;
    int length = i::StrLength(future_keyword);
    for (int j = 0; j < length; j++) {
      matcher.AddChar(future_keyword[j]);
    }
    CHECK_EQ(i::Token::IDENTIFIER, matcher.token());
  }

  // Zero isn't ignored at first.
  i::KeywordMatcher bad_start;
  bad_start.AddChar(0);
  CHECK_EQ(i::Token::IDENTIFIER, bad_start.token());
  bad_start.AddChar('i');
  bad_start.AddChar('f');
  CHECK_EQ(i::Token::IDENTIFIER, bad_start.token());

  // Zero isn't ignored at end.
  i::KeywordMatcher bad_end;
  bad_end.AddChar('i');
  bad_end.AddChar('f');
  CHECK_EQ(i::Token::IF, bad_end.token());
  bad_end.AddChar(0);
  CHECK_EQ(i::Token::IDENTIFIER, bad_end.token());

  // Case isn't ignored.
  i::KeywordMatcher bad_case;
  bad_case.AddChar('i');
  bad_case.AddChar('F');
  CHECK_EQ(i::Token::IDENTIFIER, bad_case.token());

  // If we mark it as failure, continuing won't help.
  i::KeywordMatcher full_stop;
  full_stop.AddChar('i');
  CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
  full_stop.Fail();
  CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
  full_stop.AddChar('f');
  CHECK_EQ(i::Token::IDENTIFIER, full_stop.token());
}

TEST(ScanHTMLEndComments) {
  // Regression test. See:
  //    http://code.google.com/p/chromium/issues/detail?id=53548
  // Tests that --> is correctly interpreted as comment-to-end-of-line if there
  // is only whitespace before it on the line, even after a multiline-comment
  // comment. This was not the case if it occurred before the first real token
  // in the input.
  const char* tests[] = {
      // Before first real token.
      "--> is eol-comment\nvar y = 37;\n",
      "\n --> is eol-comment\nvar y = 37;\n",
      "/* precomment */ --> is eol-comment\nvar y = 37;\n",
      "\n/* precomment */ --> is eol-comment\nvar y = 37;\n",
      // After first real token.
      "var x = 42;\n--> is eol-comment\nvar y = 37;\n",
      "var x = 42;\n/* precomment */ --> is eol-comment\nvar y = 37;\n",
      NULL
  };

  // Parser/Scanner needs a stack limit.
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  for (int i = 0; tests[i]; i++) {
    v8::ScriptData* data =
        v8::ScriptData::PreCompile(tests[i], i::StrLength(tests[i]));
    CHECK(data != NULL && !data->HasError());
    delete data;
  }
}

class ScriptResource : public v8::String::ExternalAsciiStringResource {
 public:
  ScriptResource(const char* data, size_t length)
      : data_(data), length_(length) { }

  const char* data() const { return data_; }
  size_t length() const { return length_; }

 private:
  const char* data_;
  size_t length_;
};

TEST(Preparsing) {
  v8::HandleScope handles;
  v8::Persistent<v8::Context> context = v8::Context::New();
  v8::Context::Scope context_scope(context);
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  // Source containing functions that might be lazily compiled  and all types
  // of symbols (string, propertyName, regexp).
  const char* source =
      "var x = 42;"
      "function foo(a) { return function nolazy(b) { return a + b; } }"
      "function bar(a) { if (a) return function lazy(b) { return b; } }"
      "var z = {'string': 'string literal', bareword: 'propertyName', "
      "         42: 'number literal', for: 'keyword as propertyName', "
      "         f\\u006fr: 'keyword propertyname with escape'};"
      "var v = /RegExp Literal/;"
      "var w = /RegExp Literal\\u0020With Escape/gin;"
      "var y = { get getter() { return 42; }, "
      "          set setter(v) { this.value = v; }};";
  int source_length = i::StrLength(source);
  const char* error_source = "var x = y z;";
  int error_source_length = i::StrLength(error_source);

  v8::ScriptData* preparse =
      v8::ScriptData::PreCompile(source, source_length);
  CHECK(!preparse->HasError());
  bool lazy_flag = i::FLAG_lazy;
  {
    i::FLAG_lazy = true;
    ScriptResource* resource = new ScriptResource(source, source_length);
    v8::Local<v8::String> script_source = v8::String::NewExternal(resource);
    v8::Script::Compile(script_source, NULL, preparse);
  }

  {
    i::FLAG_lazy = false;

    ScriptResource* resource = new ScriptResource(source, source_length);
    v8::Local<v8::String> script_source = v8::String::NewExternal(resource);
    v8::Script::New(script_source, NULL, preparse, v8::Local<v8::String>());
  }
  delete preparse;
  i::FLAG_lazy = lazy_flag;

  // Syntax error.
  v8::ScriptData* error_preparse =
      v8::ScriptData::PreCompile(error_source, error_source_length);
  CHECK(error_preparse->HasError());
  i::ScriptDataImpl *pre_impl =
      reinterpret_cast<i::ScriptDataImpl*>(error_preparse);
  i::Scanner::Location error_location =
      pre_impl->MessageLocation();
  // Error is at "z" in source, location 10..11.
  CHECK_EQ(10, error_location.beg_pos);
  CHECK_EQ(11, error_location.end_pos);
  // Should not crash.
  const char* message = pre_impl->BuildMessage();
  i::Vector<const char*> args = pre_impl->BuildArgs();
  CHECK_GT(strlen(message), 0);
}

TEST(StandAlonePreParser) {
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  const char* programs[] = {
      "{label: 42}",
      "var x = 42;",
      "function foo(x, y) { return x + y; }",
      "native function foo(); return %ArgleBargle(glop);",
      "var x = new new Function('this.x = 42');",
      NULL
  };

  for (int i = 0; programs[i]; i++) {
    const char* program = programs[i];
    unibrow::Utf8InputBuffer<256> stream(program, strlen(program));
    i::CompleteParserRecorder log;
    i::Scanner scanner;
    scanner.Initialize(i::Handle<i::String>::null(), &stream, i::JAVASCRIPT);
    v8::preparser::PreParser<i::Scanner, i::CompleteParserRecorder> preparser;
    bool result = preparser.PreParseProgram(&scanner, &log, true);
    CHECK(result);
    i::ScriptDataImpl data(log.ExtractData());
    CHECK(!data.has_error());
  }
}

TEST(RegressChromium62639) {
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  const char* program = "var x = 'something';\n"
                        "escape: function() {}";
  // Fails parsing expecting an identifier after "function".
  // Before fix, didn't check *ok after Expect(Token::Identifier, ok),
  // and then used the invalid currently scanned literal. This always
  // failed in debug mode, and sometimes crashed in release mode.

  unibrow::Utf8InputBuffer<256> stream(program, strlen(program));
  i::ScriptDataImpl* data =
      i::ParserApi::PreParse(i::Handle<i::String>::null(), &stream, NULL);
  CHECK(data->HasError());
  delete data;
}

TEST(Regress928) {
  // Preparsing didn't consider the catch clause of a try statement
  // as with-content, which made it assume that a function inside
  // the block could be lazily compiled, and an extra, unexpected,
  // entry was added to the data.
  int marker;
  i::StackGuard::SetStackLimit(
      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);

  const char* program =
      "try { } catch (e) { var foo = function () { /* first */ } }"
      "var bar = function () { /* second */ }";

  unibrow::Utf8InputBuffer<256> stream(program, strlen(program));
  i::ScriptDataImpl* data =
      i::ParserApi::PartialPreParse(i::Handle<i::String>::null(),
                                    &stream, NULL);
  CHECK(!data->HasError());

  data->Initialize();

  int first_function = strstr(program, "function") - program;
  int first_lbrace = first_function + strlen("function () ");
  CHECK_EQ('{', program[first_lbrace]);
  i::FunctionEntry entry1 = data->GetFunctionEntry(first_lbrace);
  CHECK(!entry1.is_valid());

  int second_function = strstr(program + first_lbrace, "function") - program;
  int second_lbrace = second_function + strlen("function () ");
  CHECK_EQ('{', program[second_lbrace]);
  i::FunctionEntry entry2 = data->GetFunctionEntry(second_lbrace);
  CHECK(entry2.is_valid());
  CHECK_EQ('}', program[entry2.end_pos() - 1]);
  delete data;
}
<|endoftext|>


<commit_before>#include "systemtray.h"

#include <QtWidgets/QApplication>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QMenu>
#include <QtCore/QProcess>
#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtGui/QIcon>

#include <signal.h>

SystemTray::SystemTray()
{
    _suspendTimer = new QTimer(this);
    connect(_suspendTimer, &QTimer::timeout, this, &SystemTray::onTimeout);
}

void SystemTray::onClick(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
    case QSystemTrayIcon::ActivationReason::Trigger:
    case QSystemTrayIcon::ActivationReason::DoubleClick:
        ToggleRedshift(!_enabled);
        break;
    case QSystemTrayIcon::ActivationReason::MiddleClick:
    case QSystemTrayIcon::ActivationReason::Context:
    case QSystemTrayIcon::ActivationReason::Unknown:
        break;
    }
}

void SystemTray::onQuit()
{
    setIcon(_iconDisabled);
    QApplication::quit();
}

void SystemTray::onRedshiftQuit(int, QProcess::ExitStatus)
{
    if (!_warnOnRedshiftQuit)
        return;

    QMessageBox::critical(0, QObject::tr("Fatal error"), QObject::tr("Redshift process has been terminated unexpectedly"));
    onQuit();
}

void SystemTray::onRedshiftOutput()
{
    if (!_redshiftProcess)
        return;

    QTextStream stream(_redshiftProcess);
    while (!stream.atEnd()) {
        auto line = stream.readLine();
        qInfo() << line;
        if (line.startsWith("Color temperature"))
            _colorTemp = line;
        else if (line.startsWith("Period:"))
            _period = line;
        else if (!line.startsWith("Status:"))
            _info += "\n" + line;
    }
}

void SystemTray::onSuspend()
{
    ToggleRedshift(!_enabled);
}

void SystemTray::onSuspend10minutes()
{
    ToggleRedshift(false);
    _suspendTimer->start(10*60*1000);
}

void SystemTray::onSuspend1hour()
{
    ToggleRedshift(false);
    _suspendTimer->start(60*60*1000);
}

void SystemTray::onSuspend2hours()
{
    ToggleRedshift(false);
    _suspendTimer->start(120*60*1000);
}

void SystemTray::onTimeout()
{
    ToggleRedshift(true);
}

void SystemTray::onGetInfo()
{
    QMessageBox::information(nullptr, "Redshift Information", _info
                             + "\n" + _period
                             + "\n" + _colorTemp, QMessageBox::Ok);
}

bool SystemTray::CreateIcon()
{
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        QMessageBox::critical(0, QObject::tr("Fatal error"), QObject::tr("No system tray available"));
        return false;
    }

    CreateMenu();

    _iconEnabled = QIcon::fromTheme("redshift-status-on", QIcon(":/icons/redshift-status-on.png"));
    _iconDisabled = QIcon::fromTheme("redshift-status-off", QIcon(":/icons/redshift-status-off.png"));

    setIcon(_iconEnabled);

    connect(this, &QSystemTrayIcon::activated, this, &SystemTray::onClick);

    show();

    return true;
}

bool SystemTray::StartRedshift()
{
    _redshiftProcess = new QProcess(this);
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("LC_ALL", "C");
    _redshiftProcess->setProcessEnvironment(env);
    _redshiftProcess->start("redshift -v");

    connect(_redshiftProcess, (void (QProcess::*)(int,QProcess::ExitStatus))&QProcess::finished, this, &SystemTray::onRedshiftQuit);
    connect(_redshiftProcess, &QProcess::readyRead, this, &SystemTray::onRedshiftOutput);

    if (!_redshiftProcess->waitForStarted(5000))
    {
        QMessageBox::critical(0, QObject::tr("Fatal error"), QObject::tr("Failed to start redshift"));
        qFatal("Failed to start redshift");
        return false;
    }

    _enabled = true;

    return true;
}

void SystemTray::ToggleRedshift(bool enable)
{
    if (!_redshiftProcess)
    {
        qFatal("QProcess pointer is null");
        return;
    }

    if (enable == _enabled)
        return;

    _enabled = enable;
    _suspendMenu->setChecked(!enable);
    setIcon(enable ? _iconEnabled : _iconDisabled);
    qInfo() << "Redshift status change: " << (enable ? "enabled" : "disabled");
    kill(_redshiftProcess->pid(), SIGUSR1);
}

void SystemTray::StopRedshift()
{
    if (_redshiftProcess && _redshiftProcess->pid())
    {
        _warnOnRedshiftQuit = false;
        _redshiftProcess->terminate();
        if (!_redshiftProcess->waitForFinished())
            qCritical() << "Redshift process failed to terminate";
    }
}

void SystemTray::CreateMenu()
{
    // Lifetime of this menu is the same as the application's
    auto trayIconMenu = new QMenu();

    _suspendMenu = new QAction(QObject::tr("Suspended"), this);
    _suspendMenu->setCheckable(true);
    _suspendMenu->setChecked(false);
    connect(_suspendMenu, &QAction::triggered, this, &SystemTray::onSuspend);

    auto suspendAction_10m = new QAction(QObject::tr("Suspend for 10 minutes"), this);
    auto suspendAction_1h = new QAction(QObject::tr("Suspend for 1 hour"), this);
    auto suspendAction_2h = new QAction(QObject::tr("Suspend for 2 hours"), this);

    connect(suspendAction_10m, &QAction::triggered, this, &SystemTray::onSuspend10minutes);
    connect(suspendAction_1h, &QAction::triggered, this, &SystemTray::onSuspend1hour);
    connect(suspendAction_2h, &QAction::triggered, this, &SystemTray::onSuspend2hours);

    auto showInfoAction = new QAction(QObject::tr("Show Info"), this);
    connect(showInfoAction, &QAction::triggered, this, &SystemTray::onGetInfo);

    auto quitAction = new QAction(QObject::tr("&Quit"), nullptr);
    connect(quitAction, &QAction::triggered, this, &SystemTray::onQuit);

    trayIconMenu->addAction(_suspendMenu);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(suspendAction_10m);
    trayIconMenu->addAction(suspendAction_1h);
    trayIconMenu->addAction(suspendAction_2h);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(showInfoAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);

    setContextMenu(trayIconMenu);
}
<commit_msg>apparently not having a system tray available is not a big deal it happens on Wayland, but the tray still works also docs state that if tray comes up it will work too<commit_after>#include "systemtray.h"

#include <QtWidgets/QApplication>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QMenu>
#include <QtCore/QProcess>
#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtGui/QIcon>

#include <signal.h>

SystemTray::SystemTray()
{
    _suspendTimer = new QTimer(this);
    connect(_suspendTimer, &QTimer::timeout, this, &SystemTray::onTimeout);
}

void SystemTray::onClick(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
    case QSystemTrayIcon::ActivationReason::Trigger:
    case QSystemTrayIcon::ActivationReason::DoubleClick:
        ToggleRedshift(!_enabled);
        break;
    case QSystemTrayIcon::ActivationReason::MiddleClick:
    case QSystemTrayIcon::ActivationReason::Context:
    case QSystemTrayIcon::ActivationReason::Unknown:
        break;
    }
}

void SystemTray::onQuit()
{
    setIcon(_iconDisabled);
    QApplication::quit();
}

void SystemTray::onRedshiftQuit(int, QProcess::ExitStatus)
{
    if (!_warnOnRedshiftQuit)
        return;

    QMessageBox::critical(0, QObject::tr("Fatal error"), QObject::tr("Redshift process has been terminated unexpectedly"));
    onQuit();
}

void SystemTray::onRedshiftOutput()
{
    if (!_redshiftProcess)
        return;

    QTextStream stream(_redshiftProcess);
    while (!stream.atEnd()) {
        auto line = stream.readLine();
        qInfo() << line;
        if (line.startsWith("Color temperature"))
            _colorTemp = line;
        else if (line.startsWith("Period:"))
            _period = line;
        else if (!line.startsWith("Status:"))
            _info += "\n" + line;
    }
}

void SystemTray::onSuspend()
{
    ToggleRedshift(!_enabled);
}

void SystemTray::onSuspend10minutes()
{
    ToggleRedshift(false);
    _suspendTimer->start(10*60*1000);
}

void SystemTray::onSuspend1hour()
{
    ToggleRedshift(false);
    _suspendTimer->start(60*60*1000);
}

void SystemTray::onSuspend2hours()
{
    ToggleRedshift(false);
    _suspendTimer->start(120*60*1000);
}

void SystemTray::onTimeout()
{
    ToggleRedshift(true);
}

void SystemTray::onGetInfo()
{
    QMessageBox::information(nullptr, "Redshift Information", _info
                             + "\n" + _period
                             + "\n" + _colorTemp, QMessageBox::Ok);
}

bool SystemTray::CreateIcon()
{
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        qWarning() << "No system tray available";
    }

    CreateMenu();

    _iconEnabled = QIcon::fromTheme("redshift-status-on", QIcon(":/icons/redshift-status-on.png"));
    _iconDisabled = QIcon::fromTheme("redshift-status-off", QIcon(":/icons/redshift-status-off.png"));

    setIcon(_iconEnabled);

    connect(this, &QSystemTrayIcon::activated, this, &SystemTray::onClick);

    show();

    return true;
}

bool SystemTray::StartRedshift()
{
    _redshiftProcess = new QProcess(this);
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("LC_ALL", "C");
    _redshiftProcess->setProcessEnvironment(env);
    _redshiftProcess->start("redshift -v");

    connect(_redshiftProcess, (void (QProcess::*)(int,QProcess::ExitStatus))&QProcess::finished, this, &SystemTray::onRedshiftQuit);
    connect(_redshiftProcess, &QProcess::readyRead, this, &SystemTray::onRedshiftOutput);

    if (!_redshiftProcess->waitForStarted(5000))
    {
        QMessageBox::critical(0, QObject::tr("Fatal error"), QObject::tr("Failed to start redshift"));
        qFatal("Failed to start redshift");
        return false;
    }

    _enabled = true;

    return true;
}

void SystemTray::ToggleRedshift(bool enable)
{
    if (!_redshiftProcess)
    {
        qFatal("QProcess pointer is null");
        return;
    }

    if (enable == _enabled)
        return;

    _enabled = enable;
    _suspendMenu->setChecked(!enable);
    setIcon(enable ? _iconEnabled : _iconDisabled);
    qInfo() << "Redshift status change: " << (enable ? "enabled" : "disabled");
    kill(_redshiftProcess->pid(), SIGUSR1);
}

void SystemTray::StopRedshift()
{
    if (_redshiftProcess && _redshiftProcess->pid())
    {
        _warnOnRedshiftQuit = false;
        _redshiftProcess->terminate();
        if (!_redshiftProcess->waitForFinished())
            qCritical() << "Redshift process failed to terminate";
    }
}

void SystemTray::CreateMenu()
{
    // Lifetime of this menu is the same as the application's
    auto trayIconMenu = new QMenu();

    _suspendMenu = new QAction(QObject::tr("Suspended"), this);
    _suspendMenu->setCheckable(true);
    _suspendMenu->setChecked(false);
    connect(_suspendMenu, &QAction::triggered, this, &SystemTray::onSuspend);

    auto suspendAction_10m = new QAction(QObject::tr("Suspend for 10 minutes"), this);
    auto suspendAction_1h = new QAction(QObject::tr("Suspend for 1 hour"), this);
    auto suspendAction_2h = new QAction(QObject::tr("Suspend for 2 hours"), this);

    connect(suspendAction_10m, &QAction::triggered, this, &SystemTray::onSuspend10minutes);
    connect(suspendAction_1h, &QAction::triggered, this, &SystemTray::onSuspend1hour);
    connect(suspendAction_2h, &QAction::triggered, this, &SystemTray::onSuspend2hours);

    auto showInfoAction = new QAction(QObject::tr("Show Info"), this);
    connect(showInfoAction, &QAction::triggered, this, &SystemTray::onGetInfo);

    auto quitAction = new QAction(QObject::tr("&Quit"), nullptr);
    connect(quitAction, &QAction::triggered, this, &SystemTray::onQuit);

    trayIconMenu->addAction(_suspendMenu);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(suspendAction_10m);
    trayIconMenu->addAction(suspendAction_1h);
    trayIconMenu->addAction(suspendAction_2h);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(showInfoAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);

    setContextMenu(trayIconMenu);
}
<|endoftext|>


<commit_before>/**
 * @file main.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2013-2014, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * @section Description
 * Cosa Arduino main program. Calls sketch functions; setup() and
 * loop() and handles the iteration.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include "Cosa/Power.hh"

/**
 * The init function; minimum setup of hardware after the bootloader.
 * This function may be overridden.
 */
void init() __attribute__((weak));
void init()
{
  // Adjust frequency scaling on Teensy; default is no scaling on Cosa
#if defined(PJRC_TEENSY_2_0) || defined(PJRC_TEENSYPP_2_0)
  Power::clock_prescale(0);
#endif

  // Set analog converter prescale factor and but do not enable conversion
#if F_CPU >= 16000000L
  ADCSRA |= (_BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0));
#elif F_CPU >= 8000000L
  ADCSRA |= (_BV(ADPS2) | _BV(ADPS1));
#else
  ADCSRA |= (_BV(ADPS1) | _BV(ADPS0));
#endif

  // Disable analog comparator
  ACSR = _BV(ACD);

  // The bootloader connects pins 0 and 1 to the USART; disconnect them
  // here so they can be used as normal digital IO.
#if defined(UCSRB)
  UCSRB = 0;
#elif defined(UCSR0B)
  UCSR0B = 0;
#endif

  // Initiate USB when needed (when CDC is attached)
#if defined(USBCON)
  USBCON = 0;
  UDCON = 0;
  UDINT = 0;
  UDIEN = 0;
#endif

  // Allow interrupts from here on
  sei();
}

/**
 * Default setup function. This function may be overridden.
 */
void setup() __attribute__((weak));
void setup() {}

/**
 * Default loop function. This function may be overridden.
 */
void loop() __attribute__((weak));
void loop() {}

/**
 * The main function. This function may be overridden.
 */
int main(void) __attribute__((weak));
int main(void)
{
  init();
  setup();
  while (1) loop();
  return (0);
}

/**
 * Default delay function; delay given number of milli-seconds.
 * @param[in] ms milli-seconds delay.
 */
static void default_delay(uint32_t ms)
{
  while (ms--) DELAY(1000);
}

/**
 * Default sleep function; delay given number of seconds.
 * @param[in] s seconds delay.
 */
static void default_sleep(uint16_t s)
{
  delay(s * 1000L);
}

/**
 * Default yield function; enter sleep mode and wait for interrupt.
 */
static void default_yield()
{
  Power::sleep();
}

/** Default setting of multi-tasking functions */
void (*delay)(uint32_t ms) = default_delay;
void (*sleep)(uint16_t s) = default_sleep;
void (*yield)() = default_yield;

/**
 * Support for local static variables
 */
namespace __cxxabiv1
{
  typedef int __guard;
  extern "C" int __cxa_guard_acquire (__guard *g)
  {
    UNUSED(g);
    return (1);
  }
  extern "C" void __cxa_guard_release (__guard *g)
  {
    UNUSED(g);
  }
  extern "C" void __cxa_guard_abort (__guard *g)
  {
    UNUSED(g);
  }
  extern "C" void __cxa_pure_virtual(void)
  {
  }
}
<commit_msg>Default loop() is now exit(0);<commit_after>/**
 * @file main.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2013-2014, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * @section Description
 * Cosa Arduino main program. Calls sketch functions; setup() and
 * loop() and handles the iteration.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include "Cosa/Power.hh"

/**
 * The init function; minimum setup of hardware after the bootloader.
 * This function may be overridden.
 */
void init() __attribute__((weak));
void init()
{
  // Adjust frequency scaling on Teensy; default is no scaling on Cosa
#if defined(PJRC_TEENSY_2_0) || defined(PJRC_TEENSYPP_2_0)
  Power::clock_prescale(0);
#endif

  // Set analog converter prescale factor and but do not enable conversion
#if F_CPU >= 16000000L
  ADCSRA |= (_BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0));
#elif F_CPU >= 8000000L
  ADCSRA |= (_BV(ADPS2) | _BV(ADPS1));
#else
  ADCSRA |= (_BV(ADPS1) | _BV(ADPS0));
#endif

  // Disable analog comparator
  ACSR = _BV(ACD);

  // The bootloader connects pins 0 and 1 to the USART; disconnect them
  // here so they can be used as normal digital IO.
#if defined(UCSRB)
  UCSRB = 0;
#elif defined(UCSR0B)
  UCSR0B = 0;
#endif

  // Initiate USB when needed (when CDC is attached)
#if defined(USBCON)
  USBCON = 0;
  UDCON = 0;
  UDINT = 0;
  UDIEN = 0;
#endif

  // Allow interrupts from here on
  sei();
}

/**
 * Default setup function. This function may be overridden.
 */
void setup() __attribute__((weak));
void setup() {}

/**
 * Default loop function. This function may be overridden.
 */
void loop() __attribute__((weak));
void loop() { exit(0); }

/**
 * The main function. This function may be overridden.
 */
int main(void) __attribute__((weak));
int main(void)
{
  init();
  setup();
  while (1) loop();
  return (0);
}

/**
 * Default delay function; delay given number of milli-seconds.
 * @param[in] ms milli-seconds delay.
 */
static void default_delay(uint32_t ms)
{
  while (ms--) DELAY(1000);
}

/**
 * Default sleep function; delay given number of seconds.
 * @param[in] s seconds delay.
 */
static void default_sleep(uint16_t s)
{
  delay(s * 1000L);
}

/**
 * Default yield function; enter sleep mode and wait for interrupt.
 */
static void default_yield()
{
  Power::sleep();
}

/** Default setting of multi-tasking functions */
void (*delay)(uint32_t ms) = default_delay;
void (*sleep)(uint16_t s) = default_sleep;
void (*yield)() = default_yield;

/**
 * Support for local static variables
 */
namespace __cxxabiv1
{
  typedef int __guard;
  extern "C" int __cxa_guard_acquire (__guard *g)
  {
    UNUSED(g);
    return (1);
  }
  extern "C" void __cxa_guard_release (__guard *g)
  {
    UNUSED(g);
  }
  extern "C" void __cxa_guard_abort (__guard *g)
  {
    UNUSED(g);
  }
  extern "C" void __cxa_pure_virtual(void)
  {
  }
}
<|endoftext|>


<commit_before>#include "init.hpp"

#include "SequenceRule"
#include "TokenRule"

using namespace sprout;

SequenceRule<OrderedTokenRule<char, std::string>> createRule()
{
    OrderedTokenRule<char, std::string> a;
    a.setTarget("Cat");
    a.setToken("Heathen");

    OrderedTokenRule<char, std::string> b;
    b.setTarget("Dog");
    b.setToken("Civilized");

    OrderedTokenRule<char, std::string> c;
    c.setTarget("Calf");
    c.setToken("Cow");

    std::vector<OrderedTokenRule<char, std::string>> rules { a, b, c };
    return SequenceRule<decltype(a)>(rules);
}

BOOST_AUTO_TEST_CASE(matchASingleSequence)
{
    auto rule = createRule();

    std::stringstream str("CatDogCalf");
    auto cursor = makeCursor<char>(str);

    auto tokens = rule.parse(cursor);
    BOOST_REQUIRE(tokens);
    BOOST_CHECK_EQUAL("Heathen", *tokens++);
    BOOST_CHECK_EQUAL("Civilized", *tokens++);
    BOOST_CHECK_EQUAL("Cow", *tokens++);
    BOOST_REQUIRE(!tokens);
}

BOOST_AUTO_TEST_CASE(sequencesFailCompletely)
{
    auto rule = createRule();

    std::stringstream str("DogCat");
    auto cursor = makeCursor<char>(str);

    auto tokens = rule.parse(cursor);
    BOOST_REQUIRE(!tokens);
}

BOOST_AUTO_TEST_CASE(partialSequencesAlsoFailCompletely)
{
    auto rule = createRule();

    std::stringstream str("CatDogCat");
    auto cursor = makeCursor<char>(str);

    auto tokens = rule.parse(cursor);
    BOOST_REQUIRE(!tokens);
}
<commit_msg>Ensure Sequence resets its iterator<commit_after>#include "init.hpp"

#include "SequenceRule"
#include "TokenRule"

using namespace sprout;

SequenceRule<OrderedTokenRule<char, std::string>> createRule()
{
    OrderedTokenRule<char, std::string> a;
    a.setTarget("Cat");
    a.setToken("Heathen");

    OrderedTokenRule<char, std::string> b;
    b.setTarget("Dog");
    b.setToken("Civilized");

    OrderedTokenRule<char, std::string> c;
    c.setTarget("Calf");
    c.setToken("Cow");

    std::vector<OrderedTokenRule<char, std::string>> rules { a, b, c };
    return SequenceRule<decltype(a)>(rules);
}

BOOST_AUTO_TEST_CASE(matchASingleSequence)
{
    auto rule = createRule();

    std::stringstream str("CatDogCalf");
    auto cursor = makeCursor<char>(str);

    auto tokens = rule.parse(cursor);
    BOOST_REQUIRE(tokens);
    BOOST_CHECK_EQUAL("Heathen", *tokens++);
    BOOST_CHECK_EQUAL("Civilized", *tokens++);
    BOOST_CHECK_EQUAL("Cow", *tokens++);
    BOOST_REQUIRE(!tokens);
}

BOOST_AUTO_TEST_CASE(sequencesFailCompletely)
{
    auto rule = createRule();

    std::stringstream str("DogCat");
    auto cursor = makeCursor<char>(str);

    auto tokens = rule.parse(cursor);
    BOOST_CHECK(!tokens);
    BOOST_CHECK_EQUAL('D', *cursor);
}

BOOST_AUTO_TEST_CASE(partialSequencesAlsoFailCompletely)
{
    auto rule = createRule();

    std::stringstream str("CatDogCat");
    auto cursor = makeCursor<char>(str);

    auto tokens = rule.parse(cursor);
    BOOST_CHECK(!tokens);
    BOOST_CHECK_EQUAL('C', *cursor);
}
<|endoftext|>


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

#include "config.h"
#include "WebMediaPlayerClientImpl.h"

#if ENABLE(VIDEO)

#include "TemporaryGlue.h"
#include "WebCanvas.h"
#include "WebCString.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebMediaPlayer.h"
#include "WebMimeRegistry.h"
#include "WebRect.h"
#include "WebSize.h"
#include "WebString.h"
#include "WebURL.h"

#include "CString.h"
#include "Frame.h"
#include "GraphicsContext.h"
#include "HTMLMediaElement.h"
#include "IntSize.h"
#include "KURL.h"
#include "MediaPlayer.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"

using namespace WebCore;

namespace WebKit {

static bool s_isEnabled = false;

void WebMediaPlayerClientImpl::setIsEnabled(bool isEnabled)
{
    s_isEnabled = isEnabled;
}

void WebMediaPlayerClientImpl::registerSelf(MediaEngineRegistrar registrar)
{
    if (s_isEnabled) {
        registrar(WebMediaPlayerClientImpl::create,
                  WebMediaPlayerClientImpl::getSupportedTypes,
                  WebMediaPlayerClientImpl::supportsType);
    }
}

// WebMediaPlayerClient --------------------------------------------------------

void WebMediaPlayerClientImpl::networkStateChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->networkStateChanged();
}

void WebMediaPlayerClientImpl::readyStateChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->readyStateChanged();
}

void WebMediaPlayerClientImpl::volumeChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->volumeChanged();
}

void WebMediaPlayerClientImpl::timeChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->timeChanged();
}

void WebMediaPlayerClientImpl::repaint()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->repaint();
}

void WebMediaPlayerClientImpl::durationChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->durationChanged();
}

void WebMediaPlayerClientImpl::rateChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->rateChanged();
}

void WebMediaPlayerClientImpl::sizeChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->sizeChanged();
}

void WebMediaPlayerClientImpl::sawUnsupportedTracks()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->mediaPlayerClient()->mediaPlayerSawUnsupportedTracks(m_mediaPlayer);
}

// MediaPlayerPrivateInterface -------------------------------------------------

void WebMediaPlayerClientImpl::load(const String& url)
{
    Frame* frame = static_cast<HTMLMediaElement*>(
        m_mediaPlayer->mediaPlayerClient())->document()->frame();
    m_webMediaPlayer.set(TemporaryGlue::createWebMediaPlayer(this, frame));
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->load(KURL(url));
}

void WebMediaPlayerClientImpl::cancelLoad()
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->cancelLoad();
}

void WebMediaPlayerClientImpl::play()
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->play();
}

void WebMediaPlayerClientImpl::pause()
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->pause();
}

IntSize WebMediaPlayerClientImpl::naturalSize() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->naturalSize();
    return IntSize();
}

bool WebMediaPlayerClientImpl::hasVideo() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->hasVideo();
    return false;
}

void WebMediaPlayerClientImpl::setVisible(bool visible)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setVisible(visible);
}

float WebMediaPlayerClientImpl::duration() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->duration();
    return 0.0f;
}

float WebMediaPlayerClientImpl::currentTime() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->currentTime();
    return 0.0f;
}

void WebMediaPlayerClientImpl::seek(float time)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->seek(time);
}

bool WebMediaPlayerClientImpl::seeking() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->seeking();
    return false;
}

void WebMediaPlayerClientImpl::setEndTime(float time)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setEndTime(time);
}

void WebMediaPlayerClientImpl::setRate(float rate)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setRate(rate);
}

bool WebMediaPlayerClientImpl::paused() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->paused();
    return false;
}

bool WebMediaPlayerClientImpl::supportsFullscreen() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->supportsFullscreen();
    return false;
}

bool WebMediaPlayerClientImpl::supportsSave() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->supportsSave();
    return false;
}

void WebMediaPlayerClientImpl::setVolume(float volume)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setVolume(volume);
}

MediaPlayer::NetworkState WebMediaPlayerClientImpl::networkState() const
{
    COMPILE_ASSERT(
        int(WebMediaPlayer::Empty) == int(MediaPlayer::Empty), Empty);
    COMPILE_ASSERT(
        int(WebMediaPlayer::Idle) == int(MediaPlayer::Idle), Idle);
    COMPILE_ASSERT(
        int(WebMediaPlayer::Loading) == int(MediaPlayer::Loading), Loading);
    COMPILE_ASSERT(
        int(WebMediaPlayer::Loaded) == int(MediaPlayer::Loaded), Loaded);
    COMPILE_ASSERT(
        int(WebMediaPlayer::FormatError) == int(MediaPlayer::FormatError),
        FormatError);
    COMPILE_ASSERT(
        int(WebMediaPlayer::NetworkError) == int(MediaPlayer::NetworkError),
        NetworkError);
    COMPILE_ASSERT(
        int(WebMediaPlayer::DecodeError) == int(MediaPlayer::DecodeError),
        DecodeError);

    if (m_webMediaPlayer.get())
        return static_cast<MediaPlayer::NetworkState>(m_webMediaPlayer->networkState());
    return MediaPlayer::Empty;
}

MediaPlayer::ReadyState WebMediaPlayerClientImpl::readyState() const
{
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveNothing) == int(MediaPlayer::HaveNothing),
        HaveNothing);
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveMetadata) == int(MediaPlayer::HaveMetadata),
        HaveMetadata);
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveCurrentData) == int(MediaPlayer::HaveCurrentData),
        HaveCurrentData);
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveFutureData) == int(MediaPlayer::HaveFutureData),
        HaveFutureData);
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveEnoughData) == int(MediaPlayer::HaveEnoughData),
        HaveEnoughData);

    if (m_webMediaPlayer.get())
        return static_cast<MediaPlayer::ReadyState>(m_webMediaPlayer->readyState());
    return MediaPlayer::HaveNothing;
}

float WebMediaPlayerClientImpl::maxTimeSeekable() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->maxTimeSeekable();
    return 0.0f;
}

float WebMediaPlayerClientImpl::maxTimeBuffered() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->maxTimeBuffered();
    return 0.0f;
}

int WebMediaPlayerClientImpl::dataRate() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->dataRate();
    return 0;
}

bool WebMediaPlayerClientImpl::totalBytesKnown() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->totalBytesKnown();
    return false;
}

unsigned WebMediaPlayerClientImpl::totalBytes() const
{
    if (m_webMediaPlayer.get())
        return static_cast<unsigned>(m_webMediaPlayer->totalBytes());
    return 0;
}

unsigned WebMediaPlayerClientImpl::bytesLoaded() const
{
    if (m_webMediaPlayer.get())
        return static_cast<unsigned>(m_webMediaPlayer->bytesLoaded());
    return 0;
}

void WebMediaPlayerClientImpl::setSize(const IntSize& size)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setSize(WebSize(size.width(), size.height()));
}

void WebMediaPlayerClientImpl::paint(GraphicsContext* context, const IntRect& rect)
{
    if (m_webMediaPlayer.get()) {
#if WEBKIT_USING_SKIA
        m_webMediaPlayer->paint(context->platformContext()->canvas(), rect);
#elif WEBKIT_USING_CG
        // If there is no preexisting platform canvas, or if the size has
        // changed, recreate the canvas.  This is to avoid recreating the bitmap
        // buffer over and over for each frame of video.
        if (!m_webCanvas ||
            m_webCanvas->getDevice()->width() != rect.width() ||
            m_webCanvas->getDevice()->height() != rect.height()) {
            m_webCanvas.set(new WebCanvas(rect.width(), rect.height(), true));
        }

        IntRect normalized_rect(0, 0, rect.width(), rect.height());
        m_webMediaPlayer->paint(m_webCanvas.get(), normalized_rect);

        // The mac coordinate system is flipped vertical from the normal skia
        // coordinates.  During painting of the frame, flip the coordinates
        // system and, for simplicity, also translate the clip rectangle to
        // start at 0,0.
        CGContext* cgContext = context->platformContext();
        CGContextSaveGState(cgContext);
        CGContextTranslateCTM(cgContext, rect.x(), rect.height() + rect.y());
        CGContextScaleCTM(cgContext, 1.0, -1.0);
        CGRect normalized_cgrect = normalized_rect;  // For DrawToContext.

        m_webCanvas->getTopPlatformDevice().DrawToContext(
            context->platformContext(), 0, 0, &normalized_cgrect);

        CGContextRestoreGState(cgContext);
#else
        notImplemented();
#endif
    }
}

void WebMediaPlayerClientImpl::setAutobuffer(bool autoBuffer)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setAutoBuffer(autoBuffer);
}

bool WebMediaPlayerClientImpl::hasSingleSecurityOrigin() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->hasSingleSecurityOrigin();
    return false;
}

MediaPlayer::MovieLoadType WebMediaPlayerClientImpl::movieLoadType() const
{
    COMPILE_ASSERT(
        int(WebMediaPlayer::Unknown) == int(MediaPlayer::Unknown),
        Unknown);
    COMPILE_ASSERT(
        int(WebMediaPlayer::Download) == int(MediaPlayer::Download),
        Download);
    COMPILE_ASSERT(
        int(WebMediaPlayer::StoredStream) == int(MediaPlayer::StoredStream),
        StoredStream);
    COMPILE_ASSERT(
        int(WebMediaPlayer::LiveStream) == int(MediaPlayer::LiveStream),
        LiveStream);

    if (m_webMediaPlayer.get())
        return static_cast<MediaPlayer::MovieLoadType>(
            m_webMediaPlayer->movieLoadType());
    return MediaPlayer::Unknown;
}

MediaPlayerPrivateInterface* WebMediaPlayerClientImpl::create(MediaPlayer* player)
{
    WebMediaPlayerClientImpl* client = new WebMediaPlayerClientImpl();
    client->m_mediaPlayer = player;
    return client;
}

void WebMediaPlayerClientImpl::getSupportedTypes(HashSet<String>& supportedTypes)
{
    // FIXME: integrate this list with WebMediaPlayerClientImpl::supportsType.
    notImplemented();
}

MediaPlayer::SupportsType WebMediaPlayerClientImpl::supportsType(const String& type,
                                                                 const String& codecs)
{
    WebMimeRegistry::SupportsType supportsType =
        webKitClient()->mimeRegistry()->supportsMediaMIMEType(type, codecs);

    switch (supportsType) {
    case WebMimeRegistry::IsNotSupported:
          return MediaPlayer::IsNotSupported;
    case WebMimeRegistry::IsSupported:
          return MediaPlayer::IsSupported;
    case WebMimeRegistry::MayBeSupported:
          return MediaPlayer::MayBeSupported;
    }
}

WebMediaPlayerClientImpl::WebMediaPlayerClientImpl()
    : m_mediaPlayer(0)
{
}

} // namespace WebKit

#endif  // ENABLE(VIDEO)
<commit_msg>Fix a "not all control paths return a value" warning and correct indentation.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "WebMediaPlayerClientImpl.h"

#if ENABLE(VIDEO)

#include "TemporaryGlue.h"
#include "WebCanvas.h"
#include "WebCString.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebMediaPlayer.h"
#include "WebMimeRegistry.h"
#include "WebRect.h"
#include "WebSize.h"
#include "WebString.h"
#include "WebURL.h"

#include "CString.h"
#include "Frame.h"
#include "GraphicsContext.h"
#include "HTMLMediaElement.h"
#include "IntSize.h"
#include "KURL.h"
#include "MediaPlayer.h"
#include "NotImplemented.h"
#include "PlatformContextSkia.h"
#include <wtf/Assertions.h>

using namespace WebCore;

namespace WebKit {

static bool s_isEnabled = false;

void WebMediaPlayerClientImpl::setIsEnabled(bool isEnabled)
{
    s_isEnabled = isEnabled;
}

void WebMediaPlayerClientImpl::registerSelf(MediaEngineRegistrar registrar)
{
    if (s_isEnabled) {
        registrar(WebMediaPlayerClientImpl::create,
                  WebMediaPlayerClientImpl::getSupportedTypes,
                  WebMediaPlayerClientImpl::supportsType);
    }
}

// WebMediaPlayerClient --------------------------------------------------------

void WebMediaPlayerClientImpl::networkStateChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->networkStateChanged();
}

void WebMediaPlayerClientImpl::readyStateChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->readyStateChanged();
}

void WebMediaPlayerClientImpl::volumeChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->volumeChanged();
}

void WebMediaPlayerClientImpl::timeChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->timeChanged();
}

void WebMediaPlayerClientImpl::repaint()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->repaint();
}

void WebMediaPlayerClientImpl::durationChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->durationChanged();
}

void WebMediaPlayerClientImpl::rateChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->rateChanged();
}

void WebMediaPlayerClientImpl::sizeChanged()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->sizeChanged();
}

void WebMediaPlayerClientImpl::sawUnsupportedTracks()
{
    ASSERT(m_mediaPlayer);
    m_mediaPlayer->mediaPlayerClient()->mediaPlayerSawUnsupportedTracks(m_mediaPlayer);
}

// MediaPlayerPrivateInterface -------------------------------------------------

void WebMediaPlayerClientImpl::load(const String& url)
{
    Frame* frame = static_cast<HTMLMediaElement*>(
        m_mediaPlayer->mediaPlayerClient())->document()->frame();
    m_webMediaPlayer.set(TemporaryGlue::createWebMediaPlayer(this, frame));
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->load(KURL(url));
}

void WebMediaPlayerClientImpl::cancelLoad()
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->cancelLoad();
}

void WebMediaPlayerClientImpl::play()
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->play();
}

void WebMediaPlayerClientImpl::pause()
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->pause();
}

IntSize WebMediaPlayerClientImpl::naturalSize() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->naturalSize();
    return IntSize();
}

bool WebMediaPlayerClientImpl::hasVideo() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->hasVideo();
    return false;
}

void WebMediaPlayerClientImpl::setVisible(bool visible)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setVisible(visible);
}

float WebMediaPlayerClientImpl::duration() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->duration();
    return 0.0f;
}

float WebMediaPlayerClientImpl::currentTime() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->currentTime();
    return 0.0f;
}

void WebMediaPlayerClientImpl::seek(float time)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->seek(time);
}

bool WebMediaPlayerClientImpl::seeking() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->seeking();
    return false;
}

void WebMediaPlayerClientImpl::setEndTime(float time)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setEndTime(time);
}

void WebMediaPlayerClientImpl::setRate(float rate)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setRate(rate);
}

bool WebMediaPlayerClientImpl::paused() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->paused();
    return false;
}

bool WebMediaPlayerClientImpl::supportsFullscreen() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->supportsFullscreen();
    return false;
}

bool WebMediaPlayerClientImpl::supportsSave() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->supportsSave();
    return false;
}

void WebMediaPlayerClientImpl::setVolume(float volume)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setVolume(volume);
}

MediaPlayer::NetworkState WebMediaPlayerClientImpl::networkState() const
{
    COMPILE_ASSERT(
        int(WebMediaPlayer::Empty) == int(MediaPlayer::Empty), Empty);
    COMPILE_ASSERT(
        int(WebMediaPlayer::Idle) == int(MediaPlayer::Idle), Idle);
    COMPILE_ASSERT(
        int(WebMediaPlayer::Loading) == int(MediaPlayer::Loading), Loading);
    COMPILE_ASSERT(
        int(WebMediaPlayer::Loaded) == int(MediaPlayer::Loaded), Loaded);
    COMPILE_ASSERT(
        int(WebMediaPlayer::FormatError) == int(MediaPlayer::FormatError),
        FormatError);
    COMPILE_ASSERT(
        int(WebMediaPlayer::NetworkError) == int(MediaPlayer::NetworkError),
        NetworkError);
    COMPILE_ASSERT(
        int(WebMediaPlayer::DecodeError) == int(MediaPlayer::DecodeError),
        DecodeError);

    if (m_webMediaPlayer.get())
        return static_cast<MediaPlayer::NetworkState>(m_webMediaPlayer->networkState());
    return MediaPlayer::Empty;
}

MediaPlayer::ReadyState WebMediaPlayerClientImpl::readyState() const
{
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveNothing) == int(MediaPlayer::HaveNothing),
        HaveNothing);
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveMetadata) == int(MediaPlayer::HaveMetadata),
        HaveMetadata);
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveCurrentData) == int(MediaPlayer::HaveCurrentData),
        HaveCurrentData);
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveFutureData) == int(MediaPlayer::HaveFutureData),
        HaveFutureData);
    COMPILE_ASSERT(
        int(WebMediaPlayer::HaveEnoughData) == int(MediaPlayer::HaveEnoughData),
        HaveEnoughData);

    if (m_webMediaPlayer.get())
        return static_cast<MediaPlayer::ReadyState>(m_webMediaPlayer->readyState());
    return MediaPlayer::HaveNothing;
}

float WebMediaPlayerClientImpl::maxTimeSeekable() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->maxTimeSeekable();
    return 0.0f;
}

float WebMediaPlayerClientImpl::maxTimeBuffered() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->maxTimeBuffered();
    return 0.0f;
}

int WebMediaPlayerClientImpl::dataRate() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->dataRate();
    return 0;
}

bool WebMediaPlayerClientImpl::totalBytesKnown() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->totalBytesKnown();
    return false;
}

unsigned WebMediaPlayerClientImpl::totalBytes() const
{
    if (m_webMediaPlayer.get())
        return static_cast<unsigned>(m_webMediaPlayer->totalBytes());
    return 0;
}

unsigned WebMediaPlayerClientImpl::bytesLoaded() const
{
    if (m_webMediaPlayer.get())
        return static_cast<unsigned>(m_webMediaPlayer->bytesLoaded());
    return 0;
}

void WebMediaPlayerClientImpl::setSize(const IntSize& size)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setSize(WebSize(size.width(), size.height()));
}

void WebMediaPlayerClientImpl::paint(GraphicsContext* context, const IntRect& rect)
{
    if (m_webMediaPlayer.get()) {
#if WEBKIT_USING_SKIA
        m_webMediaPlayer->paint(context->platformContext()->canvas(), rect);
#elif WEBKIT_USING_CG
        // If there is no preexisting platform canvas, or if the size has
        // changed, recreate the canvas.  This is to avoid recreating the bitmap
        // buffer over and over for each frame of video.
        if (!m_webCanvas ||
            m_webCanvas->getDevice()->width() != rect.width() ||
            m_webCanvas->getDevice()->height() != rect.height()) {
            m_webCanvas.set(new WebCanvas(rect.width(), rect.height(), true));
        }

        IntRect normalized_rect(0, 0, rect.width(), rect.height());
        m_webMediaPlayer->paint(m_webCanvas.get(), normalized_rect);

        // The mac coordinate system is flipped vertical from the normal skia
        // coordinates.  During painting of the frame, flip the coordinates
        // system and, for simplicity, also translate the clip rectangle to
        // start at 0,0.
        CGContext* cgContext = context->platformContext();
        CGContextSaveGState(cgContext);
        CGContextTranslateCTM(cgContext, rect.x(), rect.height() + rect.y());
        CGContextScaleCTM(cgContext, 1.0, -1.0);
        CGRect normalized_cgrect = normalized_rect;  // For DrawToContext.

        m_webCanvas->getTopPlatformDevice().DrawToContext(
            context->platformContext(), 0, 0, &normalized_cgrect);

        CGContextRestoreGState(cgContext);
#else
        notImplemented();
#endif
    }
}

void WebMediaPlayerClientImpl::setAutobuffer(bool autoBuffer)
{
    if (m_webMediaPlayer.get())
        m_webMediaPlayer->setAutoBuffer(autoBuffer);
}

bool WebMediaPlayerClientImpl::hasSingleSecurityOrigin() const
{
    if (m_webMediaPlayer.get())
        return m_webMediaPlayer->hasSingleSecurityOrigin();
    return false;
}

MediaPlayer::MovieLoadType WebMediaPlayerClientImpl::movieLoadType() const
{
    COMPILE_ASSERT(
        int(WebMediaPlayer::Unknown) == int(MediaPlayer::Unknown),
        Unknown);
    COMPILE_ASSERT(
        int(WebMediaPlayer::Download) == int(MediaPlayer::Download),
        Download);
    COMPILE_ASSERT(
        int(WebMediaPlayer::StoredStream) == int(MediaPlayer::StoredStream),
        StoredStream);
    COMPILE_ASSERT(
        int(WebMediaPlayer::LiveStream) == int(MediaPlayer::LiveStream),
        LiveStream);

    if (m_webMediaPlayer.get())
        return static_cast<MediaPlayer::MovieLoadType>(
            m_webMediaPlayer->movieLoadType());
    return MediaPlayer::Unknown;
}

MediaPlayerPrivateInterface* WebMediaPlayerClientImpl::create(MediaPlayer* player)
{
    WebMediaPlayerClientImpl* client = new WebMediaPlayerClientImpl();
    client->m_mediaPlayer = player;
    return client;
}

void WebMediaPlayerClientImpl::getSupportedTypes(HashSet<String>& supportedTypes)
{
    // FIXME: integrate this list with WebMediaPlayerClientImpl::supportsType.
    notImplemented();
}

MediaPlayer::SupportsType WebMediaPlayerClientImpl::supportsType(const String& type,
                                                                 const String& codecs)
{
    WebMimeRegistry::SupportsType supportsType =
        webKitClient()->mimeRegistry()->supportsMediaMIMEType(type, codecs);

    switch (supportsType) {
    default:
        ASSERT_NOT_REACHED();
    case WebMimeRegistry::IsNotSupported:
        return MediaPlayer::IsNotSupported;
    case WebMimeRegistry::IsSupported:
        return MediaPlayer::IsSupported;
    case WebMimeRegistry::MayBeSupported:
        return MediaPlayer::MayBeSupported;
    }
}

WebMediaPlayerClientImpl::WebMediaPlayerClientImpl()
    : m_mediaPlayer(0)
{
}

} // namespace WebKit

#endif  // ENABLE(VIDEO)
<|endoftext|>