<commit_before>// Copyright 2012 the V8 project 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 "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      33
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<commit_msg>[Auto-roll] Bump up version to 3.29.34.0<commit_after>// Copyright 2012 the V8 project 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 "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      34
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>// Clang on MacOS can find libc++ living beside the installed compiler.
// This test makes sure our libTooling-based tools emulate this properly with
// fixed compilation database.
//
// RUN: rm -rf %t
// RUN: mkdir %t
//
// Install the mock libc++ (simulates the libc++ directory structure).
// RUN: cp -r %S/Inputs/mock-libcxx %t/
//
// RUN: cp clang-check %t/mock-libcxx/bin/
// RUN: cp %s %t/test.cpp
// RUN: "%t/mock-libcxx/bin/clang-check" -p %t %t/test.cpp -- \
// RUN:     -stdlib=libc++ -target x86_64-apple-darwin \
// RUN:     -ccc-install-dir %t/mock-libcxx/bin
//
// ^ -ccc-install-dir passed to unbreak tests on *BSD where
//   getMainExecutable() relies on real argv[0] being passed
//
// UNSUPPORTED: enable_shared
#include <mock_vector>
vector v;
<commit_msg>Revert r363298 "[lit] Disable test on darwin when building shared libs."<commit_after>// Clang on MacOS can find libc++ living beside the installed compiler.
// This test makes sure our libTooling-based tools emulate this properly with
// fixed compilation database.
//
// RUN: rm -rf %t
// RUN: mkdir %t
//
// Install the mock libc++ (simulates the libc++ directory structure).
// RUN: cp -r %S/Inputs/mock-libcxx %t/
//
// RUN: cp clang-check %t/mock-libcxx/bin/
// RUN: cp %s %t/test.cpp
// RUN: "%t/mock-libcxx/bin/clang-check" -p %t %t/test.cpp -- \
// RUN:     -stdlib=libc++ -target x86_64-apple-darwin \
// RUN:     -ccc-install-dir %t/mock-libcxx/bin
//
// ^ -ccc-install-dir passed to unbreak tests on *BSD where
//   getMainExecutable() relies on real argv[0] being passed
#include <mock_vector>
vector v;
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/combiner.h"

#include "test/core/util/test_config.h"

static grpc_combiner* g_combiner;

typedef struct on_resolution_arg {
  char* expected_server_name;
  grpc_channel_args* resolver_result;
} on_resolution_arg;

void on_resolution_cb(void* arg, grpc_error* error) {
  on_resolution_arg* res = static_cast<on_resolution_arg*>(arg);
  grpc_channel_args_destroy(res->resolver_result);
}

static void test_succeeds(grpc_resolver_factory* factory, const char* string) {
  grpc_core::ExecCtx exec_ctx;
  grpc_uri* uri = grpc_uri_parse(string, 0);
  grpc_resolver_args args;
  grpc_resolver* resolver;
  gpr_log(GPR_DEBUG, "test: '%s' should be valid for '%s'", string,
          factory->vtable->scheme);
  GPR_ASSERT(uri);
  memset(&args, 0, sizeof(args));
  args.uri = uri;
  args.combiner = g_combiner;
  resolver = grpc_resolver_factory_create_resolver(factory, &args);
  GPR_ASSERT(resolver != nullptr);

  on_resolution_arg on_res_arg;
  memset(&on_res_arg, 0, sizeof(on_res_arg));
  on_res_arg.expected_server_name = uri->path;
  grpc_closure* on_resolution = GRPC_CLOSURE_CREATE(
      on_resolution_cb, &on_res_arg, grpc_schedule_on_exec_ctx);

  grpc_resolver_next_locked(resolver, &on_res_arg.resolver_result,
                            on_resolution);
  GRPC_RESOLVER_UNREF(resolver, "test_succeeds");
  grpc_uri_destroy(uri);
  /* Flush ExecCtx to avoid stack-use-after-scope on on_res_arg which is
   * accessed in the closure on_resolition_cb */
  grpc_core::ExecCtx::Get()->Flush();
}

static void test_fails(grpc_resolver_factory* factory, const char* string) {
  grpc_core::ExecCtx exec_ctx;
  grpc_uri* uri = grpc_uri_parse(string, 0);
  grpc_resolver_args args;
  grpc_resolver* resolver;
  gpr_log(GPR_DEBUG, "test: '%s' should be invalid for '%s'", string,
          factory->vtable->scheme);
  GPR_ASSERT(uri);
  memset(&args, 0, sizeof(args));
  args.uri = uri;
  args.combiner = g_combiner;
  resolver = grpc_resolver_factory_create_resolver(factory, &args);
  GPR_ASSERT(resolver == nullptr);
  grpc_uri_destroy(uri);
}

int main(int argc, char** argv) {
  grpc_resolver_factory *ipv4, *ipv6;
  grpc_test_init(argc, argv);
  grpc_init();

  g_combiner = grpc_combiner_create();

  ipv4 = grpc_resolver_factory_lookup("ipv4");
  ipv6 = grpc_resolver_factory_lookup("ipv6");

  test_fails(ipv4, "ipv4:10.2.1.1");
  test_succeeds(ipv4, "ipv4:10.2.1.1:1234");
  test_succeeds(ipv4, "ipv4:10.2.1.1:1234,127.0.0.1:4321");
  test_fails(ipv4, "ipv4:10.2.1.1:123456");
  test_fails(ipv4, "ipv4:www.google.com");
  test_fails(ipv4, "ipv4:[");
  test_fails(ipv4, "ipv4://8.8.8.8/8.8.8.8:8888");

  test_fails(ipv6, "ipv6:[");
  test_fails(ipv6, "ipv6:[::]");
  test_succeeds(ipv6, "ipv6:[::]:1234");
  test_fails(ipv6, "ipv6:[::]:123456");
  test_fails(ipv6, "ipv6:www.google.com");

  grpc_resolver_factory_unref(ipv4);
  grpc_resolver_factory_unref(ipv6);

  {
    grpc_core::ExecCtx exec_ctx;
    GRPC_COMBINER_UNREF(g_combiner, "test");
  }
  grpc_shutdown();

  return 0;
}
<commit_msg>Fix typo s/resolition/resolution<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/combiner.h"

#include "test/core/util/test_config.h"

static grpc_combiner* g_combiner;

typedef struct on_resolution_arg {
  char* expected_server_name;
  grpc_channel_args* resolver_result;
} on_resolution_arg;

void on_resolution_cb(void* arg, grpc_error* error) {
  on_resolution_arg* res = static_cast<on_resolution_arg*>(arg);
  grpc_channel_args_destroy(res->resolver_result);
}

static void test_succeeds(grpc_resolver_factory* factory, const char* string) {
  grpc_core::ExecCtx exec_ctx;
  grpc_uri* uri = grpc_uri_parse(string, 0);
  grpc_resolver_args args;
  grpc_resolver* resolver;
  gpr_log(GPR_DEBUG, "test: '%s' should be valid for '%s'", string,
          factory->vtable->scheme);
  GPR_ASSERT(uri);
  memset(&args, 0, sizeof(args));
  args.uri = uri;
  args.combiner = g_combiner;
  resolver = grpc_resolver_factory_create_resolver(factory, &args);
  GPR_ASSERT(resolver != nullptr);

  on_resolution_arg on_res_arg;
  memset(&on_res_arg, 0, sizeof(on_res_arg));
  on_res_arg.expected_server_name = uri->path;
  grpc_closure* on_resolution = GRPC_CLOSURE_CREATE(
      on_resolution_cb, &on_res_arg, grpc_schedule_on_exec_ctx);

  grpc_resolver_next_locked(resolver, &on_res_arg.resolver_result,
                            on_resolution);
  GRPC_RESOLVER_UNREF(resolver, "test_succeeds");
  grpc_uri_destroy(uri);
  /* Flush ExecCtx to avoid stack-use-after-scope on on_res_arg which is
   * accessed in the closure on_resolution_cb */
  grpc_core::ExecCtx::Get()->Flush();
}

static void test_fails(grpc_resolver_factory* factory, const char* string) {
  grpc_core::ExecCtx exec_ctx;
  grpc_uri* uri = grpc_uri_parse(string, 0);
  grpc_resolver_args args;
  grpc_resolver* resolver;
  gpr_log(GPR_DEBUG, "test: '%s' should be invalid for '%s'", string,
          factory->vtable->scheme);
  GPR_ASSERT(uri);
  memset(&args, 0, sizeof(args));
  args.uri = uri;
  args.combiner = g_combiner;
  resolver = grpc_resolver_factory_create_resolver(factory, &args);
  GPR_ASSERT(resolver == nullptr);
  grpc_uri_destroy(uri);
}

int main(int argc, char** argv) {
  grpc_resolver_factory *ipv4, *ipv6;
  grpc_test_init(argc, argv);
  grpc_init();

  g_combiner = grpc_combiner_create();

  ipv4 = grpc_resolver_factory_lookup("ipv4");
  ipv6 = grpc_resolver_factory_lookup("ipv6");

  test_fails(ipv4, "ipv4:10.2.1.1");
  test_succeeds(ipv4, "ipv4:10.2.1.1:1234");
  test_succeeds(ipv4, "ipv4:10.2.1.1:1234,127.0.0.1:4321");
  test_fails(ipv4, "ipv4:10.2.1.1:123456");
  test_fails(ipv4, "ipv4:www.google.com");
  test_fails(ipv4, "ipv4:[");
  test_fails(ipv4, "ipv4://8.8.8.8/8.8.8.8:8888");

  test_fails(ipv6, "ipv6:[");
  test_fails(ipv6, "ipv6:[::]");
  test_succeeds(ipv6, "ipv6:[::]:1234");
  test_fails(ipv6, "ipv6:[::]:123456");
  test_fails(ipv6, "ipv6:www.google.com");

  grpc_resolver_factory_unref(ipv4);
  grpc_resolver_factory_unref(ipv6);

  {
    grpc_core::ExecCtx exec_ctx;
    GRPC_COMBINER_UNREF(g_combiner, "test");
  }
  grpc_shutdown();

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 Pierre MOULON.

// 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/.

#ifndef MIMATTE_LINEAR_PROGRAMMING_INTERFACE_OSICLP_H_
#define MIMATTE_LINEAR_PROGRAMMING_INTERFACE_OSICLP_H_

#include "OsiClpSolverInterface.hpp"
#ifdef OPENMVG_HAVE_MOSEK
#include "OsiMskSolverInterface.hpp"
#endif

#include "openMVG/numeric/numeric.h"
#include "openMVG/linearProgramming/linearProgrammingInterface.hpp"

#include "CoinPackedMatrix.hpp"
#include "CoinPackedVector.hpp"

#include <vector>

/* Constraint type codes  (internal) */
#define ROWTYPE_EMPTY            0
#define ROWTYPE_LE               1
#define ROWTYPE_GE               2
#define ROWTYPE_EQ               3
#define ROWTYPE_CONSTRAINT       ROWTYPE_EQ  /* This is the mask for modes */
#define ROWTYPE_OF               4
#define ROWTYPE_INACTIVE         8
#define ROWTYPE_RELAX           16
#define ROWTYPE_GUB             32
#define ROWTYPE_OFMAX            (ROWTYPE_OF + ROWTYPE_GE)
#define ROWTYPE_OFMIN            (ROWTYPE_OF + ROWTYPE_LE)
#define ROWTYPE_CHSIGN           ROWTYPE_GE

/* Public constraint codes */
#define FR                       ROWTYPE_EMPTY
#define LE                       ROWTYPE_LE
#define GE                       ROWTYPE_GE
#define EQ                       ROWTYPE_EQ
#define OF                       ROWTYPE_OF

namespace openMVG   {
namespace linearProgramming  {

/// OSI_X wrapper for the LP_Solver
template<typename SOLVERINTERFACE>
class OSI_X_SolverWrapper : public LP_Solver
{
public :
  OSI_X_SolverWrapper(int nbParams);

  ~OSI_X_SolverWrapper();

  //--
  // Inherited functions :
  //--

  bool setup(const LP_Constraints & constraints);
  bool setup(const LP_Constraints_Sparse & constraints);

  bool solve();

  bool getSolution(std::vector<double> & estimatedParams);

private :
  SOLVERINTERFACE *si;
};

typedef OSI_X_SolverWrapper<OsiClpSolverInterface> OSI_CLP_SolverWrapper;
#ifdef OPENMVG_HAVE_MOSEK
typedef OSI_X_SolverWrapper<OsiMskSolverInterface> OSI_MOSEK_SolverWrapper;
#endif // OPENMVG_HAVE_MOSEK

template<typename SOLVERINTERFACE>
OSI_X_SolverWrapper<SOLVERINTERFACE>::OSI_X_SolverWrapper(int nbParams) : LP_Solver(nbParams)
{
  si = new SOLVERINTERFACE;
}

template<typename SOLVERINTERFACE>
OSI_X_SolverWrapper<SOLVERINTERFACE>::~OSI_X_SolverWrapper()
{
  // Memory cleaning.
  if ( si != NULL )
  {
    delete si;
    si = NULL;
  }
}

template<typename SOLVERINTERFACE>
bool OSI_X_SolverWrapper<SOLVERINTERFACE>::setup(const LP_Constraints & cstraints) //cstraints <-> constraints
{
  bool bOk = true;
  if ( si == NULL )
  {
    return false;
  }
  assert(_nbParams == cstraints._nbParams);

  int NUMVAR = cstraints._constraintMat.cols();
  int NUMCON = cstraints._constraintMat.rows();
  int NUMANZ = cstraints._constraintMat.cols() * cstraints._constraintMat.rows(); //DENSE MATRIX

  std::vector<double> col_lb(NUMVAR);//the column lower bounds
  std::vector<double> col_ub(NUMVAR);//the column upper bounds

  this->_nbParams = NUMVAR;

  if (cstraints._bminimize)
  {
    si->setObjSense( 1 );
  }
  else
  {
    si->setObjSense( -1 );
  }

  const Mat & A = cstraints._constraintMat;

  //Equality constraint will be handked by two constraintsdue to the API limitation.
  size_t nbLine = A.rows() + std::count(cstraints._vec_sign.begin(), cstraints._vec_sign.end(), EQ);

  std::vector<double> row_lb(nbLine);//the row lower bounds
  std::vector<double> row_ub(nbLine);//the row upper bounds

  CoinPackedMatrix * matrix = new CoinPackedMatrix(false,0,0);
  matrix->setDimensions(0, NUMVAR);

  //-- Add row-wise constraint
  size_t indexRow = 0;
  for (int i=0; i < A.rows(); ++i)
  {
    Vec temp = A.row(i);

    CoinPackedVector row;
    if ( cstraints._vec_sign[i] == EQ || cstraints._vec_sign[i] == LE )
    {
      int coef = 1;
      for ( int j = 0; j < A.cols() ; j++ )
      {
	row.insert(j, coef * temp.data()[j]);
      }
      row_lb[indexRow] = -1.0 * si->getInfinity();
      row_ub[indexRow] = coef * cstraints._Cst_objective(i);
      matrix->appendRow(row);
      indexRow++;
    }
    if ( cstraints._vec_sign[i] == EQ || cstraints._vec_sign[i] == GE )
    {
      int coef = -1;
      for ( int j = 0; j < A.cols() ; j++ )
      {
	      row.insert(j, coef * temp.data()[j]);
      }
      row_lb[indexRow] = -1.0 * si->getInfinity();
      row_ub[indexRow] = coef * cstraints._Cst_objective(i);
      matrix->appendRow(row);
      indexRow++;
    }
  }

  //-- Setup bounds
  if (cstraints._vec_bounds.size() == 1)
  {
    // Setup the same bound for all the parameter
    for (int i=0; i < this->_nbParams; ++i)
    {
      col_lb[i] = cstraints._vec_bounds[0].first;
      col_ub[i] = cstraints._vec_bounds[0].second;
    }
  }
  else
  {

    for (int i=0; i < this->_nbParams; ++i)
    {
      col_lb[i] = cstraints._vec_bounds[i].first;
      col_ub[i] = cstraints._vec_bounds[i].second;
    }
  }

  si->loadProblem(*matrix, &col_lb[0], &col_ub[0], cstraints._vec_cost.empty() ? NULL : &cstraints._vec_cost[0], &row_lb[0], &row_ub[0] );

  delete matrix;

  return bOk;
}

template<typename SOLVERINTERFACE>
bool OSI_X_SolverWrapper<SOLVERINTERFACE>::setup(const LP_Constraints_Sparse & cstraints) //cstraints <-> constraints
{
  bool bOk = true;
  if ( si == NULL )
  {
    return false;
  }
  assert(_nbParams == cstraints._nbParams);

  int NUMVAR = cstraints._constraintMat.cols();
  int NUMCON = cstraints._constraintMat.rows();
  int NUMANZ = cstraints._constraintMat.cols() * cstraints._constraintMat.rows(); //DENSE MATRIX
  std::vector<double> col_lb(NUMVAR);//the column lower bounds
  std::vector<double> col_ub(NUMVAR);//the column upper bounds

  this->_nbParams = NUMVAR;

  if (cstraints._bminimize)
  {
    si->setObjSense( 1 );
  }
  else
  {
    si->setObjSense( -1 );
  }

  const sRMat & A = cstraints._constraintMat;

  //Equality constraint will be handked by two constraintsdue to the API limitation.
  size_t nbLine = A.rows() + std::count(cstraints._vec_sign.begin(), cstraints._vec_sign.end(), EQ);

  std::vector<double> row_lb(nbLine);//the row lower bounds
  std::vector<double> row_ub(nbLine);//the row upper bounds

  CoinPackedMatrix * matrix = new CoinPackedMatrix(false,0,0);
  matrix->setDimensions(0, NUMVAR);

  //-- Add row-wise constraint
  size_t rowindex = 0;
  for (int i=0; i < A.rows(); ++i)
  {
    std::vector<int> vec_colno;
    std::vector<double> vec_value;
    for (sRMat::InnerIterator it(A,i); it; ++it)
    {
      vec_colno.push_back(it.col());
      vec_value.push_back(it.value());
    }

    if ( cstraints._vec_sign[i] == EQ || cstraints._vec_sign[i] == LE )
    {
      int coef = 1;
      row_lb[rowindex] = -1.0 * si->getInfinity();
      row_ub[rowindex] = coef * cstraints._Cst_objective(i);;
      matrix->appendRow( vec_colno.size(),
	                 &vec_colno[0],
	                 &vec_value[0] );
      rowindex++;
    }

    if ( cstraints._vec_sign[i] == EQ || cstraints._vec_sign[i] == GE )
    {
      int coef = -1;
      for ( std::vector<double>::iterator iter_val = vec_value.begin();
	      iter_val != vec_value.end();
	      iter_val++)
      {
  	    *iter_val *= coef;
      }
      row_lb[rowindex] = -1.0 * si->getInfinity();
      row_ub[rowindex] = coef * cstraints._Cst_objective(i);;
      matrix->appendRow( vec_colno.size(),
	                 &vec_colno[0],
	                 &vec_value[0] );
      rowindex++;
    }
  }

  //-- Setup bounds
  if (cstraints._vec_bounds.size() == 1)
  {
    // Setup the same bound for all the parameter
    for (int i=0; i < this->_nbParams; ++i)
    {
      col_lb[i] = cstraints._vec_bounds[0].first;
      col_ub[i] = cstraints._vec_bounds[0].second;
    }
  }
  else  {
    // Set the required bound per constraint
    for (int i=0; i < this->_nbParams; ++i)
    {
      col_lb[i] = cstraints._vec_bounds[i].first;
      col_ub[i] = cstraints._vec_bounds[i].second;
    }
  }

  si->loadProblem(
    *matrix,
    &col_lb[0],
    &col_ub[0],
    cstraints._vec_cost.empty() ? NULL : &cstraints._vec_cost[0],
    &row_lb[0],
    &row_ub[0]);

  delete matrix;

  return bOk;
}

template<typename SOLVERINTERFACE>
bool OSI_X_SolverWrapper<SOLVERINTERFACE>::solve()
{
  //-- Compute solution
  if ( si != NULL )
  {
    si->initialSolve();
    return si->isProvenOptimal();
  }
  return false;
}

template<typename SOLVERINTERFACE>
bool OSI_X_SolverWrapper<SOLVERINTERFACE>::getSolution(std::vector<double> & estimatedParams)
{
  if ( si != NULL )
  {
    int n = si->getNumCols();
    const double *solution;
    solution = si->getColSolution();
    for ( int i = 0; i < n ; i++ )
    {
      estimatedParams[i] = solution[i];
    }
    return true;
  }
  return false;
}

} // namespace linearProgramming
} // namespace openMVG

#endif // MIMATTE_LINEAR_PROGRAMMING_INTERFACE_OSICLP_H_

<commit_msg>Set OSI_X verbosity to minimum.<commit_after>// Copyright (c) 2012 Pierre MOULON.

// 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/.

#ifndef MIMATTE_LINEAR_PROGRAMMING_INTERFACE_OSICLP_H_
#define MIMATTE_LINEAR_PROGRAMMING_INTERFACE_OSICLP_H_

#include "OsiClpSolverInterface.hpp"
#ifdef OPENMVG_HAVE_MOSEK
#include "OsiMskSolverInterface.hpp"
#endif

#include "openMVG/numeric/numeric.h"
#include "openMVG/linearProgramming/linearProgrammingInterface.hpp"

#include "CoinPackedMatrix.hpp"
#include "CoinPackedVector.hpp"

#include <vector>

/* Constraint type codes  (internal) */
#define ROWTYPE_EMPTY            0
#define ROWTYPE_LE               1
#define ROWTYPE_GE               2
#define ROWTYPE_EQ               3
#define ROWTYPE_CONSTRAINT       ROWTYPE_EQ  /* This is the mask for modes */
#define ROWTYPE_OF               4
#define ROWTYPE_INACTIVE         8
#define ROWTYPE_RELAX           16
#define ROWTYPE_GUB             32
#define ROWTYPE_OFMAX            (ROWTYPE_OF + ROWTYPE_GE)
#define ROWTYPE_OFMIN            (ROWTYPE_OF + ROWTYPE_LE)
#define ROWTYPE_CHSIGN           ROWTYPE_GE

/* Public constraint codes */
#define FR                       ROWTYPE_EMPTY
#define LE                       ROWTYPE_LE
#define GE                       ROWTYPE_GE
#define EQ                       ROWTYPE_EQ
#define OF                       ROWTYPE_OF

namespace openMVG   {
namespace linearProgramming  {

/// OSI_X wrapper for the LP_Solver
template<typename SOLVERINTERFACE>
class OSI_X_SolverWrapper : public LP_Solver
{
public :
  OSI_X_SolverWrapper(int nbParams);

  ~OSI_X_SolverWrapper();

  //--
  // Inherited functions :
  //--

  bool setup(const LP_Constraints & constraints);
  bool setup(const LP_Constraints_Sparse & constraints);

  bool solve();

  bool getSolution(std::vector<double> & estimatedParams);

private :
  SOLVERINTERFACE *si;
};

typedef OSI_X_SolverWrapper<OsiClpSolverInterface> OSI_CLP_SolverWrapper;
#ifdef OPENMVG_HAVE_MOSEK
typedef OSI_X_SolverWrapper<OsiMskSolverInterface> OSI_MOSEK_SolverWrapper;
#endif // OPENMVG_HAVE_MOSEK

template<typename SOLVERINTERFACE>
OSI_X_SolverWrapper<SOLVERINTERFACE>::OSI_X_SolverWrapper(int nbParams) : LP_Solver(nbParams)
{
  si = new SOLVERINTERFACE;
  si->setLogLevel(0);
}

template<typename SOLVERINTERFACE>
OSI_X_SolverWrapper<SOLVERINTERFACE>::~OSI_X_SolverWrapper()
{
  // Memory cleaning.
  if ( si != NULL )
  {
    delete si;
    si = NULL;
  }
}

template<typename SOLVERINTERFACE>
bool OSI_X_SolverWrapper<SOLVERINTERFACE>::setup(const LP_Constraints & cstraints) //cstraints <-> constraints
{
  bool bOk = true;
  if ( si == NULL )
  {
    return false;
  }
  assert(_nbParams == cstraints._nbParams);

  int NUMVAR = cstraints._constraintMat.cols();
  int NUMCON = cstraints._constraintMat.rows();
  int NUMANZ = cstraints._constraintMat.cols() * cstraints._constraintMat.rows(); //DENSE MATRIX

  std::vector<double> col_lb(NUMVAR);//the column lower bounds
  std::vector<double> col_ub(NUMVAR);//the column upper bounds

  this->_nbParams = NUMVAR;

  if (cstraints._bminimize)
  {
    si->setObjSense( 1 );
  }
  else
  {
    si->setObjSense( -1 );
  }

  const Mat & A = cstraints._constraintMat;

  //Equality constraint will be handked by two constraintsdue to the API limitation.
  size_t nbLine = A.rows() + std::count(cstraints._vec_sign.begin(), cstraints._vec_sign.end(), EQ);

  std::vector<double> row_lb(nbLine);//the row lower bounds
  std::vector<double> row_ub(nbLine);//the row upper bounds

  CoinPackedMatrix * matrix = new CoinPackedMatrix(false,0,0);
  matrix->setDimensions(0, NUMVAR);

  //-- Add row-wise constraint
  size_t indexRow = 0;
  for (int i=0; i < A.rows(); ++i)
  {
    Vec temp = A.row(i);

    CoinPackedVector row;
    if ( cstraints._vec_sign[i] == EQ || cstraints._vec_sign[i] == LE )
    {
      int coef = 1;
      for ( int j = 0; j < A.cols() ; j++ )
      {
	row.insert(j, coef * temp.data()[j]);
      }
      row_lb[indexRow] = -1.0 * si->getInfinity();
      row_ub[indexRow] = coef * cstraints._Cst_objective(i);
      matrix->appendRow(row);
      indexRow++;
    }
    if ( cstraints._vec_sign[i] == EQ || cstraints._vec_sign[i] == GE )
    {
      int coef = -1;
      for ( int j = 0; j < A.cols() ; j++ )
      {
	      row.insert(j, coef * temp.data()[j]);
      }
      row_lb[indexRow] = -1.0 * si->getInfinity();
      row_ub[indexRow] = coef * cstraints._Cst_objective(i);
      matrix->appendRow(row);
      indexRow++;
    }
  }

  //-- Setup bounds
  if (cstraints._vec_bounds.size() == 1)
  {
    // Setup the same bound for all the parameter
    for (int i=0; i < this->_nbParams; ++i)
    {
      col_lb[i] = cstraints._vec_bounds[0].first;
      col_ub[i] = cstraints._vec_bounds[0].second;
    }
  }
  else
  {

    for (int i=0; i < this->_nbParams; ++i)
    {
      col_lb[i] = cstraints._vec_bounds[i].first;
      col_ub[i] = cstraints._vec_bounds[i].second;
    }
  }

  si->loadProblem(*matrix, &col_lb[0], &col_ub[0], cstraints._vec_cost.empty() ? NULL : &cstraints._vec_cost[0], &row_lb[0], &row_ub[0] );

  delete matrix;

  return bOk;
}

template<typename SOLVERINTERFACE>
bool OSI_X_SolverWrapper<SOLVERINTERFACE>::setup(const LP_Constraints_Sparse & cstraints) //cstraints <-> constraints
{
  bool bOk = true;
  if ( si == NULL )
  {
    return false;
  }
  assert(_nbParams == cstraints._nbParams);

  int NUMVAR = cstraints._constraintMat.cols();
  int NUMCON = cstraints._constraintMat.rows();
  int NUMANZ = cstraints._constraintMat.cols() * cstraints._constraintMat.rows(); //DENSE MATRIX
  std::vector<double> col_lb(NUMVAR);//the column lower bounds
  std::vector<double> col_ub(NUMVAR);//the column upper bounds

  this->_nbParams = NUMVAR;

  if (cstraints._bminimize)
  {
    si->setObjSense( 1 );
  }
  else
  {
    si->setObjSense( -1 );
  }

  const sRMat & A = cstraints._constraintMat;

  //Equality constraint will be handked by two constraintsdue to the API limitation.
  size_t nbLine = A.rows() + std::count(cstraints._vec_sign.begin(), cstraints._vec_sign.end(), EQ);

  std::vector<double> row_lb(nbLine);//the row lower bounds
  std::vector<double> row_ub(nbLine);//the row upper bounds

  CoinPackedMatrix * matrix = new CoinPackedMatrix(false,0,0);
  matrix->setDimensions(0, NUMVAR);

  //-- Add row-wise constraint
  size_t rowindex = 0;
  for (int i=0; i < A.rows(); ++i)
  {
    std::vector<int> vec_colno;
    std::vector<double> vec_value;
    for (sRMat::InnerIterator it(A,i); it; ++it)
    {
      vec_colno.push_back(it.col());
      vec_value.push_back(it.value());
    }

    if ( cstraints._vec_sign[i] == EQ || cstraints._vec_sign[i] == LE )
    {
      int coef = 1;
      row_lb[rowindex] = -1.0 * si->getInfinity();
      row_ub[rowindex] = coef * cstraints._Cst_objective(i);;
      matrix->appendRow( vec_colno.size(),
	                 &vec_colno[0],
	                 &vec_value[0] );
      rowindex++;
    }

    if ( cstraints._vec_sign[i] == EQ || cstraints._vec_sign[i] == GE )
    {
      int coef = -1;
      for ( std::vector<double>::iterator iter_val = vec_value.begin();
	      iter_val != vec_value.end();
	      iter_val++)
      {
  	    *iter_val *= coef;
      }
      row_lb[rowindex] = -1.0 * si->getInfinity();
      row_ub[rowindex] = coef * cstraints._Cst_objective(i);;
      matrix->appendRow( vec_colno.size(),
	                 &vec_colno[0],
	                 &vec_value[0] );
      rowindex++;
    }
  }

  //-- Setup bounds
  if (cstraints._vec_bounds.size() == 1)
  {
    // Setup the same bound for all the parameter
    for (int i=0; i < this->_nbParams; ++i)
    {
      col_lb[i] = cstraints._vec_bounds[0].first;
      col_ub[i] = cstraints._vec_bounds[0].second;
    }
  }
  else  {
    // Set the required bound per constraint
    for (int i=0; i < this->_nbParams; ++i)
    {
      col_lb[i] = cstraints._vec_bounds[i].first;
      col_ub[i] = cstraints._vec_bounds[i].second;
    }
  }

  si->loadProblem(
    *matrix,
    &col_lb[0],
    &col_ub[0],
    cstraints._vec_cost.empty() ? NULL : &cstraints._vec_cost[0],
    &row_lb[0],
    &row_ub[0]);

  delete matrix;

  return bOk;
}

template<typename SOLVERINTERFACE>
bool OSI_X_SolverWrapper<SOLVERINTERFACE>::solve()
{
  //-- Compute solution
  if ( si != NULL )
  {
    si->initialSolve();
    return si->isProvenOptimal();
  }
  return false;
}

template<typename SOLVERINTERFACE>
bool OSI_X_SolverWrapper<SOLVERINTERFACE>::getSolution(std::vector<double> & estimatedParams)
{
  if ( si != NULL )
  {
    int n = si->getNumCols();
    const double *solution;
    solution = si->getColSolution();
    for ( int i = 0; i < n ; i++ )
    {
      estimatedParams[i] = solution[i];
    }
    return true;
  }
  return false;
}

} // namespace linearProgramming
} // namespace openMVG

#endif // MIMATTE_LINEAR_PROGRAMMING_INTERFACE_OSICLP_H_

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "projectwelcomepagewidget.h"
#include "ui_projectwelcomepagewidget.h"

#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/dialogs/iwizard.h>

#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QPair>
#include <QtGui/QLabel>
#include <QtGui/QTreeWidgetItem>

#include <QtCore/QDebug>

using namespace ProjectExplorer::Internal;

bool ProjectWelcomePageWidget::WelcomePageData::operator==(const WelcomePageData &rhs) const
{
    return previousSession == rhs.previousSession
        && activeSession   == rhs.activeSession
        && sessionList     == rhs.sessionList
        && projectList     == rhs.projectList;
}

bool ProjectWelcomePageWidget::WelcomePageData::operator!=(const WelcomePageData &rhs) const
{
    return previousSession != rhs.previousSession
        || activeSession   != rhs.activeSession
        || sessionList     != rhs.sessionList
        || projectList     != rhs.projectList;
}

QDebug operator<<(QDebug dgb, const ProjectWelcomePageWidget::WelcomePageData &d)
{
    dgb.nospace() << "PreviousSession=" << d.previousSession
        << " activeSession=" << d.activeSession
        << " sessionList=" << d.sessionList
        << " projectList=" << d.projectList;
    return dgb;
}

ProjectWelcomePageWidget::ProjectWelcomePageWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ProjectWelcomePageWidget)
{
    ui->setupUi(this);
    ui->projTitleLabel->setStyledText(tr("Open Recent Project"));
    ui->recentSessionsTitleLabel->setStyledText(tr("Resume Session"));
    updateWelcomePage(WelcomePageData());

    connect(ui->sessTreeWidget, SIGNAL(activated(QString)), SLOT(slotSessionClicked(QString)));
    connect(ui->projTreeWidget, SIGNAL(activated(QString)), SLOT(slotProjectClicked(QString)));
    connect(ui->createNewProjectButton, SIGNAL(clicked()), SLOT(slotCreateNewProject()));
    connect(ui->manageSessionsButton, SIGNAL(clicked()), SIGNAL(manageSessions()));

}

ProjectWelcomePageWidget::~ProjectWelcomePageWidget()
{
    delete ui;
}

void ProjectWelcomePageWidget::updateWelcomePage(const WelcomePageData &welcomePageData)
{
    // Update only if data are modified
    if (welcomePageData == lastData)
        return;
    lastData = welcomePageData;

    setUpdatesEnabled(false);
    ui->sessTreeWidget->clear();
    ui->projTreeWidget->clear();

    if (welcomePageData.sessionList.count() > 0) {
        foreach (const QString &s, welcomePageData.sessionList) {
            QString str = s;
            if (welcomePageData.activeSession.isEmpty()) {
                if (s == welcomePageData.previousSession)
                    str = tr("%1 (last session)").arg(s);
            } else {
                if (s == welcomePageData.activeSession)
                    str = tr("%1 (current session)").arg(s);
            }
            ui->sessTreeWidget->addItem(str, s);
        }
        ui->sessTreeWidget->updateGeometry();
        ui->sessTreeWidget->show();
    } else {
        ui->sessTreeWidget->hide();
    }

    typedef QPair<QString, QString> QStringPair;
    if (welcomePageData.projectList.count() > 0) {
        foreach (const QStringPair &it, welcomePageData.projectList) {
            const QFileInfo fi(it.first);
            ui->projTreeWidget->addItem(it.second, it.first, fi.absolutePath());
        }
    } else {
        ui->projTreeWidget->hide();
    }
    ui->projTreeWidget->updateGeometry();
    setUpdatesEnabled(true);
}

void ProjectWelcomePageWidget::activateEditMode()
{
    Core::ModeManager *modeManager = Core::ModeManager::instance();
    if (modeManager->currentMode() == modeManager->mode(Core::Constants::MODE_WELCOME))
        modeManager->activateMode(Core::Constants::MODE_EDIT);
}

void ProjectWelcomePageWidget::slotSessionClicked(const QString &data)
{
    emit requestSession(data);
    activateEditMode();
}

void ProjectWelcomePageWidget::slotProjectClicked(const QString &data)
{
    emit requestProject(data);
    activateEditMode();
}

void ProjectWelcomePageWidget::slotCreateNewProject()
{
    Core::ICore::instance()->showNewItemDialog(tr("New Project..."),
                                               Core::IWizard::wizardsOfKind(Core::IWizard::ProjectWizard));
}
<commit_msg>welcome mode: toNativeSeparators() for project tooltips<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "projectwelcomepagewidget.h"
#include "ui_projectwelcomepagewidget.h"

#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/dialogs/iwizard.h>

#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QPair>
#include <QtGui/QLabel>
#include <QtGui/QTreeWidgetItem>

#include <QtCore/QDebug>

using namespace ProjectExplorer::Internal;

bool ProjectWelcomePageWidget::WelcomePageData::operator==(const WelcomePageData &rhs) const
{
    return previousSession == rhs.previousSession
        && activeSession   == rhs.activeSession
        && sessionList     == rhs.sessionList
        && projectList     == rhs.projectList;
}

bool ProjectWelcomePageWidget::WelcomePageData::operator!=(const WelcomePageData &rhs) const
{
    return previousSession != rhs.previousSession
        || activeSession   != rhs.activeSession
        || sessionList     != rhs.sessionList
        || projectList     != rhs.projectList;
}

QDebug operator<<(QDebug dgb, const ProjectWelcomePageWidget::WelcomePageData &d)
{
    dgb.nospace() << "PreviousSession=" << d.previousSession
        << " activeSession=" << d.activeSession
        << " sessionList=" << d.sessionList
        << " projectList=" << d.projectList;
    return dgb;
}

ProjectWelcomePageWidget::ProjectWelcomePageWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ProjectWelcomePageWidget)
{
    ui->setupUi(this);
    ui->projTitleLabel->setStyledText(tr("Open Recent Project"));
    ui->recentSessionsTitleLabel->setStyledText(tr("Resume Session"));
    updateWelcomePage(WelcomePageData());

    connect(ui->sessTreeWidget, SIGNAL(activated(QString)), SLOT(slotSessionClicked(QString)));
    connect(ui->projTreeWidget, SIGNAL(activated(QString)), SLOT(slotProjectClicked(QString)));
    connect(ui->createNewProjectButton, SIGNAL(clicked()), SLOT(slotCreateNewProject()));
    connect(ui->manageSessionsButton, SIGNAL(clicked()), SIGNAL(manageSessions()));

}

ProjectWelcomePageWidget::~ProjectWelcomePageWidget()
{
    delete ui;
}

void ProjectWelcomePageWidget::updateWelcomePage(const WelcomePageData &welcomePageData)
{
    // Update only if data are modified
    if (welcomePageData == lastData)
        return;
    lastData = welcomePageData;

    setUpdatesEnabled(false);
    ui->sessTreeWidget->clear();
    ui->projTreeWidget->clear();

    if (welcomePageData.sessionList.count() > 0) {
        foreach (const QString &s, welcomePageData.sessionList) {
            QString str = s;
            if (welcomePageData.activeSession.isEmpty()) {
                if (s == welcomePageData.previousSession)
                    str = tr("%1 (last session)").arg(s);
            } else {
                if (s == welcomePageData.activeSession)
                    str = tr("%1 (current session)").arg(s);
            }
            ui->sessTreeWidget->addItem(str, s);
        }
        ui->sessTreeWidget->updateGeometry();
        ui->sessTreeWidget->show();
    } else {
        ui->sessTreeWidget->hide();
    }

    typedef QPair<QString, QString> QStringPair;
    if (welcomePageData.projectList.count() > 0) {
        foreach (const QStringPair &it, welcomePageData.projectList) {
            const QFileInfo fi(it.first);
            ui->projTreeWidget->addItem(it.second, it.first,
                                        QDir::toNativeSeparators(fi.absolutePath()));
        }
    } else {
        ui->projTreeWidget->hide();
    }
    ui->projTreeWidget->updateGeometry();
    setUpdatesEnabled(true);
}

void ProjectWelcomePageWidget::activateEditMode()
{
    Core::ModeManager *modeManager = Core::ModeManager::instance();
    if (modeManager->currentMode() == modeManager->mode(Core::Constants::MODE_WELCOME))
        modeManager->activateMode(Core::Constants::MODE_EDIT);
}

void ProjectWelcomePageWidget::slotSessionClicked(const QString &data)
{
    emit requestSession(data);
    activateEditMode();
}

void ProjectWelcomePageWidget::slotProjectClicked(const QString &data)
{
    emit requestProject(data);
    activateEditMode();
}

void ProjectWelcomePageWidget::slotCreateNewProject()
{
    Core::ICore::instance()->showNewItemDialog(tr("New Project..."),
                                               Core::IWizard::wizardsOfKind(Core::IWizard::ProjectWizard));
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "metainfoparser.h"
#include "metainfo.h"

#include "propertymetainfo.h"
#include "model/propertyparser.h"
#include <QXmlStreamReader>
#include <QString>
#include <QFile>
#include <QtDebug>
#include <QIcon>

namespace QmlDesigner {
namespace Internal {

static bool stringToBool(const QString &boolString)
{
    QString lowerString(boolString.toLower());
    if (lowerString == "true" || lowerString == "1")
        return true;

    return false;
}

MetaInfoParser::MetaInfoParser(const MetaInfo &metaInfo)
        : m_metaInfo(metaInfo)
{
}

void MetaInfoParser::parseFile(const QString &path)
{
    QFile file;
    file.setFileName(path);
    if (!file.open(QIODevice::ReadOnly))
        throw new InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__);

    QXmlStreamReader reader;
    reader.setDevice(&file);

    while (!reader.atEnd()) {
        reader.readNext();
        tokenHandler(reader);
    }
    errorHandling(reader, file);
}

void MetaInfoParser::tokenHandler(QXmlStreamReader &reader)
{
    if (reader.isStartElement() && reader.name() == "metainfo")
        handleMetaInfoElement(reader);
}

void MetaInfoParser::handleMetaInfoElement(QXmlStreamReader &reader)
{
    while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "metainfo")) {
        reader.readNext();
        metaInfoHandler(reader);
    }
}

void MetaInfoParser::metaInfoHandler(QXmlStreamReader &reader)
{
    if (reader.isStartElement())
    {
        if (reader.name() == "enumerator")
            handleEnumElement(reader);

        if (reader.name() == "flag")
            handleFlagElement(reader);

        if (reader.name() == "node")
            handleNodeElement(reader);
    }
}

void MetaInfoParser::handleEnumElement(QXmlStreamReader &reader)
{
    QString enumeratorName = reader.attributes().value("name").toString();
    QString enumeratorScope = reader.attributes().value("scope").toString();
    EnumeratorMetaInfo enumeratorMetaInfo;
    if (m_metaInfo.hasEnumerator(enumeratorName)) {
        enumeratorMetaInfo = m_metaInfo.enumerator(enumeratorName);
    } else {
        enumeratorMetaInfo = m_metaInfo.addEnumerator(enumeratorScope, enumeratorName);
    }

    while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "enumerator")) {

        reader.readNext();
        handleEnumElementElement(reader, enumeratorMetaInfo);
    }
}

void MetaInfoParser::handleFlagElement(QXmlStreamReader &reader)
{
    QString enumeratorName = reader.attributes().value("name").toString();
    QString enumeratorScope = reader.attributes().value("scope").toString();
    EnumeratorMetaInfo enumeratorMetaInfo = m_metaInfo.addFlag(enumeratorScope, enumeratorName);

    while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "flag")) {

        reader.readNext();
        handleFlagElementElement(reader, enumeratorMetaInfo);
    }
}

void MetaInfoParser::handleEnumElementElement(QXmlStreamReader &reader, EnumeratorMetaInfo &enumeratorMetaInfo)
{
    if (reader.isStartElement() && reader.name() == "element")
    {
        bool isIntType;
        enumeratorMetaInfo.addElement(reader.attributes().value("name").toString(),
                                     reader.attributes().value("value").toString().toInt(&isIntType));
        Q_ASSERT(isIntType);
    }
}

void MetaInfoParser::handleFlagElementElement(QXmlStreamReader &reader, EnumeratorMetaInfo &enumeratorMetaInfo)
{
    if (reader.isStartElement() && reader.name() == "element")
    {
        bool isIntType;
        enumeratorMetaInfo.addElement(reader.attributes().value("name").toString(),
                                     reader.attributes().value("value").toString().toInt(&isIntType));
        Q_ASSERT(isIntType);
    }
}

void MetaInfoParser::handleNodeElement(QXmlStreamReader &reader)
{
    const QXmlStreamAttributes attributes = reader.attributes();

    const QString className = attributes.value("name").toString();
    if (className.isEmpty()) {
        reader.raiseError("Invalid element 'node' - mandatory attribute 'name' is missing");
        return;
    }

    NodeMetaInfo nodeMetaInfo;
    if (m_metaInfo.hasNodeMetaInfo(className)) {
        nodeMetaInfo = m_metaInfo.nodeMetaInfo(className);
    } else {
        qWarning() << "Metainfo: " << className << " does not exist";
       while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "node"))
            reader.readNext();
        return;
    }

    if (attributes.hasAttribute("isContainer")) {
        const QString isContainer = attributes.value("isContainer").toString();
        nodeMetaInfo.setIsContainer(stringToBool(isContainer));
    }

    if (attributes.hasAttribute("showInItemLibrary")) {
        const QString showInItemLibrary = attributes.value("showInItemLibrary").toString();
        nodeMetaInfo.setIsVisibleToItemLibrary(stringToBool(showInItemLibrary));
    }

    if (attributes.hasAttribute("category")) {
        const QString category = attributes.value("category").toString();
        nodeMetaInfo.setCategory(category);
    }

    if (attributes.hasAttribute("icon")) {
        const QString iconPath = reader.attributes().value("icon").toString();
        nodeMetaInfo.setIcon(QIcon(iconPath));
    }

    while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "node")) {
        reader.readNext();

        handleNodeInheritElement(reader, className);
        handleAbstractPropertyElement(reader, nodeMetaInfo);
        handleAbstractPropertyDefaultValueElement(reader, nodeMetaInfo);
        handleNodeItemLibraryRepresentationElement(reader, className);
    }
}

void MetaInfoParser::handleNodeItemLibraryRepresentationElement(QXmlStreamReader &reader, const QString & className)
{
    if (reader.isStartElement() && reader.name() == "itemlibraryrepresentation")
    {
        QString name = reader.attributes().value("name").toString();
        ItemLibraryInfo ItemLibraryInfo = m_metaInfo.addItemLibraryInfo(m_metaInfo.nodeMetaInfo(className), name);

        QString iconPath = reader.attributes().value("icon").toString();
        if (!iconPath.isEmpty())
            ItemLibraryInfo.setIcon(QIcon(iconPath));

        while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "itemlibraryrepresentation")) {
            reader.readNext();
            handleItemLibraryInfoPropertyElement(reader, ItemLibraryInfo);
        }
    }
}

void MetaInfoParser::handleNodeInheritElement(QXmlStreamReader &reader, const QString & className)
{
    if (reader.isStartElement() && reader.name() == "inherits")
    {
        QString superClassName = reader.attributes().value("name").toString();
        Q_ASSERT(!superClassName.isEmpty());
        m_metaInfo.addSuperClassRelationship(superClassName, className);
        reader.readNext();
    }
}

void MetaInfoParser::handleItemLibraryInfoPropertyElement(QXmlStreamReader &reader, ItemLibraryInfo &ItemLibraryInfo)
{
    if (reader.isStartElement() && reader.name() == "property")
    {
        QXmlStreamAttributes attributes(reader.attributes());
        QString name = attributes.value("name").toString();
        QString type = attributes.value("type").toString();
        QString value = attributes.value("value").toString();
        ItemLibraryInfo.addProperty(name, type, value);

        reader.readNext();
    }
}

void MetaInfoParser::handleAbstractPropertyDefaultValueElement(QXmlStreamReader &reader, NodeMetaInfo &nodeMetaInfoArg)
{
    if (reader.isStartElement() && reader.name() == "propertyDefaultValue")
    {
        const QXmlStreamAttributes attributes(reader.attributes());
        Q_ASSERT(attributes.hasAttribute("name"));
        Q_ASSERT(attributes.hasAttribute("type"));
        Q_ASSERT(attributes.hasAttribute("defaultValue"));
        const QString propertyName = attributes.value("name").toString();
        const QString propertyType = attributes.value("type").toString();
        const QString defaultValueString = attributes.value("defaultValue").toString();
        QVariant defaultValue = Internal::PropertyParser::read(propertyType,
                                                               defaultValueString,
                                                               m_metaInfo);

        QList<NodeMetaInfo> nodeMetaInfoList(nodeMetaInfoArg.superClasses());
        nodeMetaInfoList.prepend(nodeMetaInfoArg);
        foreach(const NodeMetaInfo &nodeMetaInfo, nodeMetaInfoList) {
            if (nodeMetaInfo.hasLocalProperty(propertyName)) {
                nodeMetaInfo.property(propertyName).setDefaultValue(nodeMetaInfoArg, defaultValue);
                break;
            }
        }

        reader.readNext();
    }
}

void MetaInfoParser::handleAbstractPropertyElement(QXmlStreamReader &reader, NodeMetaInfo &nodeMetaInfo)
{
    if (reader.isStartElement() && reader.name() == "property")
    {
        const QXmlStreamAttributes attributes(reader.attributes());

        const QString propertyName = attributes.value("name").toString();

        if (propertyName.isEmpty()) {
            reader.raiseError("Invalid element 'property' - attribute 'name' is missing or empty");
            return;
        }

        PropertyMetaInfo propertyMetaInfo;
        if (nodeMetaInfo.hasLocalProperty(propertyName)) {
            propertyMetaInfo = nodeMetaInfo.property(propertyName);
        } else {
            propertyMetaInfo.setName(propertyName);
        }
        propertyMetaInfo.setValid(true);

        //propertyMetaInfo.setReadable(stringToBool(attributes.value("isReadable").toString()));
        //propertyMetaInfo.setWritable(stringToBool(attributes.value("isWritable").toString()));
        //propertyMetaInfo.setResettable(stringToBool(attributes.value("isResetable").toString()));
        if (attributes.hasAttribute("isEnumType"))
            propertyMetaInfo.setEnumType(stringToBool(attributes.value("isEnumType").toString()));
        if (attributes.hasAttribute("isFlagType"))
            propertyMetaInfo.setFlagType(stringToBool(attributes.value("isFlagType").toString()));
        if (attributes.hasAttribute("showInPropertyEditor"))
            propertyMetaInfo.setIsVisibleToPropertyEditor(stringToBool(attributes.value("showInPropertyEditor").toString()));

        if (propertyMetaInfo.isEnumType()) {
            propertyMetaInfo.setType(QString("%1::%2").arg(attributes.value("enumeratorScope").toString(),
                                                           attributes.value("enumeratorName").toString()));
            propertyMetaInfo.setEnumerator(m_metaInfo.enumerator(propertyMetaInfo.type()));
        } else {
            const QString type = attributes.value("type").toString();
            if (type.isEmpty()) {
                reader.raiseError("Invalid element 'property' - attribute 'type' is missing or empty");
                return;
            }
            propertyMetaInfo.setType(attributes.value("type").toString());
        }

        if (attributes.hasAttribute("defaultValue")) {
            QVariant defaultValue = Internal::PropertyParser::read(propertyMetaInfo.type(),
                                                                   attributes.value("defaultValue").toString(),
                                                                   m_metaInfo);

            propertyMetaInfo.setDefaultValue(nodeMetaInfo, defaultValue);
        }

        nodeMetaInfo.addProperty(propertyMetaInfo);

        reader.readNext();
    }
}

void MetaInfoParser::errorHandling(QXmlStreamReader &reader, QFile &file)
{
    if (!reader.hasError())
        return;

    qDebug() << QString("Error at %1, %2:%3: %4")
            .arg(file.fileName())
            .arg(reader.lineNumber())
            .arg(reader.columnNumber())
            .arg(reader.errorString());

    file.reset();

    QString fileString = file.readAll();
    QString snippetString;
    int lineCount = 0;
    int position = reader.characterOffset();
    while (position >= 0)
    {
        if (fileString[position] == '\n') {
            if (lineCount > 3)
                break;
            lineCount++;
        }

        snippetString.prepend(fileString[position]);
        position--;
    }

    lineCount = 0;
    position = reader.characterOffset();
    while (position >= 0)
    {
        position++;
        if (fileString[position] == '\n') {
            if (lineCount > 1)
                break;
            lineCount++;
        }

        snippetString.append(fileString[position]);
    }

    qDebug() << snippetString;

}

}
}
<commit_msg>Fix indentation<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "metainfoparser.h"
#include "metainfo.h"

#include "propertymetainfo.h"
#include "model/propertyparser.h"
#include <QXmlStreamReader>
#include <QString>
#include <QFile>
#include <QtDebug>
#include <QIcon>

namespace QmlDesigner {
namespace Internal {

static bool stringToBool(const QString &boolString)
{
    QString lowerString(boolString.toLower());
    if (lowerString == "true" || lowerString == "1")
        return true;

    return false;
}

MetaInfoParser::MetaInfoParser(const MetaInfo &metaInfo)
        : m_metaInfo(metaInfo)
{
}

void MetaInfoParser::parseFile(const QString &path)
{
    QFile file;
    file.setFileName(path);
    if (!file.open(QIODevice::ReadOnly))
        throw new InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__);

    QXmlStreamReader reader;
    reader.setDevice(&file);

    while (!reader.atEnd()) {
        reader.readNext();
        tokenHandler(reader);
    }
    errorHandling(reader, file);
}

void MetaInfoParser::tokenHandler(QXmlStreamReader &reader)
{
    if (reader.isStartElement() && reader.name() == "metainfo")
        handleMetaInfoElement(reader);
}

void MetaInfoParser::handleMetaInfoElement(QXmlStreamReader &reader)
{
    while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "metainfo")) {
        reader.readNext();
        metaInfoHandler(reader);
    }
}

void MetaInfoParser::metaInfoHandler(QXmlStreamReader &reader)
{
    if (reader.isStartElement())
    {
        if (reader.name() == "enumerator")
            handleEnumElement(reader);

        if (reader.name() == "flag")
            handleFlagElement(reader);

        if (reader.name() == "node")
            handleNodeElement(reader);
    }
}

void MetaInfoParser::handleEnumElement(QXmlStreamReader &reader)
{
    QString enumeratorName = reader.attributes().value("name").toString();
    QString enumeratorScope = reader.attributes().value("scope").toString();
    EnumeratorMetaInfo enumeratorMetaInfo;
    if (m_metaInfo.hasEnumerator(enumeratorName)) {
        enumeratorMetaInfo = m_metaInfo.enumerator(enumeratorName);
    } else {
        enumeratorMetaInfo = m_metaInfo.addEnumerator(enumeratorScope, enumeratorName);
    }

    while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "enumerator")) {

        reader.readNext();
        handleEnumElementElement(reader, enumeratorMetaInfo);
    }
}

void MetaInfoParser::handleFlagElement(QXmlStreamReader &reader)
{
    QString enumeratorName = reader.attributes().value("name").toString();
    QString enumeratorScope = reader.attributes().value("scope").toString();
    EnumeratorMetaInfo enumeratorMetaInfo = m_metaInfo.addFlag(enumeratorScope, enumeratorName);

    while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "flag")) {

        reader.readNext();
        handleFlagElementElement(reader, enumeratorMetaInfo);
    }
}

void MetaInfoParser::handleEnumElementElement(QXmlStreamReader &reader, EnumeratorMetaInfo &enumeratorMetaInfo)
{
    if (reader.isStartElement() && reader.name() == "element")
    {
        bool isIntType;
        enumeratorMetaInfo.addElement(reader.attributes().value("name").toString(),
                                     reader.attributes().value("value").toString().toInt(&isIntType));
        Q_ASSERT(isIntType);
    }
}

void MetaInfoParser::handleFlagElementElement(QXmlStreamReader &reader, EnumeratorMetaInfo &enumeratorMetaInfo)
{
    if (reader.isStartElement() && reader.name() == "element")
    {
        bool isIntType;
        enumeratorMetaInfo.addElement(reader.attributes().value("name").toString(),
                                     reader.attributes().value("value").toString().toInt(&isIntType));
        Q_ASSERT(isIntType);
    }
}

void MetaInfoParser::handleNodeElement(QXmlStreamReader &reader)
{
    const QXmlStreamAttributes attributes = reader.attributes();

    const QString className = attributes.value("name").toString();
    if (className.isEmpty()) {
        reader.raiseError("Invalid element 'node' - mandatory attribute 'name' is missing");
        return;
    }

    NodeMetaInfo nodeMetaInfo;
    if (m_metaInfo.hasNodeMetaInfo(className)) {
        nodeMetaInfo = m_metaInfo.nodeMetaInfo(className);
    } else {
        qWarning() << "Metainfo: " << className << " does not exist";
        while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "node"))
            reader.readNext();
        return;
    }

    if (attributes.hasAttribute("isContainer")) {
        const QString isContainer = attributes.value("isContainer").toString();
        nodeMetaInfo.setIsContainer(stringToBool(isContainer));
    }

    if (attributes.hasAttribute("showInItemLibrary")) {
        const QString showInItemLibrary = attributes.value("showInItemLibrary").toString();
        nodeMetaInfo.setIsVisibleToItemLibrary(stringToBool(showInItemLibrary));
    }

    if (attributes.hasAttribute("category")) {
        const QString category = attributes.value("category").toString();
        nodeMetaInfo.setCategory(category);
    }

    if (attributes.hasAttribute("icon")) {
        const QString iconPath = reader.attributes().value("icon").toString();
        nodeMetaInfo.setIcon(QIcon(iconPath));
    }

    while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "node")) {
        reader.readNext();

        handleNodeInheritElement(reader, className);
        handleAbstractPropertyElement(reader, nodeMetaInfo);
        handleAbstractPropertyDefaultValueElement(reader, nodeMetaInfo);
        handleNodeItemLibraryRepresentationElement(reader, className);
    }
}

void MetaInfoParser::handleNodeItemLibraryRepresentationElement(QXmlStreamReader &reader, const QString & className)
{
    if (reader.isStartElement() && reader.name() == "itemlibraryrepresentation")
    {
        QString name = reader.attributes().value("name").toString();
        ItemLibraryInfo ItemLibraryInfo = m_metaInfo.addItemLibraryInfo(m_metaInfo.nodeMetaInfo(className), name);

        QString iconPath = reader.attributes().value("icon").toString();
        if (!iconPath.isEmpty())
            ItemLibraryInfo.setIcon(QIcon(iconPath));

        while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "itemlibraryrepresentation")) {
            reader.readNext();
            handleItemLibraryInfoPropertyElement(reader, ItemLibraryInfo);
        }
    }
}

void MetaInfoParser::handleNodeInheritElement(QXmlStreamReader &reader, const QString & className)
{
    if (reader.isStartElement() && reader.name() == "inherits")
    {
        QString superClassName = reader.attributes().value("name").toString();
        Q_ASSERT(!superClassName.isEmpty());
        m_metaInfo.addSuperClassRelationship(superClassName, className);
        reader.readNext();
    }
}

void MetaInfoParser::handleItemLibraryInfoPropertyElement(QXmlStreamReader &reader, ItemLibraryInfo &ItemLibraryInfo)
{
    if (reader.isStartElement() && reader.name() == "property")
    {
        QXmlStreamAttributes attributes(reader.attributes());
        QString name = attributes.value("name").toString();
        QString type = attributes.value("type").toString();
        QString value = attributes.value("value").toString();
        ItemLibraryInfo.addProperty(name, type, value);

        reader.readNext();
    }
}

void MetaInfoParser::handleAbstractPropertyDefaultValueElement(QXmlStreamReader &reader, NodeMetaInfo &nodeMetaInfoArg)
{
    if (reader.isStartElement() && reader.name() == "propertyDefaultValue")
    {
        const QXmlStreamAttributes attributes(reader.attributes());
        Q_ASSERT(attributes.hasAttribute("name"));
        Q_ASSERT(attributes.hasAttribute("type"));
        Q_ASSERT(attributes.hasAttribute("defaultValue"));
        const QString propertyName = attributes.value("name").toString();
        const QString propertyType = attributes.value("type").toString();
        const QString defaultValueString = attributes.value("defaultValue").toString();
        QVariant defaultValue = Internal::PropertyParser::read(propertyType,
                                                               defaultValueString,
                                                               m_metaInfo);

        QList<NodeMetaInfo> nodeMetaInfoList(nodeMetaInfoArg.superClasses());
        nodeMetaInfoList.prepend(nodeMetaInfoArg);
        foreach(const NodeMetaInfo &nodeMetaInfo, nodeMetaInfoList) {
            if (nodeMetaInfo.hasLocalProperty(propertyName)) {
                nodeMetaInfo.property(propertyName).setDefaultValue(nodeMetaInfoArg, defaultValue);
                break;
            }
        }

        reader.readNext();
    }
}

void MetaInfoParser::handleAbstractPropertyElement(QXmlStreamReader &reader, NodeMetaInfo &nodeMetaInfo)
{
    if (reader.isStartElement() && reader.name() == "property")
    {
        const QXmlStreamAttributes attributes(reader.attributes());

        const QString propertyName = attributes.value("name").toString();

        if (propertyName.isEmpty()) {
            reader.raiseError("Invalid element 'property' - attribute 'name' is missing or empty");
            return;
        }

        PropertyMetaInfo propertyMetaInfo;
        if (nodeMetaInfo.hasLocalProperty(propertyName)) {
            propertyMetaInfo = nodeMetaInfo.property(propertyName);
        } else {
            propertyMetaInfo.setName(propertyName);
        }
        propertyMetaInfo.setValid(true);

        //propertyMetaInfo.setReadable(stringToBool(attributes.value("isReadable").toString()));
        //propertyMetaInfo.setWritable(stringToBool(attributes.value("isWritable").toString()));
        //propertyMetaInfo.setResettable(stringToBool(attributes.value("isResetable").toString()));
        if (attributes.hasAttribute("isEnumType"))
            propertyMetaInfo.setEnumType(stringToBool(attributes.value("isEnumType").toString()));
        if (attributes.hasAttribute("isFlagType"))
            propertyMetaInfo.setFlagType(stringToBool(attributes.value("isFlagType").toString()));
        if (attributes.hasAttribute("showInPropertyEditor"))
            propertyMetaInfo.setIsVisibleToPropertyEditor(stringToBool(attributes.value("showInPropertyEditor").toString()));

        if (propertyMetaInfo.isEnumType()) {
            propertyMetaInfo.setType(QString("%1::%2").arg(attributes.value("enumeratorScope").toString(),
                                                           attributes.value("enumeratorName").toString()));
            propertyMetaInfo.setEnumerator(m_metaInfo.enumerator(propertyMetaInfo.type()));
        } else {
            const QString type = attributes.value("type").toString();
            if (type.isEmpty()) {
                reader.raiseError("Invalid element 'property' - attribute 'type' is missing or empty");
                return;
            }
            propertyMetaInfo.setType(attributes.value("type").toString());
        }

        if (attributes.hasAttribute("defaultValue")) {
            QVariant defaultValue = Internal::PropertyParser::read(propertyMetaInfo.type(),
                                                                   attributes.value("defaultValue").toString(),
                                                                   m_metaInfo);

            propertyMetaInfo.setDefaultValue(nodeMetaInfo, defaultValue);
        }

        nodeMetaInfo.addProperty(propertyMetaInfo);

        reader.readNext();
    }
}

void MetaInfoParser::errorHandling(QXmlStreamReader &reader, QFile &file)
{
    if (!reader.hasError())
        return;

    qDebug() << QString("Error at %1, %2:%3: %4")
            .arg(file.fileName())
            .arg(reader.lineNumber())
            .arg(reader.columnNumber())
            .arg(reader.errorString());

    file.reset();

    QString fileString = file.readAll();
    QString snippetString;
    int lineCount = 0;
    int position = reader.characterOffset();
    while (position >= 0)
    {
        if (fileString[position] == '\n') {
            if (lineCount > 3)
                break;
            lineCount++;
        }

        snippetString.prepend(fileString[position]);
        position--;
    }

    lineCount = 0;
    position = reader.characterOffset();
    while (position >= 0)
    {
        position++;
        if (fileString[position] == '\n') {
            if (lineCount > 1)
                break;
            lineCount++;
        }

        snippetString.append(fileString[position]);
    }

    qDebug() << snippetString;

}

}
}
<|endoftext|>


<commit_before>//
// aegis.hpp
// aegis.cpp
//
// Copyright (c) 2017 Sara W (sara at xandium dot net)
//
// This file is part of aegis.cpp .
//
// 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.

#pragma once

#include "config.hpp"
#include "error.hpp"
#include "structs.hpp"
#include "selfbot.hpp"
#include "basebot.hpp"
#include "ratelimit.hpp"

#include <cstdio>
#include <iostream>
#include <streambuf>
#include <sstream>
#include <functional>
#include <memory>
#include <optional>
#include <set>

#include <spdlog/spdlog.h>
#include <asio.hpp>
#include <websocketpp/common/random.hpp>
#include <websocketpp/common/thread.hpp>
#include <websocketpp/common/connection_hdl.hpp>
#include <asio/steady_timer.hpp>

#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>

#include <json.hpp>

namespace spd = spdlog;
using json = nlohmann::json;
using namespace std::literals;
using namespace std::chrono;

namespace aegis
{

using std::function;
using std::bind;
using std::ref;
namespace placeholders = std::placeholders;
using namespace aegis::rest_limits;

template<typename bottype>
class Aegis
{
public:

    /// Type of a pointer to the ASIO io_service
    typedef asio::io_service * io_service_ptr;

    /// Type of a pointer to the Websocket++ client
    typedef websocketpp::client<websocketpp::config::asio_tls_client> websocket;

    /// Type of a pointer to the Websocket++ TLS connection
    typedef websocketpp::client<websocketpp::config::asio_tls_client>::connection_type::ptr connection_ptr;

    /// Type of a pointer to the Websocket++ message payload
    typedef websocketpp::config::asio_client::message_type::ptr message_ptr;

    /// Type of a shared pointer to an io_service work object
    typedef std::shared_ptr<asio::io_service::work> work_ptr;

    Aegis(std::string_view token)
        : m_token(token)
        , m_state(UNINITIALIZED)
        , m_sequence(0)
        , m_shardid(0)
        , m_shardidmax(0)
        , m_heartbeatack(0)
        , m_ratelimit(std::bind(&Aegis::call, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        m_log = spd::stdout_color_mt("aegis");
        m_ratelimit.add(bucket_type::GUILD);
        m_ratelimit.add(bucket_type::CHANNEL);
    }

    ~Aegis()
    {
        m_work.reset();
        m_websocket.reset();
        if (m_keepalivetimer)
            m_keepalivetimer->cancel();
    }

    Aegis(const Aegis &) = delete;
    Aegis(Aegis &&) = delete;
    Aegis & operator=(const Aegis &) = delete;

    void initialize(io_service_ptr ptr, std::error_code & ec)
    {
        m_log->info("Initializing");
        if (m_state != UNINITIALIZED)
        {
            m_log->critical("aegis::initialize() called in the wrong state");
            using error::make_error_code;
            ec = make_error_code(error::invalid_state);
            return;
        }

        m_log->debug("aegis::initialize()");
        m_websocket.init_asio(ptr, ec);
        m_state = READY;
        ec = std::error_code();
    }

    void initialize(io_service_ptr ptr)
    {
        std::error_code ec;
        initialize(ptr, ec);
        if (ec)
            throw exception(ec);
    }

    //
    void initialize(std::error_code & ec)
    {
        std::unique_ptr<asio::io_service> service(new asio::io_service());
        initialize(service.get(), ec);
        if (!ec) service.release();
    }

    void initialize()
    {
        std::unique_ptr<asio::io_service> service(new asio::io_service());
        initialize(service.get());
        service.release();
    }

    void easy_start()
    {
        std::error_code ec;
        // Pass our io_service object to bot to initialize
        initialize(ec);
        if (ec) { m_log->error("Initialize fail: {}", ec.message()); return; }
        // Start a work object so that asio won't exit prematurely
        start_work();
        // Start the REST outgoing thread
        thd = std::make_unique<std::thread>([&] { rest_thread(); });
        // Create our websocket connection
        websocketcreate(ec);
        if (ec) { m_log->error("Websocket fail: {}", ec.message()); return; }
        // Connect the websocket
        connect(ec);
        if (ec) { m_log->error("Connect fail: {}", ec.message()); return; }
        starttime = std::chrono::steady_clock::now();
        // Run the bot
        run();
    }

    /// Remove the logger instance from spdlog
    void remove_logger() const
    {
        spd::drop("aegis");
    }

    void websocketcreate(std::error_code & ec)
    {
        m_log->info("Creating websocket");
        using error::make_error_code;
        if (m_state != READY)
        {
            m_log->critical("aegis::websocketcreate() called in the wrong state");
            ec = make_error_code(error::invalid_state);
            return;
        }

        std::optional<rest_reply> res;

        if constexpr (std::is_same<bottype, basebot>::value)
            res = get("/gateway/bot");
        else
            res = get("/gateway");

        if (!res.has_value() || res->content.size() == 0)
        {
            ec = make_error_code(error::get_gateway);
            return;
        }

        json ret = json::parse(res->content);
        if (ret.count("message"))
        {
            if (ret["message"] == "401: Unauthorized")
            {
                ec = make_error_code(error::invalid_token);
                return;
            }
        }

        if constexpr (std::is_same<bottype, basebot>::value)
        {
            m_shardidmax = ret["shards"];
            m_log->info("Shard count: {}", m_shardidmax);
        }
        else
            m_shardidmax = 1;

        m_gatewayurl = ret["url"].get<std::string>();

        m_websocket.clear_access_channels(websocketpp::log::alevel::all);

        m_websocket.set_tls_init_handler([](websocketpp::connection_hdl)
        {
            return websocketpp::lib::make_shared<asio::ssl::context>(asio::ssl::context::tlsv1);
        });

        m_websocket.set_message_handler(std::bind(&Aegis::onMessage, this, std::placeholders::_1, std::placeholders::_2));
        m_websocket.set_open_handler(std::bind(&Aegis::onConnect, this, std::placeholders::_1));
        m_websocket.set_close_handler(std::bind(&Aegis::onClose, this, std::placeholders::_1));
        m_websocket.set_fail_handler(std::bind(&Aegis::onClose, this, std::placeholders::_1));
        ec = std::error_code();
    }

    /// Get the internal (or external) io_service object
    asio::io_service & io_service()
    {
        return m_websocket.get_io_service();
    }

    /// Initiate websocket connection
    void connect(std::error_code & ec)
    {
        m_log->info("Websocket connecting");
        m_connection = m_websocket.get_connection("wss://gateway.discord.gg/?encoding=json&v=6", ec);
        if (ec)
        {
            m_log->error("Websocket connection failed: {0}", ec.message());
            return;
        }
        m_websocket.connect(m_connection);
    }

    void start_work()
    {
        m_work = std::make_shared<asio::io_service::work>(std::ref(io_service()));
    }

    void stop_work()
    {
        m_work.reset();
    }

    enum AegisOption
    {

    };

    void set_option(AegisOption opt, bool val);

    /// Performs a GET request on the path
    /**
     * @param path A string of the uri path to get
     *
     * @returns std::optional<std::string>
     */
    std::optional<rest_reply> get(std::string_view path);

    /// Performs a GET request on the path with content as the request body
    /**
    * @param path A string of the uri path to get
    *
    * @param content JSON formatted string to send as the body
    *
    * @returns std::optional<std::string>
    */
    std::optional<rest_reply> get(std::string_view path, std::string_view content);

    /// Performs a GET request on the path with content as the request body
    /**
    * @param path A string of the uri path to get
    *
    * @param content JSON formatted string to send as the body
    *
    * @returns std::optional<std::string>
    */
    std::optional<rest_reply> post(std::string_view path, std::string_view content);

    /// Performs an HTTP request on the path with content as the request body using the method method
    /**
    * @param path A string of the uri path to get
    *
    * @param content JSON formatted string to send as the body
    *
    * @param method The HTTP method of the request
    *
    * @returns std::optional<std::string>
    */
    std::optional<rest_reply> call(std::string_view path, std::string_view content, std::string_view method);

    /// wraps the run method of the internal io_service object
    std::size_t run()
    {
        return io_service().run();
    }

    /// Yield execution
    void yield() const
    {
        while (m_state != SHUTDOWN)
        {
            std::this_thread::yield();
        }
    }

    enum state
    {
        UNINITIALIZED = 0,
        READY = 1,
        CONNECTED = 2,
        ONLINE = 3,
        RECONNECTING = 4,
        SHUTDOWN = 5
    };

    state get_state() const
    {
        return m_state;
    }

private:

    std::unique_ptr<std::thread> thd;
    std::shared_ptr<spd::logger> m_log;

    // Gateway URL for the Discord Websocket
    std::string m_gatewayurl;

    // Websocket++ object
    websocket m_websocket;

    // Websocket++ connection
    connection_ptr m_connection;

    // Bot's token
    std::string m_token;

    //
    std::shared_ptr<asio::steady_timer> m_keepalivetimer;

    // Work object for ASIO
    work_ptr m_work;

    state m_state;
    uint64_t m_sequence;
    uint32_t m_shardid, m_shardidmax;

    int64_t m_heartbeatack;
    int64_t m_lastheartbeat;

    //std::vector<std::unique_ptr<client>> m_clients;

    ratelimit m_ratelimit;
    void onMessage(const websocketpp::connection_hdl hdl, const message_ptr msg);
    void onConnect(const websocketpp::connection_hdl hdl);
    void onClose(const websocketpp::connection_hdl hdl);
    void userMessage(json & obj);
    void processReady(json & d);
    void keepAlive(const asio::error_code& error, const int ms);

    void rest_thread();

    std::chrono::steady_clock::time_point starttime;
    std::string uptime()
    {
        std::stringstream ss;
        std::chrono::steady_clock::time_point timenow = std::chrono::steady_clock::now();

        int64_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(timenow - starttime).count();

        uint32_t seconds = (ms / 1000) % 60;
        uint32_t minutes = (((ms / 1000) - seconds) / 60) % 60;
        uint32_t hours = (((((ms / 1000) - seconds) / 60) - minutes) / 60) % 24;
        uint32_t days = (((((((ms / 1000) - seconds) / 60) - minutes) / 60) - hours) / 24);

        if (days > 0)
            ss << days << "d ";
        if (hours > 0)
            ss << hours << "h ";
        if (minutes > 0)
            ss << minutes << "m ";
        if (seconds > 0)
            ss << seconds << "s";
        return ss.str();
    }
};

}

#include "aegis_impl.hpp"

<commit_msg>Travis pls<commit_after>//
// aegis.hpp
// aegis.cpp
//
// Copyright (c) 2017 Sara W (sara at xandium dot net)
//
// This file is part of aegis.cpp .
//
// 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.

#pragma once

#include "config.hpp"
#include "error.hpp"
#include "structs.hpp"
#include "selfbot.hpp"
#include "basebot.hpp"
#include "ratelimit.hpp"

#include <cstdio>
#include <iostream>
#include <streambuf>
#include <sstream>
#include <functional>
#include <memory>
#include <optional>
#include <set>

#include <spdlog/spdlog.h>
#include <asio.hpp>
#include <websocketpp/common/random.hpp>
#include <websocketpp/common/thread.hpp>
#include <websocketpp/common/connection_hdl.hpp>
#include <asio/steady_timer.hpp>

#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>

#include <json.hpp>

namespace spd = spdlog;
using json = nlohmann::json;
using namespace std::literals;
using namespace std::chrono;

namespace aegis
{

using std::function;
using std::bind;
using std::ref;
namespace placeholders = std::placeholders;
using namespace aegis::rest_limits;

template<typename bottype>
class Aegis
{
public:

    /// Type of a pointer to the ASIO io_service
    typedef asio::io_service * io_service_ptr;

    /// Type of a pointer to the Websocket++ client
    typedef websocketpp::client<websocketpp::config::asio_tls_client> websocket;

    /// Type of a pointer to the Websocket++ TLS connection
    typedef websocketpp::client<websocketpp::config::asio_tls_client>::connection_type::ptr connection_ptr;

    /// Type of a pointer to the Websocket++ message payload
    typedef websocketpp::config::asio_client::message_type::ptr message_ptr;

    /// Type of a shared pointer to an io_service work object
    typedef std::shared_ptr<asio::io_service::work> work_ptr;

    Aegis(std::string token)
        : m_token(token)
        , m_state(UNINITIALIZED)
        , m_sequence(0)
        , m_shardid(0)
        , m_shardidmax(0)
        , m_heartbeatack(0)
        , m_ratelimit(std::bind(&Aegis::call, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        m_log = spd::stdout_color_mt("aegis");
        m_ratelimit.add(bucket_type::GUILD);
        m_ratelimit.add(bucket_type::CHANNEL);
    }

    ~Aegis()
    {
        m_work.reset();
        m_websocket.reset();
        if (m_keepalivetimer)
            m_keepalivetimer->cancel();
    }

    Aegis(const Aegis &) = delete;
    Aegis(Aegis &&) = delete;
    Aegis & operator=(const Aegis &) = delete;

    void initialize(io_service_ptr ptr, std::error_code & ec)
    {
        m_log->info("Initializing");
        if (m_state != UNINITIALIZED)
        {
            m_log->critical("aegis::initialize() called in the wrong state");
            using error::make_error_code;
            ec = make_error_code(error::invalid_state);
            return;
        }

        m_log->debug("aegis::initialize()");
        m_websocket.init_asio(ptr, ec);
        m_state = READY;
        ec = std::error_code();
    }

    void initialize(io_service_ptr ptr)
    {
        std::error_code ec;
        initialize(ptr, ec);
        if (ec)
            throw exception(ec);
    }

    //
    void initialize(std::error_code & ec)
    {
        std::unique_ptr<asio::io_service> service(new asio::io_service());
        initialize(service.get(), ec);
        if (!ec) service.release();
    }

    void initialize()
    {
        std::unique_ptr<asio::io_service> service(new asio::io_service());
        initialize(service.get());
        service.release();
    }

    void easy_start()
    {
        std::error_code ec;
        // Pass our io_service object to bot to initialize
        initialize(ec);
        if (ec) { m_log->error("Initialize fail: {}", ec.message()); return; }
        // Start a work object so that asio won't exit prematurely
        start_work();
        // Start the REST outgoing thread
        thd = std::make_unique<std::thread>([&] { rest_thread(); });
        // Create our websocket connection
        websocketcreate(ec);
        if (ec) { m_log->error("Websocket fail: {}", ec.message()); return; }
        // Connect the websocket
        connect(ec);
        if (ec) { m_log->error("Connect fail: {}", ec.message()); return; }
        starttime = std::chrono::steady_clock::now();
        // Run the bot
        run();
    }

    /// Remove the logger instance from spdlog
    void remove_logger() const
    {
        spd::drop("aegis");
    }

    void websocketcreate(std::error_code & ec)
    {
        m_log->info("Creating websocket");
        using error::make_error_code;
        if (m_state != READY)
        {
            m_log->critical("aegis::websocketcreate() called in the wrong state");
            ec = make_error_code(error::invalid_state);
            return;
        }

        std::optional<rest_reply> res;

        if constexpr (std::is_same<bottype, basebot>::value)
            res = get("/gateway/bot");
        else
            res = get("/gateway");

        if (!res.has_value() || res->content.size() == 0)
        {
            ec = make_error_code(error::get_gateway);
            return;
        }

        json ret = json::parse(res->content);
        if (ret.count("message"))
        {
            if (ret["message"] == "401: Unauthorized")
            {
                ec = make_error_code(error::invalid_token);
                return;
            }
        }

        if constexpr (std::is_same<bottype, basebot>::value)
        {
            m_shardidmax = ret["shards"];
            m_log->info("Shard count: {}", m_shardidmax);
        }
        else
            m_shardidmax = 1;

        m_gatewayurl = ret["url"].get<std::string>();

        m_websocket.clear_access_channels(websocketpp::log::alevel::all);

        m_websocket.set_tls_init_handler([](websocketpp::connection_hdl)
        {
            return websocketpp::lib::make_shared<asio::ssl::context>(asio::ssl::context::tlsv1);
        });

        m_websocket.set_message_handler(std::bind(&Aegis::onMessage, this, std::placeholders::_1, std::placeholders::_2));
        m_websocket.set_open_handler(std::bind(&Aegis::onConnect, this, std::placeholders::_1));
        m_websocket.set_close_handler(std::bind(&Aegis::onClose, this, std::placeholders::_1));
        m_websocket.set_fail_handler(std::bind(&Aegis::onClose, this, std::placeholders::_1));
        ec = std::error_code();
    }

    /// Get the internal (or external) io_service object
    asio::io_service & io_service()
    {
        return m_websocket.get_io_service();
    }

    /// Initiate websocket connection
    void connect(std::error_code & ec)
    {
        m_log->info("Websocket connecting");
        m_connection = m_websocket.get_connection("wss://gateway.discord.gg/?encoding=json&v=6", ec);
        if (ec)
        {
            m_log->error("Websocket connection failed: {0}", ec.message());
            return;
        }
        m_websocket.connect(m_connection);
    }

    void start_work()
    {
        m_work = std::make_shared<asio::io_service::work>(std::ref(io_service()));
    }

    void stop_work()
    {
        m_work.reset();
    }

    enum AegisOption
    {

    };

    void set_option(AegisOption opt, bool val);

    /// Performs a GET request on the path
    /**
     * @param path A string of the uri path to get
     *
     * @returns std::optional<std::string>
     */
    std::optional<rest_reply> get(std::string_view path);

    /// Performs a GET request on the path with content as the request body
    /**
    * @param path A string of the uri path to get
    *
    * @param content JSON formatted string to send as the body
    *
    * @returns std::optional<std::string>
    */
    std::optional<rest_reply> get(std::string_view path, std::string_view content);

    /// Performs a GET request on the path with content as the request body
    /**
    * @param path A string of the uri path to get
    *
    * @param content JSON formatted string to send as the body
    *
    * @returns std::optional<std::string>
    */
    std::optional<rest_reply> post(std::string_view path, std::string_view content);

    /// Performs an HTTP request on the path with content as the request body using the method method
    /**
    * @param path A string of the uri path to get
    *
    * @param content JSON formatted string to send as the body
    *
    * @param method The HTTP method of the request
    *
    * @returns std::optional<std::string>
    */
    std::optional<rest_reply> call(std::string_view path, std::string_view content, std::string_view method);

    /// wraps the run method of the internal io_service object
    std::size_t run()
    {
        return io_service().run();
    }

    /// Yield execution
    void yield() const
    {
        while (m_state != SHUTDOWN)
        {
            std::this_thread::yield();
        }
    }

    enum state
    {
        UNINITIALIZED = 0,
        READY = 1,
        CONNECTED = 2,
        ONLINE = 3,
        RECONNECTING = 4,
        SHUTDOWN = 5
    };

    state get_state() const
    {
        return m_state;
    }

private:

    std::unique_ptr<std::thread> thd;
    std::shared_ptr<spd::logger> m_log;

    // Gateway URL for the Discord Websocket
    std::string m_gatewayurl;

    // Websocket++ object
    websocket m_websocket;

    // Websocket++ connection
    connection_ptr m_connection;

    // Bot's token
    std::string m_token;

    //
    std::shared_ptr<asio::steady_timer> m_keepalivetimer;

    // Work object for ASIO
    work_ptr m_work;

    state m_state;
    uint64_t m_sequence;
    uint32_t m_shardid, m_shardidmax;

    int64_t m_heartbeatack;
    int64_t m_lastheartbeat;

    //std::vector<std::unique_ptr<client>> m_clients;

    ratelimit m_ratelimit;
    void onMessage(const websocketpp::connection_hdl hdl, const message_ptr msg);
    void onConnect(const websocketpp::connection_hdl hdl);
    void onClose(const websocketpp::connection_hdl hdl);
    void userMessage(json & obj);
    void processReady(json & d);
    void keepAlive(const asio::error_code& error, const int ms);

    void rest_thread();

    std::chrono::steady_clock::time_point starttime;
    std::string uptime()
    {
        std::stringstream ss;
        std::chrono::steady_clock::time_point timenow = std::chrono::steady_clock::now();

        int64_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(timenow - starttime).count();

        uint32_t seconds = (ms / 1000) % 60;
        uint32_t minutes = (((ms / 1000) - seconds) / 60) % 60;
        uint32_t hours = (((((ms / 1000) - seconds) / 60) - minutes) / 60) % 24;
        uint32_t days = (((((((ms / 1000) - seconds) / 60) - minutes) / 60) - hours) / 24);

        if (days > 0)
            ss << days << "d ";
        if (hours > 0)
            ss << hours << "h ";
        if (minutes > 0)
            ss << minutes << "m ";
        if (seconds > 0)
            ss << seconds << "s";
        return ss.str();
    }
};

}

#include "aegis_impl.hpp"

<|endoftext|>


<commit_before>/*******************************************************************************
 * include/arrays/span.hpp
 *
 * Copyright (C) 2018 Marvin Löbel <loebel.marvin@gmail.com>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#pragma once

#include <cstring>
#include <iostream>

#include "util/common.hpp"
#include "util/debug_assert.hpp"

template <typename T>
class span {

public:
  inline span(T* ptr, size_t size) : ptr_(ptr), size_(size) { }

  inline size_t size() const {
    return size_;
  }

  inline T& operator[](size_t i) const {
    DCHECK(i < size());
    return ptr_[i];
  }

  inline T* data() const {
    return ptr_;
  }

  inline span slice(size_t start, size_t end) const {
    DCHECK(start <= m_size);
    DCHECK(end <= m_size);
    DCHECK(start <= end);
    return span{ptr_ + start, end - start};
  }

private:
  T* ptr_;
  size_t size_;
};

/******************************************************************************/
<commit_msg>fix rebase fallout<commit_after>/*******************************************************************************
 * include/arrays/span.hpp
 *
 * Copyright (C) 2018 Marvin Löbel <loebel.marvin@gmail.com>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#pragma once

#include <cstring>
#include <iostream>

#include "util/common.hpp"
#include "util/debug_assert.hpp"

template <typename T>
class span {

public:
  inline span(T* ptr, size_t size) : ptr_(ptr), size_(size) { }

  inline size_t size() const {
    return size_;
  }

  inline T& operator[](size_t i) const {
    DCHECK(i < size());
    return ptr_[i];
  }

  inline T* data() const {
    return ptr_;
  }

  inline span slice(size_t start, size_t end) const {
    DCHECK(start <= size_);
    DCHECK(end <= size_);
    DCHECK(start <= end);
    return span{ptr_ + start, end - start};
  }

private:
  T* ptr_;
  size_t size_;
};

/******************************************************************************/
<|endoftext|>