<commit_before>// Copyright 2016-2017 Francesco Biscani (bluescarni@gmail.com)
//
// This file is part of the mp++ library.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <limits>
#include <mp++/detail/utils.hpp>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <typeinfo>

#include "test_utils.hpp"

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

using namespace mppp;
using namespace mppp_test;

using uint_types = std::tuple<unsigned char, unsigned short, unsigned, unsigned long, unsigned long long>;
using sint_types = std::tuple<signed char, short, int, long, long long>;

struct uint_uint_safe_cast_tester {
    template <typename T>
    struct runner {
        template <typename U, enable_if_t<(std::numeric_limits<T>::max() <= std::numeric_limits<U>::max()), int> = 0>
        void operator()(const U &) const
        {
        }
        template <typename U, enable_if_t<(std::numeric_limits<T>::max() > std::numeric_limits<U>::max()), int> = 0>
        void operator()(const U &) const
        {
            REQUIRE((std::is_same<T, decltype(safe_cast<T>(U(0)))>::value));
            REQUIRE(safe_cast<T>(U(0)) == 0u);
            REQUIRE(safe_cast<T>(U(2)) == 2u);
            REQUIRE(safe_cast<T>(std::numeric_limits<U>::max()) == std::numeric_limits<U>::max());
            REQUIRE(safe_cast<T>(U(std::numeric_limits<U>::max() - 1u)) == std::numeric_limits<U>::max() - 1u);
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(T(T(std::numeric_limits<U>::max()) + 1u)), std::overflow_error,
                [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between unsigned integral types: the input value "
                                  + std::to_string(T(std::numeric_limits<U>::max()) + 1u)
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(std::numeric_limits<T>::max()), std::overflow_error, [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between unsigned integral types: the input value "
                                  + std::to_string(std::numeric_limits<T>::max())
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
        }
    };
    template <typename T>
    void operator()(const T &) const
    {
        tuple_for_each(uint_types{}, runner<T>{});
    }
};

TEST_CASE("uint_uint_safe_cast")
{
    tuple_for_each(uint_types{}, uint_uint_safe_cast_tester{});
}

struct sint_sint_safe_cast_tester {
    template <typename T>
    struct runner {
        template <typename U,
                  enable_if_t<(std::numeric_limits<T>::max() <= std::numeric_limits<U>::max()
                               && std::numeric_limits<T>::min() >= std::numeric_limits<U>::min()),
                              int> = 0>
        void operator()(const U &) const
        {
        }
        template <typename U,
                  enable_if_t<(std::numeric_limits<T>::max() > std::numeric_limits<U>::max()
                               && std::numeric_limits<T>::min() < std::numeric_limits<U>::min()),
                              int> = 0>
        void operator()(const U &) const
        {
            REQUIRE((std::is_same<T, decltype(safe_cast<T>(U(0)))>::value));
            REQUIRE(safe_cast<T>(U(0)) == 0);
            REQUIRE(safe_cast<T>(U(2)) == 2);
            REQUIRE(safe_cast<T>(U(-2)) == -2);
            REQUIRE(safe_cast<T>(std::numeric_limits<U>::max()) == std::numeric_limits<U>::max());
            REQUIRE(safe_cast<T>(U(std::numeric_limits<U>::max() - 1)) == std::numeric_limits<U>::max() - 1);
            REQUIRE(safe_cast<T>(U(std::numeric_limits<U>::min() + 1)) == std::numeric_limits<U>::min() + 1);
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(T(T(std::numeric_limits<U>::max()) + 1)), std::overflow_error,
                [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between signed integral types: the input value "
                                  + std::to_string(T(std::numeric_limits<U>::max()) + 1)
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(T(T(std::numeric_limits<U>::min()) - 1)), std::overflow_error,
                [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between signed integral types: the input value "
                                  + std::to_string(T(std::numeric_limits<U>::min()) - 1)
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(std::numeric_limits<T>::max()), std::overflow_error, [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between signed integral types: the input value "
                                  + std::to_string(std::numeric_limits<T>::max())
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(std::numeric_limits<T>::min()), std::overflow_error, [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between signed integral types: the input value "
                                  + std::to_string(std::numeric_limits<T>::min())
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
        }
    };
    template <typename T>
    void operator()(const T &) const
    {
        tuple_for_each(sint_types{}, runner<T>{});
    }
};

TEST_CASE("sint_sint_safe_cast")
{
    tuple_for_each(sint_types{}, sint_sint_safe_cast_tester{});
}

struct sint_uint_safe_cast_tester {
    template <typename S>
    struct runner {
        template <typename U>
        void operator()(const U &) const
        {
            using uS = make_unsigned<S>;
            REQUIRE((std::is_same<U, decltype(safe_cast<U>(S(0)))>::value));
            REQUIRE(safe_cast<U>(S(0)) == U(0));
            REQUIRE_THROWS_PREDICATE(safe_cast<U>(S(-1)), std::overflow_error, [](const std::overflow_error &oe) {
                return std::string(oe.what())
                       == "Error in the safe conversion from a signed integral type to an unsigned integral type: the "
                          "input value "
                              + std::to_string(S(-1)) + " does not fit in the range of the target type "
                              + typeid(U).name();
            });
            if (uS(std::numeric_limits<S>::max()) > std::numeric_limits<U>::max()) {
                REQUIRE(safe_cast<U>(S(std::numeric_limits<U>::max())) == std::numeric_limits<U>::max());
                REQUIRE_THROWS_PREDICATE(safe_cast<U>(S(S(std::numeric_limits<U>::max()) + 1)), std::overflow_error,
                                         [](const std::overflow_error &oe) {
                                             return std::string(oe.what())
                                                    == "Error in the safe conversion from a signed integral type to an "
                                                       "unsigned integral type: the input value "
                                                           + std::to_string(S(S(std::numeric_limits<U>::max()) + 1))
                                                           + " does not fit in the range of the target type "
                                                           + typeid(U).name();
                                         });
                REQUIRE_THROWS_PREDICATE(safe_cast<U>(std::numeric_limits<S>::max()), std::overflow_error,
                                         [](const std::overflow_error &oe) {
                                             return std::string(oe.what())
                                                    == "Error in the safe conversion from a signed integral type to an "
                                                       "unsigned integral type: the input value "
                                                           + std::to_string(std::numeric_limits<S>::max())
                                                           + " does not fit in the range of the target type "
                                                           + typeid(U).name();
                                         });
            } else {
                REQUIRE(safe_cast<U>(std::numeric_limits<S>::max()) == uS(std::numeric_limits<S>::max()));
            }
        }
    };
    template <typename T>
    void operator()(const T &) const
    {
        tuple_for_each(uint_types{}, runner<T>{});
    }
};

TEST_CASE("sint_uint_safe_cast")
{
    tuple_for_each(sint_types{}, sint_uint_safe_cast_tester{});
}

struct uint_sint_safe_cast_tester {
    template <typename U>
    struct runner {
        template <typename S>
        void operator()(const S &) const
        {
            using uS = make_unsigned<S>;
            REQUIRE((std::is_same<S, decltype(safe_cast<S>(U(0)))>::value));
            REQUIRE(safe_cast<S>(U(0)) == S(0));
            REQUIRE(safe_cast<S>(U(10)) == S(10));
            if (std::numeric_limits<U>::max() > uS(std::numeric_limits<S>::max())) {
                REQUIRE(safe_cast<S>(U(std::numeric_limits<S>::max())) == std::numeric_limits<S>::max());
                REQUIRE_THROWS_PREDICATE(
                    safe_cast<S>(U(U(std::numeric_limits<S>::max()) + 1u)), std::overflow_error,
                    [](const std::overflow_error &oe) {
                        return std::string(oe.what())
                               == "Error in the safe conversion from an unsigned integral type to a "
                                  "signed integral type: the input value "
                                      + std::to_string(U(U(std::numeric_limits<S>::max()) + 1))
                                      + " does not fit in the range of the target type " + typeid(S).name();
                    });
                REQUIRE_THROWS_PREDICATE(
                    safe_cast<S>(std::numeric_limits<U>::max()), std::overflow_error,
                    [](const std::overflow_error &oe) {
                        return std::string(oe.what())
                               == "Error in the safe conversion from an unsigned integral type to a "
                                  "signed integral type: the input value "
                                      + std::to_string(std::numeric_limits<U>::max())
                                      + " does not fit in the range of the target type " + typeid(S).name();
                    });
            } else {
                REQUIRE(uS(safe_cast<S>(std::numeric_limits<U>::max())) == std::numeric_limits<U>::max());
            }
        }
    };
    template <typename T>
    void operator()(const T &) const
    {
        tuple_for_each(sint_types{}, runner<T>{});
    }
};

TEST_CASE("uint_sint_safe_cast")
{
    tuple_for_each(uint_types{}, uint_sint_safe_cast_tester{});
}
<commit_msg>Small change.<commit_after>// Copyright 2016-2017 Francesco Biscani (bluescarni@gmail.com)
//
// This file is part of the mp++ library.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <limits>
#include <mp++/mp++.hpp>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <typeinfo>

#include "test_utils.hpp"

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

using namespace mppp;
using namespace mppp_test;

using uint_types = std::tuple<unsigned char, unsigned short, unsigned, unsigned long, unsigned long long>;
using sint_types = std::tuple<signed char, short, int, long, long long>;

struct uint_uint_safe_cast_tester {
    template <typename T>
    struct runner {
        template <typename U, enable_if_t<(std::numeric_limits<T>::max() <= std::numeric_limits<U>::max()), int> = 0>
        void operator()(const U &) const
        {
        }
        template <typename U, enable_if_t<(std::numeric_limits<T>::max() > std::numeric_limits<U>::max()), int> = 0>
        void operator()(const U &) const
        {
            REQUIRE((std::is_same<T, decltype(safe_cast<T>(U(0)))>::value));
            REQUIRE(safe_cast<T>(U(0)) == 0u);
            REQUIRE(safe_cast<T>(U(2)) == 2u);
            REQUIRE(safe_cast<T>(std::numeric_limits<U>::max()) == std::numeric_limits<U>::max());
            REQUIRE(safe_cast<T>(U(std::numeric_limits<U>::max() - 1u)) == std::numeric_limits<U>::max() - 1u);
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(T(T(std::numeric_limits<U>::max()) + 1u)), std::overflow_error,
                [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between unsigned integral types: the input value "
                                  + std::to_string(T(std::numeric_limits<U>::max()) + 1u)
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(std::numeric_limits<T>::max()), std::overflow_error, [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between unsigned integral types: the input value "
                                  + std::to_string(std::numeric_limits<T>::max())
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
        }
    };
    template <typename T>
    void operator()(const T &) const
    {
        tuple_for_each(uint_types{}, runner<T>{});
    }
};

TEST_CASE("uint_uint_safe_cast")
{
    tuple_for_each(uint_types{}, uint_uint_safe_cast_tester{});
}

struct sint_sint_safe_cast_tester {
    template <typename T>
    struct runner {
        template <typename U,
                  enable_if_t<(std::numeric_limits<T>::max() <= std::numeric_limits<U>::max()
                               && std::numeric_limits<T>::min() >= std::numeric_limits<U>::min()),
                              int> = 0>
        void operator()(const U &) const
        {
        }
        template <typename U,
                  enable_if_t<(std::numeric_limits<T>::max() > std::numeric_limits<U>::max()
                               && std::numeric_limits<T>::min() < std::numeric_limits<U>::min()),
                              int> = 0>
        void operator()(const U &) const
        {
            REQUIRE((std::is_same<T, decltype(safe_cast<T>(U(0)))>::value));
            REQUIRE(safe_cast<T>(U(0)) == 0);
            REQUIRE(safe_cast<T>(U(2)) == 2);
            REQUIRE(safe_cast<T>(U(-2)) == -2);
            REQUIRE(safe_cast<T>(std::numeric_limits<U>::max()) == std::numeric_limits<U>::max());
            REQUIRE(safe_cast<T>(U(std::numeric_limits<U>::max() - 1)) == std::numeric_limits<U>::max() - 1);
            REQUIRE(safe_cast<T>(U(std::numeric_limits<U>::min() + 1)) == std::numeric_limits<U>::min() + 1);
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(T(T(std::numeric_limits<U>::max()) + 1)), std::overflow_error,
                [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between signed integral types: the input value "
                                  + std::to_string(T(std::numeric_limits<U>::max()) + 1)
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(T(T(std::numeric_limits<U>::min()) - 1)), std::overflow_error,
                [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between signed integral types: the input value "
                                  + std::to_string(T(std::numeric_limits<U>::min()) - 1)
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(std::numeric_limits<T>::max()), std::overflow_error, [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between signed integral types: the input value "
                                  + std::to_string(std::numeric_limits<T>::max())
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
            REQUIRE_THROWS_PREDICATE(
                safe_cast<U>(std::numeric_limits<T>::min()), std::overflow_error, [](const std::overflow_error &oe) {
                    return std::string(oe.what())
                           == "Error in the safe conversion between signed integral types: the input value "
                                  + std::to_string(std::numeric_limits<T>::min())
                                  + " does not fit in the range of the target type " + typeid(U).name();
                });
        }
    };
    template <typename T>
    void operator()(const T &) const
    {
        tuple_for_each(sint_types{}, runner<T>{});
    }
};

TEST_CASE("sint_sint_safe_cast")
{
    tuple_for_each(sint_types{}, sint_sint_safe_cast_tester{});
}

struct sint_uint_safe_cast_tester {
    template <typename S>
    struct runner {
        template <typename U>
        void operator()(const U &) const
        {
            using uS = make_unsigned<S>;
            REQUIRE((std::is_same<U, decltype(safe_cast<U>(S(0)))>::value));
            REQUIRE(safe_cast<U>(S(0)) == U(0));
            REQUIRE_THROWS_PREDICATE(safe_cast<U>(S(-1)), std::overflow_error, [](const std::overflow_error &oe) {
                return std::string(oe.what())
                       == "Error in the safe conversion from a signed integral type to an unsigned integral type: the "
                          "input value "
                              + std::to_string(S(-1)) + " does not fit in the range of the target type "
                              + typeid(U).name();
            });
            if (uS(std::numeric_limits<S>::max()) > std::numeric_limits<U>::max()) {
                REQUIRE(safe_cast<U>(S(std::numeric_limits<U>::max())) == std::numeric_limits<U>::max());
                REQUIRE_THROWS_PREDICATE(safe_cast<U>(S(S(std::numeric_limits<U>::max()) + 1)), std::overflow_error,
                                         [](const std::overflow_error &oe) {
                                             return std::string(oe.what())
                                                    == "Error in the safe conversion from a signed integral type to an "
                                                       "unsigned integral type: the input value "
                                                           + std::to_string(S(S(std::numeric_limits<U>::max()) + 1))
                                                           + " does not fit in the range of the target type "
                                                           + typeid(U).name();
                                         });
                REQUIRE_THROWS_PREDICATE(safe_cast<U>(std::numeric_limits<S>::max()), std::overflow_error,
                                         [](const std::overflow_error &oe) {
                                             return std::string(oe.what())
                                                    == "Error in the safe conversion from a signed integral type to an "
                                                       "unsigned integral type: the input value "
                                                           + std::to_string(std::numeric_limits<S>::max())
                                                           + " does not fit in the range of the target type "
                                                           + typeid(U).name();
                                         });
            } else {
                REQUIRE(safe_cast<U>(std::numeric_limits<S>::max()) == uS(std::numeric_limits<S>::max()));
            }
        }
    };
    template <typename T>
    void operator()(const T &) const
    {
        tuple_for_each(uint_types{}, runner<T>{});
    }
};

TEST_CASE("sint_uint_safe_cast")
{
    tuple_for_each(sint_types{}, sint_uint_safe_cast_tester{});
}

struct uint_sint_safe_cast_tester {
    template <typename U>
    struct runner {
        template <typename S>
        void operator()(const S &) const
        {
            using uS = make_unsigned<S>;
            REQUIRE((std::is_same<S, decltype(safe_cast<S>(U(0)))>::value));
            REQUIRE(safe_cast<S>(U(0)) == S(0));
            REQUIRE(safe_cast<S>(U(10)) == S(10));
            if (std::numeric_limits<U>::max() > uS(std::numeric_limits<S>::max())) {
                REQUIRE(safe_cast<S>(U(std::numeric_limits<S>::max())) == std::numeric_limits<S>::max());
                REQUIRE_THROWS_PREDICATE(
                    safe_cast<S>(U(U(std::numeric_limits<S>::max()) + 1u)), std::overflow_error,
                    [](const std::overflow_error &oe) {
                        return std::string(oe.what())
                               == "Error in the safe conversion from an unsigned integral type to a "
                                  "signed integral type: the input value "
                                      + std::to_string(U(U(std::numeric_limits<S>::max()) + 1))
                                      + " does not fit in the range of the target type " + typeid(S).name();
                    });
                REQUIRE_THROWS_PREDICATE(
                    safe_cast<S>(std::numeric_limits<U>::max()), std::overflow_error,
                    [](const std::overflow_error &oe) {
                        return std::string(oe.what())
                               == "Error in the safe conversion from an unsigned integral type to a "
                                  "signed integral type: the input value "
                                      + std::to_string(std::numeric_limits<U>::max())
                                      + " does not fit in the range of the target type " + typeid(S).name();
                    });
            } else {
                REQUIRE(uS(safe_cast<S>(std::numeric_limits<U>::max())) == std::numeric_limits<U>::max());
            }
        }
    };
    template <typename T>
    void operator()(const T &) const
    {
        tuple_for_each(sint_types{}, runner<T>{});
    }
};

TEST_CASE("uint_sint_safe_cast")
{
    tuple_for_each(uint_types{}, uint_sint_safe_cast_tester{});
}
<|endoftext|>


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

#include "webkit/support/gc_extension.h"

#include "v8/include/v8.h"

const char kGCExtensionName[] = "v8/GCController";

namespace extensions_v8 {

// static
v8::Extension* GCExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kGCExtensionName,
      "(function () {"
      "   var v8_gc;"
      "   if (gc) v8_gc = gc;"
      "   GCController = new Object();"
      "   GCController.collect ="
      "     function() {if (v8_gc) v8_gc(); };"
      " })();");
  return extension;
}

}  // namespace extensions_v8
<commit_msg>Add GCController.minorCollect(), which triggers one minor GC cycle<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/support/gc_extension.h"

#include "v8/include/v8.h"

const char kGCExtensionName[] = "v8/GCController";

namespace extensions_v8 {

// static
v8::Extension* GCExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kGCExtensionName,
      "(function () {"
      "   var v8_gc;"
      "   if (gc) v8_gc = gc;"
      "   GCController = new Object();"
      "   GCController.collect ="
      "     function() {if (v8_gc) v8_gc(); };"
      "   GCController.minorCollect ="
      "     function() {if (v8_gc) v8_gc(true); };"
      " })();");
  return extension;
}

}  // namespace extensions_v8
<|endoftext|>


<commit_before>#include "instance.h"

/*void Instance::set_id(int i){
	id = i;
}

void Instance::set_task_number(int t){
	tasks_number = t;
}*/

void Instance::generate_instance(int quantity, int max_time, int identifier, bool verbose){
	srand(time(NULL));
	this->id = identifier;
	this->tasks_number = quantity;
	int t1_1, t1_2, rt, mt, opt;
	for (int i = 0; i < quantity; i++){
		Task t(task_v.size());
		t1_1 = rand() % max_time+1;
		t1_2 = rand() % max_time+1;
		if ( i < quantity/2 ){
			rt = 0;
		}else{
			rt = rand() % ((max_time*(quantity/4))+1);
		}
		t.set_op_t(1, t1_1);
		t.set_op_t(2, t1_2);
		t.set_ready_t(rt);
		task_v.push_back(t);
		//debug only:
		if (verbose == true){
		 std::cout << t1_1 << ";" << t1_2 << ";" << 1 << ";" << 2 << ";" << rt <<';'<< endl;
		}
	}
	if (verbose == true){
		std::cout << "---------------------------------------------------------------------------\n";
	}
	for (int i = 0; i < quantity/5; i++){
		Maitenance m(i);
		mt = rand() % (max_time /2 ) + 1;
		opt = mt + max_time * i;
		m.set_start_t(mt);
		m.set_duration(opt);
		if (verbose == true){
			std::cout << i << ';' << 1 << ';' << opt << ';' << mt << ';' << endl;
		}
		maitenance_v.push_back(m);
	}
}

void Instance::dump_instance(string filename){
	ofstream file(filename.c_str());
	//file.open(filename.c_str());
	if (file.good() == true){
		file << "****" << id << "****\n";
		file << tasks_number << endl;
		for(vector<int>::size_type i = 0; i < task_v.size(); i++){
			file << task_v[i].get_op_t(1) << ";" << task_v[i].get_op_t(2) << ";" << "1" <<";" << "2" << ";" << task_v[i].get_ready_t() << ";" << endl;
		}
		for (vector<int>::size_type i = 0; i < maitenance_v.size(); i++){
			file << maitenance_v[i].get_id() <<';' << 1 << ";" << maitenance_v[i].get_start_t() << ";" << maitenance_v[i].get_duration() << ";" <<  endl;
		}
	}
	else{
		cerr<<"Cannot open and write to instance file!\n";
		exit(-1);
	}
	file.close();
	clear_all();
}

void Instance::read_instance(string filename){
	string s;
	int quantity, tmp;
	fstream file;

	file.open(filename.c_str());
	if(file.good() == true){
		getline(file, s); //ignoring one line
		getline(file, s);
			quantity = atoi(s.c_str());
			std::cout << quantity << endl;
			for (int i = 0; i < quantity; i++){
				Task t(i);
				getline(file, s, ';');
				tmp = atoi(s.c_str());
				t.set_op_t(1, tmp);
				getline(file, s, ';');
				tmp = atoi(s.c_str());
				t.set_op_t(2,tmp);
				getline(file, s, ';'); //ignoring two lines
				getline(file, s, ';');
				getline(file, s, ';');
				tmp = atoi(s.c_str());
				t.set_ready_t(tmp);
				task_v.push_back(t);
				//std::cout << t.get_op_time(1) << ";" << t.get_op_time(2) << ";" << "1" <<";" << "2" << ";" << t.get_rt() << ";" << endl;
			}

		for(int i = 0; i < quantity/5; i++){
			getline(file, s, ';');
			tmp = atoi(s.c_str());
			Maitenance m(tmp);
			getline(file, s, ';'); // ignoring machine number
			getline(file, s, ';');
			tmp = atoi(s.c_str());
			m.set_duration(tmp);
			getline(file, s, ';');
			tmp = atoi(s.c_str());
			m.set_start_t(tmp);
			maitenance_v.push_back(m);
			//std::cout <<  m.get_id() << ";" << m.get_opt() << ";" << m.get_mt() << ";" << endl;
		}

	}
	else{
		cerr <<"Cannot open and read instance file!\n";
		exit(-1);
	}
	file.close();
}

void Instance::clear_task_v(){
	task_v.clear();
}

void Instance::clear_maitenance_v(){
	maitenance_v.clear();
}

void Instance::clear_all(){
	clear_task_v();
	clear_maitenance_v();
}

vector<Task> Instance::get_tasks(){
	return this->task_v;
}

vector<Maitenance> Instance::get_maitenances(){
	return this->maitenance_v;
}

<commit_msg>check<commit_after>#include "instance.h"

/*void Instance::set_id(int i){
	id = i;
}

void Instance::set_task_number(int t){
	tasks_number = t;
}*/

void Instance::generate_instance(int quantity, int max_time, int identifier, bool verbose){
	srand(time(NULL));
	this->id = identifier;
	this->tasks_number = quantity;
	int t1_1, t1_2, rt, mt, opt;
	for (int i = 0; i < quantity; i++){
		Task t(task_v.size());
		t1_1 = rand() % max_time+1;
		t1_2 = rand() % max_time+1;
		if ( i < quantity/2 ){
			rt = 0;
		}else{
			rt = rand() % ((max_time*(quantity/4))+1);
		}
		t.set_op_t(1, t1_1);
		t.set_op_t(2, t1_2);
		t.set_ready_t(rt);
		task_v.push_back(t);
		//debug only:
		if (verbose == true){
		 std::cout << t1_1 << ";" << t1_2 << ";" << 1 << ";" << 2 << ";" << rt <<';'<< endl;
		}
	}
	if (verbose == true){
		std::cout << "---------------------------------------------------------------------------\n";
	}
	for (int i = 0; i < quantity/5; i++){
		Maitenance m(i);
		mt = rand() % (max_time /2 ) + 1;
		opt = mt + max_time * i;
		m.set_start_t(mt);
		m.set_duration(opt);
		if (verbose == true){
			std::cout << i << ';' << 1 << ';' << opt << ';' << mt << ';' << endl;
		}
		maitenance_v.push_back(m);
	}
}

void Instance::dump_instance(string filename){
	ofstream file(filename.c_str());
	//file.open(filename.c_str());
	if (file.good() == true){
		file << "****" << id << "****\n";
		file << tasks_number << endl;
		for(vector<int>::size_type i = 0; i < task_v.size(); i++){
			file << task_v[i].get_op_t(1) << ";" << task_v[i].get_op_t(2) << ";" << "1" <<";" << "2" << ";" << task_v[i].get_ready_t() << ";" << endl;
		}
		for (vector<int>::size_type i = 0; i < maitenance_v.size(); i++){
			file << maitenance_v[i].get_id() <<';' << 1 << ";" << maitenance_v[i].get_start_t() << ";" << maitenance_v[i].get_duration() << ";" <<  endl;
		}
	}
	else{
		cerr<<"Cannot open and write to instance file!\n";
		exit(-1);
	}
	file.close();
	clear_all();
}

void Instance::read_instance(string filename){
	string s;
	int quantity, tmp;
	fstream file;
	file.open(filename.c_str());
	if(file.good() == true){
		getline(file, s); //ignoring one line
		getline(file, s);
			quantity = atoi(s.c_str());
			std::cout << quantity << endl;
			for (int i = 0; i < quantity; i++){
				Task t(i);
				getline(file, s, ';');
				tmp = atoi(s.c_str());
				t.set_op_t(1, tmp);
				getline(file, s, ';');
				tmp = atoi(s.c_str());
				t.set_op_t(2,tmp);
				getline(file, s, ';'); //ignoring two lines
				getline(file, s, ';');
				getline(file, s, ';');
				tmp = atoi(s.c_str());
				t.set_ready_t(tmp);
				task_v.push_back(t);
				//std::cout << t.get_op_time(1) << ";" << t.get_op_time(2) << ";" << "1" <<";" << "2" << ";" << t.get_rt() << ";" << endl;
			}

		for(int i = 0; i < quantity/5; i++){
			getline(file, s, ';');
			tmp = atoi(s.c_str());
			Maitenance m(tmp);
			getline(file, s, ';'); // ignoring machine number
			getline(file, s, ';');
			tmp = atoi(s.c_str());
			m.set_duration(tmp);
			getline(file, s, ';');
			tmp = atoi(s.c_str());
			m.set_start_t(tmp);
			maitenance_v.push_back(m);
			//std::cout <<  m.get_id() << ";" << m.get_opt() << ";" << m.get_mt() << ";" << endl;
		}

	}
	else{
		cerr <<"Cannot open and read instance file!\n";
		exit(-1);
	}
	file.close();
}

void Instance::clear_task_v(){
	task_v.clear();
}

void Instance::clear_maitenance_v(){
	maitenance_v.clear();
}

void Instance::clear_all(){
	clear_task_v();
	clear_maitenance_v();
}

vector<Task> Instance::get_tasks(){
	return this->task_v;
}

vector<Maitenance> Instance::get_maitenances(){
	return this->maitenance_v;
}

<|endoftext|>


<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// StdAir
#include <stdair/basic/ProgressStatusSet.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// SEvMgr
#include <sevmgr/bom/EventQueue.hpp>
#include <sevmgr/command/EventQueueManager.hpp>

namespace SEVMGR {

  // //////////////////////////////////////////////////////////////////////
  void EventQueueManager::
  buildSampleQueue (stdair::STDAIR_ServicePtr_T lSTDAIR_ServicePtr,
		    EventQueue& ioEventQueue) {

    // Total number of events
    stdair::Count_T lNbOfEvents (2);
    addStatus(ioEventQueue, stdair::EventType::BKG_REQ, lNbOfEvents);

    // Create a shared pointer on a first booking request
    // Date of the request (15-MAY-2011)
    const stdair::BookingRequestStruct& lBookingRequest =
      buildSampleBookingRequest (lSTDAIR_ServicePtr);

    // TODO: understand why the following form does not work, knowing
    // that:
    // typedef boost::shared_ptr<stdair::BookingRequestStruct> stdair::BookingRequestPtr_T
    // stdair::BookingRequestPtr_T oBookingRequest_ptr =
    //   boost::make_shared<stdair::BookingRequestStruct> (lInteractiveBookingRequest);
    const stdair::BookingRequestPtr_T lBookingRequest_ptr =
      stdair::BookingRequestPtr_T(new stdair::BookingRequestStruct(lBookingRequest));

    // Create an event structure
    stdair::EventStruct lEventStruct (stdair::EventType::BKG_REQ,
				      lBookingRequest_ptr);

    // Add the event into the queue
    addEvent(ioEventQueue, lEventStruct);

    // Create a second shared pointer on a second booking request
    // Date of the request (22-JAN-2010)
    const bool isForCRS = true;
    const stdair::BookingRequestStruct& lBookingRequestForCRS =
      buildSampleBookingRequest (lSTDAIR_ServicePtr, isForCRS);

    // TODO: understand why the following form does not work, knowing
    // that:
    // typedef boost::shared_ptr<stdair::BookingRequestStruct> stdair::BookingRequestPtr_T
    // stdair::BookingRequestPtr_T oBookingRequest_ptr =
    //   boost::make_shared<stdair::BookingRequestStruct> (lInteractiveBookingRequest);
    const stdair::BookingRequestPtr_T lBookingRequestForCRS_ptr =
      stdair::BookingRequestPtr_T(new stdair::BookingRequestStruct(lBookingRequestForCRS));

    // Create an event structure
    stdair::EventStruct lEventStructForCRS (stdair::EventType::BKG_REQ,
					    lBookingRequestForCRS_ptr);

    // Add the event into the queue
    addEvent(ioEventQueue, lEventStructForCRS);
  }

  // //////////////////////////////////////////////////////////////////////
  stdair::BookingRequestStruct EventQueueManager::
  buildSampleBookingRequest(stdair::STDAIR_ServicePtr_T lSTDAIR_ServicePtr,
			    const bool isForCRS) {

    // Delegate the booking request building to the dedicated service
    stdair::BookingRequestStruct oBookingRequest =
      lSTDAIR_ServicePtr->buildSampleBookingRequest (isForCRS);

    return oBookingRequest;
  }

  // ////////////////////////////////////////////////////////////////////
  void EventQueueManager::reset (EventQueue& ioEventQueue) {

    /**
     * Reset the EventQueue object.
     */
    ioEventQueue.reset();
  }

  // ////////////////////////////////////////////////////////////////////
  void EventQueueManager::addEvent (EventQueue& ioEventQueue,
                                     stdair::EventStruct& iEventStruct) {

    /**
     * Add the event to the event queue.
     */
    ioEventQueue.addEvent(iEventStruct);
  }

  // //////////////////////////////////////////////////////////////////////
  const std::string EventQueueManager::
  list (const EventQueue& iEventQueue) {

    /**
     * Describe the event queue key
     */
    const std::string& lEventListStr = iEventQueue.list();

    //
    return lEventListStr;
  }

  // //////////////////////////////////////////////////////////////////////
  const std::string EventQueueManager::
  describeKey (const EventQueue& iEventQueue) {

    /**
     * Describe the event queue key
     */
    const std::string& lEventQueueKeyStr = iEventQueue.describeKey();

    //
    return lEventQueueKeyStr;
  }

  // ////////////////////////////////////////////////////////////////////
  stdair::ProgressStatusSet EventQueueManager::
  popEvent (EventQueue& ioEventQueue,
            stdair::EventStruct& iEventStruct) {

    try {
      /**
       * Extract the first event from the queue
       */
      const stdair::ProgressStatusSet& lProgressStatusSet
	= ioEventQueue.popEvent (iEventStruct);

      //
      return lProgressStatusSet;

    } catch (EventQueueException& lEventQueueException) {

      std::ostringstream oErrorMessage;
      oErrorMessage << "The event queue is empty: no event can be popped out.";
      std::cerr << oErrorMessage.str() << std::endl;
      STDAIR_LOG_DEBUG(oErrorMessage.str());

    }

    //
    return stdair::ProgressStatusSet(stdair::EventType::BKG_REQ);
  }

  // ////////////////////////////////////////////////////////////////////
  void EventQueueManager::
  updateStatus (EventQueue& ioEventQueue,
                const stdair::EventType::EN_EventType& iEventType,
                const stdair::Count_T& iEventCount) {

    /**
     * Update the status of the given event type with the given count
     */
    ioEventQueue.updateStatus (iEventType, iEventCount);
  }

  // ////////////////////////////////////////////////////////////////////
  void EventQueueManager::
  addStatus (EventQueue& ioEventQueue,
             const stdair::EventType::EN_EventType& iEventType,
             const stdair::Count_T& iEventCount) {

    /**
     * Add the status of the given event type and initialize it
     * with the given count
     */
    ioEventQueue.addStatus (iEventType, iEventCount);
  }

  // ////////////////////////////////////////////////////////////////////
  bool EventQueueManager::
  isQueueDone (const EventQueue& iEventQueue) {

    /**
     * Check if the event queue is done
     */
    const bool isQueueDone = iEventQueue.isQueueDone();

    //
    return isQueueDone;
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getQueueSize (const EventQueue& iEventQueue) {

    /**
     * Calculates the size of the event queue
     */
    const stdair::Count_T& lQueueSize = iEventQueue.getQueueSize();

    //
    return lQueueSize;
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getExpectedTotalNumberOfEventsToBeGenerated (const EventQueue& ioEventQueue) {

    /**
     * Calculate the expected total number of events with the given type
     */
    const stdair::Count_T& lExpectedTotalNumberOfEvents =
      ioEventQueue.getExpectedTotalNbOfEvents ();

    //
    return lExpectedTotalNumberOfEvents;
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getExpectedTotalNumberOfEventsToBeGenerated (const EventQueue& ioEventQueue,
                                               const stdair::EventType::EN_EventType& iEventType) {

    /**
     * Calculate the expected total number of events with the given type
     */
    const stdair::Count_T& lExpectedTotalNumberOfEvents =
      ioEventQueue.getExpectedTotalNbOfEvents (iEventType);

    //
    return lExpectedTotalNumberOfEvents;
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getActualTotalNumberOfEventsToBeGenerated (const EventQueue& ioEventQueue) {

    /**
     * Calculate the actual total number of events with the given type
     */
    const stdair::Count_T& lActualTotalNumberOfEvents =
      ioEventQueue.getActualTotalNbOfEvents ();

    //
    return lActualTotalNumberOfEvents;

  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getActualTotalNumberOfEventsToBeGenerated (const EventQueue& ioEventQueue,
                                             const stdair::EventType::EN_EventType& iEventType) {

    /**
     * Calculate the actual total number of events with the given type
     */
    const stdair::Count_T& lActualTotalNumberOfEvents =
      ioEventQueue.getActualTotalNbOfEvents (iEventType);

    //
    return lActualTotalNumberOfEvents;

  }

  //////////////////////////////////////////////////////////////////////
  void EventQueueManager::
  setActualTotalNbOfEvents (EventQueue& iEventQueue,
                            const stdair::Count_T& iActualTotalNbOfEvents) {

    /**
     * Calculate the actual total number of events in the queue
     */
    iEventQueue.setActualTotalNbOfEvents (iActualTotalNbOfEvents);

  }

}
<commit_msg>[Dev] Added two break points in the default event queue: the default event queue is now composed of two booking requests and two break points.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// StdAir
#include <stdair/basic/ProgressStatusSet.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/BreakPointStruct.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// SEvMgr
#include <sevmgr/bom/EventQueue.hpp>
#include <sevmgr/command/EventQueueManager.hpp>

namespace SEVMGR {

  // //////////////////////////////////////////////////////////////////////
  void EventQueueManager::
  buildSampleQueue (stdair::STDAIR_ServicePtr_T lSTDAIR_ServicePtr,
		    EventQueue& ioEventQueue) {

    // Total number of booking requests into the queue
    stdair::Count_T lNbOfBookingRequests (2);
    addStatus(ioEventQueue, stdair::EventType::BKG_REQ, lNbOfBookingRequests);

    // Create a shared pointer on a first booking request
    // Date of the request (15-MAY-2011)
    const stdair::BookingRequestStruct& lBookingRequest =
      buildSampleBookingRequest (lSTDAIR_ServicePtr);

    // TODO: understand why the following form does not work, knowing
    // that:
    // typedef boost::shared_ptr<stdair::BookingRequestStruct> stdair::BookingRequestPtr_T
    // stdair::BookingRequestPtr_T oBookingRequest_ptr =
    //   boost::make_shared<stdair::BookingRequestStruct> (lInteractiveBookingRequest);
    const stdair::BookingRequestPtr_T lBookingRequest_ptr =
      stdair::BookingRequestPtr_T(new stdair::BookingRequestStruct(lBookingRequest));

    // Create an event structure
    stdair::EventStruct lEventStruct (stdair::EventType::BKG_REQ,
				      lBookingRequest_ptr);

    // Add the event into the queue
    addEvent(ioEventQueue, lEventStruct);

    // Create a second shared pointer on a second booking request
    // Date of the request (22-JAN-2010)
    const bool isForCRS = true;
    const stdair::BookingRequestStruct& lBookingRequestForCRS =
      buildSampleBookingRequest (lSTDAIR_ServicePtr, isForCRS);

    // TODO: understand why the following form does not work, knowing
    // that:
    // typedef boost::shared_ptr<stdair::BookingRequestStruct> stdair::BookingRequestPtr_T
    // stdair::BookingRequestPtr_T oBookingRequest_ptr =
    //   boost::make_shared<stdair::BookingRequestStruct> (lInteractiveBookingRequest);
    const stdair::BookingRequestPtr_T lBookingRequestForCRS_ptr =
      stdair::BookingRequestPtr_T(new stdair::BookingRequestStruct(lBookingRequestForCRS));

    // Create an event structure
    stdair::EventStruct lEventStructForCRS (stdair::EventType::BKG_REQ,
					    lBookingRequestForCRS_ptr);

    // Add the event into the queue
    addEvent(ioEventQueue, lEventStructForCRS);

    // Total number of break points into the queue
    stdair::Count_T lNbOfBreakPoints (2);
    addStatus(ioEventQueue, stdair::EventType::BRK_PT, lNbOfBreakPoints);

    // Create a shared pointer on a second break point
    // Date of the break point (21-JAN-2010)
    const stdair::Date_T lBP1Date (2010, boost::gregorian::Jan, 21);
    // Time of the break point (00:00)
    const stdair::Duration_T lBP1Time (0, 0, 0);
    // Date-time of the break point  (made of the date and time above)
    const stdair::DateTime_T lBP1DateTime (lBP1Date, lBP1Time);

    // TODO: understand why the form above does not work.
    const stdair::BreakPointPtr_T lBreakPoint1_ptr =
      stdair::BreakPointPtr_T(new stdair::BreakPointStruct(lBP1DateTime));

    // Create an event structure
    stdair::EventStruct lEventBreakPoint1 (stdair::EventType::BRK_PT,
					   lBreakPoint1_ptr);

    // Add the event into the queue
    addEvent(ioEventQueue, lEventBreakPoint1);

    // Create a shared pointer on a second break point
    // Date of the break point (14-MAY-2011)
    const stdair::Date_T lBP2Date (2011, boost::gregorian::May, 14);
    // Time of the break point (00:00)
    const stdair::Duration_T lBP2Time (0, 0, 0);
    // Date-time of the break point  (made of the date and time above)
    const stdair::DateTime_T lBP2DateTime (lBP2Date, lBP2Time);

    // TODO: understand why the form above does not work.
    const stdair::BreakPointPtr_T lBreakPoint2_ptr =
      stdair::BreakPointPtr_T(new stdair::BreakPointStruct(lBP2DateTime));

    // Create an event structure
    stdair::EventStruct lEventBreakPoint2 (stdair::EventType::BRK_PT,
					   lBreakPoint2_ptr);

    // Add the event into the queue
    addEvent(ioEventQueue, lEventBreakPoint2);

  }

  // //////////////////////////////////////////////////////////////////////
  stdair::BookingRequestStruct EventQueueManager::
  buildSampleBookingRequest(stdair::STDAIR_ServicePtr_T lSTDAIR_ServicePtr,
			    const bool isForCRS) {

    // Delegate the booking request building to the dedicated service
    stdair::BookingRequestStruct oBookingRequest =
      lSTDAIR_ServicePtr->buildSampleBookingRequest (isForCRS);

    return oBookingRequest;
  }

  // ////////////////////////////////////////////////////////////////////
  void EventQueueManager::reset (EventQueue& ioEventQueue) {

    /**
     * Reset the EventQueue object.
     */
    ioEventQueue.reset();
  }

  // ////////////////////////////////////////////////////////////////////
  void EventQueueManager::addEvent (EventQueue& ioEventQueue,
                                     stdair::EventStruct& iEventStruct) {

    /**
     * Add the event to the event queue.
     */
    ioEventQueue.addEvent(iEventStruct);
  }

  // //////////////////////////////////////////////////////////////////////
  const std::string EventQueueManager::
  list (const EventQueue& iEventQueue) {

    /**
     * Describe the event queue key
     */
    const std::string& lEventListStr = iEventQueue.list();

    //
    return lEventListStr;
  }

  // //////////////////////////////////////////////////////////////////////
  const std::string EventQueueManager::
  describeKey (const EventQueue& iEventQueue) {

    /**
     * Describe the event queue key
     */
    const std::string& lEventQueueKeyStr = iEventQueue.describeKey();

    //
    return lEventQueueKeyStr;
  }

  // ////////////////////////////////////////////////////////////////////
  stdair::ProgressStatusSet EventQueueManager::
  popEvent (EventQueue& ioEventQueue,
            stdair::EventStruct& iEventStruct) {

    try {
      /**
       * Extract the first event from the queue
       */
      const stdair::ProgressStatusSet& lProgressStatusSet
	= ioEventQueue.popEvent (iEventStruct);

      //
      return lProgressStatusSet;

    } catch (EventQueueException& lEventQueueException) {

      std::ostringstream oErrorMessage;
      oErrorMessage << "The event queue is empty: no event can be popped out.";
      std::cerr << oErrorMessage.str() << std::endl;
      STDAIR_LOG_DEBUG(oErrorMessage.str());

    }

    //
    return stdair::ProgressStatusSet(stdair::EventType::BKG_REQ);
  }

  // ////////////////////////////////////////////////////////////////////
  void EventQueueManager::
  updateStatus (EventQueue& ioEventQueue,
                const stdair::EventType::EN_EventType& iEventType,
                const stdair::Count_T& iEventCount) {

    /**
     * Update the status of the given event type with the given count
     */
    ioEventQueue.updateStatus (iEventType, iEventCount);
  }

  // ////////////////////////////////////////////////////////////////////
  void EventQueueManager::
  addStatus (EventQueue& ioEventQueue,
             const stdair::EventType::EN_EventType& iEventType,
             const stdair::Count_T& iEventCount) {

    /**
     * Add the status of the given event type and initialize it
     * with the given count
     */
    ioEventQueue.addStatus (iEventType, iEventCount);
  }

  // ////////////////////////////////////////////////////////////////////
  bool EventQueueManager::
  isQueueDone (const EventQueue& iEventQueue) {

    /**
     * Check if the event queue is done
     */
    const bool isQueueDone = iEventQueue.isQueueDone();

    //
    return isQueueDone;
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getQueueSize (const EventQueue& iEventQueue) {

    /**
     * Calculates the size of the event queue
     */
    const stdair::Count_T& lQueueSize = iEventQueue.getQueueSize();

    //
    return lQueueSize;
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getExpectedTotalNumberOfEventsToBeGenerated (const EventQueue& ioEventQueue) {

    /**
     * Calculate the expected total number of events with the given type
     */
    const stdair::Count_T& lExpectedTotalNumberOfEvents =
      ioEventQueue.getExpectedTotalNbOfEvents ();

    //
    return lExpectedTotalNumberOfEvents;
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getExpectedTotalNumberOfEventsToBeGenerated (const EventQueue& ioEventQueue,
                                               const stdair::EventType::EN_EventType& iEventType) {

    /**
     * Calculate the expected total number of events with the given type
     */
    const stdair::Count_T& lExpectedTotalNumberOfEvents =
      ioEventQueue.getExpectedTotalNbOfEvents (iEventType);

    //
    return lExpectedTotalNumberOfEvents;
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getActualTotalNumberOfEventsToBeGenerated (const EventQueue& ioEventQueue) {

    /**
     * Calculate the actual total number of events with the given type
     */
    const stdair::Count_T& lActualTotalNumberOfEvents =
      ioEventQueue.getActualTotalNbOfEvents ();

    //
    return lActualTotalNumberOfEvents;

  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::Count_T& EventQueueManager::
  getActualTotalNumberOfEventsToBeGenerated (const EventQueue& ioEventQueue,
                                             const stdair::EventType::EN_EventType& iEventType) {

    /**
     * Calculate the actual total number of events with the given type
     */
    const stdair::Count_T& lActualTotalNumberOfEvents =
      ioEventQueue.getActualTotalNbOfEvents (iEventType);

    //
    return lActualTotalNumberOfEvents;

  }

  //////////////////////////////////////////////////////////////////////
  void EventQueueManager::
  setActualTotalNbOfEvents (EventQueue& iEventQueue,
                            const stdair::Count_T& iActualTotalNbOfEvents) {

    /**
     * Calculate the actual total number of events in the queue
     */
    iEventQueue.setActualTotalNbOfEvents (iActualTotalNbOfEvents);

  }

}
<|endoftext|>


<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#include <stdexcept>
#include <ndn-cpp/common.hpp>
#include <ndn-cpp/interest.hpp>

using namespace std;

namespace ndn {

bool
Interest::matchesName(const Name &name) const
{
  if (!name_.isPrefixOf(name))
    return false;

  if (minSuffixComponents_ >= 0 &&
    // Add 1 for the implicit digest.
      !(name.size() + 1 - name_.size() >= minSuffixComponents_))
    return false;

  if (maxSuffixComponents_ >= 0 &&
    // Add 1 for the implicit digest.
    !(name.size() + 1 - name_.size() <= maxSuffixComponents_))
    return false;

  if (!exclude_.empty() && name.size() > name_.size() &&
      exclude_.isExcluded(name[name_.size()]))
    return false;

  return true;
}

std::ostream &
operator << (std::ostream &os, const Interest &interest)
{
  os << interest.getName();

  char delim = '?';

  if (interest.getMinSuffixComponents() >= 0) {
    os << delim << "ndn.MinSuffixComponents=" << interest.getMinSuffixComponents();
    delim = '&';
  }
  if (interest.getMaxSuffixComponents() >= 0) {
    os << delim << "ndn.MaxSuffixComponents=" << interest.getMaxSuffixComponents();
    delim = '&';
  }
  if (interest.getChildSelector() >= 0) {
    os << delim << "ndn.ChildSelector=" << interest.getChildSelector();
    delim = '&';
  }
  if (interest.getMustBeFresh()) {
    os << delim << "ndn.MustBeFresh=" << interest.getMustBeFresh();
    delim = '&';
  }
  if (interest.getScope() >= 0) {
    os << delim << "ndn.Scope=" << interest.getScope();
    delim = '&';
  }
  if (interest.getInterestLifetime() >= 0) {
    os << delim << "ndn.InterestLifetime=" << interest.getInterestLifetime();
    delim = '&';
  }

  if (interest.getNonce() > 0) {
    os << delim << "ndn.Nonce=" << interest.getNonce();
    delim = '&';
  }
  if (!interest.getExclude().empty()) {
    os << delim << "ndn.Exclude=" << interest.getExclude();
    delim = '&';
  }

  return os;
}

const Block&
Interest::wireEncode() const
{
  if (wire_.hasWire())
    return wire_;

  wire_ = Block(Tlv::Interest);
  wire_.push_back(getName().wireEncode());

  // selectors
  {
    Block selectors(Tlv::Selectors);

    if (getMinSuffixComponents() >= 0) {
      OBufferStream os;
      Tlv::writeVarNumber(os, Tlv::MinSuffixComponents);
      Tlv::writeVarNumber(os, Tlv::sizeOfNonNegativeInteger(getMinSuffixComponents()));
      Tlv::writeNonNegativeInteger(os, getMinSuffixComponents());

      selectors.push_back(Block(os.buf()));
    }
    if (getMaxSuffixComponents() >= 0) {
      OBufferStream os;
      Tlv::writeVarNumber(os, Tlv::MaxSuffixComponents);
      Tlv::writeVarNumber(os, Tlv::sizeOfNonNegativeInteger(getMaxSuffixComponents()));
      Tlv::writeNonNegativeInteger(os, getMaxSuffixComponents());

      selectors.push_back(Block(os.buf()));
    }
    if (!getExclude().empty()) {
      selectors.push_back(getExclude().wireEncode());
    }
    if (getChildSelector() >= 0) {
      OBufferStream os;
      Tlv::writeVarNumber(os, Tlv::ChildSelector);
      Tlv::writeVarNumber(os, Tlv::sizeOfNonNegativeInteger(getChildSelector()));
      Tlv::writeNonNegativeInteger(os, getChildSelector());

      selectors.push_back(Block(os.buf()));
    }
    if (getMustBeFresh()) {
      OBufferStream os;
      Tlv::writeVarNumber(os, Tlv::MustBeFresh);
      Tlv::writeVarNumber(os, 0);

      selectors.push_back(Block(os.buf()));
    }

    selectors.encode();
    wire_.push_back(selectors);
  }

  // Nonce
  {
    OBufferStream os;
    Tlv::writeVarNumber(os, Tlv::Nonce);
    Tlv::writeVarNumber(os, Tlv::sizeOfNonNegativeInteger(getNonce()));
    Tlv::writeNonNegativeInteger(os, getNonce());

    wire_.push_back(Block(os.buf()));
  }

  if (getScope() >= 0) {
    OBufferStream os;
    Tlv::writeVarNumber(os, Tlv::Scope);
    Tlv::writeVarNumber(os, Tlv::sizeOfNonNegativeInteger(getScope()));
    Tlv::writeNonNegativeInteger(os, getScope());

    wire_.push_back(Block(os.buf()));
  }
  if (getInterestLifetime() >= 0) {
    OBufferStream os;
    Tlv::writeVarNumber(os, Tlv::InterestLifetime);
    Tlv::writeVarNumber(os, Tlv::sizeOfNonNegativeInteger(getInterestLifetime()));
    Tlv::writeNonNegativeInteger(os, getInterestLifetime());

    wire_.push_back(Block(os.buf()));
  }

  wire_.encode();
  return wire_;
}

void
Interest::wireDecode(const Block &wire)
{
  wire_ = wire;
  wire_.parse();

  // Name
  name_.wireDecode(wire_.get(Tlv::Name));

  // Selectors
  Block::element_iterator selectors = wire_.find(Tlv::Selectors);
  if (selectors != wire_.getAll().end())
    {
      selectors->parse();

      // MinSuffixComponents
      Block::element_iterator val = selectors->find(Tlv::MinSuffixComponents);
      if (val != selectors->getAll().end())
        {
          Buffer::const_iterator begin = val->value_begin();
          minSuffixComponents_ = Tlv::readNonNegativeInteger(val->value_size(), begin, val->value_end());
        }

      // MaxSuffixComponents
      val = selectors->find(Tlv::MaxSuffixComponents);
      if (val != selectors->getAll().end())
        {
          Buffer::const_iterator begin = val->value_begin();
          maxSuffixComponents_ = Tlv::readNonNegativeInteger(val->value_size(), begin, val->value_end());
        }

      // Exclude
      val = selectors->find(Tlv::Exclude);
      if (val != selectors->getAll().end())
        {
          exclude_.wireDecode(*val);
        }

      // ChildSelector
      val = selectors->find(Tlv::ChildSelector);
      if (val != selectors->getAll().end())
        {
          Buffer::const_iterator begin = val->value_begin();
          childSelector_ = Tlv::readNonNegativeInteger(val->value_size(), begin, val->value_end());
        }

      //MustBeFresh aka AnswerOriginKind
      val = selectors->find(Tlv::MustBeFresh);
      if (val != selectors->getAll().end())
        {
          mustBeFresh_ = true;
        }
    }

  // Nonce
  Block::element_iterator val = wire_.find(Tlv::Nonce);
  if (val != wire_.getAll().end())
    {
      Buffer::const_iterator begin = val->value_begin();
      nonce_ = Tlv::readNonNegativeInteger(val->value_size(), begin, val->value_end());
    }

  // Scope
  val = wire_.find(Tlv::Scope);
  if (val != wire_.getAll().end())
    {
      Buffer::const_iterator begin = val->value_begin();
      scope_ = Tlv::readNonNegativeInteger(val->value_size(), begin, val->value_end());
    }

  // InterestLifetime
  val = wire_.find(Tlv::InterestLifetime);
  if (val != wire_.getAll().end())
    {
      Buffer::const_iterator begin = val->value_begin();
      interestLifetime_ = Tlv::readNonNegativeInteger(val->value_size(), begin, val->value_end());
    }
}

}
<commit_msg>interest: Update TLV encoding/decoding<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#include <stdexcept>
#include <ndn-cpp/common.hpp>
#include <ndn-cpp/interest.hpp>

using namespace std;

namespace ndn {

bool
Interest::matchesName(const Name &name) const
{
  if (!name_.isPrefixOf(name))
    return false;

  if (minSuffixComponents_ >= 0 &&
    // Add 1 for the implicit digest.
      !(name.size() + 1 - name_.size() >= minSuffixComponents_))
    return false;

  if (maxSuffixComponents_ >= 0 &&
    // Add 1 for the implicit digest.
    !(name.size() + 1 - name_.size() <= maxSuffixComponents_))
    return false;

  if (!exclude_.empty() && name.size() > name_.size() &&
      exclude_.isExcluded(name[name_.size()]))
    return false;

  return true;
}

std::ostream &
operator << (std::ostream &os, const Interest &interest)
{
  os << interest.getName();

  char delim = '?';

  if (interest.getMinSuffixComponents() >= 0) {
    os << delim << "ndn.MinSuffixComponents=" << interest.getMinSuffixComponents();
    delim = '&';
  }
  if (interest.getMaxSuffixComponents() >= 0) {
    os << delim << "ndn.MaxSuffixComponents=" << interest.getMaxSuffixComponents();
    delim = '&';
  }
  if (interest.getChildSelector() >= 0) {
    os << delim << "ndn.ChildSelector=" << interest.getChildSelector();
    delim = '&';
  }
  if (interest.getMustBeFresh()) {
    os << delim << "ndn.MustBeFresh=" << interest.getMustBeFresh();
    delim = '&';
  }
  if (interest.getScope() >= 0) {
    os << delim << "ndn.Scope=" << interest.getScope();
    delim = '&';
  }
  if (interest.getInterestLifetime() >= 0) {
    os << delim << "ndn.InterestLifetime=" << interest.getInterestLifetime();
    delim = '&';
  }

  if (interest.getNonce() > 0) {
    os << delim << "ndn.Nonce=" << interest.getNonce();
    delim = '&';
  }
  if (!interest.getExclude().empty()) {
    os << delim << "ndn.Exclude=" << interest.getExclude();
    delim = '&';
  }

  return os;
}

const Block&
Interest::wireEncode() const
{
  if (wire_.hasWire())
    return wire_;

  // Interest ::= INTEREST-TYPE TLV-LENGTH
  //                Name
  //                Selectors?
  //                Nonce
  //                Scope?
  //                InterestLifetime?

  wire_ = Block(Tlv::Interest);
  wire_.push_back(getName().wireEncode());

  // selectors
  {
    Block selectors(Tlv::Selectors);

    if (getMinSuffixComponents() >= 0) {
      selectors.push_back
        (nonNegativeIntegerBlock(Tlv::MinSuffixComponents, getMinSuffixComponents()));
    }
    if (getMaxSuffixComponents() >= 0) {
      selectors.push_back
        (nonNegativeIntegerBlock(Tlv::MaxSuffixComponents, getMaxSuffixComponents()));
    }
    if (!getExclude().empty()) {
      selectors.push_back
        (getExclude().wireEncode());
    }
    if (getChildSelector() >= 0) {
      selectors.push_back
        (nonNegativeIntegerBlock(Tlv::ChildSelector, getChildSelector()));
    }
    if (getMustBeFresh()) {
      selectors.push_back
        (booleanBlock(Tlv::MustBeFresh));
    }

    selectors.encode();
    wire_.push_back(selectors);
  }

  // Nonce
  {
    wire_.push_back
      (nonNegativeIntegerBlock(Tlv::Nonce, getNonce()));
  }

  if (getScope() >= 0) {
    wire_.push_back
      (nonNegativeIntegerBlock(Tlv::Scope, getScope()));
  }
  if (getInterestLifetime() >= 0) {
    wire_.push_back
      (nonNegativeIntegerBlock(Tlv::InterestLifetime, getInterestLifetime()));
  }

  wire_.encode();
  return wire_;
}

void
Interest::wireDecode(const Block &wire)
{
  wire_ = wire;
  wire_.parse();

  // Interest ::= INTEREST-TYPE TLV-LENGTH
  //                Name
  //                Selectors?
  //                Nonce
  //                Scope?
  //                InterestLifetime?

  // Name
  name_.wireDecode(wire_.get(Tlv::Name));

  // Selectors
  Block::element_iterator selectors = wire_.find(Tlv::Selectors);
  if (selectors != wire_.getAll().end())
    {
      selectors->parse();

      // MinSuffixComponents
      Block::element_iterator val = selectors->find(Tlv::MinSuffixComponents);
      if (val != selectors->getAll().end())
        {
          minSuffixComponents_ = readNonNegativeInteger(*val);
        }

      // MaxSuffixComponents
      val = selectors->find(Tlv::MaxSuffixComponents);
      if (val != selectors->getAll().end())
        {
          maxSuffixComponents_ = readNonNegativeInteger(*val);
        }

      // Exclude
      val = selectors->find(Tlv::Exclude);
      if (val != selectors->getAll().end())
        {
          exclude_.wireDecode(*val);
        }

      // ChildSelector
      val = selectors->find(Tlv::ChildSelector);
      if (val != selectors->getAll().end())
        {
          childSelector_ = readNonNegativeInteger(*val);
        }

      //MustBeFresh aka AnswerOriginKind
      val = selectors->find(Tlv::MustBeFresh);
      if (val != selectors->getAll().end())
        {
          mustBeFresh_ = true;
        }
    }

  // Nonce
  Block::element_iterator val = wire_.find(Tlv::Nonce);
  if (val != wire_.getAll().end())
    {
      nonce_ = readNonNegativeInteger(*val);
    }

  // Scope
  val = wire_.find(Tlv::Scope);
  if (val != wire_.getAll().end())
    {
      scope_ = readNonNegativeInteger(*val);
    }

  // InterestLifetime
  val = wire_.find(Tlv::InterestLifetime);
  if (val != wire_.getAll().end())
    {
      interestLifetime_ = readNonNegativeInteger(*val);
    }
}

}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "BBE/SimpleFile.h"
#include <fstream>
#include <iostream>
#include <stdlib.h>

bbe::List<char> bbe::simpleFile::readBinaryFile(const bbe::String & filepath)
{
	//UNTESTED
	std::cout << filepath.getLength() << std::endl;
	std::cout << filepath.getRaw() << std::endl;
	for(std::size_t i = 0; i<filepath.getLength(); i++){
		std::cout << filepath.getRaw()[i] << std::endl;
	}

	wchar_t path_w[1024];
	char path[1024];
	memset(path_w, 0, 1024*sizeof(wchar_t));

	std::cout << "OLA!" << std::endl;
	if(filepath.getLength() >= sizeof(path) - 1)
	{
		throw std::runtime_error("Path too long!");
	}
	for(std::size_t i = 0; i<filepath.getLength(); i++)
	{
		std::cout << "OLA!" << std::endl;
		path_w[i] = filepath.getRaw()[i];
	}

	std::cout << "OLA!" << std::endl;
	std::size_t length = wcstombs(path, path_w, sizeof(path));
	if(length >= sizeof(path) - 1)
	{
		throw std::runtime_error("Path too long!");
	}
	std::cout << "Reading File: " << path << std::endl;
	std::ifstream file(path, std::ios::binary | std::ios::ate);

	if (file)
	{
		size_t fileSize = (size_t)file.tellg();
		bbe::List<char> fileBuffer;
		fileBuffer.resizeCapacityAndLength(fileSize);
		file.seekg(0);
		file.read(fileBuffer.getRaw(), fileSize);
		file.close();
		return fileBuffer;
	}
	else
	{
		throw std::runtime_error("Failed to open file!");
	}
}

void bbe::simpleFile::writeFloatArrToFile(const bbe::String & filePath, float * arr, size_t size)
{
	char path[1024];
	std::size_t length = wcstombs(path, filePath.getRaw(), sizeof(path));
	if(length >= sizeof(path) - 1)
	{
		throw std::runtime_error("Path too long!");
	}
	std::ofstream file(path);
	for (std::size_t i = 0; i < size; i++)
	{
		file << arr[i] << "\n";
	}
	file.close();
}
<commit_msg>UNSTABLE COMMIT! Removed wchar_t usage in simpleFile<commit_after>#include "stdafx.h"
#include "BBE/SimpleFile.h"
#include <fstream>
#include <iostream>
#include <stdlib.h>

bbe::List<char> bbe::simpleFile::readBinaryFile(const bbe::String & filepath)
{
	//UNTESTED
	std::ifstream file(filepath.getRaw(), std::ios::binary | std::ios::ate);

	if (file)
	{
		size_t fileSize = (size_t)file.tellg();
		bbe::List<char> fileBuffer;
		fileBuffer.resizeCapacityAndLength(fileSize);
		file.seekg(0);
		file.read(fileBuffer.getRaw(), fileSize);
		file.close();
		return fileBuffer;
	}
	else
	{
		throw std::runtime_error("Failed to open file!");
	}
}

void bbe::simpleFile::writeFloatArrToFile(const bbe::String & filePath, float * arr, size_t size)
{
	std::ofstream file(filePath.getRaw());
	for (std::size_t i = 0; i < size; i++)
	{
		file << arr[i] << "\n";
	}
	file.close();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <bitset>

using namespace std;

#define CRCANSI "11000000000000101"

class CRCEncoder
{
public://change to private

	void Calculate(string messege)
	{
		messege = "1101010000000000000000";
		//messege = "1001";
		bitset<8> msg(messege);
		bitset<16> poly(CRCANSI);

		int result;

		result = msg.to_ulong() % poly.to_ulong();

		cout << msg.to_ulong() << endl;
		cout << poly.to_ulong() << endl;
		cout << result << endl;

	}

};

<commit_msg>started to implement an xor algorithm for subtraction<commit_after>#include <iostream>
#include <bitset>

using namespace std;

#define CRCANSI "11000000000000101"

class CRCEncoder
{
public://change to private

	void Calculate(string messege)
	{
		messege = "1101010000000000000000";
		//messege = "1001";
		/*bitset<8> msg(messege);
		bitset<16> poly(CRCANSI);

		int result;

		result = msg.to_ulong() % poly.to_ulong();

		cout << msg.to_ulong() << endl;
		cout << poly.to_ulong() << endl;
		cout << result << endl;*/

		/*	int num1[] = { 1, 0, 1, 0, 1, 0, 1, 1, 0 };
			int num2[] = { 1, 0, 0 };
			string result = "";

			for (int c = 0; c < 8; c++)
			{
			for (int i = 0; i < 3; i++)
			{
			result += to_string(num1[i] ^ num2[i]);
			}
			cout << result << endl;
			result = "";
			}
			*/
		bitset <16> num1("010101010010010110");
		bitset <16> num2("100");
		bitset <16> result;
		num1 ^= num2;
		cout << num1;// << endl;
	}

};<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "s60radiotunercontrol_since32.h"
#include "s60radiotunerservice.h"

#include <QtCore/qdebug.h>
#include <RadioFmTunerUtility.h>

S60RadioTunerControl::S60RadioTunerControl(QObject *parent)
    : QRadioTunerControl(parent)
    , m_error(0)
    , m_radioUtility(NULL)
    , m_fmTunerUtility(NULL)
    , m_playerUtility(NULL)
    , m_audioInitializationComplete(false)
    , m_muted(false)
    , m_isStereo(true)
    , m_vol(100)
    , m_signal(0)
    , m_radioError(QRadioTuner::NoError)
    , m_scanning(false)
    , m_currentBand(QRadioTuner::FM)
    , m_currentFreq(87500000)
    , m_stereoMode(QRadioTuner::Auto)
    , m_apiTunerState(QRadioTuner::StoppedState)
    , m_maxVolume(100)
{
    initRadio();
}

S60RadioTunerControl::~S60RadioTunerControl()
{
	if (m_fmTunerUtility) {
		m_fmTunerUtility->Close();
	}

	if(m_playerUtility) {
		m_playerUtility->Close();
	}

	delete m_radioUtility;
}

QRadioTuner::State S60RadioTunerControl::state() const
{
    return m_apiTunerState;
}

QRadioTuner::Band S60RadioTunerControl::band() const
{
    return m_currentBand;
}

bool S60RadioTunerControl::isBandSupported(QRadioTuner::Band b) const
{
	if(b == QRadioTuner::FM)
		return true;
	else if(b == QRadioTuner::LW)
		return false;
	else if(b == QRadioTuner::AM)
		return true;
	else if(b == QRadioTuner::SW)
		return false;
	else
		return false;
}

void S60RadioTunerControl::setBand(QRadioTuner::Band b)
{
    QRadioTuner::Band tempBand = b;
    if (tempBand != m_currentBand) {
        m_currentBand = b;
        emit bandChanged(m_currentBand);
    }
}

int S60RadioTunerControl::frequency() const
{
    return m_currentFreq;
}

void S60RadioTunerControl::setFrequency(int frequency)
{
	m_currentFreq = frequency;
	m_fmTunerUtility->SetFrequency(m_currentFreq);
}
int S60RadioTunerControl::frequencyStep(QRadioTuner::Band b) const
{
    int step = 0;
    if(b == QRadioTuner::FM)
        step = 100000; // 100kHz steps
    else if(b == QRadioTuner::LW)
        step = 1000; // 1kHz steps
    else if(b == QRadioTuner::AM)
        step = 1000; // 1kHz steps
    else if(b == QRadioTuner::SW)
        step = 500; // 500Hz steps

    return step;
}

QPair<int,int> S60RadioTunerControl::frequencyRange(QRadioTuner::Band band) const
{
    int bottomFreq;
    int topFreq;

    int bandError = KErrNone;
    TFmRadioFrequencyRange range;

    if (m_fmTunerUtility) {
        bandError = m_fmTunerUtility->GetFrequencyRange(range, bottomFreq, topFreq);
    }
    if (!bandError) {
        return qMakePair<int,int>(bottomFreq, topFreq);
    }

    return qMakePair<int,int>(0,0);
}

bool S60RadioTunerControl::isStereo() const
{
    return m_isStereo;
}

QRadioTuner::StereoMode S60RadioTunerControl::stereoMode() const
{
    return m_stereoMode;
}

void S60RadioTunerControl::setStereoMode(QRadioTuner::StereoMode mode)
{
	if (m_fmTunerUtility) {
	    if (QRadioTuner::ForceMono == mode) {
	    	m_fmTunerUtility->ForceMonoReception(true);
	    	m_stereoMode = QRadioTuner::ForceMono;
			m_isStereo = false;
	    } else {
	    	m_fmTunerUtility->ForceMonoReception(false);
			m_isStereo = true;
			m_stereoMode = QRadioTuner::ForceStereo;
	    }
	}
}

int S60RadioTunerControl::signalStrength() const
{
    // return value is a percentage value
    if (m_fmTunerUtility) {
        TInt maxSignalStrength;
        TInt currentSignalStrength;
        m_error = m_fmTunerUtility->GetMaxSignalStrength(maxSignalStrength);

        if (m_error == KErrNone) {
            m_error = m_fmTunerUtility->GetSignalStrength(currentSignalStrength);
            if (m_error == KErrNone) {
				if (currentSignalStrength == 0 || maxSignalStrength == 0) {
					return currentSignalStrength;
				}
                m_signal = ((TInt64)currentSignalStrength) * 100 / maxSignalStrength;
            }
        }
    }
    return m_signal;
}

int S60RadioTunerControl::volume() const
{
    return m_vol;
}

void S60RadioTunerControl::setVolume(int volume)
{
	if (m_playerUtility) {
		m_vol = volume;
		volume *= m_volMultiplier;
		m_playerUtility->SetVolume(volume);
		emit volumeChanged(m_vol);
	}
}

bool S60RadioTunerControl::isMuted() const
{
    return m_muted;
}

void S60RadioTunerControl::setMuted(bool muted)
{
	if (m_playerUtility) {
		m_muted = muted;
		m_playerUtility->Mute(m_muted);
	}
}

bool S60RadioTunerControl::isSearching() const
{
	return m_scanning;
}

void S60RadioTunerControl::cancelSearch()
{
	m_fmTunerUtility->CancelStationSeek();
	m_scanning = false;
	emit searchingChanged(false);
}

void S60RadioTunerControl::searchForward()
{
	m_fmTunerUtility->StationSeek(true);
	m_scanning = true;
	emit searchingChanged(true);
}

void S60RadioTunerControl::searchBackward()
{
	m_fmTunerUtility->StationSeek(false);
	m_scanning = true;
	emit searchingChanged(true);
}

bool S60RadioTunerControl::isValid() const
{
    return m_available;
}

bool S60RadioTunerControl::initRadio()
{
	m_available = false;
	// create an instance of Radio Utility factory and indicate
	// FM Radio is a primary client
	TRAPD(utilityError,
		m_radioUtility = CRadioUtility::NewL(ETrue);
		// Get a tuner utility
		m_fmTunerUtility = &m_radioUtility->RadioFmTunerUtilityL(*this);
		// we want to listen radio in offline mode too
		m_fmTunerUtility->EnableTunerInOfflineMode(ETrue);
		// Get a player utility
		m_playerUtility = &m_radioUtility->RadioPlayerUtilityL(*this);
	);
	if (utilityError != KErrNone) {
        m_radioError = QRadioTuner::ResourceError;
		return m_available;
	}

	m_tunerControl = false;

	m_available = true;
	return m_available;
}

bool S60RadioTunerControl::isAvailable() const
{
	return m_available;
}

QtMultimediaKit::AvailabilityError S60RadioTunerControl::availabilityError() const
{
	if (m_available)
		return QtMultimediaKit::NoError;
	else
		return QtMultimediaKit::ResourceError;
}

void S60RadioTunerControl::start()
{
	if (!m_tunerControl) {
		m_fmTunerUtility->RequestTunerControl();
		m_apiTunerState = QRadioTuner::ActiveState;
		emit stateChanged(m_apiTunerState);
	} else {
		m_playerUtility->Play();
		m_apiTunerState = QRadioTuner::ActiveState;
		emit stateChanged(m_apiTunerState);
	}

}

void S60RadioTunerControl::stop()
{
	if (m_playerUtility) {
		m_playerUtility->Stop();
		m_apiTunerState = QRadioTuner::StoppedState;
		emit stateChanged(m_apiTunerState);
    }
}

QRadioTuner::Error S60RadioTunerControl::error() const
{
    return m_radioError;
}
QString S60RadioTunerControl::errorString() const
{
	return m_errorString;
}

void S60RadioTunerControl::MrpoStateChange(TPlayerState aState, TInt aError)
{
	if (aError == KErrNone){
		m_radioError = QRadioTuner::NoError;
		if (aState == ERadioPlayerIdle) {
			m_apiTunerState = QRadioTuner::ActiveState;
		} else if (aState == ERadioPlayerPlaying) {
			m_apiTunerState = QRadioTuner::ActiveState;
		}
	}
	emit stateChanged(m_apiTunerState);
}

void S60RadioTunerControl::MrpoVolumeChange(TInt aVolume)
{
	m_vol = aVolume;
    emit volumeChanged(m_vol);
}

void S60RadioTunerControl::MrpoMuteChange(TBool aMute)
{
	m_muted = aMute;
	emit mutedChanged(m_muted);
}

void S60RadioTunerControl::MrpoBalanceChange(TInt aLeftPercentage, TInt aRightPercentage)
{
	// no actions
}

void S60RadioTunerControl::MrftoRequestTunerControlComplete(TInt aError)
{
	if (aError == KErrNone) {
		m_playerUtility->GetMaxVolume(m_maxVolume);
		m_volMultiplier = float(m_maxVolume)/float(100);
		m_radioError = QRadioTuner::NoError;
		m_tunerControl = true;
		m_available = true;
		m_fmTunerUtility->SetFrequency(m_currentFreq);
		m_playerUtility->Play();
		int signal = signalStrength();
		if (m_signal != signal) {
			emit signalStrengthChanged(signal);
			m_signal = signal;
		}

	} else if (aError == KFmRadioErrAntennaNotConnected) {
		m_radioError = QRadioTuner::OpenError;
	} else if (aError == KErrAlreadyExists){
		m_radioError = QRadioTuner::ResourceError;
	} else if (aError == KFmRadioErrFrequencyOutOfBandRange) {
		m_radioError = QRadioTuner::OutOfRangeError;
	}else{
		m_radioError = QRadioTuner::OpenError;
	}

}

void S60RadioTunerControl::MrftoSetFrequencyRangeComplete(TInt aError)
{
	if (aError == KFmRadioErrFrequencyOutOfBandRange || KFmRadioErrFrequencyNotValid) {
		m_radioError = QRadioTuner::OutOfRangeError;
	} else if (aError == KFmRadioErrHardwareFaulty || KFmRadioErrOfflineMode) {
		m_radioError = QRadioTuner::OpenError;
	}
}

void S60RadioTunerControl::MrftoSetFrequencyComplete(TInt aError)
{
	if (aError == KErrNone) {
		m_radioError = QRadioTuner::NoError;
	} else if (aError == KFmRadioErrFrequencyOutOfBandRange || KFmRadioErrFrequencyNotValid) {
		m_radioError = QRadioTuner::OutOfRangeError;
	} else if (aError == KFmRadioErrHardwareFaulty || KFmRadioErrOfflineMode) {
		m_radioError = QRadioTuner::OpenError;
	}
}

void S60RadioTunerControl::MrftoStationSeekComplete(TInt aError, TInt aFrequency)
{
	m_scanning = false;
	if (aError == KErrNone) {
		m_radioError = QRadioTuner::NoError;
		m_currentFreq = aFrequency;
	} else {
		m_radioError = QRadioTuner::OpenError;
	}
}

void S60RadioTunerControl::MrftoFmTransmitterStatusChange(TBool aActive)
{
	//no actions
}

void S60RadioTunerControl::MrftoAntennaStatusChange(TBool aAttached)
{
	if (aAttached && m_tunerControl) {
		m_playerUtility->Play();
	}
}

void S60RadioTunerControl::MrftoOfflineModeStatusChange(TBool /*aOfflineMode*/)
{

}

void S60RadioTunerControl::MrftoFrequencyRangeChange(TFmRadioFrequencyRange aBand /*, TInt aMinFreq, TInt aMaxFreq*/)
{
	if (aBand == EFmRangeEuroAmerica) {
		setBand(QRadioTuner::FM);
	}
}

void S60RadioTunerControl::MrftoFrequencyChange(TInt aNewFrequency)
{
	m_currentFreq = aNewFrequency;
	emit frequencyChanged(m_currentFreq);

	int signal = signalStrength();
	if (m_signal != signal) {
		emit signalStrengthChanged(signal);
		m_signal = signal;
	}
}

void S60RadioTunerControl::MrftoForcedMonoChange(TBool aForcedMono)
{
	if (aForcedMono) {
		m_stereoMode = QRadioTuner::ForceMono;
	} else {
		m_stereoMode = QRadioTuner::ForceStereo;
	}
	emit stereoStatusChanged(!aForcedMono);
}

void S60RadioTunerControl::MrftoSquelchChange(TBool aSquelch)
{
	// no actions
}
<commit_msg>Fix for bug QTMOBILITY-725<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "s60radiotunercontrol_since32.h"
#include "s60radiotunerservice.h"

#include <QtCore/qdebug.h>
#include <RadioFmTunerUtility.h>

S60RadioTunerControl::S60RadioTunerControl(QObject *parent)
    : QRadioTunerControl(parent)
    , m_error(0)
    , m_radioUtility(NULL)
    , m_fmTunerUtility(NULL)
    , m_playerUtility(NULL)
    , m_audioInitializationComplete(false)
    , m_muted(false)
    , m_isStereo(true)
    , m_vol(100)
    , m_signal(0)
    , m_radioError(QRadioTuner::NoError)
    , m_scanning(false)
    , m_currentBand(QRadioTuner::FM)
    , m_currentFreq(87500000)
    , m_stereoMode(QRadioTuner::Auto)
    , m_apiTunerState(QRadioTuner::StoppedState)
    , m_maxVolume(100)
{
    initRadio();
}

S60RadioTunerControl::~S60RadioTunerControl()
{
	if (m_fmTunerUtility) {
		m_fmTunerUtility->Close();
	}

	if(m_playerUtility) {
		m_playerUtility->Close();
	}

	delete m_radioUtility;
}

QRadioTuner::State S60RadioTunerControl::state() const
{
    return m_apiTunerState;
}

QRadioTuner::Band S60RadioTunerControl::band() const
{
    return m_currentBand;
}

bool S60RadioTunerControl::isBandSupported(QRadioTuner::Band b) const
{
	if(b == QRadioTuner::FM)
		return true;
	else if(b == QRadioTuner::LW)
		return false;
	else if(b == QRadioTuner::AM)
		return true;
	else if(b == QRadioTuner::SW)
		return false;
	else
		return false;
}

void S60RadioTunerControl::setBand(QRadioTuner::Band b)
{
    QRadioTuner::Band tempBand = b;
    if (tempBand != m_currentBand) {
        m_currentBand = b;
        emit bandChanged(m_currentBand);
    }
}

int S60RadioTunerControl::frequency() const
{
    return m_currentFreq;
}

void S60RadioTunerControl::setFrequency(int frequency)
{
	m_currentFreq = frequency;
	m_fmTunerUtility->SetFrequency(m_currentFreq);
}
int S60RadioTunerControl::frequencyStep(QRadioTuner::Band b) const
{
    int step = 0;
    if(b == QRadioTuner::FM)
        step = 100000; // 100kHz steps
    else if(b == QRadioTuner::LW)
        step = 1000; // 1kHz steps
    else if(b == QRadioTuner::AM)
        step = 1000; // 1kHz steps
    else if(b == QRadioTuner::SW)
        step = 500; // 500Hz steps

    return step;
}

QPair<int,int> S60RadioTunerControl::frequencyRange(QRadioTuner::Band band) const
{
    int bottomFreq;
    int topFreq;

    int bandError = KErrNone;
    TFmRadioFrequencyRange range;

    if (m_fmTunerUtility) {
        bandError = m_fmTunerUtility->GetFrequencyRange(range, bottomFreq, topFreq);
    }
    if (!bandError) {
        return qMakePair<int,int>(bottomFreq, topFreq);
    }

    return qMakePair<int,int>(0,0);
}

bool S60RadioTunerControl::isStereo() const
{
    return m_isStereo;
}

QRadioTuner::StereoMode S60RadioTunerControl::stereoMode() const
{
    return m_stereoMode;
}

void S60RadioTunerControl::setStereoMode(QRadioTuner::StereoMode mode)
{
	if (m_fmTunerUtility) {
	    if (QRadioTuner::ForceMono == mode) {
	    	m_fmTunerUtility->ForceMonoReception(true);
	    	m_stereoMode = QRadioTuner::ForceMono;
			m_isStereo = false;
	    } else {
	    	m_fmTunerUtility->ForceMonoReception(false);
			m_isStereo = true;
			m_stereoMode = QRadioTuner::ForceStereo;
	    }
	}
}

int S60RadioTunerControl::signalStrength() const
{
    // return value is a percentage value
    if (m_fmTunerUtility) {
        TInt maxSignalStrength;
        TInt currentSignalStrength;
        m_error = m_fmTunerUtility->GetMaxSignalStrength(maxSignalStrength);

        if (m_error == KErrNone) {
            m_error = m_fmTunerUtility->GetSignalStrength(currentSignalStrength);
            if (m_error == KErrNone) {
				if (currentSignalStrength == 0 || maxSignalStrength == 0) {
					return currentSignalStrength;
				}
                m_signal = ((TInt64)currentSignalStrength) * 100 / maxSignalStrength;
            }
        }
    }
    return m_signal;
}

int S60RadioTunerControl::volume() const
{
    return m_vol;
}

void S60RadioTunerControl::setVolume(int volume)
{
	if (m_playerUtility) {
		m_vol = volume;
		volume *= m_volMultiplier;
		m_playerUtility->SetVolume(volume);
		emit volumeChanged(m_vol);
	}
}

bool S60RadioTunerControl::isMuted() const
{
    return m_muted;
}

void S60RadioTunerControl::setMuted(bool muted)
{
	if (m_playerUtility) {
		m_muted = muted;
		m_playerUtility->Mute(m_muted);
	}
}

bool S60RadioTunerControl::isSearching() const
{
	return m_scanning;
}

void S60RadioTunerControl::cancelSearch()
{
	m_fmTunerUtility->CancelStationSeek();
	m_scanning = false;
	emit searchingChanged(false);
}

void S60RadioTunerControl::searchForward()
{
	m_fmTunerUtility->StationSeek(true);
	m_scanning = true;
	emit searchingChanged(true);
}

void S60RadioTunerControl::searchBackward()
{
	m_fmTunerUtility->StationSeek(false);
	m_scanning = true;
	emit searchingChanged(true);
}

bool S60RadioTunerControl::isValid() const
{
    return m_available;
}

bool S60RadioTunerControl::initRadio()
{
	m_available = false;
	// create an instance of Radio Utility factory and indicate
	// FM Radio is a primary client
	TRAPD(utilityError,
		m_radioUtility = CRadioUtility::NewL(ETrue);
		// Get a tuner utility
		m_fmTunerUtility = &m_radioUtility->RadioFmTunerUtilityL(*this);
		// we want to listen radio in offline mode too
		m_fmTunerUtility->EnableTunerInOfflineMode(ETrue);
		// Get a player utility
		m_playerUtility = &m_radioUtility->RadioPlayerUtilityL(*this);
	);
	if (utilityError != KErrNone) {
        m_radioError = QRadioTuner::ResourceError;
		return m_available;
	}

	m_tunerControl = false;

	m_available = true;
	return m_available;
}

bool S60RadioTunerControl::isAvailable() const
{
	return m_available;
}

QtMultimediaKit::AvailabilityError S60RadioTunerControl::availabilityError() const
{
	if (m_available)
		return QtMultimediaKit::NoError;
	else
		return QtMultimediaKit::ResourceError;
}

void S60RadioTunerControl::start()
{
	if (!m_tunerControl) {
		m_fmTunerUtility->RequestTunerControl();
		m_apiTunerState = QRadioTuner::ActiveState;
		emit stateChanged(m_apiTunerState);
	} else {
		m_playerUtility->Play();
		m_apiTunerState = QRadioTuner::ActiveState;
		emit stateChanged(m_apiTunerState);
	}

}

void S60RadioTunerControl::stop()
{
	if (m_playerUtility) {
		m_playerUtility->Stop();
		m_apiTunerState = QRadioTuner::StoppedState;
		emit stateChanged(m_apiTunerState);
    }
}

QRadioTuner::Error S60RadioTunerControl::error() const
{
    return m_radioError;
}
QString S60RadioTunerControl::errorString() const
{
	return m_errorString;
}

void S60RadioTunerControl::MrpoStateChange(TPlayerState aState, TInt aError)
{
	if (aError == KErrNone){
		m_radioError = QRadioTuner::NoError;
		if (aState == ERadioPlayerIdle) {
			m_apiTunerState = QRadioTuner::ActiveState;
		} else if (aState == ERadioPlayerPlaying) {
			m_apiTunerState = QRadioTuner::ActiveState;
		}
	}
	else {
        m_apiTunerState = QRadioTuner::StoppedState;
    }
	emit stateChanged(m_apiTunerState);
}

void S60RadioTunerControl::MrpoVolumeChange(TInt aVolume)
{
	m_vol = aVolume;
    emit volumeChanged(m_vol);
}

void S60RadioTunerControl::MrpoMuteChange(TBool aMute)
{
	m_muted = aMute;
	emit mutedChanged(m_muted);
}

void S60RadioTunerControl::MrpoBalanceChange(TInt aLeftPercentage, TInt aRightPercentage)
{
	// no actions
}

void S60RadioTunerControl::MrftoRequestTunerControlComplete(TInt aError)
{
	if (aError == KErrNone) {
		m_playerUtility->GetMaxVolume(m_maxVolume);
		m_volMultiplier = float(m_maxVolume)/float(100);
		m_radioError = QRadioTuner::NoError;
		m_tunerControl = true;
		m_available = true;
		m_fmTunerUtility->SetFrequency(m_currentFreq);
		m_playerUtility->Play();
		int signal = signalStrength();
		if (m_signal != signal) {
			emit signalStrengthChanged(signal);
			m_signal = signal;
		}

	} else if (aError == KFmRadioErrAntennaNotConnected) {
		m_radioError = QRadioTuner::OpenError;
	} else if (aError == KErrAlreadyExists){
		m_radioError = QRadioTuner::ResourceError;
	} else if (aError == KFmRadioErrFrequencyOutOfBandRange) {
		m_radioError = QRadioTuner::OutOfRangeError;
	}else{
		m_radioError = QRadioTuner::OpenError;
	}

}

void S60RadioTunerControl::MrftoSetFrequencyRangeComplete(TInt aError)
{
	if (aError == KFmRadioErrFrequencyOutOfBandRange || KFmRadioErrFrequencyNotValid) {
		m_radioError = QRadioTuner::OutOfRangeError;
	} else if (aError == KFmRadioErrHardwareFaulty || KFmRadioErrOfflineMode) {
		m_radioError = QRadioTuner::OpenError;
	}
}

void S60RadioTunerControl::MrftoSetFrequencyComplete(TInt aError)
{
	if (aError == KErrNone) {
		m_radioError = QRadioTuner::NoError;
	} else if (aError == KFmRadioErrFrequencyOutOfBandRange || KFmRadioErrFrequencyNotValid) {
		m_radioError = QRadioTuner::OutOfRangeError;
	} else if (aError == KFmRadioErrHardwareFaulty || KFmRadioErrOfflineMode) {
		m_radioError = QRadioTuner::OpenError;
	}
}

void S60RadioTunerControl::MrftoStationSeekComplete(TInt aError, TInt aFrequency)
{
	m_scanning = false;
	if (aError == KErrNone) {
		m_radioError = QRadioTuner::NoError;
		m_currentFreq = aFrequency;
	} else {
		m_radioError = QRadioTuner::OpenError;
	}
}

void S60RadioTunerControl::MrftoFmTransmitterStatusChange(TBool aActive)
{
	//no actions
}

void S60RadioTunerControl::MrftoAntennaStatusChange(TBool aAttached)
{
	if (aAttached && m_tunerControl) {
		m_playerUtility->Play();
	}
}

void S60RadioTunerControl::MrftoOfflineModeStatusChange(TBool /*aOfflineMode*/)
{

}

void S60RadioTunerControl::MrftoFrequencyRangeChange(TFmRadioFrequencyRange aBand /*, TInt aMinFreq, TInt aMaxFreq*/)
{
	if (aBand == EFmRangeEuroAmerica) {
		setBand(QRadioTuner::FM);
	}
}

void S60RadioTunerControl::MrftoFrequencyChange(TInt aNewFrequency)
{
	m_currentFreq = aNewFrequency;
	emit frequencyChanged(m_currentFreq);

	int signal = signalStrength();
	if (m_signal != signal) {
		emit signalStrengthChanged(signal);
		m_signal = signal;
	}
}

void S60RadioTunerControl::MrftoForcedMonoChange(TBool aForcedMono)
{
	if (aForcedMono) {
		m_stereoMode = QRadioTuner::ForceMono;
	} else {
		m_stereoMode = QRadioTuner::ForceStereo;
	}
	emit stereoStatusChanged(!aForcedMono);
}

void S60RadioTunerControl::MrftoSquelchChange(TBool aSquelch)
{
	// no actions
}
<|endoftext|>


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

#include "app/atom_main_delegate.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "browser/atom_browser_client.h"
#include "content/public/common/content_switches.h"
#include "renderer/atom_renderer_client.h"
#include "ui/base/resource/resource_bundle.h"
#include "base/path_service.h"

namespace atom {

AtomMainDelegate::AtomMainDelegate() {
}

AtomMainDelegate::~AtomMainDelegate() {
}

bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
  // Disable logging out to debug.log on Windows
#if defined(OS_WIN)
  logging::LoggingSettings settings;
#if defined(DEBUG)
  settings.logging_dest = logging::LOG_TO_ALL;
  settings.log_file = L"debug.log";
  settings.lock_log = logging::LOCK_LOG_FILE;
  settings.delete_old = logging::DELETE_OLD_LOG_FILE;
#else
  settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif
  settings.dcheck_state =
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
  logging::InitLogging(settings);
#endif  // defined(OS_WIN)

  // Logging with pid and timestamp.
  logging::SetLogItems(true, false, true, false);

  return brightray::MainDelegate::BasicStartupComplete(exit_code);
}

void AtomMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
  OverrideChildProcessPath();
  OverrideFrameworkBundlePath();
#endif
  InitializeResourceBundle();

  CommandLine* command_line = CommandLine::ForCurrentProcess();

  // Disable renderer sandbox for most of node's functions.
  command_line->AppendSwitch(switches::kNoSandbox);

  // Disable accelerated compositing since it caused a lot of troubles (black
  // devtools, screen flashes) and needed lots of effort to make it right.
  command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);

  // Add a flag to mark the end of switches added by atom-shell.
  command_line->AppendSwitch("no-more-switches");
}

void AtomMainDelegate::InitializeResourceBundle() {
  base::FilePath path;
#if defined(OS_MACOSX)
  path = GetResourcesPakFilePath();
#else
  base::FilePath pak_dir;
  PathService::Get(base::DIR_MODULE, &pak_dir);
  path = pak_dir.Append(FILE_PATH_LITERAL("content_shell.pak"));
#endif

  ui::ResourceBundle::InitSharedInstanceWithPakPath(path);
}

content::ContentBrowserClient* AtomMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new AtomBrowserClient);
  return browser_client_.get();
}

content::ContentRendererClient*
    AtomMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new AtomRendererClient);
  return renderer_client_.get();
}

}  // namespace atom
<commit_msg>Don't append duplicate arguments to renderer process.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/atom_main_delegate.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "browser/atom_browser_client.h"
#include "content/public/common/content_switches.h"
#include "renderer/atom_renderer_client.h"
#include "ui/base/resource/resource_bundle.h"
#include "base/path_service.h"

namespace atom {

AtomMainDelegate::AtomMainDelegate() {
}

AtomMainDelegate::~AtomMainDelegate() {
}

bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
  // Disable logging out to debug.log on Windows
#if defined(OS_WIN)
  logging::LoggingSettings settings;
#if defined(DEBUG)
  settings.logging_dest = logging::LOG_TO_ALL;
  settings.log_file = L"debug.log";
  settings.lock_log = logging::LOCK_LOG_FILE;
  settings.delete_old = logging::DELETE_OLD_LOG_FILE;
#else
  settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif
  settings.dcheck_state =
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
  logging::InitLogging(settings);
#endif  // defined(OS_WIN)

  // Logging with pid and timestamp.
  logging::SetLogItems(true, false, true, false);

  return brightray::MainDelegate::BasicStartupComplete(exit_code);
}

void AtomMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
  OverrideChildProcessPath();
  OverrideFrameworkBundlePath();
#endif
  InitializeResourceBundle();

  CommandLine* command_line = CommandLine::ForCurrentProcess();
  std::string process_type = command_line->GetSwitchValueASCII(
      switches::kProcessType);

  // Don't append arguments for renderer process.
  if (process_type == switches::kRendererProcess)
    return;

  // Disable renderer sandbox for most of node's functions.
  command_line->AppendSwitch(switches::kNoSandbox);

  // Disable accelerated compositing since it caused a lot of troubles (black
  // devtools, screen flashes) and needed lots of effort to make it right.
  command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);

  // Add a flag to mark the end of switches added by atom-shell.
  command_line->AppendSwitch("no-more-switches");
}

void AtomMainDelegate::InitializeResourceBundle() {
  base::FilePath path;
#if defined(OS_MACOSX)
  path = GetResourcesPakFilePath();
#else
  base::FilePath pak_dir;
  PathService::Get(base::DIR_MODULE, &pak_dir);
  path = pak_dir.Append(FILE_PATH_LITERAL("content_shell.pak"));
#endif

  ui::ResourceBundle::InitSharedInstanceWithPakPath(path);
}

content::ContentBrowserClient* AtomMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new AtomBrowserClient);
  return browser_client_.get();
}

content::ContentRendererClient*
    AtomMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new AtomRendererClient);
  return renderer_client_.get();
}

}  // namespace atom
<|endoftext|>