<commit_before>#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <iostream>

namespace {

class OpenMeshVectorTest : public testing::Test {

    protected:

        // This function is called before each test is run
        virtual void SetUp() {

            // Do some initial stuff with the member data here...
        }

        // This function is called after all tests are through
        virtual void TearDown() {

            // Do some final stuff with the member data here...
        }

};

/*
 * ====================================================================
 * Define tests below
 * ====================================================================
 */

/* Compute surface area via cross product
 */
TEST_F(OpenMeshVectorTest, ComputeTriangleSurfaceWithCrossProduct) {

  //
  // vec1
  //  x
  //  |
  //  |
  //  |
  //  x------>x vec2
  //

  OpenMesh::Vec3d vec1(0.0,1.0,0.0);
  OpenMesh::Vec3d vec2(1.0,0.0,0.0);

  double area = 0.5 * cross(vec1,vec2).norm();
  EXPECT_EQ(0.5f , area ) << "Wrong area in cross product function";

  area = 0.5 * ( vec1 % vec2 ).norm();
  EXPECT_EQ(0.5f , area ) << "Wrong area in cross product operator";

}

/* Check OpenMesh Vector type abs function
 */
TEST_F(OpenMeshVectorTest, AbsTest) {

  OpenMesh::Vec3d vec1(0.5,0.5,-0.5);

  EXPECT_EQ( vec1.l8_norm() , 0.5f ) << "Wrong l8norm computation";

}

/* Compute surface area via cross product
 */
TEST_F(OpenMeshVectorTest, VectorCasting) {

  OpenMesh::Vec3d vecd(1.0,2.0,3.0);
  OpenMesh::Vec3f vecf = OpenMesh::vector_cast<OpenMesh::Vec3f>(vecd);
  EXPECT_EQ(1.f, vecf[0]) << "vector type cast failed on component 0";
  EXPECT_EQ(2.f, vecf[1]) << "vector type cast failed on component 1";
  EXPECT_EQ(3.f, vecf[2]) << "vector type cast failed on component 2";

  OpenMesh::Vec4d vecd4(40.0,30.0,20.0,10.0);
  vecd = OpenMesh::vector_cast<OpenMesh::Vec3d>(vecd4);
  EXPECT_EQ(40.0, vecd[0]) << "vector dimension cast failed on component 0";
  EXPECT_EQ(30.0, vecd[1]) << "vector dimension cast failed on component 1";
  EXPECT_EQ(20.0, vecd[2]) << "vector dimension cast failed on component 2";

}

#if __cplusplus > 199711L || defined(__GXX_EXPERIMENTAL_CXX0X__)
TEST_F(OpenMeshVectorTest, cpp11_constructors) {
    OpenMesh::Vec3d vec1 { 1.2, 2.0, 3.0 };

    EXPECT_EQ(1.2, vec1[0]);
    EXPECT_EQ(2.0, vec1[1]);
    EXPECT_EQ(3.0, vec1[2]);

    OpenMesh::Vec4f vec2 { 1.2f, 3.5f, 1.0f, 0.0f };

    EXPECT_EQ(1.2f, vec2[0]);
    EXPECT_EQ(3.5f, vec2[1]);
    EXPECT_EQ(1.0f, vec2[2]);
    EXPECT_EQ(0.0f, vec2[3]);

    OpenMesh::Vec4f vec2b { vec2 };

    EXPECT_EQ(1.2f, vec2b[0]);
    EXPECT_EQ(3.5f, vec2b[1]);
    EXPECT_EQ(1.0f, vec2b[2]);
    EXPECT_EQ(0.0f, vec2b[3]);

    OpenMesh::Vec4d vec4d { 1.23 };
    EXPECT_EQ(1.23, vec4d[0]);
    EXPECT_EQ(1.23, vec4d[1]);
    EXPECT_EQ(1.23, vec4d[2]);
    EXPECT_EQ(1.23, vec4d[3]);
}

TEST_F(OpenMeshVectorTest, cpp11_htmlColorLiteral) {
    static constexpr OpenMesh::Vec4f rose = 0xFFC7F1FF_htmlColor;

    EXPECT_EQ(0xFFC7F1FF_htmlColor, rose);

    const OpenMesh::Vec4f light_blue = 0x1FCFFFFF_htmlColor;
    EXPECT_LE((OpenMesh::Vec4f(0.1215686274f, 0.8117647058f, 1.0f, 1.0f)
        - light_blue).sqrnorm(), 1e-10);

    const auto light_blue_2 = 0x1FCFFFFF_htmlColor;
    // Check whether auto type deduction works as expected.
    static_assert(std::is_same<decltype(light_blue_2), decltype(light_blue)>
        ::value, "Bad type deduced from _htmlColor literal.");
    EXPECT_EQ(light_blue, light_blue_2);
}

namespace {
class C {
    public:
        C() {}
        C(const C &rhs) { ADD_FAILURE() << "Copy constructor used."; }
        C(C &&rhs) { ++copy_con; }
        C &operator= (const C &rhs) {
            ADD_FAILURE() << "Copy assignemnt used.";
            return *this;
        }
        C &operator= (C &&rhs) { ++copy_ass; return *this; }

        static int copy_con;
        static int copy_ass;
};

int C::copy_con = 0;
int C::copy_ass = 0;
}

/**
 * Checks two things:
 *   1) Whether VectorT works with a non-arithmetic type.
 *   2) Whether move construction and assignment works.
 */
TEST_F(OpenMeshVectorTest, move_constructor_assignment) {

    C::copy_con = 0;
    C::copy_ass = 0;

    // Test move assigning.
    OpenMesh::VectorT<C, 3> x, y;
    x = std::move(y);
    EXPECT_EQ(3, C::copy_ass);
    EXPECT_EQ(0, C::copy_con);

    // Test move constructing.
    OpenMesh::VectorT<C, 3> z(std::move(x));
    EXPECT_EQ(3, C::copy_ass);
    EXPECT_EQ(3, C::copy_con);
}

#endif // C++11

TEST_F(OpenMeshVectorTest, BasicLinearAlgebra) {
    OpenMesh::Vec3d v(1, 2, 3);
    EXPECT_EQ(v[0], 1.0);
    EXPECT_EQ(v[1], 2.0);
    EXPECT_EQ(v[2], 3.0);

    EXPECT_EQ(OpenMesh::Vec3d(-1, -2, -3), -v);
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, 2).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 2, 3).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, -4).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(-4, 2, 3).max());
    EXPECT_EQ(4, OpenMesh::Vec3d(1, 3, -4).max_abs());
    EXPECT_EQ(4, OpenMesh::Vec3d(-4, 2, 3).max_abs());

    EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, 2).min());
    EXPECT_EQ(1, OpenMesh::Vec3d(1, 2, 3).min());
    EXPECT_EQ(-4, OpenMesh::Vec3d(1, 3, -4).min());
    EXPECT_EQ(-4, OpenMesh::Vec3d(-4, 2, 3).min());
    EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, -4).min_abs());
    EXPECT_EQ(2, OpenMesh::Vec3d(-4, 2, 3).min_abs());

    EXPECT_NEAR(14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(1, 2, 3), 1e-6);
    EXPECT_NEAR(-14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6);
    EXPECT_NEAR(14, OpenMesh::Vec3d(-1, -2, -3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6);
}

TEST_F(OpenMeshVectorTest, normalized_cond) {
    OpenMesh::Vec3d v1(1, -2, 3), v2(0, 0, 0);
    EXPECT_EQ(OpenMesh::Vec3d(0, 0, 0), v2.normalize_cond());
    const auto r1 = OpenMesh::Vec3d(0.2672612419124244, -0.5345224838248488, 0.8017837257372732) - v1.normalize_cond();
    EXPECT_NEAR(r1[0], 0.0, 1e-12);
    EXPECT_NEAR(r1[1], 0.0, 1e-12);
    EXPECT_NEAR(r1[2], 0.0, 1e-12);
}

TEST_F(OpenMeshVectorTest, size_dim) {
    OpenMesh::Vec3d v3d(1, 2, 3);
    OpenMesh::Vec3f v3f(1, 2, 3);
    OpenMesh::Vec2i v2i(1, 2);

    EXPECT_EQ(3u, v3d.size());
    EXPECT_EQ(3, v3d.dim());
    EXPECT_EQ(3u, v3f.size());
    EXPECT_EQ(3, v3f.dim());
    EXPECT_EQ(2u, v2i.size());
    EXPECT_EQ(2, v2i.dim());
}

}
<commit_msg>C++11: Made a unit test C++98 compatible.<commit_after>#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <iostream>

namespace {

class OpenMeshVectorTest : public testing::Test {

    protected:

        // This function is called before each test is run
        virtual void SetUp() {

            // Do some initial stuff with the member data here...
        }

        // This function is called after all tests are through
        virtual void TearDown() {

            // Do some final stuff with the member data here...
        }

};

/*
 * ====================================================================
 * Define tests below
 * ====================================================================
 */

/* Compute surface area via cross product
 */
TEST_F(OpenMeshVectorTest, ComputeTriangleSurfaceWithCrossProduct) {

  //
  // vec1
  //  x
  //  |
  //  |
  //  |
  //  x------>x vec2
  //

  OpenMesh::Vec3d vec1(0.0,1.0,0.0);
  OpenMesh::Vec3d vec2(1.0,0.0,0.0);

  double area = 0.5 * cross(vec1,vec2).norm();
  EXPECT_EQ(0.5f , area ) << "Wrong area in cross product function";

  area = 0.5 * ( vec1 % vec2 ).norm();
  EXPECT_EQ(0.5f , area ) << "Wrong area in cross product operator";

}

/* Check OpenMesh Vector type abs function
 */
TEST_F(OpenMeshVectorTest, AbsTest) {

  OpenMesh::Vec3d vec1(0.5,0.5,-0.5);

  EXPECT_EQ( vec1.l8_norm() , 0.5f ) << "Wrong l8norm computation";

}

/* Compute surface area via cross product
 */
TEST_F(OpenMeshVectorTest, VectorCasting) {

  OpenMesh::Vec3d vecd(1.0,2.0,3.0);
  OpenMesh::Vec3f vecf = OpenMesh::vector_cast<OpenMesh::Vec3f>(vecd);
  EXPECT_EQ(1.f, vecf[0]) << "vector type cast failed on component 0";
  EXPECT_EQ(2.f, vecf[1]) << "vector type cast failed on component 1";
  EXPECT_EQ(3.f, vecf[2]) << "vector type cast failed on component 2";

  OpenMesh::Vec4d vecd4(40.0,30.0,20.0,10.0);
  vecd = OpenMesh::vector_cast<OpenMesh::Vec3d>(vecd4);
  EXPECT_EQ(40.0, vecd[0]) << "vector dimension cast failed on component 0";
  EXPECT_EQ(30.0, vecd[1]) << "vector dimension cast failed on component 1";
  EXPECT_EQ(20.0, vecd[2]) << "vector dimension cast failed on component 2";

}

#if __cplusplus > 199711L || defined(__GXX_EXPERIMENTAL_CXX0X__)
TEST_F(OpenMeshVectorTest, cpp11_constructors) {
    OpenMesh::Vec3d vec1 { 1.2, 2.0, 3.0 };

    EXPECT_EQ(1.2, vec1[0]);
    EXPECT_EQ(2.0, vec1[1]);
    EXPECT_EQ(3.0, vec1[2]);

    OpenMesh::Vec4f vec2 { 1.2f, 3.5f, 1.0f, 0.0f };

    EXPECT_EQ(1.2f, vec2[0]);
    EXPECT_EQ(3.5f, vec2[1]);
    EXPECT_EQ(1.0f, vec2[2]);
    EXPECT_EQ(0.0f, vec2[3]);

    OpenMesh::Vec4f vec2b { vec2 };

    EXPECT_EQ(1.2f, vec2b[0]);
    EXPECT_EQ(3.5f, vec2b[1]);
    EXPECT_EQ(1.0f, vec2b[2]);
    EXPECT_EQ(0.0f, vec2b[3]);

    OpenMesh::Vec4d vec4d { 1.23 };
    EXPECT_EQ(1.23, vec4d[0]);
    EXPECT_EQ(1.23, vec4d[1]);
    EXPECT_EQ(1.23, vec4d[2]);
    EXPECT_EQ(1.23, vec4d[3]);
}

TEST_F(OpenMeshVectorTest, cpp11_htmlColorLiteral) {
    static constexpr OpenMesh::Vec4f rose = 0xFFC7F1FF_htmlColor;

    EXPECT_EQ(0xFFC7F1FF_htmlColor, rose);

    const OpenMesh::Vec4f light_blue = 0x1FCFFFFF_htmlColor;
    EXPECT_LE((OpenMesh::Vec4f(0.1215686274f, 0.8117647058f, 1.0f, 1.0f)
        - light_blue).sqrnorm(), 1e-10);

    const auto light_blue_2 = 0x1FCFFFFF_htmlColor;
    // Check whether auto type deduction works as expected.
    static_assert(std::is_same<decltype(light_blue_2), decltype(light_blue)>
        ::value, "Bad type deduced from _htmlColor literal.");
    EXPECT_EQ(light_blue, light_blue_2);
}

namespace {
class C {
    public:
        C() {}
        C(const C &rhs) { ADD_FAILURE() << "Copy constructor used."; }
        C(C &&rhs) { ++copy_con; }
        C &operator= (const C &rhs) {
            ADD_FAILURE() << "Copy assignemnt used.";
            return *this;
        }
        C &operator= (C &&rhs) { ++copy_ass; return *this; }

        static int copy_con;
        static int copy_ass;
};

int C::copy_con = 0;
int C::copy_ass = 0;
}

/**
 * Checks two things:
 *   1) Whether VectorT works with a non-arithmetic type.
 *   2) Whether move construction and assignment works.
 */
TEST_F(OpenMeshVectorTest, move_constructor_assignment) {

    C::copy_con = 0;
    C::copy_ass = 0;

    // Test move assigning.
    OpenMesh::VectorT<C, 3> x, y;
    x = std::move(y);
    EXPECT_EQ(3, C::copy_ass);
    EXPECT_EQ(0, C::copy_con);

    // Test move constructing.
    OpenMesh::VectorT<C, 3> z(std::move(x));
    EXPECT_EQ(3, C::copy_ass);
    EXPECT_EQ(3, C::copy_con);
}

#endif // C++11

TEST_F(OpenMeshVectorTest, BasicLinearAlgebra) {
    OpenMesh::Vec3d v(1, 2, 3);
    EXPECT_EQ(v[0], 1.0);
    EXPECT_EQ(v[1], 2.0);
    EXPECT_EQ(v[2], 3.0);

    EXPECT_EQ(OpenMesh::Vec3d(-1, -2, -3), -v);
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, 2).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 2, 3).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, -4).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(-4, 2, 3).max());
    EXPECT_EQ(4, OpenMesh::Vec3d(1, 3, -4).max_abs());
    EXPECT_EQ(4, OpenMesh::Vec3d(-4, 2, 3).max_abs());

    EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, 2).min());
    EXPECT_EQ(1, OpenMesh::Vec3d(1, 2, 3).min());
    EXPECT_EQ(-4, OpenMesh::Vec3d(1, 3, -4).min());
    EXPECT_EQ(-4, OpenMesh::Vec3d(-4, 2, 3).min());
    EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, -4).min_abs());
    EXPECT_EQ(2, OpenMesh::Vec3d(-4, 2, 3).min_abs());

    EXPECT_NEAR(14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(1, 2, 3), 1e-6);
    EXPECT_NEAR(-14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6);
    EXPECT_NEAR(14, OpenMesh::Vec3d(-1, -2, -3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6);
}

TEST_F(OpenMeshVectorTest, normalized_cond) {
    OpenMesh::Vec3d v1(1, -2, 3), v2(0, 0, 0);
    EXPECT_EQ(OpenMesh::Vec3d(0, 0, 0), v2.normalize_cond());
    const OpenMesh::Vec3d r1 =
            OpenMesh::Vec3d(
                     0.2672612419124244,
                    -0.5345224838248488,
                     0.8017837257372732) - v1.normalize_cond();
    EXPECT_NEAR(r1[0], 0.0, 1e-12);
    EXPECT_NEAR(r1[1], 0.0, 1e-12);
    EXPECT_NEAR(r1[2], 0.0, 1e-12);
}

TEST_F(OpenMeshVectorTest, size_dim) {
    OpenMesh::Vec3d v3d(1, 2, 3);
    OpenMesh::Vec3f v3f(1, 2, 3);
    OpenMesh::Vec2i v2i(1, 2);

    EXPECT_EQ(3u, v3d.size());
    EXPECT_EQ(3, v3d.dim());
    EXPECT_EQ(3u, v3f.size());
    EXPECT_EQ(3, v3f.dim());
    EXPECT_EQ(2u, v2i.size());
    EXPECT_EQ(2, v2i.dim());
}

}
<|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 "remoting/jingle_glue/jingle_client.h"

#include "base/logging.h"
#include "base/message_loop.h"
#include "jingle/notifier/communicator/gaia_token_pre_xmpp_auth.h"
#include "remoting/jingle_glue/iq_request.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/relay_port_allocator.h"
#include "remoting/jingle_glue/xmpp_socket_adapter.h"
#include "third_party/libjingle/source/talk/base/asyncsocket.h"
#include "third_party/libjingle/source/talk/base/ssladapter.h"
#include "third_party/libjingle/source/talk/p2p/base/sessionmanager.h"
#include "third_party/libjingle/source/talk/p2p/base/transport.h"
#include "third_party/libjingle/source/talk/p2p/client/sessionmanagertask.h"
#include "third_party/libjingle/source/talk/session/tunnel/tunnelsessionclient.h"
#include "third_party/libjingle/source/talk/xmpp/prexmppauth.h"
#include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h"

namespace remoting {

JingleClient::JingleClient(JingleThread* thread)
    : thread_(thread),
      callback_(NULL),
      client_(NULL),
      state_(START),
      initialized_(false),
      closed_(false) {
}

JingleClient::~JingleClient() {
  AutoLock auto_lock(state_lock_);
  DCHECK(!initialized_ || closed_);
}

void JingleClient::Init(
    const std::string& username, const std::string& auth_token,
    const std::string& auth_token_service, Callback* callback) {
  DCHECK_NE(username, "");

  {
    AutoLock auto_lock(state_lock_);
    DCHECK(!initialized_ && !closed_);
    initialized_ = true;

    DCHECK(callback != NULL);
    callback_ = callback;
  }

  message_loop()->PostTask(
      FROM_HERE, NewRunnableMethod(this, &JingleClient::DoInitialize,
                                   username, auth_token, auth_token_service));
}

void JingleClient::DoInitialize(const std::string& username,
                                const std::string& auth_token,
                                const std::string& auth_token_service) {
  DCHECK_EQ(message_loop(), MessageLoop::current());

  buzz::Jid login_jid(username);

  buzz::XmppClientSettings settings;
  settings.set_user(login_jid.node());
  settings.set_host(login_jid.domain());
  settings.set_resource("chromoting");
  settings.set_use_tls(true);
  settings.set_token_service(auth_token_service);
  settings.set_auth_cookie(auth_token);
  settings.set_server(talk_base::SocketAddress("talk.google.com", 5222));

  client_ = new buzz::XmppClient(thread_->task_pump());
  client_->SignalStateChange.connect(
      this, &JingleClient::OnConnectionStateChanged);

  buzz::AsyncSocket* socket = new XmppSocketAdapter(settings, false);

  client_->Connect(settings, "", socket, CreatePreXmppAuth(settings));
  client_->Start();

  network_manager_.reset(new talk_base::NetworkManager());

  RelayPortAllocator* port_allocator =
      new RelayPortAllocator(network_manager_.get(), "transp2");
  port_allocator_.reset(port_allocator);
  port_allocator->SetJingleInfo(client_);

  session_manager_.reset(new cricket::SessionManager(port_allocator_.get()));

  cricket::SessionManagerTask* receiver =
      new cricket::SessionManagerTask(client_, session_manager_.get());
  receiver->EnableOutgoingMessages();
  receiver->Start();
}

void JingleClient::Close() {
  Close(NULL);
}

void JingleClient::Close(Task* closed_task) {
  {
    AutoLock auto_lock(state_lock_);
    // If the client is already closed then don't close again.
    if (closed_) {
      if (closed_task)
        thread_->message_loop()->PostTask(FROM_HERE, closed_task);
      return;
    }
    closed_task_.reset(closed_task);
    closed_ = true;
  }

  message_loop()->PostTask(
      FROM_HERE, NewRunnableMethod(this, &JingleClient::DoClose));
}

void JingleClient::DoClose() {
  DCHECK_EQ(message_loop(), MessageLoop::current());
  DCHECK(closed_);

  session_manager_.reset();
  port_allocator_.reset();
  network_manager_.reset();

  if (client_) {
    client_->Disconnect();
    // Client is deleted by TaskRunner.
    client_ = NULL;
  }

  if (closed_task_.get()) {
    closed_task_->Run();
    closed_task_.reset();
  }
}

std::string JingleClient::GetFullJid() {
  AutoLock auto_lock(full_jid_lock_);
  return full_jid_;
}

IqRequest* JingleClient::CreateIqRequest() {
  return new IqRequest(this);
}

MessageLoop* JingleClient::message_loop() {
  return thread_->message_loop();
}

cricket::SessionManager* JingleClient::session_manager() {
  DCHECK_EQ(message_loop(), MessageLoop::current());
  return session_manager_.get();
}

void JingleClient::OnConnectionStateChanged(buzz::XmppEngine::State state) {
  switch (state) {
    case buzz::XmppEngine::STATE_START:
      UpdateState(START);
      break;
    case buzz::XmppEngine::STATE_OPENING:
      UpdateState(CONNECTING);
      break;
    case buzz::XmppEngine::STATE_OPEN:
      SetFullJid(client_->jid().Str());
      UpdateState(CONNECTED);
      break;
    case buzz::XmppEngine::STATE_CLOSED:
      UpdateState(CLOSED);
      break;
    default:
      NOTREACHED();
      break;
  }
}

void JingleClient::SetFullJid(const std::string& full_jid) {
  AutoLock auto_lock(full_jid_lock_);
  full_jid_ = full_jid;
}

void JingleClient::UpdateState(State new_state) {
  if (new_state != state_) {
    state_ = new_state;
    {
      // We have to have the lock held, otherwise we cannot be sure that
      // the client hasn't been closed when we call the callback.
      AutoLock auto_lock(state_lock_);
      if (!closed_)
        callback_->OnStateChange(this, new_state);
    }
  }
}

buzz::PreXmppAuth* JingleClient::CreatePreXmppAuth(
    const buzz::XmppClientSettings& settings) {
  buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY);
  return new notifier::GaiaTokenPreXmppAuth(jid.Str(), settings.auth_cookie(),
                                            settings.token_service());
}

}  // namespace remoting
<commit_msg>Fix crash when shutting down xmpp connection.<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 "remoting/jingle_glue/jingle_client.h"

#include "base/logging.h"
#include "base/message_loop.h"
#include "jingle/notifier/communicator/gaia_token_pre_xmpp_auth.h"
#include "remoting/jingle_glue/iq_request.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/relay_port_allocator.h"
#include "remoting/jingle_glue/xmpp_socket_adapter.h"
#include "third_party/libjingle/source/talk/base/asyncsocket.h"
#include "third_party/libjingle/source/talk/base/ssladapter.h"
#include "third_party/libjingle/source/talk/p2p/base/sessionmanager.h"
#include "third_party/libjingle/source/talk/p2p/base/transport.h"
#include "third_party/libjingle/source/talk/p2p/client/sessionmanagertask.h"
#include "third_party/libjingle/source/talk/session/tunnel/tunnelsessionclient.h"
#include "third_party/libjingle/source/talk/xmpp/prexmppauth.h"
#include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h"

namespace remoting {

JingleClient::JingleClient(JingleThread* thread)
    : thread_(thread),
      callback_(NULL),
      client_(NULL),
      state_(START),
      initialized_(false),
      closed_(false) {
}

JingleClient::~JingleClient() {
  AutoLock auto_lock(state_lock_);
  DCHECK(!initialized_ || closed_);
}

void JingleClient::Init(
    const std::string& username, const std::string& auth_token,
    const std::string& auth_token_service, Callback* callback) {
  DCHECK_NE(username, "");

  {
    AutoLock auto_lock(state_lock_);
    DCHECK(!initialized_ && !closed_);
    initialized_ = true;

    DCHECK(callback != NULL);
    callback_ = callback;
  }

  message_loop()->PostTask(
      FROM_HERE, NewRunnableMethod(this, &JingleClient::DoInitialize,
                                   username, auth_token, auth_token_service));
}

void JingleClient::DoInitialize(const std::string& username,
                                const std::string& auth_token,
                                const std::string& auth_token_service) {
  DCHECK_EQ(message_loop(), MessageLoop::current());

  buzz::Jid login_jid(username);

  buzz::XmppClientSettings settings;
  settings.set_user(login_jid.node());
  settings.set_host(login_jid.domain());
  settings.set_resource("chromoting");
  settings.set_use_tls(true);
  settings.set_token_service(auth_token_service);
  settings.set_auth_cookie(auth_token);
  settings.set_server(talk_base::SocketAddress("talk.google.com", 5222));

  client_ = new buzz::XmppClient(thread_->task_pump());
  client_->SignalStateChange.connect(
      this, &JingleClient::OnConnectionStateChanged);

  buzz::AsyncSocket* socket = new XmppSocketAdapter(settings, false);

  client_->Connect(settings, "", socket, CreatePreXmppAuth(settings));
  client_->Start();

  network_manager_.reset(new talk_base::NetworkManager());

  RelayPortAllocator* port_allocator =
      new RelayPortAllocator(network_manager_.get(), "transp2");
  port_allocator_.reset(port_allocator);
  port_allocator->SetJingleInfo(client_);

  session_manager_.reset(new cricket::SessionManager(port_allocator_.get()));

  cricket::SessionManagerTask* receiver =
      new cricket::SessionManagerTask(client_, session_manager_.get());
  receiver->EnableOutgoingMessages();
  receiver->Start();
}

void JingleClient::Close() {
  Close(NULL);
}

void JingleClient::Close(Task* closed_task) {
  {
    AutoLock auto_lock(state_lock_);
    // If the client is already closed then don't close again.
    if (closed_) {
      if (closed_task)
        thread_->message_loop()->PostTask(FROM_HERE, closed_task);
      return;
    }
    closed_task_.reset(closed_task);
    closed_ = true;
  }

  message_loop()->PostTask(
      FROM_HERE, NewRunnableMethod(this, &JingleClient::DoClose));
}

void JingleClient::DoClose() {
  DCHECK_EQ(message_loop(), MessageLoop::current());
  DCHECK(closed_);

  session_manager_.reset();
  port_allocator_.reset();
  network_manager_.reset();

  if (client_) {
    client_->Disconnect();
    // Client is deleted by TaskRunner.
    client_ = NULL;
  }

  if (closed_task_.get()) {
    closed_task_->Run();
    closed_task_.reset();
  }
}

std::string JingleClient::GetFullJid() {
  AutoLock auto_lock(full_jid_lock_);
  return full_jid_;
}

IqRequest* JingleClient::CreateIqRequest() {
  return new IqRequest(this);
}

MessageLoop* JingleClient::message_loop() {
  return thread_->message_loop();
}

cricket::SessionManager* JingleClient::session_manager() {
  DCHECK_EQ(message_loop(), MessageLoop::current());
  return session_manager_.get();
}

void JingleClient::OnConnectionStateChanged(buzz::XmppEngine::State state) {
  switch (state) {
    case buzz::XmppEngine::STATE_START:
      UpdateState(START);
      break;
    case buzz::XmppEngine::STATE_OPENING:
      UpdateState(CONNECTING);
      break;
    case buzz::XmppEngine::STATE_OPEN:
      SetFullJid(client_->jid().Str());
      UpdateState(CONNECTED);
      break;
    case buzz::XmppEngine::STATE_CLOSED:
      UpdateState(CLOSED);
      // Client is destroyed by the TaskRunner after the client is
      // closed. Reset the pointer so we don't try to use it later.
      client_ = NULL;
      break;
    default:
      NOTREACHED();
      break;
  }
}

void JingleClient::SetFullJid(const std::string& full_jid) {
  AutoLock auto_lock(full_jid_lock_);
  full_jid_ = full_jid;
}

void JingleClient::UpdateState(State new_state) {
  if (new_state != state_) {
    state_ = new_state;
    {
      // We have to have the lock held, otherwise we cannot be sure that
      // the client hasn't been closed when we call the callback.
      AutoLock auto_lock(state_lock_);
      if (!closed_)
        callback_->OnStateChange(this, new_state);
    }
  }
}

buzz::PreXmppAuth* JingleClient::CreatePreXmppAuth(
    const buzz::XmppClientSettings& settings) {
  buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY);
  return new notifier::GaiaTokenPreXmppAuth(jid.Str(), settings.auth_cookie(),
                                            settings.token_service());
}

}  // namespace remoting
<|endoftext|>


<commit_before>#include "tile.h"
#include "animation.h"
#include "camera.h"

#include "util/bitmap.h"
#include "util/debug.h"
#include "util/load_exception.h"
#include "util/token.h"

using namespace std;
using namespace Platformer;

Tile::Tile():
row(0),
column(0){
}

Tile::Tile(const Token * token, std::map< std::string, Animation *> & animations):
row(0),
column(0){
    TokenView view = token->view();
    while (view.hasMore()){
        try{
            const Token * tok;
            view >> tok;
            if (*tok == "image"){
		std::string name;
		tok->view() >> name;
		animation = animations[name];
            } else if (*tok == "position"){
		tok->view() >> row >> column;
	    } else {
                Global::debug( 3 ) << "Unhandled Tile attribute: "<< endl;
                if (Global::getDebug() >= 3){
                    token->print(" ");
                }
            }
        } catch ( const TokenException & ex ) {
            throw LoadException(__FILE__, __LINE__, ex, "Tile parse error");
        } catch ( const LoadException & ex ) {
            throw ex;
        }
    }
}

Tile::~Tile(){
}

void Tile::act(){
}

void Tile::draw(int x, int y, const Bitmap & bmp){
    if (animation){
	animation->draw(x, y, bmp);
    }
}

void Tile::setAnimation(Animation * anim){
}

TileManager::TileManager(const Token * token, std::map< std::string, Animation *> & animations):
tileX(0),
tileY(0),
dimensionsX(0),
dimensionsY(0){
    TokenView view = token->view();
    while (view.hasMore()){
        try{
            const Token * tok;
            view >> tok;
            if (*tok == "tile-size"){
		tok->view() >> tileX >> tileY;
            } else if (*tok == "dimensions"){
		tok->view() >> dimensionsX >> dimensionsY;
            } else if (*tok == "tile"){
		Tile * tile = new Tile(tok, animations);
		const int row = tile->getRow();
		const int col = tile->getColumn();
		// Do first one
		tiles[tile->getRow()][tile->getColumn()] = tile;
		// Check repeatables
		int times = 0;
		if (tok->match("_/repeat-up", times)){
		    for (int i = row-1; i >= (row - times); --i){
			if (i < 0){
			    break;
			}
			tiles[i][tile->getColumn()] = tile;
		    }
		}
		if (tok->match("_/repeat-down", times)){
		    for (int i = row+1; i <= row + times; ++i){
			if (i > dimensionsY){
			    break;
			}
			tiles[i][tile->getColumn()] = tile;
		    }
		}
		if (tok->match("_/repeat-left", times)){
		    for (int i = col-1; i >= (col - times); --i){
			if (i < 0){
			    break;
			}
			tiles[tile->getRow()][i] = tile;
		    }
		}
		if (tok->match("_/repeat-right", times)){
		    for (int i = col+1; i <= col + times; ++i){
			if (i > dimensionsX){
			    break;
			}
			tiles[tile->getRow()][i] = tile;
		    }
		}
	    } else {
                Global::debug( 3 ) << "Unhandled Tilemap attribute: "<< endl;
                if (Global::getDebug() >= 3){
                    token->print(" ");
                }
            }
        } catch ( const TokenException & ex ) {
            throw LoadException(__FILE__, __LINE__, ex, "Tilemap parse error");
        } catch ( const LoadException & ex ) {
            throw ex;
        }
    }
}

TileManager::~TileManager(){
    for (tileMap::iterator i = tiles.begin(); i != tiles.end(); ++i){
	for (std::map< int, Tile *>::iterator j = i->second.begin(); j != i->second.end(); j++){
	    if (j->second){
		delete j->second;
	    }
	}
    }
}

void TileManager::act(){
}

void TileManager::draw(const Camera & camera){
    // Render tiles
    const int x = (int)((camera.getX())/tileX);
    const int y = (int)((camera.getY())/tileY);
    const int w = x + (int)(camera.getWindow().getWidth()/tileX) + 1;
    const int h = y + (int)(camera.getWindow().getHeight()/tileY);
    int posy = y * tileY - camera.getY();
    for(int row = y; row < h; ++row){
	int posx = x * tileX - camera.getX();
	for(int column = x; column < w; ++column){
	    Tile * tile = tiles[row][column];
	    if (tile){
		tile->draw(posx, posy, camera.getWindow());
	    }
	    posx+=tileX;
	}
	posy+=tileY;
    }
}

<commit_msg>Change image to animation to correctly reflect the object.<commit_after>#include "tile.h"
#include "animation.h"
#include "camera.h"

#include "util/bitmap.h"
#include "util/debug.h"
#include "util/load_exception.h"
#include "util/token.h"

using namespace std;
using namespace Platformer;

Tile::Tile():
row(0),
column(0){
}

Tile::Tile(const Token * token, std::map< std::string, Animation *> & animations):
row(0),
column(0){
    TokenView view = token->view();
    while (view.hasMore()){
        try{
            const Token * tok;
            view >> tok;
            if (*tok == "animation"){
		std::string name;
		tok->view() >> name;
		animation = animations[name];
            } else if (*tok == "position"){
		tok->view() >> row >> column;
	    } else {
                Global::debug( 3 ) << "Unhandled Tile attribute: "<< endl;
                if (Global::getDebug() >= 3){
                    token->print(" ");
                }
            }
        } catch ( const TokenException & ex ) {
            throw LoadException(__FILE__, __LINE__, ex, "Tile parse error");
        } catch ( const LoadException & ex ) {
            throw ex;
        }
    }
}

Tile::~Tile(){
}

void Tile::act(){
}

void Tile::draw(int x, int y, const Bitmap & bmp){
    if (animation){
	animation->draw(x, y, bmp);
    }
}

void Tile::setAnimation(Animation * anim){
}

TileManager::TileManager(const Token * token, std::map< std::string, Animation *> & animations):
tileX(0),
tileY(0),
dimensionsX(0),
dimensionsY(0){
    TokenView view = token->view();
    while (view.hasMore()){
        try{
            const Token * tok;
            view >> tok;
            if (*tok == "tile-size"){
		tok->view() >> tileX >> tileY;
            } else if (*tok == "dimensions"){
		tok->view() >> dimensionsX >> dimensionsY;
            } else if (*tok == "tile"){
		Tile * tile = new Tile(tok, animations);
		const int row = tile->getRow();
		const int col = tile->getColumn();
		// Do first one
		tiles[tile->getRow()][tile->getColumn()] = tile;
		// Check repeatables
		int times = 0;
		if (tok->match("_/repeat-up", times)){
		    for (int i = row-1; i >= (row - times); --i){
			if (i < 0){
			    break;
			}
			tiles[i][tile->getColumn()] = tile;
		    }
		}
		if (tok->match("_/repeat-down", times)){
		    for (int i = row+1; i <= row + times; ++i){
			if (i > dimensionsY){
			    break;
			}
			tiles[i][tile->getColumn()] = tile;
		    }
		}
		if (tok->match("_/repeat-left", times)){
		    for (int i = col-1; i >= (col - times); --i){
			if (i < 0){
			    break;
			}
			tiles[tile->getRow()][i] = tile;
		    }
		}
		if (tok->match("_/repeat-right", times)){
		    for (int i = col+1; i <= col + times; ++i){
			if (i > dimensionsX){
			    break;
			}
			tiles[tile->getRow()][i] = tile;
		    }
		}
	    } else {
                Global::debug( 3 ) << "Unhandled Tilemap attribute: "<< endl;
                if (Global::getDebug() >= 3){
                    token->print(" ");
                }
            }
        } catch ( const TokenException & ex ) {
            throw LoadException(__FILE__, __LINE__, ex, "Tilemap parse error");
        } catch ( const LoadException & ex ) {
            throw ex;
        }
    }
}

TileManager::~TileManager(){
    for (tileMap::iterator i = tiles.begin(); i != tiles.end(); ++i){
	for (std::map< int, Tile *>::iterator j = i->second.begin(); j != i->second.end(); j++){
	    if (j->second){
		delete j->second;
	    }
	}
    }
}

void TileManager::act(){
}

void TileManager::draw(const Camera & camera){
    // Render tiles
    const int x = (int)((camera.getX())/tileX);
    const int y = (int)((camera.getY())/tileY);
    const int w = x + (int)(camera.getWindow().getWidth()/tileX) + 1;
    const int h = y + (int)(camera.getWindow().getHeight()/tileY);
    int posy = y * tileY - camera.getY();
    for(int row = y; row < h; ++row){
	int posx = x * tileX - camera.getX();
	for(int column = x; column < w; ++column){
	    Tile * tile = tiles[row][column];
	    if (tile){
		tile->draw(posx, posy, camera.getWindow());
	    }
	    posx+=tileX;
	}
	posy+=tileY;
    }
}

<|endoftext|>


<commit_before>/*
video_resource.cpp
This file is part of:
GAME PENCIL ENGINE
https://create.pawbyte.com
Copyright (c) 2014-2020 Nathan Hurde, Chase Lee.

Copyright (c) 2014-2020 PawByte LLC.
Copyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page )

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

-Game Pencil Engine <https://create.pawbyte.com>

*/

#include "video_resource.h"
#include "gpe_editor_settings.h"

std::string SUPPORTED_VIDEO_EXT[SUPPORTED_VIDEO_FORMAT_COUNT];

videoResource::videoResource(GPE_GeneralResourceContainer * pFolder)
{
    projectParentFolder = pFolder;
    resourceFileName = " ";
    resourceName = " ";
    for( int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++)
    {
        videoFileName[i] = "";
    }
    videoId = -1;
    videoType = 0;
    videoEditorMainNote = new GPE_Label_Text("Video playback in editor not supported.","Video playback in editor not supported.");

    videoGroupName = new GPE_TextInputBasic("","default=blank");
    videoGroupName->set_label("Video Group");

    defaultVolume = new GPE_TextInputNumber("100",true,0,100);
    defaultVolume->set_string("100");
    defaultVolume->set_label("Default Volume:");

    openExternalEditorButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/rocket.png","Opens Audio In External Editor");
    refreshResourceDataButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/refresh.png","Refreshes this resource's media files");
}

videoResource::~videoResource()
{
    if( videoEditorMainNote!=NULL)
    {
        delete videoEditorMainNote;
        videoEditorMainNote = NULL;
    }
    if( defaultVolume!=NULL)
    {
        delete defaultVolume;
        defaultVolume = NULL;
    }
    if( videoGroupName!=NULL)
    {
        delete videoGroupName;
        videoGroupName = NULL;
    }
    if( openExternalEditorButton!=NULL)
    {
        delete openExternalEditorButton;
        openExternalEditorButton = NULL;
    }
    if( refreshResourceDataButton!=NULL)
    {
        delete refreshResourceDataButton;
        refreshResourceDataButton = NULL;
    }
}

bool videoResource::build_intohtml5_file(std::ofstream * fileTarget, int leftTabAmount)
{
    if( fileTarget!=NULL && fileTarget->is_open() )
    {
        std::string nestedTabsStr = generate_tabs( leftTabAmount  );
        std::string nestedTabsStrObjFunc = generate_tabs( leftTabAmount +1 );
        std::string html5SpShName = get_name();

        *fileTarget << nestedTabsStr << "var " + html5SpShName + " =  GPE.rsm.add_video(";
        *fileTarget << int_to_string (exportBuildGlobalId ) + ",";
        *fileTarget << "'"+html5SpShName + "',";
        for( int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++)
        {
            if( (int)videoFileName[i].size() > 3)
            {
                *fileTarget << "'resources/videos/"+get_short_filename( videoFileName[i] )+"',";
            }
            else
            {
                *fileTarget << "'',";
            }
        }
        if( videoGroupName!=NULL)
        {
            *fileTarget << "'"+videoGroupName->get_string()+"',";
        }
        else
        {
            *fileTarget << "'',";
        }
        if( defaultVolume!=NULL)
        {
            *fileTarget << defaultVolume->get_held_number() << "";
        }
        else
        {
            *fileTarget << "100";
        }
        *fileTarget << "); \n";

        return true;
    }
    return false;
}

bool videoResource::build_intocpp_file(std::ofstream * fileTarget, int leftTabAmount  )
{
    return true;
}

void videoResource::compile_cpp()
{

}

bool videoResource::copy_video_source(std::string outDirectoryName)
{
    std::string copyDestinationStr = "";
    bool copyErrorFound = false;
    for( int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT ; i++)
    {
        if((int)videoFileName[i].size() > 0)
        {
            copyDestinationStr = outDirectoryName+"/"+ get_short_filename(videoFileName[i],true);
            GPE_Report(videoFileName[i]+" attempted to copy to "+copyDestinationStr);
            if( copy_file(videoFileName[i],copyDestinationStr )==false)
            {
                copyErrorFound = true;
            }
        }
    }
    return copyErrorFound;
}

bool videoResource::include_local_files( std::string pBuildDir , int buildType )
{
    appendToFile(get_user_settings_folder()+"resources_check.txt", get_name() +"...");
    return true;
}

void videoResource::load_video(std::string newFileName)
{
    if( (int) newFileName.size()>0 )
    {
        bool isvideoFile = true;
        std::string newFileExt = get_file_ext(newFileName);

        if( newFileExt=="mp4")
        {
            videoFileName[mp4FileName] = newFileName;
        }
        else if( newFileExt=="ogg")
        {
            videoFileName[oggVideoFileName] = newFileName;
        }
        else if( newFileExt=="webm")
        {
            videoFileName[webmFileName] = newFileName;
        }
        else
        {
            display_user_alert("[Alert - "+resourceName+"]","Unsupported file type added.");
        }
        if( isvideoFile)
        {
            copy_video_source( file_to_dir(parentProjectName)+"/gpe_project/resources/videos" );
        }
    }
}

void videoResource::preprocess_self(std::string alternatePath)
{
    if( resourcePostProcessed == false  || file_exists(alternatePath) )
    {
        if( GPE_LOADER != NULL )
        {
            GPE_LOADER->update_submessages( "Processing Video",resourceName );
        }

        std::string otherColContainerName = "";

        std::string newFileIn ="";
        std::string soughtDir = file_to_dir(parentProjectName)+"/gpe_project/resources/videos/";
        if( file_exists(alternatePath) )
        {
            newFileIn = alternatePath;
            soughtDir = get_path_from_file(newFileIn);
        }
        else
        {
            newFileIn = soughtDir + resourceName+".gpf";
        }
        std::ifstream gameResourceFileIn( newFileIn.c_str() );

        GPE_Report("Loading video - "+newFileIn);
        //If the level file could be loaded
        if( !gameResourceFileIn.fail() && gameResourceFileIn.is_open())
        {
            int equalPos = 0;
            std::string firstChar="";
            std::string keyString="";
            std::string valString="";
            std::string subValString="";
            std::string currLine="";
            std::string currLineToBeProcessed;
            float foundFileVersion = 0;
            std::string fFontFile = "";
            while ( gameResourceFileIn.good() )
            {
                getline (gameResourceFileIn,currLine); //gets the next line of the file
                currLineToBeProcessed = trim_left_inplace(currLine);
                currLineToBeProcessed = trim_right_inplace(currLineToBeProcessed);
                if( foundFileVersion <=0)
                {
                    //Empty Line skipping is only allowed at the top of the file
                    if(!currLineToBeProcessed.empty() )
                    {
                        //Comment skipping is only allowed at the top of the file
                        if( currLineToBeProcessed[0]!= '#' && currLineToBeProcessed[0]!='/'  )
                        {
                            //searches for an equal character and parses through the variable
                            equalPos=currLineToBeProcessed.find_first_of("=");
                            if(equalPos!=(int)std::string::npos)
                            {
                                //if the equalPos is present, then parse on through and carryon
                                keyString = currLineToBeProcessed.substr(0,equalPos);
                                valString = currLineToBeProcessed.substr(equalPos+1,currLineToBeProcessed.length());
                                if( keyString=="Version")
                                {
                                    foundFileVersion = string_to_float(valString);
                                }
                            }
                        }
                    }
                }
                else if( foundFileVersion <= 2)
                {
                    //Begin processing the file.
                    if(!currLineToBeProcessed.empty() )
                    {
                        equalPos=currLineToBeProcessed.find_first_of("=");
                        if(equalPos!=(int)std::string::npos)
                        {
                            //if the equalPos is present, then parse on through and carryon
                            keyString = currLineToBeProcessed.substr(0,equalPos);
                            valString = currLineToBeProcessed.substr(equalPos+1,currLineToBeProcessed.length());

                            if( keyString=="ResourceName")
                            {
                                renameBox->set_string(valString);
                            }
                            else if( keyString=="videoFileLocation")
                            {
                                load_video( soughtDir+valString );
                            }
                            else if( keyString=="VideoGroup")
                            {
                                videoGroupName->set_string(valString);
                            }
                            else if( keyString=="DefaultVolume")
                            {
                                defaultVolume->set_number(string_to_int(valString,100));
                            }
                            else
                            {
                                for(int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++)
                                {
                                    if( keyString=="videoFile["+SUPPORTED_VIDEO_EXT[i]+"]")
                                    {
                                        if( (int)valString.size() > 3)
                                        {
                                            load_video( soughtDir+valString );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    GPE_Report("Invalid FoundFileVersion ="+float_to_string(foundFileVersion)+".");
                }
            }

            if( GPE_LOADER != NULL )
            {
                GPE_LOADER->increment_and_update( "Video resource processed",resourceName );
            }
        }
        else
        {
            if( GPE_LOADER != NULL )
            {
                GPE_LOADER->increment_and_update( "Video resource processingg error occurred",resourceName );
            }
        }
    }
}

void videoResource::prerender_self()
{
    standardEditableGameResource::prerender_self();
}

void videoResource::process_self(GPE_Rect * viewedSpace,GPE_Rect * cam )
{
    viewedSpace = GPE_find_camera(viewedSpace);
    cam = GPE_find_camera(cam);
    if(cam!=NULL && viewedSpace!=NULL && PANEL_GENERAL_EDITOR!=NULL)
    {
        PANEL_GENERAL_EDITOR->clear_panel();
        PANEL_GENERAL_EDITOR->add_gui_element(videoEditorMainNote,true);
        PANEL_GENERAL_EDITOR->add_gui_element(renameBox,true);

        PANEL_GENERAL_EDITOR->add_gui_element(refreshResourceDataButton,false );
        PANEL_GENERAL_EDITOR->add_gui_element(loadResourceButton,false );
        PANEL_GENERAL_EDITOR->add_gui_element(openExternalEditorButton,true);

        PANEL_GENERAL_EDITOR->add_gui_element(videoGroupName, true);
        PANEL_GENERAL_EDITOR->add_gui_element(defaultVolume,true);
        PANEL_GENERAL_EDITOR->add_gui_element(confirmResourceButton,true);
        PANEL_GENERAL_EDITOR->add_gui_element(cancelResourceButton,true);
        //PANEL_GENERAL_EDITOR->set_maxed_out_width();
        PANEL_GENERAL_EDITOR->process_self(NULL, NULL);

        if( loadResourceButton!=NULL && loadResourceButton->is_clicked() )
        {
            std::string newFileName = GPE_GetOpenFileName("Load In an video File","Video",MAIN_GUI_SETTINGS->fileOpenVideoDir);
            load_video(newFileName);
        }
        else if( confirmResourceButton!=NULL && confirmResourceButton->is_clicked() )
        {
            save_resource();
        }
        else if( cancelResourceButton->is_clicked() )
        {
            resourcePostProcessed = false;
            preprocess_self();
        }
        else if( openExternalEditorButton!=NULL &&  openExternalEditorButton->is_clicked() )
        {
            bool hasFileToOpen = false;
            int ii = 0;
            for( ii = 0; ii < SUPPORTED_VIDEO_FORMAT_COUNT; ii++)
            {
                if( (int)videoFileName[ii].size() > 0)
                {
                    hasFileToOpen = true;
                    break;
                }
            }
            if( hasFileToOpen )
            {
                GPE_open_context_menu(-1,-1,256);
                MAIN_CONTEXT_MENU->set_width(openExternalEditorButton->get_width() );
                for( ii = 0; ii < SUPPORTED_VIDEO_FORMAT_COUNT; ii++)
                {
                    if( (int)videoFileName[ii].size() > 0)
                    {
                        MAIN_CONTEXT_MENU->add_menu_option("Edit "+SUPPORTED_VIDEO_EXT[ii],ii);
                    }
                }
                int menuSelection = GPE_Get_Context_Result();
                if( menuSelection >=0 && menuSelection < SUPPORTED_VIDEO_FORMAT_COUNT)
                {
                    std::string fileToEdit = videoFileName[menuSelection];

                    if( MAIN_EDITOR_SETTINGS!=NULL && MAIN_EDITOR_SETTINGS->pencilExternalEditorsFile[GPE_EXTERNAL_EDITOR_VID]!=NULL)
                    {
                        GPE_OpenProgram(MAIN_EDITOR_SETTINGS->pencilExternalEditorsFile[GPE_EXTERNAL_EDITOR_VID]->get_string(),fileToEdit, true );
                    }
                    else
                    {
                        GPE_OpenURL(fileToEdit);
                    }
                    /*
                    fileToEdit = "\"C:/Program Files (x86)/Audacity/audacity.exe\" \""+fileToEdit+"\"";
                    GPE_OpenURL(fileToEdit);*/
                    appendToFile(get_user_settings_folder()+"gpe_error_log2.txt","Attempting to edit ["+fileToEdit+"]...");
                }
            }
        }
        else if( refreshResourceDataButton!=NULL &&  refreshResourceDataButton->is_clicked() )
        {
            resourcePostProcessed = false;
            preprocess_self();
        }
    }
}

void videoResource::render_self(GPE_Rect * viewedSpace,GPE_Rect *cam )
{
    viewedSpace = GPE_find_camera(viewedSpace);
    cam = GPE_find_camera(cam);
    if( cam!=NULL && viewedSpace!=NULL)
    {
        for( int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++)
        {
            if( videoFileName[i].size()> 0)
            {
                gfs->render_text( viewedSpace->w-GENERAL_GPE_GUI_PADDING*3,GENERAL_GPE_GUI_PADDING+GPE_AVERAGE_LINE_HEIGHT*i,SUPPORTED_VIDEO_EXT[i]+" is attatched",GPE_MAIN_THEME->Main_Box_Font_Highlight_Color,GPE_DEFAULT_FONT,FA_RIGHT,FA_TOP);
            }
            else
            {
                gfs->render_text( viewedSpace->w-GENERAL_GPE_GUI_PADDING*3,GENERAL_GPE_GUI_PADDING+GPE_AVERAGE_LINE_HEIGHT*i,SUPPORTED_VIDEO_EXT[i]+" not attatched",GPE_MAIN_THEME->Main_Box_Font_Color,GPE_DEFAULT_FONT,FA_RIGHT,FA_TOP);
            }
        }
        gfs->render_text( viewedSpace->w/2, viewedSpace->h-32, "HTML5 Feature. Currently not supported in C++/Native runtime",GPE_MAIN_THEME->Main_Box_Font_Color,GPE_DEFAULT_FONT, FA_CENTER, FA_BOTTOM, 255);
    }
    //
}

void videoResource::save_resource(std::string alternatePath, int backupId)
{
    if( GPE_LOADER != NULL )
    {
        GPE_LOADER->update_submessages( "Saving Game video", resourceName );
    }

    bool usingAltSaveSource = false;
    std::string newFileOut ="";
    std::string soughtDir = get_path_from_file(alternatePath);
    if( path_exists(soughtDir) )
    {
        newFileOut = alternatePath;
        usingAltSaveSource= true;
    }
    else
    {
        soughtDir = file_to_dir(parentProjectName)+"/gpe_project/resources/videos/";
        newFileOut = soughtDir + resourceName+".gpf";
    }
    std::ofstream newSaveDataFile( newFileOut.c_str() );
    //If the scene file could be saved
    if( !newSaveDataFile.fail() && newSaveDataFile.is_open() )
    {
        write_header_on_file(&newSaveDataFile);

        std::string resFileLocation = "";
        std::string resFileCopySrc;
        std::string resFileCopyDest;

        for(int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++)
        {
            if( (int)videoFileName[i].size() > 3)
            {
                resFileLocation = get_short_filename (videoFileName[i],true );
                newSaveDataFile << "videoFile["+SUPPORTED_VIDEO_EXT[i]+"]="+resFileLocation+"\n";
                if( (int)resFileLocation.size() > 0 && usingAltSaveSource )
                {
                    resFileCopySrc = file_to_dir(parentProjectName)+"/gpe_project/resources/video/"+resFileLocation;
                    resFileCopyDest = soughtDir+resFileLocation;
                    if( file_exists(resFileCopyDest) )
                    {
                        /*
                        if( GPE_Display_Basic_Prompt("[WARNING]Video File Already exists?","Are you sure you will like to overwrite your ["+resFileLocation+"] Video file? This action is irreversible!")==DISPLAY_QUERY_YES)
                        {
                            copy_file(resFileCopySrc,resFileCopyDest);
                        }
                        */
                    }
                    else
                    {
                        copy_file(resFileCopySrc,resFileCopyDest);
                    }
                }
            }
        }

        if( defaultVolume!=NULL)
        {
            newSaveDataFile << "DefaultVolume="+int_to_string(defaultVolume->get_held_number() )+"\n";
        }

        if( videoGroupName!=NULL)
        {
            newSaveDataFile << "VideoGroup="+videoGroupName->get_string()+"\n";

        }

        newSaveDataFile.close();
        if( !usingAltSaveSource)
        {
            isModified = false;
        }
        if( GPE_LOADER != NULL )
        {
            GPE_LOADER->increment_and_update( "Video resource saved",resourceName );
        }
        return;
    }

    GPE_Main_Logs->log_general_error("Unable to save file ["+newFileOut+"]");
    if( GPE_LOADER != NULL )
    {
        GPE_LOADER->increment_and_update( "Video resource unable to save",resourceName );
    }
}

bool videoResource::write_data_into_projectfile(std::ofstream * fileTarget, int nestedFoldersIn)
{
    if( fileTarget!=NULL)
    {
        if( fileTarget->is_open() )
        {
            std::string nestedTabsStr = generate_tabs( nestedFoldersIn );
            *fileTarget << nestedTabsStr << "video=" << resourceName << "," << get_global_rid() << ",\n";
            return true;
        }
    }
    return false;
}
<commit_msg>Delete video_resource.cpp<commit_after><|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 <pybind11/pybind11.h>
#include <modules/python3/python3module.h>

#include <modules/python3/pythoninterpreter.h>
#include <modules/python3/pythonexecutionoutputobservable.h>

#include <modules/python3/processors/numpymandelbrot.h>
#include <modules/python3/processors/numpyvolume.h>
#include <modules/python3/processors/numpymeshcreatetest.h>

#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/commandlineparser.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/python3/pythonscript.h>
#include <modules/python3/pythonlogger.h>

namespace inviwo {

Python3Module::Python3Module(InviwoApplication* app)
    : InviwoModule(app, "Python3")
    , pythonInterpreter_(util::make_unique<PythonInterpreter>(this))
    , pythonScriptArg_("p", "pythonScript", "Specify a python script to run at startup", false, "",
                       "Path to the file containing the script") {

    registerProcessor<NumPyVolume>();
    registerProcessor<NumpyMandelbrot>();
    registerProcessor<NumPyMeshCreateTest>();

    pythonInterpreter_->addObserver(&pythonLogger_);
    app->getCommandLineParser().add(
        &pythonScriptArg_,
        [this]() {
            auto filename = pythonScriptArg_.getValue();
            if (!filesystem::fileExists(filename)) {
                LogWarn("Could not run script, file does not exist: " << filename);
                return;
            }
            PythonScriptDisk s(filename);
            s.run();
        },
        100);

    app->dispatchFront([&]() {
        pythonInterpreter_->runString("import inviwopy");  // we need to import inviwopy to trigger
                                                           // the initialization code in
                                                           // inviwopy.cpp, this is needed to be
                                                           // able to cast cpp/inviwo objects to
                                                           // python objects
        //PythonScriptDisk(getPath() + "/scripts/documentgenerator.py").run();
    });
}

Python3Module::~Python3Module() { pythonInterpreter_->removeObserver(&pythonLogger_); }

void Python3Module::registerPythonInitCallback(PythonInitCallback callback) {
    callbackObjects_.push_back(callback);
}

void Python3Module::invokePythonInitCallbacks(pybind11::module* objects) {
    for (auto& c : callbackObjects_) {
        c(objects);
    }
}

}  // namespace
<commit_msg>Python3: use post module registration hook<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 <pybind11/pybind11.h>
#include <modules/python3/python3module.h>

#include <modules/python3/pythoninterpreter.h>
#include <modules/python3/pythonexecutionoutputobservable.h>

#include <modules/python3/processors/numpymandelbrot.h>
#include <modules/python3/processors/numpyvolume.h>
#include <modules/python3/processors/numpymeshcreatetest.h>

#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/commandlineparser.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/python3/pythonscript.h>
#include <modules/python3/pythonlogger.h>

namespace inviwo {

Python3Module::Python3Module(InviwoApplication* app)
    : InviwoModule(app, "Python3")
    , pythonInterpreter_(util::make_unique<PythonInterpreter>(this))
    , pythonScriptArg_("p", "pythonScript", "Specify a python script to run at startup", false, "",
                       "Path to the file containing the script") {

    registerProcessor<NumPyVolume>();
    registerProcessor<NumpyMandelbrot>();
    registerProcessor<NumPyMeshCreateTest>();

    pythonInterpreter_->addObserver(&pythonLogger_);
    app->getCommandLineParser().add(
        &pythonScriptArg_,
        [this]() {
            auto filename = pythonScriptArg_.getValue();
            if (!filesystem::fileExists(filename)) {
                LogWarn("Could not run script, file does not exist: " << filename);
                return;
            }
            PythonScriptDisk s(filename);
            s.run();
        },
        100);

    app->addPostModulesRegistrationCallback([&]() {
        pythonInterpreter_->runString("import inviwopy");  // we need to import inviwopy to trigger
                                                           // the initialization code in
                                                           // inviwopy.cpp, this is needed to be
                                                           // able to cast cpp/inviwo objects to
                                                           // python objects
        //PythonScriptDisk(getPath() + "/scripts/documentgenerator.py").run();
    });
}

Python3Module::~Python3Module() { pythonInterpreter_->removeObserver(&pythonLogger_); }

void Python3Module::registerPythonInitCallback(PythonInitCallback callback) {
    callbackObjects_.push_back(callback);
}

void Python3Module::invokePythonInitCallbacks(pybind11::module* objects) {
    for (auto& c : callbackObjects_) {
        c(objects);
    }
}

}  // namespace
<|endoftext|>


<commit_before>#include <igvc/SerialPort.h>
#include <iostream>

using namespace std;
using namespace boost::asio;

SerialPort::SerialPort(string device, int baud)
    : port(ioservice),
      path(device)
{
    try
    {
        port.open(device);
    } catch(...){}

    if( !port.is_open() ) {
        throw runtime_error("Could not open serial port " + device);
    }

    try
    {
        port.set_option(boost::asio::serial_port_base::baud_rate(baud));
        port.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
        port.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
    } catch(...) {
        throw runtime_error("Could not open serial port " + device);
    }
}

void SerialPort::flush()
{
    ::tcflush(port.lowest_layer().native_handle(), TCIOFLUSH);
}

SerialPort::~SerialPort()
{
    port.close();
}

bool SerialPort::isOpen()
{
    return port.is_open();
}

void SerialPort::write(string msg)
{
    if(port.is_open())
        boost::asio::write(port, boost::asio::buffer(msg.c_str(),msg.length()));
}

void SerialPort::write(char *buffer, int length)
{
    boost::asio::write(port, boost::asio::buffer(buffer, length));
}

void SerialPort::write(unsigned char *buffer, int length)
{
    if(port.is_open())
        boost::asio::write(port, boost::asio::buffer(buffer, length));
}

char SerialPort::read()
{
    if(!port.is_open()) return -1;

    char in;
    try
    {
        boost::asio::read(port, buffer(&in, 1));
    } catch (boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >& err) {
        throw runtime_error("Error reading serial port");
    }
    return in;
}

char* SerialPort::read(int numBytes)
{
    if(!port.is_open())
        return (char*)"";
    char* bytes = new char[numBytes];
    for(int i = 0; i < numBytes; i++)
        bytes[i] = read();
    return bytes;
}

string SerialPort::readln()
{
    string line = "";
    while(true)
    {
        char in = read();
        if(in == '\n')
            return line;
        if(in == '\r')
            return line;
        line = line + in;
    }
}

string SerialPort::devicePath()
{
    return path;
}
<commit_msg>added serial port close before throwing errors<commit_after>#include <igvc/SerialPort.h>
#include <iostream>

using namespace std;
using namespace boost::asio;

SerialPort::SerialPort(string device, int baud)
    : port(ioservice),
      path(device)
{
    try
    {
        port.open(device);
    } catch(...){}

    if( !port.is_open() ) {
        throw runtime_error("Could not open serial port " + device);
    }

    try
    {
        port.set_option(boost::asio::serial_port_base::baud_rate(baud));
        port.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
        port.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
    } catch(...) {
        port.close();
        throw runtime_error("Could not open serial port " + device);
    }
}

void SerialPort::flush()
{
    ::tcflush(port.lowest_layer().native_handle(), TCIOFLUSH);
}

SerialPort::~SerialPort()
{
    port.close();
}

bool SerialPort::isOpen()
{
    return port.is_open();
}

void SerialPort::write(string msg)
{
    if(port.is_open())
        boost::asio::write(port, boost::asio::buffer(msg.c_str(),msg.length()));
}

void SerialPort::write(char *buffer, int length)
{
    boost::asio::write(port, boost::asio::buffer(buffer, length));
}

void SerialPort::write(unsigned char *buffer, int length)
{
    if(port.is_open())
        boost::asio::write(port, boost::asio::buffer(buffer, length));
}

char SerialPort::read()
{
    if(!port.is_open()) return -1;

    char in;
    try
    {
        boost::asio::read(port, buffer(&in, 1));
    } catch (boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >& err) {
        port.close();
        throw runtime_error("Error reading serial port");
    }
    return in;
}

char* SerialPort::read(int numBytes)
{
    if(!port.is_open())
        return (char*)"";
    char* bytes = new char[numBytes];
    for(int i = 0; i < numBytes; i++)
        bytes[i] = read();
    return bytes;
}

string SerialPort::readln()
{
    string line = "";
    while(true)
    {
        char in = read();
        if(in == '\n')
            return line;
        if(in == '\r')
            return line;
        line = line + in;
    }
}

string SerialPort::devicePath()
{
    return path;
}
<|endoftext|>


<commit_before><commit_msg>sat: fixup schedule_requests_sat.cc<commit_after><|endoftext|>


<commit_before>#pragma once

///////////////////////////////////////////////////////////////////////////////
/// @file DBBackend.hpp
/// @author BrainlessLabs
/// @version 0.3
/// @brief Implements the database backend.
///////////////////////////////////////////////////////////////////////////////
#include <soci/soci.h>
#include "blib/utils/Singleton.hpp"
#include "blib/bun/DbLogger.hpp"
#include <memory>

#define BUN_SQLITE

#ifdef BUN_SQLITE

#include <soci/sqlite3/soci-sqlite3.h>

#elif BUN_POSTGRES
#include <soci/postgresql/soci-postgresql.h>
#elif BUN_MYSQL
#include <soci/mysql/soci-mysql.h>
#endif

namespace blib {
    namespace bun {
        namespace __private {
            struct DbGenericType{
            };

            struct DbTypeSqlite : DbGenericType{
            };

            struct DbTypePostgres : DbGenericType{
            };

            struct DbTypeMySql : DbGenericType{
            };

            template<typename T = DbGenericType>
            class DbBackend : public blib::Singleton<DbBackend<T>> {
            private:
                bool _ok;
                soci::session _sql_session;

                //DbBackend() = default;

            public:
                bool ok() const {
                    return _ok;
                }

                bool connect(std::string const &in_params) {
                    const soci::backend_factory backend_factory =
#ifdef BUN_SQLITE
                    soci::sqlite3;
#elif BUN_POSTGRES
                    soci::postgresql;
#elif BUN_MYSQL
                    soci::mysql;
#endif
                    try {
                        _sql_session.open(backend_factory, in_params);
                        _ok = true;
                    }
                    catch (std::exception const &except) {
                        _ok = false;
                    }
                }

                soci::session &session() {
                    return _sql_session;
                }
            };

			/////////////////////////////////////////////////
			/// @class ConvertToSOCIType
			/// @brief Convert a basic type to a type available for soci.
			/// @details Supported type can be found in http://soci.sourceforge.net/doc/master/types/
			///          So all basic C++ types will be converted to closest type. By default same type is returned.
			/////////////////////////////////////////////////
			template<typename T>
			struct ConvertToSOCIType {
				using type = T;
			};

			template<>
			struct ConvertToSOCIType<float> {
				using type = double;
			};

			template<typename T>
			typename ConvertToSOCIType<T>::type convertToSOCIType(T const & val) {
				return static_cast<ConvertToSOCIType<T>::type>(val);
			}
        }
    }
}
<commit_msg>Adding string conversion<commit_after>#pragma once

///////////////////////////////////////////////////////////////////////////////
/// @file DBBackend.hpp
/// @author BrainlessLabs
/// @version 0.3
/// @brief Implements the database backend.
///////////////////////////////////////////////////////////////////////////////
#include <soci/soci.h>
#include "blib/utils/Singleton.hpp"
#include "blib/bun/DbLogger.hpp"
#include <memory>

#define BUN_SQLITE

#ifdef BUN_SQLITE

#include <soci/sqlite3/soci-sqlite3.h>

#elif BUN_POSTGRES
#include <soci/postgresql/soci-postgresql.h>
#elif BUN_MYSQL
#include <soci/mysql/soci-mysql.h>
#endif

namespace blib {
    namespace bun {
        namespace __private {
            struct DbGenericType{
            };

            struct DbTypeSqlite : DbGenericType{
            };

            struct DbTypePostgres : DbGenericType{
            };

            struct DbTypeMySql : DbGenericType{
            };

            template<typename T = DbGenericType>
            class DbBackend : public blib::Singleton<DbBackend<T>> {
            private:
                bool _ok;
                soci::session _sql_session;

                //DbBackend() = default;

            public:
                bool ok() const {
                    return _ok;
                }

                bool connect(std::string const &in_params) {
                    const soci::backend_factory backend_factory =
#ifdef BUN_SQLITE
                    soci::sqlite3;
#elif BUN_POSTGRES
                    soci::postgresql;
#elif BUN_MYSQL
                    soci::mysql;
#endif
                    try {
                        _sql_session.open(backend_factory, in_params);
                        _ok = true;
                    }
                    catch (std::exception const &except) {
                        _ok = false;
                    }
                }

                soci::session &session() {
                    return _sql_session;
                }
            };

			/////////////////////////////////////////////////
			/// @class ConvertToSOCIType
			/// @brief Convert a basic type to a type available for soci.
			/// @details Supported type can be found in http://soci.sourceforge.net/doc/master/types/
			///          So all basic C++ types will be converted to closest type. By default same type is returned.
			/////////////////////////////////////////////////
			template<typename T>
			struct ConvertToSOCIType {
				using type = T;
			};

			template<>
			struct ConvertToSOCIType<float> {
				using type = double;
			};

			/// @brief Works for all stuff where the default type conversion operator is overloaded.
			template<typename T>
			typename ConvertToSOCIType<T>::type convertToSOCIType(T const & val) {
				return (ConvertToSOCIType<T>::type)(val);
			}

			std::string convertToSOCIType( char const* val) {
				std::string ret = val;
				return std::move(ret);
			}
        }
    }
}
<|endoftext|>


<commit_before>/*
 * Launch WAS child processes.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "was_launch.hxx"
#include "system/fd_util.h"
#include "system/fd-util.h"
#include "system/sigutil.h"
#include "spawn/Spawn.hxx"
#include "spawn/Prepared.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "util/ConstBuffer.hxx"

#include <daemon/log.h>
#include <inline/compiler.h>

#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

#ifdef __linux
#include <sched.h>
#endif

void
WasProcess::Close()
{
    if (control_fd >= 0) {
        close(control_fd);
        control_fd = -1;
    }

    if (input_fd >= 0) {
        close(input_fd);
        input_fd = -1;
    }

    if (output_fd >= 0) {
        close(output_fd);
        output_fd = -1;
    }
}

struct was_run_args {
    sigset_t signals;

    PreparedChildProcess child;
};

gcc_noreturn
static int
was_run(void *ctx)
{
    struct was_run_args *args = (struct was_run_args *)ctx;

    install_default_signal_handlers();
    leave_signal_section(&args->signals);

    Exec(std::move(args->child));
}

bool
was_launch(WasProcess *process,
           const char *executable_path,
           ConstBuffer<const char *> args,
           const ChildOptions &options,
           GError **error_r)
{
    int control_fds[2], input_fds[2], output_fds[2];

    if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) {
        set_error_errno_msg(error_r, "failed to create socket pair");
        return false;
    }

    if (pipe_cloexec(input_fds) < 0) {
        set_error_errno_msg(error_r, "failed to create first pipe");
        close(control_fds[0]);
        close(control_fds[1]);
        return false;
    }

    if (pipe_cloexec(output_fds) < 0) {
        set_error_errno_msg(error_r, "failed to create second pipe");
        close(control_fds[0]);
        close(control_fds[1]);
        close(input_fds[0]);
        close(input_fds[1]);
        return false;
    }

    struct was_run_args run_args;

    run_args.child.stdin_fd = output_fds[0];
    run_args.child.stdout_fd = input_fds[1];
    /* fd2 is retained */
    run_args.child.control_fd = control_fds[1];

    run_args.child.Append(executable_path);
    for (auto i : args)
        run_args.child.Append(i);

    if (!options.CopyTo(run_args.child, true, nullptr, error_r)) {
        close(control_fds[0]);
        close(input_fds[0]);
        close(output_fds[1]);
        return false;
    }

    int clone_flags = SIGCHLD;
    clone_flags = options.ns.GetCloneFlags(clone_flags);

    /* avoid race condition due to libevent signal handler in child
       process */
    enter_signal_section(&run_args.signals);

    char stack[8192];

    long pid = clone(was_run, stack + sizeof(stack),
                     clone_flags, &run_args);
    if (pid < 0) {
        leave_signal_section(&run_args.signals);

        set_error_errno_msg(error_r, "clone() failed");
        close(control_fds[0]);
        close(input_fds[0]);
        close(output_fds[1]);
        return false;
    }

    leave_signal_section(&run_args.signals);

    fd_set_nonblock(input_fds[0], true);
    fd_set_nonblock(output_fds[1], true);

    process->pid = pid;
    process->control_fd = control_fds[0];
    process->input_fd = input_fds[0];
    process->output_fd = output_fds[1];
    return true;
}
<commit_msg>was/launch: use SpawnChildProcess()<commit_after>/*
 * Launch WAS child processes.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "was_launch.hxx"
#include "system/fd_util.h"
#include "system/fd-util.h"
#include "spawn/Spawn.hxx"
#include "spawn/Prepared.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "util/ConstBuffer.hxx"

#include <daemon/log.h>
#include <inline/compiler.h>

#include <sys/socket.h>
#include <unistd.h>

void
WasProcess::Close()
{
    if (control_fd >= 0) {
        close(control_fd);
        control_fd = -1;
    }

    if (input_fd >= 0) {
        close(input_fd);
        input_fd = -1;
    }

    if (output_fd >= 0) {
        close(output_fd);
        output_fd = -1;
    }
}

bool
was_launch(WasProcess *process,
           const char *executable_path,
           ConstBuffer<const char *> args,
           const ChildOptions &options,
           GError **error_r)
{
    int control_fds[2], input_fds[2], output_fds[2];

    if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) {
        set_error_errno_msg(error_r, "failed to create socket pair");
        return false;
    }

    if (pipe_cloexec(input_fds) < 0) {
        set_error_errno_msg(error_r, "failed to create first pipe");
        close(control_fds[0]);
        close(control_fds[1]);
        return false;
    }

    if (pipe_cloexec(output_fds) < 0) {
        set_error_errno_msg(error_r, "failed to create second pipe");
        close(control_fds[0]);
        close(control_fds[1]);
        close(input_fds[0]);
        close(input_fds[1]);
        return false;
    }

    PreparedChildProcess p;

    p.stdin_fd = output_fds[0];
    p.stdout_fd = input_fds[1];
    /* fd2 is retained */
    p.control_fd = control_fds[1];

    p.Append(executable_path);
    for (auto i : args)
        p.Append(i);

    if (!options.CopyTo(p, true, nullptr, error_r)) {
        close(control_fds[0]);
        close(input_fds[0]);
        close(output_fds[1]);
        return false;
    }

    pid_t pid = SpawnChildProcess(std::move(p));
    if (pid < 0) {
        set_error_errno_msg2(error_r, -pid, "clone() failed");
        close(control_fds[0]);
        close(input_fds[0]);
        close(output_fds[1]);
        return false;
    }

    fd_set_nonblock(input_fds[0], true);
    fd_set_nonblock(output_fds[1], true);

    process->pid = pid;
    process->control_fd = control_fds[0];
    process->input_fd = input_fds[0];
    process->output_fd = output_fds[1];
    return true;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef SVX_BORDERLINE_HXX
#define SVX_BORDERLINE_HXX

#include <com/sun/star/table/BorderLineStyle.hpp>

#include <tools/color.hxx>
#include <svl/poolitem.hxx>
#include <editeng/editengdllapi.h>
#include <svtools/ctrlbox.hxx>

// Line defaults in twips (former Writer defaults):

#define DEF_LINE_WIDTH_0        1
#define DEF_LINE_WIDTH_1        20
#define DEF_LINE_WIDTH_2        50
#define DEF_LINE_WIDTH_3        80
#define DEF_LINE_WIDTH_4        100
#define DEF_LINE_WIDTH_5        10

// ============================================================================

namespace editeng {

    // values from ::com::sun::star::table::BorderLineStyle
    typedef sal_Int16 SvxBorderStyle;

    // convert border style between Word formats and LO
    SvxBorderStyle EDITENG_DLLPUBLIC ConvertBorderStyleFromWord(int);
    /// convert border width in twips between Word formats and LO
    double EDITENG_DLLPUBLIC ConvertBorderWidthToWord(SvxBorderStyle, double);
    double EDITENG_DLLPUBLIC ConvertBorderWidthFromWord(SvxBorderStyle,
            double, int);

    class EDITENG_DLLPUBLIC SvxBorderLine
    {
    protected:
        Color  aColor;

        long m_nWidth;
        bool m_bMirrorWidths;
        BorderWidthImpl m_aWidthImpl;
        long m_nMult;
        long m_nDiv;

        SvxBorderStyle   m_nStyle;
        sal_uInt16 nOutWidth;
        sal_uInt16 nInWidth;
        sal_uInt16 nDistance;

        bool             m_bUseLeftTop;
        Color            (*m_pColorOutFn)( Color );
        Color            (*m_pColorInFn)( Color );
        Color            (*m_pColorGapFn)( Color );

    public:
        SvxBorderLine( const Color *pCol = 0,
                long nWidth = 0, SvxBorderStyle nStyle =
                    ::com::sun::star::table::BorderLineStyle::SOLID,
                bool bUseLeftTop = false,
                Color (*pColorOutFn)( Color ) = &darkColor,
                Color (*pColorInFn)( Color ) = &darkColor,
                Color (*pColorGapFn)( Color ) = NULL );
        SvxBorderLine( const SvxBorderLine& r );

        SvxBorderLine& operator=( const SvxBorderLine& r );

        const Color&    GetColor() const { return aColor; }
        Color           GetColorOut( bool bLeftOrTop = true ) const;
        Color           GetColorIn( bool bLeftOrTop = true ) const;
        bool            HasGapColor() const { return m_pColorGapFn != NULL; }
        Color           GetColorGap() const;

        void            SetWidth( long nWidth = 0 ) { m_nWidth = nWidth; }
        /** Guess the style and width from the three lines widths values.

            When the value of nStyle is SvxBorderLine::DOUBLE, the style set will be guessed
            using the three values to match the best possible style among the following:
                - SvxBorderLine::DOUBLE
                - SvxBorderLine::THINTHICK_SMALLGAP
                - SvxBorderLine::THINTHICK_MEDIUMGAP
                - SvxBorderLine::THINTHICK_LARGEGAP
                - SvxBorderLine::THICKTHIN_SMALLGAP
                - SvxBorderLine::THICKTHIN_MEDIUMGAP
                - SvxBorderLine::THICKTHIN_LARGEGAP

            If no styles matches the width, then the width is set to 0.

            There is one known case that could fit several styles: \a nIn = \a nDist = 0.75 pt,
            \a nOut = 1.5 pt. This case fits SvxBorderLine::THINTHICK_SMALLGAP and
            SvxBorderLine::THINTHICK_MEDIUMGAP with a 1.5 pt width and
            SvxBorderLine::THINTHICK_LARGEGAP with a 0.75 pt width. The same case happens
            also for thick-thin styles.

            \param nStyle the border style used to guess the width.
            \param nIn the width of the inner line in 1th pt
            \param nOut the width of the outer line in 1th pt
            \param nDist the width of the gap between the lines in 1th pt
         */
        void            GuessLinesWidths( SvxBorderStyle nStyle, sal_uInt16 nOut, sal_uInt16 nIn = 0, sal_uInt16 nDist = 0 );

        // TODO Hacky method to mirror lines in only a few cases
        void            SetMirrorWidths( bool bMirror = true ) { m_bMirrorWidths = bMirror; }
        long            GetWidth( ) const { return m_nWidth; }
        sal_uInt16      GetOutWidth() const;
        sal_uInt16      GetInWidth() const;
        sal_uInt16      GetDistance() const;

        SvxBorderStyle  GetBorderLineStyle() const { return m_nStyle; }

        void            SetColor( const Color &rColor ) { aColor = rColor; }
        void            SetColorOutFn( Color (*pColorOutFn)( Color ) ) { m_pColorOutFn = pColorOutFn; }
        void            SetColorInFn( Color (*pColorInFn)( Color ) ) { m_pColorInFn = pColorInFn; }
        void            SetColorGapFn( Color (*pColorGapFn)( Color ) ) { m_pColorGapFn = pColorGapFn; }
        void            SetUseLeftTop( bool bUseLeftTop ) { m_bUseLeftTop = bUseLeftTop; }
        void            SetBorderLineStyle( SvxBorderStyle nNew );
        void            ScaleMetrics( long nMult, long nDiv );

        sal_Bool            operator==( const SvxBorderLine &rCmp ) const;

        OUString        GetValueString( SfxMapUnit eSrcUnit, SfxMapUnit eDestUnit,
                                        const IntlWrapper* pIntl,
                                        sal_Bool bMetricStr = sal_False ) const;

        bool            HasPriority( const SvxBorderLine& rOtherLine ) const;

        bool isEmpty() const {
            return m_aWidthImpl.IsEmpty()
                || m_nStyle == ::com::sun::star::table::BorderLineStyle::NONE
                || m_nWidth == 0;
        }
        bool isDouble() const { return m_aWidthImpl.IsDouble(); }
        sal_uInt16 GetScaledWidth() const { return GetOutWidth() + GetInWidth() + GetDistance(); }

        static Color darkColor( Color aMain );
        static Color lightColor( Color aMain );

        static Color threeDLightColor( Color aMain );
        static Color threeDMediumColor( Color aMain );
        static Color threeDDarkColor( Color aMain );

        static BorderWidthImpl getWidthImpl( SvxBorderStyle nStyle );
    };

EDITENG_DLLPUBLIC bool operator!=( const SvxBorderLine& rLeft, const SvxBorderLine& rRight );

} // namespace editeng

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unused width members from BorderLine class<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef SVX_BORDERLINE_HXX
#define SVX_BORDERLINE_HXX

#include <com/sun/star/table/BorderLineStyle.hpp>

#include <tools/color.hxx>
#include <svl/poolitem.hxx>
#include <editeng/editengdllapi.h>
#include <svtools/ctrlbox.hxx>

// Line defaults in twips (former Writer defaults):

#define DEF_LINE_WIDTH_0        1
#define DEF_LINE_WIDTH_1        20
#define DEF_LINE_WIDTH_2        50
#define DEF_LINE_WIDTH_3        80
#define DEF_LINE_WIDTH_4        100
#define DEF_LINE_WIDTH_5        10

// ============================================================================

namespace editeng {

    // values from ::com::sun::star::table::BorderLineStyle
    typedef sal_Int16 SvxBorderStyle;

    // convert border style between Word formats and LO
    SvxBorderStyle EDITENG_DLLPUBLIC ConvertBorderStyleFromWord(int);
    /// convert border width in twips between Word formats and LO
    double EDITENG_DLLPUBLIC ConvertBorderWidthToWord(SvxBorderStyle, double);
    double EDITENG_DLLPUBLIC ConvertBorderWidthFromWord(SvxBorderStyle,
            double, int);

    class EDITENG_DLLPUBLIC SvxBorderLine
    {
    protected:
        Color  aColor;

        long m_nWidth;
        bool m_bMirrorWidths;
        BorderWidthImpl m_aWidthImpl;
        long m_nMult;
        long m_nDiv;

        SvxBorderStyle   m_nStyle;

        bool             m_bUseLeftTop;
        Color            (*m_pColorOutFn)( Color );
        Color            (*m_pColorInFn)( Color );
        Color            (*m_pColorGapFn)( Color );

    public:
        SvxBorderLine( const Color *pCol = 0,
                long nWidth = 0, SvxBorderStyle nStyle =
                    ::com::sun::star::table::BorderLineStyle::SOLID,
                bool bUseLeftTop = false,
                Color (*pColorOutFn)( Color ) = &darkColor,
                Color (*pColorInFn)( Color ) = &darkColor,
                Color (*pColorGapFn)( Color ) = NULL );
        SvxBorderLine( const SvxBorderLine& r );

        SvxBorderLine& operator=( const SvxBorderLine& r );

        const Color&    GetColor() const { return aColor; }
        Color           GetColorOut( bool bLeftOrTop = true ) const;
        Color           GetColorIn( bool bLeftOrTop = true ) const;
        bool            HasGapColor() const { return m_pColorGapFn != NULL; }
        Color           GetColorGap() const;

        void            SetWidth( long nWidth = 0 ) { m_nWidth = nWidth; }
        /** Guess the style and width from the three lines widths values.

            When the value of nStyle is SvxBorderLine::DOUBLE, the style set will be guessed
            using the three values to match the best possible style among the following:
                - SvxBorderLine::DOUBLE
                - SvxBorderLine::THINTHICK_SMALLGAP
                - SvxBorderLine::THINTHICK_MEDIUMGAP
                - SvxBorderLine::THINTHICK_LARGEGAP
                - SvxBorderLine::THICKTHIN_SMALLGAP
                - SvxBorderLine::THICKTHIN_MEDIUMGAP
                - SvxBorderLine::THICKTHIN_LARGEGAP

            If no styles matches the width, then the width is set to 0.

            There is one known case that could fit several styles: \a nIn = \a nDist = 0.75 pt,
            \a nOut = 1.5 pt. This case fits SvxBorderLine::THINTHICK_SMALLGAP and
            SvxBorderLine::THINTHICK_MEDIUMGAP with a 1.5 pt width and
            SvxBorderLine::THINTHICK_LARGEGAP with a 0.75 pt width. The same case happens
            also for thick-thin styles.

            \param nStyle the border style used to guess the width.
            \param nIn the width of the inner line in 1th pt
            \param nOut the width of the outer line in 1th pt
            \param nDist the width of the gap between the lines in 1th pt
         */
        void            GuessLinesWidths( SvxBorderStyle nStyle, sal_uInt16 nOut, sal_uInt16 nIn = 0, sal_uInt16 nDist = 0 );

        // TODO Hacky method to mirror lines in only a few cases
        void            SetMirrorWidths( bool bMirror = true ) { m_bMirrorWidths = bMirror; }
        long            GetWidth( ) const { return m_nWidth; }
        sal_uInt16      GetOutWidth() const;
        sal_uInt16      GetInWidth() const;
        sal_uInt16      GetDistance() const;

        SvxBorderStyle  GetBorderLineStyle() const { return m_nStyle; }

        void            SetColor( const Color &rColor ) { aColor = rColor; }
        void            SetColorOutFn( Color (*pColorOutFn)( Color ) ) { m_pColorOutFn = pColorOutFn; }
        void            SetColorInFn( Color (*pColorInFn)( Color ) ) { m_pColorInFn = pColorInFn; }
        void            SetColorGapFn( Color (*pColorGapFn)( Color ) ) { m_pColorGapFn = pColorGapFn; }
        void            SetUseLeftTop( bool bUseLeftTop ) { m_bUseLeftTop = bUseLeftTop; }
        void            SetBorderLineStyle( SvxBorderStyle nNew );
        void            ScaleMetrics( long nMult, long nDiv );

        sal_Bool            operator==( const SvxBorderLine &rCmp ) const;

        OUString        GetValueString( SfxMapUnit eSrcUnit, SfxMapUnit eDestUnit,
                                        const IntlWrapper* pIntl,
                                        sal_Bool bMetricStr = sal_False ) const;

        bool            HasPriority( const SvxBorderLine& rOtherLine ) const;

        bool isEmpty() const {
            return m_aWidthImpl.IsEmpty()
                || m_nStyle == ::com::sun::star::table::BorderLineStyle::NONE
                || m_nWidth == 0;
        }
        bool isDouble() const { return m_aWidthImpl.IsDouble(); }
        sal_uInt16 GetScaledWidth() const { return GetOutWidth() + GetInWidth() + GetDistance(); }

        static Color darkColor( Color aMain );
        static Color lightColor( Color aMain );

        static Color threeDLightColor( Color aMain );
        static Color threeDMediumColor( Color aMain );
        static Color threeDDarkColor( Color aMain );

        static BorderWidthImpl getWidthImpl( SvxBorderStyle nStyle );
    };

EDITENG_DLLPUBLIC bool operator!=( const SvxBorderLine& rLeft, const SvxBorderLine& rRight );

} // namespace editeng

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>