<commit_before>/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <QDomDocument>
#include <QDomElement>
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/correlation/correlator.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"

using namespace com::centreon::broker;

CCB_BEGIN()
namespace correlation {
  // Load count.
  static unsigned int instances(0);

  // Correlation object.
  static misc::shared_ptr<multiplexing::hooker> obj;

  /**
   *  Module deinitialization routine.
   */
  void module_deinit() {
    // Decrement instance number.
    if (!--correlation::instances) {
      // Unregister correlation object.
      multiplexing::engine::instance().unhook(*correlation::obj);
      correlation::obj.clear();
    }
    return ;
  }

  /**
   *  Module initialization routine.
   *
   *  @param[in] arg Configuration argument.
   */
  void module_init(void const* arg) {
    // Increment instance number.
    if (!correlation::instances++) {
      // Check that correlation is enabled.
      config::state const& cfg(*static_cast<config::state const*>(arg));
      bool loaded(false);
      QMap<QString, QString>::const_iterator
        it(cfg.params().find("correlation"));
      if (it != cfg.params().end()) {
        // Parameters.
        QString correlation_file;
        QString retention_file;

        // Parse XML.
        QDomDocument d;
        if (d.setContent(it.value())) {
          // Browse first-level elements.
          QDomElement root(d.documentElement());
          QDomNodeList level1(root.childNodes());
          for (int i = 0, len = level1.size(); i < len; ++i) {
            QDomElement elem(level1.item(i).toElement());
            if (!elem.isNull()) {
              QString name(elem.tagName());
              if (name == "file")
                correlation_file = elem.text();
              else if (name == "retention")
                retention_file = elem.text();
            }
          }
        }

        // File exists, load it.
        if (!correlation_file.isEmpty()) {
          // Create and register correlation object.
          misc::shared_ptr<correlation::correlator>
            crltr(new correlation::correlator);
          try {
            crltr->load(correlation_file, retention_file);
            correlation::obj = crltr.staticCast<multiplexing::hooker>();
            multiplexing::engine::instance().hook(*correlation::obj);
            loaded = true;
          }
          catch (std::exception const& e) {
            logging::config(logging::high) << "correlation: " \
              "configuration loading error: " << e.what();
          }
          catch (...) {
            logging::config(logging::high) << "correlation: " \
              "configuration loading error";
          }
        }
      }
      if (!loaded)
        logging::config(logging::high) << "correlation: invalid " \
          "correlation configuration, correlation engine is NOT loaded";
    }
    return ;
  }
}
CCB_END()

extern "C" {
  /**
   *  Module deinitialization routine.
   */
  void broker_module_deinit() {
    correlation::module_deinit();
    return ;
  }

  /**
   *  Module initialization routine redirector.
   *
   *  @param[in] arg Configuration argument.
   */
  void broker_module_init(void const* arg) {
    correlation::module_init(arg);
    return ;
  }

  /**
   *  Module update routine.
   *
   *  @param[in] arg Configuration argument.
   */
  void broker_module_update(void const* arg) {
    correlation::module_deinit();
    correlation::module_init(arg);
    return ;
  }
}
<commit_msg>correlation: disable and then reenable the correlation engine during a configuration update request. This fixes #4272.<commit_after>/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <QDomDocument>
#include <QDomElement>
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/correlation/correlator.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"

using namespace com::centreon::broker;

CCB_BEGIN()
namespace correlation {
  // Load count.
  static unsigned int instances(0);

  // Correlation object.
  static misc::shared_ptr<multiplexing::hooker> obj;

  /**
   *  Module deinitialization routine.
   */
  void module_deinit() {
    // Decrement instance number.
    if (!--correlation::instances) {
      // Unregister correlation object.
      multiplexing::engine::instance().unhook(*correlation::obj);
      correlation::obj.clear();
    }
    return ;
  }

  /**
   *  Module initialization routine.
   *
   *  @param[in] arg Configuration argument.
   */
  void module_init(void const* arg) {
    // Increment instance number.
    if (!correlation::instances++) {
      // Check that correlation is enabled.
      config::state const& cfg(*static_cast<config::state const*>(arg));
      bool loaded(false);
      QMap<QString, QString>::const_iterator
        it(cfg.params().find("correlation"));
      if (it != cfg.params().end()) {
        // Parameters.
        QString correlation_file;
        QString retention_file;

        // Parse XML.
        QDomDocument d;
        if (d.setContent(it.value())) {
          // Browse first-level elements.
          QDomElement root(d.documentElement());
          QDomNodeList level1(root.childNodes());
          for (int i = 0, len = level1.size(); i < len; ++i) {
            QDomElement elem(level1.item(i).toElement());
            if (!elem.isNull()) {
              QString name(elem.tagName());
              if (name == "file")
                correlation_file = elem.text();
              else if (name == "retention")
                retention_file = elem.text();
            }
          }
        }

        // File exists, load it.
        if (!correlation_file.isEmpty()) {
          // Create and register correlation object.
          misc::shared_ptr<correlation::correlator>
            crltr(new correlation::correlator);
          try {
            crltr->load(correlation_file, retention_file);
            correlation::obj = crltr.staticCast<multiplexing::hooker>();
            multiplexing::engine::instance().hook(*correlation::obj);
            loaded = true;
          }
          catch (std::exception const& e) {
            logging::config(logging::high) << "correlation: " \
              "configuration loading error: " << e.what();
          }
          catch (...) {
            logging::config(logging::high) << "correlation: " \
              "configuration loading error";
          }
        }
      }
      if (!loaded)
        logging::config(logging::high) << "correlation: invalid " \
          "correlation configuration, correlation engine is NOT loaded";
    }
    return ;
  }
}
CCB_END()

extern "C" {
  /**
   *  Module deinitialization routine.
   */
  void broker_module_deinit() {
    correlation::module_deinit();
    return ;
  }

  /**
   *  Module initialization routine redirector.
   *
   *  @param[in] arg Configuration argument.
   */
  void broker_module_init(void const* arg) {
    correlation::module_init(arg);
    return ;
  }

  /**
   *  Module update routine.
   *
   *  @param[in] arg Configuration argument.
   */
  void broker_module_update(void const* arg) {
    if (!correlation::obj.isNull())
      correlation::obj->stopping();
    correlation::module_deinit();
    correlation::module_init(arg);
    correlation::obj->starting();
    return ;
  }
}
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-

/**
 *
 * @ingroup rd_programs
 * \defgroup robotDevastation robotDevastation
 *
 * @brief The Robot Devastation PC client. Creates an instance of the RobotDevastation class.
 *
 * @section legal Legal
 *
 * Copyright: ASROB 2012-2014 (C) Robotics Society of the Universidad Carlos III de Madrid (http://asrob.uc3m.es)
 * Robot Devastation project
 *
 * Authors:
 * David Estevez (2014-present),
 * Juan G. Victores (2012-present),
 * Santiago Morante (2012-2014).
 *
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see $RD_ROOT/main/doc/LGPL.TXT
 *
 * @section installation Installation
 *
 * The module is compiled when ENABLE_robotDevastation is activated (default: ON). For further
 * installation steps refer to your own system installation guidelines.
 *
 * @section running Running (assuming correct installation, see previous section)
 *
 * It should be straightforward to run the default test mode. Just click on the icon or open a terminal and write:
 *
\verbatim
rdClient
\endverbatim
 *
 * @section interfacing Interfacing with robotDevastation
 *
 * Press 'space' to shoot!
 *
 * @section modify Modify
 *
 * This file can be edited at
 * $RD_ROOT/src/programs/robotDevastation/main.cpp
 *
 */

#include <iostream>

#include <yarp/os/Network.h>

#include "RdUtils.hpp"
#include "RobotDevastation.hpp"

int main(int argc, char *argv[]) {

    printf("--------------------------------------------------------------\n");
    printf("Robot Devastation @ ASROB 2014 (C) Robotics Society of the Universidad Carlos III de Madrid\n");
    printf("Welcome to Robot Devastation v0.2, developed by David Estevez and Juan G Victores.\n");
    printf("Based on Robot Devastation v0.1, developed by Santiago Morante and Juan G Victores.\n");
    printf(GREEN);
    printf(" ____       _           _   ____                      _        _   _             \n");
    printf("|  _ \\ ___ | |__   ___ | |_|  _ \\  _____   ____ _ ___| |_ __ _| |_(_) ___  _ __  \n");
    printf("| |_) / _ \\| '_ \\ / _ \\| __| | | |/ _ \\ \\ / / _` / __| __/ _` | __| |/ _ \\| '_ \\ \n");
    printf("|  _ < (_) | |_) | (_) | |_| |_| |  __/\\ V / (_| \\__ \\ || (_| | |_| | (_) | | | |\n");
    printf("|_| \\_\\___/|_.__/ \\___/ \\__|____/ \\___| \\_/ \\__,_|___/\\__\\__,_|\\__|_|\\___/|_| |_|\n");
    printf(RESET);
    printf("\n");
    printf("Fire with 'space'. Reload with 'r'. Move with 'Left, Up, Down, Right'. Run \"robotDevastation --help\" for help.\n");
    printf("For a full description, please visit http://asrob.uc3m.es/rddoc/group__robotDevastation.html.\n");
    printf("--------------------------------------------------------------\n");

    yarp::os::ResourceFinder rf;
    rf.setVerbose(false);
    rf.setDefaultContext("robotDevastation");
    rf.setDefaultConfigFile("robotDevastation.ini");
    rf.configure(argc, argv);

    if(rf.check("help"))
    {
        printf("RobotDevastation optional parameters:\n");
        printf("\t--help (this help)\t--from [file.ini]\t--context [path]\n");
        printf("\t--mockupRobotManager  //-- Fake robot motors\n");
        printf("\t--mockupImageManager  //-- Fake robot camera\n");
        printf("\t--yarpLocalImageManager  //-- Local webcam as camera\n");
        return 0;
    }

    rd::RobotDevastation robotDevastation;
    return robotDevastation.runModule(rf);  //-- Internally calls rd::RobotDevastation::configure(yarp::os::ResourceFinder &rf)

}

<commit_msg>document --fullscreen parameter (experimental)<commit_after>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-

/**
 *
 * @ingroup rd_programs
 * \defgroup robotDevastation robotDevastation
 *
 * @brief The Robot Devastation PC client. Creates an instance of the RobotDevastation class.
 *
 * @section legal Legal
 *
 * Copyright: ASROB 2012-2014 (C) Robotics Society of the Universidad Carlos III de Madrid (http://asrob.uc3m.es)
 * Robot Devastation project
 *
 * Authors:
 * David Estevez (2014-present),
 * Juan G. Victores (2012-present),
 * Santiago Morante (2012-2014).
 *
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see $RD_ROOT/main/doc/LGPL.TXT
 *
 * @section installation Installation
 *
 * The module is compiled when ENABLE_robotDevastation is activated (default: ON). For further
 * installation steps refer to your own system installation guidelines.
 *
 * @section running Running (assuming correct installation, see previous section)
 *
 * It should be straightforward to run the default test mode. Just click on the icon or open a terminal and write:
 *
\verbatim
rdClient
\endverbatim
 *
 * @section interfacing Interfacing with robotDevastation
 *
 * Press 'space' to shoot!
 *
 * @section modify Modify
 *
 * This file can be edited at
 * $RD_ROOT/src/programs/robotDevastation/main.cpp
 *
 */

#include <iostream>

#include <yarp/os/Network.h>

#include "RdUtils.hpp"
#include "RobotDevastation.hpp"

int main(int argc, char *argv[]) {

    printf("--------------------------------------------------------------\n");
    printf("Robot Devastation @ ASROB 2014 (C) Robotics Society of the Universidad Carlos III de Madrid\n");
    printf("Welcome to Robot Devastation v0.2, developed by David Estevez and Juan G Victores.\n");
    printf("Based on Robot Devastation v0.1, developed by Santiago Morante and Juan G Victores.\n");
    printf(GREEN);
    printf(" ____       _           _   ____                      _        _   _             \n");
    printf("|  _ \\ ___ | |__   ___ | |_|  _ \\  _____   ____ _ ___| |_ __ _| |_(_) ___  _ __  \n");
    printf("| |_) / _ \\| '_ \\ / _ \\| __| | | |/ _ \\ \\ / / _` / __| __/ _` | __| |/ _ \\| '_ \\ \n");
    printf("|  _ < (_) | |_) | (_) | |_| |_| |  __/\\ V / (_| \\__ \\ || (_| | |_| | (_) | | | |\n");
    printf("|_| \\_\\___/|_.__/ \\___/ \\__|____/ \\___| \\_/ \\__,_|___/\\__\\__,_|\\__|_|\\___/|_| |_|\n");
    printf(RESET);
    printf("\n");
    printf("Fire with 'space'. Reload with 'r'. Move with 'Left, Up, Down, Right'. Run \"robotDevastation --help\" for help.\n");
    printf("For a full description, please visit http://asrob.uc3m.es/rddoc/group__robotDevastation.html.\n");
    printf("--------------------------------------------------------------\n");

    yarp::os::ResourceFinder rf;
    rf.setVerbose(false);
    rf.setDefaultContext("robotDevastation");
    rf.setDefaultConfigFile("robotDevastation.ini");
    rf.configure(argc, argv);

    if(rf.check("help"))
    {
        printf("RobotDevastation optional parameters:\n");
        printf("\t--help (this help)\t--from [file.ini]\t--context [path]\n");
        printf("\t--mockupRobotManager  //-- Fake robot motors\n");
        printf("\t--mockupImageManager  //-- Fake robot camera\n");
        printf("\t--yarpLocalImageManager  //-- Local webcam as camera\n");
        printf("\t--fullscreen //-- Fullscreen mode (experimental)\n");
        return 0;
    }

    rd::RobotDevastation robotDevastation;
    return robotDevastation.runModule(rf);  //-- Internally calls rd::RobotDevastation::configure(yarp::os::ResourceFinder &rf)

}

<|endoftext|>


<commit_before>/*=============================================================================
	Copyright (c) 2012-2013 Richard Otis

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

// N-Dimensional uniform grid

#ifndef INCLUDED_NDGRID
#define INCLUDED_NDGRID

#include <vector>
#include <utility>

struct NDGrid {
	template <typename Func> static void sample(
			const std::vector<std::pair<double,double> > &extents,
			const double grid_points_per_major_axis,
			const Func &func,
			std::vector<double>& address) {
		if (address.size() == extents.size()) {
			// terminating condition; address is complete
			func(address);
		}
		else {
			const double max_extent = extents[address.size()].second;
			const double min_extent = extents[address.size()].first;
			double step = (max_extent - min_extent) / grid_points_per_major_axis;
			for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
				double location = step*j + min_extent;
				address.push_back(location);
				// recursive step
				NDGrid::sample(extents, grid_points_per_major_axis, func, address);
				address.pop_back(); // remove the element we just added (this way avoids copying)
			}
		}
	}
	template <typename Func> static inline void sample(
			const std::vector<std::pair<double,double> > &extents,
			const double grid_points_per_major_axis,
			const Func &func) {
		std::vector<double> address;
		NDGrid::sample(extents, grid_points_per_major_axis, func, address);
	}
	template <typename Func> static void sample(
			const double min_extent,
			const double max_extent,
			const std::size_t dimension,
			const double grid_points_per_major_axis,
			const Func &func,
			std::vector<double>& address) {
		if (address.size() == dimension) {
			// terminating condition; address is complete
			func(address);
		}
		else {
			double step = (max_extent - min_extent) / grid_points_per_major_axis;
			for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
				double location = step*j + min_extent;
				address.push_back(location);
				// recursive step
				NDGrid::sample(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
				address.pop_back(); // remove the element we just added (this way avoids copying)
			}
		}
	}
	template <typename Func> static inline void sample(
			const double min_extent,
			const double max_extent,
			const std::size_t dimension,
			const double grid_points_per_major_axis,
			const Func &func) {
		std::vector<double> address;
		NDGrid::sample(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
	}
};

#endif
<commit_msg>Prevent duplicate point generation for fixed variables<commit_after>/*=============================================================================
	Copyright (c) 2012-2013 Richard Otis

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

// N-Dimensional uniform grid

#ifndef INCLUDED_NDGRID
#define INCLUDED_NDGRID

#include <vector>
#include <utility>

struct NDGrid {
	template <typename Func> static void sample(
			const std::vector<std::pair<double,double> > &extents,
			const double grid_points_per_major_axis,
			const Func &func,
			std::vector<double>& address) {
		if (address.size() == extents.size()) {
			// terminating condition; address is complete
			func(address);
		}
		else {
			const double max_extent = extents[address.size()].second;
			const double min_extent = extents[address.size()].first;
			double step = (max_extent - min_extent) / grid_points_per_major_axis;
			for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
				double location = step*j + min_extent;
				address.push_back(location);
				// recursive step
				NDGrid::sample(extents, grid_points_per_major_axis, func, address);
				address.pop_back(); // remove the element we just added (this way avoids copying)
				if (step == 0) break; // don't generate duplicate points
			}
		}
	}
	template <typename Func> static inline void sample(
			const std::vector<std::pair<double,double> > &extents,
			const double grid_points_per_major_axis,
			const Func &func) {
		std::vector<double> address;
		NDGrid::sample(extents, grid_points_per_major_axis, func, address);
	}
	template <typename Func> static void sample(
			const double min_extent,
			const double max_extent,
			const std::size_t dimension,
			const double grid_points_per_major_axis,
			const Func &func,
			std::vector<double>& address) {
		if (address.size() == dimension) {
			// terminating condition; address is complete
			func(address);
		}
		else {
			double step = (max_extent - min_extent) / grid_points_per_major_axis;
			for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
				double location = step*j + min_extent;
				address.push_back(location);
				// recursive step
				NDGrid::sample(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
				address.pop_back(); // remove the element we just added (this way avoids copying)
				if (step == 0) break; // don't generate duplicate points
			}
		}
	}
	template <typename Func> static inline void sample(
			const double min_extent,
			const double max_extent,
			const std::size_t dimension,
			const double grid_points_per_major_axis,
			const Func &func) {
		std::vector<double> address;
		NDGrid::sample(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
	}
};

#endif
<|endoftext|>


<commit_before><commit_msg>refactor(map): changing map.at() by map.find()<commit_after><|endoftext|>


<commit_before>#pragma once
#include <mutex>

namespace Doremi
{
    namespace Utilities
    {
        namespace IO
        {
            class Mutex : public std::mutex
            {
            public:
                /**
                Returns true if successfully initialized
                */
                virtual bool Initialize(const std::string& p_name) = 0;

                virtual void lock() = 0;

                virtual bool try_lock() = 0;

                virtual bool try_lock(const uint32_t& p_timeout) = 0;

                virtual void unlock() = 0;
            };
        }
    }
}<commit_msg>Added ~virtual destructor to Mutex interface<commit_after>#pragma once
#include <mutex>

namespace Doremi
{
    namespace Utilities
    {
        namespace IO
        {
            class Mutex : public std::mutex
            {
            public:
                virtual ~Mutex() {}

                /**
                Returns true if successfully initialized
                */
                virtual bool Initialize(const std::string& p_name) = 0;

                virtual void lock() = 0;

                virtual bool try_lock() = 0;

                virtual bool try_lock(const uint32_t& p_timeout) = 0;

                virtual void unlock() = 0;
            };
        }
    }
}<|endoftext|>


<commit_before>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "utilities.h"

#include <stdexcept>
#include <iomanip>
#include <sstream>

namespace libcellml {

bool convertToDouble(const std::string &candidate, double *value)
{
    bool canConvert = false;
    // Try to convert the input string to double.
    try
    {
        double tmp = std::stod(candidate);
        if (value) {
            *value = tmp;
        }
        canConvert = true;
    } catch (...) {
        canConvert = false;
    }

    return canConvert;
}

bool hasNonWhitespaceCharacters(const std::string &input)
{
    return input.find_first_not_of(" \t\n\v\f\r") != input.npos;;
}

std::string convertDoubleToString(double value)
{
    std::ostringstream strs;
    strs << std::setprecision(std::numeric_limits<double>::digits10) << value;
    return strs.str();
}

}
<commit_msg>Add limits header include.<commit_after>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "utilities.h"

#include <stdexcept>
#include <iomanip>
#include <limits>
#include <sstream>

namespace libcellml {

bool convertToDouble(const std::string &candidate, double *value)
{
    bool canConvert = false;
    // Try to convert the input string to double.
    try
    {
        double tmp = std::stod(candidate);
        if (value) {
            *value = tmp;
        }
        canConvert = true;
    } catch (...) {
        canConvert = false;
    }

    return canConvert;
}

bool hasNonWhitespaceCharacters(const std::string &input)
{
    return input.find_first_not_of(" \t\n\v\f\r") != input.npos;;
}

std::string convertDoubleToString(double value)
{
    std::ostringstream strs;
    strs << std::setprecision(std::numeric_limits<double>::digits10) << value;
    return strs.str();
}

}
<|endoftext|>


<commit_before><commit_msg>MAVLink FTP: Update implementation according to updates specs The MAVLink specs for CreateFile in MAVLink FTP were updated on Dec 23, 2020 (today) with a behavior change to truncate a file if it already existed, following the UNIX standard behavior: https://pubs.opengroup.org/onlinepubs/9699919799/functions/creat.html. This change is tracking that spec change. While it is a functional change, the limited usage of the FTP protocol and the fact that implementations should not rely on error states to determine wether to truncate a file or not makes this a viable change.<commit_after><|endoftext|>


<commit_before>// Copyright 2013 The Flutter 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 <chrono>
#include <thread>

#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/thread.h"
#include "flutter/testing/testing.h"

namespace fml {

TEST(CountDownLatchTest, CanWaitOnZero) {
  CountDownLatch latch(0);
  latch.Wait();
}

TEST(CountDownLatchTest, CanWait) {
  fml::Thread thread("test_thread");
  const size_t count = 100;
  size_t current_count = 0;
  CountDownLatch latch(count);
  auto decrement_latch_on_thread = [runner = thread.GetTaskRunner(), &latch,
                                    &current_count]() {
    runner->PostTask([&latch, &current_count]() {
      std::this_thread::sleep_for(std::chrono::microseconds(100));
      current_count++;
      latch.CountDown();
    });
  };
  for (size_t i = 0; i < count; ++i) {
    decrement_latch_on_thread();
  }
  latch.Wait();
  ASSERT_EQ(current_count, count);
}

}  // namespace fml
<commit_msg>Disable flakey CountDownLatchTest.CanWait unit test on Fuchsia (#15982)<commit_after>// Copyright 2013 The Flutter 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 <chrono>
#include <thread>

#include "flutter/fml/build_config.h"
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/thread.h"
#include "flutter/testing/testing.h"

namespace fml {

TEST(CountDownLatchTest, CanWaitOnZero) {
  CountDownLatch latch(0);
  latch.Wait();
}

#if OS_FUCHSIA
#define CanWait DISABLED_CanWait
#else
#define CanWait CanWait
#endif
TEST(CountDownLatchTest, CanWait) {
  fml::Thread thread("test_thread");
  const size_t count = 100;
  size_t current_count = 0;
  CountDownLatch latch(count);
  auto decrement_latch_on_thread = [runner = thread.GetTaskRunner(), &latch,
                                    &current_count]() {
    runner->PostTask([&latch, &current_count]() {
      std::this_thread::sleep_for(std::chrono::microseconds(100));
      current_count++;
      latch.CountDown();
    });
  };
  for (size_t i = 0; i < count; ++i) {
    decrement_latch_on_thread();
  }
  latch.Wait();
  ASSERT_EQ(current_count, count);
}

}  // namespace fml
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: progressbarwrapper.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-09-09 17:11:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_PROGRESSBARWRAPPER_HXX_
#include <uielement/progressbarwrapper.hxx>
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_STATUSINDICATOR_HXX_
#include <helper/statusindicator.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
#include <uielement/statusindicatorinterfacewrapper.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _DRAFTS_COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <drafts/com/sun/star/ui/UIElementType.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________
using namespace ::com::sun::star;

namespace framework{

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

ProgressBarWrapper::ProgressBarWrapper() :
UIElementWrapperBase( ::drafts::com::sun::star::ui::UIElementType::PROGRESSBAR )
    ,   m_bOwnsInstance( sal_False )
    ,   m_nRange( 100 )
    ,   m_nValue( 0 )
{
}

ProgressBarWrapper::~ProgressBarWrapper()
{
}

// public interfaces
void ProgressBarWrapper::setStatusBar( const uno::Reference< awt::XWindow >& rStatusBar, sal_Bool bOwnsInstance )
{
    ResetableGuard aGuard( m_aLock );

    if ( m_bDisposed )
        return;

    if ( m_bOwnsInstance )
    {
        // dispose XWindow reference our our status bar
        uno::Reference< lang::XComponent > xComponent( m_xStatusBar, uno::UNO_QUERY );
        try
        {
            if ( xComponent.is() )
                xComponent->dispose();
        }
        catch ( uno::Exception& )
        {
        }
        m_xStatusBar.clear();
    }

    m_bOwnsInstance = bOwnsInstance;
    m_xStatusBar    = rStatusBar;
}

uno::Reference< awt::XWindow > ProgressBarWrapper::getStatusBar() const
{
    ResetableGuard aGuard( m_aLock );

    if ( m_bDisposed )
        return uno::Reference< awt::XWindow >();

    return m_xStatusBar;
}

// wrapped methods of ::com::sun::star::task::XStatusIndicator
void ProgressBarWrapper::start( const ::rtl::OUString& Text, ::sal_Int32 Range )
throw (uno::RuntimeException)
{
    uno::Reference< awt::XWindow > xWindow;

    {
        ResetableGuard aGuard( m_aLock );

        if ( m_bDisposed )
            return;

        xWindow  = m_xStatusBar;
        m_nValue = 0;
        m_nRange = Range;
    }

    if ( xWindow.is() )
    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
        Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
        if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR )
        {
            StatusBar* pStatusBar = (StatusBar *)pWindow;
            if ( !pStatusBar->IsProgressMode() )
                pStatusBar->StartProgressMode( Text );
            else
                pStatusBar->SetText( Text );
        }
    }
}

void ProgressBarWrapper::end()
throw (uno::RuntimeException)
{
    uno::Reference< awt::XWindow > xWindow;

    {
        ResetableGuard aGuard( m_aLock );

        if ( m_bDisposed )
            return;

        xWindow  = m_xStatusBar;
        m_nRange = 100;
        m_nValue = 0;
    }

    if ( xWindow.is() )
    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
        Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
        if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR )
        {
            StatusBar* pStatusBar = (StatusBar *)pWindow;
            if ( pStatusBar->IsProgressMode() )
                pStatusBar->EndProgressMode();
        }
    }
}

void ProgressBarWrapper::setText( const ::rtl::OUString& Text )
throw (uno::RuntimeException)
{
    uno::Reference< awt::XWindow > xWindow;
    sal_Int32 nValue( 0 );

    {
        ResetableGuard aGuard( m_aLock );

        if ( m_bDisposed )
            return;

        xWindow  = m_xStatusBar;
        m_aText  = Text;
        nValue   = m_nValue;
    }

    if ( xWindow.is() )
    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
        Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
        if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR )
        {
            StatusBar* pStatusBar = (StatusBar *)pWindow;
            if( pStatusBar->IsProgressMode() )
            {
                pStatusBar->SetUpdateMode( FALSE );
                pStatusBar->EndProgressMode();
                pStatusBar->StartProgressMode( Text );
                pStatusBar->SetProgressValue( USHORT( nValue ));
                pStatusBar->SetUpdateMode( TRUE );
            }
            else
                pStatusBar->SetText( Text );
        }
    }
}

void ProgressBarWrapper::setValue( ::sal_Int32 nValue )
throw (uno::RuntimeException)
{
    uno::Reference< awt::XWindow > xWindow;
    rtl::OUString aText;
    sal_Bool      bSetValue( sal_False );

    {
        ResetableGuard aGuard( m_aLock );

        if ( m_bDisposed )
            return;

        xWindow  = m_xStatusBar;

        double fVal( 0 );
        if ( m_nRange > 0 )
        {
            fVal = ( double( nValue ) / double( m_nRange )) * 100;
            fVal = std::max( double( 0 ), std::min( fVal, double( 100 )));
        }

        if ( m_nValue != sal_Int32( fVal ))
        {
            m_nValue = sal_Int32( fVal );
            bSetValue = sal_True;
        }

        nValue   = m_nValue;
        aText    = m_aText;
    }

    if ( xWindow.is() && bSetValue )
    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
        Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
        if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR )
        {
            StatusBar* pStatusBar = (StatusBar *)pWindow;
            if ( !pStatusBar->IsProgressMode() )
                pStatusBar->StartProgressMode( aText );
            pStatusBar->SetProgressValue( USHORT( nValue ));
        }
    }
}

void ProgressBarWrapper::reset()
throw (uno::RuntimeException)
{
    setText( rtl::OUString() );
    setValue( 0 );
}

// XInitialization
void SAL_CALL ProgressBarWrapper::initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException)
{
    // dummy - do nothing
}

// XUpdatable
void SAL_CALL ProgressBarWrapper::update()
throw (uno::RuntimeException)
{
    // dummy - do nothing
}

// XComponent
void SAL_CALL ProgressBarWrapper::dispose()
throw (uno::RuntimeException)
{
    uno::Reference< lang::XComponent > xThis(
        static_cast< cppu::OWeakObject* >(this),
        uno::UNO_QUERY );

    {
        ResetableGuard aLock( m_aLock );

        if ( m_bDisposed )
            return;
    }

    {
        lang::EventObject aEvent( xThis );
        m_aListenerContainer.disposeAndClear( aEvent );

        ResetableGuard aLock( m_aLock );
        if ( m_bOwnsInstance )
        {
            try
            {
                uno::Reference< lang::XComponent > xComponent( m_xStatusBar, uno::UNO_QUERY );
                if ( xComponent.is() )
                    xComponent->dispose();
            }
            catch ( lang::DisposedException& )
            {
            }
        }

        m_xStatusBar.clear();
        m_bDisposed = sal_True;
    }
}

// XUIElement
uno::Reference< uno::XInterface > SAL_CALL ProgressBarWrapper::getRealInterface()
throw (uno::RuntimeException)
{
    /* SAFE AREA ----------------------------------------------------------------------------------------------- */
    // Ready for multithreading
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        return uno::Reference< uno::XInterface >();
    else
    {
        uno::Reference< uno::XInterface > xComp( m_xProgressBarIfacWrapper );
        if ( !xComp.is() )
        {
            StatusIndicatorInterfaceWrapper* pWrapper =
                new StatusIndicatorInterfaceWrapper(
                    uno::Reference< lang::XComponent >(
                        static_cast< cppu::OWeakObject* >( this ),
                        uno::UNO_QUERY ));
                xComp = uno::Reference< uno::XInterface >(
                    static_cast< cppu::OWeakObject* >( pWrapper ),
                    uno::UNO_QUERY );
             m_xProgressBarIfacWrapper = xComp;
        }

        return xComp;
    }
}

}       //  namespace framework
<commit_msg>INTEGRATION: CWS removedrafts (1.2.114); FILE MERGED 2005/02/17 12:47:49 cd 1.2.114.1: #i42557# move UNOIDL types from drafts to com<commit_after>/*************************************************************************
 *
 *  $RCSfile: progressbarwrapper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 19:43:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_PROGRESSBARWRAPPER_HXX_
#include <uielement/progressbarwrapper.hxx>
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_STATUSINDICATOR_HXX_
#include <helper/statusindicator.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
#include <uielement/statusindicatorinterfacewrapper.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <com/sun/star/ui/UIElementType.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________
using namespace ::com::sun::star;

namespace framework{

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

ProgressBarWrapper::ProgressBarWrapper() :
UIElementWrapperBase( ::com::sun::star::ui::UIElementType::PROGRESSBAR )
    ,   m_bOwnsInstance( sal_False )
    ,   m_nRange( 100 )
    ,   m_nValue( 0 )
{
}

ProgressBarWrapper::~ProgressBarWrapper()
{
}

// public interfaces
void ProgressBarWrapper::setStatusBar( const uno::Reference< awt::XWindow >& rStatusBar, sal_Bool bOwnsInstance )
{
    ResetableGuard aGuard( m_aLock );

    if ( m_bDisposed )
        return;

    if ( m_bOwnsInstance )
    {
        // dispose XWindow reference our our status bar
        uno::Reference< lang::XComponent > xComponent( m_xStatusBar, uno::UNO_QUERY );
        try
        {
            if ( xComponent.is() )
                xComponent->dispose();
        }
        catch ( uno::Exception& )
        {
        }
        m_xStatusBar.clear();
    }

    m_bOwnsInstance = bOwnsInstance;
    m_xStatusBar    = rStatusBar;
}

uno::Reference< awt::XWindow > ProgressBarWrapper::getStatusBar() const
{
    ResetableGuard aGuard( m_aLock );

    if ( m_bDisposed )
        return uno::Reference< awt::XWindow >();

    return m_xStatusBar;
}

// wrapped methods of ::com::sun::star::task::XStatusIndicator
void ProgressBarWrapper::start( const ::rtl::OUString& Text, ::sal_Int32 Range )
throw (uno::RuntimeException)
{
    uno::Reference< awt::XWindow > xWindow;

    {
        ResetableGuard aGuard( m_aLock );

        if ( m_bDisposed )
            return;

        xWindow  = m_xStatusBar;
        m_nValue = 0;
        m_nRange = Range;
    }

    if ( xWindow.is() )
    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
        Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
        if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR )
        {
            StatusBar* pStatusBar = (StatusBar *)pWindow;
            if ( !pStatusBar->IsProgressMode() )
                pStatusBar->StartProgressMode( Text );
            else
                pStatusBar->SetText( Text );
        }
    }
}

void ProgressBarWrapper::end()
throw (uno::RuntimeException)
{
    uno::Reference< awt::XWindow > xWindow;

    {
        ResetableGuard aGuard( m_aLock );

        if ( m_bDisposed )
            return;

        xWindow  = m_xStatusBar;
        m_nRange = 100;
        m_nValue = 0;
    }

    if ( xWindow.is() )
    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
        Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
        if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR )
        {
            StatusBar* pStatusBar = (StatusBar *)pWindow;
            if ( pStatusBar->IsProgressMode() )
                pStatusBar->EndProgressMode();
        }
    }
}

void ProgressBarWrapper::setText( const ::rtl::OUString& Text )
throw (uno::RuntimeException)
{
    uno::Reference< awt::XWindow > xWindow;
    sal_Int32 nValue( 0 );

    {
        ResetableGuard aGuard( m_aLock );

        if ( m_bDisposed )
            return;

        xWindow  = m_xStatusBar;
        m_aText  = Text;
        nValue   = m_nValue;
    }

    if ( xWindow.is() )
    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
        Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
        if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR )
        {
            StatusBar* pStatusBar = (StatusBar *)pWindow;
            if( pStatusBar->IsProgressMode() )
            {
                pStatusBar->SetUpdateMode( FALSE );
                pStatusBar->EndProgressMode();
                pStatusBar->StartProgressMode( Text );
                pStatusBar->SetProgressValue( USHORT( nValue ));
                pStatusBar->SetUpdateMode( TRUE );
            }
            else
                pStatusBar->SetText( Text );
        }
    }
}

void ProgressBarWrapper::setValue( ::sal_Int32 nValue )
throw (uno::RuntimeException)
{
    uno::Reference< awt::XWindow > xWindow;
    rtl::OUString aText;
    sal_Bool      bSetValue( sal_False );

    {
        ResetableGuard aGuard( m_aLock );

        if ( m_bDisposed )
            return;

        xWindow  = m_xStatusBar;

        double fVal( 0 );
        if ( m_nRange > 0 )
        {
            fVal = ( double( nValue ) / double( m_nRange )) * 100;
            fVal = std::max( double( 0 ), std::min( fVal, double( 100 )));
        }

        if ( m_nValue != sal_Int32( fVal ))
        {
            m_nValue = sal_Int32( fVal );
            bSetValue = sal_True;
        }

        nValue   = m_nValue;
        aText    = m_aText;
    }

    if ( xWindow.is() && bSetValue )
    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
        Window* pWindow = VCLUnoHelper::GetWindow( xWindow );
        if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR )
        {
            StatusBar* pStatusBar = (StatusBar *)pWindow;
            if ( !pStatusBar->IsProgressMode() )
                pStatusBar->StartProgressMode( aText );
            pStatusBar->SetProgressValue( USHORT( nValue ));
        }
    }
}

void ProgressBarWrapper::reset()
throw (uno::RuntimeException)
{
    setText( rtl::OUString() );
    setValue( 0 );
}

// XInitialization
void SAL_CALL ProgressBarWrapper::initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException)
{
    // dummy - do nothing
}

// XUpdatable
void SAL_CALL ProgressBarWrapper::update()
throw (uno::RuntimeException)
{
    // dummy - do nothing
}

// XComponent
void SAL_CALL ProgressBarWrapper::dispose()
throw (uno::RuntimeException)
{
    uno::Reference< lang::XComponent > xThis(
        static_cast< cppu::OWeakObject* >(this),
        uno::UNO_QUERY );

    {
        ResetableGuard aLock( m_aLock );

        if ( m_bDisposed )
            return;
    }

    {
        lang::EventObject aEvent( xThis );
        m_aListenerContainer.disposeAndClear( aEvent );

        ResetableGuard aLock( m_aLock );
        if ( m_bOwnsInstance )
        {
            try
            {
                uno::Reference< lang::XComponent > xComponent( m_xStatusBar, uno::UNO_QUERY );
                if ( xComponent.is() )
                    xComponent->dispose();
            }
            catch ( lang::DisposedException& )
            {
            }
        }

        m_xStatusBar.clear();
        m_bDisposed = sal_True;
    }
}

// XUIElement
uno::Reference< uno::XInterface > SAL_CALL ProgressBarWrapper::getRealInterface()
throw (uno::RuntimeException)
{
    /* SAFE AREA ----------------------------------------------------------------------------------------------- */
    // Ready for multithreading
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        return uno::Reference< uno::XInterface >();
    else
    {
        uno::Reference< uno::XInterface > xComp( m_xProgressBarIfacWrapper );
        if ( !xComp.is() )
        {
            StatusIndicatorInterfaceWrapper* pWrapper =
                new StatusIndicatorInterfaceWrapper(
                    uno::Reference< lang::XComponent >(
                        static_cast< cppu::OWeakObject* >( this ),
                        uno::UNO_QUERY ));
                xComp = uno::Reference< uno::XInterface >(
                    static_cast< cppu::OWeakObject* >( pWrapper ),
                    uno::UNO_QUERY );
             m_xProgressBarIfacWrapper = xComp;
        }

        return xComp;
    }
}

}       //  namespace framework
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "ogglength.h"
#include <vorbis/vorbisfile.h>
#include "utilities.h"
#include <vector>
#include <cstdio>
#include <string>
#include <exception>
#include <boost/lexical_cast.hpp>

// Automatically link to libogg, libvorbis, and libvorbis file if using MSVC.
// Use the dynamic versions if OGG_DYNAMIC is defined, use the static versions if OGG_STATIC is defined or neither is defined.
// If linking statically, the libraries must have been compiled with the same standard library settings (debug vs. release)
#ifdef _MSC_VER
#if defined(OGG_STATIC) && defined(OGG_DYNAMIC)
#error Ogg static or Ogg dynamic - pick one, not both
#endif
#ifdef OGG_DYNAMIC
#pragma comment(lib, "libogg.lib")
#pragma comment(lib, "libvorbis.lib")
#pragma comment(lib, "libvorbisfile.lib")
#else
#pragma comment(lib, "libogg_static.lib")
#pragma comment(lib, "libvorbis_static.lib")
#pragma comment(lib, "libvorbisfile_static.lib")
#endif
#endif

using namespace std;
using namespace boost;
using namespace lhcutilities;

namespace ogglength
{

OggVorbisFile::OggVorbisFile(const char* filePath) : m_handle(new _OggVorbisFile())
{
	// ov_fopen taking a char* instead of a const char* is an acknowledged bug in the API
	int openResult = ov_fopen(const_cast<char*>(filePath), &(m_handle->file));
	if(openResult != 0)
	{
		throw OggVorbisError("Error opening Ogg Vorbis file.");
	}

	m_handle->opened = true;
}

OggVorbis_File* OggVorbisFile::get()
{
	return &(m_handle->file);
}

double GetReportedTime(const char* filePath)
{
	OggVorbisFile oggFile(filePath);
	double reportedTime = ov_time_total(oggFile.get(), -1);
	if(reportedTime == OV_EINVAL) // I think this can happen if the file is marked as unseekable in the Vorbis headers?
	{
		throw OggVorbisError("Ogg Vorbis file is not seekable.");
	}
	return reportedTime;
}

double GetRealTime(const char* filePath)
{
	OggVorbisFile oggFile(filePath);
	double totalTimeRead = 0;
	char buffer[4096];
	int logicalBitstreamRead = -555;
	int logicalBitstreamReading = -1;

	long totalBytesRead = 0;
	long totalSamplesRead = 0;

	long bytesRead;
	int pcmWordSize = 2; // 16-bit samples
	while((bytesRead = ov_read(oggFile.get(), buffer, 4096, 0, pcmWordSize, 1, &logicalBitstreamRead)) > 0)
	{
		if(logicalBitstreamReading == -1)
		{
			logicalBitstreamReading = logicalBitstreamRead;
		}
		else if(logicalBitstreamReading != logicalBitstreamRead)
		{
			throw OggVorbisError("More than one logical bitstream in the file. Can't handle that currently.");
		}
		long samplesRead = bytesRead / pcmWordSize;
		double timeRead = (double)(samplesRead) / oggFile.get()->vi[logicalBitstreamRead].rate;
		int numChannels = oggFile.get()->vi[logicalBitstreamRead].channels;
		timeRead /= numChannels;

		totalBytesRead += bytesRead;
		totalSamplesRead += samplesRead;
		totalTimeRead += timeRead;
	}

	if(bytesRead < 0)
	{
		throw OggVorbisError("Error while decoding. The file may be corrupt.");
	}

	return totalTimeRead;
}

// Sets the length of an Ogg Vorbis file in samples.
// This is done by changing the granule position field of the last Ogg page.
// The file is assumed to be a normal Ogg Vorbis file (1 logical bitstream).
// If the file is not an Ogg file, a logic_error will be thrown.
// If the file is an Ogg file but not a file containing only a Vorbis bitstream, behavior is undefined.
// ogglength::OggVorbisError will be thrown if the he file could not be opened or some other IO error occurs
// or the file does not appear to be an Ogg Vorbis file or seems corrupt.
// If the function returns without throwing an exception, it succeeded.
void ChangeSongLength(const char* filePath, double numSeconds)
{
	FILE* file = NULL;
	try
	{
		file = OpenOrDie(filePath, "r+b");

		unsigned char version; // Version field of an Ogg page
		unsigned char headerType; // Header type field of an Ogg page.
		ogg_uint32_t sampleRate = 0;
		ogg_int32_t savedBitstreamSerialNumber;

		// Read Ogg pages until we get to the last page. Have the seek pointer at granule position then.
		while(true)
		{
			// All Ogg pages begin with the bytes "OggS"
			vector<unsigned char> buffer = ReadBytesOrDie(file, 4);
			if(buffer[0] != 'O' || buffer[1] != 'g' || buffer[2] != 'g' || buffer[3] != 'S')
			{
				throw OggVorbisError("File does not appear to be an Ogg file or is corrupted.");
			}

			// Ogg version field. Currently should always be 0.
			version = ReadOrDie<unsigned char>(file);
			if(version != 0)
			{
				throw OggVorbisError("Ogg version is " + lexical_cast<string>((unsigned int)(version)) + ". Don't know how to handle versions other than 0.");
			}

			// Header type field indicates if this page is the beginning,
			// end, or middle of an Ogg logical bitstream.
			// It is permitted for a page to be both beginning and end - that means it's the only page.
			headerType = ReadOrDie<unsigned char>(file);
			bool continuation = CheckBit(headerType, 0);
			bool beginningOfStream = CheckBit(headerType, 1);
			bool endOfStream = CheckBit(headerType, 2);

			// End of stream bit was set in the header type field - this is the last page of the logical bitstream
			if(endOfStream)
			{
				break;
			}

			// In Vorbis logical bitstreams, the granule position is the number of the last sample
			// contained in this frame.
			ogg_int64_t granulePosition = ReadOrDie<ogg_int64_t>(file);
			// Bitstream serial number might be of interest if we wanted to be able to handle Ogg files with
			// multiple logical bitstreams...but we don't care.
			ogg_int32_t bitstreamSerialNumber = ReadOrDie<ogg_int32_t>(file);
			if(sampleRate != 0 && bitstreamSerialNumber != savedBitstreamSerialNumber)
			{
				throw OggVorbisError("More than one logical bitstream in the file. Can't handle that currently.");
			}
			savedBitstreamSerialNumber = bitstreamSerialNumber;

			ogg_int32_t pageSequenceNumber = ReadOrDie<ogg_int32_t>(file);
			ogg_int32_t checksum = ReadOrDie<ogg_int32_t>(file);
			unsigned char numSegments = ReadOrDie<unsigned char>(file);

			if(sampleRate == 0)
			{
				vector<unsigned char> segmentSizes = ReadBytesOrDie(file, numSegments);
				ogg_uint32_t vorbisHeaderPacketSize = 0;
				for(int segIndex = 0; segIndex < numSegments; segIndex++)
				{
					vorbisHeaderPacketSize += segmentSizes[segIndex];
					if(segmentSizes[segIndex] < 255)
					{
						break;
					}
				}

				if(vorbisHeaderPacketSize < 16)
				{
					throw OggVorbisError("Couldn't read Vorbis header.");
				}

				unsigned char packetType = ReadOrDie<unsigned char>(file);
				if(packetType != 1)
				{
					throw OggVorbisError("Does not appear to be an Ogg Vorbis file.");
				}

				vector<unsigned char> vorbisString = ReadBytesOrDie(file, 6);
				if(vorbisString[0] != 'v' || vorbisString[1] != 'o' || vorbisString[2] != 'r'
				|| vorbisString[3] != 'b' || vorbisString[4] != 'i' || vorbisString[5] != 's')
				{
					throw OggVorbisError("Does not appear to be an Ogg Vorbis file.");
				}

				ogg_uint32_t vorbisVersion = ReadOrDie<ogg_uint32_t>(file);
				if(vorbisVersion != 0)
				{
					throw OggVorbisError("Vorbis version is not 0, don't know how to handle other version.");
				}

				unsigned char numChannels = ReadOrDie<unsigned char>(file);
				sampleRate = ReadOrDie<ogg_uint32_t>(file);
				if(sampleRate == 0)
				{
					throw OggVorbisError("File has a sample rate of 0. O_o");
				}

				ogg_int32_t pageDataSize = 0;
				for(unsigned char segmentIndex = 0; segmentIndex < numSegments; segmentIndex++)
				{
					unsigned char segmentSize = segmentSizes[segmentIndex];
					pageDataSize += segmentSize;
				}

				ogg_int32_t unreadDataBytes = pageDataSize - 16;
				SeekOrDie(file, unreadDataBytes, Seek_Cur);
			}
			else
			{
				// We're not reading the data portion of the page, so we don't need to know how
				// large each segment is, just the total size.
				ogg_int32_t pageDataSize = 0;
				for(unsigned char segmentIndex = 0; segmentIndex < numSegments; segmentIndex++)
				{
					unsigned char segmentSize = ReadOrDie<unsigned char>(file);
					pageDataSize += segmentSize;
				}

				// Skip the data of the page, we're not interested in it.
				SeekOrDie(file, pageDataSize, Seek_Cur);
			}

		}

		// Converting from seconds to samples might cause the result to be off be 1 if the number of seconds
		// came from GetRealTime().
		ogg_int64_t numSamples = (ogg_int64_t)(numSeconds * sampleRate);

		// Remember where the granule position field is, we're going to edit it later.
		// For now, we're reading the entire page so we can calculate what the checksum
		// should be after we change the granule position field.
		long granulePositionPosition = TellOrDie(file);

		ogg_int64_t granulePosition = ReadOrDie<ogg_int64_t>(file);
		granulePosition = numSamples; // Set to what it will be for checksum calculation

		ogg_int32_t bitstreamSerialNumber = ReadOrDie<ogg_int32_t>(file);
		ogg_int32_t pageSequenceNumber = ReadOrDie<ogg_int32_t>(file);

		ogg_int32_t checksum = ReadOrDie<ogg_int32_t>(file);
		checksum = 0; // Set to 0 for checksum calculation

		unsigned char numSegments = ReadOrDie<unsigned char>(file);

		vector<unsigned char> segmentSizes = ReadBytesOrDie(file, numSegments);

		// Reconstruct the header (with the new granule position) as a byte vector for checksumming
		vector<unsigned char> headerBytes;
		headerBytes.push_back('O');
		headerBytes.push_back('g');
		headerBytes.push_back('g');
		headerBytes.push_back('S');
		headerBytes.push_back(version);
		headerBytes.push_back(headerType);
		AppendBytes(headerBytes, granulePosition);
		AppendBytes(headerBytes, bitstreamSerialNumber);
		AppendBytes(headerBytes, pageSequenceNumber);
		AppendBytes(headerBytes, checksum);
		headerBytes.push_back(numSegments);
		headerBytes.insert(headerBytes.end(), segmentSizes.begin(), segmentSizes.end());

		// Calculate the size of the data part of the page
		ogg_int32_t pageDataSize = 0;
		for(unsigned char segmentIndex = 0; segmentIndex < numSegments; segmentIndex++)
		{
			unsigned char segmentSize = segmentSizes[segmentIndex];
			pageDataSize += segmentSize;
		}

		// Read the entire data part of the page into a byte vector for checksumming
		vector<unsigned char> dataBytes = ReadBytesOrDie(file, pageDataSize);

		ogg_page page;
		page.header_len = headerBytes.size();
		page.header = &(headerBytes[0]);
		page.body_len = dataBytes.size();
		if(dataBytes.size() > 0)
		{
			page.body = &(dataBytes[0]);
		}

		// Let libogg do the tricky CRC stuff
		ogg_page_checksum_set(&page);
		checksum = GetFromBytes<ogg_int32_t>(headerBytes, 22);

		// Finally, write the updated granule position and checksum. We're not changing the file
		// size or moving anything around, so we can just edit the file in place.
		SeekOrDie(file, granulePositionPosition, Seek_Set);
		WriteOrDie(file, granulePosition);
		SeekOrDie(file, 8, Seek_Cur);
		WriteOrDie(file, checksum);
	}
	catch(IoError& ex)
	{
		if(file != NULL)
		{
			fclose(file); // Clean up if something went wrong
			throw OggVorbisError(ex.what());
		}
	}
	catch(OggVorbisError&)
	{
		if(file != NULL)
		{
			fclose(file); // Clean up if something went wrong
			throw;
		}
	}

	fclose(file); // Clean up
}

} // end namespace ogglength
<commit_msg>Protection against a divide by zero crash if the number of channels reported by a file is 0. libvorbis might error out if it sees that, but just in case.<commit_after>#include "stdafx.h"
#include "ogglength.h"
#include <vorbis/vorbisfile.h>
#include "utilities.h"
#include <vector>
#include <cstdio>
#include <string>
#include <exception>
#include <boost/lexical_cast.hpp>

// Automatically link to libogg, libvorbis, and libvorbis file if using MSVC.
// Use the dynamic versions if OGG_DYNAMIC is defined, use the static versions if OGG_STATIC is defined or neither is defined.
// If linking statically, the libraries must have been compiled with the same standard library settings (debug vs. release)
#ifdef _MSC_VER
#if defined(OGG_STATIC) && defined(OGG_DYNAMIC)
#error Ogg static or Ogg dynamic - pick one, not both
#endif
#ifdef OGG_DYNAMIC
#pragma comment(lib, "libogg.lib")
#pragma comment(lib, "libvorbis.lib")
#pragma comment(lib, "libvorbisfile.lib")
#else
#pragma comment(lib, "libogg_static.lib")
#pragma comment(lib, "libvorbis_static.lib")
#pragma comment(lib, "libvorbisfile_static.lib")
#endif
#endif

using namespace std;
using namespace boost;
using namespace lhcutilities;

namespace ogglength
{

OggVorbisFile::OggVorbisFile(const char* filePath) : m_handle(new _OggVorbisFile())
{
	// ov_fopen taking a char* instead of a const char* is an acknowledged bug in the API
	int openResult = ov_fopen(const_cast<char*>(filePath), &(m_handle->file));
	if(openResult != 0)
	{
		throw OggVorbisError("Error opening Ogg Vorbis file.");
	}

	m_handle->opened = true;
}

OggVorbis_File* OggVorbisFile::get()
{
	return &(m_handle->file);
}

double GetReportedTime(const char* filePath)
{
	OggVorbisFile oggFile(filePath);
	double reportedTime = ov_time_total(oggFile.get(), -1);
	if(reportedTime == OV_EINVAL) // I think this can happen if the file is marked as unseekable in the Vorbis headers?
	{
		throw OggVorbisError("Ogg Vorbis file is not seekable.");
	}
	return reportedTime;
}

double GetRealTime(const char* filePath)
{
	OggVorbisFile oggFile(filePath);
	double totalTimeRead = 0;
	char buffer[4096];
	int logicalBitstreamRead = -555;
	int logicalBitstreamReading = -1;

	long totalBytesRead = 0;
	long totalSamplesRead = 0;

	long bytesRead;
	int pcmWordSize = 2; // 16-bit samples
	while((bytesRead = ov_read(oggFile.get(), buffer, 4096, 0, pcmWordSize, 1, &logicalBitstreamRead)) > 0)
	{
		if(logicalBitstreamReading == -1)
		{
			logicalBitstreamReading = logicalBitstreamRead;
		}
		else if(logicalBitstreamReading != logicalBitstreamRead)
		{
			throw OggVorbisError("More than one logical bitstream in the file. Can't handle that currently.");
		}
		long samplesRead = bytesRead / pcmWordSize;
		double timeRead = (double)(samplesRead) / oggFile.get()->vi[logicalBitstreamRead].rate;
		int numChannels = oggFile.get()->vi[logicalBitstreamRead].channels;
		if(numChannels <= 0)
		{
			throw OggVorbisError("Number of channels is not a positive number.");
		}
		timeRead /= numChannels;

		totalBytesRead += bytesRead;
		totalSamplesRead += samplesRead;
		totalTimeRead += timeRead;
	}

	if(bytesRead < 0)
	{
		throw OggVorbisError("Error while decoding. The file may be corrupt.");
	}

	return totalTimeRead;
}

// Sets the length of an Ogg Vorbis file in samples.
// This is done by changing the granule position field of the last Ogg page.
// The file is assumed to be a normal Ogg Vorbis file (1 logical bitstream).
// If the file is not an Ogg file, a logic_error will be thrown.
// If the file is an Ogg file but not a file containing only a Vorbis bitstream, behavior is undefined.
// ogglength::OggVorbisError will be thrown if the he file could not be opened or some other IO error occurs
// or the file does not appear to be an Ogg Vorbis file or seems corrupt.
// If the function returns without throwing an exception, it succeeded.
void ChangeSongLength(const char* filePath, double numSeconds)
{
	FILE* file = NULL;
	try
	{
		file = OpenOrDie(filePath, "r+b");

		unsigned char version; // Version field of an Ogg page
		unsigned char headerType; // Header type field of an Ogg page.
		ogg_uint32_t sampleRate = 0;
		ogg_int32_t savedBitstreamSerialNumber;

		// Read Ogg pages until we get to the last page. Have the seek pointer at granule position then.
		while(true)
		{
			// All Ogg pages begin with the bytes "OggS"
			vector<unsigned char> buffer = ReadBytesOrDie(file, 4);
			if(buffer[0] != 'O' || buffer[1] != 'g' || buffer[2] != 'g' || buffer[3] != 'S')
			{
				throw OggVorbisError("File does not appear to be an Ogg file or is corrupted.");
			}

			// Ogg version field. Currently should always be 0.
			version = ReadOrDie<unsigned char>(file);
			if(version != 0)
			{
				throw OggVorbisError("Ogg version is " + lexical_cast<string>((unsigned int)(version)) + ". Don't know how to handle versions other than 0.");
			}

			// Header type field indicates if this page is the beginning,
			// end, or middle of an Ogg logical bitstream.
			// It is permitted for a page to be both beginning and end - that means it's the only page.
			headerType = ReadOrDie<unsigned char>(file);
			bool continuation = CheckBit(headerType, 0);
			bool beginningOfStream = CheckBit(headerType, 1);
			bool endOfStream = CheckBit(headerType, 2);

			// End of stream bit was set in the header type field - this is the last page of the logical bitstream
			if(endOfStream)
			{
				break;
			}

			// In Vorbis logical bitstreams, the granule position is the number of the last sample
			// contained in this frame.
			ogg_int64_t granulePosition = ReadOrDie<ogg_int64_t>(file);
			// Bitstream serial number might be of interest if we wanted to be able to handle Ogg files with
			// multiple logical bitstreams...but we don't care.
			ogg_int32_t bitstreamSerialNumber = ReadOrDie<ogg_int32_t>(file);
			if(sampleRate != 0 && bitstreamSerialNumber != savedBitstreamSerialNumber)
			{
				throw OggVorbisError("More than one logical bitstream in the file. Can't handle that currently.");
			}
			savedBitstreamSerialNumber = bitstreamSerialNumber;

			ogg_int32_t pageSequenceNumber = ReadOrDie<ogg_int32_t>(file);
			ogg_int32_t checksum = ReadOrDie<ogg_int32_t>(file);
			unsigned char numSegments = ReadOrDie<unsigned char>(file);

			if(sampleRate == 0)
			{
				vector<unsigned char> segmentSizes = ReadBytesOrDie(file, numSegments);
				ogg_uint32_t vorbisHeaderPacketSize = 0;
				for(int segIndex = 0; segIndex < numSegments; segIndex++)
				{
					vorbisHeaderPacketSize += segmentSizes[segIndex];
					if(segmentSizes[segIndex] < 255)
					{
						break;
					}
				}

				if(vorbisHeaderPacketSize < 16)
				{
					throw OggVorbisError("Couldn't read Vorbis header.");
				}

				unsigned char packetType = ReadOrDie<unsigned char>(file);
				if(packetType != 1)
				{
					throw OggVorbisError("Does not appear to be an Ogg Vorbis file.");
				}

				vector<unsigned char> vorbisString = ReadBytesOrDie(file, 6);
				if(vorbisString[0] != 'v' || vorbisString[1] != 'o' || vorbisString[2] != 'r'
				|| vorbisString[3] != 'b' || vorbisString[4] != 'i' || vorbisString[5] != 's')
				{
					throw OggVorbisError("Does not appear to be an Ogg Vorbis file.");
				}

				ogg_uint32_t vorbisVersion = ReadOrDie<ogg_uint32_t>(file);
				if(vorbisVersion != 0)
				{
					throw OggVorbisError("Vorbis version is not 0, don't know how to handle other version.");
				}

				unsigned char numChannels = ReadOrDie<unsigned char>(file);
				sampleRate = ReadOrDie<ogg_uint32_t>(file);
				if(sampleRate == 0)
				{
					throw OggVorbisError("File has a sample rate of 0. O_o");
				}

				ogg_int32_t pageDataSize = 0;
				for(unsigned char segmentIndex = 0; segmentIndex < numSegments; segmentIndex++)
				{
					unsigned char segmentSize = segmentSizes[segmentIndex];
					pageDataSize += segmentSize;
				}

				ogg_int32_t unreadDataBytes = pageDataSize - 16;
				SeekOrDie(file, unreadDataBytes, Seek_Cur);
			}
			else
			{
				// We're not reading the data portion of the page, so we don't need to know how
				// large each segment is, just the total size.
				ogg_int32_t pageDataSize = 0;
				for(unsigned char segmentIndex = 0; segmentIndex < numSegments; segmentIndex++)
				{
					unsigned char segmentSize = ReadOrDie<unsigned char>(file);
					pageDataSize += segmentSize;
				}

				// Skip the data of the page, we're not interested in it.
				SeekOrDie(file, pageDataSize, Seek_Cur);
			}

		}

		// Converting from seconds to samples might cause the result to be off be 1 if the number of seconds
		// came from GetRealTime().
		ogg_int64_t numSamples = (ogg_int64_t)(numSeconds * sampleRate);

		// Remember where the granule position field is, we're going to edit it later.
		// For now, we're reading the entire page so we can calculate what the checksum
		// should be after we change the granule position field.
		long granulePositionPosition = TellOrDie(file);

		ogg_int64_t granulePosition = ReadOrDie<ogg_int64_t>(file);
		granulePosition = numSamples; // Set to what it will be for checksum calculation

		ogg_int32_t bitstreamSerialNumber = ReadOrDie<ogg_int32_t>(file);
		ogg_int32_t pageSequenceNumber = ReadOrDie<ogg_int32_t>(file);

		ogg_int32_t checksum = ReadOrDie<ogg_int32_t>(file);
		checksum = 0; // Set to 0 for checksum calculation

		unsigned char numSegments = ReadOrDie<unsigned char>(file);

		vector<unsigned char> segmentSizes = ReadBytesOrDie(file, numSegments);

		// Reconstruct the header (with the new granule position) as a byte vector for checksumming
		vector<unsigned char> headerBytes;
		headerBytes.push_back('O');
		headerBytes.push_back('g');
		headerBytes.push_back('g');
		headerBytes.push_back('S');
		headerBytes.push_back(version);
		headerBytes.push_back(headerType);
		AppendBytes(headerBytes, granulePosition);
		AppendBytes(headerBytes, bitstreamSerialNumber);
		AppendBytes(headerBytes, pageSequenceNumber);
		AppendBytes(headerBytes, checksum);
		headerBytes.push_back(numSegments);
		headerBytes.insert(headerBytes.end(), segmentSizes.begin(), segmentSizes.end());

		// Calculate the size of the data part of the page
		ogg_int32_t pageDataSize = 0;
		for(unsigned char segmentIndex = 0; segmentIndex < numSegments; segmentIndex++)
		{
			unsigned char segmentSize = segmentSizes[segmentIndex];
			pageDataSize += segmentSize;
		}

		// Read the entire data part of the page into a byte vector for checksumming
		vector<unsigned char> dataBytes = ReadBytesOrDie(file, pageDataSize);

		ogg_page page;
		page.header_len = headerBytes.size();
		page.header = &(headerBytes[0]);
		page.body_len = dataBytes.size();
		if(dataBytes.size() > 0)
		{
			page.body = &(dataBytes[0]);
		}

		// Let libogg do the tricky CRC stuff
		ogg_page_checksum_set(&page);
		checksum = GetFromBytes<ogg_int32_t>(headerBytes, 22);

		// Finally, write the updated granule position and checksum. We're not changing the file
		// size or moving anything around, so we can just edit the file in place.
		SeekOrDie(file, granulePositionPosition, Seek_Set);
		WriteOrDie(file, granulePosition);
		SeekOrDie(file, 8, Seek_Cur);
		WriteOrDie(file, checksum);
	}
	catch(IoError& ex)
	{
		if(file != NULL)
		{
			fclose(file); // Clean up if something went wrong
			throw OggVorbisError(ex.what());
		}
	}
	catch(OggVorbisError&)
	{
		if(file != NULL)
		{
			fclose(file); // Clean up if something went wrong
			throw;
		}
	}

	fclose(file); // Clean up
}

} // end namespace ogglength
<|endoftext|>


<commit_before>/*
 * Common.hpp
 *
 * Created on: 26 kwi 2014
 * Author: Lech Kulina
 * E-Mail: kulinalech@gmail.com
 */

#ifndef COMMON_HPP_
#define COMMON_HPP_

#include <boost/utility.hpp>
#include <boost/signals2.hpp>

#define COSMIC_UNUSED(x) (void)x

namespace Cosmic {

namespace Common {

    template<class S>
    class SignalAdapter {
        public:
            typedef S Signal;
            typedef typename Signal::slot_type Slot;
            typedef boost::signals2::connection Connection;

            explicit SignalAdapter(Signal& signal);

            Connection connect(const Slot& slot);
            void disconnect(const Slot& slot);

        private:
            Signal& signal;
    };

    template<class S>
    SignalAdapter<S>::SignalAdapter(Signal& signal) :
        signal(signal) {}

    template<class S>
    inline typename SignalAdapter<S>::Connection
    SignalAdapter<S>::connect(const typename SignalAdapter<S>::Slot& slot) {
        return signal.connect(slot);
    }

    template<class S>
    inline void SignalAdapter<S>::disconnect(const Slot& slot) {
        signal.disconnect(slot);
    }
}

}

#endif /* COMMON_HPP_ */
<commit_msg>Disable signal adapters copy ctor and assign op<commit_after>/*
 * Common.hpp
 *
 * Created on: 26 kwi 2014
 * Author: Lech Kulina
 * E-Mail: kulinalech@gmail.com
 */

#ifndef COMMON_HPP_
#define COMMON_HPP_

#include <boost/utility.hpp>
#include <boost/signals2.hpp>

#define COSMIC_UNUSED(x) (void)x

namespace Cosmic {

namespace Common {

    template<class S>
    class SignalAdapter {
        public:
            typedef S Signal;
            typedef typename Signal::slot_type Slot;
            typedef boost::signals2::connection Connection;

            explicit SignalAdapter(Signal& signal);
            SignalAdapter(const SignalAdapter&) = delete;
            SignalAdapter& operator=(const SignalAdapter&) = delete;

            Connection connect(const Slot& slot);
            void disconnect(const Slot& slot);

        private:
            Signal& signal;
    };

    template<class S>
    SignalAdapter<S>::SignalAdapter(Signal& signal) :
        signal(signal) {}

    template<class S>
    inline typename SignalAdapter<S>::Connection
    SignalAdapter<S>::connect(const typename SignalAdapter<S>::Slot& slot) {
        return signal.connect(slot);
    }

    template<class S>
    inline void SignalAdapter<S>::disconnect(const Slot& slot) {
        signal.disconnect(slot);
    }
}

}

#endif /* COMMON_HPP_ */
<|endoftext|>


<commit_before>#include "sqltenging.h"

sqltenging::sqltenging()
{
    _db = QSqlDatabase::addDatabase("QSQLITE");
    QString dbName = "vln1.sqlite";
    _db.setDatabaseName(dbName);
    _db.open();
}
// VELAR
vector<velar> sqltenging::lesaVelar()
{
    string sql = "SELECT * FROM TolvuVelar";

    return selectVelar(sql);
}

void sqltenging::baetaVidVel(string nafn, int bAr, bool byggd, string tegund)
{
    string sql = "INSERT INTO TolvuVelar(Nafn, Byggingarar, Byggd, Tegund)"
                  "VALUES('" + nafn + "'," + to_string(bAr) + "," + to_string(byggd) + ",'" + tegund + "')";
    udiSkipun(sql);
}

void sqltenging::eydaVel(int id)
{

    string sql = "DELETE FROM TolvuVelar WHERE ID = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::uppfaeraVel(int id, string nafn, int bAr, bool byggd, string tegund)
{
    string sql = "UPDATE TolvuVelar "
                 "SET nafn = '" +  nafn + "'"
                 ", byggingarar = " + to_string(bAr) +
                 ", byggd = " + to_string(byggd) +
                 ", tegund = '" + tegund + "'"
                 "WHERE ID = " + to_string(id);

    udiSkipun(sql);
}

void sqltenging::tortimaVelum()
{
    string terminator = "DELETE FROM TolvuVelar";
    udiSkipun(terminator);
}

// FOLK
vector<tolvufolk> sqltenging::lesaFolk() const
{
    string sql = "SELECT * FROM TolvuFolk";

    return selectFolk(sql);
}

void sqltenging::baetaVidFolk(string fNafn, string eNafn, char kyn, int fAr, int dAr)
{
    string sql = "INSERT INTO TolvuFolk(ForNafn, EftirNafn, Kyn, FaedingarAr, DanarAr)"
                  "VALUES('" + fNafn + "','" + eNafn + "','" + kyn + "'," + to_string(fAr) + "," + to_string(dAr) + ")";
    udiSkipun(sql);
}
void sqltenging::eydaFolk(int id)
{

    string sql = "DELETE FROM TolvuFolk WHERE ID = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::uppfaeraFolk(int id, string fNafn, string eNafn, char kyn, int fAr, int dAr)
{
    string sql = "UPDATE TolvuFolk "
                 "SET fornafn = '" +  fNafn + "'"
                 ", eftirnafn = '" + eNafn + "'"
                 ", kyn = '" + kyn + "'"
                 ", faedingarAr = " + to_string(fAr) +
                 ", danarAr = " + to_string(dAr) + " "
                 "WHERE ID = " + to_string(id);

    udiSkipun(sql);
}

void sqltenging::tortimaFolki()
{
    string terminator = "DELETE FROM tolvufolk";
    udiSkipun(terminator);
}

//Vensl

vector<velar> sqltenging::venslNafn(int id, string nafn)
{
    string sql = "SELECT f.fornafn, f.eftirnafn t.nafn FROM TolvuFolk f"
                 "INNER JOIN VenslFolkVelar v ON v.folk_id = f.id"
                 "INNER JOIN tolvuvelar t ON v.vel_id = t.id"
                 "WHERE ID = '" + nafn "'." + to_string(id);

    return selectVelar(sql);
}

// Private Functions
vector<tolvufolk> sqltenging::selectFolk(string sql) const
{
    vector<tolvufolk> t;
    QSqlQuery query(_db);
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    query.exec(cstr);

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string fornafn = query.value("fornafn").toString().toStdString();
        string eftirnafn = query.value("eftirnafn").toString().toStdString();
        char kyn = query.value("kyn").toString().toStdString()[0];
        int faedingarar = query.value("faedingarar").toUInt();
        int danarar = query.value("danarar").toUInt();

        t.push_back(tolvufolk(id, fornafn, eftirnafn, kyn, faedingarar, danarar));
    }

    return t;
}

vector<velar> sqltenging::selectVelar(string sql) const
{
    vector<velar> v;
    QSqlQuery query(_db);
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    query.exec(cstr);

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string nafn = query.value("Nafn").toString().toStdString();
        int ar = query.value("byggingarar").toUInt();
        bool byggd = query.value("byggd").toBool();
        string tegund = query.value("tegund").toString().toStdString();

        v.push_back(velar(id, nafn, ar, tegund, byggd));
    }

    return v;
}

void sqltenging::udiSkipun(string sql)
{
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    QSqlQuery query(_db);
    query.exec(cstr);
    delete[] cstr;
}
// End of private functions
<commit_msg>conflict fix<commit_after>#include "sqltenging.h"

sqltenging::sqltenging()
{
    _db = QSqlDatabase::addDatabase("QSQLITE");
    QString dbName = "vln1.sqlite";
    _db.setDatabaseName(dbName);
    _db.open();
}
// VELAR
vector<velar> sqltenging::lesaVelar()
{
    string sql = "SELECT * FROM TolvuVelar";

    return selectVelar(sql);
}

void sqltenging::baetaVidVel(string nafn, int bAr, bool byggd, string tegund)
{
    string sql = "INSERT INTO TolvuVelar(Nafn, Byggingarar, Byggd, Tegund)"
                  "VALUES('" + nafn + "'," + to_string(bAr) + "," + to_string(byggd) + ",'" + tegund + "')";
    udiSkipun(sql);
}

void sqltenging::eydaVel(int id)
{

    string sql = "DELETE FROM TolvuVelar WHERE ID = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::uppfaeraVel(int id, string nafn, int bAr, bool byggd, string tegund)
{
    string sql = "UPDATE TolvuVelar "
                 "SET nafn = '" +  nafn + "'"
                 ", byggingarar = " + to_string(bAr) +
                 ", byggd = " + to_string(byggd) +
                 ", tegund = '" + tegund + "'"
                 "WHERE ID = " + to_string(id);

    udiSkipun(sql);
}

void sqltenging::tortimaVelum()
{
    string terminator = "DELETE FROM TolvuVelar";
    udiSkipun(terminator);
}

// FOLK
vector<tolvufolk> sqltenging::lesaFolk() const
{
    string sql = "SELECT * FROM TolvuFolk";

    return selectFolk(sql);
}

void sqltenging::baetaVidFolk(string fNafn, string eNafn, char kyn, int fAr, int dAr)
{
    string sql = "INSERT INTO TolvuFolk(ForNafn, EftirNafn, Kyn, FaedingarAr, DanarAr)"
                  "VALUES('" + fNafn + "','" + eNafn + "','" + kyn + "'," + to_string(fAr) + "," + to_string(dAr) + ")";
    udiSkipun(sql);
}
void sqltenging::eydaFolk(int id)
{

    string sql = "DELETE FROM TolvuFolk WHERE ID = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::uppfaeraFolk(int id, string fNafn, string eNafn, char kyn, int fAr, int dAr)
{
    string sql = "UPDATE TolvuFolk "
                 "SET fornafn = '" +  fNafn + "'"
                 ", eftirnafn = '" + eNafn + "'"
                 ", kyn = '" + kyn + "'"
                 ", faedingarAr = " + to_string(fAr) +
                 ", danarAr = " + to_string(dAr) + " "
                 "WHERE ID = " + to_string(id);

    udiSkipun(sql);
}

void sqltenging::tortimaFolki()
{
    string terminator = "DELETE FROM tolvufolk";
    udiSkipun(terminator);
}

//Vensl

// Private Functions
vector<tolvufolk> sqltenging::selectFolk(string sql) const
{
    vector<tolvufolk> t;
    QSqlQuery query(_db);
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    query.exec(cstr);

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string fornafn = query.value("fornafn").toString().toStdString();
        string eftirnafn = query.value("eftirnafn").toString().toStdString();
        char kyn = query.value("kyn").toString().toStdString()[0];
        int faedingarar = query.value("faedingarar").toUInt();
        int danarar = query.value("danarar").toUInt();

        t.push_back(tolvufolk(id, fornafn, eftirnafn, kyn, faedingarar, danarar));
    }

    return t;
}

vector<velar> sqltenging::selectVelar(string sql) const
{
    vector<velar> v;
    QSqlQuery query(_db);
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    query.exec(cstr);

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string nafn = query.value("Nafn").toString().toStdString();
        int ar = query.value("byggingarar").toUInt();
        bool byggd = query.value("byggd").toBool();
        string tegund = query.value("tegund").toString().toStdString();

        v.push_back(velar(id, nafn, ar, tegund, byggd));
    }

    return v;
}

void sqltenging::udiSkipun(string sql)
{
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    QSqlQuery query(_db);
    query.exec(cstr);
    delete[] cstr;
}
// End of private functions
<|endoftext|>


<commit_before>/*
 * CommHandler.cpp
 *
 * Objectified access to the subscribe ports of the main control thread which other units may use to access messages.
 *
 *  Created on: Jan 10, 2013
 *      Author: maestro
 */

#include <iostream>
#include "CommHandler.h"

using namespace std;

	CommHandler::CommHandler (InputPort<hubomsg::CanMessage>* port1,
			InputPort<hubomsg::HuboCmd>* port2,
			InputPort<hubomsg::HuboState>* port3){
		canPort = port1;
		orPort = port2;
		achPort = port3;

		newCanData = false;
		newAchData = false;
	}

	void CommHandler::update(){
		hubomsg::HuboCmd huboCmd = hubomsg::HuboCmd();
		hubomsg::CanMessage canMessage = hubomsg::CanMessage();

		if (NewData == this->canPort->read(canMessage)){
			//Received update from CanGateway
			this->newCanData = true;
			this->currMessage = canMessage;

		}
		if (NewData == this->orPort->read(huboCmd)){
			this->newORData = true;
			this->currCmd = huboCmd;
		}
		if (NewData == this->achPort->read(achState)){
			this->newAchData = true;
			this->currState = achState;
		}
	}

	hubomsg::CanMessage CommHandler::getMessage(){
		newCanData = false;
		return currMessage;
	}

	hubomsg::HuboCmd CommHandler::getCmd(){
		newORData = false;
		return currCmd;
	}

	hubomsg::HuboState CommHandler::getState(){
		newAchData = false;
		return currState;
	}

	bool CommHandler::isNew(int port){
		switch (port){
		case 1:
			return newCanData;
		case 2:
			return newORData;
		case 3:
			return newAchData;
		}
		return false;
	}

<commit_msg>Added in variable declaration.<commit_after>/*
 * CommHandler.cpp
 *
 * Objectified access to the subscribe ports of the main control thread which other units may use to access messages.
 *
 *  Created on: Jan 10, 2013
 *      Author: maestro
 */

#include <iostream>
#include "CommHandler.h"

using namespace std;

	CommHandler::CommHandler (InputPort<hubomsg::CanMessage>* port1,
			InputPort<hubomsg::HuboCmd>* port2,
			InputPort<hubomsg::HuboState>* port3){
		canPort = port1;
		orPort = port2;
		achPort = port3;

		newCanData = false;
		newAchData = false;
	}

	void CommHandler::update(){
		hubomsg::HuboCmd huboCmd = hubomsg::HuboCmd();
		hubomsg::CanMessage canMessage = hubomsg::CanMessage();
		hubomsg::HuboState achState = hubomsg::HuboState();

		if (NewData == this->canPort->read(canMessage)){
			//Received update from CanGateway
			this->newCanData = true;
			this->currMessage = canMessage;

		}
		if (NewData == this->orPort->read(huboCmd)){
			this->newORData = true;
			this->currCmd = huboCmd;
		}
		if (NewData == this->achPort->read(achState)){
			this->newAchData = true;
			this->currState = achState;
		}
	}

	hubomsg::CanMessage CommHandler::getMessage(){
		newCanData = false;
		return currMessage;
	}

	hubomsg::HuboCmd CommHandler::getCmd(){
		newORData = false;
		return currCmd;
	}

	hubomsg::HuboState CommHandler::getState(){
		newAchData = false;
		return currState;
	}

	bool CommHandler::isNew(int port){
		switch (port){
		case 1:
			return newCanData;
		case 2:
			return newORData;
		case 3:
			return newAchData;
		}
		return false;
	}

<|endoftext|>


<commit_before>#pragma once
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <structmember.h>

/* Wrapper classes for internal objects are defined in python. They must have __slots__ defined.
 * A slot can be accessed in O(1) once detect_class(...) and slot_offset(...) is called.
 */

#define SLOT(obj, type, offset) (*(type **)((char *)obj + offset))

/* Shortcuts */

#define NEW_REF(obj) (Py_INCREF(obj), obj)

/* Classes defined in python must be instantiated using new_object(...)
 * The allocated memory is initialized to zero.
 * Slots can be set using the SLOT(...) macro.
 */
inline PyObject * _new_object(PyTypeObject * type) {
    PyObject * res = 0;
    Py_INCREF(type);
    if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
        res = PyObject_GC_New(PyObject, type);
    } else {
        res = PyObject_New(PyObject, type);
    }
    // PyObject_GC_Track(wrapper);
    memset((char *)res + sizeof(PyObject), 0, type->tp_basicsize - sizeof(PyObject));
    return res;
}

#define new_object(type, typeobj) (type *)_new_object(typeobj)
#define call_function(function, ...) PyObject_CallFunctionObjArgs(function, __VA_ARGS__, (void *)0)

inline void replace_object(PyObject *& src, PyObject * dst) {
    Py_INCREF(dst);
    Py_DECREF(src);
    src = dst;
}
<commit_msg>fix memset<commit_after>#pragma once
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <structmember.h>

/* Wrapper classes for internal objects are defined in python. They must have __slots__ defined.
 * A slot can be accessed in O(1) once detect_class(...) and slot_offset(...) is called.
 */

#define SLOT(obj, type, offset) (*(type **)((char *)obj + offset))

/* Shortcuts */

#define NEW_REF(obj) (Py_INCREF(obj), obj)

/* Classes defined in python must be instantiated using new_object(...)
 * The allocated memory is initialized to zero.
 * Slots can be set using the SLOT(...) macro.
 */
inline PyObject * _new_object(PyTypeObject * type, int size) {
    PyObject * res = 0;
    Py_INCREF(type);
    if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
        res = PyObject_GC_New(PyObject, type);
    } else {
        res = PyObject_New(PyObject, type);
    }
    // PyObject_GC_Track(wrapper);
    memset((char *)res + sizeof(PyObject), 0, size - sizeof(PyObject));
    return res;
}

#define new_object(type, typeobj) (type *)_new_object(typeobj, sizeof(type))
#define call_function(function, ...) PyObject_CallFunctionObjArgs(function, __VA_ARGS__, (void *)0)

inline void replace_object(PyObject *& src, PyObject * dst) {
    Py_INCREF(dst);
    Py_DECREF(src);
    src = dst;
}
<|endoftext|>