<commit_before>// Copyright (c) 2009 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include "libmv/multiview/2DAffine.h"
#include <iostream>
namespace libmv {

bool Affine2D_FromCorrespondencesLinear(const Mat &x1, const Mat &x2,
                                            Mat3 *M)  {

  assert(2 == x1.rows());
  assert(2 <= x1.cols());
  assert(x1.rows() == x2.rows());
  assert(x1.cols() == x2.cols());

  int n = x1.cols();
  Mat A(4, 4);
  A.setZero();
  Mat B(4, 1);
  B.setZero();
  for (int i = 0; i < n; ++i) {
    int j=(i%2)*2;
    A(j,0) += -x1(1,i);
    A(j,1) +=  x1(0,i);
    A(j,2) +=  1.0;
    A(j,3) =  0.0;

    A(j+1,0) += x1(0,i);
    A(j+1,1) += x1(1,i);
    A(j+1,2) = 0.0;
    A(j+1,3) += 1.0;

    // x'
    B(j,0)   += x2(0,i);
    B(j+1,0) += x2(1,i);
  }
  // Does A is invertible ?
  if( fabs(A.determinant()) < 1e-1) {
     return false;
  }
  Mat res = A.inverse() * B;

  // Configure output matrix :
  (*M)(0,0) = res(1,0);   (*M)(0,1) = res(0,0);// cos sin
  (*M)(1,0) = -res(0,0);  (*M)(1,1) = res(1,0);// sin cos
  (*M)(0,2) = res(2,0);// tx
  (*M)(1,2) = res(3,0);// ty
  // Force homogeneous coord
  (*M)(2,2) = 1.0;
  return true;
}

}
<commit_msg>- Fix for windows. Some matrix value are not initialized to 0.0.<commit_after>// Copyright (c) 2009 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include "libmv/multiview/2DAffine.h"
#include <iostream>
namespace libmv {

bool Affine2D_FromCorrespondencesLinear(const Mat &x1, const Mat &x2,
                                            Mat3 *M)  {

  assert(2 == x1.rows());
  assert(2 <= x1.cols());
  assert(x1.rows() == x2.rows());
  assert(x1.cols() == x2.cols());

  int n = x1.cols();
  Mat A(4, 4);
  A.setZero();
  Mat B(4, 1);
  B.setZero();
  for (int i = 0; i < n; ++i) {
    int j=(i%2)*2;
    A(j,0) += -x1(1,i);
    A(j,1) +=  x1(0,i);
    A(j,2) +=  1.0;
    A(j,3) =  0.0;

    A(j+1,0) += x1(0,i);
    A(j+1,1) += x1(1,i);
    A(j+1,2) = 0.0;
    A(j+1,3) += 1.0;

    // x'
    B(j,0)   += x2(0,i);
    B(j+1,0) += x2(1,i);
  }
  // Does A is invertible ?
  if( fabs(A.determinant()) < 1e-1) {
     return false;
  }
  Mat res = A.inverse() * B;

  // Configure output matrix :
  (*M)(0,0) = res(1,0);   (*M)(0,1) = res(0,0);// cos sin
  (*M)(1,0) = -res(0,0);  (*M)(1,1) = res(1,0);// sin cos
  (*M)(0,2) = res(2,0);// tx
  (*M)(1,2) = res(3,0);// ty
  (*M)(2,0) = (*M)(2,1) = 0.0;
  // Force homogeneous coord
  (*M)(2,2) = 1.0;
  return true;
}

}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <functional>
#include <unordered_map>
#include <map>

#include <boost/optional.hpp>
#include <boost/variant/get.hpp>
#include <boost/variant.hpp>
#include <boost/lexical_cast.hpp>

#include "config.h"

namespace liquidpp {
enum class ValueTag {
   Object,
   Range,
   Null,
   OutOfRange,
   SubValue
};

struct test {
   std::string s;
   string_view sv;
   long long i;
   double f;
   bool b;
   ValueTag t;
};

struct Value {
private:
   boost::variant<string_view, std::string, std::intmax_t, double, bool, ValueTag> data{ValueTag::Null};

public:
   Value() = default;

   Value(const Value&) = default;

   Value(Value&&) = default;

   Value& operator=(const Value&) = default;

   Value& operator=(Value&&) = default;

   Value(ValueTag tag)
      : data(tag) {}

   Value(const std::string& v)
      : data(v) {}

   Value(std::string&& v)
      : data(std::move(v)) {}

   static Value fromBool(bool b) {
      Value res;
      res.data = b;
      assert(res.isBool());
      return res;
   }

   template<typename T>
   static Value fromIntegral(T t) {
      Value res;
      res.data = static_cast<std::intmax_t>(t);
      assert(res.isIntegral());
      return res;
   }

   template<typename T>
   static Value fromFloatingPoint(T t) {
      Value res;
      res.data = static_cast<double>(t);
      assert(res.isFloatingPoint());
      return res;
   }

   static Value reference(string_view sv) {
      Value res;
      res.data = sv;
      return res;
   }

   bool isValueTag() const {
      return data.which() == 5;
   }

   bool isSimpleValue() const {
      return !isValueTag();
   }

   bool isNil() const {
      if (isValueTag()) {
         auto tagVal = boost::get<ValueTag>(data);
         if (tagVal == ValueTag::Null || tagVal == ValueTag::OutOfRange)
            return true;
      }
      return false;
   }

   bool isBool() const {
      return data.which() == 4;
   }

   bool isTrue() const {
      return isBool() && boost::get<bool>(data);
   }

   bool isFalse() const {
      return isBool() && (boost::get<bool>(data) == false);
   }

   bool isIntegral() const {
      return data.which() == 2;
   }

   bool isFloatingPoint() const {
      return data.which() == 3;
   }

   bool isNumber() const {
      return isIntegral() || isFloatingPoint();
   }

   bool isStringType() const {
      if (data.which() == 0 || data.which() == 1)
         return true;
      return false;
   }

   explicit operator bool() const {
      if (isFalse() || isNil())
         return false;
      return true;
   }

   bool operator!() const {
      if (*this)
         return false;
      return true;
   }

   bool isStringViewRepresentable() const {
      return !isNumber();
   }

   Value& operator|=(const Value& v) {
      if (!*this)
         *this = v;
      return *this;
   }

   Value& operator&=(const Value& v) {
      if (*this)
         *this = v;
      return *this;
   }

   std::string toString() const {
      if (isIntegral())
         return boost::lexical_cast<std::string>(boost::get<std::int64_t>(data));
      else if (isFloatingPoint())
         return boost::lexical_cast<std::string>(boost::get<double>(data));
      else
         return (**this).to_string();
   }

   string_view operator*() const {
      // TODO: static_visitor
      if (data.which() == 0)
         return boost::get<string_view>(data);
      if (data.which() == 1)
         return boost::get<std::string>(data);
      if (isBool())
         return isTrue() ? "true" : "false";
      return string_view{};
   }

private:
   template<typename Comparsion>
   struct Compare : public boost::static_visitor<bool> {
      template<typename T, typename U>
      bool operator()(const T& left, const U& right) const {
         return false;
      }

      template<typename T>
      bool operator()(const T& left, const T& right) const {
         return Comparsion{}(left, right);
      }

      bool operator()(const string_view& left, const std::string& right) const {
         return Comparsion{}(left, string_view{right});
      }

      bool operator()(const std::string& left, const string_view& right) const {
         return Comparsion{}(string_view{left}, right);
      }

      bool operator()(const double& left, const std::intmax_t& right) const {
         return Comparsion{}(left, static_cast<double>(right));
      }

      bool operator()(const std::intmax_t& left, const double& right) const {
         return Comparsion{}(static_cast<double>(left), right);
      }
   };

   template<template <typename> class C>
   bool compareWith(const Value& other) const
   {
      Compare<C<void>> comp;
      return boost::apply_visitor(comp, this->data, other.data);
   }

public:
   bool operator==(const Value& other) const {
      return compareWith<std::equal_to>(other);
   }

   bool operator!=(const Value& other) const {
      return compareWith<std::not_equal_to>(other);
   }

   bool operator<(const Value& other) const {
      return compareWith<std::less>(other);
   }

   bool operator<=(const Value& other) const {
      return compareWith<std::less_equal>(other);
   }

   bool operator>(const Value& other) const {
      return compareWith<std::greater>(other);
   }

   bool operator>=(const Value& other) const {
      return compareWith<std::greater_equal>(other);
   }

   bool contains(const Value& other) const {
      if (!isStringType())
         return false;

      auto thisStr = **this;
      auto otherStr = other.toString();
      return thisStr.find(otherStr) != std::string::npos;
   }

   bool operator==(ValueTag tag) const {
      if (isValueTag())
         return boost::get<ValueTag>(data) == tag;
      return false;
   }

   bool operator!=(ValueTag tag) const {
      return !(*this == tag);
   }
};

using OptIndex = boost::optional<size_t>;
using ValueGetter = std::function<Value(OptIndex, string_view)>;

template<typename T>
struct ValueConverter : public std::false_type {
};

template<typename T>
constexpr bool hasValueConverter = ValueConverter<T>::value;

inline Value toValue(std::string v) {
   return Value(std::move(v));
}

inline Value toValue(const char* v) {
   return Value(std::string{v});
}

template<size_t Len>
Value toValue(const char (&v)[Len]) {
   return Value(std::string{v});
}

inline Value toValue(bool b) {
   return Value::fromBool(b);
}

template<typename T>
Value toValue(T t, std::enable_if_t<!hasValueConverter<T> && std::is_integral<T>::value, void**> = 0) {
   return Value::fromIntegral(t);
}

template<typename T>
Value toValue(T t, std::enable_if_t<!hasValueConverter<T> && std::is_floating_point<T>::value, void**> = 0) {
   return Value::fromFloatingPoint(t);
}

template<typename T>
std::string toValue(const T& value, std::enable_if_t<hasValueConverter<T>, void**> = 0) {
   return ValueConverter<T>::get(value);
}

namespace impl {
template<typename KeyT, typename ValueT>
struct AssociativeContainerConverter : public std::true_type {
   template<typename T>
   static auto get(T&& map) {
      return [map = std::forward<T>(map)](OptIndex
      idx, string_view
      path) -> Value
      {
         auto itr = map.find(boost::lexical_cast<KeyT>(path));
         if (itr != map.end())
            return toValue(itr->second);
         return ValueTag::Null;
      };
   }
};
}

template<typename KeyT, typename ValueT>
struct ValueConverter<std::map<KeyT, ValueT>> : public impl::AssociativeContainerConverter<KeyT, ValueT> {
};

template<typename KeyT, typename ValueT>
struct ValueConverter<std::unordered_map<KeyT, ValueT>> : public impl::AssociativeContainerConverter<KeyT, ValueT> {
};

template<typename ValueT>
struct ValueConverter<std::vector<ValueT>> : public std::true_type {
   template<typename T>
   static auto get(T&& vec) {
      return [vec = std::forward<T>(vec)](OptIndex
      idx, string_view
      path) -> Value
      {
         if (!idx)
            return ValueTag::Range;
         if (*idx < vec.size())
            return toValue(vec[*idx]);
         return ValueTag::OutOfRange;
      };
   }
};
}
<commit_msg>Explicitly include <vector><commit_after>#pragma once

#include <string>
#include <functional>
#include <unordered_map>
#include <map>
#include <vector>

#include <boost/optional.hpp>
#include <boost/variant/get.hpp>
#include <boost/variant.hpp>
#include <boost/lexical_cast.hpp>

#include "config.h"

namespace liquidpp {
enum class ValueTag {
   Object,
   Range,
   Null,
   OutOfRange,
   SubValue
};

struct test {
   std::string s;
   string_view sv;
   long long i;
   double f;
   bool b;
   ValueTag t;
};

struct Value {
private:
   boost::variant<string_view, std::string, std::intmax_t, double, bool, ValueTag> data{ValueTag::Null};

public:
   Value() = default;

   Value(const Value&) = default;

   Value(Value&&) = default;

   Value& operator=(const Value&) = default;

   Value& operator=(Value&&) = default;

   Value(ValueTag tag)
      : data(tag) {}

   Value(const std::string& v)
      : data(v) {}

   Value(std::string&& v)
      : data(std::move(v)) {}

   static Value fromBool(bool b) {
      Value res;
      res.data = b;
      assert(res.isBool());
      return res;
   }

   template<typename T>
   static Value fromIntegral(T t) {
      Value res;
      res.data = static_cast<std::intmax_t>(t);
      assert(res.isIntegral());
      return res;
   }

   template<typename T>
   static Value fromFloatingPoint(T t) {
      Value res;
      res.data = static_cast<double>(t);
      assert(res.isFloatingPoint());
      return res;
   }

   static Value reference(string_view sv) {
      Value res;
      res.data = sv;
      return res;
   }

   bool isValueTag() const {
      return data.which() == 5;
   }

   bool isSimpleValue() const {
      return !isValueTag();
   }

   bool isNil() const {
      if (isValueTag()) {
         auto tagVal = boost::get<ValueTag>(data);
         if (tagVal == ValueTag::Null || tagVal == ValueTag::OutOfRange)
            return true;
      }
      return false;
   }

   bool isBool() const {
      return data.which() == 4;
   }

   bool isTrue() const {
      return isBool() && boost::get<bool>(data);
   }

   bool isFalse() const {
      return isBool() && (boost::get<bool>(data) == false);
   }

   bool isIntegral() const {
      return data.which() == 2;
   }

   bool isFloatingPoint() const {
      return data.which() == 3;
   }

   bool isNumber() const {
      return isIntegral() || isFloatingPoint();
   }

   bool isStringType() const {
      if (data.which() == 0 || data.which() == 1)
         return true;
      return false;
   }

   explicit operator bool() const {
      if (isFalse() || isNil())
         return false;
      return true;
   }

   bool operator!() const {
      if (*this)
         return false;
      return true;
   }

   bool isStringViewRepresentable() const {
      return !isNumber();
   }

   Value& operator|=(const Value& v) {
      if (!*this)
         *this = v;
      return *this;
   }

   Value& operator&=(const Value& v) {
      if (*this)
         *this = v;
      return *this;
   }

   std::string toString() const {
      if (isIntegral())
         return boost::lexical_cast<std::string>(boost::get<std::int64_t>(data));
      else if (isFloatingPoint())
         return boost::lexical_cast<std::string>(boost::get<double>(data));
      else
         return (**this).to_string();
   }

   string_view operator*() const {
      // TODO: static_visitor
      if (data.which() == 0)
         return boost::get<string_view>(data);
      if (data.which() == 1)
         return boost::get<std::string>(data);
      if (isBool())
         return isTrue() ? "true" : "false";
      return string_view{};
   }

private:
   template<typename Comparsion>
   struct Compare : public boost::static_visitor<bool> {
      template<typename T, typename U>
      bool operator()(const T& left, const U& right) const {
         return false;
      }

      template<typename T>
      bool operator()(const T& left, const T& right) const {
         return Comparsion{}(left, right);
      }

      bool operator()(const string_view& left, const std::string& right) const {
         return Comparsion{}(left, string_view{right});
      }

      bool operator()(const std::string& left, const string_view& right) const {
         return Comparsion{}(string_view{left}, right);
      }

      bool operator()(const double& left, const std::intmax_t& right) const {
         return Comparsion{}(left, static_cast<double>(right));
      }

      bool operator()(const std::intmax_t& left, const double& right) const {
         return Comparsion{}(static_cast<double>(left), right);
      }
   };

   template<template <typename> class C>
   bool compareWith(const Value& other) const
   {
      Compare<C<void>> comp;
      return boost::apply_visitor(comp, this->data, other.data);
   }

public:
   bool operator==(const Value& other) const {
      return compareWith<std::equal_to>(other);
   }

   bool operator!=(const Value& other) const {
      return compareWith<std::not_equal_to>(other);
   }

   bool operator<(const Value& other) const {
      return compareWith<std::less>(other);
   }

   bool operator<=(const Value& other) const {
      return compareWith<std::less_equal>(other);
   }

   bool operator>(const Value& other) const {
      return compareWith<std::greater>(other);
   }

   bool operator>=(const Value& other) const {
      return compareWith<std::greater_equal>(other);
   }

   bool contains(const Value& other) const {
      if (!isStringType())
         return false;

      auto thisStr = **this;
      auto otherStr = other.toString();
      return thisStr.find(otherStr) != std::string::npos;
   }

   bool operator==(ValueTag tag) const {
      if (isValueTag())
         return boost::get<ValueTag>(data) == tag;
      return false;
   }

   bool operator!=(ValueTag tag) const {
      return !(*this == tag);
   }
};

using OptIndex = boost::optional<size_t>;
using ValueGetter = std::function<Value(OptIndex, string_view)>;

template<typename T>
struct ValueConverter : public std::false_type {
};

template<typename T>
constexpr bool hasValueConverter = ValueConverter<T>::value;

inline Value toValue(std::string v) {
   return Value(std::move(v));
}

inline Value toValue(const char* v) {
   return Value(std::string{v});
}

template<size_t Len>
Value toValue(const char (&v)[Len]) {
   return Value(std::string{v});
}

inline Value toValue(bool b) {
   return Value::fromBool(b);
}

template<typename T>
Value toValue(T t, std::enable_if_t<!hasValueConverter<T> && std::is_integral<T>::value, void**> = 0) {
   return Value::fromIntegral(t);
}

template<typename T>
Value toValue(T t, std::enable_if_t<!hasValueConverter<T> && std::is_floating_point<T>::value, void**> = 0) {
   return Value::fromFloatingPoint(t);
}

template<typename T>
std::string toValue(const T& value, std::enable_if_t<hasValueConverter<T>, void**> = 0) {
   return ValueConverter<T>::get(value);
}

namespace impl {
template<typename KeyT, typename ValueT>
struct AssociativeContainerConverter : public std::true_type {
   template<typename T>
   static auto get(T&& map) {
      return [map = std::forward<T>(map)](OptIndex
      idx, string_view
      path) -> Value
      {
         auto itr = map.find(boost::lexical_cast<KeyT>(path));
         if (itr != map.end())
            return toValue(itr->second);
         return ValueTag::Null;
      };
   }
};
}

template<typename KeyT, typename ValueT>
struct ValueConverter<std::map<KeyT, ValueT>> : public impl::AssociativeContainerConverter<KeyT, ValueT> {
};

template<typename KeyT, typename ValueT>
struct ValueConverter<std::unordered_map<KeyT, ValueT>> : public impl::AssociativeContainerConverter<KeyT, ValueT> {
};

template<typename ValueT>
struct ValueConverter<std::vector<ValueT>> : public std::true_type {
   template<typename T>
   static auto get(T&& vec) {
      return [vec = std::forward<T>(vec)](OptIndex
      idx, string_view
      path) -> Value
      {
         if (!idx)
            return ValueTag::Range;
         if (*idx < vec.size())
            return toValue(vec[*idx]);
         return ValueTag::OutOfRange;
      };
   }
};
}
<|endoftext|>


<commit_before>#include <string.h>
#include <iostream>
#include <xf86drm.h>
#include <xf86drmMode.h>

#include "kms++.h"

using namespace std;

namespace kms
{

DrmObject::DrmObject(Card& card, uint32_t object_type)
	:m_id(-1), m_card(card), m_object_type(object_type)
{
}

DrmObject::DrmObject(Card& card, uint32_t id, uint32_t object_type, uint32_t idx)
	:m_id(id), m_card(card), m_object_type(object_type), m_idx(idx)
{
	refresh_props();
}

DrmObject::~DrmObject()
{

}

void DrmObject::refresh_props()
{
	auto props = drmModeObjectGetProperties(card().fd(), this->id(), this->object_type());

	if (props == nullptr)
		return;

	for (unsigned i = 0; i < props->count_props; ++i) {
		uint32_t prop_id = props->props[i];
		uint64_t prop_value = props->prop_values[i];

		m_prop_values[prop_id] = prop_value;
	}

	drmModeFreeObjectProperties(props);
}

void DrmObject::print_props() const
{
	for (auto it = m_prop_values.begin(); it != m_prop_values.end(); ++it) {
		cout << "\t" << card().get_prop(it->first)->name() <<
			" = " << it->second << endl;
	}
}

uint64_t DrmObject::get_prop_value(uint32_t id) const
{
	return m_prop_values.at(id);
}

uint64_t DrmObject::get_prop_value(const char *name) const
{
	for (auto pair : m_prop_values) {
		auto prop = card().get_prop(pair.first);
		if (strcmp(name, prop->name()) == 0)
			return m_prop_values.at(prop->id());
	}

	throw invalid_argument("foo");
}
}
<commit_msg>Proper exception string to DrmObject::get_prop_value()<commit_after>#include <string.h>
#include <iostream>
#include <xf86drm.h>
#include <xf86drmMode.h>

#include "kms++.h"

using namespace std;

namespace kms
{

DrmObject::DrmObject(Card& card, uint32_t object_type)
	:m_id(-1), m_card(card), m_object_type(object_type)
{
}

DrmObject::DrmObject(Card& card, uint32_t id, uint32_t object_type, uint32_t idx)
	:m_id(id), m_card(card), m_object_type(object_type), m_idx(idx)
{
	refresh_props();
}

DrmObject::~DrmObject()
{

}

void DrmObject::refresh_props()
{
	auto props = drmModeObjectGetProperties(card().fd(), this->id(), this->object_type());

	if (props == nullptr)
		return;

	for (unsigned i = 0; i < props->count_props; ++i) {
		uint32_t prop_id = props->props[i];
		uint64_t prop_value = props->prop_values[i];

		m_prop_values[prop_id] = prop_value;
	}

	drmModeFreeObjectProperties(props);
}

void DrmObject::print_props() const
{
	for (auto it = m_prop_values.begin(); it != m_prop_values.end(); ++it) {
		cout << "\t" << card().get_prop(it->first)->name() <<
			" = " << it->second << endl;
	}
}

uint64_t DrmObject::get_prop_value(uint32_t id) const
{
	return m_prop_values.at(id);
}

uint64_t DrmObject::get_prop_value(const char *name) const
{
	for (auto pair : m_prop_values) {
		auto prop = card().get_prop(pair.first);
		if (strcmp(name, prop->name()) == 0)
			return m_prop_values.at(prop->id());
	}

	throw invalid_argument((string(name) + ": property not found").c_str());
}
}
<|endoftext|>


<commit_before>

#include <time.h>
#include <sys/time.h>
#include <signal.h>   // SIGKILL

#include "logMsg/logMsg.h"                          // LM_X

#include "au/string.h"                             // au::xml_...
#include "au/TokenTaker.h"                          // au::TokenTake
#include "au/ErrorManager.h"                       // au::ErrorManager
#include "au/Token.h"                       // au::Token
#include "au/xml.h"         // au::xml...

#include "Notification.h"                           // engine::Notification

#include "engine/EngineElement.h"					// engine::EngineElement
#include "engine/ProcessItem.h"                     // engine::ProcessItem
#include "engine/DiskOperation.h"					// engine::DiskOperation
#include "engine/NotificationElement.h"       // engine::EngineNotificationElement

#include "engine/MemoryManager.h"
#include "engine/DiskManager.h"
#include "engine/ProcessManager.h"

#include "engine/Engine.h"							// Own interface

// Goyo. From 60 to 60000
#define ENGINE_MAX_RUNNING_TIME     60000

NAMESPACE_BEGIN(engine)

// Common engine
Engine *engine = NULL;

void* runEngineBakground(void* e )
{
    engine->run();
    return NULL;
}

Engine::Engine() :  EngineService("Engine") , token("EngineToken")
{
    running_element = NULL;                         // Initially, no running element
    flag_finish_threads = false;                    // Put this to "true" when destroying Engine
}

Engine::~Engine()
{
    // Waiting for all threads to finish
    engine->finish_threads();

    // Remove pending elements in Engine
    elements.clearList();
}

Engine* Engine::shared()
{
    if (!engine )
        LM_X(1,("Please init Engine with Engine::init()"));
    return engine;
}

void Engine::init()
{
    if ( engine )
    {
        LM_W(("Init engine twice... just ignoring"));
        return;
    }

    // Create the unique engine entity
    engine = new Engine();

    // Add a simple periodic element to not die inmediatelly
    EngineElement *element = new NotificationElement( new Notification("alive") , 10 );
    engine->elements.push_back( element );

    LM_T( LmtEngine , ("Running engine in background...") );
    pthread_create(&engine->t, 0, runEngineBakground, NULL);

    // Function to remove this engine and all EngineServices like MemoryMamager, DiskManager, ProcessManager etc...
    atexit( destroy_engine_services );
}

void Engine::finish_threads()
{
    flag_finish_threads = true;
    LM_M(("Waiting threads of Engine to finish..."));
    pthread_join(t, NULL);
    LM_M(("All Engine threads finished"));
}

void Engine::run()
{

    LM_T( LmtEngine , ("Engine run"));

    counter = 0;            // Init the counter to elements managed by this run-time

    while( true )
    {
        // Keep a total counter of loops
        counter++;

        // Finish this thread if necessary
        if( flag_finish_threads )
            return;

        // Check if there are elements in the list
        bool isEmpty;
        {
            // Mutex protection
            au::TokenTaker tt(&token , "Engine::getNextElement");
            isEmpty = ( elements.size() == 0);
        }

        if( isEmpty )
        {
            LM_T( LmtEngine, ("SamsonEngine: No more elements to process in the engine. Quitting ..."));
            return;
        }

        // Get time for the next engine element
        double t;
        {
            // Mutex protection to access elements
            au::TokenTaker tt(&token , "Engine::getNextElement");
            t = elements.front()->getTimeToTrigger();
        }

        if( t > 0 )
        {
            if ( t > 0.1 )
                t = 0.1; // Max time to sleep to avoid locks...

            // Sleeping a bit for the next engine element...
            LM_T( LmtEngine, ("Engine: Sleeping %.2f secs ..." , 2*t));

            {
                // Mutex protection to show list
                au::TokenTaker tt(&token , "Engine::getNextElement");
                LM_T( LmtEngine, ("--------------------------------------------------------" ));
                au::list<EngineElement>::iterator it_elements;
                for (it_elements = elements.begin() ; it_elements != elements.end() ; it_elements++ )
                {
                    EngineElement *element = *it_elements;
                    LM_T( LmtEngine, ("%s" , element->getShortDescription().c_str() ));
                }
                LM_T( LmtEngine, ("--------------------------------------------------------" ));
            }

            {
                au::ExecesiveTimeAlarm alarm( "Engine sleep" , t );
                int microsecons = t*1000000;
                usleep( microsecons );
            }
            continue; // Loop again to check again...
        }

        // Get the top element to be executed
        {
            // Mutex protection to access elements
            au::TokenTaker tt(&token , "Engine::getNextElement");

            running_element = elements.front();
            elements.pop_front();
        }

        // Run or sleep
        if ( !running_element )
            LM_X(1,("Internal error at Engine"));

        {
            // Execute the item selected as running_element
            LM_T( LmtEngine, ("[START] Engine executing %s" , running_element->getDescription().c_str() ));

            int excesive_time = - running_element->getTimeToTrigger();
            if ( excesive_time > 10 )
            {
                LM_W(("Task %s delayed %d seconds in starting. This should not be more than 10"
                      , running_element->getDescription().c_str()
                      , excesive_time
                      ));
            }

            {
                // Run the item controlling excesive time
                au::ExecesiveTimeAlarm alarm( au::str("ProcessItem run '%s'",running_element->getDescription().c_str() ));
                running_element->run();
            }

            LM_T( LmtEngine, ("[DONE] Engine executing %s" , running_element->getDescription().c_str()));

            EngineElement * _running_element = running_element;
            running_element = NULL; // Put running element to NULL

            if( _running_element->isRepeated() )
            {
                // Insert again
                _running_element->Reschedule();
                add( _running_element );
            }
            else
                delete _running_element;

        }
    }
}

std::list<EngineElement*>::iterator Engine::_find_pos( EngineElement *e)
{
    for (std::list<EngineElement*>::iterator i = elements.begin() ; i != elements.end() ; i++)
    {
        if ( (*i)->getTimeToTrigger() > e->getTimeToTrigger() )
            return i;
    }

    return elements.end();
}

#pragma mark ----

// get xml information
void Engine::getInfo( std::ostringstream& output)
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::str");

    au::xml_open(output, "engine");

    au::xml_simple(output , "loops" , counter );

    if( running_element )
        au::xml_simple( output , "running_element" , running_element->getDescription() );
    else
        au::xml_simple( output , "running_element" , "No running element" );

    au::xml_iterate_list( output , "elements" , elements );

    au::xml_simple( output , "uptime" , uptime.diffTimeInSeconds() );

    au::xml_close(output , "engine");

}

// Functions to register objects ( general and for a particular notification )
void Engine::register_object( Object* object )
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::register_object" );

    objectsManager.add( object );
}

void Engine::register_object_for_channel( Object* object, const char* channel )
{
    // Mutex protection
    au::TokenTaker tt(&token,"Engine::register_object_for_channel");

    objectsManager.add( object , channel );
}

// Generic method to unregister an object
void Engine::unregister_object( Object* object )
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::unregister_object");

    objectsManager.remove( object );
}

// Run a particular notification
// Only executed from friend class "NotificationElement"
void Engine::send( Notification * notification )
{
    objectsManager.send( notification );
}

// Add a notification
void Engine::notify( Notification*  notification )
{
    // Push a notification element with the notification
    add( new NotificationElement( notification ) );
}

void Engine::notify( Notification*  notification , int seconds )
{
    // Push a notification element with the notification ( in this case with periodic time )
    add( new NotificationElement( notification , seconds ) );
}

// Function to add a simple foreground tasks
void Engine::add( EngineElement *element )
{
    // Mutex protection
    au::TokenTaker tt(&token);

    // Insert an element in the engine
    elements.insert( _find_pos( element ) ,  element );

    // Wake up main thread if sleeping
    tt.wakeUp();
}

// Get an object by its registry names
Object* Engine::getObjectByName( const char *name )
{
    // Mutex protection
    au::TokenTaker tt(&token);

    return objectsManager.getObjectByName(name);

}

NAMESPACE_END<commit_msg>SAMSON-291 some new execesite time alerts<commit_after>

#include <time.h>
#include <sys/time.h>
#include <signal.h>   // SIGKILL

#include "logMsg/logMsg.h"                          // LM_X

#include "au/string.h"                             // au::xml_...
#include "au/TokenTaker.h"                          // au::TokenTake
#include "au/ErrorManager.h"                       // au::ErrorManager
#include "au/Token.h"                       // au::Token
#include "au/xml.h"         // au::xml...

#include "Notification.h"                           // engine::Notification

#include "engine/EngineElement.h"					// engine::EngineElement
#include "engine/ProcessItem.h"                     // engine::ProcessItem
#include "engine/DiskOperation.h"					// engine::DiskOperation
#include "engine/NotificationElement.h"       // engine::EngineNotificationElement

#include "engine/MemoryManager.h"
#include "engine/DiskManager.h"
#include "engine/ProcessManager.h"

#include "engine/Engine.h"							// Own interface

// Goyo. From 60 to 60000
#define ENGINE_MAX_RUNNING_TIME     60000

NAMESPACE_BEGIN(engine)

// Common engine
Engine *engine = NULL;

void* runEngineBakground(void* e )
{
    engine->run();
    return NULL;
}

Engine::Engine() :  EngineService("Engine") , token("EngineToken")
{
    running_element = NULL;                         // Initially, no running element
    flag_finish_threads = false;                    // Put this to "true" when destroying Engine
}

Engine::~Engine()
{
    // Waiting for all threads to finish
    engine->finish_threads();

    // Remove pending elements in Engine
    elements.clearList();
}

Engine* Engine::shared()
{
    if (!engine )
        LM_X(1,("Please init Engine with Engine::init()"));
    return engine;
}

void Engine::init()
{
    if ( engine )
    {
        LM_W(("Init engine twice... just ignoring"));
        return;
    }

    // Create the unique engine entity
    engine = new Engine();

    // Add a simple periodic element to not die inmediatelly
    EngineElement *element = new NotificationElement( new Notification("alive") , 10 );
    engine->elements.push_back( element );

    LM_T( LmtEngine , ("Running engine in background...") );
    pthread_create(&engine->t, 0, runEngineBakground, NULL);

    // Function to remove this engine and all EngineServices like MemoryMamager, DiskManager, ProcessManager etc...
    atexit( destroy_engine_services );
}

void Engine::finish_threads()
{
    flag_finish_threads = true;
    LM_M(("Waiting threads of Engine to finish..."));
    pthread_join(t, NULL);
    LM_M(("All Engine threads finished"));
}

void Engine::run()
{

    LM_T( LmtEngine , ("Engine run"));

    counter = 0;            // Init the counter to elements managed by this run-time

    while( true )
    {
        // Keep a total counter of loops
        counter++;

        // Finish this thread if necessary
        if( flag_finish_threads )
            return;

        // Check if there are elements in the list
        bool isEmpty;
        {
            // Mutex protection
            au::TokenTaker tt(&token , "Engine::getNextElement");
            isEmpty = ( elements.size() == 0);
        }

        if( isEmpty )
        {
            LM_T( LmtEngine, ("SamsonEngine: No more elements to process in the engine. Quitting ..."));
            return;
        }

        // Get time for the next engine element
        double t;
        {
            // Mutex protection to access elements
            au::TokenTaker tt(&token , "Engine::getNextElement");
            t = elements.front()->getTimeToTrigger();
        }

        if( t > 0 )
        {
            if ( t > 0.1 )
                t = 0.1; // Max time to sleep to avoid locks...

            // Sleeping a bit for the next engine element...
            LM_T( LmtEngine, ("Engine: Sleeping %.2f secs ..." , t));

            /*
            {
                // Mutex protection to show list
                au::TokenTaker tt(&token , "Engine::getNextElement");
                LM_T( LmtEngine, ("--------------------------------------------------------" ));
                au::list<EngineElement>::iterator it_elements;
                for (it_elements = elements.begin() ; it_elements != elements.end() ; it_elements++ )
                {
                    EngineElement *element = *it_elements;
                    LM_T( LmtEngine, ("%s" , element->getShortDescription().c_str() ));
                }
                LM_T( LmtEngine, ("--------------------------------------------------------" ));
            }
             */

            {
                au::ExecesiveTimeAlarm alarm( "Engine sleep" , 2*t );
                int microsecons = t*1000000;
                usleep( microsecons );
            }
            continue; // Loop again to check again...
        }

        // Get the top element to be executed
        {
            // Mutex protection to access elements
            au::TokenTaker tt(&token , "Engine::getNextElement");

            running_element = elements.front();
            elements.pop_front();
        }

        // Run or sleep
        if ( !running_element )
            LM_X(1,("Internal error at Engine"));

        {
            // Execute the item selected as running_element
            LM_T( LmtEngine, ("[START] Engine executing %s" , running_element->getDescription().c_str() ));

            int excesive_time = - running_element->getTimeToTrigger();
            if ( excesive_time > 10 )
            {
                LM_W(("Task %s delayed %d seconds in starting. This should not be more than 10"
                      , running_element->getDescription().c_str()
                      , excesive_time
                      ));
            }

            {
                // Run the item controlling excesive time
                au::ExecesiveTimeAlarm alarm( au::str("ProcessItem run '%s'",running_element->getDescription().c_str() ));
                running_element->run();
            }

            LM_T( LmtEngine, ("[DONE] Engine executing %s" , running_element->getDescription().c_str()));

            EngineElement * _running_element = running_element;
            running_element = NULL; // Put running element to NULL

            if( _running_element->isRepeated() )
            {
                // Insert again
                _running_element->Reschedule();
                add( _running_element );
            }
            else
                delete _running_element;

        }
    }
}

std::list<EngineElement*>::iterator Engine::_find_pos( EngineElement *e)
{
    for (std::list<EngineElement*>::iterator i = elements.begin() ; i != elements.end() ; i++)
    {
        if ( (*i)->getTimeToTrigger() > e->getTimeToTrigger() )
            return i;
    }

    return elements.end();
}

#pragma mark ----

// get xml information
void Engine::getInfo( std::ostringstream& output)
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::str");

    au::xml_open(output, "engine");

    au::xml_simple(output , "loops" , counter );

    if( running_element )
        au::xml_simple( output , "running_element" , running_element->getDescription() );
    else
        au::xml_simple( output , "running_element" , "No running element" );

    au::xml_iterate_list( output , "elements" , elements );

    au::xml_simple( output , "uptime" , uptime.diffTimeInSeconds() );

    au::xml_close(output , "engine");

}

// Functions to register objects ( general and for a particular notification )
void Engine::register_object( Object* object )
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::register_object" );

    objectsManager.add( object );
}

void Engine::register_object_for_channel( Object* object, const char* channel )
{
    // Mutex protection
    au::TokenTaker tt(&token,"Engine::register_object_for_channel");

    objectsManager.add( object , channel );
}

// Generic method to unregister an object
void Engine::unregister_object( Object* object )
{
    // Mutex protection
    au::TokenTaker tt(&token , "Engine::unregister_object");

    objectsManager.remove( object );
}

// Run a particular notification
// Only executed from friend class "NotificationElement"
void Engine::send( Notification * notification )
{
    objectsManager.send( notification );
}

// Add a notification
void Engine::notify( Notification*  notification )
{
    // Push a notification element with the notification
    add( new NotificationElement( notification ) );
}

void Engine::notify( Notification*  notification , int seconds )
{
    // Push a notification element with the notification ( in this case with periodic time )
    add( new NotificationElement( notification , seconds ) );
}

// Function to add a simple foreground tasks
void Engine::add( EngineElement *element )
{
    // Mutex protection
    au::TokenTaker tt(&token);

    // Insert an element in the engine
    elements.insert( _find_pos( element ) ,  element );

    // Wake up main thread if sleeping
    tt.wakeUp();
}

// Get an object by its registry names
Object* Engine::getObjectByName( const char *name )
{
    // Mutex protection
    au::TokenTaker tt(&token);

    return objectsManager.getObjectByName(name);

}

NAMESPACE_END<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ChartController_Position.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:32:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "ChartController.hxx"

#include "dlg_RotateDiagram.hxx"
#include "macros.hxx"
#include "ChartWindow.hxx"
#include "Rotation.hxx"
#include "ChartModelHelper.hxx"
#include "DrawViewWrapper.hxx"
#include "PositionAndSizeHelper.hxx"

#ifndef _COM_SUN_STAR_CHART2_SCENEDESCRIPTOR_HPP_
#include <com/sun/star/chart2/SceneDescriptor.hpp>
#endif

// header for define RET_OK
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif

#ifndef _SVX_DIALOG_HXX
#include <svx/svxdlg.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void lcl_getPositionAndSizeFromItemSet( const SfxItemSet& rItemSet, Rectangle& rPosAndSize )
{
    long nPosX(0);
    long nPosY(0);
    long nSizX(0);
    long nSizY(0);

    const SfxPoolItem* pPoolItem=NULL;
    //read position
    if (SFX_ITEM_SET==rItemSet.GetItemState(SID_ATTR_TRANSFORM_POS_X,TRUE,&pPoolItem))
        nPosX=((const SfxInt32Item*)pPoolItem)->GetValue();
    if (SFX_ITEM_SET==rItemSet.GetItemState(SID_ATTR_TRANSFORM_POS_Y,TRUE,&pPoolItem))
        nPosY=((const SfxInt32Item*)pPoolItem)->GetValue();
    //read size
    if (SFX_ITEM_SET==rItemSet.GetItemState(SID_ATTR_TRANSFORM_WIDTH,TRUE,&pPoolItem))
        nSizX=((const SfxUInt32Item*)pPoolItem)->GetValue();
    if (SFX_ITEM_SET==rItemSet.GetItemState(SID_ATTR_TRANSFORM_HEIGHT,TRUE,&pPoolItem))
        nSizY=((const SfxUInt32Item*)pPoolItem)->GetValue();

    rPosAndSize = Rectangle(Point(nPosX,nPosY),Size(nSizX,nSizY));
}

void SAL_CALL ChartController::executeDispatch_PositionAndSize( const ::rtl::OUString& rObjectCID )
{
    if( !rObjectCID.getLength() )
        return;

    bool bChanged = false;
    SfxAbstractTabDialog * pDlg = NULL;
    try
    {
        SfxItemSet aItemSet = m_pDrawViewWrapper->getPositionAndSizeItemSetFromMarkedObject();

        //prepare and open dialog
        Window* pParent( NULL );
        SdrView* pSdrView = m_pDrawViewWrapper;
        bool bResizePossible=true;

        SvxAbstractDialogFactory * pFact = SvxAbstractDialogFactory::Create();
        DBG_ASSERT( pFact, "No dialog factory" );
        pDlg = pFact->CreateSchTransformTabDialog(
            NULL, &aItemSet, pSdrView, ResId( RID_SCH_TransformTabDLG_SVXPAGE_ANGLE ), bResizePossible );
        DBG_ASSERT( pDlg, "Couldn't create SchTransformTabDialog" );

        if( pDlg->Execute() == RET_OK )
        {
            const SfxItemSet* pOutItemSet = pDlg->GetOutputItemSet();
            if(pOutItemSet)
            {
                Rectangle aObjectRect;
                aItemSet.Put(*pOutItemSet);//overwrite old values with new values (-> all items are set)
                lcl_getPositionAndSizeFromItemSet( aItemSet, aObjectRect );
                Rectangle aPageRect( Point(0,0),m_pChartWindow->GetOutputSize() );

                bChanged = PositionAndSizeHelper::moveObject( m_aSelectedObjectCID
                            , m_aModel->getModel()
                            , awt::Rectangle(aObjectRect.getX(),aObjectRect.getY(),aObjectRect.getWidth(),aObjectRect.getHeight())
                            , awt::Rectangle(aPageRect.getX(),aPageRect.getY(),aPageRect.getWidth(),aPageRect.getHeight())
                            );
            }
        }
        delete pDlg;
    }
    catch( uno::Exception& e)
    {
        delete pDlg;
        ASSERT_EXCEPTION( e );
    }
    //make sure that all objects using  m_pChartView are already deleted
    if(bChanged)
    {
        m_bViewDirty = true;
        m_pChartWindow->Invalidate();
    }
}

void SAL_CALL ChartController::executeDispatch_RotateDiagram()
{
    bool bChanged = false;
    try
    {
        Window* pParent( NULL );
        double fXAngle, fYAngle, fZAngle;
        fXAngle=fYAngle=fZAngle=0.0;

        //get angle from model
        SceneDescriptor aSceneDescriptor;
        uno::Reference< beans::XPropertySet > xProp( ChartModelHelper::findDiagram( m_aModel->getModel() ), uno::UNO_QUERY );
        if( xProp.is() && (xProp->getPropertyValue( C2U( "SceneProperties" ) )>>=aSceneDescriptor) )
        {
            Rotation::getEulerFromAxisAngleRepresentation( aSceneDescriptor.aDirection, aSceneDescriptor.fRotationAngle
                , fXAngle, fYAngle, fZAngle );
        }

        //open dialog
        RotateDiagramDialog aDlg( pParent, fXAngle, fYAngle, fZAngle );
        if( aDlg.Execute() == RET_OK )
        {
            aDlg.getAngle( fXAngle, fYAngle, fZAngle );
            Rotation::getAxisAngleFromEulerRepresentation( aSceneDescriptor.aDirection, aSceneDescriptor.fRotationAngle
                , fXAngle, fYAngle, fZAngle );
            xProp->setPropertyValue( C2U( "SceneProperties" ), uno::makeAny(aSceneDescriptor) );
            bChanged = true;
        }
    }
    catch( uno::RuntimeException& e)
    {
        ASSERT_EXCEPTION( e );
    }
    //make sure that all objects using  m_pChartView are already deleted
    if(bChanged)
    {
        m_bViewDirty = true;
        m_pChartWindow->Invalidate();
    }
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.80); FILE MERGED 2006/09/01 17:18:39 kaib 1.5.80.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ChartController_Position.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:04:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ChartController.hxx"

#include "dlg_RotateDiagram.hxx"
#include "macros.hxx"
#include "ChartWindow.hxx"
#include "Rotation.hxx"
#include "ChartModelHelper.hxx"
#include "DrawViewWrapper.hxx"
#include "PositionAndSizeHelper.hxx"

#ifndef _COM_SUN_STAR_CHART2_SCENEDESCRIPTOR_HPP_
#include <com/sun/star/chart2/SceneDescriptor.hpp>
#endif

// header for define RET_OK
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif

#ifndef _SVX_DIALOG_HXX
#include <svx/svxdlg.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void lcl_getPositionAndSizeFromItemSet( const SfxItemSet& rItemSet, Rectangle& rPosAndSize )
{
    long nPosX(0);
    long nPosY(0);
    long nSizX(0);
    long nSizY(0);

    const SfxPoolItem* pPoolItem=NULL;
    //read position
    if (SFX_ITEM_SET==rItemSet.GetItemState(SID_ATTR_TRANSFORM_POS_X,TRUE,&pPoolItem))
        nPosX=((const SfxInt32Item*)pPoolItem)->GetValue();
    if (SFX_ITEM_SET==rItemSet.GetItemState(SID_ATTR_TRANSFORM_POS_Y,TRUE,&pPoolItem))
        nPosY=((const SfxInt32Item*)pPoolItem)->GetValue();
    //read size
    if (SFX_ITEM_SET==rItemSet.GetItemState(SID_ATTR_TRANSFORM_WIDTH,TRUE,&pPoolItem))
        nSizX=((const SfxUInt32Item*)pPoolItem)->GetValue();
    if (SFX_ITEM_SET==rItemSet.GetItemState(SID_ATTR_TRANSFORM_HEIGHT,TRUE,&pPoolItem))
        nSizY=((const SfxUInt32Item*)pPoolItem)->GetValue();

    rPosAndSize = Rectangle(Point(nPosX,nPosY),Size(nSizX,nSizY));
}

void SAL_CALL ChartController::executeDispatch_PositionAndSize( const ::rtl::OUString& rObjectCID )
{
    if( !rObjectCID.getLength() )
        return;

    bool bChanged = false;
    SfxAbstractTabDialog * pDlg = NULL;
    try
    {
        SfxItemSet aItemSet = m_pDrawViewWrapper->getPositionAndSizeItemSetFromMarkedObject();

        //prepare and open dialog
        Window* pParent( NULL );
        SdrView* pSdrView = m_pDrawViewWrapper;
        bool bResizePossible=true;

        SvxAbstractDialogFactory * pFact = SvxAbstractDialogFactory::Create();
        DBG_ASSERT( pFact, "No dialog factory" );
        pDlg = pFact->CreateSchTransformTabDialog(
            NULL, &aItemSet, pSdrView, ResId( RID_SCH_TransformTabDLG_SVXPAGE_ANGLE ), bResizePossible );
        DBG_ASSERT( pDlg, "Couldn't create SchTransformTabDialog" );

        if( pDlg->Execute() == RET_OK )
        {
            const SfxItemSet* pOutItemSet = pDlg->GetOutputItemSet();
            if(pOutItemSet)
            {
                Rectangle aObjectRect;
                aItemSet.Put(*pOutItemSet);//overwrite old values with new values (-> all items are set)
                lcl_getPositionAndSizeFromItemSet( aItemSet, aObjectRect );
                Rectangle aPageRect( Point(0,0),m_pChartWindow->GetOutputSize() );

                bChanged = PositionAndSizeHelper::moveObject( m_aSelectedObjectCID
                            , m_aModel->getModel()
                            , awt::Rectangle(aObjectRect.getX(),aObjectRect.getY(),aObjectRect.getWidth(),aObjectRect.getHeight())
                            , awt::Rectangle(aPageRect.getX(),aPageRect.getY(),aPageRect.getWidth(),aPageRect.getHeight())
                            );
            }
        }
        delete pDlg;
    }
    catch( uno::Exception& e)
    {
        delete pDlg;
        ASSERT_EXCEPTION( e );
    }
    //make sure that all objects using  m_pChartView are already deleted
    if(bChanged)
    {
        m_bViewDirty = true;
        m_pChartWindow->Invalidate();
    }
}

void SAL_CALL ChartController::executeDispatch_RotateDiagram()
{
    bool bChanged = false;
    try
    {
        Window* pParent( NULL );
        double fXAngle, fYAngle, fZAngle;
        fXAngle=fYAngle=fZAngle=0.0;

        //get angle from model
        SceneDescriptor aSceneDescriptor;
        uno::Reference< beans::XPropertySet > xProp( ChartModelHelper::findDiagram( m_aModel->getModel() ), uno::UNO_QUERY );
        if( xProp.is() && (xProp->getPropertyValue( C2U( "SceneProperties" ) )>>=aSceneDescriptor) )
        {
            Rotation::getEulerFromAxisAngleRepresentation( aSceneDescriptor.aDirection, aSceneDescriptor.fRotationAngle
                , fXAngle, fYAngle, fZAngle );
        }

        //open dialog
        RotateDiagramDialog aDlg( pParent, fXAngle, fYAngle, fZAngle );
        if( aDlg.Execute() == RET_OK )
        {
            aDlg.getAngle( fXAngle, fYAngle, fZAngle );
            Rotation::getAxisAngleFromEulerRepresentation( aSceneDescriptor.aDirection, aSceneDescriptor.fRotationAngle
                , fXAngle, fYAngle, fZAngle );
            xProp->setPropertyValue( C2U( "SceneProperties" ), uno::makeAny(aSceneDescriptor) );
            bChanged = true;
        }
    }
    catch( uno::RuntimeException& e)
    {
        ASSERT_EXCEPTION( e );
    }
    //make sure that all objects using  m_pChartView are already deleted
    if(bChanged)
    {
        m_bViewDirty = true;
        m_pChartWindow->Invalidate();
    }
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "chrome/browser/chromeos/drive/resource_entry_conversion.h"

#include <algorithm>
#include <string>

#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/drive/drive_api_util.h"
#include "chrome/browser/google_apis/gdata_wapi_parser.h"
#include "net/base/escape.h"
#include "url/gurl.h"

namespace drive {

namespace {

const char kSharedWithMeLabel[] = "shared-with-me";

// Checks if |entry| has a label "shared-with-me", which is added to entries
// shared with the user.
bool HasSharedWithMeLabel(const google_apis::ResourceEntry& entry) {
  std::vector<std::string>::const_iterator it =
      std::find(entry.labels().begin(), entry.labels().end(),
                kSharedWithMeLabel);
  return it != entry.labels().end();
}

}  // namespace

bool ConvertToResourceEntry(const google_apis::ResourceEntry& input,
                            ResourceEntry* output) {
  DCHECK(output);

  // For regular files, the 'filename' and 'title' attribute in the metadata
  // may be different (e.g. due to rename). To be consistent with the web
  // interface and other client to use the 'title' attribute, instead of
  // 'filename', as the file name in the local snapshot.
  output->set_title(input.title());
  output->set_base_name(util::NormalizeFileName(output->title()));
  output->set_resource_id(input.resource_id());

  // Sets parent Resource ID. On drive.google.com, a file can have multiple
  // parents or no parent, but we are forcing a tree-shaped structure (i.e. no
  // multi-parent or zero-parent entries). Therefore the first found "parent" is
  // used for the entry and if the entry has no parent, we assign a special ID
  // which represents no-parent entries. Tracked in http://crbug.com/158904.
  const google_apis::Link* parent_link =
      input.GetLinkByType(google_apis::Link::LINK_PARENT);
  if (parent_link) {
    output->set_parent_resource_id(util::ExtractResourceIdFromUrl(
        parent_link->href()));
  }
  // Apply mapping from an empty parent to the special dummy directory.
  if (output->parent_resource_id().empty())
    output->set_parent_resource_id(util::kDriveOtherDirSpecialResourceId);

  output->set_deleted(input.deleted());
  output->set_shared_with_me(HasSharedWithMeLabel(input));

  PlatformFileInfoProto* file_info = output->mutable_file_info();

  file_info->set_last_modified(input.updated_time().ToInternalValue());
  // If the file has never been viewed (last_viewed_time().is_null() == true),
  // then we will set the last_accessed field in the protocol buffer to 0.
  file_info->set_last_accessed(input.last_viewed_time().ToInternalValue());
  file_info->set_creation_time(input.published_time().ToInternalValue());

  if (input.is_file() || input.is_hosted_document()) {
    FileSpecificInfo* file_specific_info = output->mutable_file_specific_info();
    if (input.is_file()) {
      file_info->set_size(input.file_size());
      file_specific_info->set_md5(input.file_md5());

      // The resumable-edit-media link should only be present for regular
      // files as hosted documents are not uploadable.
    } else if (input.is_hosted_document()) {
      // Attach .g<something> extension to hosted documents so we can special
      // case their handling in UI.
      // TODO(satorux): Figure out better way how to pass input info like kind
      // to UI through the File API stack.
      const std::string document_extension = input.GetHostedDocumentExtension();
      file_specific_info->set_document_extension(document_extension);
      output->set_base_name(
          util::NormalizeFileName(output->title() + document_extension));

      // We don't know the size of hosted docs and it does not matter since
      // is has no effect on the quota.
      file_info->set_size(0);
    }
    file_info->set_is_directory(false);
    file_specific_info->set_content_mime_type(input.content_mime_type());
    file_specific_info->set_is_hosted_document(input.is_hosted_document());

    const google_apis::Link* thumbnail_link =
        input.GetLinkByType(google_apis::Link::LINK_THUMBNAIL);
    if (thumbnail_link)
      file_specific_info->set_thumbnail_url(thumbnail_link->href().spec());

    const google_apis::Link* alternate_link =
        input.GetLinkByType(google_apis::Link::LINK_ALTERNATE);
    if (alternate_link)
      file_specific_info->set_alternate_url(alternate_link->href().spec());
  } else if (input.is_folder()) {
    file_info->set_is_directory(true);
  } else {
    // Some resource entries don't map into files (i.e. sites).
    return false;
  }

  return true;
}

}  // namespace drive
<commit_msg>Drive: Do not treat type-unknown deleted entries as an error.<commit_after>// Copyright (c) 2012 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 "chrome/browser/chromeos/drive/resource_entry_conversion.h"

#include <algorithm>
#include <string>

#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/drive/drive_api_util.h"
#include "chrome/browser/google_apis/gdata_wapi_parser.h"
#include "net/base/escape.h"
#include "url/gurl.h"

namespace drive {

namespace {

const char kSharedWithMeLabel[] = "shared-with-me";

// Checks if |entry| has a label "shared-with-me", which is added to entries
// shared with the user.
bool HasSharedWithMeLabel(const google_apis::ResourceEntry& entry) {
  std::vector<std::string>::const_iterator it =
      std::find(entry.labels().begin(), entry.labels().end(),
                kSharedWithMeLabel);
  return it != entry.labels().end();
}

}  // namespace

bool ConvertToResourceEntry(const google_apis::ResourceEntry& input,
                            ResourceEntry* output) {
  DCHECK(output);

  // For regular files, the 'filename' and 'title' attribute in the metadata
  // may be different (e.g. due to rename). To be consistent with the web
  // interface and other client to use the 'title' attribute, instead of
  // 'filename', as the file name in the local snapshot.
  output->set_title(input.title());
  output->set_base_name(util::NormalizeFileName(output->title()));
  output->set_resource_id(input.resource_id());

  // Sets parent Resource ID. On drive.google.com, a file can have multiple
  // parents or no parent, but we are forcing a tree-shaped structure (i.e. no
  // multi-parent or zero-parent entries). Therefore the first found "parent" is
  // used for the entry and if the entry has no parent, we assign a special ID
  // which represents no-parent entries. Tracked in http://crbug.com/158904.
  const google_apis::Link* parent_link =
      input.GetLinkByType(google_apis::Link::LINK_PARENT);
  if (parent_link) {
    output->set_parent_resource_id(util::ExtractResourceIdFromUrl(
        parent_link->href()));
  }
  // Apply mapping from an empty parent to the special dummy directory.
  if (output->parent_resource_id().empty())
    output->set_parent_resource_id(util::kDriveOtherDirSpecialResourceId);

  output->set_deleted(input.deleted());
  output->set_shared_with_me(HasSharedWithMeLabel(input));

  PlatformFileInfoProto* file_info = output->mutable_file_info();

  file_info->set_last_modified(input.updated_time().ToInternalValue());
  // If the file has never been viewed (last_viewed_time().is_null() == true),
  // then we will set the last_accessed field in the protocol buffer to 0.
  file_info->set_last_accessed(input.last_viewed_time().ToInternalValue());
  file_info->set_creation_time(input.published_time().ToInternalValue());

  if (input.is_file() || input.is_hosted_document()) {
    FileSpecificInfo* file_specific_info = output->mutable_file_specific_info();
    if (input.is_file()) {
      file_info->set_size(input.file_size());
      file_specific_info->set_md5(input.file_md5());

      // The resumable-edit-media link should only be present for regular
      // files as hosted documents are not uploadable.
    } else if (input.is_hosted_document()) {
      // Attach .g<something> extension to hosted documents so we can special
      // case their handling in UI.
      // TODO(satorux): Figure out better way how to pass input info like kind
      // to UI through the File API stack.
      const std::string document_extension = input.GetHostedDocumentExtension();
      file_specific_info->set_document_extension(document_extension);
      output->set_base_name(
          util::NormalizeFileName(output->title() + document_extension));

      // We don't know the size of hosted docs and it does not matter since
      // is has no effect on the quota.
      file_info->set_size(0);
    }
    file_info->set_is_directory(false);
    file_specific_info->set_content_mime_type(input.content_mime_type());
    file_specific_info->set_is_hosted_document(input.is_hosted_document());

    const google_apis::Link* thumbnail_link =
        input.GetLinkByType(google_apis::Link::LINK_THUMBNAIL);
    if (thumbnail_link)
      file_specific_info->set_thumbnail_url(thumbnail_link->href().spec());

    const google_apis::Link* alternate_link =
        input.GetLinkByType(google_apis::Link::LINK_ALTERNATE);
    if (alternate_link)
      file_specific_info->set_alternate_url(alternate_link->href().spec());
  } else if (input.is_folder()) {
    file_info->set_is_directory(true);
  } else {
    // There are two cases to reach here.
    // * The entry is something that doesn't map into files (i.e. sites).
    //   We don't handle these kind of entries hence return false.
    // * The entry is un-shared to you by other owner. In that case, we
    //   get an entry with only deleted() and resource_id() fields are
    //   filled. Since we want to delete such entries locally as well,
    //   in that case we need to return true to proceed.
    return input.deleted();
  }

  return true;
}

}  // namespace drive
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "base/command_line.h"
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_input_method_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_locker_tester.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/views/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/textfield/textfield.h"
#include "views/window/window_gtk.h"

namespace {

// An object that wait for lock state and fullscreen state.
class Waiter : public NotificationObserver {
 public:
  explicit Waiter(Browser* browser)
      : browser_(browser) {
    registrar_.Add(this,
                   NotificationType::SCREEN_LOCK_STATE_CHANGED,
                   NotificationService::AllSources());
    handler_id_ = g_signal_connect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        "window-state-event",
        G_CALLBACK(OnWindowStateEventThunk),
        this);
  }

  ~Waiter() {
    g_signal_handler_disconnect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        handler_id_);
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);
    MessageLoop::current()->Quit();
  }

  // Wait until the two conditions are met.
  void Wait(bool locker_state, bool fullscreen) {
    scoped_ptr<chromeos::test::ScreenLockerTester>
        tester(chromeos::ScreenLocker::GetTester());
    while (tester->IsLocked() != locker_state ||
           browser_->window()->IsFullscreen() != fullscreen) {
      ui_test_utils::RunMessageLoop();
    }
    // Make sure all pending tasks are executed.
    ui_test_utils::RunAllPendingInMessageLoop();
  }

  CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,
                       GdkEventWindowState*);

 private:
  Browser* browser_;
  gulong handler_id_;
  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(Waiter);
};

gboolean Waiter::OnWindowStateEvent(GtkWidget* widget,
                                    GdkEventWindowState* event) {
  MessageLoop::current()->Quit();
  return false;
}

}  // namespace

namespace chromeos {

class ScreenLockerTest : public CrosInProcessBrowserTest {
 public:
  ScreenLockerTest() : mock_screen_lock_library_(NULL),
                       mock_input_method_library_(NULL) {
  }

 protected:
  MockScreenLockLibrary *mock_screen_lock_library_;
  MockInputMethodLibrary *mock_input_method_library_;

  // Test the no password mode with different unlock scheme given by
  // |unlock| function.
  void TestNoPassword(void (unlock)(views::Widget*)) {
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    UserManager::Get()->OffTheRecordUserLoggedIn();
    ScreenLocker::Show();
    scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
    tester->EmulateWindowManagerReady();
    ui_test_utils::WaitForNotification(
        NotificationType::SCREEN_LOCK_STATE_CHANGED);
    EXPECT_TRUE(tester->IsLocked());
    tester->InjectMockAuthenticator("", "");

    unlock(tester->GetWidget());

    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_TRUE(tester->IsLocked());

    // Emulate LockScreen request from PowerManager (via SessionManager).
    ScreenLocker::Hide();
    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_FALSE(tester->IsLocked());
  }

 private:
  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    cros_mock_->InitMockScreenLockLibrary();
    mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
    mock_input_method_library_ = cros_mock_->mock_input_method_library();
    EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    // Expectations for the status are on the screen lock window.
    cros_mock_->SetStatusAreaMocksExpectations();
    // Expectations for the status area on the browser window.
    cros_mock_->SetStatusAreaMocksExpectations();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
    command_line->AppendSwitch(switches::kNoFirstRun);
  }

  DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);
};

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {
  EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())
      .Times(1)
      .WillRepeatedly((testing::Return(0)))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  UserManager::Get()->UserLoggedIn("user");
  ScreenLocker::Show();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  tester->EmulateWindowManagerReady();
  ui_test_utils::WaitForNotification(
      NotificationType::SCREEN_LOCK_STATE_CHANGED);

  // Test to make sure that the widget is actually appearing and is of
  // reasonable size, preventing a regression of
  // http://code.google.com/p/chromium-os/issues/detail?id=5987
  gfx::Rect lock_bounds;
  tester->GetChildWidget()->GetBounds(&lock_bounds, true);
  EXPECT_GT(lock_bounds.width(), 10);
  EXPECT_GT(lock_bounds.height(), 10);

  tester->InjectMockAuthenticator("user", "pass");
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("fail");
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  // Successful authentication simply send a unlock request to PowerManager.
  EXPECT_TRUE(tester->IsLocked());

  // Emulate LockScreen request from PowerManager (via SessionManager).
  // TODO(oshima): Find out better way to handle this in mock.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  {
    Waiter waiter(browser());
    browser()->ToggleFullscreenMode();
    waiter.Wait(false /* not locked */, true /* full screen */);
    EXPECT_TRUE(browser()->window()->IsFullscreen());
    EXPECT_FALSE(tester->IsLocked());
  }
  {
    Waiter waiter(browser());
    UserManager::Get()->UserLoggedIn("user");
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    waiter.Wait(true /* locked */, false /* full screen */);
    EXPECT_FALSE(browser()->window()->IsFullscreen());
    EXPECT_TRUE(tester->IsLocked());
  }
  tester->InjectMockAuthenticator("user", "pass");
  tester->EnterPassword("pass");
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

void MouseMove(views::Widget* widget) {
  ui_controls::SendMouseMove(10, 10);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseMove) {
  TestNoPassword(MouseMove);
}

void MouseClick(views::Widget* widget) {
  ui_controls::SendMouseClick(ui_controls::RIGHT);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseClick) {
  TestNoPassword(MouseClick);
}

void KeyPress(views::Widget* widget) {
  ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),
                            app::VKEY_SPACE, false, false, false, false);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithKeyPress) {
  TestNoPassword(KeyPress);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestShowTwice) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(2)
      .RetiresOnSaturation();

  UserManager::Get()->UserLoggedIn("user");
  ScreenLocker::Show();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  tester->EmulateWindowManagerReady();
  ui_test_utils::WaitForNotification(
      NotificationType::SCREEN_LOCK_STATE_CHANGED);
  EXPECT_TRUE(tester->IsLocked());

  // Calling Show again simply send LockCompleted signal.
  ScreenLocker::Show();
  EXPECT_TRUE(tester->IsLocked());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

}  // namespace chromeos
<commit_msg>Wait for all tasks to finish before exitting the test.<commit_after>// Copyright (c) 2010 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 "base/command_line.h"
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_input_method_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_locker_tester.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/views/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/textfield/textfield.h"
#include "views/window/window_gtk.h"

namespace {

// An object that wait for lock state and fullscreen state.
class Waiter : public NotificationObserver {
 public:
  explicit Waiter(Browser* browser)
      : browser_(browser) {
    registrar_.Add(this,
                   NotificationType::SCREEN_LOCK_STATE_CHANGED,
                   NotificationService::AllSources());
    handler_id_ = g_signal_connect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        "window-state-event",
        G_CALLBACK(OnWindowStateEventThunk),
        this);
  }

  ~Waiter() {
    g_signal_handler_disconnect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        handler_id_);
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);
    MessageLoop::current()->Quit();
  }

  // Wait until the two conditions are met.
  void Wait(bool locker_state, bool fullscreen) {
    scoped_ptr<chromeos::test::ScreenLockerTester>
        tester(chromeos::ScreenLocker::GetTester());
    while (tester->IsLocked() != locker_state ||
           browser_->window()->IsFullscreen() != fullscreen) {
      ui_test_utils::RunMessageLoop();
    }
    // Make sure all pending tasks are executed.
    ui_test_utils::RunAllPendingInMessageLoop();
  }

  CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,
                       GdkEventWindowState*);

 private:
  Browser* browser_;
  gulong handler_id_;
  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(Waiter);
};

gboolean Waiter::OnWindowStateEvent(GtkWidget* widget,
                                    GdkEventWindowState* event) {
  MessageLoop::current()->Quit();
  return false;
}

}  // namespace

namespace chromeos {

class ScreenLockerTest : public CrosInProcessBrowserTest {
 public:
  ScreenLockerTest() : mock_screen_lock_library_(NULL),
                       mock_input_method_library_(NULL) {
  }

 protected:
  MockScreenLockLibrary *mock_screen_lock_library_;
  MockInputMethodLibrary *mock_input_method_library_;

  // Test the no password mode with different unlock scheme given by
  // |unlock| function.
  void TestNoPassword(void (unlock)(views::Widget*)) {
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    UserManager::Get()->OffTheRecordUserLoggedIn();
    ScreenLocker::Show();
    scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
    tester->EmulateWindowManagerReady();
    ui_test_utils::WaitForNotification(
        NotificationType::SCREEN_LOCK_STATE_CHANGED);
    EXPECT_TRUE(tester->IsLocked());
    tester->InjectMockAuthenticator("", "");

    unlock(tester->GetWidget());

    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_TRUE(tester->IsLocked());

    // Emulate LockScreen request from PowerManager (via SessionManager).
    ScreenLocker::Hide();
    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_FALSE(tester->IsLocked());
  }

 private:
  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    cros_mock_->InitMockScreenLockLibrary();
    mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
    mock_input_method_library_ = cros_mock_->mock_input_method_library();
    EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    // Expectations for the status are on the screen lock window.
    cros_mock_->SetStatusAreaMocksExpectations();
    // Expectations for the status area on the browser window.
    cros_mock_->SetStatusAreaMocksExpectations();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
    command_line->AppendSwitch(switches::kNoFirstRun);
  }

  DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);
};

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {
  EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())
      .Times(1)
      .WillRepeatedly((testing::Return(0)))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  UserManager::Get()->UserLoggedIn("user");
  ScreenLocker::Show();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  tester->EmulateWindowManagerReady();
  ui_test_utils::WaitForNotification(
      NotificationType::SCREEN_LOCK_STATE_CHANGED);

  // Test to make sure that the widget is actually appearing and is of
  // reasonable size, preventing a regression of
  // http://code.google.com/p/chromium-os/issues/detail?id=5987
  gfx::Rect lock_bounds;
  tester->GetChildWidget()->GetBounds(&lock_bounds, true);
  EXPECT_GT(lock_bounds.width(), 10);
  EXPECT_GT(lock_bounds.height(), 10);

  tester->InjectMockAuthenticator("user", "pass");
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("fail");
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  // Successful authentication simply send a unlock request to PowerManager.
  EXPECT_TRUE(tester->IsLocked());

  // Emulate LockScreen request from PowerManager (via SessionManager).
  // TODO(oshima): Find out better way to handle this in mock.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  {
    Waiter waiter(browser());
    browser()->ToggleFullscreenMode();
    waiter.Wait(false /* not locked */, true /* full screen */);
    EXPECT_TRUE(browser()->window()->IsFullscreen());
    EXPECT_FALSE(tester->IsLocked());
  }
  {
    Waiter waiter(browser());
    UserManager::Get()->UserLoggedIn("user");
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    waiter.Wait(true /* locked */, false /* full screen */);
    EXPECT_FALSE(browser()->window()->IsFullscreen());
    EXPECT_TRUE(tester->IsLocked());
  }
  tester->InjectMockAuthenticator("user", "pass");
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

void MouseMove(views::Widget* widget) {
  ui_controls::SendMouseMove(10, 10);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseMove) {
  TestNoPassword(MouseMove);
}

void MouseClick(views::Widget* widget) {
  ui_controls::SendMouseClick(ui_controls::RIGHT);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseClick) {
  TestNoPassword(MouseClick);
}

void KeyPress(views::Widget* widget) {
  ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),
                            app::VKEY_SPACE, false, false, false, false);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithKeyPress) {
  TestNoPassword(KeyPress);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestShowTwice) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(2)
      .RetiresOnSaturation();

  UserManager::Get()->UserLoggedIn("user");
  ScreenLocker::Show();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  tester->EmulateWindowManagerReady();
  ui_test_utils::WaitForNotification(
      NotificationType::SCREEN_LOCK_STATE_CHANGED);
  EXPECT_TRUE(tester->IsLocked());

  // Calling Show again simply send LockCompleted signal.
  ScreenLocker::Show();
  EXPECT_TRUE(tester->IsLocked());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

}  // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Debugger) {
  ASSERT_TRUE(RunExtensionTest("debugger")) << message_;
}
<commit_msg>[Sheriff] Disabling ExtensionApiTest.Debugger which flaky in browser tests on Windows.<commit_after>// Copyright (c) 2012 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Debugger is flaky on browser_tests on Windows: crbug.com/234166.
#if defined(OS_WIN)
#define MAYBE(x) DISABLED_##x
#else
#define MAYBE(x) x
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE(Debugger)) {
  ASSERT_TRUE(RunExtensionTest("debugger")) << message_;
}
<|endoftext|>


<commit_before>#include <czmq++/czmq.hpp>

#include <thread>

void client_task(const std::string& server_public_text)
{
    //  Load our persistent certificate from disk
    czmqpp::certificate client_cert =
        czmqpp::load_cert("client_cert.txt");
    assert(client_cert.self());

    //  Create client socket and configure it to use full encryption
    czmqpp::context ctx;
    assert(ctx.self());
    czmqpp::socket client(ctx, ZMQ_PULL);
    assert(client.self());
    client_cert.apply(client);
    client.set_curve_serverkey(server_public_text);
    int rc = client.connect("tcp://127.0.0.1:9000");
    assert(rc == 0);

    //  Wait for our message, that signals the test was successful
    czmqpp::message msg;
    msg.receive(client);
    assert(msg.parts().size() == 1);
    assert((msg.parts()[0] == czmqpp::data_chunk{{0xde, 0xad, 0xbe, 0xef}}));
    puts("Ironhouse test OK");
}

void server_task(czmqpp::certificate server_cert)
{
    czmqpp::context ctx;
    assert(ctx.self());

    //  Start the authenticator and tell it do authenticate clients
    //  via the certificates stored in the .curve directory.
    czmqpp::authenticator auth(ctx);
    auth.set_verbose(true);
    auth.allow("127.0.0.1");
    auth.configure_curve("*", ".curve");

    czmqpp::socket server(ctx, ZMQ_PUSH);
    assert(server.self());
    server_cert.apply(server);
    server.set_curve_server(1);
    int rc = server.bind("tcp://*:9000");
    assert(rc != -1);

    //  Send our test message, just once
    czmqpp::message msg;
    msg.append(czmqpp::data_chunk{{0xde, 0xad, 0xbe, 0xef}});
    msg.send(server);

    zclock_sleep(200);
}

int main()
{
    //  Create the certificate store directory and client certs
    czmqpp::certificate client_cert = czmqpp::new_cert();
    int rc = zsys_dir_create(".curve");
    assert(rc == 0);
    client_cert.set_meta("name", "Client test certificate");
    client_cert.save_public(".curve/testcert.pub");
    rc = client_cert.save("client_cert.txt");
    assert(rc == 0);

    //  Create the server certificate
    czmqpp::certificate server_cert(czmqpp::new_cert());

    //  Now start the two detached threads; each of these has their
    //  own ZeroMQ context.
    std::string server_public_text = server_cert.public_text();
    std::thread server_thread(server_task, std::move(server_cert));
    std::thread client_thread(client_task, server_public_text);

    client_thread.join();
    server_thread.join();
    return 0;
}

<commit_msg>cleanup example header.<commit_after>#include <thread>
#include <czmq++/czmq.hpp>

void client_task(const std::string& server_public_text)
{
    //  Load our persistent certificate from disk
    czmqpp::certificate client_cert =
        czmqpp::load_cert("client_cert.txt");
    assert(client_cert.self());

    //  Create client socket and configure it to use full encryption
    czmqpp::context ctx;
    assert(ctx.self());
    czmqpp::socket client(ctx, ZMQ_PULL);
    assert(client.self());
    client_cert.apply(client);
    client.set_curve_serverkey(server_public_text);
    int rc = client.connect("tcp://127.0.0.1:9000");
    assert(rc == 0);

    //  Wait for our message, that signals the test was successful
    czmqpp::message msg;
    msg.receive(client);
    assert(msg.parts().size() == 1);
    assert((msg.parts()[0] == czmqpp::data_chunk{{0xde, 0xad, 0xbe, 0xef}}));
    puts("Ironhouse test OK");
}

void server_task(czmqpp::certificate server_cert)
{
    czmqpp::context ctx;
    assert(ctx.self());

    //  Start the authenticator and tell it do authenticate clients
    //  via the certificates stored in the .curve directory.
    czmqpp::authenticator auth(ctx);
    auth.set_verbose(true);
    auth.allow("127.0.0.1");
    auth.configure_curve("*", ".curve");

    czmqpp::socket server(ctx, ZMQ_PUSH);
    assert(server.self());
    server_cert.apply(server);
    server.set_curve_server(1);
    int rc = server.bind("tcp://*:9000");
    assert(rc != -1);

    //  Send our test message, just once
    czmqpp::message msg;
    msg.append(czmqpp::data_chunk{{0xde, 0xad, 0xbe, 0xef}});
    msg.send(server);

    zclock_sleep(200);
}

int main()
{
    //  Create the certificate store directory and client certs
    czmqpp::certificate client_cert = czmqpp::new_cert();
    int rc = zsys_dir_create(".curve");
    assert(rc == 0);
    client_cert.set_meta("name", "Client test certificate");
    client_cert.save_public(".curve/testcert.pub");
    rc = client_cert.save("client_cert.txt");
    assert(rc == 0);

    //  Create the server certificate
    czmqpp::certificate server_cert(czmqpp::new_cert());

    //  Now start the two detached threads; each of these has their
    //  own ZeroMQ context.
    std::string server_public_text = server_cert.public_text();
    std::thread server_thread(server_task, std::move(server_cert));
    std::thread client_thread(client_task, server_public_text);

    client_thread.join();
    server_thread.join();
    return 0;
}

<|endoftext|>