<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSQLiteQuery.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkSQLiteQuery.h"

#include "vtkObjectFactory.h"
#include "vtkSQLiteDatabase.h"
#include "vtkStringArray.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"

#include <vtksqlite/vtk_sqlite3.h>

#include <assert.h>

#include <vtksys/ios/sstream>
#include <vtksys/stl/vector>

#define BEGIN_TRANSACTION "BEGIN TRANSACTION"
#define COMMIT_TRANSACTION "COMMIT"
#define ROLLBACK_TRANSACTION "ROLLBACK"

vtkCxxRevisionMacro(vtkSQLiteQuery, "1.9");
vtkStandardNewMacro(vtkSQLiteQuery);

// ----------------------------------------------------------------------
class vtkSQLiteQuery::implementation
{
public:
  vtkstd::vector<const unsigned char*> BlobData;
  vtkstd::vector<unsigned long> BlobSize;
};

// ----------------------------------------------------------------------
vtkSQLiteQuery::vtkSQLiteQuery() :
  Implementation(new implementation())
{
  this->Statement = NULL;
  this->InitialFetch = true;
  this->LastErrorText = NULL;
  this->TransactionInProgress = false;
}

// ----------------------------------------------------------------------
vtkSQLiteQuery::~vtkSQLiteQuery()
{
  delete this->Implementation;

  this->SetLastErrorText(NULL);
  if (this->TransactionInProgress)
    {
    this->RollbackTransaction();
    }

  if (this->Statement != NULL)
    {
    if (this->Database != NULL)
      {
      vtk_sqlite3_finalize(this->Statement);
      this->Statement = NULL;
      }
    }
}

// ----------------------------------------------------------------------
void vtkSQLiteQuery::PrintSelf(ostream  &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "Statement: ";
  if (this->Statement)
    {
    os << this->Statement << "\n";
    }
  else
    {
    os << "(null)" << "\n";
    }
  os << indent << "InitialFetch: " << InitialFetch;
  os << indent << "InitialFetchResult: " << InitialFetchResult;
  os << indent << "TransactionInProgress: " << TransactionInProgress;
  os << indent << "LastErrorText: "
    << (this->LastErrorText ? this->LastErrorText : "(null)") << endl;
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::Execute()
{

  if (this->Query == NULL)
    {
    vtkErrorMacro(<<"Cannot execute before a query has been set.");
    return false;
    }

  if (this->Statement != NULL)
    {
    int finalizeStatus = vtk_sqlite3_finalize(this->Statement);
    if (finalizeStatus != VTK_SQLITE_OK)
      {
      vtkWarningMacro(<<"Execute(): Finalize returned unexpected code "
                      << finalizeStatus);
      }
    this->Statement = NULL;
    }

  vtkSQLiteDatabase *dbContainer =
    vtkSQLiteDatabase::SafeDownCast(this->Database);
  assert(dbContainer != NULL);

  vtk_sqlite3 *db = dbContainer->SQLiteInstance;
  const char *unused_statement;

  int prepareStatus = vtk_sqlite3_prepare_v2(db,
                                             this->Query,
                                             static_cast<int>(strlen(this->Query)),
                                             &this->Statement,
                                             &unused_statement);

  if (prepareStatus != VTK_SQLITE_OK)
    {
    this->SetLastErrorText(vtk_sqlite3_errmsg(db));
    vtkDebugMacro(<<"Execute(): vtk_sqlite3_prepare_v2() failed with error message "
                  << this->GetLastErrorText());
    this->Active = false;
    return false;
    }

  for(vtkstd::vector<unsigned char*>::size_type i = 0; i != this->Implementation->BlobData.size(); ++i)
    {
    vtk_sqlite3_bind_blob(
      this->Statement,
      i+1,
      this->Implementation->BlobData[i],
      this->Implementation->BlobSize[i],
      VTK_SQLITE_STATIC);
    }

  vtkDebugMacro(<<"Execute(): Query ready to execute.");

  this->InitialFetch = true;
  int result = vtk_sqlite3_step(this->Statement);
  this->InitialFetchResult = result;

  this->Implementation->BlobData.clear();
  this->Implementation->BlobSize.clear();

  if (result == VTK_SQLITE_DONE)
    {
    this->SetLastErrorText(NULL);
    this->Active = true;
    return true;
    }
  else if (result != VTK_SQLITE_ROW)
    {
    this->SetLastErrorText(vtk_sqlite3_errmsg(db));
    vtkDebugMacro(<< "Execute(): vtk_sqlite3_step() returned error message "
                  << this->GetLastErrorText());
    this->Active = false;
    return false;
    }

  this->SetLastErrorText(NULL);
  this->Active = true;
  return true;
}

// ----------------------------------------------------------------------
int vtkSQLiteQuery::GetNumberOfFields()
{
  if (! this->Active)
    {
    vtkErrorMacro(<<"GetNumberOfFields(): Query is not active!");
    return 0;
    }
  else
    {
    return vtk_sqlite3_column_count(this->Statement);
    }
}

// ----------------------------------------------------------------------
const char * vtkSQLiteQuery::GetFieldName(int column)
{
  if (! this->Active)
    {
    vtkErrorMacro(<<"GetFieldName(): Query is not active!");
    return NULL;
    }
  else if (column < 0 || column >= this->GetNumberOfFields())
    {
    vtkErrorMacro(<<"GetFieldName(): Illegal field index "
                  << column);
    return NULL;
    }
  else
    {
    return vtk_sqlite3_column_name(this->Statement, column);
    }
}

// ----------------------------------------------------------------------
int vtkSQLiteQuery::GetFieldType(int column)
{
  if (! this->Active)
    {
    vtkErrorMacro(<<"GetFieldType(): Query is not active!");
    return -1;
    }
  else if (column < 0 || column >= this->GetNumberOfFields())
    {
    vtkErrorMacro(<<"GetFieldType(): Illegal field index "
                  << column);
    return -1;
    }
  else
    {
    switch (vtk_sqlite3_column_type(this->Statement, column))
      {
      case VTK_SQLITE_INTEGER:
        return VTK_INT;
      case VTK_SQLITE_FLOAT:
        return VTK_FLOAT;
      case VTK_SQLITE_TEXT:
        return VTK_STRING;
      case VTK_SQLITE_BLOB:
        return VTK_STRING; // until we have a BLOB type of our own
      case VTK_SQLITE_NULL:
        return VTK_VOID; // ??? what makes sense here?
      default:
      {
      vtkErrorMacro(<<"GetFieldType(): Unknown data type "
                    << vtk_sqlite3_column_type(this->Statement, column)
                    <<" from SQLite.");
      return VTK_VOID;
      }
      }
    }
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::NextRow()
{
  if (! this->IsActive())
    {
    vtkErrorMacro(<<"NextRow(): Query is not active!");
    return false;
    }

  if (this->InitialFetch)
    {
    vtkDebugMacro(<<"NextRow(): Initial fetch being handled.");
    this->InitialFetch = false;
    if (this->InitialFetchResult == VTK_SQLITE_DONE)
      {
      return false;
      }
    else
      {
      return true;
      }
    }
  else
    {
    int result = vtk_sqlite3_step(this->Statement);
    if (result == VTK_SQLITE_DONE)
      {
      return false;
      }
    else if (result == VTK_SQLITE_ROW)
      {
      return true;
      }
    else
      {
      vtkSQLiteDatabase *dbContainer = vtkSQLiteDatabase::SafeDownCast( this->Database );
      assert(dbContainer != NULL);
      vtk_sqlite3 *db = dbContainer->SQLiteInstance;
      this->SetLastErrorText(vtk_sqlite3_errmsg(db));
      vtkErrorMacro(<<"NextRow(): Database returned error code "
                    << result << " with the following message: "
                    << this->GetLastErrorText());
      this->Active = false;
      return false;
      }
    }
}

// ----------------------------------------------------------------------
vtkVariant vtkSQLiteQuery::DataValue(vtkIdType column)
{
  if (this->IsActive() == false)
    {
    vtkWarningMacro(<<"DataValue() called on inactive query");
    return vtkVariant();
    }
  else if (column < 0 || column >= this->GetNumberOfFields())
    {
    vtkWarningMacro(<<"DataValue() called with out-of-range column index "
                    << column);
    return vtkVariant();
    }
  else
    {
    switch (vtk_sqlite3_column_type(this->Statement, column))
      {
      case VTK_SQLITE_INTEGER:
        return vtkVariant(vtk_sqlite3_column_int(this->Statement, column));

      case VTK_SQLITE_FLOAT:
        return vtkVariant(vtk_sqlite3_column_double(this->Statement, column));

      case VTK_SQLITE_TEXT:
      {
      vtksys_ios::ostringstream str;
      str << vtk_sqlite3_column_text(this->Statement, column);
      return vtkVariant(vtkStdString(str.str()));
      }

      case VTK_SQLITE_BLOB:
      {
      // XXX BLOB support has not been properly exercised yet.
      const char *blobData = reinterpret_cast<const char *>(vtk_sqlite3_column_text(this->Statement, column));

      return vtkVariant(vtkStdString(blobData));
      }

      case VTK_SQLITE_NULL:
      default:
        return vtkVariant();
      }
    }
}

// ----------------------------------------------------------------------
const char * vtkSQLiteQuery::GetLastErrorText()
{
  return this->LastErrorText;
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::HasError()
{
  return (this->GetLastErrorText() != NULL);
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::BeginTransaction()
{
  if (this->TransactionInProgress)
    {
    vtkErrorMacro(<<"Cannot start a transaction.  One is already in progress.");
    return false;
    }

  vtkSQLiteDatabase *dbContainer = vtkSQLiteDatabase::SafeDownCast( this->Database );
  assert(dbContainer != NULL);

  vtk_sqlite3 *db = dbContainer->SQLiteInstance;
  char *errorMessage = NULL;
  int result = vtk_sqlite3_exec(db, BEGIN_TRANSACTION, NULL, NULL, &errorMessage);

  if (result == VTK_SQLITE_OK)
    {
    this->TransactionInProgress = true;
    this->SetLastErrorText(NULL);
    vtkDebugMacro(<<"BeginTransaction() succeeded.");
    return true;
    }
  else
    {
    vtkErrorMacro(<<"BeginTransaction(): sqlite3_exec returned unexpected result code " << result);
    if (errorMessage)
      {
      vtkErrorMacro(<< " and error message " << errorMessage);
      }
    this->TransactionInProgress = false;
    return false;
    }
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::CommitTransaction()
{
  if (this->Statement)
    {
    vtk_sqlite3_finalize(this->Statement);
    this->Statement = NULL;
    }

  if (!this->TransactionInProgress)
    {
    vtkErrorMacro(<<"Cannot commit.  There is no transaction in progress.");
    return false;
    }

  vtkSQLiteDatabase *dbContainer = vtkSQLiteDatabase::SafeDownCast( this->Database );
  assert(dbContainer != NULL);
  vtk_sqlite3 *db = dbContainer->SQLiteInstance;
  char *errorMessage = NULL;
  int result = vtk_sqlite3_exec(db, COMMIT_TRANSACTION, NULL, NULL, &errorMessage);

  if (result == VTK_SQLITE_OK)
    {
    this->TransactionInProgress = false;
    this->SetLastErrorText(NULL);
    vtkDebugMacro(<<"CommitTransaction() succeeded.");
    return true;
    }
  else
    {
    vtkErrorMacro(<<"CommitTransaction(): sqlite3_exec returned unexpected result code " << result);
    if (errorMessage)
      {
      this->SetLastErrorText(errorMessage);
      vtkErrorMacro(<< " and error message " << errorMessage);
      }
    assert(1==0);
    return false;
    }

}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::RollbackTransaction()
{
  if (!this->TransactionInProgress)
    {
    vtkErrorMacro(<<"Cannot rollback.  There is no transaction in progress.");
    return false;
    }

  vtkSQLiteDatabase *dbContainer = vtkSQLiteDatabase::SafeDownCast( this->Database );
  assert(dbContainer != NULL);
  vtk_sqlite3 *db = dbContainer->SQLiteInstance;
  char *errorMessage = NULL;
  int result = vtk_sqlite3_exec(db, ROLLBACK_TRANSACTION, NULL, NULL, &errorMessage);

  if (result == VTK_SQLITE_OK)
    {
    this->TransactionInProgress = false;
    this->SetLastErrorText(NULL);
    vtkDebugMacro(<<"RollbackTransaction() succeeded.");
    return true;
    }
  else
    {
    vtkErrorMacro(<<"RollbackTransaction(): sqlite3_exec returned unexpected result code " << result);
    if (errorMessage)
      {
      this->SetLastErrorText(errorMessage);
      vtkErrorMacro(<< " and error message " << errorMessage);
      }
    return false;
    }
}

void vtkSQLiteQuery::AddParameterBinding(const unsigned char* data, unsigned long size)
{
  this->Implementation->BlobData.push_back(data);
  this->Implementation->BlobSize.push_back(size);
}

<commit_msg>COMP: Try to eliminate a dashboard warning.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSQLiteQuery.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkSQLiteQuery.h"

#include "vtkObjectFactory.h"
#include "vtkSQLiteDatabase.h"
#include "vtkStringArray.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"

#include <vtksqlite/vtk_sqlite3.h>

#include <assert.h>

#include <vtksys/ios/sstream>
#include <vtksys/stl/vector>

#define BEGIN_TRANSACTION "BEGIN TRANSACTION"
#define COMMIT_TRANSACTION "COMMIT"
#define ROLLBACK_TRANSACTION "ROLLBACK"

vtkCxxRevisionMacro(vtkSQLiteQuery, "1.10");
vtkStandardNewMacro(vtkSQLiteQuery);

// ----------------------------------------------------------------------
class vtkSQLiteQuery::implementation
{
public:
  vtkstd::vector<const unsigned char*> BlobData;
  vtkstd::vector<unsigned long> BlobSize;
};

// ----------------------------------------------------------------------
vtkSQLiteQuery::vtkSQLiteQuery() :
  Implementation(new implementation())
{
  this->Statement = NULL;
  this->InitialFetch = true;
  this->LastErrorText = NULL;
  this->TransactionInProgress = false;
}

// ----------------------------------------------------------------------
vtkSQLiteQuery::~vtkSQLiteQuery()
{
  delete this->Implementation;

  this->SetLastErrorText(NULL);
  if (this->TransactionInProgress)
    {
    this->RollbackTransaction();
    }

  if (this->Statement != NULL)
    {
    if (this->Database != NULL)
      {
      vtk_sqlite3_finalize(this->Statement);
      this->Statement = NULL;
      }
    }
}

// ----------------------------------------------------------------------
void vtkSQLiteQuery::PrintSelf(ostream  &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "Statement: ";
  if (this->Statement)
    {
    os << this->Statement << "\n";
    }
  else
    {
    os << "(null)" << "\n";
    }
  os << indent << "InitialFetch: " << InitialFetch;
  os << indent << "InitialFetchResult: " << InitialFetchResult;
  os << indent << "TransactionInProgress: " << TransactionInProgress;
  os << indent << "LastErrorText: "
    << (this->LastErrorText ? this->LastErrorText : "(null)") << endl;
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::Execute()
{

  if (this->Query == NULL)
    {
    vtkErrorMacro(<<"Cannot execute before a query has been set.");
    return false;
    }

  if (this->Statement != NULL)
    {
    int finalizeStatus = vtk_sqlite3_finalize(this->Statement);
    if (finalizeStatus != VTK_SQLITE_OK)
      {
      vtkWarningMacro(<<"Execute(): Finalize returned unexpected code "
                      << finalizeStatus);
      }
    this->Statement = NULL;
    }

  vtkSQLiteDatabase *dbContainer =
    vtkSQLiteDatabase::SafeDownCast(this->Database);
  assert(dbContainer != NULL);

  vtk_sqlite3 *db = dbContainer->SQLiteInstance;
  const char *unused_statement;

  int prepareStatus = vtk_sqlite3_prepare_v2(db,
                                             this->Query,
                                             static_cast<int>(strlen(this->Query)),
                                             &this->Statement,
                                             &unused_statement);

  if (prepareStatus != VTK_SQLITE_OK)
    {
    this->SetLastErrorText(vtk_sqlite3_errmsg(db));
    vtkDebugMacro(<<"Execute(): vtk_sqlite3_prepare_v2() failed with error message "
                  << this->GetLastErrorText());
    this->Active = false;
    return false;
    }

  for(vtkstd::vector<unsigned char*>::size_type i = 0; i != this->Implementation->BlobData.size(); ++i)
    {
    vtk_sqlite3_bind_blob(
      this->Statement,
      static_cast<int>(i+1),
      this->Implementation->BlobData[i],
      this->Implementation->BlobSize[i],
      VTK_SQLITE_STATIC);
    }

  vtkDebugMacro(<<"Execute(): Query ready to execute.");

  this->InitialFetch = true;
  int result = vtk_sqlite3_step(this->Statement);
  this->InitialFetchResult = result;

  this->Implementation->BlobData.clear();
  this->Implementation->BlobSize.clear();

  if (result == VTK_SQLITE_DONE)
    {
    this->SetLastErrorText(NULL);
    this->Active = true;
    return true;
    }
  else if (result != VTK_SQLITE_ROW)
    {
    this->SetLastErrorText(vtk_sqlite3_errmsg(db));
    vtkDebugMacro(<< "Execute(): vtk_sqlite3_step() returned error message "
                  << this->GetLastErrorText());
    this->Active = false;
    return false;
    }

  this->SetLastErrorText(NULL);
  this->Active = true;
  return true;
}

// ----------------------------------------------------------------------
int vtkSQLiteQuery::GetNumberOfFields()
{
  if (! this->Active)
    {
    vtkErrorMacro(<<"GetNumberOfFields(): Query is not active!");
    return 0;
    }
  else
    {
    return vtk_sqlite3_column_count(this->Statement);
    }
}

// ----------------------------------------------------------------------
const char * vtkSQLiteQuery::GetFieldName(int column)
{
  if (! this->Active)
    {
    vtkErrorMacro(<<"GetFieldName(): Query is not active!");
    return NULL;
    }
  else if (column < 0 || column >= this->GetNumberOfFields())
    {
    vtkErrorMacro(<<"GetFieldName(): Illegal field index "
                  << column);
    return NULL;
    }
  else
    {
    return vtk_sqlite3_column_name(this->Statement, column);
    }
}

// ----------------------------------------------------------------------
int vtkSQLiteQuery::GetFieldType(int column)
{
  if (! this->Active)
    {
    vtkErrorMacro(<<"GetFieldType(): Query is not active!");
    return -1;
    }
  else if (column < 0 || column >= this->GetNumberOfFields())
    {
    vtkErrorMacro(<<"GetFieldType(): Illegal field index "
                  << column);
    return -1;
    }
  else
    {
    switch (vtk_sqlite3_column_type(this->Statement, column))
      {
      case VTK_SQLITE_INTEGER:
        return VTK_INT;
      case VTK_SQLITE_FLOAT:
        return VTK_FLOAT;
      case VTK_SQLITE_TEXT:
        return VTK_STRING;
      case VTK_SQLITE_BLOB:
        return VTK_STRING; // until we have a BLOB type of our own
      case VTK_SQLITE_NULL:
        return VTK_VOID; // ??? what makes sense here?
      default:
      {
      vtkErrorMacro(<<"GetFieldType(): Unknown data type "
                    << vtk_sqlite3_column_type(this->Statement, column)
                    <<" from SQLite.");
      return VTK_VOID;
      }
      }
    }
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::NextRow()
{
  if (! this->IsActive())
    {
    vtkErrorMacro(<<"NextRow(): Query is not active!");
    return false;
    }

  if (this->InitialFetch)
    {
    vtkDebugMacro(<<"NextRow(): Initial fetch being handled.");
    this->InitialFetch = false;
    if (this->InitialFetchResult == VTK_SQLITE_DONE)
      {
      return false;
      }
    else
      {
      return true;
      }
    }
  else
    {
    int result = vtk_sqlite3_step(this->Statement);
    if (result == VTK_SQLITE_DONE)
      {
      return false;
      }
    else if (result == VTK_SQLITE_ROW)
      {
      return true;
      }
    else
      {
      vtkSQLiteDatabase *dbContainer = vtkSQLiteDatabase::SafeDownCast( this->Database );
      assert(dbContainer != NULL);
      vtk_sqlite3 *db = dbContainer->SQLiteInstance;
      this->SetLastErrorText(vtk_sqlite3_errmsg(db));
      vtkErrorMacro(<<"NextRow(): Database returned error code "
                    << result << " with the following message: "
                    << this->GetLastErrorText());
      this->Active = false;
      return false;
      }
    }
}

// ----------------------------------------------------------------------
vtkVariant vtkSQLiteQuery::DataValue(vtkIdType column)
{
  if (this->IsActive() == false)
    {
    vtkWarningMacro(<<"DataValue() called on inactive query");
    return vtkVariant();
    }
  else if (column < 0 || column >= this->GetNumberOfFields())
    {
    vtkWarningMacro(<<"DataValue() called with out-of-range column index "
                    << column);
    return vtkVariant();
    }
  else
    {
    switch (vtk_sqlite3_column_type(this->Statement, column))
      {
      case VTK_SQLITE_INTEGER:
        return vtkVariant(vtk_sqlite3_column_int(this->Statement, column));

      case VTK_SQLITE_FLOAT:
        return vtkVariant(vtk_sqlite3_column_double(this->Statement, column));

      case VTK_SQLITE_TEXT:
      {
      vtksys_ios::ostringstream str;
      str << vtk_sqlite3_column_text(this->Statement, column);
      return vtkVariant(vtkStdString(str.str()));
      }

      case VTK_SQLITE_BLOB:
      {
      // XXX BLOB support has not been properly exercised yet.
      const char *blobData = reinterpret_cast<const char *>(vtk_sqlite3_column_text(this->Statement, column));

      return vtkVariant(vtkStdString(blobData));
      }

      case VTK_SQLITE_NULL:
      default:
        return vtkVariant();
      }
    }
}

// ----------------------------------------------------------------------
const char * vtkSQLiteQuery::GetLastErrorText()
{
  return this->LastErrorText;
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::HasError()
{
  return (this->GetLastErrorText() != NULL);
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::BeginTransaction()
{
  if (this->TransactionInProgress)
    {
    vtkErrorMacro(<<"Cannot start a transaction.  One is already in progress.");
    return false;
    }

  vtkSQLiteDatabase *dbContainer = vtkSQLiteDatabase::SafeDownCast( this->Database );
  assert(dbContainer != NULL);

  vtk_sqlite3 *db = dbContainer->SQLiteInstance;
  char *errorMessage = NULL;
  int result = vtk_sqlite3_exec(db, BEGIN_TRANSACTION, NULL, NULL, &errorMessage);

  if (result == VTK_SQLITE_OK)
    {
    this->TransactionInProgress = true;
    this->SetLastErrorText(NULL);
    vtkDebugMacro(<<"BeginTransaction() succeeded.");
    return true;
    }
  else
    {
    vtkErrorMacro(<<"BeginTransaction(): sqlite3_exec returned unexpected result code " << result);
    if (errorMessage)
      {
      vtkErrorMacro(<< " and error message " << errorMessage);
      }
    this->TransactionInProgress = false;
    return false;
    }
}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::CommitTransaction()
{
  if (this->Statement)
    {
    vtk_sqlite3_finalize(this->Statement);
    this->Statement = NULL;
    }

  if (!this->TransactionInProgress)
    {
    vtkErrorMacro(<<"Cannot commit.  There is no transaction in progress.");
    return false;
    }

  vtkSQLiteDatabase *dbContainer = vtkSQLiteDatabase::SafeDownCast( this->Database );
  assert(dbContainer != NULL);
  vtk_sqlite3 *db = dbContainer->SQLiteInstance;
  char *errorMessage = NULL;
  int result = vtk_sqlite3_exec(db, COMMIT_TRANSACTION, NULL, NULL, &errorMessage);

  if (result == VTK_SQLITE_OK)
    {
    this->TransactionInProgress = false;
    this->SetLastErrorText(NULL);
    vtkDebugMacro(<<"CommitTransaction() succeeded.");
    return true;
    }
  else
    {
    vtkErrorMacro(<<"CommitTransaction(): sqlite3_exec returned unexpected result code " << result);
    if (errorMessage)
      {
      this->SetLastErrorText(errorMessage);
      vtkErrorMacro(<< " and error message " << errorMessage);
      }
    assert(1==0);
    return false;
    }

}

// ----------------------------------------------------------------------
bool vtkSQLiteQuery::RollbackTransaction()
{
  if (!this->TransactionInProgress)
    {
    vtkErrorMacro(<<"Cannot rollback.  There is no transaction in progress.");
    return false;
    }

  vtkSQLiteDatabase *dbContainer = vtkSQLiteDatabase::SafeDownCast( this->Database );
  assert(dbContainer != NULL);
  vtk_sqlite3 *db = dbContainer->SQLiteInstance;
  char *errorMessage = NULL;
  int result = vtk_sqlite3_exec(db, ROLLBACK_TRANSACTION, NULL, NULL, &errorMessage);

  if (result == VTK_SQLITE_OK)
    {
    this->TransactionInProgress = false;
    this->SetLastErrorText(NULL);
    vtkDebugMacro(<<"RollbackTransaction() succeeded.");
    return true;
    }
  else
    {
    vtkErrorMacro(<<"RollbackTransaction(): sqlite3_exec returned unexpected result code " << result);
    if (errorMessage)
      {
      this->SetLastErrorText(errorMessage);
      vtkErrorMacro(<< " and error message " << errorMessage);
      }
    return false;
    }
}

void vtkSQLiteQuery::AddParameterBinding(const unsigned char* data, unsigned long size)
{
  this->Implementation->BlobData.push_back(data);
  this->Implementation->BlobSize.push_back(size);
}

<|endoftext|>


<commit_before><commit_msg>Use namespaces consistently<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

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

// INCLUDE ---------------------------------------------------------------
#include "scitems.hxx"
#include <vcl/msgbox.hxx>
#include <sfx2/childwin.hxx>
#include <sfx2/dispatch.hxx>

#include "tabvwsh.hxx"
#include "sc.hrc"
#include "globstr.hrc"
#include "global.hxx"
#include "scmod.hxx"
#include "docsh.hxx"
#include "document.hxx"
#include "uiitems.hxx"
#include "pivot.hxx"
#include "namedlg.hxx"
#include "solvrdlg.hxx"
#include "optsolver.hxx"
#include "tabopdlg.hxx"
#include "autoform.hxx"         // Core
#include "autofmt.hxx"          // Dialog
#include "consdlg.hxx"
#include "filtdlg.hxx"
#include "dbnamdlg.hxx"
#include "pvlaydlg.hxx"
#include "areasdlg.hxx"
#include "condfrmt.hxx"
#include "rangeutl.hxx"
#include "crnrdlg.hxx"
#include "formula.hxx"
#include "cell.hxx"             // Input Status Edit-Zellen
#include "acredlin.hxx"
#include "highred.hxx"
#include "simpref.hxx"
#include "funcdesc.hxx"
#include "dpobject.hxx"

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

void ScTabViewShell::SetCurRefDlgId( sal_uInt16 nNew )
{
    //  CurRefDlgId is stored in ScModule to find if a ref dialog is open,
    //  and in the view to identify the view that has opened the dialog
    nCurRefDlgId = nNew;
}

SfxModelessDialog* ScTabViewShell::CreateRefDialog(
                        SfxBindings* pB, SfxChildWindow* pCW, SfxChildWinInfo* pInfo,
                        Window* pParent, sal_uInt16 nSlotId )
{
    //  Dialog nur aufmachen, wenn ueber ScModule::SetRefDialog gerufen, damit
    //  z.B. nach einem Absturz offene Ref-Dialoge nicht wiederkommen (#42341#).

    if ( SC_MOD()->GetCurRefDlgId() != nSlotId )
        return NULL;

    if ( nCurRefDlgId != nSlotId )
    {
        //  the dialog has been opened in a different view
        //  -> lock the dispatcher for this view (modal mode)

        GetViewData()->GetDispatcher().Lock( sal_True );    // lock is reset when closing dialog
        return NULL;
    }

    SfxModelessDialog* pResult = 0;

    if(pCW)
        pCW->SetHideNotDelete(sal_True);

    switch( nSlotId )
    {
        case FID_DEFINE_NAME:
        pResult = new ScNameDlg( pB, pCW, pParent, GetViewData(),
                                 ScAddress( GetViewData()->GetCurX(),
                                            GetViewData()->GetCurY(),
                                            GetViewData()->GetTabNo() ) );
        break;

        case SID_DEFINE_COLROWNAMERANGES:
        {
            pResult = new ScColRowNameRangesDlg( pB, pCW, pParent, GetViewData() );
        }
        break;

        case SID_OPENDLG_CONSOLIDATE:
        {
            SfxItemSet aArgSet( GetPool(),
                                SCITEM_CONSOLIDATEDATA,
                                SCITEM_CONSOLIDATEDATA );

            const ScConsolidateParam* pDlgData =
                            GetViewData()->GetDocument()->GetConsolidateDlgData();

            if ( !pDlgData )
            {
                ScConsolidateParam  aConsParam;
                SCCOL nStartCol, nEndCol;
                SCROW nStartRow, nEndRow;
                SCTAB nStartTab, nEndTab;

                GetViewData()->GetSimpleArea( nStartCol, nStartRow, nStartTab,
                                              nEndCol,   nEndRow,   nEndTab );

                PutInOrder( nStartCol, nEndCol );
                PutInOrder( nStartRow, nEndRow );
                PutInOrder( nStartTab, nEndTab );

                aConsParam.nCol = nStartCol;
                aConsParam.nRow = nStartRow;
                aConsParam.nTab = nStartTab;

                aArgSet.Put( ScConsolidateItem( SCITEM_CONSOLIDATEDATA,
                                                &aConsParam ) );
            }
            else
            {
                aArgSet.Put( ScConsolidateItem( SCITEM_CONSOLIDATEDATA, pDlgData ) );
            }
            pResult = new ScConsolidateDlg( pB, pCW, pParent, aArgSet );
        }
        break;

        case SID_DEFINE_DBNAME:
        {
            //  wenn auf einem bestehenden Bereich aufgerufen, den markieren
            GetDBData( sal_True, SC_DB_OLD );
            const ScMarkData& rMark = GetViewData()->GetMarkData();
            if ( !rMark.IsMarked() && !rMark.IsMultiMarked() )
                MarkDataArea( false );

            pResult = new ScDbNameDlg( pB, pCW, pParent, GetViewData() );
        }
        break;

        case SID_SPECIAL_FILTER:
        {
            ScQueryParam    aQueryParam;
            SfxItemSet      aArgSet( GetPool(),
                                     SCITEM_QUERYDATA,
                                     SCITEM_QUERYDATA );

            ScDBData* pDBData = GetDBData(false, SC_DB_MAKE, SC_DBSEL_ROW_DOWN);
            pDBData->ExtendDataArea(GetViewData()->GetDocument());
            pDBData->GetQueryParam( aQueryParam );

            ScRange aArea;
            pDBData->GetArea(aArea);
            MarkRange(aArea, false);

            ScQueryItem aItem( SCITEM_QUERYDATA, GetViewData(), &aQueryParam );
            ScRange aAdvSource;
            if (pDBData->GetAdvancedQuerySource(aAdvSource))
                aItem.SetAdvancedQuerySource( &aAdvSource );

            aArgSet.Put( aItem );

            // aktuelle Tabelle merken (wg. RefInput im Dialog)
            GetViewData()->SetRefTabNo( GetViewData()->GetTabNo() );

            pResult = new ScSpecialFilterDlg( pB, pCW, pParent, aArgSet );
        }
        break;

        case SID_FILTER:
        {

            ScQueryParam    aQueryParam;
            SfxItemSet      aArgSet( GetPool(),
                                     SCITEM_QUERYDATA,
                                     SCITEM_QUERYDATA );

            ScDBData* pDBData = GetDBData(false, SC_DB_MAKE, SC_DBSEL_ROW_DOWN);
            pDBData->ExtendDataArea(GetViewData()->GetDocument());
            pDBData->GetQueryParam( aQueryParam );

            ScRange aArea;
            pDBData->GetArea(aArea);
            MarkRange(aArea, false);

            aArgSet.Put( ScQueryItem( SCITEM_QUERYDATA,
                                      GetViewData(),
                                      &aQueryParam ) );

            // aktuelle Tabelle merken (wg. RefInput im Dialog)
            GetViewData()->SetRefTabNo( GetViewData()->GetTabNo() );

            pResult = new ScFilterDlg( pB, pCW, pParent, aArgSet );
        }
        break;

        case SID_OPENDLG_TABOP:
        {
            ScViewData*  pViewData  = GetViewData();
            ScRefAddress  aCurPos   ( pViewData->GetCurX(),
                                      pViewData->GetCurY(),
                                      pViewData->GetTabNo(),
                                      false, false, false );

            pResult = new ScTabOpDlg( pB, pCW, pParent, pViewData->GetDocument(), aCurPos );
        }
        break;

        case SID_OPENDLG_SOLVE:
        {
            ScViewData*  pViewData  = GetViewData();
            ScAddress aCurPos(  pViewData->GetCurX(),
                                pViewData->GetCurY(),
                                pViewData->GetTabNo());
            pResult = new ScSolverDlg( pB, pCW, pParent, pViewData->GetDocument(), aCurPos );
        }
        break;

        case SID_OPENDLG_OPTSOLVER:
        {
            ScViewData* pViewData = GetViewData();
            ScAddress aCurPos( pViewData->GetCurX(), pViewData->GetCurY(), pViewData->GetTabNo());
            pResult = new ScOptSolverDlg( pB, pCW, pParent, pViewData->GetDocShell(), aCurPos );
        }
        break;

        case SID_OPENDLG_PIVOTTABLE:
        {
            //  all settings must be in pDialogDPObject

            if( pDialogDPObject )
            {
                // Check for an existing datapilot output.
                ScViewData* pViewData = GetViewData();
                ScDPObject* pObj = GetViewData()->GetDocument()->GetDPAtCursor(
                    pViewData->GetCurX(), pViewData->GetCurY(), pViewData->GetTabNo());

                GetViewData()->SetRefTabNo( GetViewData()->GetTabNo() );
                pResult = new ScDPLayoutDlg( pB, pCW, pParent, *pDialogDPObject, pObj == NULL);
            }
        }
        break;

        case SID_OPENDLG_EDIT_PRINTAREA:
        {
            pResult = new ScPrintAreasDlg( pB, pCW, pParent );
        }
        break;

        case SID_OPENDLG_CONDFRMT:
        {
            ScViewData* pViewData = GetViewData();

            ScDocument* pDoc = pViewData->GetDocument();
            const ScConditionalFormat* pForm = pDoc->GetCondFormat(
                pViewData->GetCurX(), pViewData->GetCurY(), pViewData->GetTabNo() );

            // aktuelle Tabelle merken (wg. RefInput im Dialog)
            pViewData->SetRefTabNo( pViewData->GetTabNo() );

            pResult = new ScConditionalFormatDlg( pB, pCW, pParent, pDoc, pForm );
        }
        break;

        case SID_OPENDLG_FUNCTION:
        {
            //  Dialog schaut selber, was in der Zelle steht

            pResult = new ScFormulaDlg( pB, pCW, pParent, GetViewData(),ScGlobal::GetStarCalcFunctionMgr() );
        }
        break;

        case FID_CHG_SHOW:
        {
            //  Dialog schaut selber, was in der Zelle steht

            pResult = new ScHighlightChgDlg( pB, pCW, pParent, GetViewData() );
        }
        break;

        case WID_SIMPLE_REF:
        {
            //  Dialog schaut selber, was in der Zelle steht

            ScViewData* pViewData = GetViewData();
            pViewData->SetRefTabNo( pViewData->GetTabNo() );
            pResult = new ScSimpleRefDlg( pB, pCW, pParent, pViewData );
        }
        break;

        default:
        OSL_FAIL( "ScTabViewShell::CreateRefDialog: unbekannte ID" );
        break;
    }

    if (pResult)
    {
        //  Die Dialoge gehen immer mit eingeklapptem Zusaetze-Button auf,
        //  darum muss die Groesse ueber das Initialize gerettet werden
        //  (oder den Zusaetze-Status mit speichern !!!)

        Size aSize = pResult->GetSizePixel();
        pResult->Initialize( pInfo );
        pResult->SetSizePixel(aSize);
    }

    return pResult;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Store ScDocument* locally.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

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

// INCLUDE ---------------------------------------------------------------
#include "scitems.hxx"
#include <vcl/msgbox.hxx>
#include <sfx2/childwin.hxx>
#include <sfx2/dispatch.hxx>

#include "tabvwsh.hxx"
#include "sc.hrc"
#include "globstr.hrc"
#include "global.hxx"
#include "scmod.hxx"
#include "docsh.hxx"
#include "document.hxx"
#include "uiitems.hxx"
#include "pivot.hxx"
#include "namedlg.hxx"
#include "solvrdlg.hxx"
#include "optsolver.hxx"
#include "tabopdlg.hxx"
#include "autoform.hxx"         // Core
#include "autofmt.hxx"          // Dialog
#include "consdlg.hxx"
#include "filtdlg.hxx"
#include "dbnamdlg.hxx"
#include "pvlaydlg.hxx"
#include "areasdlg.hxx"
#include "condfrmt.hxx"
#include "rangeutl.hxx"
#include "crnrdlg.hxx"
#include "formula.hxx"
#include "cell.hxx"             // Input Status Edit-Zellen
#include "acredlin.hxx"
#include "highred.hxx"
#include "simpref.hxx"
#include "funcdesc.hxx"
#include "dpobject.hxx"

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

void ScTabViewShell::SetCurRefDlgId( sal_uInt16 nNew )
{
    //  CurRefDlgId is stored in ScModule to find if a ref dialog is open,
    //  and in the view to identify the view that has opened the dialog
    nCurRefDlgId = nNew;
}

SfxModelessDialog* ScTabViewShell::CreateRefDialog(
                        SfxBindings* pB, SfxChildWindow* pCW, SfxChildWinInfo* pInfo,
                        Window* pParent, sal_uInt16 nSlotId )
{
    //  Dialog nur aufmachen, wenn ueber ScModule::SetRefDialog gerufen, damit
    //  z.B. nach einem Absturz offene Ref-Dialoge nicht wiederkommen (#42341#).

    if ( SC_MOD()->GetCurRefDlgId() != nSlotId )
        return NULL;

    if ( nCurRefDlgId != nSlotId )
    {
        //  the dialog has been opened in a different view
        //  -> lock the dispatcher for this view (modal mode)

        GetViewData()->GetDispatcher().Lock( sal_True );    // lock is reset when closing dialog
        return NULL;
    }

    SfxModelessDialog* pResult = 0;

    if(pCW)
        pCW->SetHideNotDelete(sal_True);

    ScDocument* pDoc = GetViewData()->GetDocument();

    switch( nSlotId )
    {
        case FID_DEFINE_NAME:
        pResult = new ScNameDlg( pB, pCW, pParent, GetViewData(),
                                 ScAddress( GetViewData()->GetCurX(),
                                            GetViewData()->GetCurY(),
                                            GetViewData()->GetTabNo() ) );
        break;

        case SID_DEFINE_COLROWNAMERANGES:
        {
            pResult = new ScColRowNameRangesDlg( pB, pCW, pParent, GetViewData() );
        }
        break;

        case SID_OPENDLG_CONSOLIDATE:
        {
            SfxItemSet aArgSet( GetPool(),
                                SCITEM_CONSOLIDATEDATA,
                                SCITEM_CONSOLIDATEDATA );

            const ScConsolidateParam* pDlgData =
                            pDoc->GetConsolidateDlgData();

            if ( !pDlgData )
            {
                ScConsolidateParam  aConsParam;
                SCCOL nStartCol, nEndCol;
                SCROW nStartRow, nEndRow;
                SCTAB nStartTab, nEndTab;

                GetViewData()->GetSimpleArea( nStartCol, nStartRow, nStartTab,
                                              nEndCol,   nEndRow,   nEndTab );

                PutInOrder( nStartCol, nEndCol );
                PutInOrder( nStartRow, nEndRow );
                PutInOrder( nStartTab, nEndTab );

                aConsParam.nCol = nStartCol;
                aConsParam.nRow = nStartRow;
                aConsParam.nTab = nStartTab;

                aArgSet.Put( ScConsolidateItem( SCITEM_CONSOLIDATEDATA,
                                                &aConsParam ) );
            }
            else
            {
                aArgSet.Put( ScConsolidateItem( SCITEM_CONSOLIDATEDATA, pDlgData ) );
            }
            pResult = new ScConsolidateDlg( pB, pCW, pParent, aArgSet );
        }
        break;

        case SID_DEFINE_DBNAME:
        {
            //  wenn auf einem bestehenden Bereich aufgerufen, den markieren
            GetDBData( sal_True, SC_DB_OLD );
            const ScMarkData& rMark = GetViewData()->GetMarkData();
            if ( !rMark.IsMarked() && !rMark.IsMultiMarked() )
                MarkDataArea( false );

            pResult = new ScDbNameDlg( pB, pCW, pParent, GetViewData() );
        }
        break;

        case SID_SPECIAL_FILTER:
        {
            ScQueryParam    aQueryParam;
            SfxItemSet      aArgSet( GetPool(),
                                     SCITEM_QUERYDATA,
                                     SCITEM_QUERYDATA );

            ScDBData* pDBData = GetDBData(false, SC_DB_MAKE, SC_DBSEL_ROW_DOWN);
            pDBData->ExtendDataArea(pDoc);
            pDBData->GetQueryParam( aQueryParam );

            ScRange aArea;
            pDBData->GetArea(aArea);
            MarkRange(aArea, false);

            ScQueryItem aItem( SCITEM_QUERYDATA, GetViewData(), &aQueryParam );
            ScRange aAdvSource;
            if (pDBData->GetAdvancedQuerySource(aAdvSource))
                aItem.SetAdvancedQuerySource( &aAdvSource );

            aArgSet.Put( aItem );

            // aktuelle Tabelle merken (wg. RefInput im Dialog)
            GetViewData()->SetRefTabNo( GetViewData()->GetTabNo() );

            pResult = new ScSpecialFilterDlg( pB, pCW, pParent, aArgSet );
        }
        break;

        case SID_FILTER:
        {

            ScQueryParam    aQueryParam;
            SfxItemSet      aArgSet( GetPool(),
                                     SCITEM_QUERYDATA,
                                     SCITEM_QUERYDATA );

            ScDBData* pDBData = GetDBData(false, SC_DB_MAKE, SC_DBSEL_ROW_DOWN);
            pDBData->ExtendDataArea(pDoc);
            pDBData->GetQueryParam( aQueryParam );

            ScRange aArea;
            pDBData->GetArea(aArea);
            MarkRange(aArea, false);

            aArgSet.Put( ScQueryItem( SCITEM_QUERYDATA,
                                      GetViewData(),
                                      &aQueryParam ) );

            // aktuelle Tabelle merken (wg. RefInput im Dialog)
            GetViewData()->SetRefTabNo( GetViewData()->GetTabNo() );

            pResult = new ScFilterDlg( pB, pCW, pParent, aArgSet );
        }
        break;

        case SID_OPENDLG_TABOP:
        {
            ScViewData*  pViewData  = GetViewData();
            ScRefAddress  aCurPos   ( pViewData->GetCurX(),
                                      pViewData->GetCurY(),
                                      pViewData->GetTabNo(),
                                      false, false, false );

            pResult = new ScTabOpDlg( pB, pCW, pParent, pViewData->GetDocument(), aCurPos );
        }
        break;

        case SID_OPENDLG_SOLVE:
        {
            ScViewData*  pViewData  = GetViewData();
            ScAddress aCurPos(  pViewData->GetCurX(),
                                pViewData->GetCurY(),
                                pViewData->GetTabNo());
            pResult = new ScSolverDlg( pB, pCW, pParent, pViewData->GetDocument(), aCurPos );
        }
        break;

        case SID_OPENDLG_OPTSOLVER:
        {
            ScViewData* pViewData = GetViewData();
            ScAddress aCurPos( pViewData->GetCurX(), pViewData->GetCurY(), pViewData->GetTabNo());
            pResult = new ScOptSolverDlg( pB, pCW, pParent, pViewData->GetDocShell(), aCurPos );
        }
        break;

        case SID_OPENDLG_PIVOTTABLE:
        {
            //  all settings must be in pDialogDPObject

            if( pDialogDPObject )
            {
                // Check for an existing datapilot output.
                ScViewData* pViewData = GetViewData();
                ScDPObject* pObj = pDoc->GetDPAtCursor(
                    pViewData->GetCurX(), pViewData->GetCurY(), pViewData->GetTabNo());

                GetViewData()->SetRefTabNo( GetViewData()->GetTabNo() );
                pResult = new ScDPLayoutDlg( pB, pCW, pParent, *pDialogDPObject, pObj == NULL);
            }
        }
        break;

        case SID_OPENDLG_EDIT_PRINTAREA:
        {
            pResult = new ScPrintAreasDlg( pB, pCW, pParent );
        }
        break;

        case SID_OPENDLG_CONDFRMT:
        {
            ScViewData* pViewData = GetViewData();

            const ScConditionalFormat* pForm = pDoc->GetCondFormat(
                pViewData->GetCurX(), pViewData->GetCurY(), pViewData->GetTabNo() );

            // aktuelle Tabelle merken (wg. RefInput im Dialog)
            pViewData->SetRefTabNo( pViewData->GetTabNo() );

            pResult = new ScConditionalFormatDlg( pB, pCW, pParent, pDoc, pForm );
        }
        break;

        case SID_OPENDLG_FUNCTION:
        {
            //  Dialog schaut selber, was in der Zelle steht

            pResult = new ScFormulaDlg( pB, pCW, pParent, GetViewData(),ScGlobal::GetStarCalcFunctionMgr() );
        }
        break;

        case FID_CHG_SHOW:
        {
            //  Dialog schaut selber, was in der Zelle steht

            pResult = new ScHighlightChgDlg( pB, pCW, pParent, GetViewData() );
        }
        break;

        case WID_SIMPLE_REF:
        {
            //  Dialog schaut selber, was in der Zelle steht

            ScViewData* pViewData = GetViewData();
            pViewData->SetRefTabNo( pViewData->GetTabNo() );
            pResult = new ScSimpleRefDlg( pB, pCW, pParent, pViewData );
        }
        break;

        default:
        OSL_FAIL( "ScTabViewShell::CreateRefDialog: unbekannte ID" );
        break;
    }

    if (pResult)
    {
        //  Die Dialoge gehen immer mit eingeklapptem Zusaetze-Button auf,
        //  darum muss die Groesse ueber das Initialize gerettet werden
        //  (oder den Zusaetze-Status mit speichern !!!)

        Size aSize = pResult->GetSizePixel();
        pResult->Initialize( pInfo );
        pResult->SetSizePixel(aSize);
    }

    return pResult;
}

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


<commit_before>#ifndef CERT_TRANS_LOG_STRICT_CONSISTENT_STORE_INL_H_
#define CERT_TRANS_LOG_STRICT_CONSISTENT_STORE_INL_H_

#include "log/strict_consistent_store.h"

namespace cert_trans {

StrictConsistentStore::StrictConsistentStore(
    const MasterElection* election, ConsistentStore<LoggedEntry>* peer)
    : election_(CHECK_NOTNULL(election)), peer_(CHECK_NOTNULL(peer)) {
}

util::StatusOr<int64_t> StrictConsistentStore::NextAvailableSequenceNumber()
    const {
  if (!election_->IsMaster()) {
    return util::Status(util::error::PERMISSION_DENIED,
                        "Not currently master.");
  }
  return peer_->NextAvailableSequenceNumber();
}

util::Status StrictConsistentStore::SetServingSTH(
    const ct::SignedTreeHead& new_sth) {
  if (!election_->IsMaster()) {
    return util::Status(util::error::PERMISSION_DENIED,
                        "Not currently master.");
  }
  return peer_->SetServingSTH(new_sth);
}

util::Status StrictConsistentStore::UpdateSequenceMapping(
    EntryHandle<ct::SequenceMapping>* entry) {
  if (!election_->IsMaster()) {
    return util::Status(util::error::PERMISSION_DENIED,
                        "Not currently master.");
  }
  return peer_->UpdateSequenceMapping(entry);
}

util::Status StrictConsistentStore::SetClusterConfig(
    const ct::ClusterConfig& config) {
  if (!election_->IsMaster()) {
    return util::Status(util::error::PERMISSION_DENIED,
                        "Not currently master.");
  }
  return peer_->SetClusterConfig(config);
}

util::StatusOr<int64_t> StrictConsistentStore::CleanupOldEntries() {
  if (!election_->IsMaster()) {
    return util::Status(util::error::PERMISSION_DENIED,
                        "Not currently master.");
  }
  return peer_->CleanupOldEntries();
}

}  // namespace cert_trans

#endif  // CERT_TRANS_LOG_STRICT_CONSISTENT_STORE_INL_H_
<commit_msg>Remove header guards and add "using" statements.<commit_after>#include "log/strict_consistent_store.h"

using ct::SignedTreeHead;
using util::Status;
using util::StatusOr;

namespace cert_trans {

StrictConsistentStore::StrictConsistentStore(
    const MasterElection* election, ConsistentStore<LoggedEntry>* peer)
    : election_(CHECK_NOTNULL(election)), peer_(CHECK_NOTNULL(peer)) {
}

StatusOr<int64_t> StrictConsistentStore::NextAvailableSequenceNumber() const {
  if (!election_->IsMaster()) {
    return Status(util::error::PERMISSION_DENIED, "Not currently master.");
  }
  return peer_->NextAvailableSequenceNumber();
}

Status StrictConsistentStore::SetServingSTH(const SignedTreeHead& new_sth) {
  if (!election_->IsMaster()) {
    return Status(util::error::PERMISSION_DENIED, "Not currently master.");
  }
  return peer_->SetServingSTH(new_sth);
}

Status StrictConsistentStore::UpdateSequenceMapping(
    EntryHandle<ct::SequenceMapping>* entry) {
  if (!election_->IsMaster()) {
    return Status(util::error::PERMISSION_DENIED, "Not currently master.");
  }
  return peer_->UpdateSequenceMapping(entry);
}

Status StrictConsistentStore::SetClusterConfig(
    const ct::ClusterConfig& config) {
  if (!election_->IsMaster()) {
    return Status(util::error::PERMISSION_DENIED, "Not currently master.");
  }
  return peer_->SetClusterConfig(config);
}

StatusOr<int64_t> StrictConsistentStore::CleanupOldEntries() {
  if (!election_->IsMaster()) {
    return Status(util::error::PERMISSION_DENIED, "Not currently master.");
  }
  return peer_->CleanupOldEntries();
}

}  // namespace cert_trans
<|endoftext|>


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

#include "media/audio/mac/audio_low_latency_output_mac.h"

#include "base/basictypes.h"
#include "base/logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"

using media::SwizzleCoreAudioLayout5_1;

// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.

AUAudioOutputStream::AUAudioOutputStream(
    AudioManagerMac* manager, AudioParameters params)
    : manager_(manager),
      source_(NULL),
      output_unit_(0),
      volume_(1) {
  // We must have a manager.
  DCHECK(manager_);
  // A frame is one sample across all channels. In interleaved audio the per
  // frame fields identify the set of n |channels|. In uncompressed audio, a
  // packet is always one frame.
  format_.mSampleRate = params.sample_rate;
  format_.mFormatID = kAudioFormatLinearPCM;
  format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
                         kLinearPCMFormatFlagIsSignedInteger;
  format_.mBitsPerChannel = params.bits_per_sample;
  format_.mChannelsPerFrame = params.channels;
  format_.mFramesPerPacket = 1;
  format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels) / 8;
  format_.mBytesPerFrame = format_.mBytesPerPacket;

  // Calculate the number of sample frames per callback.
  number_of_frames_ = params.GetPacketSize() / format_.mBytesPerPacket;
}

AUAudioOutputStream::~AUAudioOutputStream() {
}

bool AUAudioOutputStream::Open() {
  // Open and initialize the DefaultOutputUnit.
  Component comp;
  ComponentDescription desc;

  desc.componentType = kAudioUnitType_Output;
  desc.componentSubType = kAudioUnitSubType_DefaultOutput;
  desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  desc.componentFlags = 0;
  desc.componentFlagsMask = 0;
  comp = FindNextComponent(0, &desc);
  DCHECK(comp);

  OSStatus result = OpenAComponent(comp, &output_unit_);
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  result = AudioUnitInitialize(output_unit_);

  DCHECK_EQ(result, 0);
  if (result)
    return false;

  return Configure();
}

bool AUAudioOutputStream::Configure() {
  // Set the render callback.
  AURenderCallbackStruct input;
  input.inputProc = InputProc;
  input.inputProcRefCon = this;
  OSStatus result = AudioUnitSetProperty(
      output_unit_,
      kAudioUnitProperty_SetRenderCallback,
      kAudioUnitScope_Global,
      0,
      &input,
      sizeof(input));

  DCHECK_EQ(result, 0);
  if (result)
    return false;

  // Set the stream format.
  result = AudioUnitSetProperty(
      output_unit_,
      kAudioUnitProperty_StreamFormat,
      kAudioUnitScope_Input,
      0,
      &format_,
      sizeof(format_));
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  // Set the buffer frame size.
  UInt32 buffer_size = number_of_frames_;
  result = AudioUnitSetProperty(
      output_unit_,
      kAudioDevicePropertyBufferFrameSize,
      kAudioUnitScope_Output,
      0,
      &buffer_size,
      sizeof(buffer_size));
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  return true;
}

void AUAudioOutputStream::Close() {
  if (output_unit_)
    CloseComponent(output_unit_);

  // Inform the audio manager that we have been closed. This can cause our
  // destruction.
  manager_->ReleaseOutputStream(this);
}

void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
  DCHECK(callback);
  source_ = callback;

  AudioOutputUnitStart(output_unit_);
}

void AUAudioOutputStream::Stop() {
  // We request a synchronous stop, so the next call can take some time. In
  // the windows implementation we block here as well.
  source_ = NULL;

  AudioOutputUnitStop(output_unit_);
}

void AUAudioOutputStream::SetVolume(double volume) {
  if (!output_unit_)
    return;
  volume_ = static_cast<float>(volume);

  // TODO(crogers): set volume property
}

void AUAudioOutputStream::GetVolume(double* volume) {
  if (!output_unit_)
    return;
  *volume = volume_;
}

// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
                                     AudioBufferList* io_data) {
  AudioBuffer& buffer = io_data->mBuffers[0];
  uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
  uint32 filled = source_->OnMoreData(
      this, audio_data, buffer.mDataByteSize, AudioBuffersState(0, 0));

  // Handle channel order for 5.1 audio.
  if (format_.mChannelsPerFrame == 6) {
    if (format_.mBitsPerChannel == 8) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<uint8*>(audio_data), filled);
    } else if (format_.mBitsPerChannel == 16) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<int16*>(audio_data), filled);
    } else if (format_.mBitsPerChannel == 32) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<int32*>(audio_data), filled);
    }
  }

  return noErr;
}

// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
                                        AudioUnitRenderActionFlags*,
                                        const AudioTimeStamp*,
                                        UInt32,
                                        UInt32 number_of_frames,
                                        AudioBufferList* io_data) {
  AUAudioOutputStream* audio_output =
      static_cast<AUAudioOutputStream*>(user_data);
  DCHECK(audio_output);
  if (!audio_output)
    return -1;

  return audio_output->Render(number_of_frames, io_data);
}

double AUAudioOutputStream::HardwareSampleRate() {
  // Determine the default output device's sample-rate.
  AudioDeviceID device_id = kAudioDeviceUnknown;
  UInt32 info_size = sizeof(device_id);

  AudioObjectPropertyAddress default_input_device_address = {
      kAudioHardwarePropertyDefaultInputDevice,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
  };
  OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
                                               &default_input_device_address,
                                               0,
                                               0,
                                               &info_size,
                                               &device_id);
  DCHECK_EQ(result, 0);
  if (result)
    return 0.0;  // error

  Float64 nominal_sample_rate;
  info_size = sizeof(nominal_sample_rate);

  AudioObjectPropertyAddress nominal_sample_rate_address = {
      kAudioDevicePropertyNominalSampleRate,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
  };
  result = AudioObjectGetPropertyData(device_id,
                                      &nominal_sample_rate_address,
                                      0,
                                      0,
                                      &info_size,
                                      &nominal_sample_rate);
  DCHECK_EQ(result, 0);
  if (result)
    return 0.0;  // error

  return nominal_sample_rate;
}
<commit_msg>media/audio/mac/audio_low_latency_output_mac.cc is missing an #include.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/audio/mac/audio_low_latency_output_mac.h"

#include <CoreServices/CoreServices.h>

#include "base/basictypes.h"
#include "base/logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"

using media::SwizzleCoreAudioLayout5_1;

// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.

AUAudioOutputStream::AUAudioOutputStream(
    AudioManagerMac* manager, AudioParameters params)
    : manager_(manager),
      source_(NULL),
      output_unit_(0),
      volume_(1) {
  // We must have a manager.
  DCHECK(manager_);
  // A frame is one sample across all channels. In interleaved audio the per
  // frame fields identify the set of n |channels|. In uncompressed audio, a
  // packet is always one frame.
  format_.mSampleRate = params.sample_rate;
  format_.mFormatID = kAudioFormatLinearPCM;
  format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
                         kLinearPCMFormatFlagIsSignedInteger;
  format_.mBitsPerChannel = params.bits_per_sample;
  format_.mChannelsPerFrame = params.channels;
  format_.mFramesPerPacket = 1;
  format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels) / 8;
  format_.mBytesPerFrame = format_.mBytesPerPacket;

  // Calculate the number of sample frames per callback.
  number_of_frames_ = params.GetPacketSize() / format_.mBytesPerPacket;
}

AUAudioOutputStream::~AUAudioOutputStream() {
}

bool AUAudioOutputStream::Open() {
  // Open and initialize the DefaultOutputUnit.
  Component comp;
  ComponentDescription desc;

  desc.componentType = kAudioUnitType_Output;
  desc.componentSubType = kAudioUnitSubType_DefaultOutput;
  desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  desc.componentFlags = 0;
  desc.componentFlagsMask = 0;
  comp = FindNextComponent(0, &desc);
  DCHECK(comp);

  OSStatus result = OpenAComponent(comp, &output_unit_);
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  result = AudioUnitInitialize(output_unit_);

  DCHECK_EQ(result, 0);
  if (result)
    return false;

  return Configure();
}

bool AUAudioOutputStream::Configure() {
  // Set the render callback.
  AURenderCallbackStruct input;
  input.inputProc = InputProc;
  input.inputProcRefCon = this;
  OSStatus result = AudioUnitSetProperty(
      output_unit_,
      kAudioUnitProperty_SetRenderCallback,
      kAudioUnitScope_Global,
      0,
      &input,
      sizeof(input));

  DCHECK_EQ(result, 0);
  if (result)
    return false;

  // Set the stream format.
  result = AudioUnitSetProperty(
      output_unit_,
      kAudioUnitProperty_StreamFormat,
      kAudioUnitScope_Input,
      0,
      &format_,
      sizeof(format_));
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  // Set the buffer frame size.
  UInt32 buffer_size = number_of_frames_;
  result = AudioUnitSetProperty(
      output_unit_,
      kAudioDevicePropertyBufferFrameSize,
      kAudioUnitScope_Output,
      0,
      &buffer_size,
      sizeof(buffer_size));
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  return true;
}

void AUAudioOutputStream::Close() {
  if (output_unit_)
    CloseComponent(output_unit_);

  // Inform the audio manager that we have been closed. This can cause our
  // destruction.
  manager_->ReleaseOutputStream(this);
}

void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
  DCHECK(callback);
  source_ = callback;

  AudioOutputUnitStart(output_unit_);
}

void AUAudioOutputStream::Stop() {
  // We request a synchronous stop, so the next call can take some time. In
  // the windows implementation we block here as well.
  source_ = NULL;

  AudioOutputUnitStop(output_unit_);
}

void AUAudioOutputStream::SetVolume(double volume) {
  if (!output_unit_)
    return;
  volume_ = static_cast<float>(volume);

  // TODO(crogers): set volume property
}

void AUAudioOutputStream::GetVolume(double* volume) {
  if (!output_unit_)
    return;
  *volume = volume_;
}

// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
                                     AudioBufferList* io_data) {
  AudioBuffer& buffer = io_data->mBuffers[0];
  uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
  uint32 filled = source_->OnMoreData(
      this, audio_data, buffer.mDataByteSize, AudioBuffersState(0, 0));

  // Handle channel order for 5.1 audio.
  if (format_.mChannelsPerFrame == 6) {
    if (format_.mBitsPerChannel == 8) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<uint8*>(audio_data), filled);
    } else if (format_.mBitsPerChannel == 16) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<int16*>(audio_data), filled);
    } else if (format_.mBitsPerChannel == 32) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<int32*>(audio_data), filled);
    }
  }

  return noErr;
}

// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
                                        AudioUnitRenderActionFlags*,
                                        const AudioTimeStamp*,
                                        UInt32,
                                        UInt32 number_of_frames,
                                        AudioBufferList* io_data) {
  AUAudioOutputStream* audio_output =
      static_cast<AUAudioOutputStream*>(user_data);
  DCHECK(audio_output);
  if (!audio_output)
    return -1;

  return audio_output->Render(number_of_frames, io_data);
}

double AUAudioOutputStream::HardwareSampleRate() {
  // Determine the default output device's sample-rate.
  AudioDeviceID device_id = kAudioDeviceUnknown;
  UInt32 info_size = sizeof(device_id);

  AudioObjectPropertyAddress default_input_device_address = {
      kAudioHardwarePropertyDefaultInputDevice,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
  };
  OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
                                               &default_input_device_address,
                                               0,
                                               0,
                                               &info_size,
                                               &device_id);
  DCHECK_EQ(result, 0);
  if (result)
    return 0.0;  // error

  Float64 nominal_sample_rate;
  info_size = sizeof(nominal_sample_rate);

  AudioObjectPropertyAddress nominal_sample_rate_address = {
      kAudioDevicePropertyNominalSampleRate,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
  };
  result = AudioObjectGetPropertyData(device_id,
                                      &nominal_sample_rate_address,
                                      0,
                                      0,
                                      &info_size,
                                      &nominal_sample_rate);
  DCHECK_EQ(result, 0);
  if (result)
    return 0.0;  // error

  return nominal_sample_rate;
}
<|endoftext|>


<commit_before>#include "physics/physics_system.h"

#include <PxPhysicsAPI.h>

#include "cooking/PxCooking.h"
#include "core/crc32.h"
#include "editor/editor_server.h"
#include "editor/property_descriptor.h"
#include "engine/engine.h"
#include "physics/physics_scene.h"
#include "physics/physics_system_impl.h"
#include "universe/component_event.h"
#include "universe/entity_moved_event.h"

#pragma comment(lib, "PhysXVisualDebuggerSDKCHECKED.lib")
#pragma comment(lib, "PhysX3CHECKED_x86.lib")
#pragma comment(lib, "PhysX3CommonCHECKED_x86.lib")
#pragma comment(lib, "PhysX3ExtensionsCHECKED.lib")
#pragma comment(lib, "PhysX3CharacterKinematicCHECKED_x86.lib")
#pragma comment(lib, "PhysX3CookingCHECKED_x86.lib")

namespace Lux
{

static const uint32_t box_rigid_actor_type = crc32("box_rigid_actor");
static const uint32_t controller_type = crc32("physical_controller");

extern "C" IPlugin* createPlugin()
{
	return LUX_NEW(PhysicsSystem)();
}

struct CustomErrorCallback : public physx::PxErrorCallback
{
	virtual void reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line);
};

void PhysicsSystem::onCreateUniverse(Universe& universe)
{
	m_impl->m_scene = LUX_NEW(PhysicsScene)();
	m_impl->m_scene->create(*this, universe);

}

void PhysicsSystem::onDestroyUniverse(Universe& universe)
{
	m_impl->m_scene->destroy();
	LUX_DELETE(m_impl->m_scene);
	m_impl->m_scene = NULL;
}

void PhysicsSystem::serialize(ISerializer& serializer)
{
	m_impl->m_scene->serialize(serializer);
}

void PhysicsSystem::deserialize(ISerializer& serializer)
{
	m_impl->m_scene->deserialize(serializer);
}

void PhysicsSystem::sendMessage(const char* message)
{
	if(strcmp("render", message) == 0)
	{
		m_impl->m_scene->render();
	}
}

Component PhysicsSystem::createComponent(uint32_t component_type, const Entity& entity)
{
	if(component_type == controller_type)
	{
		return m_impl->m_scene->createController(entity);
	}
	else if(component_type == box_rigid_actor_type)
	{
		return m_impl->m_scene->createBoxRigidActor(entity);
	}
	return Component::INVALID;
}

void PhysicsSystem::update(float dt)
{
	m_impl->m_scene->update(dt);
}

bool PhysicsSystem::create(Engine& engine)
{
	engine.getEditorServer()->registerProperty("box_rigid_actor", LUX_NEW(PropertyDescriptor<PhysicsScene>)(crc32("dynamic"), &PhysicsScene::getIsDynamic, &PhysicsScene::setIsDynamic));
	engine.getEditorServer()->registerProperty("box_rigid_actor", LUX_NEW(PropertyDescriptor<PhysicsScene>)(crc32("size"), &PhysicsScene::getHalfExtents, &PhysicsScene::setHalfExtents));
	engine.getEditorServer()->registerCreator(box_rigid_actor_type, *this);
	engine.getEditorServer()->registerCreator(controller_type, *this);

	m_impl = LUX_NEW(PhysicsSystemImpl);
	m_impl->m_allocator = LUX_NEW(physx::PxDefaultAllocator)();
	m_impl->m_error_callback = LUX_NEW(CustomErrorCallback)();
	m_impl->m_foundation = PxCreateFoundation(
		PX_PHYSICS_VERSION,
		*m_impl->m_allocator,
		*m_impl->m_error_callback
	);

	m_impl->m_physics = PxCreatePhysics(
		PX_PHYSICS_VERSION,
		*m_impl->m_foundation,
		physx::PxTolerancesScale()
	);

	m_impl->m_controller_manager = PxCreateControllerManager(*m_impl->m_foundation);
	m_impl->m_cooking = PxCreateCooking(PX_PHYSICS_VERSION, *m_impl->m_foundation, physx::PxCookingParams());
	m_impl->connect2VisualDebugger();
	return true;
}

void PhysicsSystem::destroy()
{
	m_impl->m_controller_manager->release();
	m_impl->m_cooking->release();
	m_impl->m_physics->release();
	m_impl->m_foundation->release();
	LUX_DELETE(m_impl->m_allocator);
	LUX_DELETE(m_impl->m_error_callback);
	LUX_DELETE(m_impl);
	m_impl = 0;
}

bool PhysicsSystemImpl::connect2VisualDebugger()
{
	if(m_physics->getPvdConnectionManager() == NULL)
		return false;

	const char* pvd_host_ip = "127.0.0.1";
	int port = 5425;
	unsigned int timeout = 100;
	physx::PxVisualDebuggerConnectionFlags connectionFlags = physx::PxVisualDebuggerExt::getAllConnectionFlags();

	PVD::PvdConnection* theConnection = physx::PxVisualDebuggerExt::createConnection(m_physics->getPvdConnectionManager(), pvd_host_ip, port, timeout, connectionFlags);
	return theConnection != NULL;
}

void CustomErrorCallback::reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line)
{
	printf(message);
}

} // !namespace Lux

<commit_msg>log PhysX errors<commit_after>#include "physics/physics_system.h"

#include <PxPhysicsAPI.h>

#include "cooking/PxCooking.h"
#include "core/crc32.h"
#include "core/log.h"
#include "editor/editor_server.h"
#include "editor/property_descriptor.h"
#include "engine/engine.h"
#include "physics/physics_scene.h"
#include "physics/physics_system_impl.h"
#include "universe/component_event.h"
#include "universe/entity_moved_event.h"

#pragma comment(lib, "PhysXVisualDebuggerSDKCHECKED.lib")
#pragma comment(lib, "PhysX3CHECKED_x86.lib")
#pragma comment(lib, "PhysX3CommonCHECKED_x86.lib")
#pragma comment(lib, "PhysX3ExtensionsCHECKED.lib")
#pragma comment(lib, "PhysX3CharacterKinematicCHECKED_x86.lib")
#pragma comment(lib, "PhysX3CookingCHECKED_x86.lib")

namespace Lux
{

static const uint32_t box_rigid_actor_type = crc32("box_rigid_actor");
static const uint32_t controller_type = crc32("physical_controller");

extern "C" IPlugin* createPlugin()
{
	return LUX_NEW(PhysicsSystem)();
}

struct CustomErrorCallback : public physx::PxErrorCallback
{
	virtual void reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line);
};

void PhysicsSystem::onCreateUniverse(Universe& universe)
{
	m_impl->m_scene = LUX_NEW(PhysicsScene)();
	m_impl->m_scene->create(*this, universe);

}

void PhysicsSystem::onDestroyUniverse(Universe& universe)
{
	m_impl->m_scene->destroy();
	LUX_DELETE(m_impl->m_scene);
	m_impl->m_scene = NULL;
}

void PhysicsSystem::serialize(ISerializer& serializer)
{
	m_impl->m_scene->serialize(serializer);
}

void PhysicsSystem::deserialize(ISerializer& serializer)
{
	m_impl->m_scene->deserialize(serializer);
}

void PhysicsSystem::sendMessage(const char* message)
{
	if(strcmp("render", message) == 0)
	{
		m_impl->m_scene->render();
	}
}

Component PhysicsSystem::createComponent(uint32_t component_type, const Entity& entity)
{
	if(component_type == controller_type)
	{
		return m_impl->m_scene->createController(entity);
	}
	else if(component_type == box_rigid_actor_type)
	{
		return m_impl->m_scene->createBoxRigidActor(entity);
	}
	return Component::INVALID;
}

void PhysicsSystem::update(float dt)
{
	m_impl->m_scene->update(dt);
}

bool PhysicsSystem::create(Engine& engine)
{
	engine.getEditorServer()->registerProperty("box_rigid_actor", LUX_NEW(PropertyDescriptor<PhysicsScene>)(crc32("dynamic"), &PhysicsScene::getIsDynamic, &PhysicsScene::setIsDynamic));
	engine.getEditorServer()->registerProperty("box_rigid_actor", LUX_NEW(PropertyDescriptor<PhysicsScene>)(crc32("size"), &PhysicsScene::getHalfExtents, &PhysicsScene::setHalfExtents));
	engine.getEditorServer()->registerCreator(box_rigid_actor_type, *this);
	engine.getEditorServer()->registerCreator(controller_type, *this);

	m_impl = LUX_NEW(PhysicsSystemImpl);
	m_impl->m_allocator = LUX_NEW(physx::PxDefaultAllocator)();
	m_impl->m_error_callback = LUX_NEW(CustomErrorCallback)();
	m_impl->m_foundation = PxCreateFoundation(
		PX_PHYSICS_VERSION,
		*m_impl->m_allocator,
		*m_impl->m_error_callback
	);

	m_impl->m_physics = PxCreatePhysics(
		PX_PHYSICS_VERSION,
		*m_impl->m_foundation,
		physx::PxTolerancesScale()
	);

	m_impl->m_controller_manager = PxCreateControllerManager(*m_impl->m_foundation);
	m_impl->m_cooking = PxCreateCooking(PX_PHYSICS_VERSION, *m_impl->m_foundation, physx::PxCookingParams());
	m_impl->connect2VisualDebugger();
	return true;
}

void PhysicsSystem::destroy()
{
	m_impl->m_controller_manager->release();
	m_impl->m_cooking->release();
	m_impl->m_physics->release();
	m_impl->m_foundation->release();
	LUX_DELETE(m_impl->m_allocator);
	LUX_DELETE(m_impl->m_error_callback);
	LUX_DELETE(m_impl);
	m_impl = 0;
}

bool PhysicsSystemImpl::connect2VisualDebugger()
{
	if(m_physics->getPvdConnectionManager() == NULL)
		return false;

	const char* pvd_host_ip = "127.0.0.1";
	int port = 5425;
	unsigned int timeout = 100;
	physx::PxVisualDebuggerConnectionFlags connectionFlags = physx::PxVisualDebuggerExt::getAllConnectionFlags();

	PVD::PvdConnection* theConnection = physx::PxVisualDebuggerExt::createConnection(m_physics->getPvdConnectionManager(), pvd_host_ip, port, timeout, connectionFlags);
	return theConnection != NULL;
}

void CustomErrorCallback::reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line)
{
	g_log_error.log("PhysX", message);
}

} // !namespace Lux

<|endoftext|>


<commit_before>/*
 * store-credit.cpp
 *
 *  Created on: Feb 1, 2014
 *      Author: thiago
 */
#include <fstream>
using namespace std;

class Solution {
	int _size;
	int* _items;

public:
	void setSize(int s) { _size = s; }
	void setItems(int* i) { _items = i; }
	int itemCount() { return _size; }
	int* getItems() { return _items; }

};

class TestCase {
	int _credit;
	int _itemQty;
	int* _prices;

	bool rightCombo(int* combo, int size) {
		int sum = 0;
		for (int i = 0; i < size; i++) {
			sum += _prices[combo[i]];
		}
		return sum == this->_credit;
	}

public:
	void setCredit(int c) { _credit = c; }
	void setItemQty(int q) { _itemQty = q; }
	void setPrices(int* p) { _prices = p; }
	Solution findSolution();
};

TestCase* createTestCasesFromFile(char*, int*);
Solution* findSolutions(int, TestCase*);
void outpoutSolutionsToFile(char*, int, Solution*);
int* getFirstCombo(int);
bool nextCombo(int*, int);

int main(int argc, char** argv) {
	if (argc != 3) return 1;

	int testcaseQty;
	TestCase* testCases = createTestCasesFromFile(argv[1], &testcaseQty);
	Solution* solutions = findSolutions(testcaseQty, testCases);
	outpoutSolutionsToFile(argv[2], testcaseQty, solutions);

	delete testCases;
	delete solutions;

	return 0;
}

TestCase* createTestCasesFromFile(char* fname, int* tc_count) {
	ifstream infile(fname);

	infile >> *tc_count;

	// Initialize test cases
	TestCase* testcases = new TestCase[*tc_count];
	for (int tc_num = 0; tc_num < *tc_count; tc_num++) {
		int credit;
		infile >> credit;
		testcases[tc_num].setCredit(credit);

		int itemQty;
		infile >> itemQty;
		testcases[tc_num].setItemQty(itemQty);

		int* prices = new int[itemQty];
		for (int i = 0; i < itemQty; i++) {
			infile >> prices[i];
		}
		testcases[tc_num].setPrices(prices);
	}

	infile.close();

	return testcases;
}

Solution* findSolutions(int tc_count, TestCase* testCases) {
	Solution* solutions = new Solution[tc_count];

	for (int tc_num = 0; tc_num < tc_count; tc_num++) {
		solutions[tc_num] = testCases[tc_num].findSolution();
	}

	return solutions;
}

void outpoutSolutionsToFile(char* fname, int tc_count, Solution* solutions) {
	ofstream outfile(fname);

	for (int tc_num = 0; tc_num < tc_count; tc_num++) {
		outfile << "Case #" << tc_num + 1 << ": ";
		for (int s_item = 0; s_item < solutions[tc_num].itemCount(); s_item++) {
			outfile << solutions[tc_num].getItems()[s_item] + 1 << " ";
		}
		outfile << endl;
	}

	outfile.close();
}

int* getFirstCombo(int size) {
	int* combo = new int[size];
	for (int i = 0; i < size; i++) combo[i] = i;
	return combo;
}

bool nextCombo(int* combo, int size, int max) {
	int elem = size - 1;
	while (elem < size) {
		if (combo[elem] < max) {
			combo[elem]++;
			elem++;
			if (elem < size) combo[elem] = combo[elem - 1];
		} else {
			elem--;
			if (elem < 0) return false;
		}
	}

	return true;
}

Solution TestCase::findSolution() {
	Solution solution;

	for (int i = 1; i <= this->_itemQty; i++) {
		int* combo = getFirstCombo(i);
		bool solved = this->rightCombo(combo, i);
		while (!solved && nextCombo(combo, i, this->_itemQty - 1)) {
			solved = this->rightCombo(combo, i);
		}

		if (solved) {
			solution.setSize(i);
			solution.setItems(combo);
			break;
		}
	}

	return solution;
}
<commit_msg>previous code was finding solutions for just one item. each solution consisted of TWO items.<commit_after>/*
 * store-credit.cpp
 *
 *  Created on: Feb 1, 2014
 *      Author: thiago
 */
#include <fstream>
using namespace std;

class Solution {
	int* _items;

public:
	void setItems(int* i) { _items = i; }
	int* getItems() { return _items; }
};

class TestCase {
	int _credit;
	int _itemQty;
	int* _prices;

	bool rightCombo(int* combo) {
		int sum = 0;
		for (int i = 0; i < 2; i++) {
			sum += _prices[combo[i]];
		}
		return sum == this->_credit;
	}

public:
	void setCredit(int c) { _credit = c; }
	void setItemQty(int q) { _itemQty = q; }
	void setPrices(int* p) { _prices = p; }
	Solution findSolution();
};

TestCase* createTestCasesFromFile(char*, int*);
Solution* findSolutions(int, TestCase*);
void outpoutSolutionsToFile(char*, int, Solution*);
int* getFirstCombo();
void nextCombo(int*, int);

int main(int argc, char** argv) {
	if (argc != 3) return 1;

	int testcaseQty;
	TestCase* testCases = createTestCasesFromFile(argv[1], &testcaseQty);
	Solution* solutions = findSolutions(testcaseQty, testCases);
	outpoutSolutionsToFile(argv[2], testcaseQty, solutions);

	delete testCases;
	delete solutions;

	return 0;
}

TestCase* createTestCasesFromFile(char* fname, int* tc_count) {
	ifstream infile(fname);

	infile >> *tc_count;

	// Initialize test cases
	TestCase* testcases = new TestCase[*tc_count];
	for (int tc_num = 0; tc_num < *tc_count; tc_num++) {
		int credit;
		infile >> credit;
		testcases[tc_num].setCredit(credit);

		int itemQty;
		infile >> itemQty;
		testcases[tc_num].setItemQty(itemQty);

		int* prices = new int[itemQty];
		for (int i = 0; i < itemQty; i++) {
			infile >> prices[i];
		}
		testcases[tc_num].setPrices(prices);
	}

	infile.close();

	return testcases;
}

Solution* findSolutions(int tc_count, TestCase* testCases) {
	Solution* solutions = new Solution[tc_count];

	for (int tc_num = 0; tc_num < tc_count; tc_num++) {
		solutions[tc_num] = testCases[tc_num].findSolution();
	}

	return solutions;
}

void outpoutSolutionsToFile(char* fname, int tc_count, Solution* solutions) {
	ofstream outfile(fname);

	for (int tc_num = 0; tc_num < tc_count; tc_num++) {
		outfile << "Case #" << tc_num + 1 << ": ";
		for (int s_item = 0; s_item < 2; s_item++) {
			outfile << solutions[tc_num].getItems()[s_item] + 1 << " ";
		}
		outfile << endl;
	}

	outfile.close();
}

int* getFirstCombo() {
	int* combo = new int[2];
	for (int i = 0; i < 2; i++) combo[i] = i;
	return combo;
}

void nextCombo(int* combo, int max) {
	int elem = 1;
	while (elem < 2) {
		if (combo[elem] < max) {
			combo[elem]++;
			elem++;
			if (elem < 2) combo[elem] = combo[elem - 1];
		} else {
			elem--;
		}
	}
}

Solution TestCase::findSolution() {
	Solution solution;

	int* combo = getFirstCombo();
	while (!this->rightCombo(combo)) {
		nextCombo(combo, this->_itemQty - 1);
	}
	solution.setItems(combo);

	return solution;
}
<|endoftext|>


<commit_before>// Copyright 2016 Open Source Robotics Foundation, Inc.
//
// 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 <inttypes.h>
#include <iostream>
#include <string>

#include "rclcpp/rclcpp.hpp"

#define USAGE "USAGE:\n  ros2param get <node/variable>\n  ros2param set <node/variable> <value>"

typedef enum
{
  PARAM_NONE,
  PARAM_GET,
  PARAM_SET,
} param_operation_t;

rclcpp::parameter::ParameterVariant
parse_args(int argc, char ** argv, std::string & remote_node, param_operation_t & op)
{
  if (argc < 3) {
    return rclcpp::parameter::ParameterVariant();
  }

  std::string verb = argv[1];
  std::string name = argv[2];
  size_t slash = name.find('/');
  if ((slash == std::string::npos) ||
    (slash == 0) ||
    (slash == (name.size() - 1)))
  {
    return rclcpp::parameter::ParameterVariant();
  }
  remote_node = name.substr(0, slash);
  std::string variable = name.substr(slash + 1, name.size() - slash - 1);

  if ((verb == "get") && (argc == 3)) {
    op = PARAM_GET;
    return rclcpp::parameter::ParameterVariant(variable, 0);
  }
  if ((verb == "set") && (argc == 4)) {
    op = PARAM_SET;
    std::string value = argv[3];
    char * endptr;
    int l = strtol(value.c_str(), &endptr, 10);
    if ((errno == 0) && (*endptr == '\0')) {
      return rclcpp::parameter::ParameterVariant(variable, l);
    }
    errno = 0;
    double d = strtod(value.c_str(), &endptr);
    if ((errno == 0) && (*endptr == '\0')) {
      return rclcpp::parameter::ParameterVariant(variable, d);
    }
    if ((value == "true") || (value == "True")) {
      return rclcpp::parameter::ParameterVariant(variable, true);
    }
    if ((value == "false") || (value == "False")) {
      return rclcpp::parameter::ParameterVariant(variable, false);
    }
    return rclcpp::parameter::ParameterVariant(variable, value);
  }
  return rclcpp::parameter::ParameterVariant();
}

int main(int argc, char ** argv)
{
  rclcpp::init(argc, argv);

  std::string remote_node;
  param_operation_t op = PARAM_NONE;

  auto var = parse_args(argc, argv, remote_node, op);

  if (op == PARAM_NONE) {
    fprintf(stderr, "%s\n", USAGE);
    return 1;
  }

  auto node = rclcpp::Node::make_shared("ros2param");
  auto parameters_client =
    std::make_shared<rclcpp::parameter_client::AsyncParametersClient>(node, remote_node);

  if (op == PARAM_GET) {
    auto get_parameters_result = parameters_client->get_parameters({var.get_name()});
    auto get_result = rclcpp::spin_until_future_complete(
      node, get_parameters_result, std::chrono::milliseconds(1000));
    if ((get_result != rclcpp::executor::FutureReturnCode::SUCCESS) ||
      (get_parameters_result.get().size() != 1) ||
      (get_parameters_result.get()[0].get_type() == rclcpp::parameter::PARAMETER_NOT_SET))
    {
      fprintf(stderr, "Failed to get parameter\n");
      return 1;
    } else {
      auto result = get_parameters_result.get()[0];
      if (result.get_type() == rclcpp::parameter::PARAMETER_BOOL) {
        printf("%s\n", result.get_value<bool>() ? "true" : "false");
      } else if (result.get_type() == rclcpp::parameter::PARAMETER_INTEGER) {
        printf("%" PRId64 "\n", result.get_value<int64_t>());
      } else if (result.get_type() == rclcpp::parameter::PARAMETER_DOUBLE) {
        printf("%f\n", result.get_value<double>());
      } else if (result.get_type() == rclcpp::parameter::PARAMETER_STRING) {
        printf("%s\n", result.get_value<std::string>().c_str());
      } else if (result.get_type() == rclcpp::parameter::PARAMETER_BYTES) {
        fprintf(stderr, "BYTES type not implemented\n");
        return 1;
      }
    }
  } else if (op == PARAM_SET) {
    auto set_parameters_result = parameters_client->set_parameters({var});
    auto set_result = rclcpp::spin_until_future_complete(
      node, set_parameters_result, std::chrono::milliseconds(1000));
    if (set_result != rclcpp::executor::FutureReturnCode::SUCCESS) {
      fprintf(stderr, "Failed to set parameter\n");
      return 1;
    }
  } else {
    fprintf(stderr, "%s\n", USAGE);
    return 1;
  }
  return 0;
}
<commit_msg>Added list verb functionality (#119)<commit_after>// Copyright 2016 Open Source Robotics Foundation, Inc.
//
// 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 <inttypes.h>
#include <iostream>
#include <string>

#include "rclcpp/rclcpp.hpp"

#define USAGE \
  "USAGE:\n  ros2param get <node/variable>\n  ros2param set <node/variable> <value>\n" \
  "  ros2param list <node>"

typedef enum
{
  PARAM_NONE,
  PARAM_GET,
  PARAM_SET,
  PARAM_LIST,
} param_operation_t;

rclcpp::parameter::ParameterVariant
parse_args(int argc, char ** argv, std::string & remote_node, param_operation_t & op)
{
  if (argc < 3) {
    return rclcpp::parameter::ParameterVariant();
  }

  std::string verb = argv[1];
  std::string name = argv[2];

  if (verb == "list") {
    op = PARAM_LIST;
    remote_node = name;
    return rclcpp::parameter::ParameterVariant();
  }

  size_t slash = name.find('/');
  if ((slash == std::string::npos) ||
    (slash == 0) ||
    (slash == (name.size() - 1)))
  {
    return rclcpp::parameter::ParameterVariant();
  }
  remote_node = name.substr(0, slash);
  std::string variable = name.substr(slash + 1, name.size() - slash - 1);

  if ((verb == "get") && (argc == 3)) {
    op = PARAM_GET;
    return rclcpp::parameter::ParameterVariant(variable, 0);
  }
  if ((verb == "set") && (argc == 4)) {
    op = PARAM_SET;
    std::string value = argv[3];
    char * endptr;
    int l = strtol(value.c_str(), &endptr, 10);
    if ((errno == 0) && (*endptr == '\0')) {
      return rclcpp::parameter::ParameterVariant(variable, l);
    }
    errno = 0;
    double d = strtod(value.c_str(), &endptr);
    if ((errno == 0) && (*endptr == '\0')) {
      return rclcpp::parameter::ParameterVariant(variable, d);
    }
    if ((value == "true") || (value == "True")) {
      return rclcpp::parameter::ParameterVariant(variable, true);
    }
    if ((value == "false") || (value == "False")) {
      return rclcpp::parameter::ParameterVariant(variable, false);
    }
    return rclcpp::parameter::ParameterVariant(variable, value);
  }
  return rclcpp::parameter::ParameterVariant();
}

int main(int argc, char ** argv)
{
  rclcpp::init(argc, argv);

  std::string remote_node;
  param_operation_t op = PARAM_NONE;

  auto var = parse_args(argc, argv, remote_node, op);

  if (op == PARAM_NONE) {
    fprintf(stderr, "%s\n", USAGE);
    return 1;
  }

  auto node = rclcpp::Node::make_shared("ros2param");
  auto parameters_client =
    std::make_shared<rclcpp::parameter_client::AsyncParametersClient>(node, remote_node);
  auto parameter_service = std::make_shared<rclcpp::parameter_service::ParameterService>(node);

  if (op == PARAM_GET) {
    auto get_parameters_result = parameters_client->get_parameters({var.get_name()});
    auto get_result = rclcpp::spin_until_future_complete(
      node, get_parameters_result, std::chrono::milliseconds(1000));
    if ((get_result != rclcpp::executor::FutureReturnCode::SUCCESS) ||
      (get_parameters_result.get().size() != 1) ||
      (get_parameters_result.get()[0].get_type() == rclcpp::parameter::PARAMETER_NOT_SET))
    {
      fprintf(stderr, "Failed to get parameter\n");
      return 1;
    }

    auto result = get_parameters_result.get()[0];
    if (result.get_type() == rclcpp::parameter::PARAMETER_BOOL) {
      printf("%s\n", result.get_value<bool>() ? "true" : "false");
    } else if (result.get_type() == rclcpp::parameter::PARAMETER_INTEGER) {
      printf("%" PRId64 "\n", result.get_value<int64_t>());
    } else if (result.get_type() == rclcpp::parameter::PARAMETER_DOUBLE) {
      printf("%f\n", result.get_value<double>());
    } else if (result.get_type() == rclcpp::parameter::PARAMETER_STRING) {
      printf("%s\n", result.get_value<std::string>().c_str());
    } else if (result.get_type() == rclcpp::parameter::PARAMETER_BYTES) {
      fprintf(stderr, "BYTES type not implemented\n");
      return 1;
    }

  } else if (op == PARAM_SET) {
    auto set_parameters_result = parameters_client->set_parameters({var});
    auto set_result = rclcpp::spin_until_future_complete(
      node, set_parameters_result, std::chrono::milliseconds(1000));
    if (set_result != rclcpp::executor::FutureReturnCode::SUCCESS) {
      fprintf(stderr, "Failed to set parameter\n");
      return 1;
    }
  } else if (op == PARAM_LIST) {
    auto list_parameters_result = parameters_client->list_parameters({}, 10);
    auto list_result = rclcpp::spin_until_future_complete(
      node, list_parameters_result, std::chrono::milliseconds(10000));
    if (list_result == rclcpp::executor::FutureReturnCode::SUCCESS) {
      printf("Node %s has %zu parameters:\n", remote_node.c_str(),
        list_parameters_result.get().names.size());
      for (auto name : list_parameters_result.get().names) {
        printf("%s\n", name.c_str());
      }
    } else if (list_result == rclcpp::executor::FutureReturnCode::TIMEOUT) {
      fprintf(stderr, "Timed out trying to list parameters: 10 seconds\n");
      return 1;
    } else {
      fprintf(stderr, "Error listing parameters\n");
      return 1;
    }
  } else {
    fprintf(stderr, "%s\n", USAGE);
    return 1;
  }
  return 0;
}
<|endoftext|>