<commit_before>/***********************************************************************
    filename:   CEGUIDirect3D9RenderTarget.cpp
    created:    Tue Feb 10 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/Direct3D9/RenderTarget.h"
#include "CEGUI/RendererModules/Direct3D9/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/Exceptions.h"
#include <d3dx9.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
Direct3D9RenderTarget::Direct3D9RenderTarget(Direct3D9Renderer& owner) :
    d_owner(owner),
    d_device(owner.getDevice()),
    d_area(0, 0, 0, 0),
    d_matrixValid(false)
{
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::draw(const GeometryBuffer& buffer)
{
    buffer.draw();
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::draw(const RenderQueue& queue)
{
    queue.draw();
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::setArea(const Rectf& area)
{
    d_area = area;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
const Rectf& Direct3D9RenderTarget::getArea() const
{
    return d_area;
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::activate()
{
    if (!d_matrixValid)
        updateMatrix();

    D3DVIEWPORT9 vp;
    setupViewport(vp);
    d_device->SetViewport(&vp);

    d_owner.getDevice()->SetTransform(D3DTS_PROJECTION, &d_matrix);
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::deactivate()
{
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::unprojectPoint(const GeometryBuffer& buff,
                                           const Vector2f& p_in,
                                           Vector2f& p_out) const
{
    if (!d_matrixValid)
        updateMatrix();

    const Direct3D9GeometryBuffer& gb =
        static_cast<const Direct3D9GeometryBuffer&>(buff);

    D3DVIEWPORT9 vp;
    setupViewport(vp);

    D3DXVECTOR3 in_vec;
    in_vec.z = 0.0f;

    // project points to create a plane orientated with GeometryBuffer's data
    D3DXVECTOR3 p1;
    D3DXVECTOR3 p2;
    D3DXVECTOR3 p3;
    in_vec.x = 0;
    in_vec.y = 0;
    D3DXVec3Project(&p1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    in_vec.x = 1;
    in_vec.y = 0;
    D3DXVec3Project(&p2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    in_vec.x = 0;
    in_vec.y = 1;
    D3DXVec3Project(&p3, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    // create plane from projected points
    D3DXPLANE surface_plane;
    D3DXPlaneFromPoints(&surface_plane, &p1, &p2, &p3);

    // unproject ends of ray
    in_vec.x = vp.Width * 0.5f;
    in_vec.y = vp.Height * 0.5f;
    in_vec.z = -d_viewDistance;
    D3DXVECTOR3 t1;
    D3DXVec3Unproject(&t1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    in_vec.x = p_in.d_x;
    in_vec.y = p_in.d_y;
    in_vec.z = 0.0f;
    D3DXVECTOR3 t2;
    D3DXVec3Unproject(&t2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    // get intersection of ray and plane
    D3DXVECTOR3 intersect;
    D3DXPlaneIntersectLine(&intersect, &surface_plane, &t1, &t2);

    p_out.d_x = intersect.x;
    p_out.d_y = intersect.y;
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::updateMatrix() const
{
    const float fov = 0.523598776f;
    const float w = d_area.getWidth();
    const float h = d_area.getHeight();
    const float aspect = w / h;
    const float midx = w * 0.5f;
    const float midy = h * 0.5f;
    d_viewDistance = midx / (aspect * 0.267949192431123f);

    D3DXVECTOR3 eye(midx, midy, -d_viewDistance);
    D3DXVECTOR3 at(midx, midy, 1);
    D3DXVECTOR3 up(0, -1, 0);

    D3DXMATRIX tmp;
    D3DXMatrixMultiply(&d_matrix,
        D3DXMatrixLookAtRH(&d_matrix, &eye, &at, &up),
        D3DXMatrixPerspectiveFovRH(&tmp, fov, aspect,
                                   d_viewDistance * 0.5f,
                                   d_viewDistance * 2.0f));

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::setupViewport(D3DVIEWPORT9& vp) const
{
    vp.X = static_cast<DWORD>(d_area.left());
    vp.Y = static_cast<DWORD>(d_area.top());
    vp.Width = static_cast<DWORD>(d_area.getWidth());
    vp.Height = static_cast<DWORD>(d_area.getHeight());
    vp.MinZ = 0.0f;
    vp.MaxZ = 1.0f;
}

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

} // End of  CEGUI namespace section
<commit_msg>MOD: add initialize viewDistance in Direct3D9RenderTarget<commit_after>/***********************************************************************
    filename:   CEGUIDirect3D9RenderTarget.cpp
    created:    Tue Feb 10 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/Direct3D9/RenderTarget.h"
#include "CEGUI/RendererModules/Direct3D9/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/Exceptions.h"
#include <d3dx9.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
Direct3D9RenderTarget::Direct3D9RenderTarget(Direct3D9Renderer& owner) :
    d_owner(owner),
    d_device(owner.getDevice()),
    d_area(0, 0, 0, 0),
    d_viewDistance(0),
    d_matrixValid(false)
{
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::draw(const GeometryBuffer& buffer)
{
    buffer.draw();
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::draw(const RenderQueue& queue)
{
    queue.draw();
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::setArea(const Rectf& area)
{
    d_area = area;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
const Rectf& Direct3D9RenderTarget::getArea() const
{
    return d_area;
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::activate()
{
    if (!d_matrixValid)
        updateMatrix();

    D3DVIEWPORT9 vp;
    setupViewport(vp);
    d_device->SetViewport(&vp);

    d_owner.getDevice()->SetTransform(D3DTS_PROJECTION, &d_matrix);
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::deactivate()
{
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::unprojectPoint(const GeometryBuffer& buff,
                                           const Vector2f& p_in,
                                           Vector2f& p_out) const
{
    if (!d_matrixValid)
        updateMatrix();

    const Direct3D9GeometryBuffer& gb =
        static_cast<const Direct3D9GeometryBuffer&>(buff);

    D3DVIEWPORT9 vp;
    setupViewport(vp);

    D3DXVECTOR3 in_vec;
    in_vec.z = 0.0f;

    // project points to create a plane orientated with GeometryBuffer's data
    D3DXVECTOR3 p1;
    D3DXVECTOR3 p2;
    D3DXVECTOR3 p3;
    in_vec.x = 0;
    in_vec.y = 0;
    D3DXVec3Project(&p1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    in_vec.x = 1;
    in_vec.y = 0;
    D3DXVec3Project(&p2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    in_vec.x = 0;
    in_vec.y = 1;
    D3DXVec3Project(&p3, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    // create plane from projected points
    D3DXPLANE surface_plane;
    D3DXPlaneFromPoints(&surface_plane, &p1, &p2, &p3);

    // unproject ends of ray
    in_vec.x = vp.Width * 0.5f;
    in_vec.y = vp.Height * 0.5f;
    in_vec.z = -d_viewDistance;
    D3DXVECTOR3 t1;
    D3DXVec3Unproject(&t1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    in_vec.x = p_in.d_x;
    in_vec.y = p_in.d_y;
    in_vec.z = 0.0f;
    D3DXVECTOR3 t2;
    D3DXVec3Unproject(&t2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix());

    // get intersection of ray and plane
    D3DXVECTOR3 intersect;
    D3DXPlaneIntersectLine(&intersect, &surface_plane, &t1, &t2);

    p_out.d_x = intersect.x;
    p_out.d_y = intersect.y;
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::updateMatrix() const
{
    const float fov = 0.523598776f;
    const float w = d_area.getWidth();
    const float h = d_area.getHeight();
    const float aspect = w / h;
    const float midx = w * 0.5f;
    const float midy = h * 0.5f;
    d_viewDistance = midx / (aspect * 0.267949192431123f);

    D3DXVECTOR3 eye(midx, midy, -d_viewDistance);
    D3DXVECTOR3 at(midx, midy, 1);
    D3DXVECTOR3 up(0, -1, 0);

    D3DXMATRIX tmp;
    D3DXMatrixMultiply(&d_matrix,
        D3DXMatrixLookAtRH(&d_matrix, &eye, &at, &up),
        D3DXMatrixPerspectiveFovRH(&tmp, fov, aspect,
                                   d_viewDistance * 0.5f,
                                   d_viewDistance * 2.0f));

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
void Direct3D9RenderTarget::setupViewport(D3DVIEWPORT9& vp) const
{
    vp.X = static_cast<DWORD>(d_area.left());
    vp.Y = static_cast<DWORD>(d_area.top());
    vp.Width = static_cast<DWORD>(d_area.getWidth());
    vp.Height = static_cast<DWORD>(d_area.getHeight());
    vp.MinZ = 0.0f;
    vp.MaxZ = 1.0f;
}

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

} // End of  CEGUI namespace section
<|endoftext|>


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

#include "chrome/browser/sync/notifier/chrome_system_resources.h"

#include <cstdlib>
#include <cstring>
#include <string>

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"

namespace sync_notifier {

ChromeSystemResources::ChromeSystemResources() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
}

ChromeSystemResources::~ChromeSystemResources() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  StopScheduler();
}

invalidation::Time ChromeSystemResources::current_time() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  return base::Time::Now();
}

void ChromeSystemResources::StartScheduler() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  scoped_runnable_method_factory_.reset(
      new ScopedRunnableMethodFactory<ChromeSystemResources>(this));
}

void ChromeSystemResources::StopScheduler() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  scoped_runnable_method_factory_.reset();
  STLDeleteElements(&posted_tasks_);
}

void ChromeSystemResources::ScheduleWithDelay(
    invalidation::TimeDelta delay,
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  Task* task_to_post = MakeTaskToPost(task);
  if (!task_to_post) {
    return;
  }
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE, task_to_post, delay.InMillisecondsRoundedUp());
}

void ChromeSystemResources::ScheduleImmediately(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  Task* task_to_post = MakeTaskToPost(task);
  if (!task_to_post) {
    return;
  }
  MessageLoop::current()->PostTask(FROM_HERE, task_to_post);
}

// The listener thread is just our current thread.
void ChromeSystemResources::ScheduleOnListenerThread(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  ScheduleImmediately(task);
}

// We're already on a separate thread, so always return true.
bool ChromeSystemResources::IsRunningOnInternalThread() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  return true;
}

void ChromeSystemResources::Log(
    LogLevel level, const char* file, int line,
    const char* format, ...) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  logging::LogSeverity log_severity = logging::LOG_INFO;
  switch (level) {
    case INFO_LEVEL:
      log_severity = logging::LOG_INFO;
      break;
    case WARNING_LEVEL:
      log_severity = logging::LOG_WARNING;
      break;
    case ERROR_LEVEL:
      log_severity = logging::LOG_ERROR;
      break;
  }
  // We treat LOG(INFO) as VLOG(1).
  if ((log_severity >= logging::GetMinLogLevel()) &&
      ((log_severity != logging::LOG_INFO) ||
       (1 <= logging::GetVlogLevelHelper(file, ::strlen(file))))) {
    va_list ap;
    va_start(ap, format);
    std::string result;
    StringAppendV(&result, format, ap);
    logging::LogMessage(file, line, log_severity).stream() << result;
    va_end(ap);
  }
}

void ChromeSystemResources::WriteState(
    const invalidation::string& state,
    invalidation::StorageCallback* callback) {
  // TODO(akalin): Write the given state to persistent storage.
  callback->Run(false);
  delete callback;
}

Task* ChromeSystemResources::MakeTaskToPost(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  DCHECK(invalidation::IsCallbackRepeatable(task));
  if (!scoped_runnable_method_factory_.get()) {
    delete task;
    return NULL;
  }
  posted_tasks_.insert(task);
  Task* task_to_post =
      scoped_runnable_method_factory_->NewRunnableMethod(
          &ChromeSystemResources::RunPostedTask, task);
  return task_to_post;
}

void ChromeSystemResources::RunPostedTask(invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  RunAndDeleteClosure(task);
  posted_tasks_.erase(task);
}

}  // namespace sync_notifier
<commit_msg>[Sync] Fixed flipped return value from 61851.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/sync/notifier/chrome_system_resources.h"

#include <cstdlib>
#include <cstring>
#include <string>

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"

namespace sync_notifier {

ChromeSystemResources::ChromeSystemResources() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
}

ChromeSystemResources::~ChromeSystemResources() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  StopScheduler();
}

invalidation::Time ChromeSystemResources::current_time() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  return base::Time::Now();
}

void ChromeSystemResources::StartScheduler() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  scoped_runnable_method_factory_.reset(
      new ScopedRunnableMethodFactory<ChromeSystemResources>(this));
}

void ChromeSystemResources::StopScheduler() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  scoped_runnable_method_factory_.reset();
  STLDeleteElements(&posted_tasks_);
}

void ChromeSystemResources::ScheduleWithDelay(
    invalidation::TimeDelta delay,
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  Task* task_to_post = MakeTaskToPost(task);
  if (!task_to_post) {
    return;
  }
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE, task_to_post, delay.InMillisecondsRoundedUp());
}

void ChromeSystemResources::ScheduleImmediately(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  Task* task_to_post = MakeTaskToPost(task);
  if (!task_to_post) {
    return;
  }
  MessageLoop::current()->PostTask(FROM_HERE, task_to_post);
}

// The listener thread is just our current thread (i.e., the
// notifications thread).
void ChromeSystemResources::ScheduleOnListenerThread(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  ScheduleImmediately(task);
}

// 'Internal thread' means 'not the listener thread'.  Since the
// listener thread is the notifications thread, always return false.
bool ChromeSystemResources::IsRunningOnInternalThread() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  return false;
}

void ChromeSystemResources::Log(
    LogLevel level, const char* file, int line,
    const char* format, ...) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  logging::LogSeverity log_severity = logging::LOG_INFO;
  switch (level) {
    case INFO_LEVEL:
      log_severity = logging::LOG_INFO;
      break;
    case WARNING_LEVEL:
      log_severity = logging::LOG_WARNING;
      break;
    case ERROR_LEVEL:
      log_severity = logging::LOG_ERROR;
      break;
  }
  // We treat LOG(INFO) as VLOG(1).
  if ((log_severity >= logging::GetMinLogLevel()) &&
      ((log_severity != logging::LOG_INFO) ||
       (1 <= logging::GetVlogLevelHelper(file, ::strlen(file))))) {
    va_list ap;
    va_start(ap, format);
    std::string result;
    StringAppendV(&result, format, ap);
    logging::LogMessage(file, line, log_severity).stream() << result;
    va_end(ap);
  }
}

void ChromeSystemResources::WriteState(
    const invalidation::string& state,
    invalidation::StorageCallback* callback) {
  // TODO(akalin): Write the given state to persistent storage.
  callback->Run(false);
  delete callback;
}

Task* ChromeSystemResources::MakeTaskToPost(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  DCHECK(invalidation::IsCallbackRepeatable(task));
  if (!scoped_runnable_method_factory_.get()) {
    delete task;
    return NULL;
  }
  posted_tasks_.insert(task);
  Task* task_to_post =
      scoped_runnable_method_factory_->NewRunnableMethod(
          &ChromeSystemResources::RunPostedTask, task);
  return task_to_post;
}

void ChromeSystemResources::RunPostedTask(invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  RunAndDeleteClosure(task);
  posted_tasks_.erase(task);
}

}  // namespace sync_notifier
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _MODE_T_
typedef int mode_t;
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);

#endif

#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef O_RANDOM
#define O_RANDOM 0
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#include "libtorrent/assert.hpp"

namespace
{
	enum { mode_in = 1, mode_out = 2 };

	mode_t map_open_mode(int m)
	{
		if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
		TORRENT_ASSERT(false);
		return 0;
	}

#ifdef WIN32
	std::string utf8_native(std::string const& s)
	{
		try
		{
			std::wstring ws;
			libtorrent::utf8_wchar(s, ws);
			std::size_t size = wcstombs(0, ws.c_str(), 0);
			if (size == std::size_t(-1)) return s;
			std::string ret;
			ret.resize(size);
			size = wcstombs(&ret[0], ws.c_str(), size + 1);
			if (size == wchar_t(-1)) return s;
			ret.resize(size);
			return ret;
		}
		catch(std::exception)
		{
			return s;
		}
	}
#else
	std::string const& utf8_native(std::string const& s)
	{
		return s;
	}
#endif

}

namespace libtorrent
{
	namespace fs = boost::filesystem;

	const file::open_mode file::in(mode_in);
	const file::open_mode file::out(mode_out);

	const file::seek_mode file::begin(1);
	const file::seek_mode file::end(2);

	struct file::impl
	{
		impl()
			: m_fd(-1)
			, m_open_mode(0)
		{}

		impl(fs::path const& path, int mode, error_code& ec)
			: m_fd(-1)
			, m_open_mode(0)
		{
			open(path, mode, ec);
		}

		~impl()
		{
			close();
		}

		bool open(fs::path const& path, int mode, error_code& ec)
		{
			close();
#ifdef TORRENT_WINDOWS

			const int permissions = _S_IREAD | _S_IWRITE;

#ifdef defined UNICODE
#define open _wopen
			std::wstring file_path(safe_convert(path.native_file_string()));
#else
#define open _open
			std::string const& file_path = path.native_file_string();
#endif
#else // if not windows
			const mode_t permissions = S_IRWXU | S_IRGRP | S_IROTH;
			std::string const& file_path = path.native_file_string();
#endif
			m_fd = ::open(file_path.c_str(), map_open_mode(mode), permissions);

#ifdef TORRENT_WINDOWS
#undef open
#endif

			if (m_fd == -1)
			{
				ec = error_code(errno, get_posix_category());
				return false;
			}
			m_open_mode = mode;
			return true;
		}

		void close()
		{
			if (m_fd == -1) return;

#ifdef _WIN32
			::_close(m_fd);
#else
			::close(m_fd);
#endif
			m_fd = -1;
			m_open_mode = 0;
		}

		size_type read(char* buf, size_type num_bytes, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode & mode_in);
			TORRENT_ASSERT(m_fd != -1);

#ifdef _WIN32
			size_type ret = ::_read(m_fd, buf, num_bytes);
#else
			size_type ret = ::read(m_fd, buf, num_bytes);
#endif
			if (ret == -1) ec = error_code(errno, get_posix_category());
			return ret;
		}

		size_type write(const char* buf, size_type num_bytes, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode & mode_out);
			TORRENT_ASSERT(m_fd != -1);

			// TODO: Test this a bit more, what happens with random failures in
			// the files?
//			if ((rand() % 100) > 80)
//				throw file_error("debug");

#ifdef _WIN32
			size_type ret = ::_write(m_fd, buf, num_bytes);
#else
			size_type ret = ::write(m_fd, buf, num_bytes);
#endif
			if (ret == -1) ec = error_code(errno, get_posix_category());
			return ret;
		}

		bool set_size(size_type s, error_code& ec)
		{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
			if (ftruncate(m_fd, s) < 0)
			{
				ec = error_code(errno, get_posix_category());
				return false;
			}
			return true;
#endif
		}

		size_type seek(size_type offset, int m, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
			size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
			size_type ret = lseek(m_fd, offset, seekdir);
#endif

			// For some strange reason this fails
			// on win32. Use windows specific file
			// wrapper instead.
			if (ret < 0) ec = error_code(errno, get_posix_category());
			return ret;
		}

		size_type tell(error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			size_type ret;
#ifdef _WIN32
			ret = _telli64(m_fd);
#else
			ret = lseek(m_fd, 0, SEEK_CUR);
#endif
			if (ret < 0) ec = error_code(errno, get_posix_category());
			return ret;
		}

		int m_fd;
		int m_open_mode;
	};

	// pimpl forwardings

	file::file() : m_impl(new impl()) {}

	file::file(fs::path const& p, file::open_mode m, error_code& ec)
		: m_impl(new impl(p, m.m_mask, ec))
	{}

	file::~file() {}

	bool file::open(fs::path const& p, file::open_mode m, error_code& ec)
	{
		return m_impl->open(p, m.m_mask, ec);
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
	{
		return m_impl->write(buf, num_bytes, ec);
	}

	size_type file::read(char* buf, size_type num_bytes, error_code& ec)
	{
		return m_impl->read(buf, num_bytes, ec);
	}

	bool file::set_size(size_type s, error_code& ec)
	{
		return m_impl->set_size(s, ec);
	}

	size_type file::seek(size_type pos, file::seek_mode m, error_code& ec)
	{
		return m_impl->seek(pos, m.m_val, ec);
	}

	size_type file::tell(error_code& ec)
	{
		return m_impl->tell(ec);
	}
}
<commit_msg>set all permission bits on files and let umask handle reducing permissions<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _MODE_T_
typedef int mode_t;
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);

#endif

#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef O_RANDOM
#define O_RANDOM 0
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#include "libtorrent/assert.hpp"

namespace
{
	enum { mode_in = 1, mode_out = 2 };

	mode_t map_open_mode(int m)
	{
		if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
		TORRENT_ASSERT(false);
		return 0;
	}

#ifdef WIN32
	std::string utf8_native(std::string const& s)
	{
		try
		{
			std::wstring ws;
			libtorrent::utf8_wchar(s, ws);
			std::size_t size = wcstombs(0, ws.c_str(), 0);
			if (size == std::size_t(-1)) return s;
			std::string ret;
			ret.resize(size);
			size = wcstombs(&ret[0], ws.c_str(), size + 1);
			if (size == wchar_t(-1)) return s;
			ret.resize(size);
			return ret;
		}
		catch(std::exception)
		{
			return s;
		}
	}
#else
	std::string const& utf8_native(std::string const& s)
	{
		return s;
	}
#endif

}

namespace libtorrent
{
	namespace fs = boost::filesystem;

	const file::open_mode file::in(mode_in);
	const file::open_mode file::out(mode_out);

	const file::seek_mode file::begin(1);
	const file::seek_mode file::end(2);

	struct file::impl
	{
		impl()
			: m_fd(-1)
			, m_open_mode(0)
		{}

		impl(fs::path const& path, int mode, error_code& ec)
			: m_fd(-1)
			, m_open_mode(0)
		{
			open(path, mode, ec);
		}

		~impl()
		{
			close();
		}

		bool open(fs::path const& path, int mode, error_code& ec)
		{
			close();
#ifdef TORRENT_WINDOWS

			const int permissions = _S_IREAD | _S_IWRITE;

#ifdef defined UNICODE
#define open _wopen
			std::wstring file_path(safe_convert(path.native_file_string()));
#else
#define open _open
			std::string const& file_path = path.native_file_string();
#endif
#else // if not windows
			// rely on default umask to filter x and w permissions
			// for group and others
			const mode_t permissions = S_IRWXU | S_IRWXG | S_IRWXO;
			std::string const& file_path = path.native_file_string();
#endif
			m_fd = ::open(file_path.c_str(), map_open_mode(mode), permissions);

#ifdef TORRENT_WINDOWS
#undef open
#endif

			if (m_fd == -1)
			{
				ec = error_code(errno, get_posix_category());
				return false;
			}
			m_open_mode = mode;
			return true;
		}

		void close()
		{
			if (m_fd == -1) return;

#ifdef _WIN32
			::_close(m_fd);
#else
			::close(m_fd);
#endif
			m_fd = -1;
			m_open_mode = 0;
		}

		size_type read(char* buf, size_type num_bytes, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode & mode_in);
			TORRENT_ASSERT(m_fd != -1);

#ifdef _WIN32
			size_type ret = ::_read(m_fd, buf, num_bytes);
#else
			size_type ret = ::read(m_fd, buf, num_bytes);
#endif
			if (ret == -1) ec = error_code(errno, get_posix_category());
			return ret;
		}

		size_type write(const char* buf, size_type num_bytes, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode & mode_out);
			TORRENT_ASSERT(m_fd != -1);

			// TODO: Test this a bit more, what happens with random failures in
			// the files?
//			if ((rand() % 100) > 80)
//				throw file_error("debug");

#ifdef _WIN32
			size_type ret = ::_write(m_fd, buf, num_bytes);
#else
			size_type ret = ::write(m_fd, buf, num_bytes);
#endif
			if (ret == -1) ec = error_code(errno, get_posix_category());
			return ret;
		}

		bool set_size(size_type s, error_code& ec)
		{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
			if (ftruncate(m_fd, s) < 0)
			{
				ec = error_code(errno, get_posix_category());
				return false;
			}
			return true;
#endif
		}

		size_type seek(size_type offset, int m, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
			size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
			size_type ret = lseek(m_fd, offset, seekdir);
#endif

			// For some strange reason this fails
			// on win32. Use windows specific file
			// wrapper instead.
			if (ret < 0) ec = error_code(errno, get_posix_category());
			return ret;
		}

		size_type tell(error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			size_type ret;
#ifdef _WIN32
			ret = _telli64(m_fd);
#else
			ret = lseek(m_fd, 0, SEEK_CUR);
#endif
			if (ret < 0) ec = error_code(errno, get_posix_category());
			return ret;
		}

		int m_fd;
		int m_open_mode;
	};

	// pimpl forwardings

	file::file() : m_impl(new impl()) {}

	file::file(fs::path const& p, file::open_mode m, error_code& ec)
		: m_impl(new impl(p, m.m_mask, ec))
	{}

	file::~file() {}

	bool file::open(fs::path const& p, file::open_mode m, error_code& ec)
	{
		return m_impl->open(p, m.m_mask, ec);
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
	{
		return m_impl->write(buf, num_bytes, ec);
	}

	size_type file::read(char* buf, size_type num_bytes, error_code& ec)
	{
		return m_impl->read(buf, num_bytes, ec);
	}

	bool file::set_size(size_type s, error_code& ec)
	{
		return m_impl->set_size(s, ec);
	}

	size_type file::seek(size_type pos, file::seek_mode m, error_code& ec)
	{
		return m_impl->seek(pos, m.m_val, ec);
	}

	size_type file::tell(error_code& ec)
	{
		return m_impl->tell(ec);
	}
}
<|endoftext|>


<commit_before>#include "robobo.h"
#include <string.h> // C strings to handle args

int main(int argc, char** argv) {
	if (argc > 1) { // analyze arguments
		bool exitAfter = false;
		for (int i = 1; i < argc; i++) { // iterate through all arguments
			if (strcmp(argv[i], "--help") == 0) {
				std::cout << "RoBoBo-IRC-BoBo IRC Bot Help" << std::endl;
				std::cout << std::endl;
				std::cout << "RoBoBo can connect to IRC servers.  All of its functionality outside of" << std::endl << "connecting to servers is provided by loaded modules." << std::endl;
				std::cout << "See the README file for more information." << std::endl;
				std::cout << std::endl;
				std::cout << "Some command line arguments are provided to perform certain actions.  With no" << std::endl << "parameters, the bot will run as a bot.  With some command line arguments, the" << std::endl << "functionality of the bot can be changed." << std::endl;
				std::cout << "Command Line Arguments:" << std::endl;
				std::cout << "\t--help: display this help and exit" << std::endl;
				std::cout << "\t--version: display RoBoBo's version and exit" << std::endl;
				exitAfter = true;
			} else if (strcmp(argv[i], "--version") == 0) {
				std::cout << "RoBoBo-IRC-BoBo Pre-alpha Development Version" << std::endl;
				exitAfter = true;
			}
			std::cout << std::endl; // add a newline after a parameter's output
		}
		if (exitAfter)
			return 0;
	}
	new ModuleInterface (new ConfigReader ());
	pthread_exit(NULL);
}<commit_msg>Add shorthand arguments.<commit_after>#include "robobo.h"
#include <string.h> // C strings to handle args

int main(int argc, char** argv) {
	if (argc > 1) { // analyze arguments
		bool exitAfter = false;
		for (int i = 1; i < argc; i++) { // iterate through all arguments
			if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {
				std::cout << "RoBoBo-IRC-BoBo IRC Bot Help" << std::endl;
				std::cout << std::endl;
				std::cout << "RoBoBo can connect to IRC servers.  All of its functionality outside of" << std::endl << "connecting to servers is provided by loaded modules." << std::endl;
				std::cout << "See the README file for more information." << std::endl;
				std::cout << std::endl;
				std::cout << "Some command line arguments are provided to perform certain actions.  With no" << std::endl << "parameters, the bot will run as a bot.  With some command line arguments, the" << std::endl << "functionality of the bot can be changed." << std::endl;
				std::cout << "Command Line Arguments:" << std::endl;
				std::cout << "\t--help: display this help and exit" << std::endl;
				std::cout << "\t--version: display RoBoBo's version and exit" << std::endl;
				exitAfter = true;
			} else if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
				std::cout << "RoBoBo-IRC-BoBo Pre-alpha Development Version" << std::endl;
				exitAfter = true;
			}
			std::cout << std::endl; // add a newline after a parameter's output
		}
		if (exitAfter)
			return 0;
	}
	new ModuleInterface (new ConfigReader ());
	pthread_exit(NULL);
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TransitionPreset.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:13:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _COM_SUN_STAR_ANIMATIONS_XTIMECONTAINER_HPP_
#include <com/sun/star/animations/XTimeContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_XTRANSITIONFILTER_HPP_
#include <com/sun/star/animations/XTransitionFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XEnumerationAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_ANIMATIONNODETYPE_HPP_
#include <com/sun/star/animations/AnimationNodeType.hpp>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif

#include <tools/debug.hxx>

#ifndef _SD_CUSTOMANIMATIONPRESET_HXX
#include <TransitionPreset.hxx>
#endif

#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif

#include <algorithm>

#include "sdpage.hxx"

using namespace ::vos;
using namespace ::com::sun::star;
using namespace ::com::sun::star::animations;

using ::rtl::OUString;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::container::XEnumerationAccess;
using ::com::sun::star::container::XEnumeration;
using ::com::sun::star::beans::NamedValue;

namespace sd {

typedef std::hash_map<rtl::OUString, rtl::OUString, comphelper::UStringHash, comphelper::UStringEqual> UStringMap;
extern Reference< XAnimationNode > implImportEffects( const Reference< XMultiServiceFactory >& xConfigProvider, const OUString& rPath );
extern void implImportLabels( const Reference< XMultiServiceFactory >& xConfigProvider, const OUString& rNodePath, UStringMap& rStringMap );

TransitionPreset::TransitionPreset( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode )
{
    // first locate preset id
    Sequence< NamedValue > aUserData( xNode->getUserData() );
    sal_Int32 nLength = aUserData.getLength();
    const NamedValue* p = aUserData.getConstArray();
    while( nLength-- )
    {
        if( p->Name.equalsAscii( "preset-id" ) )
        {
            p->Value >>= maPresetId;
            break;
        }
    }

    // second, locate transition filter element
    Reference< XEnumerationAccess > xEnumerationAccess( xNode, UNO_QUERY_THROW );
    Reference< XEnumeration > xEnumeration( xEnumerationAccess->createEnumeration(), UNO_QUERY_THROW );
    Reference< XTransitionFilter > xTransition( xEnumeration->nextElement(), UNO_QUERY_THROW );

    mnTransition = xTransition->getTransition();
    mnSubtype = xTransition->getSubtype();
    mbDirection = xTransition->getDirection();
    mnFadeColor = xTransition->getFadeColor();
}

bool TransitionPreset::importTransitionPresetList( TransitionPresetList& rList )
{
    try
    {
        // Get service factory
        Reference< XMultiServiceFactory > xServiceFactory( comphelper::getProcessServiceFactory() );
        DBG_ASSERT( xServiceFactory.is(), "sd::CustomAnimationPresets::import(), got no service manager" );
        if( !xServiceFactory.is() )
            return false;

        // import ui strings
        Reference< XMultiServiceFactory > xConfigProvider(
            xServiceFactory->createInstance(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ))),
            UNO_QUERY_THROW );

        UStringMap aTransitionNameMape;
        const OUString aTransitionPath( RTL_CONSTASCII_USTRINGPARAM( "/org.openoffice.Office.UI.Effects/UserInterface/Transitions" ) );
        implImportLabels( xConfigProvider, aTransitionPath, aTransitionNameMape );

        // import transition presets
        INetURLObject   aURL( SvtPathOptions().GetConfigPath() );
        aURL.Append( String( RTL_CONSTASCII_USTRINGPARAM("soffice.cfg") ) );
        aURL.Append( String( RTL_CONSTASCII_USTRINGPARAM("simpress" ) ) );
        aURL.Append( String( RTL_CONSTASCII_USTRINGPARAM("transitions.xml" ) ) );

        Reference< XEnumerationAccess > xEnumerationAccess( implImportEffects( xServiceFactory, aURL.GetMainURL( INetURLObject::NO_DECODE ) ), UNO_QUERY_THROW );
        Reference< XEnumeration > xEnumeration( xEnumerationAccess->createEnumeration(), UNO_QUERY_THROW );
        while( xEnumeration->hasMoreElements() )
        {
            Reference< XAnimationNode > xChildNode( xEnumeration->nextElement(), UNO_QUERY_THROW );
            if( xChildNode->getType() == AnimationNodeType::PAR )
            {
                // create it
                TransitionPresetPtr pPreset( new TransitionPreset( xChildNode ) );

                // name it
                OUString aPresetId( pPreset->getPresetId() );
                if( aPresetId.getLength() )
                {
                    UStringMap::const_iterator aIter( aTransitionNameMape.find( aPresetId ) );
                    if( aIter != aTransitionNameMape.end() )
                        pPreset->maUIName = (*aIter).second;

                    // add it
                    rList.push_back( pPreset );
                }
            }
            else
            {
                DBG_ERROR( "sd::TransitionPreset::importTransitionPresetList(), missformed xml configuration file, giving up!" );
                break;
            }
        }

        return true;
    }
    catch( Exception& e )
    {
        (void)e;
        DBG_ERROR( "sd::TransitionPreset::importResources(), Exception cought!" );
    }

    return false;
}

TransitionPresetList* TransitionPreset::mpTransitionPresetList = 0;

const TransitionPresetList& TransitionPreset::getTransitionPresetList()
{
    if( !mpTransitionPresetList )
    {
        OGuard aGuard( Application::GetSolarMutex() );
        if( !mpTransitionPresetList )
        {
            mpTransitionPresetList = new sd::TransitionPresetList();
            sd::TransitionPreset::importTransitionPresetList( *mpTransitionPresetList );
        }
    }

    return *mpTransitionPresetList;
}

void TransitionPreset::apply( SdPage* pSlide ) const
{
    if( pSlide )
    {
        pSlide->setTransitionType( mnTransition );
        pSlide->setTransitionSubtype( mnSubtype );
        pSlide->setTransitionDirection( mbDirection );
        pSlide->setTransitionFadeColor( mnFadeColor );
    }
}

}

<commit_msg>#100000# added missing include<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TransitionPreset.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-23 12:12:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _COM_SUN_STAR_ANIMATIONS_XTIMECONTAINER_HPP_
#include <com/sun/star/animations/XTimeContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_XTRANSITIONFILTER_HPP_
#include <com/sun/star/animations/XTransitionFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XEnumerationAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_ANIMATIONNODETYPE_HPP_
#include <com/sun/star/animations/AnimationNodeType.hpp>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif

#include <tools/debug.hxx>

#ifndef _SD_CUSTOMANIMATIONPRESET_HXX
#include <TransitionPreset.hxx>
#endif

#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif

#include <algorithm>

#include "sdpage.hxx"
#include <hash_map>

using namespace ::vos;
using namespace ::com::sun::star;
using namespace ::com::sun::star::animations;

using ::rtl::OUString;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::container::XEnumerationAccess;
using ::com::sun::star::container::XEnumeration;
using ::com::sun::star::beans::NamedValue;

namespace sd {

typedef std::hash_map<rtl::OUString, rtl::OUString, comphelper::UStringHash, comphelper::UStringEqual> UStringMap;
extern Reference< XAnimationNode > implImportEffects( const Reference< XMultiServiceFactory >& xConfigProvider, const OUString& rPath );
extern void implImportLabels( const Reference< XMultiServiceFactory >& xConfigProvider, const OUString& rNodePath, UStringMap& rStringMap );

TransitionPreset::TransitionPreset( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode )
{
    // first locate preset id
    Sequence< NamedValue > aUserData( xNode->getUserData() );
    sal_Int32 nLength = aUserData.getLength();
    const NamedValue* p = aUserData.getConstArray();
    while( nLength-- )
    {
        if( p->Name.equalsAscii( "preset-id" ) )
        {
            p->Value >>= maPresetId;
            break;
        }
    }

    // second, locate transition filter element
    Reference< XEnumerationAccess > xEnumerationAccess( xNode, UNO_QUERY_THROW );
    Reference< XEnumeration > xEnumeration( xEnumerationAccess->createEnumeration(), UNO_QUERY_THROW );
    Reference< XTransitionFilter > xTransition( xEnumeration->nextElement(), UNO_QUERY_THROW );

    mnTransition = xTransition->getTransition();
    mnSubtype = xTransition->getSubtype();
    mbDirection = xTransition->getDirection();
    mnFadeColor = xTransition->getFadeColor();
}

bool TransitionPreset::importTransitionPresetList( TransitionPresetList& rList )
{
    try
    {
        // Get service factory
        Reference< XMultiServiceFactory > xServiceFactory( comphelper::getProcessServiceFactory() );
        DBG_ASSERT( xServiceFactory.is(), "sd::CustomAnimationPresets::import(), got no service manager" );
        if( !xServiceFactory.is() )
            return false;

        // import ui strings
        Reference< XMultiServiceFactory > xConfigProvider(
            xServiceFactory->createInstance(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider" ))),
            UNO_QUERY_THROW );

        UStringMap aTransitionNameMape;
        const OUString aTransitionPath( RTL_CONSTASCII_USTRINGPARAM( "/org.openoffice.Office.UI.Effects/UserInterface/Transitions" ) );
        implImportLabels( xConfigProvider, aTransitionPath, aTransitionNameMape );

        // import transition presets
        INetURLObject   aURL( SvtPathOptions().GetConfigPath() );
        aURL.Append( String( RTL_CONSTASCII_USTRINGPARAM("soffice.cfg") ) );
        aURL.Append( String( RTL_CONSTASCII_USTRINGPARAM("simpress" ) ) );
        aURL.Append( String( RTL_CONSTASCII_USTRINGPARAM("transitions.xml" ) ) );

        Reference< XEnumerationAccess > xEnumerationAccess( implImportEffects( xServiceFactory, aURL.GetMainURL( INetURLObject::NO_DECODE ) ), UNO_QUERY_THROW );
        Reference< XEnumeration > xEnumeration( xEnumerationAccess->createEnumeration(), UNO_QUERY_THROW );
        while( xEnumeration->hasMoreElements() )
        {
            Reference< XAnimationNode > xChildNode( xEnumeration->nextElement(), UNO_QUERY_THROW );
            if( xChildNode->getType() == AnimationNodeType::PAR )
            {
                // create it
                TransitionPresetPtr pPreset( new TransitionPreset( xChildNode ) );

                // name it
                OUString aPresetId( pPreset->getPresetId() );
                if( aPresetId.getLength() )
                {
                    UStringMap::const_iterator aIter( aTransitionNameMape.find( aPresetId ) );
                    if( aIter != aTransitionNameMape.end() )
                        pPreset->maUIName = (*aIter).second;

                    // add it
                    rList.push_back( pPreset );
                }
            }
            else
            {
                DBG_ERROR( "sd::TransitionPreset::importTransitionPresetList(), missformed xml configuration file, giving up!" );
                break;
            }
        }

        return true;
    }
    catch( Exception& e )
    {
        (void)e;
        DBG_ERROR( "sd::TransitionPreset::importResources(), Exception cought!" );
    }

    return false;
}

TransitionPresetList* TransitionPreset::mpTransitionPresetList = 0;

const TransitionPresetList& TransitionPreset::getTransitionPresetList()
{
    if( !mpTransitionPresetList )
    {
        OGuard aGuard( Application::GetSolarMutex() );
        if( !mpTransitionPresetList )
        {
            mpTransitionPresetList = new sd::TransitionPresetList();
            sd::TransitionPreset::importTransitionPresetList( *mpTransitionPresetList );
        }
    }

    return *mpTransitionPresetList;
}

void TransitionPreset::apply( SdPage* pSlide ) const
{
    if( pSlide )
    {
        pSlide->setTransitionType( mnTransition );
        pSlide->setTransitionSubtype( mnSubtype );
        pSlide->setTransitionDirection( mbDirection );
        pSlide->setTransitionFadeColor( mnFadeColor );
    }
}

}

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// append_test.cpp
//
// Identification: test/executor/append_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <vector>

#include "common/harness.h"

#include "planner/append_plan.h"

#include "common/types.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "executor/append_executor.h"
#include "storage/data_table.h"
#include "concurrency/transaction_manager_factory.h"

#include "executor/executor_tests_util.h"
#include "executor/mock_executor.h"

using ::testing::NotNull;
using ::testing::Return;

namespace peloton {
namespace test {

namespace {

class AppendTests : public PelotonTest {};

void RunTest(executor::AppendExecutor &executor, size_t expected_num_tuples) {
  EXPECT_TRUE(executor.Init());

  std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles;
  while (executor.Execute()) {
    result_tiles.emplace_back(executor.GetOutput());
  }

  size_t actual_num_tuples_returned = 0;
  for (auto &tile : result_tiles) {
    actual_num_tuples_returned += tile->GetTupleCount();
  }

  EXPECT_EQ(expected_num_tuples, actual_num_tuples_returned);
}

TEST_F(AppendTests, AppendTwoTest) {
  // Create the plan node
  planner::AppendPlan node;

  // Create and set up executor
  executor::AppendExecutor executor(&node, nullptr);

  MockExecutor child_executor1;
  MockExecutor child_executor2;

  executor.AddChild(&child_executor1);
  executor.AddChild(&child_executor2);

  EXPECT_CALL(child_executor1, DInit()).WillOnce(Return(true));

  EXPECT_CALL(child_executor2, DInit()).WillOnce(Return(true));

  EXPECT_CALL(child_executor1, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  EXPECT_CALL(child_executor2, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  size_t tile_size = 10;
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  txn_manager.BeginTransaction();
  std::unique_ptr<storage::DataTable> data_table(
      ExecutorTestsUtil::CreateTable(tile_size));
  ExecutorTestsUtil::PopulateTable(data_table.get(), tile_size * NUM_CACHED_TG, false,
                                   false, false);
  txn_manager.CommitTransaction();

  std::unique_ptr<executor::LogicalTile> ltile0(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0)));

  std::unique_ptr<executor::LogicalTile> ltile1(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1)));

  std::unique_ptr<executor::LogicalTile> ltile2(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(2)));

  EXPECT_CALL(child_executor1, GetOutput()).WillOnce(Return(ltile0.release()));

  EXPECT_CALL(child_executor2, GetOutput())
      .WillOnce(Return(ltile1.release()))
      .WillOnce(Return(ltile2.release()));

  RunTest(executor, tile_size * 3);
}
}
}
}
<commit_msg>pass append test<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// append_test.cpp
//
// Identification: test/executor/append_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <vector>

#include "common/harness.h"

#include "planner/append_plan.h"

#include "common/types.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "executor/append_executor.h"
#include "storage/data_table.h"
#include "concurrency/transaction_manager_factory.h"

#include "executor/executor_tests_util.h"
#include "executor/mock_executor.h"

using ::testing::NotNull;
using ::testing::Return;

namespace peloton {
namespace test {

namespace {

class AppendTests : public PelotonTest {};

void RunTest(executor::AppendExecutor &executor, size_t expected_num_tuples) {
  EXPECT_TRUE(executor.Init());

  std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles;
  while (executor.Execute()) {
    result_tiles.emplace_back(executor.GetOutput());
  }

  size_t actual_num_tuples_returned = 0;
  for (auto &tile : result_tiles) {
    actual_num_tuples_returned += tile->GetTupleCount();
  }

  EXPECT_EQ(expected_num_tuples, actual_num_tuples_returned);
}

TEST_F(AppendTests, AppendTwoTest) {
  // Create the plan node
  planner::AppendPlan node;

  // Create and set up executor
  executor::AppendExecutor executor(&node, nullptr);

  MockExecutor child_executor1;
  MockExecutor child_executor2;

  executor.AddChild(&child_executor1);
  executor.AddChild(&child_executor2);

  EXPECT_CALL(child_executor1, DInit()).WillOnce(Return(true));

  EXPECT_CALL(child_executor2, DInit()).WillOnce(Return(true));

  EXPECT_CALL(child_executor1, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  EXPECT_CALL(child_executor2, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  size_t tile_size = 10;
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  txn_manager.BeginTransaction();
  std::unique_ptr<storage::DataTable> data_table(
      ExecutorTestsUtil::CreateTable(tile_size));
  ExecutorTestsUtil::PopulateTable(data_table.get(), tile_size * 10, false,
                                   false, false);
  txn_manager.CommitTransaction();

  std::unique_ptr<executor::LogicalTile> ltile0(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0)));

  std::unique_ptr<executor::LogicalTile> ltile1(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1)));

  std::unique_ptr<executor::LogicalTile> ltile2(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(2)));

  EXPECT_CALL(child_executor1, GetOutput()).WillOnce(Return(ltile0.release()));

  EXPECT_CALL(child_executor2, GetOutput())
      .WillOnce(Return(ltile1.release()))
      .WillOnce(Return(ltile2.release()));

  RunTest(executor, tile_size * 3);
}
}
}
}
<|endoftext|>


<commit_before>// SPDX-License-Identifier: LGPL-2.1-or-later
/*
 * This file is part of libgpiod.
 *
 * Copyright (C) 2017-2018 Bartosz Golaszewski <bartekgola@gmail.com>
 */

#include <gpiod.hpp>

#include <system_error>
#include <map>

namespace gpiod {

namespace {

const ::std::map<int, int> reqtype_mapping = {
	{ line_request::DIRECTION_AS_IS,	GPIOD_LINE_REQUEST_DIRECTION_AS_IS, },
	{ line_request::DIRECTION_INPUT,	GPIOD_LINE_REQUEST_DIRECTION_INPUT, },
	{ line_request::DIRECTION_OUTPUT,	GPIOD_LINE_REQUEST_DIRECTION_OUTPUT, },
	{ line_request::EVENT_FALLING_EDGE,	GPIOD_LINE_REQUEST_EVENT_FALLING_EDGE, },
	{ line_request::EVENT_RISING_EDGE,	GPIOD_LINE_REQUEST_EVENT_RISING_EDGE, },
	{ line_request::EVENT_BOTH_EDGES,	GPIOD_LINE_REQUEST_EVENT_BOTH_EDGES, },
};

struct bitset_cmp
{
	bool operator()(const ::std::bitset<32>& lhs, const ::std::bitset<32>& rhs)
	{
		return lhs.to_ulong() < rhs.to_ulong();
	}
};

const ::std::map<::std::bitset<32>, int, bitset_cmp> reqflag_mapping = {
	{ line_request::FLAG_ACTIVE_LOW,	GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW, },
	{ line_request::FLAG_OPEN_DRAIN,	GPIOD_LINE_REQUEST_FLAG_OPEN_DRAIN, },
	{ line_request::FLAG_OPEN_SOURCE,	GPIOD_LINE_REQUEST_FLAG_OPEN_SOURCE, },
};

} /* namespace */

const ::std::bitset<32> line_request::FLAG_ACTIVE_LOW("001");
const ::std::bitset<32> line_request::FLAG_OPEN_SOURCE("010");
const ::std::bitset<32> line_request::FLAG_OPEN_DRAIN("100");

const unsigned int line_bulk::MAX_LINES = GPIOD_LINE_BULK_MAX_LINES;

line_bulk::line_bulk(const ::std::vector<line>& lines)
	: _m_bulk()
{
	this->_m_bulk.reserve(lines.size());

	for (auto& it: lines)
		this->append(it);
}

void line_bulk::append(const line& new_line)
{
	if (!new_line)
		throw ::std::logic_error("line_bulk cannot hold empty line objects");

	if (this->_m_bulk.size() >= MAX_LINES)
		throw ::std::logic_error("maximum number of lines reached");

	if (this->_m_bulk.size() >= 1 && this->_m_bulk.begin()->get_chip() != new_line.get_chip())
		throw std::logic_error("line_bulk cannot hold GPIO lines from different chips");

	this->_m_bulk.push_back(new_line);
}

line& line_bulk::get(unsigned int offset)
{
	return this->_m_bulk.at(offset);
}

line& line_bulk::operator[](unsigned int offset)
{
	return this->_m_bulk[offset];
}

unsigned int line_bulk::size(void) const noexcept
{
	return this->_m_bulk.size();
}

bool line_bulk::empty(void) const noexcept
{
	return this->_m_bulk.empty();
}

void line_bulk::clear(void)
{
	this->_m_bulk.clear();
}

void line_bulk::request(const line_request& config, const std::vector<int> default_vals) const
{
	this->throw_if_empty();

	if (!default_vals.empty() && this->size() != default_vals.size())
		throw ::std::invalid_argument("the number of default values must correspond with the number of lines");

	::gpiod_line_request_config conf;
	::gpiod_line_bulk bulk;
	int rv;

	this->to_line_bulk(::std::addressof(bulk));

	conf.consumer = config.consumer.c_str();
	conf.request_type = reqtype_mapping.at(config.request_type);
	conf.flags = 0;

	for (auto& it: reqflag_mapping) {
		if ((it.first & config.flags).to_ulong())
			conf.flags |= it.second;
	}

	rv = ::gpiod_line_request_bulk(::std::addressof(bulk),
				       ::std::addressof(conf),
				       default_vals.empty() ? NULL : default_vals.data());
	if (rv)
		throw ::std::system_error(errno, ::std::system_category(),
					  "error requesting GPIO lines");
}

void line_bulk::release(void) const
{
	this->throw_if_empty();

	::gpiod_line_bulk bulk;

	this->to_line_bulk(::std::addressof(bulk));

	::gpiod_line_release_bulk(::std::addressof(bulk));
}

::std::vector<int> line_bulk::get_values(void) const
{
	this->throw_if_empty();

	::std::vector<int> values;
	::gpiod_line_bulk bulk;
	int rv;

	this->to_line_bulk(::std::addressof(bulk));
	values.resize(this->_m_bulk.size());

	rv = ::gpiod_line_get_value_bulk(::std::addressof(bulk), values.data());
	if (rv)
		throw ::std::system_error(errno, ::std::system_category(),
					  "error reading GPIO line values");

	return ::std::move(values);
}

void line_bulk::set_values(const ::std::vector<int>& values) const
{
	this->throw_if_empty();

	if (values.size() != this->_m_bulk.size())
		throw ::std::invalid_argument("the size of values array must correspond with the number of lines");

	::gpiod_line_bulk bulk;
	int rv;

	this->to_line_bulk(::std::addressof(bulk));

	rv = ::gpiod_line_set_value_bulk(::std::addressof(bulk), values.data());
	if (rv)
		throw ::std::system_error(errno, ::std::system_category(),
					  "error setting GPIO line values");
}

line_bulk line_bulk::event_wait(const ::std::chrono::nanoseconds& timeout) const
{
	this->throw_if_empty();

	::gpiod_line_bulk bulk, event_bulk;
	::timespec ts;
	line_bulk ret;
	int rv;

	this->to_line_bulk(::std::addressof(bulk));

	::gpiod_line_bulk_init(::std::addressof(event_bulk));

	ts.tv_sec = timeout.count() / 1000000000ULL;
	ts.tv_nsec = timeout.count() % 1000000000ULL;

	rv = ::gpiod_line_event_wait_bulk(::std::addressof(bulk),
					  ::std::addressof(ts),
					  ::std::addressof(event_bulk));
	if (rv < 0) {
		throw ::std::system_error(errno, ::std::system_category(),
					  "error polling for events");
	} else if (rv > 0) {
		for (unsigned int i = 0; i < event_bulk.num_lines; i++)
			ret.append(line(event_bulk.lines[i], this->_m_bulk[i].get_chip()));
	}

	return ::std::move(ret);
}

line_bulk::operator bool(void) const noexcept
{
	return !this->_m_bulk.empty();
}

bool line_bulk::operator!(void) const noexcept
{
	return this->_m_bulk.empty();
}

line_bulk::iterator::iterator(const ::std::vector<line>::iterator& it)
	: _m_iter(it)
{

}

line_bulk::iterator& line_bulk::iterator::operator++(void)
{
	this->_m_iter++;

	return *this;
}

const line& line_bulk::iterator::operator*(void) const
{
	return *this->_m_iter;
}

const line* line_bulk::iterator::operator->(void) const
{
	return this->_m_iter.operator->();
}

bool line_bulk::iterator::operator==(const iterator& rhs) const noexcept
{
	return this->_m_iter == rhs._m_iter;
}

bool line_bulk::iterator::operator!=(const iterator& rhs) const noexcept
{
	return this->_m_iter != rhs._m_iter;
}

line_bulk::iterator line_bulk::begin(void) noexcept
{
	return ::std::move(line_bulk::iterator(this->_m_bulk.begin()));
}

line_bulk::iterator line_bulk::end(void) noexcept
{
	return ::std::move(line_bulk::iterator(this->_m_bulk.end()));
}

void line_bulk::throw_if_empty(void) const
{
	if (this->_m_bulk.empty())
		throw std::logic_error("line_bulk not holding any GPIO lines");
}

void line_bulk::to_line_bulk(::gpiod_line_bulk *bulk) const
{
	::gpiod_line_bulk_init(bulk);
	for (auto& it: this->_m_bulk)
		::gpiod_line_bulk_add(bulk, it._m_line);
}

} /* namespace gpiod */
<commit_msg>bindings: cxx: initialize the line_request flags before using them<commit_after>// SPDX-License-Identifier: LGPL-2.1-or-later
/*
 * This file is part of libgpiod.
 *
 * Copyright (C) 2017-2018 Bartosz Golaszewski <bartekgola@gmail.com>
 */

#include <gpiod.hpp>

#include <system_error>
#include <map>

namespace gpiod {

const ::std::bitset<32> line_request::FLAG_ACTIVE_LOW("001");
const ::std::bitset<32> line_request::FLAG_OPEN_SOURCE("010");
const ::std::bitset<32> line_request::FLAG_OPEN_DRAIN("100");

namespace {

const ::std::map<int, int> reqtype_mapping = {
	{ line_request::DIRECTION_AS_IS,	GPIOD_LINE_REQUEST_DIRECTION_AS_IS, },
	{ line_request::DIRECTION_INPUT,	GPIOD_LINE_REQUEST_DIRECTION_INPUT, },
	{ line_request::DIRECTION_OUTPUT,	GPIOD_LINE_REQUEST_DIRECTION_OUTPUT, },
	{ line_request::EVENT_FALLING_EDGE,	GPIOD_LINE_REQUEST_EVENT_FALLING_EDGE, },
	{ line_request::EVENT_RISING_EDGE,	GPIOD_LINE_REQUEST_EVENT_RISING_EDGE, },
	{ line_request::EVENT_BOTH_EDGES,	GPIOD_LINE_REQUEST_EVENT_BOTH_EDGES, },
};

struct bitset_cmp
{
	bool operator()(const ::std::bitset<32>& lhs, const ::std::bitset<32>& rhs)
	{
		return lhs.to_ulong() < rhs.to_ulong();
	}
};

const ::std::map<::std::bitset<32>, int, bitset_cmp> reqflag_mapping = {
	{ line_request::FLAG_ACTIVE_LOW,	GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW, },
	{ line_request::FLAG_OPEN_DRAIN,	GPIOD_LINE_REQUEST_FLAG_OPEN_DRAIN, },
	{ line_request::FLAG_OPEN_SOURCE,	GPIOD_LINE_REQUEST_FLAG_OPEN_SOURCE, },
};

} /* namespace */

const unsigned int line_bulk::MAX_LINES = GPIOD_LINE_BULK_MAX_LINES;

line_bulk::line_bulk(const ::std::vector<line>& lines)
	: _m_bulk()
{
	this->_m_bulk.reserve(lines.size());

	for (auto& it: lines)
		this->append(it);
}

void line_bulk::append(const line& new_line)
{
	if (!new_line)
		throw ::std::logic_error("line_bulk cannot hold empty line objects");

	if (this->_m_bulk.size() >= MAX_LINES)
		throw ::std::logic_error("maximum number of lines reached");

	if (this->_m_bulk.size() >= 1 && this->_m_bulk.begin()->get_chip() != new_line.get_chip())
		throw std::logic_error("line_bulk cannot hold GPIO lines from different chips");

	this->_m_bulk.push_back(new_line);
}

line& line_bulk::get(unsigned int offset)
{
	return this->_m_bulk.at(offset);
}

line& line_bulk::operator[](unsigned int offset)
{
	return this->_m_bulk[offset];
}

unsigned int line_bulk::size(void) const noexcept
{
	return this->_m_bulk.size();
}

bool line_bulk::empty(void) const noexcept
{
	return this->_m_bulk.empty();
}

void line_bulk::clear(void)
{
	this->_m_bulk.clear();
}

void line_bulk::request(const line_request& config, const std::vector<int> default_vals) const
{
	this->throw_if_empty();

	if (!default_vals.empty() && this->size() != default_vals.size())
		throw ::std::invalid_argument("the number of default values must correspond with the number of lines");

	::gpiod_line_request_config conf;
	::gpiod_line_bulk bulk;
	int rv;

	this->to_line_bulk(::std::addressof(bulk));

	conf.consumer = config.consumer.c_str();
	conf.request_type = reqtype_mapping.at(config.request_type);
	conf.flags = 0;

	for (auto& it: reqflag_mapping) {
		if ((it.first & config.flags).to_ulong())
			conf.flags |= it.second;
	}

	rv = ::gpiod_line_request_bulk(::std::addressof(bulk),
				       ::std::addressof(conf),
				       default_vals.empty() ? NULL : default_vals.data());
	if (rv)
		throw ::std::system_error(errno, ::std::system_category(),
					  "error requesting GPIO lines");
}

void line_bulk::release(void) const
{
	this->throw_if_empty();

	::gpiod_line_bulk bulk;

	this->to_line_bulk(::std::addressof(bulk));

	::gpiod_line_release_bulk(::std::addressof(bulk));
}

::std::vector<int> line_bulk::get_values(void) const
{
	this->throw_if_empty();

	::std::vector<int> values;
	::gpiod_line_bulk bulk;
	int rv;

	this->to_line_bulk(::std::addressof(bulk));
	values.resize(this->_m_bulk.size());

	rv = ::gpiod_line_get_value_bulk(::std::addressof(bulk), values.data());
	if (rv)
		throw ::std::system_error(errno, ::std::system_category(),
					  "error reading GPIO line values");

	return ::std::move(values);
}

void line_bulk::set_values(const ::std::vector<int>& values) const
{
	this->throw_if_empty();

	if (values.size() != this->_m_bulk.size())
		throw ::std::invalid_argument("the size of values array must correspond with the number of lines");

	::gpiod_line_bulk bulk;
	int rv;

	this->to_line_bulk(::std::addressof(bulk));

	rv = ::gpiod_line_set_value_bulk(::std::addressof(bulk), values.data());
	if (rv)
		throw ::std::system_error(errno, ::std::system_category(),
					  "error setting GPIO line values");
}

line_bulk line_bulk::event_wait(const ::std::chrono::nanoseconds& timeout) const
{
	this->throw_if_empty();

	::gpiod_line_bulk bulk, event_bulk;
	::timespec ts;
	line_bulk ret;
	int rv;

	this->to_line_bulk(::std::addressof(bulk));

	::gpiod_line_bulk_init(::std::addressof(event_bulk));

	ts.tv_sec = timeout.count() / 1000000000ULL;
	ts.tv_nsec = timeout.count() % 1000000000ULL;

	rv = ::gpiod_line_event_wait_bulk(::std::addressof(bulk),
					  ::std::addressof(ts),
					  ::std::addressof(event_bulk));
	if (rv < 0) {
		throw ::std::system_error(errno, ::std::system_category(),
					  "error polling for events");
	} else if (rv > 0) {
		for (unsigned int i = 0; i < event_bulk.num_lines; i++)
			ret.append(line(event_bulk.lines[i], this->_m_bulk[i].get_chip()));
	}

	return ::std::move(ret);
}

line_bulk::operator bool(void) const noexcept
{
	return !this->_m_bulk.empty();
}

bool line_bulk::operator!(void) const noexcept
{
	return this->_m_bulk.empty();
}

line_bulk::iterator::iterator(const ::std::vector<line>::iterator& it)
	: _m_iter(it)
{

}

line_bulk::iterator& line_bulk::iterator::operator++(void)
{
	this->_m_iter++;

	return *this;
}

const line& line_bulk::iterator::operator*(void) const
{
	return *this->_m_iter;
}

const line* line_bulk::iterator::operator->(void) const
{
	return this->_m_iter.operator->();
}

bool line_bulk::iterator::operator==(const iterator& rhs) const noexcept
{
	return this->_m_iter == rhs._m_iter;
}

bool line_bulk::iterator::operator!=(const iterator& rhs) const noexcept
{
	return this->_m_iter != rhs._m_iter;
}

line_bulk::iterator line_bulk::begin(void) noexcept
{
	return ::std::move(line_bulk::iterator(this->_m_bulk.begin()));
}

line_bulk::iterator line_bulk::end(void) noexcept
{
	return ::std::move(line_bulk::iterator(this->_m_bulk.end()));
}

void line_bulk::throw_if_empty(void) const
{
	if (this->_m_bulk.empty())
		throw std::logic_error("line_bulk not holding any GPIO lines");
}

void line_bulk::to_line_bulk(::gpiod_line_bulk *bulk) const
{
	::gpiod_line_bulk_init(bulk);
	for (auto& it: this->_m_bulk)
		::gpiod_line_bulk_add(bulk, it._m_line);
}

} /* namespace gpiod */
<|endoftext|>


<commit_before>#include "selfdrive/ui/qt/widgets/keyboard.h"

#include <vector>

#include <QButtonGroup>
#include <QHBoxLayout>
#include <QMap>
#include <QTouchEvent>
#include <QVBoxLayout>

const QString BACKSPACE_KEY = "⌫";
const QString ENTER_KEY = "→";

const QMap<QString, int> KEY_STRETCH = {{"  ", 5}, {ENTER_KEY, 2}};

const QStringList CONTROL_BUTTONS = {"↑", "↓", "ABC", "#+=", "123", BACKSPACE_KEY, ENTER_KEY};

const float key_spacing_vertical = 20;
const float key_spacing_horizontal = 15;

KeyButton::KeyButton(const QString &text, QWidget *parent) : QPushButton(text, parent) {
  setAttribute(Qt::WA_AcceptTouchEvents);
  setFocusPolicy(Qt::NoFocus);
}

bool KeyButton::event(QEvent *event) {
  if (event->type() == QEvent::TouchBegin || event->type() == QEvent::TouchEnd) {
    QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
    if (!touchEvent->touchPoints().empty()) {
      const QEvent::Type mouseType = event->type() == QEvent::TouchBegin ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease;
      QMouseEvent mouseEvent(mouseType, touchEvent->touchPoints().front().pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
      QPushButton::event(&mouseEvent);
      event->accept();
      parentWidget()->update();
      return true;
    }
  }
  return QPushButton::event(event);
}

KeyboardLayout::KeyboardLayout(QWidget* parent, const std::vector<QVector<QString>>& layout) : QWidget(parent) {
  QVBoxLayout* main_layout = new QVBoxLayout(this);
  main_layout->setMargin(0);
  main_layout->setSpacing(0);

  QButtonGroup* btn_group = new QButtonGroup(this);
  QObject::connect(btn_group, SIGNAL(buttonClicked(QAbstractButton*)), parent, SLOT(handleButton(QAbstractButton*)));

  for (const auto &s : layout) {
    QHBoxLayout *hlayout = new QHBoxLayout;
    hlayout->setSpacing(0);

    if (main_layout->count() == 1) {
      hlayout->addSpacing(90);
    }

    for (const QString &p : s) {
      KeyButton* btn = new KeyButton(p);
      if (p == BACKSPACE_KEY) {
        btn->setAutoRepeat(true);
      } else if (p == ENTER_KEY) {
        btn->setStyleSheet("background-color: #465BEA;");
      }
      btn->setFixedHeight(135 + key_spacing_vertical);
      btn_group->addButton(btn);
      hlayout->addWidget(btn, KEY_STRETCH.value(p, 1));
    }

    if (main_layout->count() == 1) {
      hlayout->addSpacing(90);
    }

    main_layout->addLayout(hlayout);
  }

  setStyleSheet(QString(R"(
    QPushButton {
      font-size: 75px;
      margin-left: %1px;
      margin-right: %1px;
      margin-top: %2px;
      margin-bottom: %2px;
      padding: 0px;
      border-radius: 10px;
      color: #dddddd;
      background-color: #444444;
    }
    QPushButton:pressed {
      background-color: #333333;
    }
  )").arg(key_spacing_vertical / 2).arg(key_spacing_horizontal / 2));
}

Keyboard::Keyboard(QWidget *parent) : QFrame(parent) {
  main_layout = new QStackedLayout(this);
  main_layout->setMargin(0);

  // lowercase
  std::vector<QVector<QString>> lowercase = {
    {"q","w","e","r","t","y","u","i","o","p"},
    {"a","s","d","f","g","h","j","k","l"},
    {"↑","z","x","c","v","b","n","m",BACKSPACE_KEY},
    {"123","  ",".",ENTER_KEY},
  };
  main_layout->addWidget(new KeyboardLayout(this, lowercase));

  // uppercase
  std::vector<QVector<QString>> uppercase = {
    {"Q","W","E","R","T","Y","U","I","O","P"},
    {"A","S","D","F","G","H","J","K","L"},
    {"↓","Z","X","C","V","B","N","M",BACKSPACE_KEY},
    {"123","  ",".",ENTER_KEY},
  };
  main_layout->addWidget(new KeyboardLayout(this, uppercase));

  // numbers + specials
  std::vector<QVector<QString>> numbers = {
    {"1","2","3","4","5","6","7","8","9","0"},
    {"-","/",":",";","(",")","$","&&","@","\""},
    {"#+=",".",",","?","!","`",BACKSPACE_KEY},
    {"ABC","  ",".",ENTER_KEY},
  };
  main_layout->addWidget(new KeyboardLayout(this, numbers));

  // extra specials
  std::vector<QVector<QString>> specials = {
    {"[","]","{","}","#","%","^","*","+","="},
    {"_","\\","|","~","<",">","€","£","¥","•"},
    {"123",".",",","?","!","`",BACKSPACE_KEY},
    {"ABC","  ",".",ENTER_KEY},
  };
  main_layout->addWidget(new KeyboardLayout(this, specials));

  main_layout->setCurrentIndex(0);
}

void Keyboard::handleButton(QAbstractButton* btn) {
  const QString &key = btn->text();
  if (CONTROL_BUTTONS.contains(key)) {
    if (key == "↓" || key == "ABC") {
      main_layout->setCurrentIndex(0);
    } else if (key == "↑") {
      main_layout->setCurrentIndex(1);
    } else if (key == "123") {
      main_layout->setCurrentIndex(2);
    } else if (key == "#+=") {
      main_layout->setCurrentIndex(3);
    } else if (key == ENTER_KEY) {
      main_layout->setCurrentIndex(0);
      emit emitEnter();
    } else if (key == BACKSPACE_KEY) {
      emit emitBackspace();
    }
  } else {
    if ("A" <= key && key <= "Z") {
      main_layout->setCurrentIndex(0);
    }
    emit emitKey(key);
  }
}
<commit_msg>keyboard: replace backtick with apostrophe (#23104)<commit_after>#include "selfdrive/ui/qt/widgets/keyboard.h"

#include <vector>

#include <QButtonGroup>
#include <QHBoxLayout>
#include <QMap>
#include <QTouchEvent>
#include <QVBoxLayout>

const QString BACKSPACE_KEY = "⌫";
const QString ENTER_KEY = "→";

const QMap<QString, int> KEY_STRETCH = {{"  ", 5}, {ENTER_KEY, 2}};

const QStringList CONTROL_BUTTONS = {"↑", "↓", "ABC", "#+=", "123", BACKSPACE_KEY, ENTER_KEY};

const float key_spacing_vertical = 20;
const float key_spacing_horizontal = 15;

KeyButton::KeyButton(const QString &text, QWidget *parent) : QPushButton(text, parent) {
  setAttribute(Qt::WA_AcceptTouchEvents);
  setFocusPolicy(Qt::NoFocus);
}

bool KeyButton::event(QEvent *event) {
  if (event->type() == QEvent::TouchBegin || event->type() == QEvent::TouchEnd) {
    QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
    if (!touchEvent->touchPoints().empty()) {
      const QEvent::Type mouseType = event->type() == QEvent::TouchBegin ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease;
      QMouseEvent mouseEvent(mouseType, touchEvent->touchPoints().front().pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
      QPushButton::event(&mouseEvent);
      event->accept();
      parentWidget()->update();
      return true;
    }
  }
  return QPushButton::event(event);
}

KeyboardLayout::KeyboardLayout(QWidget* parent, const std::vector<QVector<QString>>& layout) : QWidget(parent) {
  QVBoxLayout* main_layout = new QVBoxLayout(this);
  main_layout->setMargin(0);
  main_layout->setSpacing(0);

  QButtonGroup* btn_group = new QButtonGroup(this);
  QObject::connect(btn_group, SIGNAL(buttonClicked(QAbstractButton*)), parent, SLOT(handleButton(QAbstractButton*)));

  for (const auto &s : layout) {
    QHBoxLayout *hlayout = new QHBoxLayout;
    hlayout->setSpacing(0);

    if (main_layout->count() == 1) {
      hlayout->addSpacing(90);
    }

    for (const QString &p : s) {
      KeyButton* btn = new KeyButton(p);
      if (p == BACKSPACE_KEY) {
        btn->setAutoRepeat(true);
      } else if (p == ENTER_KEY) {
        btn->setStyleSheet("background-color: #465BEA;");
      }
      btn->setFixedHeight(135 + key_spacing_vertical);
      btn_group->addButton(btn);
      hlayout->addWidget(btn, KEY_STRETCH.value(p, 1));
    }

    if (main_layout->count() == 1) {
      hlayout->addSpacing(90);
    }

    main_layout->addLayout(hlayout);
  }

  setStyleSheet(QString(R"(
    QPushButton {
      font-size: 75px;
      margin-left: %1px;
      margin-right: %1px;
      margin-top: %2px;
      margin-bottom: %2px;
      padding: 0px;
      border-radius: 10px;
      color: #dddddd;
      background-color: #444444;
    }
    QPushButton:pressed {
      background-color: #333333;
    }
  )").arg(key_spacing_vertical / 2).arg(key_spacing_horizontal / 2));
}

Keyboard::Keyboard(QWidget *parent) : QFrame(parent) {
  main_layout = new QStackedLayout(this);
  main_layout->setMargin(0);

  // lowercase
  std::vector<QVector<QString>> lowercase = {
    {"q","w","e","r","t","y","u","i","o","p"},
    {"a","s","d","f","g","h","j","k","l"},
    {"↑","z","x","c","v","b","n","m",BACKSPACE_KEY},
    {"123","  ",".",ENTER_KEY},
  };
  main_layout->addWidget(new KeyboardLayout(this, lowercase));

  // uppercase
  std::vector<QVector<QString>> uppercase = {
    {"Q","W","E","R","T","Y","U","I","O","P"},
    {"A","S","D","F","G","H","J","K","L"},
    {"↓","Z","X","C","V","B","N","M",BACKSPACE_KEY},
    {"123","  ",".",ENTER_KEY},
  };
  main_layout->addWidget(new KeyboardLayout(this, uppercase));

  // numbers + specials
  std::vector<QVector<QString>> numbers = {
    {"1","2","3","4","5","6","7","8","9","0"},
    {"-","/",":",";","(",")","$","&&","@","\""},
    {"#+=",".",",","?","!","`",BACKSPACE_KEY},
    {"ABC","  ",".",ENTER_KEY},
  };
  main_layout->addWidget(new KeyboardLayout(this, numbers));

  // extra specials
  std::vector<QVector<QString>> specials = {
    {"[","]","{","}","#","%","^","*","+","="},
    {"_","\\","|","~","<",">","€","£","¥","•"},
    {"123",".",",","?","!","'",BACKSPACE_KEY},
    {"ABC","  ",".",ENTER_KEY},
  };
  main_layout->addWidget(new KeyboardLayout(this, specials));

  main_layout->setCurrentIndex(0);
}

void Keyboard::handleButton(QAbstractButton* btn) {
  const QString &key = btn->text();
  if (CONTROL_BUTTONS.contains(key)) {
    if (key == "↓" || key == "ABC") {
      main_layout->setCurrentIndex(0);
    } else if (key == "↑") {
      main_layout->setCurrentIndex(1);
    } else if (key == "123") {
      main_layout->setCurrentIndex(2);
    } else if (key == "#+=") {
      main_layout->setCurrentIndex(3);
    } else if (key == ENTER_KEY) {
      main_layout->setCurrentIndex(0);
      emit emitEnter();
    } else if (key == BACKSPACE_KEY) {
      emit emitBackspace();
    }
  } else {
    if ("A" <= key && key <= "Z") {
      main_layout->setCurrentIndex(0);
    }
    emit emitKey(key);
  }
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Epg.cpp : Epg Viewer dialog
 ****************************************************************************
 * Copyright © 2010 VideoLAN and AUTHORS
 *
 * Authors:    Jean-Baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "dialogs/epg.hpp"

#include "components/epg/EPGWidget.hpp"

#include <QVBoxLayout>
#include <QSplitter>
#include <QLabel>
#include <QGroupBox>
#include <QPushButton>
#include <QTextEdit>

#include "qt4.hpp"
#include "input_manager.hpp"

EpgDialog::EpgDialog( intf_thread_t *_p_intf ): QVLCFrame( _p_intf )
{
    setWindowTitle( qtr( "Program Guide" ) );

    QVBoxLayout *layout = new QVBoxLayout( this );
    layout->setMargin( 0 );
    epg = new EPGWidget( this );

    QGroupBox *descBox = new QGroupBox( qtr( "Description" ), this );

    QVBoxLayout *boxLayout = new QVBoxLayout( descBox );

    description = new QTextEdit( this );
    description->setReadOnly( true );
    description->setFrameStyle( QFrame::Sunken | QFrame::StyledPanel );
    description->setAutoFillBackground( true );
    description->setAlignment( Qt::AlignLeft | Qt::AlignTop );
    description->setFixedHeight( 100 );

    QPalette palette;
    palette.setBrush(QPalette::Active, QPalette::Window, palette.brush( QPalette::Base ) );
    description->setPalette( palette );

    title = new QLabel( qtr( "Title" ), this );

    boxLayout->addWidget( title );
    boxLayout->addWidget( description );

    layout->addWidget( epg, 10 );
    layout->addWidget( descBox );

    CONNECT( epg, itemSelectionChanged( EPGEvent *), this, showEvent( EPGEvent *) );
    CONNECT( THEMIM->getIM(), epgChanged(), this, updateInfos() );

    QPushButton *update = new QPushButton( qtr( "Update" ) ); //Temporary to test
    layout->addWidget( update, 0, Qt::AlignRight );
    BUTTONACT( update, updateInfos() );

    QPushButton *close = new QPushButton( qtr( "&Close" ) );
    layout->addWidget( close, 0, Qt::AlignRight );
    BUTTONACT( close, close() );

    updateInfos();
    readSettings( "EPGDialog", QSize( 650, 450 ) );
}

EpgDialog::~EpgDialog()
{
    writeSettings( "EPGDialog" );
}

void EpgDialog::showEvent( EPGEvent *event )
{
    if( !event ) return;

    QDateTime end = event->start.addSecs( event->duration );
    title->setText( event->start.toString( "hh:mm" ) + " - "
                    + end.toString( "hh:mm" ) + " : "
                    + event->name );

    if( !event->description.isEmpty() )
        description->setText( event->description );
    else
        description->setText( event->shortDescription );
}

void EpgDialog::updateInfos()
{
    if( !THEMIM->getInput() ) return;

    msg_Dbg( p_intf, "Found %i EPG items", input_GetItem( THEMIM->getInput())->i_epg);
    epg->updateEPG( input_GetItem( THEMIM->getInput())->pp_epg, input_GetItem( THEMIM->getInput())->i_epg );

}
<commit_msg>Qt/EPG: Display the short description and the long one when available.<commit_after>/*****************************************************************************
 * Epg.cpp : Epg Viewer dialog
 ****************************************************************************
 * Copyright © 2010 VideoLAN and AUTHORS
 *
 * Authors:    Jean-Baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "dialogs/epg.hpp"

#include "components/epg/EPGWidget.hpp"

#include <QVBoxLayout>
#include <QSplitter>
#include <QLabel>
#include <QGroupBox>
#include <QPushButton>
#include <QTextEdit>

#include "qt4.hpp"
#include "input_manager.hpp"

EpgDialog::EpgDialog( intf_thread_t *_p_intf ): QVLCFrame( _p_intf )
{
    setWindowTitle( qtr( "Program Guide" ) );

    QVBoxLayout *layout = new QVBoxLayout( this );
    layout->setMargin( 0 );
    epg = new EPGWidget( this );

    QGroupBox *descBox = new QGroupBox( qtr( "Description" ), this );

    QVBoxLayout *boxLayout = new QVBoxLayout( descBox );

    description = new QTextEdit( this );
    description->setReadOnly( true );
    description->setFrameStyle( QFrame::Sunken | QFrame::StyledPanel );
    description->setAutoFillBackground( true );
    description->setAlignment( Qt::AlignLeft | Qt::AlignTop );
    description->setFixedHeight( 100 );

    QPalette palette;
    palette.setBrush(QPalette::Active, QPalette::Window, palette.brush( QPalette::Base ) );
    description->setPalette( palette );

    title = new QLabel( qtr( "Title" ), this );

    boxLayout->addWidget( title );
    boxLayout->addWidget( description );

    layout->addWidget( epg, 10 );
    layout->addWidget( descBox );

    CONNECT( epg, itemSelectionChanged( EPGEvent *), this, showEvent( EPGEvent *) );
    CONNECT( THEMIM->getIM(), epgChanged(), this, updateInfos() );

    QPushButton *update = new QPushButton( qtr( "Update" ) ); //Temporary to test
    layout->addWidget( update, 0, Qt::AlignRight );
    BUTTONACT( update, updateInfos() );

    QPushButton *close = new QPushButton( qtr( "&Close" ) );
    layout->addWidget( close, 0, Qt::AlignRight );
    BUTTONACT( close, close() );

    updateInfos();
    readSettings( "EPGDialog", QSize( 650, 450 ) );
}

EpgDialog::~EpgDialog()
{
    writeSettings( "EPGDialog" );
}

void EpgDialog::showEvent( EPGEvent *event )
{
    if( !event ) return;

    QDateTime end = event->start.addSecs( event->duration );
    title->setText( event->start.toString( "hh:mm" ) + " - "
                    + end.toString( "hh:mm" ) + " : "
                    + event->name
                    + ( event->shortDescription.isEmpty()
                        ? "" : " - " + event->shortDescription ) );

    description->setText( event->description );
}

void EpgDialog::updateInfos()
{
    if( !THEMIM->getInput() ) return;

    msg_Dbg( p_intf, "Found %i EPG items", input_GetItem( THEMIM->getInput())->i_epg);
    epg->updateEPG( input_GetItem( THEMIM->getInput())->pp_epg, input_GetItem( THEMIM->getInput())->i_epg );

}
<|endoftext|>