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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkAutomaticTopologyMeshSourceTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <math.h>
#include <time.h>

#include <iostream>
#include <set>

#include "itkMesh.h"
#include "itkAutomaticTopologyMeshSource.h"

int
itkAutomaticTopologyMeshSourceTest(int, char* [] )
{

  // Declare the type of the Mesh
  typedef itk::Mesh<double>                         MeshType;
  typedef MeshType::PointType                       PointType;
  typedef MeshType::CellType                        CellType;

  typedef itk::AutomaticTopologyMeshSource< MeshType >   MeshSourceType;
  typedef MeshSourceType::IdentifierType                 IdentifierType;
  typedef MeshSourceType::IdentifierArrayType            IdentifierArrayType;

  MeshSourceType::Pointer meshSource;

  meshSource = MeshSourceType::New();

  // Begin using various AddPoint functions to add the vertices of a
  // cube.

  // Point expressed as an itk::Point.

  PointType p;

  p[ 0 ] = 0;
  p[ 1 ] = 0;
  p[ 2 ] = 0;
  meshSource->AddPoint( p );

  // Point expressed as a C array.

  float a[3];
  a[ 0 ] = 1;
  a[ 1 ] = 0;
  a[ 2 ] = 0;
  meshSource->AddPoint( a );

  // Points expressed using their coordinates.
  meshSource->AddPoint( 0, 1, 0 );
  meshSource->AddPoint( 1, 1, 0 );
  meshSource->AddPoint( 0, 0, 1 );
  meshSource->AddPoint( 1, 0, 1 );
  meshSource->AddPoint( 0, 1, 1 );
  meshSource->AddPoint( 1, 1, 1 );

  // Done adding vertices of a cube.

  // Add a cell of each type using an Array of point IDs.  Here we use
  // the fact that the IDs are assigned in order, and the fact that
  // the Add[Cell] methods only use the first N entries of the array.

  IdentifierArrayType idArray( 8 );
  {
  for( IdentifierType i = 0; i < 8; i++ )
    {
    idArray[ i ] = i;
    }
  }

  meshSource->AddVertex( idArray );
  meshSource->AddLine( idArray );
  meshSource->AddTriangle( idArray );
  meshSource->AddQuadrilateral( idArray );
  meshSource->AddTetrahedron( idArray );   // Degenerate; that's OK.
  meshSource->AddHexahedron( idArray );

  // Now add a new cube of points.  It overlaps along one face.

  IdentifierArrayType idArray1( 8 );
  idArray1[ 0 ] = meshSource->AddPoint( 1, 0, 0 );
  idArray1[ 1 ] = meshSource->AddPoint( 2, 0, 0 );
  idArray1[ 2 ] = meshSource->AddPoint( 1, 1, 0 );
  idArray1[ 3 ] = meshSource->AddPoint( 2, 1, 0 );
  idArray1[ 4 ] = meshSource->AddPoint( 1, 0, 1 );
  idArray1[ 5 ] = meshSource->AddPoint( 2, 0, 1 );
  idArray1[ 6 ] = meshSource->AddPoint( 1, 1, 1 );
  idArray1[ 7 ] = meshSource->AddPoint( 2, 1, 1 );

  // Add cells using parameter lists of IDs.

  meshSource->AddVertex( idArray[7] );

  // PROBLEM LINE
  meshSource->AddLine( idArray[6], idArray[7] );

#if 0

  meshSource->AddTriangle( idArray[5], idArray[6], idArray[7] );

  meshSource->AddQuadrilateral( idArray[4], idArray[5],
                                idArray[6], idArray[7] );

  meshSource->AddTetrahedron( idArray[0], idArray[2],
                              idArray[4], idArray[6] );

  meshSource->AddHexahedron( idArray[0], idArray[1],
                             idArray[2], idArray[3],
                             idArray[4], idArray[5],
                             idArray[6], idArray[7] );

  // Add cells using new point identifiers.

  meshSource->AddVertex( meshSource->AddPoint( 3, 1, 1 ) );

#if 0
  // PROBLEM LINES
  meshSource->AddLine(
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );
#endif

  meshSource->AddTriangle(
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddQuadrilateral(
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 2, 0, 0 ),
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 2, 1, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  // Add cells using C arrays of point coordinates.
  MeshSourceType::CoordinateType points[8][3] =
    {
      {3, 0, 0},
      {4, 0, 0},
      {3, 1, 0},
      {4, 1, 0},
      {3, 0, 1},
      {4, 0, 1},
      {3, 1, 1},
      {4, 1, 1}
    };

  meshSource->AddVertex( points[7] );
  meshSource->AddLine( points[6], points[7] );
  meshSource->AddTriangle( points[5], points[6], points[7] );
  meshSource->AddQuadrilateral( points[4], points[5], points[6], points[7] );
  meshSource->AddTetrahedron( points[3], points[5], points[6], points[7] );
  meshSource->AddHexahedron( points[0], points[1], points[2], points[3],
                             points[4], points[5], points[6], points[7] );

#endif // 0

  // Print out the resulting mesh data.
  std::cout << MeshType::Pointer(meshSource->GetOutput()) << std::endl;

#if 0

  // Now do a sanity check.  Create a mesh consisting of a pair of
  // tetrahedra sharing a face and a pair of cubes sharing a face, and
  // then check properties.
  meshSource = MeshSourceType::New();

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 0, 0, 0 ),
    meshSource->AddPoint( 1, 0, 0 ),
    meshSource->AddPoint( 0, 1, 0 ),
    meshSource->AddPoint( 0, 0, 1 )
    );

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 1, 1, 1 ),
    meshSource->AddPoint( 1, 0, 0 ),
    meshSource->AddPoint( 0, 1, 0 ),
    meshSource->AddPoint( 0, 0, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 2, 0, 0 ),
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 2, 1, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 4, 0, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 4, 1, 0 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 4, 0, 1 ),
    meshSource->AddPoint( 3, 1, 1 ),
    meshSource->AddPoint( 4, 1, 1 )
    );

  try
    {
    meshSource->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "Exception thrown during Update() " << std::endl;
    std::cerr << exp << std::endl;
    return EXIT_FAILURE;
    }

  MeshType* mesh = meshSource->GetOutput();

  // Print out the resulting mesh data.
  std::cout << MeshType::Pointer( mesh ) << std::endl;

  // ... In more detail.

  unsigned int i;

  std::cout << mesh->GetNumberOfPoints() << " points:" << std::endl;
  for( i = 0; i < mesh->GetNumberOfPoints(); i++ )
    {
    PointType point;
    if( mesh->GetPoint( i, &point ) )
      {
      std::cout << i << ": " << point << std::endl;
      }
    }

  std::cout << "\n" << mesh->GetNumberOfCells() << " cells:" << std::endl;
  for( i = 0; i < mesh->GetNumberOfCells(); i++ )
    {
    typedef MeshType::CellAutoPointer CellAutoPointer;
    CellAutoPointer cell;
    if( mesh->GetCell( i, cell ) )
      {
      std::cout << i << ": ";
      typedef CellType::PointIdConstIterator PointIdIterator;
      PointIdIterator pointIter = cell->PointIdsBegin();
      PointIdIterator pointsEnd = cell->PointIdsEnd();
      for( ; pointIter != pointsEnd; ++pointIter )
        {
        std::cout << *pointIter << " ";
        }
      std::cout << std::endl;
      }
    }
  std::cout << "\n";

  for( i = 0; i < mesh->GetNumberOfCells(); i++ )
    {
    typedef MeshType::CellAutoPointer CellAutoPointer;
    CellAutoPointer cell;
    if( mesh->GetCell( i, cell ) )
      {
      if( cell->GetType() == CellType::LINE_CELL )
        {
        std::cout << "Cell " << i << ":\n";

        typedef MeshSourceType::IdentifierType IdentifierType;
        typedef std::set<IdentifierType> NeighborSet;
        NeighborSet cellSet;

        mesh->GetCellBoundaryFeatureNeighbors( 0, i, 0, &cellSet );
        std::cout << "Neighbors across vertex 0: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n";

        mesh->GetCellBoundaryFeatureNeighbors( 0, i, 1, &cellSet );
        std::cout << "Neighbors across vertex 1: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n";

        mesh->GetCellNeighbors( i, &cellSet );
        std::cout << "Neighbors having edge as boundary: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n" << std::endl;

        }
      }
    }

  // Check that the right number of points has been added.

  int numPoints = meshSource->GetOutput()->GetNumberOfPoints();
  if( numPoints != 17 )
    {
    std::cerr << "Mesh shows " << numPoints
              << " points, but 17 were added." << std::endl;
    return EXIT_FAILURE;
    }

  // Check that the right number of cells has been added.

  int numCells = meshSource->GetOutput()->GetNumberOfCells();
  if( numCells != 68 )
    {
    std::cerr << "Mesh shows "
              << numCells
              << " cells, but 68 were added." << std::endl;
    return EXIT_FAILURE;
    }

#endif

  return EXIT_SUCCESS;

}

<commit_msg>ENH: better coverage.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkAutomaticTopologyMeshSourceTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <math.h>
#include <time.h>

#include <iostream>
#include <set>

#include "itkMesh.h"
#include "itkAutomaticTopologyMeshSource.h"

int
itkAutomaticTopologyMeshSourceTest(int, char* [] )
{

  // Declare the type of the Mesh
  typedef itk::Mesh<double>                         MeshType;
  typedef MeshType::PointType                       PointType;
  typedef MeshType::CellType                        CellType;

  typedef itk::AutomaticTopologyMeshSource< MeshType >   MeshSourceType;
  typedef MeshSourceType::IdentifierType                 IdentifierType;
  typedef MeshSourceType::IdentifierArrayType            IdentifierArrayType;

  MeshSourceType::Pointer meshSource;

  meshSource = MeshSourceType::New();

  // Begin using various AddPoint functions to add the vertices of a
  // cube.

  // Point expressed as an itk::Point.

  PointType p;

  p[ 0 ] = 0;
  p[ 1 ] = 0;
  p[ 2 ] = 0;
  meshSource->AddPoint( p );

  // Point expressed as a C array.

  float a[3];
  a[ 0 ] = 1;
  a[ 1 ] = 0;
  a[ 2 ] = 0;
  meshSource->AddPoint( a );

  // Points expressed using their coordinates.
  meshSource->AddPoint( 0, 1, 0 );
  meshSource->AddPoint( 1, 1, 0 );
  meshSource->AddPoint( 0, 0, 1 );
  meshSource->AddPoint( 1, 0, 1 );
  meshSource->AddPoint( 0, 1, 1 );
  meshSource->AddPoint( 1, 1, 1 );

  // Done adding vertices of a cube.

  // Add a cell of each type using an Array of point IDs.  Here we use
  // the fact that the IDs are assigned in order, and the fact that
  // the Add[Cell] methods only use the first N entries of the array.

  IdentifierArrayType idArray( 8 );
  {
  for( IdentifierType i = 0; i < 8; i++ )
    {
    idArray[ i ] = i;
    }
  }

  meshSource->AddVertex( idArray );
  meshSource->AddLine( idArray );
  meshSource->AddTriangle( idArray );
  meshSource->AddQuadrilateral( idArray );
  meshSource->AddTetrahedron( idArray );   // Degenerate; that's OK.
  meshSource->AddHexahedron( idArray );

  // Now add a new cube of points.  It overlaps along one face.

  IdentifierArrayType idArray1( 8 );
  idArray1[ 0 ] = meshSource->AddPoint( 1, 0, 0 );
  idArray1[ 1 ] = meshSource->AddPoint( 2, 0, 0 );
  idArray1[ 2 ] = meshSource->AddPoint( 1, 1, 0 );
  idArray1[ 3 ] = meshSource->AddPoint( 2, 1, 0 );
  idArray1[ 4 ] = meshSource->AddPoint( 1, 0, 1 );
  idArray1[ 5 ] = meshSource->AddPoint( 2, 0, 1 );
  idArray1[ 6 ] = meshSource->AddPoint( 1, 1, 1 );
  idArray1[ 7 ] = meshSource->AddPoint( 2, 1, 1 );

  // Add cells using parameter lists of IDs.

  meshSource->AddVertex( idArray[7] );

  // PROBLEM LINE
  meshSource->AddLine( idArray[6], idArray[7] );

  meshSource->AddTriangle( idArray[5], idArray[6], idArray[7] );

  meshSource->AddQuadrilateral( idArray[4], idArray[5],
                                idArray[6], idArray[7] );

  meshSource->AddTetrahedron( idArray[0], idArray[2],
                              idArray[4], idArray[6] );

  meshSource->AddHexahedron( idArray[0], idArray[1],
                             idArray[2], idArray[3],
                             idArray[4], idArray[5],
                             idArray[6], idArray[7] );

  // Add cells using new point identifiers.

  meshSource->AddVertex( meshSource->AddPoint( 3, 1, 1 ) );

  // PROBLEM LINES
  meshSource->AddLine(
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddTriangle(
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddQuadrilateral(
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 2, 0, 0 ),
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 2, 1, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  // Add cells using C arrays of point coordinates.
  MeshSourceType::CoordinateType points[8][3] =
    {
      {3, 0, 0},
      {4, 0, 0},
      {3, 1, 0},
      {4, 1, 0},
      {3, 0, 1},
      {4, 0, 1},
      {3, 1, 1},
      {4, 1, 1}
    };

  meshSource->AddVertex( points[7] );
  meshSource->AddLine( points[6], points[7] );
  meshSource->AddTriangle( points[5], points[6], points[7] );
  meshSource->AddQuadrilateral( points[4], points[5], points[6], points[7] );
  meshSource->AddTetrahedron( points[3], points[5], points[6], points[7] );
  meshSource->AddHexahedron( points[0], points[1], points[2], points[3],
                             points[4], points[5], points[6], points[7] );

  // Print out the resulting mesh data.
  std::cout << MeshType::Pointer(meshSource->GetOutput()) << std::endl;

  // Now do a sanity check.  Create a mesh consisting of a pair of
  // tetrahedra sharing a face and a pair of cubes sharing a face, and
  // then check properties.
  meshSource = MeshSourceType::New();

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 0, 0, 0 ),
    meshSource->AddPoint( 1, 0, 0 ),
    meshSource->AddPoint( 0, 1, 0 ),
    meshSource->AddPoint( 0, 0, 1 )
    );

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 1, 1, 1 ),
    meshSource->AddPoint( 1, 0, 0 ),
    meshSource->AddPoint( 0, 1, 0 ),
    meshSource->AddPoint( 0, 0, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 2, 0, 0 ),
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 2, 1, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 4, 0, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 4, 1, 0 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 4, 0, 1 ),
    meshSource->AddPoint( 3, 1, 1 ),
    meshSource->AddPoint( 4, 1, 1 )
    );

  try
    {
    meshSource->Update();
    }
  catch( itk::ExceptionObject & exp )
    {
    std::cerr << "Exception thrown during Update() " << std::endl;
    std::cerr << exp << std::endl;
    return EXIT_FAILURE;
    }

  MeshType* mesh = meshSource->GetOutput();

  // Print out the resulting mesh data.
  std::cout << MeshType::Pointer( mesh ) << std::endl;

  // ... In more detail.

  unsigned int i;

  std::cout << mesh->GetNumberOfPoints() << " points:" << std::endl;
  for( i = 0; i < mesh->GetNumberOfPoints(); i++ )
    {
    PointType point;
    if( mesh->GetPoint( i, &point ) )
      {
      std::cout << i << ": " << point << std::endl;
      }
    }

  std::cout << "\n" << mesh->GetNumberOfCells() << " cells:" << std::endl;
  for( i = 0; i < mesh->GetNumberOfCells(); i++ )
    {
    typedef MeshType::CellAutoPointer CellAutoPointer;
    CellAutoPointer cell;
    if( mesh->GetCell( i, cell ) )
      {
      std::cout << i << ": ";
      typedef CellType::PointIdConstIterator PointIdIterator;
      PointIdIterator pointIter = cell->PointIdsBegin();
      PointIdIterator pointsEnd = cell->PointIdsEnd();
      for( ; pointIter != pointsEnd; ++pointIter )
        {
        std::cout << *pointIter << " ";
        }
      std::cout << std::endl;
      }
    }
  std::cout << "\n";

  for( i = 0; i < mesh->GetNumberOfCells(); i++ )
    {
    typedef MeshType::CellAutoPointer CellAutoPointer;
    CellAutoPointer cell;
    if( mesh->GetCell( i, cell ) )
      {
      if( cell->GetType() == CellType::LINE_CELL )
        {
        std::cout << "Cell " << i << ":\n";

        typedef MeshSourceType::IdentifierType IdentifierType;
        typedef std::set<IdentifierType> NeighborSet;
        NeighborSet cellSet;

        mesh->GetCellBoundaryFeatureNeighbors( 0, i, 0, &cellSet );
        std::cout << "Neighbors across vertex 0: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n";

        mesh->GetCellBoundaryFeatureNeighbors( 0, i, 1, &cellSet );
        std::cout << "Neighbors across vertex 1: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n";

        mesh->GetCellNeighbors( i, &cellSet );
        std::cout << "Neighbors having edge as boundary: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n" << std::endl;

        }
      }
    }

  // Check that the right number of points has been added.

  int numPoints = meshSource->GetOutput()->GetNumberOfPoints();
  if( numPoints != 17 )
    {
    std::cerr << "Mesh shows " << numPoints
              << " points, but 17 were added." << std::endl;
    return EXIT_FAILURE;
    }

  // Check that the right number of cells has been added.

  int numCells = meshSource->GetOutput()->GetNumberOfCells();
  if( numCells != 68 )
    {
    std::cerr << "Mesh shows "
              << numCells
              << " cells, but 68 were added." << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}

<|endoftext|>


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

#include "chrome/browser/ui/views/action_box_menu.h"

#include "chrome/browser/ui/toolbar/action_box_menu_model.h"
#include "chrome/browser/ui/views/browser_action_view.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/view.h"

#if defined(OS_WIN)
// Included for MENU_POPUPITEM and a few other Windows specific constants.
#include <vssym32.h>
#include "ui/base/native_theme/native_theme_win.h"
#endif

////////////////////////////////////////////////////////////////////////////////
// ActionBoxMenu

ActionBoxMenu::ActionBoxMenu(Browser* browser,
                             ActionBoxMenuModel* model,
                             bool starred)
    : browser_(browser),
      root_(NULL),
      model_(model),
      starred_(starred) {
}

ActionBoxMenu::~ActionBoxMenu() {
}

void ActionBoxMenu::Init() {
  DCHECK(!root_);
  root_ = new views::MenuItemView(this);
  root_->set_has_icons(true);
  PopulateMenu();
}

void ActionBoxMenu::RunMenu(views::MenuButton* menu_button) {
  gfx::Point screen_location;
  views::View::ConvertPointToScreen(menu_button, &screen_location);
  menu_runner_.reset(new views::MenuRunner(root_));
  // Ignore the result since we don't need to handle a deleted menu specially.
  ignore_result(
      menu_runner_->RunMenuAt(menu_button->GetWidget(),
                              menu_button,
                              gfx::Rect(screen_location, menu_button->size()),
                              views::MenuItemView::TOPRIGHT,
                              views::MenuRunner::HAS_MNEMONICS));
}

void ActionBoxMenu::ExecuteCommand(int id) {
};

views::Border* ActionBoxMenu::CreateMenuBorder() {
  // TODO(yefim): Use correct theme color on non-Windows.
  SkColor border_color = SK_ColorBLACK;
#if defined(OS_WIN)
  // TODO(yefim): Move to Windows only files if possible.
  border_color = ui::NativeThemeWin::instance()->GetThemeColorWithDefault(
      ui::NativeThemeWin::MENU, MENU_POPUPITEM, MPI_NORMAL, TMT_TEXTCOLOR,
      COLOR_MENUTEXT);
#endif
  return views::Border::CreateSolidBorder(1, border_color);
}

views::Background* ActionBoxMenu::CreateMenuBackground() {
  // TODO(yefim): Use correct theme color on non-Windows.
  SkColor background_color = SK_ColorWHITE;
#if defined(OS_WIN)
  // TODO(yefim): Move to Windows only files if possible.
  background_color = ui::NativeThemeWin::instance()->GetThemeColorWithDefault(
      ui::NativeThemeWin::TEXTFIELD, EP_BACKGROUND, EBS_NORMAL,
      TMT_BACKGROUND, COLOR_WINDOW);
#endif
  return views::Background::CreateSolidBackground(background_color);
}

int ActionBoxMenu::GetCurrentTabId() const {
  return 0;
}

void ActionBoxMenu::OnBrowserActionExecuted(BrowserActionButton* button) {
}

void ActionBoxMenu::OnBrowserActionVisibilityChanged() {
}

gfx::Point ActionBoxMenu::GetViewContentOffset() const {
  return gfx::Point(0, 0);
}

bool ActionBoxMenu::NeedToShowMultipleIconStates() const {
  return false;
}

bool ActionBoxMenu::NeedToShowTooltip() const {
  return false;
}

void ActionBoxMenu::WriteDragDataForView(views::View* sender,
                                         const gfx::Point& press_pt,
                                         ui::OSExchangeData* data) {
}

int ActionBoxMenu::GetDragOperationsForView(views::View* sender,
                                            const gfx::Point& p) {
  return 0;
}

bool ActionBoxMenu::CanStartDragForView(views::View* sender,
                                        const gfx::Point& press_pt,
                                        const gfx::Point& p) {
  return false;
}

void ActionBoxMenu::Observe(int type,
                            const content::NotificationSource& source,
                            const content::NotificationDetails& details) {
}

void ActionBoxMenu::PopulateMenu() {
  int item_id = 1;
  AddBookmarkMenuItem(root_, &item_id);
  if (model_->GetItemCount() > 0)
    root_->AppendSeparator();

  const extensions::ExtensionList& action_box_items =
      model_->action_box_menu_items();
  for (size_t model_index = 0; model_index < action_box_items.size();
       ++model_index) {
    DCHECK(model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_COMMAND);
    views::MenuItemView* menu_item = root_->AppendMenuItemFromModel(
        model_, model_index, item_id + model_index);
    menu_item->SetMargins(0, 0);
    const extensions::Extension* extension = action_box_items[model_index];
    BrowserActionView* view = new BrowserActionView(extension,
        browser_, this);
    browser_action_views_.push_back(view);
    menu_item->SetIconView(view);
  }
}

views::MenuItemView* ActionBoxMenu::AddBookmarkMenuItem(
    views::MenuItemView* parent,
    int* item_id) {
  string16 label = l10n_util::GetStringUTF16(starred_ ?
      IDS_TOOLTIP_STARRED : IDS_TOOLTIP_STAR);
  gfx::ImageSkia* icon =
      ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
          starred_ ? IDR_STAR_LIT : IDR_STAR);
  views::MenuItemView* item =
      parent->AppendMenuItemWithIcon(*item_id, label, *icon);
  (*item_id)++;
  return item;
}
<commit_msg>Fix aura compile.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/action_box_menu.h"

#include "chrome/browser/ui/toolbar/action_box_menu_model.h"
#include "chrome/browser/ui/views/browser_action_view.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/view.h"

#if defined(OS_WIN) && !defined(USE_AURA)
// Included for MENU_POPUPITEM and a few other Windows specific constants.
#include <vssym32.h>
#include "ui/base/native_theme/native_theme_win.h"
#endif

////////////////////////////////////////////////////////////////////////////////
// ActionBoxMenu

ActionBoxMenu::ActionBoxMenu(Browser* browser,
                             ActionBoxMenuModel* model,
                             bool starred)
    : browser_(browser),
      root_(NULL),
      model_(model),
      starred_(starred) {
}

ActionBoxMenu::~ActionBoxMenu() {
}

void ActionBoxMenu::Init() {
  DCHECK(!root_);
  root_ = new views::MenuItemView(this);
  root_->set_has_icons(true);
  PopulateMenu();
}

void ActionBoxMenu::RunMenu(views::MenuButton* menu_button) {
  gfx::Point screen_location;
  views::View::ConvertPointToScreen(menu_button, &screen_location);
  menu_runner_.reset(new views::MenuRunner(root_));
  // Ignore the result since we don't need to handle a deleted menu specially.
  ignore_result(
      menu_runner_->RunMenuAt(menu_button->GetWidget(),
                              menu_button,
                              gfx::Rect(screen_location, menu_button->size()),
                              views::MenuItemView::TOPRIGHT,
                              views::MenuRunner::HAS_MNEMONICS));
}

void ActionBoxMenu::ExecuteCommand(int id) {
};

views::Border* ActionBoxMenu::CreateMenuBorder() {
  // TODO(yefim): Use correct theme color on non-Windows.
  SkColor border_color = SK_ColorBLACK;
#if defined(OS_WIN) && !defined(USE_AURA)
  // TODO(yefim): Move to Windows only files if possible.
  border_color = ui::NativeThemeWin::instance()->GetThemeColorWithDefault(
      ui::NativeThemeWin::MENU, MENU_POPUPITEM, MPI_NORMAL, TMT_TEXTCOLOR,
      COLOR_MENUTEXT);
#endif
  return views::Border::CreateSolidBorder(1, border_color);
}

views::Background* ActionBoxMenu::CreateMenuBackground() {
  // TODO(yefim): Use correct theme color on non-Windows.
  SkColor background_color = SK_ColorWHITE;
#if defined(OS_WIN) && !defined(USE_AURA)
  // TODO(yefim): Move to Windows only files if possible.
  background_color = ui::NativeThemeWin::instance()->GetThemeColorWithDefault(
      ui::NativeThemeWin::TEXTFIELD, EP_BACKGROUND, EBS_NORMAL,
      TMT_BACKGROUND, COLOR_WINDOW);
#endif
  return views::Background::CreateSolidBackground(background_color);
}

int ActionBoxMenu::GetCurrentTabId() const {
  return 0;
}

void ActionBoxMenu::OnBrowserActionExecuted(BrowserActionButton* button) {
}

void ActionBoxMenu::OnBrowserActionVisibilityChanged() {
}

gfx::Point ActionBoxMenu::GetViewContentOffset() const {
  return gfx::Point(0, 0);
}

bool ActionBoxMenu::NeedToShowMultipleIconStates() const {
  return false;
}

bool ActionBoxMenu::NeedToShowTooltip() const {
  return false;
}

void ActionBoxMenu::WriteDragDataForView(views::View* sender,
                                         const gfx::Point& press_pt,
                                         ui::OSExchangeData* data) {
}

int ActionBoxMenu::GetDragOperationsForView(views::View* sender,
                                            const gfx::Point& p) {
  return 0;
}

bool ActionBoxMenu::CanStartDragForView(views::View* sender,
                                        const gfx::Point& press_pt,
                                        const gfx::Point& p) {
  return false;
}

void ActionBoxMenu::Observe(int type,
                            const content::NotificationSource& source,
                            const content::NotificationDetails& details) {
}

void ActionBoxMenu::PopulateMenu() {
  int item_id = 1;
  AddBookmarkMenuItem(root_, &item_id);
  if (model_->GetItemCount() > 0)
    root_->AppendSeparator();

  const extensions::ExtensionList& action_box_items =
      model_->action_box_menu_items();
  for (size_t model_index = 0; model_index < action_box_items.size();
       ++model_index) {
    DCHECK(model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_COMMAND);
    views::MenuItemView* menu_item = root_->AppendMenuItemFromModel(
        model_, model_index, item_id + model_index);
    menu_item->SetMargins(0, 0);
    const extensions::Extension* extension = action_box_items[model_index];
    BrowserActionView* view = new BrowserActionView(extension,
        browser_, this);
    browser_action_views_.push_back(view);
    menu_item->SetIconView(view);
  }
}

views::MenuItemView* ActionBoxMenu::AddBookmarkMenuItem(
    views::MenuItemView* parent,
    int* item_id) {
  string16 label = l10n_util::GetStringUTF16(starred_ ?
      IDS_TOOLTIP_STARRED : IDS_TOOLTIP_STAR);
  gfx::ImageSkia* icon =
      ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
          starred_ ? IDR_STAR_LIT : IDR_STAR);
  views::MenuItemView* item =
      parent->AppendMenuItemWithIcon(*item_id, label, *icon);
  (*item_id)++;
  return item;
}
<|endoftext|>


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

#include "chrome/common/child_process_logging.h"

#include <windows.h>

#include "base/string_util.h"
#include "chrome/common/chrome_constants.h"
#include "googleurl/src/gurl.h"

namespace child_process_logging {

typedef void (__cdecl *MainSetActiveURL)(const wchar_t*);

void SetActiveURL(const GURL& url) {
  HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
  if (!exe_module)
    return;

  MainSetActiveURL set_active_url =
      reinterpret_cast<MainSetActiveURL>(
          GetProcAddress(exe_module, "SetActiveURL"));
  if (!set_active_url)
    return;

  (set_active_url)(UTF8ToWide(url.possibly_invalid_spec()).c_str());
}

}  // namespace child_process_logging
<commit_msg>Added a static function pointer to cache the SetActiveURL pointer. - Windows only change.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/child_process_logging.h"

#include <windows.h>

#include "base/string_util.h"
#include "chrome/common/chrome_constants.h"
#include "googleurl/src/gurl.h"

namespace child_process_logging {
// exported in breakpad_win.cc: void __declspec(dllexport) __cdecl SetActiveURL.
typedef void (__cdecl *MainSetActiveURL)(const wchar_t*);

void SetActiveURL(const GURL& url) {
  static MainSetActiveURL set_active_url = NULL;
  // note: benign race condition on set_active_url.
  if (!set_active_url) {
    HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
    if (!exe_module)
      return;
    set_active_url = reinterpret_cast<MainSetActiveURL>(
        GetProcAddress(exe_module, "SetActiveURL"));
    if (!set_active_url)
      return;
  }

  (set_active_url)(UTF8ToWide(url.possibly_invalid_spec()).c_str());
}

}  // namespace child_process_logging
<|endoftext|>


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

#include "chrome/common/net/cookie_monster_sqlite.h"

#include "base/logging.h"
#include "base/ref_counted.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"

// This class is designed to be shared between any calling threads and the
// database thread.  It batches operations and commits them on a timer.
class SQLitePersistentCookieStore::Backend
    : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
 public:
  // The passed database pointer must be already-initialized. This object will
  // take ownership.
  explicit Backend(sqlite3* db, MessageLoop* loop)
      : db_(db),
        background_loop_(loop),
        cache_(new SqliteStatementCache(db)),
        num_pending_(0) {
    DCHECK(db_) << "Database must exist.";
  }

  // You should call Close() before destructing this object.
  ~Backend() {
    DCHECK(!db_) << "Close should have already been called.";
    DCHECK(num_pending_ == 0 && pending_.empty());
  }

  // Batch a cookie add
  void AddCookie(const std::string& key,
                 const net::CookieMonster::CanonicalCookie& cc);
  // Batch a cookie delete
  void DeleteCookie(const net::CookieMonster::CanonicalCookie& cc);
  // Commit and pending operations and close the database, must be called
  // before the object is destructed.
  void Close();

 private:
  class PendingOperation {
   public:
    typedef enum {
      COOKIE_ADD,
      COOKIE_DELETE,
    } OperationType;

    PendingOperation(OperationType op,
                     const std::string& key,
                     const net::CookieMonster::CanonicalCookie& cc)
        : op_(op), key_(key), cc_(cc) { }

    OperationType op() const { return op_; }
    const std::string& key() const { return key_; }
    const net::CookieMonster::CanonicalCookie& cc() const { return cc_; }

   private:
    OperationType op_;
    std::string key_;  // Only used for OP_ADD
    net::CookieMonster::CanonicalCookie cc_;
  };

 private:
  // Batch a cookie operation (add or delete)
  void BatchOperation(PendingOperation::OperationType op,
                      const std::string& key,
                      const net::CookieMonster::CanonicalCookie& cc);
  // Commit our pending operations to the database.
  void Commit();
  // Close() executed on the background thread.
  void InternalBackgroundClose();

  sqlite3* db_;
  MessageLoop* background_loop_;
  SqliteStatementCache* cache_;

  typedef std::list<PendingOperation*> PendingOperationsList;
  PendingOperationsList pending_;
  PendingOperationsList::size_type num_pending_;
  Lock pending_lock_;  // Guard pending_ and num_pending_

  DISALLOW_EVIL_CONSTRUCTORS(Backend);
};

void SQLitePersistentCookieStore::Backend::AddCookie(
    const std::string& key,
    const net::CookieMonster::CanonicalCookie& cc) {
  BatchOperation(PendingOperation::COOKIE_ADD, key, cc);
}

void SQLitePersistentCookieStore::Backend::DeleteCookie(
    const net::CookieMonster::CanonicalCookie& cc) {
  BatchOperation(PendingOperation::COOKIE_DELETE, std::string(), cc);
}

void SQLitePersistentCookieStore::Backend::BatchOperation(
    PendingOperation::OperationType op,
    const std::string& key,
    const net::CookieMonster::CanonicalCookie& cc) {
  // Commit every 30 seconds.
  static const int kCommitIntervalMs = 30 * 1000;
  // Commit right away if we have more than 512 outstanding operations.
  static const int kCommitAfterBatchSize = 512;
  DCHECK(MessageLoop::current() != background_loop_);

  // We do a full copy of the cookie here, and hopefully just here.
  scoped_ptr<PendingOperation> po(new PendingOperation(op, key, cc));
  CHECK(po.get());

  PendingOperationsList::size_type num_pending;
  {
    AutoLock locked(pending_lock_);
    pending_.push_back(po.release());
    num_pending = ++num_pending_;
  }

  // TODO(abarth): What if the DB thread is being destroyed on the UI thread?
  if (num_pending == 1) {
    // We've gotten our first entry for this batch, fire off the timer.
    background_loop_->PostDelayedTask(FROM_HERE,
        NewRunnableMethod(this, &Backend::Commit), kCommitIntervalMs);
  } else if (num_pending == kCommitAfterBatchSize) {
    // We've reached a big enough batch, fire off a commit now.
    background_loop_->PostTask(FROM_HERE,
        NewRunnableMethod(this, &Backend::Commit));
  }
}

void SQLitePersistentCookieStore::Backend::Commit() {
  DCHECK(MessageLoop::current() == background_loop_);
  PendingOperationsList ops;
  {
    AutoLock locked(pending_lock_);
    pending_.swap(ops);
    num_pending_ = 0;
  }

  // Maybe an old timer fired or we are already Close()'ed.
  if (!db_ || ops.empty())
    return;

  SQLITE_UNIQUE_STATEMENT(add_smt, *cache_,
                          "INSERT INTO cookies VALUES (?,?,?,?,?,?,?,?)");
  if (!add_smt.is_valid()) {
    NOTREACHED();
    return;
  }
  SQLITE_UNIQUE_STATEMENT(del_smt, *cache_,
                          "DELETE FROM cookies WHERE creation_utc=?");
  if (!del_smt.is_valid()) {
    NOTREACHED();
    return;
  }

  SQLTransaction transaction(db_);
  transaction.Begin();
  for (PendingOperationsList::iterator it = ops.begin();
       it != ops.end(); ++it) {
    // Free the cookies as we commit them to the database.
    scoped_ptr<PendingOperation> po(*it);
    switch (po->op()) {
      case PendingOperation::COOKIE_ADD:
        add_smt->reset();
        add_smt->bind_int64(0, po->cc().CreationDate().ToInternalValue());
        add_smt->bind_string(1, po->key());
        add_smt->bind_string(2, po->cc().Name());
        add_smt->bind_string(3, po->cc().Value());
        add_smt->bind_string(4, po->cc().Path());
        add_smt->bind_int64(5, po->cc().ExpiryDate().ToInternalValue());
        add_smt->bind_int(6, po->cc().IsSecure());
        add_smt->bind_int(7, po->cc().IsHttpOnly());
        if (add_smt->step() != SQLITE_DONE) {
          NOTREACHED() << "Could not add a cookie to the DB.";
        }
        break;
      case PendingOperation::COOKIE_DELETE:
        del_smt->reset();
        del_smt->bind_int64(0, po->cc().CreationDate().ToInternalValue());
        if (del_smt->step() != SQLITE_DONE) {
          NOTREACHED() << "Could not delete a cookie from the DB.";
        }
        break;
      default:
        NOTREACHED();
        break;
    }
  }
  transaction.Commit();
}

// Fire off a close message to the background thread.  We could still have a
// pending commit timer that will be holding a reference on us, but if/when
// this fires we will already have been cleaned up and it will be ignored.
void SQLitePersistentCookieStore::Backend::Close() {
  DCHECK(MessageLoop::current() != background_loop_);
  // Must close the backend on the background thread.
  // TODO(abarth): What if the DB thread is being destroyed on the UI thread?
  background_loop_->PostTask(FROM_HERE,
      NewRunnableMethod(this, &Backend::InternalBackgroundClose));
}

void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
  DCHECK(MessageLoop::current() == background_loop_);
  // Commit any pending operations
  Commit();
  // We must destroy the cache before closing the database.
  delete cache_;
  cache_ = NULL;
  sqlite3_close(db_);
  db_ = NULL;
}

SQLitePersistentCookieStore::SQLitePersistentCookieStore(
    const std::wstring& path, MessageLoop* background_loop)
    : path_(path),
      background_loop_(background_loop) {
  DCHECK(background_loop) << "SQLitePersistentCookieStore needs a MessageLoop";
}

SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
  if (backend_.get()) {
    backend_->Close();
    // Release our reference, it will probably still have a reference if the
    // background thread has not run Close() yet.
    backend_ = NULL;
  }
}

// Version number of the database.
static const int kCurrentVersionNumber = 2;

namespace {

// Initializes the cookies table, returning true on success.
bool InitTable(sqlite3* db) {
  if (!DoesSqliteTableExist(db, "cookies")) {
    if (sqlite3_exec(db, "CREATE TABLE cookies ("
                         "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
                         "host_key TEXT NOT NULL,"
                         "name TEXT NOT NULL,"
                         "value TEXT NOT NULL,"
                         "path TEXT NOT NULL,"
                         // We only store persistent, so we know it expires
                         "expires_utc INTEGER NOT NULL,"
                         "secure INTEGER NOT NULL,"
                         "httponly INTEGER NOT NULL)",
                         NULL, NULL, NULL) != SQLITE_OK)
      return false;
  }

  // Try to create the index every time. Older versions did not have this index,
  // so we want those people to get it. Ignore errors, since it may exist.
  sqlite3_exec(db, "CREATE INDEX cookie_times ON cookies (creation_utc)",
               NULL, NULL, NULL);

  return true;
}

}  // namespace

bool SQLitePersistentCookieStore::Load(
    std::vector<net::CookieMonster::KeyedCanonicalCookie>* cookies) {
  DCHECK(!path_.empty());
  sqlite3* db;
  if (sqlite3_open(WideToUTF8(path_).c_str(), &db) != SQLITE_OK) {
    NOTREACHED() << "Unable to open cookie DB.";
    return false;
  }

  if (!EnsureDatabaseVersion(db) || !InitTable(db)) {
    NOTREACHED() << "Unable to initialize cookie DB.";
    sqlite3_close(db);
    return false;
  }

  // Slurp all the cookies into the out-vector.
  SQLStatement smt;
  if (smt.prepare(db, "SELECT * FROM cookies") != SQLITE_OK) {
    NOTREACHED() << "select statement prep failed";
    sqlite3_close(db);
    return false;
  }

  // Step the statement and do the preload operation. Preload() requires that a
  // statement be open on the database, so we oblige. We don't bother keeping
  // this and reset the statement so we can read all the rows.
  //
  // The Preload call makes the read faster, since we will be reading most of
  // the database, it's better to read it in one chunk than have a lot of seeks
  // bringing it in organically.
  if (smt.step() != SQLITE_ROW)
    sqlite3Preload(db);
  smt.reset();

  while (smt.step() == SQLITE_ROW) {
    std::string key = smt.column_string(1);
    scoped_ptr<net::CookieMonster::CanonicalCookie> cc(
        new net::CookieMonster::CanonicalCookie(
            smt.column_string(2),                            // name
            smt.column_string(3),                            // value
            smt.column_string(4),                            // path
            smt.column_int(6) != 0,                          // secure
            smt.column_int(7) != 0,                          // httponly
            Time::FromInternalValue(smt.column_int64(0)),    // creation_utc
            true,                                            // has_expires
            Time::FromInternalValue(smt.column_int64(5))));  // expires_utc
    // Memory allocation failed.
    if (!cc.get())
      break;

    DLOG_IF(WARNING,
            cc->CreationDate() > Time::Now()) << L"CreationDate too recent";
    cookies->push_back(
        net::CookieMonster::KeyedCanonicalCookie(smt.column_string(1),
                                                 cc.release()));
  }

  // Create the backend, this will take ownership of the db pointer.
  backend_ = new Backend(db, background_loop_);

  return true;
}

bool SQLitePersistentCookieStore::EnsureDatabaseVersion(sqlite3* db) {
  // Version check.
  if (!meta_table_.Init(std::string(), kCurrentVersionNumber, db))
    return false;

  int compat_version = meta_table_.GetCompatibleVersionNumber();
  if (compat_version > kCurrentVersionNumber) {
    DLOG(WARNING) << "Cookie DB version from the future: " << compat_version;
    return false;
  }

  return true;
}

void SQLitePersistentCookieStore::AddCookie(
    const std::string& key,
    const net::CookieMonster::CanonicalCookie& cc) {
  if (backend_.get())
    backend_->AddCookie(key, cc);
}

void SQLitePersistentCookieStore::DeleteCookie(
    const net::CookieMonster::CanonicalCookie& cc) {
  if (backend_.get())
    backend_->DeleteCookie(cc);
}

<commit_msg>Add a missing include and match a constant type better.  From phajdan.jr. Review URL: http://codereview.chromium.org/2922<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/net/cookie_monster_sqlite.h"

#include <list>

#include "base/basictypes.h"
#include "base/logging.h"
#include "base/ref_counted.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/common/sqlite_compiled_statement.h"
#include "chrome/common/sqlite_utils.h"

// This class is designed to be shared between any calling threads and the
// database thread.  It batches operations and commits them on a timer.
class SQLitePersistentCookieStore::Backend
    : public base::RefCountedThreadSafe<SQLitePersistentCookieStore::Backend> {
 public:
  // The passed database pointer must be already-initialized. This object will
  // take ownership.
  explicit Backend(sqlite3* db, MessageLoop* loop)
      : db_(db),
        background_loop_(loop),
        cache_(new SqliteStatementCache(db)),
        num_pending_(0) {
    DCHECK(db_) << "Database must exist.";
  }

  // You should call Close() before destructing this object.
  ~Backend() {
    DCHECK(!db_) << "Close should have already been called.";
    DCHECK(num_pending_ == 0 && pending_.empty());
  }

  // Batch a cookie add
  void AddCookie(const std::string& key,
                 const net::CookieMonster::CanonicalCookie& cc);
  // Batch a cookie delete
  void DeleteCookie(const net::CookieMonster::CanonicalCookie& cc);
  // Commit and pending operations and close the database, must be called
  // before the object is destructed.
  void Close();

 private:
  class PendingOperation {
   public:
    typedef enum {
      COOKIE_ADD,
      COOKIE_DELETE,
    } OperationType;

    PendingOperation(OperationType op,
                     const std::string& key,
                     const net::CookieMonster::CanonicalCookie& cc)
        : op_(op), key_(key), cc_(cc) { }

    OperationType op() const { return op_; }
    const std::string& key() const { return key_; }
    const net::CookieMonster::CanonicalCookie& cc() const { return cc_; }

   private:
    OperationType op_;
    std::string key_;  // Only used for OP_ADD
    net::CookieMonster::CanonicalCookie cc_;
  };

 private:
  // Batch a cookie operation (add or delete)
  void BatchOperation(PendingOperation::OperationType op,
                      const std::string& key,
                      const net::CookieMonster::CanonicalCookie& cc);
  // Commit our pending operations to the database.
  void Commit();
  // Close() executed on the background thread.
  void InternalBackgroundClose();

  sqlite3* db_;
  MessageLoop* background_loop_;
  SqliteStatementCache* cache_;

  typedef std::list<PendingOperation*> PendingOperationsList;
  PendingOperationsList pending_;
  PendingOperationsList::size_type num_pending_;
  Lock pending_lock_;  // Guard pending_ and num_pending_

  DISALLOW_EVIL_CONSTRUCTORS(Backend);
};

void SQLitePersistentCookieStore::Backend::AddCookie(
    const std::string& key,
    const net::CookieMonster::CanonicalCookie& cc) {
  BatchOperation(PendingOperation::COOKIE_ADD, key, cc);
}

void SQLitePersistentCookieStore::Backend::DeleteCookie(
    const net::CookieMonster::CanonicalCookie& cc) {
  BatchOperation(PendingOperation::COOKIE_DELETE, std::string(), cc);
}

void SQLitePersistentCookieStore::Backend::BatchOperation(
    PendingOperation::OperationType op,
    const std::string& key,
    const net::CookieMonster::CanonicalCookie& cc) {
  // Commit every 30 seconds.
  static const int kCommitIntervalMs = 30 * 1000;
  // Commit right away if we have more than 512 outstanding operations.
  static const size_t kCommitAfterBatchSize = 512;
  DCHECK(MessageLoop::current() != background_loop_);

  // We do a full copy of the cookie here, and hopefully just here.
  scoped_ptr<PendingOperation> po(new PendingOperation(op, key, cc));
  CHECK(po.get());

  PendingOperationsList::size_type num_pending;
  {
    AutoLock locked(pending_lock_);
    pending_.push_back(po.release());
    num_pending = ++num_pending_;
  }

  // TODO(abarth): What if the DB thread is being destroyed on the UI thread?
  if (num_pending == 1) {
    // We've gotten our first entry for this batch, fire off the timer.
    background_loop_->PostDelayedTask(FROM_HERE,
        NewRunnableMethod(this, &Backend::Commit), kCommitIntervalMs);
  } else if (num_pending == kCommitAfterBatchSize) {
    // We've reached a big enough batch, fire off a commit now.
    background_loop_->PostTask(FROM_HERE,
        NewRunnableMethod(this, &Backend::Commit));
  }
}

void SQLitePersistentCookieStore::Backend::Commit() {
  DCHECK(MessageLoop::current() == background_loop_);
  PendingOperationsList ops;
  {
    AutoLock locked(pending_lock_);
    pending_.swap(ops);
    num_pending_ = 0;
  }

  // Maybe an old timer fired or we are already Close()'ed.
  if (!db_ || ops.empty())
    return;

  SQLITE_UNIQUE_STATEMENT(add_smt, *cache_,
                          "INSERT INTO cookies VALUES (?,?,?,?,?,?,?,?)");
  if (!add_smt.is_valid()) {
    NOTREACHED();
    return;
  }
  SQLITE_UNIQUE_STATEMENT(del_smt, *cache_,
                          "DELETE FROM cookies WHERE creation_utc=?");
  if (!del_smt.is_valid()) {
    NOTREACHED();
    return;
  }

  SQLTransaction transaction(db_);
  transaction.Begin();
  for (PendingOperationsList::iterator it = ops.begin();
       it != ops.end(); ++it) {
    // Free the cookies as we commit them to the database.
    scoped_ptr<PendingOperation> po(*it);
    switch (po->op()) {
      case PendingOperation::COOKIE_ADD:
        add_smt->reset();
        add_smt->bind_int64(0, po->cc().CreationDate().ToInternalValue());
        add_smt->bind_string(1, po->key());
        add_smt->bind_string(2, po->cc().Name());
        add_smt->bind_string(3, po->cc().Value());
        add_smt->bind_string(4, po->cc().Path());
        add_smt->bind_int64(5, po->cc().ExpiryDate().ToInternalValue());
        add_smt->bind_int(6, po->cc().IsSecure());
        add_smt->bind_int(7, po->cc().IsHttpOnly());
        if (add_smt->step() != SQLITE_DONE) {
          NOTREACHED() << "Could not add a cookie to the DB.";
        }
        break;
      case PendingOperation::COOKIE_DELETE:
        del_smt->reset();
        del_smt->bind_int64(0, po->cc().CreationDate().ToInternalValue());
        if (del_smt->step() != SQLITE_DONE) {
          NOTREACHED() << "Could not delete a cookie from the DB.";
        }
        break;
      default:
        NOTREACHED();
        break;
    }
  }
  transaction.Commit();
}

// Fire off a close message to the background thread.  We could still have a
// pending commit timer that will be holding a reference on us, but if/when
// this fires we will already have been cleaned up and it will be ignored.
void SQLitePersistentCookieStore::Backend::Close() {
  DCHECK(MessageLoop::current() != background_loop_);
  // Must close the backend on the background thread.
  // TODO(abarth): What if the DB thread is being destroyed on the UI thread?
  background_loop_->PostTask(FROM_HERE,
      NewRunnableMethod(this, &Backend::InternalBackgroundClose));
}

void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() {
  DCHECK(MessageLoop::current() == background_loop_);
  // Commit any pending operations
  Commit();
  // We must destroy the cache before closing the database.
  delete cache_;
  cache_ = NULL;
  sqlite3_close(db_);
  db_ = NULL;
}

SQLitePersistentCookieStore::SQLitePersistentCookieStore(
    const std::wstring& path, MessageLoop* background_loop)
    : path_(path),
      background_loop_(background_loop) {
  DCHECK(background_loop) << "SQLitePersistentCookieStore needs a MessageLoop";
}

SQLitePersistentCookieStore::~SQLitePersistentCookieStore() {
  if (backend_.get()) {
    backend_->Close();
    // Release our reference, it will probably still have a reference if the
    // background thread has not run Close() yet.
    backend_ = NULL;
  }
}

// Version number of the database.
static const int kCurrentVersionNumber = 2;

namespace {

// Initializes the cookies table, returning true on success.
bool InitTable(sqlite3* db) {
  if (!DoesSqliteTableExist(db, "cookies")) {
    if (sqlite3_exec(db, "CREATE TABLE cookies ("
                         "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY,"
                         "host_key TEXT NOT NULL,"
                         "name TEXT NOT NULL,"
                         "value TEXT NOT NULL,"
                         "path TEXT NOT NULL,"
                         // We only store persistent, so we know it expires
                         "expires_utc INTEGER NOT NULL,"
                         "secure INTEGER NOT NULL,"
                         "httponly INTEGER NOT NULL)",
                         NULL, NULL, NULL) != SQLITE_OK)
      return false;
  }

  // Try to create the index every time. Older versions did not have this index,
  // so we want those people to get it. Ignore errors, since it may exist.
  sqlite3_exec(db, "CREATE INDEX cookie_times ON cookies (creation_utc)",
               NULL, NULL, NULL);

  return true;
}

}  // namespace

bool SQLitePersistentCookieStore::Load(
    std::vector<net::CookieMonster::KeyedCanonicalCookie>* cookies) {
  DCHECK(!path_.empty());
  sqlite3* db;
  if (sqlite3_open(WideToUTF8(path_).c_str(), &db) != SQLITE_OK) {
    NOTREACHED() << "Unable to open cookie DB.";
    return false;
  }

  if (!EnsureDatabaseVersion(db) || !InitTable(db)) {
    NOTREACHED() << "Unable to initialize cookie DB.";
    sqlite3_close(db);
    return false;
  }

  // Slurp all the cookies into the out-vector.
  SQLStatement smt;
  if (smt.prepare(db, "SELECT * FROM cookies") != SQLITE_OK) {
    NOTREACHED() << "select statement prep failed";
    sqlite3_close(db);
    return false;
  }

  // Step the statement and do the preload operation. Preload() requires that a
  // statement be open on the database, so we oblige. We don't bother keeping
  // this and reset the statement so we can read all the rows.
  //
  // The Preload call makes the read faster, since we will be reading most of
  // the database, it's better to read it in one chunk than have a lot of seeks
  // bringing it in organically.
  if (smt.step() != SQLITE_ROW)
    sqlite3Preload(db);
  smt.reset();

  while (smt.step() == SQLITE_ROW) {
    std::string key = smt.column_string(1);
    scoped_ptr<net::CookieMonster::CanonicalCookie> cc(
        new net::CookieMonster::CanonicalCookie(
            smt.column_string(2),                            // name
            smt.column_string(3),                            // value
            smt.column_string(4),                            // path
            smt.column_int(6) != 0,                          // secure
            smt.column_int(7) != 0,                          // httponly
            Time::FromInternalValue(smt.column_int64(0)),    // creation_utc
            true,                                            // has_expires
            Time::FromInternalValue(smt.column_int64(5))));  // expires_utc
    // Memory allocation failed.
    if (!cc.get())
      break;

    DLOG_IF(WARNING,
            cc->CreationDate() > Time::Now()) << L"CreationDate too recent";
    cookies->push_back(
        net::CookieMonster::KeyedCanonicalCookie(smt.column_string(1),
                                                 cc.release()));
  }

  // Create the backend, this will take ownership of the db pointer.
  backend_ = new Backend(db, background_loop_);

  return true;
}

bool SQLitePersistentCookieStore::EnsureDatabaseVersion(sqlite3* db) {
  // Version check.
  if (!meta_table_.Init(std::string(), kCurrentVersionNumber, db))
    return false;

  int compat_version = meta_table_.GetCompatibleVersionNumber();
  if (compat_version > kCurrentVersionNumber) {
    DLOG(WARNING) << "Cookie DB version from the future: " << compat_version;
    return false;
  }

  return true;
}

void SQLitePersistentCookieStore::AddCookie(
    const std::string& key,
    const net::CookieMonster::CanonicalCookie& cc) {
  if (backend_.get())
    backend_->AddCookie(key, cc);
}

void SQLitePersistentCookieStore::DeleteCookie(
    const net::CookieMonster::CanonicalCookie& cc) {
  if (backend_.get())
    backend_->DeleteCookie(cc);
}

<|endoftext|>


<commit_before>/*
 *  ContentBubble.cpp
 *  Render
 *
 *  Created by Todd Vanderlin on 2/26/11.
 *  Copyright 2011 Interactive Design. All rights reserved.
 *
 */

#include "ContentBubble.h"

ofTrueTypeFont ContentBubble::font;

//--------------------------------------------------------------
ContentBubble::ContentBubble() {

	bAnimateOut = false;
	bAnimateIn = false;
	rigidBody		 = NULL;
	bTouched		 = false;
	bDoubleTouched	 = false;
	rotateY			 = 0;
	touchID			 = -1;
	distanceToTarget = 10000; // so i dont call sqrt() so much.
	rotateYTarget	 = 0;
	targetForce		= 20.f;

	if(ofRandomuf()>0.5){
		rotateYDirection = 180;
	}else{
		rotateYDirection = -180;
	}
	alpha = 255;

	bAlive = false;

	// for now!
	offScreenTaget.y = -100;
	offScreenTaget.z = -200;

	bobTheta.x = ofRandomuf() * PI;
	bobTheta.y = ofRandomuf() * PI;
	bobTheta.z = ofRandomuf() * PI;
}

//--------------------------------------------------------------
void ContentBubble::createContentBubble() {

	color.r = ofRandom(0, 255);
	color.g = ofRandom(0, 255);
	color.b = ofRandom(0, 255);
	color.a = 25;

	touchAlphaTarget = 0;
	touchAlpha		 = 0;

	for (int i=0; i<16; i++) {
		billboadMatrix[i] = 0;
		m[i]			  = 0;
	}

	bAlive = true;
	birthDate = ofGetElapsedTimeMillis();
}

//--------------------------------------------------------------
void ContentBubble::gotoTarget(float scale) {
	if(rigidBody->isBody()) {

		rigidBody->body->setDamping(0.99, 0.99); // <-- add some crazy damping

		ofVec3f frc = target - rigidBody->getBulletPosition();
		distanceToTarget = frc.length();
		float d = ABS(distanceToTarget) * scale;
		d *= targetForce;
		frc.normalize();
		frc *= d;

		rigidBody->body->clearForces();
		rigidBody->body->applyCentralForce(btVector3(frc.x, frc.y, frc.z));

		// printf("taget\n");
	}
}
//--------------------------------------------------------------
void ContentBubble::bobMe() {

	bobTheta += 0.02;

	float amp = 100;
	target.x = resetTarget.x + cos(	bobTheta.x ) * 10.0;
	target.y = resetTarget.y + sin(	bobTheta.y ) * amp;
	target.z = resetTarget.z + sin(	bobTheta.z ) * 30.0;
}

//--------------------------------------------------------------
void ContentBubble::setTarget(float x, float y, float z) {
	target = ofVec3f(x, y, z);
	resetTarget = ofVec3f(x, y, z);
}

//--------------------------------------------------------------
void ContentBubble::setTarget(ofVec3f v) {
	setTarget(v.x, v.y, v.z);
}

//--------------------------------------------------------------
ofVec3f ContentBubble::getPosition() {
	if(rigidBody->isBody()) {
		return rigidBody->getPosition();
	}
}

//--------------------------------------------------------------
void ContentBubble::addForce(float x, float y, float z, float scale) {
	if(rigidBody->isBody()) {

		// rigidBody->body->setDamping(0.99, 0.99); // <-- add some crazy damping

		ofVec3f frc = ofVec3f(x, y, z) * scale;
		rigidBody->body->clearForces();
		rigidBody->body->applyCentralForce(btVector3(frc.x, frc.y, frc.z));

	}
}

//--------------------------------------------------------------
void ContentBubble::goOffScreen() {
	if(rigidBody->isBody()) {

		rigidBody->body->setDamping(0.99, 0.99); // <-- add some crazy damping

		ofVec3f frc = offScreenTaget - rigidBody->getBulletPosition();
		distanceToTarget = frc.length();
		float d = ABS(distanceToTarget);
		d *= 20.0;
		frc.normalize();
		frc *= d;

		rigidBody->body->clearForces();
		rigidBody->body->applyCentralForce(btVector3(frc.x, frc.y, frc.z));

	}
}

//--------------------------------------------------------------
void ContentBubble::addAtrractionForce(float x, float y, float z, float scale) {
	if(rigidBody->isBody()) {

		ofVec3f frc = ofVec3f(x, y, z) - rigidBody->getBulletPosition();
		distanceToTarget = frc.length();
		float d = ABS(distanceToTarget);
		d *= scale;
		frc.normalize();
		frc *= d;

		rigidBody->body->clearForces();
		rigidBody->body->applyCentralForce(btVector3(frc.x, frc.y, frc.z));

	}
}

//--------------------------------------------------------------
void ContentBubble::addAtrractionForce(ofVec3f &p, float scale) {
	addAtrractionForce(p.x, p.y, p.z, scale);
}

//--------------------------------------------------------------
void ContentBubble::doubleTouched() {
	bDoubleTouched = true;
}

//--------------------------------------------------------------
void ContentBubble::setRadius(float r) {

	btSphereShape * sphereShape = (btSphereShape*)rigidBody->body->getCollisionShape();
	sphereShape->setUnscaledRadius(r);
	radius = r;

}

//--------------------------------------------------------------
void ContentBubble::lerpRadius(float r,float speed) {
	setRadius(radius + (r-radius)*speed);
}

//--------------------------------------------------------------
void ContentBubble::update() {

	//lazyload the font
	if(!font.bLoadedOk){
		font.loadFont("global/font/Gotham-Bold.otf", 50);
		if(font.bLoadedOk) {
			printf("--- font is loaded ---\n");
		}
	}

	touchAlpha += (touchAlphaTarget-touchAlpha) * 0.1;
	rotateY += (rotateYTarget-rotateY) * 0.05;
	if(bDoubleTouched){
		touchAlphaTarget = 160;
		rotateYTarget = rotateYDirection;
	}else{
		touchAlphaTarget = 0;
		rotateYTarget = 0;
	}

	age = ofGetElapsedTimeMillis()-birthDate;

	if(rigidBody->isBody()) {

		pos = rigidBody->getPosition();
		rigidBody->body->getWorldTransform().getOpenGLMatrix(m);
		btSphereShape * sphereShape = (btSphereShape*)rigidBody->shape;

		//radius doesn't include the margin, so draw with margin
		radius = sphereShape->getMargin();

		// create the billboard matrix
		for (int i=0; i<16; i++) {
			billboadMatrix[i] = m[i];
		}

		// ripped from here
		// http://lighthouse3d.com/opengl/billboarding/index.php?billCheat
		for(int i=0; i<3; i++ ) {
			for(int j=0; j<3; j++ ) {
				if ( i==j)  billboadMatrix[i*4+j] = 1.0;
				else		billboadMatrix[i*4+j] = 0.0;
			}
		}
	}
}

//--------------------------------------------------------------
void ContentBubble::pushBubble() {

	if(rigidBody->isBody()) {

		glPushMatrix();
		glMultMatrixf(m);

	}

}

//--------------------------------------------------------------
void ContentBubble::popBubble() {
	if(rigidBody->isBody()) {
		glPopMatrix();
	}

}

//--------------------------------------------------------------
void ContentBubble::pushBillboard() {
	glPushMatrix();
	glMultMatrixf(billboadMatrix);
}

//--------------------------------------------------------------
void ContentBubble::popBillboard() {
	glPopMatrix();
}

//--------------------------------------------------------------
void ContentBubble::drawTwitterData() {
	glEnable(GL_DEPTH_TEST);
	glPushMatrix();
	glMultMatrixf(billboadMatrix);

	glRotatef(rotateY,0,1,0);
	// the twitter icon and text
	if(data) {
		//if no twitter icon, don't draw.
		if(data->profileImage.width != 0){

			float data_radius = radius*0.9;

			//lazyload the font
			if(!font.bLoadedOk){
				font.loadFont("global/font/Gotham-Bold.otf",50);
				if(font.bLoadedOk) {
					printf("--- font is loaded ---\n");
				}
			}

			{
				//draw twitter icon as a disk
				ofSetColor(255,255,255, alpha);
				data->profileImage.bind();
				float w = data->profileImage.width;
				float h = data->profileImage.height;
				//draw the circle-masked thumbnail
				int steps = 60;
				float inc = TWO_PI/(float)steps;
				glBegin(GL_TRIANGLE_FAN);
				for(int i=0;i<steps;i++){
					float x = cos(inc*i);
					float y = sin(inc*i);
					glTexCoord2f((x+1)*w*0.5,(y+1)*h*0.5);
					glVertex2f(x*data_radius,y*data_radius);
				}
				glEnd();
				data->profileImage.unbind();
			}

			{
				glPushMatrix();
				glRotatef(180,0,1,0);
				glTranslatef(0,0,0.1);

				//draw twitter media as a disk
				ofSetColor(color,alpha);
				if(data->media.size()){
					ofSetColor(255,255,255, alpha);
					data->media[0].mediaImage.bind();
				}
				float w = data->profileImage.width;
				float h = data->profileImage.height;
				//draw the circle-masked thumbnail
				int steps = 60;
				float inc = TWO_PI/(float)steps;
				glBegin(GL_TRIANGLE_FAN);
				for(int i=0;i<steps;i++){
					float x = cos(inc*i);
					float y = sin(inc*i);
					glTexCoord2f((x+1)*w*0.5,(y+1)*h*0.5);
					glVertex2f(x*data_radius,y*data_radius);
				}
				glEnd();
				data->profileImage.unbind();
				glPopMatrix();
			}

			{
				//draw twitter text content
				ofRectangle textBB = font.getStringBoundingBox(data->userName, 0,0);
				glPushMatrix();
				float s = data_radius/textBB.width*1.75;
				glScalef(s,s,s);
				glTranslated(-textBB.width/2, 0,0.2);
				ofSetColor(0,0,0, alpha);
				font.drawString(data->userName,0,0);
				glTranslatef(2,2,0.2);
				ofSetColor(255,255,255, alpha);
				font.drawString(data->userName,0,0);
				data->profileImage.unbind();
				glPopMatrix();
			}

			{
				//draw twitter text content
				string txt = data->text;
				if(txt.empty())txt="lorem ipsum";
				ofRectangle textBB = font.getStringBoundingBox(txt, 0,0);
				glPushMatrix();
				float s = data_radius/textBB.width*1.75;
				glScalef(s,s,s);
				glRotatef(180,0,1,0);
				glTranslated(-textBB.width/2, 0,0.2);
				ofSetColor(0,0,0, alpha);
				font.drawString(txt,0,0);
				glTranslatef(2,2,0.2);
				ofSetColor(255,255,255, alpha);
				font.drawString(txt,0,0);
				data->profileImage.unbind();
				glPopMatrix();
			}

		}

	}
	glPopMatrix();
}

//--------------------------------------------------------------
void ContentBubble::drawHighLight() {

	glDisable(GL_DEPTH_TEST);

	glPushMatrix();
	glMultMatrixf(billboadMatrix);

	// little touch outline...
	ofEnableAlphaBlending();
	float rad_extend = radius + 100;
	//draw circular hailo
	glBegin(GL_TRIANGLE_STRIP);
	int steps = 30;
	float inc = TWO_PI/steps;
	for(int i=0;i<steps+1;i++){
		float x = cos(i*inc);
		float y = sin(i*inc);

		if(bDoubleTouched) {
			glColor4f(1, 0, 0, touchAlpha/255.0);
		} else {
			glColor4f(1,1,1, touchAlpha/255.0);
		}
		glVertex3f(x*radius,y*radius, 0);
		glColor4f(1,1,1,0);
		glVertex3f(x*rad_extend,y*rad_extend, 0);

	}
	glEnd();
	glPopMatrix();
}

//--------------------------------------------------------------
void ContentBubble::draw() {

	// for debuggin...
	//ofSetColor(255, 255, 0);
	//drawSphere(target, 3, 10);
	glEnable(GL_DEPTH_TEST);
	// the main bubble sphere
	ofSetColor(color, alpha);
	ofFill();
	drawSphere(ofVec3f(0, 0, 0), radius, 60);
}

<commit_msg>added behaviors for buzz and intvw  modes<commit_after>/*
 *  ContentBubble.cpp
 *  Render
 *
 *  Created by Todd Vanderlin on 2/26/11.
 *  Copyright 2011 Interactive Design. All rights reserved.
 *
 */

#include "ContentBubble.h"

ofTrueTypeFont ContentBubble::font;

//--------------------------------------------------------------
ContentBubble::ContentBubble() {

	bAnimateOut = false;
	bAnimateIn = false;
	rigidBody		 = NULL;
	bTouched		 = false;
	bDoubleTouched	 = false;
	rotateY			 = 0;
	touchID			 = -1;
	distanceToTarget = 10000; // so i dont call sqrt() so much.
	rotateYTarget	 = 0;
	targetForce		= 20.f;

	if(ofRandomuf()>0.5){
		rotateYDirection = 180;
	}else{
		rotateYDirection = -180;
	}
	alpha = 255;

	bAlive = false;

	// for now!
	offScreenTaget.y = -100;
	offScreenTaget.z = -200;

	bobTheta.x = ofRandomuf() * PI;
	bobTheta.y = ofRandomuf() * PI;
	bobTheta.z = ofRandomuf() * PI;

	buzzTime	= 0;
	buzzWait	= 0.1;
	loopCounter = 0;
}

//--------------------------------------------------------------
void ContentBubble::createContentBubble() {

	color.r = ofRandom(0, 255);
	color.g = ofRandom(0, 255);
	color.b = ofRandom(0, 255);
	color.a = 25;

	touchAlphaTarget = 0;
	touchAlpha		 = 0;

	for (int i=0; i<16; i++) {
		billboadMatrix[i] = 0;
		m[i]			  = 0;
	}

	bAlive = true;
	birthDate = ofGetElapsedTimeMillis();
}

//--------------------------------------------------------------
void ContentBubble::gotoTarget(float scale) {
	if(rigidBody->isBody()) {

		rigidBody->body->setDamping(0.99, 0.99); // <-- add some crazy damping

		ofVec3f frc = target - rigidBody->getBulletPosition();
		distanceToTarget = frc.length();
		float d = ABS(distanceToTarget) * scale;
		d *= targetForce;
		frc.normalize();
		frc *= d;

		rigidBody->body->clearForces();
		rigidBody->body->applyCentralForce(btVector3(frc.x, frc.y, frc.z));

		// printf("taget\n");
	}
}
//--------------------------------------------------------------
void ContentBubble::bobMe() {

	bobTheta += 0.02;

	float amp = 100;
	target.x = resetTarget.x + cos(	bobTheta.x ) * 10.0;
	target.y = resetTarget.y + sin(	bobTheta.y ) * amp;
	target.z = resetTarget.z + sin(	bobTheta.z ) * 30.0;
}

//--------------------------------------------------------------
void ContentBubble::buzzMe() {

	// maybe there is a moe elegant solution...

	float tForce = 50.f;
	if(targetForce < tForce)
		targetForce = targetForce + (tForce-targetForce)*.1;

	float dt = ofGetElapsedTimef() - buzzTime;

	if(dt > buzzWait)
	{
		buzzTime = ofGetElapsedTimef();
		buzzWait = ofRandom(.1,.5);

		float rads = ofRandom(60,80);
		float angle = ofRandom(0,TWO_PI);
		buzzDest.x = resetTarget.x + rads * cos(angle);
		buzzDest.y = resetTarget.y + rads * sin(angle);

		buzzOrig = getPosition();
	}

	float pct = 1 - powf( (dt / buzzWait),.75);

	target.x = pct * buzzOrig.x + (1-pct) * buzzDest.x;
	target.y = pct * buzzOrig.y + (1-pct) * buzzDest.y;

}

//--------------------------------------------------------------
void ContentBubble::loopMe(float interactiveWidth,float interactiveHeight){

	if(loopCounter < 1 ) loopCounter += .0015;

	if( getPosition().y < -radius )
	{
		loopCounter = 0;
		rigidBody->setPosition(ofVec3f( (interactiveWidth/2.f) + ofRandom(-300, 300), interactiveHeight+radius, getPosition().z ), ofVec3f(0,0,0), 0);
	}

	target.x = getPosition().x;
	target.y = ofLerp(interactiveHeight,-radius,loopCounter);
}

//--------------------------------------------------------------
void ContentBubble::setTarget(float x, float y, float z) {
	target = ofVec3f(x, y, z);
	resetTarget = ofVec3f(x, y, z);
}

//--------------------------------------------------------------
void ContentBubble::setTarget(ofVec3f v) {
	setTarget(v.x, v.y, v.z);
}

//--------------------------------------------------------------
ofVec3f ContentBubble::getPosition() {
	if(rigidBody->isBody()) {
		return rigidBody->getPosition();
	}
}

//--------------------------------------------------------------
void ContentBubble::addForce(float x, float y, float z, float scale) {
	if(rigidBody->isBody()) {

		// rigidBody->body->setDamping(0.99, 0.99); // <-- add some crazy damping

		ofVec3f frc = ofVec3f(x, y, z) * scale;
		rigidBody->body->clearForces();
		rigidBody->body->applyCentralForce(btVector3(frc.x, frc.y, frc.z));

	}
}

//--------------------------------------------------------------
void ContentBubble::goOffScreen() {
	if(rigidBody->isBody()) {

		rigidBody->body->setDamping(0.99, 0.99); // <-- add some crazy damping

		ofVec3f frc = offScreenTaget - rigidBody->getBulletPosition();
		distanceToTarget = frc.length();
		float d = ABS(distanceToTarget);
		d *= 20.0;
		frc.normalize();
		frc *= d;

		rigidBody->body->clearForces();
		rigidBody->body->applyCentralForce(btVector3(frc.x, frc.y, frc.z));

	}
}

//--------------------------------------------------------------
void ContentBubble::addAtrractionForce(float x, float y, float z, float scale) {
	if(rigidBody->isBody()) {

		ofVec3f frc = ofVec3f(x, y, z) - rigidBody->getBulletPosition();
		distanceToTarget = frc.length();
		float d = ABS(distanceToTarget);
		d *= scale;
		frc.normalize();
		frc *= d;

		rigidBody->body->clearForces();
		rigidBody->body->applyCentralForce(btVector3(frc.x, frc.y, frc.z));

	}
}

//--------------------------------------------------------------
void ContentBubble::addAtrractionForce(ofVec3f &p, float scale) {
	addAtrractionForce(p.x, p.y, p.z, scale);
}

//--------------------------------------------------------------
void ContentBubble::doubleTouched() {
	bDoubleTouched = true;
}

//--------------------------------------------------------------
void ContentBubble::setRadius(float r) {

	btSphereShape * sphereShape = (btSphereShape*)rigidBody->body->getCollisionShape();
	sphereShape->setUnscaledRadius(r);
	radius = r;

}

//--------------------------------------------------------------
void ContentBubble::lerpRadius(float r,float speed) {
	setRadius(radius + (r-radius)*speed);
}

//--------------------------------------------------------------
void ContentBubble::update() {

	//lazyload the font
	if(!font.bLoadedOk){
		font.loadFont("global/font/Gotham-Bold.otf", 50);
		if(font.bLoadedOk) {
			printf("--- font is loaded ---\n");
		}
	}

	touchAlpha += (touchAlphaTarget-touchAlpha) * 0.1;
	rotateY += (rotateYTarget-rotateY) * 0.05;
	if(bDoubleTouched){
		touchAlphaTarget = 160;
		rotateYTarget = rotateYDirection;
	}else{
		touchAlphaTarget = 0;
		rotateYTarget = 0;
	}

	age = ofGetElapsedTimeMillis()-birthDate;

	if(rigidBody->isBody()) {

		pos = rigidBody->getPosition();
		rigidBody->body->getWorldTransform().getOpenGLMatrix(m);
		btSphereShape * sphereShape = (btSphereShape*)rigidBody->shape;

		//radius doesn't include the margin, so draw with margin
		radius = sphereShape->getMargin();

		// create the billboard matrix
		for (int i=0; i<16; i++) {
			billboadMatrix[i] = m[i];
		}

		// ripped from here
		// http://lighthouse3d.com/opengl/billboarding/index.php?billCheat
		for(int i=0; i<3; i++ ) {
			for(int j=0; j<3; j++ ) {
				if ( i==j)  billboadMatrix[i*4+j] = 1.0;
				else		billboadMatrix[i*4+j] = 0.0;
			}
		}
	}
}

//--------------------------------------------------------------
void ContentBubble::pushBubble() {

	if(rigidBody->isBody()) {

		glPushMatrix();
		glMultMatrixf(m);

	}

}

//--------------------------------------------------------------
void ContentBubble::popBubble() {
	if(rigidBody->isBody()) {
		glPopMatrix();
	}

}

//--------------------------------------------------------------
void ContentBubble::pushBillboard() {
	glPushMatrix();
	glMultMatrixf(billboadMatrix);
}

//--------------------------------------------------------------
void ContentBubble::popBillboard() {
	glPopMatrix();
}

//--------------------------------------------------------------
void ContentBubble::drawTwitterData() {
	glEnable(GL_DEPTH_TEST);
	glPushMatrix();
	glMultMatrixf(billboadMatrix);

	glRotatef(rotateY,0,1,0);
	// the twitter icon and text
	if(data) {
		//if no twitter icon, don't draw.
		if(data->profileImage.width != 0){

			float data_radius = radius*0.9;

			//lazyload the font
			if(!font.bLoadedOk){
				font.loadFont("global/font/Gotham-Bold.otf",50);
				if(font.bLoadedOk) {
					printf("--- font is loaded ---\n");
				}
			}

			{
				//draw twitter icon as a disk
				ofSetColor(255,255,255, alpha);
				data->profileImage.bind();
				float w = data->profileImage.width;
				float h = data->profileImage.height;
				//draw the circle-masked thumbnail
				int steps = 60;
				float inc = TWO_PI/(float)steps;
				glBegin(GL_TRIANGLE_FAN);
				for(int i=0;i<steps;i++){
					float x = cos(inc*i);
					float y = sin(inc*i);
					glTexCoord2f((x+1)*w*0.5,(y+1)*h*0.5);
					glVertex2f(x*data_radius,y*data_radius);
				}
				glEnd();
				data->profileImage.unbind();
			}

			{
				glPushMatrix();
				glRotatef(180,0,1,0);
				glTranslatef(0,0,0.1);

				//draw twitter media as a disk
				ofSetColor(color,alpha);
				if(data->media.size()){
					ofSetColor(255,255,255, alpha);
					data->media[0].mediaImage.bind();
				}
				float w = data->profileImage.width;
				float h = data->profileImage.height;
				//draw the circle-masked thumbnail
				int steps = 60;
				float inc = TWO_PI/(float)steps;
				glBegin(GL_TRIANGLE_FAN);
				for(int i=0;i<steps;i++){
					float x = cos(inc*i);
					float y = sin(inc*i);
					glTexCoord2f((x+1)*w*0.5,(y+1)*h*0.5);
					glVertex2f(x*data_radius,y*data_radius);
				}
				glEnd();
				data->profileImage.unbind();
				glPopMatrix();
			}

			{
				//draw twitter text content
				ofRectangle textBB = font.getStringBoundingBox(data->userName, 0,0);
				glPushMatrix();
				float s = data_radius/textBB.width*1.75;
				glScalef(s,s,s);
				glTranslated(-textBB.width/2, 0,0.2);
				ofSetColor(0,0,0, alpha);
				font.drawString(data->userName,0,0);
				glTranslatef(2,2,0.2);
				ofSetColor(255,255,255, alpha);
				font.drawString(data->userName,0,0);
				data->profileImage.unbind();
				glPopMatrix();
			}

			{
				//draw twitter text content
				string txt = data->text;
				if(txt.empty())txt="lorem ipsum";
				ofRectangle textBB = font.getStringBoundingBox(txt, 0,0);
				glPushMatrix();
				float s = data_radius/textBB.width*1.75;
				glScalef(s,s,s);
				glRotatef(180,0,1,0);
				glTranslated(-textBB.width/2, 0,0.2);
				ofSetColor(0,0,0, alpha);
				font.drawString(txt,0,0);
				glTranslatef(2,2,0.2);
				ofSetColor(255,255,255, alpha);
				font.drawString(txt,0,0);
				data->profileImage.unbind();
				glPopMatrix();
			}

		}

	}
	glPopMatrix();
}

//--------------------------------------------------------------
void ContentBubble::drawHighLight() {

	glDisable(GL_DEPTH_TEST);

	glPushMatrix();
	glMultMatrixf(billboadMatrix);

	// little touch outline...
	ofEnableAlphaBlending();
	float rad_extend = radius + 100;
	//draw circular hailo
	glBegin(GL_TRIANGLE_STRIP);
	int steps = 30;
	float inc = TWO_PI/steps;
	for(int i=0;i<steps+1;i++){
		float x = cos(i*inc);
		float y = sin(i*inc);

		if(bDoubleTouched) {
			glColor4f(1, 0, 0, touchAlpha/255.0);
		} else {
			glColor4f(1,1,1, touchAlpha/255.0);
		}
		glVertex3f(x*radius,y*radius, 0);
		glColor4f(1,1,1,0);
		glVertex3f(x*rad_extend,y*rad_extend, 0);

	}
	glEnd();
	glPopMatrix();
}

//--------------------------------------------------------------
void ContentBubble::draw() {

	// for debuggin...
	//ofSetColor(255, 255, 0);
	//drawSphere(target, 3, 10);
	glEnable(GL_DEPTH_TEST);
	// the main bubble sphere
	ofSetColor(color, alpha);
	ofFill();
	drawSphere(ofVec3f(0, 0, 0), radius, 60);
}

<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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 "Geometry.h"
#include "sg/common/World.h"

namespace ospray {
  namespace sg {

    Geometry::Geometry(const std::string &type)
    {
      createChild("material", "Material");
      createChild("type", "string", type);
      setValue((OSPGeometry)nullptr);
    }

    std::string Geometry::toString() const
    {
      return "ospray::sg::Geometry";
    }

    void Geometry::preCommit(RenderContext &)
    {
      auto ospGeometry = valueAs<OSPGeometry>();
      if (!ospGeometry) {
        auto type = child("type").valueAs<std::string>();
        ospGeometry = ospNewGeometry(type.c_str());
        setValue(ospGeometry);

        child("bounds") = computeBounds();
      }
    }

    void Geometry::postCommit(RenderContext &)
    {
      auto ospGeometry = valueAs<OSPGeometry>();
      if (hasChild("material") && !hasChild("materialList")) {
        ospSetMaterial(ospGeometry, child("material").valueAs<OSPMaterial>());
      }
      ospCommit(ospGeometry);
    }

    void Geometry::postRender(RenderContext& ctx)
    {
      auto ospGeometry = valueAs<OSPGeometry>();
      if (ospGeometry)
        ospAddGeometry(ctx.currentOSPModel, ospGeometry);
    }

  } // ::ospray::sg
} // ::ospray
<commit_msg>create a default material list instead of blindly adding a material in sg<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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 "Geometry.h"
#include "sg/common/World.h"

namespace ospray {
  namespace sg {

    Geometry::Geometry(const std::string &type)
    {
      auto matList =
        createChild("materialList", "MaterialList").nodeAs<MaterialList>();
      matList->push_back(createNode("default", "Material")->nodeAs<Material>());

      createChild("type", "string", type);
      setValue((OSPGeometry)nullptr);
    }

    std::string Geometry::toString() const
    {
      return "ospray::sg::Geometry";
    }

    void Geometry::preCommit(RenderContext &)
    {
      auto ospGeometry = valueAs<OSPGeometry>();
      if (!ospGeometry) {
        auto type = child("type").valueAs<std::string>();
        ospGeometry = ospNewGeometry(type.c_str());
        setValue(ospGeometry);

        child("bounds") = computeBounds();
      }
    }

    void Geometry::postCommit(RenderContext &)
    {
      auto ospGeometry = valueAs<OSPGeometry>();
      if (hasChild("material") && !hasChild("materialList")) {
        ospSetMaterial(ospGeometry, child("material").valueAs<OSPMaterial>());
      }
      ospCommit(ospGeometry);
    }

    void Geometry::postRender(RenderContext& ctx)
    {
      auto ospGeometry = valueAs<OSPGeometry>();
      if (ospGeometry)
        ospAddGeometry(ctx.currentOSPModel, ospGeometry);
    }

  } // ::ospray::sg
} // ::ospray
<|endoftext|>